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