Miscellaneous minor code cleanup for MRW's review comments
[trust_router.git] / common / tr_config.c
1 /*
2  * Copyright (c) 2012-2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdlib.h>
36 #include <string.h>
37 #include <jansson.h>
38 #include <dirent.h>
39 #include <talloc.h>
40
41 #include <tr_cfgwatch.h>
42 #include <tr_comm.h>
43 #include <tr_config.h>
44 #include <tr_gss_names.h>
45 #include <tr_debug.h>
46 #include <tr_filter.h>
47 #include <trust_router/tr_constraint.h>
48 #include <tr_idp.h>
49 #include <tr.h>
50 #include <trust_router/trp.h>
51
52 #if JANSSON_VERSION_HEX < 0x020500
53 #include "jansson_iterators.h"
54 #endif
55
56 void tr_print_config (TR_CFG *cfg) {
57   tr_notice("tr_print_config: Logging running trust router configuration.");
58   tr_print_comms(cfg->ctable);
59 }
60
61 void tr_print_comms (TR_COMM_TABLE *ctab)
62 {
63   TR_COMM *comm = NULL;
64
65   for (comm = ctab->comms; NULL != comm; comm = comm->next) {
66     tr_notice("tr_print_config: Community %s:", comm->id->buf);
67
68     tr_notice("tr_print_config:  - Member IdPs:");
69     tr_print_comm_idps(ctab, comm);
70
71     tr_notice("tr_print_config:  - Member RPs:");
72     tr_print_comm_rps(ctab, comm);
73   }
74 }
75
76 void tr_print_comm_idps(TR_COMM_TABLE *ctab, TR_COMM *comm)
77 {
78   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
79   TR_COMM_ITER *iter=NULL;
80   TR_IDP_REALM *idp = NULL;
81   char *s=NULL;
82
83   iter=tr_comm_iter_new(tmp_ctx);
84   if (iter==NULL) {
85     tr_notice("tr_print_config: unable to allocate IdP iterator.");
86     talloc_free(tmp_ctx);
87     return;
88   }
89   
90   for (idp=tr_idp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
91        NULL!=idp;
92        idp=tr_idp_realm_iter_next(iter)) {
93     s=tr_idp_realm_to_str(tmp_ctx, idp);
94     if (s!=NULL)
95       tr_notice("tr_print_config:    - @%s", s);
96     else
97       tr_notice("tr_print_config: unable to allocate IdP output string.");
98   }
99   talloc_free(tmp_ctx);
100 }
101
102 void tr_print_comm_rps(TR_COMM_TABLE *ctab, TR_COMM *comm)
103 {
104   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
105   TR_COMM_ITER *iter=NULL;
106   TR_RP_REALM *rp = NULL;
107   char *s=NULL;
108
109   iter=tr_comm_iter_new(tmp_ctx);
110   if (iter==NULL) {
111     tr_notice("tr_print_config: unable to allocate RP iterator.");
112     talloc_free(tmp_ctx);
113     return;
114   }
115   
116   for (rp=tr_rp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
117        NULL!=rp;
118        rp=tr_rp_realm_iter_next(iter)) {
119     s=tr_rp_realm_to_str(tmp_ctx, rp);
120     if (s!=NULL)
121       tr_notice("tr_print_config:    - @%s", s);
122     else
123       tr_notice("tr_print_config: unable to allocate RP output string.");
124   }
125   talloc_free(tmp_ctx);
126 }
127
128 static int tr_cfg_destructor(void *object)
129 {
130   TR_CFG *cfg = talloc_get_type_abort(object, TR_CFG);
131   if (cfg->files)
132     g_array_unref(cfg->files);
133   return 0;
134 }
135 TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
136 {
137   TR_CFG *cfg=talloc(mem_ctx, TR_CFG);
138   if (cfg!=NULL) {
139     cfg->internal=NULL;
140     cfg->rp_clients=NULL;
141     cfg->peers=NULL;
142     cfg->default_servers=NULL;
143     cfg->ctable=tr_comm_table_new(cfg);
144     if (cfg->ctable==NULL) {
145       talloc_free(cfg);
146       return NULL;
147     }
148     cfg->files = g_array_new(FALSE, FALSE, sizeof(TR_CFG_FILE));
149     if (cfg->files == NULL) {
150       talloc_free(cfg);
151       return NULL;
152     }
153     talloc_set_destructor((void *)cfg, tr_cfg_destructor);
154   }
155   return cfg;
156 }
157
158 void tr_cfg_free (TR_CFG *cfg)
159 {
160   talloc_free(cfg);
161 }
162
163 TR_CFG_MGR *tr_cfg_mgr_new(TALLOC_CTX *mem_ctx)
164 {
165   return talloc_zero(mem_ctx, TR_CFG_MGR);
166 }
167
168 void tr_cfg_mgr_free (TR_CFG_MGR *cfg_mgr) {
169   talloc_free(cfg_mgr);
170 }
171
172 TR_CFG_RC tr_apply_new_config (TR_CFG_MGR *cfg_mgr)
173 {
174   /* cfg_mgr->active is allowed to be null, but new cannot be */
175   if ((cfg_mgr==NULL) || (cfg_mgr->new==NULL))
176     return TR_CFG_BAD_PARAMS;
177
178   if (cfg_mgr->active != NULL)
179     tr_cfg_free(cfg_mgr->active);
180
181   cfg_mgr->active = cfg_mgr->new;
182   cfg_mgr->new=NULL; /* only keep a single handle on the new configuration */
183
184   tr_log_threshold(cfg_mgr->active->internal->log_threshold);
185   tr_console_threshold(cfg_mgr->active->internal->console_threshold);
186
187   return TR_CFG_SUCCESS;
188 }
189
190
191 TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
192 {
193   TR_CFG_RC rc = TR_CFG_SUCCESS;
194
195   if (!trc)
196     return TR_CFG_BAD_PARAMS;
197
198   if ((NULL == trc->internal)||
199       (NULL == trc->internal->hostname)) {
200     tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
201     rc = TR_CFG_ERROR;
202   }
203
204   if (NULL == trc->rp_clients) {
205     tr_debug("tr_cfg_validate: Error: No RP Clients configured");
206     rc = TR_CFG_ERROR;
207   }
208
209   if (0==tr_comm_table_size(trc->ctable)) {
210     tr_debug("tr_cfg_validate: Error: No Communities configured");
211     rc = TR_CFG_ERROR;
212   }
213
214   if ((NULL == trc->default_servers) && (NULL == trc->ctable->idp_realms)) {
215     tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
216     rc = TR_CFG_ERROR;
217   }
218   
219   return rc;
220 }
221
222 static void tr_cfg_log_json_error(const char *label, json_error_t *rc)
223 {
224   tr_debug("%s: JSON parse error on line %d: %s",
225            label,
226            rc->line,
227            rc->text);
228 }
229
230 /**
231  * Parse a config file and return its JSON structure. Also emits a serial number to the log
232  * if one is present.
233  *
234  * @param file_with_path The file (with path!) to parse
235  * @return Pointer to the result of parsing, or null on error
236  */
237 static json_t *tr_cfg_parse_one_config_file(const char *file_with_path)
238 {
239   json_t *jcfg=NULL;
240   json_error_t rc;
241
242   if (NULL==(jcfg=json_load_file(file_with_path, 
243                                  JSON_DISABLE_EOF_CHECK|JSON_REJECT_DUPLICATES, &rc))) {
244     tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.", 
245              file_with_path);
246     tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
247     return NULL;
248   }
249
250   return jcfg;
251 }
252
253 /* extract serial number */
254 static json_int_t get_cfg_serial(json_t *jcfg)
255 {
256   json_t *jser=NULL;
257
258   if (NULL != (jser = json_object_get(jcfg, "serial_number"))) {
259     if (json_is_integer(jser)) {
260       return json_integer_value(jser);
261     }
262   }
263   return TR_CFG_INVALID_SERIAL;
264 }
265
266 /**
267  * Helper to free an array returned by tr_cfg_parse_config_files
268  * @param n_jcfgs
269  * @param jcfgs
270  */
271 static void tr_cfg_parse_free_jcfgs(unsigned int n_jcfgs, json_t **jcfgs)
272 {
273   int ii=0;
274   for (ii=0; ii<n_jcfgs; ii++)
275     json_decref(jcfgs[ii]);
276   talloc_free(jcfgs);
277 }
278
279 /**
280  * Parse a list of configuration files. Returns an array of JSON objects, free this with
281  * tr_cfg_parse_free_jcfgs(), a helper function
282  *
283  * @param config_dir
284  * @param n_files
285  * @param cfg_files
286  * @return
287  */
288 static json_t **tr_cfg_parse_config_files(TALLOC_CTX *mem_ctx, unsigned int n_files, GArray *files)
289 {
290   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
291   unsigned int ii=0;
292   json_t **jcfgs=NULL;
293   TR_CFG_FILE *this_file = NULL;
294
295   /* first allocate the jcfgs */
296   jcfgs=talloc_array(NULL, json_t *, n_files);
297   if (jcfgs==NULL) {
298     tr_crit("tr_parse_config_files: cannot allocate JSON structure array");
299     goto cleanup;
300   }
301   for (ii=0; ii<n_files; ii++) {
302     this_file = &g_array_index(files, TR_CFG_FILE, ii);
303     jcfgs[ii]=tr_cfg_parse_one_config_file(this_file->name);
304     if (jcfgs[ii]==NULL) {
305       tr_err("tr_parse_config: Error parsing JSON in %s", this_file->name);
306       tr_cfg_parse_free_jcfgs(ii, jcfgs); /* frees the JSON objects and the jcfgs array */
307       jcfgs=NULL;
308       goto cleanup;
309     }
310
311     this_file->serial = get_cfg_serial(jcfgs[ii]);
312     if (this_file->serial != TR_CFG_INVALID_SERIAL) {
313       tr_notice("tr_parse_config_files: Attempting to load revision %"
314                     JSON_INTEGER_FORMAT
315                     " of '%s'.",
316                 this_file->serial,
317                 this_file->name);
318     } else {
319       tr_notice("tr_parse_config_files: Attempting to load '%s'.",
320                 this_file->name);
321     }
322   }
323
324 cleanup:
325   if (jcfgs)
326     talloc_steal(mem_ctx, jcfgs); /* give this to the caller's context if we succeeded */
327   talloc_free(tmp_ctx);
328   return jcfgs;
329 }
330
331 /* define a type for config parse functions */
332 typedef TR_CFG_RC (TR_CFG_PARSE_FN)(TR_CFG *, json_t *);
333 /**
334  * Helper function to parse a collection of JSON structures using a generic parse function.
335  *
336  * @param cfg Config structure to receive results
337  * @param parse_fn Function to apply
338  * @param n_jcfg Number of JSON structures in the array
339  * @param jcfgs Pointer to an array of decoded JSON structures
340  * @param key Key to extract from each jcfg before parsing, or NULL to use the object itself
341  * @return TR_CFG_SUCCESS on success, _FAIL or an error code on failure
342  */
343 static TR_CFG_RC tr_cfg_parse_helper(TR_CFG *cfg,
344                                      TR_CFG_PARSE_FN parse_fn,
345                                      unsigned int n_jcfg,
346                                      json_t **jcfgs,
347                                      const char *key)
348 {
349   size_t ii=0;
350   json_t *this_jcfg=NULL;
351   TR_CFG_RC ret=TR_CFG_ERROR;
352
353   if ((cfg==NULL) || (jcfgs==NULL) || (parse_fn==NULL))
354     return TR_CFG_ERROR;
355
356   for (ii=0; ii<n_jcfg; ii++) {
357     if (key)
358       this_jcfg = json_object_get(jcfgs[ii], key);
359     else
360       this_jcfg = jcfgs[ii];
361
362     /* do not try to parse a missing jcfg */
363     if (this_jcfg == NULL)
364       continue;
365
366     ret=parse_fn(cfg, this_jcfg);
367     if (ret!=TR_CFG_SUCCESS)
368       break;
369   }
370   return ret;
371 }
372
373 static void add_files(TR_CFG *cfg, unsigned int n, char **filenames)
374 {
375   TR_CFG_FILE frec = {0};
376
377   while ((n--) > 0) {
378     frec.name = talloc_strdup(cfg, filenames[n]);
379     frec.serial = TR_CFG_INVALID_SERIAL;
380
381     g_array_append_val(cfg->files, frec);
382   }
383 }
384
385 /**
386  *  Read a list of configuration files
387  *
388  * @param cfg_mgr Configuration manager
389  * @param n_files Number of entries in cfg_files
390  * @param files_with_paths Array of filenames with path to load
391  * @return TR_CFG_SUCCESS on success, TR_CFG_ERROR or a more specific error on failure
392  */
393 TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, unsigned int n_files, char **files_with_paths)
394 {
395   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
396   json_t **jcfgs=NULL;
397   TR_CFG_RC cfg_rc=TR_CFG_ERROR;
398
399   if ((!cfg_mgr) || (!files_with_paths)) {
400     cfg_rc=TR_CFG_BAD_PARAMS;
401     goto cleanup;
402   }
403
404   /* get a fresh config to fill in, freeing old one if needed */
405   if (cfg_mgr->new != NULL)
406     tr_cfg_free(cfg_mgr->new);
407   cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
408   if (cfg_mgr->new == NULL) {
409     cfg_rc=TR_CFG_NOMEM;
410     goto cleanup;
411   }
412
413   /* add the list of files to the config */
414   add_files(cfg_mgr->new, n_files, files_with_paths);
415
416   /* first parse the json */
417   jcfgs=tr_cfg_parse_config_files(tmp_ctx, n_files, cfg_mgr->new->files);
418   if (jcfgs==NULL) {
419     cfg_rc=TR_CFG_NOPARSE;
420     goto cleanup;
421   }
422
423   cfg_mgr->new->peers=trp_ptable_new(cfg_mgr); /* not sure why this isn't in cfg_mgr->new's context */
424
425   /* now run through the parsers on the JSON */
426   if ((TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_internal, n_files, jcfgs, "tr_internal"))) ||
427       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_local_orgs, n_files, jcfgs, NULL))) ||
428       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_peer_orgs, n_files, jcfgs, NULL))) ||
429       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_default_servers, n_files, jcfgs,
430                                                       NULL))) ||
431       (TR_CFG_SUCCESS != (cfg_rc= tr_cfg_parse_helper(cfg_mgr->new, tr_cfg_parse_comms, n_files, jcfgs, NULL))))
432     goto cleanup; /* cfg_rc was set above */
433
434   /* make sure we got a complete, consistent configuration */
435   if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
436     tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
437     cfg_rc=TR_CFG_ERROR;
438     goto cleanup;
439   }
440
441   /* success! */
442   talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
443   cfg_rc=TR_CFG_SUCCESS;
444
445 cleanup:
446   if (jcfgs!=NULL)
447     tr_cfg_parse_free_jcfgs(n_files, jcfgs);
448   talloc_free(tmp_ctx);
449   return cfg_rc;
450 }
451
452 static int is_cfg_file(const struct dirent *dent) {
453   size_t n;
454
455   /* Only accept filenames ending in ".cfg" and starting with a character
456    * other than an ASCII '.' */
457
458   /* filename must be at least 4 characters long to be acceptable */
459   n=strlen(dent->d_name);
460   if (n < 4) {
461     return 0;
462   }
463
464   /* filename must not start with '.' */
465   if ('.' == dent->d_name[0]) {
466     return 0;
467   }
468
469   /* If the above passed and the last four characters of the filename are .cfg, accept.
470    * (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
471   if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
472     return 1;
473   }
474
475   /* otherwise, return false. */
476   return 0;
477 }
478
479 /* Find configuration files in a particular directory. Returns the
480  * number of entries found, 0 if none are found, or <0 for some
481  * errors. If n>=0, the cfg_files parameter will contain a newly
482  * allocated array of pointers to struct dirent entries, as returned
483  * by scandir(). These can be freed with tr_free_config_file_list().
484  */
485 int tr_find_config_files(const char *config_dir, struct dirent ***cfg_files) {
486   int n = 0;
487   
488   n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
489
490   if (n < 0) {
491     perror("scandir");
492     tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
493   } 
494
495   return n;
496 }
497
498 /* Free memory allocated for configuration file list returned from tr_find_config_files().
499  * This can be called regardless of the return value of tr_find_config_values(). */
500 void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
501   int ii;
502
503   /* if n < 0, then scandir did not allocate anything because it failed */
504   if((n>=0) && (*cfg_files != NULL)) {
505     for(ii=0; ii<n; ii++) {
506       free((*cfg_files)[ii]);
507     }
508     free(*cfg_files); /* safe even if n==0 */
509     *cfg_files=NULL; /* this will help prevent accidentally freeing twice */
510   }
511 }