Parse RP clients from new-style configuration files.
[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_debug.h>
45 #include <tr_filter.h>
46 #include <trust_router/tr_constraint.h>
47 #include <tr_idp.h>
48 #include <tr.h>
49
50 void tr_print_config (TR_CFG *cfg) {
51   tr_notice("tr_print_config: Logging running trust router configuration.");
52   tr_print_comms(cfg->comms);
53 }
54
55 void tr_print_comms (TR_COMM *comm_list) {
56   TR_COMM *comm = NULL;
57
58   for (comm = comm_list; NULL != comm; comm = comm->next) {
59     tr_notice("tr_print_config: Community %s:", comm->id->buf);
60
61     tr_notice("tr_print_config:  - Member IdPs:");
62     tr_print_comm_idps(comm->idp_realms);
63
64     tr_notice("tr_print_config:  - Member RPs:");
65     tr_print_comm_rps(comm->rp_realms);
66   }
67 }
68
69 void tr_print_comm_idps (TR_IDP_REALM *idp_list) {
70   TR_IDP_REALM *idp = NULL;
71
72   for (idp = idp_list; NULL != idp; idp = idp->comm_next) {
73     tr_notice("tr_print_config:    - @%s", idp->realm_id->buf);
74   }
75 }
76
77 void tr_print_comm_rps(TR_RP_REALM *rp_list) {
78   TR_RP_REALM *rp = NULL;
79
80   for (rp = rp_list; NULL != rp; rp = rp->next) {
81     tr_notice("tr_print_config:    - %s", rp->realm_name->buf);
82   }
83 }
84
85 TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
86 {
87   return talloc_zero(mem_ctx, TR_CFG);
88 }
89
90 void tr_cfg_free (TR_CFG *cfg) {
91   talloc_free(cfg);
92 }
93
94 TR_CFG_MGR *tr_cfg_mgr_new(TALLOC_CTX *mem_ctx)
95 {
96   return talloc_zero(mem_ctx, TR_CFG_MGR);
97 }
98
99 void tr_cfg_mgr_free (TR_CFG_MGR *cfg_mgr) {
100   talloc_free(cfg_mgr);
101 }
102
103 TR_CFG_RC tr_apply_new_config (TR_CFG_MGR *cfg_mgr)
104 {
105   /* cfg_mgr->active is allowed to be null, but new cannot be */
106   if ((cfg_mgr==NULL) || (cfg_mgr->new==NULL))
107     return TR_CFG_BAD_PARAMS;
108
109   if (cfg_mgr->active != NULL)
110     tr_cfg_free(cfg_mgr->active);
111
112   cfg_mgr->active = cfg_mgr->new;
113   cfg_mgr->new=NULL; /* only keep a single handle on the new configuration */
114
115   tr_log_threshold(cfg_mgr->active->internal->log_threshold);
116   tr_console_threshold(cfg_mgr->active->internal->console_threshold);
117
118   return TR_CFG_SUCCESS;
119 }
120
121 static TR_CFG_RC tr_cfg_parse_internal(TR_CFG *trc, json_t *jcfg)
122 {
123   json_t *jint = NULL;
124   json_t *jmtd = NULL;
125   json_t *jtidsp = NULL;
126   json_t *jtrpsp = NULL;
127   json_t *jhname = NULL;
128   json_t *jlog = NULL;
129   json_t *jconthres = NULL;
130   json_t *jlogthres = NULL;
131   json_t *jcfgpoll = NULL;
132   json_t *jcfgsettle = NULL;
133   json_t *jroutesweep = NULL;
134   json_t *jrouteupdate = NULL;
135   json_t *jrouteconnect = NULL;
136
137   if ((!trc) || (!jcfg))
138     return TR_CFG_BAD_PARAMS;
139
140   if (NULL == trc->internal) {
141     if (NULL == (trc->internal = talloc_zero(trc, TR_CFG_INTERNAL)))
142       return TR_CFG_NOMEM;
143   }
144
145   if (NULL != (jint = json_object_get(jcfg, "tr_internal"))) {
146     if (NULL != (jmtd = json_object_get(jint, "max_tree_depth"))) {
147       if (json_is_number(jmtd)) {
148         trc->internal->max_tree_depth = json_integer_value(jmtd);
149       } else {
150         tr_debug("tr_cfg_parse_internal: Parsing error, max_tree_depth is not a number.");
151         return TR_CFG_NOPARSE;
152       }
153     } else {
154       /* If not configured, use the default */
155       trc->internal->max_tree_depth = TR_DEFAULT_MAX_TREE_DEPTH;
156     }
157     if (NULL != (jtidsp = json_object_get(jint, "tids_port"))) {
158       if (json_is_number(jtidsp)) {
159         trc->internal->tids_port = json_integer_value(jtidsp);
160       } else {
161         tr_debug("tr_cfg_parse_internal: Parsing error, tids_port is not a number.");
162         return TR_CFG_NOPARSE;
163       }
164     } else {
165       /* If not configured, use the default */
166       trc->internal->tids_port = TR_DEFAULT_TIDS_PORT;
167     }
168     if (NULL != (jtrpsp = json_object_get(jint, "trps_port"))) {
169       if (json_is_number(jtrpsp)) {
170         trc->internal->trps_port = json_integer_value(jtrpsp);
171       } else {
172         tr_debug("tr_cfg_parse_internal: Parsing error, trps_port is not a number.");
173         return TR_CFG_NOPARSE;
174       }
175     } else {
176       /* If not configured, use the default */
177       trc->internal->trps_port = TR_DEFAULT_TRPS_PORT;
178     }
179     if (NULL != (jhname = json_object_get(jint, "hostname"))) {
180       if (json_is_string(jhname)) {
181         trc->internal->hostname = json_string_value(jhname);
182       } else {
183         tr_debug("tr_cfg_parse_internal: Parsing error, hostname is not a string.");
184         return TR_CFG_NOPARSE;
185       }
186     }
187     if (NULL != (jcfgpoll = json_object_get(jint, "cfg_poll_interval"))) {
188       if (json_is_number(jcfgpoll)) {
189         trc->internal->cfg_poll_interval = json_integer_value(jcfgpoll);
190       } else {
191         tr_debug("tr_cfg_parse_internal: Parsing error, cfg_poll_interval is not a number.");
192         return TR_CFG_NOPARSE;
193       }
194     } else {
195       trc->internal->cfg_poll_interval = TR_CFGWATCH_DEFAULT_POLL;
196     }
197
198     if (NULL != (jcfgsettle = json_object_get(jint, "cfg_settling_time"))) {
199       if (json_is_number(jcfgsettle)) {
200         trc->internal->cfg_settling_time = json_integer_value(jcfgsettle);
201       } else {
202         tr_debug("tr_cfg_parse_internal: Parsing error, cfg_settling_time is not a number.");
203         return TR_CFG_NOPARSE;
204       }
205     } else {
206       trc->internal->cfg_settling_time = TR_CFGWATCH_DEFAULT_SETTLE;
207     }
208
209     if (NULL != (jrouteconnect = json_object_get(jint, "trp_connect_interval"))) {
210       if (json_is_number(jrouteconnect)) {
211         trc->internal->trp_connect_interval = json_integer_value(jrouteconnect);
212       } else {
213         tr_debug("tr_cfg_parse_internal: Parsing error, trp_connect_interval is not a number.");
214         return TR_CFG_NOPARSE;
215       }
216     } else {
217       /* if not configured, use the default */
218       trc->internal->trp_connect_interval=TR_DEFAULT_TRP_CONNECT_INTERVAL;
219     }
220
221     if (NULL != (jroutesweep = json_object_get(jint, "trp_sweep_interval"))) {
222       if (json_is_number(jroutesweep)) {
223         trc->internal->trp_sweep_interval = json_integer_value(jroutesweep);
224       } else {
225         tr_debug("tr_cfg_parse_internal: Parsing error, trp_sweep_interval is not a number.");
226         return TR_CFG_NOPARSE;
227       }
228     } else {
229       /* if not configured, use the default */
230       trc->internal->trp_sweep_interval=TR_DEFAULT_TRP_SWEEP_INTERVAL;
231     }
232
233     if (NULL != (jrouteupdate = json_object_get(jint, "trp_update_interval"))) {
234       if (json_is_number(jrouteupdate)) {
235         trc->internal->trp_update_interval = json_integer_value(jrouteupdate);
236       } else {
237         tr_debug("tr_cfg_parse_internal: Parsing error, trp_update_interval is not a number.");
238         return TR_CFG_NOPARSE;
239       }
240     } else {
241       /* if not configured, use the default */
242       trc->internal->trp_update_interval=TR_DEFAULT_TRP_UPDATE_INTERVAL;
243     }
244
245     if (NULL != (jlog = json_object_get(jint, "logging"))) {
246       if (NULL != (jlogthres = json_object_get(jlog, "log_threshold"))) {
247         if (json_is_string(jlogthres)) {
248           trc->internal->log_threshold = str2sev(json_string_value(jlogthres));
249         } else {
250           tr_debug("tr_cfg_parse_internal: Parsing error, log_threshold is not a string.");
251           return TR_CFG_NOPARSE;
252         }
253       } else {
254         /* If not configured, use the default */
255         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
256       }
257
258       if (NULL != (jconthres = json_object_get(jlog, "console_threshold"))) {
259         if (json_is_string(jconthres)) {
260             trc->internal->console_threshold = str2sev(json_string_value(jconthres));
261         } else {
262           tr_debug("tr_cfg_parse_internal: Parsing error, console_threshold is not a string.");
263           return TR_CFG_NOPARSE;
264         }
265       } else {
266         /* If not configured, use the default */
267         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
268       }
269     } else {
270         /* If not configured, use the default */
271         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
272         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
273     }
274
275     tr_debug("tr_cfg_parse_internal: Internal config parsed.");
276     return TR_CFG_SUCCESS;
277   }
278   return TR_CFG_SUCCESS;
279 }
280
281 static TR_CONSTRAINT *tr_cfg_parse_one_constraint(TALLOC_CTX *mem_ctx, char *ctype, json_t *jc, TR_CFG_RC *rc)
282 {
283   TR_CONSTRAINT *cons=NULL;
284   int i=0;
285
286   if ((!ctype) || (!jc) || (!rc) ||
287       (!json_is_array(jc)) ||
288       (0 >= json_array_size(jc)) ||
289       (TR_MAX_CONST_MATCHES < json_array_size(jc)) ||
290       (!json_is_string(json_array_get(jc, 0)))) {
291     tr_err("tr_cfg_parse_one_constraint: config error.");
292     *rc=TR_CFG_NOPARSE;
293     return NULL;
294   }
295
296   if (NULL==(cons=tr_constraint_new(mem_ctx))) {
297     tr_debug("tr_cfg_parse_one_constraint: Out of memory (cons).");
298     *rc=TR_CFG_NOMEM;
299     return NULL;
300   }
301
302   if (NULL==(cons->type=tr_new_name(ctype))) {
303     tr_err("tr_cfg_parse_one_constraint: Out of memory (type).");
304     *rc=TR_CFG_NOMEM;
305     tr_constraint_free(cons);
306     return NULL;
307   }
308
309   for (i=0; i < json_array_size(jc); i++) {
310     cons->matches[i]=tr_new_name(json_string_value(json_array_get(jc, i)));
311     if (cons->matches[i]==NULL) {
312       tr_err("tr_cfg_parse_one_constraint: Out of memory (match %d).", i+1);
313       *rc=TR_CFG_NOMEM;
314       tr_constraint_free(cons);
315       return NULL;
316     }
317   }
318
319   return cons;
320 }
321
322 static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR_FILTER_TYPE ftype, TR_CFG_RC *rc)
323 {
324   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
325   TR_FILTER *filt=NULL;
326   json_t *jfaction=NULL;
327   json_t *jfspecs=NULL;
328   json_t *jffield=NULL;
329   json_t *jfmatch=NULL;
330   json_t *jrc=NULL;
331   json_t *jdc=NULL;
332   int i=0, j=0;
333
334   *rc=TR_CFG_ERROR;
335
336   if ((jfilt==NULL) || (rc==NULL)) {
337     tr_err("tr_cfg_parse_one_filter: null argument");
338     *rc=TR_CFG_BAD_PARAMS;
339     goto cleanup;
340   }
341     
342   if (NULL==(filt=tr_filter_new(tmp_ctx))) {
343     tr_err("tr_cfg_parse_one_filter: Out of memory.");
344     *rc=TR_CFG_NOMEM;
345     goto cleanup;
346   }
347   tr_filter_set_type(filt, ftype);
348
349   /* make sure we have space to represent the filter */
350   if (json_array_size(jfilt) > TR_MAX_FILTER_LINES) {
351     tr_err("tr_cfg_parse_one_filter: Filter has too many lines, maximum of %d.", TR_MAX_FILTER_LINES);
352     *rc=TR_CFG_NOPARSE;
353     goto cleanup;
354   }
355
356   /* For each entry in the filter... */
357   for (i=0; i < json_array_size(jfilt); i++) {
358     if ((NULL==(jfaction=json_object_get(json_array_get(jfilt, i), "action"))) ||
359         (!json_is_string(jfaction))) {
360       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action.");
361       *rc=TR_CFG_NOPARSE;
362       goto cleanup;
363     }
364  
365     if ((NULL==(jfspecs=json_object_get(json_array_get(jfilt, i), "specs"))) ||
366         (!json_is_array(jfspecs)) ||
367         (0==json_array_size(jfspecs))) {
368       tr_debug("tr_cfg_parse_one_filter: Error parsing filter specs.");
369       *rc=TR_CFG_NOPARSE;
370       goto cleanup;
371     }
372   
373     if (TR_MAX_FILTER_SPECS < json_array_size(jfspecs)) {
374       tr_debug("tr_cfg_parse_one_filter: Filter has too many specs, maximimum of %d.", TR_MAX_FILTER_SPECS);
375       *rc=TR_CFG_NOPARSE;
376       goto cleanup;
377     }
378
379     if (NULL==(filt->lines[i]=tr_fline_new(filt))) {
380       tr_debug("tr_cfg_parse_one_filter: Out of memory allocating filter line %d.", i+1);
381       *rc=TR_CFG_NOMEM;
382       goto cleanup;
383     }
384
385     if (!strcmp(json_string_value(jfaction), "accept")) {
386       filt->lines[i]->action=TR_FILTER_ACTION_ACCEPT;
387     }
388     else if (!strcmp(json_string_value(jfaction), "reject")) {
389       filt->lines[i]->action=TR_FILTER_ACTION_REJECT;
390     }
391     else {
392       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.", json_string_value(jfaction));
393       *rc=TR_CFG_NOPARSE;
394       goto cleanup;
395     }
396
397     if (NULL!=(jrc=json_object_get(json_array_get(jfilt, i), "realm_constraints"))) {
398       if (!json_is_array(jrc)) {
399         tr_err("tr_cfg_parse_one_filter: cannot parse realm_constraints, not an array.");
400         *rc=TR_CFG_NOPARSE;
401         goto cleanup;
402       } else if (json_array_size(jrc)>TR_MAX_CONST_MATCHES) {
403         tr_err("tr_cfg_parse_one_filter: realm_constraints has too many entries, maximum of %d.",
404                TR_MAX_CONST_MATCHES);
405         *rc=TR_CFG_NOPARSE;
406         goto cleanup;
407       } else if (json_array_size(jrc)>0) {
408         /* ok we actually have entries to process */
409         if (NULL==(filt->lines[i]->realm_cons=tr_cfg_parse_one_constraint(filt->lines[i], "realm", jrc, rc))) {
410           tr_debug("tr_cfg_parse_one_filter: Error parsing realm constraint");
411           *rc=TR_CFG_NOPARSE;
412           goto cleanup;
413         }
414       }
415     }
416
417     if (NULL!=(jdc=json_object_get(json_array_get(jfilt, i), "domain_constraints"))) {
418       if (!json_is_array(jdc)) {
419         tr_err("tr_cfg_parse_one_filter: cannot parse domain_constraints, not an array.");
420         *rc=TR_CFG_NOPARSE;
421         goto cleanup;
422       } else if (json_array_size(jdc)>TR_MAX_CONST_MATCHES) {
423         tr_err("tr_cfg_parse_one_filter: domain_constraints has too many entries, maximum of %d.",
424                TR_MAX_CONST_MATCHES);
425         *rc=TR_CFG_NOPARSE;
426         goto cleanup;
427       } else if (json_array_size(jdc)>0) {
428         if (NULL==(filt->lines[i]->domain_cons=tr_cfg_parse_one_constraint(filt->lines[i], "domain", jdc, rc))) {
429           tr_debug("tr_cfg_parse_one_filter: Error parsing domain constraint");
430           *rc=TR_CFG_NOPARSE;
431           goto cleanup;
432         }
433       }
434     }
435
436     /*For each filter spec within the filter line... */
437     for (j=0; j <json_array_size(jfspecs); j++) {
438       if ((NULL==(jffield=json_object_get(json_array_get(jfspecs, j), "field"))) ||
439           (!json_is_string(jffield)) ||
440           (NULL==(jfmatch=json_object_get(json_array_get(jfspecs, j), "match"))) ||
441           (!json_is_string(jfmatch))) {
442         tr_debug("tr_cfg_parse_one_filter: Error parsing filter field and match for filter spec %d, filter line %d.", i, j);
443         *rc=TR_CFG_NOPARSE;
444         goto cleanup;
445       }
446
447       if (NULL==(filt->lines[i]->specs[j]=tr_fspec_new(filt->lines[i]))) {
448         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
449         *rc=TR_CFG_NOMEM;
450         goto cleanup;
451       }
452
453       if ((NULL==(filt->lines[i]->specs[j]->field=tr_new_name(json_string_value(jffield)))) ||
454           (NULL==(filt->lines[i]->specs[j]->match=tr_new_name(json_string_value(jfmatch))))) {
455         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
456         *rc=TR_CFG_NOMEM;
457         goto cleanup;
458       }
459     }
460   }
461   *rc=TR_CFG_SUCCESS;
462   talloc_steal(mem_ctx, filt);
463   
464  cleanup:
465   talloc_free(tmp_ctx);
466   return filt;
467 }
468
469 static TR_FILTER *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_CFG_RC *rc)
470 {
471   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
472   json_t *jfilt;
473   TR_FILTER *filt=NULL;
474   int ii=0;
475
476   *rc=TR_CFG_ERROR;
477
478   /* no filters */
479   if (jfilts==NULL) {
480     *rc=TR_CFG_SUCCESS;
481     goto cleanup;
482   }
483
484   jfilt=json_object_get(jfilts, "tid_inbound");
485   if (jfilt!=NULL) {
486     filt=tr_cfg_parse_one_filter(tmp_ctx, jfilt, TR_FILTER_TYPE_TID_INCOMING, rc);
487     if (*rc!=TR_CFG_SUCCESS) {
488       tr_debug("tr_cfg_parse_filters: Error parsing tid_inbound filter.");
489       *rc=TR_CFG_NOPARSE;
490       goto cleanup;
491     }
492   } else {
493     tr_debug("tr_cfg_parse_filters: Unknown filter types in filter block.");
494     *rc=TR_CFG_NOPARSE;
495     goto cleanup;
496   }
497   
498   *rc=TR_CFG_SUCCESS;
499
500  cleanup:
501   if (*rc==TR_CFG_SUCCESS)
502     talloc_steal(mem_ctx, filt);
503   else {
504     talloc_free(filt);
505     filt=NULL;
506   }
507
508   talloc_free(tmp_ctx);
509   return filt;
510 }
511
512 static TR_AAA_SERVER *tr_cfg_parse_one_aaa_server(TALLOC_CTX *mem_ctx, json_t *jaddr, TR_CFG_RC *rc)
513 {
514   TR_AAA_SERVER *aaa = NULL;
515   TR_NAME *name=NULL;
516
517   if ((!jaddr) || (!json_is_string(jaddr))) {
518     tr_debug("tr_cfg_parse_one_aaa_server: Bad parameters.");
519     *rc = TR_CFG_BAD_PARAMS;
520     return NULL;
521   }
522
523   name=tr_new_name(json_string_value(jaddr));
524   if (name==NULL) {
525     tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating hostname.");
526     *rc = TR_CFG_NOMEM;
527     return NULL;
528   }
529
530   aaa=tr_aaa_server_new(mem_ctx, name);
531   if (aaa==NULL) {
532     tr_free_name(name);
533     tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating AAA server.");
534     *rc = TR_CFG_NOMEM;
535     return NULL;
536   }
537
538   return aaa;
539 }
540
541 static TR_AAA_SERVER *tr_cfg_parse_aaa_servers(TALLOC_CTX *mem_ctx, json_t *jaaas, TR_CFG_RC *rc) 
542 {
543   TALLOC_CTX *tmp_ctx=NULL;
544   TR_AAA_SERVER *aaa = NULL;
545   TR_AAA_SERVER *temp_aaa = NULL;
546   int i = 0;
547
548   for (i = 0; i < json_array_size(jaaas); i++) {
549     /* rc gets set in here */
550     if (NULL == (temp_aaa = tr_cfg_parse_one_aaa_server(tmp_ctx, json_array_get(jaaas, i), rc))) {
551       talloc_free(tmp_ctx);
552       return NULL;
553     }
554     /* TBD -- IPv6 addresses */
555     //    tr_debug("tr_cfg_parse_aaa_servers: Configuring AAA Server: ip_addr = %s.", inet_ntoa(temp_aaa->aaa_server_addr));
556     temp_aaa->next = aaa;
557     aaa = temp_aaa;
558   }
559   tr_debug("tr_cfg_parse_aaa_servers: Finished (rc=%d)", *rc);
560
561   for (temp_aaa=aaa; temp_aaa!=NULL; temp_aaa=temp_aaa->next)
562     talloc_steal(mem_ctx, temp_aaa);
563   talloc_free(tmp_ctx);
564   return aaa;
565 }
566
567 static TR_APC *tr_cfg_parse_apc(TALLOC_CTX *mem_ctx, json_t *japc, TR_CFG_RC *rc)
568 {
569   TR_APC *apc=NULL;
570   TR_NAME *name=NULL;
571   
572   *rc = TR_CFG_SUCCESS;         /* presume success */
573
574   if ((!japc) || (!rc) || (!json_is_string(japc))) {
575     tr_debug("tr_cfg_parse_apc: Bad parameters.");
576     if (rc) 
577       *rc = TR_CFG_BAD_PARAMS;
578     return NULL;
579   }
580
581   apc=tr_apc_new(mem_ctx);
582   if (apc==NULL) {
583     tr_debug("tr_cfg_parse_apc: Out of memory.");
584     *rc = TR_CFG_NOMEM;
585     return NULL;
586   }
587
588   name=tr_new_name(json_string_value(japc));
589   if (name==NULL) {
590     tr_debug("tr_cfg_parse_apc: No memory for APC name.");
591     tr_apc_free(apc);
592     *rc = TR_CFG_NOMEM;
593     return NULL;
594   }
595   tr_apc_set_id(apc, name); /* apc is now responsible for freeing the name */
596
597   return apc;
598 }
599
600 static TR_NAME *tr_cfg_parse_name(TALLOC_CTX *mem_ctx, json_t *jname, TR_CFG_RC *rc)
601 {
602   TR_NAME *name=NULL;
603   *rc=TR_CFG_ERROR;
604
605   if ((jname==NULL) || (!json_is_string(jname))) {
606     tr_err("tr_cfg_parse_name: name missing or not a string");
607     *rc=TR_CFG_BAD_PARAMS;
608     name=NULL;
609   } else {
610     name=tr_new_name(json_string_value(jname));
611     if (name==NULL) {
612       tr_err("tr_cfg_parse_name: could not allocate name");
613       *rc=TR_CFG_NOMEM;
614     } else {
615       *rc=TR_CFG_SUCCESS;
616     }
617   }
618   return name;  
619 }
620
621 static int tr_cfg_parse_shared_config(json_t *jsc, TR_CFG_RC *rc)
622 {
623   const char *shared=NULL;
624   *rc=TR_CFG_SUCCESS;
625   
626   if ((jsc==NULL) ||
627       (!json_is_string(jsc)) ||
628       (NULL==(shared=json_string_value(jsc)))) {
629     *rc=TR_CFG_BAD_PARAMS;
630     return -1;
631   }
632
633   if (0==strcmp(shared, "no"))
634     return 0;
635   else if (0==strcmp(shared, "yes"))
636     return 1;
637
638   /* any other value is an error */
639   tr_debug("tr_cfg_parse_shared_config: invalid shared_config value \"%s\" (should be \"yes\" or \"no\")",
640            shared);
641   *rc=TR_CFG_NOPARSE;
642   return -1;
643 }
644
645 /* Parse the identity provider object from a realm and fill in the given TR_IDP_REALM. */
646 static TR_CFG_RC tr_cfg_parse_idp(TR_IDP_REALM *idp, json_t *jidp)
647 {
648   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
649   TR_APC *apcs=NULL;
650   TR_AAA_SERVER *aaa=NULL;
651   TR_CFG_RC rc=TR_CFG_ERROR;
652
653   if (jidp==NULL)
654     goto cleanup;
655
656   idp->origin=TR_REALM_LOCAL; /* if we're parsing it from a config file, it's local */
657   idp->shared_config=tr_cfg_parse_shared_config(json_object_get(jidp, "shared_config"), &rc);
658   if (rc!=TR_CFG_SUCCESS) {
659     tr_err("tr_cfg_parse_idp: missing or malformed shared_config specification");
660     rc=TR_CFG_NOPARSE;
661     goto cleanup;
662   }
663
664   apcs=tr_cfg_parse_apc(tmp_ctx, json_object_get(jidp, "apc"), &rc);
665   if ((rc!=TR_CFG_SUCCESS) || (apcs==NULL)) {
666     tr_err("tr_cfg_parse_idp: unable to parse APC");
667     rc=TR_CFG_NOPARSE;
668     goto cleanup;
669   }
670   tr_debug("tr_cfg_parse_idp: APC=\"%.*s\"",
671            apcs->id->len,
672            apcs->id->buf);
673
674   aaa=tr_cfg_parse_aaa_servers(idp, json_object_get(jidp, "aaa_servers"), &rc);
675   if ((rc!=TR_CFG_SUCCESS) || (aaa==NULL)) {
676     tr_err("tr_cfg_parse_idp: unable to parse AAA servers");
677     rc=TR_CFG_NOPARSE;
678     goto cleanup;
679   }
680
681   /* done, fill in the idp structures */
682   idp->apcs=apcs;
683   talloc_steal(idp, apcs);
684   idp->aaa_servers=aaa;
685   rc=TR_CFG_SUCCESS;
686
687  cleanup:
688   if (rc!=TR_CFG_SUCCESS) {
689     if (apcs!=NULL)
690       tr_apc_free(apcs);
691     if (aaa!=NULL)
692       tr_aaa_server_free(aaa);
693   }
694
695   talloc_free(tmp_ctx);
696   return rc;
697 }
698
699 /* parses idp realm */
700 static TR_IDP_REALM *tr_cfg_parse_one_idp_realm(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
701 {
702   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
703   TR_IDP_REALM *realm=NULL;
704   TR_CFG_RC call_rc=TR_CFG_ERROR;
705
706   *rc=TR_CFG_ERROR; /* default to error if not set */
707
708   if ((!jrealm) || (!rc)) {
709     tr_err("tr_cfg_parse_one_idp_realm: Bad parameters.");
710     if (rc)
711       *rc=TR_CFG_BAD_PARAMS;
712     goto cleanup;
713   }
714
715   if (NULL==(realm=tr_idp_realm_new(tmp_ctx))) {
716     tr_err("tr_cfg_parse_one_idp_realm: could not allocate idp realm.");
717     *rc=TR_CFG_NOMEM;
718     goto cleanup;
719   }
720
721   /* must have a name */
722   realm->realm_id=tr_cfg_parse_name(realm,
723                                     json_object_get(jrealm, "realm"),
724                                    &call_rc);
725   if ((call_rc!=TR_CFG_SUCCESS) || (realm->realm_id==NULL)) {
726     tr_err("tr_cfg_parse_one_idp_realm: could not parse realm name");
727     *rc=TR_CFG_NOPARSE;
728     goto cleanup;
729   }
730   tr_debug("tr_cfg_parse_one_idp_realm: realm_id=\"%.*s\"",
731            realm->realm_id->len,
732            realm->realm_id->buf);
733         
734   call_rc=tr_cfg_parse_idp(realm, json_object_get(jrealm, "identity_provider"));
735   if (call_rc!=TR_CFG_SUCCESS) {
736     tr_err("tr_cfg_parse_one_idp_realm: could not parse identity_provider.");
737     *rc=TR_CFG_NOPARSE;
738     goto cleanup;
739   }
740
741   *rc=TR_CFG_SUCCESS;
742
743   cleanup:
744     if (*rc==TR_CFG_SUCCESS)
745       talloc_steal(mem_ctx, realm);
746     else {
747       talloc_free(realm);
748       realm=NULL;
749     }
750
751     talloc_free(tmp_ctx);
752     return realm;
753   }
754
755   /* Determine whether the realm is an IDP realm */
756 static int tr_cfg_is_idp_realm(json_t *jrealm)
757 {
758   /* If a realm spec contains an identity_provider, it's an IDP realm. */
759   if (NULL != json_object_get(jrealm, "identity_provider"))
760     return 1;
761   else
762     return 0;
763 }
764
765 /* Parse any idp realms in the j_realms object. Ignores other realm types. */
766 static TR_IDP_REALM *tr_cfg_parse_idp_realms(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
767 {
768   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
769   TR_IDP_REALM *realms=NULL;
770   TR_IDP_REALM *new_realm=NULL;
771   json_t *this_jrealm=NULL;
772   int ii=0;
773
774   *rc=TR_CFG_ERROR;
775   if ((jrealms==NULL) || (!json_is_array(jrealms))) {
776     tr_err("tr_cfg_parse_idp_realms: realms not an array");
777     *rc=TR_CFG_BAD_PARAMS;
778     goto cleanup;
779   }
780
781   for (ii=0; ii<json_array_size(jrealms); ii++) {
782     this_jrealm=json_array_get(jrealms, ii);
783     if (tr_cfg_is_idp_realm(this_jrealm)) {
784       new_realm=tr_cfg_parse_one_idp_realm(tmp_ctx, this_jrealm, rc);
785       if ((*rc)!=TR_CFG_SUCCESS) {
786         tr_err("tr_cfg_parse_idp_realms: error decoding realm entry %d", ii+1);
787         *rc=TR_CFG_NOPARSE;
788         goto cleanup;
789       }
790       realms=tr_idp_realm_add(realms, new_realm);
791     }
792   }
793   
794   *rc=TR_CFG_SUCCESS;
795   talloc_steal(mem_ctx, realms);
796
797 cleanup:
798   talloc_free(tmp_ctx);
799   return realms;
800 }
801
802 static TR_CFG_RC tr_cfg_parse_gss_names(TR_RP_CLIENT *client, json_t *jgss_names)
803 {
804   json_t *jname=NULL;
805   int ii=0;
806   TR_NAME *name=NULL;
807
808   if ((client==NULL) || (jgss_names==NULL)) {
809     tr_err("tr_cfg_parse_gss_names: Bad parameters.");
810     return TR_CFG_BAD_PARAMS;
811   }
812
813   if (!json_is_array(jgss_names)) {
814     tr_err("tr_cfg_parse_gss_names: gss_names not an array.");
815     return TR_CFG_NOPARSE;
816   }
817
818   for (ii=0; ii<json_array_size(jgss_names); ii++) {
819     jname=json_array_get(jgss_names, ii);
820     if (!json_is_string(jname)) {
821       tr_err("tr_cfg_parse_gss_names: Encountered non-string gss name.");
822       return TR_CFG_NOPARSE;
823     }
824     name=tr_new_name(json_string_value(jname));
825     if (name==NULL) {
826       tr_err("tr_cfg_parse_gss_names: Out of memory allocating gss name.");
827       return TR_CFG_NOMEM;
828     }
829     if (tr_rp_client_add_gss_name(client, name)!=0) {
830       tr_free_name(name);
831       tr_err("tr_cfg_parse_gss_names: Unable to add gss name to RP client.");
832       return TR_CFG_ERROR;
833     }
834   }
835
836   return TR_CFG_SUCCESS;
837 }
838
839 /* parses rp client */
840 static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
841 {
842   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
843   TR_RP_CLIENT *client=NULL;
844   TR_CFG_RC call_rc=TR_CFG_ERROR;
845   TR_FILTER *new_filt=NULL;
846
847   *rc=TR_CFG_ERROR; /* default to error if not set */
848
849   if ((!jrealm) || (!rc)) {
850     tr_err("tr_cfg_parse_one_rp_client: Bad parameters.");
851     if (rc)
852       *rc=TR_CFG_BAD_PARAMS;
853     goto cleanup;
854   }
855
856   if (NULL==(client=tr_rp_client_new(tmp_ctx))) {
857     tr_err("tr_cfg_parse_one_rp_client: could not allocate rp client.");
858     *rc=TR_CFG_NOMEM;
859     goto cleanup;
860   }
861
862   call_rc=tr_cfg_parse_gss_names(client, json_object_get(jrealm, "gss_names"));
863   if (call_rc!=TR_CFG_SUCCESS) {
864     tr_err("tr_cfg_parse_one_rp_client: could not parse gss_names.");
865     *rc=TR_CFG_NOPARSE;
866     goto cleanup;
867   }
868
869   /* parse filters */
870   new_filt=tr_cfg_parse_filters(tmp_ctx, json_object_get(jrealm, "filters"), &call_rc);
871   if (call_rc!=TR_CFG_SUCCESS) {
872     tr_err("tr_cfg_parse_one_rp_client: could not parse filters.");
873     *rc=TR_CFG_NOPARSE;
874     goto cleanup;
875   }
876
877   tr_rp_client_set_filter(client, new_filt);
878   *rc=TR_CFG_SUCCESS;
879
880   cleanup:
881     if (*rc==TR_CFG_SUCCESS)
882       talloc_steal(mem_ctx, client);
883     else {
884       talloc_free(client);
885       client=NULL;
886     }
887
888     talloc_free(tmp_ctx);
889     return client;
890   }
891
892   /* Determine whether the realm is an RP realm */
893 static int tr_cfg_is_rp_realm(json_t *jrealm)
894 {
895   /* Check that we have a gss name. */
896   if (NULL != json_object_get(jrealm, "gss_names"))
897     return 1;
898   else
899     return 0;
900 }
901
902 /* Parse any rp clients in the j_realms object. Ignores other realms. */
903 static TR_RP_CLIENT *tr_cfg_parse_rp_clients(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
904 {
905   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
906   TR_RP_CLIENT *clients=NULL;
907   TR_RP_CLIENT *new_client=NULL;
908   json_t *this_jrealm=NULL;
909   int ii=0;
910
911   *rc=TR_CFG_ERROR;
912   if ((jrealms==NULL) || (!json_is_array(jrealms))) {
913     tr_err("tr_cfg_parse_rp_clients: realms not an array");
914     *rc=TR_CFG_BAD_PARAMS;
915     goto cleanup;
916   }
917
918   for (ii=0; ii<json_array_size(jrealms); ii++) {
919     this_jrealm=json_array_get(jrealms, ii);
920     if (tr_cfg_is_rp_realm(this_jrealm)) {
921       new_client=tr_cfg_parse_one_rp_client(tmp_ctx, this_jrealm, rc);
922       if ((*rc)!=TR_CFG_SUCCESS) {
923         tr_err("tr_cfg_parse_rp_clients: error decoding realm entry %d", ii+1);
924         *rc=TR_CFG_NOPARSE;
925         goto cleanup;
926       }
927       clients=tr_rp_client_add(clients, new_client);
928     }
929   }
930   
931   *rc=TR_CFG_SUCCESS;
932   talloc_steal(mem_ctx, clients);
933
934 cleanup:
935   talloc_free(tmp_ctx);
936   return clients;
937 }
938
939 /* takes a talloc context, but currently does not use it */
940 static TR_NAME *tr_cfg_parse_org_name(TALLOC_CTX *mem_ctx, json_t *j_org, TR_CFG_RC *rc)
941 {
942   TR_NAME *name=NULL;
943
944   if ((j_org==NULL) || (rc==NULL) || (!json_is_string(j_org))) {
945     tr_debug("tr_cfg_parse_org_name: Bad parameters.");
946     if (rc!=NULL)
947       *rc = TR_CFG_BAD_PARAMS; /* fill in return value if we can */
948     return NULL;
949   }
950
951   name=tr_new_name(json_string_value(j_org));
952   if (name==NULL)
953     *rc=TR_CFG_NOMEM;
954   else
955     *rc=TR_CFG_SUCCESS;
956   return name;
957 }
958
959 /* Update the community information with data from a new batch of IDP realms.
960  * May partially add realms if there is a failure, no guarantees.
961  * Call like comms=tr_comm_idp_update(comms, new_realms, &rc) */
962 static TR_COMM *tr_cfg_comm_idp_update(TALLOC_CTX *mem_ctx, TR_COMM *comms, TR_IDP_REALM *new_realms, TR_CFG_RC *rc)
963 {
964   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
965   TR_COMM *comm=NULL; /* community looked up in comms table */
966   TR_COMM *new_comms=NULL; /* new communities as we create them */
967   TR_IDP_REALM *realm=NULL;
968   TR_APC *apc=NULL; /* apc of one realm */
969
970   if (rc==NULL) {
971     *rc=TR_CFG_BAD_PARAMS;
972     goto cleanup;
973   }
974
975   /* start with an empty list communities, then fill that in */
976   for (realm=new_realms; realm!=NULL; realm=realm->next) {
977     for (apc=realm->apcs; apc!=NULL; apc=apc->next) {
978       comm=tr_comm_lookup(comms, apc->id);
979       if (comm==NULL) {
980         comm=tr_comm_new(tmp_ctx);
981         if (comm==NULL) {
982           tr_debug("tr_cfg_comm_idp_update: unable to allocate new community.");
983           *rc=TR_CFG_NOMEM;
984           goto cleanup;
985         }
986         /* fill in the community with info */
987         comm->type=TR_COMM_APC; /* realms added this way are in APCs */
988         comm->expiration_interval=TR_DEFAULT_APC_EXPIRATION_INTERVAL;
989         comm->id=tr_dup_name(apc->id);
990         tr_comm_add_idp_realm(comm, realm);
991         new_comms=tr_comm_add(new_comms, comm);
992       } else {
993         /* add this realm to the comm */
994         tr_comm_add_idp_realm(comm, realm);
995       }
996     }
997   }
998
999   /* we successfully built a list, add it to the other list */
1000   comms=tr_comm_add(comms, new_comms);
1001   talloc_steal(mem_ctx, comms);
1002  cleanup:
1003   talloc_free(tmp_ctx);
1004   return comms;
1005 }
1006
1007
1008 static TR_CFG_RC tr_cfg_parse_one_local_org(TR_CFG *trc, json_t *jlorg)
1009 {
1010   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1011   TR_CFG_RC retval=TR_CFG_ERROR; /* our return code */
1012   TR_CFG_RC rc=TR_CFG_ERROR; /* return code from functions we call */
1013   TR_NAME *org_name=NULL;
1014   json_t *j_org=NULL;
1015   json_t *j_realms=NULL;
1016   TR_IDP_REALM *new_idp_realms=NULL;
1017   TR_RP_CLIENT *new_rp_clients=NULL;
1018
1019   tr_debug("tr_cfg_parse_one_local_org: parsing local organization");
1020
1021   /* get organization_name (optional) */
1022   if (NULL==(j_org=json_object_get(jlorg, "organization_name"))) {
1023     tr_debug("tr_cfg_parse_one_local_org: organization_name unspecified");
1024   } else {
1025     org_name=tr_cfg_parse_org_name(tmp_ctx, j_org, &rc);
1026     if (rc==TR_CFG_SUCCESS) {
1027       tr_debug("tr_cfg_parse_one_local_org: organization_name=\"%.*s\"",
1028                org_name->len,
1029                org_name->buf);
1030       /* we don't actually do anything with this, but we could */
1031       tr_free_name(org_name);
1032       org_name=NULL; 
1033     }
1034   }
1035
1036   /* Now get realms. Allow this to be missing; even though that is a pointless organization entry,
1037    * it's harmless. Report a warning because that might be unintentional. */
1038   if (NULL==(j_realms=json_object_get(jlorg, "realms"))) {
1039     tr_warning("tr_cfg_parse_one_local_org: warning - no realms in this local organization");
1040   } else {
1041     /* Allocate in the tmp_ctx so these will be cleaned up if we do not complete successfully. */
1042     new_idp_realms=tr_cfg_parse_idp_realms(tmp_ctx, j_realms, &rc);
1043     if (rc!=TR_CFG_SUCCESS)
1044       goto cleanup;
1045
1046     new_rp_clients=tr_cfg_parse_rp_clients(tmp_ctx, j_realms, &rc);
1047     if (rc!=TR_CFG_SUCCESS)
1048       goto cleanup;
1049   }
1050   retval=TR_CFG_SUCCESS;
1051   
1052 cleanup:
1053   /* if we succeeded, link things to the configuration and move out of tmp context */
1054   if (retval==TR_CFG_SUCCESS) {
1055     if (new_idp_realms!=NULL) {
1056       trc->idp_realms=tr_idp_realm_add(trc->idp_realms, new_idp_realms); /* fixes talloc contexts except for head*/
1057       talloc_steal(trc, trc->idp_realms); /* make sure the head is in the right context */
1058       trc->comms=tr_cfg_comm_idp_update(trc, trc->comms, new_idp_realms, &rc); /* put realm info in community table */
1059     }
1060
1061     if (new_rp_clients!=NULL) {
1062       trc->rp_clients=tr_rp_client_add(trc->rp_clients, new_rp_clients); /* fixes talloc contexts */
1063       talloc_steal(trc, trc->rp_clients); /* make sure head is in the right context */
1064     }
1065   }
1066
1067   talloc_free(tmp_ctx);
1068   return rc;
1069 }
1070
1071 /* Parse local organizations if present. Returns success if there are none. On failure, the configuration is unreliable. */
1072 static TR_CFG_RC tr_cfg_parse_local_orgs(TR_CFG *trc, json_t *jcfg)
1073 {
1074   json_t *jlocorgs=NULL;
1075   int ii=0;
1076
1077   jlocorgs=json_object_get(jcfg, "local_organizations");
1078   if (jlocorgs==NULL)
1079     return TR_CFG_SUCCESS;
1080
1081   if (!json_is_array(jlocorgs)) {
1082     tr_err("tr_cfg_parse_local_orgs: local_organizations is not an array.");
1083     return TR_CFG_NOPARSE;
1084   }
1085
1086   for (ii=0; ii<json_array_size(jlocorgs); ii++) {
1087     if (tr_cfg_parse_one_local_org(trc, json_array_get(jlocorgs, ii))!=TR_CFG_SUCCESS) {
1088       tr_err("tr_cfg_parse_local_orgs: error parsing local_organization %d.", ii+1);
1089       return TR_CFG_NOPARSE;
1090     }
1091   }
1092
1093   return TR_CFG_SUCCESS;
1094 }
1095              
1096
1097 TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
1098 {
1099   TR_CFG_RC rc = TR_CFG_SUCCESS;
1100
1101   if (!trc)
1102     return TR_CFG_BAD_PARAMS;
1103
1104   if ((NULL == trc->internal)||
1105       (NULL == trc->internal->hostname)) {
1106     tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
1107     rc = TR_CFG_ERROR;
1108   }
1109
1110   if (NULL == trc->rp_clients) {
1111     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
1112     rc = TR_CFG_ERROR;
1113   }
1114
1115   if (NULL == trc->comms) {
1116     tr_debug("tr_cfg_validate: Error: No Communities configured");
1117     rc = TR_CFG_ERROR;
1118   }
1119
1120   if ((NULL == trc->default_servers) && (NULL == trc->idp_realms)) {
1121     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
1122     rc = TR_CFG_ERROR;
1123   }
1124   
1125   return rc;
1126 }
1127
1128 /* Join two paths and return a pointer to the result. This should be freed
1129  * via talloc_free. Returns NULL on failure. */
1130 static char *join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
1131 {
1132   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
1133 }
1134
1135 TR_CFG_RC tr_cfg_parse_one_config_file(TR_CFG *cfg, const char *file_with_path)
1136 {
1137   json_t *jcfg=NULL;
1138   json_t *jser=NULL;
1139   json_error_t rc;
1140
1141   if (NULL==(jcfg=json_load_file(file_with_path, 
1142                                  JSON_DISABLE_EOF_CHECK, &rc))) {
1143     tr_debug("tr_parse_config: Error parsing config file %s.", 
1144              file_with_path);
1145     return TR_CFG_NOPARSE;
1146   }
1147
1148   // Look for serial number and log it if it exists
1149   if (NULL!=(jser=json_object_get(jcfg, "serial_number"))) {
1150     if (json_is_number(jser)) {
1151       tr_notice("tr_read_config: Attempting to load revision %" JSON_INTEGER_FORMAT " of '%s'.",
1152                 json_integer_value(jser),
1153                 file_with_path);
1154     }
1155   }
1156
1157   /* TODO: parse using the new functions */
1158 #if 0
1159   if ((TR_CFG_SUCCESS != tr_cfg_parse_internal(cfg, jcfg)) ||
1160       (TR_CFG_SUCCESS != tr_cfg_parse_rp_clients(cfg, jcfg)) ||
1161       (TR_CFG_SUCCESS != tr_cfg_parse_idp_realms(cfg, jcfg)) ||
1162       (TR_CFG_SUCCESS != tr_cfg_parse_default_servers(cfg, jcfg)) ||
1163       (TR_CFG_SUCCESS != tr_cfg_parse_comms(cfg, jcfg))) {
1164
1165   }
1166 #endif
1167   if (TR_CFG_SUCCESS != tr_cfg_parse_local_orgs(cfg, jcfg))
1168     return TR_CFG_ERROR;
1169
1170   return TR_CFG_SUCCESS;
1171 }
1172
1173 /* Reads configuration files in config_dir ("" or "./" will use the current directory). */
1174 TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, const char *config_dir, int n, struct dirent **cfg_files)
1175 {
1176   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
1177   json_t *jcfg;
1178   json_t *jser;
1179   json_error_t rc;
1180   char *file_with_path;
1181   int ii;
1182   TR_CFG_RC cfg_rc=TR_CFG_ERROR;
1183
1184   if ((!cfg_mgr) || (!cfg_files) || (n<=0)) {
1185     cfg_rc=TR_CFG_BAD_PARAMS;
1186     goto cleanup;
1187   }
1188
1189   if (cfg_mgr->new != NULL)
1190     tr_cfg_free(cfg_mgr->new);
1191   cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
1192   if (cfg_mgr->new == NULL) {
1193     cfg_rc=TR_CFG_NOMEM;
1194     goto cleanup;
1195   }
1196
1197   /* Parse configuration information from each config file */
1198   for (ii=0; ii<n; ii++) {
1199     file_with_path=join_paths(tmp_ctx, config_dir, cfg_files[ii]->d_name); /* must free result with talloc_free */
1200     if(file_with_path == NULL) {
1201       tr_crit("tr_parse_config: error joining path.");
1202       cfg_rc=TR_CFG_NOMEM;
1203       goto cleanup;
1204     }
1205     tr_debug("tr_parse_config: Parsing %s.", cfg_files[ii]->d_name); /* print the filename without the path */
1206     cfg_rc=tr_cfg_parse_one_config_file(cfg_mgr->new, file_with_path);
1207     if (cfg_rc!=TR_CFG_SUCCESS) {
1208       tr_crit("tr_parse_config: error parsing %s", file_with_path);
1209       goto cleanup;
1210     }
1211     talloc_free(file_with_path); /* done with filename */
1212   }
1213
1214   /* make sure we got a complete, consistent configuration */
1215   if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
1216     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
1217     cfg_rc=TR_CFG_ERROR;
1218     goto cleanup;
1219   }
1220
1221   /* success! */
1222   talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
1223   cfg_rc=TR_CFG_SUCCESS;
1224
1225 cleanup:
1226   talloc_free(tmp_ctx);
1227   return cfg_rc;
1228 }
1229
1230 TR_IDP_REALM *tr_cfg_find_idp (TR_CFG *tr_cfg, TR_NAME *idp_id, TR_CFG_RC *rc)
1231 {
1232
1233   TR_IDP_REALM *cfg_idp;
1234
1235   if ((!tr_cfg) || (!idp_id)) {
1236     if (rc)
1237       *rc = TR_CFG_BAD_PARAMS;
1238     return NULL;
1239   }
1240
1241   for (cfg_idp = tr_cfg->idp_realms; NULL != cfg_idp; cfg_idp = cfg_idp->next) {
1242     if (!tr_name_cmp (idp_id, cfg_idp->realm_id)) {
1243       tr_debug("tr_cfg_find_idp: Found %s.", idp_id->buf);
1244       return cfg_idp;
1245     }
1246   }
1247   /* if we didn't find one, return NULL */ 
1248   return NULL;
1249 }
1250
1251 TR_RP_CLIENT *tr_cfg_find_rp (TR_CFG *tr_cfg, TR_NAME *rp_gss, TR_CFG_RC *rc)
1252 {
1253   TR_RP_CLIENT *cfg_rp;
1254   int i;
1255
1256   if ((!tr_cfg) || (!rp_gss)) {
1257     if (rc)
1258       *rc = TR_CFG_BAD_PARAMS;
1259     return NULL;
1260   }
1261
1262   for (cfg_rp = tr_cfg->rp_clients; NULL != cfg_rp; cfg_rp = cfg_rp->next) {
1263     for (i = 0; i < TR_MAX_GSS_NAMES; i++) {
1264       if (!tr_name_cmp (rp_gss, cfg_rp->gss_names[i])) {
1265         tr_debug("tr_cfg_find_rp: Found %s.", rp_gss->buf);
1266         return cfg_rp;
1267       }
1268     }
1269   }
1270   /* if we didn't find one, return NULL */ 
1271   return NULL;
1272 }
1273
1274 static int is_cfg_file(const struct dirent *dent) {
1275   int n;
1276
1277   /* Only accept filenames ending in ".cfg" and starting with a character
1278    * other than an ASCII '.' */
1279
1280   /* filename must be at least 4 characters long to be acceptable */
1281   n=strlen(dent->d_name);
1282   if (n < 4) {
1283     return 0;
1284   }
1285
1286   /* filename must not start with '.' */
1287   if ('.' == dent->d_name[0]) {
1288     return 0;
1289   }
1290
1291   /* If the above passed and the last four characters of the filename are .cfg, accept.
1292    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
1293   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
1294     return 1;
1295   }
1296
1297   /* otherwise, return false. */
1298   return 0;
1299 }
1300
1301 /* Find configuration files in a particular directory. Returns the
1302  * number of entries found, 0 if none are found, or <0 for some
1303  * errors. If n>=0, the cfg_files parameter will contain a newly
1304  * allocated array of pointers to struct dirent entries, as returned
1305  * by scandir(). These can be freed with tr_free_config_file_list().
1306  */
1307 int tr_find_config_files (const char *config_dir, struct dirent ***cfg_files) {
1308   int n = 0;
1309   
1310   n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
1311
1312   if (n < 0) {
1313     perror("scandir");
1314     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
1315   } 
1316
1317   return n;
1318 }
1319
1320 /* Free memory allocated for configuration file list returned from tr_find_config_files().
1321  * This can be called regardless of the return value of tr_find_config_values(). */
1322 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
1323   int ii;
1324
1325   /* if n < 0, then scandir did not allocate anything because it failed */
1326   if((n>=0) && (*cfg_files != NULL)) {
1327     for(ii=0; ii<n; ii++) {
1328       free((*cfg_files)[ii]);
1329     }
1330     free(*cfg_files); /* safe even if n==0 */
1331     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
1332   }
1333 }