services: Wait for all services to terminate before exiting.
[wine] / programs / services / rpc.c
1 /*
2  * Services.exe - RPC functions
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 <winternl.h>
26 #include <winsvc.h>
27 #include <ntsecapi.h>
28 #include <rpc.h>
29
30 #include "wine/list.h"
31 #include "wine/unicode.h"
32 #include "wine/debug.h"
33
34 #include "services.h"
35 #include "svcctl.h"
36
37 extern HANDLE CDECL __wine_make_process_system(void);
38
39 WINE_DEFAULT_DEBUG_CHANNEL(service);
40
41 static const GENERIC_MAPPING g_scm_generic =
42 {
43     (STANDARD_RIGHTS_READ | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_QUERY_LOCK_STATUS),
44     (STANDARD_RIGHTS_WRITE | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_MODIFY_BOOT_CONFIG),
45     (STANDARD_RIGHTS_EXECUTE | SC_MANAGER_CONNECT | SC_MANAGER_LOCK),
46     SC_MANAGER_ALL_ACCESS
47 };
48
49 static const GENERIC_MAPPING g_svc_generic =
50 {
51     (STANDARD_RIGHTS_READ | SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_INTERROGATE | SERVICE_ENUMERATE_DEPENDENTS),
52     (STANDARD_RIGHTS_WRITE | SERVICE_CHANGE_CONFIG),
53     (STANDARD_RIGHTS_EXECUTE | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_USER_DEFINED_CONTROL),
54     SERVICE_ALL_ACCESS
55 };
56
57 typedef enum
58 {
59     SC_HTYPE_DONT_CARE = 0,
60     SC_HTYPE_MANAGER,
61     SC_HTYPE_SERVICE
62 } SC_HANDLE_TYPE;
63
64 struct sc_handle
65 {
66     SC_HANDLE_TYPE type;
67     DWORD access;
68 };
69
70 struct sc_manager_handle       /* service control manager handle */
71 {
72     struct sc_handle hdr;
73     struct scmdatabase *db;
74 };
75
76 struct sc_service_handle       /* service handle */
77 {
78     struct sc_handle hdr;
79     struct service_entry *service_entry;
80 };
81
82 struct sc_lock
83 {
84     struct scmdatabase *db;
85 };
86
87 static void free_service_strings(struct service_entry *old, struct service_entry *new)
88 {
89     QUERY_SERVICE_CONFIGW *old_cfg = &old->config;
90     QUERY_SERVICE_CONFIGW *new_cfg = &new->config;
91
92     if (old_cfg->lpBinaryPathName != new_cfg->lpBinaryPathName)
93         HeapFree(GetProcessHeap(), 0, old_cfg->lpBinaryPathName);
94
95     if (old_cfg->lpLoadOrderGroup != new_cfg->lpLoadOrderGroup)
96         HeapFree(GetProcessHeap(), 0, old_cfg->lpLoadOrderGroup);
97
98     if (old_cfg->lpServiceStartName != new_cfg->lpServiceStartName)
99         HeapFree(GetProcessHeap(), 0, old_cfg->lpServiceStartName);
100
101     if (old_cfg->lpDisplayName != new_cfg->lpDisplayName)
102         HeapFree(GetProcessHeap(), 0, old_cfg->lpDisplayName);
103
104     if (old->dependOnServices != new->dependOnServices)
105         HeapFree(GetProcessHeap(), 0, old->dependOnServices);
106
107     if (old->dependOnGroups != new->dependOnGroups)
108         HeapFree(GetProcessHeap(), 0, old->dependOnGroups);
109 }
110
111 /* Check if the given handle is of the required type and allows the requested access. */
112 static DWORD validate_context_handle(SC_RPC_HANDLE handle, DWORD type, DWORD needed_access, struct sc_handle **out_hdr)
113 {
114     struct sc_handle *hdr = handle;
115
116     if (type != SC_HTYPE_DONT_CARE && hdr->type != type)
117     {
118         WINE_ERR("Handle is of an invalid type (%d, %d)\n", hdr->type, type);
119         return ERROR_INVALID_HANDLE;
120     }
121
122     if ((needed_access & hdr->access) != needed_access)
123     {
124         WINE_ERR("Access denied - handle created with access %x, needed %x\n", hdr->access, needed_access);
125         return ERROR_ACCESS_DENIED;
126     }
127
128     *out_hdr = hdr;
129     return ERROR_SUCCESS;
130 }
131
132 static DWORD validate_scm_handle(SC_RPC_HANDLE handle, DWORD needed_access, struct sc_manager_handle **manager)
133 {
134     struct sc_handle *hdr;
135     DWORD err = validate_context_handle(handle, SC_HTYPE_MANAGER, needed_access, &hdr);
136     if (err == ERROR_SUCCESS)
137         *manager = (struct sc_manager_handle *)hdr;
138     return err;
139 }
140
141 static DWORD validate_service_handle(SC_RPC_HANDLE handle, DWORD needed_access, struct sc_service_handle **service)
142 {
143     struct sc_handle *hdr;
144     DWORD err = validate_context_handle(handle, SC_HTYPE_SERVICE, needed_access, &hdr);
145     if (err == ERROR_SUCCESS)
146         *service = (struct sc_service_handle *)hdr;
147     return err;
148 }
149
150 DWORD __cdecl svcctl_OpenSCManagerW(
151     MACHINE_HANDLEW MachineName, /* Note: this parameter is ignored */
152     LPCWSTR DatabaseName,
153     DWORD dwAccessMask,
154     SC_RPC_HANDLE *handle)
155 {
156     struct sc_manager_handle *manager;
157
158     WINE_TRACE("(%s, %s, %x)\n", wine_dbgstr_w(MachineName), wine_dbgstr_w(DatabaseName), dwAccessMask);
159
160     if (DatabaseName != NULL && DatabaseName[0])
161     {
162         if (strcmpW(DatabaseName, SERVICES_FAILED_DATABASEW) == 0)
163             return ERROR_DATABASE_DOES_NOT_EXIST;
164         if (strcmpW(DatabaseName, SERVICES_ACTIVE_DATABASEW) != 0)
165             return ERROR_INVALID_NAME;
166     }
167
168     if (!(manager = HeapAlloc(GetProcessHeap(), 0, sizeof(*manager))))
169         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
170
171     manager->hdr.type = SC_HTYPE_MANAGER;
172
173     if (dwAccessMask & MAXIMUM_ALLOWED)
174         dwAccessMask |= SC_MANAGER_ALL_ACCESS;
175     manager->hdr.access = dwAccessMask;
176     RtlMapGenericMask(&manager->hdr.access, &g_scm_generic);
177     manager->db = active_database;
178     *handle = &manager->hdr;
179
180     return ERROR_SUCCESS;
181 }
182
183 static void SC_RPC_HANDLE_destroy(SC_RPC_HANDLE handle)
184 {
185     struct sc_handle *hdr = handle;
186     switch (hdr->type)
187     {
188         case SC_HTYPE_MANAGER:
189         {
190             struct sc_manager_handle *manager = (struct sc_manager_handle *)hdr;
191             HeapFree(GetProcessHeap(), 0, manager);
192             break;
193         }
194         case SC_HTYPE_SERVICE:
195         {
196             struct sc_service_handle *service = (struct sc_service_handle *)hdr;
197             release_service(service->service_entry);
198             HeapFree(GetProcessHeap(), 0, service);
199             break;
200         }
201         default:
202             WINE_ERR("invalid handle type %d\n", hdr->type);
203             RpcRaiseException(ERROR_INVALID_HANDLE);
204     }
205 }
206
207 DWORD __cdecl svcctl_GetServiceDisplayNameW(
208     SC_RPC_HANDLE hSCManager,
209     LPCWSTR lpServiceName,
210     WCHAR *lpBuffer,
211     DWORD *cchBufSize)
212 {
213     struct sc_manager_handle *manager;
214     struct service_entry *entry;
215     DWORD err;
216
217     WINE_TRACE("(%s, %d)\n", wine_dbgstr_w(lpServiceName), *cchBufSize);
218
219     if ((err = validate_scm_handle(hSCManager, 0, &manager)) != ERROR_SUCCESS)
220         return err;
221
222     scmdatabase_lock_shared(manager->db);
223
224     entry = scmdatabase_find_service(manager->db, lpServiceName);
225     if (entry != NULL)
226     {
227         LPCWSTR name;
228         int len;
229         service_lock_shared(entry);
230         name = get_display_name(entry);
231         len = strlenW(name);
232         if (len <= *cchBufSize)
233         {
234             err = ERROR_SUCCESS;
235             memcpy(lpBuffer, name, (len + 1)*sizeof(*name));
236         }
237         else
238             err = ERROR_INSUFFICIENT_BUFFER;
239         *cchBufSize = len;
240         service_unlock(entry);
241     }
242     else
243         err = ERROR_SERVICE_DOES_NOT_EXIST;
244
245     scmdatabase_unlock(manager->db);
246
247     if (err != ERROR_SUCCESS)
248         lpBuffer[0] = 0;
249
250     return err;
251 }
252
253 DWORD __cdecl svcctl_GetServiceKeyNameW(
254     SC_RPC_HANDLE hSCManager,
255     LPCWSTR lpServiceDisplayName,
256     WCHAR *lpBuffer,
257     DWORD *cchBufSize)
258 {
259     struct service_entry *entry;
260     struct sc_manager_handle *manager;
261     DWORD err;
262
263     WINE_TRACE("(%s, %d)\n", wine_dbgstr_w(lpServiceDisplayName), *cchBufSize);
264
265     if ((err = validate_scm_handle(hSCManager, 0, &manager)) != ERROR_SUCCESS)
266         return err;
267
268     scmdatabase_lock_shared(manager->db);
269
270     entry = scmdatabase_find_service_by_displayname(manager->db, lpServiceDisplayName);
271     if (entry != NULL)
272     {
273         int len;
274         service_lock_shared(entry);
275         len = strlenW(entry->name);
276         if (len <= *cchBufSize)
277         {
278             err = ERROR_SUCCESS;
279             memcpy(lpBuffer, entry->name, (len + 1)*sizeof(*entry->name));
280         }
281         else
282             err = ERROR_INSUFFICIENT_BUFFER;
283         *cchBufSize = len;
284         service_unlock(entry);
285     }
286     else
287         err = ERROR_SERVICE_DOES_NOT_EXIST;
288
289     scmdatabase_unlock(manager->db);
290
291     if (err != ERROR_SUCCESS)
292         lpBuffer[0] = 0;
293
294     return err;
295 }
296
297 static DWORD create_handle_for_service(struct service_entry *entry, DWORD dwDesiredAccess, SC_RPC_HANDLE *phService)
298 {
299     struct sc_service_handle *service;
300
301     if (!(service = HeapAlloc(GetProcessHeap(), 0, sizeof(*service))))
302     {
303         release_service(entry);
304         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
305     }
306
307     service->hdr.type = SC_HTYPE_SERVICE;
308     service->hdr.access = dwDesiredAccess;
309     RtlMapGenericMask(&service->hdr.access, &g_svc_generic);
310     service->service_entry = entry;
311     if (dwDesiredAccess & MAXIMUM_ALLOWED)
312         dwDesiredAccess |= SERVICE_ALL_ACCESS;
313
314     *phService = &service->hdr;
315     return ERROR_SUCCESS;
316 }
317
318 DWORD __cdecl svcctl_OpenServiceW(
319     SC_RPC_HANDLE hSCManager,
320     LPCWSTR lpServiceName,
321     DWORD dwDesiredAccess,
322     SC_RPC_HANDLE *phService)
323 {
324     struct sc_manager_handle *manager;
325     struct service_entry *entry;
326     DWORD err;
327
328     WINE_TRACE("(%s, 0x%x)\n", wine_dbgstr_w(lpServiceName), dwDesiredAccess);
329
330     if ((err = validate_scm_handle(hSCManager, 0, &manager)) != ERROR_SUCCESS)
331         return err;
332     if (!validate_service_name(lpServiceName))
333         return ERROR_INVALID_NAME;
334
335     scmdatabase_lock_shared(manager->db);
336     entry = scmdatabase_find_service(manager->db, lpServiceName);
337     if (entry != NULL)
338         InterlockedIncrement(&entry->ref_count);
339     scmdatabase_unlock(manager->db);
340
341     if (entry == NULL)
342         return ERROR_SERVICE_DOES_NOT_EXIST;
343
344     return create_handle_for_service(entry, dwDesiredAccess, phService);
345 }
346
347 static DWORD parse_dependencies(const WCHAR *dependencies, struct service_entry *entry)
348 {
349     WCHAR *services = NULL, *groups, *s;
350     DWORD len, len_services = 0, len_groups = 0;
351     const WCHAR *ptr = dependencies;
352
353     if (!dependencies || !dependencies[0])
354     {
355         entry->dependOnServices = NULL;
356         entry->dependOnGroups = NULL;
357         return ERROR_SUCCESS;
358     }
359
360     while (*ptr)
361     {
362         len = strlenW(ptr) + 1;
363         if (ptr[0] == '+' && ptr[1])
364             len_groups += len - 1;
365         else
366             len_services += len;
367         ptr += len;
368     }
369     if (!len_services) entry->dependOnServices = NULL;
370     else
371     {
372         services = HeapAlloc(GetProcessHeap(), 0, (len_services + 1) * sizeof(WCHAR));
373         if (!services)
374             return ERROR_OUTOFMEMORY;
375
376         s = services;
377         ptr = dependencies;
378         while (*ptr)
379         {
380             len = strlenW(ptr) + 1;
381             if (*ptr != '+')
382             {
383                 strcpyW(s, ptr);
384                 s += len;
385             }
386             ptr += len;
387         }
388         *s = 0;
389         entry->dependOnServices = services;
390     }
391     if (!len_groups) entry->dependOnGroups = NULL;
392     else
393     {
394         groups = HeapAlloc(GetProcessHeap(), 0, (len_groups + 1) * sizeof(WCHAR));
395         if (!groups)
396         {
397             HeapFree(GetProcessHeap(), 0, services);
398             return ERROR_OUTOFMEMORY;
399         }
400         s = groups;
401         ptr = dependencies;
402         while (*ptr)
403         {
404             len = strlenW(ptr) + 1;
405             if (ptr[0] == '+' && ptr[1])
406             {
407                 strcpyW(s, ptr + 1);
408                 s += len - 1;
409             }
410             ptr += len;
411         }
412         *s = 0;
413         entry->dependOnGroups = groups;
414     }
415
416     return ERROR_SUCCESS;
417 }
418
419 DWORD __cdecl svcctl_CreateServiceW(
420     SC_RPC_HANDLE hSCManager,
421     LPCWSTR lpServiceName,
422     LPCWSTR lpDisplayName,
423     DWORD dwDesiredAccess,
424     DWORD dwServiceType,
425     DWORD dwStartType,
426     DWORD dwErrorControl,
427     LPCWSTR lpBinaryPathName,
428     LPCWSTR lpLoadOrderGroup,
429     DWORD *lpdwTagId,
430     const BYTE *lpDependencies,
431     DWORD dwDependenciesSize,
432     LPCWSTR lpServiceStartName,
433     const BYTE *lpPassword,
434     DWORD dwPasswordSize,
435     SC_RPC_HANDLE *phService)
436 {
437     struct sc_manager_handle *manager;
438     struct service_entry *entry;
439     DWORD err;
440
441     WINE_TRACE("(%s, %s, 0x%x, %s)\n", wine_dbgstr_w(lpServiceName), wine_dbgstr_w(lpDisplayName), dwDesiredAccess, wine_dbgstr_w(lpBinaryPathName));
442
443     if ((err = validate_scm_handle(hSCManager, SC_MANAGER_CREATE_SERVICE, &manager)) != ERROR_SUCCESS)
444         return err;
445
446     if (!validate_service_name(lpServiceName))
447         return ERROR_INVALID_NAME;
448     if (!check_multisz((LPCWSTR)lpDependencies, dwDependenciesSize) || !lpServiceName[0] || !lpBinaryPathName[0])
449         return ERROR_INVALID_PARAMETER;
450
451     if (lpPassword)
452         WINE_FIXME("Don't know how to add a password\n");   /* I always get ERROR_GEN_FAILURE */
453
454     err = service_create(lpServiceName, &entry);
455     if (err != ERROR_SUCCESS)
456         return err;
457
458     err = parse_dependencies((LPCWSTR)lpDependencies, entry);
459     if (err != ERROR_SUCCESS)
460         return err;
461
462     entry->ref_count = 1;
463     entry->config.dwServiceType = entry->status.dwServiceType = dwServiceType;
464     entry->config.dwStartType = dwStartType;
465     entry->config.dwErrorControl = dwErrorControl;
466     entry->config.lpBinaryPathName = strdupW(lpBinaryPathName);
467     entry->config.lpLoadOrderGroup = strdupW(lpLoadOrderGroup);
468     entry->config.lpServiceStartName = strdupW(lpServiceStartName);
469     entry->config.lpDisplayName = strdupW(lpDisplayName);
470
471     if (lpdwTagId)      /* TODO: In most situations a non-NULL TagId will generate an ERROR_INVALID_PARAMETER. */
472         entry->config.dwTagId = *lpdwTagId;
473     else
474         entry->config.dwTagId = 0;
475
476     /* other fields NULL*/
477
478     if (!validate_service_config(entry))
479     {
480         WINE_ERR("Invalid data while trying to create service\n");
481         free_service_entry(entry);
482         return ERROR_INVALID_PARAMETER;
483     }
484
485     scmdatabase_lock_exclusive(manager->db);
486
487     if (scmdatabase_find_service(manager->db, lpServiceName))
488     {
489         scmdatabase_unlock(manager->db);
490         free_service_entry(entry);
491         return ERROR_SERVICE_EXISTS;
492     }
493
494     if (scmdatabase_find_service_by_displayname(manager->db, get_display_name(entry)))
495     {
496         scmdatabase_unlock(manager->db);
497         free_service_entry(entry);
498         return ERROR_DUPLICATE_SERVICE_NAME;
499     }
500
501     err = scmdatabase_add_service(manager->db, entry);
502     if (err != ERROR_SUCCESS)
503     {
504         scmdatabase_unlock(manager->db);
505         free_service_entry(entry);
506         return err;
507     }
508     scmdatabase_unlock(manager->db);
509
510     return create_handle_for_service(entry, dwDesiredAccess, phService);
511 }
512
513 DWORD __cdecl svcctl_DeleteService(
514     SC_RPC_HANDLE hService)
515 {
516     struct sc_service_handle *service;
517     DWORD err;
518
519     if ((err = validate_service_handle(hService, DELETE, &service)) != ERROR_SUCCESS)
520         return err;
521
522     scmdatabase_lock_exclusive(service->service_entry->db);
523     service_lock_exclusive(service->service_entry);
524
525     if (!is_marked_for_delete(service->service_entry))
526         err = scmdatabase_remove_service(service->service_entry->db, service->service_entry);
527     else
528         err = ERROR_SERVICE_MARKED_FOR_DELETE;
529
530     service_unlock(service->service_entry);
531     scmdatabase_unlock(service->service_entry->db);
532
533     return err;
534 }
535
536 DWORD __cdecl svcctl_QueryServiceConfigW(
537         SC_RPC_HANDLE hService,
538         QUERY_SERVICE_CONFIGW *config)
539 {
540     struct sc_service_handle *service;
541     DWORD err;
542
543     WINE_TRACE("(%p)\n", config);
544
545     if ((err = validate_service_handle(hService, SERVICE_QUERY_CONFIG, &service)) != 0)
546         return err;
547
548     service_lock_shared(service->service_entry);
549     config->dwServiceType = service->service_entry->config.dwServiceType;
550     config->dwStartType = service->service_entry->config.dwStartType;
551     config->dwErrorControl = service->service_entry->config.dwErrorControl;
552     config->lpBinaryPathName = strdupW(service->service_entry->config.lpBinaryPathName);
553     config->lpLoadOrderGroup = strdupW(service->service_entry->config.lpLoadOrderGroup);
554     config->dwTagId = service->service_entry->config.dwTagId;
555     config->lpDependencies = NULL; /* TODO */
556     config->lpServiceStartName = strdupW(service->service_entry->config.lpServiceStartName);
557     config->lpDisplayName = strdupW(service->service_entry->config.lpDisplayName);
558     service_unlock(service->service_entry);
559
560     return ERROR_SUCCESS;
561 }
562
563 DWORD __cdecl svcctl_ChangeServiceConfigW(
564         SC_RPC_HANDLE hService,
565         DWORD dwServiceType,
566         DWORD dwStartType,
567         DWORD dwErrorControl,
568         LPCWSTR lpBinaryPathName,
569         LPCWSTR lpLoadOrderGroup,
570         DWORD *lpdwTagId,
571         const BYTE *lpDependencies,
572         DWORD dwDependenciesSize,
573         LPCWSTR lpServiceStartName,
574         const BYTE *lpPassword,
575         DWORD dwPasswordSize,
576         LPCWSTR lpDisplayName)
577 {
578     struct service_entry new_entry, *entry;
579     struct sc_service_handle *service;
580     DWORD err;
581
582     WINE_TRACE("\n");
583
584     if ((err = validate_service_handle(hService, SERVICE_CHANGE_CONFIG, &service)) != 0)
585         return err;
586
587     if (!check_multisz((LPCWSTR)lpDependencies, dwDependenciesSize))
588         return ERROR_INVALID_PARAMETER;
589
590     /* first check if the new configuration is correct */
591     service_lock_exclusive(service->service_entry);
592
593     if (is_marked_for_delete(service->service_entry))
594     {
595         service_unlock(service->service_entry);
596         return ERROR_SERVICE_MARKED_FOR_DELETE;
597     }
598
599     if (lpDisplayName != NULL &&
600         (entry = scmdatabase_find_service_by_displayname(service->service_entry->db, lpDisplayName)) &&
601         (entry != service->service_entry))
602     {
603         service_unlock(service->service_entry);
604         return ERROR_DUPLICATE_SERVICE_NAME;
605     }
606
607     new_entry = *service->service_entry;
608
609     if (dwServiceType != SERVICE_NO_CHANGE)
610         new_entry.config.dwServiceType = dwServiceType;
611
612     if (dwStartType != SERVICE_NO_CHANGE)
613         new_entry.config.dwStartType = dwStartType;
614
615     if (dwErrorControl != SERVICE_NO_CHANGE)
616         new_entry.config.dwErrorControl = dwErrorControl;
617
618     if (lpBinaryPathName != NULL)
619         new_entry.config.lpBinaryPathName = (LPWSTR)lpBinaryPathName;
620
621     if (lpLoadOrderGroup != NULL)
622         new_entry.config.lpLoadOrderGroup = (LPWSTR)lpLoadOrderGroup;
623
624     if (lpdwTagId != NULL)
625         WINE_FIXME("Changing tag id not supported\n");
626
627     if (lpServiceStartName != NULL)
628         new_entry.config.lpServiceStartName = (LPWSTR)lpServiceStartName;
629
630     if (lpPassword != NULL)
631         WINE_FIXME("Setting password not supported\n");
632
633     if (lpDisplayName != NULL)
634         new_entry.config.lpDisplayName = (LPWSTR)lpDisplayName;
635
636     err = parse_dependencies((LPCWSTR)lpDependencies, &new_entry);
637     if (err != ERROR_SUCCESS)
638     {
639         service_unlock(service->service_entry);
640         return err;
641     }
642
643     if (!validate_service_config(&new_entry))
644     {
645         WINE_ERR("The configuration after the change wouldn't be valid\n");
646         service_unlock(service->service_entry);
647         return ERROR_INVALID_PARAMETER;
648     }
649
650     /* configuration OK. The strings needs to be duplicated */
651     if (lpBinaryPathName != NULL)
652         new_entry.config.lpBinaryPathName = strdupW(lpBinaryPathName);
653
654     if (lpLoadOrderGroup != NULL)
655         new_entry.config.lpLoadOrderGroup = strdupW(lpLoadOrderGroup);
656
657     if (lpServiceStartName != NULL)
658         new_entry.config.lpServiceStartName = strdupW(lpServiceStartName);
659
660     if (lpDisplayName != NULL)
661         new_entry.config.lpDisplayName = strdupW(lpDisplayName);
662
663     /* try to save to Registry, commit or rollback depending on success */
664     err = save_service_config(&new_entry);
665     if (ERROR_SUCCESS == err)
666     {
667         free_service_strings(service->service_entry, &new_entry);
668         *service->service_entry = new_entry;
669     }
670     else free_service_strings(&new_entry, service->service_entry);
671     service_unlock(service->service_entry);
672
673     return err;
674 }
675
676 DWORD __cdecl svcctl_SetServiceStatus(
677     SC_RPC_HANDLE hServiceStatus,
678     LPSERVICE_STATUS lpServiceStatus)
679 {
680     struct sc_service_handle *service;
681     DWORD err;
682
683     WINE_TRACE("(%p, %p)\n", hServiceStatus, lpServiceStatus);
684
685     if ((err = validate_service_handle(hServiceStatus, SERVICE_SET_STATUS, &service)) != 0)
686         return err;
687
688     service_lock_exclusive(service->service_entry);
689     /* FIXME: be a bit more discriminant about what parts of the status we set
690      * and check that fields are valid */
691     service->service_entry->status.dwServiceType = lpServiceStatus->dwServiceType;
692     service->service_entry->status.dwCurrentState = lpServiceStatus->dwCurrentState;
693     service->service_entry->status.dwControlsAccepted = lpServiceStatus->dwControlsAccepted;
694     service->service_entry->status.dwWin32ExitCode = lpServiceStatus->dwWin32ExitCode;
695     service->service_entry->status.dwServiceSpecificExitCode = lpServiceStatus->dwServiceSpecificExitCode;
696     service->service_entry->status.dwCheckPoint = lpServiceStatus->dwCheckPoint;
697     service->service_entry->status.dwWaitHint = lpServiceStatus->dwWaitHint;
698     service_unlock(service->service_entry);
699
700     if (service->service_entry->status_changed_event)
701         SetEvent(service->service_entry->status_changed_event);
702
703     return ERROR_SUCCESS;
704 }
705
706 DWORD __cdecl svcctl_ChangeServiceConfig2W( SC_RPC_HANDLE hService, DWORD level, SERVICE_CONFIG2W *config )
707 {
708     struct sc_service_handle *service;
709     DWORD err;
710
711     if ((err = validate_service_handle(hService, SERVICE_CHANGE_CONFIG, &service)) != 0)
712         return err;
713
714     switch (level)
715     {
716     case SERVICE_CONFIG_DESCRIPTION:
717         {
718             WCHAR *descr = NULL;
719
720             if (config->descr.lpDescription[0])
721             {
722                 if (!(descr = strdupW( config->descr.lpDescription )))
723                     return ERROR_NOT_ENOUGH_MEMORY;
724             }
725
726             WINE_TRACE( "changing service %p descr to %s\n", service, wine_dbgstr_w(descr) );
727             service_lock_exclusive( service->service_entry );
728             HeapFree( GetProcessHeap(), 0, service->service_entry->description );
729             service->service_entry->description = descr;
730             save_service_config( service->service_entry );
731             service_unlock( service->service_entry );
732         }
733         break;
734     case SERVICE_CONFIG_FAILURE_ACTIONS:
735         WINE_FIXME( "SERVICE_CONFIG_FAILURE_ACTIONS not implemented: period %u msg %s cmd %s\n",
736                     config->actions.dwResetPeriod,
737                     wine_dbgstr_w(config->actions.lpRebootMsg),
738                     wine_dbgstr_w(config->actions.lpCommand) );
739         break;
740     case SERVICE_CONFIG_PRESHUTDOWN_INFO:
741         WINE_TRACE( "changing service %p preshutdown timeout to %d\n",
742                 service, config->preshutdown.dwPreshutdownTimeout );
743         service_lock_exclusive( service->service_entry );
744         service->service_entry->preshutdown_timeout = config->preshutdown.dwPreshutdownTimeout;
745         save_service_config( service->service_entry );
746         service_unlock( service->service_entry );
747         break;
748     default:
749         WINE_FIXME("level %u not implemented\n", level);
750         err = ERROR_INVALID_LEVEL;
751         break;
752     }
753     return err;
754 }
755
756 DWORD __cdecl svcctl_QueryServiceConfig2W( SC_RPC_HANDLE hService, DWORD level,
757                                            BYTE *buffer, DWORD size, LPDWORD needed )
758 {
759     struct sc_service_handle *service;
760     DWORD err;
761
762     memset(buffer, 0, size);
763
764     if ((err = validate_service_handle(hService, SERVICE_QUERY_STATUS, &service)) != 0)
765         return err;
766
767     switch (level)
768     {
769     case SERVICE_CONFIG_DESCRIPTION:
770         {
771             SERVICE_DESCRIPTIONW *descr = (SERVICE_DESCRIPTIONW *)buffer;
772
773             service_lock_shared(service->service_entry);
774             *needed = sizeof(*descr);
775             if (service->service_entry->description)
776                 *needed += (strlenW(service->service_entry->description) + 1) * sizeof(WCHAR);
777             if (size >= *needed)
778             {
779                 if (service->service_entry->description)
780                 {
781                     /* store a buffer offset instead of a pointer */
782                     descr->lpDescription = (WCHAR *)((BYTE *)(descr + 1) - buffer);
783                     strcpyW( (WCHAR *)(descr + 1), service->service_entry->description );
784                 }
785                 else descr->lpDescription = NULL;
786             }
787             else err = ERROR_INSUFFICIENT_BUFFER;
788             service_unlock(service->service_entry);
789         }
790         break;
791
792     case SERVICE_CONFIG_PRESHUTDOWN_INFO:
793         service_lock_shared(service->service_entry);
794
795         *needed = sizeof(SERVICE_PRESHUTDOWN_INFO);
796         if (size >= *needed)
797             ((LPSERVICE_PRESHUTDOWN_INFO)buffer)->dwPreshutdownTimeout =
798                 service->service_entry->preshutdown_timeout;
799         else err = ERROR_INSUFFICIENT_BUFFER;
800
801         service_unlock(service->service_entry);
802         break;
803
804     default:
805         WINE_FIXME("level %u not implemented\n", level);
806         err = ERROR_INVALID_LEVEL;
807         break;
808     }
809     return err;
810 }
811
812 DWORD __cdecl svcctl_QueryServiceStatusEx(
813     SC_RPC_HANDLE hService,
814     SC_STATUS_TYPE InfoLevel,
815     BYTE *lpBuffer,
816     DWORD cbBufSize,
817     LPDWORD pcbBytesNeeded)
818 {
819     struct sc_service_handle *service;
820     DWORD err;
821     LPSERVICE_STATUS_PROCESS pSvcStatusData;
822
823     memset(lpBuffer, 0, cbBufSize);
824
825     if ((err = validate_service_handle(hService, SERVICE_QUERY_STATUS, &service)) != 0)
826         return err;
827
828     if (InfoLevel != SC_STATUS_PROCESS_INFO)
829         return ERROR_INVALID_LEVEL;
830
831     pSvcStatusData = (LPSERVICE_STATUS_PROCESS) lpBuffer;
832     if (pSvcStatusData == NULL)
833         return ERROR_INVALID_PARAMETER;
834
835     if (cbBufSize < sizeof(SERVICE_STATUS_PROCESS))
836     {
837         if( pcbBytesNeeded != NULL)
838             *pcbBytesNeeded = sizeof(SERVICE_STATUS_PROCESS);
839
840         return ERROR_INSUFFICIENT_BUFFER;
841     }
842
843     service_lock_shared(service->service_entry);
844
845     pSvcStatusData->dwServiceType = service->service_entry->status.dwServiceType;
846     pSvcStatusData->dwCurrentState = service->service_entry->status.dwCurrentState;
847     pSvcStatusData->dwControlsAccepted = service->service_entry->status.dwControlsAccepted;
848     pSvcStatusData->dwWin32ExitCode = service->service_entry->status.dwWin32ExitCode;
849     pSvcStatusData->dwServiceSpecificExitCode = service->service_entry->status.dwServiceSpecificExitCode;
850     pSvcStatusData->dwCheckPoint = service->service_entry->status.dwCheckPoint;
851     pSvcStatusData->dwWaitHint = service->service_entry->status.dwWaitHint;
852     pSvcStatusData->dwProcessId = service->service_entry->status.dwProcessId;
853     pSvcStatusData->dwServiceFlags = service->service_entry->status.dwServiceFlags;
854
855     service_unlock(service->service_entry);
856
857     return ERROR_SUCCESS;
858 }
859
860 /******************************************************************************
861  * service_accepts_control
862  */
863 static BOOL service_accepts_control(const struct service_entry *service, DWORD dwControl)
864 {
865     DWORD a = service->status.dwControlsAccepted;
866
867     switch (dwControl)
868     {
869     case SERVICE_CONTROL_INTERROGATE:
870         return TRUE;
871     case SERVICE_CONTROL_STOP:
872         if (a&SERVICE_ACCEPT_STOP)
873             return TRUE;
874         break;
875     case SERVICE_CONTROL_SHUTDOWN:
876         if (a&SERVICE_ACCEPT_SHUTDOWN)
877             return TRUE;
878         break;
879     case SERVICE_CONTROL_PAUSE:
880     case SERVICE_CONTROL_CONTINUE:
881         if (a&SERVICE_ACCEPT_PAUSE_CONTINUE)
882             return TRUE;
883         break;
884     case SERVICE_CONTROL_PARAMCHANGE:
885         if (a&SERVICE_ACCEPT_PARAMCHANGE)
886             return TRUE;
887         break;
888     case SERVICE_CONTROL_NETBINDADD:
889     case SERVICE_CONTROL_NETBINDREMOVE:
890     case SERVICE_CONTROL_NETBINDENABLE:
891     case SERVICE_CONTROL_NETBINDDISABLE:
892         if (a&SERVICE_ACCEPT_NETBINDCHANGE)
893             return TRUE;
894     case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
895         if (a&SERVICE_ACCEPT_HARDWAREPROFILECHANGE)
896             return TRUE;
897         break;
898     case SERVICE_CONTROL_POWEREVENT:
899         if (a&SERVICE_ACCEPT_POWEREVENT)
900             return TRUE;
901         break;
902     case SERVICE_CONTROL_SESSIONCHANGE:
903         if (a&SERVICE_ACCEPT_SESSIONCHANGE)
904             return TRUE;
905         break;
906     }
907     return FALSE;
908 }
909
910 /******************************************************************************
911  * service_send_command
912  */
913 BOOL service_send_command( struct service_entry *service, HANDLE pipe,
914                            const void *data, DWORD size, DWORD *result )
915 {
916     OVERLAPPED overlapped;
917     DWORD count;
918     BOOL r;
919
920     overlapped.hEvent = service->overlapped_event;
921     r = WriteFile(pipe, data, size, &count, &overlapped);
922     if (!r && GetLastError() == ERROR_IO_PENDING)
923     {
924         WaitForSingleObject( service->overlapped_event, service_pipe_timeout );
925         r = GetOverlappedResult( pipe, &overlapped, &count, FALSE );
926     }
927     if (!r || count != size)
928     {
929         WINE_ERR("service protocol error - failed to write pipe!\n");
930         return FALSE;
931     }
932     r = ReadFile(pipe, result, sizeof *result, &count, &overlapped);
933     if (!r && GetLastError() == ERROR_IO_PENDING)
934     {
935         WaitForSingleObject( service->overlapped_event, service_pipe_timeout );
936         r = GetOverlappedResult( pipe, &overlapped, &count, FALSE );
937     }
938     if (!r || count != sizeof *result)
939     {
940         WINE_ERR("service protocol error - failed to read pipe "
941             "r = %d  count = %d!\n", r, count);
942         return FALSE;
943     }
944     return r;
945 }
946
947 /******************************************************************************
948  * service_send_control
949  */
950 static BOOL service_send_control(struct service_entry *service, HANDLE pipe, DWORD dwControl, DWORD *result)
951 {
952     service_start_info *ssi;
953     DWORD len;
954     BOOL r;
955
956     /* calculate how much space we need to send the startup info */
957     len = strlenW(service->name) + 1;
958
959     ssi = HeapAlloc(GetProcessHeap(),0,FIELD_OFFSET(service_start_info, data[len]));
960     ssi->cmd = WINESERV_SENDCONTROL;
961     ssi->control = dwControl;
962     ssi->total_size = FIELD_OFFSET(service_start_info, data[len]);
963     ssi->name_size = strlenW(service->name) + 1;
964     strcpyW( ssi->data, service->name );
965
966     r = service_send_command( service, pipe, ssi, ssi->total_size, result );
967     HeapFree( GetProcessHeap(), 0, ssi );
968     return r;
969 }
970
971 DWORD __cdecl svcctl_StartServiceW(
972     SC_RPC_HANDLE hService,
973     DWORD dwNumServiceArgs,
974     LPCWSTR *lpServiceArgVectors)
975 {
976     struct sc_service_handle *service;
977     DWORD err;
978
979     WINE_TRACE("(%p, %d, %p)\n", hService, dwNumServiceArgs, lpServiceArgVectors);
980
981     if ((err = validate_service_handle(hService, SERVICE_START, &service)) != 0)
982         return err;
983
984     if (service->service_entry->config.dwStartType == SERVICE_DISABLED)
985         return ERROR_SERVICE_DISABLED;
986
987     err = service_start(service->service_entry, dwNumServiceArgs, lpServiceArgVectors);
988
989     return err;
990 }
991
992 DWORD __cdecl svcctl_ControlService(
993     SC_RPC_HANDLE hService,
994     DWORD dwControl,
995     SERVICE_STATUS *lpServiceStatus)
996 {
997     DWORD access_required;
998     struct sc_service_handle *service;
999     DWORD err;
1000     BOOL ret;
1001     HANDLE control_mutex;
1002     HANDLE control_pipe;
1003
1004     WINE_TRACE("(%p, %d, %p)\n", hService, dwControl, lpServiceStatus);
1005
1006     switch (dwControl)
1007     {
1008     case SERVICE_CONTROL_CONTINUE:
1009     case SERVICE_CONTROL_NETBINDADD:
1010     case SERVICE_CONTROL_NETBINDDISABLE:
1011     case SERVICE_CONTROL_NETBINDENABLE:
1012     case SERVICE_CONTROL_NETBINDREMOVE:
1013     case SERVICE_CONTROL_PARAMCHANGE:
1014     case SERVICE_CONTROL_PAUSE:
1015         access_required = SERVICE_PAUSE_CONTINUE;
1016         break;
1017     case SERVICE_CONTROL_INTERROGATE:
1018         access_required = SERVICE_INTERROGATE;
1019         break;
1020     case SERVICE_CONTROL_STOP:
1021         access_required = SERVICE_STOP;
1022         break;
1023     default:
1024         if (dwControl >= 128 && dwControl <= 255)
1025             access_required = SERVICE_USER_DEFINED_CONTROL;
1026         else
1027             return ERROR_INVALID_PARAMETER;
1028     }
1029
1030     if ((err = validate_service_handle(hService, access_required, &service)) != 0)
1031         return err;
1032
1033     service_lock_exclusive(service->service_entry);
1034
1035     if (lpServiceStatus)
1036     {
1037         lpServiceStatus->dwServiceType = service->service_entry->status.dwServiceType;
1038         lpServiceStatus->dwCurrentState = service->service_entry->status.dwCurrentState;
1039         lpServiceStatus->dwControlsAccepted = service->service_entry->status.dwControlsAccepted;
1040         lpServiceStatus->dwWin32ExitCode = service->service_entry->status.dwWin32ExitCode;
1041         lpServiceStatus->dwServiceSpecificExitCode = service->service_entry->status.dwServiceSpecificExitCode;
1042         lpServiceStatus->dwCheckPoint = service->service_entry->status.dwCheckPoint;
1043         lpServiceStatus->dwWaitHint = service->service_entry->status.dwWaitHint;
1044     }
1045
1046     switch (service->service_entry->status.dwCurrentState)
1047     {
1048     case SERVICE_STOPPED:
1049         service_unlock(service->service_entry);
1050         return ERROR_SERVICE_NOT_ACTIVE;
1051     case SERVICE_START_PENDING:
1052         if (dwControl==SERVICE_CONTROL_STOP)
1053             break;
1054         /* fall thru */
1055     case SERVICE_STOP_PENDING:
1056         service_unlock(service->service_entry);
1057         return ERROR_SERVICE_CANNOT_ACCEPT_CTRL;
1058     }
1059
1060     if (!service_accepts_control(service->service_entry, dwControl))
1061     {
1062         service_unlock(service->service_entry);
1063         return ERROR_INVALID_SERVICE_CONTROL;
1064     }
1065
1066     /* prevent races by caching these variables and clearing them on
1067      * stop here instead of outside the services lock */
1068     control_mutex = service->service_entry->control_mutex;
1069     control_pipe = service->service_entry->control_pipe;
1070     if (dwControl == SERVICE_CONTROL_STOP)
1071     {
1072         service->service_entry->control_mutex = NULL;
1073         service->service_entry->control_pipe = INVALID_HANDLE_VALUE;
1074     }
1075
1076     service_unlock(service->service_entry);
1077
1078     ret = WaitForSingleObject(control_mutex, 30000);
1079     if (ret == WAIT_OBJECT_0)
1080     {
1081         DWORD result = ERROR_SUCCESS;
1082
1083         ret = service_send_control(service->service_entry, control_pipe, dwControl, &result);
1084
1085         if (dwControl == SERVICE_CONTROL_STOP)
1086         {
1087             CloseHandle(control_mutex);
1088             CloseHandle(control_pipe);
1089         }
1090         else
1091             ReleaseMutex(control_mutex);
1092
1093         return result;
1094     }
1095     else
1096     {
1097         if (dwControl == SERVICE_CONTROL_STOP)
1098         {
1099             CloseHandle(control_mutex);
1100             CloseHandle(control_pipe);
1101         }
1102         return ERROR_SERVICE_REQUEST_TIMEOUT;
1103     }
1104 }
1105
1106 DWORD __cdecl svcctl_CloseServiceHandle(
1107     SC_RPC_HANDLE *handle)
1108 {
1109     WINE_TRACE("(&%p)\n", *handle);
1110
1111     SC_RPC_HANDLE_destroy(*handle);
1112     *handle = NULL;
1113
1114     return ERROR_SUCCESS;
1115 }
1116
1117 static void SC_RPC_LOCK_destroy(SC_RPC_LOCK hLock)
1118 {
1119     struct sc_lock *lock = hLock;
1120     scmdatabase_unlock_startup(lock->db);
1121     HeapFree(GetProcessHeap(), 0, lock);
1122 }
1123
1124 void __RPC_USER SC_RPC_LOCK_rundown(SC_RPC_LOCK hLock)
1125 {
1126     SC_RPC_LOCK_destroy(hLock);
1127 }
1128
1129 DWORD __cdecl svcctl_LockServiceDatabase(
1130     SC_RPC_HANDLE hSCManager,
1131     SC_RPC_LOCK *phLock)
1132 {
1133     struct sc_manager_handle *manager;
1134     struct sc_lock *lock;
1135     DWORD err;
1136
1137     WINE_TRACE("(%p, %p)\n", hSCManager, phLock);
1138
1139     if ((err = validate_scm_handle(hSCManager, SC_MANAGER_LOCK, &manager)) != ERROR_SUCCESS)
1140         return err;
1141
1142     err = scmdatabase_lock_startup(manager->db);
1143     if (err != ERROR_SUCCESS)
1144         return err;
1145
1146     lock = HeapAlloc(GetProcessHeap(), 0, sizeof(struct sc_lock));
1147     if (!lock)
1148     {
1149         scmdatabase_unlock_startup(manager->db);
1150         return ERROR_NOT_ENOUGH_SERVER_MEMORY;
1151     }
1152
1153     lock->db = manager->db;
1154     *phLock = lock;
1155
1156     return ERROR_SUCCESS;
1157 }
1158
1159 DWORD __cdecl svcctl_UnlockServiceDatabase(
1160     SC_RPC_LOCK *phLock)
1161 {
1162     WINE_TRACE("(&%p)\n", *phLock);
1163
1164     SC_RPC_LOCK_destroy(*phLock);
1165     *phLock = NULL;
1166
1167     return ERROR_SUCCESS;
1168 }
1169
1170 static BOOL map_state(DWORD state, DWORD mask)
1171 {
1172     switch (state)
1173     {
1174     case SERVICE_START_PENDING:
1175     case SERVICE_STOP_PENDING:
1176     case SERVICE_RUNNING:
1177     case SERVICE_CONTINUE_PENDING:
1178     case SERVICE_PAUSE_PENDING:
1179     case SERVICE_PAUSED:
1180         if (SERVICE_ACTIVE & mask) return TRUE;
1181         break;
1182     case SERVICE_STOPPED:
1183         if (SERVICE_INACTIVE & mask) return TRUE;
1184         break;
1185     default:
1186         WINE_ERR("unknown state %u\n", state);
1187         break;
1188     }
1189     return FALSE;
1190 }
1191
1192 DWORD __cdecl svcctl_EnumServicesStatusW(
1193     SC_RPC_HANDLE hmngr,
1194     DWORD type,
1195     DWORD state,
1196     BYTE *buffer,
1197     DWORD size,
1198     LPDWORD needed,
1199     LPDWORD returned)
1200 {
1201     DWORD err, sz, total_size, num_services;
1202     DWORD_PTR offset;
1203     struct sc_manager_handle *manager;
1204     struct service_entry *service;
1205     ENUM_SERVICE_STATUSW *s;
1206
1207     WINE_TRACE("(%p, 0x%x, 0x%x, %p, %u, %p, %p)\n", hmngr, type, state, buffer, size, needed, returned);
1208
1209     if (!type || !state)
1210         return ERROR_INVALID_PARAMETER;
1211
1212     if ((err = validate_scm_handle(hmngr, SC_MANAGER_ENUMERATE_SERVICE, &manager)) != ERROR_SUCCESS)
1213         return err;
1214
1215     scmdatabase_lock_exclusive(manager->db);
1216
1217     total_size = num_services = 0;
1218     LIST_FOR_EACH_ENTRY(service, &manager->db->services, struct service_entry, entry)
1219     {
1220         if ((service->status.dwServiceType & type) && map_state(service->status.dwCurrentState, state))
1221         {
1222             total_size += sizeof(ENUM_SERVICE_STATUSW);
1223             total_size += (strlenW(service->name) + 1) * sizeof(WCHAR);
1224             if (service->config.lpDisplayName)
1225             {
1226                 total_size += (strlenW(service->config.lpDisplayName) + 1) * sizeof(WCHAR);
1227             }
1228             num_services++;
1229         }
1230     }
1231     *returned = 0;
1232     *needed = total_size;
1233     if (total_size > size)
1234     {
1235         scmdatabase_unlock(manager->db);
1236         return ERROR_MORE_DATA;
1237     }
1238     s = (ENUM_SERVICE_STATUSW *)buffer;
1239     offset = num_services * sizeof(ENUM_SERVICE_STATUSW);
1240     LIST_FOR_EACH_ENTRY(service, &manager->db->services, struct service_entry, entry)
1241     {
1242         if ((service->status.dwServiceType & type) && map_state(service->status.dwCurrentState, state))
1243         {
1244             sz = (strlenW(service->name) + 1) * sizeof(WCHAR);
1245             memcpy(buffer + offset, service->name, sz);
1246             s->lpServiceName = (WCHAR *)offset; /* store a buffer offset instead of a pointer */
1247             offset += sz;
1248
1249             if (!service->config.lpDisplayName) s->lpDisplayName = NULL;
1250             else
1251             {
1252                 sz = (strlenW(service->config.lpDisplayName) + 1) * sizeof(WCHAR);
1253                 memcpy(buffer + offset, service->config.lpDisplayName, sz);
1254                 s->lpDisplayName = (WCHAR *)offset;
1255                 offset += sz;
1256             }
1257             memcpy(&s->ServiceStatus, &service->status, sizeof(SERVICE_STATUS));
1258             s++;
1259         }
1260     }
1261     *returned = num_services;
1262     *needed = 0;
1263     scmdatabase_unlock(manager->db);
1264     return ERROR_SUCCESS;
1265 }
1266
1267 static struct service_entry *find_service_by_group(struct scmdatabase *db, const WCHAR *group)
1268 {
1269     struct service_entry *service;
1270     LIST_FOR_EACH_ENTRY(service, &db->services, struct service_entry, entry)
1271     {
1272         if (service->config.lpLoadOrderGroup && !strcmpiW(group, service->config.lpLoadOrderGroup))
1273             return service;
1274     }
1275     return NULL;
1276 }
1277
1278 static BOOL match_group(const WCHAR *g1, const WCHAR *g2)
1279 {
1280     if (!g2) return TRUE;
1281     if (!g2[0] && (!g1 || !g1[0])) return TRUE;
1282     if (g1 && !strcmpW(g1, g2)) return TRUE;
1283     return FALSE;
1284 }
1285
1286 DWORD __cdecl svcctl_EnumServicesStatusExW(
1287     SC_RPC_HANDLE hmngr,
1288     DWORD type,
1289     DWORD state,
1290     BYTE *buffer,
1291     DWORD size,
1292     LPDWORD needed,
1293     LPDWORD returned,
1294     LPCWSTR group)
1295 {
1296     DWORD err, sz, total_size, num_services;
1297     DWORD_PTR offset;
1298     struct sc_manager_handle *manager;
1299     struct service_entry *service;
1300     ENUM_SERVICE_STATUS_PROCESSW *s;
1301
1302     WINE_TRACE("(%p, 0x%x, 0x%x, %p, %u, %p, %p, %s)\n", hmngr, type, state, buffer, size,
1303                needed, returned, wine_dbgstr_w(group));
1304
1305     if (!type || !state)
1306         return ERROR_INVALID_PARAMETER;
1307
1308     if ((err = validate_scm_handle(hmngr, SC_MANAGER_ENUMERATE_SERVICE, &manager)) != ERROR_SUCCESS)
1309         return err;
1310
1311     scmdatabase_lock_exclusive(manager->db);
1312
1313     if (group && !find_service_by_group(manager->db, group))
1314     {
1315         scmdatabase_unlock(manager->db);
1316         return ERROR_SERVICE_DOES_NOT_EXIST;
1317     }
1318
1319     total_size = num_services = 0;
1320     LIST_FOR_EACH_ENTRY(service, &manager->db->services, struct service_entry, entry)
1321     {
1322         if ((service->status.dwServiceType & type) && map_state(service->status.dwCurrentState, state)
1323             && match_group(service->config.lpLoadOrderGroup, group))
1324         {
1325             total_size += sizeof(ENUM_SERVICE_STATUS_PROCESSW);
1326             total_size += (strlenW(service->name) + 1) * sizeof(WCHAR);
1327             if (service->config.lpDisplayName)
1328             {
1329                 total_size += (strlenW(service->config.lpDisplayName) + 1) * sizeof(WCHAR);
1330             }
1331             num_services++;
1332         }
1333     }
1334     *returned = 0;
1335     *needed = total_size;
1336     if (total_size > size)
1337     {
1338         scmdatabase_unlock(manager->db);
1339         return ERROR_MORE_DATA;
1340     }
1341     s = (ENUM_SERVICE_STATUS_PROCESSW *)buffer;
1342     offset = num_services * sizeof(ENUM_SERVICE_STATUS_PROCESSW);
1343     LIST_FOR_EACH_ENTRY(service, &manager->db->services, struct service_entry, entry)
1344     {
1345         if ((service->status.dwServiceType & type) && map_state(service->status.dwCurrentState, state)
1346             && match_group(service->config.lpLoadOrderGroup, group))
1347         {
1348             sz = (strlenW(service->name) + 1) * sizeof(WCHAR);
1349             memcpy(buffer + offset, service->name, sz);
1350             s->lpServiceName = (WCHAR *)offset; /* store a buffer offset instead of a pointer */
1351             offset += sz;
1352
1353             if (!service->config.lpDisplayName) s->lpDisplayName = NULL;
1354             else
1355             {
1356                 sz = (strlenW(service->config.lpDisplayName) + 1) * sizeof(WCHAR);
1357                 memcpy(buffer + offset, service->config.lpDisplayName, sz);
1358                 s->lpDisplayName = (WCHAR *)offset;
1359                 offset += sz;
1360             }
1361             s->ServiceStatusProcess = service->status;
1362             s++;
1363         }
1364     }
1365     *returned = num_services;
1366     *needed = 0;
1367     scmdatabase_unlock(manager->db);
1368     return ERROR_SUCCESS;
1369 }
1370
1371 DWORD __cdecl svcctl_QueryServiceObjectSecurity(void)
1372 {
1373     WINE_FIXME("\n");
1374     return ERROR_CALL_NOT_IMPLEMENTED;
1375 }
1376
1377 DWORD __cdecl svcctl_SetServiceObjectSecurity(void)
1378 {
1379     WINE_FIXME("\n");
1380     return ERROR_CALL_NOT_IMPLEMENTED;
1381 }
1382
1383 DWORD __cdecl svcctl_QueryServiceStatus(void)
1384 {
1385     WINE_FIXME("\n");
1386     return ERROR_CALL_NOT_IMPLEMENTED;
1387 }
1388
1389
1390 DWORD __cdecl svcctl_NotifyBootConfigStatus(void)
1391 {
1392     WINE_FIXME("\n");
1393     return ERROR_CALL_NOT_IMPLEMENTED;
1394 }
1395
1396 DWORD __cdecl svcctl_SCSetServiceBitsW(void)
1397 {
1398     WINE_FIXME("\n");
1399     return ERROR_CALL_NOT_IMPLEMENTED;
1400 }
1401
1402
1403 DWORD __cdecl svcctl_EnumDependentServicesW(void)
1404 {
1405     WINE_FIXME("\n");
1406     return ERROR_CALL_NOT_IMPLEMENTED;
1407 }
1408
1409 DWORD __cdecl svcctl_QueryServiceLockStatusW(void)
1410 {
1411     WINE_FIXME("\n");
1412     return ERROR_CALL_NOT_IMPLEMENTED;
1413 }
1414
1415 DWORD __cdecl svcctl_SCSetServiceBitsA(void)
1416 {
1417     WINE_FIXME("\n");
1418     return ERROR_CALL_NOT_IMPLEMENTED;
1419 }
1420
1421 DWORD __cdecl svcctl_ChangeServiceConfigA(void)
1422 {
1423     WINE_FIXME("\n");
1424     return ERROR_CALL_NOT_IMPLEMENTED;
1425 }
1426
1427 DWORD __cdecl svcctl_CreateServiceA(void)
1428 {
1429     WINE_FIXME("\n");
1430     return ERROR_CALL_NOT_IMPLEMENTED;
1431 }
1432
1433 DWORD __cdecl svcctl_EnumDependentServicesA(void)
1434 {
1435     WINE_FIXME("\n");
1436     return ERROR_CALL_NOT_IMPLEMENTED;
1437 }
1438
1439 DWORD __cdecl svcctl_EnumServicesStatusA(void)
1440 {
1441     WINE_FIXME("\n");
1442     return ERROR_CALL_NOT_IMPLEMENTED;
1443 }
1444
1445 DWORD __cdecl svcctl_OpenSCManagerA(void)
1446 {
1447     WINE_FIXME("\n");
1448     return ERROR_CALL_NOT_IMPLEMENTED;
1449 }
1450
1451 DWORD __cdecl svcctl_OpenServiceA(void)
1452 {
1453     WINE_FIXME("\n");
1454     return ERROR_CALL_NOT_IMPLEMENTED;
1455 }
1456
1457 DWORD __cdecl svcctl_QueryServiceConfigA(void)
1458 {
1459     WINE_FIXME("\n");
1460     return ERROR_CALL_NOT_IMPLEMENTED;
1461 }
1462
1463 DWORD __cdecl svcctl_QueryServiceLockStatusA(void)
1464 {
1465     WINE_FIXME("\n");
1466     return ERROR_CALL_NOT_IMPLEMENTED;
1467 }
1468
1469 DWORD __cdecl svcctl_StartServiceA(void)
1470 {
1471     WINE_FIXME("\n");
1472     return ERROR_CALL_NOT_IMPLEMENTED;
1473 }
1474
1475 DWORD __cdecl svcctl_GetServiceDisplayNameA(void)
1476 {
1477     WINE_FIXME("\n");
1478     return ERROR_CALL_NOT_IMPLEMENTED;
1479 }
1480
1481 DWORD __cdecl svcctl_GetServiceKeyNameA(void)
1482 {
1483     WINE_FIXME("\n");
1484     return ERROR_CALL_NOT_IMPLEMENTED;
1485 }
1486
1487 DWORD __cdecl svcctl_GetCurrentGroupStateW(void)
1488 {
1489     WINE_FIXME("\n");
1490     return ERROR_CALL_NOT_IMPLEMENTED;
1491 }
1492
1493 DWORD __cdecl svcctl_EnumServiceGroupW(void)
1494 {
1495     WINE_FIXME("\n");
1496     return ERROR_CALL_NOT_IMPLEMENTED;
1497 }
1498
1499 DWORD __cdecl svcctl_ChangeServiceConfig2A(void)
1500 {
1501     WINE_FIXME("\n");
1502     return ERROR_CALL_NOT_IMPLEMENTED;
1503 }
1504
1505 DWORD __cdecl svcctl_QueryServiceConfig2A(void)
1506 {
1507     WINE_FIXME("\n");
1508     return ERROR_CALL_NOT_IMPLEMENTED;
1509 }
1510
1511
1512 DWORD RPC_Init(void)
1513 {
1514     WCHAR transport[] = SVCCTL_TRANSPORT;
1515     WCHAR endpoint[] = SVCCTL_ENDPOINT;
1516     DWORD err;
1517
1518     if ((err = RpcServerUseProtseqEpW(transport, 0, endpoint, NULL)) != ERROR_SUCCESS)
1519     {
1520         WINE_ERR("RpcServerUseProtseq failed with error %u\n", err);
1521         return err;
1522     }
1523
1524     if ((err = RpcServerRegisterIf(svcctl_v2_0_s_ifspec, 0, 0)) != ERROR_SUCCESS)
1525     {
1526         WINE_ERR("RpcServerRegisterIf failed with error %u\n", err);
1527         return err;
1528     }
1529
1530     if ((err = RpcServerListen(1, RPC_C_LISTEN_MAX_CALLS_DEFAULT, TRUE)) != ERROR_SUCCESS)
1531     {
1532         WINE_ERR("RpcServerListen failed with error %u\n", err);
1533         return err;
1534     }
1535     return ERROR_SUCCESS;
1536 }
1537
1538 DWORD RPC_MainLoop(void)
1539 {
1540     DWORD err;
1541     HANDLE hExitEvent = __wine_make_process_system();
1542
1543     SetEvent(g_hStartedEvent);
1544
1545     WINE_TRACE("Entered main loop\n");
1546
1547     do
1548     {
1549         err = WaitForSingleObjectEx(hExitEvent, INFINITE, TRUE);
1550         WINE_TRACE("Wait returned %d\n", err);
1551     } while (err != WAIT_OBJECT_0);
1552
1553     WINE_TRACE("Object signaled - wine shutdown\n");
1554     CloseHandle(hExitEvent);
1555     return ERROR_SUCCESS;
1556 }
1557
1558 void __RPC_USER SC_RPC_HANDLE_rundown(SC_RPC_HANDLE handle)
1559 {
1560     SC_RPC_HANDLE_destroy(handle);
1561 }
1562
1563 void  __RPC_FAR * __RPC_USER MIDL_user_allocate(SIZE_T len)
1564 {
1565     return HeapAlloc(GetProcessHeap(), 0, len);
1566 }
1567
1568 void __RPC_USER MIDL_user_free(void __RPC_FAR * ptr)
1569 {
1570     HeapFree(GetProcessHeap(), 0, ptr);
1571 }