VirtualBox

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

Last change on this file since 78750 was 78162, checked in by vboxsync, 6 years ago

Shared Clipboard/Additions: Make feature optional (if VBOX_WITH_SHARED_CLIPBOARD is being set).

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