b07c8dd69ba3d20fabcc36f91a14cb542fbd5328
[trust_router.git] / common / tr_config.c
1 /*
2  * Copyright (c) 2012, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdlib.h>
36 #include <string.h>
37 #include <jansson.h>
38 #include <dirent.h>
39 #include <talloc.h>
40
41 #include <tr_cfgwatch.h>
42 #include <tr_comm.h>
43 #include <tr_config.h>
44 #include <tr_gss.h>
45 #include <tr_debug.h>
46 #include <tr_filter.h>
47 #include <trust_router/tr_constraint.h>
48 #include <tr_idp.h>
49 #include <tr.h>
50 #include <trust_router/trp.h>
51
52 void tr_print_config (TR_CFG *cfg) {
53   tr_notice("tr_print_config: Logging running trust router configuration.");
54   tr_print_comms(cfg->ctable);
55 }
56
57 void tr_print_comms (TR_COMM_TABLE *ctab)
58 {
59   TR_COMM *comm = NULL;
60
61   for (comm = ctab->comms; NULL != comm; comm = comm->next) {
62     tr_notice("tr_print_config: Community %s:", comm->id->buf);
63
64     tr_notice("tr_print_config:  - Member IdPs:");
65     tr_print_comm_idps(ctab, comm);
66
67     tr_notice("tr_print_config:  - Member RPs:");
68     tr_print_comm_rps(ctab, comm);
69   }
70 }
71
72 void tr_print_comm_idps(TR_COMM_TABLE *ctab, TR_COMM *comm)
73 {
74   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
75   TR_COMM_ITER *iter=NULL;
76   TR_IDP_REALM *idp = NULL;
77   char *s=NULL;
78
79   iter=tr_comm_iter_new(tmp_ctx);
80   if (iter==NULL) {
81     tr_notice("tr_print_config: unable to allocate IdP iterator.");
82     talloc_free(tmp_ctx);
83     return;
84   }
85   
86   for (idp=tr_idp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
87        NULL!=idp;
88        idp=tr_idp_realm_iter_next(iter)) {
89     s=tr_idp_realm_to_str(tmp_ctx, idp);
90     if (s!=NULL)
91       tr_notice("tr_print_config:    - @%s", s);
92     else
93       tr_notice("tr_print_config: unable to allocate IdP output string.");
94   }
95   talloc_free(tmp_ctx);
96 }
97
98 void tr_print_comm_rps(TR_COMM_TABLE *ctab, TR_COMM *comm)
99 {
100   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
101   TR_COMM_ITER *iter=NULL;
102   TR_RP_REALM *rp = NULL;
103   char *s=NULL;
104
105   iter=tr_comm_iter_new(tmp_ctx);
106   if (iter==NULL) {
107     tr_notice("tr_print_config: unable to allocate RP iterator.");
108     talloc_free(tmp_ctx);
109     return;
110   }
111   
112   for (rp=tr_rp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
113        NULL!=rp;
114        rp=tr_rp_realm_iter_next(iter)) {
115     s=tr_rp_realm_to_str(tmp_ctx, rp);
116     if (s!=NULL)
117       tr_notice("tr_print_config:    - @%s", s);
118     else
119       tr_notice("tr_print_config: unable to allocate RP output string.");
120   }
121   talloc_free(tmp_ctx);
122 }
123
124 TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
125 {
126   TR_CFG *cfg=talloc(mem_ctx, TR_CFG);
127   if (cfg!=NULL) {
128     cfg->internal=NULL;
129     cfg->rp_clients=NULL;
130     cfg->peers=NULL;
131     cfg->default_servers=NULL;
132     cfg->ctable=tr_comm_table_new(cfg);
133     if (cfg->ctable==NULL) {
134       talloc_free(cfg);
135       cfg=NULL;
136     }
137   }
138   return cfg;
139 }
140
141 void tr_cfg_free (TR_CFG *cfg)
142 {
143   talloc_free(cfg);
144 }
145
146 TR_CFG_MGR *tr_cfg_mgr_new(TALLOC_CTX *mem_ctx)
147 {
148   return talloc_zero(mem_ctx, TR_CFG_MGR);
149 }
150
151 void tr_cfg_mgr_free (TR_CFG_MGR *cfg_mgr) {
152   talloc_free(cfg_mgr);
153 }
154
155 TR_CFG_RC tr_apply_new_config (TR_CFG_MGR *cfg_mgr)
156 {
157   /* cfg_mgr->active is allowed to be null, but new cannot be */
158   if ((cfg_mgr==NULL) || (cfg_mgr->new==NULL))
159     return TR_CFG_BAD_PARAMS;
160
161   if (cfg_mgr->active != NULL)
162     tr_cfg_free(cfg_mgr->active);
163
164   cfg_mgr->active = cfg_mgr->new;
165   cfg_mgr->new=NULL; /* only keep a single handle on the new configuration */
166
167   tr_log_threshold(cfg_mgr->active->internal->log_threshold);
168   tr_console_threshold(cfg_mgr->active->internal->console_threshold);
169
170   return TR_CFG_SUCCESS;
171 }
172
173 static TR_CFG_RC tr_cfg_parse_internal(TR_CFG *trc, json_t *jcfg)
174 {
175   json_t *jint = NULL;
176   json_t *jmtd = NULL;
177   json_t *jtidsp = NULL;
178   json_t *jtrpsp = NULL;
179   json_t *jhname = NULL;
180   json_t *jlog = NULL;
181   json_t *jconthres = NULL;
182   json_t *jlogthres = NULL;
183   json_t *jcfgpoll = NULL;
184   json_t *jcfgsettle = NULL;
185   json_t *jroutesweep = NULL;
186   json_t *jrouteupdate = NULL;
187   json_t *jrouteconnect = NULL;
188
189   if ((!trc) || (!jcfg))
190     return TR_CFG_BAD_PARAMS;
191
192   if (NULL == trc->internal) {
193     if (NULL == (trc->internal = talloc_zero(trc, TR_CFG_INTERNAL)))
194       return TR_CFG_NOMEM;
195   }
196
197   if (NULL != (jint = json_object_get(jcfg, "tr_internal"))) {
198     if (NULL != (jmtd = json_object_get(jint, "max_tree_depth"))) {
199       if (json_is_number(jmtd)) {
200         trc->internal->max_tree_depth = json_integer_value(jmtd);
201       } else {
202         tr_debug("tr_cfg_parse_internal: Parsing error, max_tree_depth is not a number.");
203         return TR_CFG_NOPARSE;
204       }
205     } else {
206       /* If not configured, use the default */
207       trc->internal->max_tree_depth = TR_DEFAULT_MAX_TREE_DEPTH;
208     }
209     if (NULL != (jtidsp = json_object_get(jint, "tids_port"))) {
210       if (json_is_number(jtidsp)) {
211         trc->internal->tids_port = json_integer_value(jtidsp);
212       } else {
213         tr_debug("tr_cfg_parse_internal: Parsing error, tids_port is not a number.");
214         return TR_CFG_NOPARSE;
215       }
216     } else {
217       /* If not configured, use the default */
218       trc->internal->tids_port = TR_DEFAULT_TIDS_PORT;
219     }
220     if (NULL != (jtrpsp = json_object_get(jint, "trps_port"))) {
221       if (json_is_number(jtrpsp)) {
222         trc->internal->trps_port = json_integer_value(jtrpsp);
223       } else {
224         tr_debug("tr_cfg_parse_internal: Parsing error, trps_port is not a number.");
225         return TR_CFG_NOPARSE;
226       }
227     } else {
228       /* If not configured, use the default */
229       trc->internal->trps_port = TR_DEFAULT_TRPS_PORT;
230     }
231     if (NULL != (jhname = json_object_get(jint, "hostname"))) {
232       if (json_is_string(jhname)) {
233         trc->internal->hostname = json_string_value(jhname);
234       } else {
235         tr_debug("tr_cfg_parse_internal: Parsing error, hostname is not a string.");
236         return TR_CFG_NOPARSE;
237       }
238     }
239     if (NULL != (jcfgpoll = json_object_get(jint, "cfg_poll_interval"))) {
240       if (json_is_number(jcfgpoll)) {
241         trc->internal->cfg_poll_interval = json_integer_value(jcfgpoll);
242       } else {
243         tr_debug("tr_cfg_parse_internal: Parsing error, cfg_poll_interval is not a number.");
244         return TR_CFG_NOPARSE;
245       }
246     } else {
247       trc->internal->cfg_poll_interval = TR_CFGWATCH_DEFAULT_POLL;
248     }
249
250     if (NULL != (jcfgsettle = json_object_get(jint, "cfg_settling_time"))) {
251       if (json_is_number(jcfgsettle)) {
252         trc->internal->cfg_settling_time = json_integer_value(jcfgsettle);
253       } else {
254         tr_debug("tr_cfg_parse_internal: Parsing error, cfg_settling_time is not a number.");
255         return TR_CFG_NOPARSE;
256       }
257     } else {
258       trc->internal->cfg_settling_time = TR_CFGWATCH_DEFAULT_SETTLE;
259     }
260
261     if (NULL != (jrouteconnect = json_object_get(jint, "trp_connect_interval"))) {
262       if (json_is_number(jrouteconnect)) {
263         trc->internal->trp_connect_interval = json_integer_value(jrouteconnect);
264       } else {
265         tr_debug("tr_cfg_parse_internal: Parsing error, trp_connect_interval is not a number.");
266         return TR_CFG_NOPARSE;
267       }
268     } else {
269       /* if not configured, use the default */
270       trc->internal->trp_connect_interval=TR_DEFAULT_TRP_CONNECT_INTERVAL;
271     }
272
273     if (NULL != (jroutesweep = json_object_get(jint, "trp_sweep_interval"))) {
274       if (json_is_number(jroutesweep)) {
275         trc->internal->trp_sweep_interval = json_integer_value(jroutesweep);
276       } else {
277         tr_debug("tr_cfg_parse_internal: Parsing error, trp_sweep_interval is not a number.");
278         return TR_CFG_NOPARSE;
279       }
280     } else {
281       /* if not configured, use the default */
282       trc->internal->trp_sweep_interval=TR_DEFAULT_TRP_SWEEP_INTERVAL;
283     }
284
285     if (NULL != (jrouteupdate = json_object_get(jint, "trp_update_interval"))) {
286       if (json_is_number(jrouteupdate)) {
287         trc->internal->trp_update_interval = json_integer_value(jrouteupdate);
288       } else {
289         tr_debug("tr_cfg_parse_internal: Parsing error, trp_update_interval is not a number.");
290         return TR_CFG_NOPARSE;
291       }
292     } else {
293       /* if not configured, use the default */
294       trc->internal->trp_update_interval=TR_DEFAULT_TRP_UPDATE_INTERVAL;
295     }
296
297     if (NULL != (jlog = json_object_get(jint, "logging"))) {
298       if (NULL != (jlogthres = json_object_get(jlog, "log_threshold"))) {
299         if (json_is_string(jlogthres)) {
300           trc->internal->log_threshold = str2sev(json_string_value(jlogthres));
301         } else {
302           tr_debug("tr_cfg_parse_internal: Parsing error, log_threshold is not a string.");
303           return TR_CFG_NOPARSE;
304         }
305       } else {
306         /* If not configured, use the default */
307         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
308       }
309
310       if (NULL != (jconthres = json_object_get(jlog, "console_threshold"))) {
311         if (json_is_string(jconthres)) {
312             trc->internal->console_threshold = str2sev(json_string_value(jconthres));
313         } else {
314           tr_debug("tr_cfg_parse_internal: Parsing error, console_threshold is not a string.");
315           return TR_CFG_NOPARSE;
316         }
317       } else {
318         /* If not configured, use the default */
319         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
320       }
321     } else {
322         /* If not configured, use the default */
323         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
324         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
325     }
326
327     tr_debug("tr_cfg_parse_internal: Internal config parsed.");
328     return TR_CFG_SUCCESS;
329   }
330   return TR_CFG_SUCCESS;
331 }
332
333 static TR_CONSTRAINT *tr_cfg_parse_one_constraint(TALLOC_CTX *mem_ctx, char *ctype, json_t *jc, TR_CFG_RC *rc)
334 {
335   TR_CONSTRAINT *cons=NULL;
336   int i=0;
337
338   if ((!ctype) || (!jc) || (!rc) ||
339       (!json_is_array(jc)) ||
340       (0 >= json_array_size(jc)) ||
341       (TR_MAX_CONST_MATCHES < json_array_size(jc)) ||
342       (!json_is_string(json_array_get(jc, 0)))) {
343     tr_err("tr_cfg_parse_one_constraint: config error.");
344     *rc=TR_CFG_NOPARSE;
345     return NULL;
346   }
347
348   if (NULL==(cons=tr_constraint_new(mem_ctx))) {
349     tr_debug("tr_cfg_parse_one_constraint: Out of memory (cons).");
350     *rc=TR_CFG_NOMEM;
351     return NULL;
352   }
353
354   if (NULL==(cons->type=tr_new_name(ctype))) {
355     tr_err("tr_cfg_parse_one_constraint: Out of memory (type).");
356     *rc=TR_CFG_NOMEM;
357     tr_constraint_free(cons);
358     return NULL;
359   }
360
361   for (i=0; i < json_array_size(jc); i++) {
362     cons->matches[i]=tr_new_name(json_string_value(json_array_get(jc, i)));
363     if (cons->matches[i]==NULL) {
364       tr_err("tr_cfg_parse_one_constraint: Out of memory (match %d).", i+1);
365       *rc=TR_CFG_NOMEM;
366       tr_constraint_free(cons);
367       return NULL;
368     }
369   }
370
371   return cons;
372 }
373
374 static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR_FILTER_TYPE ftype, TR_CFG_RC *rc)
375 {
376   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
377   TR_FILTER *filt=NULL;
378   json_t *jfaction=NULL;
379   json_t *jfspecs=NULL;
380   json_t *jffield=NULL;
381   json_t *jfmatch=NULL;
382   json_t *jrc=NULL;
383   json_t *jdc=NULL;
384   TR_NAME *name=NULL;
385   int i=0, j=0;
386
387   *rc=TR_CFG_ERROR;
388
389   if ((jfilt==NULL) || (rc==NULL)) {
390     tr_err("tr_cfg_parse_one_filter: null argument");
391     *rc=TR_CFG_BAD_PARAMS;
392     goto cleanup;
393   }
394     
395   if (NULL==(filt=tr_filter_new(tmp_ctx))) {
396     tr_err("tr_cfg_parse_one_filter: Out of memory.");
397     *rc=TR_CFG_NOMEM;
398     goto cleanup;
399   }
400   tr_filter_set_type(filt, ftype);
401
402   /* make sure we have space to represent the filter */
403   if (json_array_size(jfilt) > TR_MAX_FILTER_LINES) {
404     tr_err("tr_cfg_parse_one_filter: Filter has too many lines, maximum of %d.", TR_MAX_FILTER_LINES);
405     *rc=TR_CFG_NOPARSE;
406     goto cleanup;
407   }
408
409   /* For each entry in the filter... */
410   for (i=0; i < json_array_size(jfilt); i++) {
411     if ((NULL==(jfaction=json_object_get(json_array_get(jfilt, i), "action"))) ||
412         (!json_is_string(jfaction))) {
413       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action.");
414       *rc=TR_CFG_NOPARSE;
415       goto cleanup;
416     }
417  
418     if ((NULL==(jfspecs=json_object_get(json_array_get(jfilt, i), "specs"))) ||
419         (!json_is_array(jfspecs)) ||
420         (0==json_array_size(jfspecs))) {
421       tr_debug("tr_cfg_parse_one_filter: Error parsing filter specs.");
422       *rc=TR_CFG_NOPARSE;
423       goto cleanup;
424     }
425   
426     if (TR_MAX_FILTER_SPECS < json_array_size(jfspecs)) {
427       tr_debug("tr_cfg_parse_one_filter: Filter has too many specs, maximimum of %d.", TR_MAX_FILTER_SPECS);
428       *rc=TR_CFG_NOPARSE;
429       goto cleanup;
430     }
431
432     if (NULL==(filt->lines[i]=tr_fline_new(filt))) {
433       tr_debug("tr_cfg_parse_one_filter: Out of memory allocating filter line %d.", i+1);
434       *rc=TR_CFG_NOMEM;
435       goto cleanup;
436     }
437
438     if (!strcmp(json_string_value(jfaction), "accept")) {
439       filt->lines[i]->action=TR_FILTER_ACTION_ACCEPT;
440     }
441     else if (!strcmp(json_string_value(jfaction), "reject")) {
442       filt->lines[i]->action=TR_FILTER_ACTION_REJECT;
443     }
444     else {
445       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.", json_string_value(jfaction));
446       *rc=TR_CFG_NOPARSE;
447       goto cleanup;
448     }
449
450     if (NULL!=(jrc=json_object_get(json_array_get(jfilt, i), "realm_constraints"))) {
451       if (!json_is_array(jrc)) {
452         tr_err("tr_cfg_parse_one_filter: cannot parse realm_constraints, not an array.");
453         *rc=TR_CFG_NOPARSE;
454         goto cleanup;
455       } else if (json_array_size(jrc)>TR_MAX_CONST_MATCHES) {
456         tr_err("tr_cfg_parse_one_filter: realm_constraints has too many entries, maximum of %d.",
457                TR_MAX_CONST_MATCHES);
458         *rc=TR_CFG_NOPARSE;
459         goto cleanup;
460       } else if (json_array_size(jrc)>0) {
461         /* ok we actually have entries to process */
462         if (NULL==(filt->lines[i]->realm_cons=tr_cfg_parse_one_constraint(filt->lines[i], "realm", jrc, rc))) {
463           tr_debug("tr_cfg_parse_one_filter: Error parsing realm constraint");
464           *rc=TR_CFG_NOPARSE;
465           goto cleanup;
466         }
467       }
468     }
469
470     if (NULL!=(jdc=json_object_get(json_array_get(jfilt, i), "domain_constraints"))) {
471       if (!json_is_array(jdc)) {
472         tr_err("tr_cfg_parse_one_filter: cannot parse domain_constraints, not an array.");
473         *rc=TR_CFG_NOPARSE;
474         goto cleanup;
475       } else if (json_array_size(jdc)>TR_MAX_CONST_MATCHES) {
476         tr_err("tr_cfg_parse_one_filter: domain_constraints has too many entries, maximum of %d.",
477                TR_MAX_CONST_MATCHES);
478         *rc=TR_CFG_NOPARSE;
479         goto cleanup;
480       } else if (json_array_size(jdc)>0) {
481         if (NULL==(filt->lines[i]->domain_cons=tr_cfg_parse_one_constraint(filt->lines[i], "domain", jdc, rc))) {
482           tr_debug("tr_cfg_parse_one_filter: Error parsing domain constraint");
483           *rc=TR_CFG_NOPARSE;
484           goto cleanup;
485         }
486       }
487     }
488
489     /*For each filter spec within the filter line... */
490     for (j=0; j <json_array_size(jfspecs); j++) {
491       if ((NULL==(jffield=json_object_get(json_array_get(jfspecs, j), "field"))) ||
492           (!json_is_string(jffield))) {
493         tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing field for filer spec %d, filter line %d.", i, j);
494         *rc=TR_CFG_NOPARSE;
495         goto cleanup;
496       }
497
498       /* check that we have a match attribute */
499       if (NULL==(jfmatch=json_object_get(json_array_get(jfspecs, j), "match"))) {
500         tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing match for filer spec %d, filter line %d.", i, j);
501         *rc=TR_CFG_NOPARSE;
502         goto cleanup;
503       }
504
505       /* check that match is a string */
506       if (!json_is_string(jfmatch)) {
507         tr_debug("tr_cfg_parse_one_filter: Error parsing filter: match not a string for filter spec %d, filter line %d.", i, j);
508         *rc=TR_CFG_NOPARSE;
509         goto cleanup;
510       }
511
512       /* allocate the filter spec */
513       if (NULL==(filt->lines[i]->specs[j]=tr_fspec_new(filt->lines[i]))) {
514         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
515         *rc=TR_CFG_NOMEM;
516         goto cleanup;
517       }
518
519       /* fill in the field */
520       if (NULL==(filt->lines[i]->specs[j]->field=tr_new_name(json_string_value(jffield)))) {
521         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
522         *rc=TR_CFG_NOMEM;
523         goto cleanup;
524       }
525
526       /* fill in the matches */
527       if (NULL==(name=tr_new_name(json_string_value(jfmatch)))) {
528         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
529         *rc=TR_CFG_NOMEM;
530         goto cleanup;
531       }
532       tr_fspec_set_match(filt->lines[i]->specs[j], name);
533     }
534   }
535   *rc=TR_CFG_SUCCESS;
536   talloc_steal(mem_ctx, filt);
537   
538  cleanup:
539   talloc_free(tmp_ctx);
540   if (*rc!=TR_CFG_SUCCESS)
541     filt=NULL;
542   return filt;
543 }
544
545 static TR_FILTER *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_CFG_RC *rc)
546 {
547   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
548   json_t *jfilt;
549   TR_FILTER *filt=NULL;
550
551   *rc=TR_CFG_ERROR;
552
553   /* no filters */
554   if (jfilts==NULL) {
555     *rc=TR_CFG_SUCCESS;
556     goto cleanup;
557   }
558
559   jfilt=json_object_get(jfilts, "tid_inbound");
560   if (jfilt!=NULL) {
561     filt=tr_cfg_parse_one_filter(tmp_ctx, jfilt, TR_FILTER_TYPE_TID_INCOMING, rc);
562     if (*rc!=TR_CFG_SUCCESS) {
563       tr_debug("tr_cfg_parse_filters: Error parsing tid_inbound filter.");
564       *rc=TR_CFG_NOPARSE;
565       goto cleanup;
566     }
567   } else {
568     tr_debug("tr_cfg_parse_filters: Unknown filter types in filter block.");
569     *rc=TR_CFG_NOPARSE;
570     goto cleanup;
571   }
572   
573   *rc=TR_CFG_SUCCESS;
574
575  cleanup:
576   if (*rc==TR_CFG_SUCCESS)
577     talloc_steal(mem_ctx, filt);
578   else if (filt!=NULL) {
579     talloc_free(filt);
580     filt=NULL;
581   }
582
583   talloc_free(tmp_ctx);
584   return filt;
585 }
586
587 static TR_AAA_SERVER *tr_cfg_parse_one_aaa_server(TALLOC_CTX *mem_ctx, json_t *jaddr, TR_CFG_RC *rc)
588 {
589   TR_AAA_SERVER *aaa = NULL;
590   TR_NAME *name=NULL;
591
592   if ((!jaddr) || (!json_is_string(jaddr))) {
593     tr_debug("tr_cfg_parse_one_aaa_server: Bad parameters.");
594     *rc = TR_CFG_BAD_PARAMS;
595     return NULL;
596   }
597
598   name=tr_new_name(json_string_value(jaddr));
599   if (name==NULL) {
600     tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating hostname.");
601     *rc = TR_CFG_NOMEM;
602     return NULL;
603   }
604
605   aaa=tr_aaa_server_new(mem_ctx, name);
606   if (aaa==NULL) {
607     tr_free_name(name);
608     tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating AAA server.");
609     *rc = TR_CFG_NOMEM;
610     return NULL;
611   }
612
613   return aaa;
614 }
615
616 static TR_AAA_SERVER *tr_cfg_parse_aaa_servers(TALLOC_CTX *mem_ctx, json_t *jaaas, TR_CFG_RC *rc) 
617 {
618   TALLOC_CTX *tmp_ctx=NULL;
619   TR_AAA_SERVER *aaa = NULL;
620   TR_AAA_SERVER *temp_aaa = NULL;
621   int i = 0;
622
623   for (i = 0; i < json_array_size(jaaas); i++) {
624     /* rc gets set in here */
625     if (NULL == (temp_aaa = tr_cfg_parse_one_aaa_server(tmp_ctx, json_array_get(jaaas, i), rc))) {
626       talloc_free(tmp_ctx);
627       return NULL;
628     }
629     /* TBD -- IPv6 addresses */
630     //    tr_debug("tr_cfg_parse_aaa_servers: Configuring AAA Server: ip_addr = %s.", inet_ntoa(temp_aaa->aaa_server_addr));
631     temp_aaa->next = aaa;
632     aaa = temp_aaa;
633   }
634   tr_debug("tr_cfg_parse_aaa_servers: Finished (rc=%d)", *rc);
635
636   for (temp_aaa=aaa; temp_aaa!=NULL; temp_aaa=temp_aaa->next)
637     talloc_steal(mem_ctx, temp_aaa);
638   talloc_free(tmp_ctx);
639   return aaa;
640 }
641
642 static TR_APC *tr_cfg_parse_one_apc(TALLOC_CTX *mem_ctx, json_t *japc, TR_CFG_RC *rc)
643 {
644   TR_APC *apc=NULL;
645   TR_NAME *name=NULL;
646   
647   *rc = TR_CFG_SUCCESS;         /* presume success */
648
649   if ((!japc) || (!rc) || (!json_is_string(japc))) {
650     tr_debug("tr_cfg_parse_one_apc: Bad parameters.");
651     if (rc) 
652       *rc = TR_CFG_BAD_PARAMS;
653     return NULL;
654   }
655
656   apc=tr_apc_new(mem_ctx);
657   if (apc==NULL) {
658     tr_debug("tr_cfg_parse_one_apc: Out of memory.");
659     *rc = TR_CFG_NOMEM;
660     return NULL;
661   }
662
663   name=tr_new_name(json_string_value(japc));
664   if (name==NULL) {
665     tr_debug("tr_cfg_parse_one_apc: No memory for APC name.");
666     tr_apc_free(apc);
667     *rc = TR_CFG_NOMEM;
668     return NULL;
669   }
670   tr_apc_set_id(apc, name); /* apc is now responsible for freeing the name */
671
672   return apc;
673 }
674
675 static TR_APC *tr_cfg_parse_apcs(TALLOC_CTX *mem_ctx, json_t *japcs, TR_CFG_RC *rc)
676 {
677   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
678   TR_APC *apcs=NULL;
679   TR_APC *new_apc=NULL;
680   int ii=0;
681   TR_CFG_RC call_rc=TR_CFG_ERROR;
682   
683   *rc = TR_CFG_SUCCESS;         /* presume success */
684
685   if ((!japcs) || (!rc) || (!json_is_array(japcs))) {
686     tr_debug("tr_cfg_parse_one_apc: Bad parameters.");
687     if (rc) 
688       *rc = TR_CFG_BAD_PARAMS;
689     return NULL;
690   }
691
692   for (ii=0; ii<json_array_size(japcs); ii++) {
693     new_apc=tr_cfg_parse_one_apc(tmp_ctx, json_array_get(japcs, ii), &call_rc);
694     if ((call_rc!=TR_CFG_SUCCESS) || (new_apc==NULL)) {
695       tr_debug("tr_cfg_parse_apcs: Error parsing APC %d.", ii+1);
696       *rc=TR_CFG_NOPARSE;
697       goto cleanup;
698     }
699     tr_apc_add(apcs, new_apc);
700   }
701
702   talloc_steal(mem_ctx, apcs);
703   *rc=TR_CFG_SUCCESS;
704
705  cleanup:
706   talloc_free(tmp_ctx);
707   return apcs;
708 }
709
710 static TR_NAME *tr_cfg_parse_name(TALLOC_CTX *mem_ctx, json_t *jname, TR_CFG_RC *rc)
711 {
712   TR_NAME *name=NULL;
713   *rc=TR_CFG_ERROR;
714
715   if ((jname==NULL) || (!json_is_string(jname))) {
716     tr_err("tr_cfg_parse_name: name missing or not a string");
717     *rc=TR_CFG_BAD_PARAMS;
718     name=NULL;
719   } else {
720     name=tr_new_name(json_string_value(jname));
721     if (name==NULL) {
722       tr_err("tr_cfg_parse_name: could not allocate name");
723       *rc=TR_CFG_NOMEM;
724     } else {
725       *rc=TR_CFG_SUCCESS;
726     }
727   }
728   return name;  
729 }
730
731 static int tr_cfg_parse_shared_config(json_t *jsc, TR_CFG_RC *rc)
732 {
733   const char *shared=NULL;
734   *rc=TR_CFG_SUCCESS;
735   
736   if ((jsc==NULL) ||
737       (!json_is_string(jsc)) ||
738       (NULL==(shared=json_string_value(jsc)))) {
739     *rc=TR_CFG_BAD_PARAMS;
740     return -1;
741   }
742
743   if (0==strcmp(shared, "no"))
744     return 0;
745   else if (0==strcmp(shared, "yes"))
746     return 1;
747
748   /* any other value is an error */
749   tr_debug("tr_cfg_parse_shared_config: invalid shared_config value \"%s\" (should be \"yes\" or \"no\")",
750            shared);
751   *rc=TR_CFG_NOPARSE;
752   return -1;
753 }
754
755 static TR_REALM_ORIGIN tr_cfg_realm_origin(json_t *jrealm)
756 {
757   json_t *jremote=json_object_get(jrealm, "remote");
758   const char *s=NULL;
759
760   if (jremote==NULL)
761     return TR_REALM_LOCAL;
762   if (!json_is_string(jremote)) {
763     tr_warning("tr_cfg_realm_origin: \"remote\" is not a string, assuming this is a local realm.");
764     return TR_REALM_LOCAL;
765   }
766   s=json_string_value(jremote);
767   if (strcasecmp(s, "yes")==0)
768     return TR_REALM_REMOTE_INCOMPLETE;
769   else if (strcasecmp(s, "no")!=0)
770     tr_warning("tr_cfg_realm_origin: \"remote\" is neither 'yes' nor 'no', assuming this is a local realm.");
771
772   return TR_REALM_LOCAL;
773 }
774
775 /* Parse the identity provider object from a realm and fill in the given TR_IDP_REALM. */
776 static TR_CFG_RC tr_cfg_parse_idp(TR_IDP_REALM *idp, json_t *jidp)
777 {
778   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
779   TR_APC *apcs=NULL;
780   TR_AAA_SERVER *aaa=NULL;
781   TR_CFG_RC rc=TR_CFG_ERROR;
782   
783   if (jidp==NULL)
784     goto cleanup;
785
786   idp->shared_config=tr_cfg_parse_shared_config(json_object_get(jidp, "shared_config"), &rc);
787   if (rc!=TR_CFG_SUCCESS) {
788     tr_err("tr_cfg_parse_idp: missing or malformed shared_config specification");
789     rc=TR_CFG_NOPARSE;
790     goto cleanup;
791   }
792
793   apcs=tr_cfg_parse_apcs(tmp_ctx, json_object_get(jidp, "apcs"), &rc);
794   if ((rc!=TR_CFG_SUCCESS) || (apcs==NULL)) {
795     tr_err("tr_cfg_parse_idp: unable to parse APC");
796     rc=TR_CFG_NOPARSE;
797     goto cleanup;
798   }
799   
800   aaa=tr_cfg_parse_aaa_servers(idp, json_object_get(jidp, "aaa_servers"), &rc);
801   if (rc!=TR_CFG_SUCCESS) {
802     tr_err("tr_cfg_parse_idp: unable to parse AAA servers");
803     rc=TR_CFG_NOPARSE;
804     goto cleanup;
805   }
806   
807   tr_debug("tr_cfg_parse_idp: APC=\"%.*s\"",
808            apcs->id->len,
809            apcs->id->buf);
810   
811   /* done, fill in the idp structures */
812   idp->apcs=apcs;
813   talloc_steal(idp, apcs);
814   idp->aaa_servers=aaa;
815   rc=TR_CFG_SUCCESS;
816   
817 cleanup:
818   if (rc!=TR_CFG_SUCCESS) {
819     if (apcs!=NULL)
820       tr_apc_free(apcs);
821     if (aaa!=NULL)
822       tr_aaa_server_free(aaa);
823   }
824   
825   talloc_free(tmp_ctx);
826   return rc;
827 }
828
829 /* parses idp realm */
830 static TR_IDP_REALM *tr_cfg_parse_one_idp_realm(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
831 {
832   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
833   TR_IDP_REALM *realm=NULL;
834   TR_CFG_RC call_rc=TR_CFG_ERROR;
835
836   *rc=TR_CFG_ERROR; /* default to error if not set */
837
838   if ((!jrealm) || (!rc)) {
839     tr_err("tr_cfg_parse_one_idp_realm: Bad parameters.");
840     if (rc)
841       *rc=TR_CFG_BAD_PARAMS;
842     goto cleanup;
843   }
844
845   if (NULL==(realm=tr_idp_realm_new(tmp_ctx))) {
846     tr_err("tr_cfg_parse_one_idp_realm: could not allocate idp realm.");
847     *rc=TR_CFG_NOMEM;
848     goto cleanup;
849   }
850
851   realm->origin=tr_cfg_realm_origin(jrealm);
852   if (realm->origin!=TR_REALM_LOCAL) {
853     tr_debug("tr_cfg_parse_one_idp_realm: realm is remote, should not have full IdP info.");
854     *rc=TR_CFG_NOPARSE;
855     goto cleanup;
856   }
857
858   /* must have a name */
859   realm->realm_id=tr_cfg_parse_name(realm,
860                                     json_object_get(jrealm, "realm"),
861                                    &call_rc);
862   if ((call_rc!=TR_CFG_SUCCESS) || (realm->realm_id==NULL)) {
863     tr_err("tr_cfg_parse_one_idp_realm: could not parse realm name");
864     *rc=TR_CFG_NOPARSE;
865     goto cleanup;
866   }
867   tr_debug("tr_cfg_parse_one_idp_realm: realm_id=\"%.*s\"",
868            realm->realm_id->len,
869            realm->realm_id->buf);
870         
871   call_rc=tr_cfg_parse_idp(realm, json_object_get(jrealm, "identity_provider"));
872   if (call_rc!=TR_CFG_SUCCESS) {
873     tr_err("tr_cfg_parse_one_idp_realm: could not parse identity_provider.");
874     *rc=TR_CFG_NOPARSE;
875     goto cleanup;
876   }
877   
878   *rc=TR_CFG_SUCCESS;
879
880 cleanup:
881   if (*rc==TR_CFG_SUCCESS)
882     talloc_steal(mem_ctx, realm);
883   else {
884     talloc_free(realm);
885     realm=NULL;
886   }
887   
888   talloc_free(tmp_ctx);
889   return realm;
890 }
891
892   /* Determine whether the realm is an IDP realm */
893 static int tr_cfg_is_idp_realm(json_t *jrealm)
894 {
895   /* If a realm spec contains an identity_provider, it's an IDP realm. */
896   if (NULL != json_object_get(jrealm, "identity_provider"))
897     return 1;
898   else
899     return 0;
900 }
901
902 static TR_IDP_REALM *tr_cfg_parse_one_remote_realm(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
903 {
904   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
905   TR_IDP_REALM *realm=talloc(mem_ctx, TR_IDP_REALM);
906   
907   *rc=TR_CFG_ERROR; /* default to error if not set */
908
909   if ((!jrealm) || (!rc)) {
910     tr_err("tr_cfg_parse_one_remote_realm: Bad parameters.");
911     if (rc)
912       *rc=TR_CFG_BAD_PARAMS;
913     goto cleanup;
914   }
915
916   if (NULL==(realm=tr_idp_realm_new(tmp_ctx))) {
917     tr_err("tr_cfg_parse_one_remote_realm: could not allocate idp realm.");
918     *rc=TR_CFG_NOMEM;
919     goto cleanup;
920   }
921
922   /* must have a name */
923   realm->realm_id=tr_cfg_parse_name(realm,
924                                     json_object_get(jrealm, "realm"),
925                                     rc);
926   if ((*rc!=TR_CFG_SUCCESS) || (realm->realm_id==NULL)) {
927     tr_err("tr_cfg_parse_one_remote_realm: could not parse realm name");
928     *rc=TR_CFG_NOPARSE;
929     goto cleanup;
930   }
931   tr_debug("tr_cfg_parse_one_remote_realm: realm_id=\"%.*s\"",
932            realm->realm_id->len,
933            realm->realm_id->buf);
934
935   realm->origin=tr_cfg_realm_origin(jrealm);
936   *rc=TR_CFG_SUCCESS;
937
938 cleanup:
939   if (*rc==TR_CFG_SUCCESS)
940     talloc_steal(mem_ctx, realm);
941   else {
942     talloc_free(realm);
943     realm=NULL;
944   }
945   
946   talloc_free(tmp_ctx);
947   return realm;
948 }
949
950 static int tr_cfg_is_remote_realm(json_t *jrealm)
951 {
952   return (tr_cfg_realm_origin(jrealm)!=TR_REALM_LOCAL);
953 }
954
955 /* Parse any idp realms in the j_realms object. Ignores other realm types. */
956 static TR_IDP_REALM *tr_cfg_parse_idp_realms(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
957 {
958   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
959   TR_IDP_REALM *realms=NULL;
960   TR_IDP_REALM *new_realm=NULL;
961   json_t *this_jrealm=NULL;
962   int ii=0;
963
964   *rc=TR_CFG_ERROR;
965   if ((jrealms==NULL) || (!json_is_array(jrealms))) {
966     tr_err("tr_cfg_parse_idp_realms: realms not an array");
967     *rc=TR_CFG_BAD_PARAMS;
968     goto cleanup;
969   }
970
971   for (ii=0; ii<json_array_size(jrealms); ii++) {
972     this_jrealm=json_array_get(jrealms, ii);
973     if (tr_cfg_is_idp_realm(this_jrealm)) {
974       new_realm=tr_cfg_parse_one_idp_realm(tmp_ctx, this_jrealm, rc);
975       if ((*rc)!=TR_CFG_SUCCESS) {
976         tr_err("tr_cfg_parse_idp_realms: error decoding realm entry %d", ii+1);
977         *rc=TR_CFG_NOPARSE;
978         goto cleanup;
979       }
980       tr_idp_realm_add(realms, new_realm);
981     } else if (tr_cfg_is_remote_realm(this_jrealm)) {
982       new_realm=tr_cfg_parse_one_remote_realm(tmp_ctx, this_jrealm, rc);
983       if ((*rc)!=TR_CFG_SUCCESS) {
984         tr_err("tr_cfg_parse_idp_realms: error decoding remote realm entry %d", ii+1);
985         *rc=TR_CFG_NOPARSE;
986         goto cleanup;
987       }
988       tr_idp_realm_add(realms, new_realm);
989     }
990   }
991   
992   *rc=TR_CFG_SUCCESS;
993   talloc_steal(mem_ctx, realms);
994
995 cleanup:
996   talloc_free(tmp_ctx);
997   return realms;
998 }
999
1000 static TR_GSS_NAMES *tr_cfg_parse_gss_names(TALLOC_CTX *mem_ctx, json_t *jgss_names, TR_CFG_RC *rc)
1001 {
1002   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1003   TR_GSS_NAMES *gn=NULL;
1004   json_t *jname=NULL;
1005   int ii=0;
1006   TR_NAME *name=NULL;
1007
1008   if ((rc==NULL) || (jgss_names==NULL)) {
1009     tr_err("tr_cfg_parse_gss_names: Bad parameters.");
1010     *rc=TR_CFG_BAD_PARAMS;
1011
1012   }
1013
1014   if (!json_is_array(jgss_names)) {
1015     tr_err("tr_cfg_parse_gss_names: gss_names not an array.");
1016     *rc=TR_CFG_NOPARSE;
1017     goto cleanup;
1018   }
1019
1020   gn=tr_gss_names_new(tmp_ctx);
1021   for (ii=0; ii<json_array_size(jgss_names); ii++) {
1022     jname=json_array_get(jgss_names, ii);
1023     if (!json_is_string(jname)) {
1024       tr_err("tr_cfg_parse_gss_names: Encountered non-string gss name.");
1025       *rc=TR_CFG_NOPARSE;
1026       goto cleanup;
1027     }
1028
1029     name=tr_new_name(json_string_value(jname));
1030     if (name==NULL) {
1031       tr_err("tr_cfg_parse_gss_names: Out of memory allocating gss name.");
1032       *rc=TR_CFG_NOMEM;
1033       goto cleanup;
1034     }
1035
1036     if (tr_gss_names_add(gn, name)!=0) {
1037       tr_free_name(name);
1038       tr_err("tr_cfg_parse_gss_names: Unable to add gss name to RP client.");
1039       *rc=TR_CFG_ERROR;
1040       goto cleanup;
1041     }
1042   }
1043
1044   talloc_steal(mem_ctx, gn);
1045   *rc=TR_CFG_SUCCESS;
1046
1047  cleanup:
1048   talloc_free(tmp_ctx);
1049   if ((*rc!=TR_CFG_SUCCESS) && (gn!=NULL))
1050     gn=NULL;
1051   return gn;
1052 }
1053
1054 /* default filter accepts realm and *.realm */
1055 static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_CFG_RC *rc)
1056 {
1057   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1058   TR_FILTER *filt=NULL;
1059   TR_CONSTRAINT *cons=NULL;
1060   TR_NAME *name=NULL;
1061   TR_NAME *n_prefix=tr_new_name("*.");
1062   TR_NAME *n_rp_realm_1=tr_new_name("rp_realm");
1063   TR_NAME *n_rp_realm_2=tr_new_name("rp_realm");
1064   TR_NAME *n_domain=tr_new_name("domain");
1065   TR_NAME *n_realm=tr_new_name("realm");
1066   
1067
1068   if ((realm==NULL) || (rc==NULL)) {
1069     tr_debug("tr_cfg_default_filter: invalid arguments.");
1070     if (rc!=NULL)
1071       *rc=TR_CFG_BAD_PARAMS;
1072     goto cleanup;
1073   }
1074
1075   if ((n_prefix==NULL) ||
1076       (n_rp_realm_1==NULL) ||
1077       (n_rp_realm_2==NULL) ||
1078       (n_domain==NULL) ||
1079       (n_realm==NULL)) {
1080     tr_debug("tr_cfg_default_filter: unable to allocate names.");
1081     *rc=TR_CFG_NOMEM;
1082     goto cleanup;
1083   }
1084
1085   filt=tr_filter_new(tmp_ctx);
1086   if (filt==NULL) {
1087     tr_debug("tr_cfg_default_filter: could not allocate filter.");
1088     *rc=TR_CFG_NOMEM;
1089     goto cleanup;
1090   }
1091   tr_filter_set_type(filt, TR_FILTER_TYPE_TID_INCOMING);
1092   filt->lines[0]=tr_fline_new(filt);
1093   if (filt->lines[0]==NULL) {
1094     tr_debug("tr_cfg_default_filter: could not allocate filter line.");
1095     *rc=TR_CFG_NOMEM;
1096     goto cleanup;
1097   }
1098
1099   filt->lines[0]->action=TR_FILTER_ACTION_ACCEPT;
1100   filt->lines[0]->specs[0]=tr_fspec_new(filt->lines[0]);
1101   filt->lines[0]->specs[0]->field=n_rp_realm_1;
1102   n_rp_realm_1=NULL; /* we don't own this name any more */
1103
1104   name=tr_dup_name(realm);
1105   if (name==NULL) {
1106     tr_debug("tr_cfg_default_filter: could not allocate realm name.");
1107     *rc=TR_CFG_NOMEM;
1108     goto cleanup;
1109   }
1110   tr_fspec_set_match(filt->lines[0]->specs[0], name);
1111   name=NULL; /* we no longer own the name */
1112
1113   /* now do the wildcard name */
1114   filt->lines[0]->specs[1]=tr_fspec_new(filt->lines[0]);
1115   filt->lines[0]->specs[1]->field=n_rp_realm_2;
1116   n_rp_realm_2=NULL; /* we don't own this name any more */
1117
1118   if (NULL==(name=tr_name_cat(n_prefix, realm))) {
1119     tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name.");
1120     *rc=TR_CFG_NOMEM;
1121     goto cleanup;
1122   }
1123
1124   tr_fspec_set_match(filt->lines[0]->specs[1], name);
1125   name=NULL; /* we no longer own the name */
1126
1127   /* domain constraint */
1128   if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
1129     tr_debug("tr_cfg_default_filter: could not allocate domain constraint.");
1130     *rc=TR_CFG_NOMEM;
1131     goto cleanup;
1132   }
1133
1134   cons->type=n_domain;
1135   n_domain=NULL; /* belongs to the constraint now */
1136   name=tr_dup_name(realm);
1137   if (name==NULL) {
1138     tr_debug("tr_cfg_default_filter: could not allocate realm name for domain constraint.");
1139     *rc=TR_CFG_NOMEM;
1140     goto cleanup;
1141   }
1142   cons->matches[0]=name;
1143   name=tr_name_cat(n_prefix, realm);
1144   if (name==NULL) {
1145     tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for domain constraint.");
1146     *rc=TR_CFG_NOMEM;
1147     goto cleanup;
1148   }
1149   cons->matches[1]=name;
1150   name=NULL;
1151   filt->lines[0]->domain_cons=cons;
1152
1153
1154   /* realm constraint */
1155   if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
1156     tr_debug("tr_cfg_default_filter: could not allocate realm constraint.");
1157     *rc=TR_CFG_NOMEM;
1158     goto cleanup;
1159   }
1160
1161   cons->type=n_realm;
1162   n_realm=NULL; /* belongs to the constraint now */
1163   name=tr_dup_name(realm);
1164   if (name==NULL) {
1165     tr_debug("tr_cfg_default_filter: could not allocate realm name for realm constraint.");
1166     *rc=TR_CFG_NOMEM;
1167     goto cleanup;
1168   }
1169   cons->matches[0]=name;
1170   name=tr_name_cat(n_prefix, realm);
1171   if (name==NULL) {
1172     tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for realm constraint.");
1173     *rc=TR_CFG_NOMEM;
1174     goto cleanup;
1175   }
1176   cons->matches[1]=name;
1177   name=NULL;
1178   filt->lines[0]->realm_cons=cons;
1179
1180   talloc_steal(mem_ctx, filt);
1181 cleanup:
1182   talloc_free(tmp_ctx);
1183
1184   if (*rc!=TR_CFG_SUCCESS)
1185     filt=NULL;
1186
1187   if (n_prefix!=NULL)
1188     tr_free_name(n_prefix);
1189   if (n_rp_realm_1!=NULL)
1190     tr_free_name(n_rp_realm_1);
1191   if (n_rp_realm_2!=NULL)
1192     tr_free_name(n_rp_realm_2);
1193   if (n_realm!=NULL)
1194     tr_free_name(n_realm);
1195   if (n_domain!=NULL)
1196     tr_free_name(n_domain);
1197   if (name!=NULL)
1198     tr_free_name(name);
1199
1200   return filt;
1201 }
1202
1203 /* parses rp client */
1204 static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
1205 {
1206   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1207   TR_RP_CLIENT *client=NULL;
1208   TR_CFG_RC call_rc=TR_CFG_ERROR;
1209   TR_FILTER *new_filt=NULL;
1210   TR_NAME *realm=NULL;
1211   json_t *jfilt=NULL;
1212   json_t *jrealm_id=NULL;
1213
1214   *rc=TR_CFG_ERROR; /* default to error if not set */
1215
1216   if ((!jrealm) || (!rc)) {
1217     tr_err("tr_cfg_parse_one_rp_client: Bad parameters.");
1218     if (rc)
1219       *rc=TR_CFG_BAD_PARAMS;
1220     goto cleanup;
1221   }
1222
1223   if ((NULL==(jrealm_id=json_object_get(jrealm, "realm"))) || (!json_is_string(jrealm_id))) {
1224     tr_debug("tr_cfg_parse_one_rp_client: no realm ID found.");
1225     *rc=TR_CFG_BAD_PARAMS;
1226     goto cleanup;
1227   } 
1228
1229   tr_debug("tr_cfg_parse_one_rp_client: realm_id=\"%s\"", json_string_value(jrealm_id));
1230   realm=tr_new_name(json_string_value(jrealm_id));
1231   if (realm==NULL) {
1232     tr_err("tr_cfg_parse_one_rp_client: could not allocate realm ID.");
1233     *rc=TR_CFG_NOMEM;
1234     goto cleanup;
1235   }
1236
1237   if (NULL==(client=tr_rp_client_new(tmp_ctx))) {
1238     tr_err("tr_cfg_parse_one_rp_client: could not allocate rp client.");
1239     *rc=TR_CFG_NOMEM;
1240     goto cleanup;
1241   }
1242
1243   client->gss_names=tr_cfg_parse_gss_names(client, json_object_get(jrealm, "gss_names"), &call_rc);
1244
1245   if (call_rc!=TR_CFG_SUCCESS) {
1246     tr_err("tr_cfg_parse_one_rp_client: could not parse gss_names.");
1247     *rc=TR_CFG_NOPARSE;
1248     goto cleanup;
1249   }
1250
1251   /* parse filters */
1252   jfilt=json_object_get(jrealm, "filters");
1253   if (jfilt!=NULL) {
1254     new_filt=tr_cfg_parse_filters(tmp_ctx, jfilt, &call_rc);
1255     if (call_rc!=TR_CFG_SUCCESS) {
1256       tr_err("tr_cfg_parse_one_rp_client: could not parse filters.");
1257       *rc=TR_CFG_NOPARSE;
1258       goto cleanup;
1259     }
1260   } else {
1261     tr_debug("tr_cfg_parse_one_rp_client: no filters specified, using default filters.");
1262     new_filt=tr_cfg_default_filter(tmp_ctx, realm, &call_rc);
1263     if (call_rc!=TR_CFG_SUCCESS) {
1264       tr_err("tr_cfg_parse_one_rp_client: could not set default filters.");
1265       *rc=TR_CFG_NOPARSE;
1266       goto cleanup;
1267     }
1268   }
1269
1270   tr_rp_client_set_filter(client, new_filt);
1271   *rc=TR_CFG_SUCCESS;
1272
1273   cleanup:
1274   if (realm!=NULL)
1275     tr_free_name(realm);
1276
1277     if (*rc==TR_CFG_SUCCESS)
1278       talloc_steal(mem_ctx, client);
1279     else {
1280       talloc_free(client);
1281       client=NULL;
1282     }
1283
1284     talloc_free(tmp_ctx);
1285     return client;
1286   }
1287
1288   /* Determine whether the realm is an RP realm */
1289 static int tr_cfg_is_rp_realm(json_t *jrealm)
1290 {
1291   /* Check that we have a gss name. */
1292   if (NULL != json_object_get(jrealm, "gss_names"))
1293     return 1;
1294   else
1295     return 0;
1296 }
1297
1298 /* Parse any rp clients in the j_realms object. Ignores other realms. */
1299 static TR_RP_CLIENT *tr_cfg_parse_rp_clients(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
1300 {
1301   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1302   TR_RP_CLIENT *clients=NULL;
1303   TR_RP_CLIENT *new_client=NULL;
1304   json_t *this_jrealm=NULL;
1305   int ii=0;
1306
1307   *rc=TR_CFG_ERROR;
1308   if ((jrealms==NULL) || (!json_is_array(jrealms))) {
1309     tr_err("tr_cfg_parse_rp_clients: realms not an array");
1310     *rc=TR_CFG_BAD_PARAMS;
1311     goto cleanup;
1312   }
1313
1314   for (ii=0; ii<json_array_size(jrealms); ii++) {
1315     this_jrealm=json_array_get(jrealms, ii);
1316     if (tr_cfg_is_rp_realm(this_jrealm)) {
1317       new_client=tr_cfg_parse_one_rp_client(tmp_ctx, this_jrealm, rc);
1318       if ((*rc)!=TR_CFG_SUCCESS) {
1319         tr_err("tr_cfg_parse_rp_clients: error decoding realm entry %d", ii+1);
1320         *rc=TR_CFG_NOPARSE;
1321         goto cleanup;
1322       }
1323       tr_rp_client_add(clients, new_client);
1324     }
1325   }
1326   
1327   *rc=TR_CFG_SUCCESS;
1328   talloc_steal(mem_ctx, clients);
1329
1330 cleanup:
1331   talloc_free(tmp_ctx);
1332   return clients;
1333 }
1334
1335 /* takes a talloc context, but currently does not use it */
1336 static TR_NAME *tr_cfg_parse_org_name(TALLOC_CTX *mem_ctx, json_t *j_org, TR_CFG_RC *rc)
1337 {
1338   TR_NAME *name=NULL;
1339
1340   if ((j_org==NULL) || (rc==NULL) || (!json_is_string(j_org))) {
1341     tr_debug("tr_cfg_parse_org_name: Bad parameters.");
1342     if (rc!=NULL)
1343       *rc = TR_CFG_BAD_PARAMS; /* fill in return value if we can */
1344     return NULL;
1345   }
1346
1347   name=tr_new_name(json_string_value(j_org));
1348   if (name==NULL)
1349     *rc=TR_CFG_NOMEM;
1350   else
1351     *rc=TR_CFG_SUCCESS;
1352   return name;
1353 }
1354
1355 #if 0
1356 /* TODO: are we using this? JLR */
1357 /* Update the community information with data from a new batch of IDP realms.
1358  * May partially add realms if there is a failure, no guarantees.
1359  * Call like comms=tr_comm_idp_update(comms, new_realms, &rc) */
1360 static TR_COMM *tr_cfg_comm_idp_update(TALLOC_CTX *mem_ctx,
1361                                        TR_COMM_TABLE *ctab,
1362                                        TR_IDP_REALM *new_realms,
1363                                        TR_CFG_RC *rc)
1364 {
1365   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1366   TR_COMM *comm=NULL; /* community looked up in comms table */
1367   TR_COMM *new_comms=NULL; /* new communities as we create them */
1368   TR_IDP_REALM *realm=NULL;
1369   TR_APC *apc=NULL; /* apc of one realm */
1370
1371   if (rc==NULL) {
1372     *rc=TR_CFG_BAD_PARAMS;
1373     goto cleanup;
1374   }
1375
1376   /* start with an empty list communities, then fill that in */
1377   for (realm=new_realms; realm!=NULL; realm=realm->next) {
1378     for (apc=realm->apcs; apc!=NULL; apc=apc->next) {
1379       comm=tr_comm_lookup(comms, apc->id);
1380       if (comm==NULL) {
1381         comm=tr_comm_new(tmp_ctx);
1382         if (comm==NULL) {
1383           tr_debug("tr_cfg_comm_idp_update: unable to allocate new community.");
1384           *rc=TR_CFG_NOMEM;
1385           goto cleanup;
1386         }
1387         /* fill in the community with info */
1388         comm->type=TR_COMM_APC; /* realms added this way are in APCs */
1389         comm->expiration_interval=TR_DEFAULT_APC_EXPIRATION_INTERVAL;
1390         tr_comm_set_id(comm, tr_dup_name(apc->id));
1391         tr_comm_add_idp_realm(comm, realm);
1392         tr_comm_add(new_comms, comm);
1393       } else {
1394         /* add this realm to the comm */
1395         tr_comm_add_idp_realm(comm, realm);
1396       }
1397     }
1398   }
1399
1400   /* we successfully built a list, add it to the other list */
1401   tr_comm_add(comms, new_comms);
1402   talloc_steal(mem_ctx, comms);
1403  cleanup:
1404   talloc_free(tmp_ctx);
1405   return comms;
1406 }
1407 #endif
1408
1409 static TR_CFG_RC tr_cfg_parse_one_local_org(TR_CFG *trc, json_t *jlorg)
1410 {
1411   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1412   TR_CFG_RC retval=TR_CFG_ERROR; /* our return code */
1413   TR_CFG_RC rc=TR_CFG_ERROR; /* return code from functions we call */
1414   TR_NAME *org_name=NULL;
1415   json_t *j_org=NULL;
1416   json_t *j_realms=NULL;
1417   TR_IDP_REALM *new_idp_realms=NULL;
1418   TR_RP_CLIENT *new_rp_clients=NULL;
1419
1420   tr_debug("tr_cfg_parse_one_local_org: parsing local organization");
1421
1422   /* get organization_name (optional) */
1423   if (NULL==(j_org=json_object_get(jlorg, "organization_name"))) {
1424     tr_debug("tr_cfg_parse_one_local_org: organization_name unspecified");
1425   } else {
1426     org_name=tr_cfg_parse_org_name(tmp_ctx, j_org, &rc);
1427     if (rc==TR_CFG_SUCCESS) {
1428       tr_debug("tr_cfg_parse_one_local_org: organization_name=\"%.*s\"",
1429                org_name->len,
1430                org_name->buf);
1431       /* we don't actually do anything with this, but we could */
1432       tr_free_name(org_name);
1433       org_name=NULL; 
1434     }
1435   }
1436
1437   /* Now get realms. Allow this to be missing; even though that is a pointless organization entry,
1438    * it's harmless. Report a warning because that might be unintentional. */
1439   if (NULL==(j_realms=json_object_get(jlorg, "realms"))) {
1440     tr_warning("tr_cfg_parse_one_local_org: warning - no realms in this local organization");
1441   } else {
1442     /* Allocate in the tmp_ctx so these will be cleaned up if we do not complete successfully. */
1443     new_idp_realms=tr_cfg_parse_idp_realms(tmp_ctx, j_realms, &rc);
1444     if (rc!=TR_CFG_SUCCESS)
1445       goto cleanup;
1446
1447     new_rp_clients=tr_cfg_parse_rp_clients(tmp_ctx, j_realms, &rc);
1448     if (rc!=TR_CFG_SUCCESS)
1449       goto cleanup;
1450   }
1451   retval=TR_CFG_SUCCESS;
1452   
1453 cleanup:
1454   /* if we succeeded, link things to the configuration and move out of tmp context */
1455   if (retval==TR_CFG_SUCCESS) {
1456     if (new_idp_realms!=NULL) {
1457       tr_idp_realm_add(trc->ctable->idp_realms, new_idp_realms); /* fixes talloc contexts except for head*/
1458       talloc_steal(trc, trc->ctable->idp_realms); /* make sure the head is in the right context */
1459     }
1460
1461     if (new_rp_clients!=NULL) {
1462       tr_rp_client_add(trc->rp_clients, new_rp_clients); /* fixes talloc contexts */
1463       talloc_steal(trc, trc->rp_clients); /* make sure head is in the right context */
1464     }
1465   }
1466
1467   talloc_free(tmp_ctx);
1468   return rc;
1469 }
1470
1471 /* Parse local organizations if present. Returns success if there are none. On failure, the configuration is unreliable. */
1472 static TR_CFG_RC tr_cfg_parse_local_orgs(TR_CFG *trc, json_t *jcfg)
1473 {
1474   json_t *jlocorgs=NULL;
1475   int ii=0;
1476
1477   jlocorgs=json_object_get(jcfg, "local_organizations");
1478   if (jlocorgs==NULL)
1479     return TR_CFG_SUCCESS;
1480
1481   if (!json_is_array(jlocorgs)) {
1482     tr_err("tr_cfg_parse_local_orgs: local_organizations is not an array.");
1483     return TR_CFG_NOPARSE;
1484   }
1485
1486   for (ii=0; ii<json_array_size(jlocorgs); ii++) {
1487     if (tr_cfg_parse_one_local_org(trc, json_array_get(jlocorgs, ii))!=TR_CFG_SUCCESS) {
1488       tr_err("tr_cfg_parse_local_orgs: error parsing local_organization %d.", ii+1);
1489       return TR_CFG_NOPARSE;
1490     }
1491   }
1492
1493   return TR_CFG_SUCCESS;
1494 }
1495
1496 static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
1497 {
1498   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1499   json_t *jhost=NULL;
1500   json_t *jport=NULL;
1501   json_t *jgss=NULL;
1502   TRP_PEER *new_peer=NULL;
1503   TR_GSS_NAMES *names=NULL;
1504   TR_CFG_RC rc=TR_CFG_ERROR;
1505
1506   jhost=json_object_get(jporg, "hostname");
1507   jport=json_object_get(jporg, "port");
1508   jgss=json_object_get(jporg, "gss_names");
1509
1510   if ((jhost==NULL) || (!json_is_string(jhost))) {
1511     tr_err("tr_cfg_parse_one_peer_org: hostname not specified or not a string.");
1512     rc=TR_CFG_NOPARSE;
1513     goto cleanup;
1514   }
1515
1516   if ((jport!=NULL) && (!json_is_number(jport))) {
1517     /* note that not specifying the port is allowed, but if set it must be a number */
1518     tr_err("tr_cfg_parse_one_peer_org: port is not a number.");
1519     rc=TR_CFG_NOPARSE;
1520     goto cleanup;
1521   }
1522   
1523   if ((jgss==NULL) || (!json_is_array(jgss))) {
1524     tr_err("tr_cfg_parse_one_peer_org: gss_names not specified or not an array.");
1525     rc=TR_CFG_NOPARSE;
1526     goto cleanup;
1527   }
1528
1529   new_peer=trp_peer_new(tmp_ctx);
1530   if (new_peer==NULL) {
1531     tr_err("tr_cfg_parse_one_peer_org: could not allocate new peer.");
1532     rc=TR_CFG_NOMEM;
1533     goto cleanup;
1534   }
1535
1536   trp_peer_set_server(new_peer, json_string_value(jhost));
1537   if (jport==NULL)
1538     trp_peer_set_port(new_peer, TRP_PORT);
1539   else
1540     trp_peer_set_port(new_peer, json_integer_value(jport));
1541
1542   names=tr_cfg_parse_gss_names(tmp_ctx, jgss, &rc);
1543   if (rc!=TR_CFG_SUCCESS) {
1544     tr_err("tr_cfg_parse_one_peer_org: unable to parse gss names.");
1545     rc=TR_CFG_NOPARSE;
1546     goto cleanup;
1547   }
1548   trp_peer_set_gss_names(new_peer, names);
1549
1550   /* success! */
1551   trp_ptable_add(trc->peers, new_peer);
1552   rc=TR_CFG_SUCCESS;
1553
1554  cleanup:
1555   talloc_free(tmp_ctx);
1556   return rc;
1557 }
1558
1559 /* Parse peer organizations, if present. Returns success if there are none. */
1560 static TR_CFG_RC tr_cfg_parse_peer_orgs(TR_CFG *trc, json_t *jcfg)
1561 {
1562   json_t *jpeerorgs=NULL;
1563   int ii=0;
1564
1565   jpeerorgs=json_object_get(jcfg, "peer_organizations");
1566   if (jpeerorgs==NULL)
1567     return TR_CFG_SUCCESS;
1568
1569   if (!json_is_array(jpeerorgs)) {
1570     tr_err("tr_cfg_parse_peer_orgs: peer_organizations is not an array.");
1571     return TR_CFG_NOPARSE;
1572   }
1573
1574   for (ii=0; ii<json_array_size(jpeerorgs); ii++) {
1575     if (tr_cfg_parse_one_peer_org(trc, json_array_get(jpeerorgs, ii))!=TR_CFG_SUCCESS) {
1576       tr_err("tr_cfg_parse_peer_orgs: error parsing peer_organization %d.", ii+1);
1577       return TR_CFG_NOPARSE;
1578     }
1579   }
1580
1581   return TR_CFG_SUCCESS;
1582 }
1583              
1584 static TR_CFG_RC tr_cfg_parse_default_servers (TR_CFG *trc, json_t *jcfg) 
1585 {
1586   json_t *jdss = NULL;
1587   TR_CFG_RC rc = TR_CFG_SUCCESS;
1588   TR_AAA_SERVER *ds = NULL;
1589   int i = 0;
1590
1591   if ((!trc) || (!jcfg))
1592     return TR_CFG_BAD_PARAMS;
1593
1594   /* If there are default servers, store them */
1595   if ((NULL != (jdss = json_object_get(jcfg, "default_servers"))) &&
1596       (json_is_array(jdss)) &&
1597       (0 < json_array_size(jdss))) {
1598
1599     for (i = 0; i < json_array_size(jdss); i++) {
1600       if (NULL == (ds = tr_cfg_parse_one_aaa_server(trc,
1601                                                     json_array_get(jdss, i), 
1602                                                    &rc))) {
1603         return rc;
1604       }
1605       tr_debug("tr_cfg_parse_default_servers: Default server configured: %s", ds->hostname->buf);
1606       ds->next = trc->default_servers;
1607       trc->default_servers = ds;
1608     }
1609   } 
1610
1611   tr_debug("tr_cfg_parse_default_servers: Finished (rc=%d)", rc);
1612   return rc;
1613 }
1614
1615 static void tr_cfg_parse_comm_idps(TR_CFG *trc, json_t *jidps, TR_COMM *comm, TR_CFG_RC *rc)
1616 {
1617   TR_IDP_REALM *found_idp=NULL;
1618   int i = 0;
1619
1620   if ((!trc) ||
1621       (!jidps) ||
1622       (!json_is_array(jidps))) {
1623     if (rc)
1624       *rc = TR_CFG_BAD_PARAMS;
1625     return;
1626   }
1627
1628   for (i=0; i < json_array_size(jidps); i++) {
1629     found_idp=tr_cfg_find_idp(trc, 
1630                               tr_new_name((char *)json_string_value(json_array_get(jidps, i))), 
1631                               rc);
1632     if ((found_idp==NULL) || (*rc!=TR_CFG_SUCCESS)) {
1633       tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.", 
1634                (char *)json_string_value(json_array_get(jidps, i)));
1635       *rc=TR_CFG_ERROR;
1636       return;
1637     }
1638     tr_comm_add_idp_realm(trc->ctable, comm, found_idp, NULL, NULL); /* no provenance, never expires */
1639   }
1640
1641   *rc=TR_CFG_SUCCESS;
1642   return;
1643 }
1644
1645 static void tr_cfg_parse_comm_rps(TR_CFG *trc, json_t *jrps, TR_COMM *comm, TR_CFG_RC *rc)
1646 {
1647   TR_RP_REALM *found_rp=NULL;
1648   TR_RP_REALM *new_rp=NULL;
1649   TR_NAME *rp_name=NULL;
1650   const char *s=NULL;
1651   int ii=0;
1652
1653   if ((!trc) ||
1654       (!jrps) ||
1655       (!json_is_array(jrps))) {
1656     if (rc)
1657       *rc = TR_CFG_BAD_PARAMS;
1658     return;
1659   }
1660
1661   for (ii=0; ii<json_array_size(jrps); ii++) {
1662     /* get the RP name as a string */
1663     s=json_string_value(json_array_get(jrps, ii));
1664     if (s==NULL) {
1665       tr_notice("tr_cfg_parse_comm_rps: null RP found in community %.*s, ignoring.",
1666                 tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1667       continue;
1668     }
1669
1670     /* convert string to TR_NAME */
1671     rp_name=tr_new_name(s);
1672     if (rp_name==NULL) {
1673       tr_err("tr_cfg_parse_comm_rps: unable to allocate RP name for %s in community %.*s.",
1674              s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1675     }
1676
1677     /* see if we already have this RP in this community */
1678     found_rp=tr_comm_find_rp(trc->ctable, comm, rp_name);
1679     if (found_rp!=NULL) {
1680       tr_notice("tr_cfg_parse_comm_rps: RP %s repeated in community %.*s.",
1681                 s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1682       tr_free_name(rp_name);
1683       continue;
1684     }
1685
1686     /* Add the RP to the community, first see if we have the RP in any community */
1687     found_rp=tr_rp_realm_lookup(trc->ctable->rp_realms, rp_name);
1688     if (found_rp!=NULL) {
1689       tr_debug("tr_cfg_parse_comm_rps: RP realm %s already exists.", s);
1690       new_rp=found_rp; /* use it rather than creating a new realm record */
1691     } else {
1692       new_rp=tr_rp_realm_new(NULL);
1693       if (new_rp==NULL) {
1694         tr_err("tr_cfg_parse_comm_rps: unable to allocate RP record for %s in community %.*s.",
1695                s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1696       }
1697       tr_debug("tr_cfg_parse_comm_rps: setting name to %s", rp_name->buf);
1698       tr_rp_realm_set_id(new_rp, rp_name);
1699       rp_name=NULL; /* rp_name no longer belongs to us */
1700       tr_rp_realm_add(trc->ctable->rp_realms, new_rp);
1701     }
1702     tr_comm_add_rp_realm(trc->ctable, comm, new_rp, NULL, NULL);
1703   }
1704 }
1705
1706 static TR_COMM *tr_cfg_parse_one_comm (TALLOC_CTX *mem_ctx, TR_CFG *trc, json_t *jcomm, TR_CFG_RC *rc)
1707 {
1708   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1709   TR_COMM *comm = NULL;
1710   json_t *jid = NULL;
1711   json_t *jtype = NULL;
1712   json_t *japcs = NULL;
1713   json_t *jidps = NULL;
1714   json_t *jrps = NULL;
1715
1716   if ((!trc) || (!jcomm) || (!rc)) {
1717     tr_debug("tr_cfg_parse_one_comm: Bad parameters.");
1718     if (rc)
1719       *rc = TR_CFG_BAD_PARAMS;
1720     goto cleanup;
1721   }
1722
1723   comm=tr_comm_new(tmp_ctx);
1724   if (comm==NULL) {
1725     tr_crit("tr_cfg_parse_one_comm: Out of memory.");
1726     *rc = TR_CFG_NOMEM;
1727     goto cleanup;
1728   }
1729
1730
1731   if ((NULL == (jid = json_object_get(jcomm, "community_id"))) ||
1732       (!json_is_string(jid)) ||
1733       (NULL == (jtype = json_object_get(jcomm, "type"))) ||
1734       (!json_is_string(jtype)) ||
1735       (NULL == (japcs = json_object_get(jcomm, "apcs"))) ||
1736       (!json_is_array(japcs)) ||
1737       (NULL == (jidps = json_object_get(jcomm, "idp_realms"))) ||
1738       (!json_is_array(jidps)) ||
1739       (NULL == (jrps = json_object_get(jcomm, "rp_realms"))) ||
1740       (!json_is_array(jrps))) {
1741     tr_debug("tr_cfg_parse_one_comm: Error parsing Communities configuration.");
1742     *rc = TR_CFG_NOPARSE;
1743     comm=NULL;
1744     goto cleanup;
1745   }
1746
1747   tr_comm_set_id(comm, tr_new_name(json_string_value(jid)));
1748   if (NULL == tr_comm_get_id(comm)) {
1749     tr_debug("tr_cfg_parse_one_comm: No memory for community id.");
1750     *rc = TR_CFG_NOMEM;
1751     comm=NULL;
1752     goto cleanup;
1753   }
1754
1755   if (0 == strcmp(json_string_value(jtype), "apc")) {
1756     comm->type = TR_COMM_APC;
1757   } else if (0 == strcmp(json_string_value(jtype), "coi")) {
1758     comm->type = TR_COMM_COI;
1759     if (NULL == (comm->apcs = tr_cfg_parse_apcs(trc, japcs, rc))) {
1760       tr_debug("tr_cfg_parse_one_comm: Can't parse APCs for COI %s.",
1761                tr_comm_get_id(comm)->buf);
1762       comm=NULL;
1763       goto cleanup;
1764     }
1765   } else {
1766     tr_debug("tr_cfg_parse_one_comm: Invalid community type, comm = %s, type = %s",
1767              tr_comm_get_id(comm)->buf, json_string_value(jtype));
1768     *rc = TR_CFG_NOPARSE;
1769     comm=NULL;
1770     goto cleanup;
1771   }
1772
1773   tr_cfg_parse_comm_idps(trc, jidps, comm, rc);
1774   if (TR_CFG_SUCCESS != *rc) {
1775     tr_debug("tr_cfg_parse_one_comm: Can't parse IDP realms for comm %s.",
1776              tr_comm_get_id(comm)->buf);
1777     comm=NULL;
1778     goto cleanup;
1779   }
1780
1781   tr_cfg_parse_comm_rps(trc, jrps, comm, rc);
1782   if (TR_CFG_SUCCESS != *rc) {
1783     tr_debug("tr_cfg_parse_one_comm: Can't parse RP realms for comm %s .",
1784              tr_comm_get_id(comm)->buf);
1785     comm=NULL;
1786     goto cleanup;
1787   }
1788
1789   if (TR_COMM_APC == comm->type) {
1790     json_t *jexpire  = json_object_get(jcomm, "expiration_interval");
1791     comm->expiration_interval = 43200; /*30 days*/
1792     if (jexpire) {
1793         if (!json_is_integer(jexpire)) {
1794           fprintf(stderr, "tr_parse_one_comm: expiration_interval is not an integer\n");
1795     comm=NULL;
1796     goto cleanup;
1797         }
1798         comm->expiration_interval = json_integer_value(jexpire);
1799         if (comm->expiration_interval <= 10)
1800           comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
1801         if (comm->expiration_interval > 129600) /* 90 days*/
1802         comm->expiration_interval = 129600;
1803     }
1804   }
1805
1806 cleanup:
1807   if (comm!=NULL)
1808     talloc_steal(mem_ctx, comm);
1809   talloc_free(tmp_ctx);
1810   return comm;
1811 }
1812
1813 static TR_CFG_RC tr_cfg_parse_comms (TR_CFG *trc, json_t *jcfg) 
1814 {
1815   json_t *jcomms = NULL;
1816   TR_CFG_RC rc = TR_CFG_SUCCESS;
1817   TR_COMM *comm = NULL;
1818   int i = 0;
1819
1820   if ((!trc) || (!jcfg)) {
1821     tr_debug("tr_cfg_parse_comms: Bad Parameters.");
1822     return TR_CFG_BAD_PARAMS;
1823   }
1824
1825   if (NULL != (jcomms = json_object_get(jcfg, "communities"))) {
1826     if (!json_is_array(jcomms)) {
1827       return TR_CFG_NOPARSE;
1828     }
1829
1830     for (i = 0; i < json_array_size(jcomms); i++) {
1831       if (NULL == (comm = tr_cfg_parse_one_comm(NULL, /* TODO: use a talloc context */
1832                                                 trc, 
1833                                                 json_array_get(jcomms, i), 
1834                                                &rc))) {
1835         return rc;
1836       }
1837       tr_debug("tr_cfg_parse_comms: Community configured: %s.",
1838                tr_comm_get_id(comm)->buf);
1839
1840       tr_comm_table_add_comm(trc->ctable, comm);
1841     }
1842   }
1843   tr_debug("tr_cfg_parse_comms: Finished (rc=%d)", rc);
1844   return rc;
1845 }
1846
1847 TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
1848 {
1849   TR_CFG_RC rc = TR_CFG_SUCCESS;
1850
1851   if (!trc)
1852     return TR_CFG_BAD_PARAMS;
1853
1854   if ((NULL == trc->internal)||
1855       (NULL == trc->internal->hostname)) {
1856     tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
1857     rc = TR_CFG_ERROR;
1858   }
1859
1860   if (NULL == trc->rp_clients) {
1861     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
1862     rc = TR_CFG_ERROR;
1863   }
1864
1865   if (0==tr_comm_table_size(trc->ctable)) {
1866     tr_debug("tr_cfg_validate: Error: No Communities configured");
1867     rc = TR_CFG_ERROR;
1868   }
1869
1870   if ((NULL == trc->default_servers) && (NULL == trc->ctable->idp_realms)) {
1871     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
1872     rc = TR_CFG_ERROR;
1873   }
1874   
1875   return rc;
1876 }
1877
1878 /* Join two paths and return a pointer to the result. This should be freed
1879  * via talloc_free. Returns NULL on failure. */
1880 static char *join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
1881 {
1882   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
1883 }
1884
1885 static void tr_cfg_log_json_error(const char *label, json_error_t *rc)
1886 {
1887   tr_debug("%s: JSON parse error on line %d: %s",
1888            label,
1889            rc->line,
1890            rc->text);
1891 }
1892
1893 TR_CFG_RC tr_cfg_parse_one_config_file(TR_CFG *cfg, const char *file_with_path)
1894 {
1895   json_t *jcfg=NULL;
1896   json_t *jser=NULL;
1897   json_error_t rc;
1898
1899   if (NULL==(jcfg=json_load_file(file_with_path, 
1900                                  JSON_DISABLE_EOF_CHECK, &rc))) {
1901     tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.", 
1902              file_with_path);
1903     tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
1904     return TR_CFG_NOPARSE;
1905   }
1906
1907   // Look for serial number and log it if it exists
1908   if (NULL!=(jser=json_object_get(jcfg, "serial_number"))) {
1909     if (json_is_number(jser)) {
1910       tr_notice("tr_parse_one_config_file: Attempting to load revision %" JSON_INTEGER_FORMAT " of '%s'.",
1911                 json_integer_value(jser),
1912                 file_with_path);
1913     }
1914   }
1915
1916   if ((TR_CFG_SUCCESS != tr_cfg_parse_internal(cfg, jcfg)) ||
1917       (TR_CFG_SUCCESS != tr_cfg_parse_local_orgs(cfg, jcfg)) ||
1918       (TR_CFG_SUCCESS != tr_cfg_parse_peer_orgs(cfg, jcfg)) ||
1919       (TR_CFG_SUCCESS != tr_cfg_parse_default_servers(cfg, jcfg)) ||
1920       (TR_CFG_SUCCESS != tr_cfg_parse_comms(cfg, jcfg)))
1921     return TR_CFG_ERROR;
1922
1923   return TR_CFG_SUCCESS;
1924 }
1925
1926 /* Reads configuration files in config_dir ("" or "./" will use the current directory). */
1927 TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, const char *config_dir, int n, struct dirent **cfg_files)
1928 {
1929   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1930   char *file_with_path;
1931   int ii;
1932   TR_CFG_RC cfg_rc=TR_CFG_ERROR;
1933
1934   if ((!cfg_mgr) || (!cfg_files) || (n<=0)) {
1935     cfg_rc=TR_CFG_BAD_PARAMS;
1936     goto cleanup;
1937   }
1938
1939   if (cfg_mgr->new != NULL)
1940     tr_cfg_free(cfg_mgr->new);
1941   cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
1942   if (cfg_mgr->new == NULL) {
1943     cfg_rc=TR_CFG_NOMEM;
1944     goto cleanup;
1945   }
1946
1947   cfg_mgr->new->peers=trp_ptable_new(cfg_mgr);
1948
1949   /* Parse configuration information from each config file */
1950   for (ii=0; ii<n; ii++) {
1951     file_with_path=join_paths(tmp_ctx, config_dir, cfg_files[ii]->d_name); /* must free result with talloc_free */
1952     if(file_with_path == NULL) {
1953       tr_crit("tr_parse_config: error joining path.");
1954       cfg_rc=TR_CFG_NOMEM;
1955       goto cleanup;
1956     }
1957     tr_debug("tr_parse_config: Parsing %s.", cfg_files[ii]->d_name); /* print the filename without the path */
1958     cfg_rc=tr_cfg_parse_one_config_file(cfg_mgr->new, file_with_path);
1959     if (cfg_rc!=TR_CFG_SUCCESS) {
1960       tr_crit("tr_parse_config: Error parsing %s", file_with_path);
1961       goto cleanup;
1962     }
1963     talloc_free(file_with_path); /* done with filename */
1964   }
1965
1966   /* make sure we got a complete, consistent configuration */
1967   if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
1968     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
1969     cfg_rc=TR_CFG_ERROR;
1970     goto cleanup;
1971   }
1972
1973   /* success! */
1974   talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
1975   cfg_rc=TR_CFG_SUCCESS;
1976
1977 cleanup:
1978   talloc_free(tmp_ctx);
1979   return cfg_rc;
1980 }
1981
1982 TR_IDP_REALM *tr_cfg_find_idp (TR_CFG *tr_cfg, TR_NAME *idp_id, TR_CFG_RC *rc)
1983 {
1984
1985   TR_IDP_REALM *cfg_idp;
1986
1987   if ((!tr_cfg) || (!idp_id)) {
1988     if (rc)
1989       *rc = TR_CFG_BAD_PARAMS;
1990     return NULL;
1991   }
1992
1993   for (cfg_idp = tr_cfg->ctable->idp_realms; NULL != cfg_idp; cfg_idp = cfg_idp->next) {
1994     if (!tr_name_cmp (idp_id, cfg_idp->realm_id)) {
1995       tr_debug("tr_cfg_find_idp: Found %s.", idp_id->buf);
1996       return cfg_idp;
1997     }
1998   }
1999   /* if we didn't find one, return NULL */ 
2000   return NULL;
2001 }
2002
2003 TR_RP_CLIENT *tr_cfg_find_rp (TR_CFG *tr_cfg, TR_NAME *rp_gss, TR_CFG_RC *rc)
2004 {
2005   TR_RP_CLIENT *cfg_rp;
2006
2007   if ((!tr_cfg) || (!rp_gss)) {
2008     if (rc)
2009       *rc = TR_CFG_BAD_PARAMS;
2010     return NULL;
2011   }
2012
2013   for (cfg_rp = tr_cfg->rp_clients; NULL != cfg_rp; cfg_rp = cfg_rp->next) {
2014     if (tr_gss_names_matches(cfg_rp->gss_names, rp_gss)) {
2015       tr_debug("tr_cfg_find_rp: Found %s.", rp_gss->buf);
2016       return cfg_rp;
2017     }
2018   }
2019   /* if we didn't find one, return NULL */ 
2020   return NULL;
2021 }
2022
2023 static int is_cfg_file(const struct dirent *dent) {
2024   int n;
2025
2026   /* Only accept filenames ending in ".cfg" and starting with a character
2027    * other than an ASCII '.' */
2028
2029   /* filename must be at least 4 characters long to be acceptable */
2030   n=strlen(dent->d_name);
2031   if (n < 4) {
2032     return 0;
2033   }
2034
2035   /* filename must not start with '.' */
2036   if ('.' == dent->d_name[0]) {
2037     return 0;
2038   }
2039
2040   /* If the above passed and the last four characters of the filename are .cfg, accept.
2041    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
2042   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
2043     return 1;
2044   }
2045
2046   /* otherwise, return false. */
2047   return 0;
2048 }
2049
2050 /* Find configuration files in a particular directory. Returns the
2051  * number of entries found, 0 if none are found, or <0 for some
2052  * errors. If n>=0, the cfg_files parameter will contain a newly
2053  * allocated array of pointers to struct dirent entries, as returned
2054  * by scandir(). These can be freed with tr_free_config_file_list().
2055  */
2056 int tr_find_config_files (const char *config_dir, struct dirent ***cfg_files) {
2057   int n = 0;
2058   
2059   n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
2060
2061   if (n < 0) {
2062     perror("scandir");
2063     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
2064   } 
2065
2066   return n;
2067 }
2068
2069 /* Free memory allocated for configuration file list returned from tr_find_config_files().
2070  * This can be called regardless of the return value of tr_find_config_values(). */
2071 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
2072   int ii;
2073
2074   /* if n < 0, then scandir did not allocate anything because it failed */
2075   if((n>=0) && (*cfg_files != NULL)) {
2076     for(ii=0; ii<n; ii++) {
2077       free((*cfg_files)[ii]);
2078     }
2079     free(*cfg_files); /* safe even if n==0 */
2080     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
2081   }
2082 }