Merge pull request #51 from painless-security/jennifer/monitoring_client_and_server
[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 <argp.h>
38 #include <event2/event.h>
39 #include <talloc.h>
40 #include <signal.h>
41 #include <time.h>
42
43 #include <tid_internal.h>
44 #include <mon_internal.h>
45 #include <tr_mon.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
56 /***** command-line option handling / setup *****/
57
58 static void print_version_info(void)
59 {
60   printf("Moonshot Trust Router %s\n\n", PACKAGE_VERSION);
61 }
62
63 /* Strip trailing / from a path name.*/
64 static void remove_trailing_slash(char *s) {
65   size_t n;
66
67   n=strlen(s);
68   if(s[n-1]=='/') {
69     s[n-1]='\0';
70   }
71 }
72
73 /* argp global parameters */
74 const char *argp_program_bug_address=PACKAGE_BUGREPORT; /* bug reporting address */
75
76 /* doc strings */
77 static const char doc[]=PACKAGE_NAME " - Moonshot Trust Router " PACKAGE_VERSION;
78 static const char arg_doc[]=""; /* string describing arguments, if any */
79
80 /* define the options here. Fields are:
81  * { long-name, short-name, variable name, options, help description } */
82 static const struct argp_option cmdline_options[] = {
83     { "config-dir", 'c', "DIR", 0, "Specify configuration file location (default is current directory)"},
84     { "config-validate", 'C', NULL, 0, "Validate configuration files and exit"},
85     { "version", 1, NULL, 0, "Print version information and exit"},
86     { NULL }
87 };
88
89 /* structure for communicating with option parser */
90 struct cmdline_args {
91     int version_requested;
92     int validate_config_and_exit;
93     char *config_dir;
94 };
95
96 /* parser for individual options - fills in a struct cmdline_args */
97 static error_t parse_option(int key, char *arg, struct argp_state *state)
98 {
99   /* get a shorthand to the command line argument structure, part of state */
100   struct cmdline_args *arguments=state->input;
101
102   switch (key) {
103     case 'c':
104       if (arg == NULL) {
105         /* somehow we got called without an argument */
106         return ARGP_ERR_UNKNOWN;
107       }
108       arguments->config_dir=arg;
109       break;
110
111     case 1:
112       arguments->version_requested=1;
113       break;
114
115     case 'C':
116       arguments->validate_config_and_exit=1;
117       break;
118
119     default:
120       return ARGP_ERR_UNKNOWN;
121   }
122
123   return 0; /* success */
124 }
125
126 /* assemble the argp parser */
127 static struct argp argp = {cmdline_options, parse_option, arg_doc, doc};
128
129
130 /***** talloc error handling *****/
131 /* called when talloc tries to abort */
132 static void tr_abort(const char *reason)
133 {
134   tr_crit("tr_abort: Critical error, talloc aborted. Reason: %s", reason);
135   abort();
136 }
137
138 #if TALLOC_DEBUG_ENABLE
139 static void tr_talloc_log(const char *msg)
140 {
141   tr_debug("talloc: %s", msg);
142 }
143 #endif /* TALLOC_DEBUG_ENABLE */
144
145 static void configure_signals(void)
146 {
147   sigset_t signals;
148   /* ignore SIGPIPE */
149   sigemptyset(&signals);
150   sigaddset(&signals, SIGPIPE);
151   pthread_sigmask(SIG_BLOCK, &signals, NULL);
152 }
153
154 /* TODO move this function */
155 static json_t *tr_mon_handle_version(void *cookie)
156 {
157   return json_string(PACKAGE_VERSION);
158 }
159
160 static json_t *tr_mon_handle_uptime(void *cookie)
161 {
162   time_t *start_time = cookie;
163   return json_integer(time(NULL) - (*start_time));
164 }
165
166 int main(int argc, char *argv[])
167 {
168   TALLOC_CTX *main_ctx=NULL;
169
170   TR_INSTANCE *tr = NULL;
171   struct cmdline_args opts;
172   struct event_base *ev_base;
173   struct tr_socket_event tids_ev = {0};
174   struct tr_socket_event mon_ev = {0};
175   struct event *cfgwatch_ev;
176
177   time_t start_time = time(NULL); /* TODO move this? */
178
179   configure_signals();
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.version_requested=0;
195   opts.validate_config_and_exit=0;
196   opts.config_dir=".";
197
198   /* parse the command line*/
199   argp_parse(&argp, argc, argv, 0, 0, &opts);
200
201   /* process options */
202   remove_trailing_slash(opts.config_dir);
203
204
205   /***** Print version info *****/
206   print_version_info();
207   if (opts.version_requested)
208     return 0; /* requested that we print version and exit */
209
210   /***** create a Trust Router instance *****/
211   if (NULL == (tr = tr_create(main_ctx))) {
212     tr_crit("Unable to create Trust Router instance, exiting.");
213     return 1;
214   }
215
216   /***** initialize the trust path query server instance *****/
217   if (NULL == (tr->tids = tids_new(tr))) {
218     tr_crit("Error initializing Trust Path Query Server instance.");
219     return 1;
220   }
221
222   /***** initialize the trust router protocol server instance *****/
223   if (NULL == (tr->trps = trps_new(tr))) {
224     tr_crit("Error initializing Trust Router Protocol Server instance.");
225     return 1;
226   }
227
228   /***** initialize the monitoring interface instance *****/
229   if (NULL == (tr->mons = mons_new(tr))) {
230     tr_crit("Error initializing monitoring interface instance.");
231     return 1;
232   }
233   /* Monitor our tids/trps instances */
234   tr->mons->tids = tr->tids;
235   tr->mons->trps = tr->trps;
236
237   /* TODO do this more systematically */
238   mons_register_handler(tr->mons, MON_CMD_SHOW, OPT_TYPE_SHOW_VERSION, tr_mon_handle_version, NULL);
239   mons_register_handler(tr->mons, MON_CMD_SHOW, OPT_TYPE_SHOW_UPTIME, tr_mon_handle_uptime, &start_time);
240
241   /***** process configuration *****/
242   tr->cfgwatch=tr_cfgwatch_create(tr);
243   if (tr->cfgwatch == NULL) {
244     tr_crit("Unable to create configuration watcher object, exiting.");
245     return 1;
246   }
247   tr->cfgwatch->config_dir=opts.config_dir;
248   tr->cfgwatch->cfg_mgr=tr->cfg_mgr;
249   tr->cfgwatch->update_cb=tr_config_changed; /* handle configuration changes */
250   tr->cfgwatch->update_cookie=(void *)tr;
251   if (0 != tr_read_and_apply_config(tr->cfgwatch)) {
252     tr_crit("Error reading configuration, exiting.");
253     return 1;
254   }
255
256   /***** Exit here if we are just validating our configuration *****/
257   if (opts.validate_config_and_exit) {
258     printf("Valid configuration found in %s.\n", opts.config_dir);
259     return 0;
260   }
261   /***** Set up the event loop *****/
262   ev_base=tr_event_loop_init(); /* Set up the event loop */
263   if (ev_base==NULL) {
264     tr_crit("Error initializing event loop.");
265     return 1;
266   }
267
268   /* already set config_dir, fstat_list and n_files earlier */
269   if (0 != tr_cfgwatch_event_init(ev_base, tr->cfgwatch, &cfgwatch_ev)) {
270     tr_crit("Error initializing configuration file watcher.");
271     return 1;
272   }
273
274   /* install monitoring interface events */
275   tr_debug("Initializing monitoring interface events.");
276   if (0 != tr_mons_event_init(ev_base, tr->mons, tr->cfg_mgr, &mon_ev)) {
277     tr_crit("Error initializing monitoring interface.");
278     return 1;
279   }
280
281   /* install TID server events */
282   tr_debug("Initializing TID server events.");
283   if (0 != tr_tids_event_init(ev_base,
284                               tr->tids,
285                               tr->cfg_mgr,
286                               tr->trps,
287                              &tids_ev)) {
288     tr_crit("Error initializing Trust Path Query Server instance.");
289     return 1;
290   }
291
292   /* install TRP handler events */
293   tr_debug("Initializing Dynamic Trust Router Protocol events.");
294   if (TRP_SUCCESS != tr_trps_event_init(ev_base, tr)) {
295     tr_crit("Error initializing Trust Path Query Server instance.");
296     return 1;
297   }
298
299   tr_debug("Starting event loop.");
300   tr_event_loop_run(ev_base); /* does not return until we are done */
301
302   tr_destroy(tr); /* thanks to talloc, should destroy everything */
303
304   talloc_free(main_ctx);
305   return 0;
306 }