shell32/tests: Fix test failure on some NT4.
[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
28 #include "wine/unicode.h"
29 #include "wine/debug.h"
30 #include "svcctl.h"
31
32 #include "services.h"
33
34 #define MAX_SERVICE_NAME 260
35
36 WINE_DEFAULT_DEBUG_CHANNEL(service);
37
38 HANDLE g_hStartedEvent;
39 struct scmdatabase *active_database;
40
41 static const int is_win64 = (sizeof(void *) > sizeof(int));
42
43 static const WCHAR SZ_LOCAL_SYSTEM[] = {'L','o','c','a','l','S','y','s','t','e','m',0};
44
45 /* Registry constants */
46 static const WCHAR SZ_SERVICES_KEY[] = { 'S','y','s','t','e','m','\\',
47       'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
48       'S','e','r','v','i','c','e','s',0 };
49
50 /* Service key values names */
51 static const WCHAR SZ_DISPLAY_NAME[]      = {'D','i','s','p','l','a','y','N','a','m','e',0 };
52 static const WCHAR SZ_TYPE[]              = {'T','y','p','e',0 };
53 static const WCHAR SZ_START[]             = {'S','t','a','r','t',0 };
54 static const WCHAR SZ_ERROR[]             = {'E','r','r','o','r','C','o','n','t','r','o','l',0 };
55 static const WCHAR SZ_IMAGE_PATH[]        = {'I','m','a','g','e','P','a','t','h',0};
56 static const WCHAR SZ_GROUP[]             = {'G','r','o','u','p',0};
57 static const WCHAR SZ_DEPEND_ON_SERVICE[] = {'D','e','p','e','n','d','O','n','S','e','r','v','i','c','e',0};
58 static const WCHAR SZ_DEPEND_ON_GROUP[]   = {'D','e','p','e','n','d','O','n','G','r','o','u','p',0};
59 static const WCHAR SZ_OBJECT_NAME[]       = {'O','b','j','e','c','t','N','a','m','e',0};
60 static const WCHAR SZ_TAG[]               = {'T','a','g',0};
61 static const WCHAR SZ_DESCRIPTION[]       = {'D','e','s','c','r','i','p','t','i','o','n',0};
62
63
64 DWORD service_create(LPCWSTR name, struct service_entry **entry)
65 {
66     *entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**entry));
67     if (!*entry)
68         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
69     (*entry)->name = strdupW(name);
70     if (!(*entry)->name)
71     {
72         HeapFree(GetProcessHeap(), 0, *entry);
73         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
74     }
75     (*entry)->control_pipe = INVALID_HANDLE_VALUE;
76     (*entry)->status.dwCurrentState = SERVICE_STOPPED;
77     (*entry)->status.dwWin32ExitCode = ERROR_SERVICE_NEVER_STARTED;
78     /* all other fields are zero */
79     return ERROR_SUCCESS;
80 }
81
82 void free_service_entry(struct service_entry *entry)
83 {
84     HeapFree(GetProcessHeap(), 0, entry->name);
85     HeapFree(GetProcessHeap(), 0, entry->config.lpBinaryPathName);
86     HeapFree(GetProcessHeap(), 0, entry->config.lpDependencies);
87     HeapFree(GetProcessHeap(), 0, entry->config.lpLoadOrderGroup);
88     HeapFree(GetProcessHeap(), 0, entry->config.lpServiceStartName);
89     HeapFree(GetProcessHeap(), 0, entry->config.lpDisplayName);
90     HeapFree(GetProcessHeap(), 0, entry->description);
91     HeapFree(GetProcessHeap(), 0, entry->dependOnServices);
92     HeapFree(GetProcessHeap(), 0, entry->dependOnGroups);
93     CloseHandle(entry->control_mutex);
94     CloseHandle(entry->control_pipe);
95     CloseHandle(entry->status_changed_event);
96     HeapFree(GetProcessHeap(), 0, entry);
97 }
98
99 static DWORD load_service_config(HKEY hKey, struct service_entry *entry)
100 {
101     DWORD err;
102     WCHAR *wptr;
103
104     if ((err = load_reg_string(hKey, SZ_IMAGE_PATH,   TRUE, &entry->config.lpBinaryPathName)) != 0)
105         return err;
106     if ((err = load_reg_string(hKey, SZ_GROUP,        0,    &entry->config.lpLoadOrderGroup)) != 0)
107         return err;
108     if ((err = load_reg_string(hKey, SZ_OBJECT_NAME,  TRUE, &entry->config.lpServiceStartName)) != 0)
109         return err;
110     if ((err = load_reg_string(hKey, SZ_DISPLAY_NAME, 0,    &entry->config.lpDisplayName)) != 0)
111         return err;
112     if ((err = load_reg_string(hKey, SZ_DESCRIPTION,  0,    &entry->description)) != 0)
113         return err;
114     if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_SERVICE, TRUE, &entry->dependOnServices)) != 0)
115         return err;
116     if ((err = load_reg_multisz(hKey, SZ_DEPEND_ON_GROUP, FALSE, &entry->dependOnGroups)) != 0)
117         return err;
118
119     if ((err = load_reg_dword(hKey, SZ_TYPE,  &entry->config.dwServiceType)) != 0)
120         return err;
121     if ((err = load_reg_dword(hKey, SZ_START, &entry->config.dwStartType)) != 0)
122         return err;
123     if ((err = load_reg_dword(hKey, SZ_ERROR, &entry->config.dwErrorControl)) != 0)
124         return err;
125     if ((err = load_reg_dword(hKey, SZ_TAG,   &entry->config.dwTagId)) != 0)
126         return err;
127
128     WINE_TRACE("Image path           = %s\n", wine_dbgstr_w(entry->config.lpBinaryPathName) );
129     WINE_TRACE("Group                = %s\n", wine_dbgstr_w(entry->config.lpLoadOrderGroup) );
130     WINE_TRACE("Service account name = %s\n", wine_dbgstr_w(entry->config.lpServiceStartName) );
131     WINE_TRACE("Display name         = %s\n", wine_dbgstr_w(entry->config.lpDisplayName) );
132     WINE_TRACE("Service dependencies : %s\n", entry->dependOnServices[0] ? "" : "(none)");
133     for (wptr = entry->dependOnServices; *wptr; wptr += strlenW(wptr) + 1)
134         WINE_TRACE("    * %s\n", wine_dbgstr_w(wptr));
135     WINE_TRACE("Group dependencies   : %s\n", entry->dependOnGroups[0] ? "" : "(none)");
136     for (wptr = entry->dependOnGroups; *wptr; wptr += strlenW(wptr) + 1)
137         WINE_TRACE("    * %s\n", wine_dbgstr_w(wptr));
138
139     return ERROR_SUCCESS;
140 }
141
142 static DWORD reg_set_string_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
143 {
144     if (!string)
145     {
146         DWORD err;
147         err = RegDeleteValueW(hKey, value_name);
148         if (err != ERROR_FILE_NOT_FOUND)
149             return err;
150
151         return ERROR_SUCCESS;
152     }
153
154     return RegSetValueExW(hKey, value_name, 0, REG_SZ, (const BYTE*)string, sizeof(WCHAR)*(strlenW(string) + 1));
155 }
156
157 static DWORD reg_set_multisz_value(HKEY hKey, LPCWSTR value_name, LPCWSTR string)
158 {
159     const WCHAR *ptr;
160
161     if (!string)
162     {
163         DWORD err;
164         err = RegDeleteValueW(hKey, value_name);
165         if (err != ERROR_FILE_NOT_FOUND)
166             return err;
167
168         return ERROR_SUCCESS;
169     }
170
171     ptr = string;
172     while (*ptr) ptr += strlenW(ptr) + 1;
173     return RegSetValueExW(hKey, value_name, 0, REG_MULTI_SZ, (const BYTE*)string, sizeof(WCHAR)*(ptr - string + 1));
174 }
175
176 DWORD save_service_config(struct service_entry *entry)
177 {
178     DWORD err;
179     HKEY hKey = NULL;
180
181     err = RegCreateKeyW(entry->db->root_key, entry->name, &hKey);
182     if (err != ERROR_SUCCESS)
183         goto cleanup;
184
185     if ((err = reg_set_string_value(hKey, SZ_DISPLAY_NAME, entry->config.lpDisplayName)) != 0)
186         goto cleanup;
187     if ((err = reg_set_string_value(hKey, SZ_IMAGE_PATH, entry->config.lpBinaryPathName)) != 0)
188         goto cleanup;
189     if ((err = reg_set_string_value(hKey, SZ_GROUP, entry->config.lpLoadOrderGroup)) != 0)
190         goto cleanup;
191     if ((err = reg_set_string_value(hKey, SZ_OBJECT_NAME, entry->config.lpServiceStartName)) != 0)
192         goto cleanup;
193     if ((err = reg_set_string_value(hKey, SZ_DESCRIPTION, entry->description)) != 0)
194         goto cleanup;
195     if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_SERVICE, entry->dependOnServices)) != 0)
196         goto cleanup;
197     if ((err = reg_set_multisz_value(hKey, SZ_DEPEND_ON_GROUP, entry->dependOnGroups)) != 0)
198         goto cleanup;
199     if ((err = RegSetValueExW(hKey, SZ_START, 0, REG_DWORD, (LPBYTE)&entry->config.dwStartType, sizeof(DWORD))) != 0)
200         goto cleanup;
201     if ((err = RegSetValueExW(hKey, SZ_ERROR, 0, REG_DWORD, (LPBYTE)&entry->config.dwErrorControl, sizeof(DWORD))) != 0)
202         goto cleanup;
203
204     if ((err = RegSetValueExW(hKey, SZ_TYPE, 0, REG_DWORD, (LPBYTE)&entry->config.dwServiceType, sizeof(DWORD))) != 0)
205         goto cleanup;
206
207     if (entry->config.dwTagId)
208         err = RegSetValueExW(hKey, SZ_TAG, 0, REG_DWORD, (LPBYTE)&entry->config.dwTagId, sizeof(DWORD));
209     else
210         err = RegDeleteValueW(hKey, SZ_TAG);
211
212     if (err != 0 && err != ERROR_FILE_NOT_FOUND)
213         goto cleanup;
214
215     err = ERROR_SUCCESS;
216 cleanup:
217     RegCloseKey(hKey);
218     return err;
219 }
220
221 DWORD scmdatabase_add_service(struct scmdatabase *db, struct service_entry *service)
222 {
223     int err;
224     service->db = db;
225     if ((err = save_service_config(service)) != ERROR_SUCCESS)
226     {
227         WINE_ERR("Couldn't store service configuration: error %u\n", err);
228         return ERROR_GEN_FAILURE;
229     }
230
231     list_add_tail(&db->services, &service->entry);
232     return ERROR_SUCCESS;
233 }
234
235 DWORD scmdatabase_remove_service(struct scmdatabase *db, struct service_entry *service)
236 {
237     int err;
238
239     err = RegDeleteTreeW(db->root_key, service->name);
240
241     if (err != 0)
242         return err;
243
244     list_remove(&service->entry);
245     service->entry.next = service->entry.prev = NULL;
246     return ERROR_SUCCESS;
247 }
248
249 static void scmdatabase_autostart_services(struct scmdatabase *db)
250 {
251     struct service_entry **services_list;
252     unsigned int i = 0;
253     unsigned int size = 32;
254     struct service_entry *service;
255
256     services_list = HeapAlloc(GetProcessHeap(), 0, size * sizeof(services_list[0]));
257     if (!services_list)
258         return;
259
260     scmdatabase_lock_shared(db);
261
262     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
263     {
264         if (service->config.dwStartType == SERVICE_BOOT_START ||
265             service->config.dwStartType == SERVICE_SYSTEM_START ||
266             service->config.dwStartType == SERVICE_AUTO_START)
267         {
268             if (i+1 >= size)
269             {
270                 struct service_entry **slist_new;
271                 size *= 2;
272                 slist_new = HeapReAlloc(GetProcessHeap(), 0, services_list, size * sizeof(services_list[0]));
273                 if (!slist_new)
274                     break;
275                 services_list = slist_new;
276             }
277             services_list[i] = service;
278             service->ref_count++;
279             i++;
280         }
281     }
282
283     scmdatabase_unlock(db);
284
285     size = i;
286     for (i = 0; i < size; i++)
287     {
288         DWORD err;
289         const WCHAR *argv[2];
290         service = services_list[i];
291         argv[0] = service->name;
292         argv[1] = NULL;
293         err = service_start(service, 1, argv);
294         /* FIXME: do something if the service failed to start */
295         release_service(service);
296     }
297
298     HeapFree(GetProcessHeap(), 0, services_list);
299 }
300
301 BOOL validate_service_name(LPCWSTR name)
302 {
303     return (name && name[0] && !strchrW(name, '/') && !strchrW(name, '\\'));
304 }
305
306 BOOL validate_service_config(struct service_entry *entry)
307 {
308     if (entry->config.dwServiceType & SERVICE_WIN32 && (entry->config.lpBinaryPathName == NULL || !entry->config.lpBinaryPathName[0]))
309     {
310         WINE_ERR("Service %s is Win32 but has no image path set\n", wine_dbgstr_w(entry->name));
311         return FALSE;
312     }
313
314     switch (entry->config.dwServiceType)
315     {
316     case SERVICE_KERNEL_DRIVER:
317     case SERVICE_FILE_SYSTEM_DRIVER:
318     case SERVICE_WIN32_OWN_PROCESS:
319     case SERVICE_WIN32_SHARE_PROCESS:
320         /* No problem */
321         break;
322     case SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS:
323     case SERVICE_WIN32_SHARE_PROCESS | SERVICE_INTERACTIVE_PROCESS:
324         /* These can be only run as LocalSystem */
325         if (entry->config.lpServiceStartName && strcmpiW(entry->config.lpServiceStartName, SZ_LOCAL_SYSTEM) != 0)
326         {
327             WINE_ERR("Service %s is interactive but has a start name\n", wine_dbgstr_w(entry->name));
328             return FALSE;
329         }
330         break;
331     default:
332         WINE_ERR("Service %s has an unknown service type (0x%x)\n", wine_dbgstr_w(entry->name), entry->config.dwServiceType);
333         return FALSE;
334     }
335
336     /* StartType can only be a single value (if several values are mixed the result is probably not what was intended) */
337     if (entry->config.dwStartType > SERVICE_DISABLED)
338     {
339         WINE_ERR("Service %s has an unknown start type\n", wine_dbgstr_w(entry->name));
340         return FALSE;
341     }
342
343     /* SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services */
344     if (((entry->config.dwStartType == SERVICE_BOOT_START) || (entry->config.dwStartType == SERVICE_SYSTEM_START)) &&
345         ((entry->config.dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (entry->config.dwServiceType & SERVICE_WIN32_SHARE_PROCESS)))
346     {
347         WINE_ERR("Service %s - SERVICE_BOOT_START and SERVICE_SYSTEM_START are only allowed for driver services\n", wine_dbgstr_w(entry->name));
348         return FALSE;
349     }
350
351     if (entry->config.lpServiceStartName == NULL)
352         entry->config.lpServiceStartName = strdupW(SZ_LOCAL_SYSTEM);
353
354     return TRUE;
355 }
356
357
358 struct service_entry *scmdatabase_find_service(struct scmdatabase *db, LPCWSTR name)
359 {
360     struct service_entry *service;
361
362     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
363     {
364         if (strcmpiW(name, service->name) == 0)
365             return service;
366     }
367
368     return NULL;
369 }
370
371 struct service_entry *scmdatabase_find_service_by_displayname(struct scmdatabase *db, LPCWSTR name)
372 {
373     struct service_entry *service;
374
375     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
376     {
377         if (service->config.lpDisplayName && strcmpiW(name, service->config.lpDisplayName) == 0)
378             return service;
379     }
380
381     return NULL;
382 }
383
384 void release_service(struct service_entry *service)
385 {
386     if (InterlockedDecrement(&service->ref_count) == 0 && is_marked_for_delete(service))
387         free_service_entry(service);
388 }
389
390 static DWORD scmdatabase_create(struct scmdatabase **db)
391 {
392     DWORD err;
393
394     *db = HeapAlloc(GetProcessHeap(), 0, sizeof(**db));
395     if (!*db)
396         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
397
398     (*db)->service_start_lock = FALSE;
399     list_init(&(*db)->services);
400
401     InitializeCriticalSection(&(*db)->cs);
402
403     err = RegCreateKeyExW(HKEY_LOCAL_MACHINE, SZ_SERVICES_KEY, 0, NULL,
404                           REG_OPTION_NON_VOLATILE, MAXIMUM_ALLOWED, NULL,
405                           &(*db)->root_key, NULL);
406     if (err != ERROR_SUCCESS)
407         HeapFree(GetProcessHeap(), 0, *db);
408
409     return err;
410 }
411
412 static void scmdatabase_destroy(struct scmdatabase *db)
413 {
414     RegCloseKey(db->root_key);
415     DeleteCriticalSection(&db->cs);
416     HeapFree(GetProcessHeap(), 0, db);
417 }
418
419 static DWORD scmdatabase_load_services(struct scmdatabase *db)
420 {
421     DWORD err;
422     int i;
423
424     for (i = 0; TRUE; i++)
425     {
426         WCHAR szName[MAX_SERVICE_NAME];
427         struct service_entry *entry;
428         HKEY hServiceKey;
429
430         err = RegEnumKeyW(db->root_key, i, szName, MAX_SERVICE_NAME);
431         if (err == ERROR_NO_MORE_ITEMS)
432             break;
433
434         if (err != 0)
435         {
436             WINE_ERR("Error %d reading key %d name - skipping\n", err, i);
437             continue;
438         }
439
440         err = service_create(szName, &entry);
441         if (err != ERROR_SUCCESS)
442             break;
443
444         WINE_TRACE("Loading service %s\n", wine_dbgstr_w(szName));
445         err = RegOpenKeyExW(db->root_key, szName, 0, KEY_READ, &hServiceKey);
446         if (err == ERROR_SUCCESS)
447         {
448             err = load_service_config(hServiceKey, entry);
449             RegCloseKey(hServiceKey);
450         }
451
452         if (err != ERROR_SUCCESS)
453         {
454             WINE_ERR("Error %d reading registry key for service %s - skipping\n", err, wine_dbgstr_w(szName));
455             free_service_entry(entry);
456             continue;
457         }
458
459         if (entry->config.dwServiceType == 0)
460         {
461             /* Maybe an application only wrote some configuration in the service key. Continue silently */
462             WINE_TRACE("Even the service type not set for service %s - skipping\n", wine_dbgstr_w(szName));
463             free_service_entry(entry);
464             continue;
465         }
466
467         if (!validate_service_config(entry))
468         {
469             WINE_ERR("Invalid configuration of service %s - skipping\n", wine_dbgstr_w(szName));
470             free_service_entry(entry);
471             continue;
472         }
473
474         entry->status.dwServiceType = entry->config.dwServiceType;
475         entry->db = db;
476
477         list_add_tail(&db->services, &entry->entry);
478     }
479     return ERROR_SUCCESS;
480 }
481
482 DWORD scmdatabase_lock_startup(struct scmdatabase *db)
483 {
484     if (InterlockedCompareExchange(&db->service_start_lock, TRUE, FALSE))
485         return ERROR_SERVICE_DATABASE_LOCKED;
486     return ERROR_SUCCESS;
487 }
488
489 void scmdatabase_unlock_startup(struct scmdatabase *db)
490 {
491     InterlockedCompareExchange(&db->service_start_lock, FALSE, TRUE);
492 }
493
494 void scmdatabase_lock_shared(struct scmdatabase *db)
495 {
496     EnterCriticalSection(&db->cs);
497 }
498
499 void scmdatabase_lock_exclusive(struct scmdatabase *db)
500 {
501     EnterCriticalSection(&db->cs);
502 }
503
504 void scmdatabase_unlock(struct scmdatabase *db)
505 {
506     LeaveCriticalSection(&db->cs);
507 }
508
509 void service_lock_shared(struct service_entry *service)
510 {
511     EnterCriticalSection(&service->db->cs);
512 }
513
514 void service_lock_exclusive(struct service_entry *service)
515 {
516     EnterCriticalSection(&service->db->cs);
517 }
518
519 void service_unlock(struct service_entry *service)
520 {
521     LeaveCriticalSection(&service->db->cs);
522 }
523
524 /* only one service started at a time, so there is no race on the registry
525  * value here */
526 static LPWSTR service_get_pipe_name(void)
527 {
528     static const WCHAR format[] = { '\\','\\','.','\\','p','i','p','e','\\',
529         'n','e','t','\\','N','t','C','o','n','t','r','o','l','P','i','p','e','%','u',0};
530     static const WCHAR service_current_key_str[] = { 'S','Y','S','T','E','M','\\',
531         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
532         'C','o','n','t','r','o','l','\\',
533         'S','e','r','v','i','c','e','C','u','r','r','e','n','t',0};
534     LPWSTR name;
535     DWORD len;
536     HKEY service_current_key;
537     DWORD service_current = -1;
538     LONG ret;
539     DWORD type;
540
541     ret = RegCreateKeyExW(HKEY_LOCAL_MACHINE, service_current_key_str, 0,
542         NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL,
543         &service_current_key, NULL);
544     if (ret != ERROR_SUCCESS)
545         return NULL;
546     len = sizeof(service_current);
547     ret = RegQueryValueExW(service_current_key, NULL, NULL, &type,
548         (BYTE *)&service_current, &len);
549     if ((ret == ERROR_SUCCESS && type == REG_DWORD) || ret == ERROR_FILE_NOT_FOUND)
550     {
551         service_current++;
552         RegSetValueExW(service_current_key, NULL, 0, REG_DWORD,
553             (BYTE *)&service_current, sizeof(service_current));
554     }
555     RegCloseKey(service_current_key);
556     if ((ret != ERROR_SUCCESS || type != REG_DWORD) && (ret != ERROR_FILE_NOT_FOUND))
557         return NULL;
558     len = sizeof(format)/sizeof(WCHAR) + 10 /* strlenW("4294967295") */;
559     name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
560     if (!name)
561         return NULL;
562     snprintfW(name, len, format, service_current);
563     return name;
564 }
565
566 static DWORD service_start_process(struct service_entry *service_entry, HANDLE *process)
567 {
568     PROCESS_INFORMATION pi;
569     STARTUPINFOW si;
570     LPWSTR path = NULL;
571     DWORD size;
572     BOOL r;
573
574     service_lock_exclusive(service_entry);
575
576     size = ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,NULL,0);
577     path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
578     if (!path) return ERROR_NOT_ENOUGH_SERVER_MEMORY;
579     ExpandEnvironmentStringsW(service_entry->config.lpBinaryPathName,path,size);
580
581     if (service_entry->config.dwServiceType == SERVICE_KERNEL_DRIVER)
582     {
583         static const WCHAR winedeviceW[] = {'\\','w','i','n','e','d','e','v','i','c','e','.','e','x','e',' ',0};
584         WCHAR system_dir[MAX_PATH];
585         DWORD type, len;
586
587         GetSystemDirectoryW( system_dir, MAX_PATH );
588         if (is_win64)
589         {
590             if (!GetBinaryTypeW( path, &type ))
591             {
592                 HeapFree( GetProcessHeap(), 0, path );
593                 return GetLastError();
594             }
595             if (type == SCS_32BIT_BINARY) GetSystemWow64DirectoryW( system_dir, MAX_PATH );
596         }
597
598         len = strlenW( system_dir ) + sizeof(winedeviceW)/sizeof(WCHAR) + strlenW(service_entry->name);
599         HeapFree( GetProcessHeap(), 0, path );
600         if (!(path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
601             return ERROR_NOT_ENOUGH_SERVER_MEMORY;
602         lstrcpyW( path, system_dir );
603         lstrcatW( path, winedeviceW );
604         lstrcatW( path, service_entry->name );
605     }
606
607     ZeroMemory(&si, sizeof(STARTUPINFOW));
608     si.cb = sizeof(STARTUPINFOW);
609     if (!(service_entry->config.dwServiceType & SERVICE_INTERACTIVE_PROCESS))
610     {
611         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};
612         si.lpDesktop = desktopW;
613     }
614
615     service_entry->status.dwCurrentState = SERVICE_START_PENDING;
616
617     service_unlock(service_entry);
618
619     r = CreateProcessW(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
620     HeapFree(GetProcessHeap(),0,path);
621     if (!r)
622     {
623         service_lock_exclusive(service_entry);
624         service_entry->status.dwCurrentState = SERVICE_STOPPED;
625         service_unlock(service_entry);
626         return GetLastError();
627     }
628
629     service_entry->status.dwProcessId = pi.dwProcessId;
630     *process = pi.hProcess;
631     CloseHandle( pi.hThread );
632
633     return ERROR_SUCCESS;
634 }
635
636 static DWORD service_wait_for_startup(struct service_entry *service_entry, HANDLE process_handle)
637 {
638     WINE_TRACE("%p\n", service_entry);
639
640     for (;;)
641     {
642         DWORD dwCurrentStatus;
643         HANDLE handles[2] = { service_entry->status_changed_event, process_handle };
644         DWORD ret;
645         ret = WaitForMultipleObjects(sizeof(handles)/sizeof(handles[0]), handles, FALSE, 20000);
646         if (ret != WAIT_OBJECT_0)
647             return ERROR_SERVICE_REQUEST_TIMEOUT;
648         service_lock_shared(service_entry);
649         dwCurrentStatus = service_entry->status.dwCurrentState;
650         service_unlock(service_entry);
651         if (dwCurrentStatus == SERVICE_RUNNING)
652         {
653             WINE_TRACE("Service started successfully\n");
654             return ERROR_SUCCESS;
655         }
656         if (dwCurrentStatus != SERVICE_START_PENDING)
657             return ERROR_SERVICE_REQUEST_TIMEOUT;
658     }
659 }
660
661 /******************************************************************************
662  * service_send_start_message
663  */
664 static BOOL service_send_start_message(struct service_entry *service, LPCWSTR *argv, DWORD argc)
665 {
666     DWORD i, len, count, result;
667     service_start_info *ssi;
668     LPWSTR p;
669     BOOL r;
670
671     WINE_TRACE("%s %p %d\n", wine_dbgstr_w(service->name), argv, argc);
672
673     /* FIXME: this can block so should be done in another thread */
674     r = ConnectNamedPipe(service->control_pipe, NULL);
675     if (!r && GetLastError() != ERROR_PIPE_CONNECTED)
676     {
677         WINE_ERR("pipe connect failed\n");
678         return FALSE;
679     }
680
681     /* calculate how much space do we need to send the startup info */
682     len = strlenW(service->name) + 1;
683     for (i=0; i<argc; i++)
684         len += strlenW(argv[i])+1;
685     len++;
686
687     ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
688     ssi->cmd = WINESERV_STARTINFO;
689     ssi->control = 0;
690     ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
691     ssi->name_size = strlenW(service->name) + 1;
692     strcpyW( ssi->data, service->name );
693
694     /* copy service args into a single buffer*/
695     p = &ssi->data[ssi->name_size];
696     for (i=0; i<argc; i++)
697     {
698         strcpyW(p, argv[i]);
699         p += strlenW(p) + 1;
700     }
701     *p=0;
702
703     r = WriteFile(service->control_pipe, ssi, ssi->total_size, &count, NULL);
704     if (r)
705     {
706         r = ReadFile(service->control_pipe, &result, sizeof result, &count, NULL);
707         if (r && result)
708         {
709             SetLastError(result);
710             r = FALSE;
711         }
712     }
713
714     HeapFree(GetProcessHeap(),0,ssi);
715
716     return r;
717 }
718
719 DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
720 {
721     DWORD err;
722     LPWSTR name;
723     HANDLE process_handle = NULL;
724
725     err = scmdatabase_lock_startup(service->db);
726     if (err != ERROR_SUCCESS)
727         return err;
728
729     if (service->control_pipe != INVALID_HANDLE_VALUE)
730     {
731         scmdatabase_unlock_startup(service->db);
732         return ERROR_SERVICE_ALREADY_RUNNING;
733     }
734
735     service->control_mutex = CreateMutexW(NULL, TRUE, NULL);
736
737     if (!service->status_changed_event)
738         service->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
739
740     name = service_get_pipe_name();
741     service->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX,
742                   PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
743     HeapFree(GetProcessHeap(), 0, name);
744     if (service->control_pipe==INVALID_HANDLE_VALUE)
745     {
746         WINE_ERR("failed to create pipe for %s, error = %d\n",
747             wine_dbgstr_w(service->name), GetLastError());
748         scmdatabase_unlock_startup(service->db);
749         return GetLastError();
750     }
751
752     err = service_start_process(service, &process_handle);
753
754     if (err == ERROR_SUCCESS)
755     {
756         if (!service_send_start_message(service, service_argv, service_argc))
757             err = ERROR_SERVICE_REQUEST_TIMEOUT;
758     }
759
760     if (err == ERROR_SUCCESS)
761         err = service_wait_for_startup(service, process_handle);
762
763     if (process_handle)
764         CloseHandle(process_handle);
765
766     ReleaseMutex(service->control_mutex);
767     scmdatabase_unlock_startup(service->db);
768
769     WINE_TRACE("returning %d\n", err);
770
771     return err;
772 }
773
774
775 int main(int argc, char *argv[])
776 {
777     static const WCHAR svcctl_started_event[] = SVCCTL_STARTED_EVENT;
778     DWORD err;
779     g_hStartedEvent = CreateEventW(NULL, TRUE, FALSE, svcctl_started_event);
780     err = scmdatabase_create(&active_database);
781     if (err != ERROR_SUCCESS)
782         return err;
783     if ((err = scmdatabase_load_services(active_database)) != ERROR_SUCCESS)
784         return err;
785     if ((err = RPC_Init()) == ERROR_SUCCESS)
786     {
787         scmdatabase_autostart_services(active_database);
788         RPC_MainLoop();
789     }
790     scmdatabase_destroy(active_database);
791     return err;
792 }