services: Fix memory leak of some data in the service record.
[wine] / programs / services / services.c
1 /*
2  * Services - controls services keeps track of their state
3  *
4  * Copyright 2007 Google (Mikolaj Zalewski)
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #define WIN32_LEAN_AND_MEAN
22
23 #include <stdarg.h>
24 #include <windows.h>
25 #include <winsvc.h>
26 #include <rpc.h>
27
28 #include "wine/unicode.h"
29 #include "wine/debug.h"
30 #include "svcctl.h"
31
32 #include "services.h"
33
34 #define MAX_SERVICE_NAME 260
35
36 WINE_DEFAULT_DEBUG_CHANNEL(service);
37
38 HANDLE g_hStartedEvent;
39 struct scmdatabase *active_database;
40
41 static const WCHAR SZ_LOCAL_SYSTEM[] = {'L','o','c','a','l','S','y','s','t','e','m',0};
42
43 /* Registry constants */
44 static const WCHAR SZ_SERVICES_KEY[] = { 'S','y','s','t','e','m','\\',
45       'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
46       'S','e','r','v','i','c','e','s',0 };
47
48 /* Service key values names */
49 static const WCHAR SZ_DISPLAY_NAME[]      = {'D','i','s','p','l','a','y','N','a','m','e',0 };
50 static const WCHAR SZ_TYPE[]              = {'T','y','p','e',0 };
51 static const WCHAR SZ_START[]             = {'S','t','a','r','t',0 };
52 static const WCHAR SZ_ERROR[]             = {'E','r','r','o','r','C','o','n','t','r','o','l',0 };
53 static const WCHAR SZ_IMAGE_PATH[]        = {'I','m','a','g','e','P','a','t','h',0};
54 static const WCHAR SZ_GROUP[]             = {'G','r','o','u','p',0};
55 static const WCHAR SZ_DEPEND_ON_SERVICE[] = {'D','e','p','e','n','d','O','n','S','e','r','v','i','c','e',0};
56 static const WCHAR SZ_DEPEND_ON_GROUP[]   = {'D','e','p','e','n','d','O','n','G','r','o','u','p',0};
57 static const WCHAR SZ_OBJECT_NAME[]       = {'O','b','j','e','c','t','N','a','m','e',0};
58 static const WCHAR SZ_TAG[]               = {'T','a','g',0};
59 static const WCHAR SZ_DESCRIPTION[]       = {'D','e','s','c','r','i','p','t','i','o','n',0};
60
61
62 DWORD service_create(LPCWSTR name, struct service_entry **entry)
63 {
64     *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
65     if (!*entry)
66         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
67     (*entry)->name = strdupW(name);
68     if (!(*entry)->name)
69     {
70         HeapFree(GetProcessHeap(), 0, *entry);
71         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
72     }
73     (*entry)->control_pipe = INVALID_HANDLE_VALUE;
74     return ERROR_SUCCESS;
75 }
76
77 void free_service_entry(struct service_entry *entry)
78 {
79     HeapFree(GetProcessHeap(), 0, entry->name);
80     HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
81     HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
82     HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
83     HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
84     HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
85     HeapFree(GetProcessHeap(), 0, entry->description);
86     HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
87     HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
88     CloseHandle(entry->control_mutex);
89     CloseHandle(entry->control_pipe);
90     CloseHandle(entry->status_changed_event);
91     HeapFree(GetProcessHeap(), 0, entry);
92 }
93
94 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
95 {
96     DWORD err;
97     WCHAR *wptr;
98
99     if ((err = load_reg_string(hKey, SZ_IMAGE_PATH,   TRUE, &entry->config.lpBinaryPathName)) != 0)
100         return err;
101     if ((err = load_reg_string(hKey, SZ_GROUP,        0,    &entry->config.lpLoadOrderGroup)) != 0)
102         return err;
103     if ((err = load_reg_string(hKey, SZ_OBJECT_NAME,  TRUE, &entry->config.lpServiceStartName)) != 0)
104         return err;
105     if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0,    &entry->config.lpDisplayName)) != 0)
106         return err;
107     if ((err = load_reg_string(hKey, SZ_DESCRIPTION,  0,    &entry->description)) != 0)
108         return err;
109     if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, &entry->dependOnServices)) != 0)
110         return err;
111     if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP,   &entry->dependOnGroups)) != 0)
112         return err;
113
114     if ((err = load_reg_dword(hKey, SZ_TYPE,  &entry->config.dwServiceType)) != 0)
115         return err;
116     if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
117         return err;
118     if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
119         return err;
120     if ((err = load_reg_dword(hKey, SZ_TAG,   &entry->config.dwTagId)) != 0)
121         return err;
122
123     WINE_TRACE("Image path           = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
124     WINE_TRACE("Group                = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
125     WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
126     WINE_TRACE("Display name         = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
127     WINE_TRACE("Service dependancies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
128     for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
129         WINE_TRACE("    * %s\n", wine_dbgstr_w(wptr));
130     WINE_TRACE("Group dependancies   : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
131     for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
132         WINE_TRACE("    * %s\n", wine_dbgstr_w(wptr));
133
134     return ERROR_SUCCESS;
135 }
136
137 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
138 {
139     if (!string)
140     {
141         DWORD err;
142         err = RegDeleteValueW(hKey, value_name);
143         if (err != ERROR_FILE_NOT_FOUND)
144             return err;
145
146         return ERROR_SUCCESS;
147     }
148
149     return RegSetValueExW(hKey, value_name, 0, REG_SZ, (LPBYTE)string, sizeof(WCHAR)*(strlenW(string) + 1));
150 }
151
152 DWORD save_service_config(struct service_entry *entry)
153 {
154     DWORD err;
155     HKEY hKey = NULL;
156
157     err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
158     if (err != ERROR_SUCCESS)
159         goto cleanup;
160
161     if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
162         goto cleanup;
163     if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
164         goto cleanup;
165     if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
166         goto cleanup;
167     if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
168         goto cleanup;
169     if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
170         goto cleanup;
171     if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
172         goto cleanup;
173     if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
174         goto cleanup;
175
176     if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
177         goto cleanup;
178
179     if (entry->config.dwTagId)
180         err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
181     else
182         err = RegDeleteValueW(hKey, SZ_TAG);
183
184     if (err != 0 && err != ERROR_FILE_NOT_FOUND)
185         goto cleanup;
186
187     err = ERROR_SUCCESS;
188 cleanup:
189     RegCloseKey(hKey);
190     return err;
191 }
192
193 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
194 {
195     int err;
196     service->db = db;
197     if ((err = save_service_config(service)) != ERROR_SUCCESS)
198     {
199         WINE_ERR("Couldn't store service configuration: error %u\n", err);
200         return ERROR_GEN_FAILURE;
201     }
202
203     list_add_tail(&db->services, &service->entry);
204     return ERROR_SUCCESS;
205 }
206
207 DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
208 {
209     int err;
210
211     err = RegDeleteTreeW(db->root_key, service->name);
212
213     if (err != 0)
214         return err;
215
216     list_remove(&service->entry);
217     service->entry.next = service->entry.prev = NULL;
218     return ERROR_SUCCESS;
219 }
220
221 BOOL validate_service_name(LPCWSTR name)
222 {
223     return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
224 }
225
226 BOOL validate_service_config(struct service_entry *entry)
227 {
228     if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
229     {
230         WINE_ERR("Service %s is Win32 but have no image path set\n", wine_dbgstr_w(entry->name));
231         return FALSE;
232     }
233
234     switch (entry->config.dwServiceType)
235     {
236     case SERVICE_KERNEL_DRIVER:
237     case SERVICE_FILE_SYSTEM_DRIVER:
238     case SERVICE_WIN32_OWN_PROCESS:
239     case SERVICE_WIN32_SHARE_PROCESS:
240         /* No problem */
241         break;
242     case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
243     case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
244         /* These can be only run as LocalSystem */
245         if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
246         {
247             WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
248             return FALSE;
249         }
250         break;
251     default:
252         WINE_ERR("Service %s have unknown service type\n", wine_dbgstr_w(entry->name));
253         return FALSE;
254     }
255
256     /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
257     if (entry->config.dwStartType > SERVICE_DISABLED)
258     {
259         WINE_ERR("Service %s have unknown start type\n", wine_dbgstr_w(entry->name));
260         return FALSE;
261     }
262
263     /* SERVICE_BOOT_START and SERVICE_SYSTEM_START or only allowed for driver services */
264     if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
265         ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
266     {
267         WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
268         return FALSE;
269     }
270
271     if (entry->config.lpServiceStartName == NULL)
272         entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
273
274     return TRUE;
275 }
276
277
278 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
279 {
280     struct service_entry *service;
281
282     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
283     {
284         if (strcmpiW(name, service->name) == 0)
285             return service;
286     }
287
288     return NULL;
289 }
290
291 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
292 {
293     struct service_entry *service;
294
295     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
296     {
297         if (strcmpiW(name, service->config.lpDisplayName) == 0)
298             return service;
299     }
300
301     return NULL;
302 }
303
304 void release_service(struct service_entry *service)
305 {
306     if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
307         free_service_entry(service);
308 }
309
310 static DWORD scmdatabase_create(struct scmdatabase **db)
311 {
312     DWORD err;
313
314     *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
315     if (!*db)
316         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
317
318     (*db)->service_start_lock = FALSE;
319     list_init(&(*db)->services);
320
321     InitializeCriticalSection(&(*db)->cs);
322
323     err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
324                           REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
325                           &(*db)->root_key, NULL);
326     if (err != ERROR_SUCCESS)
327         HeapFree(GetProcessHeap(), 0, *db);
328
329     return err;
330 }
331
332 static void scmdatabase_destroy(struct scmdatabase *db)
333 {
334     RegCloseKey(db->root_key);
335     DeleteCriticalSection(&db->cs);
336     HeapFree(GetProcessHeap(), 0, db);
337 }
338
339 static DWORD scmdatabase_load_services(struct scmdatabase *db)
340 {
341     DWORD err;
342     int i;
343
344     for (i = 0; TRUE; i++)
345     {
346         WCHAR szName[MAX_SERVICE_NAME];
347         struct service_entry *entry;
348         HKEY hServiceKey;
349
350         err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
351         if (err == ERROR_NO_MORE_ITEMS)
352             break;
353
354         if (err != 0)
355         {
356             WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
357             continue;
358         }
359
360         err = service_create(szName, &entry);
361         if (err != ERROR_SUCCESS)
362             break;
363
364         WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
365         err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ | KEY_WRITE, &hServiceKey);
366         if (err == ERROR_SUCCESS)
367         {
368             err = load_service_config(hServiceKey, entry);
369             RegCloseKey(hServiceKey);
370         }
371
372         if (err != ERROR_SUCCESS)
373         {
374             WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
375             free_service_entry(entry);
376             continue;
377         }
378
379         if (entry->config.dwServiceType == 0)
380         {
381             /* Maybe an application only wrote some configuration in the service key. Continue silently */
382             WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
383             free_service_entry(entry);
384             continue;
385         }
386
387         if (!validate_service_config(entry))
388         {
389             WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
390             free_service_entry(entry);
391             continue;
392         }
393
394         entry->status.dwServiceType = entry->config.dwServiceType;
395         entry->status.dwCurrentState = SERVICE_STOPPED;
396         entry->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
397         entry->db = db;
398         /* all other fields are zero */
399
400         list_add_tail(&db->services, &entry->entry);
401     }
402     return ERROR_SUCCESS;
403 }
404
405 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
406 {
407     if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
408         return ERROR_SERVICE_DATABASE_LOCKED;
409     return ERROR_SUCCESS;
410 }
411
412 void scmdatabase_unlock_startup(struct scmdatabase *db)
413 {
414     InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
415 }
416
417 void scmdatabase_lock_shared(struct scmdatabase *db)
418 {
419     EnterCriticalSection(&db->cs);
420 }
421
422 void scmdatabase_lock_exclusive(struct scmdatabase *db)
423 {
424     EnterCriticalSection(&db->cs);
425 }
426
427 void scmdatabase_unlock(struct scmdatabase *db)
428 {
429     LeaveCriticalSection(&db->cs);
430 }
431
432 void service_lock_shared(struct service_entry *service)
433 {
434     EnterCriticalSection(&service->db->cs);
435 }
436
437 void service_lock_exclusive(struct service_entry *service)
438 {
439     EnterCriticalSection(&service->db->cs);
440 }
441
442 void service_unlock(struct service_entry *service)
443 {
444     LeaveCriticalSection(&service->db->cs);
445 }
446
447 int main(int argc, char *argv[])
448 {
449     static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
450     DWORD err;
451     g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
452     err = scmdatabase_create(&active_database);
453     if (err != ERROR_SUCCESS)
454         return err;
455     if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
456         return err;
457     err = RPC_MainLoop();
458     scmdatabase_destroy(active_database);
459     return err;
460 }