VirtualBox

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

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

6813 - stage 3 rev 1

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