Use json_is_true() in place of json_boolean_value() for compatibility
[trust_router.git] / tr / tr_cfgwatch.c
1 /*
2  * Copyright (c) 2016, 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 <sys/stat.h>
36 #include <talloc.h>
37
38 #include <tr_config.h>
39 #include <tr_debug.h>
40 #include <tr_event.h>
41 #include <tr_cfgwatch.h>
42
43 /* Initialize a new tr_cfgwatch_data struct. Free this with talloc. */
44 TR_CFGWATCH *tr_cfgwatch_create(TALLOC_CTX *mem_ctx)
45 {
46   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
47   TR_CFGWATCH *new_cfg;
48   
49   new_cfg=talloc_zero(tmp_ctx, TR_CFGWATCH);
50   if (new_cfg == NULL) {
51     tr_debug("tr_cfgwatch_create: Allocation failed.");
52   } 
53   talloc_steal(mem_ctx, new_cfg);
54   talloc_free(tmp_ctx);
55   return new_cfg;
56 }
57
58 /* Obtain the file modification time as seconds since epoch. Returns 0 on success. */
59 static int tr_get_mtime(const char *path, struct timespec *ts)
60 {
61   struct stat file_status;
62
63   if (stat(path, &file_status) != 0) {
64     return -1;
65   } else {
66     (*ts)=file_status.st_mtim;
67   }
68   return 0;
69 }
70
71 static char *tr_join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
72 {
73   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
74 }
75
76 static int tr_fstat_namecmp(const void *p1_arg, const void *p2_arg)
77 {
78   struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
79   struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
80
81   return strcmp(p1->name, p2->name);
82 }
83
84 static int tr_fstat_mtimecmp(const void *p1_arg, const void *p2_arg)
85 {
86   struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
87   struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
88
89   if (p1->mtime.tv_sec == p2->mtime.tv_sec)
90     return (p1->mtime.tv_nsec) - (p2->mtime.tv_nsec);
91   else
92     return (p1->mtime.tv_sec) - (p2->mtime.tv_sec);
93 }
94
95 /* Get status of all files in cfg_files. Returns list, or NULL on error.
96  * Files are sorted by filename. 
97  * After success, caller must eventually free result with talloc_free. */
98 static struct tr_fstat *tr_fstat_get_all(TALLOC_CTX *mem_ctx,
99                                          const char *config_path,
100                                          struct dirent **cfg_files,
101                                          int n_files)
102 {
103   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
104   struct tr_fstat *fstat_list=NULL;
105   int ii=0;
106
107   /* create a new fstat list (may be discarded) */
108   fstat_list=talloc_array(tmp_ctx, struct tr_fstat, n_files);
109   if (fstat_list==NULL) {
110     tr_err("tr_fstat_get_all: Could not allocate fstat list.");
111     goto cleanup;
112   }
113
114   for (ii=0; ii<n_files; ii++) {
115     fstat_list[ii].name=talloc_strdup(fstat_list, cfg_files[ii]->d_name);
116     if (0 != tr_get_mtime(tr_join_paths(tmp_ctx, config_path, fstat_list[ii].name),
117                          &(fstat_list[ii].mtime))) {
118       tr_warning("tr_fstat_get_all: Could not obtain mtime for file %s", fstat_list[ii].name);
119     }
120   }
121
122   /* sort the list */
123   qsort(fstat_list, n_files, sizeof(struct tr_fstat), tr_fstat_namecmp);
124
125   /* put list in the caller's context and return it */
126   talloc_steal(mem_ctx, fstat_list);
127  cleanup:
128   talloc_free(tmp_ctx);
129   return fstat_list;
130 }
131
132 /* Checks whether any config files have appeared/disappeared/modified.
133  * Returns 1 if so, 0 otherwise. */
134 static int tr_cfgwatch_update_needed(TR_CFGWATCH *cfg_status)
135 {
136   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
137   struct tr_fstat *fstat_list=NULL;
138   int n_files=0;
139   int ii=0;
140   struct dirent **cfg_files=NULL;
141   int update_needed=0; /* return value */
142
143   /* get the list, must free cfg_files later with tr_free_cfg_file_list */
144   n_files = tr_find_config_files(cfg_status->config_dir, &cfg_files);
145   if (n_files <= 0) {
146     tr_warning("tr_cfgwatch_update: configuration files disappeared, skipping update.");
147     goto cleanup;
148   }
149
150   /* create a new fstat list (will be discarded) */
151   fstat_list=tr_fstat_get_all(tmp_ctx, cfg_status->config_dir, cfg_files, n_files);
152   if (fstat_list==NULL) {
153     tr_err("tr_cfgwatch_update: Error getting fstat list.");
154     goto cleanup;
155   }
156
157   /* see if the number of files change, if so need to update */
158   if (n_files != cfg_status->n_files) {
159     tr_debug("tr_cfgwatch_update: Changed number of config files (was %d, now %d).",
160              cfg_status->n_files,
161              n_files);
162     update_needed=1;
163     talloc_free(cfg_status->fstat_list);
164     cfg_status->n_files=n_files;
165     cfg_status->fstat_list=fstat_list;
166     talloc_steal(cfg_status, fstat_list);
167     goto cleanup;
168   }
169
170   /* See if any files have a changed mtime. Both are sorted by name so this is easy. */
171   for (ii=0; ii<n_files; ii++) {
172     if ((0 != tr_fstat_mtimecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))
173        || (0 != tr_fstat_namecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))){
174       update_needed=1;
175       talloc_free(cfg_status->fstat_list);
176       cfg_status->n_files=n_files;
177       cfg_status->fstat_list=fstat_list;
178       talloc_steal(cfg_status, fstat_list);
179       goto cleanup;
180     }
181   }
182
183  cleanup:
184   tr_free_config_file_list(n_files, &cfg_files);
185   talloc_free(tmp_ctx);
186   return update_needed;
187 }
188
189 /* Join two paths and return a pointer to the result. This should be freed
190  * via talloc_free. Returns NULL on failure. */
191 static char *join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
192 {
193   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
194 }
195
196 /**
197  * Join a directory name with the filenames from an array of struct dirent.
198  * Outputs an array of pointers to strings that must be freed via talloc_free on
199  * the array. The strings in the array are in the context of the array, so will
200  * be freed automatically.
201  *
202  * @param ctx talloc context to contain the result on success
203  * @param dir
204  * @param n_files
205  * @param files
206  * @return Null on failure, or an array of pointers to strings
207  */
208 static char **dirent_to_full_path(TALLOC_CTX *mem_ctx, const char *dir, unsigned int n_files, struct dirent **files)
209 {
210   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
211   unsigned int ii=0;
212   char **files_with_paths=talloc_array(tmp_ctx, char *, n_files);
213
214   if (files_with_paths==NULL) {
215     tr_crit("dirent_to_full_path: unable to allocate filename array");
216     goto cleanup;
217   }
218
219   for (ii=0; ii<n_files; ii++) {
220     files_with_paths[ii]=join_paths(files_with_paths, dir, files[ii]->d_name);
221     if(files_with_paths[ii] == NULL) {
222       tr_crit("dirent_to_full_path: error joining path for %s.", files[ii]->d_name);
223       files_with_paths=NULL; /* will be freed automatically by talloc_free */
224       goto cleanup;
225     }
226   }
227
228 cleanup:
229   if (files_with_paths!=NULL)
230     talloc_steal(mem_ctx, files_with_paths);
231   talloc_free(tmp_ctx);
232   return files_with_paths;
233 }
234
235
236 /* must specify the ctx and tr in cfgwatch! */
237 int tr_read_and_apply_config(TR_CFGWATCH *cfgwatch)
238 {
239   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
240   char *config_dir=cfgwatch->config_dir;
241   unsigned int n_files = 0;
242   struct dirent **cfg_files=NULL;
243   TR_CFG_RC rc = TR_CFG_SUCCESS;        /* presume success */
244   struct tr_fstat *new_fstat_list=NULL;
245   char **files_with_paths=NULL;
246   int retval=0;
247
248   /* find the configuration files -- n.b., tr_find_config_files()
249    * allocates memory to cfg_files which we must later free */
250   tr_debug("Reading configuration files from %s/", config_dir);
251   n_files = tr_find_config_files(config_dir, &cfg_files);
252   if (n_files <= 0) {
253     tr_debug("tr_read_and_apply_config: No configuration files.");
254     retval=1; goto cleanup;
255   }
256   /* n_files > 0 from here on */
257
258   /* Get the list of update times.
259    * Do this before loading in case they change between obtaining their timestamp
260    * and reading the file---this way they will immediately reload if this happens. */
261   new_fstat_list=tr_fstat_get_all(tmp_ctx, config_dir, cfg_files, (unsigned int)n_files);
262   if (new_fstat_list==NULL) {
263     tr_debug("tr_read_and_apply_config: Could not allocate config file status list.");
264     retval=1; goto cleanup;
265   }
266
267   /* get the filenames with their paths */
268   files_with_paths=dirent_to_full_path(tmp_ctx, config_dir, n_files, cfg_files);
269   if (files_with_paths==NULL) {
270     tr_err("tr_read_and_apply_config: Could not append path to filenames.");
271     retval=1; goto cleanup;
272   }
273
274   /* now fill it in (tr_parse_config allocates space for new config) */
275   if (TR_CFG_SUCCESS != (rc = tr_parse_config(cfgwatch->cfg_mgr, n_files, files_with_paths))) {
276     tr_debug("tr_read_and_apply_config: Error parsing configuration information, rc=%d.", rc);
277     retval=1; goto cleanup;
278   }
279
280   /* apply new configuration (nulls new, manages context ownership) */
281   if (TR_CFG_SUCCESS != (rc = tr_apply_new_config(cfgwatch->cfg_mgr))) {
282     tr_debug("tr_read_and_apply_config: Error applying configuration, rc = %d.", rc);
283     retval=1; goto cleanup;
284   }
285
286   /* call callback to notify system of new configuration */
287   tr_debug("tr_read_and_apply_config: calling update callback function.");
288   if (cfgwatch->update_cb!=NULL)
289     cfgwatch->update_cb(cfgwatch->cfg_mgr->active, cfgwatch->update_cookie);
290
291   /* give ownership of the new_fstat_list to caller's context */
292   if (cfgwatch->fstat_list != NULL) {
293     /* free the old one */
294     talloc_free(cfgwatch->fstat_list);
295   }
296   cfgwatch->n_files=n_files;
297   cfgwatch->fstat_list=new_fstat_list;
298   talloc_steal(cfgwatch, new_fstat_list);
299   new_fstat_list=NULL;
300
301  cleanup:
302   tr_free_config_file_list(n_files, &cfg_files);
303   talloc_free(tmp_ctx);
304   cfgwatch->cfg_mgr->new=NULL; /* this has been freed, either explicitly or with tmp_ctx */
305   return retval;
306 }
307
308
309 static void tr_cfgwatch_event_cb(int listener, short event, void *arg)
310 {
311   TR_CFGWATCH *cfg_status=(TR_CFGWATCH *) arg;
312   struct timeval now, diff;;
313
314   if (tr_cfgwatch_update_needed(cfg_status)) {
315     tr_notice("Configuration file change detected, waiting for changes to settle.");
316     cfg_status->change_detected=1;
317
318     if (0 != gettimeofday(&cfg_status->last_change_detected, NULL)) {
319       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (1).");
320     }
321   }
322
323   if (cfg_status->change_detected) {
324     if (0 != gettimeofday(&now, NULL)) {
325       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (2).");
326     }
327     timersub(&now, &cfg_status->last_change_detected, &diff);
328     if (!timercmp(&diff, &cfg_status->settling_time, <)) {
329       tr_notice("Configuration file change settled, attempting to update configuration.");
330       if (0 != tr_read_and_apply_config(cfg_status))
331         tr_warning("Configuration file update failed. Using previous configuration.");
332       else
333         tr_notice("Configuration updated successfully.");
334       cfg_status->change_detected=0;
335     }
336   }
337 }
338
339
340 /* Configure the cfgwatch instance and set up its event handler.
341  * Returns 0 on success, nonzero on failure. Points
342  * *cfgwatch_ev to the event struct. */
343 int tr_cfgwatch_event_init(struct event_base *base,
344                            TR_CFGWATCH *cfg_status,
345                            struct event **cfgwatch_ev)
346 {
347   if (cfgwatch_ev == NULL) {
348     tr_debug("tr_cfgwatch_event_init: Null cfgwatch_ev.");
349     return 1;
350   }
351
352   /* zero out the change detection fields */
353   cfg_status->change_detected=0;
354   cfg_status->last_change_detected.tv_sec=0;
355   cfg_status->last_change_detected.tv_usec=0;
356
357   /* create the event and enable it */
358   *cfgwatch_ev=event_new(base, -1, EV_TIMEOUT|EV_PERSIST, tr_cfgwatch_event_cb, (void *)cfg_status);
359   event_add(*cfgwatch_ev, &(cfg_status->poll_interval));
360
361   tr_info("tr_cfgwatch_event_init: Added configuration file watcher with %0d.%06d second poll interval.",
362            cfg_status->poll_interval.tv_sec,
363            cfg_status->poll_interval.tv_usec);
364   return 0;
365 }
366