VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/xpcom/server.cpp@ 98651

Last change on this file since 98651 was 98103, checked in by vboxsync, 20 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.5 KB
Line 
1/* $Id: server.cpp 98103 2023-01-17 14:15:46Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2004-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_MAIN_VBOXSVC
29#include <ipcIService.h>
30#include <ipcCID.h>
31
32#include <nsIComponentRegistrar.h>
33
34#include <nsGenericFactory.h>
35
36#include "prio.h"
37#include "prproces.h"
38
39#include "server.h"
40
41#include "LoggingNew.h"
42
43#include <VBox/param.h>
44#include <VBox/version.h>
45
46#include <iprt/buildconfig.h>
47#include <iprt/initterm.h>
48#include <iprt/critsect.h>
49#include <iprt/getopt.h>
50#include <iprt/message.h>
51#include <iprt/string.h>
52#include <iprt/stream.h>
53#include <iprt/path.h>
54#include <iprt/timer.h>
55#include <iprt/env.h>
56
57#include <signal.h> // for the signal handler
58#include <stdlib.h>
59#include <unistd.h>
60#include <errno.h>
61#include <fcntl.h>
62#include <sys/stat.h>
63#include <sys/resource.h>
64
65/////////////////////////////////////////////////////////////////////////////
66// VirtualBox component instantiation
67/////////////////////////////////////////////////////////////////////////////
68
69#include <nsIGenericFactory.h>
70#include <VBox/com/VirtualBox.h>
71
72#include "VBox/com/NativeEventQueue.h"
73
74#include "ApplianceImpl.h"
75#include "AudioAdapterImpl.h"
76#include "BandwidthControlImpl.h"
77#include "BandwidthGroupImpl.h"
78#include "NetworkServiceRunner.h"
79#include "DHCPServerImpl.h"
80#include "GuestOSTypeImpl.h"
81#include "HostImpl.h"
82#include "HostNetworkInterfaceImpl.h"
83#include "MachineImpl.h"
84#include "MediumFormatImpl.h"
85#include "MediumImpl.h"
86#include "NATEngineImpl.h"
87#include "NetworkAdapterImpl.h"
88#include "ParallelPortImpl.h"
89#include "ProgressProxyImpl.h"
90#include "SerialPortImpl.h"
91#include "SharedFolderImpl.h"
92#include "SnapshotImpl.h"
93#include "StorageControllerImpl.h"
94#include "SystemPropertiesImpl.h"
95#include "USBControllerImpl.h"
96#include "USBDeviceFiltersImpl.h"
97#include "VFSExplorerImpl.h"
98#include "VirtualBoxImpl.h"
99#include "VRDEServerImpl.h"
100#ifdef VBOX_WITH_USB
101# include "HostUSBDeviceImpl.h"
102# include "USBDeviceFilterImpl.h"
103# include "USBDeviceImpl.h"
104#endif
105#ifdef VBOX_WITH_EXTPACK
106# include "ExtPackManagerImpl.h"
107#endif
108# include "NATNetworkImpl.h"
109
110// This needs to stay - it is needed by the service registration below, and
111// is defined in the automatically generated VirtualBoxWrap.cpp
112extern nsIClassInfo *NS_CLASSINFO_NAME(VirtualBoxWrap);
113NS_DECL_CI_INTERFACE_GETTER(VirtualBoxWrap)
114
115////////////////////////////////////////////////////////////////////////////////
116
117static bool gAutoShutdown = false;
118/** Delay before shutting down the VirtualBox server after the last
119 * VirtualBox instance is released, in ms */
120static uint32_t gShutdownDelayMs = 5000;
121
122static com::NativeEventQueue *gEventQ = NULL;
123static PRBool volatile gKeepRunning = PR_TRUE;
124static PRBool volatile gAllowSigUsrQuit = PR_TRUE;
125
126/////////////////////////////////////////////////////////////////////////////
127
128/**
129 * VirtualBox class factory that destroys the created instance right after
130 * the last reference to it is released by the client, and recreates it again
131 * when necessary (so VirtualBox acts like a singleton object).
132 */
133class VirtualBoxClassFactory : public VirtualBox
134{
135public:
136
137 virtual ~VirtualBoxClassFactory()
138 {
139 LogFlowFunc(("Deleting VirtualBox...\n"));
140
141 FinalRelease();
142 sInstance = NULL;
143
144 LogFlowFunc(("VirtualBox object deleted.\n"));
145 RTPrintf("Informational: VirtualBox object deleted.\n");
146 }
147
148 NS_IMETHOD_(nsrefcnt) Release()
149 {
150 /* we overload Release() to guarantee the VirtualBox destructor is
151 * always called on the main thread */
152
153 nsrefcnt count = VirtualBox::Release();
154
155 if (count == 1)
156 {
157 /* the last reference held by clients is being released
158 * (see GetInstance()) */
159
160 bool onMainThread = RTThreadIsMain(RTThreadSelf());
161 PRBool timerStarted = PR_FALSE;
162
163 /* sTimer is null if this call originates from FactoryDestructor()*/
164 if (sTimer != NULL)
165 {
166 LogFlowFunc(("Last VirtualBox instance was released.\n"));
167 LogFlowFunc(("Scheduling server shutdown in %u ms...\n",
168 gShutdownDelayMs));
169
170 /* make sure the previous timer (if any) is stopped;
171 * otherwise RTTimerStart() will definitely fail. */
172 RTTimerLRStop(sTimer);
173
174 int vrc = RTTimerLRStart(sTimer, gShutdownDelayMs * RT_NS_1MS_64);
175 AssertRC(vrc);
176 timerStarted = RT_BOOL(RT_SUCCESS(vrc));
177 }
178 else
179 {
180 LogFlowFunc(("Last VirtualBox instance was released "
181 "on XPCOM shutdown.\n"));
182 Assert(onMainThread);
183 }
184
185 gAllowSigUsrQuit = PR_TRUE;
186
187 if (!timerStarted)
188 {
189 if (!onMainThread)
190 {
191 /* Failed to start the timer, post the shutdown event
192 * manually if not on the main thread already. */
193 ShutdownTimer(NULL, NULL, 0);
194 }
195 else
196 {
197 /* Here we come if:
198 *
199 * a) gEventQ is 0 which means either FactoryDestructor() is called
200 * or the IPC/DCONNECT shutdown sequence is initiated by the
201 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
202 * happens on the main thread.
203 *
204 * b) gEventQ has reported we're on the main thread. This means
205 * that DestructEventHandler() has been called, but another
206 * client was faster and requested VirtualBox again.
207 *
208 * In either case, there is nothing to do.
209 *
210 * Note: case b) is actually no more valid since we don't
211 * call Release() from DestructEventHandler() in this case
212 * any more. Thus, we assert below.
213 */
214
215 Assert(!gEventQ);
216 }
217 }
218 }
219
220 return count;
221 }
222
223 class MaybeQuitEvent : public NativeEvent
224 {
225 public:
226 MaybeQuitEvent() :
227 m_fSignal(false)
228 {
229 }
230
231 MaybeQuitEvent(bool fSignal) :
232 m_fSignal(fSignal)
233 {
234 }
235
236 private:
237 /* called on the main thread */
238 void *handler()
239 {
240 LogFlowFuncEnter();
241
242 Assert(RTCritSectIsInitialized(&sLock));
243
244 /* stop accepting GetInstance() requests on other threads during
245 * possible destruction */
246 RTCritSectEnter(&sLock);
247
248 nsrefcnt count = 1;
249
250 /* sInstance is NULL here if it was deleted immediately after
251 * creation due to initialization error. See GetInstance(). */
252 if (sInstance != NULL)
253 {
254 /* Safe way to get current refcount is by first increasing and
255 * then decreasing. Keep in mind that the Release is overloaded
256 * (see VirtualBoxClassFactory::Release) and will start the
257 * timer again if the returned count is 1. It won't do harm,
258 * but also serves no purpose, so stop it ASAP. */
259 sInstance->AddRef();
260 count = sInstance->Release();
261 if (count == 1)
262 {
263 RTTimerLRStop(sTimer);
264 /* Release the guard reference added in GetInstance() */
265 sInstance->Release();
266 }
267 }
268
269 if (count == 1)
270 {
271 if (gAutoShutdown || m_fSignal)
272 {
273 Assert(sInstance == NULL);
274 LogFlowFunc(("Terminating the server process...\n"));
275 /* make it leave the event loop */
276 gKeepRunning = PR_FALSE;
277 }
278 else
279 LogFlowFunc(("No automatic shutdown.\n"));
280 }
281 else
282 {
283 /* This condition is quite rare: a new client happened to
284 * connect after this event has been posted to the main queue
285 * but before it started to process it. */
286 LogRel(("Destruction is canceled (refcnt=%d).\n", count));
287 }
288
289 RTCritSectLeave(&sLock);
290
291 LogFlowFuncLeave();
292 return NULL;
293 }
294
295 bool m_fSignal;
296 };
297
298 static DECLCALLBACK(void) ShutdownTimer(RTTIMERLR hTimerLR, void *pvUser, uint64_t /*iTick*/)
299 {
300 NOREF(hTimerLR);
301 NOREF(pvUser);
302
303 /* A "too late" event is theoretically possible if somebody
304 * manually ended the server after a destruction has been scheduled
305 * and this method was so lucky that it got a chance to run before
306 * the timer was killed. */
307 com::NativeEventQueue *q = gEventQ;
308 AssertReturnVoid(q);
309
310 /* post a quit event to the main queue */
311 MaybeQuitEvent *ev = new MaybeQuitEvent(false /* fSignal */);
312 if (!q->postEvent(ev))
313 delete ev;
314
315 /* A failure above means we've been already stopped (for example
316 * by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
317 * will do the job. Nothing to do. */
318 }
319
320 static NS_IMETHODIMP FactoryConstructor()
321 {
322 LogFlowFunc(("\n"));
323
324 /* create a critsect to protect object construction */
325 if (RT_FAILURE(RTCritSectInit(&sLock)))
326 return NS_ERROR_OUT_OF_MEMORY;
327
328 int vrc = RTTimerLRCreateEx(&sTimer, 0, 0, ShutdownTimer, NULL);
329 if (RT_FAILURE(vrc))
330 {
331 LogFlowFunc(("Failed to create a timer! (vrc=%Rrc)\n", vrc));
332 return NS_ERROR_FAILURE;
333 }
334
335 return NS_OK;
336 }
337
338 static NS_IMETHODIMP FactoryDestructor()
339 {
340 LogFlowFunc(("\n"));
341
342 RTTimerLRDestroy(sTimer);
343 sTimer = NULL;
344
345 if (sInstance != NULL)
346 {
347 /* Either posting a destruction event failed for some reason (most
348 * likely, the quit event has been received before the last release),
349 * or the client has terminated abnormally w/o releasing its
350 * VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
351 * Release the guard reference we added in GetInstance(). */
352 sInstance->Release();
353 }
354
355 /* Destroy lock after releasing the VirtualBox instance, otherwise
356 * there are races with cleanup. */
357 RTCritSectDelete(&sLock);
358
359 return NS_OK;
360 }
361
362 static nsresult GetInstance(VirtualBox **inst)
363 {
364 LogFlowFunc(("Getting VirtualBox object...\n"));
365
366 RTCritSectEnter(&sLock);
367
368 if (!gKeepRunning)
369 {
370 LogFlowFunc(("Process termination requested first. Refusing.\n"));
371
372 RTCritSectLeave(&sLock);
373
374 /* this rv is what CreateInstance() on the client side returns
375 * when the server process stops accepting events. Do the same
376 * here. The client wrapper should attempt to start a new process in
377 * response to a failure from us. */
378 return NS_ERROR_ABORT;
379 }
380
381 nsresult rv = NS_OK;
382
383 if (sInstance == NULL)
384 {
385 LogFlowFunc(("Creating new VirtualBox object...\n"));
386 sInstance = new VirtualBoxClassFactory();
387 if (sInstance != NULL)
388 {
389 /* make an extra AddRef to take the full control
390 * on the VirtualBox destruction (see FinalRelease()) */
391 sInstance->AddRef();
392
393 sInstance->AddRef(); /* protect FinalConstruct() */
394 rv = sInstance->FinalConstruct();
395 RTPrintf("Informational: VirtualBox object created (rc=%Rhrc).\n", rv);
396 if (NS_FAILED(rv))
397 {
398 /* On failure diring VirtualBox initialization, delete it
399 * immediately on the current thread by releasing all
400 * references in order to properly schedule the server
401 * shutdown. Since the object is fully deleted here, there
402 * is a chance to fix the error and request a new
403 * instantiation before the server terminates. However,
404 * the main reason to maintain the shutdown delay on
405 * failure is to let the front-end completely fetch error
406 * info from a server-side IVirtualBoxErrorInfo object. */
407 sInstance->Release();
408 sInstance->Release();
409 Assert(sInstance == NULL);
410 }
411 else
412 {
413 /* On success, make sure the previous timer is stopped to
414 * cancel a scheduled server termination (if any). */
415 gAllowSigUsrQuit = PR_FALSE;
416 RTTimerLRStop(sTimer);
417 }
418 }
419 else
420 {
421 rv = NS_ERROR_OUT_OF_MEMORY;
422 }
423 }
424 else
425 {
426 LogFlowFunc(("Using existing VirtualBox object...\n"));
427 nsrefcnt count = sInstance->AddRef();
428 Assert(count > 1);
429
430 if (count >= 2)
431 {
432 LogFlowFunc(("Another client has requested a reference to VirtualBox, canceling destruction...\n"));
433
434 /* make sure the previous timer is stopped */
435 gAllowSigUsrQuit = PR_FALSE;
436 RTTimerLRStop(sTimer);
437 }
438 }
439
440 *inst = sInstance;
441
442 RTCritSectLeave(&sLock);
443
444 return rv;
445 }
446
447private:
448
449 /* Don't be confused that sInstance is of the *ClassFactory type. This is
450 * actually a singleton instance (*ClassFactory inherits the singleton
451 * class; we combined them just for "simplicity" and used "static" for
452 * factory methods. *ClassFactory here is necessary for a couple of extra
453 * methods. */
454
455 static VirtualBoxClassFactory *sInstance;
456 static RTCRITSECT sLock;
457
458 static RTTIMERLR sTimer;
459};
460
461VirtualBoxClassFactory *VirtualBoxClassFactory::sInstance = NULL;
462RTCRITSECT VirtualBoxClassFactory::sLock;
463
464RTTIMERLR VirtualBoxClassFactory::sTimer = NIL_RTTIMERLR;
465
466NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC(VirtualBox, VirtualBoxClassFactory::GetInstance)
467
468////////////////////////////////////////////////////////////////////////////////
469
470typedef NSFactoryDestructorProcPtr NSFactoryConstructorProcPtr;
471
472/**
473 * Enhanced module component information structure.
474 *
475 * nsModuleComponentInfo lacks the factory construction callback, here we add
476 * it. This callback is called straight after a nsGenericFactory instance is
477 * successfully created in RegisterSelfComponents.
478 */
479struct nsModuleComponentInfoPlusFactoryConstructor
480{
481 /** standard module component information */
482 const nsModuleComponentInfo *mpModuleComponentInfo;
483 /** (optional) Factory Construction Callback */
484 NSFactoryConstructorProcPtr mFactoryConstructor;
485};
486
487/////////////////////////////////////////////////////////////////////////////
488
489/**
490 * Helper function to register self components upon start-up
491 * of the out-of-proc server.
492 */
493static nsresult
494RegisterSelfComponents(nsIComponentRegistrar *registrar,
495 const nsModuleComponentInfoPlusFactoryConstructor *aComponents,
496 PRUint32 count)
497{
498 nsresult rc = NS_OK;
499 const nsModuleComponentInfoPlusFactoryConstructor *info = aComponents;
500 for (PRUint32 i = 0; i < count && NS_SUCCEEDED(rc); i++, info++)
501 {
502 /* skip components w/o a constructor */
503 if (!info->mpModuleComponentInfo->mConstructor)
504 continue;
505 /* create a new generic factory for a component and register it */
506 nsIGenericFactory *factory;
507 rc = NS_NewGenericFactory(&factory, info->mpModuleComponentInfo);
508 if (NS_SUCCEEDED(rc) && info->mFactoryConstructor)
509 {
510 rc = info->mFactoryConstructor();
511 if (NS_FAILED(rc))
512 NS_RELEASE(factory);
513 }
514 if (NS_SUCCEEDED(rc))
515 {
516 rc = registrar->RegisterFactory(info->mpModuleComponentInfo->mCID,
517 info->mpModuleComponentInfo->mDescription,
518 info->mpModuleComponentInfo->mContractID,
519 factory);
520 NS_RELEASE(factory);
521 }
522 }
523 return rc;
524}
525
526/////////////////////////////////////////////////////////////////////////////
527
528static ipcIService *gIpcServ = nsnull;
529static const char *g_pszPidFile = NULL;
530
531class ForceQuitEvent : public NativeEvent
532{
533 void *handler()
534 {
535 LogFlowFunc(("\n"));
536
537 gKeepRunning = PR_FALSE;
538
539 if (g_pszPidFile)
540 RTFileDelete(g_pszPidFile);
541
542 return NULL;
543 }
544};
545
546static void signal_handler(int sig)
547{
548 com::NativeEventQueue *q = gEventQ;
549 if (q && gKeepRunning)
550 {
551 if (sig == SIGUSR1)
552 {
553 if (gAllowSigUsrQuit)
554 {
555 /* terminate the server process if it is idle */
556 VirtualBoxClassFactory::MaybeQuitEvent *ev = new VirtualBoxClassFactory::MaybeQuitEvent(true /* fSignal */);
557 if (!q->postEvent(ev))
558 delete ev;
559 }
560 /* else do nothing */
561 }
562 else
563 {
564 /* post a force quit event to the queue */
565 ForceQuitEvent *ev = new ForceQuitEvent();
566 if (!q->postEvent(ev))
567 delete ev;
568 }
569 }
570}
571
572static nsresult vboxsvcSpawnDaemonByReExec(const char *pszPath, bool fAutoShutdown, const char *pszPidFile)
573{
574 PRFileDesc *readable = nsnull, *writable = nsnull;
575 PRProcessAttr *attr = nsnull;
576 nsresult rv = NS_ERROR_FAILURE;
577 PRFileDesc *devNull;
578 unsigned args_index = 0;
579 // The ugly casts are necessary because the PR_CreateProcessDetached has
580 // a const array of writable strings as a parameter. It won't write. */
581 char * args[1 + 1 + 2 + 1];
582 args[args_index++] = (char *)pszPath;
583 if (fAutoShutdown)
584 args[args_index++] = (char *)"--auto-shutdown";
585 if (pszPidFile)
586 {
587 args[args_index++] = (char *)"--pidfile";
588 args[args_index++] = (char *)pszPidFile;
589 }
590 args[args_index++] = 0;
591
592 // Use a pipe to determine when the daemon process is in the position
593 // to actually process requests. The daemon will write "READY" to the pipe.
594 if (PR_CreatePipe(&readable, &writable) != PR_SUCCESS)
595 goto end;
596 PR_SetFDInheritable(writable, PR_TRUE);
597
598 attr = PR_NewProcessAttr();
599 if (!attr)
600 goto end;
601
602 if (PR_ProcessAttrSetInheritableFD(attr, writable, VBOXSVC_STARTUP_PIPE_NAME) != PR_SUCCESS)
603 goto end;
604
605 devNull = PR_Open("/dev/null", PR_RDWR, 0);
606 if (!devNull)
607 goto end;
608
609 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, devNull);
610 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, devNull);
611 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardError, devNull);
612
613 if (PR_CreateProcessDetached(pszPath, (char * const *)args, nsnull, attr) != PR_SUCCESS)
614 goto end;
615
616 // Close /dev/null
617 PR_Close(devNull);
618 // Close the child end of the pipe to make it the only owner of the
619 // file descriptor, so that unexpected closing can be detected.
620 PR_Close(writable);
621 writable = nsnull;
622
623 char msg[10];
624 memset(msg, '\0', sizeof(msg));
625 if ( PR_Read(readable, msg, sizeof(msg)-1) != 5
626 || strcmp(msg, "READY"))
627 goto end;
628
629 rv = NS_OK;
630
631end:
632 if (readable)
633 PR_Close(readable);
634 if (writable)
635 PR_Close(writable);
636 if (attr)
637 PR_DestroyProcessAttr(attr);
638 return rv;
639}
640
641static void showUsage(const char *pcszFileName)
642{
643 RTPrintf(VBOX_PRODUCT " VBoxSVC "
644 VBOX_VERSION_STRING "\n"
645 "Copyright (C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n");
646 RTPrintf("By default the service will be started in the background.\n"
647 "\n");
648 RTPrintf("Usage:\n"
649 "\n");
650 RTPrintf(" %s\n", pcszFileName);
651 RTPrintf("\n");
652 RTPrintf("Options:\n");
653 RTPrintf(" -a, --automate Start XPCOM on demand and daemonize.\n");
654 RTPrintf(" -A, --auto-shutdown Shuts down service if no longer in use.\n");
655 RTPrintf(" -d, --daemonize Starts service in background.\n");
656 RTPrintf(" -D, --shutdown-delay <ms> Sets shutdown delay in ms.\n");
657 RTPrintf(" -h, --help Displays this help.\n");
658 RTPrintf(" -p, --pidfile <path> Uses a specific pidfile.\n");
659 RTPrintf(" -F, --logfile <path> Uses a specific logfile.\n");
660 RTPrintf(" -R, --logrotate <count> Number of old log files to keep.\n");
661 RTPrintf(" -S, --logsize <bytes> Maximum size of a log file before rotating.\n");
662 RTPrintf(" -I, --loginterval <s> Maximum amount of time to put in a log file.\n");
663
664 RTPrintf("\n");
665}
666
667int main(int argc, char **argv)
668{
669 /*
670 * Initialize the VBox runtime without loading
671 * the support driver
672 */
673 int vrc = RTR3InitExe(argc, &argv, 0);
674 if (RT_FAILURE(vrc))
675 return RTMsgInitFailure(vrc);
676
677 static const RTGETOPTDEF s_aOptions[] =
678 {
679 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
680 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
681 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
682 { "--help", 'h', RTGETOPT_REQ_NOTHING },
683 { "--shutdown-delay", 'D', RTGETOPT_REQ_UINT32 },
684 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
685 { "--logfile", 'F', RTGETOPT_REQ_STRING },
686 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
687 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
688 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
689 };
690
691 const char *pszLogFile = NULL;
692 uint32_t cHistory = 10; // enable log rotation, 10 files
693 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
694 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
695 bool fDaemonize = false;
696 PRFileDesc *daemon_pipe_wr = nsnull;
697
698 RTGETOPTSTATE GetOptState;
699 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
700 AssertRC(vrc);
701
702 RTGETOPTUNION ValueUnion;
703 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
704 {
705 switch (vrc)
706 {
707 case 'a':
708 /* --automate mode means we are started by XPCOM on
709 * demand. Daemonize ourselves and activate
710 * auto-shutdown. */
711 gAutoShutdown = true;
712 fDaemonize = true;
713 break;
714
715 case 'A':
716 /* --auto-shutdown mode means we're already daemonized. */
717 gAutoShutdown = true;
718 break;
719
720 case 'd':
721 fDaemonize = true;
722 break;
723
724 case 'D':
725 gShutdownDelayMs = ValueUnion.u32;
726 break;
727
728 case 'p':
729 g_pszPidFile = ValueUnion.psz;
730 break;
731
732 case 'F':
733 pszLogFile = ValueUnion.psz;
734 break;
735
736 case 'R':
737 cHistory = ValueUnion.u32;
738 break;
739
740 case 'S':
741 uHistoryFileSize = ValueUnion.u64;
742 break;
743
744 case 'I':
745 uHistoryFileTime = ValueUnion.u32;
746 break;
747
748 case 'h':
749 showUsage(argv[0]);
750 return RTEXITCODE_SYNTAX;
751
752 case 'V':
753 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
754 return RTEXITCODE_SUCCESS;
755
756 default:
757 return RTGetOptPrintError(vrc, &ValueUnion);
758 }
759 }
760
761 if (fDaemonize)
762 {
763 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
764 exit(126);
765 }
766
767 nsresult rc;
768
769 /** @todo Merge this code with svcmain.cpp (use Logging.cpp?). */
770 char szLogFile[RTPATH_MAX];
771 if (!pszLogFile)
772 {
773 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
774 if (RT_SUCCESS(vrc))
775 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
776 }
777 else
778 {
779 if (!RTStrPrintf(szLogFile, sizeof(szLogFile), "%s", pszLogFile))
780 vrc = VERR_NO_MEMORY;
781 }
782 if (RT_FAILURE(vrc))
783 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create logging file name, rc=%Rrc", vrc);
784
785 RTERRINFOSTATIC ErrInfo;
786 vrc = com::VBoxLogRelCreate("XPCOM Server", szLogFile,
787 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
788 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
789 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
790 cHistory, uHistoryFileTime, uHistoryFileSize,
791 RTErrInfoInitStatic(&ErrInfo));
792 if (RT_FAILURE(vrc))
793 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, vrc);
794
795 /* Set up a build identifier so that it can be seen from core dumps what
796 * exact build was used to produce the core. Same as in Console::i_powerUpThread(). */
797 static char saBuildID[48];
798 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
799 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
800
801 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
802 RTEnvUnset("NSPR_INHERIT_FDS");
803
804 const nsModuleComponentInfo VirtualBoxInfo = {
805 "VirtualBox component",
806 NS_VIRTUALBOX_CID,
807 NS_VIRTUALBOX_CONTRACTID,
808 VirtualBoxConstructor, // constructor function
809 NULL, // registration function
810 NULL, // deregistration function
811 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
812 NS_CI_INTERFACE_GETTER_NAME(VirtualBoxWrap),
813 NULL, // language helper
814 &NS_CLASSINFO_NAME(VirtualBoxWrap),
815 0 // flags
816 };
817
818 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
819 {
820 &VirtualBoxInfo,
821 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
822 }
823 };
824
825 do /* goto avoidance only */
826 {
827 rc = com::Initialize();
828 if (NS_FAILED(rc))
829 {
830 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
831 break;
832 }
833
834 nsCOMPtr<nsIComponentRegistrar> registrar;
835 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
836 if (NS_FAILED(rc))
837 {
838 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
839 break;
840 }
841
842 registrar->AutoRegister(nsnull);
843 rc = RegisterSelfComponents(registrar, components,
844 NS_ARRAY_LENGTH(components));
845 if (NS_FAILED(rc))
846 {
847 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
848 break;
849 }
850
851 nsCOMPtr<ipcIService> ipcServ(do_GetService(IPC_SERVICE_CONTRACTID, &rc));
852 if (NS_FAILED(rc))
853 {
854 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
855 break;
856 }
857
858 NS_ADDREF(gIpcServ = ipcServ);
859
860 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
861
862 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
863 if (NS_FAILED(rc))
864 {
865 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
866 "Is another server already running?\n", rc, rc));
867
868 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
869 "Is another server already running?\n",
870 VBOXSVC_IPC_NAME, rc);
871 NS_RELEASE(gIpcServ);
872 break;
873 }
874
875 {
876 /* setup signal handling to convert some signals to a quit event */
877 struct sigaction sa;
878 sa.sa_handler = signal_handler;
879 sigemptyset(&sa.sa_mask);
880 sa.sa_flags = 0;
881 sigaction(SIGINT, &sa, NULL);
882 sigaction(SIGQUIT, &sa, NULL);
883 sigaction(SIGTERM, &sa, NULL);
884// XXX Temporary allow release assertions to terminate VBoxSVC
885// sigaction(SIGTRAP, &sa, NULL);
886 sigaction(SIGUSR1, &sa, NULL);
887 }
888
889 {
890 char szBuf[80];
891 size_t cSize;
892
893 cSize = RTStrPrintf(szBuf, sizeof(szBuf),
894 VBOX_PRODUCT" XPCOM Server Version "
895 VBOX_VERSION_STRING);
896 for (size_t i = cSize; i > 0; i--)
897 putchar('*');
898 RTPrintf("\n%s\n", szBuf);
899 RTPrintf("Copyright (C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n");
900#ifdef DEBUG
901 RTPrintf("Debug version.\n");
902#endif
903 }
904
905 if (daemon_pipe_wr != nsnull)
906 {
907 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
908 /* now we're ready, signal the parent process */
909 PR_Write(daemon_pipe_wr, RT_STR_TUPLE("READY"));
910 /* close writing end of the pipe, its job is done */
911 PR_Close(daemon_pipe_wr);
912 }
913 else
914 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
915
916 if (g_pszPidFile)
917 {
918 RTFILE hPidFile = NIL_RTFILE;
919 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
920 if (RT_SUCCESS(vrc))
921 {
922 char szBuf[64];
923 size_t cchToWrite = RTStrPrintf(szBuf, sizeof(szBuf), "%ld\n", (long)getpid());
924 RTFileWrite(hPidFile, szBuf, cchToWrite, NULL);
925 RTFileClose(hPidFile);
926 }
927 }
928
929 // Increase the file table size to 10240 or as high as possible.
930 struct rlimit lim;
931 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
932 {
933 if ( lim.rlim_cur < 10240
934 && lim.rlim_cur < lim.rlim_max)
935 {
936 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
937 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
938 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
939 }
940 }
941 else
942 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
943
944 /* get the main thread's event queue */
945 gEventQ = com::NativeEventQueue::getMainEventQueue();
946 if (!gEventQ)
947 {
948 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
949 break;
950 }
951
952 while (gKeepRunning)
953 {
954 vrc = gEventQ->processEventQueue(RT_INDEFINITE_WAIT);
955 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
956 {
957 LogRel(("Failed to wait for events! (rc=%Rrc)", vrc));
958 break;
959 }
960 }
961
962 gEventQ = NULL;
963 RTPrintf("Terminated event loop.\n");
964
965 /* unregister ourselves. After this point, clients will start a new
966 * process because they won't be able to resolve the server name.*/
967 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
968 }
969 while (0); // this scopes the nsCOMPtrs
970
971 NS_IF_RELEASE(gIpcServ);
972
973 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
974
975 LogFlowFunc(("Calling com::Shutdown()...\n"));
976 rc = com::Shutdown();
977 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
978
979 if (NS_FAILED(rc))
980 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
981
982 RTPrintf("XPCOM server has shutdown.\n");
983
984 if (g_pszPidFile)
985 RTFileDelete(g_pszPidFile);
986
987 return RTEXITCODE_SUCCESS;
988}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette