Resolve circular header dependencies.
[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)->active_cfg->idp_realms, 
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)->active_cfg->default_servers,
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->active_cfg->rp_clients, 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_debug("tr_read_and_apply_config: No configuration files.");
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_debug("tr_read_and_apply_config: Could not allocate config file status list.");
486     retval=1; goto cleanup;
487   }
488
489   /* allocate a new configuration, dumping an old one if needed */
490   if(cfgwatch->tr->new_cfg != NULL)
491     tr_cfg_free(cfgwatch->tr->new_cfg);
492   cfgwatch->tr->new_cfg=tr_cfg_new(tmp_ctx);
493   if (cfgwatch->tr->new_cfg==NULL) {
494     tr_debug("tr_read_and_apply_config: Error allocating new_cfg.");
495     retval=1; goto cleanup;
496   }
497   /* now fill it in */
498   if (TR_CFG_SUCCESS != (rc = tr_parse_config(cfgwatch->tr->new_cfg, config_dir, n_files, cfg_files))) {
499     tr_debug("tr_read_and_apply_config: Error decoding configuration information, rc=%d.", rc);
500     retval=1; goto cleanup;
501   }
502
503   /* apply initial configuration */
504   if (TR_CFG_SUCCESS != (rc = tr_apply_new_config(&cfgwatch->tr->active_cfg,
505                                                  &cfgwatch->tr->new_cfg))) {
506     tr_debug("tr_read_and_apply_config: Error applying configuration, rc = %d.", rc);
507     retval=1; goto cleanup;
508   }
509   talloc_steal(cfgwatch->ctx, cfgwatch->tr->active_cfg); /* hand over ownership */
510
511   /* give ownership of the new_fstat_list to caller's context */
512   if (cfgwatch->fstat_list != NULL) {
513     /* free the old one */
514     talloc_free(cfgwatch->fstat_list);
515   }
516   cfgwatch->n_files=n_files;
517   cfgwatch->fstat_list=new_fstat_list;
518   talloc_steal(cfgwatch->ctx, new_fstat_list);
519   new_fstat_list=NULL;
520
521  cleanup:
522   tr_free_config_file_list(n_files, &cfg_files);
523   talloc_free(tmp_ctx);
524   return retval;
525 }
526
527
528 /* Checks whether any config files have appeared/disappeared/modified.
529  * Returns 1 if so, 0 otherwise. */
530 static int tr_cfgwatch_update_needed(TR_CFGWATCH *cfg_status)
531 {
532   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
533   struct tr_fstat *fstat_list=NULL;
534   int n_files=0;
535   int ii=0;
536   struct dirent **cfg_files=NULL;
537   int update_needed=0; /* return value */
538
539   /* get the list, must free cfg_files later with tr_free_cfg_file_list */
540   n_files = tr_find_config_files(cfg_status->config_dir, &cfg_files);
541   if (n_files <= 0) {
542     tr_warning("tr_cfgwatch_update: configuration files disappeared, skipping update.");
543     goto cleanup;
544   }
545
546   /* create a new fstat list (will be discarded) */
547   fstat_list=tr_fstat_get_all(tmp_ctx, cfg_status->config_dir, cfg_files, n_files);
548   if (fstat_list==NULL) {
549     tr_err("tr_cfgwatch_update: Error getting fstat list.");
550     goto cleanup;
551   }
552
553   /* see if the number of files change, if so need to update */
554   if (n_files != cfg_status->n_files) {
555     tr_debug("tr_cfgwatch_update: Changed number of config files (was %d, now %d).",
556              cfg_status->n_files,
557              n_files);
558     update_needed=1;
559     talloc_free(cfg_status->fstat_list);
560     cfg_status->n_files=n_files;
561     cfg_status->fstat_list=fstat_list;
562     talloc_steal(cfg_status->ctx, fstat_list);
563     goto cleanup;
564   }
565
566   /* See if any files have a changed mtime. Both are sorted by name so this is easy. */
567   for (ii=0; ii<n_files; ii++) {
568     if ((0 != tr_fstat_mtimecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))
569        || (0 != tr_fstat_namecmp(&fstat_list[ii], &cfg_status->fstat_list[ii]))){
570       update_needed=1;
571       talloc_free(cfg_status->fstat_list);
572       cfg_status->n_files=n_files;
573       cfg_status->fstat_list=fstat_list;
574       talloc_steal(cfg_status->ctx, fstat_list);
575       goto cleanup;
576     }
577   }
578
579  cleanup:
580   tr_free_config_file_list(n_files, &cfg_files);
581   talloc_free(tmp_ctx);
582   return update_needed;
583 }
584
585 static void tr_cfgwatch_event_cb(int listener, short event, void *arg)
586 {
587   TR_CFGWATCH *cfg_status=(TR_CFGWATCH *) arg;
588   struct timeval now, diff;;
589
590   if (tr_cfgwatch_update_needed(cfg_status)) {
591     tr_notice("Configuration file change detected, waiting for changes to settle.");
592     /*    if (!cfg_status->change_detected) {*/
593       cfg_status->change_detected=1;
594
595       if (0 != gettimeofday(&cfg_status->last_change_detected, NULL)) {
596         tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (1).");
597         /*      }*/
598     }
599   }
600
601   if (cfg_status->change_detected) {
602     if (0 != gettimeofday(&now, NULL)) {
603       tr_err("tr_cfgwatch_event_cb: gettimeofday() failed (2).");
604     }
605     timersub(&now, &cfg_status->last_change_detected, &diff);
606     if (!timercmp(&diff, &cfg_status->settling_time, <)) {
607       tr_notice("Configuration file change settled, updating configuration.");
608       if (0 != tr_read_and_apply_config(cfg_status))
609         tr_warning("Configuration file update failed. Using previous configuration.");
610       else
611         tr_notice("Configuration updated successfully.");
612       cfg_status->change_detected=0;
613     }
614   }
615 }
616
617
618 /* Configure the cfgwatch instance and set up its event handler.
619  * Returns 0 on success, nonzero on failure. Points
620  * *cfgwatch_ev to the event struct. */
621 static int tr_cfgwatch_event_init(struct event_base *base,
622                                   TR_CFGWATCH *cfg_status,
623                                   struct event **cfgwatch_ev)
624 {
625   if (cfgwatch_ev == NULL) {
626     tr_debug("tr_cfgwatch_event_init: Null cfgwatch_ev.");
627     return 1;
628   }
629
630   /* zero out the change detection fields */
631   cfg_status->change_detected=0;
632   cfg_status->last_change_detected.tv_sec=0;
633   cfg_status->last_change_detected.tv_usec=0;
634
635   /* create the event and enable it */
636   *cfgwatch_ev=event_new(base, -1, EV_TIMEOUT|EV_PERSIST, tr_cfgwatch_event_cb, (void *)cfg_status);
637   event_add(*cfgwatch_ev, &(cfg_status->poll_interval));
638
639   tr_info("tr_cfgwatch_event_init: Added configuration file watcher with %0d.%06d second poll interval.",
640            cfg_status->poll_interval.tv_sec,
641            cfg_status->poll_interval.tv_usec);
642   return 0;
643 }
644
645
646 /***** command-line option handling / setup *****/
647
648 /* Strip trailing / from a path name.*/
649 static void remove_trailing_slash(char *s) {
650   size_t n;
651
652   n=strlen(s);
653   if(s[n-1]=='/') {
654     s[n-1]='\0';
655   }
656 }
657
658 /* argp global parameters */
659 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
660
661 /* doc strings */
662 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router";
663 static const char arg_doc[]=""; /* string describing arguments, if any */
664
665 /* define the options here. Fields are:
666  * { long-name, short-name, variable name, options, help description } */
667 static const struct argp_option cmdline_options[] = {
668     { "config-dir", 'c', "DIR", 0, "Specify configuration file location (default is current directory)"},
669     { NULL }
670 };
671
672 /* structure for communicating with option parser */
673 struct cmdline_args {
674   char *config_dir;
675 };
676
677 /* parser for individual options - fills in a struct cmdline_args */
678 static error_t parse_option(int key, char *arg, struct argp_state *state)
679 {
680   /* get a shorthand to the command line argument structure, part of state */
681   struct cmdline_args *arguments=state->input;
682
683   switch (key) {
684   case 'c':
685     if (arg == NULL) {
686       /* somehow we got called without an argument */
687       return ARGP_ERR_UNKNOWN;
688     }
689     arguments->config_dir=arg;
690     break;
691
692   default:
693     return ARGP_ERR_UNKNOWN;
694   }
695
696   return 0; /* success */
697 }
698
699 /* assemble the argp parser */
700 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
701
702
703 int main (int argc, char *argv[])
704
705 {
706   TALLOC_CTX *main_ctx=talloc_new(NULL);
707
708   TR_INSTANCE *tr = NULL;
709   struct cmdline_args opts;
710   struct event_base *ev_base;
711   struct tr_socket_event tids_ev;
712   struct event *cfgwatch_ev;
713   TR_CFGWATCH *cfgwatch; /* config file watcher status */
714
715   /* Use standalone logging */
716   tr_log_open();
717
718   /***** parse command-line arguments *****/
719   /* set defaults */
720   opts.config_dir=".";
721
722   /* parse the command line*/
723   argp_parse(&argp, argc, argv, 0, 0, &opts);
724
725   /* process options */
726   remove_trailing_slash(opts.config_dir);
727
728   /* Get a configuration status object */
729   cfgwatch=tr_cfgwatch_create(main_ctx);
730   if (cfgwatch == NULL) {
731     tr_err("Unable to create configuration watcher object, exiting.");
732     return 1;
733   }
734   
735   /***** create a Trust Router instance *****/
736   if (NULL == (tr = tr_create())) {
737     tr_crit("Unable to create Trust Router instance, exiting.");
738     return 1;
739   }
740
741   /***** process configuration *****/
742   cfgwatch->config_dir=opts.config_dir;
743   cfgwatch->ctx=main_ctx;
744   cfgwatch->tr=tr;
745   if (0 != tr_read_and_apply_config(cfgwatch)) {
746     tr_crit("Error reading configuration, exiting.");
747     return 1;
748   }
749
750   /***** initialize the trust path query server instance *****/
751   if (0 == (tr->tids = tids_create ())) {
752     tr_crit("Error initializing Trust Path Query Server instance.");
753     exit(1);
754   }
755
756   /***** Set up the event loop *****/
757   ev_base=tr_event_loop_init(); /* Set up the event loop */
758
759   /* install configuration file watching events */
760   cfgwatch->poll_interval=(struct timeval) {1,0}; /* set poll interval in {sec, usec} */
761   cfgwatch->settling_time=(struct timeval) {5,0}; /* delay for changes to settle before updating */
762   
763   /* already set config_dir, fstat_list and n_files earlier */
764   if (0 != tr_cfgwatch_event_init(ev_base, cfgwatch, &cfgwatch_ev)) {
765     tr_crit("Error initializing configuration file watcher.");
766     exit(1);
767   }
768
769   /*tr_status_event_init();*/ /* install status reporting events */
770
771   /* install TID server events */
772   if (0 != tr_tids_event_init(ev_base, tr, &tids_ev)) {
773     tr_crit("Error initializing Trust Path Query Server instance.");
774     exit(1);
775   }
776
777   /*tr_trp_event_init();*/ /* install TRP handler events */
778
779   fflush(stdout); fflush(stderr);
780   tr_event_loop_run(ev_base); /* does not return until we are done */
781
782   /* TODO: update the cleanup code */
783   tids_destroy(tr->tids);
784   tr_destroy(tr);
785
786   talloc_free(main_ctx);
787   exit(0);
788 }