ucrtbase: Expose the fabsf function on arm.
[wine.git] / programs / services / services.c
blobae5da2bad75bcdd9ccf7c165c2cb0b1b266b3631
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 HANDLE g_hStartedEvent;
40 struct scmdatabase *active_database;
42 DWORD service_pipe_timeout = 10000;
43 DWORD service_kill_timeout = 60000;
44 static DWORD default_preshutdown_timeout = 180000;
45 static void *env = NULL;
46 static HKEY service_current_key = NULL;
48 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
50 static const WCHAR SZ_LOCAL_SYSTEM[] = {'L','o','c','a','l','S','y','s','t','e','m',0};
52 /* Registry constants */
53 static const WCHAR SZ_SERVICES_KEY[] = { 'S','y','s','t','e','m','\\',
54 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
55 'S','e','r','v','i','c','e','s',0 };
57 /* Service key values names */
58 static const WCHAR SZ_DISPLAY_NAME[] = {'D','i','s','p','l','a','y','N','a','m','e',0 };
59 static const WCHAR SZ_TYPE[] = {'T','y','p','e',0 };
60 static const WCHAR SZ_START[] = {'S','t','a','r','t',0 };
61 static const WCHAR SZ_ERROR[] = {'E','r','r','o','r','C','o','n','t','r','o','l',0 };
62 static const WCHAR SZ_IMAGE_PATH[] = {'I','m','a','g','e','P','a','t','h',0};
63 static const WCHAR SZ_GROUP[] = {'G','r','o','u','p',0};
64 static const WCHAR SZ_DEPEND_ON_SERVICE[] = {'D','e','p','e','n','d','O','n','S','e','r','v','i','c','e',0};
65 static const WCHAR SZ_DEPEND_ON_GROUP[] = {'D','e','p','e','n','d','O','n','G','r','o','u','p',0};
66 static const WCHAR SZ_OBJECT_NAME[] = {'O','b','j','e','c','t','N','a','m','e',0};
67 static const WCHAR SZ_TAG[] = {'T','a','g',0};
68 static const WCHAR SZ_DESCRIPTION[] = {'D','e','s','c','r','i','p','t','i','o','n',0};
69 static const WCHAR SZ_PRESHUTDOWN[] = {'P','r','e','s','h','u','t','d','o','w','n','T','i','m','e','o','u','t',0};
70 static const WCHAR SZ_WOW64[] = {'W','O','W','6','4',0};
72 static DWORD process_create(const WCHAR *name, struct process_entry **entry)
74 DWORD err;
76 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
77 if (!*entry)
78 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
79 (*entry)->ref_count = 1;
80 (*entry)->control_mutex = CreateMutexW(NULL, TRUE, NULL);
81 if (!(*entry)->control_mutex)
82 goto error;
83 (*entry)->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
84 if (!(*entry)->overlapped_event)
85 goto error;
86 (*entry)->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
87 if (!(*entry)->status_changed_event)
88 goto error;
89 (*entry)->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
90 PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL);
91 if ((*entry)->control_pipe == INVALID_HANDLE_VALUE)
92 goto error;
93 /* all other fields are zero */
94 return ERROR_SUCCESS;
96 error:
97 err = GetLastError();
98 if ((*entry)->control_mutex)
99 CloseHandle((*entry)->control_mutex);
100 if ((*entry)->overlapped_event)
101 CloseHandle((*entry)->overlapped_event);
102 if ((*entry)->status_changed_event)
103 CloseHandle((*entry)->status_changed_event);
104 HeapFree(GetProcessHeap(), 0, *entry);
105 return err;
108 static void free_process_entry(struct process_entry *entry)
110 CloseHandle(entry->process);
111 CloseHandle(entry->control_mutex);
112 CloseHandle(entry->control_pipe);
113 CloseHandle(entry->overlapped_event);
114 CloseHandle(entry->status_changed_event);
115 HeapFree(GetProcessHeap(), 0, entry);
118 DWORD service_create(LPCWSTR name, struct service_entry **entry)
120 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
121 if (!*entry)
122 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
123 (*entry)->name = strdupW(name);
124 if (!(*entry)->name)
126 HeapFree(GetProcessHeap(), 0, *entry);
127 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
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 HeapFree(GetProcessHeap(), 0, entry->name);
140 HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
141 HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
142 HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
143 HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
144 HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
145 HeapFree(GetProcessHeap(), 0, entry->description);
146 HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
147 HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
148 if (entry->process) release_process(entry->process);
149 HeapFree(GetProcessHeap(), 0, entry);
152 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
154 DWORD err, value = 0;
155 WCHAR *wptr;
157 if ((err = load_reg_string(hKey, SZ_IMAGE_PATH, TRUE, &entry->config.lpBinaryPathName)) != 0)
158 return err;
159 if ((err = load_reg_string(hKey, SZ_GROUP, 0, &entry->config.lpLoadOrderGroup)) != 0)
160 return err;
161 if ((err = load_reg_string(hKey, SZ_OBJECT_NAME, TRUE, &entry->config.lpServiceStartName)) != 0)
162 return err;
163 if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0, &entry->config.lpDisplayName)) != 0)
164 return err;
165 if ((err = load_reg_string(hKey, SZ_DESCRIPTION, 0, &entry->description)) != 0)
166 return err;
167 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
168 return err;
169 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
170 return err;
172 if ((err = load_reg_dword(hKey, SZ_TYPE, &entry->config.dwServiceType)) != 0)
173 return err;
174 if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
175 return err;
176 if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
177 return err;
178 if ((err = load_reg_dword(hKey, SZ_TAG, &entry->config.dwTagId)) != 0)
179 return err;
180 if ((err = load_reg_dword(hKey, SZ_PRESHUTDOWN, &entry->preshutdown_timeout)) != 0)
181 return err;
183 if (load_reg_dword(hKey, SZ_WOW64, &value) == 0 && value == 1)
184 entry->is_wow64 = TRUE;
186 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
187 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
188 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
189 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
190 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
191 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
192 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
193 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
194 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
195 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
197 return ERROR_SUCCESS;
200 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
202 if (!string)
204 DWORD err;
205 err = RegDeleteValueW(hKey, value_name);
206 if (err != ERROR_FILE_NOT_FOUND)
207 return err;
209 return ERROR_SUCCESS;
212 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
215 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
217 const WCHAR *ptr;
219 if (!string)
221 DWORD err;
222 err = RegDeleteValueW(hKey, value_name);
223 if (err != ERROR_FILE_NOT_FOUND)
224 return err;
226 return ERROR_SUCCESS;
229 ptr = string;
230 while (*ptr) ptr += strlenW(ptr) + 1;
231 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
234 DWORD save_service_config(struct service_entry *entry)
236 DWORD err;
237 HKEY hKey = NULL;
239 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
240 if (err != ERROR_SUCCESS)
241 goto cleanup;
243 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
244 goto cleanup;
245 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
246 goto cleanup;
247 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
248 goto cleanup;
249 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
250 goto cleanup;
251 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
252 goto cleanup;
253 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
254 goto cleanup;
255 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
256 goto cleanup;
257 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
258 goto cleanup;
259 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
260 goto cleanup;
261 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
262 goto cleanup;
263 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
264 goto cleanup;
265 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
266 goto cleanup;
267 if (entry->is_wow64)
269 const DWORD is_wow64 = 1;
270 if ((err = RegSetValueExW(hKey, SZ_WOW64, 0, REG_DWORD, (LPBYTE)&is_wow64, sizeof(DWORD))) != 0)
271 goto cleanup;
274 if (entry->config.dwTagId)
275 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
276 else
277 err = RegDeleteValueW(hKey, SZ_TAG);
279 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
280 goto cleanup;
282 err = ERROR_SUCCESS;
283 cleanup:
284 RegCloseKey(hKey);
285 return err;
288 static void scmdatabase_add_process(struct scmdatabase *db, struct process_entry *process)
290 process->db = db;
291 list_add_tail(&db->processes, &process->entry);
294 static void scmdatabase_remove_process(struct scmdatabase *db, struct process_entry *process)
296 list_remove(&process->entry);
297 process->entry.next = process->entry.prev = NULL;
300 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
302 int err;
303 service->db = db;
304 if ((err = save_service_config(service)) != ERROR_SUCCESS)
306 WINE_ERR("Couldn't store service configuration: error %u\n", err);
307 return ERROR_GEN_FAILURE;
310 list_add_tail(&db->services, &service->entry);
311 return ERROR_SUCCESS;
314 static void scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
316 RegDeleteTreeW(db->root_key, service->name);
317 list_remove(&service->entry);
318 service->entry.next = service->entry.prev = NULL;
321 static void scmdatabase_autostart_services(struct scmdatabase *db)
323 struct service_entry **services_list;
324 unsigned int i = 0;
325 unsigned int size = 32;
326 struct service_entry *service;
328 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
329 if (!services_list)
330 return;
332 scmdatabase_lock(db);
334 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
336 if (service->config.dwStartType == SERVICE_BOOT_START ||
337 service->config.dwStartType == SERVICE_SYSTEM_START ||
338 service->config.dwStartType == SERVICE_AUTO_START)
340 if (i+1 >= size)
342 struct service_entry **slist_new;
343 size *= 2;
344 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
345 if (!slist_new)
346 break;
347 services_list = slist_new;
349 services_list[i] = service;
350 InterlockedIncrement(&service->ref_count);
351 i++;
355 scmdatabase_unlock(db);
357 size = i;
358 for (i = 0; i < size; i++)
360 DWORD err;
361 service = services_list[i];
362 err = service_start(service, 0, NULL);
363 if (err != ERROR_SUCCESS)
364 WINE_FIXME("Auto-start service %s failed to start: %d\n",
365 wine_dbgstr_w(service->name), err);
366 release_service(service);
369 HeapFree(GetProcessHeap(), 0, services_list);
372 static void scmdatabase_wait_terminate(struct scmdatabase *db)
374 struct list pending = LIST_INIT(pending);
375 void *ptr;
377 scmdatabase_lock(db);
378 list_move_tail(&pending, &db->processes);
379 while ((ptr = list_head(&pending)))
381 struct process_entry *process = grab_process(LIST_ENTRY(ptr, struct process_entry, entry));
383 scmdatabase_unlock(db);
384 WaitForSingleObject(process->process, INFINITE);
385 scmdatabase_lock(db);
387 list_remove(&process->entry);
388 list_add_tail(&db->processes, &process->entry);
389 release_process(process);
391 scmdatabase_unlock(db);
394 BOOL validate_service_name(LPCWSTR name)
396 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
399 BOOL validate_service_config(struct service_entry *entry)
401 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
403 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
404 return FALSE;
407 switch (entry->config.dwServiceType)
409 case SERVICE_KERNEL_DRIVER:
410 case SERVICE_FILE_SYSTEM_DRIVER:
411 case SERVICE_WIN32_OWN_PROCESS:
412 case SERVICE_WIN32_SHARE_PROCESS:
413 /* No problem */
414 break;
415 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
416 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
417 /* These can be only run as LocalSystem */
418 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
420 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
421 return FALSE;
423 break;
424 default:
425 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
426 return FALSE;
429 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
430 if (entry->config.dwStartType > SERVICE_DISABLED)
432 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
433 return FALSE;
436 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
437 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
438 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
440 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
441 return FALSE;
444 if (entry->config.lpServiceStartName == NULL)
445 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
447 return TRUE;
451 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
453 struct service_entry *service;
455 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
457 if (strcmpiW(name, service->name) == 0)
458 return service;
461 return NULL;
464 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
466 struct service_entry *service;
468 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
470 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
471 return service;
474 return NULL;
477 struct process_entry *grab_process(struct process_entry *process)
479 if (process)
480 InterlockedIncrement(&process->ref_count);
481 return process;
484 void release_process(struct process_entry *process)
486 struct scmdatabase *db = process->db;
488 scmdatabase_lock(db);
489 if (InterlockedDecrement(&process->ref_count) == 0)
491 scmdatabase_remove_process(db, process);
492 free_process_entry(process);
494 scmdatabase_unlock(db);
497 void release_service(struct service_entry *service)
499 struct scmdatabase *db = service->db;
501 scmdatabase_lock(db);
502 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
504 scmdatabase_remove_service(db, service);
505 free_service_entry(service);
507 scmdatabase_unlock(db);
510 static DWORD scmdatabase_create(struct scmdatabase **db)
512 DWORD err;
514 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
515 if (!*db)
516 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
518 (*db)->service_start_lock = FALSE;
519 list_init(&(*db)->processes);
520 list_init(&(*db)->services);
522 InitializeCriticalSection(&(*db)->cs);
523 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
525 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
526 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
527 &(*db)->root_key, NULL);
528 if (err != ERROR_SUCCESS)
529 HeapFree(GetProcessHeap(), 0, *db);
531 return err;
534 static void scmdatabase_destroy(struct scmdatabase *db)
536 RegCloseKey(db->root_key);
537 db->cs.DebugInfo->Spare[0] = 0;
538 DeleteCriticalSection(&db->cs);
539 HeapFree(GetProcessHeap(), 0, db);
542 static DWORD scmdatabase_load_services(struct scmdatabase *db)
544 DWORD err;
545 int i;
547 for (i = 0; TRUE; i++)
549 WCHAR szName[MAX_SERVICE_NAME];
550 struct service_entry *entry;
551 HKEY hServiceKey;
553 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
554 if (err == ERROR_NO_MORE_ITEMS)
555 break;
557 if (err != 0)
559 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
560 continue;
563 err = service_create(szName, &entry);
564 if (err != ERROR_SUCCESS)
565 break;
567 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
568 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
569 if (err == ERROR_SUCCESS)
571 err = load_service_config(hServiceKey, entry);
572 RegCloseKey(hServiceKey);
575 if (err != ERROR_SUCCESS)
577 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
578 free_service_entry(entry);
579 continue;
582 if (entry->config.dwServiceType == 0)
584 /* Maybe an application only wrote some configuration in the service key. Continue silently */
585 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
586 free_service_entry(entry);
587 continue;
590 if (!validate_service_config(entry))
592 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
593 free_service_entry(entry);
594 continue;
597 entry->status.dwServiceType = entry->config.dwServiceType;
598 entry->db = db;
600 list_add_tail(&db->services, &entry->entry);
601 release_service(entry);
603 return ERROR_SUCCESS;
606 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
608 if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
609 return ERROR_SERVICE_DATABASE_LOCKED;
610 return ERROR_SUCCESS;
613 void scmdatabase_unlock_startup(struct scmdatabase *db)
615 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
618 void scmdatabase_lock(struct scmdatabase *db)
620 EnterCriticalSection(&db->cs);
623 void scmdatabase_unlock(struct scmdatabase *db)
625 LeaveCriticalSection(&db->cs);
628 void service_lock(struct service_entry *service)
630 EnterCriticalSection(&service->db->cs);
633 void service_unlock(struct service_entry *service)
635 LeaveCriticalSection(&service->db->cs);
638 /* only one service started at a time, so there is no race on the registry
639 * value here */
640 static LPWSTR service_get_pipe_name(void)
642 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
643 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
644 static WCHAR name[sizeof(format)/sizeof(WCHAR) + 10]; /* strlenW("4294967295") */
645 static DWORD service_current = 0;
646 DWORD len, value = -1;
647 LONG ret;
648 DWORD type;
650 len = sizeof(value);
651 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
652 (BYTE *)&value, &len);
653 if (ret == ERROR_SUCCESS && type == REG_DWORD)
654 service_current = max(service_current, value + 1);
655 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
656 (BYTE *)&service_current, sizeof(service_current));
657 sprintfW(name, format, service_current);
658 service_current++;
659 return name;
662 static DWORD get_service_binary_path(const struct service_entry *service_entry, WCHAR **path)
664 DWORD size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, NULL, 0);
666 *path = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
667 if (!*path)
668 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
670 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, *path, size);
672 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER ||
673 service_entry->config.dwServiceType == SERVICE_FILE_SYSTEM_DRIVER)
675 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
676 WCHAR system_dir[MAX_PATH];
677 DWORD type, len;
679 GetSystemDirectoryW( system_dir, MAX_PATH );
680 if (is_win64)
682 if (!GetBinaryTypeW( *path, &type ))
684 HeapFree( GetProcessHeap(), 0, *path );
685 return GetLastError();
687 if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
690 len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
691 HeapFree( GetProcessHeap(), 0, *path );
692 if (!(*path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
693 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
695 lstrcpyW( *path, system_dir );
696 lstrcatW( *path, winedeviceW );
697 lstrcatW( *path, service_entry->name );
698 return ERROR_SUCCESS;
701 /* if service image is configured to systemdir, redirect it to wow64 systemdir */
702 if (service_entry->is_wow64)
704 WCHAR system_dir[MAX_PATH], *redirected;
705 DWORD len;
707 GetSystemDirectoryW( system_dir, MAX_PATH );
708 len = strlenW( system_dir );
710 if (strncmpiW( system_dir, *path, len ))
711 return ERROR_SUCCESS;
713 GetSystemWow64DirectoryW( system_dir, MAX_PATH );
715 redirected = HeapAlloc( GetProcessHeap(), 0, (strlenW( *path ) + strlenW( system_dir ))*sizeof(WCHAR));
716 if (!redirected)
718 HeapFree( GetProcessHeap(), 0, *path );
719 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
722 strcpyW( redirected, system_dir );
723 strcatW( redirected, &(*path)[len] );
724 HeapFree( GetProcessHeap(), 0, *path );
725 *path = redirected;
726 TRACE("redirected to %s\n", debugstr_w(redirected));
729 return ERROR_SUCCESS;
732 static DWORD service_start_process(struct service_entry *service_entry, struct process_entry **new_process)
734 struct process_entry *process;
735 PROCESS_INFORMATION pi;
736 STARTUPINFOW si;
737 LPWSTR path = NULL;
738 DWORD err;
739 BOOL r;
741 service_lock(service_entry);
743 if ((process = service_entry->process))
745 if (WaitForSingleObject(process->process, 0) == WAIT_TIMEOUT)
747 service_unlock(service_entry);
748 return ERROR_SERVICE_ALREADY_RUNNING;
750 release_process(process);
751 service_entry->process = NULL;
754 service_entry->force_shutdown = FALSE;
756 if ((err = process_create(service_get_pipe_name(), &process)))
758 WINE_ERR("failed to create process object for %s, error = %u\n",
759 wine_dbgstr_w(service_entry->name), err);
760 service_unlock(service_entry);
761 return err;
764 if ((err = get_service_binary_path(service_entry, &path)))
766 service_unlock(service_entry);
767 free_process_entry(process);
768 return err;
771 ZeroMemory(&si, sizeof(STARTUPINFOW));
772 si.cb = sizeof(STARTUPINFOW);
773 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
775 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};
776 si.lpDesktop = desktopW;
779 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
780 scmdatabase_add_process(service_entry->db, process);
781 service_entry->process = process;
783 service_unlock(service_entry);
785 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
786 HeapFree(GetProcessHeap(),0,path);
787 if (!r)
789 err = GetLastError();
790 service_terminate(service_entry);
791 return err;
794 service_entry->status.dwProcessId = pi.dwProcessId;
795 process->process = pi.hProcess;
796 CloseHandle( pi.hThread );
798 *new_process = process;
799 return ERROR_SUCCESS;
802 static DWORD process_wait_for_startup(struct process_entry *process)
804 HANDLE handles[2] = { process->status_changed_event, process->process };
805 DWORD ret;
807 ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
808 return (ret == WAIT_OBJECT_0) ? ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
811 static DWORD service_is_running(struct service_entry *service)
813 DWORD state;
815 service_lock(service);
816 state = service->status.dwCurrentState;
817 service_unlock(service);
819 return (state == SERVICE_START_PENDING || state == SERVICE_RUNNING) ?
820 ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
823 /******************************************************************************
824 * process_send_start_message
826 static BOOL process_send_start_message(struct process_entry *process, const WCHAR *name,
827 LPCWSTR *argv, DWORD argc)
829 OVERLAPPED overlapped;
830 DWORD i, len, result;
831 service_start_info *ssi;
832 LPWSTR p;
833 BOOL r;
835 WINE_TRACE("%p %s %p %d\n", process, wine_dbgstr_w(name), argv, argc);
837 overlapped.hEvent = process->overlapped_event;
838 if (!ConnectNamedPipe(process->control_pipe, &overlapped))
840 if (GetLastError() == ERROR_IO_PENDING)
842 HANDLE handles[2];
843 handles[0] = process->overlapped_event;
844 handles[1] = process->process;
845 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
846 CancelIo(process->control_pipe);
847 if (!HasOverlappedIoCompleted( &overlapped ))
849 WINE_ERR("service %s failed to start\n", wine_dbgstr_w(name));
850 return FALSE;
853 else if (GetLastError() != ERROR_PIPE_CONNECTED)
855 WINE_ERR("pipe connect failed\n");
856 return FALSE;
860 /* calculate how much space do we need to send the startup info */
861 len = strlenW(name) + 1;
862 for (i=0; i<argc; i++)
863 len += strlenW(argv[i])+1;
864 len++;
866 ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
867 ssi->cmd = WINESERV_STARTINFO;
868 ssi->control = 0;
869 ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
870 ssi->name_size = strlenW(name) + 1;
871 strcpyW(ssi->data, name);
873 /* copy service args into a single buffer*/
874 p = &ssi->data[ssi->name_size];
875 for (i=0; i<argc; i++)
877 strcpyW(p, argv[i]);
878 p += strlenW(p) + 1;
880 *p=0;
882 r = process_send_command( process, ssi, ssi->total_size, &result );
883 if (r && result)
885 SetLastError(result);
886 r = FALSE;
889 HeapFree(GetProcessHeap(),0,ssi);
891 return r;
894 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
896 struct process_entry *process = NULL;
897 DWORD err;
899 err = scmdatabase_lock_startup(service->db);
900 if (err != ERROR_SUCCESS)
901 return err;
903 err = service_start_process(service, &process);
904 if (err == ERROR_SUCCESS)
906 if (!process_send_start_message(process, service->name, service_argv, service_argc))
907 err = ERROR_SERVICE_REQUEST_TIMEOUT;
909 if (err == ERROR_SUCCESS)
910 err = process_wait_for_startup(process);
912 if (err == ERROR_SUCCESS)
913 err = service_is_running(service);
915 if (err == ERROR_SUCCESS)
916 ReleaseMutex(process->control_mutex);
917 else
918 service_terminate(service);
921 scmdatabase_unlock_startup(service->db);
923 WINE_TRACE("returning %d\n", err);
925 return err;
928 void service_terminate(struct service_entry *service)
930 struct process_entry *process;
932 service_lock(service);
933 if ((process = service->process))
935 TerminateProcess(process->process, 0);
936 release_process(process);
937 service->process = NULL;
939 service->status.dwProcessId = 0;
940 service->status.dwCurrentState = SERVICE_STOPPED;
941 service_unlock(service);
944 void process_terminate(struct process_entry *process)
946 struct scmdatabase *db = process->db;
947 struct service_entry *service;
949 scmdatabase_lock(db);
950 TerminateProcess(process->process, 0);
951 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
953 if (service->process != process) continue;
954 service->status.dwProcessId = 0;
955 service->status.dwCurrentState = SERVICE_STOPPED;
956 service->process = NULL;
958 scmdatabase_unlock(db);
961 static void load_registry_parameters(void)
963 static const WCHAR controlW[] =
964 { 'S','y','s','t','e','m','\\',
965 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
966 'C','o','n','t','r','o','l',0 };
967 static const WCHAR pipetimeoutW[] =
968 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
969 static const WCHAR killtimeoutW[] =
970 {'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};
971 HKEY key;
972 WCHAR buffer[64];
973 DWORD type, count, val;
975 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
977 count = sizeof(buffer);
978 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
979 type == REG_SZ && (val = atoiW( buffer )))
980 service_pipe_timeout = val;
982 count = sizeof(buffer);
983 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
984 type == REG_SZ && (val = atoiW( buffer )))
985 service_kill_timeout = val;
987 RegCloseKey( key );
990 int main(int argc, char *argv[])
992 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
993 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
994 'C','o','n','t','r','o','l','\\',
995 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
996 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
997 HANDLE htok;
998 DWORD err;
1000 g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
1002 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
1004 CreateEnvironmentBlock(&env, htok, FALSE);
1005 CloseHandle(htok);
1008 if (!env)
1009 WINE_ERR("failed to create services environment\n");
1011 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
1012 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
1013 &service_current_key, NULL);
1014 if (err != ERROR_SUCCESS)
1015 return err;
1017 load_registry_parameters();
1018 err = scmdatabase_create(&active_database);
1019 if (err != ERROR_SUCCESS)
1020 return err;
1021 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
1022 return err;
1023 if ((err = RPC_Init()) == ERROR_SUCCESS)
1025 scmdatabase_autostart_services(active_database);
1026 events_loop();
1027 scmdatabase_wait_terminate(active_database);
1029 scmdatabase_destroy(active_database);
1030 if (env)
1031 DestroyEnvironmentBlock(env);
1033 WINE_TRACE("services.exe exited with code %d\n", err);
1034 return err;