ntdll: Print process id in the relay log if requested.
[wine/multimedia.git] / programs / services / services.c
blob133583782746007fd2ad8a680f079404cdb31711
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 DWORD service_create(LPCWSTR name, struct service_entry **entry)
73 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
74 if (!*entry)
75 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
76 (*entry)->name = strdupW(name);
77 if (!(*entry)->name)
79 HeapFree(GetProcessHeap(), 0, *entry);
80 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
82 (*entry)->control_pipe = INVALID_HANDLE_VALUE;
83 (*entry)->status.dwCurrentState = SERVICE_STOPPED;
84 (*entry)->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
85 (*entry)->preshutdown_timeout = default_preshutdown_timeout;
86 /* all other fields are zero */
87 return ERROR_SUCCESS;
90 void free_service_entry(struct service_entry *entry)
92 HeapFree(GetProcessHeap(), 0, entry->name);
93 HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
94 HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
95 HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
96 HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
97 HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
98 HeapFree(GetProcessHeap(), 0, entry->description);
99 HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
100 HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
101 CloseHandle(entry->process);
102 CloseHandle(entry->control_mutex);
103 CloseHandle(entry->control_pipe);
104 CloseHandle(entry->overlapped_event);
105 CloseHandle(entry->status_changed_event);
106 HeapFree(GetProcessHeap(), 0, entry);
109 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
111 DWORD err, value = 0;
112 WCHAR *wptr;
114 if ((err = load_reg_string(hKey, SZ_IMAGE_PATH, TRUE, &entry->config.lpBinaryPathName)) != 0)
115 return err;
116 if ((err = load_reg_string(hKey, SZ_GROUP, 0, &entry->config.lpLoadOrderGroup)) != 0)
117 return err;
118 if ((err = load_reg_string(hKey, SZ_OBJECT_NAME, TRUE, &entry->config.lpServiceStartName)) != 0)
119 return err;
120 if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0, &entry->config.lpDisplayName)) != 0)
121 return err;
122 if ((err = load_reg_string(hKey, SZ_DESCRIPTION, 0, &entry->description)) != 0)
123 return err;
124 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
125 return err;
126 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
127 return err;
129 if ((err = load_reg_dword(hKey, SZ_TYPE, &entry->config.dwServiceType)) != 0)
130 return err;
131 if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
132 return err;
133 if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
134 return err;
135 if ((err = load_reg_dword(hKey, SZ_TAG, &entry->config.dwTagId)) != 0)
136 return err;
137 if ((err = load_reg_dword(hKey, SZ_PRESHUTDOWN, &entry->preshutdown_timeout)) != 0)
138 return err;
140 if (load_reg_dword(hKey, SZ_WOW64, &value) == 0 && value == 1)
141 entry->is_wow64 = TRUE;
143 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
144 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
145 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
146 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
147 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
148 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
149 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
150 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
151 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
152 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
154 return ERROR_SUCCESS;
157 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
159 if (!string)
161 DWORD err;
162 err = RegDeleteValueW(hKey, value_name);
163 if (err != ERROR_FILE_NOT_FOUND)
164 return err;
166 return ERROR_SUCCESS;
169 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
172 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
174 const WCHAR *ptr;
176 if (!string)
178 DWORD err;
179 err = RegDeleteValueW(hKey, value_name);
180 if (err != ERROR_FILE_NOT_FOUND)
181 return err;
183 return ERROR_SUCCESS;
186 ptr = string;
187 while (*ptr) ptr += strlenW(ptr) + 1;
188 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
191 DWORD save_service_config(struct service_entry *entry)
193 DWORD err;
194 HKEY hKey = NULL;
196 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
197 if (err != ERROR_SUCCESS)
198 goto cleanup;
200 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
201 goto cleanup;
202 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
203 goto cleanup;
204 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
205 goto cleanup;
206 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
207 goto cleanup;
208 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
209 goto cleanup;
210 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
211 goto cleanup;
212 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
213 goto cleanup;
214 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
215 goto cleanup;
216 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
217 goto cleanup;
218 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
219 goto cleanup;
220 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
221 goto cleanup;
222 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
223 goto cleanup;
224 if (entry->is_wow64)
226 const DWORD is_wow64 = 1;
227 if ((err = RegSetValueExW(hKey, SZ_WOW64, 0, REG_DWORD, (LPBYTE)&is_wow64, sizeof(DWORD))) != 0)
228 goto cleanup;
231 if (entry->config.dwTagId)
232 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
233 else
234 err = RegDeleteValueW(hKey, SZ_TAG);
236 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
237 goto cleanup;
239 err = ERROR_SUCCESS;
240 cleanup:
241 RegCloseKey(hKey);
242 return err;
245 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
247 int err;
248 service->db = db;
249 if ((err = save_service_config(service)) != ERROR_SUCCESS)
251 WINE_ERR("Couldn't store service configuration: error %u\n", err);
252 return ERROR_GEN_FAILURE;
255 list_add_tail(&db->services, &service->entry);
256 return ERROR_SUCCESS;
259 static DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
261 int err;
263 err = RegDeleteTreeW(db->root_key, service->name);
265 if (err != 0)
266 return err;
268 list_remove(&service->entry);
269 service->entry.next = service->entry.prev = NULL;
270 return ERROR_SUCCESS;
273 static void scmdatabase_autostart_services(struct scmdatabase *db)
275 struct service_entry **services_list;
276 unsigned int i = 0;
277 unsigned int size = 32;
278 struct service_entry *service;
280 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
281 if (!services_list)
282 return;
284 scmdatabase_lock_shared(db);
286 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
288 if (service->config.dwStartType == SERVICE_BOOT_START ||
289 service->config.dwStartType == SERVICE_SYSTEM_START ||
290 service->config.dwStartType == SERVICE_AUTO_START)
292 if (i+1 >= size)
294 struct service_entry **slist_new;
295 size *= 2;
296 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
297 if (!slist_new)
298 break;
299 services_list = slist_new;
301 services_list[i] = service;
302 service->ref_count++;
303 i++;
307 scmdatabase_unlock(db);
309 size = i;
310 for (i = 0; i < size; i++)
312 DWORD err;
313 service = services_list[i];
314 err = service_start(service, 0, NULL);
315 if (err != ERROR_SUCCESS)
316 WINE_FIXME("Auto-start service %s failed to start: %d\n",
317 wine_dbgstr_w(service->name), err);
318 release_service(service);
321 HeapFree(GetProcessHeap(), 0, services_list);
324 static void scmdatabase_wait_terminate(struct scmdatabase *db)
326 struct service_entry *service;
327 BOOL run = TRUE;
329 scmdatabase_lock_shared(db);
330 while(run)
332 run = FALSE;
333 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
335 if(service->process)
337 scmdatabase_unlock(db);
338 WaitForSingleObject(service->process, INFINITE);
339 scmdatabase_lock_shared(db);
340 CloseHandle(service->process);
341 service->process = NULL;
342 run = TRUE;
343 break;
347 scmdatabase_unlock(db);
350 BOOL validate_service_name(LPCWSTR name)
352 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
355 BOOL validate_service_config(struct service_entry *entry)
357 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
359 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
360 return FALSE;
363 switch (entry->config.dwServiceType)
365 case SERVICE_KERNEL_DRIVER:
366 case SERVICE_FILE_SYSTEM_DRIVER:
367 case SERVICE_WIN32_OWN_PROCESS:
368 case SERVICE_WIN32_SHARE_PROCESS:
369 /* No problem */
370 break;
371 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
372 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
373 /* These can be only run as LocalSystem */
374 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
376 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
377 return FALSE;
379 break;
380 default:
381 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
382 return FALSE;
385 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
386 if (entry->config.dwStartType > SERVICE_DISABLED)
388 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
389 return FALSE;
392 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
393 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
394 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
396 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
397 return FALSE;
400 if (entry->config.lpServiceStartName == NULL)
401 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
403 return TRUE;
407 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
409 struct service_entry *service;
411 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
413 if (strcmpiW(name, service->name) == 0)
414 return service;
417 return NULL;
420 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
422 struct service_entry *service;
424 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
426 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
427 return service;
430 return NULL;
433 void release_service(struct service_entry *service)
435 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
437 scmdatabase_lock_exclusive(service->db);
438 service_lock_exclusive(service);
439 scmdatabase_remove_service(service->db, service);
440 service_unlock(service);
441 scmdatabase_unlock(service->db);
442 free_service_entry(service);
446 static DWORD scmdatabase_create(struct scmdatabase **db)
448 DWORD err;
450 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
451 if (!*db)
452 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
454 (*db)->service_start_lock = FALSE;
455 list_init(&(*db)->services);
457 InitializeCriticalSection(&(*db)->cs);
458 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
460 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
461 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
462 &(*db)->root_key, NULL);
463 if (err != ERROR_SUCCESS)
464 HeapFree(GetProcessHeap(), 0, *db);
466 return err;
469 static void scmdatabase_destroy(struct scmdatabase *db)
471 RegCloseKey(db->root_key);
472 db->cs.DebugInfo->Spare[0] = 0;
473 DeleteCriticalSection(&db->cs);
474 HeapFree(GetProcessHeap(), 0, db);
477 static DWORD scmdatabase_load_services(struct scmdatabase *db)
479 DWORD err;
480 int i;
482 for (i = 0; TRUE; i++)
484 WCHAR szName[MAX_SERVICE_NAME];
485 struct service_entry *entry;
486 HKEY hServiceKey;
488 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
489 if (err == ERROR_NO_MORE_ITEMS)
490 break;
492 if (err != 0)
494 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
495 continue;
498 err = service_create(szName, &entry);
499 if (err != ERROR_SUCCESS)
500 break;
502 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
503 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
504 if (err == ERROR_SUCCESS)
506 err = load_service_config(hServiceKey, entry);
507 RegCloseKey(hServiceKey);
510 if (err != ERROR_SUCCESS)
512 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
513 free_service_entry(entry);
514 continue;
517 if (entry->config.dwServiceType == 0)
519 /* Maybe an application only wrote some configuration in the service key. Continue silently */
520 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
521 free_service_entry(entry);
522 continue;
525 if (!validate_service_config(entry))
527 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
528 free_service_entry(entry);
529 continue;
532 entry->status.dwServiceType = entry->config.dwServiceType;
533 entry->db = db;
535 list_add_tail(&db->services, &entry->entry);
537 return ERROR_SUCCESS;
540 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
542 if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
543 return ERROR_SERVICE_DATABASE_LOCKED;
544 return ERROR_SUCCESS;
547 void scmdatabase_unlock_startup(struct scmdatabase *db)
549 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
552 void scmdatabase_lock_shared(struct scmdatabase *db)
554 EnterCriticalSection(&db->cs);
557 void scmdatabase_lock_exclusive(struct scmdatabase *db)
559 EnterCriticalSection(&db->cs);
562 void scmdatabase_unlock(struct scmdatabase *db)
564 LeaveCriticalSection(&db->cs);
567 void service_lock_shared(struct service_entry *service)
569 EnterCriticalSection(&service->db->cs);
572 void service_lock_exclusive(struct service_entry *service)
574 EnterCriticalSection(&service->db->cs);
577 void service_unlock(struct service_entry *service)
579 LeaveCriticalSection(&service->db->cs);
582 /* only one service started at a time, so there is no race on the registry
583 * value here */
584 static LPWSTR service_get_pipe_name(void)
586 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
587 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
588 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
589 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
590 'C','o','n','t','r','o','l','\\',
591 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
592 LPWSTR name;
593 DWORD len;
594 HKEY service_current_key;
595 DWORD service_current = -1;
596 LONG ret;
597 DWORD type;
599 ret = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
600 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
601 &service_current_key, NULL);
602 if (ret != ERROR_SUCCESS)
603 return NULL;
604 len = sizeof(service_current);
605 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
606 (BYTE *)&service_current, &len);
607 if ((ret == ERROR_SUCCESS && type == REG_DWORD) || ret == ERROR_FILE_NOT_FOUND)
609 service_current++;
610 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
611 (BYTE *)&service_current, sizeof(service_current));
613 RegCloseKey(service_current_key);
614 if ((ret != ERROR_SUCCESS || type != REG_DWORD) && (ret != ERROR_FILE_NOT_FOUND))
615 return NULL;
616 len = sizeof(format)/sizeof(WCHAR) + 10 /* strlenW("4294967295") */;
617 name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
618 if (!name)
619 return NULL;
620 snprintfW(name, len, format, service_current);
621 return name;
624 static DWORD get_service_binary_path(const struct service_entry *service_entry, WCHAR **path)
626 DWORD size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, NULL, 0);
628 *path = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
629 if (!*path)
630 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
632 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, *path, size);
634 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER)
636 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
637 WCHAR system_dir[MAX_PATH];
638 DWORD type, len;
640 GetSystemDirectoryW( system_dir, MAX_PATH );
641 if (is_win64)
643 if (!GetBinaryTypeW( *path, &type ))
645 HeapFree( GetProcessHeap(), 0, *path );
646 return GetLastError();
648 if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
651 len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
652 HeapFree( GetProcessHeap(), 0, *path );
653 if (!(*path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
654 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
656 lstrcpyW( *path, system_dir );
657 lstrcatW( *path, winedeviceW );
658 lstrcatW( *path, service_entry->name );
659 return ERROR_SUCCESS;
662 /* if service image is configured to systemdir, redirect it to wow64 systemdir */
663 if (service_entry->is_wow64)
665 WCHAR system_dir[MAX_PATH], *redirected;
666 DWORD len;
668 GetSystemDirectoryW( system_dir, MAX_PATH );
669 len = strlenW( system_dir );
671 if (strncmpiW( system_dir, *path, len ))
672 return ERROR_SUCCESS;
674 GetSystemWow64DirectoryW( system_dir, MAX_PATH );
676 redirected = HeapAlloc( GetProcessHeap(), 0, (strlenW( *path ) + strlenW( system_dir ))*sizeof(WCHAR));
677 if (!redirected)
679 HeapFree( GetProcessHeap(), 0, *path );
680 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
683 strcpyW( redirected, system_dir );
684 strcatW( redirected, &(*path)[len] );
685 HeapFree( GetProcessHeap(), 0, *path );
686 *path = redirected;
687 TRACE("redirected to %s\n", debugstr_w(redirected));
690 return ERROR_SUCCESS;
693 static DWORD service_start_process(struct service_entry *service_entry, HANDLE *process)
695 PROCESS_INFORMATION pi;
696 STARTUPINFOW si;
697 LPWSTR path = NULL;
698 DWORD err;
699 BOOL r;
701 service_lock_exclusive(service_entry);
703 if (!env)
705 HANDLE htok;
707 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
708 CreateEnvironmentBlock(&env, htok, FALSE);
710 if (!env)
711 WINE_ERR("failed to create services environment\n");
714 if ((err = get_service_binary_path(service_entry, &path)))
716 service_unlock(service_entry);
717 return err;
720 ZeroMemory(&si, sizeof(STARTUPINFOW));
721 si.cb = sizeof(STARTUPINFOW);
722 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
724 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};
725 si.lpDesktop = desktopW;
728 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
730 service_unlock(service_entry);
732 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
733 HeapFree(GetProcessHeap(),0,path);
734 if (!r)
736 service_lock_exclusive(service_entry);
737 service_entry->status.dwCurrentState = SERVICE_STOPPED;
738 service_unlock(service_entry);
739 return GetLastError();
742 service_entry->status.dwProcessId = pi.dwProcessId;
743 service_entry->process = pi.hProcess;
744 *process = pi.hProcess;
745 CloseHandle( pi.hThread );
747 return ERROR_SUCCESS;
750 static DWORD service_wait_for_startup(struct service_entry *service_entry, HANDLE process_handle)
752 HANDLE handles[2] = { service_entry->status_changed_event, process_handle };
753 DWORD state, ret;
755 WINE_TRACE("%p\n", service_entry);
757 ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
758 if (ret != WAIT_OBJECT_0)
759 return ERROR_SERVICE_REQUEST_TIMEOUT;
760 service_lock_shared(service_entry);
761 state = service_entry->status.dwCurrentState;
762 service_unlock(service_entry);
763 if (state == SERVICE_START_PENDING)
765 WINE_TRACE("Service state changed to SERVICE_START_PENDING\n");
766 return ERROR_SUCCESS;
768 else if (state == SERVICE_RUNNING)
770 WINE_TRACE("Service started successfully\n");
771 return ERROR_SUCCESS;
774 return ERROR_SERVICE_REQUEST_TIMEOUT;
777 /******************************************************************************
778 * service_send_start_message
780 static BOOL service_send_start_message(struct service_entry *service, HANDLE process_handle,
781 LPCWSTR *argv, DWORD argc)
783 OVERLAPPED overlapped;
784 DWORD i, len, result;
785 service_start_info *ssi;
786 LPWSTR p;
787 BOOL r;
789 WINE_TRACE("%s %p %d\n", wine_dbgstr_w(service->name), argv, argc);
791 overlapped.hEvent = service->overlapped_event;
792 if (!ConnectNamedPipe(service->control_pipe, &overlapped))
794 if (GetLastError() == ERROR_IO_PENDING)
796 HANDLE handles[2];
797 handles[0] = service->overlapped_event;
798 handles[1] = process_handle;
799 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
800 CancelIo( service->control_pipe );
801 if (!HasOverlappedIoCompleted( &overlapped ))
803 WINE_ERR( "service %s failed to start\n", wine_dbgstr_w( service->name ));
804 return FALSE;
807 else if (GetLastError() != ERROR_PIPE_CONNECTED)
809 WINE_ERR("pipe connect failed\n");
810 return FALSE;
814 /* calculate how much space do we need to send the startup info */
815 len = strlenW(service->name) + 1;
816 for (i=0; i<argc; i++)
817 len += strlenW(argv[i])+1;
818 len++;
820 ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
821 ssi->cmd = WINESERV_STARTINFO;
822 ssi->control = 0;
823 ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
824 ssi->name_size = strlenW(service->name) + 1;
825 strcpyW( ssi->data, service->name );
827 /* copy service args into a single buffer*/
828 p = &ssi->data[ssi->name_size];
829 for (i=0; i<argc; i++)
831 strcpyW(p, argv[i]);
832 p += strlenW(p) + 1;
834 *p=0;
836 r = service_send_command( service, service->control_pipe, ssi, ssi->total_size, &result );
837 if (r && result)
839 SetLastError(result);
840 r = FALSE;
843 HeapFree(GetProcessHeap(),0,ssi);
845 return r;
848 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
850 DWORD err;
851 LPWSTR name;
852 HANDLE process_handle = NULL;
854 err = scmdatabase_lock_startup(service->db);
855 if (err != ERROR_SUCCESS)
856 return err;
858 if (WaitForSingleObject(service->process, 0) == WAIT_TIMEOUT)
860 scmdatabase_unlock_startup(service->db);
861 return ERROR_SERVICE_ALREADY_RUNNING;
864 CloseHandle(service->control_pipe);
865 service->control_mutex = CreateMutexW(NULL, TRUE, NULL);
867 if (!service->status_changed_event)
868 service->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
869 if (!service->overlapped_event)
870 service->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
872 name = service_get_pipe_name();
873 service->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
874 PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
875 HeapFree(GetProcessHeap(), 0, name);
876 if (service->control_pipe==INVALID_HANDLE_VALUE)
878 WINE_ERR("failed to create pipe for %s, error = %d\n",
879 wine_dbgstr_w(service->name), GetLastError());
880 err = GetLastError();
882 else
884 err = service_start_process(service, &process_handle);
885 if (err == ERROR_SUCCESS)
887 if (!service_send_start_message(service, process_handle, service_argv, service_argc))
888 err = ERROR_SERVICE_REQUEST_TIMEOUT;
891 if (err == ERROR_SUCCESS)
892 err = service_wait_for_startup(service, process_handle);
895 if (err == ERROR_SUCCESS)
896 ReleaseMutex(service->control_mutex);
897 else
898 service_terminate(service);
899 scmdatabase_unlock_startup(service->db);
901 WINE_TRACE("returning %d\n", err);
903 return err;
906 void service_terminate(struct service_entry *service)
908 service_lock_exclusive(service);
909 TerminateProcess(service->process, 0);
910 CloseHandle(service->process);
911 service->process = NULL;
912 CloseHandle(service->status_changed_event);
913 service->status_changed_event = NULL;
914 CloseHandle(service->control_mutex);
915 service->control_mutex = NULL;
916 CloseHandle(service->control_pipe);
917 service->control_pipe = INVALID_HANDLE_VALUE;
919 service->status.dwProcessId = 0;
920 service->status.dwCurrentState = SERVICE_STOPPED;
921 service_unlock(service);
924 static void load_registry_parameters(void)
926 static const WCHAR controlW[] =
927 { 'S','y','s','t','e','m','\\',
928 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
929 'C','o','n','t','r','o','l',0 };
930 static const WCHAR pipetimeoutW[] =
931 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
932 static const WCHAR killtimeoutW[] =
933 {'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};
934 HKEY key;
935 WCHAR buffer[64];
936 DWORD type, count, val;
938 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
940 count = sizeof(buffer);
941 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
942 type == REG_SZ && (val = atoiW( buffer )))
943 service_pipe_timeout = val;
945 count = sizeof(buffer);
946 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
947 type == REG_SZ && (val = atoiW( buffer )))
948 service_kill_timeout = val;
950 RegCloseKey( key );
953 int main(int argc, char *argv[])
955 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
956 DWORD err;
958 g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
959 load_registry_parameters();
960 err = scmdatabase_create(&active_database);
961 if (err != ERROR_SUCCESS)
962 return err;
963 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
964 return err;
965 if ((err = RPC_Init()) == ERROR_SUCCESS)
967 scmdatabase_autostart_services(active_database);
968 events_loop();
969 scmdatabase_wait_terminate(active_database);
971 scmdatabase_destroy(active_database);
972 if (env)
973 DestroyEnvironmentBlock(env);
975 WINE_TRACE("services.exe exited with code %d\n", err);
976 return err;