invitation.c: fix socket error checking on Windows
[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 "conf.h"
24 #include "connection.h"
25 #include "control.h"
26 #include "device.h"
27 #include "edge.h"
28 #include "event.h"
29 #include "logger.h"
30 #include "names.h"
31 #include "net.h"
32 #include "node.h"
33 #include "process.h"
34 #include "subnet.h"
35 #include "utils.h"
36 #include "xalloc.h"
37 #include "version.h"
38
39 /* If zero, don't detach from the terminal. */
40 bool do_detach = true;
41 bool sigalrm = false;
42
43 extern char **g_argv;
44 extern bool use_logfile;
45 extern bool use_syslog;
46
47 /* Some functions the less gifted operating systems might lack... */
48
49 #ifdef HAVE_MINGW
50 static SC_HANDLE manager = NULL;
51 static SC_HANDLE service = NULL;
52 static SERVICE_STATUS status = {0};
53 static SERVICE_STATUS_HANDLE statushandle = 0;
54
55 static bool install_service(void) {
56         char command[4096] = "\"";
57         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
58
59         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
60
61         if(!manager) {
62                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
63                 return false;
64         }
65
66         HMODULE module = GetModuleHandle(NULL);
67         GetModuleFileName(module, command + 1, sizeof(command) - 1);
68         command[sizeof(command) - 1] = 0;
69
70         strncat(command, "\"", sizeof(command) - strlen(command));
71
72         for(char **argp = g_argv + 1; *argp; argp++) {
73                 char *space = strchr(*argp, ' ');
74                 strncat(command, " ", sizeof(command) - strlen(command));
75
76                 if(space) {
77                         strncat(command, "\"", sizeof(command) - strlen(command));
78                 }
79
80                 strncat(command, *argp, sizeof(command) - strlen(command));
81
82                 if(space) {
83                         strncat(command, "\"", sizeof(command) - strlen(command));
84                 }
85         }
86
87         service = CreateService(manager, identname, identname,
88                                 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
89                                 command, NULL, NULL, NULL, NULL, NULL);
90
91         if(!service) {
92                 DWORD lasterror = GetLastError();
93                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
94
95                 if(lasterror != ERROR_SERVICE_EXISTS) {
96                         return false;
97                 }
98         }
99
100         if(service) {
101                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
102                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service installed", identname);
103         } else {
104                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
105         }
106
107         if(!StartService(service, 0, NULL)) {
108                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
109         } else {
110                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service started", identname);
111         }
112
113         return true;
114 }
115
116 io_t stop_io;
117
118 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID data, LPVOID context) {
119         (void)type;
120         (void)data;
121         (void)context;
122
123         switch(request) {
124         case SERVICE_CONTROL_INTERROGATE:
125                 SetServiceStatus(statushandle, &status);
126                 return NO_ERROR;
127
128         case SERVICE_CONTROL_STOP:
129                 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
130                 break;
131
132         case SERVICE_CONTROL_SHUTDOWN:
133                 logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
134                 break;
135
136         default:
137                 logger(DEBUG_ALWAYS, LOG_WARNING, "Got unexpected request %d", (int)request);
138                 return ERROR_CALL_NOT_IMPLEMENTED;
139         }
140
141         status.dwWaitHint = 1000;
142         status.dwCurrentState = SERVICE_STOP_PENDING;
143         SetServiceStatus(statushandle, &status);
144
145         if(WSASetEvent(stop_io.event) == FALSE) {
146                 abort();
147         }
148
149         return NO_ERROR;
150 }
151
152 VOID WINAPI run_service(DWORD argc, LPTSTR *argv) {
153         extern int main2(int argc, char **argv);
154
155         status.dwServiceType = SERVICE_WIN32;
156         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
157         status.dwWin32ExitCode = 0;
158         status.dwServiceSpecificExitCode = 0;
159         status.dwCheckPoint = 0;
160
161         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
162
163         if(!statushandle) {
164                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
165         } else {
166                 status.dwWaitHint = 30000;
167                 status.dwCurrentState = SERVICE_START_PENDING;
168                 SetServiceStatus(statushandle, &status);
169
170                 status.dwWaitHint = 0;
171                 status.dwCurrentState = SERVICE_RUNNING;
172                 SetServiceStatus(statushandle, &status);
173
174                 main2(argc, argv);
175
176                 status.dwWaitHint = 0;
177                 status.dwCurrentState = SERVICE_STOPPED;
178                 SetServiceStatus(statushandle, &status);
179         }
180
181         return;
182 }
183
184 bool init_service(void) {
185         SERVICE_TABLE_ENTRY services[] = {
186                 {identname, run_service},
187                 {NULL, NULL}
188         };
189
190         if(!StartServiceCtrlDispatcher(services)) {
191                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
192                         return false;
193                 } else {
194                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
195                 }
196         }
197
198         return true;
199 }
200 #endif
201
202 /*
203   Detach from current terminal
204 */
205 bool detach(void) {
206         logmode_t logmode;
207
208 #ifndef HAVE_MINGW
209         signal(SIGPIPE, SIG_IGN);
210         signal(SIGUSR1, SIG_IGN);
211         signal(SIGUSR2, SIG_IGN);
212         signal(SIGWINCH, SIG_IGN);
213
214         closelogger();
215 #endif
216
217         if(do_detach) {
218 #ifndef HAVE_MINGW
219
220                 if(daemon(1, 0)) {
221                         logger(DEBUG_ALWAYS, LOG_ERR, "Couldn't detach from terminal: %s", strerror(errno));
222                         return false;
223                 }
224
225 #else
226
227                 if(!statushandle) {
228                         exit(!install_service());
229                 }
230
231 #endif
232         }
233
234         if(use_logfile) {
235                 logmode = LOGMODE_FILE;
236         } else if(use_syslog || do_detach) {
237                 logmode = LOGMODE_SYSLOG;
238         } else {
239                 logmode = LOGMODE_STDERR;
240         }
241
242         openlogger(identname, logmode);
243
244         logger(DEBUG_ALWAYS, LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
245                BUILD_VERSION, BUILD_DATE, BUILD_TIME, debug_level);
246
247         return true;
248 }