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