VirtualBox

source: vbox/trunk/src/VBox/Additions/x11/VBoxClient/main.cpp@ 69046

Last change on this file since 69046 was 68562, checked in by vboxsync, 7 years ago

merging vbglioc r117719: VBoxClient: avoid use RTEXITCODE where possible, use RTMsg* where possible, added options for forground execution (like VBoxService -f), added comprehensible error on syntax errors (wasting my time), wasted time figuring out that the logging to stdout fun done in the -d case is useless now (probably due to moving VbglR3InitUser from top of main() to service code).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 14.0 KB
Line 
1/* $Id: main.cpp 68562 2017-08-31 12:10:16Z vboxsync $ */
2/** @file
3 * VirtualBox Guest Additions - X11 Client.
4 */
5
6/*
7 * Copyright (C) 2006-2016 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 <sys/types.h>
19#include <sys/wait.h>
20#include <stdlib.h> /* For exit */
21#include <stdio.h>
22#include <string.h>
23#include <unistd.h>
24#include <errno.h>
25#include <poll.h>
26#include <signal.h>
27
28#include <X11/Xlib.h>
29#include <X11/Xatom.h>
30
31#include <iprt/buildconfig.h>
32#include <iprt/critsect.h>
33#include <iprt/env.h>
34#include <iprt/file.h>
35#include <iprt/initterm.h>
36#include <iprt/message.h>
37#include <iprt/path.h>
38#include <iprt/param.h>
39#include <iprt/stream.h>
40#include <iprt/string.h>
41#include <iprt/types.h>
42#include <VBox/VBoxGuestLib.h>
43#include <VBox/log.h>
44
45#include "VBoxClient.h"
46
47/*static int (*gpfnOldIOErrorHandler)(Display *) = NULL; - unused */
48
49/** Object representing the service we are running. This has to be global
50 * so that the cleanup routine can access it. */
51struct VBCLSERVICE **g_pService;
52/** The name of our pidfile. It is global for the benefit of the cleanup
53 * routine. */
54static char g_szPidFile[RTPATH_MAX] = "";
55/** The file handle of our pidfile. It is global for the benefit of the
56 * cleanup routine. */
57static RTFILE g_hPidFile;
58/** Global critical section held during the clean-up routine (to prevent it
59 * being called on multiple threads at once) or things which may not happen
60 * during clean-up (e.g. pausing and resuming the service).
61 */
62RTCRITSECT g_critSect;
63/** Counter of how often our deamon has been respawned. */
64unsigned cRespawn = 0;
65
66/**
67 * Exit with a fatal error.
68 *
69 * This is used by the VBClFatalError macro and thus needs to be external.
70 */
71void vbclFatalError(char *pszMessage)
72{
73 char *pszCommand;
74 int status;
75 if (pszMessage && cRespawn == 0)
76 {
77 pszCommand = RTStrAPrintf2("notify-send \"VBoxClient: %s\"", pszMessage);
78 if (pszCommand)
79 {
80 status = system(pszCommand);
81 if (WEXITSTATUS(status) != 0) /* Utility or extension not available. */
82 {
83 pszCommand = RTStrAPrintf2("xmessage -buttons OK:0 -center \"VBoxClient: %s\"",
84 pszMessage);
85 if (pszCommand)
86 {
87 status = system(pszCommand);
88 if (WEXITSTATUS(status) != 0) /* Utility or extension not available. */
89 {
90 RTPrintf("VBoxClient: %s", pszMessage);
91 }
92 }
93 }
94 }
95 }
96 _exit(RTEXITCODE_FAILURE);
97}
98
99/**
100 * Clean up if we get a signal or something.
101 *
102 * This is extern so that we can call it from other compilation units.
103 */
104void VBClCleanUp(bool fExit /*=true*/)
105{
106 /* We never release this, as we end up with a call to exit(3) which is not
107 * async-safe. Unless we fix this application properly, we should be sure
108 * never to exit from anywhere except from this method. */
109 int rc = RTCritSectEnter(&g_critSect);
110 if (RT_FAILURE(rc))
111 VBClFatalError(("VBoxClient: Failure while acquiring the global critical section, rc=%Rrc\n", rc));
112 if (g_pService)
113 (*g_pService)->cleanup(g_pService);
114 if (g_szPidFile[0] && g_hPidFile)
115 VbglR3ClosePidFile(g_szPidFile, g_hPidFile);
116 if (fExit)
117 exit(RTEXITCODE_SUCCESS);
118}
119
120/**
121 * A standard signal handler which cleans up and exits.
122 */
123static void vboxClientSignalHandler(int cSignal)
124{
125 LogRel(("VBoxClient: terminated with signal %d\n", cSignal));
126 /** Disable seamless mode */
127 RTPrintf(("VBoxClient: terminating...\n"));
128 VBClCleanUp();
129}
130
131/**
132 * Xlib error handler for certain errors that we can't avoid.
133 */
134static int vboxClientXLibErrorHandler(Display *pDisplay, XErrorEvent *pError)
135{
136 char errorText[1024];
137
138 XGetErrorText(pDisplay, pError->error_code, errorText, sizeof(errorText));
139 LogRelFlow(("VBoxClient: an X Window protocol error occurred: %s (error code %d). Request code: %d, minor code: %d, serial number: %d\n", errorText, pError->error_code, pError->request_code, pError->minor_code, pError->serial));
140 return 0;
141}
142
143/**
144 * Xlib error handler for fatal errors. This often means that the programme is still running
145 * when X exits.
146 */
147static int vboxClientXLibIOErrorHandler(Display *pDisplay)
148{
149 RT_NOREF1(pDisplay);
150 LogRel(("VBoxClient: a fatal guest X Window error occurred. This may just mean that the Window system was shut down while the client was still running.\n"));
151 VBClCleanUp();
152 return 0; /* We should never reach this. */
153}
154
155/**
156 * Reset all standard termination signals to call our signal handler, which
157 * cleans up and exits.
158 */
159static void vboxClientSetSignalHandlers(void)
160{
161 struct sigaction sigAction;
162
163 LogRelFlowFunc(("\n"));
164 sigAction.sa_handler = vboxClientSignalHandler;
165 sigemptyset(&sigAction.sa_mask);
166 sigAction.sa_flags = 0;
167 sigaction(SIGHUP, &sigAction, NULL);
168 sigaction(SIGINT, &sigAction, NULL);
169 sigaction(SIGQUIT, &sigAction, NULL);
170 sigaction(SIGPIPE, &sigAction, NULL);
171 sigaction(SIGALRM, &sigAction, NULL);
172 sigaction(SIGTERM, &sigAction, NULL);
173 sigaction(SIGUSR1, &sigAction, NULL);
174 sigaction(SIGUSR2, &sigAction, NULL);
175 LogRelFlowFunc(("returning\n"));
176}
177
178/**
179 * Print out a usage message and exit with success.
180 */
181static void vboxClientUsage(const char *pcszFileName)
182{
183 RTPrintf("Usage: %s --clipboard|"
184#ifdef VBOX_WITH_DRAG_AND_DROP
185 "--draganddrop|"
186#endif
187 "--display|"
188# ifdef VBOX_WITH_GUEST_PROPS
189 "--checkhostversion|"
190#endif
191 "--seamless|check3d|"
192 "--vmsvga [-d|--nodaemon]\n", pcszFileName);
193 RTPrintf("Starts the VirtualBox DRM/X Window System guest services.\n\n");
194 RTPrintf("Options:\n");
195 RTPrintf(" --clipboard starts the shared clipboard service\n");
196#ifdef VBOX_WITH_DRAG_AND_DROP
197 RTPrintf(" --draganddrop starts the drag and drop service\n");
198#endif
199 RTPrintf(" --display starts the display management service\n");
200#ifdef VBOX_WITH_GUEST_PROPS
201 RTPrintf(" --checkhostversion starts the host version notifier service\n");
202#endif
203 RTPrintf(" --check3d tests whether 3D pass-through is enabled\n");
204 RTPrintf(" --seamless starts the seamless windows service\n");
205 RTPrintf(" --vmsvga starts VMSVGA dynamic resizing for DRM or for X11\n");
206 RTPrintf(" -f, --foreground run in the foreground (no daemonizing)\n");
207 RTPrintf(" -d, --nodaemon continues running as a system service\n");
208 RTPrintf(" -h, --help shows this help text\n");
209 RTPrintf(" -V, --version shows version information\n");
210 RTPrintf("\n");
211}
212
213/**
214 * Complains about seeing more than one service specification.
215 *
216 * @returns RTEXITCODE_SYNTAX.
217 */
218static int vbclSyntaxOnlyOneService(void)
219{
220 RTMsgError("More than one service specified! Only one, please.");
221 return RTEXITCODE_SYNTAX;
222}
223
224/**
225 * The main loop for the VBoxClient daemon.
226 * @todo Clean up for readability.
227 */
228int main(int argc, char *argv[])
229{
230 /* Initialise our runtime before all else. */
231 int rc = RTR3InitExe(argc, &argv, 0);
232 if (RT_FAILURE(rc))
233 return RTMsgInitFailure(rc);
234
235 /* This should never be called twice in one process - in fact one Display
236 * object should probably never be used from multiple threads anyway. */
237 if (!XInitThreads())
238 VBClFatalError(("Failed to initialize X11 threads\n"));
239
240 /* Get our file name for usage info and hints. */
241 const char *pcszFileName = RTPathFilename(argv[0]);
242 if (!pcszFileName)
243 pcszFileName = "VBoxClient";
244
245 /* Parse our option(s) */
246 /** @todo Use RTGetOpt() if the arguments become more complex. */
247 bool fDaemonise = true;
248 bool fRespawn = true;
249 for (int i = 1; i < argc; ++i)
250 {
251 if ( !strcmp(argv[i], "-f")
252 || !strcmp(argv[i], "--foreground")
253 || !strcmp(argv[i], "-d")
254 || !strcmp(argv[i], "--nodaemon"))
255 {
256 /* If the user is running in "no daemon" mode anyway, send critical
257 * logging to stdout as well. */
258 /** @todo r=bird: Since the release logger isn't created until the service
259 * calls VbglR3InitUser or VbglR3Init or RTLogCreate, this whole
260 * exercise is pointless. Added --init-vbgl-user and --init-vbgl-full
261 * for getting some work done. */
262 PRTLOGGER pReleaseLog = RTLogRelGetDefaultInstance();
263 if (pReleaseLog)
264 rc = RTLogDestinations(pReleaseLog, "stdout");
265 if (pReleaseLog && RT_FAILURE(rc))
266 return RTMsgErrorExitFailure("failed to redivert error output, rc=%Rrc", rc);
267
268 fDaemonise = false;
269 if ( !strcmp(argv[i], "-f")
270 || !strcmp(argv[i], "--foreground"))
271 fRespawn = false;
272 }
273 else if (!strcmp(argv[i], "--no-respawn"))
274 {
275 fRespawn = false;
276 }
277 else if (!strcmp(argv[i], "--clipboard"))
278 {
279 if (g_pService)
280 return vbclSyntaxOnlyOneService();
281 g_pService = VBClGetClipboardService();
282 }
283 else if (!strcmp(argv[i], "--display"))
284 {
285 if (g_pService)
286 return vbclSyntaxOnlyOneService();
287 g_pService = VBClGetDisplayService();
288 }
289 else if (!strcmp(argv[i], "--seamless"))
290 {
291 if (g_pService)
292 return vbclSyntaxOnlyOneService();
293 g_pService = VBClGetSeamlessService();
294 }
295 else if (!strcmp(argv[i], "--checkhostversion"))
296 {
297 if (g_pService)
298 return vbclSyntaxOnlyOneService();
299 g_pService = VBClGetHostVersionService();
300 }
301#ifdef VBOX_WITH_DRAG_AND_DROP
302 else if (!strcmp(argv[i], "--draganddrop"))
303 {
304 if (g_pService)
305 return vbclSyntaxOnlyOneService();
306 g_pService = VBClGetDragAndDropService();
307 }
308#endif /* VBOX_WITH_DRAG_AND_DROP */
309 else if (!strcmp(argv[i], "--check3d"))
310 {
311 if (g_pService)
312 return vbclSyntaxOnlyOneService();
313 g_pService = VBClCheck3DService();
314 }
315 else if (!strcmp(argv[i], "--vmsvga"))
316 {
317 if (g_pService)
318 return vbclSyntaxOnlyOneService();
319 g_pService = VBClDisplaySVGAService();
320 }
321 /* bird: this is just a quick hack to get something out of the LogRel statements in the code. */
322 else if (!strcmp(argv[i], "--init-vbgl-user"))
323 {
324 rc = VbglR3InitUser();
325 if (RT_FAILURE(rc))
326 return RTMsgErrorExitFailure("VbglR3InitUser failed: %Rrc", rc);
327 }
328 else if (!strcmp(argv[i], "--init-vbgl-full"))
329 {
330 rc = VbglR3Init();
331 if (RT_FAILURE(rc))
332 return RTMsgErrorExitFailure("VbglR3Init failed: %Rrc", rc);
333 }
334 else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
335 {
336 vboxClientUsage(pcszFileName);
337 return RTEXITCODE_SUCCESS;
338 }
339 else if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version"))
340 {
341 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
342 return RTEXITCODE_SUCCESS;
343 }
344 else
345 {
346 RTMsgError("unrecognized option `%s'", argv[i]);
347 RTMsgInfo("Try `%s --help' for more information", pcszFileName);
348 return RTEXITCODE_SYNTAX;
349 }
350 }
351 if (!g_pService)
352 {
353 RTMsgError("No service specified. Quitting because nothing to do!");
354 return RTEXITCODE_SYNTAX;
355 }
356
357 rc = RTCritSectInit(&g_critSect);
358 if (RT_FAILURE(rc))
359 VBClFatalError(("Initialising critical section failed: %Rrc\n", rc));
360 if ((*g_pService)->getPidFilePath)
361 {
362 rc = RTPathUserHome(g_szPidFile, sizeof(g_szPidFile));
363 if (RT_FAILURE(rc))
364 VBClFatalError(("Getting home directory for PID file failed: %Rrc\n", rc));
365 rc = RTPathAppend(g_szPidFile, sizeof(g_szPidFile),
366 (*g_pService)->getPidFilePath());
367 if (RT_FAILURE(rc))
368 VBClFatalError(("Creating PID file path failed: %Rrc\n", rc));
369 if (fDaemonise)
370 rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */, fRespawn, &cRespawn);
371 if (RT_FAILURE(rc))
372 VBClFatalError(("Daemonizing failed: %Rrc\n", rc));
373 if (g_szPidFile[0])
374 rc = VbglR3PidFile(g_szPidFile, &g_hPidFile);
375 if (rc == VERR_FILE_LOCK_VIOLATION) /* Already running. */
376 return RTEXITCODE_SUCCESS;
377 if (RT_FAILURE(rc))
378 VBClFatalError(("Creating PID file failed: %Rrc\n", rc));
379 }
380 /* Set signal handlers to clean up on exit. */
381 vboxClientSetSignalHandlers();
382#ifndef VBOXCLIENT_WITHOUT_X11
383 /* Set an X11 error handler, so that we don't die when we get unavoidable
384 * errors. */
385 XSetErrorHandler(vboxClientXLibErrorHandler);
386 /* Set an X11 I/O error handler, so that we can shutdown properly on
387 * fatal errors. */
388 XSetIOErrorHandler(vboxClientXLibIOErrorHandler);
389#endif
390 rc = (*g_pService)->init(g_pService);
391 if (RT_SUCCESS(rc))
392 {
393 rc = (*g_pService)->run(g_pService, fDaemonise);
394 if (RT_FAILURE(rc))
395 LogRel2(("Running service failed: %Rrc\n", rc));
396 }
397 else
398 {
399 /** @todo r=andy Should we return an appropriate exit code if the service failed to init?
400 * Must be tested carefully with our init scripts first. */
401 LogRel2(("Initializing service failed: %Rrc\n", rc));
402 }
403 VBClCleanUp(false /*fExit*/);
404 return RTEXITCODE_SUCCESS;
405}
406
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