VirtualBox

source: vbox/trunk/src/VBox/Additions/x11/VBoxClient/logging.cpp@ 99585

Last change on this file since 99585 was 99585, checked in by vboxsync, 13 months ago

Guest Additions/VBoxClient: Implemented "--session-type" parameter and automatic detection of the session type, to detect the current desktop environment at runtime. Makes now use of the VBGHLog facilities. bugref:10427

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.8 KB
Line 
1/* $Id: logging.cpp 99585 2023-05-03 15:12:56Z vboxsync $ */
2/** @file
3 * VirtualBox Guest Additions - X11 Client.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29#include <sys/wait.h>
30#include <stdlib.h>
31
32#include <iprt/buildconfig.h>
33#include <iprt/file.h>
34#include <iprt/process.h>
35#include <iprt/stream.h>
36#include <iprt/system.h>
37
38#ifdef VBOX_WITH_DBUS
39# include <VBox/dbus.h>
40#endif
41#include <VBox/VBoxGuestLib.h>
42
43#include <VBox/GuestHost/Log.h>
44
45#include <package-generated.h>
46#include "VBoxClient.h"
47
48/** Logging parameters. */
49/** @todo Make this configurable later. */
50static PRTLOGGER g_pLoggerRelease = NULL;
51static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
52static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /* Max 1 day per file. */
53static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
54
55/** Custom log prefix (to be set externally). */
56static char *g_pszCustomLogPrefix;
57
58extern unsigned g_cRespawn;
59
60
61/**
62 * Fallback notification helper using 'notify-send'.
63 *
64 * @returns VBox status code.
65 * @returns VERR_NOT_SUPPORTED if 'notify-send' is not available, or there was an error while running 'notify-send'.
66 * @param pszMessage Message to notify desktop environment with.
67 */
68int vbclNotifyFallbackNotifySend(const char *pszMessage)
69{
70 AssertPtrReturn(pszMessage, VERR_INVALID_POINTER);
71
72 int rc = VINF_SUCCESS;
73
74 if (g_cRespawn == 0)
75 {
76 char *pszCommand = RTStrAPrintf2("notify-send \"VBoxClient: %s\"", pszMessage);
77 if (pszCommand)
78 {
79 int status = system(pszCommand);
80
81 RTStrFree(pszCommand);
82
83 if (WEXITSTATUS(status) != 0) /* Utility or extension not available. */
84 {
85 pszCommand = RTStrAPrintf2("xmessage -buttons OK:0 -center \"VBoxClient: %s\"",
86 pszMessage);
87 if (pszCommand)
88 {
89 status = system(pszCommand);
90 if (WEXITSTATUS(status) != 0) /* Utility or extension not available. */
91 rc = VERR_NOT_SUPPORTED;
92
93 RTStrFree(pszCommand);
94 }
95 else
96 rc = VERR_NO_MEMORY;
97 }
98 }
99 else
100 rc = VERR_NO_MEMORY;
101 }
102
103 return rc;
104}
105
106/**
107 * Shows a notification on the desktop.
108 *
109 * @returns VBox status code.
110 * @returns VERR_NOT_SUPPORTED if the current desktop environment is not supported.
111 * @param pszHeader Header text to show.
112 * @param pszBody Body text to show.
113 *
114 * @note How this notification will look like depends on the actual desktop environment implementing
115 * the actual notification service. Currently only D-BUS-compatible environments are supported.
116 *
117 * Most notification implementations have length limits on their header / body texts, so keep
118 * the text(s) short.
119 */
120int VBClShowNotify(const char *pszHeader, const char *pszBody)
121{
122 AssertPtrReturn(pszHeader, VERR_INVALID_POINTER);
123 AssertPtrReturn(pszBody, VERR_INVALID_POINTER);
124
125 int rc;
126# ifdef VBOX_WITH_DBUS
127 rc = RTDBusLoadLib(); /** @todo Does this init / load the lib only once? Need to check this. */
128 if (RT_FAILURE(rc))
129 {
130 VBClLogError("D-Bus seems not to be installed; no desktop notifications available\n");
131 return rc;
132 }
133
134 DBusConnection *conn;
135 DBusMessage* msg = NULL;
136 conn = dbus_bus_get(DBUS_BUS_SESSION, NULL);
137 if (conn == NULL)
138 {
139 VBClLogError("Could not retrieve D-BUS session bus\n");
140 rc = VERR_INVALID_HANDLE;
141 }
142 else
143 {
144 msg = dbus_message_new_method_call("org.freedesktop.Notifications",
145 "/org/freedesktop/Notifications",
146 "org.freedesktop.Notifications",
147 "Notify");
148 if (msg == NULL)
149 {
150 VBClLogError("Could not create D-BUS message!\n");
151 rc = VERR_INVALID_HANDLE;
152 }
153 else
154 rc = VINF_SUCCESS;
155 }
156 if (RT_SUCCESS(rc))
157 {
158 uint32_t msg_replace_id = 0;
159 const char *msg_app = "VBoxClient";
160 const char *msg_icon = "";
161 const char *msg_summary = pszHeader;
162 const char *msg_body = pszBody;
163 int32_t msg_timeout = -1; /* Let the notification server decide */
164
165 DBusMessageIter iter;
166 DBusMessageIter array;
167 /*DBusMessageIter dict; - unused */
168 /*DBusMessageIter value; - unused */
169 /*DBusMessageIter variant; - unused */
170 /*DBusMessageIter data; - unused */
171
172 /* Format: UINT32 org.freedesktop.Notifications.Notify
173 * (STRING app_name, UINT32 replaces_id, STRING app_icon, STRING summary, STRING body,
174 * ARRAY actions, DICT hints, INT32 expire_timeout)
175 */
176 dbus_message_iter_init_append(msg,&iter);
177 dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_app);
178 dbus_message_iter_append_basic(&iter,DBUS_TYPE_UINT32,&msg_replace_id);
179 dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_icon);
180 dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_summary);
181 dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_body);
182 dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,DBUS_TYPE_STRING_AS_STRING,&array);
183 dbus_message_iter_close_container(&iter,&array);
184 dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,"{sv}",&array);
185 dbus_message_iter_close_container(&iter,&array);
186 dbus_message_iter_append_basic(&iter,DBUS_TYPE_INT32,&msg_timeout);
187
188 DBusError err;
189 dbus_error_init(&err);
190
191 DBusMessage *reply;
192 reply = dbus_connection_send_with_reply_and_block(conn, msg, 30 * 1000 /* 30 seconds timeout */, &err);
193 if (dbus_error_is_set(&err))
194 VBClLogError("D-BUS returned an error while sending the notification: %s", err.message);
195 else if (reply)
196 {
197 dbus_connection_flush(conn);
198 dbus_message_unref(reply);
199 }
200 if (dbus_error_is_set(&err))
201 dbus_error_free(&err);
202 }
203 if (msg != NULL)
204 dbus_message_unref(msg);
205# else
206 /** @todo Implement me */
207 RT_NOREF(pszHeader, pszBody);
208 rc = VERR_NOT_SUPPORTED;
209# endif /* VBOX_WITH_DBUS */
210
211 /* Try to use a fallback if the stuff above fails or is not available. */
212 if (RT_FAILURE(rc))
213 rc = vbclNotifyFallbackNotifySend(pszBody);
214
215 /* If everything fails, still print out our notification to stdout, in the hope
216 * someone still gets aware of it. */
217 if (RT_FAILURE(rc))
218 VBClLogInfo("*** Notification: %s - %s ***\n", pszHeader, pszBody);
219
220 return rc;
221}
222
223/**
224 * Logs a fatal error, notifies the desktop environment via a message and
225 * exits the application immediately.
226 *
227 * @param pszFormat Format string to log.
228 * @param ... Variable arguments for format string. Optional.
229 */
230void VBClLogFatalError(const char *pszFormat, ...)
231{
232 va_list va;
233 va_start(va, pszFormat);
234 VBGHLogFatalErrorV(pszFormat, va);
235 va_end(va);
236}
237
238/**
239 * Logs an error message to the (release) logging instance.
240 *
241 * @param pszFormat Format string to log.
242 */
243void VBClLogError(const char *pszFormat, ...)
244{
245 va_list va;
246 va_start(va, pszFormat);
247 VBGHLogErrorV(pszFormat, va);
248 va_end(va);
249}
250
251/**
252 * Logs an info message to the (release) logging instance.
253 *
254 * @param pszFormat Format string to log.
255 */
256void VBClLogInfo(const char *pszFormat, ...)
257{
258 va_list va;
259 va_start(va, pszFormat);
260 VBGHLogInfoV(pszFormat, va);
261 va_end(va);
262}
263
264/**
265 * Displays a verbose message based on the currently
266 * set global verbosity level.
267 *
268 * @param iLevel Minimum log level required to display this message.
269 * @param pszFormat The message text.
270 * @param ... Format arguments.
271 */
272void VBClLogVerbose(unsigned iLevel, const char *pszFormat, ...)
273{
274 va_list va;
275 va_start(va, pszFormat);
276 VBGHLogVerboseV(iLevel, pszFormat, va);
277 va_end(va);
278}
279
280/**
281 * @callback_method_impl{FNRTLOGPHASE, Release logger callback}
282 */
283static DECLCALLBACK(void) vbClLogHeaderFooter(PRTLOGGER pLoggerRelease, RTLOGPHASE enmPhase, PFNRTLOGPHASEMSG pfnLog)
284{
285 /* Some introductory information. */
286 static RTTIMESPEC s_TimeSpec;
287 char szTmp[256];
288 if (enmPhase == RTLOGPHASE_BEGIN)
289 RTTimeNow(&s_TimeSpec);
290 RTTimeSpecToString(&s_TimeSpec, szTmp, sizeof(szTmp));
291
292 switch (enmPhase)
293 {
294 case RTLOGPHASE_BEGIN:
295 {
296 pfnLog(pLoggerRelease,
297 "VBoxClient %s r%s (verbosity: %u) %s (%s %s) release log\n"
298 "Log opened %s\n",
299 RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity, VBOX_BUILD_TARGET,
300 __DATE__, __TIME__, szTmp);
301
302 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
303 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
304 pfnLog(pLoggerRelease, "OS Product: %s\n", szTmp);
305 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
306 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
307 pfnLog(pLoggerRelease, "OS Release: %s\n", szTmp);
308 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
309 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
310 pfnLog(pLoggerRelease, "OS Version: %s\n", szTmp);
311 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
312 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
313 pfnLog(pLoggerRelease, "OS Service Pack: %s\n", szTmp);
314
315 /* the package type is interesting for Linux distributions */
316 char szExecName[RTPATH_MAX];
317 char *pszExecName = RTProcGetExecutablePath(szExecName, sizeof(szExecName));
318 pfnLog(pLoggerRelease,
319 "Executable: %s\n"
320 "Process ID: %u\n"
321 "Package type: %s"
322#ifdef VBOX_OSE
323 " (OSE)"
324#endif
325 "\n",
326 pszExecName ? pszExecName : "unknown",
327 RTProcSelf(),
328 VBOX_PACKAGE_STRING);
329 break;
330 }
331
332 case RTLOGPHASE_PREROTATE:
333 pfnLog(pLoggerRelease, "Log rotated - Log started %s\n", szTmp);
334 break;
335
336 case RTLOGPHASE_POSTROTATE:
337 pfnLog(pLoggerRelease, "Log continuation - Log started %s\n", szTmp);
338 break;
339
340 case RTLOGPHASE_END:
341 pfnLog(pLoggerRelease, "End of log file - Log started %s\n", szTmp);
342 break;
343
344 default:
345 /* nothing */
346 break;
347 }
348}
349
350static DECLCALLBACK(size_t) vbClLogPrefixCb(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser)
351{
352 size_t cbPrefix = 0;
353
354 RT_NOREF(pLogger);
355 RT_NOREF(pvUser);
356
357 if (g_pszCustomLogPrefix)
358 {
359 cbPrefix = RT_MIN(strlen(g_pszCustomLogPrefix), cchBuf);
360 memcpy(pchBuf, g_pszCustomLogPrefix, cbPrefix);
361 }
362
363 return cbPrefix;
364}
365
366/**
367 * Creates the default release logger outputting to the specified file.
368 *
369 * Pass NULL to disabled logging.
370 *
371 * @return IPRT status code.
372 * @param pszLogFile Filename for log output. NULL disables custom handling.
373 */
374int VBClLogCreate(const char *pszLogFile)
375{
376 if (!pszLogFile)
377 return VINF_SUCCESS;
378
379 /* Create release logger (stdout + file). */
380 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
381 RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME | RTLOGFLAGS_PREFIX_CUSTOM;
382#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
383 fFlags |= RTLOGFLAGS_USECRLF;
384#endif
385 int rc = RTLogCreateEx(&g_pLoggerRelease, "VBOXCLIENT_RELEASE_LOG", fFlags, "all",
386 RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX /*cMaxEntriesPerGroup*/,
387 0 /*cBufDescs*/, NULL /*paBufDescs*/, RTLOGDEST_STDOUT | RTLOGDEST_USER,
388 vbClLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
389 NULL /*pOutputIf*/, NULL /*pvOutputIfUser*/,
390 NULL /*pErrInfo*/, "%s", pszLogFile ? pszLogFile : "");
391 if (RT_SUCCESS(rc))
392 {
393 /* register this logger as the release logger */
394 RTLogRelSetDefaultInstance(g_pLoggerRelease);
395
396 rc = RTLogSetCustomPrefixCallback(g_pLoggerRelease, vbClLogPrefixCb, NULL);
397 if (RT_FAILURE(rc))
398 VBClLogError("unable to register custom log prefix callback\n");
399
400 /* Explicitly flush the log in case of VBOXSERVICE_RELEASE_LOG=buffered. */
401 RTLogFlush(g_pLoggerRelease);
402 }
403
404 return rc;
405}
406
407/**
408 * Set custom log prefix.
409 *
410 * @param pszPrefix Custom log prefix string.
411 */
412void VBClLogSetLogPrefix(const char *pszPrefix)
413{
414 g_pszCustomLogPrefix = (char *)pszPrefix;
415}
416
417/**
418 * Destroys the currently active logging instance.
419 */
420void VBClLogDestroy(void)
421{
422 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
423}
424
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use