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