oleaut32: Remove unnecessary consts.
[wine.git] / programs / services / services.c
blob1973d279503d7996fe437eb977cc95b60465c5ab
1 /*
2 * Services - controls services keeps track of their state
4 * Copyright 2007 Google (Mikolaj Zalewski)
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.
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.
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
21 #define WIN32_LEAN_AND_MEAN
23 #include <stdarg.h>
24 #include <windows.h>
25 #include <winsvc.h>
26 #include <rpc.h>
27 #include <userenv.h>
29 #include "wine/unicode.h"
30 #include "wine/debug.h"
31 #include "svcctl.h"
33 #include "services.h"
35 #define MAX_SERVICE_NAME 260
37 WINE_DEFAULT_DEBUG_CHANNEL(service);
39 struct scmdatabase *active_database;
41 DWORD service_pipe_timeout = 10000;
42 DWORD service_kill_timeout = 60000;
43 static DWORD default_preshutdown_timeout = 180000;
44 static void *environment = NULL;
45 static HKEY service_current_key = NULL;
47 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
49 static const WCHAR SZ_LOCAL_SYSTEM[] = {'L','o','c','a','l','S','y','s','t','e','m',0};
51 /* Registry constants */
52 static const WCHAR SZ_SERVICES_KEY[] = { 'S','y','s','t','e','m','\\',
53 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
54 'S','e','r','v','i','c','e','s',0 };
56 /* Service key values names */
57 static const WCHAR SZ_DISPLAY_NAME[] = {'D','i','s','p','l','a','y','N','a','m','e',0 };
58 static const WCHAR SZ_TYPE[] = {'T','y','p','e',0 };
59 static const WCHAR SZ_START[] = {'S','t','a','r','t',0 };
60 static const WCHAR SZ_ERROR[] = {'E','r','r','o','r','C','o','n','t','r','o','l',0 };
61 static const WCHAR SZ_IMAGE_PATH[] = {'I','m','a','g','e','P','a','t','h',0};
62 static const WCHAR SZ_GROUP[] = {'G','r','o','u','p',0};
63 static const WCHAR SZ_DEPEND_ON_SERVICE[] = {'D','e','p','e','n','d','O','n','S','e','r','v','i','c','e',0};
64 static const WCHAR SZ_DEPEND_ON_GROUP[] = {'D','e','p','e','n','d','O','n','G','r','o','u','p',0};
65 static const WCHAR SZ_OBJECT_NAME[] = {'O','b','j','e','c','t','N','a','m','e',0};
66 static const WCHAR SZ_TAG[] = {'T','a','g',0};
67 static const WCHAR SZ_DESCRIPTION[] = {'D','e','s','c','r','i','p','t','i','o','n',0};
68 static const WCHAR SZ_PRESHUTDOWN[] = {'P','r','e','s','h','u','t','d','o','w','n','T','i','m','e','o','u','t',0};
69 static const WCHAR SZ_WOW64[] = {'W','O','W','6','4',0};
71 static DWORD process_create(const WCHAR *name, struct process_entry **entry)
73 DWORD err;
75 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
76 if (!*entry)
77 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
78 (*entry)->ref_count = 1;
79 (*entry)->control_mutex = CreateMutexW(NULL, TRUE, NULL);
80 if (!(*entry)->control_mutex)
81 goto error;
82 (*entry)->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
83 if (!(*entry)->overlapped_event)
84 goto error;
85 (*entry)->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
86 PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL);
87 if ((*entry)->control_pipe == INVALID_HANDLE_VALUE)
88 goto error;
89 /* all other fields are zero */
90 return ERROR_SUCCESS;
92 error:
93 err = GetLastError();
94 if ((*entry)->control_mutex)
95 CloseHandle((*entry)->control_mutex);
96 if ((*entry)->overlapped_event)
97 CloseHandle((*entry)->overlapped_event);
98 HeapFree(GetProcessHeap(), 0, *entry);
99 return err;
102 static void free_process_entry(struct process_entry *entry)
104 CloseHandle(entry->process);
105 CloseHandle(entry->control_mutex);
106 CloseHandle(entry->control_pipe);
107 CloseHandle(entry->overlapped_event);
108 HeapFree(GetProcessHeap(), 0, entry);
111 DWORD service_create(LPCWSTR name, struct service_entry **entry)
113 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
114 if (!*entry)
115 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
116 (*entry)->name = strdupW(name);
117 if (!(*entry)->name)
119 HeapFree(GetProcessHeap(), 0, *entry);
120 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
122 (*entry)->status_changed_event = CreateEventW(NULL, TRUE, FALSE, NULL);
123 if (!(*entry)->status_changed_event)
125 HeapFree(GetProcessHeap(), 0, (*entry)->name);
126 HeapFree(GetProcessHeap(), 0, *entry);
127 return GetLastError();
129 (*entry)->ref_count = 1;
130 (*entry)->status.dwCurrentState = SERVICE_STOPPED;
131 (*entry)->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
132 (*entry)->preshutdown_timeout = default_preshutdown_timeout;
133 /* all other fields are zero */
134 return ERROR_SUCCESS;
137 void free_service_entry(struct service_entry *entry)
139 CloseHandle(entry->status_changed_event);
140 HeapFree(GetProcessHeap(), 0, entry->name);
141 HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
142 HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
143 HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
144 HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
145 HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
146 HeapFree(GetProcessHeap(), 0, entry->description);
147 HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
148 HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
149 if (entry->process) release_process(entry->process);
150 HeapFree(GetProcessHeap(), 0, entry);
153 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
155 DWORD err, value = 0;
156 WCHAR *wptr;
158 if ((err = load_reg_string(hKey, SZ_IMAGE_PATH, TRUE, &entry->config.lpBinaryPathName)) != 0)
159 return err;
160 if ((err = load_reg_string(hKey, SZ_GROUP, 0, &entry->config.lpLoadOrderGroup)) != 0)
161 return err;
162 if ((err = load_reg_string(hKey, SZ_OBJECT_NAME, TRUE, &entry->config.lpServiceStartName)) != 0)
163 return err;
164 if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0, &entry->config.lpDisplayName)) != 0)
165 return err;
166 if ((err = load_reg_string(hKey, SZ_DESCRIPTION, 0, &entry->description)) != 0)
167 return err;
168 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
169 return err;
170 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
171 return err;
173 if ((err = load_reg_dword(hKey, SZ_TYPE, &entry->config.dwServiceType)) != 0)
174 return err;
175 if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
176 return err;
177 if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
178 return err;
179 if ((err = load_reg_dword(hKey, SZ_TAG, &entry->config.dwTagId)) != 0)
180 return err;
181 if ((err = load_reg_dword(hKey, SZ_PRESHUTDOWN, &entry->preshutdown_timeout)) != 0)
182 return err;
184 if (load_reg_dword(hKey, SZ_WOW64, &value) == 0 && value == 1)
185 entry->is_wow64 = TRUE;
187 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
188 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
189 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
190 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
191 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
192 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
193 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
194 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
195 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
196 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
198 return ERROR_SUCCESS;
201 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
203 if (!string)
205 DWORD err;
206 err = RegDeleteValueW(hKey, value_name);
207 if (err != ERROR_FILE_NOT_FOUND)
208 return err;
210 return ERROR_SUCCESS;
213 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
216 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
218 const WCHAR *ptr;
220 if (!string)
222 DWORD err;
223 err = RegDeleteValueW(hKey, value_name);
224 if (err != ERROR_FILE_NOT_FOUND)
225 return err;
227 return ERROR_SUCCESS;
230 ptr = string;
231 while (*ptr) ptr += strlenW(ptr) + 1;
232 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
235 DWORD save_service_config(struct service_entry *entry)
237 DWORD err;
238 HKEY hKey = NULL;
240 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
241 if (err != ERROR_SUCCESS)
242 goto cleanup;
244 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
245 goto cleanup;
246 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
247 goto cleanup;
248 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
249 goto cleanup;
250 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
251 goto cleanup;
252 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
253 goto cleanup;
254 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
255 goto cleanup;
256 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
257 goto cleanup;
258 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
259 goto cleanup;
260 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
261 goto cleanup;
262 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
263 goto cleanup;
264 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
265 goto cleanup;
266 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
267 goto cleanup;
268 if (entry->is_wow64)
270 const DWORD is_wow64 = 1;
271 if ((err = RegSetValueExW(hKey, SZ_WOW64, 0, REG_DWORD, (LPBYTE)&is_wow64, sizeof(DWORD))) != 0)
272 goto cleanup;
275 if (entry->config.dwTagId)
276 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
277 else
278 err = RegDeleteValueW(hKey, SZ_TAG);
280 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
281 goto cleanup;
283 err = ERROR_SUCCESS;
284 cleanup:
285 RegCloseKey(hKey);
286 return err;
289 static void scmdatabase_add_process(struct scmdatabase *db, struct process_entry *process)
291 process->db = db;
292 list_add_tail(&db->processes, &process->entry);
295 static void scmdatabase_remove_process(struct scmdatabase *db, struct process_entry *process)
297 list_remove(&process->entry);
298 process->entry.next = process->entry.prev = NULL;
301 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
303 int err;
304 service->db = db;
305 if ((err = save_service_config(service)) != ERROR_SUCCESS)
307 WINE_ERR("Couldn't store service configuration: error %u\n", err);
308 return ERROR_GEN_FAILURE;
311 list_add_tail(&db->services, &service->entry);
312 return ERROR_SUCCESS;
315 static void scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
317 RegDeleteTreeW(db->root_key, service->name);
318 list_remove(&service->entry);
319 service->entry.next = service->entry.prev = NULL;
322 static int compare_tags(const void *a, const void *b)
324 struct service_entry *service_a = *(struct service_entry **)a;
325 struct service_entry *service_b = *(struct service_entry **)b;
326 return service_a->config.dwTagId - service_b->config.dwTagId;
329 static void scmdatabase_autostart_services(struct scmdatabase *db)
331 struct service_entry **services_list;
332 unsigned int i = 0;
333 unsigned int size = 32;
334 struct service_entry *service;
336 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
337 if (!services_list)
338 return;
340 scmdatabase_lock(db);
342 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
344 if (service->config.dwStartType == SERVICE_BOOT_START ||
345 service->config.dwStartType == SERVICE_SYSTEM_START ||
346 service->config.dwStartType == SERVICE_AUTO_START)
348 if (i+1 >= size)
350 struct service_entry **slist_new;
351 size *= 2;
352 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
353 if (!slist_new)
354 break;
355 services_list = slist_new;
357 services_list[i++] = grab_service(service);
360 size = i;
362 scmdatabase_unlock(db);
363 qsort(services_list, size, sizeof(services_list[0]), compare_tags);
364 scmdatabase_lock_startup(db, INFINITE);
366 for (i = 0; i < size; i++)
368 DWORD err;
369 service = services_list[i];
370 err = service_start(service, 0, NULL);
371 if (err != ERROR_SUCCESS)
372 WINE_FIXME("Auto-start service %s failed to start: %d\n",
373 wine_dbgstr_w(service->name), err);
374 release_service(service);
377 scmdatabase_unlock_startup(db);
378 HeapFree(GetProcessHeap(), 0, services_list);
381 static void scmdatabase_wait_terminate(struct scmdatabase *db)
383 struct list pending = LIST_INIT(pending);
384 void *ptr;
386 scmdatabase_lock(db);
387 list_move_tail(&pending, &db->processes);
388 while ((ptr = list_head(&pending)))
390 struct process_entry *process = grab_process(LIST_ENTRY(ptr, struct process_entry, entry));
392 scmdatabase_unlock(db);
393 WaitForSingleObject(process->process, INFINITE);
394 scmdatabase_lock(db);
396 list_remove(&process->entry);
397 list_add_tail(&db->processes, &process->entry);
398 release_process(process);
400 scmdatabase_unlock(db);
403 BOOL validate_service_name(LPCWSTR name)
405 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
408 BOOL validate_service_config(struct service_entry *entry)
410 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
412 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
413 return FALSE;
416 switch (entry->config.dwServiceType)
418 case SERVICE_KERNEL_DRIVER:
419 case SERVICE_FILE_SYSTEM_DRIVER:
420 case SERVICE_WIN32_OWN_PROCESS:
421 case SERVICE_WIN32_SHARE_PROCESS:
422 /* No problem */
423 break;
424 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
425 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
426 /* These can be only run as LocalSystem */
427 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
429 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
430 return FALSE;
432 break;
433 default:
434 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
435 return FALSE;
438 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
439 if (entry->config.dwStartType > SERVICE_DISABLED)
441 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
442 return FALSE;
445 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
446 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
447 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
449 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
450 return FALSE;
453 if (entry->config.lpServiceStartName == NULL)
454 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
456 return TRUE;
460 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
462 struct service_entry *service;
464 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
466 if (strcmpiW(name, service->name) == 0)
467 return service;
470 return NULL;
473 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
475 struct service_entry *service;
477 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
479 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
480 return service;
483 return NULL;
486 struct process_entry *grab_process(struct process_entry *process)
488 if (process)
489 InterlockedIncrement(&process->ref_count);
490 return process;
493 void release_process(struct process_entry *process)
495 struct scmdatabase *db = process->db;
497 scmdatabase_lock(db);
498 if (InterlockedDecrement(&process->ref_count) == 0)
500 scmdatabase_remove_process(db, process);
501 free_process_entry(process);
503 scmdatabase_unlock(db);
506 struct service_entry *grab_service(struct service_entry *service)
508 if (service)
509 InterlockedIncrement(&service->ref_count);
510 return service;
513 void release_service(struct service_entry *service)
515 struct scmdatabase *db = service->db;
517 scmdatabase_lock(db);
518 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
520 scmdatabase_remove_service(db, service);
521 free_service_entry(service);
523 scmdatabase_unlock(db);
526 static DWORD scmdatabase_create(struct scmdatabase **db)
528 DWORD err;
530 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
531 if (!*db)
532 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
534 (*db)->service_start_lock = FALSE;
535 list_init(&(*db)->processes);
536 list_init(&(*db)->services);
538 InitializeCriticalSection(&(*db)->cs);
539 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
541 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
542 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
543 &(*db)->root_key, NULL);
544 if (err != ERROR_SUCCESS)
545 HeapFree(GetProcessHeap(), 0, *db);
547 return err;
550 static void scmdatabase_destroy(struct scmdatabase *db)
552 RegCloseKey(db->root_key);
553 db->cs.DebugInfo->Spare[0] = 0;
554 DeleteCriticalSection(&db->cs);
555 HeapFree(GetProcessHeap(), 0, db);
558 static DWORD scmdatabase_load_services(struct scmdatabase *db)
560 DWORD err;
561 int i;
563 for (i = 0; TRUE; i++)
565 WCHAR szName[MAX_SERVICE_NAME];
566 struct service_entry *entry;
567 HKEY hServiceKey;
569 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
570 if (err == ERROR_NO_MORE_ITEMS)
571 break;
573 if (err != 0)
575 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
576 continue;
579 err = service_create(szName, &entry);
580 if (err != ERROR_SUCCESS)
581 break;
583 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
584 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
585 if (err == ERROR_SUCCESS)
587 err = load_service_config(hServiceKey, entry);
588 RegCloseKey(hServiceKey);
591 if (err != ERROR_SUCCESS)
593 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
594 free_service_entry(entry);
595 continue;
598 if (entry->config.dwServiceType == 0)
600 /* Maybe an application only wrote some configuration in the service key. Continue silently */
601 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
602 free_service_entry(entry);
603 continue;
606 if (!validate_service_config(entry))
608 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
609 free_service_entry(entry);
610 continue;
613 entry->status.dwServiceType = entry->config.dwServiceType;
614 entry->db = db;
616 list_add_tail(&db->services, &entry->entry);
617 release_service(entry);
619 return ERROR_SUCCESS;
622 BOOL scmdatabase_lock_startup(struct scmdatabase *db, int timeout)
624 while (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
626 if (timeout != INFINITE)
628 timeout -= 10;
629 if (timeout <= 0) return FALSE;
631 Sleep(10);
633 return TRUE;
636 void scmdatabase_unlock_startup(struct scmdatabase *db)
638 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
641 void scmdatabase_lock(struct scmdatabase *db)
643 EnterCriticalSection(&db->cs);
646 void scmdatabase_unlock(struct scmdatabase *db)
648 LeaveCriticalSection(&db->cs);
651 void service_lock(struct service_entry *service)
653 EnterCriticalSection(&service->db->cs);
656 void service_unlock(struct service_entry *service)
658 LeaveCriticalSection(&service->db->cs);
661 /* only one service started at a time, so there is no race on the registry
662 * value here */
663 static LPWSTR service_get_pipe_name(void)
665 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
666 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
667 static WCHAR name[sizeof(format)/sizeof(WCHAR) + 10]; /* strlenW("4294967295") */
668 static DWORD service_current = 0;
669 DWORD len, value = -1;
670 LONG ret;
671 DWORD type;
673 len = sizeof(value);
674 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
675 (BYTE *)&value, &len);
676 if (ret == ERROR_SUCCESS && type == REG_DWORD)
677 service_current = max(service_current, value + 1);
678 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
679 (BYTE *)&service_current, sizeof(service_current));
680 sprintfW(name, format, service_current);
681 service_current++;
682 return name;
685 static DWORD get_service_binary_path(const struct service_entry *service_entry, WCHAR **path)
687 DWORD size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, NULL, 0);
689 *path = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
690 if (!*path)
691 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
693 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, *path, size);
695 /* if service image is configured to systemdir, redirect it to wow64 systemdir */
696 if (service_entry->is_wow64)
698 WCHAR system_dir[MAX_PATH], *redirected;
699 DWORD len;
701 GetSystemDirectoryW( system_dir, MAX_PATH );
702 len = strlenW( system_dir );
704 if (strncmpiW( system_dir, *path, len ))
705 return ERROR_SUCCESS;
707 GetSystemWow64DirectoryW( system_dir, MAX_PATH );
709 redirected = HeapAlloc( GetProcessHeap(), 0, (strlenW( *path ) + strlenW( system_dir ))*sizeof(WCHAR));
710 if (!redirected)
712 HeapFree( GetProcessHeap(), 0, *path );
713 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
716 strcpyW( redirected, system_dir );
717 strcatW( redirected, &(*path)[len] );
718 HeapFree( GetProcessHeap(), 0, *path );
719 *path = redirected;
720 TRACE("redirected to %s\n", debugstr_w(redirected));
723 return ERROR_SUCCESS;
726 static DWORD get_winedevice_binary_path(struct service_entry *service_entry, WCHAR **path, BOOL *is_wow64)
728 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',0};
729 WCHAR system_dir[MAX_PATH];
730 DWORD type;
732 if (!is_win64)
733 *is_wow64 = FALSE;
734 else if (GetBinaryTypeW(*path, &type))
735 *is_wow64 = (type == SCS_32BIT_BINARY);
736 else
737 *is_wow64 = service_entry->is_wow64;
739 GetSystemDirectoryW(system_dir, MAX_PATH);
740 HeapFree(GetProcessHeap(), 0, *path);
741 if (!(*path = HeapAlloc(GetProcessHeap(), 0, strlenW(system_dir) * sizeof(WCHAR) + sizeof(winedeviceW))))
742 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
744 strcpyW(*path, system_dir);
745 strcatW(*path, winedeviceW);
746 return ERROR_SUCCESS;
749 static struct process_entry *get_winedevice_process(struct service_entry *service_entry, WCHAR *path, BOOL is_wow64)
751 struct service_entry *winedevice_entry;
753 if (!service_entry->config.lpLoadOrderGroup)
754 return NULL;
756 LIST_FOR_EACH_ENTRY(winedevice_entry, &service_entry->db->services, struct service_entry, entry)
758 if (winedevice_entry->status.dwCurrentState != SERVICE_START_PENDING &&
759 winedevice_entry->status.dwCurrentState != SERVICE_RUNNING) continue;
760 if (!winedevice_entry->process) continue;
762 if (winedevice_entry->is_wow64 != is_wow64) continue;
763 if (!winedevice_entry->config.lpBinaryPathName) continue;
764 if (strcmpW(winedevice_entry->config.lpBinaryPathName, path)) continue;
766 if (!winedevice_entry->config.lpLoadOrderGroup) continue;
767 if (strcmpW(winedevice_entry->config.lpLoadOrderGroup, service_entry->config.lpLoadOrderGroup)) continue;
769 return grab_process(winedevice_entry->process);
772 return NULL;
775 static DWORD add_winedevice_service(const struct service_entry *service, WCHAR *path, BOOL is_wow64,
776 struct service_entry **entry)
778 static const WCHAR format[] = {'W','i','n','e','d','e','v','i','c','e','%','u',0};
779 static WCHAR name[sizeof(format)/sizeof(WCHAR) + 10]; /* strlenW("4294967295") */
780 static DWORD current = 0;
781 struct scmdatabase *db = service->db;
782 DWORD err;
784 for (;;)
786 sprintfW(name, format, ++current);
787 if (!scmdatabase_find_service(db, name)) break;
790 err = service_create(name, entry);
791 if (err != ERROR_SUCCESS)
792 return err;
794 (*entry)->is_wow64 = is_wow64;
795 (*entry)->config.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
796 (*entry)->config.dwStartType = SERVICE_DEMAND_START;
797 (*entry)->status.dwServiceType = (*entry)->config.dwServiceType;
799 if (!((*entry)->config.lpBinaryPathName = strdupW(path)))
800 goto error;
801 if (!((*entry)->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM)))
802 goto error;
803 if (!((*entry)->config.lpDisplayName = strdupW(name)))
804 goto error;
805 if (service->config.lpLoadOrderGroup &&
806 !((*entry)->config.lpLoadOrderGroup = strdupW(service->config.lpLoadOrderGroup)))
807 goto error;
809 (*entry)->db = db;
811 list_add_tail(&db->services, &(*entry)->entry);
812 mark_for_delete(*entry);
813 return ERROR_SUCCESS;
815 error:
816 free_service_entry(*entry);
817 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
820 static DWORD service_start_process(struct service_entry *service_entry, struct process_entry **new_process,
821 BOOL *shared_process)
823 struct process_entry *process;
824 PROCESS_INFORMATION pi;
825 STARTUPINFOW si;
826 BOOL is_wow64 = FALSE;
827 HANDLE token;
828 WCHAR *path;
829 DWORD err;
830 BOOL r;
832 service_lock(service_entry);
834 if ((process = service_entry->process))
836 if (WaitForSingleObject(process->process, 0) == WAIT_TIMEOUT)
838 service_unlock(service_entry);
839 return ERROR_SERVICE_ALREADY_RUNNING;
841 service_entry->process = NULL;
842 process->use_count--;
843 release_process(process);
846 service_entry->force_shutdown = FALSE;
848 if ((err = get_service_binary_path(service_entry, &path)))
850 service_unlock(service_entry);
851 return err;
854 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER ||
855 service_entry->config.dwServiceType == SERVICE_FILE_SYSTEM_DRIVER)
857 struct service_entry *winedevice_entry;
858 WCHAR *group;
860 if ((err = get_winedevice_binary_path(service_entry, &path, &is_wow64)))
862 service_unlock(service_entry);
863 HeapFree(GetProcessHeap(), 0, path);
864 return err;
867 if ((process = get_winedevice_process(service_entry, path, is_wow64)))
869 HeapFree(GetProcessHeap(), 0, path);
870 goto found;
873 err = add_winedevice_service(service_entry, path, is_wow64, &winedevice_entry);
874 HeapFree(GetProcessHeap(), 0, path);
875 if (err != ERROR_SUCCESS)
877 service_unlock(service_entry);
878 return err;
881 group = strdupW(winedevice_entry->config.lpLoadOrderGroup);
882 service_unlock(service_entry);
884 err = service_start(winedevice_entry, group != NULL, (const WCHAR **)&group);
885 HeapFree(GetProcessHeap(), 0, group);
886 if (err != ERROR_SUCCESS)
888 release_service(winedevice_entry);
889 return err;
892 service_lock(service_entry);
893 process = grab_process(winedevice_entry->process);
894 release_service(winedevice_entry);
896 if (!process)
898 service_unlock(service_entry);
899 return ERROR_SERVICE_REQUEST_TIMEOUT;
902 found:
903 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
904 service_entry->status.dwControlsAccepted = 0;
905 ResetEvent(service_entry->status_changed_event);
907 service_entry->process = grab_process(process);
908 service_entry->shared_process = *shared_process = TRUE;
909 process->use_count++;
910 service_unlock(service_entry);
912 err = WaitForSingleObject(process->control_mutex, 30000);
913 if (err != WAIT_OBJECT_0)
915 release_process(process);
916 return ERROR_SERVICE_REQUEST_TIMEOUT;
919 *new_process = process;
920 return ERROR_SUCCESS;
923 if ((err = process_create(service_get_pipe_name(), &process)))
925 WINE_ERR("failed to create process object for %s, error = %u\n",
926 wine_dbgstr_w(service_entry->name), err);
927 service_unlock(service_entry);
928 HeapFree(GetProcessHeap(), 0, path);
929 return err;
932 ZeroMemory(&si, sizeof(STARTUPINFOW));
933 si.cb = sizeof(STARTUPINFOW);
934 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
936 static WCHAR desktopW[] = {'_','_','w','i','n','e','s','e','r','v','i','c','e','_','w','i','n','s','t','a','t','i','o','n','\\','D','e','f','a','u','l','t',0};
937 si.lpDesktop = desktopW;
940 if (!environment && OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &token))
942 CreateEnvironmentBlock(&environment, token, FALSE);
943 CloseHandle(token);
946 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
947 service_entry->status.dwControlsAccepted = 0;
948 ResetEvent(service_entry->status_changed_event);
950 scmdatabase_add_process(service_entry->db, process);
951 service_entry->process = grab_process(process);
952 service_entry->shared_process = *shared_process = FALSE;
953 process->use_count++;
954 service_unlock(service_entry);
956 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, environment, NULL, &si, &pi);
957 HeapFree(GetProcessHeap(), 0, path);
958 if (!r)
960 err = GetLastError();
961 process_terminate(process);
962 release_process(process);
963 return err;
966 process->process_id = pi.dwProcessId;
967 process->process = pi.hProcess;
968 CloseHandle( pi.hThread );
970 *new_process = process;
971 return ERROR_SUCCESS;
974 static DWORD service_wait_for_startup(struct service_entry *service, struct process_entry *process)
976 HANDLE handles[2] = { service->status_changed_event, process->process };
977 DWORD result;
979 result = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
980 if (result != WAIT_OBJECT_0)
981 return ERROR_SERVICE_REQUEST_TIMEOUT;
983 service_lock(service);
984 result = service->status.dwCurrentState;
985 service_unlock(service);
987 return (result == SERVICE_START_PENDING || result == SERVICE_RUNNING) ?
988 ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
991 /******************************************************************************
992 * process_send_start_message
994 static DWORD process_send_start_message(struct process_entry *process, BOOL shared_process,
995 const WCHAR *name, const WCHAR **argv, DWORD argc)
997 OVERLAPPED overlapped;
998 DWORD i, len, result;
999 WCHAR *str, *p;
1001 WINE_TRACE("%p %s %p %d\n", process, wine_dbgstr_w(name), argv, argc);
1003 overlapped.hEvent = process->overlapped_event;
1004 if (!ConnectNamedPipe(process->control_pipe, &overlapped))
1006 if (GetLastError() == ERROR_IO_PENDING)
1008 HANDLE handles[2];
1009 handles[0] = process->overlapped_event;
1010 handles[1] = process->process;
1011 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
1012 CancelIo(process->control_pipe);
1013 if (!HasOverlappedIoCompleted( &overlapped ))
1015 WINE_ERR("service %s failed to start\n", wine_dbgstr_w(name));
1016 return ERROR_SERVICE_REQUEST_TIMEOUT;
1019 else if (GetLastError() != ERROR_PIPE_CONNECTED)
1021 WINE_ERR("pipe connect failed\n");
1022 return ERROR_SERVICE_REQUEST_TIMEOUT;
1026 len = strlenW(name) + 1;
1027 for (i = 0; i < argc; i++)
1028 len += strlenW(argv[i])+1;
1029 len = (len + 1) * sizeof(WCHAR);
1031 if (!(str = HeapAlloc(GetProcessHeap(), 0, len)))
1032 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
1034 p = str;
1035 strcpyW(p, name);
1036 p += strlenW(name) + 1;
1037 for (i = 0; i < argc; i++)
1039 strcpyW(p, argv[i]);
1040 p += strlenW(p) + 1;
1042 *p = 0;
1044 if (!process_send_control(process, shared_process, name,
1045 SERVICE_CONTROL_START, (const BYTE *)str, len, &result))
1046 result = ERROR_SERVICE_REQUEST_TIMEOUT;
1048 HeapFree(GetProcessHeap(), 0, str);
1049 return result;
1052 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
1054 struct process_entry *process = NULL;
1055 BOOL shared_process;
1056 DWORD err;
1058 err = service_start_process(service, &process, &shared_process);
1059 if (err == ERROR_SUCCESS)
1061 err = process_send_start_message(process, shared_process, service->name, service_argv, service_argc);
1063 if (err == ERROR_SUCCESS)
1064 err = service_wait_for_startup(service, process);
1066 if (err != ERROR_SUCCESS)
1068 service_lock(service);
1069 service->status.dwCurrentState = SERVICE_STOPPED;
1070 service->process = NULL;
1071 if (!--process->use_count) process_terminate(process);
1072 release_process(process);
1073 service_unlock(service);
1076 ReleaseMutex(process->control_mutex);
1077 release_process(process);
1080 WINE_TRACE("returning %d\n", err);
1081 return err;
1084 void process_terminate(struct process_entry *process)
1086 struct scmdatabase *db = process->db;
1087 struct service_entry *service;
1089 scmdatabase_lock(db);
1090 TerminateProcess(process->process, 0);
1091 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
1093 if (service->process != process) continue;
1094 service->status.dwCurrentState = SERVICE_STOPPED;
1095 service->process = NULL;
1096 process->use_count--;
1097 release_process(process);
1099 scmdatabase_unlock(db);
1102 static void load_registry_parameters(void)
1104 static const WCHAR controlW[] =
1105 { 'S','y','s','t','e','m','\\',
1106 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
1107 'C','o','n','t','r','o','l',0 };
1108 static const WCHAR pipetimeoutW[] =
1109 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
1110 static const WCHAR killtimeoutW[] =
1111 {'W','a','i','t','T','o','K','i','l','l','S','e','r','v','i','c','e','T','i','m','e','o','u','t',0};
1112 HKEY key;
1113 WCHAR buffer[64];
1114 DWORD type, count, val;
1116 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
1118 count = sizeof(buffer);
1119 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
1120 type == REG_SZ && (val = atoiW( buffer )))
1121 service_pipe_timeout = val;
1123 count = sizeof(buffer);
1124 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
1125 type == REG_SZ && (val = atoiW( buffer )))
1126 service_kill_timeout = val;
1128 RegCloseKey( key );
1131 int main(int argc, char *argv[])
1133 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
1134 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
1135 'C','o','n','t','r','o','l','\\',
1136 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
1137 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
1138 HANDLE started_event;
1139 DWORD err;
1141 started_event = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1143 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
1144 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
1145 &service_current_key, NULL);
1146 if (err != ERROR_SUCCESS)
1147 return err;
1149 load_registry_parameters();
1150 err = scmdatabase_create(&active_database);
1151 if (err != ERROR_SUCCESS)
1152 return err;
1153 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
1154 return err;
1155 if ((err = RPC_Init()) == ERROR_SUCCESS)
1157 scmdatabase_autostart_services(active_database);
1158 SetEvent(started_event);
1159 WaitForSingleObject(exit_event, INFINITE);
1160 scmdatabase_wait_terminate(active_database);
1161 RPC_Stop();
1163 scmdatabase_destroy(active_database);
1164 if (environment)
1165 DestroyEnvironmentBlock(environment);
1167 WINE_TRACE("services.exe exited with code %d\n", err);
1168 return err;