summaryrefslogtreecommitdiff
path: root/open-vm-tools/services/vmtoolsd/cmdLine.c
blob: 63acdc81526f64ac22b8d5105b1d47c9b2bab83b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*********************************************************
 * Copyright (C) 2008 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/**
 * @file cmdLine.c
 *
 *    Parses the daemon's command line arguments. Some commands may cause the
 *    process to exit.
 */

#include "toolsCoreInt.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if !defined(G_PLATFORM_WIN32)
#  include <unistd.h>
#endif
#include <glib/gi18n.h>

#include "vm_assert.h"
#include "conf.h"
#include "rpcout.h"
#include "str.h"
#include "vmcheck.h"
#include "vmtoolsd_version.h"
#include "vmware/tools/log.h"
#include "vmware/tools/utils.h"
#include "vmware/tools/i18n.h"
#include "vm_version.h"

/**
 * Runs the given Tools RPC command, printing the result to the terminal and
 * exiting the application afterwards.
 *
 * @param[in]  option      Unused.
 * @param[in]  value       RPC command.
 * @param[in]  data        Unused.
 * @param[out] error       Unused.
 *
 * @return This function doesn't return.
 */

static gboolean
ToolsCoreRunCommand(const gchar *option,
                    const gchar *value,
                    gpointer data,
                    GError **error)
{
#if defined(_WIN32)
   VMTools_AttachConsole();
#endif
   if (VmCheck_IsVirtualWorld()) {
      char *result = NULL;
      Bool status = FALSE;

      status = RpcOut_sendOne(&result, NULL, "%s", value);

      if (!status) {
         g_printerr("%s\n", result ? result : "NULL");
      } else {
         g_print("%s\n", result);
      }

      vm_free(result);
      exit(status ? 0 : 1);
   }
   g_printerr("%s\n",
              SU_(cmdline.rpcerror, "Unable to send command to VMware hypervisor."));
   exit(1);
}


#if defined(G_PLATFORM_WIN32)

/**
 * Function used to ignore command line arguments.
 *
 * @param[in]  option      Unused.
 * @param[in]  value       Unused.
 * @param[in]  data        Unused.
 * @param[out] error       Unused.
 *
 * @return TRUE
 */

static gboolean
ToolsCoreIgnoreArg(const gchar *option,
                   const gchar *value,
                   gpointer data,
                   GError **error)
{
   return TRUE;
}


/**
 * Signals a specific event in a running service instance. Since this function
 * doesn't know whether the service is running through the SCM, it first tries
 * to open a local event, and if that fails, tries a global event.
 *
 * @param[in]  svcname     Name of the service to be signaled.
 * @param[in]  evtFmt      Format string for the event name. It should expect
 *                         a single string parameter.
 *
 * @return Whether successfully signaled the running service.
 */

static gboolean
ToolsCoreSignalEvent(const gchar *svcname,
                     const wchar_t *evtFmt)
{
   gboolean ret = FALSE;
   gchar *msg;
   wchar_t *evt;
   HANDLE h = NULL;

   ASSERT(svcname != NULL);

   evt = Str_Aswprintf(NULL, evtFmt, L"Local", svcname);
   if (evt == NULL) {
      g_printerr("Out of memory!\n");
      goto exit;
   }

   h = OpenEvent(EVENT_MODIFY_STATE, FALSE, evt);
   if (h != NULL) {
      goto dispatch;
   }

   vm_free(evt);
   evt = Str_Aswprintf(NULL, evtFmt, L"Global", svcname);
   if (evt == NULL) {
      g_printerr("Out of memory!\n");
      goto exit;
   }

   h = OpenEvent(EVENT_MODIFY_STATE, FALSE, evt);
   if (h == NULL) {
      goto error;
   }

dispatch:
   if (!SetEvent(h)) {
      goto error;
   }

   ret = TRUE;
   goto exit;

error:
   msg = g_win32_error_message(GetLastError());
   g_printerr("Cannot open event: %s\n", msg);
   g_free(msg);

exit:
   vm_free(evt);
   CloseHandle(h);
   return ret;
}

#endif


/**
 * Error hook called when command line parsing fails. On Win32, make sure we
 * have a terminal where to show the error message.
 *
 * @param[in] context    Unused.
 * @param[in] group      Unused.
 * @param[in] data       Unused.
 * @param[in] error      Unused.
 */

static void
ToolsCoreCmdLineError(GOptionContext *context,
                      GOptionGroup *group,
                      gpointer data,
                      GError **error)
{
#if defined(_WIN32)
   VMTools_AttachConsole();
#endif
}


/**
 * Parses the command line. For a list of available options, look at the source
 * below, where the option array is declared.
 *
 * @param[out] state    Parsed options will be placed in this struct.
 * @param[in]  argc     Argument count.
 * @param[in]  argv     Argument array.
 *
 * @return TRUE on success.
 */

gboolean
ToolsCore_ParseCommandLine(ToolsServiceState *state,
                           int argc,
                           char *argv[])
{
   int i = 0;
   char *cmdStr = NULL;
   gboolean ret = FALSE;
   gboolean version = FALSE;
#if defined(G_PLATFORM_WIN32)
   gboolean dumpState = FALSE;
   gboolean kill = FALSE;
#endif
   gboolean unused;
   GOptionEntry clOptions[] = {
      { "name", 'n', 0, G_OPTION_ARG_STRING, &state->name,
         SU_(cmdline.name, "Name of the service being started."),
         SU_(cmdline.name.argument, "svcname") },
      { "common-path", '\0', 0, G_OPTION_ARG_FILENAME, &state->commonPath,
         SU_(cmdline.commonpath, "Path to the common plugin directory."),
         SU_(cmdline.path, "path") },
      { "plugin-path", 'p', 0, G_OPTION_ARG_FILENAME, &state->pluginPath,
         SU_(cmdline.pluginpath, "Path to the plugin directory."),
         SU_(cmdline.path, "path") },
      { "cmd", '\0', 0, G_OPTION_ARG_CALLBACK, ToolsCoreRunCommand,
         SU_(cmdline.rpc, "Sends an RPC command to the host and exits."),
         SU_(cmdline.rpc.command, "command") },
#if defined(G_PLATFORM_WIN32)
      { "dump-state", 's', 0, G_OPTION_ARG_NONE, &dumpState,
         SU_(cmdline.state, "Dumps the internal state of a running service instance to the logs."),
         NULL },
      { "kill", 'k', 0, G_OPTION_ARG_NONE, &kill,
         SU_(cmdline.kill, "Stops a running instance of a tools service."),
         NULL },
      { "install", 'i', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, ToolsCoreIgnoreArg,
         SU_(cmdline.install, "Installs the service with the Service Control Manager."),
         SU_(cmdline.install.args, "args") },
      { "uninstall", 'u', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, ToolsCoreIgnoreArg,
         SU_(cmdline.uninstall, "Uninstalls the service from the Service Control Manager."),
         NULL },
      { "displayname", 'd', 0, G_OPTION_ARG_STRING, &state->displayName,
         SU_(cmdline.displayname, "Service display name (only used with -i)."),
         SU_(cmdline.displayname.argument, "name") },
#else
      { "background", 'b', 0, G_OPTION_ARG_FILENAME, &state->pidFile,
         SU_(cmdline.background, "Runs in the background and creates a pid file."),
         SU_(cmdline.background.pidfile, "pidfile") },
      { "blockFd", '\0', 0, G_OPTION_ARG_INT, &state->ctx.blockFD,
         SU_(cmdline.blockfd, "File descriptor for the VMware blocking fs."),
         SU_(cmdline.blockfd.fd, "fd") },
#endif
      { "config", 'c', 0, G_OPTION_ARG_FILENAME, &state->configFile,
         SU_(cmdline.config, "Uses the config file at the given path."),
         SU_(cmdline.path, "path") },
      { "debug", 'g', 0, G_OPTION_ARG_FILENAME, &state->debugPlugin,
         SU_(cmdline.debug, "Runs in debug mode, using the given plugin."),
         SU_(cmdline.path, "path") },
      { "log", 'l', 0, G_OPTION_ARG_NONE, &unused,
         SU_(cmdline.log, "Ignored, kept for backwards compatibility."),
         NULL },
      { "version", 'v', 0, G_OPTION_ARG_NONE, &version,
         SU_(cmdline.version, "Prints the daemon version and exits."),
         NULL },
      { NULL }
   };
   GError *error = NULL;
   GOptionContext *context = NULL;

#if !defined(G_PLATFORM_WIN32)
   state->ctx.blockFD = -1;
#endif

   /*
    * Form the commandline for debug log before calling
    * g_option_context_parse(), because it modifies argv.
    */
   cmdStr = Str_SafeAsprintf(NULL, "%s", argv[0]);
   for (i = 1; i < argc; i++) {
      char *prefix = cmdStr;
      cmdStr = Str_SafeAsprintf(NULL, "%s %s", prefix, argv[i]);
      free(prefix);
      /*
       * NOTE: We can't log the cmdStr here, we can
       * only log it after logging gets configured.
       * Logging it before ToolsCore_ReloadConfig call
       * will not generate proper logs.
       */
   }

   context = g_option_context_new(NULL);
#if GLIB_CHECK_VERSION(2, 12, 0)
   g_option_context_set_summary(context, N_("Runs the VMware Tools daemon."));
#endif
   g_option_context_add_main_entries(context, clOptions, NULL);
   g_option_group_set_error_hook(g_option_context_get_main_group(context),
                                 ToolsCoreCmdLineError);

   if (!g_option_context_parse(context, &argc, &argv, &error)) {
      g_printerr("%s: %s\n", N_("Command line parsing failed"), error->message);
      goto exit;
   }

   if (version) {
      g_print("%s %s (%s)\n", _("VMware Tools daemon, version"),
              VMTOOLSD_VERSION_STRING, BUILD_NUMBER);
      exit(0);
   }

   if (state->name == NULL) {
      state->name = VMTOOLS_GUEST_SERVICE;
      state->mainService = TRUE;
   } else {
      if (strcmp(state->name, TOOLSCORE_COMMON) == 0) {
         g_printerr("%s is an invalid container name.\n", state->name);
         goto exit;
      }
      state->mainService = (strcmp(state->name, VMTOOLS_GUEST_SERVICE) == 0);
   }

   /* Configure logging system. */
   ToolsCore_ReloadConfig(state, TRUE);

   /* Log the commandline for debugging purposes. */
   g_debug("CmdLine: \"%s\"\n", cmdStr);

#if defined(G_PLATFORM_WIN32)
   if (kill) {
      exit(ToolsCoreSignalEvent(state->name, QUIT_EVENT_NAME_FMT) ? 0 : 1);
   }
   if (dumpState) {
      exit(ToolsCoreSignalEvent(state->name, DUMP_STATE_EVENT_NAME_FMT) ? 0 : 1);
   }
#else
   /* If not running the "vmusr" service, ignore the blockFd parameter. */
   if (strcmp(state->name, VMTOOLS_USER_SERVICE) != 0) {
      if (state->ctx.blockFD >= 0) {
         close(state->ctx.blockFD);
      }
      state->ctx.blockFD = -1;
   }
#endif

   ret = TRUE;

exit:
   free(cmdStr);
   g_clear_error(&error);
   g_option_context_free(context);
   return ret;
}