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