2 * QEMU Guest Agent helpers for win32 service management
4 * Copyright IBM Corp. 2012
7 * Gal Hammer <ghammer@redhat.com>
8 * Michael Roth <mdroth@linux.vnet.ibm.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
17 #include "qga/service-win32.h"
19 static int printf_win_error(const char *text
)
21 DWORD err
= GetLastError();
25 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
26 FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
29 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
32 n
= fprintf(stderr
, "%s. (Error: %d) %s", text
, (int)err
, message
);
38 int ga_install_service(const char *path
, const char *logfile
,
39 const char *state_dir
)
41 int ret
= EXIT_FAILURE
;
44 TCHAR module_fname
[MAX_PATH
];
46 SERVICE_DESCRIPTION desc
= { (char *)QGA_SERVICE_DESCRIPTION
};
48 if (GetModuleFileName(NULL
, module_fname
, MAX_PATH
) == 0) {
49 printf_win_error("No full path to service's executable");
53 cmdline
= g_string_new(module_fname
);
54 g_string_append(cmdline
, " -d");
57 g_string_append_printf(cmdline
, " -p %s", path
);
60 g_string_append_printf(cmdline
, " -l %s -v", logfile
);
63 g_string_append_printf(cmdline
, " -t %s", state_dir
);
66 g_debug("service's cmdline: %s", cmdline
->str
);
68 manager
= OpenSCManager(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
69 if (manager
== NULL
) {
70 printf_win_error("No handle to service control manager");
74 service
= CreateService(manager
, QGA_SERVICE_NAME
, QGA_SERVICE_DISPLAY_NAME
,
75 SERVICE_ALL_ACCESS
, SERVICE_WIN32_OWN_PROCESS
, SERVICE_AUTO_START
,
76 SERVICE_ERROR_NORMAL
, cmdline
->str
, NULL
, NULL
, NULL
, NULL
, NULL
);
77 if (service
== NULL
) {
78 printf_win_error("Failed to install service");
82 ChangeServiceConfig2(service
, SERVICE_CONFIG_DESCRIPTION
, &desc
);
83 fprintf(stderr
, "Service was installed successfully.\n");
85 CloseServiceHandle(service
);
88 CloseServiceHandle(manager
);
91 g_string_free(cmdline
, TRUE
);
95 int ga_uninstall_service(void)
100 manager
= OpenSCManager(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
101 if (manager
== NULL
) {
102 printf_win_error("No handle to service control manager");
106 service
= OpenService(manager
, QGA_SERVICE_NAME
, DELETE
);
107 if (service
== NULL
) {
108 printf_win_error("No handle to service");
109 CloseServiceHandle(manager
);
113 if (DeleteService(service
) == FALSE
) {
114 printf_win_error("Failed to delete service");
116 fprintf(stderr
, "Service was deleted successfully.\n");
119 CloseServiceHandle(service
);
120 CloseServiceHandle(manager
);