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