summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2011-10-07 21:06:39 +0200
committerLennart Poettering <lennart@poettering.net>2011-10-07 22:02:05 +0200
commit87d2c1ff6a7375f03476767e6f59454bcc5cd04b (patch)
tree26824a2485942702b3472cc73191c01e78c622d1
parent9a36607584bbd1d78775353e022a51794b4e27b1 (diff)
downloadsystemd-87d2c1ff6a7375f03476767e6f59454bcc5cd04b.tar.gz
systemd-87d2c1ff6a7375f03476767e6f59454bcc5cd04b.tar.bz2
systemd-87d2c1ff6a7375f03476767e6f59454bcc5cd04b.zip
journal: add preliminary incomplete implementation
-rw-r--r--.gitignore6
-rw-r--r--Makefile.am63
-rw-r--r--po/.gitignore1
-rw-r--r--src/automount.c2
-rw-r--r--src/cgroup-show.c2
l---------src/journal/Makefile1
-rw-r--r--src/journal/journal-def.h139
-rw-r--r--src/journal/journal-private.h53
-rw-r--r--src/journal/journalctl.c91
-rw-r--r--src/journal/journald.c460
-rw-r--r--src/journal/lookup3.c1003
-rw-r--r--src/journal/lookup3.h25
-rw-r--r--src/journal/sd-journal.c1333
-rw-r--r--src/journal/sd-journal.h74
-rw-r--r--src/journal/test-journal.c93
-rw-r--r--src/journal/wjournal.c57
-rw-r--r--src/journal/wjournal.h39
-rw-r--r--src/kmsg-syslogd.c216
-rw-r--r--src/loginctl.c2
-rw-r--r--src/machine-id-setup.c40
-rw-r--r--src/manager.c4
-rw-r--r--src/pam-module.c34
-rw-r--r--src/sd-id128.c210
-rw-r--r--src/sd-id128.h56
-rw-r--r--src/stdout-syslog-bridge.c3
-rw-r--r--src/systemctl.c4
-rw-r--r--src/test-id128.c49
-rw-r--r--src/util.c276
-rw-r--r--src/util.h14
l---------tmpfiles.d/Makefile1
30 files changed, 4076 insertions, 275 deletions
diff --git a/.gitignore b/.gitignore
index f4a8a45b4a..265801ff5f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
+systemd-journalctl
+systemd-journald
+test-id128
+test-journal
test-install
org.freedesktop.hostname1.xml
org.freedesktop.locale1.xml
@@ -91,7 +95,7 @@ install-sh
missing
stamp-*
*.stamp
-Makefile
+/Makefile
ltmain.sh
*.tar.bz2
*.tar.gz
diff --git a/Makefile.am b/Makefile.am
index f4a17aa7f5..9bf92ad7ac 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -134,7 +134,8 @@ rootbin_PROGRAMS = \
systemd-ask-password \
systemd-tty-ask-password-agent \
systemd-tmpfiles \
- systemd-machine-id-setup
+ systemd-machine-id-setup \
+ systemd-journalctl
bin_PROGRAMS = \
systemd-cgls \
@@ -173,7 +174,8 @@ rootlibexec_PROGRAMS = \
systemd-detect-virt \
systemd-sysctl \
systemd-logind \
- systemd-uaccess
+ systemd-uaccess \
+ systemd-journald
if ENABLE_BINFMT
rootlibexec_PROGRAMS += \
@@ -225,7 +227,9 @@ noinst_PROGRAMS = \
test-env-replace \
test-strv \
test-login \
- test-install
+ test-install \
+ test-id128 \
+ test-journal
if HAVE_PAM
pamlib_LTLIBRARIES = \
@@ -685,7 +689,8 @@ libsystemd_core_la_SOURCES = \
src/dbus-common.c \
src/sd-daemon.c \
src/install.c \
- src/cgroup-attr.c
+ src/cgroup-attr.c \
+ src/sd-id128.c
nodist_libsystemd_core_la_SOURCES = \
src/load-fragment-gperf.c \
@@ -947,6 +952,53 @@ test_install_CFLAGS = \
test_install_LDADD = \
libsystemd-basic.la
+test_id128_SOURCES = \
+ src/test-id128.c \
+ src/sd-id128.c
+
+test_id128_CFLAGS = \
+ $(AM_CFLAGS)
+
+test_id128_LDADD = \
+ libsystemd-basic.la
+
+test_journal_SOURCES = \
+ src/journal/test-journal.c \
+ src/journal/sd-journal.c \
+ src/journal/lookup3.c \
+ src/sd-id128.c
+
+test_journal_CFLAGS = \
+ $(AM_CFLAGS)
+
+test_journal_LDADD = \
+ libsystemd-basic.la
+
+systemd_journald_SOURCES = \
+ src/journal/journald.c \
+ src/journal/sd-journal.c \
+ src/journal/lookup3.c \
+ src/sd-id128.c
+
+systemd_journald_CFLAGS = \
+ $(AM_CFLAGS)
+
+systemd_journald_LDADD = \
+ libsystemd-basic.la \
+ libsystemd-daemon.la
+
+systemd_journalctl_SOURCES = \
+ src/journal/journalctl.c \
+ src/journal/sd-journal.c \
+ src/journal/lookup3.c \
+ src/sd-id128.c
+
+systemd_journalctl_CFLAGS = \
+ $(AM_CFLAGS)
+
+systemd_journalctl_LDADD = \
+ libsystemd-basic.la
+
systemd_stdout_syslog_bridge_SOURCES = \
src/stdout-syslog-bridge.c \
src/tcpwrap.c
@@ -1142,7 +1194,8 @@ systemd_tmpfiles_LDADD = \
systemd_machine_id_setup_SOURCES = \
src/machine-id-setup.c \
- src/machine-id-main.c
+ src/machine-id-main.c \
+ src/sd-id128.c
systemd_machine_id_setup_CFLAGS = \
$(AM_CFLAGS)
diff --git a/po/.gitignore b/po/.gitignore
index 251edd4c81..ee1215654d 100644
--- a/po/.gitignore
+++ b/po/.gitignore
@@ -1,3 +1,4 @@
POTFILES
Makefile.in.in
.intltool-merge-cache
+Makefile
diff --git a/src/automount.c b/src/automount.c
index 29b807de51..6cf3c311b3 100644
--- a/src/automount.c
+++ b/src/automount.c
@@ -770,7 +770,7 @@ static void automount_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
if (packet.v5_packet.pid > 0) {
char *p = NULL;
- get_process_name(packet.v5_packet.pid, &p);
+ get_process_comm(packet.v5_packet.pid, &p);
log_debug("Got direct mount request for %s, triggered by %lu (%s)", packet.v5_packet.name, (unsigned long) packet.v5_packet.pid, strna(p));
free(p);
diff --git a/src/cgroup-show.c b/src/cgroup-show.c
index bc9c216329..03c942c66e 100644
--- a/src/cgroup-show.c
+++ b/src/cgroup-show.c
@@ -133,7 +133,7 @@ static int show_cgroup_one_by_path(const char *path, const char *prefix, unsigne
for (i = 0; i < n; i++) {
char *t = NULL;
- get_process_cmdline(pids[i], n_columns, &t);
+ get_process_cmdline(pids[i], n_columns, true, &t);
printf("%s%s %*lu %s\n",
prefix,
diff --git a/src/journal/Makefile b/src/journal/Makefile
new file mode 120000
index 0000000000..d0b0e8e008
--- /dev/null
+++ b/src/journal/Makefile
@@ -0,0 +1 @@
+../Makefile \ No newline at end of file
diff --git a/src/journal/journal-def.h b/src/journal/journal-def.h
new file mode 100644
index 0000000000..0d865ae2a2
--- /dev/null
+++ b/src/journal/journal-def.h
@@ -0,0 +1,139 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foojournaldefhfoo
+#define foojournaldefhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+
+#include "macro.h"
+#include "sd-id128.h"
+
+typedef struct Header Header;
+typedef struct ObjectHeader ObjectHeader;
+typedef union Object Object;
+typedef struct DataObject DataObject;
+typedef struct EntryObject EntryObject;
+typedef struct HashTableObject HashTableObject;
+typedef struct BisectTableObject BisectTableObject;
+typedef struct EntryItem EntryItem;
+typedef struct HashItem HashItem;
+
+/* Object types */
+enum {
+ OBJECT_UNUSED,
+ OBJECT_DATA,
+ OBJECT_ENTRY,
+ OBJECT_HASH_TABLE,
+ OBJECT_BISECT_TABLE
+};
+
+_packed_ struct ObjectHeader {
+ uint8_t type;
+ uint8_t reserved[3];
+ uint64_t size;
+ uint8_t payload[];
+};
+
+_packed_ struct DataObject {
+ ObjectHeader object;
+ uint64_t hash;
+ uint64_t head_entry_offset;
+ uint64_t tail_entry_offset;
+ uint64_t prev_hash_offset;
+ uint64_t next_hash_offset;
+ uint8_t payload[];
+};
+
+_packed_ struct EntryItem {
+ uint64_t object_offset;
+ uint64_t prev_entry_offset;
+ uint64_t next_entry_offset;
+};
+
+_packed_ struct EntryObject {
+ ObjectHeader object;
+ uint64_t seqnum;
+ uint64_t realtime;
+ uint64_t monotonic;
+ uint64_t prev_entry_offset;
+ uint64_t next_entry_offset;
+ EntryItem items[];
+};
+
+_packed_ struct HashItem {
+ uint64_t head_hash_offset;
+ uint64_t tail_hash_offset;
+};
+
+_packed_ struct HashTableObject {
+ ObjectHeader object;
+ HashItem table[];
+};
+
+_packed_ struct BisectTableObject {
+ ObjectHeader object;
+ uint64_t table[];
+};
+
+union Object {
+ ObjectHeader object;
+ DataObject data;
+ EntryObject entry;
+ HashTableObject hash_table;
+ BisectTableObject bisect_table;
+};
+
+enum {
+ STATE_OFFLINE,
+ STATE_ONLINE,
+ STATE_ARCHIVED
+};
+
+_packed_ struct Header {
+ uint8_t signature[8]; /* "LPKSHHRH" */
+ uint32_t compatible_flags;
+ uint32_t incompatible_flags;
+ uint32_t state;
+ uint8_t reserved[4];
+ sd_id128_t file_id;
+ sd_id128_t machine_id;
+ sd_id128_t boot_id;
+ uint64_t arena_offset;
+ uint64_t arena_size;
+ uint64_t arena_max_size;
+ uint64_t arena_min_size;
+ uint64_t arena_keep_free;
+ uint64_t hash_table_offset; /* for looking up data objects */
+ uint64_t hash_table_size;
+ uint64_t bisect_table_offset; /* for looking up entry objects */
+ uint64_t bisect_table_size;
+ uint64_t head_object_offset;
+ uint64_t tail_object_offset;
+ uint64_t head_entry_offset;
+ uint64_t tail_entry_offset;
+ uint64_t last_bisect_offset;
+ uint64_t n_objects;
+ uint64_t seqnum_base;
+ uint64_t seqnum;
+};
+
+#endif
diff --git a/src/journal/journal-private.h b/src/journal/journal-private.h
new file mode 100644
index 0000000000..863a39893b
--- /dev/null
+++ b/src/journal/journal-private.h
@@ -0,0 +1,53 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foojournalprivatehfoo
+#define foojournalprivatehfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+
+#include "sd-journal.h"
+#include "journal-def.h"
+#include "util.h"
+
+typedef struct JournalFile JournalFile;
+
+int journal_file_open(sd_journal *j, const char *fname, int flags, mode_t mode, JournalFile **ret);
+
+void journal_file_close(JournalFile *j);
+
+int journal_file_move_to_object(JournalFile *f, uint64_t offset, Object **ret);
+
+uint64_t journal_file_entry_n_items(Object *o);
+
+int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, Object **ret, uint64_t *offset);
+
+int journal_file_move_to_entry(JournalFile *f, uint64_t seqnum, Object **ret, uint64_t *offset);
+
+int journal_file_find_first_entry(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset);
+int journal_file_find_last_entry(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset);
+
+int journal_file_next_entry(JournalFile *f, Object *o, Object **ret, uint64_t *offset);
+int journal_file_prev_entry(JournalFile *f, Object *o, Object **ret, uint64_t *offset);
+
+void journal_file_dump(JournalFile *f);
+
+#endif
diff --git a/src/journal/journalctl.c b/src/journal/journalctl.c
new file mode 100644
index 0000000000..838e8436e4
--- /dev/null
+++ b/src/journal/journalctl.c
@@ -0,0 +1,91 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <errno.h>
+#include <stddef.h>
+
+#include "journal-private.h"
+
+int main(int argc, char *argv[]) {
+ int r;
+ JournalFile *f;
+ Object *o = NULL;
+
+ log_parse_environment();
+ log_open();
+
+ r = journal_file_open(NULL, "/var/log/journal/system.journal", O_RDONLY, 0644, &f);
+ if (r == -ENOENT)
+ r = journal_file_open(NULL, "/run/log/journal/system.journal", O_RDONLY, 0644, &f);
+
+ if (r < 0) {
+ log_error("Failed to open journal: %s", strerror(-r));
+ return EXIT_FAILURE;
+ }
+
+ for (;;) {
+ uint64_t offset;
+ uint64_t n, i;
+
+ r = journal_file_next_entry(f, o, &o, &offset);
+ if (r < 0) {
+ log_error("Failed to read journal: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (r == 0)
+ break;
+
+ printf("entry: %llu\n", (unsigned long long) le64toh(o->entry.seqnum));
+
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++) {
+ uint64_t p, l;
+
+ p = le64toh(o->entry.items[i].object_offset);
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0) {
+ log_error("Failed to move to data: %s", strerror(-r));
+ goto finish;
+ }
+
+ if (le64toh(o->object.type) != OBJECT_DATA) {
+ log_error("Invalid file");
+ goto finish;
+ }
+
+ l = o->object.size - offsetof(Object, data.payload);
+ printf("\t[%.*s]\n", (int) l, o->data.payload);
+
+ r = journal_file_move_to_object(f, offset, &o);
+ if (r < 0) {
+ log_error("Failed to move back to entry: %s", strerror(-r));
+ goto finish;
+ }
+ }
+ }
+
+finish:
+ journal_file_close(f);
+
+ return 0;
+}
diff --git a/src/journal/journald.c b/src/journal/journald.c
new file mode 100644
index 0000000000..9297ca6fb7
--- /dev/null
+++ b/src/journal/journald.c
@@ -0,0 +1,460 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#include <errno.h>
+#include <sys/signalfd.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "hashmap.h"
+#include "journal-private.h"
+#include "sd-daemon.h"
+#include "socket-util.h"
+
+typedef struct Server {
+ int syslog_fd;
+ int epoll_fd;
+ int signal_fd;
+
+ JournalFile *system_journal;
+ Hashmap *user_journals;
+} Server;
+
+static void process_message(Server *s, const char *buf, struct ucred *ucred, struct timeval *tv) {
+ char *message = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
+ *source_time = NULL, *boot_id = NULL, *machine_id = NULL,
+ *comm = NULL, *cmdline = NULL, *hostname = NULL,
+ *audit_session = NULL, *audit_loginuid = NULL,
+ *syslog_priority = NULL, *syslog_facility = NULL,
+ *exe = NULL;
+ dual_timestamp ts;
+ struct iovec iovec[15];
+ unsigned n = 0;
+ char idbuf[33];
+ sd_id128_t id;
+ int r;
+ char *t;
+ int priority = LOG_USER | LOG_INFO;
+
+ dual_timestamp_get(&ts);
+
+ parse_syslog_priority((char**) &buf, &priority);
+ skip_syslog_date((char**) &buf);
+
+ if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_priority);
+
+ if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], syslog_facility);
+
+ message = strappend("MESSAGE=", buf);
+ if (message)
+ IOVEC_SET_STRING(iovec[n++], message);
+
+ if (ucred) {
+ uint32_t session;
+ uid_t loginuid;
+
+ if (asprintf(&pid, "PID=%lu", (unsigned long) ucred->pid) >= 0)
+ IOVEC_SET_STRING(iovec[n++], pid);
+
+ if (asprintf(&uid, "UID=%lu", (unsigned long) ucred->uid) >= 0)
+ IOVEC_SET_STRING(iovec[n++], uid);
+
+ if (asprintf(&gid, "GID=%lu", (unsigned long) ucred->gid) >= 0)
+ IOVEC_SET_STRING(iovec[n++], gid);
+
+ r = get_process_comm(ucred->pid, &t);
+ if (r >= 0) {
+ comm = strappend("COMM=", t);
+ if (comm)
+ IOVEC_SET_STRING(iovec[n++], comm);
+ free(t);
+ }
+
+ r = get_process_exe(ucred->pid, &t);
+ if (r >= 0) {
+ exe = strappend("EXE=", t);
+ if (comm)
+ IOVEC_SET_STRING(iovec[n++], exe);
+ free(t);
+ }
+
+ r = get_process_cmdline(ucred->pid, LINE_MAX, false, &t);
+ if (r >= 0) {
+ cmdline = strappend("CMDLINE=", t);
+ if (cmdline)
+ IOVEC_SET_STRING(iovec[n++], cmdline);
+ free(t);
+ }
+
+ r = audit_session_from_pid(ucred->pid, &session);
+ if (r >= 0)
+ if (asprintf(&audit_session, "AUDIT_SESSION=%lu", (unsigned long) session) >= 0)
+ IOVEC_SET_STRING(iovec[n++], audit_session);
+
+ r = audit_loginuid_from_pid(ucred->pid, &loginuid);
+ if (r >= 0)
+ if (asprintf(&audit_loginuid, "AUDIT_LOGINUID=%lu", (unsigned long) loginuid) >= 0)
+ IOVEC_SET_STRING(iovec[n++], audit_loginuid);
+ }
+
+ if (tv) {
+ if (asprintf(&source_time, "SOURCE_REALTIME_TIMESTAMP=%llu",
+ (unsigned long long) timeval_load(tv)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], source_time);
+ }
+
+ r = sd_id128_get_boot(&id);
+ if (r >= 0)
+ if (asprintf(&boot_id, "BOOT_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], boot_id);
+
+ r = sd_id128_get_machine(&id);
+ if (r >= 0)
+ if (asprintf(&machine_id, "MACHINE_ID=%s", sd_id128_to_string(id, idbuf)) >= 0)
+ IOVEC_SET_STRING(iovec[n++], machine_id);
+
+ t = gethostname_malloc();
+ if (t) {
+ hostname = strappend("HOSTNAME=", t);
+ if (hostname)
+ IOVEC_SET_STRING(iovec[n++], hostname);
+ free(t);
+ }
+
+ r = journal_file_append_entry(s->system_journal, &ts, iovec, n, NULL, NULL);
+ if (r < 0)
+ log_error("Failed to write entry: %s", strerror(-r));
+
+
+ free(message);
+ free(pid);
+ free(uid);
+ free(gid);
+ free(comm);
+ free(cmdline);
+ free(source_time);
+ free(boot_id);
+ free(machine_id);
+ free(hostname);
+ free(audit_session);
+ free(audit_loginuid);
+ free(syslog_facility);
+ free(syslog_priority);
+}
+
+static int process_event(Server *s, struct epoll_event *ev) {
+ assert(s);
+
+ if (ev->events != EPOLLIN) {
+ log_info("Got invalid event from epoll.");
+ return -EIO;
+ }
+
+ if (ev->data.fd == s->signal_fd) {
+ struct signalfd_siginfo sfsi;
+ ssize_t n;
+
+ n = read(s->signal_fd, &sfsi, sizeof(sfsi));
+ if (n != sizeof(sfsi)) {
+
+ if (n >= 0)
+ return -EIO;
+
+ if (errno == EINTR || errno == EAGAIN)
+ return 0;
+
+ return -errno;
+ }
+
+ log_debug("Received SIG%s", signal_to_string(sfsi.ssi_signo));
+ return 0;
+
+ } else {
+ for (;;) {
+ char buf[LINE_MAX+1];
+ struct msghdr msghdr;
+ struct iovec iovec;
+ struct ucred *ucred = NULL;
+ struct timeval *tv = NULL;
+ struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr cmsghdr;
+ uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
+ CMSG_SPACE(sizeof(struct timeval))];
+ } control;
+ ssize_t n;
+ char *e;
+
+ zero(iovec);
+ iovec.iov_base = buf;
+ iovec.iov_len = sizeof(buf)-1;
+
+ zero(control);
+ zero(msghdr);
+ msghdr.msg_iov = &iovec;
+ msghdr.msg_iovlen = 1;
+ msghdr.msg_control = &control;
+ msghdr.msg_controllen = sizeof(control);
+
+ n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
+ if (n < 0) {
+
+ if (errno == EINTR || errno == EAGAIN)
+ return 1;
+
+ log_error("recvmsg() failed: %m");
+ return -errno;
+ }
+
+ for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
+
+ if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_CREDENTIALS &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred)))
+ ucred = (struct ucred*) CMSG_DATA(cmsg);
+ else if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SO_TIMESTAMP &&
+ cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
+ tv = (struct timeval*) CMSG_DATA(cmsg);
+ }
+
+ e = memchr(buf, '\n', n);
+ if (e)
+ *e = 0;
+ else
+ buf[n] = 0;
+
+ process_message(s, strstrip(buf), ucred, tv);
+ }
+ }
+
+ return 1;
+}
+
+
+static int open_system_journal(JournalFile **f) {
+ int r;
+
+ r = journal_file_open(NULL, "/var/log/journal/system.journal", O_RDWR|O_CREAT, 0644, f);
+ if (r == -ENOENT) {
+ mkdir_p("/run/log/journal", 0755);
+
+ r = journal_file_open(NULL, "/run/log/journal/system.journal", O_RDWR|O_CREAT, 0644, f);
+ }
+
+ return r;
+}
+
+static int server_init(Server *s) {
+ int n, one, r;
+ struct epoll_event ev;
+ sigset_t mask;
+
+ assert(s);
+
+ zero(*s);
+ s->syslog_fd = s->signal_fd = -1;
+
+ s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (s->epoll_fd < 0) {
+ log_error("Failed to create epoll object: %m");
+ return -errno;
+ }
+
+ n = sd_listen_fds(true);
+ if (n < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
+ return n;
+ }
+
+ if (n > 1) {
+ log_error("Too many file descriptors passed.");
+ return -EINVAL;
+ }
+
+ if (n == 1)
+ s->syslog_fd = SD_LISTEN_FDS_START;
+ else {
+ union sockaddr_union sa;
+
+ s->syslog_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
+ if (s->syslog_fd < 0) {
+ log_error("socket() failed: %m");
+ return -errno;
+ }
+
+ zero(sa);
+ sa.un.sun_family = AF_UNIX;
+ strncpy(sa.un.sun_path, "/run/systemd/syslog", sizeof(sa.un.sun_path));
+
+ unlink(sa.un.sun_path);
+
+ r = bind(s->syslog_fd, &sa.sa, sizeof(sa.un));
+ if (r < 0) {
+ log_error("bind() failed: %m");
+ return -errno;
+ }
+
+ chmod(sa.un.sun_path, 0666);
+ }
+
+ one = 1;
+ r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_PASSCRED failed: %m");
+ return -errno;
+ }
+
+ one = 1;
+ r = setsockopt(s->syslog_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
+ if (r < 0) {
+ log_error("SO_TIMESTAMP failed: %m");
+ return -errno;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->syslog_fd;
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->syslog_fd, &ev) < 0) {
+ log_error("Failed to add server fd to epoll object: %m");
+ return -errno;
+ }
+
+ s->user_journals = hashmap_new(trivial_hash_func, trivial_compare_func);
+ if (!s->user_journals) {
+ log_error("Out of memory.");
+ return -ENOMEM;
+ }
+
+ r = open_system_journal(&s->system_journal);
+ if (r < 0) {
+ log_error("Failed to open journal: %s", strerror(-r));
+ return r;
+ }
+
+ assert_se(sigemptyset(&mask) == 0);
+ sigset_add_many(&mask, SIGINT, SIGTERM, -1);
+ assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
+
+ s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (s->signal_fd < 0) {
+ log_error("signalfd(): %m");
+ return -errno;
+ }
+
+ zero(ev);
+ ev.events = EPOLLIN;
+ ev.data.fd = s->signal_fd;
+
+ if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, s->signal_fd, &ev) < 0) {
+ log_error("epoll_ctl(): %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static void server_done(Server *s) {
+ JournalFile *f;
+ assert(s);
+
+ if (s->system_journal)
+ journal_file_close(s->system_journal);
+
+ while ((f = hashmap_steal_first(s->user_journals)))
+ journal_file_close(f);
+
+ hashmap_free(s->user_journals);
+
+ if (s->epoll_fd >= 0)
+ close_nointr_nofail(s->epoll_fd);
+
+ if (s->signal_fd >= 0)
+ close_nointr_nofail(s->signal_fd);
+
+ if (s->syslog_fd >= 0)
+ close_nointr_nofail(s->syslog_fd);
+}
+
+int main(int argc, char *argv[]) {
+ Server server;
+ int r;
+
+ /* if (getppid() != 1) { */
+ /* log_error("This program should be invoked by init only."); */
+ /* return EXIT_FAILURE; */
+ /* } */
+
+ if (argc > 1) {
+ log_error("This program does not take arguments.");
+ return EXIT_FAILURE;
+ }
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ r = server_init(&server);
+ if (r < 0)
+ goto finish;
+
+ log_debug("systemd-journald running as pid %lu", (unsigned long) getpid());
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing messages...");
+
+ for (;;) {
+ struct epoll_event event;
+
+ r = epoll_wait(server.epoll_fd, &event, 1, -1);
+ if (r < 0) {
+
+ if (errno == EINTR)
+ continue;
+
+ log_error("epoll_wait() failed: %m");
+ r = -errno;
+ goto finish;
+ } else if (r == 0)
+ break;
+
+ r = process_event(&server, &event);
+ if (r < 0)
+ goto finish;
+ else if (r == 0)
+ break;
+ }
+
+finish:
+ sd_notify(false,
+ "STATUS=Shutting down...");
+
+ server_done(&server);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/journal/lookup3.c b/src/journal/lookup3.c
new file mode 100644
index 0000000000..b90093a5e2
--- /dev/null
+++ b/src/journal/lookup3.c
@@ -0,0 +1,1003 @@
+/* Slightly modified by Lennart Poettering, to avoid name clashes, and
+ * unexport a few functions. */
+
+#include "lookup3.h"
+
+/*
+-------------------------------------------------------------------------------
+lookup3.c, by Bob Jenkins, May 2006, Public Domain.
+
+These are functions for producing 32-bit hashes for hash table lookup.
+hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
+are externally useful functions. Routines to test the hash are included
+if SELF_TEST is defined. You can use this free for any purpose. It's in
+the public domain. It has no warranty.
+
+You probably want to use hashlittle(). hashlittle() and hashbig()
+hash byte arrays. hashlittle() is is faster than hashbig() on
+little-endian machines. Intel and AMD are little-endian machines.
+On second thought, you probably want hashlittle2(), which is identical to
+hashlittle() except it returns two 32-bit hashes for the price of one.
+You could implement hashbig2() if you wanted but I haven't bothered here.
+
+If you want to find a hash of, say, exactly 7 integers, do
+ a = i1; b = i2; c = i3;
+ mix(a,b,c);
+ a += i4; b += i5; c += i6;
+ mix(a,b,c);
+ a += i7;
+ final(a,b,c);
+then use c as the hash value. If you have a variable length array of
+4-byte integers to hash, use hashword(). If you have a byte array (like
+a character string), use hashlittle(). If you have several byte arrays, or
+a mix of things, see the comments above hashlittle().
+
+Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
+then mix those integers. This is fast (you can do a lot more thorough
+mixing with 12*3 instructions on 3 integers than you can with 3 instructions
+on 1 byte), but shoehorning those bytes into integers efficiently is messy.
+-------------------------------------------------------------------------------
+*/
+/* #define SELF_TEST 1 */
+
+#include <stdio.h> /* defines printf for tests */
+#include <time.h> /* defines time_t for timings in the test */
+#include <stdint.h> /* defines uint32_t etc */
+#include <sys/param.h> /* attempt to define endianness */
+#ifdef linux
+# include <endian.h> /* attempt to define endianness */
+#endif
+
+/*
+ * My best guess at if you are big-endian or little-endian. This may
+ * need adjustment.
+ */
+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
+ __BYTE_ORDER == __LITTLE_ENDIAN) || \
+ (defined(i386) || defined(__i386__) || defined(__i486__) || \
+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
+# define HASH_LITTLE_ENDIAN 1
+# define HASH_BIG_ENDIAN 0
+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
+ __BYTE_ORDER == __BIG_ENDIAN) || \
+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 1
+#else
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 0
+#endif
+
+#define hashsize(n) ((uint32_t)1<<(n))
+#define hashmask(n) (hashsize(n)-1)
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+ 4 6 8 16 19 4
+ 9 15 3 18 27 15
+ 14 9 3 7 17 3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta. I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche. There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a. The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism. Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism. I did what I could. Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+ a -= c; a ^= rot(c, 4); c += b; \
+ b -= a; b ^= rot(a, 6); a += c; \
+ c -= b; c ^= rot(b, 8); b += a; \
+ a -= c; a ^= rot(c,16); c += b; \
+ b -= a; b ^= rot(a,19); a += c; \
+ c -= b; c ^= rot(b, 4); b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different. This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+ 4 8 15 26 3 22 24
+ 10 8 15 26 3 22 24
+ 11 8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+ c ^= b; c -= rot(b,14); \
+ a ^= c; a -= rot(c,11); \
+ b ^= a; b -= rot(a,25); \
+ c ^= b; c -= rot(b,16); \
+ a ^= c; a -= rot(c,4); \
+ b ^= a; b -= rot(a,14); \
+ c ^= b; c -= rot(b,24); \
+}
+
+/*
+--------------------------------------------------------------------
+ This works on all machines. To be useful, it requires
+ -- that the key be an array of uint32_t's, and
+ -- that the length be the number of uint32_t's in the key
+
+ The function hashword() is identical to hashlittle() on little-endian
+ machines, and identical to hashbig() on big-endian machines,
+ except that the length has to be measured in uint32_ts rather than in
+ bytes. hashlittle() is more complicated than hashword() only because
+ hashlittle() has to dance around fitting the key bytes into registers.
+--------------------------------------------------------------------
+*/
+uint32_t jenkins_hashword(
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t initval) /* the previous hash, or an arbitrary value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ return c;
+}
+
+
+/*
+--------------------------------------------------------------------
+hashword2() -- same as hashword(), but take two seeds and return two
+32-bit values. pc and pb must both be nonnull, and *pc and *pb must
+both be initialized with seeds. If you pass in (*pb)==0, the output
+(*pc) will be the same as the return value from hashword().
+--------------------------------------------------------------------
+*/
+void jenkins_hashword2 (
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t *pc, /* IN: seed OUT: primary hash value */
+uint32_t *pb) /* IN: more seed OUT: secondary hash value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc;
+ c += *pb;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ *pc=c; *pb=b;
+}
+
+
+/*
+-------------------------------------------------------------------------------
+hashlittle() -- hash a variable-length key into a 32-bit value
+ k : the key (the unaligned variable-length array of bytes)
+ length : the length of the key, counting by bytes
+ initval : can be any 4-byte value
+Returns a 32-bit value. Every bit of the key affects every bit of
+the return value. Two keys differing by one or two bits will have
+totally different hash values.
+
+The best hash table sizes are powers of 2. There is no need to do
+mod a prime (mod is sooo slow!). If you need less than 32 bits,
+use a bitmask. For example, if you need only 10 bits, do
+ h = (h & hashmask(10));
+In which case, the hash table should have hashsize(10) elements.
+
+If you are hashing n strings (uint8_t **)k, do it like this:
+ for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+
+By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
+code any way you wish, private, educational, or commercial. It's free.
+
+Use for hash table lookup, or anything where one collision in 2^^32 is
+acceptable. Do NOT use for cryptographic purposes.
+-------------------------------------------------------------------------------
+*/
+
+uint32_t jenkins_hashlittle( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : return c;
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : return c; /* zero length requires no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+
+/*
+ * hashlittle2: return 2 32-bit hash values
+ *
+ * This is identical to hashlittle(), except it returns two 32-bit hash
+ * values instead of just one. This is good enough for hash table
+ * lookup with 2^^64 buckets, or if you want a second hash if you're not
+ * happy with the first, or if you want a probably-unique 64-bit ID for
+ * the key. *pc is better mixed than *pb, so use *pc first. If you want
+ * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
+ */
+void jenkins_hashlittle2(
+ const void *key, /* the key to hash */
+ size_t length, /* length of the key */
+ uint32_t *pc, /* IN: primary initval, OUT: primary hash */
+ uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc;
+ c += *pb;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+ }
+
+ final(a,b,c);
+ *pc=c; *pb=b;
+}
+
+
+
+/*
+ * hashbig():
+ * This is the same as hashword() on big-endian machines. It is different
+ * from hashlittle() on all machines. hashbig() takes advantage of
+ * big-endian byte ordering.
+ */
+uint32_t jenkins_hashbig( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c;
+ union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]<<8" actually reads beyond the end of the string, but
+ * then shifts out the part it's not allowed to read. Because the
+ * string is aligned, the illegal read is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff00; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff0000; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff000000; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff00; break;
+ case 2 : a+=k[0]&0xffff0000; break;
+ case 1 : a+=k[0]&0xff000000; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<8; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<16; /* fall through */
+ case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */
+ case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */
+ case 1 : a+=((uint32_t)k8[0])<<24; break;
+ case 0 : return c;
+ }
+
+#endif /* !VALGRIND */
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += ((uint32_t)k[0])<<24;
+ a += ((uint32_t)k[1])<<16;
+ a += ((uint32_t)k[2])<<8;
+ a += ((uint32_t)k[3]);
+ b += ((uint32_t)k[4])<<24;
+ b += ((uint32_t)k[5])<<16;
+ b += ((uint32_t)k[6])<<8;
+ b += ((uint32_t)k[7]);
+ c += ((uint32_t)k[8])<<24;
+ c += ((uint32_t)k[9])<<16;
+ c += ((uint32_t)k[10])<<8;
+ c += ((uint32_t)k[11]);
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[11];
+ case 11: c+=((uint32_t)k[10])<<8;
+ case 10: c+=((uint32_t)k[9])<<16;
+ case 9 : c+=((uint32_t)k[8])<<24;
+ case 8 : b+=k[7];
+ case 7 : b+=((uint32_t)k[6])<<8;
+ case 6 : b+=((uint32_t)k[5])<<16;
+ case 5 : b+=((uint32_t)k[4])<<24;
+ case 4 : a+=k[3];
+ case 3 : a+=((uint32_t)k[2])<<8;
+ case 2 : a+=((uint32_t)k[1])<<16;
+ case 1 : a+=((uint32_t)k[0])<<24;
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+
+#ifdef SELF_TEST
+
+/* used for timings */
+void driver1()
+{
+ uint8_t buf[256];
+ uint32_t i;
+ uint32_t h=0;
+ time_t a,z;
+
+ time(&a);
+ for (i=0; i<256; ++i) buf[i] = 'x';
+ for (i=0; i<1; ++i)
+ {
+ h = hashlittle(&buf[0],1,h);
+ }
+ time(&z);
+ if (z-a > 0) printf("time %d %.8x\n", z-a, h);
+}
+
+/* check that every input bit changes every output bit half the time */
+#define HASHSTATE 1
+#define HASHLEN 1
+#define MAXPAIR 60
+#define MAXLEN 70
+void driver2()
+{
+ uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
+ uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
+ uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
+ uint32_t x[HASHSTATE],y[HASHSTATE];
+ uint32_t hlen;
+
+ printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
+ for (hlen=0; hlen < MAXLEN; ++hlen)
+ {
+ z=0;
+ for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */
+ {
+ for (j=0; j<8; ++j) /*------------------------ for each input bit, */
+ {
+ for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
+ {
+ for (l=0; l<HASHSTATE; ++l)
+ e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
+
+ /*---- check that every output bit is affected by that input bit */
+ for (k=0; k<MAXPAIR; k+=2)
+ {
+ uint32_t finished=1;
+ /* keys have one bit different */
+ for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;}
+ /* have a and b be two keys differing in only one bit */
+ a[i] ^= (k<<j);
+ a[i] ^= (k>>(8-j));
+ c[0] = hashlittle(a, hlen, m);
+ b[i] ^= ((k+1)<<j);
+ b[i] ^= ((k+1)>>(8-j));
+ d[0] = hashlittle(b, hlen, m);
+ /* check every bit is 1, 0, set, and not set at least once */
+ for (l=0; l<HASHSTATE; ++l)
+ {
+ e[l] &= (c[l]^d[l]);
+ f[l] &= ~(c[l]^d[l]);
+ g[l] &= c[l];
+ h[l] &= ~c[l];
+ x[l] &= d[l];
+ y[l] &= ~d[l];
+ if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
+ }
+ if (finished) break;
+ }
+ if (k>z) z=k;
+ if (k==MAXPAIR)
+ {
+ printf("Some bit didn't change: ");
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x ",
+ e[0],f[0],g[0],h[0],x[0],y[0]);
+ printf("i %d j %d m %d len %d\n", i, j, m, hlen);
+ }
+ if (z==MAXPAIR) goto done;
+ }
+ }
+ }
+ done:
+ if (z < MAXPAIR)
+ {
+ printf("Mix success %2d bytes %2d initvals ",i,m);
+ printf("required %d trials\n", z/2);
+ }
+ }
+ printf("\n");
+}
+
+/* Check for reading beyond the end of the buffer and alignment problems */
+void driver3()
+{
+ uint8_t buf[MAXLEN+20], *b;
+ uint32_t len;
+ uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
+ uint32_t h;
+ uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
+ uint32_t i;
+ uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
+ uint32_t j;
+ uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
+ uint32_t ref,x,y;
+ uint8_t *p;
+
+ printf("Endianness. These lines should all be the same (for values filled in):\n");
+ printf("%.8x %.8x %.8x\n",
+ hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
+ p = q;
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qq[1];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqq[2];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqqq[3];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ printf("\n");
+
+ /* check that hashlittle2 and hashlittle produce the same results */
+ i=47; j=0;
+ hashlittle2(q, sizeof(q), &i, &j);
+ if (hashlittle(q, sizeof(q), 47) != i)
+ printf("hashlittle2 and hashlittle mismatch\n");
+
+ /* check that hashword2 and hashword produce the same results */
+ len = 0xdeadbeef;
+ i=47, j=0;
+ hashword2(&len, 1, &i, &j);
+ if (hashword(&len, 1, 47) != i)
+ printf("hashword2 and hashword mismatch %x %x\n",
+ i, hashword(&len, 1, 47));
+
+ /* check hashlittle doesn't read before or after the ends of the string */
+ for (h=0, b=buf+1; h<8; ++h, ++b)
+ {
+ for (i=0; i<MAXLEN; ++i)
+ {
+ len = i;
+ for (j=0; j<i; ++j) *(b+j)=0;
+
+ /* these should all be equal */
+ ref = hashlittle(b, len, (uint32_t)1);
+ *(b+i)=(uint8_t)~0;
+ *(b-1)=(uint8_t)~0;
+ x = hashlittle(b, len, (uint32_t)1);
+ y = hashlittle(b, len, (uint32_t)1);
+ if ((ref != x) || (ref != y))
+ {
+ printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
+ h, i);
+ }
+ }
+ }
+}
+
+/* check for problems with nulls */
+ void driver4()
+{
+ uint8_t buf[1];
+ uint32_t h,i,state[HASHSTATE];
+
+
+ buf[0] = ~0;
+ for (i=0; i<HASHSTATE; ++i) state[i] = 1;
+ printf("These should all be different\n");
+ for (i=0, h=0; i<8; ++i)
+ {
+ h = hashlittle(buf, 0, h);
+ printf("%2ld 0-byte strings, hash is %.8x\n", i, h);
+ }
+}
+
+void driver5()
+{
+ uint32_t b,c;
+ b=0, c=0, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* deadbeef deadbeef */
+ b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* bd5b7dde deadbeef */
+ b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* 9c093ccd bd5b7dde */
+ b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* 17770551 ce7226e6 */
+ b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* e3607cae bd371de4 */
+ b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b);
+ printf("hash is %.8lx %.8lx\n", c, b); /* cd628161 6cbea4b3 */
+ c = hashlittle("Four score and seven years ago", 30, 0);
+ printf("hash is %.8lx\n", c); /* 17770551 */
+ c = hashlittle("Four score and seven years ago", 30, 1);
+ printf("hash is %.8lx\n", c); /* cd628161 */
+}
+
+
+int main()
+{
+ driver1(); /* test that the key is hashed: used for timings */
+ driver2(); /* test that whole key is hashed thoroughly */
+ driver3(); /* test that nothing but the key is hashed */
+ driver4(); /* test hashing multiple buffers (all buffers are null) */
+ driver5(); /* test the hash against known vectors */
+ return 1;
+}
+
+#endif /* SELF_TEST */
diff --git a/src/journal/lookup3.h b/src/journal/lookup3.h
new file mode 100644
index 0000000000..31cc2f57b0
--- /dev/null
+++ b/src/journal/lookup3.h
@@ -0,0 +1,25 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foolookup3hfoo
+#define foolookup3hfoo
+
+#include <inttypes.h>
+#include <sys/types.h>
+
+uint32_t jenkins_hashword(const uint32_t *k, size_t length, uint32_t initval);
+void jenkins_hashword2(const uint32_t *k, size_t length, uint32_t *pc, uint32_t *pb);
+
+uint32_t jenkins_hashlittle(const void *key, size_t length, uint32_t initval);
+void jenkins_hashlittle2(const void *key, size_t length, uint32_t *pc, uint32_t *pb);
+
+uint32_t jenkins_hashbig(const void *key, size_t length, uint32_t initval);
+
+static inline uint64_t hash64(const void *data, size_t length) {
+ uint32_t a = 0, b = 0;
+
+ jenkins_hashlittle2(data, length, &a, &b);
+
+ return ((uint64_t) a << 32ULL) | (uint64_t) b;
+}
+
+#endif
diff --git a/src/journal/sd-journal.c b/src/journal/sd-journal.c
new file mode 100644
index 0000000000..f1dd92927c
--- /dev/null
+++ b/src/journal/sd-journal.c
@@ -0,0 +1,1333 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <sys/mman.h>
+#include <errno.h>
+#include <sys/uio.h>
+#include <unistd.h>
+#include <sys/statvfs.h>
+#include <fcntl.h>
+#include <stddef.h>
+
+#include "sd-journal.h"
+#include "journal-def.h"
+#include "journal-private.h"
+#include "lookup3.h"
+#include "list.h"
+
+#define DEFAULT_ARENA_MAX_SIZE (16ULL*1024ULL*1024ULL*1024ULL)
+#define DEFAULT_ARENA_MIN_SIZE (256ULL*1024ULL)
+#define DEFAULT_ARENA_KEEP_FREE (1ULL*1024ULL*1024ULL)
+
+#define DEFAULT_HASH_TABLE_SIZE (2047ULL*16ULL)
+#define DEFAULT_BISECT_TABLE_SIZE ((DEFAULT_ARENA_MAX_SIZE/(64ULL*1024ULL))*8ULL)
+
+#define DEFAULT_WINDOW_SIZE (128ULL*1024ULL*1024ULL)
+
+struct JournalFile {
+ sd_journal *journal;
+
+ int fd;
+ char *path;
+ struct stat last_stat;
+ int prot;
+ bool writable;
+
+ Header *header;
+
+ HashItem *hash_table;
+ void *hash_table_window;
+ uint64_t hash_table_window_size;
+
+ uint64_t *bisect_table;
+ void *bisect_table_window;
+ uint64_t bisect_table_window_size;
+
+ void *window;
+ uint64_t window_offset;
+ uint64_t window_size;
+
+ Object *current;
+ uint64_t current_offset;
+
+ LIST_FIELDS(JournalFile, files);
+};
+
+struct sd_journal {
+ LIST_HEAD(JournalFile, files);
+};
+
+static const char signature[] = { 'L', 'P', 'K', 'S', 'H', 'H', 'R', 'H' };
+
+#define ALIGN64(x) (((x) + 7ULL) & ~7ULL)
+
+void journal_file_close(JournalFile *f) {
+ assert(f);
+
+ if (f->journal)
+ LIST_REMOVE(JournalFile, files, f->journal->files, f);
+
+ if (f->fd >= 0)
+ close_nointr_nofail(f->fd);
+
+ if (f->header)
+ munmap(f->header, PAGE_ALIGN(sizeof(Header)));
+
+ if (f->hash_table_window)
+ munmap(f->hash_table_window, f->hash_table_window_size);
+
+ if (f->bisect_table_window)
+ munmap(f->bisect_table_window, f->bisect_table_window_size);
+
+ if (f->window)
+ munmap(f->window, f->window_size);
+
+ free(f->path);
+ free(f);
+}
+
+static int journal_file_init_header(JournalFile *f) {
+ Header h;
+ ssize_t k;
+ int r;
+
+ assert(f);
+
+ zero(h);
+ memcpy(h.signature, signature, 8);
+ h.arena_offset = htole64(ALIGN64(sizeof(h)));
+ h.arena_max_size = htole64(DEFAULT_ARENA_MAX_SIZE);
+ h.arena_min_size = htole64(DEFAULT_ARENA_MIN_SIZE);
+ h.arena_keep_free = htole64(DEFAULT_ARENA_KEEP_FREE);
+
+ r = sd_id128_randomize(&h.file_id);
+ if (r < 0)
+ return r;
+
+ k = pwrite(f->fd, &h, sizeof(h), 0);
+ if (k < 0)
+ return -errno;
+
+ if (k != sizeof(h))
+ return -EIO;
+
+ return 0;
+}
+
+static int journal_file_refresh_header(JournalFile *f) {
+ int r;
+
+ assert(f);
+
+ r = sd_id128_get_machine(&f->header->machine_id);
+ if (r < 0)
+ return r;
+
+ r = sd_id128_get_boot(&f->header->boot_id);
+ if (r < 0)
+ return r;
+
+ f->header->state = htole32(STATE_ONLINE);
+ return 0;
+}
+
+static int journal_file_verify_header(JournalFile *f) {
+ assert(f);
+
+ if (memcmp(f->header, signature, 8))
+ return -EBADMSG;
+
+ if (f->header->incompatible_flags != 0)
+ return -EPROTONOSUPPORT;
+
+ if ((uint64_t) f->last_stat.st_size < (le64toh(f->header->arena_offset) + le64toh(f->header->arena_size)))
+ return -ENODATA;
+
+ if (f->writable) {
+ uint32_t state;
+ sd_id128_t machine_id;
+ int r;
+
+ r = sd_id128_get_machine(&machine_id);
+ if (r < 0)
+ return r;
+
+ if (!sd_id128_equal(machine_id, f->header->machine_id))
+ return -EHOSTDOWN;
+
+ state = le32toh(f->header->state);
+
+ if (state == STATE_ONLINE)
+ log_debug("Journal file %s is already online. Assuming unclean closing. Ignoring.", f->path);
+ else if (state == STATE_ARCHIVED)
+ return -ESHUTDOWN;
+ else if (state != STATE_OFFLINE)
+ log_debug("Journal file %s has unknown state %u. Ignoring.", f->path, state);
+ }
+
+ return 0;
+}
+
+static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
+ uint64_t asize;
+ uint64_t old_size, new_size;
+
+ assert(f);
+
+ if (offset < le64toh(f->header->arena_offset))
+ return -EINVAL;
+
+ new_size = PAGE_ALIGN(offset + size);
+
+ /* We assume that this file is not sparse, and we know that
+ * for sure, since we alway call posix_fallocate()
+ * ourselves */
+
+ old_size =
+ le64toh(f->header->arena_offset) +
+ le64toh(f->header->arena_size);
+
+ if (old_size >= new_size)
+ return 0;
+
+ asize = new_size - le64toh(f->header->arena_offset);
+
+ if (asize > le64toh(f->header->arena_min_size)) {
+ struct statvfs svfs;
+
+ if (fstatvfs(f->fd, &svfs) >= 0) {
+ uint64_t available;
+
+ available = svfs.f_bfree * svfs.f_bsize;
+
+ if (available >= f->header->arena_keep_free)
+ available -= f->header->arena_keep_free;
+ else
+ available = 0;
+
+ if (new_size - old_size > available)
+ return -E2BIG;
+ }
+ }
+
+ if (asize > le64toh(f->header->arena_max_size))
+ return -E2BIG;
+
+ if (posix_fallocate(f->fd, 0, new_size) < 0)
+ return -errno;
+
+ if (fstat(f->fd, &f->last_stat) < 0)
+ return -errno;
+
+ f->header->arena_size = htole64(asize);
+
+ return 0;
+}
+
+static int journal_file_map(
+ JournalFile *f,
+ uint64_t offset,
+ uint64_t size,
+ void **_window,
+ uint64_t *_woffset,
+ uint64_t *_wsize,
+ void **ret) {
+
+ uint64_t woffset, wsize;
+ void *window;
+
+ assert(f);
+ assert(size > 0);
+ assert(ret);
+
+ woffset = offset & ~((uint64_t) page_size() - 1ULL);
+ wsize = size + (offset - woffset);
+ wsize = PAGE_ALIGN(wsize);
+
+ window = mmap(NULL, wsize, f->prot, MAP_SHARED, f->fd, woffset);
+ if (window == MAP_FAILED)
+ return -errno;
+
+ if (_window)
+ *_window = window;
+
+ if (_woffset)
+ *_woffset = woffset;
+
+ if (_wsize)
+ *_wsize = wsize;
+
+ *ret = (uint8_t*) window + (offset - woffset);
+
+ return 0;
+}
+
+static int journal_file_move_to(JournalFile *f, uint64_t offset, uint64_t size, void **ret) {
+ void *p;
+ uint64_t delta;
+ int r;
+
+ assert(f);
+ assert(ret);
+
+ if (_likely_(f->window &&
+ f->window_offset <= offset &&
+ f->window_offset+f->window_size >= offset + size)) {
+
+ *ret = (uint8_t*) f->window + (offset - f->window_offset);
+ return 0;
+ }
+
+ if (f->window) {
+ if (munmap(f->window, f->window_size) < 0)
+ return -errno;
+
+ f->window = NULL;
+ f->window_size = f->window_offset = 0;
+ }
+
+ if (size < DEFAULT_WINDOW_SIZE) {
+ /* If the default window size is larger then what was
+ * asked for extend the mapping a bit in the hope to
+ * minimize needed remappings later on. We add half
+ * the window space before and half behind the
+ * requested mapping */
+
+ delta = PAGE_ALIGN((DEFAULT_WINDOW_SIZE - size) / 2);
+
+ if (offset < delta)
+ delta = offset;
+
+ offset -= delta;
+ size += (DEFAULT_WINDOW_SIZE - delta);
+ } else
+ delta = 0;
+
+ r = journal_file_map(f,
+ offset, size,
+ &f->window, &f->window_offset, &f->window_size,
+ & p);
+
+ if (r < 0)
+ return r;
+
+ *ret = (uint8_t*) p + delta;
+ return 0;
+}
+
+static bool verify_hash(Object *o) {
+ uint64_t t;
+
+ assert(o);
+
+ t = le64toh(o->object.type);
+ if (t == OBJECT_DATA) {
+ uint64_t s, h1, h2;
+
+ s = le64toh(o->object.size);
+
+ h1 = le64toh(o->data.hash);
+ h2 = hash64(o->data.payload, s - offsetof(Object, data.payload));
+
+ return h1 == h2;
+ }
+
+ return true;
+}
+
+int journal_file_move_to_object(JournalFile *f, uint64_t offset, Object **ret) {
+ int r;
+ void *t;
+ Object *o;
+ uint64_t s;
+
+ assert(f);
+ assert(ret);
+
+ r = journal_file_move_to(f, offset, sizeof(ObjectHeader), &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+ s = le64toh(o->object.size);
+
+ if (s < sizeof(ObjectHeader))
+ return -EBADMSG;
+
+ if (s > sizeof(ObjectHeader)) {
+ r = journal_file_move_to(f, offset, s, &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+ }
+
+ if (!verify_hash(o))
+ return -EBADMSG;
+
+ *ret = o;
+ return 0;
+}
+
+static uint64_t journal_file_seqnum(JournalFile *f) {
+ uint64_t r;
+
+ assert(f);
+
+ r = le64toh(f->header->seqnum) + 1;
+ f->header->seqnum = htole64(r);
+
+ return r;
+}
+
+static int journal_file_append_object(JournalFile *f, uint64_t size, Object **ret, uint64_t *offset) {
+ int r;
+ uint64_t p;
+ Object *tail, *o;
+ void *t;
+
+ assert(f);
+ assert(size >= sizeof(ObjectHeader));
+ assert(offset);
+ assert(ret);
+
+ p = le64toh(f->header->tail_object_offset);
+
+ if (p == 0)
+ p = le64toh(f->header->arena_offset);
+ else {
+ r = journal_file_move_to_object(f, p, &tail);
+ if (r < 0)
+ return r;
+
+ p += ALIGN64(le64toh(tail->object.size));
+ }
+
+ r = journal_file_allocate(f, p, size);
+ if (r < 0)
+ return r;
+
+ r = journal_file_move_to(f, p, size, &t);
+ if (r < 0)
+ return r;
+
+ o = (Object*) t;
+
+ zero(o->object);
+ o->object.type = htole64(OBJECT_UNUSED);
+ zero(o->object.reserved);
+ o->object.size = htole64(size);
+
+ f->header->tail_object_offset = htole64(p);
+ if (f->header->head_object_offset == 0)
+ f->header->head_object_offset = htole64(p);
+
+ f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
+
+ *ret = o;
+ *offset = p;
+
+ return 0;
+}
+
+static int journal_file_setup_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ Object *o;
+ int r;
+
+ assert(f);
+
+ s = DEFAULT_HASH_TABLE_SIZE;
+ r = journal_file_append_object(f, offsetof(Object, hash_table.table) + s, &o, &p);
+ if (r < 0)
+ return r;
+
+ o->object.type = htole64(OBJECT_HASH_TABLE);
+ memset(o->hash_table.table, 0, s);
+
+ f->header->hash_table_offset = htole64(p + offsetof(Object, hash_table.table));
+ f->header->hash_table_size = htole64(s);
+
+ return 0;
+}
+
+static int journal_file_setup_bisect_table(JournalFile *f) {
+ uint64_t s, p;
+ Object *o;
+ int r;
+
+ assert(f);
+
+ s = DEFAULT_BISECT_TABLE_SIZE;
+ r = journal_file_append_object(f, offsetof(Object, bisect_table.table) + s, &o, &p);
+ if (r < 0)
+ return r;
+
+ o->object.type = htole64(OBJECT_BISECT_TABLE);
+ memset(o->bisect_table.table, 0, s);
+
+ f->header->bisect_table_offset = htole64(p + offsetof(Object, bisect_table.table));
+ f->header->bisect_table_size = htole64(s);
+
+ return 0;
+}
+
+static int journal_file_map_hash_table(JournalFile *f) {
+ uint64_t s, p;
+ void *t;
+ int r;
+
+ assert(f);
+
+ p = le64toh(f->header->hash_table_offset);
+ s = le64toh(f->header->hash_table_size);
+
+ r = journal_file_map(f,
+ p, s,
+ &f->hash_table_window, NULL, &f->hash_table_window_size,
+ &t);
+ if (r < 0)
+ return r;
+
+ f->hash_table = t;
+ return 0;
+}
+
+static int journal_file_map_bisect_table(JournalFile *f) {
+ uint64_t s, p;
+ void *t;
+ int r;
+
+ assert(f);
+
+ p = le64toh(f->header->bisect_table_offset);
+ s = le64toh(f->header->bisect_table_size);
+
+ r = journal_file_map(f,
+ p, s,
+ &f->bisect_table_window, NULL, &f->bisect_table_window_size,
+ &t);
+
+ if (r < 0)
+ return r;
+
+ f->bisect_table = t;
+ return 0;
+}
+
+static int journal_file_link_data(JournalFile *f, Object *o, uint64_t offset, uint64_t hash_index) {
+ uint64_t p;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+ assert(o->object.type == htole64(OBJECT_DATA));
+
+ o->data.head_entry_offset = o->data.tail_entry_offset = 0;
+ o->data.next_hash_offset = 0;
+
+ p = le64toh(f->hash_table[hash_index].tail_hash_offset);
+ if (p == 0) {
+ /* Only entry in the hash table is easy */
+
+ o->data.prev_hash_offset = 0;
+ f->hash_table[hash_index].head_hash_offset = htole64(offset);
+ } else {
+ o->data.prev_hash_offset = htole64(p);
+
+ /* Temporarily move back to the previous data object,
+ * to patch in pointer */
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ o->data.next_hash_offset = offset;
+
+ r = journal_file_move_to_object(f, offset, &o);
+ if (r < 0)
+ return r;
+ }
+
+ f->hash_table[hash_index].tail_hash_offset = htole64(offset);
+
+ return 0;
+}
+
+static int journal_file_append_data(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset) {
+ uint64_t hash, h, p, np;
+ uint64_t osize;
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(data || size == 0);
+
+ osize = offsetof(Object, data.payload) + size;
+
+ hash = hash64(data, size);
+ h = hash % (le64toh(f->header->hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->hash_table[h].head_hash_offset);
+
+ while (p != 0) {
+ /* Look for this data object in the hash table */
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_DATA)
+ return -EBADMSG;
+
+ if (le64toh(o->object.size) == osize &&
+ memcmp(o->data.payload, data, size) == 0) {
+
+ if (le64toh(o->data.hash) != hash)
+ return -EBADMSG;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 0;
+ }
+
+ p = le64toh(o->data.next_hash_offset);
+ }
+
+ r = journal_file_append_object(f, osize, &o, &np);
+ if (r < 0)
+ return r;
+
+ o->object.type = htole64(OBJECT_DATA);
+ o->data.hash = htole64(hash);
+ memcpy(o->data.payload, data, size);
+
+ r = journal_file_link_data(f, o, np, h);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = np;
+
+ return 0;
+}
+
+uint64_t journal_file_entry_n_items(Object *o) {
+ assert(o);
+ assert(o->object.type == htole64(OBJECT_ENTRY));
+
+ return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
+}
+
+static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
+ uint64_t p, q;
+ int r;
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+
+ p = le64toh(o->entry.items[i].object_offset);
+ if (p == 0)
+ return -EINVAL;
+
+ o->entry.items[i].next_entry_offset = 0;
+
+ /* Move to the data object */
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (o->object.type != htole64(OBJECT_DATA))
+ return -EBADMSG;
+
+ q = le64toh(o->data.tail_entry_offset);
+ o->data.tail_entry_offset = htole64(offset);
+
+ if (q == 0)
+ o->data.head_entry_offset = htole64(offset);
+ else {
+ uint64_t n, j;
+
+ /* Move to previous entry */
+ r = journal_file_move_to_object(f, q, &o);
+ if (r < 0)
+ return r;
+
+ if (o->object.type != htole64(OBJECT_ENTRY))
+ return -EBADMSG;
+
+ n = journal_file_entry_n_items(o);
+ for (j = 0; j < n; j++)
+ if (le64toh(o->entry.items[j].object_offset) == p)
+ break;
+
+ if (j >= n)
+ return -EBADMSG;
+
+ o->entry.items[j].next_entry_offset = offset;
+ }
+
+ /* Move back to original entry */
+ r = journal_file_move_to_object(f, offset, &o);
+ if (r < 0)
+ return r;
+
+ o->entry.items[i].prev_entry_offset = q;
+ return 0;
+}
+
+static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
+ uint64_t p, i, n, k, a, b;
+ int r;
+
+ assert(f);
+ assert(o);
+ assert(offset > 0);
+ assert(o->object.type == htole64(OBJECT_ENTRY));
+
+ /* Link up the entry itself */
+ p = le64toh(f->header->tail_entry_offset);
+
+ o->entry.prev_entry_offset = f->header->tail_entry_offset;
+ o->entry.next_entry_offset = 0;
+
+ if (p == 0)
+ f->header->head_entry_offset = htole64(offset);
+ else {
+ /* Temporarily move back to the previous entry, to
+ * patch in pointer */
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ o->entry.next_entry_offset = htole64(offset);
+
+ r = journal_file_move_to_object(f, offset, &o);
+ if (r < 0)
+ return r;
+ }
+
+ f->header->tail_entry_offset = htole64(offset);
+
+ /* Link up the items */
+ n = journal_file_entry_n_items(o);
+ for (i = 0; i < n; i++) {
+ r = journal_file_link_entry_item(f, o, offset, i);
+ if (r < 0)
+ return r;
+ }
+
+ /* Link up the entry in the bisect table */
+ n = le64toh(f->header->bisect_table_size) / sizeof(uint64_t);
+ k = le64toh(f->header->arena_max_size) / n;
+
+ a = (le64toh(f->header->last_bisect_offset) + k - 1) / k;
+ b = offset / k;
+
+ for (; a <= b; a++)
+ f->bisect_table[a] = htole64(offset);
+
+ f->header->last_bisect_offset = htole64(offset + le64toh(o->object.size));
+
+ return 0;
+}
+
+static int journal_file_append_entry_internal(JournalFile *f, const dual_timestamp *ts, const EntryItem items[], unsigned n_items, Object **ret, uint64_t *offset) {
+ uint64_t np;
+ uint64_t osize;
+ Object *o;
+ int r;
+
+ assert(f);
+ assert(items || n_items == 0);
+
+ osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
+
+ r = journal_file_append_object(f, osize, &o, &np);
+ if (r < 0)
+ return r;
+
+ o->object.type = htole64(OBJECT_ENTRY);
+ o->entry.seqnum = htole64(journal_file_seqnum(f));
+ memcpy(o->entry.items, items, n_items * sizeof(EntryItem));
+ o->entry.realtime = htole64(ts->realtime);
+ o->entry.monotonic = htole64(ts->monotonic);
+
+ r = journal_file_link_entry(f, o, np);
+ if (r < 0)
+ return r;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = np;
+
+ return 0;
+}
+
+int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, Object **ret, uint64_t *offset) {
+ unsigned i;
+ EntryItem *items;
+ int r;
+
+ assert(f);
+
+ items = new(EntryItem, n_iovec);
+ if (!items)
+ return -ENOMEM;
+
+ for (i = 0; i < n_iovec; i++) {
+ uint64_t p;
+
+ r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, NULL, &p);
+ if (r < 0)
+ goto finish;
+
+ items[i].object_offset = htole64(p);
+ }
+
+ r = journal_file_append_entry_internal(f, ts, items, n_iovec, ret, offset);
+
+finish:
+ free(items);
+
+ return r;
+}
+
+int journal_file_move_to_entry(JournalFile *f, uint64_t seqnum, Object **ret, uint64_t *offset) {
+ Object *o;
+ uint64_t lower, upper, p, n, k;
+ int r;
+
+ assert(f);
+
+ n = le64toh(f->header->bisect_table_size) / sizeof(uint64_t);
+ k = le64toh(f->header->arena_max_size) / n;
+
+ lower = 0;
+ upper = le64toh(f->header->last_bisect_offset)/k+1;
+
+ while (lower < upper) {
+ k = (upper + lower) / 2;
+ p = le64toh(f->bisect_table[k]);
+
+ if (p == 0) {
+ upper = k;
+ continue;
+ }
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (o->object.type != htole64(OBJECT_ENTRY))
+ return -EBADMSG;
+
+ if (o->entry.seqnum == seqnum) {
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+ } else if (seqnum < o->entry.seqnum)
+ upper = k;
+ else if (seqnum > o->entry.seqnum)
+ lower = k+1;
+ }
+
+ assert(lower == upper);
+
+ if (lower <= 0)
+ return 0;
+
+ /* The object we are looking for is between
+ * bisect_table[lower-1] and bisect_table[lower] */
+
+ p = le64toh(f->bisect_table[lower-1]);
+
+ for (;;) {
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (o->entry.seqnum == seqnum) {
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+
+ } if (seqnum < o->entry.seqnum)
+ return 0;
+
+ if (o->entry.next_entry_offset == 0)
+ return 0;
+
+ p = le64toh(o->entry.next_entry_offset);
+ }
+
+ return 0;
+}
+
+int journal_file_next_entry(JournalFile *f, Object *o, Object **ret, uint64_t *offset) {
+ uint64_t np;
+ int r;
+
+ assert(f);
+
+ if (!o)
+ np = le64toh(f->header->head_entry_offset);
+ else {
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EINVAL;
+
+ np = le64toh(o->entry.next_entry_offset);
+ }
+
+ if (np == 0)
+ return 0;
+
+ r = journal_file_move_to_object(f, np, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EBADMSG;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = np;
+
+ return 1;
+}
+
+int journal_file_prev_entry(JournalFile *f, Object *o, Object **ret, uint64_t *offset) {
+ uint64_t np;
+ int r;
+
+ assert(f);
+
+ if (!o)
+ np = le64toh(f->header->tail_entry_offset);
+ else {
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EINVAL;
+
+ np = le64toh(o->entry.prev_entry_offset);
+ }
+
+ if (np == 0)
+ return 0;
+
+ r = journal_file_move_to_object(f, np, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EBADMSG;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = np;
+
+ return 1;
+}
+
+int journal_file_find_first_entry(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset) {
+ uint64_t p, osize, hash, h;
+ int r;
+
+ assert(f);
+ assert(data || size == 0);
+
+ osize = offsetof(Object, data.payload) + size;
+
+ hash = hash64(data, size);
+ h = hash % (le64toh(f->header->hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->hash_table[h].head_hash_offset);
+
+ while (p != 0) {
+ Object *o;
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_DATA)
+ return -EBADMSG;
+
+ if (le64toh(o->object.size) == osize &&
+ memcmp(o->data.payload, data, size) == 0) {
+
+ if (le64toh(o->data.hash) != hash)
+ return -EBADMSG;
+
+ if (o->data.head_entry_offset == 0)
+ return 0;
+
+ p = le64toh(o->data.head_entry_offset);
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EBADMSG;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+ }
+
+ p = le64toh(o->data.next_hash_offset);
+ }
+
+ return 0;
+}
+
+int journal_file_find_last_entry(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset) {
+ uint64_t p, osize, hash, h;
+ int r;
+
+ assert(f);
+ assert(data || size == 0);
+
+ osize = offsetof(Object, data.payload) + size;
+
+ hash = hash64(data, size);
+ h = hash % (le64toh(f->header->hash_table_size) / sizeof(HashItem));
+ p = le64toh(f->hash_table[h].tail_hash_offset);
+
+ while (p != 0) {
+ Object *o;
+
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_DATA)
+ return -EBADMSG;
+
+ if (le64toh(o->object.size) == osize &&
+ memcmp(o->data.payload, data, size) == 0) {
+
+ if (le64toh(o->data.hash) != hash)
+ return -EBADMSG;
+
+ if (o->data.tail_entry_offset == 0)
+ return 0;
+
+ p = le64toh(o->data.tail_entry_offset);
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ return r;
+
+ if (le64toh(o->object.type) != OBJECT_ENTRY)
+ return -EBADMSG;
+
+ if (ret)
+ *ret = o;
+
+ if (offset)
+ *offset = p;
+
+ return 1;
+ }
+
+ p = le64toh(o->data.prev_hash_offset);
+ }
+
+ return 0;
+}
+
+void journal_file_dump(JournalFile *f) {
+ char a[33], b[33], c[33];
+ Object *o;
+ int r;
+ uint64_t p;
+
+ assert(f);
+
+ printf("File ID: %s\n"
+ "Machine ID: %s\n"
+ "Boot ID: %s\n"
+ "Arena size: %llu\n",
+ sd_id128_to_string(f->header->file_id, a),
+ sd_id128_to_string(f->header->machine_id, b),
+ sd_id128_to_string(f->header->boot_id, c),
+ (unsigned long long) le64toh(f->header->arena_size));
+
+ p = le64toh(f->header->head_object_offset);
+ while (p != 0) {
+ r = journal_file_move_to_object(f, p, &o);
+ if (r < 0)
+ goto fail;
+
+ switch (o->object.type) {
+
+ case OBJECT_UNUSED:
+ printf("Type: OBJECT_UNUSED\n");
+ break;
+
+ case OBJECT_DATA:
+ printf("Type: OBJECT_DATA\n");
+ break;
+
+ case OBJECT_ENTRY:
+ printf("Type: OBJECT_ENTRY %llu\n", (unsigned long long) le64toh(o->entry.seqnum));
+ break;
+
+ case OBJECT_HASH_TABLE:
+ printf("Type: OBJECT_HASH_TABLE\n");
+ break;
+
+ case OBJECT_BISECT_TABLE:
+ printf("Type: OBJECT_BISECT_TABLE\n");
+ break;
+ }
+
+ if (p == le64toh(f->header->tail_object_offset))
+ p = 0;
+ else
+ p = p + ALIGN64(le64toh(o->object.size));
+ }
+
+ return;
+fail:
+ log_error("File corrupt");
+}
+
+int journal_file_open(
+ sd_journal *j,
+ const char *fname,
+ int flags,
+ mode_t mode,
+ JournalFile **ret) {
+
+ JournalFile *f;
+ int r;
+ bool newly_created = false;
+
+ assert(fname);
+
+ if ((flags & O_ACCMODE) != O_RDONLY &&
+ (flags & O_ACCMODE) != O_RDWR)
+ return -EINVAL;
+
+ f = new0(JournalFile, 1);
+ if (!f)
+ return -ENOMEM;
+
+ f->writable = (flags & O_ACCMODE) != O_RDONLY;
+ f->prot = prot_from_flags(flags);
+
+ f->fd = open(fname, flags|O_CLOEXEC, mode);
+ if (f->fd < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ f->path = strdup(fname);
+ if (!f->path) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ if (fstat(f->fd, &f->last_stat) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ if (f->last_stat.st_size == 0 && f->writable) {
+ newly_created = true;
+
+ r = journal_file_init_header(f);
+ if (r < 0)
+ goto fail;
+
+ if (fstat(f->fd, &f->last_stat) < 0) {
+ r = -errno;
+ goto fail;
+ }
+ }
+
+ if (f->last_stat.st_size < (off_t) sizeof(Header)) {
+ r = -EIO;
+ goto fail;
+ }
+
+ f->header = mmap(NULL, PAGE_ALIGN(sizeof(Header)), prot_from_flags(flags), MAP_SHARED, f->fd, 0);
+ if (f->header == MAP_FAILED) {
+ f->header = NULL;
+ r = -errno;
+ goto fail;
+ }
+
+ if (!newly_created) {
+ r = journal_file_verify_header(f);
+ if (r < 0)
+ goto fail;
+ }
+
+ if (f->writable) {
+ r = journal_file_refresh_header(f);
+ if (r < 0)
+ goto fail;
+ }
+
+ if (newly_created) {
+
+ r = journal_file_setup_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_setup_bisect_table(f);
+ if (r < 0)
+ goto fail;
+ }
+
+ r = journal_file_map_hash_table(f);
+ if (r < 0)
+ goto fail;
+
+ r = journal_file_map_bisect_table(f);
+ if (r < 0)
+ goto fail;
+
+ if (j) {
+ LIST_PREPEND(JournalFile, files, j->files, f);
+ f->journal = j;
+ }
+
+ if (ret)
+ *ret = f;
+
+ return 0;
+
+fail:
+ journal_file_close(f);
+
+ return r;
+}
+
+int sd_journal_open(sd_journal **ret) {
+ sd_journal *j;
+ char *fn;
+ const char *p;
+ int r = 0;
+ const char search_paths[] =
+ "/run/log/journal\0"
+ "/var/log/journal\0";
+
+ assert(ret);
+
+ j = new0(sd_journal, 1);
+ if (!j)
+ return -ENOMEM;
+
+ NULSTR_FOREACH(p, search_paths) {
+ DIR *d;
+
+ d = opendir(p);
+ if (!d) {
+ if (errno != ENOENT && r == 0)
+ r = -errno;
+
+ continue;
+ }
+
+ for (;;) {
+ struct dirent buf, *de;
+ int k;
+
+ k = readdir_r(d, &buf, &de);
+ if (k != 0) {
+ if (r == 0)
+ r = -k;
+
+ break;
+ }
+
+ if (!de)
+ break;
+
+ if (!dirent_is_file_with_suffix(de, ".journal"))
+ continue;
+
+ fn = join(p, "/", de->d_name, NULL);
+ if (!fn) {
+ r = -ENOMEM;
+ closedir(d);
+ goto fail;
+ }
+
+ k = journal_file_open(j, fn, O_RDONLY, 0, NULL);
+ if (k < 0 && r == 0)
+ r = -k;
+
+ free(fn);
+ }
+ }
+
+ if (!j->files) {
+ if (r >= 0)
+ r = -ENOENT;
+
+ goto fail;
+ }
+
+ *ret = j;
+ return 0;
+
+fail:
+ sd_journal_close(j);
+
+ return r;
+};
+
+void sd_journal_close(sd_journal *j) {
+ assert(j);
+
+ while (j->files)
+ journal_file_close(j->files);
+
+ free(j);
+}
diff --git a/src/journal/sd-journal.h b/src/journal/sd-journal.h
new file mode 100644
index 0000000000..8170dea87c
--- /dev/null
+++ b/src/journal/sd-journal.h
@@ -0,0 +1,74 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foojournalhfoo
+#define foojournalhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <sys/types.h>
+
+#include "sd-id128.h"
+
+/* TODO:
+ *
+ * - implement rotation
+ * - check LE/BE conversion for 8bit, 16bit, 32bit values
+ * - implement parallel traversal
+ * - implement audit gateway
+ * - implement native gateway
+ * - extend hash table/bisect table as we go
+ */
+
+typedef struct sd_journal sd_journal;
+
+int sd_journal_open(sd_journal **ret);
+void sd_journal_close(sd_journal *j);
+
+int sd_journal_previous(sd_journal *j);
+int sd_journal_next(sd_journal *j);
+
+void* sd_journal_get(sd_journal *j, const char *field, size_t *size);
+uint64_t sd_journal_get_seqnum(sd_journal *j);
+uint64_t sd_journal_get_realtime_usec(sd_journal *j);
+uint64_t sd_journal_get_monotonic_usec(sd_journal *j);
+
+int sd_journal_add_match(sd_journal *j, const char *item, size_t *size);
+
+int sd_journal_seek_head(sd_journal *j);
+int sd_journal_seek_tail(sd_journal *j);
+
+int sd_journal_seek_seqnum(sd_journal *j, uint64_t seqnum);
+int sd_journal_seek_monotonic_usec(sd_journal *j, uint64_t usec);
+int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec);
+
+uint64_t sd_journal_get_max_size(sd_journal *j);
+uint64_t sd_journal_get_min_size(sd_journal *j);
+uint64_t sd_journal_get_keep_free(sd_journal *j);
+
+int sd_journal_set_max_size(sd_journal *j, uint64_t size);
+int sd_journal_set_min_size(sd_journal *j, uint64_t size);
+int sd_journal_set_keep_free(sd_journal *j, uint64_t size);
+
+sd_id128_t sd_journal_get_file_id(sd_journal *j);
+sd_id128_t sd_journal_get_machine_id(sd_journal *j);
+sd_id128_t sd_journal_get_boot_id(sd_journal *j);
+
+#endif
diff --git a/src/journal/test-journal.c b/src/journal/test-journal.c
new file mode 100644
index 0000000000..92bef5f3ef
--- /dev/null
+++ b/src/journal/test-journal.c
@@ -0,0 +1,93 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+
+#include "journal-private.h"
+#include "log.h"
+
+int main(int argc, char *argv[]) {
+ dual_timestamp ts;
+ JournalFile *f;
+ struct iovec iovec;
+ static const char test[] = "test", test2[] = "test2";
+ Object *o;
+
+ log_set_max_level(LOG_DEBUG);
+
+ assert_se(journal_file_open(NULL, "test", O_RDWR|O_CREAT, 0666, &f) == 0);
+
+ dual_timestamp_get(&ts);
+
+ iovec.iov_base = (void*) test;
+ iovec.iov_len = strlen(test);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL) == 0);
+
+ iovec.iov_base = (void*) test2;
+ iovec.iov_len = strlen(test2);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL) == 0);
+
+ iovec.iov_base = (void*) test;
+ iovec.iov_len = strlen(test);
+ assert_se(journal_file_append_entry(f, &ts, &iovec, 1, NULL, NULL) == 0);
+
+ journal_file_dump(f);
+
+ assert(journal_file_next_entry(f, NULL, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_next_entry(f, o, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_next_entry(f, o, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_next_entry(f, o, &o, NULL) == 0);
+
+ assert(journal_file_find_first_entry(f, test, strlen(test), &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_find_last_entry(f, test, strlen(test), &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_find_last_entry(f, test2, strlen(test2), &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_find_first_entry(f, test2, strlen(test2), &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_find_first_entry(f, "quux", 4, &o, NULL) == 0);
+
+ assert(journal_file_move_to_entry(f, 1, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 1);
+
+ assert(journal_file_move_to_entry(f, 3, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 3);
+
+ assert(journal_file_move_to_entry(f, 2, &o, NULL) == 1);
+ assert(le64toh(o->entry.seqnum) == 2);
+
+ assert(journal_file_move_to_entry(f, 10, &o, NULL) == 0);
+
+ journal_file_close(f);
+
+ return 0;
+}
diff --git a/src/journal/wjournal.c b/src/journal/wjournal.c
new file mode 100644
index 0000000000..3122aa054e
--- /dev/null
+++ b/src/journal/wjournal.c
@@ -0,0 +1,57 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include "wjournal.h"
+#include "journal-def.h"
+
+struct WJournal {
+ int fd;
+
+ Header *header;
+ HashItem *hash_table;
+ uint64_t *bisect_table;
+};
+
+int wjournal_open(const char *fn, WJournal **ret) {
+ assert(fn);
+ assert(ret);
+}
+
+void wjournal_close(WJournal *j) {
+ assert(j);
+
+ if (j->fd >= 0)
+ close_nointr_nofail(j->fd);
+
+ if (j->header) {
+ munmap(j->header, PAGE_ALIGN(sizeof(Header)));
+
+ }
+
+ free(j);
+}
+
+int wjournal_write_object_begin(WJournal *j, uint64_t type, uint64_t size, Object **ret);
+int wjournal_write_object_finish(WJournal *j, Object *ret);
+
+int wjournal_write_field(WJournal *j, const char *buffer, uint64_t size, Object **ret);
+int wjournal_write_entry(WJournal *j, const Field *fields, unsigned n_fields, Object **ret);
+int wjournal_write_eof(WJournal *j);
diff --git a/src/journal/wjournal.h b/src/journal/wjournal.h
new file mode 100644
index 0000000000..b0250d0fe2
--- /dev/null
+++ b/src/journal/wjournal.h
@@ -0,0 +1,39 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef foojournalhfoo
+#define foojournalhfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+
+typedef struct WJournal WJournal;
+
+int wjournal_open(const char *fn, WJournal **ret);
+void wjournal_close(WJournal *j);
+
+int wjournal_write_object_begin(WJournal *j, uint64_t type, uint64_t size, Object **ret);
+int wjournal_write_object_finish(WJournal *j, Object *ret);
+
+int wjournal_write_field(WJournal *j, const char *buffer, uint64_t size, Object **ret);
+int wjournal_write_entry(WJournal *j, const Field *fields, unsigned n_fields, Object **ret);
+int wjournal_write_eof(WJournal *j);
+
+#endif
diff --git a/src/kmsg-syslogd.c b/src/kmsg-syslogd.c
index 0901a0e49b..70cc0730ee 100644
--- a/src/kmsg-syslogd.c
+++ b/src/kmsg-syslogd.c
@@ -65,45 +65,53 @@ static void server_done(Server *s) {
fdset_free(s->syslog_fds);
}
-static int server_init(Server *s, unsigned n_sockets) {
- int r;
- unsigned i;
+static int server_init(Server *s) {
+ int i, r, n;
struct epoll_event ev;
sigset_t mask;
assert(s);
- assert(n_sockets > 0);
zero(*s);
-
s->kmsg_fd = s->signal_fd = -1;
- if ((s->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0) {
- r = -errno;
- log_error("Failed to create epoll object: %s", strerror(errno));
- goto fail;
+ s->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
+ if (s->epoll_fd < 0) {
+ log_error("Failed to create epoll object: %m");
+ return -errno;
+ }
+
+ s->syslog_fds = fdset_new();
+ if (!s->syslog_fds) {
+ log_error("Failed to allocate file descriptor set: %s", strerror(ENOMEM));
+ return -ENOMEM;
}
- if (!(s->syslog_fds = fdset_new())) {
- r = -ENOMEM;
- log_error("Failed to allocate file descriptor set: %s", strerror(errno));
- goto fail;
+ n = sd_listen_fds(true);
+ if (n < 0) {
+ log_error("Failed to read listening file descriptors from environment: %s", strerror(-n));
+ return n;
+ }
+
+ if (n <= 0 || n > SERVER_FD_MAX) {
+ log_error("No or too many file descriptors passed.");
+ return -EINVAL;
}
- for (i = 0; i < n_sockets; i++) {
+ for (i = 0; i < n; i++) {
int fd, one = 1;
fd = SD_LISTEN_FDS_START+i;
- if ((r = sd_is_socket(fd, AF_UNSPEC, SOCK_DGRAM, -1)) < 0) {
+ r = sd_is_socket(fd, AF_UNSPEC, SOCK_DGRAM, -1);
+ if (r < 0) {
log_error("Failed to determine file descriptor type: %s", strerror(-r));
- goto fail;
+ return r;
}
if (!r) {
log_error("Wrong file descriptor type.");
- r = -EINVAL;
- goto fail;
+ return -EINVAL;
}
if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
@@ -113,18 +121,19 @@ static int server_init(Server *s, unsigned n_sockets) {
ev.events = EPOLLIN;
ev.data.fd = fd;
if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
- r = -errno;
- log_error("Failed to add server fd to epoll object: %s", strerror(errno));
- goto fail;
+ log_error("Failed to add server fd to epoll object: %m");
+ return -errno;
}
- if ((r = fdset_put(s->syslog_fds, fd)) < 0) {
+ r = fdset_put(s->syslog_fds, fd);
+ if (r < 0) {
log_error("Failed to store file descriptor in set: %s", strerror(-r));
- goto fail;
+ return r;
}
}
- if ((s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
+ s->kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
+ if (s->kmsg_fd < 0) {
log_error("Failed to open /dev/kmsg for logging: %m");
return -errno;
}
@@ -133,7 +142,8 @@ static int server_init(Server *s, unsigned n_sockets) {
sigset_add_many(&mask, SIGINT, SIGTERM, -1);
assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
- if ((s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
+ s->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
+ if (s->signal_fd < 0) {
log_error("signalfd(): %m");
return -errno;
}
@@ -148,80 +158,6 @@ static int server_init(Server *s, unsigned n_sockets) {
}
return 0;
-
-fail:
- server_done(s);
- return r;
-}
-
-static void skip_date(const char **buf) {
- enum {
- LETTER,
- SPACE,
- NUMBER,
- SPACE_OR_NUMBER,
- COLON
- } sequence[] = {
- LETTER, LETTER, LETTER,
- SPACE,
- SPACE_OR_NUMBER, NUMBER,
- SPACE,
- SPACE_OR_NUMBER, NUMBER,
- COLON,
- SPACE_OR_NUMBER, NUMBER,
- COLON,
- SPACE_OR_NUMBER, NUMBER,
- SPACE
- };
-
- const char *p;
- unsigned i;
-
- assert(buf);
- assert(*buf);
-
- p = *buf;
-
- for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
-
- if (!*p)
- return;
-
- switch (sequence[i]) {
-
- case SPACE:
- if (*p != ' ')
- return;
- break;
-
- case SPACE_OR_NUMBER:
- if (*p == ' ')
- break;
-
- /* fall through */
-
- case NUMBER:
- if (*p < '0' || *p > '9')
- return;
-
- break;
-
- case LETTER:
- if (!(*p >= 'A' && *p <= 'Z') &&
- !(*p >= 'a' && *p <= 'z'))
- return;
-
- break;
-
- case COLON:
- if (*p != ':')
- return;
- break;
-
- }
- }
-
- *buf = p;
}
static int read_process(const char **buf, struct iovec *iovec) {
@@ -266,28 +202,6 @@ static int read_process(const char **buf, struct iovec *iovec) {
return 1;
}
-static void skip_pid(const char **buf) {
- const char *p;
-
- assert(buf);
- assert(*buf);
-
- p = *buf;
-
- if (*p != '[')
- return;
-
- p++;
- p += strspn(p, "0123456789");
-
- if (*p != ']')
- return;
-
- p++;
-
- *buf = p;
-}
-
static int write_message(Server *s, const char *buf, struct ucred *ucred) {
ssize_t k;
char priority[6], pid[16];
@@ -314,14 +228,14 @@ static int write_message(Server *s, const char *buf, struct ucred *ucred) {
IOVEC_SET_STRING(iovec[i++], priority);
/* Second, skip date */
- skip_date(&buf);
+ skip_syslog_date((char**) &buf);
/* Then, add process if set */
if (read_process(&buf, &iovec[i]) > 0)
i++;
else if (ucred &&
ucred->pid > 0 &&
- get_process_name(ucred->pid, &process) >= 0)
+ get_process_comm(ucred->pid, &process) >= 0)
IOVEC_SET_STRING(iovec[i++], process);
/* Skip the stored PID if we have a better one */
@@ -330,7 +244,7 @@ static int write_message(Server *s, const char *buf, struct ucred *ucred) {
char_array_0(pid);
IOVEC_SET_STRING(iovec[i++], pid);
- skip_pid(&buf);
+ skip_syslog_pid((char**) &buf);
if (*buf == ':')
buf++;
@@ -368,7 +282,8 @@ static int process_event(Server *s, struct epoll_event *ev) {
struct signalfd_siginfo sfsi;
ssize_t n;
- if ((n = read(s->signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
+ n = read(s->signal_fd, &sfsi, sizeof(sfsi));
+ if (n != sizeof(sfsi)) {
if (n >= 0)
return -EIO;
@@ -407,7 +322,8 @@ static int process_event(Server *s, struct epoll_event *ev) {
msghdr.msg_control = &control;
msghdr.msg_controllen = sizeof(control);
- if ((n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT)) < 0) {
+ n = recvmsg(ev->data.fd, &msghdr, MSG_DONTWAIT);
+ if (n < 0) {
if (errno == EINTR || errno == EAGAIN)
return 1;
@@ -424,12 +340,14 @@ static int process_event(Server *s, struct epoll_event *ev) {
else
ucred = NULL;
- if ((e = memchr(buf, '\n', n)))
+ e = memchr(buf, '\n', n);
+ if (e)
*e = 0;
else
buf[n] = 0;
- if ((k = write_message(s, strstrip(buf), ucred)) < 0)
+ k = write_message(s, strstrip(buf), ucred);
+ if (k < 0)
return k;
}
}
@@ -439,7 +357,7 @@ static int process_event(Server *s, struct epoll_event *ev) {
int main(int argc, char *argv[]) {
Server server;
- int r = EXIT_FAILURE, n;
+ int r;
if (getppid() != 1) {
log_error("This program should be invoked by init only.");
@@ -457,18 +375,9 @@ int main(int argc, char *argv[]) {
umask(0022);
- if ((n = sd_listen_fds(true)) < 0) {
- log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
- return EXIT_FAILURE;
- }
-
- if (n <= 0 || n > SERVER_FD_MAX) {
- log_error("No or too many file descriptors passed.");
- return EXIT_FAILURE;
- }
-
- if (server_init(&server, (unsigned) n) < 0)
- return EXIT_FAILURE;
+ r = server_init(&server);
+ if (r < 0)
+ goto finish;
log_debug("systemd-kmsg-syslogd running as pid %lu", (unsigned long) getpid());
@@ -478,36 +387,33 @@ int main(int argc, char *argv[]) {
for (;;) {
struct epoll_event event;
- int k;
- if ((k = epoll_wait(server.epoll_fd, &event, 1, -1)) < 0) {
+ r = epoll_wait(server.epoll_fd, &event, 1, -1);
+ if (r < 0) {
if (errno == EINTR)
continue;
log_error("epoll_wait() failed: %m");
- goto fail;
- }
-
- if (k <= 0)
+ r = -errno;
+ goto finish;
+ } else if (r == 0)
break;
- if ((k = process_event(&server, &event)) < 0)
- goto fail;
-
- if (k == 0)
+ r = process_event(&server, &event);
+ if (r < 0)
+ goto finish;
+ else if (r == 0)
break;
}
- r = EXIT_SUCCESS;
-
log_debug("systemd-kmsg-syslogd stopped as pid %lu", (unsigned long) getpid());
-fail:
+finish:
sd_notify(false,
"STATUS=Shutting down...");
server_done(&server);
- return r;
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
diff --git a/src/loginctl.c b/src/loginctl.c
index 89762b66b0..1be47c8dde 100644
--- a/src/loginctl.c
+++ b/src/loginctl.c
@@ -393,7 +393,7 @@ static void print_session_status_info(SessionStatusInfo *i) {
printf("\t Leader: %u", (unsigned) i->leader);
- get_process_name(i->leader, &t);
+ get_process_comm(i->leader, &t);
if (t) {
printf(" (%s)", t);
free(t);
diff --git a/src/machine-id-setup.c b/src/machine-id-setup.c
index 519521fe67..9b25b10438 100644
--- a/src/machine-id-setup.c
+++ b/src/machine-id-setup.c
@@ -31,21 +31,12 @@
#include "macro.h"
#include "util.h"
#include "log.h"
-
-static void make_v4_uuid(unsigned char *id) {
- /* Stolen from generate_random_uuid() of drivers/char/random.c
- * in the kernel sources */
-
- /* Set UUID version to 4 --- truly random generation */
- id[6] = (id[6] & 0x0F) | 0x40;
-
- /* Set the UUID variant to DCE */
- id[8] = (id[8] & 0x3F) | 0x80;
-}
+#include "sd-id128.h"
static int generate(char id[34]) {
- int fd;
- unsigned char buf[16], *p;
+ int fd, r;
+ unsigned char *p;
+ sd_id128_t buf;
char *q;
ssize_t k;
@@ -68,26 +59,13 @@ static int generate(char id[34]) {
}
/* If that didn't work, generate a random machine id */
- fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
- if (fd < 0) {
- log_error("Failed to open /dev/urandom: %m");
- return -errno;
- }
-
- k = loop_read(fd, buf, sizeof(buf), false);
- close_nointr_nofail(fd);
-
- if (k != sizeof(buf)) {
- log_error("Failed to read /dev/urandom: %s", strerror(k < 0 ? -k : EIO));
- return k < 0 ? (int) k : -EIO;
+ r = sd_id128_randomize(&buf);
+ if (r < 0) {
+ log_error("Failed to open /dev/urandom: %s", strerror(-r));
+ return r;
}
- /* Turn this into a valid v4 UUID, to be nice. Note that we
- * only guarantee this for newly generated UUIDs, not for
- * pre-existing ones.*/
- make_v4_uuid(buf);
-
- for (p = buf, q = id; p < buf + sizeof(buf); p++, q += 2) {
+ for (p = buf.bytes, q = id; p < buf.bytes + sizeof(buf); p++, q += 2) {
q[0] = hexchar(*p >> 4);
q[1] = hexchar(*p & 15);
}
diff --git a/src/manager.c b/src/manager.c
index e626347dec..ac5bbef1a8 100644
--- a/src/manager.c
+++ b/src/manager.c
@@ -2024,7 +2024,7 @@ static int manager_dispatch_sigchld(Manager *m) {
if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
char *name = NULL;
- get_process_name(si.si_pid, &name);
+ get_process_comm(si.si_pid, &name);
log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
free(name);
}
@@ -2109,7 +2109,7 @@ static int manager_process_signal_fd(Manager *m) {
if (sfsi.ssi_pid > 0) {
char *p = NULL;
- get_process_name(sfsi.ssi_pid, &p);
+ get_process_comm(sfsi.ssi_pid, &p);
log_debug("Received SIG%s from PID %lu (%s).",
signal_to_string(sfsi.ssi_signo),
diff --git a/src/pam-module.c b/src/pam-module.c
index dd05f93d42..78f9b30d5b 100644
--- a/src/pam-module.c
+++ b/src/pam-module.c
@@ -163,42 +163,24 @@ static int get_user_data(
const char *username = NULL;
struct passwd *pw = NULL;
+ uid_t uid;
int r;
- bool have_loginuid = false;
- char *s;
assert(handle);
assert(ret_username);
assert(ret_pw);
- if (have_effective_cap(CAP_AUDIT_CONTROL) > 0) {
- /* Only use audit login uid if we are executed with
- * sufficient capabilities so that pam_loginuid could
- * do its job. If we are lacking the CAP_AUDIT_CONTROL
- * capabality we most likely are being run in a
- * container and /proc/self/loginuid is useless since
- * it probably contains a uid of the host system. */
-
- if (read_one_line_file("/proc/self/loginuid", &s) >= 0) {
- uid_t uid;
-
- r = parse_uid(s, &uid);
- free(s);
-
- if (r >= 0 && uid != (uint32_t) -1) {
- have_loginuid = true;
- pw = pam_modutil_getpwuid(handle, uid);
- }
- }
- }
-
- if (!have_loginuid) {
- if ((r = pam_get_user(handle, &username, NULL)) != PAM_SUCCESS) {
+ r = audit_loginuid_from_pid(0, &uid);
+ if (r >= 0)
+ pw = pam_modutil_getpwuid(handle, uid);
+ else {
+ r = pam_get_user(handle, &username, NULL);
+ if (r != PAM_SUCCESS) {
pam_syslog(handle, LOG_ERR, "Failed to get user name.");
return r;
}
- if (!username || !*username) {
+ if (isempty(username)) {
pam_syslog(handle, LOG_ERR, "User name not valid.");
return PAM_AUTH_ERR;
}
diff --git a/src/sd-id128.c b/src/sd-id128.c
new file mode 100644
index 0000000000..f5e0432a3f
--- /dev/null
+++ b/src/sd-id128.c
@@ -0,0 +1,210 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "sd-id128.h"
+#include "util.h"
+#include "macro.h"
+
+char *sd_id128_to_string(sd_id128_t id, char s[33]) {
+ unsigned n;
+
+ assert(s);
+
+ for (n = 0; n < 16; n++) {
+ s[n*2] = hexchar(id.bytes[n] >> 4);
+ s[n*2+1] = hexchar(id.bytes[n] & 0xF);
+ }
+
+ s[32] = 0;
+
+ return s;
+}
+
+int sd_id128_from_string(const char s[33], sd_id128_t *ret) {
+ unsigned n;
+ sd_id128_t t;
+
+ assert(s);
+ assert(ret);
+
+ for (n = 0; n < 16; n++) {
+ int a, b;
+
+ a = unhexchar(s[n*2]);
+ if (a < 0)
+ return -EINVAL;
+
+ b = unhexchar(s[n*2+1]);
+ if (b < 0)
+ return -EINVAL;
+
+ t.bytes[n] = (a << 4) | b;
+ }
+
+ if (s[32] != 0)
+ return -EINVAL;
+
+ *ret = t;
+ return 0;
+}
+
+sd_id128_t sd_id128_make_v4_uuid(sd_id128_t id) {
+ /* Stolen from generate_random_uuid() of drivers/char/random.c
+ * in the kernel sources */
+
+ /* Set UUID version to 4 --- truly random generation */
+ id.bytes[6] = (id.bytes[6] & 0x0F) | 0x40;
+
+ /* Set the UUID variant to DCE */
+ id.bytes[8] = (id.bytes[8] & 0x3F) | 0x80;
+
+ return id;
+}
+
+int sd_id128_get_machine(sd_id128_t *ret) {
+ static __thread sd_id128_t saved_machine_id;
+ static __thread bool saved_machine_id_valid = false;
+ int fd;
+ char buf[32];
+ ssize_t k;
+ unsigned j;
+ sd_id128_t t;
+
+ if (saved_machine_id_valid) {
+ *ret = saved_machine_id;
+ return 0;
+ }
+
+ fd = open("/etc/machine-id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, buf, 32, false);
+ close_nointr_nofail(fd);
+
+ if (k < 0)
+ return (int) k;
+
+ if (k < 32)
+ return -EIO;
+
+ for (j = 0; j < 16; j++) {
+ int a, b;
+
+ a = unhexchar(buf[j*2]);
+ b = unhexchar(buf[j*2+1]);
+
+ if (a < 0 || b < 0)
+ return -EIO;
+
+ t.bytes[j] = a << 4 | b;
+ }
+
+ saved_machine_id = t;
+ saved_machine_id_valid = true;
+
+ *ret = t;
+ return 0;
+}
+
+int sd_id128_get_boot(sd_id128_t *ret) {
+ static __thread sd_id128_t saved_boot_id;
+ static __thread bool saved_boot_id_valid = false;
+ int fd;
+ char buf[36];
+ ssize_t k;
+ unsigned j;
+ sd_id128_t t;
+ char *p;
+
+ if (saved_boot_id_valid) {
+ *ret = saved_boot_id;
+ return 0;
+ }
+
+ fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, buf, 36, false);
+ close_nointr_nofail(fd);
+
+ if (k < 0)
+ return (int) k;
+
+ if (k < 36)
+ return -EIO;
+
+ for (j = 0, p = buf; j < 16; j++) {
+ int a, b;
+
+ if (*p == '-')
+ p++;
+
+ a = unhexchar(p[0]);
+ b = unhexchar(p[1]);
+
+ if (a < 0 || b < 0)
+ return -EIO;
+
+ t.bytes[j] = a << 4 | b;
+
+ p += 2;
+ }
+
+ saved_boot_id = t;
+ saved_boot_id_valid = true;
+
+ *ret = t;
+ return 0;
+}
+
+int sd_id128_randomize(sd_id128_t *ret) {
+ int fd;
+ ssize_t k;
+ sd_id128_t t;
+
+ assert(ret);
+
+ fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
+ if (fd < 0)
+ return -errno;
+
+ k = loop_read(fd, &t, 16, false);
+ close_nointr_nofail(fd);
+
+ if (k < 0)
+ return (int) k;
+
+ if (k < 16)
+ return -EIO;
+
+ /* Turn this into a valid v4 UUID, to be nice. Note that we
+ * only guarantee this for newly generated UUIDs, not for
+ * pre-existing ones.*/
+
+ *ret = sd_id128_make_v4_uuid(t);
+ return 0;
+}
diff --git a/src/sd-id128.h b/src/sd-id128.h
new file mode 100644
index 0000000000..bfae78b97d
--- /dev/null
+++ b/src/sd-id128.h
@@ -0,0 +1,56 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+#ifndef fooid128hfoo
+#define fooid128hfoo
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <string.h>
+
+typedef union sd_id128 sd_id128_t;
+
+union sd_id128 {
+ uint8_t bytes[16];
+ uint64_t qwords[2];
+};
+
+char *sd_id128_to_string(sd_id128_t id, char s[33]);
+
+int sd_id128_from_string(const char s[33], sd_id128_t *ret);
+
+int sd_id128_randomize(sd_id128_t *ret);
+
+sd_id128_t sd_id128_make_v4_uuid(sd_id128_t id);
+
+int sd_id128_get_machine(sd_id128_t *ret);
+
+int sd_id128_get_boot(sd_id128_t *ret);
+
+#define SD_ID128_MAKE(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) \
+ ((sd_id128_t) { .bytes = { 0x##v0, 0x##v1, 0x##v2, 0x##v3, 0x##v4, 0x##v5, 0x##v6, 0x##v7, \
+ 0x##v8, 0x##v9, 0x##v10, 0x##v11, 0x##v12, 0x##v13, 0x##v14, 0x##v15 }})
+
+static inline bool sd_id128_equal(sd_id128_t a, sd_id128_t b) {
+ return memcmp(&a, &b, 16) == 0;
+}
+
+#endif
diff --git a/src/stdout-syslog-bridge.c b/src/stdout-syslog-bridge.c
index 9a0408819e..d50df22c88 100644
--- a/src/stdout-syslog-bridge.c
+++ b/src/stdout-syslog-bridge.c
@@ -649,7 +649,8 @@ int main(int argc, char *argv[]) {
umask(0022);
- if ((n = sd_listen_fds(true)) < 0) {
+ n = sd_listen_fds(true);
+ if (n < 0) {
log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
return EXIT_FAILURE;
}
diff --git a/src/systemctl.c b/src/systemctl.c
index 0de2444d43..a423fdbf93 100644
--- a/src/systemctl.c
+++ b/src/systemctl.c
@@ -2182,7 +2182,7 @@ static void print_status_info(UnitStatusInfo *i) {
if (i->running) {
char *t = NULL;
- get_process_name(i->main_pid, &t);
+ get_process_comm(i->main_pid, &t);
if (t) {
printf(" (%s)", t);
free(t);
@@ -2216,7 +2216,7 @@ static void print_status_info(UnitStatusInfo *i) {
printf(" Control: %u", (unsigned) i->control_pid);
- get_process_name(i->control_pid, &t);
+ get_process_comm(i->control_pid, &t);
if (t) {
printf(" (%s)", t);
free(t);
diff --git a/src/test-id128.c b/src/test-id128.c
new file mode 100644
index 0000000000..6c3928d2e9
--- /dev/null
+++ b/src/test-id128.c
@@ -0,0 +1,49 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ systemd is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ systemd is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <string.h>
+
+#include "sd-id128.h"
+#include "util.h"
+#include "macro.h"
+
+#define ID128_WALDI SD_ID128_MAKE(01, 02, 03, 04, 05, 06, 07, 08, 09, 0a, 0b, 0c, 0d, 0e, 0f, 10)
+
+int main(int argc, char *argv[]) {
+ sd_id128_t id, id2;
+ char t[33];
+
+ assert_se(sd_id128_randomize(&id) == 0);
+ printf("random: %s\n", sd_id128_to_string(id, t));
+
+ assert_se(sd_id128_from_string(t, &id2) == 0);
+ assert_se(sd_id128_equal(id, id2));
+
+ assert_se(sd_id128_get_machine(&id) == 0);
+ printf("machine: %s\n", sd_id128_to_string(id, t));
+
+ assert_se(sd_id128_get_boot(&id) == 0);
+ printf("boot: %s\n", sd_id128_to_string(id, t));
+
+ printf("waldi: %s\n", sd_id128_to_string(ID128_WALDI, t));
+
+ return 0;
+}
diff --git a/src/util.c b/src/util.c
index 7977ee46c5..99737e4e63 100644
--- a/src/util.c
+++ b/src/util.c
@@ -55,6 +55,7 @@
#include <linux/rtc.h>
#include <glob.h>
#include <grp.h>
+#include <sys/mman.h>
#include "macro.h"
#include "util.h"
@@ -73,7 +74,7 @@ size_t page_size(void) {
static __thread size_t pgsz = 0;
long r;
- if (_likely_(pgsz))
+ if (_likely_(pgsz > 0))
return pgsz;
assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
@@ -993,46 +994,51 @@ char *truncate_nl(char *s) {
return s;
}
-int get_process_name(pid_t pid, char **name) {
- char *p;
+int get_process_comm(pid_t pid, char **name) {
int r;
- assert(pid >= 1);
assert(name);
- if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
- return -ENOMEM;
-
- r = read_one_line_file(p, name);
- free(p);
+ if (pid == 0)
+ r = read_one_line_file("/proc/self/comm", name);
+ else {
+ char *p;
+ if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
+ return -ENOMEM;
- if (r < 0)
- return r;
+ r = read_one_line_file(p, name);
+ free(p);
+ }
- return 0;
+ return r;
}
-int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
- char *p, *r, *k;
+int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
+ char *r, *k;
int c;
bool space = false;
size_t left;
FILE *f;
- assert(pid >= 1);
assert(max_length > 0);
assert(line);
- if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
- return -ENOMEM;
+ if (pid == 0)
+ f = fopen("/proc/self/cmdline", "re");
+ else {
+ char *p;
+ if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
+ return -ENOMEM;
- f = fopen(p, "re");
- free(p);
+ f = fopen(p, "re");
+ free(p);
+ }
if (!f)
return -errno;
- if (!(r = new(char, max_length))) {
+ r = new(char, max_length);
+ if (!r) {
fclose(f);
return -ENOMEM;
}
@@ -1076,13 +1082,17 @@ int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
free(r);
- if ((h = get_process_name(pid, &t)) < 0)
+ if (!comm_fallback)
+ return -ENOENT;
+
+ h = get_process_comm(pid, &t);
+ if (h < 0)
return h;
- h = asprintf(&r, "[%s]", t);
+ r = join("[", t, "]", NULL);
free(t);
- if (h < 0)
+ if (!r)
return -ENOMEM;
}
@@ -1090,6 +1100,25 @@ int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
return 0;
}
+int get_process_exe(pid_t pid, char **name) {
+ int r;
+
+ assert(name);
+
+ if (pid == 0)
+ r = readlink_malloc("/proc/self/exe", name);
+ else {
+ char *p;
+ if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
+ return -ENOMEM;
+
+ r = readlink_malloc(p, name);
+ free(p);
+ }
+
+ return r;
+}
+
char *strnappend(const char *s, const char *suffix, size_t b) {
size_t a;
char *r;
@@ -4267,7 +4296,7 @@ const char *default_term_for_tty(const char *tty) {
return term;
}
-bool dirent_is_file(struct dirent *de) {
+bool dirent_is_file(const struct dirent *de) {
assert(de);
if (ignore_file(de->d_name))
@@ -4281,6 +4310,15 @@ bool dirent_is_file(struct dirent *de) {
return true;
}
+bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
+ assert(de);
+
+ if (!dirent_is_file(de))
+ return false;
+
+ return endswith(de->d_name, suffix);
+}
+
void execute_directory(const char *directory, DIR *d, char *argv[]) {
DIR *_d = NULL;
struct dirent *de;
@@ -4453,6 +4491,98 @@ void parse_syslog_priority(char **p, int *priority) {
*p += k;
}
+void skip_syslog_pid(char **buf) {
+ char *p;
+
+ assert(buf);
+ assert(*buf);
+
+ p = *buf;
+
+ if (*p != '[')
+ return;
+
+ p++;
+ p += strspn(p, "0123456789");
+
+ if (*p != ']')
+ return;
+
+ p++;
+
+ *buf = p;
+}
+
+void skip_syslog_date(char **buf) {
+ enum {
+ LETTER,
+ SPACE,
+ NUMBER,
+ SPACE_OR_NUMBER,
+ COLON
+ } sequence[] = {
+ LETTER, LETTER, LETTER,
+ SPACE,
+ SPACE_OR_NUMBER, NUMBER,
+ SPACE,
+ SPACE_OR_NUMBER, NUMBER,
+ COLON,
+ SPACE_OR_NUMBER, NUMBER,
+ COLON,
+ SPACE_OR_NUMBER, NUMBER,
+ SPACE
+ };
+
+ char *p;
+ unsigned i;
+
+ assert(buf);
+ assert(*buf);
+
+ p = *buf;
+
+ for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
+
+ if (!*p)
+ return;
+
+ switch (sequence[i]) {
+
+ case SPACE:
+ if (*p != ' ')
+ return;
+ break;
+
+ case SPACE_OR_NUMBER:
+ if (*p == ' ')
+ break;
+
+ /* fall through */
+
+ case NUMBER:
+ if (*p < '0' || *p > '9')
+ return;
+
+ break;
+
+ case LETTER:
+ if (!(*p >= 'A' && *p <= 'Z') &&
+ !(*p >= 'a' && *p <= 'z'))
+ return;
+
+ break;
+
+ case COLON:
+ if (*p != ':')
+ return;
+ break;
+
+ }
+ }
+
+ *buf = p;
+}
+
int have_effective_cap(int value) {
cap_t cap;
cap_flag_value_t fv;
@@ -4672,21 +4802,6 @@ int vt_disallocate(const char *name) {
return 0;
}
-
-static int file_is_conf(const struct dirent *d, const char *suffix) {
- assert(d);
-
- if (ignore_file(d->d_name))
- return 0;
-
- if (d->d_type != DT_REG &&
- d->d_type != DT_LNK &&
- d->d_type != DT_UNKNOWN)
- return 0;
-
- return endswith(d->d_name, suffix);
-}
-
static int files_add(Hashmap *h, const char *path, const char *suffix) {
DIR *dir;
struct dirent buffer, *de;
@@ -4712,7 +4827,7 @@ static int files_add(Hashmap *h, const char *path, const char *suffix) {
if (!de)
break;
- if (!file_is_conf(de, suffix))
+ if (!dirent_is_file_with_suffix(de, suffix))
continue;
if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
@@ -5063,21 +5178,27 @@ int symlink_or_copy_atomic(const char *from, const char *to) {
}
int audit_session_from_pid(pid_t pid, uint32_t *id) {
- char *p, *s;
+ char *s;
uint32_t u;
int r;
- assert(pid >= 1);
assert(id);
if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
return -ENOENT;
- if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
- return -ENOMEM;
+ if (pid == 0)
+ r = read_one_line_file("/proc/self/sessionid", &s);
+ else {
+ char *p;
+
+ if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
+ return -ENOMEM;
+
+ r = read_one_line_file(p, &s);
+ free(p);
+ }
- r = read_one_line_file(p, &s);
- free(p);
if (r < 0)
return r;
@@ -5094,6 +5215,51 @@ int audit_session_from_pid(pid_t pid, uint32_t *id) {
return 0;
}
+int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
+ char *s;
+ uid_t u;
+ int r;
+
+ assert(uid);
+
+ /* Only use audit login uid if we are executed with sufficient
+ * capabilities so that pam_loginuid could do its job. If we
+ * are lacking the CAP_AUDIT_CONTROL capabality we most likely
+ * are being run in a container and /proc/self/loginuid is
+ * useless since it probably contains a uid of the host
+ * system. */
+
+ if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
+ return -ENOENT;
+
+ if (pid == 0)
+ r = read_one_line_file("/proc/self/loginuid", &s);
+ else {
+ char *p;
+
+ if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
+ return -ENOMEM;
+
+ r = read_one_line_file(p, &s);
+ free(p);
+ }
+
+ if (r < 0)
+ return r;
+
+ r = parse_uid(s, &u);
+ free(s);
+
+ if (r < 0)
+ return r;
+
+ if (u == (uid_t) -1)
+ return -ENOENT;
+
+ *uid = (uid_t) u;
+ return 0;
+}
+
bool display_is_local(const char *display) {
assert(display);
@@ -5700,3 +5866,21 @@ int strdup_or_null(const char *a, char **b) {
*b = c;
return 0;
}
+
+int prot_from_flags(int flags) {
+
+ switch (flags & O_ACCMODE) {
+
+ case O_RDONLY:
+ return PROT_READ;
+
+ case O_WRONLY:
+ return PROT_WRITE;
+
+ case O_RDWR:
+ return PROT_READ|PROT_WRITE;
+
+ default:
+ return -EINVAL;
+ }
+}
diff --git a/src/util.h b/src/util.h
index ccbe8a3efa..1a2dd5825d 100644
--- a/src/util.h
+++ b/src/util.h
@@ -248,8 +248,9 @@ int parent_of_path(const char *path, char **parent);
int rmdir_parents(const char *path, const char *stop);
-int get_process_name(pid_t pid, char **name);
-int get_process_cmdline(pid_t pid, size_t max_length, char **line);
+int get_process_comm(pid_t pid, char **name);
+int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line);
+int get_process_exe(pid_t pid, char **name);
char hexchar(int x);
int unhexchar(char c);
@@ -274,7 +275,9 @@ bool path_equal(const char *a, const char *b);
char *ascii_strlower(char *path);
-bool dirent_is_file(struct dirent *de);
+bool dirent_is_file(const struct dirent *de);
+bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix);
+
bool ignore_file(const char *filename);
bool chars_intersect(const char *a, const char *b);
@@ -415,6 +418,8 @@ bool nulstr_contains(const char*nulstr, const char *needle);
bool plymouth_running(void);
void parse_syslog_priority(char **p, int *priority);
+void skip_syslog_pid(char **buf);
+void skip_syslog_date(char **buf);
int have_effective_cap(int value);
@@ -443,6 +448,7 @@ int hwclock_get_time(struct tm *tm);
int hwclock_set_time(const struct tm *tm);
int audit_session_from_pid(pid_t pid, uint32_t *id);
+int audit_loginuid_from_pid(pid_t pid, uid_t *uid);
bool display_is_local(const char *display);
int socket_from_display(const char *display, char **path);
@@ -506,4 +512,6 @@ extern char **saved_argv;
bool kexec_loaded(void);
+int prot_from_flags(int flags);
+
#endif
diff --git a/tmpfiles.d/Makefile b/tmpfiles.d/Makefile
new file mode 120000
index 0000000000..bd1047548b
--- /dev/null
+++ b/tmpfiles.d/Makefile
@@ -0,0 +1 @@
+../src/Makefile \ No newline at end of file