Improve journal detection

We can use getpeername() and check if we have a socket that
is in /run/systemd/journal/.
This commit is contained in:
Matthias Clasen 2016-07-20 19:27:17 -04:00
parent 3892034455
commit f5a8dfb6af

View File

@ -95,6 +95,9 @@
#include <signal.h> #include <signal.h>
#include <locale.h> #include <locale.h>
#include <errno.h> #include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "glib-init.h" #include "glib-init.h"
#include "galloca.h" #include "galloca.h"
@ -1614,31 +1617,22 @@ g_log_writer_is_journald (gint output_fd)
* journal. See: https://github.com/systemd/systemd/issues/2473 * journal. See: https://github.com/systemd/systemd/issues/2473
*/ */
static gsize initialized; static gsize initialized;
static gboolean stdout_is_socket; static gboolean fd_is_journal = FALSE;
g_return_val_if_fail (output_fd >= 0, FALSE); g_return_val_if_fail (output_fd >= 0, FALSE);
if (g_once_init_enter (&initialized)) if (g_once_init_enter (&initialized))
{ {
guint64 pid = (guint64) getpid (); struct sockaddr_storage addr;
char *fdpath = g_strdup_printf ("/proc/%" G_GUINT64_FORMAT "/fd/%d", socklen_t addr_len = sizeof(addr);
pid, output_fd); int err = getpeername (output_fd, (struct sockaddr *) &addr, &addr_len);
char buf[1024]; if (err == 0 && addr.ss_family == AF_UNIX)
ssize_t bytes_read; fd_is_journal = g_str_has_prefix (((struct sockaddr_un *)&addr)->sun_path,
"/run/systemd/journal/");
if ((bytes_read = readlink (fdpath, buf, sizeof(buf) - 1)) != -1)
{
buf[bytes_read] = '\0';
stdout_is_socket = g_str_has_prefix (buf, "socket:");
}
else
stdout_is_socket = FALSE;
g_free (fdpath);
g_once_init_leave (&initialized, TRUE); g_once_init_leave (&initialized, TRUE);
} }
return stdout_is_socket; return fd_is_journal;
#else /* if !HAVE_LIBSYSTEMD */ #else /* if !HAVE_LIBSYSTEMD */
return FALSE; return FALSE;
#endif #endif