1d8bd282c0958533c1400f1de10aaeef1e860ad8
[vpp.git] / vlib / vlib / unix / main.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * main.c: Unix main routine
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39 #include <vlib/vlib.h>
40 #include <vlib/unix/unix.h>
41 #include <vlib/unix/plugin.h>
42
43 #include <signal.h>
44 #include <sys/ucontext.h>
45 #include <syslog.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <fcntl.h>
49
50 unix_main_t unix_main;
51
52 static clib_error_t *
53 unix_main_init (vlib_main_t * vm)
54 {
55   unix_main_t * um = &unix_main;
56   um->vlib_main = vm;
57   return vlib_call_init_function (vm, unix_input_init);
58 }
59
60 VLIB_INIT_FUNCTION (unix_main_init);
61
62 static void unix_signal_handler (int signum, siginfo_t * si, ucontext_t * uc)
63 {
64   uword fatal;
65   u8 * msg = 0;
66
67   msg = format (msg, "received signal %U, PC %U",
68                 format_signal, signum,
69                 format_ucontext_pc, uc);
70
71   if (signum == SIGSEGV)
72     msg = format (msg, ", faulting address %p", si->si_addr);
73
74   switch (signum)
75     {
76       /* these (caught) signals cause the application to exit */
77     case SIGTERM:
78       if (unix_main.vlib_main->main_loop_exit_set) 
79         {
80           syslog (LOG_ERR | LOG_DAEMON, "received SIGTERM, exiting...");
81
82           clib_longjmp (&unix_main.vlib_main->main_loop_exit, 
83                         VLIB_MAIN_LOOP_EXIT_CLI);
84         }
85     case SIGQUIT:
86     case SIGINT:
87     case SIGILL:
88     case SIGBUS:
89     case SIGSEGV:
90     case SIGHUP:
91     case SIGFPE:
92       fatal = 1;
93       break;
94
95       /* by default, print a message and continue */
96     default:
97       fatal = 0;
98       break;
99     }
100
101   /* Null terminate. */
102   vec_add1 (msg, 0);
103
104   if (fatal)
105     {
106       syslog (LOG_ERR | LOG_DAEMON, "%s", msg);
107       os_exit (1);
108     }
109   else
110     clib_warning ("%s", msg);
111
112   vec_free (msg);
113 }
114
115 static clib_error_t *
116 setup_signal_handlers (unix_main_t * um)
117 {
118   uword i;
119   struct sigaction sa;
120
121   for (i = 1; i < 32; i++)
122     {
123       memset (&sa, 0, sizeof (sa));
124       sa.sa_sigaction = (void *) unix_signal_handler;
125       sa.sa_flags = SA_SIGINFO;
126
127       switch (i)
128         {
129           /* these signals take the default action */
130         case SIGABRT:
131         case SIGKILL:
132         case SIGSTOP:
133         case SIGUSR1:
134         case SIGUSR2:
135           continue;
136
137           /* ignore SIGPIPE, SIGCHLD */
138         case SIGPIPE:
139         case SIGCHLD:
140           sa.sa_sigaction = (void *) SIG_IGN;
141           break;
142
143           /* catch and handle all other signals */
144         default:
145           break;
146         }
147
148       if (sigaction (i, &sa, 0) < 0)
149         return clib_error_return_unix (0, "sigaction %U", format_signal, i);
150     }
151
152   return 0;
153 }
154
155 static void unix_error_handler (void * arg, u8 * msg, int msg_len)
156 {
157   unix_main_t * um = arg;
158
159   /* Echo to stderr when interactive. */
160   if (um->flags & UNIX_FLAG_INTERACTIVE)
161     {
162       CLIB_UNUSED (int r) = write (2, msg, msg_len);
163     }
164   else
165     {
166       char save = msg[msg_len - 1];
167
168       /* Null Terminate. */
169       msg[msg_len-1] = 0;
170
171       syslog (LOG_ERR | LOG_DAEMON, "%s", msg);
172
173       msg[msg_len-1] = save;
174     }
175 }
176
177 void vlib_unix_error_report (vlib_main_t * vm, clib_error_t * error)
178 {
179     unix_main_t * um = &unix_main;
180
181     if (um->flags & UNIX_FLAG_INTERACTIVE || error == 0)
182       return;
183
184     {
185       char save;
186       u8 * msg;
187       u32 msg_len;
188
189       msg = error->what;
190       msg_len = vec_len(msg);
191
192       /* Null Terminate. */
193       save = msg[msg_len-1];
194       msg[msg_len-1] = 0;
195
196       syslog (LOG_ERR | LOG_DAEMON, "%s", msg);
197
198       msg[msg_len-1] = save;
199     }
200 }
201
202 static uword
203 startup_config_process (vlib_main_t * vm,
204                  vlib_node_runtime_t * rt,
205                  vlib_frame_t * f)
206 {
207   unix_main_t * um = &unix_main;
208   u8 * buf = 0;
209   uword l, n = 1;
210
211   vlib_process_suspend (vm, 2.0);
212
213   while (um->unix_config_complete == 0)
214     vlib_process_suspend (vm, 0.1);
215
216   if (um->startup_config_filename) {
217     unformat_input_t sub_input;
218     int fd;
219     struct stat s;
220     char *fn = (char *)um->startup_config_filename;
221         
222     fd = open (fn, O_RDONLY);
223     if (fd < 0) {
224       clib_warning ("failed to open `%s'", fn);
225       return 0;
226     }
227
228     if (fstat (fd, &s) < 0) {
229       clib_warning ("failed to stat `%s'", fn);
230     bail:
231       close(fd);
232       return 0;
233     }
234     
235     if (! (S_ISREG (s.st_mode) || S_ISLNK (s.st_mode))) {
236       clib_warning ("not a regular file: `%s'", fn);
237       goto bail;
238     }
239
240     while (n > 0)
241       {
242         l = vec_len (buf);
243         vec_resize (buf, 4096);
244         n = read (fd, buf + l, 4096);
245         if (n > 0)
246           {
247             _vec_len (buf) = l + n;
248             if (n < 4096)
249               break;
250           }
251         else
252           break;
253       }
254     if (um->log_fd && vec_len (buf))
255       {
256         u8 * lv = 0;
257         lv = format (lv, "%U: ***** Startup Config *****\n%v", 
258                      format_timeval,
259                      0 /* current bat-time */,
260                      0 /* current bat-format */,
261                      buf);
262         {
263           int rv __attribute__((unused)) = 
264             write (um->log_fd, lv, vec_len(lv));
265         }
266         vec_reset_length (lv);
267         lv = format (lv, "%U: ***** End Startup Config *****\n", 
268                      format_timeval,
269                      0 /* current bat-time */,
270                      0 /* current bat-format */);
271         {
272           int rv __attribute__((unused)) = 
273             write (um->log_fd, lv, vec_len(lv));
274         }
275         vec_free (lv);
276       }
277
278     if (vec_len(buf))
279       {
280         unformat_init_vector (&sub_input, buf);
281         vlib_cli_input (vm, &sub_input, 0, 0);
282         /* frees buf for us */
283         unformat_free (&sub_input);
284       }
285     close(fd);
286   }
287   return 0;
288 }
289
290 VLIB_REGISTER_NODE (startup_config_node,static) = {
291     .function = startup_config_process,
292     .type = VLIB_NODE_TYPE_PROCESS,
293     .name = "startup-config-process",
294 };
295
296 static clib_error_t *
297 unix_config (vlib_main_t * vm, unformat_input_t * input)
298 {
299   unix_main_t * um = &unix_main;
300   clib_error_t * error = 0;
301
302   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
303     {
304       char * cli_prompt;
305       if (unformat (input, "interactive"))
306         um->flags |= UNIX_FLAG_INTERACTIVE;
307       else if (unformat (input, "nodaemon"))
308         um->flags |= UNIX_FLAG_NODAEMON;  
309       else if (unformat (input, "cli-prompt %s", &cli_prompt))
310         vlib_unix_cli_set_prompt (cli_prompt);
311       else if (unformat (input, "cli-listen %s", &um->cli_listen_socket.config))
312         ;
313       else if (unformat (input, "cli-line-mode"))
314         um->cli_line_mode = 1;
315       else if (unformat (input, "cli-no-banner"))
316         um->cli_no_banner = 1;
317       else if (unformat (input, "cli-history-limit %d", &um->cli_history_limit))
318         ;
319       else if (unformat (input, "full-coredump"))
320         {
321           int fd;
322
323           fd = open ("/proc/self/coredump_filter", O_WRONLY);
324           if (fd > 0)
325             {
326               if (write (fd, "0x6f\n", 5) != 5)
327                 clib_unix_warning ("coredump filter write failed!");
328               close(fd);
329             }
330           else
331             clib_unix_warning ("couldn't open /proc/self/coredump_filter");
332         }
333       else if (unformat (input, "startup-config %s", 
334                          &um->startup_config_filename))
335         ;
336       else if (unformat (input, "exec %s",
337                          &um->startup_config_filename))
338         ;
339       else if (unformat (input, "log %s", &um->log_filename))
340         {
341           um->log_fd = open ((char *) um->log_filename, 
342                              O_CREAT | O_WRONLY | O_APPEND, 0644);
343           if (um->log_fd < 0)
344             {
345               clib_warning ("couldn't open log '%s'\n", um->log_filename);
346               um->log_fd = 0;
347             }
348           else
349             {
350               u8 * lv = 0;
351               lv = format (0, "%U: ***** Start: PID %d *****\n", 
352                            format_timeval,
353                            0 /* current bat-time */,
354                            0 /* current bat-format */,
355                            getpid());
356               {
357                 int rv __attribute__((unused)) = 
358                   write (um->log_fd, lv, vec_len(lv));
359               }
360               vec_free (lv);
361             }
362         }
363       else
364         return clib_error_return (0, "unknown input `%U'",
365                                   format_unformat_error, input);
366     }
367
368   if (! (um->flags & UNIX_FLAG_INTERACTIVE))
369     {
370       error = setup_signal_handlers (um);
371       if (error)
372         return error;
373
374       openlog (vm->name, LOG_CONS | LOG_PERROR | LOG_PID, LOG_DAEMON);
375       clib_error_register_handler (unix_error_handler, um);
376
377       if (! (um->flags & UNIX_FLAG_NODAEMON)
378           && daemon (/* chdir to / */ 0,
379                      /* stdin/stdout/stderr -> /dev/null */ 0) < 0)
380         clib_error_return (0, "daemon () fails");
381     }
382   um->unix_config_complete = 1;
383
384   return 0;
385 }
386
387 /* unix { ... } configuration. */
388 VLIB_CONFIG_FUNCTION (unix_config, "unix");
389
390 static clib_error_t *
391 unix_exit (vlib_main_t * vm)
392 {
393   /* Close syslog connection. */
394   closelog ();
395   return 0;
396 }
397
398 VLIB_MAIN_LOOP_EXIT_FUNCTION (unix_exit);
399
400 u8 **vlib_thread_stacks;
401
402 static uword thread0 (uword arg)
403 {
404   vlib_main_t * vm = (vlib_main_t *)arg;
405   unformat_input_t input;
406   int i;
407   
408   unformat_init_command_line (&input, (char **)vm->argv);
409   i = vlib_main (vm, &input);
410   unformat_free (&input);
411   
412   return i;
413  }
414
415 int vlib_unix_main (int argc, char * argv[])
416 {
417   vlib_main_t * vm = &vlib_global_main; /* one and only time for this! */
418   
419   clib_smp_main_t * sm = &clib_smp_main;
420   vlib_thread_main_t * tm = &vlib_thread_main;
421   unformat_input_t input;
422   u8 * thread_stacks;
423   clib_error_t * e;
424   int i;
425
426   vm->argv = (u8 **)argv;
427   vm->name = argv[0];
428   vm->heap_base = clib_mem_get_heap ();
429   ASSERT(vm->heap_base);
430
431   i = vlib_plugin_early_init (vm);
432   if (i)
433     return i;
434   
435   unformat_init_command_line (&input, (char **)vm->argv);
436   if (vm->init_functions_called == 0)
437       vm->init_functions_called = hash_create (0, /* value bytes */ 0);
438   e = vlib_call_all_config_functions (vm, &input, 1 /* early */);
439   if (e != 0)
440     {
441       clib_error_report(e);
442       return 1;
443     }
444   unformat_free (&input);
445
446   /* allocate N x 1mb stacks, aligned e.g. to a 16mb boundary */
447   thread_stacks = clib_mem_alloc_aligned 
448       (tm->n_thread_stacks * VLIB_THREAD_STACK_SIZE,
449        (VLIB_MAX_CPUS << VLIB_LOG2_THREAD_STACK_SIZE));
450
451   sm->vm_base = thread_stacks;
452   sm->log2_n_per_cpu_vm_bytes = VLIB_LOG2_THREAD_STACK_SIZE;
453
454   vec_validate (vlib_thread_stacks, tm->n_thread_stacks - 1);
455   for (i = 0; i < vec_len (vlib_thread_stacks); i++)
456     {
457       vlib_thread_stacks[i] = thread_stacks;
458
459       /* 
460        * Disallow writes to the bottom page of the stack, to
461        * catch stack overflows.
462        */
463       if (mprotect (thread_stacks, clib_mem_get_page_size(), PROT_READ) < 0)
464           clib_unix_warning ("thread stack");
465
466       thread_stacks += VLIB_THREAD_STACK_SIZE;
467     }
468   
469   i = clib_calljmp (thread0, (uword) vm, 
470                     (void *)(vlib_thread_stacks[0] + VLIB_THREAD_STACK_SIZE));
471   return i;
472 }