Fix starting tinc as a service on Windows.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2013 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         if(!manager) {
61                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
62                 return false;
63         }
64
65         HMODULE module = GetModuleHandle(NULL);
66         GetModuleFileName(module, command + 1, sizeof command - 1);
67         command[sizeof command - 1] = 0;
68
69         strncat(command, "\"", sizeof command - strlen(command));
70
71         for(char **argp = g_argv + 1; *argp; argp++) {
72                 char *space = strchr(*argp, ' ');
73                 strncat(command, " ", sizeof command - strlen(command));
74
75                 if(space)
76                         strncat(command, "\"", sizeof command - strlen(command));
77
78                 strncat(command, *argp, sizeof command - strlen(command));
79
80                 if(space)
81                         strncat(command, "\"", sizeof command - strlen(command));
82         }
83
84         service = CreateService(manager, identname, identname,
85                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
86                         command, NULL, NULL, NULL, NULL, NULL);
87
88         if(!service) {
89                 DWORD lasterror = GetLastError();
90                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
91                 if(lasterror != ERROR_SERVICE_EXISTS)
92                         return false;
93         }
94
95         if(service) {
96                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
97                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service installed", identname);
98         } else {
99                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
100         }
101
102         if(!StartService(service, 0, NULL))
103                 logger(DEBUG_ALWAYS, LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
104         else
105                 logger(DEBUG_ALWAYS, LOG_INFO, "%s service started", identname);
106
107         return true;
108 }
109
110 io_t stop_io;
111
112 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
113         switch(request) {
114                 case SERVICE_CONTROL_INTERROGATE:
115                         SetServiceStatus(statushandle, &status);
116                         return NO_ERROR;
117                 case SERVICE_CONTROL_STOP:
118                         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
119                         break;
120                 case SERVICE_CONTROL_SHUTDOWN:
121                         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
122                         break;
123                 default:
124                         logger(DEBUG_ALWAYS, LOG_WARNING, "Got unexpected request %d", (int)request);
125                         return ERROR_CALL_NOT_IMPLEMENTED;
126         }
127
128         status.dwWaitHint = 1000;
129         status.dwCurrentState = SERVICE_STOP_PENDING;
130         SetServiceStatus(statushandle, &status);
131         if (WSASetEvent(stop_io.event) == FALSE)
132                 abort();
133         return NO_ERROR;
134 }
135
136 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
137         extern int main2(int argc, char **argv);
138
139         status.dwServiceType = SERVICE_WIN32;
140         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
141         status.dwWin32ExitCode = 0;
142         status.dwServiceSpecificExitCode = 0;
143         status.dwCheckPoint = 0;
144
145         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
146
147         if (!statushandle) {
148                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
149         } else {
150                 status.dwWaitHint = 30000;
151                 status.dwCurrentState = SERVICE_START_PENDING;
152                 SetServiceStatus(statushandle, &status);
153
154                 status.dwWaitHint = 0;
155                 status.dwCurrentState = SERVICE_RUNNING;
156                 SetServiceStatus(statushandle, &status);
157
158                 main2(argc, argv);
159
160                 status.dwWaitHint = 0;
161                 status.dwCurrentState = SERVICE_STOPPED;
162                 SetServiceStatus(statushandle, &status);
163         }
164
165         return;
166 }
167
168 bool init_service(void) {
169         SERVICE_TABLE_ENTRY services[] = {
170                 {identname, run_service},
171                 {NULL, NULL}
172         };
173
174         if(!StartServiceCtrlDispatcher(services)) {
175                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
176                         return false;
177                 }
178                 else
179                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
180         }
181
182         return true;
183 }
184 #endif
185
186 /*
187   Detach from current terminal
188 */
189 bool detach(void) {
190         logmode_t logmode;
191
192 #ifndef HAVE_MINGW
193         signal(SIGPIPE, SIG_IGN);
194         signal(SIGUSR1, SIG_IGN);
195         signal(SIGUSR2, SIG_IGN);
196         signal(SIGWINCH, SIG_IGN);
197
198         closelogger();
199 #endif
200
201         if(do_detach) {
202 #ifndef HAVE_MINGW
203                 if(daemon(1, 0)) {
204                         logger(DEBUG_ALWAYS, LOG_ERR, "Couldn't detach from terminal: %s", strerror(errno));
205                         return false;
206                 }
207 #else
208                 if(!statushandle)
209                         exit(!install_service());
210 #endif
211         }
212
213         if(use_logfile)
214                 logmode = LOGMODE_FILE;
215         else if(use_syslog || do_detach)
216                 logmode = LOGMODE_SYSLOG;
217         else
218                 logmode = LOGMODE_STDERR;
219
220         openlogger(identname, logmode);
221
222         logger(DEBUG_ALWAYS, LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
223                            BUILD_VERSION, BUILD_DATE, BUILD_TIME, debug_level);
224
225         return true;
226 }