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