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