starter: Add --attach-gdb option to usage text
[strongswan.git] / src / starter / starter.c
1 /* strongSwan IPsec starter
2 * Copyright (C) 2001-2002 Mathieu Lafon - Arkoon Network Security
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 */
14
15 #include <sys/select.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <sys/stat.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <signal.h>
22 #include <syslog.h>
23 #include <unistd.h>
24 #include <sys/time.h>
25 #include <time.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <pwd.h>
30 #include <grp.h>
31 #include <pthread.h>
32
33 #include <library.h>
34 #include <hydra.h>
35 #include <utils/backtrace.h>
36 #include <threading/thread.h>
37 #include <utils/debug.h>
38
39 #include "confread.h"
40 #include "files.h"
41 #include "starterstroke.h"
42 #include "invokecharon.h"
43 #include "netkey.h"
44 #include "klips.h"
45 #include "cmp.h"
46
47 #ifndef LOG_AUTHPRIV
48 #define LOG_AUTHPRIV LOG_AUTH
49 #endif
50
51 #define CHARON_RESTART_DELAY 5
52
53 /* logging */
54 static bool log_to_stderr = TRUE;
55 static bool log_to_syslog = TRUE;
56 static level_t current_loglevel = 1;
57
58 /**
59 * logging function for scepclient
60 */
61 static void starter_dbg(debug_t group, level_t level, char *fmt, ...)
62 {
63 char buffer[8192];
64 char *current = buffer, *next;
65 va_list args;
66
67 if (level <= current_loglevel)
68 {
69 if (log_to_stderr)
70 {
71 va_start(args, fmt);
72 vfprintf(stderr, fmt, args);
73 va_end(args);
74 fprintf(stderr, "\n");
75 }
76 if (log_to_syslog)
77 {
78 /* write in memory buffer first */
79 va_start(args, fmt);
80 vsnprintf(buffer, sizeof(buffer), fmt, args);
81 va_end(args);
82
83 /* do a syslog with every line */
84 while (current)
85 {
86 next = strchr(current, '\n');
87 if (next)
88 {
89 *(next++) = '\0';
90 }
91 syslog(LOG_INFO, "%s\n", current);
92 current = next;
93 }
94 }
95 }
96 }
97
98 /**
99 * Initialize logging to stderr/syslog
100 */
101 static void init_log(const char *program)
102 {
103 dbg = starter_dbg;
104
105 if (log_to_stderr)
106 {
107 setbuf(stderr, NULL);
108 }
109 if (log_to_syslog)
110 {
111 openlog(program, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_AUTHPRIV);
112 }
113 }
114
115 /**
116 * Deinitialize logging to syslog
117 */
118 static void close_log()
119 {
120 if (log_to_syslog)
121 {
122 closelog();
123 }
124 }
125
126 /**
127 * Return codes defined by Linux Standard Base Core Specification 3.1
128 * in section 20.2. Init Script Actions
129 */
130 #define LSB_RC_SUCCESS 0 /* success */
131 #define LSB_RC_FAILURE 1 /* generic or unspecified error */
132 #define LSB_RC_INVALID_ARGUMENT 2 /* invalid or excess argument(s) */
133 #define LSB_RC_NOT_IMPLEMENTED 3 /* unimplemented feature (reload) */
134 #define LSB_RC_NOT_ALLOWED 4 /* user had insufficient privilege */
135 #define LSB_RC_NOT_INSTALLED 5 /* program is not installed */
136 #define LSB_RC_NOT_CONFIGURED 6 /* program is not configured */
137 #define LSB_RC_NOT_RUNNING 7 /* program is not running */
138
139 #define FLAG_ACTION_START_PLUTO 0x01
140 #define FLAG_ACTION_UPDATE 0x02
141 #define FLAG_ACTION_RELOAD 0x04
142 #define FLAG_ACTION_QUIT 0x08
143 #define FLAG_ACTION_LISTEN 0x10
144 #define FLAG_ACTION_START_CHARON 0x20
145
146 static unsigned int _action_ = 0;
147
148 /**
149 * Handle signals in the main thread
150 */
151 static void signal_handler(int signal)
152 {
153 switch (signal)
154 {
155 case SIGCHLD:
156 {
157 int status, exit_status = 0;
158 pid_t pid;
159 char *name = NULL;
160
161 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
162 {
163 if (pid == starter_charon_pid())
164 {
165 name = " (Charon)";
166 }
167 if (WIFSIGNALED(status))
168 {
169 DBG2(DBG_APP, "child %d%s has been killed by sig %d\n",
170 pid, name?name:"", WTERMSIG(status));
171 }
172 else if (WIFSTOPPED(status))
173 {
174 DBG2(DBG_APP, "child %d%s has been stopped by sig %d\n",
175 pid, name?name:"", WSTOPSIG(status));
176 }
177 else if (WIFEXITED(status))
178 {
179 exit_status = WEXITSTATUS(status);
180 if (exit_status >= SS_RC_FIRST && exit_status <= SS_RC_LAST)
181 {
182 _action_ = FLAG_ACTION_QUIT;
183 }
184 DBG2(DBG_APP, "child %d%s has quit (exit code %d)\n",
185 pid, name?name:"", exit_status);
186 }
187 else
188 {
189 DBG2(DBG_APP, "child %d%s has quit", pid, name?name:"");
190 }
191 if (pid == starter_charon_pid())
192 {
193 starter_charon_sigchild(pid, exit_status);
194 }
195 }
196 }
197 break;
198
199 case SIGALRM:
200 _action_ |= FLAG_ACTION_START_CHARON;
201 break;
202
203 case SIGHUP:
204 _action_ |= FLAG_ACTION_UPDATE;
205 break;
206
207 case SIGTERM:
208 case SIGQUIT:
209 case SIGINT:
210 _action_ |= FLAG_ACTION_QUIT;
211 break;
212
213 case SIGUSR1:
214 _action_ |= FLAG_ACTION_RELOAD;
215 _action_ |= FLAG_ACTION_UPDATE;
216 break;
217
218 default:
219 DBG1(DBG_APP, "fsig(): unknown signal %d -- investigate", signal);
220 break;
221 }
222 }
223
224 /**
225 * Handle fatal signals raised by threads
226 */
227 static void fatal_signal_handler(int signal)
228 {
229 backtrace_t *backtrace;
230
231 DBG1(DBG_APP, "thread %u received %d", thread_current_id(), signal);
232 backtrace = backtrace_create(2);
233 backtrace->log(backtrace, stderr, TRUE);
234 backtrace->destroy(backtrace);
235
236 DBG1(DBG_APP, "killing ourself, received critical signal");
237 abort();
238 }
239
240 #ifdef GENERATE_SELFCERT
241 static void generate_selfcert()
242 {
243 struct stat stb;
244
245 /* if ipsec.secrets file is missing then generate RSA default key pair */
246 if (stat(SECRETS_FILE, &stb) != 0)
247 {
248 mode_t oldmask;
249 FILE *f;
250 uid_t uid = 0;
251 gid_t gid = 0;
252
253 #ifdef IPSEC_GROUP
254 {
255 char buf[1024];
256 struct group group, *grp;
257
258 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) == 0 && grp)
259 {
260 gid = grp->gr_gid;
261 }
262 }
263 #endif
264 #ifdef IPSEC_USER
265 {
266 char buf[1024];
267 struct passwd passwd, *pwp;
268
269 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) == 0 && pwp)
270 {
271 uid = pwp->pw_uid;
272 }
273 }
274 #endif
275 setegid(gid);
276 seteuid(uid);
277 ignore_result(system("ipsec scepclient --out pkcs1 --out cert-self --quiet"));
278 seteuid(0);
279 setegid(0);
280
281 /* ipsec.secrets is root readable only */
282 oldmask = umask(0066);
283
284 f = fopen(SECRETS_FILE, "w");
285 if (f)
286 {
287 fprintf(f, "# /etc/ipsec.secrets - strongSwan IPsec secrets file\n");
288 fprintf(f, "\n");
289 fprintf(f, ": RSA myKey.der\n");
290 fclose(f);
291 }
292 ignore_result(chown(SECRETS_FILE, uid, gid));
293 umask(oldmask);
294 }
295 }
296 #endif /* GENERATE_SELFCERT */
297
298 static bool check_pid(char *pid_file)
299 {
300 struct stat stb;
301 FILE *pidfile;
302
303 if (stat(pid_file, &stb) == 0)
304 {
305 pidfile = fopen(pid_file, "r");
306 if (pidfile)
307 {
308 char buf[64];
309 pid_t pid = 0;
310 memset(buf, 0, sizeof(buf));
311 if (fread(buf, 1, sizeof(buf), pidfile))
312 {
313 buf[sizeof(buf) - 1] = '\0';
314 pid = atoi(buf);
315 }
316 fclose(pidfile);
317 if (pid && kill(pid, 0) == 0)
318 { /* such a process is running */
319 return TRUE;
320 }
321 }
322 DBG1(DBG_APP, "removing pidfile '%s', process not running", pid_file);
323 unlink(pid_file);
324 }
325 return FALSE;
326 }
327
328 static void usage(char *name)
329 {
330 fprintf(stderr, "Usage: starter [--nofork] [--auto-update <sec>]\n"
331 " [--debug|--debug-more|--debug-all|--nolog]\n"
332 " [--attach-gdb]\n");
333 exit(LSB_RC_INVALID_ARGUMENT);
334 }
335
336 int main (int argc, char **argv)
337 {
338 starter_config_t *cfg = NULL;
339 starter_config_t *new_cfg;
340 starter_conn_t *conn, *conn2;
341 starter_ca_t *ca, *ca2;
342
343 struct sigaction action;
344 struct stat stb;
345
346 int i;
347 int id = 1;
348 struct timespec ts;
349 unsigned long auto_update = 0;
350 time_t last_reload;
351 bool no_fork = FALSE;
352 bool attach_gdb = FALSE;
353 bool load_warning = FALSE;
354
355 library_init(NULL);
356 atexit(library_deinit);
357
358 libhydra_init("starter");
359 atexit(libhydra_deinit);
360
361 /* parse command line */
362 for (i = 1; i < argc; i++)
363 {
364 if (streq(argv[i], "--debug"))
365 {
366 current_loglevel = 2;
367 }
368 else if (streq(argv[i], "--debug-more"))
369 {
370 current_loglevel = 3;
371 }
372 else if (streq(argv[i], "--debug-all"))
373 {
374 current_loglevel = 4;
375 }
376 else if (streq(argv[i], "--nolog"))
377 {
378 current_loglevel = 0;
379 }
380 else if (streq(argv[i], "--nofork"))
381 {
382 no_fork = TRUE;
383 }
384 else if (streq(argv[i], "--attach-gdb"))
385 {
386 no_fork = TRUE;
387 attach_gdb = TRUE;
388 }
389 else if (streq(argv[i], "--auto-update") && i+1 < argc)
390 {
391 auto_update = atoi(argv[++i]);
392 if (!auto_update)
393 usage(argv[0]);
394 }
395 else
396 {
397 usage(argv[0]);
398 }
399 }
400
401 init_log("ipsec_starter");
402
403 DBG1(DBG_APP, "Starting %sSwan "VERSION" IPsec [starter]...",
404 lib->settings->get_bool(lib->settings,
405 "charon.i_dont_care_about_security_and_use_aggressive_mode_psk",
406 FALSE) ? "weak" : "strong");
407
408 #ifdef LOAD_WARNING
409 load_warning = TRUE;
410 #endif
411
412 if (lib->settings->get_bool(lib->settings, "starter.load_warning", load_warning))
413 {
414 if (lib->settings->get_str(lib->settings, "charon.load", NULL))
415 {
416 DBG1(DBG_APP, "!! Your strongswan.conf contains manual plugin load options for charon.");
417 DBG1(DBG_APP, "!! This is recommended for experts only, see");
418 DBG1(DBG_APP, "!! http://wiki.strongswan.org/projects/strongswan/wiki/PluginLoad");
419 }
420 }
421
422 /* verify that we can start */
423 if (getuid() != 0)
424 {
425 DBG1(DBG_APP, "permission denied (must be superuser)");
426 exit(LSB_RC_NOT_ALLOWED);
427 }
428
429 if (check_pid(CHARON_PID_FILE))
430 {
431 DBG1(DBG_APP, "charon is already running (%s exists) -- skipping charon start",
432 CHARON_PID_FILE);
433 }
434 else
435 {
436 _action_ |= FLAG_ACTION_START_CHARON;
437 }
438 if (stat(DEV_RANDOM, &stb) != 0)
439 {
440 DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_RANDOM);
441 exit(LSB_RC_FAILURE);
442 }
443
444 if (stat(DEV_URANDOM, &stb)!= 0)
445 {
446 DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_URANDOM);
447 exit(LSB_RC_FAILURE);
448 }
449
450 cfg = confread_load(CONFIG_FILE);
451 if (cfg == NULL || cfg->err > 0)
452 {
453 DBG1(DBG_APP, "unable to start strongSwan -- fatal errors in config");
454 if (cfg)
455 {
456 confread_free(cfg);
457 }
458 exit(LSB_RC_INVALID_ARGUMENT);
459 }
460
461 /* determine if we have a native netkey IPsec stack */
462 if (!starter_netkey_init())
463 {
464 DBG1(DBG_APP, "no netkey IPsec stack detected");
465 if (!starter_klips_init())
466 {
467 DBG1(DBG_APP, "no KLIPS IPsec stack detected");
468 DBG1(DBG_APP, "no known IPsec stack detected, ignoring!");
469 }
470 }
471
472 last_reload = time_monotonic(NULL);
473
474 if (check_pid(STARTER_PID_FILE))
475 {
476 DBG1(DBG_APP, "starter is already running (%s exists) -- no fork done",
477 STARTER_PID_FILE);
478 confread_free(cfg);
479 exit(LSB_RC_SUCCESS);
480 }
481
482 #ifdef GENERATE_SELFCERT
483 generate_selfcert();
484 #endif
485
486 /* fork if we're not debugging stuff */
487 if (!no_fork)
488 {
489 log_to_stderr = FALSE;
490
491 switch (fork())
492 {
493 case 0:
494 {
495 int fnull;
496
497 close_log();
498 closefrom(3);
499
500 fnull = open("/dev/null", O_RDWR);
501 if (fnull >= 0)
502 {
503 dup2(fnull, STDIN_FILENO);
504 dup2(fnull, STDOUT_FILENO);
505 dup2(fnull, STDERR_FILENO);
506 close(fnull);
507 }
508
509 setsid();
510 init_log("ipsec_starter");
511 }
512 break;
513 case -1:
514 DBG1(DBG_APP, "can't fork: %s", strerror(errno));
515 break;
516 default:
517 confread_free(cfg);
518 exit(LSB_RC_SUCCESS);
519 }
520 }
521
522 /* save pid file in /var/run/starter.pid */
523 {
524 FILE *fd = fopen(STARTER_PID_FILE, "w");
525
526 if (fd)
527 {
528 fprintf(fd, "%u\n", getpid());
529 fclose(fd);
530 }
531 }
532
533 /* we handle these signals only in pselect() */
534 memset(&action, 0, sizeof(action));
535 sigemptyset(&action.sa_mask);
536 sigaddset(&action.sa_mask, SIGHUP);
537 sigaddset(&action.sa_mask, SIGINT);
538 sigaddset(&action.sa_mask, SIGTERM);
539 sigaddset(&action.sa_mask, SIGQUIT);
540 sigaddset(&action.sa_mask, SIGALRM);
541 sigaddset(&action.sa_mask, SIGUSR1);
542 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
543
544 /* install a handler for fatal signals */
545 action.sa_handler = fatal_signal_handler;
546 sigaction(SIGSEGV, &action, NULL);
547 sigaction(SIGILL, &action, NULL);
548 sigaction(SIGBUS, &action, NULL);
549 action.sa_handler = SIG_IGN;
550 sigaction(SIGPIPE, &action, NULL);
551
552 /* install main signal handler */
553 action.sa_handler = signal_handler;
554 sigaction(SIGHUP, &action, NULL);
555 sigaction(SIGINT, &action, NULL);
556 sigaction(SIGTERM, &action, NULL);
557 sigaction(SIGQUIT, &action, NULL);
558 sigaction(SIGALRM, &action, NULL);
559 sigaction(SIGUSR1, &action, NULL);
560 /* this is not blocked above as we want to receive it asynchronously */
561 sigaction(SIGCHLD, &action, NULL);
562
563 /* empty mask for pselect() call below */
564 sigemptyset(&action.sa_mask);
565
566 for (;;)
567 {
568 /*
569 * Stop charon (if started) and exit
570 */
571 if (_action_ & FLAG_ACTION_QUIT)
572 {
573 if (starter_charon_pid())
574 {
575 starter_stop_charon();
576 }
577 starter_netkey_cleanup();
578 confread_free(cfg);
579 unlink(STARTER_PID_FILE);
580 DBG1(DBG_APP, "ipsec starter stopped");
581 close_log();
582 exit(LSB_RC_SUCCESS);
583 }
584
585 /*
586 * Delete all connections. Will be added below
587 */
588 if (_action_ & FLAG_ACTION_RELOAD)
589 {
590 if (starter_charon_pid())
591 {
592 for (conn = cfg->conn_first; conn; conn = conn->next)
593 {
594 if (conn->state == STATE_ADDED)
595 {
596 if (starter_charon_pid())
597 {
598 if (conn->startup == STARTUP_ROUTE)
599 {
600 starter_stroke_unroute_conn(conn);
601 }
602 starter_stroke_del_conn(conn);
603 }
604 conn->state = STATE_TO_ADD;
605 }
606 }
607 for (ca = cfg->ca_first; ca; ca = ca->next)
608 {
609 if (ca->state == STATE_ADDED)
610 {
611 if (starter_charon_pid())
612 {
613 starter_stroke_del_ca(ca);
614 }
615 ca->state = STATE_TO_ADD;
616 }
617 }
618 }
619 _action_ &= ~FLAG_ACTION_RELOAD;
620 }
621
622 /*
623 * Update configuration
624 */
625 if (_action_ & FLAG_ACTION_UPDATE)
626 {
627 DBG2(DBG_APP, "Reloading config...");
628 new_cfg = confread_load(CONFIG_FILE);
629
630 if (new_cfg && (new_cfg->err == 0))
631 {
632 /* Switch to new config. New conn will be loaded below */
633
634 /* Look for new connections that are already loaded */
635 for (conn = cfg->conn_first; conn; conn = conn->next)
636 {
637 if (conn->state == STATE_ADDED)
638 {
639 for (conn2 = new_cfg->conn_first; conn2; conn2 = conn2->next)
640 {
641 if (conn2->state == STATE_TO_ADD && starter_cmp_conn(conn, conn2))
642 {
643 conn->state = STATE_REPLACED;
644 conn2->state = STATE_ADDED;
645 conn2->id = conn->id;
646 break;
647 }
648 }
649 }
650 }
651
652 /* Remove conn sections that have become unused */
653 for (conn = cfg->conn_first; conn; conn = conn->next)
654 {
655 if (conn->state == STATE_ADDED)
656 {
657 if (starter_charon_pid())
658 {
659 if (conn->startup == STARTUP_ROUTE)
660 {
661 starter_stroke_unroute_conn(conn);
662 }
663 starter_stroke_del_conn(conn);
664 }
665 }
666 }
667
668 /* Look for new ca sections that are already loaded */
669 for (ca = cfg->ca_first; ca; ca = ca->next)
670 {
671 if (ca->state == STATE_ADDED)
672 {
673 for (ca2 = new_cfg->ca_first; ca2; ca2 = ca2->next)
674 {
675 if (ca2->state == STATE_TO_ADD && starter_cmp_ca(ca, ca2))
676 {
677 ca->state = STATE_REPLACED;
678 ca2->state = STATE_ADDED;
679 break;
680 }
681 }
682 }
683 }
684
685 /* Remove ca sections that have become unused */
686 for (ca = cfg->ca_first; ca; ca = ca->next)
687 {
688 if (ca->state == STATE_ADDED)
689 {
690 if (starter_charon_pid())
691 {
692 starter_stroke_del_ca(ca);
693 }
694 }
695 }
696 confread_free(cfg);
697 cfg = new_cfg;
698 }
699 else
700 {
701 DBG1(DBG_APP, "can't reload config file due to errors -- keeping old one");
702 if (new_cfg)
703 {
704 confread_free(new_cfg);
705 }
706 }
707 _action_ &= ~FLAG_ACTION_UPDATE;
708 last_reload = time_monotonic(NULL);
709 }
710
711 /*
712 * Start charon
713 */
714 if (_action_ & FLAG_ACTION_START_CHARON)
715 {
716 if (cfg->setup.charonstart && !starter_charon_pid())
717 {
718 DBG2(DBG_APP, "Attempting to start charon...");
719 if (starter_start_charon(cfg, no_fork, attach_gdb))
720 {
721 /* schedule next try */
722 alarm(CHARON_RESTART_DELAY);
723 }
724 starter_stroke_configure(cfg);
725 }
726 _action_ &= ~FLAG_ACTION_START_CHARON;
727
728 for (ca = cfg->ca_first; ca; ca = ca->next)
729 {
730 if (ca->state == STATE_ADDED)
731 {
732 ca->state = STATE_TO_ADD;
733 }
734 }
735
736 for (conn = cfg->conn_first; conn; conn = conn->next)
737 {
738 if (conn->state == STATE_ADDED)
739 {
740 conn->state = STATE_TO_ADD;
741 }
742 }
743 }
744
745 /*
746 * Add stale conn and ca sections
747 */
748 if (starter_charon_pid())
749 {
750 for (ca = cfg->ca_first; ca; ca = ca->next)
751 {
752 if (ca->state == STATE_TO_ADD)
753 {
754 if (starter_charon_pid())
755 {
756 starter_stroke_add_ca(ca);
757 }
758 ca->state = STATE_ADDED;
759 }
760 }
761
762 for (conn = cfg->conn_first; conn; conn = conn->next)
763 {
764 if (conn->state == STATE_TO_ADD)
765 {
766 if (conn->id == 0)
767 {
768 /* affect new unique id */
769 conn->id = id++;
770 }
771 if (starter_charon_pid())
772 {
773 starter_stroke_add_conn(cfg, conn);
774 }
775 conn->state = STATE_ADDED;
776
777 if (conn->startup == STARTUP_START)
778 {
779 if (starter_charon_pid())
780 {
781 starter_stroke_initiate_conn(conn);
782 }
783 }
784 else if (conn->startup == STARTUP_ROUTE)
785 {
786 if (starter_charon_pid())
787 {
788 starter_stroke_route_conn(conn);
789 }
790 }
791 }
792 }
793 }
794
795 /*
796 * If auto_update activated, when to stop select
797 */
798 if (auto_update)
799 {
800 time_t now = time_monotonic(NULL);
801
802 ts.tv_sec = (now < last_reload + auto_update) ?
803 (last_reload + auto_update - now) : 0;
804 ts.tv_nsec = 0;
805 }
806
807 /*
808 * Wait for something to happen
809 */
810 if (pselect(0, NULL, NULL, NULL, auto_update ? &ts : NULL,
811 &action.sa_mask) == 0)
812 {
813 /* timeout -> auto_update */
814 _action_ |= FLAG_ACTION_UPDATE;
815 }
816 }
817 exit(LSB_RC_SUCCESS);
818 }
819