Fix UBSAN warnings about conversions and overflows.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2018 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "logger.h"
24 #include "names.h"
25 #include "process.h"
26 #include "version.h"
27
28 #ifdef HAVE_MINGW
29 #include "utils.h"
30 #endif
31
32 /* If zero, don't detach from the terminal. */
33 bool do_detach = true;
34
35 extern char **g_argv;
36 extern bool use_logfile;
37 extern bool use_syslog;
38
39 /* Some functions the less gifted operating systems might lack... */
40
41 #ifdef HAVE_MINGW
42 static SC_HANDLE manager = NULL;
43 static SC_HANDLE service = NULL;
44 static SERVICE_STATUS status = {0};
45 static SERVICE_STATUS_HANDLE statushandle = 0;
46
47 static bool install_service(void) {
48         char command[4096] = "\"";
49         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
50
51         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
52
53         if(!manager) {
54                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
55                 return false;
56         }
57
58         HMODULE module = GetModuleHandle(NULL);
59         GetModuleFileName(module, command + 1, sizeof(command) - 1);
60         command[sizeof(command) - 1] = 0;
61
62         strncat(command, "\"", sizeof(command) - strlen(command));
63
64         for(char **argp = g_argv + 1; *argp; argp++) {
65                 char *space = strchr(*argp, ' ');
66                 strncat(command, " ", sizeof(command) - strlen(command));
67
68                 if(space) {
69                         strncat(command, "\"", sizeof(command) - strlen(command));
70                 }
71
72                 strncat(command, *argp, sizeof(command) - strlen(command));
73
74                 if(space) {
75                         strncat(command, "\"", sizeof(command) - strlen(command));
76                 }
77         }
78
79         service = CreateService(manager, identname, identname,
80                                 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
81                                 command, NULL, NULL, NULL, NULL, NULL);
82
83         if(!service) {
84                 DWORD lasterror = GetLastError();
85                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
86
87                 if(lasterror != ERROR_SERVICE_EXISTS) {
88                         return false;
89                 }
90         }
91
92         if(service) {
93                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
94                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service installed", identname);
95         } else {
96                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
97         }
98
99         if(!StartService(service, 0, NULL)) {
100                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
101         } else {
102                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service started", identname);
103         }
104
105         return true;
106 }
107
108 io_t stop_io;
109
110 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID data, LPVOID context) {
111         (void)type;
112         (void)data;
113         (void)context;
114
115         switch(request) {
116         case SERVICE_CONTROL_INTERROGATE:
117                 SetServiceStatus(statushandle, &status);
118                 return NO_ERROR;
119
120         case SERVICE_CONTROL_STOP:
121                 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
122                 break;
123
124         case SERVICE_CONTROL_SHUTDOWN:
125                 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
126                 break;
127
128         default:
129                 logger(DEBUG_ALWAYS, LOG_WARNING, "Got unexpected request %d", (int)request);
130                 return ERROR_CALL_NOT_IMPLEMENTED;
131         }
132
133         status.dwWaitHint = 1000;
134         status.dwCurrentState = SERVICE_STOP_PENDING;
135         SetServiceStatus(statushandle, &status);
136
137         if(WSASetEvent(stop_io.event) == FALSE) {
138                 abort();
139         }
140
141         return NO_ERROR;
142 }
143
144 VOID WINAPI run_service(DWORD argc, LPTSTR *argv) {
145         extern int main2(int argc, char **argv);
146
147         status.dwServiceType = SERVICE_WIN32;
148         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
149         status.dwWin32ExitCode = 0;
150         status.dwServiceSpecificExitCode = 0;
151         status.dwCheckPoint = 0;
152
153         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
154
155         if(!statushandle) {
156                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
157         } else {
158                 status.dwWaitHint = 30000;
159                 status.dwCurrentState = SERVICE_START_PENDING;
160                 SetServiceStatus(statushandle, &status);
161
162                 status.dwWaitHint = 0;
163                 status.dwCurrentState = SERVICE_RUNNING;
164                 SetServiceStatus(statushandle, &status);
165
166                 main2(argc, argv);
167
168                 status.dwWaitHint = 0;
169                 status.dwCurrentState = SERVICE_STOPPED;
170                 SetServiceStatus(statushandle, &status);
171         }
172
173         return;
174 }
175
176 bool init_service(void) {
177         SERVICE_TABLE_ENTRY services[] = {
178                 {identname, run_service},
179                 {NULL, NULL}
180         };
181
182         if(!StartServiceCtrlDispatcher(services)) {
183                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
184                         return false;
185                 } else {
186                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
187                 }
188         }
189
190         return true;
191 }
192 #endif
193
194 /*
195   Detach from current terminal
196 */
197 bool detach(void) {
198         logmode_t logmode;
199
200 #ifndef HAVE_MINGW
201         signal(SIGPIPE, SIG_IGN);
202         signal(SIGUSR1, SIG_IGN);
203         signal(SIGUSR2, SIG_IGN);
204         signal(SIGWINCH, SIG_IGN);
205
206         closelogger();
207 #endif
208
209         if(do_detach) {
210 #ifndef HAVE_MINGW
211
212                 if(daemon(1, 0)) {
213                         logger(DEBUG_ALWAYS, LOG_ERR, "Couldn't detach from terminal: %s", strerror(errno));
214                         return false;
215                 }
216
217 #else
218
219                 if(!statushandle) {
220                         exit(!install_service());
221                 }
222
223 #endif
224         }
225
226         if(use_logfile) {
227                 logmode = LOGMODE_FILE;
228         } else if(use_syslog || do_detach) {
229                 logmode = LOGMODE_SYSLOG;
230         } else {
231                 logmode = LOGMODE_STDERR;
232         }
233
234         openlogger(identname, logmode);
235
236         logger(DEBUG_ALWAYS, LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
237                BUILD_VERSION, BUILD_DATE, BUILD_TIME, debug_level);
238
239         return true;
240 }