Resolve circular header dependencies.
[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_config.h>
42 #include <tr_debug.h>
43 #include <tr.h>
44 #include <tr_filter.h>
45 #include <trust_router/tr_constraint.h>
46
47 void tr_print_config (FILE *stream, TR_CFG *cfg) {
48   fprintf(stream, "tr_print_config: Not yet implemented.");
49   return;
50 }
51
52 TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
53 {
54   return talloc_zero(mem_ctx, TR_CFG);
55 }
56
57 void tr_cfg_free (TR_CFG *cfg) {
58   talloc_free(cfg);
59   return;
60 }
61
62 TR_CFG_RC tr_apply_new_config (TR_CFG **active_cfg,
63                                TR_CFG **new_cfg)
64 {
65   if ((active_cfg==NULL) || (new_cfg==NULL))
66     return TR_CFG_BAD_PARAMS;
67
68   if (*active_cfg != NULL)
69     tr_cfg_free(*active_cfg);
70
71   *active_cfg = *new_cfg;
72   *new_cfg=NULL; /* only keep a single handle on the new configuration */
73
74   tr_log_threshold((*active_cfg)->internal->log_threshold);
75   tr_console_threshold((*active_cfg)->internal->console_threshold);
76
77   return TR_CFG_SUCCESS;
78 }
79
80 static TR_CFG_RC tr_cfg_parse_internal (TR_CFG *trc, json_t *jcfg) {
81   json_t *jint = NULL;
82   json_t *jmtd = NULL;
83   json_t *jtp = NULL;
84   json_t *jhname = NULL;
85   json_t *jlog = NULL;
86   json_t *jconthres = NULL;
87   json_t *jlogthres = NULL;
88
89   if ((!trc) || (!jcfg))
90     return TR_CFG_BAD_PARAMS;
91
92   if (NULL == trc->internal) {
93     if (NULL == (trc->internal = talloc_zero(trc, TR_CFG_INTERNAL)))
94       return TR_CFG_NOMEM;
95   }
96
97   if (NULL != (jint = json_object_get(jcfg, "tr_internal"))) {
98     if (NULL != (jmtd = json_object_get(jint, "max_tree_depth"))) {
99       if (json_is_number(jmtd)) {
100         trc->internal->max_tree_depth = json_integer_value(jmtd);
101       } else {
102         tr_debug("tr_cfg_parse_internal: Parsing error, max_tree_depth is not a number.");
103         return TR_CFG_NOPARSE;
104       }
105     } else {
106       /* If not configured, use the default */
107       trc->internal->max_tree_depth = TR_DEFAULT_MAX_TREE_DEPTH;
108     }
109     if (NULL != (jtp = json_object_get(jint, "tids_port"))) {
110       if (json_is_number(jtp)) {
111         trc->internal->tids_port = json_integer_value(jtp);
112       } else {
113         tr_debug("tr_cfg_parse_internal: Parsing error, port is not a number.");
114         return TR_CFG_NOPARSE;
115       }
116     } else {
117       /* If not configured, use the default */
118       trc->internal->tids_port = TR_DEFAULT_TIDS_PORT;
119     }
120     if (NULL != (jhname = json_object_get(jint, "hostname"))) {
121       if (json_is_string(jhname)) {
122         trc->internal->hostname = json_string_value(jhname);
123       } else {
124         tr_debug("tr_cfg_parse_internal: Parsing error, hostname is not a string.");
125         return TR_CFG_NOPARSE;
126       }
127     }
128
129     if (NULL != (jlog = json_object_get(jint, "logging"))) {
130       if (NULL != (jlogthres = json_object_get(jlog, "log_threshold"))) {
131         if (json_is_string(jlogthres)) {
132           trc->internal->log_threshold = str2sev(json_string_value(jlogthres));
133         } else {
134           tr_debug("tr_cfg_parse_internal: Parsing error, log_threshold is not a string.");
135           return TR_CFG_NOPARSE;
136         }
137       } else {
138         /* If not configured, use the default */
139         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
140       }
141
142       if (NULL != (jconthres = json_object_get(jlog, "console_threshold"))) {
143         if (json_is_string(jconthres)) {
144             trc->internal->console_threshold = str2sev(json_string_value(jconthres));
145         } else {
146           tr_debug("tr_cfg_parse_internal: Parsing error, console_threshold is not a string.");
147           return TR_CFG_NOPARSE;
148         }
149       } else {
150         /* If not configured, use the default */
151         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
152       }
153     } else {
154         /* If not configured, use the default */
155         trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
156         trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
157     }
158
159     tr_debug("tr_cfg_parse_internal: Internal config parsed.");
160     return TR_CFG_SUCCESS;
161   }
162   return TR_CFG_SUCCESS;
163 }
164
165 static TR_CONSTRAINT *tr_cfg_parse_one_constraint (TR_CFG *trc, char *ctype, json_t *jc, TR_CFG_RC *rc)
166 {
167   TR_CONSTRAINT *cons;
168   int i;
169
170   if ((!trc) || (!ctype) || (!jc) || (!rc) ||
171       (!json_is_array(jc)) ||
172       (0 >= json_array_size(jc)) ||
173       (TR_MAX_CONST_MATCHES < json_array_size(jc)) ||
174       (!json_is_string(json_array_get(jc, 0)))) {
175     tr_debug("tr_cfg_parse_one_constraint: config error.");
176     *rc = TR_CFG_NOPARSE;
177     return NULL;
178   }
179
180   if (NULL == (cons = talloc_zero(trc, TR_CONSTRAINT))) {
181     tr_debug("tr_cfg_parse_one_constraint: Out of memory (cons).");
182     *rc = TR_CFG_NOMEM;
183     return NULL;
184   }
185
186   if (NULL == (cons->type = tr_new_name(ctype))) {
187     tr_debug("tr_cfg_parse_one_constraint: Out of memory (type).");
188     *rc = TR_CFG_NOMEM;
189     return NULL;
190   }
191
192   for (i = 0; i < json_array_size(jc); i++) {
193     cons->matches[i] = tr_new_name((char *)(json_string_value(json_array_get(jc, i))));
194   }
195
196   return cons;
197 }
198
199 static TR_FILTER *tr_cfg_parse_one_filter (TR_CFG *trc, json_t *jfilt, TR_CFG_RC *rc)
200 {
201   TR_FILTER *filt = NULL;
202   json_t *jftype = NULL;
203   json_t *jfls = NULL;
204   json_t *jfaction = NULL;
205   json_t *jfspecs = NULL;
206   json_t *jffield = NULL;
207   json_t *jfmatch = NULL;
208   json_t *jrc = NULL;
209   json_t *jdc = NULL;
210   int i = 0, j = 0;
211
212   if ((NULL == (jftype = json_object_get(jfilt, "type"))) ||
213       (!json_is_string(jftype))) {
214     tr_debug("tr_cfg_parse_one_filter: Error parsing filter type.");
215     *rc = TR_CFG_NOPARSE;
216     return NULL;
217   }
218
219   if ((NULL == (jfls = json_object_get(jfilt, "filter_lines"))) ||
220       (!json_is_array(jfls))) {
221     tr_debug("tr_cfg_parse_one_filter: Error parsing filter type.");
222     *rc = TR_CFG_NOPARSE;
223     return NULL;
224   }
225
226   if (TR_MAX_FILTER_LINES < json_array_size(jfls)) {
227     tr_debug("tr_cfg_parse_one_filter: Filter has too many filter_lines, maximimum of %d.", TR_MAX_FILTER_LINES);
228     *rc = TR_CFG_NOPARSE;
229     return NULL;
230   }
231
232   if (NULL == (filt = talloc_zero(trc, TR_FILTER))) {
233     tr_debug("tr_cfg_parse_one_filter: Out of memory.");
234     *rc = TR_CFG_NOMEM;
235     return NULL;
236   }
237
238   if (!strcmp(json_string_value(jftype), "rp_permitted")) {
239     filt->type = TR_FILTER_TYPE_RP_PERMITTED;
240   }
241   else {
242     tr_debug("tr_cfg_parse_one_filter: Error parsing filter type, unknown type '%s'.", json_string_value(jftype));
243     *rc = TR_CFG_NOPARSE;
244     tr_filter_free(filt);
245     return NULL;
246   }
247
248   /* For each filter line... */
249   for (i = 0; i < json_array_size(jfls); i++) {
250
251     if ((NULL == (jfaction = json_object_get(json_array_get(jfls, i), "action"))) ||
252         (!json_is_string(jfaction))) {
253       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action.");
254       *rc = TR_CFG_NOPARSE;
255       tr_filter_free(filt);
256       return NULL;
257     }
258  
259     if ((NULL == (jfspecs = json_object_get(json_array_get(jfls, i), "filter_specs"))) ||
260         (!json_is_array(jfspecs)) ||
261         (0 == json_array_size(jfspecs))) {
262       tr_debug("tr_cfg_parse_one_filter: Error parsing filter specs.");
263       *rc = TR_CFG_NOPARSE;
264       tr_filter_free(filt);
265       return NULL;
266     }
267   
268     if (TR_MAX_FILTER_SPECS < json_array_size(jfspecs)) {
269       tr_debug("tr_cfg_parse_one_filter: Filter has too many filter_specs, maximimum of %d.", TR_MAX_FILTER_SPECS);
270       *rc = TR_CFG_NOPARSE;
271       tr_filter_free(filt);
272       return NULL;
273     }
274
275     if (NULL == (filt->lines[i] = talloc_zero(trc, TR_FLINE))) {
276       tr_debug("tr_cfg_parse_one_filter: Out of memory (fline).");
277       *rc = TR_CFG_NOMEM;
278       tr_filter_free(filt);
279       return NULL;
280     }
281
282     if (!strcmp(json_string_value(jfaction), "accept")) {
283         filt->lines[i]->action = TR_FILTER_ACTION_ACCEPT;
284     }
285     else if (!strcmp(json_string_value(jfaction), "reject")) {
286       filt->lines[i]->action = TR_FILTER_ACTION_REJECT;
287     }
288     else {
289       tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.", json_string_value(jfaction));
290       *rc = TR_CFG_NOPARSE;
291       tr_filter_free(filt);
292       return NULL;
293     }
294
295     if ((NULL != (jrc = json_object_get(json_array_get(jfls, i), "realm_constraints"))) &&
296         (json_is_array(jrc)) &&
297         (0 != json_array_size(jrc)) &&
298         (TR_MAX_CONST_MATCHES >= json_array_size(jrc))) {
299
300       if (NULL == (filt->lines[i]->realm_cons = tr_cfg_parse_one_constraint(trc, "realm", jrc, rc))) {
301         tr_debug("tr_cfg_parse_one_filter: Error parsing realm constraint");
302       tr_filter_free(filt);
303       return NULL;
304       }
305     }
306
307     if ((NULL != (jdc = json_object_get(json_array_get(jfls, i), "domain_constraints"))) &&
308         (json_is_array(jdc)) &&
309         (0 != json_array_size(jdc)) &&
310         (TR_MAX_CONST_MATCHES >= json_array_size(jdc))) {
311
312       if (NULL == (filt->lines[i]->domain_cons = tr_cfg_parse_one_constraint(trc, "domain", jdc, rc))) {
313         tr_debug("tr_cfg_parse_one_filter: Error parsing domain constraint");
314       tr_filter_free(filt);
315       return NULL;
316       }
317     }
318
319     /*For each filter spec within the filter line... */
320     for (j = 0; j <json_array_size(jfspecs); j++) {
321       
322       if ((NULL == (jffield = json_object_get(json_array_get(jfspecs, j), "field"))) ||
323           (!json_is_string(jffield)) ||
324           (NULL == (jfmatch = json_object_get(json_array_get(jfspecs, j), "match"))) ||
325           (!json_is_string(jfmatch))) {
326         tr_debug("tr_cfg_parse_one_filter: Error parsing filter field and match for filter spec %d, filter line %d.", i, j);
327         *rc = TR_CFG_NOPARSE;
328         tr_filter_free(filt);
329         return NULL;
330       }
331
332       if (NULL == (filt->lines[i]->specs[j] = talloc_zero(trc, TR_FSPEC))) {
333         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
334         *rc = TR_CFG_NOMEM;
335         tr_filter_free(filt);
336         return NULL;
337       }
338
339       if ((NULL == (filt->lines[i]->specs[j]->field = tr_new_name((char *)json_string_value(jffield)))) ||
340           (NULL == (filt->lines[i]->specs[j]->match = tr_new_name((char *)json_string_value(jfmatch))))) {
341         tr_debug("tr_cfg_parse_one_filter: Out of memory.");
342         *rc = TR_CFG_NOMEM;
343         tr_filter_free(filt);
344         return NULL;
345       }
346     }
347   }
348
349   return filt;
350 }
351
352 static TR_RP_CLIENT *tr_cfg_parse_one_rp_client (TR_CFG *trc, json_t *jrp, TR_CFG_RC *rc)
353 {
354   TR_RP_CLIENT *rp = NULL;
355   json_t *jgns = NULL;
356   json_t *jfilt = NULL;
357   json_t *jftype = NULL;
358   int i = 0;
359
360   if ((!trc) || (!jrp) || (!rc)) {
361     tr_debug("tr_cfg_parse_one_rp_realm: Bad parameters.");
362     if (rc)
363       *rc = TR_CFG_BAD_PARAMS;
364     return NULL;
365   }
366
367   if ((NULL == (jgns = json_object_get(jrp, "gss_names"))) ||
368       (!json_is_array(jgns))) {
369     tr_debug("tr_cfg_parse_one_rp_client: Error parsing RP client configuration, no GSS names.");
370     *rc = TR_CFG_NOPARSE;
371     return NULL;
372   }
373
374   /* TBD -- Support more than one filter per RP client? */
375   if (NULL == (jfilt = json_object_get(jrp, "filter"))) {
376     tr_debug("tr_cfg_parse_one_rp_client: Error parsing RP client configuration, no filter.");
377     *rc = TR_CFG_NOPARSE;
378     return NULL;
379   }
380
381   /* We only support rp_permitted filters for RP clients */
382   if ((NULL == (jftype = json_object_get(jfilt, "type"))) ||
383       (!json_is_string(jftype)) ||
384       (strcmp(json_string_value(jftype), "rp_permitted"))) {
385     tr_debug("tr_cfg_parse_one_rp_client: Error parsing RP client filter type.");
386     *rc = TR_CFG_NOPARSE;
387     return NULL;
388   }
389
390   if (TR_MAX_GSS_NAMES < json_array_size(jgns)) {
391     tr_debug("tr_cfg_parse_one_rp_client: RP Client has too many GSS Names.");
392     *rc = TR_CFG_NOPARSE;
393     return NULL;
394   }
395
396   if (NULL == (rp = talloc_zero(trc, TR_RP_CLIENT))) {
397     tr_debug("tr_cfg_parse_one_rp_realm: Out of memory.");
398     *rc = TR_CFG_NOMEM;
399     return NULL;
400   }
401
402   /* TBD -- support more than one filter entry per RP Client? */
403   if (NULL == (rp->filter = tr_cfg_parse_one_filter(trc, jfilt, rc))) {
404     tr_debug("tr_cfg_parse_one_rp_client: Error parsing filter.");
405     *rc = TR_CFG_NOPARSE;
406     return NULL;
407   }
408     
409   for (i = 0; i < json_array_size(jgns); i++) {
410     if (NULL == (rp->gss_names[i] = tr_new_name ((char *)json_string_value(json_array_get(jgns, i))))) {
411       tr_debug("tr_cfg_parse_one_rp_client: No memory for GSS Name.");
412       *rc = TR_CFG_NOMEM;
413       return NULL;
414     }
415   }
416   
417   return rp;
418 }
419
420 static TR_CFG_RC tr_cfg_parse_rp_clients (TR_CFG *trc, json_t *jcfg) {
421   json_t *jrps = NULL;
422   TR_RP_CLIENT *rp = NULL;
423   TR_CFG_RC rc = TR_CFG_SUCCESS;
424   int i = 0;
425
426   if ((!trc) || (!jcfg))
427     return TR_CFG_BAD_PARAMS;
428
429   if (NULL != (jrps = json_object_get(jcfg, "rp_clients"))) {
430
431     if (!json_is_array(jrps)) {
432       return TR_CFG_NOPARSE;
433     }
434
435     for (i = 0; i < json_array_size(jrps); i++) {
436       if (NULL == (rp = tr_cfg_parse_one_rp_client(trc, 
437                                                    json_array_get(jrps, i), 
438                                                    &rc))) {
439         return rc;
440       }
441       tr_debug("tr_cfg_parse_rp_clients: RP client configured -- first gss: %s", rp->gss_names[0]->buf);
442       rp->next = trc->rp_clients;
443       trc->rp_clients = rp;
444     }
445   }
446   return rc;
447 }
448
449 static TR_AAA_SERVER *tr_cfg_parse_one_aaa_server (TR_CFG *trc, json_t *jaddr, TR_CFG_RC *rc) {
450   TR_AAA_SERVER *aaa = NULL;
451
452   if ((!trc) || (!jaddr) || (!json_is_string(jaddr))) {
453     tr_debug("tr_cfg_parse_one_aaa_server: Bad parameters.");
454     *rc = TR_CFG_BAD_PARAMS;
455     return NULL;
456   }
457
458   if (NULL == (aaa = talloc_zero(trc, TR_AAA_SERVER))) {
459     tr_debug("tr_cfg_parse_one_aaa_server: Out of memory.");
460     *rc = TR_CFG_NOMEM;
461     return NULL;
462   }
463
464   aaa->hostname = tr_new_name((char *)(json_string_value(jaddr)));
465
466   return aaa;
467 }
468
469 static TR_AAA_SERVER *tr_cfg_parse_aaa_servers (TR_CFG *trc, json_t *jaaas, TR_CFG_RC *rc) 
470 {
471   TR_AAA_SERVER *aaa = NULL;
472   TR_AAA_SERVER *temp_aaa = NULL;
473   int i = 0;
474
475   for (i = 0; i < json_array_size(jaaas); i++) {
476     if (NULL == (temp_aaa = tr_cfg_parse_one_aaa_server(trc, json_array_get(jaaas, i), rc))) {
477       return NULL;
478     }
479     /* TBD -- IPv6 addresses */
480     //    tr_debug("tr_cfg_parse_aaa_servers: Configuring AAA Server: ip_addr = %s.", inet_ntoa(temp_aaa->aaa_server_addr));
481     temp_aaa->next = aaa;
482     aaa = temp_aaa;
483   }
484   return aaa;
485 }
486
487 static TR_APC *tr_cfg_parse_apcs (TR_CFG *trc, json_t *japcs, TR_CFG_RC *rc)
488 {
489   TR_APC *apc;
490
491   *rc = TR_CFG_SUCCESS;         /* presume success */
492
493   if ((!trc) || (!japcs) || (!rc)) {
494     tr_debug("tr_cfg_parse_apcs: Bad parameters.");
495     if (rc) 
496       *rc = TR_CFG_BAD_PARAMS;
497     return NULL;
498   }
499
500   if (NULL == (apc = talloc_zero(trc, TR_APC))) {
501     tr_debug("tr_cfg_parse_apcs: Out of memory.");
502     *rc = TR_CFG_NOMEM;
503     return NULL;
504   }
505
506   /* TBD, deal with more than one APC.  In the meantime, though...                */
507   /* Only parse the first APC, because we only know how to deal with one, anyway. */
508   if (0 == json_array_size(japcs))
509     return NULL;
510
511   if (NULL == (apc->id = tr_new_name((char *)json_string_value(json_array_get(japcs, 0))))) {
512     tr_debug("tr_cfg_parse_apcs: No memory for APC name.");
513     *rc = TR_CFG_NOMEM;
514     return NULL;
515   }
516
517   return apc;
518 }
519
520 static TR_IDP_REALM *tr_cfg_parse_one_idp_realm (TR_CFG *trc, json_t *jidp, TR_CFG_RC *rc) {
521   TR_IDP_REALM *idp = NULL;
522   json_t *jrid = NULL;
523   json_t *jscfg = NULL;
524   json_t *jsrvrs = NULL;
525   json_t *japcs = NULL;
526
527   if ((!trc) || (!jidp) || (!rc)) {
528     tr_debug("tr_cfg_parse_one_idp_realm: Bad parameters.");
529     if (rc)
530       *rc = TR_CFG_BAD_PARAMS;
531     return NULL;
532   }
533
534   if (NULL == (idp = talloc_zero(trc, TR_IDP_REALM))) {
535     tr_debug("tr_cfg_parse_one_idp_realm: Out of memory.");
536     *rc = TR_CFG_NOMEM;
537     return NULL;
538   }
539
540   if ((NULL == (jrid = json_object_get(jidp, "realm_id"))) ||
541       (!json_is_string(jrid)) ||
542       (NULL == (jscfg = json_object_get(jidp, "shared_config"))) ||
543       (!json_is_string(jscfg)) ||
544       (NULL == (jsrvrs = json_object_get(jidp, "aaa_servers"))) ||
545       (!json_is_array(jsrvrs))) {
546     tr_debug("tr_cfg_parse_one_idp_realm: Error parsing IDP realm configuration.");
547     *rc = TR_CFG_NOPARSE;
548     return NULL;
549   }
550
551   if (0 == strcmp(json_string_value(jscfg), "no")) {
552     idp->shared_config = 0;
553   } else {
554     idp->shared_config = 1;
555   }
556
557   if (NULL == (idp->realm_id = tr_new_name((char *)json_string_value(jrid)))) {
558     tr_debug("tr_cfg_parse_one_idp_realm: No memory for realm id.");
559     *rc = TR_CFG_NOMEM;
560     return NULL;
561   }
562
563   if (NULL == (idp->aaa_servers = tr_cfg_parse_aaa_servers(trc, jsrvrs, rc))) {
564     tr_debug("tr_cfg_parse_one_idp_realm: Can't parse AAA servers for realm %s.", idp->realm_id->buf);
565     tr_free_name(idp->realm_id);
566     return NULL;
567   }
568
569   if ((NULL != (japcs = json_object_get(jidp, "apcs"))) &&
570       (json_is_array(japcs))) {
571     if (NULL == (idp->apcs = tr_cfg_parse_apcs(trc, japcs, rc))) {
572       tr_debug("tr_cfg_parse_one_idp_realm: Can't parse APCs for realm %s .", idp->realm_id->buf);
573       tr_free_name(idp->realm_id);
574       /* TBD -- free aaa_servers */;
575       return NULL;
576     }
577   } 
578   return idp;
579 }
580
581 static TR_CFG_RC tr_cfg_parse_default_servers (TR_CFG *trc, json_t *jcfg) 
582 {
583   json_t *jdss = NULL;
584   TR_CFG_RC rc = TR_CFG_SUCCESS;
585   TR_AAA_SERVER *ds = NULL;
586   int i = 0;
587
588   if ((!trc) || (!jcfg))
589     return TR_CFG_BAD_PARAMS;
590
591   /* If there are default servers, store them */
592   if ((NULL != (jdss = json_object_get(jcfg, "default_servers"))) &&
593       (json_is_array(jdss)) &&
594       (0 < json_array_size(jdss))) {
595
596     for (i = 0; i < json_array_size(jdss); i++) {
597       if (NULL == (ds = tr_cfg_parse_one_aaa_server(trc, 
598                                                   json_array_get(jdss, i), 
599                                                   &rc))) {
600         return rc;
601       }
602       tr_debug("tr_cfg_parse_default_servers: Default server configured: %s", ds->hostname->buf);
603       ds->next = trc->default_servers;
604       trc->default_servers = ds;
605     }
606   } 
607
608   return rc;
609 }
610
611 static TR_CFG_RC tr_cfg_parse_idp_realms (TR_CFG *trc, json_t *jcfg) 
612 {
613   json_t *jidps = NULL;
614   TR_CFG_RC rc = TR_CFG_SUCCESS;
615   TR_IDP_REALM *idp = NULL;
616   int i = 0;
617
618   if ((!trc) || (!jcfg))
619     return TR_CFG_BAD_PARAMS;
620
621   /* If there are any IDP Realms, parse them */
622   if ((NULL != (jidps = json_object_get(jcfg, "idp_realms"))) &&
623       (json_is_array(jidps))) {
624     for (i = 0; i < json_array_size(jidps); i++) {
625       if (NULL == (idp = tr_cfg_parse_one_idp_realm(trc,
626                                                     json_array_get(jidps, i), 
627                                                     &rc))) {
628         return rc;
629       }
630       tr_debug("tr_cfg_parse_idp_realms: IDP realm configured: %s.", idp->realm_id->buf);
631       idp->next = trc->idp_realms;
632       trc->idp_realms = idp;
633     }
634   }
635
636   return rc;
637 }
638
639 static TR_IDP_REALM *tr_cfg_parse_comm_idps (TR_CFG *trc, json_t *jidps, TR_CFG_RC *rc)
640 {
641   TR_IDP_REALM *idp = NULL;
642   TR_IDP_REALM *temp_idp = NULL;
643   int i = 0;
644
645   if ((!trc) ||
646       (!jidps) ||
647       (!json_is_array(jidps))) {
648     if (rc)
649       *rc = TR_CFG_BAD_PARAMS;
650     return NULL;
651   }
652
653   for (i = 0; i < json_array_size(jidps); i++) {
654     if (NULL == (temp_idp = (tr_cfg_find_idp(trc, 
655                                              tr_new_name((char *)json_string_value(json_array_get(jidps, i))), 
656                                              rc)))) {
657       tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.", 
658               (char *)json_string_value(json_array_get(jidps, i)));
659       return NULL;
660     }
661
662     temp_idp->comm_next = idp;
663     idp = temp_idp;
664   }
665
666   return idp;
667 }
668
669 static TR_RP_REALM *tr_cfg_parse_comm_rps (TR_CFG *trc, json_t *jrps, TR_CFG_RC *rc)
670 {
671   TR_RP_REALM *rp = NULL;
672   TR_RP_REALM *temp_rp = NULL;
673   int i = 0;
674
675   if ((!trc) ||
676       (!jrps) ||
677       (!json_is_array(jrps))) {
678     if (rc)
679       *rc = TR_CFG_BAD_PARAMS;
680     return NULL;
681   }
682
683   for (i = (json_array_size(jrps)-1); i >= 0; i--) {
684     if (NULL == (temp_rp = talloc_zero(trc, TR_RP_REALM))) {
685       tr_debug("tr_cfg_parse_comm_rps: Can't allocate memory for RP Realm.");
686       if (rc)
687         *rc = TR_CFG_NOMEM;
688       return NULL;
689     }
690
691     if (NULL == (temp_rp->realm_name = tr_new_name((char *)json_string_value(json_array_get(jrps, i))))) {
692       tr_debug("tr_cfg_parse_comm_rps: No memory for RP Realm Name.");
693       if (rc)
694         *rc = TR_CFG_NOMEM;
695       return NULL;
696     }
697
698     temp_rp->next = rp;
699     rp = temp_rp;
700   }
701
702   return rp;
703 }
704
705 static TR_COMM *tr_cfg_parse_one_comm (TR_CFG *trc, json_t *jcomm, TR_CFG_RC *rc) {
706   TR_COMM *comm = NULL;
707   json_t *jid = NULL;
708   json_t *jtype = NULL;
709   json_t *japcs = NULL;
710   json_t *jidps = NULL;
711   json_t *jrps = NULL;
712
713   if ((!trc) || (!jcomm) || (!rc)) {
714     tr_debug("tr_cfg_parse_one_comm: Bad parameters.");
715     if (rc)
716       *rc = TR_CFG_BAD_PARAMS;
717     return NULL;
718   }
719
720   if (NULL == (comm = talloc_zero(trc, TR_COMM))) {
721     tr_crit("tr_cfg_parse_one_comm: Out of memory.");
722     *rc = TR_CFG_NOMEM;
723     return NULL;
724   }
725
726
727   if ((NULL == (jid = json_object_get(jcomm, "community_id"))) ||
728       (!json_is_string(jid)) ||
729       (NULL == (jtype = json_object_get(jcomm, "type"))) ||
730       (!json_is_string(jtype)) ||
731       (NULL == (japcs = json_object_get(jcomm, "apcs"))) ||
732       (!json_is_array(japcs)) ||
733       (NULL == (jidps = json_object_get(jcomm, "idp_realms"))) ||
734       (!json_is_array(jidps)) ||
735       (NULL == (jrps = json_object_get(jcomm, "rp_realms"))) ||
736       (!json_is_array(jrps))) {
737     tr_debug("tr_cfg_parse_one_comm: Error parsing Communities configuration.");
738     *rc = TR_CFG_NOPARSE;
739     return NULL;
740   }
741
742   if (NULL == (comm->id = tr_new_name((char *)json_string_value(jid)))) {
743     tr_debug("tr_cfg_parse_one_comm: No memory for community id.");
744     *rc = TR_CFG_NOMEM;
745     return NULL;
746   }
747
748   if (0 == strcmp(json_string_value(jtype), "apc")) {
749     comm->type = TR_COMM_APC;
750   } else if (0 == strcmp(json_string_value(jtype), "coi")) {
751     comm->type = TR_COMM_COI;
752     if (NULL == (comm->apcs = tr_cfg_parse_apcs(trc, japcs, rc))) {
753       tr_debug("tr_cfg_parse_one_comm: Can't parse APCs for COI %s.", comm->id->buf);
754       tr_free_name(comm->id);
755       return NULL;
756     }
757   } else {
758     tr_debug("tr_cfg_parse_one_comm: Invalid community type, comm = %s, type = %s", comm->id->buf, json_string_value(jtype));
759     tr_free_name(comm->id);
760     *rc = TR_CFG_NOPARSE;
761     return NULL;
762   }
763
764   comm->idp_realms = tr_cfg_parse_comm_idps(trc, jidps, rc);
765   if (TR_CFG_SUCCESS != *rc) {
766     tr_debug("tr_cfg_parse_one_comm: Can't parse IDP realms for comm %s.", comm->id->buf);
767     tr_free_name(comm->id);
768     return NULL;
769   }
770
771   comm->rp_realms = tr_cfg_parse_comm_rps(trc, jrps, rc);
772   if (TR_CFG_SUCCESS != *rc) {
773     tr_debug("tr_cfg_parse_comm: Can't parse RP realms for comm %s .", comm->id->buf);
774     tr_free_name(comm->id);
775     return NULL;
776   }
777
778   if (TR_COMM_APC == comm->type) {
779     json_t *jexpire  = json_object_get(jcomm, "expiration_interval");
780     comm->expiration_interval = 43200; /*30 days*/
781     if (jexpire) {
782         if (!json_is_integer(jexpire)) {
783           fprintf(stderr, "tr_parse_comm: expirae_interval is not an integer\n");
784           return NULL;
785         }
786         comm->expiration_interval = json_integer_value(jexpire);
787         if (comm->expiration_interval <= 10)
788           comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
789         if (comm->expiration_interval > 129600) /* 90 days*/
790         comm->expiration_interval = 129600;
791     }
792   }
793   
794   return comm;
795 }
796
797 static TR_CFG_RC tr_cfg_parse_comms (TR_CFG *trc, json_t *jcfg) 
798 {
799   json_t *jcomms = NULL;
800   TR_CFG_RC rc = TR_CFG_SUCCESS;
801   TR_COMM *comm = NULL;
802   int i = 0;
803
804   if ((!trc) || (!jcfg)) {
805     tr_debug("tr_cfg_parse_comms: Bad Parameters.");
806     return TR_CFG_BAD_PARAMS;
807   }
808
809   if (NULL != (jcomms = json_object_get(jcfg, "communities"))) {
810     if (!json_is_array(jcomms)) {
811       return TR_CFG_NOPARSE;
812     }
813
814     for (i = 0; i < json_array_size(jcomms); i++) {
815       if (NULL == (comm = tr_cfg_parse_one_comm(trc, 
816                                                 json_array_get(jcomms, i), 
817                                                 &rc))) {
818         return rc;
819       }
820       tr_debug("tr_cfg_parse_comms: Community configured: %s.", comm->id->buf);
821       comm->next = trc->comms;
822       trc->comms = comm;
823     }
824   }
825   return rc;
826 }
827
828 TR_CFG_RC tr_cfg_validate (TR_CFG *trc) {
829   TR_CFG_RC rc = TR_CFG_SUCCESS;
830
831   if (!trc)
832     return TR_CFG_BAD_PARAMS;
833
834   if ((NULL == trc->internal)||
835       (NULL == trc->internal->hostname)) {
836     tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
837     rc = TR_CFG_ERROR;
838   }
839
840   if (NULL == trc->rp_clients) {
841     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
842     rc = TR_CFG_ERROR;
843   }
844
845   if (NULL == trc->comms) {
846     tr_debug("tr_cfg_validate: Error: No Communities configured");
847     rc = TR_CFG_ERROR;
848   }
849
850   if ((NULL == trc->default_servers) && (NULL == trc->idp_realms)) {
851     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
852     rc = TR_CFG_ERROR;
853   }
854   
855   return rc;
856 }
857
858 /* Join two paths and return a pointer to the result. This should be freed
859  * via talloc_free. Returns NULL on failure. */
860 static char *join_paths(const char *p1, const char *p2) {
861   return talloc_asprintf(NULL, "%s/%s", p1, p2); /* returns NULL on a failure */
862 }
863
864 /* Reads configuration files in config_dir ("" or "./" will use the current directory). */
865 TR_CFG_RC tr_parse_config (TR_CFG *new_cfg, const char *config_dir, int n, struct dirent **cfg_files) {
866   json_t *jcfg;
867   json_error_t rc;
868   char *file_with_path;
869
870   if ((!new_cfg) || (!cfg_files) || (n<=0))
871     return TR_CFG_BAD_PARAMS;
872
873   /* Parse configuration information from each config file */
874   while (n--) {
875     file_with_path=join_paths(config_dir, cfg_files[n]->d_name); /* must free result with talloc_free */
876     if(file_with_path == NULL) {
877       tr_crit("tr_parse_config: error joining path.");
878       return TR_CFG_NOMEM;
879     }
880     tr_debug("tr_parse_config: Parsing %s.", cfg_files[n]->d_name); /* print the filename without the path */
881     if (NULL == (jcfg = json_load_file(file_with_path, 
882                                        JSON_DISABLE_EOF_CHECK, &rc))) {
883       tr_debug("tr_parse_config: Error parsing config file %s.", 
884                cfg_files[n]->d_name);
885       talloc_free(file_with_path);
886       return TR_CFG_NOPARSE;
887     }
888     talloc_free(file_with_path); /* done with filename */
889
890     if ((TR_CFG_SUCCESS != tr_cfg_parse_internal(new_cfg, jcfg)) ||
891         (TR_CFG_SUCCESS != tr_cfg_parse_rp_clients(new_cfg, jcfg)) ||
892         (TR_CFG_SUCCESS != tr_cfg_parse_idp_realms(new_cfg, jcfg)) ||
893         (TR_CFG_SUCCESS != tr_cfg_parse_default_servers(new_cfg, jcfg)) ||
894         (TR_CFG_SUCCESS != tr_cfg_parse_comms(new_cfg, jcfg))) {
895       return TR_CFG_ERROR;
896     }
897   }
898
899   /* make sure we got a complete, consistent configuration */
900   if (TR_CFG_SUCCESS != tr_cfg_validate(new_cfg)) {
901     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
902     return TR_CFG_ERROR;
903   }
904
905   return TR_CFG_SUCCESS;
906 }
907
908 TR_IDP_REALM *tr_cfg_find_idp (TR_CFG *tr_cfg, TR_NAME *idp_id, TR_CFG_RC *rc)
909 {
910
911   TR_IDP_REALM *cfg_idp;
912
913   if ((!tr_cfg) || (!idp_id)) {
914     if (rc)
915       *rc = TR_CFG_BAD_PARAMS;
916     return NULL;
917   }
918
919   for (cfg_idp = tr_cfg->idp_realms; NULL != cfg_idp; cfg_idp = cfg_idp->next) {
920     if (!tr_name_cmp (idp_id, cfg_idp->realm_id)) {
921       tr_debug("tr_cfg_find_idp: Found %s.", idp_id->buf);
922       return cfg_idp;
923     }
924   }
925   /* if we didn't find one, return NULL */ 
926   return NULL;
927 }
928
929 TR_RP_CLIENT *tr_cfg_find_rp (TR_CFG *tr_cfg, TR_NAME *rp_gss, TR_CFG_RC *rc)
930 {
931   TR_RP_CLIENT *cfg_rp;
932   int i;
933
934   if ((!tr_cfg) || (!rp_gss)) {
935     if (rc)
936       *rc = TR_CFG_BAD_PARAMS;
937     return NULL;
938   }
939
940   for (cfg_rp = tr_cfg->rp_clients; NULL != cfg_rp; cfg_rp = cfg_rp->next) {
941     for (i = 0; i < TR_MAX_GSS_NAMES; i++) {
942       if (!tr_name_cmp (rp_gss, cfg_rp->gss_names[i])) {
943         tr_debug("tr_cfg_find_rp: Found %s.", rp_gss->buf);
944         return cfg_rp;
945       }
946     }
947   }
948   /* if we didn't find one, return NULL */ 
949   return NULL;
950 }
951
952 static int is_cfg_file(const struct dirent *dent) {
953   int n;
954
955   /* Only accept filenames ending in ".cfg" and starting with a character
956    * other than an ASCII '.' */
957
958   /* filename must be at least 4 characters long to be acceptable */
959   n=strlen(dent->d_name);
960   if (n < 4) {
961     return 0;
962   }
963
964   /* filename must not start with '.' */
965   if ('.' == dent->d_name[0]) {
966     return 0;
967   }
968
969   /* If the above passed and the last four characters of the filename are .cfg, accept.
970    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
971   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
972     return 1;
973   }
974
975   /* otherwise, return false. */
976   return 0;
977 }
978
979 /* Find configuration files in a particular directory. Returns the
980  * number of entries found, 0 if none are found, or <0 for some
981  * errors. If n>=0, the cfg_files parameter will contain a newly
982  * allocated array of pointers to struct dirent entries, as returned
983  * by scandir(). These can be freed with tr_free_config_file_list().
984  */
985 int tr_find_config_files (const char *config_dir, struct dirent ***cfg_files) {
986   int n = 0, i = 0;
987   
988   n = scandir(config_dir, cfg_files, &is_cfg_file, 0);
989
990   if (n < 0) {
991     perror("scandir");
992     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
993   } else if (n == 0) {
994     tr_debug("tr_find_config: No config files found.");
995   } else {
996     i = n;
997     while(i--) {
998       tr_debug("tr_find_config: Config file found (%s).", (*cfg_files)[i]->d_name);
999     }
1000   }
1001
1002   return n;
1003 }
1004
1005 /* Free memory allocated for configuration file list returned from tr_find_config_files().
1006  * This can be called regardless of the return value of tr_find_config_values(). */
1007 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
1008   int ii;
1009
1010   /* if n < 0, then scandir did not allocate anything because it failed */
1011   if((n>=0) && (*cfg_files != NULL)) {
1012     for(ii=0; ii<n; ii++) {
1013       free((*cfg_files)[ii]);
1014     }
1015     free(*cfg_files); /* safe even if n==0 */
1016     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
1017   }
1018 }