summaryrefslogtreecommitdiff
path: root/bin/bbackupd/Win32ServiceFunctions.cpp
blob: f4c8894b3d255d2542f6b8382405fda9d8fd8ffb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//***************************************************************
// From the book "Win32 System Services: The Heart of Windows 98
// and Windows 2000"
// by Marshall Brain
// Published by Prentice Hall
// Copyright 1995 Prentice Hall.
//
// This code implements the Windows API Service interface 
// for the Box Backup for Windows native port.
// Adapted for Box Backup by Nick Knight.
//***************************************************************

#ifdef WIN32

#include "Box.h"

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif
#ifdef HAVE_PROCESS_H
	#include <process.h>
#endif

extern void TerminateService(void);
extern unsigned int WINAPI RunService(LPVOID lpParameter);

// Global variables

TCHAR* gServiceName = TEXT("Box Backup Service");
SERVICE_STATUS gServiceStatus;
SERVICE_STATUS_HANDLE gServiceStatusHandle = 0;
HANDLE gStopServiceEvent = 0;

#define SERVICE_NAME "boxbackup"

void ShowMessage(char *s)
{
	MessageBox(0, s, "Box Backup Message", 
		MB_OK | MB_SETFOREGROUND | MB_DEFAULT_DESKTOP_ONLY);
}

void ErrorHandler(char *s, DWORD err)
{
	char buf[256];
	memset(buf, 0, sizeof(buf));
	_snprintf(buf, sizeof(buf)-1, "%s (%d)", s, err);
	BOX_ERROR(buf);
	MessageBox(0, buf, "Error", 
		MB_OK | MB_SETFOREGROUND | MB_DEFAULT_DESKTOP_ONLY);
	ExitProcess(err);
}

void WINAPI ServiceControlHandler( DWORD controlCode )
{
	switch ( controlCode )
	{
		case SERVICE_CONTROL_INTERROGATE:
			break;

		case SERVICE_CONTROL_SHUTDOWN:
		case SERVICE_CONTROL_STOP:
			Beep(1000,100);
			TerminateService();
			gServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
			SetServiceStatus(gServiceStatusHandle, &gServiceStatus);

			SetEvent(gStopServiceEvent);
			return;

		case SERVICE_CONTROL_PAUSE:
			break;

		case SERVICE_CONTROL_CONTINUE:
			break;

		default:
			if ( controlCode >= 128 && controlCode <= 255 )
				// user defined control code
				break;
			else
				// unrecognised control code
				break;
	}

	SetServiceStatus( gServiceStatusHandle, &gServiceStatus );
}

// ServiceMain is called when the SCM wants to
// start the service. When it returns, the service
// has stopped. It therefore waits on an event
// just before the end of the function, and
// that event gets set when it is time to stop. 
// It also returns on any error because the
// service cannot start if there is an eror.

static char* spConfigFileName;

VOID ServiceMain(DWORD argc, LPTSTR *argv) 
{
	// initialise service status
	gServiceStatus.dwServiceType = SERVICE_WIN32;
	gServiceStatus.dwCurrentState = SERVICE_STOPPED;
	gServiceStatus.dwControlsAccepted = 0;
	gServiceStatus.dwWin32ExitCode = NO_ERROR;
	gServiceStatus.dwServiceSpecificExitCode = NO_ERROR;
	gServiceStatus.dwCheckPoint = 0;
	gServiceStatus.dwWaitHint = 0;

	gServiceStatusHandle = RegisterServiceCtrlHandler(gServiceName, 
		ServiceControlHandler);

	if (gServiceStatusHandle)
	{
		// service is starting
		gServiceStatus.dwCurrentState = SERVICE_START_PENDING;
		SetServiceStatus(gServiceStatusHandle, &gServiceStatus);

		// do initialisation here
		gStopServiceEvent = CreateEvent(0, TRUE, FALSE, 0);
		if (!gStopServiceEvent)
		{
			gServiceStatus.dwControlsAccepted &= 
				~(SERVICE_ACCEPT_STOP | 
				  SERVICE_ACCEPT_SHUTDOWN);
			gServiceStatus.dwCurrentState = SERVICE_STOPPED;
			SetServiceStatus(gServiceStatusHandle, &gServiceStatus);
			return;
		}

		HANDLE ourThread = (HANDLE)_beginthreadex(
			NULL,
			0,
			RunService,
			spConfigFileName,
			CREATE_SUSPENDED,
			NULL);

		SetThreadPriority(ourThread, THREAD_PRIORITY_LOWEST);
		ResumeThread(ourThread);

		// we are now running so tell the SCM
		gServiceStatus.dwControlsAccepted |= 
			(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);
		gServiceStatus.dwCurrentState = SERVICE_RUNNING;
		SetServiceStatus(gServiceStatusHandle, &gServiceStatus);

		// do cleanup here
		WaitForSingleObject(gStopServiceEvent, INFINITE);
		CloseHandle(gStopServiceEvent);
		gStopServiceEvent = 0;

		// service was stopped
		gServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
		SetServiceStatus(gServiceStatusHandle, &gServiceStatus);

		// service is now stopped
		gServiceStatus.dwControlsAccepted &= 
			~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);
		gServiceStatus.dwCurrentState = SERVICE_STOPPED;
		SetServiceStatus(gServiceStatusHandle, &gServiceStatus);
	}
}

void OurService(char* pConfigFileName)
{
	spConfigFileName = pConfigFileName;

	SERVICE_TABLE_ENTRY serviceTable[] = 
	{ 
		{ SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain },
		{ NULL, NULL }
	};
	BOOL success;

	// Register with the SCM
	success = StartServiceCtrlDispatcher(serviceTable);

	if (!success)
	{
		ErrorHandler("Failed to start service. Did you start "
			"Box Backup from the Service Control Manager? "
			"(StartServiceCtrlDispatcher)", GetLastError());
	}
}

int InstallService(const char* pConfigFileName)
{
	if (pConfigFileName != NULL)
	{
		struct stat st;

		if (emu_stat(pConfigFileName, &st) != 0)
		{
			BOX_ERROR("Failed to open configuration file '" <<
				pConfigFileName << "': " << strerror(errno));
			return 1;
		}

		if (!(st.st_mode & S_IFREG))
		{
	
			BOX_ERROR("Failed to open configuration file '" <<
				pConfigFileName << "': not a file");
			return 1;
		}
	}

	SC_HANDLE scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);

	if (!scm) 
	{
		BOX_ERROR("Failed to open service control manager: " <<
			GetErrorMessage(GetLastError()));
		return 1;
	}

	char cmd[MAX_PATH];
	GetModuleFileName(NULL, cmd, sizeof(cmd)-1);
	cmd[sizeof(cmd)-1] = 0;

	std::string cmdWithArgs(cmd);
	cmdWithArgs += " --service";

	if (pConfigFileName != NULL)
	{
		cmdWithArgs += " \"";
		cmdWithArgs += pConfigFileName;
		cmdWithArgs += "\"";
	}

	SC_HANDLE newService = CreateService(
		scm, 
		SERVICE_NAME, 
		"Box Backup", 
		SERVICE_ALL_ACCESS, 
		SERVICE_WIN32_OWN_PROCESS, 
		SERVICE_AUTO_START, 
		SERVICE_ERROR_NORMAL, 
		cmdWithArgs.c_str(),
		0,0,0,0,0);

	DWORD err = GetLastError();
	CloseServiceHandle(scm);

	if (!newService) 
	{
		switch (err)
		{
			case ERROR_SERVICE_EXISTS:
			{
				BOX_ERROR("Failed to create Box Backup "
					"service: it already exists");
			}
			break;

			case ERROR_SERVICE_MARKED_FOR_DELETE:
			{
				BOX_ERROR("Failed to create Box Backup "
					"service: it is waiting to be deleted");
			}
			break;

			case ERROR_DUPLICATE_SERVICE_NAME:
			{
				BOX_ERROR("Failed to create Box Backup "
					"service: a service with this name "
					"already exists");
			}
			break;

			default:
			{
				BOX_ERROR("Failed to create Box Backup "
					"service: error " <<
					GetErrorMessage(GetLastError()));
			}
		}

		return 1;
	}

	BOX_INFO("Created Box Backup service");
	
	SERVICE_DESCRIPTION desc;
	desc.lpDescription = "Backs up your data files over the Internet";
	
	if (!ChangeServiceConfig2(newService, SERVICE_CONFIG_DESCRIPTION,
		&desc))
	{
		BOX_WARNING("Failed to set description for Box Backup "
			"service: " << GetErrorMessage(GetLastError()));
	}

	CloseServiceHandle(newService);

	return 0;
}

int RemoveService(void)
{
	SC_HANDLE scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);

	if (!scm) 
	{
		BOX_ERROR("Failed to open service control manager: " <<
			GetErrorMessage(GetLastError()));
		return 1;
	}

	SC_HANDLE service = OpenService(scm, SERVICE_NAME, 
		SERVICE_ALL_ACCESS|DELETE);
	DWORD err = GetLastError();
	CloseServiceHandle(scm);

	if (!service)
	{
		if (err == ERROR_SERVICE_DOES_NOT_EXIST ||
			err == ERROR_IO_PENDING) 
			// hello microsoft? anyone home?
		{
			BOX_ERROR("Failed to open Box Backup service: "
				"not installed or not found");
		}
		else
		{
			BOX_ERROR("Failed to open Box Backup service: " <<
				GetErrorMessage(err));
		}
		return 1;
	}

	SERVICE_STATUS status;
	if (!ControlService(service, SERVICE_CONTROL_STOP, &status))
	{
		err = GetLastError();
		if (err != ERROR_SERVICE_NOT_ACTIVE)
		{
			BOX_WARNING("Failed to stop Box Backup service: " <<
				GetErrorMessage(err));
		}
	}

	BOOL deleted = DeleteService(service);
	err = GetLastError();
	CloseServiceHandle(service);

	if (deleted)
	{
		BOX_INFO("Box Backup service deleted");
		return 0;
	}
	else if (err == ERROR_SERVICE_MARKED_FOR_DELETE)
	{
		BOX_ERROR("Failed to remove Box Backup service: "
			"it is already being deleted");
	}
	else
	{
		BOX_ERROR("Failed to remove Box Backup service: " <<
			GetErrorMessage(err));
	}

	return 1;
}

#endif // WIN32