2 * Copyright (c) 2012, 2015, JANET(UK)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
39 #include <event2/event.h>
44 #include <tr_filter.h>
45 #include <tid_internal.h>
46 #include <tr_config.h>
52 /* Structure to hold TR instance and original request in one cookie */
53 typedef struct tr_resp_cookie {
59 static void tr_tidc_resp_handler (TIDC_INSTANCE *tidc,
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);
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,
75 static int tr_tids_req_handler (TIDS_INSTANCE *tids,
80 TIDC_INSTANCE *tidc = NULL;
81 TR_RESP_COOKIE resp_cookie;
82 TR_AAA_SERVER *aaa_servers = 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;
90 time_t expiration_interval;
92 if ((!tids) || (!orig_req) || (!resp) || (!tr)) {
93 tr_debug("tr_tids_req_handler: Bad parameters");
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);
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.");
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");
114 /* Check that the rp_realm matches the filter for the GSS name that
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");
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");
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");
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");
146 apc = tr_dup_name(cfg_comm->apcs->id);
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");
156 fwd_req->orig_coi = orig_req->comm;
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");
166 /* Find the AAA server(s) for this request */
167 if (NULL == (aaa_servers = tr_idp_aaa_server_lookup((TR_INSTANCE *)tids->cookie,
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,
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");
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");
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");
191 /* send a TID request to the AAA server(s), and get the answer(s) */
192 /* TBD -- Handle multiple servers */
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");
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;
210 /* Save information about this request for the response */
212 resp_cookie.orig_req = orig_req;
214 /* Set-up TID connection */
215 if (-1 == (fwd_req->conn = tidc_open_connection(tidc,
216 aaa_servers->hostname->buf,
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");
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);
232 tid_req_free(orig_req);
236 static int tr_tids_gss_handler(gss_name_t client_name, TR_NAME *gss_name,
240 TR_INSTANCE *tr = (TR_INSTANCE *) tr_in;
242 if ((!client_name) || (!gss_name) || (!tr)) {
243 tr_debug("tr_tidc_gss_handler: Bad parameters.");
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);
253 /* Store the rp client in the TR_INSTANCE structure for now...
254 * TBD -- fix me for new tasking model. */
256 tr_debug("Client's GSS Name: %s", gss_name->buf);
261 /***** event loop management ****/
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 */
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)
274 struct event_base *base=NULL;
276 base=event_base_new();
278 tr_crit("Error initializing event loop.");
284 /* run the loop, does not normally return */
285 static int tr_event_loop_run(struct event_base *base)
287 return event_base_dispatch(base);
290 /* called when a connection to the TIDS port is received */
291 static void tr_tids_event_cb(int listener, short event, void *arg)
293 TIDS_INSTANCE *tids = (TIDS_INSTANCE *)arg;
295 if (0==(event & EV_READ))
296 tr_debug("tr_tids_event_cb: unexpected event on TIDS socket (event=0x%X)", event);
298 tids_accept(tids, listener);
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,
306 struct tr_socket_event *tids_ev)
308 if (tids_ev == NULL) {
309 tr_debug("tr_tids_event_init: Null tids_ev.");
313 /* get a tids listener */
314 tids_ev->sock_fd=tids_get_listener(tr->tids,
317 tr->active_cfg->internal->hostname,
318 tr->active_cfg->internal->tids_port,
320 if (tids_ev->sock_fd < 0) {
321 tr_crit("Error opening TID server socket.");
326 tids_ev->ev=event_new(base,
331 event_add(tids_ev->ev, NULL);
337 /***** config file watching *****/
341 struct timespec mtime;
344 struct tr_cfgwatch_data {
345 struct timeval poll_interval;
347 struct tr_fstat *fstat_list;
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)
354 struct stat file_status;
356 if (stat(path, &file_status) != 0) {
359 (*ts)=file_status.st_mtim;
364 static char *tr_join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
366 return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
369 static int tr_fstat_namecmp(const void *p1_arg, const void *p2_arg)
371 struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
372 struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
374 return strcmp(p1->name, p2->name);
377 static int tr_fstat_mtimecmp(const void *p1_arg, const void *p2_arg)
379 struct tr_fstat *p1=(struct tr_fstat *) p1_arg;
380 struct tr_fstat *p2=(struct tr_fstat *) p2_arg;
382 if (p1->mtime.tv_sec == p2->mtime.tv_sec)
383 return (p1->mtime.tv_nsec) - (p2->mtime.tv_nsec);
385 return (p1->mtime.tv_sec) - (p2->mtime.tv_sec);
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,
396 TALLOC_CTX *tmp_ctx=talloc_new(NULL);
397 struct tr_fstat *fstat_list=NULL;
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.");
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);
416 qsort(fstat_list, n_files, sizeof(struct tr_fstat), tr_fstat_namecmp);
418 /* put list in the caller's context and return it */
419 talloc_steal(mem_ctx, fstat_list);
421 talloc_free(tmp_ctx);
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)
429 TALLOC_CTX *tmp_ctx=talloc_new(NULL);
430 struct tr_fstat *fstat_list=NULL;
433 struct dirent **cfg_files=NULL;
434 int update_needed=0; /* return value */
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);
439 tr_warning("tr_cfgwatch_update: configuration files disappeared, skipping update.");
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.");
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).",
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]))){
469 tr_free_config_file_list(n_files, &cfg_files);
470 talloc_free(tmp_ctx);
471 return update_needed;
474 static void tr_cfgwatch_event_cb(int listener, short event, void *arg)
476 TALLOC_CTX *tmp_ctx=talloc_new(NULL);
477 struct tr_cfgwatch_data *cfg_status=(struct tr_cfgwatch_data *) arg;
479 if (tr_cfgwatch_update_needed(cfg_status)) {
480 tr_notice("tr_cfgwatch_event_cb: update needed!"); /* remove */
483 talloc_free(tmp_ctx);
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)
494 if (cfgwatch_ev == NULL) {
495 tr_debug("tr_cfgwatch_event_init: Null cfgwatch_ev.");
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));
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);
509 /***** command-line option handling / setup *****/
511 /* Strip trailing / from a path name.*/
512 static void remove_trailing_slash(char *s) {
521 /* argp global parameters */
522 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
525 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router";
526 static const char arg_doc[]=""; /* string describing arguments, if any */
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)"},
535 /* structure for communicating with option parser */
536 struct cmdline_args {
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)
543 /* get a shorthand to the command line argument structure, part of state */
544 struct cmdline_args *arguments=state->input;
549 /* somehow we got called without an argument */
550 return ARGP_ERR_UNKNOWN;
552 arguments->config_dir=arg;
556 return ARGP_ERR_UNKNOWN;
559 return 0; /* success */
562 /* assemble the argp parser */
563 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
566 int main (int argc, char *argv[])
569 TALLOC_CTX *main_ctx=talloc_new(NULL);
571 TR_INSTANCE *tr = NULL;
572 struct dirent **cfg_files = NULL;
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;
581 /***** parse command-line arguments *****/
585 /* parse the command line*/
586 argp_parse(&argp, argc, argv, 0, 0, &opts);
588 /* process options */
589 remove_trailing_slash(opts.config_dir);
592 /* Use standalone logging */
595 /***** create a Trust Router instance *****/
596 if (NULL == (tr = tr_create())) {
597 tr_crit("Unable to create Trust Router instance, exiting.");
602 /***** process configuration *****/
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);
609 tr_crit("Can't locate configuration files, exiting.");
610 tr_free_config_file_list(n_files, &cfg_files);
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);
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);
630 /* we are now done with the config filenames, free those */
631 tr_free_config_file_list(n_files, &cfg_files);
633 /* apply initial configuration */
634 if (TR_CFG_SUCCESS != (rc = tr_apply_new_config(tr))) {
635 tr_crit("Error applying configuration, rc = %d.", rc);
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.");
646 /***** Set up the event loop *****/
647 ev_base=tr_event_loop_init(); /* Set up the event loop */
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.");
658 /*tr_status_event_init();*/ /* install status reporting events */
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.");
666 /*tr_trp_event_init();*/ /* install TRP handler events */
668 fflush(stdout); fflush(stderr);
669 tr_event_loop_run(ev_base); /* does not return until we are done */
671 /* TODO: update the cleanup code */
672 tids_destroy(tr->tids);
675 talloc_free(main_ctx);