configure: Add a check for sys/ucontext.h and include it where appropriate.
[wine.git] / programs / services / services.c
blob632d92a40af9cda5eae8b2438782716bc2a0cc78
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};
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;
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 WINE_TRACE("Image path = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
141 WINE_TRACE("Group = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
142 WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
143 WINE_TRACE("Display name = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
144 WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
145 for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
146 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
147 WINE_TRACE("Group dependencies : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
148 for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
149 WINE_TRACE(" * %s\n", wine_dbgstr_w(wptr));
151 return ERROR_SUCCESS;
154 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
156 if (!string)
158 DWORD err;
159 err = RegDeleteValueW(hKey, value_name);
160 if (err != ERROR_FILE_NOT_FOUND)
161 return err;
163 return ERROR_SUCCESS;
166 return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
169 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
171 const WCHAR *ptr;
173 if (!string)
175 DWORD err;
176 err = RegDeleteValueW(hKey, value_name);
177 if (err != ERROR_FILE_NOT_FOUND)
178 return err;
180 return ERROR_SUCCESS;
183 ptr = string;
184 while (*ptr) ptr += strlenW(ptr) + 1;
185 return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
188 DWORD save_service_config(struct service_entry *entry)
190 DWORD err;
191 HKEY hKey = NULL;
193 err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
194 if (err != ERROR_SUCCESS)
195 goto cleanup;
197 if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
198 goto cleanup;
199 if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
200 goto cleanup;
201 if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
202 goto cleanup;
203 if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
204 goto cleanup;
205 if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
206 goto cleanup;
207 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
208 goto cleanup;
209 if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
210 goto cleanup;
211 if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
212 goto cleanup;
213 if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
214 goto cleanup;
215 if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
216 goto cleanup;
217 if ((err = RegSetValueExW(hKey, SZ_PRESHUTDOWN, 0, REG_DWORD, (LPBYTE)&entry->preshutdown_timeout, sizeof(DWORD))) != 0)
218 goto cleanup;
220 if (entry->config.dwTagId)
221 err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
222 else
223 err = RegDeleteValueW(hKey, SZ_TAG);
225 if (err != 0 && err != ERROR_FILE_NOT_FOUND)
226 goto cleanup;
228 err = ERROR_SUCCESS;
229 cleanup:
230 RegCloseKey(hKey);
231 return err;
234 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
236 int err;
237 service->db = db;
238 if ((err = save_service_config(service)) != ERROR_SUCCESS)
240 WINE_ERR("Couldn't store service configuration: error %u\n", err);
241 return ERROR_GEN_FAILURE;
244 list_add_tail(&db->services, &service->entry);
245 return ERROR_SUCCESS;
248 static DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
250 int err;
252 err = RegDeleteTreeW(db->root_key, service->name);
254 if (err != 0)
255 return err;
257 list_remove(&service->entry);
258 service->entry.next = service->entry.prev = NULL;
259 return ERROR_SUCCESS;
262 static void scmdatabase_autostart_services(struct scmdatabase *db)
264 struct service_entry **services_list;
265 unsigned int i = 0;
266 unsigned int size = 32;
267 struct service_entry *service;
269 services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
270 if (!services_list)
271 return;
273 scmdatabase_lock_shared(db);
275 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
277 if (service->config.dwStartType == SERVICE_BOOT_START ||
278 service->config.dwStartType == SERVICE_SYSTEM_START ||
279 service->config.dwStartType == SERVICE_AUTO_START)
281 if (i+1 >= size)
283 struct service_entry **slist_new;
284 size *= 2;
285 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
286 if (!slist_new)
287 break;
288 services_list = slist_new;
290 services_list[i] = service;
291 service->ref_count++;
292 i++;
296 scmdatabase_unlock(db);
298 size = i;
299 for (i = 0; i < size; i++)
301 DWORD err;
302 service = services_list[i];
303 err = service_start(service, 0, NULL);
304 if (err != ERROR_SUCCESS)
305 WINE_FIXME("Auto-start service %s failed to start: %d\n",
306 wine_dbgstr_w(service->name), err);
307 release_service(service);
310 HeapFree(GetProcessHeap(), 0, services_list);
313 static void scmdatabase_wait_terminate(struct scmdatabase *db)
315 struct service_entry *service;
316 BOOL run = TRUE;
318 scmdatabase_lock_shared(db);
319 while(run)
321 run = FALSE;
322 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
324 if(service->process)
326 scmdatabase_unlock(db);
327 WaitForSingleObject(service->process, INFINITE);
328 scmdatabase_lock_shared(db);
329 CloseHandle(service->process);
330 service->process = NULL;
331 run = TRUE;
332 break;
336 scmdatabase_unlock(db);
339 BOOL validate_service_name(LPCWSTR name)
341 return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
344 BOOL validate_service_config(struct service_entry *entry)
346 if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
348 WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
349 return FALSE;
352 switch (entry->config.dwServiceType)
354 case SERVICE_KERNEL_DRIVER:
355 case SERVICE_FILE_SYSTEM_DRIVER:
356 case SERVICE_WIN32_OWN_PROCESS:
357 case SERVICE_WIN32_SHARE_PROCESS:
358 /* No problem */
359 break;
360 case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
361 case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
362 /* These can be only run as LocalSystem */
363 if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
365 WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
366 return FALSE;
368 break;
369 default:
370 WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
371 return FALSE;
374 /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
375 if (entry->config.dwStartType > SERVICE_DISABLED)
377 WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
378 return FALSE;
381 /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
382 if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
383 ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
385 WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
386 return FALSE;
389 if (entry->config.lpServiceStartName == NULL)
390 entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
392 return TRUE;
396 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
398 struct service_entry *service;
400 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
402 if (strcmpiW(name, service->name) == 0)
403 return service;
406 return NULL;
409 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
411 struct service_entry *service;
413 LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
415 if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
416 return service;
419 return NULL;
422 void release_service(struct service_entry *service)
424 if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
426 scmdatabase_lock_exclusive(service->db);
427 service_lock_exclusive(service);
428 scmdatabase_remove_service(service->db, service);
429 service_unlock(service);
430 scmdatabase_unlock(service->db);
431 free_service_entry(service);
435 static DWORD scmdatabase_create(struct scmdatabase **db)
437 DWORD err;
439 *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
440 if (!*db)
441 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
443 (*db)->service_start_lock = FALSE;
444 list_init(&(*db)->services);
446 InitializeCriticalSection(&(*db)->cs);
447 (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
449 err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
450 REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
451 &(*db)->root_key, NULL);
452 if (err != ERROR_SUCCESS)
453 HeapFree(GetProcessHeap(), 0, *db);
455 return err;
458 static void scmdatabase_destroy(struct scmdatabase *db)
460 RegCloseKey(db->root_key);
461 db->cs.DebugInfo->Spare[0] = 0;
462 DeleteCriticalSection(&db->cs);
463 HeapFree(GetProcessHeap(), 0, db);
466 static DWORD scmdatabase_load_services(struct scmdatabase *db)
468 DWORD err;
469 int i;
471 for (i = 0; TRUE; i++)
473 WCHAR szName[MAX_SERVICE_NAME];
474 struct service_entry *entry;
475 HKEY hServiceKey;
477 err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
478 if (err == ERROR_NO_MORE_ITEMS)
479 break;
481 if (err != 0)
483 WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
484 continue;
487 err = service_create(szName, &entry);
488 if (err != ERROR_SUCCESS)
489 break;
491 WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
492 err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
493 if (err == ERROR_SUCCESS)
495 err = load_service_config(hServiceKey, entry);
496 RegCloseKey(hServiceKey);
499 if (err != ERROR_SUCCESS)
501 WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
502 free_service_entry(entry);
503 continue;
506 if (entry->config.dwServiceType == 0)
508 /* Maybe an application only wrote some configuration in the service key. Continue silently */
509 WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
510 free_service_entry(entry);
511 continue;
514 if (!validate_service_config(entry))
516 WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
517 free_service_entry(entry);
518 continue;
521 entry->status.dwServiceType = entry->config.dwServiceType;
522 entry->db = db;
524 list_add_tail(&db->services, &entry->entry);
526 return ERROR_SUCCESS;
529 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
531 if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
532 return ERROR_SERVICE_DATABASE_LOCKED;
533 return ERROR_SUCCESS;
536 void scmdatabase_unlock_startup(struct scmdatabase *db)
538 InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
541 void scmdatabase_lock_shared(struct scmdatabase *db)
543 EnterCriticalSection(&db->cs);
546 void scmdatabase_lock_exclusive(struct scmdatabase *db)
548 EnterCriticalSection(&db->cs);
551 void scmdatabase_unlock(struct scmdatabase *db)
553 LeaveCriticalSection(&db->cs);
556 void service_lock_shared(struct service_entry *service)
558 EnterCriticalSection(&service->db->cs);
561 void service_lock_exclusive(struct service_entry *service)
563 EnterCriticalSection(&service->db->cs);
566 void service_unlock(struct service_entry *service)
568 LeaveCriticalSection(&service->db->cs);
571 /* only one service started at a time, so there is no race on the registry
572 * value here */
573 static LPWSTR service_get_pipe_name(void)
575 static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
576 'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
577 static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
578 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
579 'C','o','n','t','r','o','l','\\',
580 'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
581 LPWSTR name;
582 DWORD len;
583 HKEY service_current_key;
584 DWORD service_current = -1;
585 LONG ret;
586 DWORD type;
588 ret = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
589 NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
590 &service_current_key, NULL);
591 if (ret != ERROR_SUCCESS)
592 return NULL;
593 len = sizeof(service_current);
594 ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
595 (BYTE *)&service_current, &len);
596 if ((ret == ERROR_SUCCESS && type == REG_DWORD) || ret == ERROR_FILE_NOT_FOUND)
598 service_current++;
599 RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
600 (BYTE *)&service_current, sizeof(service_current));
602 RegCloseKey(service_current_key);
603 if ((ret != ERROR_SUCCESS || type != REG_DWORD) && (ret != ERROR_FILE_NOT_FOUND))
604 return NULL;
605 len = sizeof(format)/sizeof(WCHAR) + 10 /* strlenW("4294967295") */;
606 name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
607 if (!name)
608 return NULL;
609 snprintfW(name, len, format, service_current);
610 return name;
613 static DWORD service_start_process(struct service_entry *service_entry, HANDLE *process)
615 PROCESS_INFORMATION pi;
616 STARTUPINFOW si;
617 LPWSTR path = NULL;
618 DWORD size;
619 BOOL r;
621 service_lock_exclusive(service_entry);
623 if (!env)
625 HANDLE htok;
627 if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
628 CreateEnvironmentBlock(&env, htok, FALSE);
630 if (!env)
631 WINE_ERR("failed to create services environment\n");
634 size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,NULL,0);
635 path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
636 if (!path)
638 service_unlock(service_entry);
639 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
641 ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,path,size);
643 if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER)
645 static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
646 WCHAR system_dir[MAX_PATH];
647 DWORD type, len;
649 GetSystemDirectoryW( system_dir, MAX_PATH );
650 if (is_win64)
652 if (!GetBinaryTypeW( path, &type ))
654 HeapFree( GetProcessHeap(), 0, path );
655 service_unlock(service_entry);
656 return GetLastError();
658 if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
661 len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
662 HeapFree( GetProcessHeap(), 0, path );
663 if (!(path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
665 service_unlock(service_entry);
666 return ERROR_NOT_ENOUGH_SERVER_MEMORY;
668 lstrcpyW( path, system_dir );
669 lstrcatW( path, winedeviceW );
670 lstrcatW( path, service_entry->name );
673 ZeroMemory(&si, sizeof(STARTUPINFOW));
674 si.cb = sizeof(STARTUPINFOW);
675 if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
677 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};
678 si.lpDesktop = desktopW;
681 service_entry->status.dwCurrentState = SERVICE_START_PENDING;
683 service_unlock(service_entry);
685 r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
686 HeapFree(GetProcessHeap(),0,path);
687 if (!r)
689 service_lock_exclusive(service_entry);
690 service_entry->status.dwCurrentState = SERVICE_STOPPED;
691 service_unlock(service_entry);
692 return GetLastError();
695 service_entry->status.dwProcessId = pi.dwProcessId;
696 service_entry->process = pi.hProcess;
697 *process = pi.hProcess;
698 CloseHandle( pi.hThread );
700 return ERROR_SUCCESS;
703 static DWORD service_wait_for_startup(struct service_entry *service_entry, HANDLE process_handle)
705 HANDLE handles[2] = { service_entry->status_changed_event, process_handle };
706 DWORD state, ret;
708 WINE_TRACE("%p\n", service_entry);
710 ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
711 if (ret != WAIT_OBJECT_0)
712 return ERROR_SERVICE_REQUEST_TIMEOUT;
713 service_lock_shared(service_entry);
714 state = service_entry->status.dwCurrentState;
715 service_unlock(service_entry);
716 if (state == SERVICE_START_PENDING)
718 WINE_TRACE("Service state changed to SERVICE_START_PENDING\n");
719 return ERROR_SUCCESS;
721 else if (state == SERVICE_RUNNING)
723 WINE_TRACE("Service started successfully\n");
724 return ERROR_SUCCESS;
727 return ERROR_SERVICE_REQUEST_TIMEOUT;
730 /******************************************************************************
731 * service_send_start_message
733 static BOOL service_send_start_message(struct service_entry *service, HANDLE process_handle,
734 LPCWSTR *argv, DWORD argc)
736 OVERLAPPED overlapped;
737 DWORD i, len, result;
738 service_start_info *ssi;
739 LPWSTR p;
740 BOOL r;
742 WINE_TRACE("%s %p %d\n", wine_dbgstr_w(service->name), argv, argc);
744 overlapped.hEvent = service->overlapped_event;
745 if (!ConnectNamedPipe(service->control_pipe, &overlapped))
747 if (GetLastError() == ERROR_IO_PENDING)
749 HANDLE handles[2];
750 handles[0] = service->overlapped_event;
751 handles[1] = process_handle;
752 if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
753 CancelIo( service->control_pipe );
754 if (!HasOverlappedCompleted( &overlapped ))
756 WINE_ERR( "service %s failed to start\n", wine_dbgstr_w( service->name ));
757 return FALSE;
760 else if (GetLastError() != ERROR_PIPE_CONNECTED)
762 WINE_ERR("pipe connect failed\n");
763 return FALSE;
767 /* calculate how much space do we need to send the startup info */
768 len = strlenW(service->name) + 1;
769 for (i=0; i<argc; i++)
770 len += strlenW(argv[i])+1;
771 len++;
773 ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
774 ssi->cmd = WINESERV_STARTINFO;
775 ssi->control = 0;
776 ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
777 ssi->name_size = strlenW(service->name) + 1;
778 strcpyW( ssi->data, service->name );
780 /* copy service args into a single buffer*/
781 p = &ssi->data[ssi->name_size];
782 for (i=0; i<argc; i++)
784 strcpyW(p, argv[i]);
785 p += strlenW(p) + 1;
787 *p=0;
789 r = service_send_command( service, service->control_pipe, ssi, ssi->total_size, &result );
790 if (r && result)
792 SetLastError(result);
793 r = FALSE;
796 HeapFree(GetProcessHeap(),0,ssi);
798 return r;
801 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
803 DWORD err;
804 LPWSTR name;
805 HANDLE process_handle = NULL;
807 err = scmdatabase_lock_startup(service->db);
808 if (err != ERROR_SUCCESS)
809 return err;
811 if (WaitForSingleObject(service->process, 0) == WAIT_TIMEOUT)
813 scmdatabase_unlock_startup(service->db);
814 return ERROR_SERVICE_ALREADY_RUNNING;
817 CloseHandle(service->control_pipe);
818 service->control_mutex = CreateMutexW(NULL, TRUE, NULL);
820 if (!service->status_changed_event)
821 service->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
822 if (!service->overlapped_event)
823 service->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
825 name = service_get_pipe_name();
826 service->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
827 PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
828 HeapFree(GetProcessHeap(), 0, name);
829 if (service->control_pipe==INVALID_HANDLE_VALUE)
831 WINE_ERR("failed to create pipe for %s, error = %d\n",
832 wine_dbgstr_w(service->name), GetLastError());
833 err = GetLastError();
835 else
837 err = service_start_process(service, &process_handle);
838 if (err == ERROR_SUCCESS)
840 if (!service_send_start_message(service, process_handle, service_argv, service_argc))
841 err = ERROR_SERVICE_REQUEST_TIMEOUT;
844 if (err == ERROR_SUCCESS)
845 err = service_wait_for_startup(service, process_handle);
848 if (err == ERROR_SUCCESS)
849 ReleaseMutex(service->control_mutex);
850 else
851 service_terminate(service);
852 scmdatabase_unlock_startup(service->db);
854 WINE_TRACE("returning %d\n", err);
856 return err;
859 void service_terminate(struct service_entry *service)
861 service_lock_exclusive(service);
862 TerminateProcess(service->process, 0);
863 CloseHandle(service->process);
864 service->process = NULL;
865 CloseHandle(service->status_changed_event);
866 service->status_changed_event = NULL;
867 CloseHandle(service->control_mutex);
868 service->control_mutex = NULL;
869 CloseHandle(service->control_pipe);
870 service->control_pipe = INVALID_HANDLE_VALUE;
872 service->status.dwProcessId = 0;
873 service->status.dwCurrentState = SERVICE_STOPPED;
874 service_unlock(service);
877 static void load_registry_parameters(void)
879 static const WCHAR controlW[] =
880 { 'S','y','s','t','e','m','\\',
881 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
882 'C','o','n','t','r','o','l',0 };
883 static const WCHAR pipetimeoutW[] =
884 {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
885 static const WCHAR killtimeoutW[] =
886 {'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};
887 HKEY key;
888 WCHAR buffer[64];
889 DWORD type, count, val;
891 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
893 count = sizeof(buffer);
894 if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
895 type == REG_SZ && (val = atoiW( buffer )))
896 service_pipe_timeout = val;
898 count = sizeof(buffer);
899 if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
900 type == REG_SZ && (val = atoiW( buffer )))
901 service_kill_timeout = val;
903 RegCloseKey( key );
906 int main(int argc, char *argv[])
908 static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
909 DWORD err;
911 g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
912 load_registry_parameters();
913 err = scmdatabase_create(&active_database);
914 if (err != ERROR_SUCCESS)
915 return err;
916 if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
917 return err;
918 if ((err = RPC_Init()) == ERROR_SUCCESS)
920 scmdatabase_autostart_services(active_database);
921 events_loop();
922 scmdatabase_wait_terminate(active_database);
924 scmdatabase_destroy(active_database);
925 if (env)
926 DestroyEnvironmentBlock(env);
928 WINE_TRACE("services.exe exited with code %d\n", err);
929 return err;