d48902b628a23caf1b33f060e9892f3254a722dc
[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 #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 = 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 #if 0
1464 /* TODO: are we using this? JLR */
1465 /* Update the community information with data from a new batch of IDP realms.
1466  * May partially add realms if there is a failure, no guarantees.
1467  * Call like comms=tr_comm_idp_update(comms, new_realms, &rc) */
1468 static TR_COMM *tr_cfg_comm_idp_update(TALLOC_CTX *mem_ctx,
1469                                        TR_COMM_TABLE *ctab,
1470                                        TR_IDP_REALM *new_realms,
1471                                        TR_CFG_RC *rc)
1472 {
1473   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1474   TR_COMM *comm=NULL; /* community looked up in comms table */
1475   TR_COMM *new_comms=NULL; /* new communities as we create them */
1476   TR_IDP_REALM *realm=NULL;
1477   TR_APC *apc=NULL; /* apc of one realm */
1478
1479   if (rc==NULL) {
1480     *rc=TR_CFG_BAD_PARAMS;
1481     goto cleanup;
1482   }
1483
1484   /* start with an empty list communities, then fill that in */
1485   for (realm=new_realms; realm!=NULL; realm=realm->next) {
1486     for (apc=realm->apcs; apc!=NULL; apc=apc->next) {
1487       comm=tr_comm_lookup(comms, apc->id);
1488       if (comm==NULL) {
1489         comm=tr_comm_new(tmp_ctx);
1490         if (comm==NULL) {
1491           tr_debug("tr_cfg_comm_idp_update: unable to allocate new community.");
1492           *rc=TR_CFG_NOMEM;
1493           goto cleanup;
1494         }
1495         /* fill in the community with info */
1496         comm->type=TR_COMM_APC; /* realms added this way are in APCs */
1497         comm->expiration_interval=TR_DEFAULT_APC_EXPIRATION_INTERVAL;
1498         tr_comm_set_id(comm, tr_dup_name(apc->id));
1499         tr_comm_add_idp_realm(comm, realm);
1500         tr_comm_add(new_comms, comm);
1501       } else {
1502         /* add this realm to the comm */
1503         tr_comm_add_idp_realm(comm, realm);
1504       }
1505     }
1506   }
1507
1508   /* we successfully built a list, add it to the other list */
1509   tr_comm_add(comms, new_comms);
1510   talloc_steal(mem_ctx, comms);
1511  cleanup:
1512   talloc_free(tmp_ctx);
1513   return comms;
1514 }
1515 #endif
1516
1517 static TR_CFG_RC tr_cfg_parse_one_local_org(TR_CFG *trc, json_t *jlorg)
1518 {
1519   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1520   TR_CFG_RC retval=TR_CFG_ERROR; /* our return code */
1521   TR_CFG_RC rc=TR_CFG_ERROR; /* return code from functions we call */
1522   TR_NAME *org_name=NULL;
1523   json_t *j_org=NULL;
1524   json_t *j_realms=NULL;
1525   TR_IDP_REALM *new_idp_realms=NULL;
1526   TR_RP_CLIENT *new_rp_clients=NULL;
1527
1528   tr_debug("tr_cfg_parse_one_local_org: parsing local organization");
1529
1530   /* get organization_name (optional) */
1531   if (NULL==(j_org=json_object_get(jlorg, "organization_name"))) {
1532     tr_debug("tr_cfg_parse_one_local_org: organization_name unspecified");
1533   } else {
1534     org_name=tr_cfg_parse_org_name(tmp_ctx, j_org, &rc);
1535     if (rc==TR_CFG_SUCCESS) {
1536       tr_debug("tr_cfg_parse_one_local_org: organization_name=\"%.*s\"",
1537                org_name->len,
1538                org_name->buf);
1539       /* we don't actually do anything with this, but we could */
1540       tr_free_name(org_name);
1541       org_name=NULL; 
1542     }
1543   }
1544
1545   /* Now get realms. Allow this to be missing; even though that is a pointless organization entry,
1546    * it's harmless. Report a warning because that might be unintentional. */
1547   if (NULL==(j_realms=json_object_get(jlorg, "realms"))) {
1548     tr_warning("tr_cfg_parse_one_local_org: warning - no realms in this local organization");
1549   } else {
1550     /* Allocate in the tmp_ctx so these will be cleaned up if we do not complete successfully. */
1551     new_idp_realms=tr_cfg_parse_idp_realms(tmp_ctx, j_realms, &rc);
1552     if (rc!=TR_CFG_SUCCESS)
1553       goto cleanup;
1554
1555     new_rp_clients=tr_cfg_parse_rp_clients(tmp_ctx, j_realms, &rc);
1556     if (rc!=TR_CFG_SUCCESS)
1557       goto cleanup;
1558   }
1559   retval=TR_CFG_SUCCESS;
1560   
1561 cleanup:
1562   /* if we succeeded, link things to the configuration and move out of tmp context */
1563   if (retval==TR_CFG_SUCCESS) {
1564     if (new_idp_realms!=NULL) {
1565       tr_idp_realm_add(trc->ctable->idp_realms, new_idp_realms); /* fixes talloc contexts except for head*/
1566       talloc_steal(trc, trc->ctable->idp_realms); /* make sure the head is in the right context */
1567     }
1568
1569     if (new_rp_clients!=NULL) {
1570       tr_rp_client_add(trc->rp_clients, new_rp_clients); /* fixes talloc contexts */
1571       talloc_steal(trc, trc->rp_clients); /* make sure head is in the right context */
1572     }
1573   }
1574
1575   talloc_free(tmp_ctx);
1576   return rc;
1577 }
1578
1579 /* Parse local organizations if present. Returns success if there are none. On failure, the configuration is unreliable. */
1580 static TR_CFG_RC tr_cfg_parse_local_orgs(TR_CFG *trc, json_t *jcfg)
1581 {
1582   json_t *jlocorgs=NULL;
1583   size_t ii=0;
1584
1585   jlocorgs=json_object_get(jcfg, "local_organizations");
1586   if (jlocorgs==NULL)
1587     return TR_CFG_SUCCESS;
1588
1589   if (!json_is_array(jlocorgs)) {
1590     tr_err("tr_cfg_parse_local_orgs: local_organizations is not an array.");
1591     return TR_CFG_NOPARSE;
1592   }
1593
1594   for (ii=0; ii<json_array_size(jlocorgs); ii++) {
1595     if (tr_cfg_parse_one_local_org(trc, json_array_get(jlocorgs, ii))!=TR_CFG_SUCCESS) {
1596       tr_err("tr_cfg_parse_local_orgs: error parsing local_organization %d.", ii+1);
1597       return TR_CFG_NOPARSE;
1598     }
1599   }
1600
1601   return TR_CFG_SUCCESS;
1602 }
1603
1604 static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
1605 {
1606   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1607   json_t *jhost=NULL;
1608   json_t *jport=NULL;
1609   json_t *jgss=NULL;
1610   json_t *jfilt=NULL;
1611   TRP_PEER *new_peer=NULL;
1612   TR_GSS_NAMES *names=NULL;
1613   TR_FILTER_SET *filt_set=NULL;
1614   TR_CFG_RC rc=TR_CFG_ERROR;
1615
1616   jhost=json_object_get(jporg, "hostname");
1617   jport=json_object_get(jporg, "port");
1618   jgss=json_object_get(jporg, "gss_names");
1619   jfilt=json_object_get(jporg, "filters");
1620
1621   if ((jhost==NULL) || (!json_is_string(jhost))) {
1622     tr_err("tr_cfg_parse_one_peer_org: hostname not specified or not a string.");
1623     rc=TR_CFG_NOPARSE;
1624     goto cleanup;
1625   }
1626
1627   if ((jport!=NULL) && (!json_is_number(jport))) {
1628     /* note that not specifying the port is allowed, but if set it must be a number */
1629     tr_err("tr_cfg_parse_one_peer_org: port is not a number.");
1630     rc=TR_CFG_NOPARSE;
1631     goto cleanup;
1632   }
1633
1634   if ((jgss==NULL) || (!json_is_array(jgss))) {
1635     tr_err("tr_cfg_parse_one_peer_org: gss_names not specified or not an array.");
1636     rc=TR_CFG_NOPARSE;
1637     goto cleanup;
1638   }
1639
1640   if ((jfilt!=NULL) && (!json_is_object(jfilt))) {
1641     tr_err("tr_cfg_parse_one_peer_org: filters is not an object.");
1642     rc=TR_CFG_NOPARSE;
1643     goto cleanup;
1644   }
1645
1646   new_peer=trp_peer_new(tmp_ctx);
1647   if (new_peer==NULL) {
1648     tr_err("tr_cfg_parse_one_peer_org: could not allocate new peer.");
1649     rc=TR_CFG_NOMEM;
1650     goto cleanup;
1651   }
1652
1653   trp_peer_set_server(new_peer, json_string_value(jhost));
1654   if (jport==NULL)
1655     trp_peer_set_port(new_peer, TRP_PORT);
1656   else
1657     trp_peer_set_port(new_peer, json_integer_value(jport));
1658
1659   names=tr_cfg_parse_gss_names(tmp_ctx, jgss, &rc);
1660   if (rc!=TR_CFG_SUCCESS) {
1661     tr_err("tr_cfg_parse_one_peer_org: unable to parse gss names.");
1662     rc=TR_CFG_NOPARSE;
1663     goto cleanup;
1664   }
1665   trp_peer_set_gss_names(new_peer, names);
1666
1667   if (jfilt) {
1668     filt_set=tr_cfg_parse_filters(tmp_ctx, jfilt, &rc);
1669     if (rc!=TR_CFG_SUCCESS) {
1670       tr_err("tr_cfg_parse_one_peer_org: unable to parse filters.");
1671       rc=TR_CFG_NOPARSE;
1672       goto cleanup;
1673     }
1674     trp_peer_set_filters(new_peer, filt_set);
1675   }
1676
1677   /* success! */
1678   trp_ptable_add(trc->peers, new_peer);
1679   rc=TR_CFG_SUCCESS;
1680
1681  cleanup:
1682   talloc_free(tmp_ctx);
1683   return rc;
1684 }
1685
1686 /* Parse peer organizations, if present. Returns success if there are none. */
1687 static TR_CFG_RC tr_cfg_parse_peer_orgs(TR_CFG *trc, json_t *jcfg)
1688 {
1689   json_t *jpeerorgs=NULL;
1690   int ii=0;
1691
1692   jpeerorgs=json_object_get(jcfg, "peer_organizations");
1693   if (jpeerorgs==NULL)
1694     return TR_CFG_SUCCESS;
1695
1696   if (!json_is_array(jpeerorgs)) {
1697     tr_err("tr_cfg_parse_peer_orgs: peer_organizations is not an array.");
1698     return TR_CFG_NOPARSE;
1699   }
1700
1701   for (ii=0; ii<json_array_size(jpeerorgs); ii++) {
1702     if (tr_cfg_parse_one_peer_org(trc, json_array_get(jpeerorgs, ii))!=TR_CFG_SUCCESS) {
1703       tr_err("tr_cfg_parse_peer_orgs: error parsing peer_organization %d.", ii+1);
1704       return TR_CFG_NOPARSE;
1705     }
1706   }
1707
1708   return TR_CFG_SUCCESS;
1709 }
1710              
1711 static TR_CFG_RC tr_cfg_parse_default_servers (TR_CFG *trc, json_t *jcfg) 
1712 {
1713   json_t *jdss = NULL;
1714   TR_CFG_RC rc = TR_CFG_SUCCESS;
1715   TR_AAA_SERVER *ds = NULL;
1716   int i = 0;
1717
1718   if ((!trc) || (!jcfg))
1719     return TR_CFG_BAD_PARAMS;
1720
1721   /* If there are default servers, store them */
1722   if ((NULL != (jdss = json_object_get(jcfg, "default_servers"))) &&
1723       (json_is_array(jdss)) &&
1724       (0 < json_array_size(jdss))) {
1725
1726     for (i = 0; i < json_array_size(jdss); i++) {
1727       if (NULL == (ds = tr_cfg_parse_one_aaa_server(trc,
1728                                                     json_array_get(jdss, i), 
1729                                                    &rc))) {
1730         return rc;
1731       }
1732       tr_debug("tr_cfg_parse_default_servers: Default server configured: %s", ds->hostname->buf);
1733       ds->next = trc->default_servers;
1734       trc->default_servers = ds;
1735     }
1736   } 
1737
1738   tr_debug("tr_cfg_parse_default_servers: Finished (rc=%d)", rc);
1739   return rc;
1740 }
1741
1742 static void tr_cfg_parse_comm_idps(TR_CFG *trc, json_t *jidps, TR_COMM *comm, TR_CFG_RC *rc)
1743 {
1744   TR_IDP_REALM *found_idp=NULL;
1745   json_t *jidp_name=NULL;
1746   TR_NAME *idp_name=NULL;
1747   size_t ii = 0;
1748
1749   if ((!trc) ||
1750       (!jidps) ||
1751       (!json_is_array(jidps))) {
1752     if (rc)
1753       *rc = TR_CFG_BAD_PARAMS;
1754     return;
1755   }
1756
1757   json_array_foreach(jidps, ii, jidp_name) {
1758     idp_name=tr_new_name(json_string_value(jidp_name));
1759     if (idp_name==NULL) {
1760       *rc = TR_CFG_NOMEM;
1761       return;
1762     }
1763     found_idp=tr_cfg_find_idp(trc, idp_name, rc);
1764     tr_free_name(idp_name);
1765
1766     if ((found_idp==NULL) || (*rc!=TR_CFG_SUCCESS)) {
1767       tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.", json_string_value(jidp_name));
1768       *rc=TR_CFG_ERROR;
1769       return;
1770     }
1771     tr_comm_add_idp_realm(trc->ctable, comm, found_idp, 0, NULL, NULL); /* no provenance, never expires */
1772   }
1773
1774   *rc=TR_CFG_SUCCESS;
1775   return;
1776 }
1777
1778 static void tr_cfg_parse_comm_rps(TR_CFG *trc, json_t *jrps, TR_COMM *comm, TR_CFG_RC *rc)
1779 {
1780   TR_RP_REALM *found_rp=NULL;
1781   TR_RP_REALM *new_rp=NULL;
1782   TR_NAME *rp_name=NULL;
1783   const char *s=NULL;
1784   int ii=0;
1785
1786   if ((!trc) ||
1787       (!jrps) ||
1788       (!json_is_array(jrps))) {
1789     if (rc)
1790       *rc = TR_CFG_BAD_PARAMS;
1791     return;
1792   }
1793
1794   for (ii=0; ii<json_array_size(jrps); ii++) {
1795     /* get the RP name as a string */
1796     s=json_string_value(json_array_get(jrps, ii));
1797     if (s==NULL) {
1798       tr_notice("tr_cfg_parse_comm_rps: null RP found in community %.*s, ignoring.",
1799                 tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1800       continue;
1801     }
1802
1803     /* convert string to TR_NAME */
1804     rp_name=tr_new_name(s);
1805     if (rp_name==NULL) {
1806       tr_err("tr_cfg_parse_comm_rps: unable to allocate RP name for %s in community %.*s.",
1807              s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1808     }
1809
1810     /* see if we already have this RP in this community */
1811     found_rp=tr_comm_find_rp(trc->ctable, comm, rp_name);
1812     if (found_rp!=NULL) {
1813       tr_notice("tr_cfg_parse_comm_rps: RP %s repeated in community %.*s.",
1814                 s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1815       tr_free_name(rp_name);
1816       continue;
1817     }
1818
1819     /* Add the RP to the community, first see if we have the RP in any community */
1820     found_rp=tr_rp_realm_lookup(trc->ctable->rp_realms, rp_name);
1821     if (found_rp!=NULL) {
1822       tr_debug("tr_cfg_parse_comm_rps: RP realm %s already exists.", s);
1823       new_rp=found_rp; /* use it rather than creating a new realm record */
1824     } else {
1825       new_rp=tr_rp_realm_new(NULL);
1826       if (new_rp==NULL) {
1827         tr_err("tr_cfg_parse_comm_rps: unable to allocate RP record for %s in community %.*s.",
1828                s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1829       }
1830       tr_debug("tr_cfg_parse_comm_rps: setting name to %s", rp_name->buf);
1831       tr_rp_realm_set_id(new_rp, rp_name);
1832       rp_name=NULL; /* rp_name no longer belongs to us */
1833       tr_rp_realm_add(trc->ctable->rp_realms, new_rp);
1834       talloc_steal(trc->ctable, trc->ctable->rp_realms); /* make sure head is in the right context */
1835     }
1836     tr_comm_add_rp_realm(trc->ctable, comm, new_rp, 0, NULL, NULL);
1837   }
1838 }
1839
1840 static TR_COMM *tr_cfg_parse_one_comm (TALLOC_CTX *mem_ctx, TR_CFG *trc, json_t *jcomm, TR_CFG_RC *rc)
1841 {
1842   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1843   TR_COMM *comm = NULL;
1844   json_t *jid = NULL;
1845   json_t *jtype = NULL;
1846   json_t *japcs = NULL;
1847   json_t *jidps = NULL;
1848   json_t *jrps = NULL;
1849
1850   if ((!trc) || (!jcomm) || (!rc)) {
1851     tr_debug("tr_cfg_parse_one_comm: Bad parameters.");
1852     if (rc)
1853       *rc = TR_CFG_BAD_PARAMS;
1854     goto cleanup;
1855   }
1856
1857   comm=tr_comm_new(tmp_ctx);
1858   if (comm==NULL) {
1859     tr_crit("tr_cfg_parse_one_comm: Out of memory.");
1860     *rc = TR_CFG_NOMEM;
1861     goto cleanup;
1862   }
1863
1864
1865   if ((NULL == (jid = json_object_get(jcomm, "community_id"))) ||
1866       (!json_is_string(jid)) ||
1867       (NULL == (jtype = json_object_get(jcomm, "type"))) ||
1868       (!json_is_string(jtype)) ||
1869       (NULL == (japcs = json_object_get(jcomm, "apcs"))) ||
1870       (!json_is_array(japcs)) ||
1871       (NULL == (jidps = json_object_get(jcomm, "idp_realms"))) ||
1872       (!json_is_array(jidps)) ||
1873       (NULL == (jrps = json_object_get(jcomm, "rp_realms"))) ||
1874       (!json_is_array(jrps))) {
1875     tr_debug("tr_cfg_parse_one_comm: Error parsing Communities configuration.");
1876     *rc = TR_CFG_NOPARSE;
1877     comm=NULL;
1878     goto cleanup;
1879   }
1880
1881   tr_comm_set_id(comm, tr_new_name(json_string_value(jid)));
1882   if (NULL == tr_comm_get_id(comm)) {
1883     tr_debug("tr_cfg_parse_one_comm: No memory for community id.");
1884     *rc = TR_CFG_NOMEM;
1885     comm=NULL;
1886     goto cleanup;
1887   }
1888
1889   if (0 == strcmp(json_string_value(jtype), "apc")) {
1890     comm->type = TR_COMM_APC;
1891   } else if (0 == strcmp(json_string_value(jtype), "coi")) {
1892     comm->type = TR_COMM_COI;
1893     if (NULL == (comm->apcs = tr_cfg_parse_apcs(trc, japcs, rc))) {
1894       tr_debug("tr_cfg_parse_one_comm: Can't parse APCs for COI %s.",
1895                tr_comm_get_id(comm)->buf);
1896       comm=NULL;
1897       goto cleanup;
1898     }
1899   } else {
1900     tr_debug("tr_cfg_parse_one_comm: Invalid community type, comm = %s, type = %s",
1901              tr_comm_get_id(comm)->buf, json_string_value(jtype));
1902     *rc = TR_CFG_NOPARSE;
1903     comm=NULL;
1904     goto cleanup;
1905   }
1906
1907   tr_cfg_parse_comm_idps(trc, jidps, comm, rc);
1908   if (TR_CFG_SUCCESS != *rc) {
1909     tr_debug("tr_cfg_parse_one_comm: Can't parse IDP realms for comm %s.",
1910              tr_comm_get_id(comm)->buf);
1911     comm=NULL;
1912     goto cleanup;
1913   }
1914
1915   tr_cfg_parse_comm_rps(trc, jrps, comm, rc);
1916   if (TR_CFG_SUCCESS != *rc) {
1917     tr_debug("tr_cfg_parse_one_comm: Can't parse RP realms for comm %s .",
1918              tr_comm_get_id(comm)->buf);
1919     comm=NULL;
1920     goto cleanup;
1921   }
1922
1923   if (TR_COMM_APC == comm->type) {
1924     json_t *jexpire  = json_object_get(jcomm, "expiration_interval");
1925     comm->expiration_interval = 43200; /*30 days*/
1926     if (jexpire) {
1927       if (!json_is_integer(jexpire)) {
1928         tr_err("tr_parse_one_comm: expiration_interval is not an integer for comm %.*s",
1929                  tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1930         comm=NULL;
1931         goto cleanup;
1932       }
1933       comm->expiration_interval = json_integer_value(jexpire);
1934       if (comm->expiration_interval <= 10) {
1935         comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
1936         tr_notice(
1937             "tr_parse_one_comm: expiration interval for %.*s less than minimum of 11 minutes; using 11 minutes instead.",
1938             tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1939       }
1940       if (comm->expiration_interval > 129600) {
1941         /* > 90 days*/
1942         comm->expiration_interval = 129600;
1943         tr_notice(
1944             "tr_parse_one_comm: expiration interval for %.*s exceeds maximum of 90 days; using 90 days instead.",
1945             tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
1946       }
1947     }
1948   }
1949
1950 cleanup:
1951   if (comm!=NULL)
1952     talloc_steal(mem_ctx, comm);
1953   talloc_free(tmp_ctx);
1954   return comm;
1955 }
1956
1957 static TR_CFG_RC tr_cfg_parse_comms (TR_CFG *trc, json_t *jcfg) 
1958 {
1959   json_t *jcomms = NULL;
1960   TR_CFG_RC rc = TR_CFG_SUCCESS;
1961   TR_COMM *comm = NULL;
1962   int i = 0;
1963
1964   if ((!trc) || (!jcfg)) {
1965     tr_debug("tr_cfg_parse_comms: Bad Parameters.");
1966     return TR_CFG_BAD_PARAMS;
1967   }
1968
1969   if (NULL != (jcomms = json_object_get(jcfg, "communities"))) {
1970     if (!json_is_array(jcomms)) {
1971       return TR_CFG_NOPARSE;
1972     }
1973
1974     for (i = 0; i < json_array_size(jcomms); i++) {
1975       if (NULL == (comm = tr_cfg_parse_one_comm(NULL, /* TODO: use a talloc context */
1976                                                 trc, 
1977                                                 json_array_get(jcomms, i), 
1978                                                &rc))) {
1979         return rc;
1980       }
1981       tr_debug("tr_cfg_parse_comms: Community configured: %s.",
1982                tr_comm_get_id(comm)->buf);
1983
1984       tr_comm_table_add_comm(trc->ctable, comm);
1985     }
1986   }
1987   tr_debug("tr_cfg_parse_comms: Finished (rc=%d)", rc);
1988   return rc;
1989 }
1990
1991 TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
1992 {
1993   TR_CFG_RC rc = TR_CFG_SUCCESS;
1994
1995   if (!trc)
1996     return TR_CFG_BAD_PARAMS;
1997
1998   if ((NULL == trc->internal)||
1999       (NULL == trc->internal->hostname)) {
2000     tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
2001     rc = TR_CFG_ERROR;
2002   }
2003
2004   if (NULL == trc->rp_clients) {
2005     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
2006     rc = TR_CFG_ERROR;
2007   }
2008
2009   if (0==tr_comm_table_size(trc->ctable)) {
2010     tr_debug("tr_cfg_validate: Error: No Communities configured");
2011     rc = TR_CFG_ERROR;
2012   }
2013
2014   if ((NULL == trc->default_servers) && (NULL == trc->ctable->idp_realms)) {
2015     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
2016     rc = TR_CFG_ERROR;
2017   }
2018   
2019   return rc;
2020 }
2021
2022 /* Join two paths and return a pointer to the result. This should be freed
2023  * via talloc_free. Returns NULL on failure. */
2024 static char *join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
2025 {
2026   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
2027 }
2028
2029 static void tr_cfg_log_json_error(const char *label, json_error_t *rc)
2030 {
2031   tr_debug("%s: JSON parse error on line %d: %s",
2032            label,
2033            rc->line,
2034            rc->text);
2035 }
2036
2037 TR_CFG_RC tr_cfg_parse_one_config_file(TR_CFG *cfg, const char *file_with_path)
2038 {
2039   json_t *jcfg=NULL;
2040   json_t *jser=NULL;
2041   json_error_t rc;
2042
2043   if (NULL==(jcfg=json_load_file(file_with_path, 
2044                                  JSON_DISABLE_EOF_CHECK|JSON_REJECT_DUPLICATES, &rc))) {
2045     tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.", 
2046              file_with_path);
2047     tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
2048     return TR_CFG_NOPARSE;
2049   }
2050
2051   // Look for serial number and log it if it exists
2052   if (NULL!=(jser=json_object_get(jcfg, "serial_number"))) {
2053     if (json_is_number(jser)) {
2054       tr_notice("tr_parse_one_config_file: Attempting to load revision %" JSON_INTEGER_FORMAT " of '%s'.",
2055                 json_integer_value(jser),
2056                 file_with_path);
2057     }
2058   }
2059
2060   if ((TR_CFG_SUCCESS != tr_cfg_parse_internal(cfg, jcfg)) ||
2061       (TR_CFG_SUCCESS != tr_cfg_parse_local_orgs(cfg, jcfg)) ||
2062       (TR_CFG_SUCCESS != tr_cfg_parse_peer_orgs(cfg, jcfg)) ||
2063       (TR_CFG_SUCCESS != tr_cfg_parse_default_servers(cfg, jcfg)) ||
2064       (TR_CFG_SUCCESS != tr_cfg_parse_comms(cfg, jcfg)))
2065     return TR_CFG_ERROR;
2066
2067   return TR_CFG_SUCCESS;
2068 }
2069
2070 /* Reads configuration files in config_dir ("" or "./" will use the current directory). */
2071 TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, const char *config_dir, int n, struct dirent **cfg_files)
2072 {
2073   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
2074   char *file_with_path;
2075   int ii;
2076   TR_CFG_RC cfg_rc=TR_CFG_ERROR;
2077
2078   if ((!cfg_mgr) || (!cfg_files) || (n<=0)) {
2079     cfg_rc=TR_CFG_BAD_PARAMS;
2080     goto cleanup;
2081   }
2082
2083   if (cfg_mgr->new != NULL)
2084     tr_cfg_free(cfg_mgr->new);
2085   cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
2086   if (cfg_mgr->new == NULL) {
2087     cfg_rc=TR_CFG_NOMEM;
2088     goto cleanup;
2089   }
2090
2091   cfg_mgr->new->peers=trp_ptable_new(cfg_mgr); /* not sure why this isn't in cfg_mgr->new's context */
2092
2093   /* Parse configuration information from each config file */
2094   for (ii=0; ii<n; ii++) {
2095     file_with_path=join_paths(tmp_ctx, config_dir, cfg_files[ii]->d_name); /* must free result with talloc_free */
2096     if(file_with_path == NULL) {
2097       tr_crit("tr_parse_config: error joining path.");
2098       cfg_rc=TR_CFG_NOMEM;
2099       goto cleanup;
2100     }
2101     tr_debug("tr_parse_config: Parsing %s.", cfg_files[ii]->d_name); /* print the filename without the path */
2102     cfg_rc=tr_cfg_parse_one_config_file(cfg_mgr->new, file_with_path);
2103     if (cfg_rc!=TR_CFG_SUCCESS) {
2104       tr_crit("tr_parse_config: Error parsing %s", file_with_path);
2105       goto cleanup;
2106     }
2107     talloc_free(file_with_path); /* done with filename */
2108   }
2109
2110   /* make sure we got a complete, consistent configuration */
2111   if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
2112     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
2113     cfg_rc=TR_CFG_ERROR;
2114     goto cleanup;
2115   }
2116
2117   /* success! */
2118   talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
2119   cfg_rc=TR_CFG_SUCCESS;
2120
2121 cleanup:
2122   talloc_free(tmp_ctx);
2123   return cfg_rc;
2124 }
2125
2126 TR_IDP_REALM *tr_cfg_find_idp (TR_CFG *tr_cfg, TR_NAME *idp_id, TR_CFG_RC *rc)
2127 {
2128
2129   TR_IDP_REALM *cfg_idp;
2130
2131   if ((!tr_cfg) || (!idp_id)) {
2132     if (rc)
2133       *rc = TR_CFG_BAD_PARAMS;
2134     return NULL;
2135   }
2136
2137   for (cfg_idp = tr_cfg->ctable->idp_realms; NULL != cfg_idp; cfg_idp = cfg_idp->next) {
2138     if (!tr_name_cmp (idp_id, cfg_idp->realm_id)) {
2139       tr_debug("tr_cfg_find_idp: Found %s.", idp_id->buf);
2140       return cfg_idp;
2141     }
2142   }
2143   /* if we didn't find one, return NULL */ 
2144   return NULL;
2145 }
2146
2147 TR_RP_CLIENT *tr_cfg_find_rp (TR_CFG *tr_cfg, TR_NAME *rp_gss, TR_CFG_RC *rc)
2148 {
2149   TR_RP_CLIENT *cfg_rp;
2150
2151   if ((!tr_cfg) || (!rp_gss)) {
2152     if (rc)
2153       *rc = TR_CFG_BAD_PARAMS;
2154     return NULL;
2155   }
2156
2157   for (cfg_rp = tr_cfg->rp_clients; NULL != cfg_rp; cfg_rp = cfg_rp->next) {
2158     if (tr_gss_names_matches(cfg_rp->gss_names, rp_gss)) {
2159       tr_debug("tr_cfg_find_rp: Found %s.", rp_gss->buf);
2160       return cfg_rp;
2161     }
2162   }
2163   /* if we didn't find one, return NULL */ 
2164   return NULL;
2165 }
2166
2167 static int is_cfg_file(const struct dirent *dent) {
2168   int n;
2169
2170   /* Only accept filenames ending in ".cfg" and starting with a character
2171    * other than an ASCII '.' */
2172
2173   /* filename must be at least 4 characters long to be acceptable */
2174   n=strlen(dent->d_name);
2175   if (n < 4) {
2176     return 0;
2177   }
2178
2179   /* filename must not start with '.' */
2180   if ('.' == dent->d_name[0]) {
2181     return 0;
2182   }
2183
2184   /* If the above passed and the last four characters of the filename are .cfg, accept.
2185    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
2186   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
2187     return 1;
2188   }
2189
2190   /* otherwise, return false. */
2191   return 0;
2192 }
2193
2194 /* Find configuration files in a particular directory. Returns the
2195  * number of entries found, 0 if none are found, or <0 for some
2196  * errors. If n>=0, the cfg_files parameter will contain a newly
2197  * allocated array of pointers to struct dirent entries, as returned
2198  * by scandir(). These can be freed with tr_free_config_file_list().
2199  */
2200 int tr_find_config_files (const char *config_dir, struct dirent ***cfg_files) {
2201   int n = 0;
2202   
2203   n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
2204
2205   if (n < 0) {
2206     perror("scandir");
2207     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
2208   } 
2209
2210   return n;
2211 }
2212
2213 /* Free memory allocated for configuration file list returned from tr_find_config_files().
2214  * This can be called regardless of the return value of tr_find_config_values(). */
2215 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
2216   int ii;
2217
2218   /* if n < 0, then scandir did not allocate anything because it failed */
2219   if((n>=0) && (*cfg_files != NULL)) {
2220     for(ii=0; ii<n; ii++) {
2221       free((*cfg_files)[ii]);
2222     }
2223     free(*cfg_files); /* safe even if n==0 */
2224     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
2225   }
2226 }