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