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