Wildcard route requests now working.
[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/time.h>
42 #include <signal.h>
43 #include <pthread.h>
44
45 #include <tid_internal.h>
46 #include <tr_tid.h>
47 #include <tr_trp.h>
48 #include <tr_config.h>
49 #include <tr_event.h>
50 #include <tr_cfgwatch.h>
51 #include <tr.h>
52 #include <tr_debug.h>
53
54 #define TALLOC_DEBUG_ENABLE 1
55 #define DEBUG_HARDCODED_PEER_TABLE 1
56 #define DEBUG_PING_SELF 0
57
58 /***** command-line option handling / setup *****/
59
60 /* Strip trailing / from a path name.*/
61 static void remove_trailing_slash(char *s) {
62   size_t n;
63
64   n=strlen(s);
65   if(s[n-1]=='/') {
66     s[n-1]='\0';
67   }
68 }
69
70 /* argp global parameters */
71 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
72
73 /* doc strings */
74 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router";
75 static const char arg_doc[]=""; /* string describing arguments, if any */
76
77 /* define the options here. Fields are:
78  * { long-name, short-name, variable name, options, help description } */
79 static const struct argp_option cmdline_options[] = {
80     { "config-dir", 'c', "DIR", 0, "Specify configuration file location (default is current directory)"},
81     { NULL }
82 };
83
84 /* structure for communicating with option parser */
85 struct cmdline_args {
86   char *config_dir;
87 };
88
89 /* parser for individual options - fills in a struct cmdline_args */
90 static error_t parse_option(int key, char *arg, struct argp_state *state)
91 {
92   /* get a shorthand to the command line argument structure, part of state */
93   struct cmdline_args *arguments=state->input;
94
95   switch (key) {
96   case 'c':
97     if (arg == NULL) {
98       /* somehow we got called without an argument */
99       return ARGP_ERR_UNKNOWN;
100     }
101     arguments->config_dir=arg;
102     break;
103
104   default:
105     return ARGP_ERR_UNKNOWN;
106   }
107
108   return 0; /* success */
109 }
110
111 /* assemble the argp parser */
112 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
113
114
115 /***** talloc error handling *****/
116 /* called when talloc tries to abort */
117 static void tr_abort(const char *reason)
118 {
119   tr_crit("tr_abort: Critical error, talloc aborted. Reason: %s", reason);
120   abort();
121 }
122
123 #if TALLOC_DEBUG_ENABLE
124 static void tr_talloc_log(const char *msg)
125 {
126   tr_debug("talloc: %s", msg);
127 }
128 #endif /* TALLOC_DEBUG_ENABLE */
129
130
131 #if DEBUG_PING_SELF
132 struct thingy {
133   TRPS_INSTANCE *trps;
134   struct event *ev;
135 };
136
137 static void debug_ping(evutil_socket_t fd, short what, void *arg)
138 {
139   TALLOC_CTX *tmp_ctx=talloc_new(NULL);
140   struct thingy *thingy=(struct thingy *)arg;
141   TRPS_INSTANCE *trps=thingy->trps;
142   TRP_REQ *req=NULL;
143   TR_MSG msg;
144   char *encoded=NULL;
145   struct timeval interval={1, 0};
146   static int count=10;
147   TR_NAME *name=NULL;
148
149   tr_debug("debug_ping entered");
150   if (trps->trpc==NULL)
151     tr_trpc_initiate(trps, trps->hostname, trps->port);
152
153   /* create a TRP route request msg */
154   req=trp_req_new(tmp_ctx);
155   name=tr_new_name("community");
156   trp_req_set_comm(req, name);
157   name=tr_new_name("realm");
158   trp_req_set_realm(req, name);
159   tr_msg_set_trp_req(&msg, req);
160   encoded=tr_msg_encode(&msg);
161   if (encoded==NULL)
162     tr_err("debug_ping: error encoding TRP message.");
163   else {
164     tr_debug("debug_ping: sending message");
165     trps_send_msg(trps, NULL, encoded);
166     tr_msg_free_encoded(encoded);
167   }
168   if (count-- > 0)
169     evtimer_add(thingy->ev, &interval);
170 }
171 #endif /* DEBUG_PING_SELF */
172
173 static void configure_signals(void)
174 {
175   sigset_t signals;
176   /* ignore SIGPIPE */
177   sigemptyset(&signals);
178   sigaddset(&signals, SIGPIPE);
179   pthread_sigmask(SIG_BLOCK, &signals, NULL);
180 }
181
182 int main(int argc, char *argv[])
183 {
184   TALLOC_CTX *main_ctx=NULL;
185
186   TR_INSTANCE *tr = NULL;
187   struct cmdline_args opts;
188   struct event_base *ev_base;
189   struct tr_socket_event tids_ev;
190   struct event *cfgwatch_ev;
191
192 #if DEBUG_PING_SELF
193   struct event *debug_ping_ev;
194   struct timeval notime={0, 0};
195   struct thingy thingy={NULL};
196 #endif /* DEBUG_PING_SELF */
197
198   configure_signals();
199
200   /* we're going to be multithreaded, so disable null context tracking */
201   talloc_set_abort_fn(tr_abort);
202   talloc_disable_null_tracking();
203 #if TALLOC_DEBUG_ENABLE
204   talloc_set_log_fn(tr_talloc_log);
205 #endif /* TALLOC_DEBUG_ENABLE */
206   main_ctx=talloc_new(NULL);
207
208   /* Use standalone logging */
209   tr_log_open();
210
211   /***** parse command-line arguments *****/
212   /* set defaults */
213   opts.config_dir=".";
214
215   /* parse the command line*/
216   argp_parse(&argp, argc, argv, 0, 0, &opts);
217
218   /* process options */
219   remove_trailing_slash(opts.config_dir);
220
221   /***** create a Trust Router instance *****/
222   if (NULL == (tr = tr_create(main_ctx))) {
223     tr_crit("Unable to create Trust Router instance, exiting.");
224     return 1;
225   }
226
227   /***** initialize the trust path query server instance *****/
228   if (NULL == (tr->tids = tids_create (tr))) {
229     tr_crit("Error initializing Trust Path Query Server instance.");
230     return 1;
231   }
232
233   /***** initialize the trust router protocol server instance *****/
234   if (NULL == (tr->trps = trps_new(tr))) {
235     tr_crit("Error initializing Trust Router Protocol Server instance.");
236     return 1;
237   }
238
239   /***** process configuration *****/
240   tr->cfgwatch=tr_cfgwatch_create(tr);
241   if (tr->cfgwatch == NULL) {
242     tr_crit("Unable to create configuration watcher object, exiting.");
243     return 1;
244   }
245   tr->cfgwatch->config_dir=opts.config_dir;
246   tr->cfgwatch->cfg_mgr=tr->cfg_mgr;
247   tr->cfgwatch->update_cb=tr_config_changed; /* handle configuration changes */
248   tr->cfgwatch->update_cookie=(void *)tr;
249   if (0 != tr_read_and_apply_config(tr->cfgwatch)) {
250     tr_crit("Error reading configuration, exiting.");
251     return 1;
252   }
253
254   /***** Set up the event loop *****/
255   ev_base=tr_event_loop_init(); /* Set up the event loop */
256   if (ev_base==NULL) {
257     tr_crit("Error initializing event loop.");
258     return 1;
259   }
260
261   /* already set config_dir, fstat_list and n_files earlier */
262   if (0 != tr_cfgwatch_event_init(ev_base, tr->cfgwatch, &cfgwatch_ev)) {
263     tr_crit("Error initializing configuration file watcher.");
264     return 1;
265   }
266
267   /*tr_status_event_init();*/ /* install status reporting events */
268
269   /* install TID server events */
270   if (0 != tr_tids_event_init(ev_base,
271                               tr->tids,
272                               tr->cfg_mgr,
273                              &tids_ev)) {
274     tr_crit("Error initializing Trust Path Query Server instance.");
275     return 1;
276   }
277
278   /* install TRP handler events */
279   if (TRP_SUCCESS != tr_trps_event_init(ev_base, tr)) {
280     tr_crit("Error initializing Trust Path Query Server instance.");
281     return 1;
282   }
283
284 #if DEBUG_HARDCODED_PEER_TABLE
285   {
286     TRP_PEER *hc_peer=NULL;
287     char *s=NULL;
288
289     hc_peer=trp_peer_new(main_ctx); /* will later be stolen by ptable context */
290     if (hc_peer==NULL) {
291       tr_crit("Unable to allocate new peer. Aborting.");
292       return 1;
293     }
294     trp_peer_set_server(hc_peer, "epsilon.vmnet");
295     trp_peer_set_gssname(hc_peer, tr_new_name("tr-epsilon-vmnet@apc.painless-security.com"));
296     trp_peer_set_conn_status_cb(hc_peer, tr_peer_status_change, (void *)(tr->trps));
297     switch (tr->trps->port) {
298     case 10000:
299       trp_peer_set_port(hc_peer, 10001);
300       break;
301     case 10001:
302       trp_peer_set_port(hc_peer, 10000);
303       break;
304     default:
305       tr_crit("Cannot use hardcoded peer table with port other than 10000 or 10001.");
306       return 1;
307     }
308     if (TRP_SUCCESS != trps_add_peer(tr->trps, hc_peer)) {
309       tr_crit("Unable to add peer.");
310       return 1;
311     }
312
313     hc_peer=trp_peer_new(main_ctx); /* will later be stolen by ptable context */
314     if (hc_peer==NULL) {
315       tr_crit("Unable to allocate new peer. Aborting.");
316       return 1;
317     }
318     trp_peer_set_server(hc_peer, "epsilon.vmnet");
319     trp_peer_set_gssname(hc_peer, tr_new_name("trpc@apc.painless-security.com"));
320     trp_peer_set_port(hc_peer, 10002); /* not really used */
321     if (TRP_SUCCESS != trps_add_peer(tr->trps, hc_peer)) {
322       tr_crit("Unable to add peer.");
323       return 1;
324     }
325     
326     s=trp_ptable_to_str(main_ctx, tr->trps->ptable, NULL, NULL);
327     tr_debug("Peer Table:\n%s\n", s);
328     talloc_free(s);
329   }
330 #endif /* DEBUG_HARDCODED_PEER_TABLE */
331
332 #if DEBUG_PING_SELF
333   /* for debugging, send a message to peers on a timer */
334   debug_ping_ev=evtimer_new(ev_base, debug_ping, (void *)&thingy);
335   thingy.trps=tr->trps;
336   thingy.ev=debug_ping_ev;
337   evtimer_add(debug_ping_ev, &notime);
338 #endif /* DEBUG_PING_SELF */
339
340   tr_event_loop_run(ev_base); /* does not return until we are done */
341
342   /* TODO: ensure talloc is properly used so this actually works */
343   tr_destroy(tr); /* thanks to talloc, should destroy everything */
344
345   talloc_free(main_ctx);
346   return 0;
347 }