summaryrefslogtreecommitdiff
path: root/open-vm-tools/vgauth/service/main.c
blob: b0272d341cd56e75301e6f13a9416e72be83a107 (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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*********************************************************
 * Copyright (C) 2011-2015 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 main.c --
 *
 *    Entry point for the GuestAuth service.
 */

#include "serviceInt.h"
#include "service.h"
#ifdef _WIN32
#include <tchar.h>
#include "winCoreDump.h"
#endif

#ifdef _WIN32

/*
 * Turn this on to build as a Windows service.  Note that this
 * affects the cmdline arg parsing, and the default no-argument case
 * runs as a Window service.
 * This means to be run in a non-service mode, you must pass a "-d' flag.
 *
 * Most of the service code was stolen from bora/apps/vmauthd/authdService.c
 */

#define SUPPORT_WIN_SERVICE 1

/*
 * XXX
 *
 * Note that to install the service, it should be executed with its
 * complete path name, since the (un)register code just uses argv[0]
 * as the path to the executable.  A relative path will just confuse
 * the service control manager.
 */


#if SUPPORT_WIN_SERVICE

/*
 * Details about the Windows service
 */
#define VGAUTH_DISPLAY_NAME "VMware Alias Manager and Ticket Service"
#define VGAUTH_DESCRIPTION "Alias Manager and Ticket Service"

static SERVICE_STATUS VGAuthServiceStatus = { 0 };
static SERVICE_STATUS_HANDLE VGAuthServiceStatusHandle = 0;
static HANDLE hServiceThread = NULL;
static HANDLE hServiceQuitEvent = NULL;
#endif

#endif   // _WIN32

#ifndef _WIN32
#define USE_POSIX_SERVICE 1

#include <sys/types.h>
#include <unistd.h>

static gboolean isRunningAsService = FALSE;
static char *pidFileName = "/var/run/vmware/vgauthsvclog_pid.txt";

#endif


/*
 ******************************************************************************
 * ServiceStartAndRun --                                               */ /**
 *
 * Does the work to start up and run the service.  Never returns.
 *
 ******************************************************************************
 */

static void
ServiceStartAndRun(void)
{
   VGAuthError err;
   ServiceConnection *publicConn;

   gboolean auditSuccess = Pref_GetBool(gPrefs,
                                        VGAUTH_PREF_AUDIT_SUCCESS,
                                        VGAUTH_PREF_GROUP_NAME_AUDIT,
                                        TRUE);
   gchar *msgCatalog = Pref_GetString(gPrefs,
                                      VGAUTH_PREF_LOCALIZATION_DIR,
                                      VGAUTH_PREF_GROUP_NAME_LOCALIZATION,
                                      VGAUTH_PREF_DEFAULT_LOCALIZATION_CATALOG);

   I18n_BindTextDomain(VMW_TEXT_DOMAIN, NULL, msgCatalog);
   g_free(msgCatalog);

   Audit_Init(VGAUTH_SERVICE_NAME, auditSuccess);

   Log("INIT SERVICE\n");

#ifdef _WIN32
   if (ServiceOldInstanceExists()) {
      Warning("%s: another instance is running; exiting\n", __FUNCTION__);
      exit(-1);
   }
#endif

   err = ServiceAliasInitAliasStore();
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to init alias store; exiting\n", __FUNCTION__);
      exit(-1);
   }

   err = ServiceInitTickets();
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to init tickets; exiting\n", __FUNCTION__);
      exit(-1);
   }

   err = ServiceInitVerify();
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to init verification; exiting\n", __FUNCTION__);
      exit(-1);
   }

   err = ServiceRegisterIOFunctions(ServiceIOStartListen, ServiceStopIO);
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to register IO functions; exiting\n", __FUNCTION__);
      exit(-1);
   }


   err = ServiceCreatePublicConnection(&publicConn);
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to create public listen sock; exiting\n", __FUNCTION__);
      exit(-1);
   }

   err = ServiceIOStartListen(publicConn);
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to listen on public sock; exiting\n", __FUNCTION__);
      exit(-1);
   }

   err = ServiceIOPrepareMainLoop();
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to set up main loop; exiting\n", __FUNCTION__);
      exit(-1);
   }

   /*
    * This never comes back
    */
   Log("BEGIN SERVICE\n");
   err = ServiceIOMainLoop();
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to run main loop; exiting\n", __FUNCTION__);
      exit(-1);
   }

   // NOTREACHED
   return;
}


#if SUPPORT_WIN_SERVICE

/*
 ******************************************************************************
 * ServiceDoRegisterService --                                           */ /**
 *
 * (Un)registers as a Windows service.
 * Expects the path to be absolute, with the full command name.
 *
 * @param[in]   path       The path to the executable.
 * @param[in]   doRegister Set if the service is being registered.
 *
 ******************************************************************************
 */

static void
ServiceDoRegisterService(gchar *path,
                         gboolean doRegister)
{
   gboolean bRet;
   gchar *errString;

   /*
    * XXX may want to add code to turn a non-absolute path into one,
    * and tack on ".exe" if needed.  Since in theory this code
    * will only be run by an installer which knows the full path,
    * leaving it out for now.
    */

   bRet = ServiceRegisterService(doRegister,
                                 VGAUTH_SERVICE_NAME,
                                 VGAUTH_DISPLAY_NAME,
                                 VGAUTH_DESCRIPTION,
                                 path,
                                 &errString);
   if (!bRet) {
      fprintf(stderr, "%s: %s\n", path, errString);
   } else {
      if (doRegister) {
         printf("Successfully registered %s.\n", VGAUTH_DISPLAY_NAME);
      } else {
         printf("Successfully unregistered %s.\n", VGAUTH_DISPLAY_NAME);
      }
   }

   g_free(errString);
}


/*
 ******************************************************************************
 * ServiceCtrlHandler --                                                 */ /**
 *
 * @param[in]   Opcode   The opcode from the service control manager.
 *
 * Handler for Windows service control messages.
 ******************************************************************************
 */

VOID WINAPI
ServiceCtrlHandler(DWORD opCode)
{
   DWORD status;

   switch(opCode) {
   case SERVICE_CONTROL_PAUSE:
      /*
       * Do whatever it takes to pause here.
       *
       * XXX we don't actually pause any operations...
       */
      VGAuthServiceStatus.dwCurrentState = SERVICE_PAUSED;
      Log("Service Paused.\n");
      break;

   case SERVICE_CONTROL_CONTINUE:
      // Do whatever it takes to continue here.
      VGAuthServiceStatus.dwCurrentState = SERVICE_RUNNING;
      Log("Service Continuing.\n");
      break;

   case SERVICE_CONTROL_STOP:
      // Do whatever it takes to stop here.
      VGAuthServiceStatus.dwWin32ExitCode = 0;
      VGAuthServiceStatus.dwCurrentState  = SERVICE_STOP_PENDING;
      VGAuthServiceStatus.dwCheckPoint    = 0;
      VGAuthServiceStatus.dwWaitHint      = 0;

      if (!SetServiceStatus(VGAuthServiceStatusHandle, &VGAuthServiceStatus)) {
         status = GetLastError();
         VGAUTH_LOG_ERR_WIN("SetServiceStatus failed while stopping\n");
         return;
      }

      if (hServiceThread != NULL) {
         SetEvent(hServiceQuitEvent);
         if (WaitForSingleObject(hServiceThread, 15000) != WAIT_OBJECT_0) {
            Log("Forced to clobber service thread\n");
            TerminateThread(hServiceThread, 0);
         }
         CloseHandle(hServiceThread);
         hServiceThread = NULL;
         CloseHandle(hServiceQuitEvent);
         hServiceQuitEvent = NULL;
      }

      VGAuthServiceStatus.dwCurrentState = SERVICE_STOPPED;
      Log("Service Stopped.\n");
      break;

   case SERVICE_CONTROL_INTERROGATE:
      Log("Service being interrogated....\n");
      break;

   default:
      Warning("Unknown service opcode %d\n", opCode);
      break;
   }

   // Send current status.
   if (!SetServiceStatus(VGAuthServiceStatusHandle, &VGAuthServiceStatus)) {
      VGAUTH_LOG_ERR_WIN("SetServiceStatus failed.\n");
   }

   return;
}


/*
 ******************************************************************************
 * ServiceStartServiceThread --                                          */ /**
 *
 * Starts a thread to do the real work.
 *
 * @return TRUE on success
 ******************************************************************************
 */

static gboolean
ServiceStartServiceThread(void)
{
   VGAuthError err;

   if (!(hServiceQuitEvent = CreateEvent(NULL, FALSE, FALSE, NULL))) {
      VGAUTH_LOG_ERR_WIN("Failed to create shutdown event");
      return FALSE;
   }

   hServiceThread = CreateThread(NULL, 0,
                                 (LPTHREAD_START_ROUTINE) ServiceStartAndRun,
                                 NULL, 0, NULL);

   if (NULL == hServiceThread) {
      VGAUTH_LOG_ERR_WIN("Failed to start service thread\n");
      return FALSE;
   }

   err = ServiceIORegisterQuitEvent(hServiceQuitEvent);
   if (VGAUTH_E_OK != err) {
      Warning("%s: failed to register quit event\n");
      return FALSE;
   }

   return TRUE;
}


/*
 ******************************************************************************
 * ServiceServiceStart --                                                */ /**
 *
 * Service entry point.
 *
 * @param[in]   argc       Number of args (unused).
 * @param[in]   argv       Arguments (unused).
 *
 ******************************************************************************
 */

VOID WINAPI
ServiceServiceStart(DWORD argc,
                    LPTSTR *argv)
{
   BOOL bRet;
   DWORD status;

   VGAuthServiceStatus.dwServiceType        = SERVICE_WIN32;
   VGAuthServiceStatus.dwCurrentState       = SERVICE_START_PENDING;
   VGAuthServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP;

   VGAuthServiceStatusHandle = RegisterServiceCtrlHandler(_T(VGAUTH_SERVICE_NAME),
                                                           ServiceCtrlHandler);

   if (0 == VGAuthServiceStatusHandle) {
      Warning("%s: RegisterServiceCtrlHandler failed %d\n",
              __FUNCTION__, GetLastError());
      return;
   }

   /*
    * Initialization code goes here.
    */

   bRet = ServiceStartServiceThread();

   /*
    * Handle any error
    */
   if (!bRet) {
      VGAuthServiceStatus.dwCurrentState       = SERVICE_STOPPED;
      VGAuthServiceStatus.dwCheckPoint         = 0;
      VGAuthServiceStatus.dwWaitHint           = 0;
      VGAuthServiceStatus.dwWin32ExitCode      = ERROR_SERVICE_SPECIFIC_ERROR;
      VGAuthServiceStatus.dwServiceSpecificExitCode = -1;

      if (!SetServiceStatus(VGAuthServiceStatusHandle,
                            &VGAuthServiceStatus)) {
         Warning("%s: SetServiceStatus error on failure %ld\n",
                 __FUNCTION__, GetLastError());
      }
      return;
   }

   /*
    * Initialization complete - report running status.
    */
   VGAuthServiceStatus.dwCurrentState       = SERVICE_RUNNING;
   VGAuthServiceStatus.dwCheckPoint         = 0;
   VGAuthServiceStatus.dwWaitHint           = 0;

   if (!SetServiceStatus(VGAuthServiceStatusHandle, &VGAuthServiceStatus)) {
      status = GetLastError();
      Warning("%s: SetServiceStatus error %ld\n", __FUNCTION__, status);
   }

#if 0
   /*
    * Fun race here -- if we spew too soon, the debug system isn't properly
    * set up and the Log thinks its recursed and blows up.
    * A Sleep() avoids this, but since we don't really need this noise,
    * turn it off.  Leave this warning in case someone wants to turn it back on.
    */
   Log("Service Started.\n");
#endif

   return;
}


/*
 ******************************************************************************
 * ServiceRunAsService --                                                */ /**
 *
 * Starts as a Windows service.
 *
 ******************************************************************************
 */

void
ServiceRunAsService(void)
{
   gboolean haveDebugConsole = FALSE;
   SERVICE_TABLE_ENTRY DispatchTable[] = {
      { _T(VGAUTH_SERVICE_NAME), ServiceServiceStart},
      { NULL,                     NULL              }
   };

#ifdef VMX86_DEBUG
   /*
    * In devel builds, create a console so warnings are visible.  NB the
    * console won't be visible unless you also check "allow service to
    * interact with desktop" in the Services manager.  I tried hard, and
    * failed, to get the console to show up on the interactive winsta/desk
    * after we move ourselves there -- we're able to create GUI windows
    * fine -- I can only conclude that Windows is broken in this regard.
    * Google for "SetProcessWindowStation AllocConsole" and read the
    * Apache source, or see me, for an amusing story about this.  -- mginzton
    */

   haveDebugConsole = ServiceInitStdioConsole();
#endif

   /*
    * XXX: We should be able to get everything automatically redirected
    * to the new console. Try skip the InitLogging code... TBD
    * When we're in service mode, make sure the debug isn't lost.
    */
   Service_InitLogging(haveDebugConsole, FALSE);

   if (!StartServiceCtrlDispatcher(DispatchTable)) {
      Warning("%s: StartServiceCtrlDispatcher error = %d\n",
              __FUNCTION__, GetLastError());
   }
}
#endif   // SUPPORT_WIN_SERVICE


/*
 ******************************************************************************
 * main --                                                              */ /**
 *
 * The one, the only: main(). Runs the GuestAuth service.
 *
 * @param[in]  argc        Number of command line arguments.
 * @param[in]  argv        The command line arguments.
 *
 * @return 0 if the service ran successfully, -1 if there was an error during
 *         start-up or execution.
 *
 ******************************************************************************
 */

int
main(int argc,
     char *argv[])
{
   gPrefs = Pref_Init(VGAUTH_PREF_CONFIG_FILENAME);

   /*
    * Determine where the service is running from, so resources can
    * be found relative to it.
    */
   if (!g_path_is_absolute(argv[0])) {
      gchar *abs = g_find_program_in_path(argv[0]);
      if (abs == NULL || g_strcmp0(abs, argv[0]) == 0) {
         gchar *cwd = g_get_current_dir();
         g_free(abs);
         abs = g_build_filename(cwd, argv[0], NULL);
         g_free(cwd);
      }
      gInstallDir = g_path_get_dirname(abs);
      g_free(abs);
   } else {
      gInstallDir = g_path_get_dirname(argv[0]);
   }

#ifdef _WIN32
#if SUPPORT_WIN_SERVICE

   /*
    * This is the path for the service control manager.
    */
   if (argc == 1) {
      ServiceRunAsService();
      return 0;
   } else if (argc == 2) {
      // register
      if (g_strcmp0(argv[1], "-r") == 0) {
         ServiceDoRegisterService(argv[0], TRUE);
         return 0;
      // unregister
      } else if (g_strcmp0(argv[1], "-u") == 0) {
         ServiceDoRegisterService(argv[0], FALSE);
         return 0;
      // run as a cmdline app for debugging
      } else if (g_strcmp0(argv[1], "-d") == 0) {
         Service_SetLogOnStdout(TRUE);
         Service_InitLogging(FALSE, FALSE);
         ServiceStartAndRun();
         return 0;
       // run on cmdline, using log file
      } else if (g_strcmp0(argv[1], "-s") == 0) {
         Service_InitLogging(FALSE, FALSE);
         ServiceStartAndRun();
         return 0;
      }
   }

#else
   Service_SetLogOnStdout(TRUE);
   Service_InitLogging(FALSE, FALSE);
   ServiceStartAndRun();
#endif
#else // !_WIN32

#if USE_POSIX_SERVICE
   /*
    * Parse arguments.
    *
    * "-b" tells it to run as a daemon.
    * "-s" tells it to run in service mode (logging to a file).
    * "-k" tells it to kill itself.
    *
    * When running as a daemon, we restart, except with -b changed
    * to -s so we properly log to a file.
    *
    * This code assumes the only arguments supported are "-b" and "-k".
    * The replacement of "-b" before calling ServiceDamonize()
    * will need work if that changes.
    */

   if (argc > 1) {
      if (g_strcmp0(argv[1], "-k") == 0) {            // kill mode
         if (!ServiceSuicide(pidFileName)) {
            exit(-1);
         } else {
            exit(0);
         }
      } else if (g_strcmp0(argv[1], "-s") == 0) {     // service mode
         isRunningAsService = TRUE;
         Service_InitLogging(FALSE, FALSE);
      } else if (g_strcmp0(argv[1], "-b") == 0) {     // background mode
         Service_InitLogging(FALSE, FALSE);
         /*
          * We have to remove this flag to prevent an infinite loop.
          */
         argv[1] = g_strdup("-s");
         if (!ServiceDaemonize(argv[0],
                               argv,
                               SERVICE_DAEMONIZE_LOCKPID,
                               pidFileName)) {
            Warning("%s: failed to daemonize\n", __FUNCTION__);
            return -1;
         }
         // NOTREACHED
         return 0;
      } else {
         Warning("%s: unrecognized args\n", __FUNCTION__);
      }
   } else {
      /* The foreground mode */
      Service_SetLogOnStdout(TRUE);
      Service_InitLogging(FALSE, FALSE);
   }
#endif   // USE_POSIX_SERVICE
   ServiceSetSignalHandlers();
   ServiceStartAndRun();

#endif   // !_WIN32

   return 0;
}