VirtualBox

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

Last change on this file since 49871 was 49871, checked in by vboxsync, 11 years ago

6813 - User server side API wrapper code in all interfaces.. stage 4 rev 1

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