Reload configuration dynamically when files change.
[trust_router.git] / tr / tr_main.c
1 /*
2  * Copyright (c) 2012, 2015, 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 <stdio.h>
36 #include <stdlib.h>
37 #include <jansson.h>
38 #include <argp.h>
39 #include <event2/event.h>
40 #include <talloc.h>
41 #include <sys/stat.h>
42 #include <sys/time.h>
43
44 #include <tr.h>
45 #include <tr_filter.h>
46 #include <tid_internal.h>
47 #include <tr_config.h>
48 #include <tr_comm.h>
49 #include <tr_idp.h>
50 #include <tr_rp.h>
51 #include <tr_debug.h>
52
53 /* Structure to hold TR instance and original request in one cookie */
54 typedef struct tr_resp_cookie {
55   TR_INSTANCE *tr;
56   TID_REQ *orig_req;
57 } TR_RESP_COOKIE;
58
59
60 static void tr_tidc_resp_handler (TIDC_INSTANCE *tidc, 
61                         TID_REQ *req,
62                         TID_RESP *resp, 
63                         void *resp_cookie) 
64 {
65   tr_debug("tr_tidc_resp_handler: Response received (conn = %d)! Realm = %s, Community = %s.", ((TR_RESP_COOKIE *)resp_cookie)->orig_req->conn, resp->realm->buf, resp->comm->buf);
66   req->resp_rcvd = 1;
67
68   /* TBD -- handle concatentation of multiple responses to single req */
69   tids_send_response(((TR_RESP_COOKIE *)resp_cookie)->tr->tids, 
70                      ((TR_RESP_COOKIE *)resp_cookie)->orig_req, 
71                      resp);
72   
73   return;
74 }
75
76 static int tr_tids_req_handler (TIDS_INSTANCE *tids,
77                       TID_REQ *orig_req, 
78                       TID_RESP *resp,
79                       void *tr_in)
80 {
81   TIDC_INSTANCE *tidc = NULL;
82   TR_RESP_COOKIE resp_cookie;
83   TR_AAA_SERVER *aaa_servers = NULL;
84   TR_NAME *apc = NULL;
85   TID_REQ *fwd_req = NULL;
86   TR_COMM *cfg_comm = NULL;
87   TR_COMM *cfg_apc = NULL;
88   TR_INSTANCE *tr = (TR_INSTANCE *) tr_in;
89   int oaction = TR_FILTER_ACTION_REJECT;
90   int rc = 0;
91   time_t expiration_interval;
92
93   if ((!tids) || (!orig_req) || (!resp) ||  (!tr)) {
94     tr_debug("tr_tids_req_handler: Bad parameters");
95     return -1;
96   }
97
98   tr_debug("tr_tids_req_handler: Request received (conn = %d)! Realm = %s, Comm = %s", orig_req->conn, 
99          orig_req->realm->buf, orig_req->comm->buf);
100   if (tids)
101     tids->req_count++;
102
103   /* Duplicate the request, so we can modify and forward it */
104   if (NULL == (fwd_req = tid_dup_req(orig_req))) {
105     tr_debug("tr_tids_req_handler: Unable to duplicate request.");
106     return -1;
107   }
108
109   if (NULL == (cfg_comm = tr_comm_lookup(tids->cookie, orig_req->comm))) {
110     tr_notice("tr_tids_req_hander: Request for unknown comm: %s.", orig_req->comm->buf);
111     tids_send_err_response(tids, orig_req, "Unknown community");
112     return -1;
113   }
114
115   /* Check that the rp_realm matches the filter for the GSS name that 
116    * was received. */
117
118   if ((!(tr)->rp_gss) || 
119       (!(tr)->rp_gss->filter)) {
120     tr_notice("tr_tids_req_handler: No GSS name for incoming request.");
121     tids_send_err_response(tids, orig_req, "No GSS name for request");
122     return -1;
123   }
124
125   if ((TR_FILTER_NO_MATCH == tr_filter_process_rp_permitted(orig_req->rp_realm, (tr)->rp_gss->filter, orig_req->cons, &fwd_req->cons, &oaction)) ||
126       (TR_FILTER_ACTION_REJECT == oaction)) {
127     tr_notice("tr_tids_req_handler: RP realm (%s) does not match RP Realm filter for GSS name", orig_req->rp_realm->buf);
128     tids_send_err_response(tids, orig_req, "RP Realm filter error");
129     return -1;
130   }
131   /* Check that the rp_realm is a member of the community in the request */
132   if (NULL == (tr_find_comm_rp(cfg_comm, orig_req->rp_realm))) {
133     tr_notice("tr_tids_req_handler: RP Realm (%s) not member of community (%s).", orig_req->rp_realm->buf, orig_req->comm->buf);
134     tids_send_err_response(tids, orig_req, "RP COI membership error");
135     return -1;
136   }
137
138   /* Map the comm in the request from a COI to an APC, if needed */
139   if (TR_COMM_COI == cfg_comm->type) {
140     tr_debug("tr_tids_req_handler: Community was a COI, switching.");
141     /* TBD -- In theory there can be more than one?  How would that work? */
142     if ((!cfg_comm->apcs) || (!cfg_comm->apcs->id)) {
143       tr_notice("No valid APC for COI %s.", orig_req->comm->buf);
144       tids_send_err_response(tids, orig_req, "No valid APC for community");
145       return -1;
146     }
147     apc = tr_dup_name(cfg_comm->apcs->id);
148
149     /* Check that the APC is configured */
150     if (NULL == (cfg_apc = tr_comm_lookup(tids->cookie, apc))) {
151       tr_notice("tr_tids_req_hander: Request for unknown comm: %s.", apc->buf);
152       tids_send_err_response(tids, orig_req, "Unknown APC");
153       return -1;
154     }
155
156     fwd_req->comm = apc;
157     fwd_req->orig_coi = orig_req->comm;
158
159     /* Check that rp_realm is a  member of this APC */
160     if (NULL == (tr_find_comm_rp(cfg_apc, orig_req->rp_realm))) {
161       tr_notice("tr_tids_req_hander: RP Realm (%s) not member of community (%s).", orig_req->rp_realm->buf, orig_req->comm->buf);
162       tids_send_err_response(tids, orig_req, "RP APC membership error");
163       return -1;
164     }
165   }
166
167   /* Find the AAA server(s) for this request */
168   if (NULL == (aaa_servers = tr_idp_aaa_server_lookup((TR_INSTANCE *)tids->cookie, 
169                                                       orig_req->realm, 
170                                                       orig_req->comm))) {
171       tr_debug("tr_tids_req_handler: No AAA Servers for realm %s, defaulting.", orig_req->realm->buf);
172       if (NULL == (aaa_servers = tr_default_server_lookup ((TR_INSTANCE *)tids->cookie,
173                                                            orig_req->comm))) {
174         tr_notice("tr_tids_req_handler: No default AAA servers, discarded.");
175         tids_send_err_response(tids, orig_req, "No path to AAA Server(s) for realm");
176         return -1;
177       }
178   } else {
179     /* if we aren't defaulting, check idp coi and apc membership */
180     if (NULL == (tr_find_comm_idp(cfg_comm, fwd_req->realm))) {
181       tr_notice("tr_tids_req_handler: IDP Realm (%s) not member of community (%s).", orig_req->realm->buf, orig_req->comm->buf);
182       tids_send_err_response(tids, orig_req, "IDP community membership error");
183       return -1;
184     }
185     if ( cfg_apc && (NULL == (tr_find_comm_idp(cfg_apc, fwd_req->realm)))) {
186       tr_notice("tr_tids_req_handler: IDP Realm (%s) not member of APC (%s).", orig_req->realm->buf, orig_req->comm->buf);
187       tids_send_err_response(tids, orig_req, "IDP APC membership error");
188       return -1;
189     }
190   }
191
192   /* send a TID request to the AAA server(s), and get the answer(s) */
193   /* TBD -- Handle multiple servers */
194
195   if (cfg_apc)
196     expiration_interval = cfg_apc->expiration_interval;
197   else expiration_interval = cfg_comm->expiration_interval;
198   if (fwd_req->expiration_interval)
199     fwd_req->expiration_interval =  (expiration_interval < fwd_req->expiration_interval) ? expiration_interval : fwd_req->expiration_interval;
200   else fwd_req->expiration_interval = expiration_interval;
201   /* Create a TID client instance */
202   if (NULL == (tidc = tidc_create())) {
203     tr_crit("tr_tids_req_hander: Unable to allocate TIDC instance.");
204     tids_send_err_response(tids, orig_req, "Memory allocation failure");
205     return -1;
206   }
207   /* Use the DH parameters from the original request */
208   /* TBD -- this needs to be fixed when we handle more than one req per conn */
209   tidc->client_dh = orig_req->tidc_dh;
210
211   /* Save information about this request for the response */
212   resp_cookie.tr = tr;
213   resp_cookie.orig_req = orig_req;
214
215   /* Set-up TID connection */
216   if (-1 == (fwd_req->conn = tidc_open_connection(tidc, 
217                                                   aaa_servers->hostname->buf,
218                                                   TID_PORT,
219                                               &(fwd_req->gssctx)))) {
220     tr_notice("tr_tids_req_handler: Error in tidc_open_connection.");
221     tids_send_err_response(tids, orig_req, "Can't open connection to next hop TIDS");
222     return -1;
223   };
224
225   /* Send a TID request */
226   if (0 > (rc = tidc_fwd_request(tidc, fwd_req, &tr_tidc_resp_handler, (void *)&resp_cookie))) {
227     tr_notice("Error from tidc_fwd_request, rc = %d.", rc);
228     tids_send_err_response(tids, orig_req, "Can't forward request to next hop TIDS");
229     tid_req_free(orig_req);
230     return -1;
231   }
232     
233   tid_req_free(orig_req);
234   return 0;
235 }
236
237 static int tr_tids_gss_handler(gss_name_t client_name, TR_NAME *gss_name,
238                         void *tr_in)
239 {
240   TR_RP_CLIENT *rp;
241   TR_INSTANCE *tr = (TR_INSTANCE *) tr_in;
242
243   if ((!client_name) || (!gss_name) || (!tr)) {
244     tr_debug("tr_tidc_gss_handler: Bad parameters.");
245     return -1;
246   }
247   
248   /* look up the RP client matching the GSS name */
249   if ((NULL == (rp = tr_rp_client_lookup(tr, gss_name)))) {
250     tr_debug("tr_tids_gss_handler: Unknown GSS name %s", gss_name->buf);
251     return -1;
252   }
253
254   /* Store the rp client in the TR_INSTANCE structure for now... 
255    * TBD -- fix me for new tasking model. */
256   (tr)->rp_gss = rp;
257   tr_debug("Client's GSS Name: %s", gss_name->buf);
258
259   return 0;
260 }
261
262
263
264 /***** event loop management ****/
265
266 /* struct for hanging on to a socket listener event */
267 struct tr_socket_event {
268   int sock_fd; /* the fd for the socket */
269   struct event *ev; /* its event */
270 };
271
272 /* Allocate and set up the event base, return a pointer
273  * to the new event_base or NULL on failure.
274  * Does not currently enable thread-safe mode. */
275 static struct event_base *tr_event_loop_init(void)
276 {
277   struct event_base *base=NULL;
278
279   base=event_base_new();
280   if (base==NULL) {
281     tr_crit("Error initializing event loop.");
282     return NULL;
283   }
284   return base;
285 }
286
287 /* run the loop, does not normally return */
288 static int tr_event_loop_run(struct event_base *base)
289 {
290   return event_base_dispatch(base);
291 }
292
293 /* called when a connection to the TIDS port is received */
294 static void tr_tids_event_cb(int listener, short event, void *arg)
295 {
296   TIDS_INSTANCE *tids = (TIDS_INSTANCE *)arg;
297
298   if (0==(event & EV_READ))
299     tr_debug("tr_tids_event_cb: unexpected event on TIDS socket (event=0x%X)", event);
300   else 
301     tids_accept(tids, listener);
302 }
303
304 /* Configure the tids instance and set up its event handler.
305  * Returns 0 on success, nonzero on failure. Fills in
306  * *tids_event (which should be allocated). */
307 static int tr_tids_event_init(struct event_base *base,
308                               TR_INSTANCE *tr,
309                               struct tr_socket_event *tids_ev)
310 {
311   if (tids_ev == NULL) {
312     tr_debug("tr_tids_event_init: Null tids_ev.");
313     return 1;
314   }
315
316   /* get a tids listener */
317   tids_ev->sock_fd=tids_get_listener(tr->tids,
318                                       tr_tids_req_handler,
319                                       tr_tids_gss_handler,
320                                       tr->active_cfg->internal->hostname,
321                                       tr->active_cfg->internal->tids_port,
322                                       (void *)tr);
323   if (tids_ev->sock_fd < 0) {
324     tr_crit("Error opening TID server socket.");
325     return 1;
326   }
327
328   /* and its event */
329   tids_ev->ev=event_new(base,
330                         tids_ev->sock_fd,
331                         EV_READ|EV_PERSIST,
332                         tr_tids_event_cb,
333                         (void *)tr->tids);
334   event_add(tids_ev->ev, NULL);
335
336   return 0;
337 }
338
339
340 /***** config file watching *****/
341
342 struct tr_fstat {
343   char *name;
344   struct timespec mtime;
345 };
346
347 struct tr_cfgwatch_data {
348   struct timeval poll_interval; /* how often should we check for updates? */
349   struct timeval settling_time; /* how long should we wait for changes to settle before updating? */
350   char *config_dir; /* what directory are we watching? */
351   struct tr_fstat *fstat_list; /* file names and mtimes */
352   int n_files; /* number of files in fstat_list */
353   int change_detected; /* have we detected a change? */
354   struct timeval last_change_detected; /* when did we last note a changed mtime? */
355   TALLOC_CTX *ctx; /* what context should own configuration talloc blocks? */
356   TR_INSTANCE *tr; /* what trust router are we updating? */
357 };
358 typedef struct tr_cfgwatch_data TR_CFGWATCH;
359
360 /* Initialize a new tr_cfgwatch_data struct. Free this with talloc. */
361 static TR_CFGWATCH *tr_cfgwatch_create(TALLOC_CTX *mem_ctx)
362 {
363   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
364   TR_CFGWATCH *new_cfg;
365   
366   new_cfg=talloc(tmp_ctx, TR_CFGWATCH);
367   if (new_cfg == NULL) {
368     tr_debug("tr_cfgwatch_create: Allocation failed.");
369   } else {
370     timerclear(&new_cfg->poll_interval);
371     timerclear(&new_cfg->settling_time);
372     new_cfg->config_dir=NULL;
373     new_cfg->fstat_list=NULL;
374     new_cfg->n_files=0;
375     new_cfg->change_detected=0;
376     timerclear(&new_cfg->last_change_detected);
377     new_cfg->ctx=NULL;
378     new_cfg->tr=NULL;
379   }
380
381   talloc_steal(mem_ctx, new_cfg);
382   talloc_free(tmp_ctx);
383   return new_cfg;
384 }
385
386 /* Obtain the file modification time as seconds since epoch. Returns 0 on success. */
387 static int tr_get_mtime(const char *path, struct timespec *ts)
388 {
389   struct stat file_status;
390
391   if (stat(path, &file_status) != 0) {
392     return -1;
393   } else {
394     (*ts)=file_status.st_mtim;
395   }
396   return 0;
397 }
398
399 static char *tr_join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
400 {
401   return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
402 }
403
404 static int tr_fstat_namecmp(const void *p1_arg, const void *p2_arg)
405 {
406   struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
407   struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
408
409   return strcmp(p1->name, p2->name);
410 }
411
412 static int tr_fstat_mtimecmp(const void *p1_arg, const void *p2_arg)
413 {
414   struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
415   struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
416
417   if (p1->mtime.tv_sec == p2->mtime.tv_sec)
418     return (p1->mtime.tv_nsec) - (p2->mtime.tv_nsec);
419   else
420     return (p1->mtime.tv_sec) - (p2->mtime.tv_sec);
421 }
422
423 /* Get status of all files in cfg_files. Returns list, or NULL on error.
424  * Files are sorted by filename. 
425  * After success, caller must eventually free result with talloc_free. */
426 static struct tr_fstat *tr_fstat_get_all(TALLOC_CTX *mem_ctx,
427                                          const char *config_path,
428                                          struct dirent **cfg_files,
429                                          int n_files)
430 {
431   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
432   struct tr_fstat *fstat_list=NULL;
433   int ii=0;
434
435   /* create a new fstat list (may be discarded) */
436   fstat_list=talloc_array(tmp_ctx, struct tr_fstat, n_files);
437   if (fstat_list==NULL) {
438     tr_err("tr_fstat_get_all: Could not allocate fstat list.");
439     goto cleanup;
440   }
441
442   for (ii=0; ii<n_files; ii++) {
443     fstat_list[ii].name=talloc_strdup(fstat_list, cfg_files[ii]->d_name);
444     if (0 != tr_get_mtime(tr_join_paths(tmp_ctx, config_path, fstat_list[ii].name),
445                          &(fstat_list[ii].mtime))) {
446       tr_warning("tr_fstat_get_all: Could not obtain mtime for file %s", fstat_list[ii].name);
447     }
448   }
449
450   /* sort the list */
451   qsort(fstat_list, n_files, sizeof(struct tr_fstat), tr_fstat_namecmp);
452
453   /* put list in the caller's context and return it */
454   talloc_steal(mem_ctx, fstat_list);
455  cleanup:
456   talloc_free(tmp_ctx);
457   return fstat_list;
458 }
459
460 /* must specify the ctx and tr in cfgwatch! */
461 static int tr_read_and_apply_config(TR_CFGWATCH *cfgwatch)
462 {
463   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
464   char *config_dir=cfgwatch->config_dir;
465   int n_files = 0;
466   struct dirent **cfg_files=NULL;
467   TR_CFG_RC rc = TR_CFG_SUCCESS;        /* presume success */
468   struct tr_fstat *new_fstat_list=NULL;
469   int retval=0;
470
471   /* find the configuration files -- n.b., tr_find_config_files()
472    * allocates memory to cfg_files which we must later free */
473   tr_debug("Reading configuration files from %s/", config_dir);
474   n_files = tr_find_config_files(config_dir, &cfg_files);
475   if (n_files <= 0) {
476     tr_crit("Can't locate configuration files, exiting.");
477     retval=1; goto cleanup;
478   }
479
480   /* Get the list of update times.
481    * Do this before loading in case they change between obtaining their timestamp
482    * and reading the file---this way they will immediately reload if this happens. */
483   new_fstat_list=tr_fstat_get_all(tmp_ctx, config_dir, cfg_files, n_files);
484   if (new_fstat_list==NULL) {
485     tr_crit("Could not allocate config file status list.");
486     retval=1; goto cleanup;
487   }
488
489   if (TR_CFG_SUCCESS != tr_parse_config(cfgwatch->tr, config_dir, n_files, cfg_files)) {
490     tr_crit("Error decoding configuration information.");
491     retval=1; goto cleanup;
492   }
493
494   /* apply initial configuration */
495   if (TR_CFG_SUCCESS != (rc = tr_apply_new_config(cfgwatch->tr))) {
496     tr_crit("Error applying configuration, rc = %d.", rc);
497     retval=1; goto cleanup;
498   }
499
500   /* give ownership of the new_fstat_list to caller's context */
501   if (cfgwatch->fstat_list != NULL) {
502     /* free the old one */
503     talloc_free(cfgwatch->fstat_list);
504   }
505   cfgwatch->n_files=n_files;
506   cfgwatch->fstat_list=new_fstat_list;
507   talloc_steal(cfgwatch->ctx, new_fstat_list);
508   new_fstat_list=NULL;
509
510  cleanup:
511   tr_free_config_file_list(n_files, &cfg_files);
512   talloc_free(tmp_ctx);
513   return retval;
514 }
515
516
517 /* Checks whether any config files have appeared/disappeared/modified.
518  * Returns 1 if so, 0 otherwise. */
519 static int tr_cfgwatch_update_needed(TR_CFGWATCH *cfg_status)
520 {
521   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
522   struct tr_fstat *fstat_list=NULL;
523   int n_files=0;
524   int ii=0;
525   struct dirent **cfg_files=NULL;
526   int update_needed=0; /* return value */
527
528   /* get the list, must free cfg_files later with tr_free_cfg_file_list */
529   n_files = tr_find_config_files(cfg_status->config_dir, &cfg_files);
530   if (n_files <= 0) {
531     tr_warning("tr_cfgwatch_update: configuration files disappeared, skipping update.");
532     goto cleanup;
533   }
534
535   /* create a new fstat list (will be discarded) */
536   fstat_list=tr_fstat_get_all(tmp_ctx, cfg_status->config_dir, cfg_files, n_files);
537   if (fstat_list==NULL) {
538     tr_err("tr_cfgwatch_update: Error getting fstat list.");
539     goto cleanup;
540   }
541
542   /* see if the number of files change, if so need to update */
543   if (n_files != cfg_status->n_files) {
544     tr_debug("tr_cfgwatch_update: Changed number of config files (was %d, now %d).",
545              cfg_status->n_files,
546              n_files);
547     update_needed=1;
548     talloc_free(cfg_status->fstat_list);
549     cfg_status->n_files=n_files;
550     cfg_status->fstat_list=fstat_list;
551     talloc_steal(cfg_status->ctx, fstat_list);
552     goto cleanup;
553   }
554
555   /* See if any files have a changed mtime. Both are sorted by name so this is easy. */
556   for (ii=0; ii<n_files; ii++) {
557     if ((0 != tr_fstat_mtimecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))
558        || (0 != tr_fstat_namecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))){
559       update_needed=1;
560       talloc_free(cfg_status->fstat_list);
561       cfg_status->n_files=n_files;
562       cfg_status->fstat_list=fstat_list;
563       talloc_steal(cfg_status->ctx, fstat_list);
564       goto cleanup;
565     }
566   }
567
568  cleanup:
569   tr_free_config_file_list(n_files, &cfg_files);
570   talloc_free(tmp_ctx);
571   return update_needed;
572 }
573
574 static void tr_cfgwatch_event_cb(int listener, short event, void *arg)
575 {
576   TR_CFGWATCH *cfg_status=(TR_CFGWATCH *) arg;
577   struct timeval now, diff;;
578
579   if (tr_cfgwatch_update_needed(cfg_status)) {
580     tr_notice("Configuration file change detected, waiting for changes to settle.");
581     /*    if (!cfg_status->change_detected) {*/
582       cfg_status->change_detected=1;
583
584       if (0 != gettimeofday(&cfg_status->last_change_detected, NULL)) {
585         tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (1).");
586         /*      }*/
587     }
588   }
589
590   if (cfg_status->change_detected) {
591     if (0 != gettimeofday(&now, NULL)) {
592       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (2).");
593     }
594     timersub(&now, &cfg_status->last_change_detected, &diff);
595     if (!timercmp(&diff, &cfg_status->settling_time, <)) {
596       tr_notice("Configuration file change settled, updating configuration.");
597       if (0 != tr_read_and_apply_config(cfg_status))
598         tr_warning("Configuration file update failed. Using previous configuration.");
599       else
600         tr_notice("Configuration updated successfully.");
601       cfg_status->change_detected=0;
602     }
603   }
604 }
605
606
607 /* Configure the cfgwatch instance and set up its event handler.
608  * Returns 0 on success, nonzero on failure. Points
609  * *cfgwatch_ev to the event struct. */
610 static int tr_cfgwatch_event_init(struct event_base *base,
611                                   TR_CFGWATCH *cfg_status,
612                                   struct event **cfgwatch_ev)
613 {
614   if (cfgwatch_ev == NULL) {
615     tr_debug("tr_cfgwatch_event_init: Null cfgwatch_ev.");
616     return 1;
617   }
618
619   /* zero out the change detection fields */
620   cfg_status->change_detected=0;
621   cfg_status->last_change_detected.tv_sec=0;
622   cfg_status->last_change_detected.tv_usec=0;
623
624   /* create the event and enable it */
625   *cfgwatch_ev=event_new(base, -1, EV_TIMEOUT|EV_PERSIST, tr_cfgwatch_event_cb, (void *)cfg_status);
626   event_add(*cfgwatch_ev, &(cfg_status->poll_interval));
627
628   tr_info("tr_cfgwatch_event_init: Added configuration file watcher with %0d.%06d second poll interval.",
629            cfg_status->poll_interval.tv_sec,
630            cfg_status->poll_interval.tv_usec);
631   return 0;
632 }
633
634
635 /***** command-line option handling / setup *****/
636
637 /* Strip trailing / from a path name.*/
638 static void remove_trailing_slash(char *s) {
639   size_t n;
640
641   n=strlen(s);
642   if(s[n-1]=='/') {
643     s[n-1]='\0';
644   }
645 }
646
647 /* argp global parameters */
648 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
649
650 /* doc strings */
651 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router";
652 static const char arg_doc[]=""; /* string describing arguments, if any */
653
654 /* define the options here. Fields are:
655  * { long-name, short-name, variable name, options, help description } */
656 static const struct argp_option cmdline_options[] = {
657     { "config-dir", 'c', "DIR", 0, "Specify configuration file location (default is current directory)"},
658     { NULL }
659 };
660
661 /* structure for communicating with option parser */
662 struct cmdline_args {
663   char *config_dir;
664 };
665
666 /* parser for individual options - fills in a struct cmdline_args */
667 static error_t parse_option(int key, char *arg, struct argp_state *state)
668 {
669   /* get a shorthand to the command line argument structure, part of state */
670   struct cmdline_args *arguments=state->input;
671
672   switch (key) {
673   case 'c':
674     if (arg == NULL) {
675       /* somehow we got called without an argument */
676       return ARGP_ERR_UNKNOWN;
677     }
678     arguments->config_dir=arg;
679     break;
680
681   default:
682     return ARGP_ERR_UNKNOWN;
683   }
684
685   return 0; /* success */
686 }
687
688 /* assemble the argp parser */
689 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
690
691
692 int main (int argc, char *argv[])
693
694 {
695   TALLOC_CTX *main_ctx=talloc_new(NULL);
696
697   TR_INSTANCE *tr = NULL;
698   struct cmdline_args opts;
699   struct event_base *ev_base;
700   struct tr_socket_event tids_ev;
701   struct event *cfgwatch_ev;
702   TR_CFGWATCH *cfgwatch; /* config file watcher status */
703
704   /* Use standalone logging */
705   tr_log_open();
706
707   /***** parse command-line arguments *****/
708   /* set defaults */
709   opts.config_dir=".";
710
711   /* parse the command line*/
712   argp_parse(&argp, argc, argv, 0, 0, &opts);
713
714   /* process options */
715   remove_trailing_slash(opts.config_dir);
716
717   /* Get a configuration status object */
718   cfgwatch=tr_cfgwatch_create(main_ctx);
719   if (cfgwatch == NULL) {
720     tr_crit("Unable to create configuration watcher object, exiting.");
721     return 1;
722   }
723   
724   /***** create a Trust Router instance *****/
725   if (NULL == (tr = tr_create())) {
726     tr_crit("Unable to create Trust Router instance, exiting.");
727     return 1;
728   }
729
730   /***** process configuration *****/
731   cfgwatch->config_dir=opts.config_dir;
732   cfgwatch->ctx=main_ctx;
733   cfgwatch->tr=tr;
734   if (0 != tr_read_and_apply_config(cfgwatch)) {
735     tr_crit("Error reading configuration, exiting.");
736     return 1;
737   }
738
739   /***** initialize the trust path query server instance *****/
740   if (0 == (tr->tids = tids_create ())) {
741     tr_crit("Error initializing Trust Path Query Server instance.");
742     exit(1);
743   }
744
745   /***** Set up the event loop *****/
746   ev_base=tr_event_loop_init(); /* Set up the event loop */
747
748   /* install configuration file watching events */
749   cfgwatch->poll_interval=(struct timeval) {1,0}; /* set poll interval in {sec, usec} */
750   cfgwatch->settling_time=(struct timeval) {5,0}; /* delay for changes to settle before updating */
751   
752   /* already set config_dir, fstat_list and n_files earlier */
753   if (0 != tr_cfgwatch_event_init(ev_base, cfgwatch, &cfgwatch_ev)) {
754     tr_crit("Error initializing configuration file watcher.");
755     exit(1);
756   }
757
758   /*tr_status_event_init();*/ /* install status reporting events */
759
760   /* install TID server events */
761   if (0 != tr_tids_event_init(ev_base, tr, &tids_ev)) {
762     tr_crit("Error initializing Trust Path Query Server instance.");
763     exit(1);
764   }
765
766   /*tr_trp_event_init();*/ /* install TRP handler events */
767
768   fflush(stdout); fflush(stderr);
769   tr_event_loop_run(ev_base); /* does not return until we are done */
770
771   /* TODO: update the cleanup code */
772   tids_destroy(tr->tids);
773   tr_destroy(tr);
774
775   talloc_free(main_ctx);
776   exit(0);
777 }