process.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. process.c -- process management functions
  3. Copyright (C) 1999-2005 Ivo Timmermans,
  4. 2000-2015 Guus Sliepen <guus@tinc-vpn.org>
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include "system.h"
  18. #include "conf.h"
  19. #include "connection.h"
  20. #include "device.h"
  21. #include "edge.h"
  22. #include "logger.h"
  23. #include "net.h"
  24. #include "node.h"
  25. #include "pidfile.h"
  26. #include "process.h"
  27. #include "subnet.h"
  28. #include "utils.h"
  29. #include "xalloc.h"
  30. /* If zero, don't detach from the terminal. */
  31. bool do_detach = true;
  32. bool sighup = false;
  33. bool sigalrm = false;
  34. extern char *identname;
  35. extern char *pidfilename;
  36. extern char **g_argv;
  37. extern bool use_logfile;
  38. #ifndef HAVE_MINGW
  39. static sigset_t emptysigset;
  40. #endif
  41. /* Some functions the less gifted operating systems might lack... */
  42. #ifdef HAVE_MINGW
  43. extern char *identname;
  44. extern char *program_name;
  45. extern char **g_argv;
  46. static SC_HANDLE manager = NULL;
  47. static SC_HANDLE service = NULL;
  48. static SERVICE_STATUS status = {0};
  49. static SERVICE_STATUS_HANDLE statushandle = 0;
  50. bool install_service(void) {
  51. char command[4096] = "\"";
  52. char **argp;
  53. bool space;
  54. SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
  55. manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  56. if(!manager) {
  57. logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
  58. return false;
  59. }
  60. if(!strchr(program_name, '\\')) {
  61. GetCurrentDirectory(sizeof(command) - 1, command + 1);
  62. strncat(command, "\\", sizeof(command) - strlen(command));
  63. }
  64. strncat(command, program_name, sizeof(command) - strlen(command));
  65. strncat(command, "\"", sizeof(command) - strlen(command));
  66. for(argp = g_argv + 1; *argp; argp++) {
  67. space = strchr(*argp, ' ');
  68. strncat(command, " ", sizeof(command) - strlen(command));
  69. if(space) {
  70. strncat(command, "\"", sizeof(command) - strlen(command));
  71. }
  72. strncat(command, *argp, sizeof(command) - strlen(command));
  73. if(space) {
  74. strncat(command, "\"", sizeof(command) - strlen(command));
  75. }
  76. }
  77. service = CreateService(manager, identname, identname,
  78. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
  79. command, NULL, NULL, NULL, NULL, NULL);
  80. if(!service) {
  81. DWORD lasterror = GetLastError();
  82. logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
  83. if(lasterror != ERROR_SERVICE_EXISTS) {
  84. return false;
  85. }
  86. }
  87. if(service) {
  88. ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
  89. logger(LOG_INFO, "%s service installed", identname);
  90. } else {
  91. service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
  92. }
  93. if(!StartService(service, 0, NULL)) {
  94. logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
  95. } else {
  96. logger(LOG_INFO, "%s service started", identname);
  97. }
  98. return true;
  99. }
  100. bool remove_service(void) {
  101. manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  102. if(!manager) {
  103. logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
  104. return false;
  105. }
  106. service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
  107. if(!service) {
  108. logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
  109. return false;
  110. }
  111. if(!ControlService(service, SERVICE_CONTROL_STOP, &status)) {
  112. logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
  113. } else {
  114. logger(LOG_INFO, "%s service stopped", identname);
  115. }
  116. if(!DeleteService(service)) {
  117. logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
  118. return false;
  119. }
  120. logger(LOG_INFO, "%s service removed", identname);
  121. return true;
  122. }
  123. DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
  124. switch(request) {
  125. case SERVICE_CONTROL_INTERROGATE:
  126. SetServiceStatus(statushandle, &status);
  127. return NO_ERROR;
  128. case SERVICE_CONTROL_STOP:
  129. logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
  130. break;
  131. case SERVICE_CONTROL_SHUTDOWN:
  132. logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
  133. break;
  134. default:
  135. logger(LOG_WARNING, "Got unexpected request %d", (int)request);
  136. return ERROR_CALL_NOT_IMPLEMENTED;
  137. }
  138. if(running) {
  139. running = false;
  140. status.dwWaitHint = 30000;
  141. status.dwCurrentState = SERVICE_STOP_PENDING;
  142. SetServiceStatus(statushandle, &status);
  143. return NO_ERROR;
  144. } else {
  145. status.dwWaitHint = 0;
  146. status.dwCurrentState = SERVICE_STOPPED;
  147. SetServiceStatus(statushandle, &status);
  148. exit(1);
  149. }
  150. }
  151. VOID WINAPI run_service(DWORD argc, LPTSTR *argv) {
  152. extern int main2(int argc, char **argv);
  153. status.dwServiceType = SERVICE_WIN32;
  154. status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  155. status.dwWin32ExitCode = 0;
  156. status.dwServiceSpecificExitCode = 0;
  157. status.dwCheckPoint = 0;
  158. statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
  159. if(!statushandle) {
  160. logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
  161. } else {
  162. status.dwWaitHint = 30000;
  163. status.dwCurrentState = SERVICE_START_PENDING;
  164. SetServiceStatus(statushandle, &status);
  165. status.dwWaitHint = 0;
  166. status.dwCurrentState = SERVICE_RUNNING;
  167. SetServiceStatus(statushandle, &status);
  168. main2(argc, argv);
  169. status.dwWaitHint = 0;
  170. status.dwCurrentState = SERVICE_STOPPED;
  171. SetServiceStatus(statushandle, &status);
  172. }
  173. return;
  174. }
  175. bool init_service(void) {
  176. SERVICE_TABLE_ENTRY services[] = {
  177. {identname, run_service},
  178. {NULL, NULL}
  179. };
  180. if(!StartServiceCtrlDispatcher(services)) {
  181. if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  182. return false;
  183. } else {
  184. logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
  185. }
  186. }
  187. return true;
  188. }
  189. #endif
  190. #ifndef HAVE_MINGW
  191. /*
  192. check for an existing tinc for this net, and write pid to pidfile
  193. */
  194. static bool write_pidfile(void) {
  195. pid_t pid;
  196. pid = check_pid(pidfilename);
  197. if(pid) {
  198. if(netname)
  199. fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
  200. netname, (long)pid);
  201. else {
  202. fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
  203. }
  204. return false;
  205. }
  206. /* if it's locked, write-protected, or whatever */
  207. if(!write_pid(pidfilename)) {
  208. fprintf(stderr, "Couldn't write pid file %s: %s\n", pidfilename, strerror(errno));
  209. return false;
  210. }
  211. return true;
  212. }
  213. #endif
  214. /*
  215. kill older tincd for this net
  216. */
  217. bool kill_other(int signal) {
  218. #ifndef HAVE_MINGW
  219. pid_t pid;
  220. pid = read_pid(pidfilename);
  221. if(!pid) {
  222. if(netname)
  223. fprintf(stderr, "No other tincd is running for net `%s'.\n",
  224. netname);
  225. else {
  226. fprintf(stderr, "No other tincd is running.\n");
  227. }
  228. return false;
  229. }
  230. errno = 0; /* No error, sometimes errno is only changed on error */
  231. /* ESRCH is returned when no process with that pid is found */
  232. if(kill(pid, signal) && errno == ESRCH) {
  233. if(netname)
  234. fprintf(stderr, "The tincd for net `%s' is no longer running. ",
  235. netname);
  236. else {
  237. fprintf(stderr, "The tincd is no longer running. ");
  238. }
  239. fprintf(stderr, "Removing stale lock file.\n");
  240. remove_pid(pidfilename);
  241. }
  242. return true;
  243. #else
  244. return remove_service();
  245. #endif
  246. }
  247. /*
  248. Detach from current terminal, write pidfile, kill parent
  249. */
  250. bool detach(void) {
  251. setup_signals();
  252. /* First check if we can open a fresh new pidfile */
  253. #ifndef HAVE_MINGW
  254. if(!write_pidfile()) {
  255. return false;
  256. }
  257. /* If we succeeded in doing that, detach */
  258. closelogger();
  259. #endif
  260. if(do_detach) {
  261. #ifndef HAVE_MINGW
  262. if(daemon(0, 0)) {
  263. fprintf(stderr, "Couldn't detach from terminal: %s",
  264. strerror(errno));
  265. return false;
  266. }
  267. /* Now UPDATE the pid in the pidfile, because we changed it... */
  268. if(!write_pid(pidfilename)) {
  269. fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
  270. return false;
  271. }
  272. #else
  273. if(!statushandle) {
  274. exit(install_service());
  275. }
  276. #endif
  277. }
  278. openlogger(identname, use_logfile ? LOGMODE_FILE : (do_detach ? LOGMODE_SYSLOG : LOGMODE_STDERR));
  279. logger(LOG_NOTICE, "tincd %s starting, debug level %d",
  280. VERSION, debug_level);
  281. return true;
  282. }
  283. #ifdef HAVE_PUTENV
  284. void unputenv(char *p) {
  285. char *e = strchr(p, '=');
  286. if(!e) {
  287. return;
  288. }
  289. int len = e - p;
  290. #ifndef HAVE_UNSETENV
  291. #ifdef HAVE_MINGW
  292. // Windows requires putenv("FOO=") to unset %FOO%
  293. len++;
  294. #endif
  295. #endif
  296. char var[len + 1];
  297. memcpy(var, p, len);
  298. var[len] = 0;
  299. #ifdef HAVE_UNSETENV
  300. unsetenv(var);
  301. #else
  302. // We must keep what we putenv() around in memory.
  303. // To do this without memory leaks, keep things in a list and reuse if possible.
  304. static list_t list = {};
  305. for(list_node_t *node = list.head; node; node = node->next) {
  306. char *data = node->data;
  307. if(!strcmp(data, var)) {
  308. putenv(data);
  309. return;
  310. }
  311. }
  312. char *data = xstrdup(var);
  313. list_insert_tail(&list, data);
  314. putenv(data);
  315. #endif
  316. }
  317. #else
  318. void putenv(const char *p) {}
  319. void unputenv(const char *p) {}
  320. #endif
  321. bool execute_script(const char *name, char **envp) {
  322. #ifdef HAVE_SYSTEM
  323. char *scriptname;
  324. char *interpreter = NULL;
  325. config_t *cfg_interpreter;
  326. int status, len, i;
  327. cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
  328. #ifndef HAVE_MINGW
  329. len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
  330. #else
  331. if(cfg_interpreter) {
  332. len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
  333. } else {
  334. len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
  335. }
  336. #endif
  337. if(len < 0) {
  338. return false;
  339. }
  340. scriptname[len - 1] = '\0';
  341. /* First check if there is a script */
  342. if(access(scriptname + 1, F_OK)) {
  343. free(scriptname);
  344. return true;
  345. }
  346. // Custom scripts interpreter
  347. if(get_config_string(cfg_interpreter, &interpreter)) {
  348. // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
  349. free(scriptname);
  350. len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
  351. free(interpreter);
  352. if(len < 0) {
  353. return false;
  354. }
  355. }
  356. ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
  357. /* Set environment */
  358. for(i = 0; envp[i]; i++) {
  359. putenv(envp[i]);
  360. }
  361. scriptname[len - 1] = '\"';
  362. status = system(scriptname);
  363. free(scriptname);
  364. /* Unset environment */
  365. for(i = 0; envp[i]; i++) {
  366. unputenv(envp[i]);
  367. }
  368. if(status != -1) {
  369. #ifdef WEXITSTATUS
  370. if(WIFEXITED(status)) { /* Child exited by itself */
  371. if(WEXITSTATUS(status)) {
  372. logger(LOG_ERR, "Script %s exited with non-zero status %d",
  373. name, WEXITSTATUS(status));
  374. return false;
  375. }
  376. } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
  377. logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
  378. name, WTERMSIG(status), strsignal(WTERMSIG(status)));
  379. return false;
  380. } else { /* Something strange happened */
  381. logger(LOG_ERR, "Script %s terminated abnormally", name);
  382. return false;
  383. }
  384. #endif
  385. } else {
  386. logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
  387. return false;
  388. }
  389. #endif
  390. return true;
  391. }
  392. /*
  393. Signal handlers.
  394. */
  395. #ifndef HAVE_MINGW
  396. static RETSIGTYPE sigterm_handler(int a) {
  397. (void)a;
  398. logger(LOG_NOTICE, "Got %s signal", "TERM");
  399. if(running) {
  400. running = false;
  401. } else {
  402. exit(1);
  403. }
  404. }
  405. static RETSIGTYPE sigquit_handler(int a) {
  406. (void)a;
  407. logger(LOG_NOTICE, "Got %s signal", "QUIT");
  408. if(running) {
  409. running = false;
  410. } else {
  411. exit(1);
  412. }
  413. }
  414. static RETSIGTYPE fatal_signal_square(int a) {
  415. logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
  416. strsignal(a));
  417. exit(1);
  418. }
  419. static RETSIGTYPE fatal_signal_handler(int a) {
  420. struct sigaction act;
  421. logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
  422. if(do_detach) {
  423. logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
  424. act.sa_handler = fatal_signal_square;
  425. act.sa_mask = emptysigset;
  426. act.sa_flags = 0;
  427. sigaction(SIGSEGV, &act, NULL);
  428. close_network_connections();
  429. sleep(5);
  430. remove_pid(pidfilename);
  431. execvp(g_argv[0], g_argv);
  432. } else {
  433. logger(LOG_NOTICE, "Not restarting.");
  434. exit(1);
  435. }
  436. }
  437. static RETSIGTYPE sighup_handler(int a) {
  438. (void)a;
  439. logger(LOG_NOTICE, "Got %s signal", "HUP");
  440. sighup = true;
  441. }
  442. static RETSIGTYPE sigint_handler(int a) {
  443. (void)a;
  444. static int saved_debug_level = -1;
  445. logger(LOG_NOTICE, "Got %s signal", "INT");
  446. if(saved_debug_level != -1) {
  447. logger(LOG_NOTICE, "Reverting to old debug level (%d)",
  448. saved_debug_level);
  449. debug_level = saved_debug_level;
  450. saved_debug_level = -1;
  451. } else {
  452. logger(LOG_NOTICE,
  453. "Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d.",
  454. debug_level);
  455. saved_debug_level = debug_level;
  456. debug_level = 5;
  457. }
  458. }
  459. static RETSIGTYPE sigalrm_handler(int a) {
  460. (void)a;
  461. logger(LOG_NOTICE, "Got %s signal", "ALRM");
  462. sigalrm = true;
  463. }
  464. static RETSIGTYPE sigusr1_handler(int a) {
  465. (void)a;
  466. dump_connections();
  467. }
  468. static RETSIGTYPE sigusr2_handler(int a) {
  469. (void)a;
  470. devops.dump_stats();
  471. dump_nodes();
  472. dump_edges();
  473. dump_subnets();
  474. }
  475. static RETSIGTYPE sigwinch_handler(int a) {
  476. (void)a;
  477. do_purge = true;
  478. }
  479. static RETSIGTYPE unexpected_signal_handler(int a) {
  480. (void)a;
  481. logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
  482. }
  483. static RETSIGTYPE ignore_signal_handler(int a) {
  484. (void)a;
  485. ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
  486. }
  487. static struct {
  488. int signal;
  489. void (*handler)(int);
  490. } sighandlers[] = {
  491. {SIGHUP, sighup_handler},
  492. {SIGTERM, sigterm_handler},
  493. {SIGQUIT, sigquit_handler},
  494. {SIGSEGV, fatal_signal_handler},
  495. {SIGBUS, fatal_signal_handler},
  496. {SIGILL, fatal_signal_handler},
  497. {SIGPIPE, ignore_signal_handler},
  498. {SIGINT, sigint_handler},
  499. {SIGUSR1, sigusr1_handler},
  500. {SIGUSR2, sigusr2_handler},
  501. {SIGCHLD, ignore_signal_handler},
  502. {SIGALRM, sigalrm_handler},
  503. {SIGWINCH, sigwinch_handler},
  504. {SIGABRT, SIG_DFL},
  505. {0, NULL}
  506. };
  507. #endif
  508. void setup_signals(void) {
  509. #ifndef HAVE_MINGW
  510. int i;
  511. struct sigaction act;
  512. sigemptyset(&emptysigset);
  513. act.sa_handler = NULL;
  514. act.sa_mask = emptysigset;
  515. act.sa_flags = 0;
  516. /* Set a default signal handler for every signal, errors will be
  517. ignored. */
  518. for(i = 1; i < NSIG; i++) {
  519. if(!do_detach) {
  520. act.sa_handler = SIG_DFL;
  521. } else {
  522. act.sa_handler = unexpected_signal_handler;
  523. }
  524. sigaction(i, &act, NULL);
  525. }
  526. /* If we didn't detach, allow coredumps */
  527. if(!do_detach) {
  528. sighandlers[3].handler = SIG_DFL;
  529. }
  530. /* Then, for each known signal that we want to catch, assign a
  531. handler to the signal, with error checking this time. */
  532. for(i = 0; sighandlers[i].signal; i++) {
  533. act.sa_handler = sighandlers[i].handler;
  534. if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
  535. fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
  536. sighandlers[i].signal, strsignal(sighandlers[i].signal),
  537. strerror(errno));
  538. }
  539. #endif
  540. }