services: Change scmdatabase_remove_service to a void function.
[wine.git] / programs / services / services.c
blobab8081286d12023f76457ff62ba2bb9c7f515470
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(struct process_entry **entry)
74 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
75 if (!*entry)
76 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
77 (*entry)->ref_count = 1;
78 (*entry)->control_pipe = INVALID_HANDLE_VALUE;
79 /* all other fields are zero */
80 return ERROR_SUCCESS;
83 static void free_process_entry(struct process_entry *entry)
85 CloseHandle(entry->process);
86 CloseHandle(entry->control_mutex);
87 CloseHandle(entry->control_pipe);
88 CloseHandle(entry->overlapped_event);
89 CloseHandle(entry->status_changed_event);
90 HeapFree(GetProcessHeap(), 0, entry);
93 DWORD service_create(LPCWSTR name, struct service_entry **entry)
95 DWORD err;
97 *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
98 if (!*entry)
99 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
100 (*entry)->name = strdupW(name);
101 if (!(*entry)->name)
103 HeapFree(GetProcessHeap(), 0, *entry);
104 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
106 if ((err = process_create(&(*entry)->process)) != ERROR_SUCCESS)
108 HeapFree(GetProcessHeap(), 0, (*entry)->name);
109 HeapFree(GetProcessHeap(), 0, *entry);
110 return err;
112 (*entry)->ref_count = 1;
113 (*entry)->status.dwCurrentState = SERVICE_STOPPED;
114 (*entry)->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
115 (*entry)->preshutdown_timeout = default_preshutdown_timeout;
116 /* all other fields are zero */
117 return ERROR_SUCCESS;
120 void free_service_entry(struct service_entry *entry)
122 HeapFree(GetProcessHeap(), 0, entry->name);
123 HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
124 HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
125 HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
126 HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
127 HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
128 HeapFree(GetProcessHeap(), 0, entry->description);
129 HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
130 HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
131 release_process(entry->process);
132 HeapFree(GetProcessHeap(), 0, entry);
135 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
137 DWORD err, value = 0;
138 WCHAR *wptr;
140 if ((err = load_reg_string(hKey, SZ_IMAGE_PATH, TRUE, &entry->config.lpBinaryPathName)) != 0)
141 return err;
142 if ((err = load_reg_string(hKey, SZ_GROUP, 0, &entry->config.lpLoadOrderGroup)) != 0)
143 return err;
144 if ((err = load_reg_string(hKey, SZ_OBJECT_NAME, TRUE, &entry->config.lpServiceStartName)) != 0)
145 return err;
146 if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0, &entry->config.lpDisplayName)) != 0)
147 return err;
148 if ((err = load_reg_string(hKey, SZ_DESCRIPTION, 0, &entry->description)) != 0)
149 return err;
150 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
151 return err;
152 if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
153 return err;
155 if ((err = load_reg_dword(hKey, SZ_TYPE, &entry->config.dwServiceType)) != 0)
156 return err;
157 if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
158 return err;
159 if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
160 return err;
161 if ((err = load_reg_dword(hKey, SZ_TAG, &entry->config.dwTagId)) != 0)
162 return err;
163 if ((err = load_reg_dword(hKey, SZ_PRESHUTDOWN, &entry->preshutdown_timeout)) != 0)
164 return err;
166 if (load_reg_dword(hKey, SZ_WOW64, &value) == 0 && value == 1)
167 entry->is_wow64 = TRUE;
169 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
170 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
171 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
172 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
173 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
174 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
175 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
176 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
177 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
178 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
180 return ERROR_SUCCESS;
183 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
185 if (!string)
187 DWORD err;
188 err = RegDeleteValueW(hKey, value_name);
189 if (err != ERROR_FILE_NOT_FOUND)
190 return err;
192 return ERROR_SUCCESS;
195 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
198 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
200 const WCHAR *ptr;
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 ptr = string;
213 while (*ptr) ptr += strlenW(ptr) + 1;
214 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
217 DWORD save_service_config(struct service_entry *entry)
219 DWORD err;
220 HKEY hKey = NULL;
222 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
223 if (err != ERROR_SUCCESS)
224 goto cleanup;
226 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
227 goto cleanup;
228 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
229 goto cleanup;
230 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
231 goto cleanup;
232 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
233 goto cleanup;
234 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
235 goto cleanup;
236 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
237 goto cleanup;
238 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
239 goto cleanup;
240 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
241 goto cleanup;
242 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
243 goto cleanup;
244 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
245 goto cleanup;
246 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
247 goto cleanup;
248 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
249 goto cleanup;
250 if (entry->is_wow64)
252 const DWORD is_wow64 = 1;
253 if ((err = RegSetValueExW(hKey, SZ_WOW64, 0, REG_DWORD, (LPBYTE)&is_wow64, sizeof(DWORD))) != 0)
254 goto cleanup;
257 if (entry->config.dwTagId)
258 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
259 else
260 err = RegDeleteValueW(hKey, SZ_TAG);
262 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
263 goto cleanup;
265 err = ERROR_SUCCESS;
266 cleanup:
267 RegCloseKey(hKey);
268 return err;
271 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
273 int err;
274 service->db = db;
275 if ((err = save_service_config(service)) != ERROR_SUCCESS)
277 WINE_ERR("Couldn't store service configuration: error %u\n", err);
278 return ERROR_GEN_FAILURE;
281 list_add_tail(&db->services, &service->entry);
282 return ERROR_SUCCESS;
285 static void scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
287 RegDeleteTreeW(db->root_key, service->name);
288 list_remove(&service->entry);
289 service->entry.next = service->entry.prev = NULL;
292 static void scmdatabase_autostart_services(struct scmdatabase *db)
294 struct service_entry **services_list;
295 unsigned int i = 0;
296 unsigned int size = 32;
297 struct service_entry *service;
299 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
300 if (!services_list)
301 return;
303 scmdatabase_lock(db);
305 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
307 if (service->config.dwStartType == SERVICE_BOOT_START ||
308 service->config.dwStartType == SERVICE_SYSTEM_START ||
309 service->config.dwStartType == SERVICE_AUTO_START)
311 if (i+1 >= size)
313 struct service_entry **slist_new;
314 size *= 2;
315 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
316 if (!slist_new)
317 break;
318 services_list = slist_new;
320 services_list[i] = service;
321 InterlockedIncrement(&service->ref_count);
322 i++;
326 scmdatabase_unlock(db);
328 size = i;
329 for (i = 0; i < size; i++)
331 DWORD err;
332 service = services_list[i];
333 err = service_start(service, 0, NULL);
334 if (err != ERROR_SUCCESS)
335 WINE_FIXME("Auto-start service %s failed to start: %d\n",
336 wine_dbgstr_w(service->name), err);
337 release_service(service);
340 HeapFree(GetProcessHeap(), 0, services_list);
343 static void scmdatabase_wait_terminate(struct scmdatabase *db)
345 struct service_entry *service;
346 BOOL run = TRUE;
348 scmdatabase_lock(db);
349 while(run)
351 run = FALSE;
352 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
354 struct process_entry *process = service->process;
355 if (process->process)
357 scmdatabase_unlock(db);
358 WaitForSingleObject(process->process, INFINITE);
359 scmdatabase_lock(db);
360 CloseHandle(process->process);
361 process->process = NULL;
362 run = TRUE;
363 break;
367 scmdatabase_unlock(db);
370 BOOL validate_service_name(LPCWSTR name)
372 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
375 BOOL validate_service_config(struct service_entry *entry)
377 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
379 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
380 return FALSE;
383 switch (entry->config.dwServiceType)
385 case SERVICE_KERNEL_DRIVER:
386 case SERVICE_FILE_SYSTEM_DRIVER:
387 case SERVICE_WIN32_OWN_PROCESS:
388 case SERVICE_WIN32_SHARE_PROCESS:
389 /* No problem */
390 break;
391 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
392 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
393 /* These can be only run as LocalSystem */
394 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
396 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
397 return FALSE;
399 break;
400 default:
401 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
402 return FALSE;
405 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
406 if (entry->config.dwStartType > SERVICE_DISABLED)
408 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
409 return FALSE;
412 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
413 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
414 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
416 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
417 return FALSE;
420 if (entry->config.lpServiceStartName == NULL)
421 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
423 return TRUE;
427 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
429 struct service_entry *service;
431 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
433 if (strcmpiW(name, service->name) == 0)
434 return service;
437 return NULL;
440 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
442 struct service_entry *service;
444 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
446 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
447 return service;
450 return NULL;
453 struct process_entry *grab_process(struct process_entry *process)
455 if (process)
456 InterlockedIncrement(&process->ref_count);
457 return process;
460 void release_process(struct process_entry *process)
462 if (InterlockedDecrement(&process->ref_count) == 0)
463 free_process_entry(process);
466 void release_service(struct service_entry *service)
468 struct scmdatabase *db = service->db;
470 scmdatabase_lock(db);
471 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
473 scmdatabase_remove_service(db, service);
474 free_service_entry(service);
476 scmdatabase_unlock(db);
479 static DWORD scmdatabase_create(struct scmdatabase **db)
481 DWORD err;
483 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
484 if (!*db)
485 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
487 (*db)->service_start_lock = FALSE;
488 list_init(&(*db)->services);
490 InitializeCriticalSection(&(*db)->cs);
491 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
493 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
494 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
495 &(*db)->root_key, NULL);
496 if (err != ERROR_SUCCESS)
497 HeapFree(GetProcessHeap(), 0, *db);
499 return err;
502 static void scmdatabase_destroy(struct scmdatabase *db)
504 RegCloseKey(db->root_key);
505 db->cs.DebugInfo->Spare[0] = 0;
506 DeleteCriticalSection(&db->cs);
507 HeapFree(GetProcessHeap(), 0, db);
510 static DWORD scmdatabase_load_services(struct scmdatabase *db)
512 DWORD err;
513 int i;
515 for (i = 0; TRUE; i++)
517 WCHAR szName[MAX_SERVICE_NAME];
518 struct service_entry *entry;
519 HKEY hServiceKey;
521 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
522 if (err == ERROR_NO_MORE_ITEMS)
523 break;
525 if (err != 0)
527 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
528 continue;
531 err = service_create(szName, &entry);
532 if (err != ERROR_SUCCESS)
533 break;
535 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
536 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
537 if (err == ERROR_SUCCESS)
539 err = load_service_config(hServiceKey, entry);
540 RegCloseKey(hServiceKey);
543 if (err != ERROR_SUCCESS)
545 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
546 free_service_entry(entry);
547 continue;
550 if (entry->config.dwServiceType == 0)
552 /* Maybe an application only wrote some configuration in the service key. Continue silently */
553 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
554 free_service_entry(entry);
555 continue;
558 if (!validate_service_config(entry))
560 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
561 free_service_entry(entry);
562 continue;
565 entry->status.dwServiceType = entry->config.dwServiceType;
566 entry->db = db;
568 list_add_tail(&db->services, &entry->entry);
569 release_service(entry);
571 return ERROR_SUCCESS;
574 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
576 if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
577 return ERROR_SERVICE_DATABASE_LOCKED;
578 return ERROR_SUCCESS;
581 void scmdatabase_unlock_startup(struct scmdatabase *db)
583 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
586 void scmdatabase_lock(struct scmdatabase *db)
588 EnterCriticalSection(&db->cs);
591 void scmdatabase_unlock(struct scmdatabase *db)
593 LeaveCriticalSection(&db->cs);
596 void service_lock(struct service_entry *service)
598 EnterCriticalSection(&service->db->cs);
601 void service_unlock(struct service_entry *service)
603 LeaveCriticalSection(&service->db->cs);
606 /* only one service started at a time, so there is no race on the registry
607 * value here */
608 static LPWSTR service_get_pipe_name(void)
610 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
611 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
612 static WCHAR name[sizeof(format)/sizeof(WCHAR) + 10]; /* strlenW("4294967295") */
613 static DWORD service_current = 0;
614 DWORD len, value = -1;
615 LONG ret;
616 DWORD type;
618 len = sizeof(value);
619 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
620 (BYTE *)&value, &len);
621 if (ret == ERROR_SUCCESS && type == REG_DWORD)
622 service_current = max(service_current, value + 1);
623 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
624 (BYTE *)&service_current, sizeof(service_current));
625 sprintfW(name, format, service_current);
626 service_current++;
627 return name;
630 static DWORD get_service_binary_path(const struct service_entry *service_entry, WCHAR **path)
632 DWORD size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, NULL, 0);
634 *path = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
635 if (!*path)
636 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
638 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName, *path, size);
640 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER ||
641 service_entry->config.dwServiceType == SERVICE_FILE_SYSTEM_DRIVER)
643 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
644 WCHAR system_dir[MAX_PATH];
645 DWORD type, len;
647 GetSystemDirectoryW( system_dir, MAX_PATH );
648 if (is_win64)
650 if (!GetBinaryTypeW( *path, &type ))
652 HeapFree( GetProcessHeap(), 0, *path );
653 return GetLastError();
655 if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
658 len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
659 HeapFree( GetProcessHeap(), 0, *path );
660 if (!(*path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
661 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
663 lstrcpyW( *path, system_dir );
664 lstrcatW( *path, winedeviceW );
665 lstrcatW( *path, service_entry->name );
666 return ERROR_SUCCESS;
669 /* if service image is configured to systemdir, redirect it to wow64 systemdir */
670 if (service_entry->is_wow64)
672 WCHAR system_dir[MAX_PATH], *redirected;
673 DWORD len;
675 GetSystemDirectoryW( system_dir, MAX_PATH );
676 len = strlenW( system_dir );
678 if (strncmpiW( system_dir, *path, len ))
679 return ERROR_SUCCESS;
681 GetSystemWow64DirectoryW( system_dir, MAX_PATH );
683 redirected = HeapAlloc( GetProcessHeap(), 0, (strlenW( *path ) + strlenW( system_dir ))*sizeof(WCHAR));
684 if (!redirected)
686 HeapFree( GetProcessHeap(), 0, *path );
687 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
690 strcpyW( redirected, system_dir );
691 strcatW( redirected, &(*path)[len] );
692 HeapFree( GetProcessHeap(), 0, *path );
693 *path = redirected;
694 TRACE("redirected to %s\n", debugstr_w(redirected));
697 return ERROR_SUCCESS;
700 static DWORD service_start_process(struct service_entry *service_entry)
702 PROCESS_INFORMATION pi;
703 STARTUPINFOW si;
704 LPWSTR path = NULL;
705 DWORD err;
706 BOOL r;
708 service_lock(service_entry);
710 if ((err = get_service_binary_path(service_entry, &path)))
712 service_unlock(service_entry);
713 return err;
716 ZeroMemory(&si, sizeof(STARTUPINFOW));
717 si.cb = sizeof(STARTUPINFOW);
718 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
720 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};
721 si.lpDesktop = desktopW;
724 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
726 service_unlock(service_entry);
728 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
729 HeapFree(GetProcessHeap(),0,path);
730 if (!r)
732 service_lock(service_entry);
733 service_entry->status.dwCurrentState = SERVICE_STOPPED;
734 service_unlock(service_entry);
735 return GetLastError();
738 service_entry->status.dwProcessId = pi.dwProcessId;
739 service_entry->process->process = pi.hProcess;
740 CloseHandle( pi.hThread );
742 return ERROR_SUCCESS;
745 static DWORD process_wait_for_startup(struct process_entry *process)
747 HANDLE handles[2] = { process->status_changed_event, process->process };
748 DWORD ret;
750 ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
751 return (ret == WAIT_OBJECT_0) ? ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
754 static DWORD service_is_running(struct service_entry *service)
756 DWORD state;
758 service_lock(service);
759 state = service->status.dwCurrentState;
760 service_unlock(service);
762 return (state == SERVICE_START_PENDING || state == SERVICE_RUNNING) ?
763 ERROR_SUCCESS : ERROR_SERVICE_REQUEST_TIMEOUT;
766 /******************************************************************************
767 * process_send_start_message
769 static BOOL process_send_start_message(struct process_entry *process, const WCHAR *name,
770 LPCWSTR *argv, DWORD argc)
772 OVERLAPPED overlapped;
773 DWORD i, len, result;
774 service_start_info *ssi;
775 LPWSTR p;
776 BOOL r;
778 WINE_TRACE("%p %s %p %d\n", process, wine_dbgstr_w(name), argv, argc);
780 overlapped.hEvent = process->overlapped_event;
781 if (!ConnectNamedPipe(process->control_pipe, &overlapped))
783 if (GetLastError() == ERROR_IO_PENDING)
785 HANDLE handles[2];
786 handles[0] = process->overlapped_event;
787 handles[1] = process->process;
788 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
789 CancelIo(process->control_pipe);
790 if (!HasOverlappedIoCompleted( &overlapped ))
792 WINE_ERR("service %s failed to start\n", wine_dbgstr_w(name));
793 return FALSE;
796 else if (GetLastError() != ERROR_PIPE_CONNECTED)
798 WINE_ERR("pipe connect failed\n");
799 return FALSE;
803 /* calculate how much space do we need to send the startup info */
804 len = strlenW(name) + 1;
805 for (i=0; i<argc; i++)
806 len += strlenW(argv[i])+1;
807 len++;
809 ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
810 ssi->cmd = WINESERV_STARTINFO;
811 ssi->control = 0;
812 ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
813 ssi->name_size = strlenW(name) + 1;
814 strcpyW(ssi->data, name);
816 /* copy service args into a single buffer*/
817 p = &ssi->data[ssi->name_size];
818 for (i=0; i<argc; i++)
820 strcpyW(p, argv[i]);
821 p += strlenW(p) + 1;
823 *p=0;
825 r = process_send_command( process, ssi, ssi->total_size, &result );
826 if (r && result)
828 SetLastError(result);
829 r = FALSE;
832 HeapFree(GetProcessHeap(),0,ssi);
834 return r;
837 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
839 struct process_entry *process = service->process;
840 DWORD err;
842 err = scmdatabase_lock_startup(service->db);
843 if (err != ERROR_SUCCESS)
844 return err;
846 if (WaitForSingleObject(process->process, 0) == WAIT_TIMEOUT)
848 scmdatabase_unlock_startup(service->db);
849 return ERROR_SERVICE_ALREADY_RUNNING;
852 CloseHandle(process->control_pipe);
853 process->control_mutex = CreateMutexW(NULL, TRUE, NULL);
854 service->force_shutdown = FALSE;
856 if (!process->status_changed_event)
857 process->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
858 if (!process->overlapped_event)
859 process->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
861 process->control_pipe = CreateNamedPipeW(service_get_pipe_name(), PIPE_ACCESS_DUPLEX |
862 FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
863 if (process->control_pipe == INVALID_HANDLE_VALUE)
865 WINE_ERR("failed to create pipe for %s, error = %d\n",
866 wine_dbgstr_w(service->name), GetLastError());
867 err = GetLastError();
869 else
871 err = service_start_process(service);
872 if (err == ERROR_SUCCESS)
874 if (!process_send_start_message(process, service->name, service_argv, service_argc))
875 err = ERROR_SERVICE_REQUEST_TIMEOUT;
878 if (err == ERROR_SUCCESS)
879 err = process_wait_for_startup(process);
881 if (err == ERROR_SUCCESS)
882 err = service_is_running(service);
885 if (err == ERROR_SUCCESS)
886 ReleaseMutex(process->control_mutex);
887 else
888 service_terminate(service);
889 scmdatabase_unlock_startup(service->db);
891 WINE_TRACE("returning %d\n", err);
893 return err;
896 void service_terminate(struct service_entry *service)
898 struct process_entry *process = service->process;
900 service_lock(service);
901 TerminateProcess(process->process, 0);
902 CloseHandle(process->process);
903 process->process = NULL;
904 CloseHandle(process->status_changed_event);
905 process->status_changed_event = NULL;
906 CloseHandle(process->control_mutex);
907 process->control_mutex = NULL;
908 CloseHandle(process->control_pipe);
909 process->control_pipe = INVALID_HANDLE_VALUE;
911 service->status.dwProcessId = 0;
912 service->status.dwCurrentState = SERVICE_STOPPED;
913 service_unlock(service);
916 static void load_registry_parameters(void)
918 static const WCHAR controlW[] =
919 { 'S','y','s','t','e','m','\\',
920 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
921 'C','o','n','t','r','o','l',0 };
922 static const WCHAR pipetimeoutW[] =
923 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
924 static const WCHAR killtimeoutW[] =
925 {'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};
926 HKEY key;
927 WCHAR buffer[64];
928 DWORD type, count, val;
930 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
932 count = sizeof(buffer);
933 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
934 type == REG_SZ && (val = atoiW( buffer )))
935 service_pipe_timeout = val;
937 count = sizeof(buffer);
938 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
939 type == REG_SZ && (val = atoiW( buffer )))
940 service_kill_timeout = val;
942 RegCloseKey( key );
945 int main(int argc, char *argv[])
947 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
948 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
949 'C','o','n','t','r','o','l','\\',
950 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
951 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
952 HANDLE htok;
953 DWORD err;
955 g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
957 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
959 CreateEnvironmentBlock(&env, htok, FALSE);
960 CloseHandle(htok);
963 if (!env)
964 WINE_ERR("failed to create services environment\n");
966 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
967 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
968 &service_current_key, NULL);
969 if (err != ERROR_SUCCESS)
970 return err;
972 load_registry_parameters();
973 err = scmdatabase_create(&active_database);
974 if (err != ERROR_SUCCESS)
975 return err;
976 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
977 return err;
978 if ((err = RPC_Init()) == ERROR_SUCCESS)
980 scmdatabase_autostart_services(active_database);
981 events_loop();
982 scmdatabase_wait_terminate(active_database);
984 scmdatabase_destroy(active_database);
985 if (env)
986 DestroyEnvironmentBlock(env);
988 WINE_TRACE("services.exe exited with code %d\n", err);
989 return err;