Add copyright statement missing from recently added files.
[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 /* must specify the ctx and tr in cfgwatch! */
190 int tr_read_and_apply_config(TR_CFGWATCH *cfgwatch)
191 {
192   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
193   char *config_dir=cfgwatch->config_dir;
194   int n_files = 0;
195   struct dirent **cfg_files=NULL;
196   TR_CFG_RC rc = TR_CFG_SUCCESS;        /* presume success */
197   struct tr_fstat *new_fstat_list=NULL;
198   int retval=0;
199
200   /* find the configuration files -- n.b., tr_find_config_files()
201    * allocates memory to cfg_files which we must later free */
202   tr_debug("Reading configuration files from %s/", config_dir);
203   n_files = tr_find_config_files(config_dir, &cfg_files);
204   if (n_files <= 0) {
205     tr_debug("tr_read_and_apply_config: No configuration files.");
206     retval=1; goto cleanup;
207   }
208
209   /* Get the list of update times.
210    * Do this before loading in case they change between obtaining their timestamp
211    * and reading the file---this way they will immediately reload if this happens. */
212   new_fstat_list=tr_fstat_get_all(tmp_ctx, config_dir, cfg_files, n_files);
213   if (new_fstat_list==NULL) {
214     tr_debug("tr_read_and_apply_config: Could not allocate config file status list.");
215     retval=1; goto cleanup;
216   }
217   
218   /* now fill it in (tr_parse_config allocates space for new config) */
219   if (TR_CFG_SUCCESS != (rc = tr_parse_config(cfgwatch->cfg_mgr, config_dir, n_files, cfg_files))) {
220     tr_debug("tr_read_and_apply_config: Error parsing configuration information, rc=%d.", rc);
221     retval=1; goto cleanup;
222   }
223
224   /* apply new configuration (nulls new, manages context ownership) */
225   if (TR_CFG_SUCCESS != (rc = tr_apply_new_config(cfgwatch->cfg_mgr))) {
226     tr_debug("tr_read_and_apply_config: Error applying configuration, rc = %d.", rc);
227     retval=1; goto cleanup;
228   }
229
230   /* call callback to notify system of new configuration */
231   tr_debug("tr_read_and_apply_config: calling update callback function.");
232   if (cfgwatch->update_cb!=NULL)
233     cfgwatch->update_cb(cfgwatch->cfg_mgr->active, cfgwatch->update_cookie);
234
235   /* give ownership of the new_fstat_list to caller's context */
236   if (cfgwatch->fstat_list != NULL) {
237     /* free the old one */
238     talloc_free(cfgwatch->fstat_list);
239   }
240   cfgwatch->n_files=n_files;
241   cfgwatch->fstat_list=new_fstat_list;
242   talloc_steal(cfgwatch, new_fstat_list);
243   new_fstat_list=NULL;
244
245  cleanup:
246   tr_free_config_file_list(n_files, &cfg_files);
247   talloc_free(tmp_ctx);
248   cfgwatch->cfg_mgr->new=NULL; /* this has been freed, either explicitly or with tmp_ctx */
249   return retval;
250 }
251
252
253 static void tr_cfgwatch_event_cb(int listener, short event, void *arg)
254 {
255   TR_CFGWATCH *cfg_status=(TR_CFGWATCH *) arg;
256   struct timeval now, diff;;
257
258   if (tr_cfgwatch_update_needed(cfg_status)) {
259     tr_notice("Configuration file change detected, waiting for changes to settle.");
260     cfg_status->change_detected=1;
261
262     if (0 != gettimeofday(&cfg_status->last_change_detected, NULL)) {
263       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (1).");
264     }
265   }
266
267   if (cfg_status->change_detected) {
268     if (0 != gettimeofday(&now, NULL)) {
269       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (2).");
270     }
271     timersub(&now, &cfg_status->last_change_detected, &diff);
272     if (!timercmp(&diff, &cfg_status->settling_time, <)) {
273       tr_notice("Configuration file change settled, attempting to update configuration.");
274       if (0 != tr_read_and_apply_config(cfg_status))
275         tr_warning("Configuration file update failed. Using previous configuration.");
276       else
277         tr_notice("Configuration updated successfully.");
278       cfg_status->change_detected=0;
279     }
280   }
281 }
282
283
284 /* Configure the cfgwatch instance and set up its event handler.
285  * Returns 0 on success, nonzero on failure. Points
286  * *cfgwatch_ev to the event struct. */
287 int tr_cfgwatch_event_init(struct event_base *base,
288                            TR_CFGWATCH *cfg_status,
289                            struct event **cfgwatch_ev)
290 {
291   if (cfgwatch_ev == NULL) {
292     tr_debug("tr_cfgwatch_event_init: Null cfgwatch_ev.");
293     return 1;
294   }
295
296   /* zero out the change detection fields */
297   cfg_status->change_detected=0;
298   cfg_status->last_change_detected.tv_sec=0;
299   cfg_status->last_change_detected.tv_usec=0;
300
301   /* create the event and enable it */
302   *cfgwatch_ev=event_new(base, -1, EV_TIMEOUT|EV_PERSIST, tr_cfgwatch_event_cb, (void *)cfg_status);
303   event_add(*cfgwatch_ev, &(cfg_status->poll_interval));
304
305   tr_info("tr_cfgwatch_event_init: Added configuration file watcher with %0d.%06d second poll interval.",
306            cfg_status->poll_interval.tv_sec,
307            cfg_status->poll_interval.tv_usec);
308   return 0;
309 }
310