services: Wait for all services to terminate before exiting.
[wine] / programs / services / services.c
1 /*
2  * Services - controls services keeps track of their state
3  *
4  * Copyright 2007 Google (Mikolaj Zalewski)
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #define WIN32_LEAN_AND_MEAN
22
23 #include <stdarg.h>
24 #include <windows.h>
25 #include <winsvc.h>
26 #include <rpc.h>
27 #include <userenv.h>
28
29 #include "wine/unicode.h"
30 #include "wine/debug.h"
31 #include "svcctl.h"
32
33 #include "services.h"
34
35 #define MAX_SERVICE_NAME 260
36
37 WINE_DEFAULT_DEBUG_CHANNEL(service);
38
39 HANDLE g_hStartedEvent;
40 struct scmdatabase *active_database;
41
42 DWORD service_pipe_timeout = 10000;
43 DWORD service_kill_timeout = 20000;
44 static DWORD default_preshutdown_timeout = 180000;
45 static void *env = NULL;
46
47 static const int is_win64 = (sizeof(void *) > sizeof(int));
48
49 static const WCHAR SZ_LOCAL_SYSTEM[] = {'L','o','c','a','l','S','y','s','t','e','m',0};
50
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 };
55
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
70
71 DWORD service_create(LPCWSTR name, struct service_entry **entry)
72 {
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)
78     {
79         HeapFree(GetProcessHeap(), 0, *entry);
80         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
81     }
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;
88 }
89
90 void free_service_entry(struct service_entry *entry)
91 {
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);
107 }
108
109 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
110 {
111     DWORD err;
112     WCHAR *wptr;
113
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;
128
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;
139
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));
150
151     return ERROR_SUCCESS;
152 }
153
154 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
155 {
156     if (!string)
157     {
158         DWORD err;
159         err = RegDeleteValueW(hKey, value_name);
160         if (err != ERROR_FILE_NOT_FOUND)
161             return err;
162
163         return ERROR_SUCCESS;
164     }
165
166     return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
167 }
168
169 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
170 {
171     const WCHAR *ptr;
172
173     if (!string)
174     {
175         DWORD err;
176         err = RegDeleteValueW(hKey, value_name);
177         if (err != ERROR_FILE_NOT_FOUND)
178             return err;
179
180         return ERROR_SUCCESS;
181     }
182
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));
186 }
187
188 DWORD save_service_config(struct service_entry *entry)
189 {
190     DWORD err;
191     HKEY hKey = NULL;
192
193     err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
194     if (err != ERROR_SUCCESS)
195         goto cleanup;
196
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;
219
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);
224
225     if (err != 0 && err != ERROR_FILE_NOT_FOUND)
226         goto cleanup;
227
228     err = ERROR_SUCCESS;
229 cleanup:
230     RegCloseKey(hKey);
231     return err;
232 }
233
234 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
235 {
236     int err;
237     service->db = db;
238     if ((err = save_service_config(service)) != ERROR_SUCCESS)
239     {
240         WINE_ERR("Couldn't store service configuration: error %u\n", err);
241         return ERROR_GEN_FAILURE;
242     }
243
244     list_add_tail(&db->services, &service->entry);
245     return ERROR_SUCCESS;
246 }
247
248 DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
249 {
250     int err;
251
252     err = RegDeleteTreeW(db->root_key, service->name);
253
254     if (err != 0)
255         return err;
256
257     list_remove(&service->entry);
258     service->entry.next = service->entry.prev = NULL;
259     return ERROR_SUCCESS;
260 }
261
262 static void scmdatabase_autostart_services(struct scmdatabase *db)
263 {
264     struct service_entry **services_list;
265     unsigned int i = 0;
266     unsigned int size = 32;
267     struct service_entry *service;
268
269     services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
270     if (!services_list)
271         return;
272
273     scmdatabase_lock_shared(db);
274
275     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
276     {
277         if (service->config.dwStartType == SERVICE_BOOT_START ||
278             service->config.dwStartType == SERVICE_SYSTEM_START ||
279             service->config.dwStartType == SERVICE_AUTO_START)
280         {
281             if (i+1 >= size)
282             {
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;
289             }
290             services_list[i] = service;
291             service->ref_count++;
292             i++;
293         }
294     }
295
296     scmdatabase_unlock(db);
297
298     size = i;
299     for (i = 0; i < size; i++)
300     {
301         DWORD err;
302         const WCHAR *argv[2];
303         service = services_list[i];
304         argv[0] = service->name;
305         argv[1] = NULL;
306         err = service_start(service, 1, argv);
307         if (err != ERROR_SUCCESS)
308             WINE_FIXME("Auto-start service %s failed to start: %d\n",
309                        wine_dbgstr_w(service->name), err);
310         release_service(service);
311     }
312
313     HeapFree(GetProcessHeap(), 0, services_list);
314 }
315
316 static void scmdatabase_wait_terminate(struct scmdatabase *db)
317 {
318     struct service_entry *service;
319     BOOL run = TRUE;
320
321     scmdatabase_lock_shared(db);
322     while(run)
323     {
324         run = FALSE;
325         LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
326         {
327             if(service->process)
328             {
329                 scmdatabase_unlock(db);
330                 WaitForSingleObject(service->process, INFINITE);
331                 scmdatabase_lock_shared(db);
332                 CloseHandle(service->process);
333                 service->process = NULL;
334                 run = TRUE;
335                 break;
336             }
337         }
338     }
339     scmdatabase_unlock(db);
340 }
341
342 BOOL validate_service_name(LPCWSTR name)
343 {
344     return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
345 }
346
347 BOOL validate_service_config(struct service_entry *entry)
348 {
349     if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
350     {
351         WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
352         return FALSE;
353     }
354
355     switch (entry->config.dwServiceType)
356     {
357     case SERVICE_KERNEL_DRIVER:
358     case SERVICE_FILE_SYSTEM_DRIVER:
359     case SERVICE_WIN32_OWN_PROCESS:
360     case SERVICE_WIN32_SHARE_PROCESS:
361         /* No problem */
362         break;
363     case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
364     case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
365         /* These can be only run as LocalSystem */
366         if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
367         {
368             WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
369             return FALSE;
370         }
371         break;
372     default:
373         WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
374         return FALSE;
375     }
376
377     /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
378     if (entry->config.dwStartType > SERVICE_DISABLED)
379     {
380         WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
381         return FALSE;
382     }
383
384     /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
385     if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
386         ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
387     {
388         WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
389         return FALSE;
390     }
391
392     if (entry->config.lpServiceStartName == NULL)
393         entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
394
395     return TRUE;
396 }
397
398
399 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
400 {
401     struct service_entry *service;
402
403     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
404     {
405         if (strcmpiW(name, service->name) == 0)
406             return service;
407     }
408
409     return NULL;
410 }
411
412 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
413 {
414     struct service_entry *service;
415
416     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
417     {
418         if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
419             return service;
420     }
421
422     return NULL;
423 }
424
425 void release_service(struct service_entry *service)
426 {
427     if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
428         free_service_entry(service);
429 }
430
431 static DWORD scmdatabase_create(struct scmdatabase **db)
432 {
433     DWORD err;
434
435     *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
436     if (!*db)
437         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
438
439     (*db)->service_start_lock = FALSE;
440     list_init(&(*db)->services);
441
442     InitializeCriticalSection(&(*db)->cs);
443     (*db)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": scmdatabase");
444
445     err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
446                           REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
447                           &(*db)->root_key, NULL);
448     if (err != ERROR_SUCCESS)
449         HeapFree(GetProcessHeap(), 0, *db);
450
451     return err;
452 }
453
454 static void scmdatabase_destroy(struct scmdatabase *db)
455 {
456     RegCloseKey(db->root_key);
457     db->cs.DebugInfo->Spare[0] = 0;
458     DeleteCriticalSection(&db->cs);
459     HeapFree(GetProcessHeap(), 0, db);
460 }
461
462 static DWORD scmdatabase_load_services(struct scmdatabase *db)
463 {
464     DWORD err;
465     int i;
466
467     for (i = 0; TRUE; i++)
468     {
469         WCHAR szName[MAX_SERVICE_NAME];
470         struct service_entry *entry;
471         HKEY hServiceKey;
472
473         err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
474         if (err == ERROR_NO_MORE_ITEMS)
475             break;
476
477         if (err != 0)
478         {
479             WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
480             continue;
481         }
482
483         err = service_create(szName, &entry);
484         if (err != ERROR_SUCCESS)
485             break;
486
487         WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
488         err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
489         if (err == ERROR_SUCCESS)
490         {
491             err = load_service_config(hServiceKey, entry);
492             RegCloseKey(hServiceKey);
493         }
494
495         if (err != ERROR_SUCCESS)
496         {
497             WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
498             free_service_entry(entry);
499             continue;
500         }
501
502         if (entry->config.dwServiceType == 0)
503         {
504             /* Maybe an application only wrote some configuration in the service key. Continue silently */
505             WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
506             free_service_entry(entry);
507             continue;
508         }
509
510         if (!validate_service_config(entry))
511         {
512             WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
513             free_service_entry(entry);
514             continue;
515         }
516
517         entry->status.dwServiceType = entry->config.dwServiceType;
518         entry->db = db;
519
520         list_add_tail(&db->services, &entry->entry);
521     }
522     return ERROR_SUCCESS;
523 }
524
525 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
526 {
527     if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
528         return ERROR_SERVICE_DATABASE_LOCKED;
529     return ERROR_SUCCESS;
530 }
531
532 void scmdatabase_unlock_startup(struct scmdatabase *db)
533 {
534     InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
535 }
536
537 void scmdatabase_lock_shared(struct scmdatabase *db)
538 {
539     EnterCriticalSection(&db->cs);
540 }
541
542 void scmdatabase_lock_exclusive(struct scmdatabase *db)
543 {
544     EnterCriticalSection(&db->cs);
545 }
546
547 void scmdatabase_unlock(struct scmdatabase *db)
548 {
549     LeaveCriticalSection(&db->cs);
550 }
551
552 void service_lock_shared(struct service_entry *service)
553 {
554     EnterCriticalSection(&service->db->cs);
555 }
556
557 void service_lock_exclusive(struct service_entry *service)
558 {
559     EnterCriticalSection(&service->db->cs);
560 }
561
562 void service_unlock(struct service_entry *service)
563 {
564     LeaveCriticalSection(&service->db->cs);
565 }
566
567 /* only one service started at a time, so there is no race on the registry
568  * value here */
569 static LPWSTR service_get_pipe_name(void)
570 {
571     static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
572         'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
573     static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
574         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
575         'C','o','n','t','r','o','l','\\',
576         'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
577     LPWSTR name;
578     DWORD len;
579     HKEY service_current_key;
580     DWORD service_current = -1;
581     LONG ret;
582     DWORD type;
583
584     ret = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
585         NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
586         &service_current_key, NULL);
587     if (ret != ERROR_SUCCESS)
588         return NULL;
589     len = sizeof(service_current);
590     ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
591         (BYTE *)&service_current, &len);
592     if ((ret == ERROR_SUCCESS && type == REG_DWORD) || ret == ERROR_FILE_NOT_FOUND)
593     {
594         service_current++;
595         RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
596             (BYTE *)&service_current, sizeof(service_current));
597     }
598     RegCloseKey(service_current_key);
599     if ((ret != ERROR_SUCCESS || type != REG_DWORD) && (ret != ERROR_FILE_NOT_FOUND))
600         return NULL;
601     len = sizeof(format)/sizeof(WCHAR) + 10 /* strlenW("4294967295") */;
602     name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
603     if (!name)
604         return NULL;
605     snprintfW(name, len, format, service_current);
606     return name;
607 }
608
609 static DWORD service_start_process(struct service_entry *service_entry, HANDLE *process)
610 {
611     PROCESS_INFORMATION pi;
612     STARTUPINFOW si;
613     LPWSTR path = NULL;
614     DWORD size;
615     BOOL r;
616
617     service_lock_exclusive(service_entry);
618
619     if (!env)
620     {
621         HANDLE htok;
622
623         if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &htok))
624             CreateEnvironmentBlock(&env, htok, FALSE);
625
626         if (!env)
627             WINE_ERR("failed to create services environment\n");
628     }
629
630     size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,NULL,0);
631     path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
632     if (!path)
633     {
634         service_unlock(service_entry);
635         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
636     }
637     ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,path,size);
638
639     if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER)
640     {
641         static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
642         WCHAR system_dir[MAX_PATH];
643         DWORD type, len;
644
645         GetSystemDirectoryW( system_dir, MAX_PATH );
646         if (is_win64)
647         {
648             if (!GetBinaryTypeW( path, &type ))
649             {
650                 HeapFree( GetProcessHeap(), 0, path );
651                 service_unlock(service_entry);
652                 return GetLastError();
653             }
654             if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
655         }
656
657         len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
658         HeapFree( GetProcessHeap(), 0, path );
659         if (!(path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
660         {
661             service_unlock(service_entry);
662             return ERROR_NOT_ENOUGH_SERVER_MEMORY;
663         }
664         lstrcpyW( path, system_dir );
665         lstrcatW( path, winedeviceW );
666         lstrcatW( path, service_entry->name );
667     }
668
669     ZeroMemory(&si, sizeof(STARTUPINFOW));
670     si.cb = sizeof(STARTUPINFOW);
671     if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
672     {
673         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};
674         si.lpDesktop = desktopW;
675     }
676
677     service_entry->status.dwCurrentState = SERVICE_START_PENDING;
678
679     service_unlock(service_entry);
680
681     r = CreateProcessW(NULL, path, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
682     HeapFree(GetProcessHeap(),0,path);
683     if (!r)
684     {
685         service_lock_exclusive(service_entry);
686         service_entry->status.dwCurrentState = SERVICE_STOPPED;
687         service_unlock(service_entry);
688         return GetLastError();
689     }
690
691     service_entry->status.dwProcessId = pi.dwProcessId;
692     service_entry->process = pi.hProcess;
693     *process = pi.hProcess;
694     CloseHandle( pi.hThread );
695
696     return ERROR_SUCCESS;
697 }
698
699 static DWORD service_wait_for_startup(struct service_entry *service_entry, HANDLE process_handle)
700 {
701     WINE_TRACE("%p\n", service_entry);
702
703     for (;;)
704     {
705         DWORD dwCurrentStatus;
706         HANDLE handles[2] = { service_entry->status_changed_event, process_handle };
707         DWORD ret;
708         ret = WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout );
709         if (ret != WAIT_OBJECT_0)
710             return ERROR_SERVICE_REQUEST_TIMEOUT;
711         service_lock_shared(service_entry);
712         dwCurrentStatus = service_entry->status.dwCurrentState;
713         service_unlock(service_entry);
714         if (dwCurrentStatus == SERVICE_RUNNING)
715         {
716             WINE_TRACE("Service started successfully\n");
717             return ERROR_SUCCESS;
718         }
719         if (dwCurrentStatus != SERVICE_START_PENDING)
720             return ERROR_SERVICE_REQUEST_TIMEOUT;
721     }
722 }
723
724 /******************************************************************************
725  * service_send_start_message
726  */
727 static BOOL service_send_start_message(struct service_entry *service, HANDLE process_handle,
728                                        LPCWSTR *argv, DWORD argc)
729 {
730     OVERLAPPED overlapped;
731     DWORD i, len, result;
732     service_start_info *ssi;
733     LPWSTR p;
734     BOOL r;
735
736     WINE_TRACE("%s %p %d\n", wine_dbgstr_w(service->name), argv, argc);
737
738     overlapped.hEvent = service->overlapped_event;
739     if (!ConnectNamedPipe(service->control_pipe, &overlapped))
740     {
741         if (GetLastError() == ERROR_IO_PENDING)
742         {
743             HANDLE handles[2];
744             handles[0] = service->overlapped_event;
745             handles[1] = process_handle;
746             if (WaitForMultipleObjects( 2, handles, FALSE, service_pipe_timeout ) != WAIT_OBJECT_0)
747                 CancelIo( service->control_pipe );
748             if (!HasOverlappedCompleted( &overlapped ))
749             {
750                 WINE_ERR( "service %s failed to start\n", wine_dbgstr_w( service->name ));
751                 return FALSE;
752             }
753         }
754         else if (GetLastError() != ERROR_PIPE_CONNECTED)
755         {
756             WINE_ERR("pipe connect failed\n");
757             return FALSE;
758         }
759     }
760
761     /* calculate how much space do we need to send the startup info */
762     len = strlenW(service->name) + 1;
763     for (i=0; i<argc; i++)
764         len += strlenW(argv[i])+1;
765     len++;
766
767     ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
768     ssi->cmd = WINESERV_STARTINFO;
769     ssi->control = 0;
770     ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
771     ssi->name_size = strlenW(service->name) + 1;
772     strcpyW( ssi->data, service->name );
773
774     /* copy service args into a single buffer*/
775     p = &ssi->data[ssi->name_size];
776     for (i=0; i<argc; i++)
777     {
778         strcpyW(p, argv[i]);
779         p += strlenW(p) + 1;
780     }
781     *p=0;
782
783     r = service_send_command( service, service->control_pipe, ssi, ssi->total_size, &result );
784     if (r && result)
785     {
786         SetLastError(result);
787         r = FALSE;
788     }
789
790     HeapFree(GetProcessHeap(),0,ssi);
791
792     return r;
793 }
794
795 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
796 {
797     DWORD err;
798     LPWSTR name;
799     HANDLE process_handle = NULL;
800
801     err = scmdatabase_lock_startup(service->db);
802     if (err != ERROR_SUCCESS)
803         return err;
804
805     if (service->control_pipe != INVALID_HANDLE_VALUE)
806     {
807         scmdatabase_unlock_startup(service->db);
808         return ERROR_SERVICE_ALREADY_RUNNING;
809     }
810
811     service->control_mutex = CreateMutexW(NULL, TRUE, NULL);
812
813     if (!service->status_changed_event)
814         service->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
815     if (!service->overlapped_event)
816         service->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);
817
818     name = service_get_pipe_name();
819     service->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
820                   PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
821     HeapFree(GetProcessHeap(), 0, name);
822     if (service->control_pipe==INVALID_HANDLE_VALUE)
823     {
824         WINE_ERR("failed to create pipe for %s, error = %d\n",
825             wine_dbgstr_w(service->name), GetLastError());
826         err = GetLastError();
827     }
828     else
829     {
830         err = service_start_process(service, &process_handle);
831         if (err == ERROR_SUCCESS)
832         {
833             if (!service_send_start_message(service, process_handle, service_argv, service_argc))
834                 err = ERROR_SERVICE_REQUEST_TIMEOUT;
835         }
836
837         if (err == ERROR_SUCCESS)
838             err = service_wait_for_startup(service, process_handle);
839     }
840
841     if (err == ERROR_SUCCESS)
842         ReleaseMutex(service->control_mutex);
843     else
844     {
845         CloseHandle(service->overlapped_event);
846         service->overlapped_event = NULL;
847         CloseHandle(service->status_changed_event);
848         service->status_changed_event = NULL;
849         CloseHandle(service->control_mutex);
850         service->control_mutex = NULL;
851         if (service->control_pipe != INVALID_HANDLE_VALUE)
852             CloseHandle(service->control_pipe);
853         service->control_pipe = INVALID_HANDLE_VALUE;
854
855         service->status.dwProcessId = 0;
856         service_lock_exclusive(service);
857         service->status.dwCurrentState = SERVICE_STOPPED;
858         service_unlock(service);
859     }
860     scmdatabase_unlock_startup(service->db);
861
862     WINE_TRACE("returning %d\n", err);
863
864     return err;
865 }
866
867 static void load_registry_parameters(void)
868 {
869     static const WCHAR controlW[] =
870         { 'S','y','s','t','e','m','\\',
871           'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
872           'C','o','n','t','r','o','l',0 };
873     static const WCHAR pipetimeoutW[] =
874         {'S','e','r','v','i','c','e','s','P','i','p','e','T','i','m','e','o','u','t',0};
875     static const WCHAR killtimeoutW[] =
876         {'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};
877     HKEY key;
878     WCHAR buffer[64];
879     DWORD type, count, val;
880
881     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, controlW, &key )) return;
882
883     count = sizeof(buffer);
884     if (!RegQueryValueExW( key, pipetimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
885         type == REG_SZ && (val = atoiW( buffer )))
886         service_pipe_timeout = val;
887
888     count = sizeof(buffer);
889     if (!RegQueryValueExW( key, killtimeoutW, NULL, &type, (BYTE *)buffer, &count ) &&
890         type == REG_SZ && (val = atoiW( buffer )))
891         service_kill_timeout = val;
892
893     RegCloseKey( key );
894 }
895
896 int main(int argc, char *argv[])
897 {
898     static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
899     DWORD err;
900
901     g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
902     load_registry_parameters();
903     err = scmdatabase_create(&active_database);
904     if (err != ERROR_SUCCESS)
905         return err;
906     if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
907         return err;
908     if ((err = RPC_Init()) == ERROR_SUCCESS)
909     {
910         scmdatabase_autostart_services(active_database);
911         RPC_MainLoop();
912         scmdatabase_wait_terminate(active_database);
913     }
914     scmdatabase_destroy(active_database);
915     if (env)
916         DestroyEnvironmentBlock(env);
917
918     WINE_TRACE("services.exe exited with code %d\n", err);
919     return err;
920 }