ntdll: Use close_handle instead of NtClose for internal memory management functions.
[wine.git] / programs / services / services.c
blob8f53e7e7cef66c11991e791716b649f044dd0187
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;
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(struct process_entry **entry)
73 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
74 if (!*entry)
75 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
76 (*entry)->ref_count = 1;
77 (*entry)->control_pipe = INVALID_HANDLE_VALUE;
78 /* all other fields are zero */
79 return ERROR_SUCCESS;
82 static void free_process_entry(struct process_entry *entry)
84 CloseHandle(entry->process);
85 CloseHandle(entry->control_mutex);
86 CloseHandle(entry->control_pipe);
87 CloseHandle(entry->overlapped_event);
88 CloseHandle(entry->status_changed_event);
89 HeapFree(GetProcessHeap(), 0, entry);
92 DWORD service_create(LPCWSTR name, struct service_entry **entry)
94 DWORD err;
96 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
97 if (!*entry)
98 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
99 (*entry)->name = strdupW(name);
100 if (!(*entry)->name)
102 HeapFree(GetProcessHeap(), 0, *entry);
103 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
105 if ((err = process_create(&(*entry)->process)) != ERROR_SUCCESS)
107 HeapFree(GetProcessHeap(), 0, (*entry)->name);
108 HeapFree(GetProcessHeap(), 0, *entry);
109 return err;
111 (*entry)->ref_count = 1;
112 (*entry)->status.dwCurrentState = SERVICE_STOPPED;
113 (*entry)->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
114 (*entry)->preshutdown_timeout = default_preshutdown_timeout;
115 /* all other fields are zero */
116 return ERROR_SUCCESS;
119 void free_service_entry(struct service_entry *entry)
121 HeapFree(GetProcessHeap(), 0, entry->name);
122 HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
123 HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
124 HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
125 HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
126 HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
127 HeapFree(GetProcessHeap(), 0, entry->description);
128 HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
129 HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
130 release_process(entry->process);
131 HeapFree(GetProcessHeap(), 0, entry);
134 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
136 DWORD err, value = 0;
137 WCHAR *wptr;
139 if ((err = load_reg_string(hKey, SZ_IMAGE_PATH, TRUE, &entry->config.lpBinaryPathName)) != 0)
140 return err;
141 if ((err = load_reg_string(hKey, SZ_GROUP, 0, &entry->config.lpLoadOrderGroup)) != 0)
142 return err;
143 if ((err = load_reg_string(hKey, SZ_OBJECT_NAME, TRUE, &entry->config.lpServiceStartName)) != 0)
144 return err;
145 if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0, &entry->config.lpDisplayName)) != 0)
146 return err;
147 if ((err = load_reg_string(hKey, SZ_DESCRIPTION, 0, &entry->description)) != 0)
148 return err;
149 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
150 return err;
151 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
152 return err;
154 if ((err = load_reg_dword(hKey, SZ_TYPE, &entry->config.dwServiceType)) != 0)
155 return err;
156 if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
157 return err;
158 if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
159 return err;
160 if ((err = load_reg_dword(hKey, SZ_TAG, &entry->config.dwTagId)) != 0)
161 return err;
162 if ((err = load_reg_dword(hKey, SZ_PRESHUTDOWN, &entry->preshutdown_timeout)) != 0)
163 return err;
165 if (load_reg_dword(hKey, SZ_WOW64, &value) == 0 && value == 1)
166 entry->is_wow64 = TRUE;
168 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
169 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
170 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
171 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
172 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
173 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
174 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
175 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
176 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
177 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
179 return ERROR_SUCCESS;
182 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
184 if (!string)
186 DWORD err;
187 err = RegDeleteValueW(hKey, value_name);
188 if (err != ERROR_FILE_NOT_FOUND)
189 return err;
191 return ERROR_SUCCESS;
194 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
197 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
199 const WCHAR *ptr;
201 if (!string)
203 DWORD err;
204 err = RegDeleteValueW(hKey, value_name);
205 if (err != ERROR_FILE_NOT_FOUND)
206 return err;
208 return ERROR_SUCCESS;
211 ptr = string;
212 while (*ptr) ptr += strlenW(ptr) + 1;
213 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
216 DWORD save_service_config(struct service_entry *entry)
218 DWORD err;
219 HKEY hKey = NULL;
221 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
222 if (err != ERROR_SUCCESS)
223 goto cleanup;
225 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
226 goto cleanup;
227 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
228 goto cleanup;
229 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
230 goto cleanup;
231 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
232 goto cleanup;
233 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
234 goto cleanup;
235 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
236 goto cleanup;
237 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
238 goto cleanup;
239 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
240 goto cleanup;
241 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
242 goto cleanup;
243 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
244 goto cleanup;
245 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
246 goto cleanup;
247 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
248 goto cleanup;
249 if (entry->is_wow64)
251 const DWORD is_wow64 = 1;
252 if ((err = RegSetValueExW(hKey, SZ_WOW64, 0, REG_DWORD, (LPBYTE)&is_wow64, sizeof(DWORD))) != 0)
253 goto cleanup;
256 if (entry->config.dwTagId)
257 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
258 else
259 err = RegDeleteValueW(hKey, SZ_TAG);
261 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
262 goto cleanup;
264 err = ERROR_SUCCESS;
265 cleanup:
266 RegCloseKey(hKey);
267 return err;
270 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
272 int err;
273 service->db = db;
274 if ((err = save_service_config(service)) != ERROR_SUCCESS)
276 WINE_ERR("Couldn't store service configuration: error %u\n", err);
277 return ERROR_GEN_FAILURE;
280 list_add_tail(&db->services, &service->entry);
281 return ERROR_SUCCESS;
284 static DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
286 int err;
288 err = RegDeleteTreeW(db->root_key, service->name);
290 if (err != 0)
291 return err;
293 list_remove(&service->entry);
294 service->entry.next = service->entry.prev = NULL;
295 return ERROR_SUCCESS;
298 static void scmdatabase_autostart_services(struct scmdatabase *db)
300 struct service_entry **services_list;
301 unsigned int i = 0;
302 unsigned int size = 32;
303 struct service_entry *service;
305 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
306 if (!services_list)
307 return;
309 scmdatabase_lock(db);
311 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
313 if (service->config.dwStartType == SERVICE_BOOT_START ||
314 service->config.dwStartType == SERVICE_SYSTEM_START ||
315 service->config.dwStartType == SERVICE_AUTO_START)
317 if (i+1 >= size)
319 struct service_entry **slist_new;
320 size *= 2;
321 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
322 if (!slist_new)
323 break;
324 services_list = slist_new;
326 services_list[i] = service;
327 InterlockedIncrement(&service->ref_count);
328 i++;
332 scmdatabase_unlock(db);
334 size = i;
335 for (i = 0; i < size; i++)
337 DWORD err;
338 service = services_list[i];
339 err = service_start(service, 0, NULL);
340 if (err != ERROR_SUCCESS)
341 WINE_FIXME("Auto-start service %s failed to start: %d\n",
342 wine_dbgstr_w(service->name), err);
343 release_service(service);
346 HeapFree(GetProcessHeap(), 0, services_list);
349 static void scmdatabase_wait_terminate(struct scmdatabase *db)
351 struct service_entry *service;
352 BOOL run = TRUE;
354 scmdatabase_lock(db);
355 while(run)
357 run = FALSE;
358 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
360 struct process_entry *process = service->process;
361 if (process->process)
363 scmdatabase_unlock(db);
364 WaitForSingleObject(process->process, INFINITE);
365 scmdatabase_lock(db);
366 CloseHandle(process->process);
367 process->process = NULL;
368 run = TRUE;
369 break;
373 scmdatabase_unlock(db);
376 BOOL validate_service_name(LPCWSTR name)
378 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
381 BOOL validate_service_config(struct service_entry *entry)
383 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
385 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
386 return FALSE;
389 switch (entry->config.dwServiceType)
391 case SERVICE_KERNEL_DRIVER:
392 case SERVICE_FILE_SYSTEM_DRIVER:
393 case SERVICE_WIN32_OWN_PROCESS:
394 case SERVICE_WIN32_SHARE_PROCESS:
395 /* No problem */
396 break;
397 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
398 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
399 /* These can be only run as LocalSystem */
400 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
402 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
403 return FALSE;
405 break;
406 default:
407 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
408 return FALSE;
411 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
412 if (entry->config.dwStartType > SERVICE_DISABLED)
414 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
415 return FALSE;
418 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
419 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
420 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
422 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
423 return FALSE;
426 if (entry->config.lpServiceStartName == NULL)
427 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
429 return TRUE;
433 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
435 struct service_entry *service;
437 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
439 if (strcmpiW(name, service->name) == 0)
440 return service;
443 return NULL;
446 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
448 struct service_entry *service;
450 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
452 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
453 return service;
456 return NULL;
459 void release_process(struct process_entry *process)
461 if (InterlockedDecrement(&process->ref_count) == 0)
462 free_process_entry(process);
465 void release_service(struct service_entry *service)
467 struct scmdatabase *db = service->db;
469 scmdatabase_lock(db);
470 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
472 scmdatabase_remove_service(db, service);
473 free_service_entry(service);
475 scmdatabase_unlock(db);
478 static DWORD scmdatabase_create(struct scmdatabase **db)
480 DWORD err;
482 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
483 if (!*db)
484 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
486 (*db)->service_start_lock = FALSE;
487 list_init(&(*db)->services);
489 InitializeCriticalSection(&(*db)->cs);
490 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
492 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
493 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
494 &(*db)->root_key, NULL);
495 if (err != ERROR_SUCCESS)
496 HeapFree(GetProcessHeap(), 0, *db);
498 return err;
501 static void scmdatabase_destroy(struct scmdatabase *db)
503 RegCloseKey(db->root_key);
504 db->cs.DebugInfo->Spare[0] = 0;
505 DeleteCriticalSection(&db->cs);
506 HeapFree(GetProcessHeap(), 0, db);
509 static DWORD scmdatabase_load_services(struct scmdatabase *db)
511 DWORD err;
512 int i;
514 for (i = 0; TRUE; i++)
516 WCHAR szName[MAX_SERVICE_NAME];
517 struct service_entry *entry;
518 HKEY hServiceKey;
520 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
521 if (err == ERROR_NO_MORE_ITEMS)
522 break;
524 if (err != 0)
526 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
527 continue;
530 err = service_create(szName, &entry);
531 if (err != ERROR_SUCCESS)
532 break;
534 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
535 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
536 if (err == ERROR_SUCCESS)
538 err = load_service_config(hServiceKey, entry);
539 RegCloseKey(hServiceKey);
542 if (err != ERROR_SUCCESS)
544 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
545 free_service_entry(entry);
546 continue;
549 if (entry->config.dwServiceType == 0)
551 /* Maybe an application only wrote some configuration in the service key. Continue silently */
552 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
553 free_service_entry(entry);
554 continue;
557 if (!validate_service_config(entry))
559 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
560 free_service_entry(entry);
561 continue;
564 entry->status.dwServiceType = entry->config.dwServiceType;
565 entry->db = db;
567 list_add_tail(&db->services, &entry->entry);
568 release_service(entry);
570 return ERROR_SUCCESS;
573 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
575 if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
576 return ERROR_SERVICE_DATABASE_LOCKED;
577 return ERROR_SUCCESS;
580 void scmdatabase_unlock_startup(struct scmdatabase *db)
582 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
585 void scmdatabase_lock(struct scmdatabase *db)
587 EnterCriticalSection(&db->cs);
590 void scmdatabase_unlock(struct scmdatabase *db)
592 LeaveCriticalSection(&db->cs);
595 void service_lock(struct service_entry *service)
597 EnterCriticalSection(&service->db->cs);
600 void service_unlock(struct service_entry *service)
602 LeaveCriticalSection(&service->db->cs);
605 /* only one service started at a time, so there is no race on the registry
606 * value here */
607 static LPWSTR service_get_pipe_name(void)
609 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
610 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
611 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
612 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
613 'C','o','n','t','r','o','l','\\',
614 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
615 LPWSTR name;
616 DWORD len;
617 HKEY service_current_key;
618 DWORD service_current = -1;
619 LONG ret;
620 DWORD type;
622 ret = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
623 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
624 &service_current_key, NULL);
625 if (ret != ERROR_SUCCESS)
626 return NULL;
627 len = sizeof(service_current);
628 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
629 (BYTE *)&service_current, &len);
630 if ((ret == ERROR_SUCCESS && type == REG_DWORD) || ret == ERROR_FILE_NOT_FOUND)
632 service_current++;
633 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
634 (BYTE *)&service_current, sizeof(service_current));
636 RegCloseKey(service_current_key);
637 if ((ret != ERROR_SUCCESS || type != REG_DWORD) && (ret != ERROR_FILE_NOT_FOUND))
638 return NULL;
639 len = sizeof(format)/sizeof(WCHAR) + 10 /* strlenW("4294967295") */;
640 name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
641 if (!name)
642 return NULL;
643 snprintfW(name, len, format, service_current);
644 return name;
647 static DWORD get_service_binary_path(const struct service_entry *service_entry, WCHAR **path)
649 DWORD size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, NULL, 0);
651 *path = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
652 if (!*path)
653 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
655 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, *path, size);
657 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER ||
658 service_entry->config.dwServiceType == SERVICE_FILE_SYSTEM_DRIVER)
660 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
661 WCHAR system_dir[MAX_PATH];
662 DWORD type, len;
664 GetSystemDirectoryW( system_dir, MAX_PATH );
665 if (is_win64)
667 if (!GetBinaryTypeW( *path, &type ))
669 HeapFree( GetProcessHeap(), 0, *path );
670 return GetLastError();
672 if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
675 len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
676 HeapFree( GetProcessHeap(), 0, *path );
677 if (!(*path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
678 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
680 lstrcpyW( *path, system_dir );
681 lstrcatW( *path, winedeviceW );
682 lstrcatW( *path, service_entry->name );
683 return ERROR_SUCCESS;
686 /* if service image is configured to systemdir, redirect it to wow64 systemdir */
687 if (service_entry->is_wow64)
689 WCHAR system_dir[MAX_PATH], *redirected;
690 DWORD len;
692 GetSystemDirectoryW( system_dir, MAX_PATH );
693 len = strlenW( system_dir );
695 if (strncmpiW( system_dir, *path, len ))
696 return ERROR_SUCCESS;
698 GetSystemWow64DirectoryW( system_dir, MAX_PATH );
700 redirected = HeapAlloc( GetProcessHeap(), 0, (strlenW( *path ) + strlenW( system_dir ))*sizeof(WCHAR));
701 if (!redirected)
703 HeapFree( GetProcessHeap(), 0, *path );
704 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
707 strcpyW( redirected, system_dir );
708 strcatW( redirected, &(*path)[len] );
709 HeapFree( GetProcessHeap(), 0, *path );
710 *path = redirected;
711 TRACE("redirected to %s\n", debugstr_w(redirected));
714 return ERROR_SUCCESS;
717 static DWORD service_start_process(struct service_entry *service_entry)
719 PROCESS_INFORMATION pi;
720 STARTUPINFOW si;
721 LPWSTR path = NULL;
722 DWORD err;
723 BOOL r;
725 service_lock(service_entry);
727 if (!env)
729 HANDLE htok;
731 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
732 CreateEnvironmentBlock(&env, htok, FALSE);
734 if (!env)
735 WINE_ERR("failed to create services environment\n");
738 if ((err = get_service_binary_path(service_entry, &path)))
740 service_unlock(service_entry);
741 return err;
744 ZeroMemory(&si, sizeof(STARTUPINFOW));
745 si.cb = sizeof(STARTUPINFOW);
746 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
748 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};
749 si.lpDesktop = desktopW;
752 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
754 service_unlock(service_entry);
756 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
757 HeapFree(GetProcessHeap(),0,path);
758 if (!r)
760 service_lock(service_entry);
761 service_entry->status.dwCurrentState = SERVICE_STOPPED;
762 service_unlock(service_entry);
763 return GetLastError();
766 service_entry->status.dwProcessId = pi.dwProcessId;
767 service_entry->process->process = pi.hProcess;
768 CloseHandle( pi.hThread );
770 return ERROR_SUCCESS;
773 static DWORD process_wait_for_startup(struct process_entry *process)
775 HANDLE handles[2] = { process->status_changed_event, process->process };
776 DWORD ret;
778 ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
779 return (ret == WAIT_OBJECT_0) ? ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
782 static DWORD service_is_running(struct service_entry *service)
784 DWORD state;
786 service_lock(service);
787 state = service->status.dwCurrentState;
788 service_unlock(service);
790 return (state == SERVICE_START_PENDING || state == SERVICE_RUNNING) ?
791 ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
794 /******************************************************************************
795 * process_send_start_message
797 static BOOL process_send_start_message(struct process_entry *process, const WCHAR *name,
798 LPCWSTR *argv, DWORD argc)
800 OVERLAPPED overlapped;
801 DWORD i, len, result;
802 service_start_info *ssi;
803 LPWSTR p;
804 BOOL r;
806 WINE_TRACE("%p %s %p %d\n", process, wine_dbgstr_w(name), argv, argc);
808 overlapped.hEvent = process->overlapped_event;
809 if (!ConnectNamedPipe(process->control_pipe, &overlapped))
811 if (GetLastError() == ERROR_IO_PENDING)
813 HANDLE handles[2];
814 handles[0] = process->overlapped_event;
815 handles[1] = process->process;
816 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
817 CancelIo(process->control_pipe);
818 if (!HasOverlappedIoCompleted( &overlapped ))
820 WINE_ERR("service %s failed to start\n", wine_dbgstr_w(name));
821 return FALSE;
824 else if (GetLastError() != ERROR_PIPE_CONNECTED)
826 WINE_ERR("pipe connect failed\n");
827 return FALSE;
831 /* calculate how much space do we need to send the startup info */
832 len = strlenW(name) + 1;
833 for (i=0; i<argc; i++)
834 len += strlenW(argv[i])+1;
835 len++;
837 ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
838 ssi->cmd = WINESERV_STARTINFO;
839 ssi->control = 0;
840 ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
841 ssi->name_size = strlenW(name) + 1;
842 strcpyW(ssi->data, name);
844 /* copy service args into a single buffer*/
845 p = &ssi->data[ssi->name_size];
846 for (i=0; i<argc; i++)
848 strcpyW(p, argv[i]);
849 p += strlenW(p) + 1;
851 *p=0;
853 r = process_send_command( process, ssi, ssi->total_size, &result );
854 if (r && result)
856 SetLastError(result);
857 r = FALSE;
860 HeapFree(GetProcessHeap(),0,ssi);
862 return r;
865 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
867 struct process_entry *process = service->process;
868 DWORD err;
869 LPWSTR name;
871 err = scmdatabase_lock_startup(service->db);
872 if (err != ERROR_SUCCESS)
873 return err;
875 if (WaitForSingleObject(process->process, 0) == WAIT_TIMEOUT)
877 scmdatabase_unlock_startup(service->db);
878 return ERROR_SERVICE_ALREADY_RUNNING;
881 CloseHandle(process->control_pipe);
882 process->control_mutex = CreateMutexW(NULL, TRUE, NULL);
883 service->force_shutdown = FALSE;
885 if (!process->status_changed_event)
886 process->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
887 if (!process->overlapped_event)
888 process->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
890 name = service_get_pipe_name();
891 process->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
892 PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
893 HeapFree(GetProcessHeap(), 0, name);
894 if (process->control_pipe == INVALID_HANDLE_VALUE)
896 WINE_ERR("failed to create pipe for %s, error = %d\n",
897 wine_dbgstr_w(service->name), GetLastError());
898 err = GetLastError();
900 else
902 err = service_start_process(service);
903 if (err == ERROR_SUCCESS)
905 if (!process_send_start_message(process, service->name, service_argv, service_argc))
906 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);
916 if (err == ERROR_SUCCESS)
917 ReleaseMutex(process->control_mutex);
918 else
919 service_terminate(service);
920 scmdatabase_unlock_startup(service->db);
922 WINE_TRACE("returning %d\n", err);
924 return err;
927 void service_terminate(struct service_entry *service)
929 struct process_entry *process = service->process;
931 service_lock(service);
932 TerminateProcess(process->process, 0);
933 CloseHandle(process->process);
934 process->process = NULL;
935 CloseHandle(process->status_changed_event);
936 process->status_changed_event = NULL;
937 CloseHandle(process->control_mutex);
938 process->control_mutex = NULL;
939 CloseHandle(process->control_pipe);
940 process->control_pipe = INVALID_HANDLE_VALUE;
942 service->status.dwProcessId = 0;
943 service->status.dwCurrentState = SERVICE_STOPPED;
944 service_unlock(service);
947 static void load_registry_parameters(void)
949 static const WCHAR controlW[] =
950 { 'S','y','s','t','e','m','\\',
951 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
952 'C','o','n','t','r','o','l',0 };
953 static const WCHAR pipetimeoutW[] =
954 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
955 static const WCHAR killtimeoutW[] =
956 {'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};
957 HKEY key;
958 WCHAR buffer[64];
959 DWORD type, count, val;
961 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
963 count = sizeof(buffer);
964 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
965 type == REG_SZ && (val = atoiW( buffer )))
966 service_pipe_timeout = val;
968 count = sizeof(buffer);
969 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
970 type == REG_SZ && (val = atoiW( buffer )))
971 service_kill_timeout = val;
973 RegCloseKey( key );
976 int main(int argc, char *argv[])
978 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
979 DWORD err;
981 g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
982 load_registry_parameters();
983 err = scmdatabase_create(&active_database);
984 if (err != ERROR_SUCCESS)
985 return err;
986 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
987 return err;
988 if ((err = RPC_Init()) == ERROR_SUCCESS)
990 scmdatabase_autostart_services(active_database);
991 events_loop();
992 scmdatabase_wait_terminate(active_database);
994 scmdatabase_destroy(active_database);
995 if (env)
996 DestroyEnvironmentBlock(env);
998 WINE_TRACE("services.exe exited with code %d\n", err);
999 return err;