summaryrefslogtreecommitdiff
path: root/src/journal
diff options
context:
space:
mode:
Diffstat (limited to 'src/journal')
-rw-r--r--[l---------]src/journal/Makefile350
-rw-r--r--src/journal/audit-type.c29
-rw-r--r--src/journal/audit-type.h37
-rw-r--r--src/journal/cat.c2
-rw-r--r--src/journal/catalog.c766
-rw-r--r--src/journal/catalog.h36
-rw-r--r--src/journal/catalog/systemd.be.catalog260
-rw-r--r--src/journal/catalog/systemd.be@latin.catalog260
-rw-r--r--src/journal/catalog/systemd.catalog334
-rw-r--r--src/journal/catalog/systemd.da.catalog261
-rw-r--r--src/journal/catalog/systemd.fr.catalog260
-rw-r--r--src/journal/catalog/systemd.hu.catalog262
-rw-r--r--src/journal/catalog/systemd.it.catalog254
-rw-r--r--src/journal/catalog/systemd.ko.catalog264
-rw-r--r--src/journal/catalog/systemd.pl.catalog261
-rw-r--r--src/journal/catalog/systemd.pt_BR.catalog264
-rw-r--r--src/journal/catalog/systemd.ru.catalog354
-rw-r--r--src/journal/catalog/systemd.sr.catalog262
-rw-r--r--src/journal/catalog/systemd.zh_CN.catalog253
-rw-r--r--src/journal/catalog/systemd.zh_TW.catalog263
-rw-r--r--src/journal/compress.c682
-rw-r--r--src/journal/compress.h85
-rw-r--r--src/journal/fsprg.c387
-rw-r--r--src/journal/fsprg.h65
-rw-r--r--src/journal/journal-authenticate.c562
-rw-r--r--src/journal/journal-authenticate.h41
-rw-r--r--src/journal/journal-def.h237
-rw-r--r--src/journal/journal-file.c3324
-rw-r--r--src/journal/journal-file.h245
-rw-r--r--src/journal/journal-internal.h140
-rw-r--r--src/journal/journal-qrcode.h2
-rw-r--r--src/journal/journal-send.c559
-rw-r--r--src/journal/journal-vacuum.c349
-rw-r--r--src/journal/journal-vacuum.h27
-rw-r--r--src/journal/journal-verify.c1294
-rw-r--r--src/journal/journal-verify.h24
-rw-r--r--src/journal/journalctl.c4
-rw-r--r--src/journal/journald-kmsg.c2
-rw-r--r--src/journal/journald-server.c6
-rw-r--r--src/journal/journald-server.h2
-rw-r--r--src/journal/journald-stream.c4
-rw-r--r--src/journal/journald-syslog.c2
-rw-r--r--src/journal/journald.c4
-rw-r--r--src/journal/lookup3.c1009
-rw-r--r--src/journal/lookup3.h22
-rw-r--r--src/journal/mmap-cache.c725
-rw-r--r--src/journal/mmap-cache.h49
-rw-r--r--src/journal/sd-journal.c2800
-rw-r--r--src/journal/test-catalog.c2
-rw-r--r--src/journal/test-journal-enum.c2
-rw-r--r--src/journal/test-journal-flush.c2
-rw-r--r--src/journal/test-journal-init.c2
-rw-r--r--src/journal/test-journal-interleaving.c2
-rw-r--r--src/journal/test-journal-match.c2
-rw-r--r--src/journal/test-journal-send.c2
-rw-r--r--src/journal/test-journal-stream.c2
56 files changed, 4183 insertions, 13517 deletions
diff --git a/src/journal/Makefile b/src/journal/Makefile
index d0b0e8e008..43e8810680 120000..100644
--- a/src/journal/Makefile
+++ b/src/journal/Makefile
@@ -1 +1,349 @@
-../Makefile \ No newline at end of file
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+include $(dir $(lastword $(MAKEFILE_LIST)))/../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+
+$(outdir)/dns_type-list.txt: src/resolve/dns-type.h
+ $(AM_V_at)$(MKDIR_P) $(dir $@)
+ $(AM_V_GEN)$(SED) -n -r 's/.* DNS_TYPE_(\w+).*/\1/p' <$< >$@
+
+$(outdir)/dns_type-to-name.h: src/resolve/dns_type-list.txt
+ $(AM_V_at)$(MKDIR_P) $(dir $@)
+ $(AM_V_GEN)$(AWK) 'BEGIN{ print "const char *dns_type_to_string(int type) {\n\tswitch(type) {" } {printf " case DNS_TYPE_%s: return ", $$1; sub(/_/, "-"); printf "\"%s\";\n", $$1 } END{ print " default: return NULL;\n\t}\n}\n" }' <$< >$@
+
+$(outdir)/dns_type-from-name.gperf: src/resolve/dns_type-list.txt
+ $(AM_V_at)$(MKDIR_P) $(dir $@)
+ $(AM_V_GEN)$(AWK) 'BEGIN{ print "struct dns_type_name { const char* name; int id; };"; print "%null-strings"; print "%%";} { s=$$1; sub(/_/, "-", s); printf "%s, ", $$s; printf "DNS_TYPE_%s\n", $$1 }' <$< >$@
+
+systemd_journald_SOURCES = \
+ src/journal/journald.c \
+ src/journal/journald-server.h
+
+systemd_journald_LDADD = \
+ libjournal-core.la \
+ libshared.la
+
+systemd_cat_SOURCES = \
+ src/journal/cat.c
+
+systemd_cat_LDADD = \
+ libjournal-core.la
+
+# using _CFLAGS = in the conditional below would suppress AM_CFLAGS
+journalctl_CFLAGS = \
+ $(AM_CFLAGS)
+
+journalctl_SOURCES = \
+ src/journal/journalctl.c
+
+journalctl_LDADD = \
+ libshared.la \
+ libudev-core.la
+
+ifneq ($(HAVE_QRENCODE),)
+journalctl_SOURCES += \
+ src/journal/journal-qrcode.c \
+ src/journal/journal-qrcode.h
+
+journalctl_CFLAGS += \
+ $(QRENCODE_CFLAGS)
+
+journalctl_LDADD += \
+ $(QRENCODE_LIBS)
+endif
+
+test_journal_SOURCES = \
+ src/journal/test-journal.c
+
+test_journal_LDADD = \
+ libjournal-core.la
+
+test_journal_send_SOURCES = \
+ src/journal/test-journal-send.c
+
+test_journal_send_LDADD = \
+ libjournal-core.la
+
+test_journal_syslog_SOURCES = \
+ src/journal/test-journal-syslog.c
+
+test_journal_syslog_LDADD = \
+ libjournal-core.la
+
+test_journal_match_SOURCES = \
+ src/journal/test-journal-match.c
+
+test_journal_match_LDADD = \
+ libjournal-core.la
+
+test_journal_enum_SOURCES = \
+ src/journal/test-journal-enum.c
+
+test_journal_enum_LDADD = \
+ libjournal-core.la
+
+test_journal_stream_SOURCES = \
+ src/journal/test-journal-stream.c
+
+test_journal_stream_LDADD = \
+ libjournal-core.la
+
+test_journal_flush_SOURCES = \
+ src/journal/test-journal-flush.c
+
+test_journal_flush_LDADD = \
+ libjournal-core.la
+
+test_journal_init_SOURCES = \
+ src/journal/test-journal-init.c
+
+test_journal_init_LDADD = \
+ libjournal-core.la
+
+test_journal_verify_SOURCES = \
+ src/journal/test-journal-verify.c
+
+test_journal_verify_LDADD = \
+ libjournal-core.la
+
+test_journal_interleaving_SOURCES = \
+ src/journal/test-journal-interleaving.c
+
+test_journal_interleaving_LDADD = \
+ libjournal-core.la
+
+test_mmap_cache_SOURCES = \
+ src/journal/test-mmap-cache.c
+
+test_mmap_cache_LDADD = \
+ libjournal-core.la
+
+test_catalog_SOURCES = \
+ src/journal/test-catalog.c
+
+test_catalog_CPPFLAGS = \
+ $(AM_CPPFLAGS) \
+ -DCATALOG_DIR=\"$(abs_top_srcdir)/catalog\"
+
+test_catalog_LDADD = \
+ libjournal-core.la
+
+test_compress_SOURCES = \
+ src/journal/test-compress.c
+
+test_compress_LDADD = \
+ libshared.la
+
+test_compress_benchmark_SOURCES = \
+ src/journal/test-compress-benchmark.c
+
+test_compress_benchmark_LDADD = \
+ libshared.la
+
+test_audit_type_SOURCES = \
+ src/journal/test-audit-type.c
+
+test_audit_type_LDADD = \
+ libjournal-core.la
+
+libjournal_core_la_SOURCES = \
+ src/journal/journald-kmsg.c \
+ src/journal/journald-kmsg.h \
+ src/journal/journald-syslog.c \
+ src/journal/journald-syslog.h \
+ src/journal/journald-stream.c \
+ src/journal/journald-stream.h \
+ src/journal/journald-server.c \
+ src/journal/journald-server.h \
+ src/journal/journald-console.c \
+ src/journal/journald-console.h \
+ src/journal/journald-wall.c \
+ src/journal/journald-wall.h \
+ src/journal/journald-native.c \
+ src/journal/journald-native.h \
+ src/journal/journald-audit.c \
+ src/journal/journald-audit.h \
+ src/journal/journald-rate-limit.c \
+ src/journal/journald-rate-limit.h \
+ src/journal/journal-internal.h
+
+nodist_libjournal_core_la_SOURCES = \
+ src/journal/journald-gperf.c
+
+libjournal_core_la_LIBADD = \
+ libshared.la
+
+noinst_LTLIBRARIES += \
+ libjournal-core.la
+
+journal-install-hook:
+ -$(MKDIR_P) $(DESTDIR)/var/log/journal
+ -chown 0:0 $(DESTDIR)/var/log/journal
+ -chmod 755 $(DESTDIR)/var/log/journal
+ -setfacl -nm g:adm:rx,d:g:adm:rx $(DESTDIR)/var/log/journal/
+ -setfacl -nm g:wheel:rx,d:g:wheel:rx $(DESTDIR)/var/log/journal/
+
+journal-uninstall-hook:
+ -rmdir $(DESTDIR)/var/log/journal/remote
+ -rmdir $(DESTDIR)/var/log/journal/
+
+INSTALL_EXEC_HOOKS += journal-install-hook
+UNINSTALL_EXEC_HOOKS += journal-uninstall-hook
+
+# ------------------------------------------------------------------------------
+# Update catalog on installation. Do not bother if installing
+# in DESTDIR, since this is likely for packaging purposes.
+catalog-update-hook:
+ -test -n "$(DESTDIR)" || $(bindir)/journalctl --update-catalog
+
+INSTALL_DATA_HOOKS += \
+ catalog-update-hook
+
+catalog-remove-hook:
+ -test -n "$(DESTDIR)" || rm -f $(catalogstatedir)/database
+
+UNINSTALL_DATA_HOOKS += \
+ catalog-remove-hook
+
+manual_tests += \
+ test-journal-enum
+
+tests += \
+ test-journal \
+ test-journal-send \
+ test-journal-syslog \
+ test-journal-match \
+ test-journal-stream \
+ test-journal-init \
+ test-journal-verify \
+ test-journal-interleaving \
+ test-journal-flush \
+ test-mmap-cache \
+ test-catalog \
+ test-audit-type
+
+ifneq ($(HAVE_COMPRESSION),)
+tests += \
+ test-compress \
+ test-compress-benchmark
+endif
+
+
+libexec_PROGRAMS += \
+ systemd-journald
+
+bin_PROGRAMS += \
+ journalctl
+
+bin_PROGRAMS += \
+ systemd-cat
+
+dist_systemunit_DATA += \
+ units/systemd-journald.socket \
+ units/systemd-journald-dev-log.socket \
+ units/systemd-journald-audit.socket
+
+nodist_systemunit_DATA += \
+ units/systemd-journald.service \
+ units/systemd-journal-flush.service \
+ units/systemd-journal-catalog-update.service
+
+dist_pkgsysconf_DATA += \
+ src/journal/journald.conf
+
+dist_catalog_DATA = \
+ catalog/systemd.be.catalog \
+ catalog/systemd.be@latin.catalog \
+ catalog/systemd.fr.catalog \
+ catalog/systemd.it.catalog \
+ catalog/systemd.pl.catalog \
+ catalog/systemd.pt_BR.catalog \
+ catalog/systemd.ru.catalog \
+ catalog/systemd.zh_CN.catalog \
+ catalog/systemd.zh_TW.catalog \
+ catalog/systemd.catalog
+
+SOCKETS_TARGET_WANTS += \
+ systemd-journald.socket \
+ systemd-journald-dev-log.socket \
+ systemd-journald-audit.socket
+
+SYSINIT_TARGET_WANTS += \
+ systemd-journald.service \
+ systemd-journal-flush.service \
+ systemd-journal-catalog-update.service
+
+EXTRA_DIST += \
+ units/systemd-journald.service.in \
+ units/systemd-journal-flush.service.in \
+ units/systemd-journal-catalog-update.service.in
+
+gperf_gperf_sources += \
+ src/journal/journald-gperf.gperf
+
+# ------------------------------------------------------------------------------
+ifneq ($(HAVE_MICROHTTPD),)
+gatewayddocumentrootdir=$(pkgdatadir)/gatewayd
+
+libexec_PROGRAMS += \
+ systemd-journal-gatewayd
+
+systemd_journal_gatewayd_SOURCES = \
+ src/journal-remote/journal-gatewayd.c \
+ src/journal-remote/microhttpd-util.h \
+ src/journal-remote/microhttpd-util.c
+
+systemd_journal_gatewayd_LDADD = \
+ libshared.la \
+ $(MICROHTTPD_LIBS)
+
+ifneq ($(HAVE_GNUTLS),)
+systemd_journal_gatewayd_LDADD += \
+ $(GNUTLS_LIBS)
+endif
+
+systemd_journal_gatewayd_CFLAGS = \
+ $(AM_CFLAGS) \
+ $(MICROHTTPD_CFLAGS)
+
+systemd_journal_gatewayd_CPPFLAGS = \
+ $(AM_CPPFLAGS) \
+ -DDOCUMENT_ROOT=\"$(gatewayddocumentrootdir)\"
+
+dist_systemunit_DATA += \
+ units/systemd-journal-gatewayd.socket
+
+nodist_systemunit_DATA += \
+ units/systemd-journal-gatewayd.service
+
+dist_gatewayddocumentroot_DATA = \
+ src/journal-remote/browse.html
+
+endif
+
+EXTRA_DIST += \
+ units/systemd-journal-gatewayd.service.in
+
+$(eval $(value automake2autothing))
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/journal/audit-type.c b/src/journal/audit-type.c
deleted file mode 100644
index 71e8790ca8..0000000000
--- a/src/journal/audit-type.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/***
- This file is part of systemd.
-
- Copyright 2015 Zbigniew Jędrzejewski-Szmek
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <stdio.h>
-#include <linux/audit.h>
-#ifdef HAVE_AUDIT
-# include <libaudit.h>
-#endif
-
-#include "missing.h"
-#include "audit-type.h"
-#include "audit_type-to-name.h"
-#include "macro.h"
diff --git a/src/journal/audit-type.h b/src/journal/audit-type.h
deleted file mode 100644
index 1dd2163707..0000000000
--- a/src/journal/audit-type.h
+++ /dev/null
@@ -1,37 +0,0 @@
-#pragma once
-
-/***
- This file is part of systemd.
-
- Copyright 2015 Zbigniew Jędrzejewski-Szmek
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include "macro.h"
-
-const char *audit_type_to_string(int type);
-int audit_type_from_string(const char *s);
-
-/* This is inspired by DNS TYPEnnn formatting */
-#define audit_type_name_alloca(type) \
- ({ \
- const char *_s_; \
- _s_ = audit_type_to_string(type); \
- if (!_s_) { \
- _s_ = alloca(strlen("AUDIT") + DECIMAL_STR_MAX(int)); \
- sprintf((char*) _s_, "AUDIT%04i", type); \
- } \
- _s_; \
- })
diff --git a/src/journal/cat.c b/src/journal/cat.c
index 08c844d44f..93ab6e7f96 100644
--- a/src/journal/cat.c
+++ b/src/journal/cat.c
@@ -24,7 +24,7 @@
#include <stdlib.h>
#include <unistd.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "fd-util.h"
#include "parse-util.h"
diff --git a/src/journal/catalog.c b/src/journal/catalog.c
deleted file mode 100644
index 164a3a15f2..0000000000
--- a/src/journal/catalog.c
+++ /dev/null
@@ -1,766 +0,0 @@
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <errno.h>
-#include <fcntl.h>
-#include <locale.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#include "sd-id128.h"
-
-#include "alloc-util.h"
-#include "catalog.h"
-#include "conf-files.h"
-#include "fd-util.h"
-#include "fileio.h"
-#include "hashmap.h"
-#include "log.h"
-#include "mkdir.h"
-#include "path-util.h"
-#include "siphash24.h"
-#include "sparse-endian.h"
-#include "strbuf.h"
-#include "string-util.h"
-#include "strv.h"
-#include "util.h"
-
-const char * const catalog_file_dirs[] = {
- "/usr/local/lib/systemd/catalog/",
- "/usr/lib/systemd/catalog/",
- NULL
-};
-
-#define CATALOG_SIGNATURE (uint8_t[]) { 'R', 'H', 'H', 'H', 'K', 'S', 'L', 'P' }
-
-typedef struct CatalogHeader {
- uint8_t signature[8]; /* "RHHHKSLP" */
- le32_t compatible_flags;
- le32_t incompatible_flags;
- le64_t header_size;
- le64_t n_items;
- le64_t catalog_item_size;
-} CatalogHeader;
-
-typedef struct CatalogItem {
- sd_id128_t id;
- char language[32];
- le64_t offset;
-} CatalogItem;
-
-static void catalog_hash_func(const void *p, struct siphash *state) {
- const CatalogItem *i = p;
-
- siphash24_compress(&i->id, sizeof(i->id), state);
- siphash24_compress(i->language, strlen(i->language), state);
-}
-
-static int catalog_compare_func(const void *a, const void *b) {
- const CatalogItem *i = a, *j = b;
- unsigned k;
-
- for (k = 0; k < ELEMENTSOF(j->id.bytes); k++) {
- if (i->id.bytes[k] < j->id.bytes[k])
- return -1;
- if (i->id.bytes[k] > j->id.bytes[k])
- return 1;
- }
-
- return strcmp(i->language, j->language);
-}
-
-const struct hash_ops catalog_hash_ops = {
- .hash = catalog_hash_func,
- .compare = catalog_compare_func
-};
-
-static bool next_header(const char **s) {
- const char *e;
-
- e = strchr(*s, '\n');
-
- /* Unexpected end */
- if (!e)
- return false;
-
- /* End of headers */
- if (e == *s)
- return false;
-
- *s = e + 1;
- return true;
-}
-
-static const char *skip_header(const char *s) {
- while (next_header(&s))
- ;
- return s;
-}
-
-static char *combine_entries(const char *one, const char *two) {
- const char *b1, *b2;
- size_t l1, l2, n;
- char *dest, *p;
-
- /* Find split point of headers to body */
- b1 = skip_header(one);
- b2 = skip_header(two);
-
- l1 = strlen(one);
- l2 = strlen(two);
- dest = new(char, l1 + l2 + 1);
- if (!dest) {
- log_oom();
- return NULL;
- }
-
- p = dest;
-
- /* Headers from @one */
- n = b1 - one;
- p = mempcpy(p, one, n);
-
- /* Headers from @two, these will only be found if not present above */
- n = b2 - two;
- p = mempcpy(p, two, n);
-
- /* Body from @one */
- n = l1 - (b1 - one);
- if (n > 0) {
- memcpy(p, b1, n);
- p += n;
-
- /* Body from @two */
- } else {
- n = l2 - (b2 - two);
- memcpy(p, b2, n);
- p += n;
- }
-
- assert(p - dest <= (ptrdiff_t)(l1 + l2));
- p[0] = '\0';
- return dest;
-}
-
-static int finish_item(
- Hashmap *h,
- sd_id128_t id,
- const char *language,
- char *payload) {
-
- _cleanup_free_ CatalogItem *i = NULL;
- _cleanup_free_ char *combined = NULL, *prev = NULL;
- int r;
-
- assert(h);
- assert(payload);
-
- i = new0(CatalogItem, 1);
- if (!i)
- return log_oom();
-
- i->id = id;
- if (language) {
- assert(strlen(language) > 1 && strlen(language) < 32);
- strcpy(i->language, language);
- }
-
- prev = hashmap_get(h, i);
-
- /* Already have such an item, combine them */
- if (prev) {
- combined = combine_entries(payload, prev);
- if (!combined)
- return log_oom();
- r = hashmap_update(h, i, combined);
- if (r < 0)
- return r;
- combined = NULL;
-
- /* A new item */
- } else {
- r = hashmap_put(h, i, payload);
- if (r < 0)
- return r;
- i = NULL;
- }
-
- return 0;
-}
-
-int catalog_file_lang(const char* filename, char **lang) {
- char *beg, *end, *_lang;
-
- end = endswith(filename, ".catalog");
- if (!end)
- return 0;
-
- beg = end - 1;
- while (beg > filename && *beg != '.' && *beg != '/' && end - beg < 32)
- beg --;
-
- if (*beg != '.' || end <= beg + 1)
- return 0;
-
- _lang = strndup(beg + 1, end - beg - 1);
- if (!_lang)
- return -ENOMEM;
-
- *lang = _lang;
- return 1;
-}
-
-static int catalog_entry_lang(const char* filename, int line,
- const char* t, const char* deflang, char **lang) {
- size_t c;
-
- c = strlen(t);
- if (c == 0) {
- log_error("[%s:%u] Language too short.", filename, line);
- return -EINVAL;
- }
- if (c > 31) {
- log_error("[%s:%u] language too long.", filename, line);
- return -EINVAL;
- }
-
- if (deflang) {
- if (streq(t, deflang)) {
- log_warning("[%s:%u] language specified unnecessarily",
- filename, line);
- return 0;
- } else
- log_warning("[%s:%u] language differs from default for file",
- filename, line);
- }
-
- *lang = strdup(t);
- if (!*lang)
- return -ENOMEM;
-
- return 0;
-}
-
-int catalog_import_file(Hashmap *h, const char *path) {
- _cleanup_fclose_ FILE *f = NULL;
- _cleanup_free_ char *payload = NULL;
- unsigned n = 0;
- sd_id128_t id;
- _cleanup_free_ char *deflang = NULL, *lang = NULL;
- bool got_id = false, empty_line = true;
- int r;
-
- assert(h);
- assert(path);
-
- f = fopen(path, "re");
- if (!f)
- return log_error_errno(errno, "Failed to open file %s: %m", path);
-
- r = catalog_file_lang(path, &deflang);
- if (r < 0)
- log_error_errno(r, "Failed to determine language for file %s: %m", path);
- if (r == 1)
- log_debug("File %s has language %s.", path, deflang);
-
- for (;;) {
- char line[LINE_MAX];
- size_t a, b, c;
- char *t;
-
- if (!fgets(line, sizeof(line), f)) {
- if (feof(f))
- break;
-
- return log_error_errno(errno, "Failed to read file %s: %m", path);
- }
-
- n++;
-
- truncate_nl(line);
-
- if (line[0] == 0) {
- empty_line = true;
- continue;
- }
-
- if (strchr(COMMENTS "\n", line[0]))
- continue;
-
- if (empty_line &&
- strlen(line) >= 2+1+32 &&
- line[0] == '-' &&
- line[1] == '-' &&
- line[2] == ' ' &&
- (line[2+1+32] == ' ' || line[2+1+32] == '\0')) {
-
- bool with_language;
- sd_id128_t jd;
-
- /* New entry */
-
- with_language = line[2+1+32] != '\0';
- line[2+1+32] = '\0';
-
- if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) {
-
- if (got_id) {
- r = finish_item(h, id, lang ?: deflang, payload);
- if (r < 0)
- return r;
-
- payload = NULL;
- lang = mfree(lang);
- }
-
- if (with_language) {
- t = strstrip(line + 2 + 1 + 32 + 1);
-
- r = catalog_entry_lang(path, n, t, deflang, &lang);
- if (r < 0)
- return r;
- }
-
- got_id = true;
- empty_line = false;
- id = jd;
-
- if (payload)
- payload[0] = '\0';
-
- continue;
- }
- }
-
- /* Payload */
- if (!got_id) {
- log_error("[%s:%u] Got payload before ID.", path, n);
- return -EINVAL;
- }
-
- a = payload ? strlen(payload) : 0;
- b = strlen(line);
-
- c = a + (empty_line ? 1 : 0) + b + 1 + 1;
- t = realloc(payload, c);
- if (!t)
- return log_oom();
-
- if (empty_line) {
- t[a] = '\n';
- memcpy(t + a + 1, line, b);
- t[a+b+1] = '\n';
- t[a+b+2] = 0;
- } else {
- memcpy(t + a, line, b);
- t[a+b] = '\n';
- t[a+b+1] = 0;
- }
-
- payload = t;
- empty_line = false;
- }
-
- if (got_id) {
- r = finish_item(h, id, lang ?: deflang, payload);
- if (r < 0)
- return r;
- payload = NULL;
- }
-
- return 0;
-}
-
-static int64_t write_catalog(const char *database, struct strbuf *sb,
- CatalogItem *items, size_t n) {
- CatalogHeader header;
- _cleanup_fclose_ FILE *w = NULL;
- int r;
- _cleanup_free_ char *d, *p = NULL;
- size_t k;
-
- d = dirname_malloc(database);
- if (!d)
- return log_oom();
-
- r = mkdir_p(d, 0775);
- if (r < 0)
- return log_error_errno(r, "Recursive mkdir %s: %m", d);
-
- r = fopen_temporary(database, &w, &p);
- if (r < 0)
- return log_error_errno(r, "Failed to open database for writing: %s: %m",
- database);
-
- zero(header);
- memcpy(header.signature, CATALOG_SIGNATURE, sizeof(header.signature));
- header.header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8));
- header.catalog_item_size = htole64(sizeof(CatalogItem));
- header.n_items = htole64(n);
-
- r = -EIO;
-
- k = fwrite(&header, 1, sizeof(header), w);
- if (k != sizeof(header)) {
- log_error("%s: failed to write header.", p);
- goto error;
- }
-
- k = fwrite(items, 1, n * sizeof(CatalogItem), w);
- if (k != n * sizeof(CatalogItem)) {
- log_error("%s: failed to write database.", p);
- goto error;
- }
-
- k = fwrite(sb->buf, 1, sb->len, w);
- if (k != sb->len) {
- log_error("%s: failed to write strings.", p);
- goto error;
- }
-
- r = fflush_and_check(w);
- if (r < 0) {
- log_error_errno(r, "%s: failed to write database: %m", p);
- goto error;
- }
-
- fchmod(fileno(w), 0644);
-
- if (rename(p, database) < 0) {
- r = log_error_errno(errno, "rename (%s -> %s) failed: %m", p, database);
- goto error;
- }
-
- return ftello(w);
-
-error:
- (void) unlink(p);
- return r;
-}
-
-int catalog_update(const char* database, const char* root, const char* const* dirs) {
- _cleanup_strv_free_ char **files = NULL;
- char **f;
- struct strbuf *sb = NULL;
- _cleanup_hashmap_free_free_free_ Hashmap *h = NULL;
- _cleanup_free_ CatalogItem *items = NULL;
- ssize_t offset;
- char *payload;
- CatalogItem *i;
- Iterator j;
- unsigned n;
- int r;
- int64_t sz;
-
- h = hashmap_new(&catalog_hash_ops);
- sb = strbuf_new();
-
- if (!h || !sb) {
- r = log_oom();
- goto finish;
- }
-
- r = conf_files_list_strv(&files, ".catalog", root, dirs);
- if (r < 0) {
- log_error_errno(r, "Failed to get catalog files: %m");
- goto finish;
- }
-
- STRV_FOREACH(f, files) {
- log_debug("Reading file '%s'", *f);
- r = catalog_import_file(h, *f);
- if (r < 0) {
- log_error_errno(r, "Failed to import file '%s': %m", *f);
- goto finish;
- }
- }
-
- if (hashmap_size(h) <= 0) {
- log_info("No items in catalog.");
- goto finish;
- } else
- log_debug("Found %u items in catalog.", hashmap_size(h));
-
- items = new(CatalogItem, hashmap_size(h));
- if (!items) {
- r = log_oom();
- goto finish;
- }
-
- n = 0;
- HASHMAP_FOREACH_KEY(payload, i, h, j) {
- log_debug("Found " SD_ID128_FORMAT_STR ", language %s",
- SD_ID128_FORMAT_VAL(i->id),
- isempty(i->language) ? "C" : i->language);
-
- offset = strbuf_add_string(sb, payload, strlen(payload));
- if (offset < 0) {
- r = log_oom();
- goto finish;
- }
- i->offset = htole64((uint64_t) offset);
- items[n++] = *i;
- }
-
- assert(n == hashmap_size(h));
- qsort_safe(items, n, sizeof(CatalogItem), catalog_compare_func);
-
- strbuf_complete(sb);
-
- sz = write_catalog(database, sb, items, n);
- if (sz < 0)
- r = log_error_errno(sz, "Failed to write %s: %m", database);
- else {
- r = 0;
- log_debug("%s: wrote %u items, with %zu bytes of strings, %"PRIi64" total size.",
- database, n, sb->len, sz);
- }
-
-finish:
- strbuf_cleanup(sb);
-
- return r;
-}
-
-static int open_mmap(const char *database, int *_fd, struct stat *_st, void **_p) {
- const CatalogHeader *h;
- int fd;
- void *p;
- struct stat st;
-
- assert(_fd);
- assert(_st);
- assert(_p);
-
- fd = open(database, O_RDONLY|O_CLOEXEC);
- if (fd < 0)
- return -errno;
-
- if (fstat(fd, &st) < 0) {
- safe_close(fd);
- return -errno;
- }
-
- if (st.st_size < (off_t) sizeof(CatalogHeader)) {
- safe_close(fd);
- return -EINVAL;
- }
-
- p = mmap(NULL, PAGE_ALIGN(st.st_size), PROT_READ, MAP_SHARED, fd, 0);
- if (p == MAP_FAILED) {
- safe_close(fd);
- return -errno;
- }
-
- h = p;
- if (memcmp(h->signature, CATALOG_SIGNATURE, sizeof(h->signature)) != 0 ||
- le64toh(h->header_size) < sizeof(CatalogHeader) ||
- le64toh(h->catalog_item_size) < sizeof(CatalogItem) ||
- h->incompatible_flags != 0 ||
- le64toh(h->n_items) <= 0 ||
- st.st_size < (off_t) (le64toh(h->header_size) + le64toh(h->catalog_item_size) * le64toh(h->n_items))) {
- safe_close(fd);
- munmap(p, st.st_size);
- return -EBADMSG;
- }
-
- *_fd = fd;
- *_st = st;
- *_p = p;
-
- return 0;
-}
-
-static const char *find_id(void *p, sd_id128_t id) {
- CatalogItem key, *f = NULL;
- const CatalogHeader *h = p;
- const char *loc;
-
- zero(key);
- key.id = id;
-
- loc = setlocale(LC_MESSAGES, NULL);
- if (loc && loc[0] && !streq(loc, "C") && !streq(loc, "POSIX")) {
- strncpy(key.language, loc, sizeof(key.language));
- key.language[strcspn(key.language, ".@")] = 0;
-
- f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
- if (!f) {
- char *e;
-
- e = strchr(key.language, '_');
- if (e) {
- *e = 0;
- f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
- }
- }
- }
-
- if (!f) {
- zero(key.language);
- f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
- }
-
- if (!f)
- return NULL;
-
- return (const char*) p +
- le64toh(h->header_size) +
- le64toh(h->n_items) * le64toh(h->catalog_item_size) +
- le64toh(f->offset);
-}
-
-int catalog_get(const char* database, sd_id128_t id, char **_text) {
- _cleanup_close_ int fd = -1;
- void *p = NULL;
- struct stat st = {};
- char *text = NULL;
- int r;
- const char *s;
-
- assert(_text);
-
- r = open_mmap(database, &fd, &st, &p);
- if (r < 0)
- return r;
-
- s = find_id(p, id);
- if (!s) {
- r = -ENOENT;
- goto finish;
- }
-
- text = strdup(s);
- if (!text) {
- r = -ENOMEM;
- goto finish;
- }
-
- *_text = text;
- r = 0;
-
-finish:
- if (p)
- munmap(p, st.st_size);
-
- return r;
-}
-
-static char *find_header(const char *s, const char *header) {
-
- for (;;) {
- const char *v;
-
- v = startswith(s, header);
- if (v) {
- v += strspn(v, WHITESPACE);
- return strndup(v, strcspn(v, NEWLINE));
- }
-
- if (!next_header(&s))
- return NULL;
- }
-}
-
-static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) {
- if (oneline) {
- _cleanup_free_ char *subject = NULL, *defined_by = NULL;
-
- subject = find_header(s, "Subject:");
- defined_by = find_header(s, "Defined-By:");
-
- fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n",
- SD_ID128_FORMAT_VAL(id),
- strna(defined_by), strna(subject));
- } else
- fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n",
- SD_ID128_FORMAT_VAL(id), s);
-}
-
-
-int catalog_list(FILE *f, const char *database, bool oneline) {
- _cleanup_close_ int fd = -1;
- void *p = NULL;
- struct stat st;
- const CatalogHeader *h;
- const CatalogItem *items;
- int r;
- unsigned n;
- sd_id128_t last_id;
- bool last_id_set = false;
-
- r = open_mmap(database, &fd, &st, &p);
- if (r < 0)
- return r;
-
- h = p;
- items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size));
-
- for (n = 0; n < le64toh(h->n_items); n++) {
- const char *s;
-
- if (last_id_set && sd_id128_equal(last_id, items[n].id))
- continue;
-
- assert_se(s = find_id(p, items[n].id));
-
- dump_catalog_entry(f, items[n].id, s, oneline);
-
- last_id_set = true;
- last_id = items[n].id;
- }
-
- munmap(p, st.st_size);
-
- return 0;
-}
-
-int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) {
- char **item;
- int r = 0;
-
- STRV_FOREACH(item, items) {
- sd_id128_t id;
- int k;
- _cleanup_free_ char *msg = NULL;
-
- k = sd_id128_from_string(*item, &id);
- if (k < 0) {
- log_error_errno(k, "Failed to parse id128 '%s': %m", *item);
- if (r == 0)
- r = k;
- continue;
- }
-
- k = catalog_get(database, id, &msg);
- if (k < 0) {
- log_full_errno(k == -ENOENT ? LOG_NOTICE : LOG_ERR, k,
- "Failed to retrieve catalog entry for '%s': %m", *item);
- if (r == 0)
- r = k;
- continue;
- }
-
- dump_catalog_entry(f, id, msg, oneline);
- }
-
- return r;
-}
diff --git a/src/journal/catalog.h b/src/journal/catalog.h
deleted file mode 100644
index 1b1014b335..0000000000
--- a/src/journal/catalog.h
+++ /dev/null
@@ -1,36 +0,0 @@
-#pragma once
-
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <stdbool.h>
-
-#include "sd-id128.h"
-
-#include "hashmap.h"
-#include "strbuf.h"
-
-int catalog_import_file(Hashmap *h, const char *path);
-int catalog_update(const char* database, const char* root, const char* const* dirs);
-int catalog_get(const char* database, sd_id128_t id, char **data);
-int catalog_list(FILE *f, const char* database, bool oneline);
-int catalog_list_items(FILE *f, const char* database, bool oneline, char **items);
-int catalog_file_lang(const char *filename, char **lang);
-extern const char * const catalog_file_dirs[];
-extern const struct hash_ops catalog_hash_ops;
diff --git a/src/journal/catalog/systemd.be.catalog b/src/journal/catalog/systemd.be.catalog
new file mode 100644
index 0000000000..be081d6efc
--- /dev/null
+++ b/src/journal/catalog/systemd.be.catalog
@@ -0,0 +1,260 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2015 Viktar Vaŭčkievič
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Belarusian translation
+
+# The catalog format is documented on
+# Фармат каталога апісаны на старонцы
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Сэрвіс журналявання запусціўся
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Працэс сістэмнага журналявання запусціўся, адкрыў файлы для
+запісу і гатовы апрацоўваць запыты.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Сэрвіс журналявання спыніўся
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Працэс сістэмнага журналявання спыніўся і закрыў усе файлы.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Паведамленні з сэрвісу адкінуты
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Сэрвіс адправіў занадта штат паведамленняў за кароткі прамежак часу.
+Частка паведамленняў была адкінута.
+
+Майце на ўвазе, што былі адкінуты паведамлення толькі гэтага сэрвісу.
+Паведамленні іншых сэрвісаў засталіся.
+
+Мяжа, пасля якой паведамленні будуць адкінуты, наладжваецца з
+дапамогай RateLimitInterval= і RateLimitBurst= у файле
+/etc/systemd/journald.conf. Глядзіце journald.conf(5) для дэталей.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Паведамленні страчаны
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Паведамленні ядра былі страчаны, так як сістэма журналявання не паспела
+іх апрацаваць.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Працэс @COREDUMP_PID@ (@COREDUMP_COMM@) скінуў дамп памяці
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Працэс @COREDUMP_PID@ (@COREDUMP_COMM@) разбіўся і скінуў дамп памяці.
+
+Звычайна гэта сведчыць аб памылцы ў праграмным кодзе.
+Рэкамендуецца паведаміць аб гэтым распрацоўнікам.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Новая сесія № @SESSION_ID@ створана для карыстальніка @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Новая сесія з № @SESSION_ID@ створана для карыстальніка @USER_ID@.
+
+Лідар гэтай сесіі пад № @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Сесія № @SESSION_ID@ спынена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Сесія № @SESSION_ID@ спынена.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Даступна новае працоўнае месца № @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Новае працоўнае месца № @SEAT_ID@ наладжана і даступна для выкарыстання.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Працоўнае месца № @SEAT_ID@ выдалена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Працоўнае месца № @SEAT_ID@ выдалена і больш не даступна.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Час зменены
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Сістэмны гадзіннік зменены на @REALTIME@ мікрасекунд ад 1 студзеня 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Часавы пояс зменены на @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Сістэмны часавы пояс зменены на @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Запуск сістэмы завяршыўся
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Усе сістэмныя сэрвісы, неабходныя для загрузкі сістэмы, паспяхова
+запусціліся. Майце на ўвазе, што гэта не значыць, што машына нічога не
+робіць. Магчыма, некаторыя сэрвісы яшчэ ініцыялізіруюцца.
+
+На запуск ядра спатрэбілася @KERNEL_USEC@ мікрасекунд.
+
+На запуск пачатковага RAM-дыска спатрэбілася @INITRD_USEC@ мікрасекунд.
+
+На запуск сістэмных сэрвісаў спатрэбілася @USERSPACE_USEC@ мікрасекунд.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Сістэма перайшла ў стан сну @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Цяпер сістэма перайшла у стан сну @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Сістэма выйшла са стана сну @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Цяпер сістэма выйшла са стана сну @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Сістэма завяршае работу
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Пачаўся працэс выключэння сістэмы.
+Спыняюцца ўсе сістэмныя сэрвісы і дэмантуюцца файлавыя сістэмы.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Юніт @UNIT@ запускаецца
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Пачаўся працэс запуску юніта @UNIT@.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Юніт @UNIT@ запусціўся
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Працэс запуску юніта @UNIT@ завершаны.
+
+Вынік: @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Юніт @UNIT@ спыняецца
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Пачаўся працэс спынення юніта @UNIT@.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Юніт @UNIT@ спынены
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Працэс спынення юніта @UNIT@ завершаны.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Збой юніта @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Збой юніта @UNIT@.
+
+Вынік: @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Юніт @UNIT@ перачытвае сваю канфігурацыю
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Юніт @UNIT@ пачаў перачытваць сваю канфігурацыю.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Юніт @UNIT@ перачытаў сваю канфігурацыю
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Юніт @UNIT@ перачытаў сваю канфігурацыю.
+
+Вынік: @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Працэс @EXECUTABLE@ не можа быць выкананы
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Працэс @EXECUTABLE@ не можа быць выкананы ў выніку збою.
+
+Ён вярнуў памылку нумар @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Sibject: Адно ці больш паведамленняў не былі накіраваны ў syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Адно ці больш паведамленняў не былі накіраваны ў syslog сэрвіс, які
+выконваецца паралельна з journald. Звычайна гэта значыць, што
+рэалізацыя syslog не паспявае апрацаваць паведамленні з неабходнай
+хуткасцю.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Кропка мантавання не пустая
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Каталог @WHERE@ указаны як кропка мантавання (другое поле ў /etc/fstab
+ці Where= поле ў файле юніта systemd) і не пусты. Гэта не перашкаджае
+мантаванню, але існуючыя ў ім файлы будуць недаступны. Для доступу да
+іх, калі ласка, змантуйце гэтую файлавую сістэму ў іншае месца.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Віртуальная машына або кантэйнер запусціўся
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Віртуальная машына @NAME@ з лідарам № @LEADER@ запусцілася і
+гатова для выкарыстання.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Віртуальная машына або кантэйнер спынены
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Віртуальная машына @NAME@ з лідарам № @LEADER@ спынена.
diff --git a/src/journal/catalog/systemd.be@latin.catalog b/src/journal/catalog/systemd.be@latin.catalog
new file mode 100644
index 0000000000..382fdb8b04
--- /dev/null
+++ b/src/journal/catalog/systemd.be@latin.catalog
@@ -0,0 +1,260 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2015 Viktar Vaŭčkievič
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Belarusian Latin translation
+
+# The catalog format is documented on
+# Farmat kataloha apisany na staroncy
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Servis žurnaliavannia zapusciŭsia
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Praces sistemnaha žurnaliavannia zapusciŭsia, adkryŭ fajly dlia
+zapisu i hatovy apracoŭvać zapyty.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Servis žurnaliavannia spyniŭsia
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Praces sistemnaha žurnaliavannia spyniŭsia i zakryŭ usie fajly.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Paviedamlienni z servisu adkinuty
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Servis adpraviŭ zanadta štat paviedamlienniaŭ za karotki pramiežak času.
+Častka paviedamlienniaŭ byla adkinuta.
+
+Majcie na ŭvazie, što byli adkinuty paviedamliennia toĺki hetaha servisu.
+Paviedamlienni inšych servisaŭ zastalisia.
+
+Miaža, paslia jakoj paviedamlienni buduć adkinuty, naladžvajecca z
+dapamohaj RateLimitInterval= i RateLimitBurst= u fajlie
+/etc/systemd/journald.conf. Hliadzicie journald.conf(5) dlia detaliej.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Paviedamlienni stračany
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Paviedamlienni jadra byli stračany, tak jak sistema žurnaliavannia nie paspiela
+ich apracavać.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Praces @COREDUMP_PID@ (@COREDUMP_COMM@) skinuŭ damp pamiaci
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Praces @COREDUMP_PID@ (@COREDUMP_COMM@) razbiŭsia i skinuŭ damp pamiaci.
+
+Zvyčajna heta sviedčyć ab pamylcy ŭ prahramnym kodzie.
+Rekamiendujecca paviedamić ab hetym raspracoŭnikam.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Novaja siesija № @SESSION_ID@ stvorana dlia karystaĺnika @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Novaja siesija z № @SESSION_ID@ stvorana dlia karystaĺnika @USER_ID@.
+
+Lidar hetaj siesii pad № @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Siesija № @SESSION_ID@ spyniena
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Siesija № @SESSION_ID@ spyniena.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Dastupna novaje pracoŭnaje miesca № @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Novaje pracoŭnaje miesca № @SEAT_ID@ naladžana i dastupna dlia vykarystannia.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Pracoŭnaje miesca № @SEAT_ID@ vydaliena
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Pracoŭnaje miesca № @SEAT_ID@ vydaliena i boĺš nie dastupna.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Čas zmienieny
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Sistemny hadzinnik zmienieny na @REALTIME@ mikrasiekund ad 1 studzienia 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Časavy pojas zmienieny na @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Sistemny časavy pojas zmienieny na @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Zapusk sistemy zaviaršyŭsia
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Usie sistemnyja servisy, nieabchodnyja dlia zahruzki sistemy, paspiachova
+zapuscilisia. Majcie na ŭvazie, što heta nie značyć, što mašyna ničoha nie
+robić. Mahčyma, niekatoryja servisy jašče inicyjalizirujucca.
+
+Na zapusk jadra spatrebilasia @KERNEL_USEC@ mikrasiekund.
+
+Na zapusk pačatkovaha RAM-dyska spatrebilasia @INITRD_USEC@ mikrasiekund.
+
+Na zapusk sistemnych servisaŭ spatrebilasia @USERSPACE_USEC@ mikrasiekund.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Sistema pierajšla ŭ stan snu @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Ciapier sistema pierajšla u stan snu @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Sistema vyjšla sa stana snu @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Ciapier sistema vyjšla sa stana snu @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Sistema zaviaršaje rabotu
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Pačaŭsia praces vykliučennia sistemy.
+Spyniajucca ŭsie sistemnyja servisy i demantujucca fajlavyja sistemy.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Junit @UNIT@ zapuskajecca
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Pačaŭsia praces zapusku junita @UNIT@.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Junit @UNIT@ zapusciŭsia
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Praces zapusku junita @UNIT@ zavieršany.
+
+Vynik: @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Junit @UNIT@ spyniajecca
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Pačaŭsia praces spyniennia junita @UNIT@.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Junit @UNIT@ spynieny
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Praces spyniennia junita @UNIT@ zavieršany.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Zboj junita @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Zboj junita @UNIT@.
+
+Vynik: @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Junit @UNIT@ pieračytvaje svaju kanfihuracyju
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Junit @UNIT@ pačaŭ pieračytvać svaju kanfihuracyju.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Junit @UNIT@ pieračytaŭ svaju kanfihuracyju
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Junit @UNIT@ pieračytaŭ svaju kanfihuracyju.
+
+Vynik: @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Praces @EXECUTABLE@ nie moža być vykanany
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Praces @EXECUTABLE@ nie moža być vykanany ŭ vyniku zboju.
+
+Jon viarnuŭ pamylku numar @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Sibject: Adno ci boĺš paviedamlienniaŭ nie byli nakiravany ŭ syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Adno ci boĺš paviedamlienniaŭ nie byli nakiravany ŭ syslog servis, jaki
+vykonvajecca paralieĺna z journald. Zvyčajna heta značyć, što
+realizacyja syslog nie paspiavaje apracavać paviedamlienni z nieabchodnaj
+chutkasciu.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Kropka mantavannia nie pustaja
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Kataloh @WHERE@ ukazany jak kropka mantavannia (druhoje polie ŭ /etc/fstab
+ci Where= polie ŭ fajlie junita systemd) i nie pusty. Heta nie pieraškadžaje
+mantavanniu, alie isnujučyja ŭ im fajly buduć niedastupny. Dlia dostupu da
+ich, kali laska, zmantujcie hetuju fajlavuju sistemu ŭ inšaje miesca.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Virtuaĺnaja mašyna abo kantejnier zapusciŭsia
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Virtuaĺnaja mašyna @NAME@ z lidaram № @LEADER@ zapuscilasia i
+hatova dlia vykarystannia.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Virtuaĺnaja mašyna abo kantejnier spynieny
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Virtuaĺnaja mašyna @NAME@ z lidaram № @LEADER@ spyniena.
diff --git a/src/journal/catalog/systemd.catalog b/src/journal/catalog/systemd.catalog
new file mode 100644
index 0000000000..077f182a5a
--- /dev/null
+++ b/src/journal/catalog/systemd.catalog
@@ -0,0 +1,334 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+
+# The catalog format is documented on
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: The journal has been started
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system journal process has started up, opened the journal
+files for writing and is now ready to process requests.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: The journal has been stopped
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system journal process has shut down and closed all currently
+active journal files.
+
+-- ec387f577b844b8fa948f33cad9a75e6
+Subject: Disk space used by the journal
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@JOURNAL_NAME@ (@JOURNAL_PATH@) is currently using @CURRENT_USE_PRETTY@.
+Maximum allowed usage is set to @MAX_USE_PRETTY@.
+Leaving at least @DISK_KEEP_FREE_PRETTY@ free (of currently available @DISK_AVAILABLE_PRETTY@ of disk space).
+Enforced usage limit is thus @LIMIT_PRETTY@, of which @AVAILABLE_PRETTY@ are still available.
+
+The limits controlling how much disk space is used by the journal may
+be configured with SystemMaxUse=, SystemKeepFree=, SystemMaxFileSize=,
+RuntimeMaxUse=, RuntimeKeepFree=, RuntimeMaxFileSize= settings in
+/etc/systemd/journald.conf. See journald.conf(5) for details.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Messages from a service have been suppressed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+A service has logged too many messages within a time period. Messages
+from the service have been dropped.
+
+Note that only messages from the service in question have been
+dropped, other services' messages are unaffected.
+
+The limits controlling when messages are dropped may be configured
+with RateLimitInterval= and RateLimitBurst= in
+/etc/systemd/journald.conf. See journald.conf(5) for details.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Journal messages have been missed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Kernel messages have been lost as the journal system has been unable
+to process them quickly enough.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Process @COREDUMP_PID@ (@COREDUMP_COMM@) dumped core
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Process @COREDUMP_PID@ (@COREDUMP_COMM@) crashed and dumped core.
+
+This usually indicates a programming error in the crashing program and
+should be reported to its vendor as a bug.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1 de
+Subject: Speicherabbild für Prozess @COREDUMP_PID@ (@COREDUMP_COMM) generiert
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Prozess @COREDUMP_PID@ (@COREDUMP_COMM@) ist abgebrochen worden und
+ein Speicherabbild wurde generiert.
+
+Üblicherweise ist dies ein Hinweis auf einen Programmfehler und sollte
+als Fehler dem jeweiligen Hersteller gemeldet werden.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: A new session @SESSION_ID@ has been created for user @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A new session with the ID @SESSION_ID@ has been created for the user @USER_ID@.
+
+The leading process of the session is @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Session @SESSION_ID@ has been terminated
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A session with the ID @SESSION_ID@ has been terminated.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: A new seat @SEAT_ID@ is now available
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A new seat @SEAT_ID@ has been configured and is now available.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Seat @SEAT_ID@ has now been removed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A seat @SEAT_ID@ has been removed and is no longer available.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Time change
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system clock has been changed to @REALTIME@ microseconds after January 1st, 1970.
+
+-- c7a787079b354eaaa9e77b371893cd27 de
+Subject: Zeitänderung
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Die System-Zeit wurde geändert auf @REALTIME@ Mikrosekunden nach dem 1. Januar 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Time zone change to @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system timezone has been changed to @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: System start-up is now complete
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+All system services necessary queued for starting at boot have been
+successfully started. Note that this does not mean that the machine is
+now idle as services might still be busy with completing start-up.
+
+Kernel start-up required @KERNEL_USEC@ microseconds.
+
+Initial RAM disk start-up required @INITRD_USEC@ microseconds.
+
+Userspace start-up required @USERSPACE_USEC@ microseconds.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: System sleep state @SLEEP@ entered
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system has now entered the @SLEEP@ sleep state.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: System sleep state @SLEEP@ left
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The system has now left the @SLEEP@ sleep state.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: System shutdown initiated
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemd shutdown has been initiated. The shutdown has now begun and
+all system services are terminated and all file systems unmounted.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Unit @UNIT@ has begun start-up
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has begun starting up.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Unit @UNIT@ has finished start-up
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has finished starting up.
+
+The start-up result is @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Unit @UNIT@ has begun shutting down
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has begun shutting down.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Unit @UNIT@ has finished shutting down
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has finished shutting down.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Unit @UNIT@ has failed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has failed.
+
+The result is @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Unit @UNIT@ has begun reloading its configuration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has begun reloading its configuration
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Unit @UNIT@ has finished reloading its configuration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Unit @UNIT@ has finished reloading its configuration
+
+The result is @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Process @EXECUTABLE@ could not be executed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The process @EXECUTABLE@ could not be executed and failed.
+
+The error number returned by this process is @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: One or more messages could not be forwarded to syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+One or more messages could not be forwarded to the syslog service
+running side-by-side with journald. This usually indicates that the
+syslog implementation has not been able to keep up with the speed of
+messages queued.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Mount point is not empty
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The directory @WHERE@ is specified as the mount point (second field in
+/etc/fstab or Where= field in systemd unit file) and is not empty.
+This does not interfere with mounting, but the pre-exisiting files in
+this directory become inaccessible. To see those over-mounted files,
+please manually mount the underlying file system to a secondary
+location.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: A virtual machine or container has been started
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The virtual machine @NAME@ with its leader PID @LEADER@ has been
+started is now ready to use.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: A virtual machine or container has been terminated
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+The virtual machine @NAME@ with its leader PID @LEADER@ has been
+shut down.
+
+-- 36db2dfa5a9045e1bd4af5f93e1cf057
+Subject: DNSSEC mode has been turned off, as server doesn't support it
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8) resolved.conf(5)
+
+The resolver service (systemd-resolved.service) has detected that the
+configured DNS server does not support DNSSEC, and DNSSEC validation has been
+turned off as result.
+
+This event will take place if DNSSEC=allow-downgrade is configured in
+resolved.conf and the configured DNS server is incompatible with DNSSEC. Note
+that using this mode permits DNSSEC downgrade attacks, as an attacker might be
+able turn off DNSSEC validation on the system by inserting DNS replies in the
+communication channel that result in a downgrade like this.
+
+This event might be indication that the DNS server is indeed incompatible with
+DNSSEC or that an attacker has successfully managed to stage such a downgrade
+attack.
+
+-- 1675d7f172174098b1108bf8c7dc8f5d
+Subject: DNSSEC validation failed
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8)
+
+A DNS query or resource record set failed DNSSEC validation. This is usually
+indication that the communication channel used was tampered with.
+
+-- 4d4408cfd0d144859184d1e65d7c8a65
+Subject: A DNSSEC trust anchor has been revoked
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8)
+
+A DNSSEC trust anchor has been revoked. A new trust anchor has to be
+configured, or the operating system needs to be updated, to provide an updated
+DNSSEC trust anchor.
diff --git a/src/journal/catalog/systemd.da.catalog b/src/journal/catalog/systemd.da.catalog
new file mode 100644
index 0000000000..bd4d742d8a
--- /dev/null
+++ b/src/journal/catalog/systemd.da.catalog
@@ -0,0 +1,261 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Danish translation
+
+# The catalog format is documented on
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Journalen er blevet startet
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+System-journal processen har startet op, åbnet journal filerne for
+tilskrivning og er nu klar til at modtage anmodninger.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Journalen er blevet stoppet
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+System-journal processen er stoppet og har lukket alle aktive journal
+filer.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Beskeder fra en service er blevet undertrykt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+En service har logget for mange beskeder inden for en given tidsperiode.
+Beskeder fra omtalte service er blevet smidt væk.
+
+Kun beskeder fra omtalte service er smidt væk. Beskeder fra andre
+services er ikke påvirket.
+
+Grænsen for hvornår beskeder bliver smidt væk kan konfigureres
+med RateLimitInterval= og RateLimitBurst= i
+/etc/systemd/journald.conf. Se journald.conf(5) for detaljer herom.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Journal beskeder er gået tabt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Kernel beskeder er gået tabt da journal systemet ikke har været i stand
+til at håndtere dem hurtigt nok.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Fejl-fil genereret for process @COREDUMP_PID@ (@COREDUMP_COMM@)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Process @COREDUMP_PID@ (@COREDUMP_COMM@) har lukket ned og genereret en
+fejl-fil.
+
+Dette indikerer som regel en programmeringsfejl i det nedlukkede program
+og burde blive reporteret som en bug til folkene bag
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: En ny session @SESSION_ID@ er blevet lavet for bruger @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+En ny session med ID @SESSION_ID@ er blevet lavet for brugeren @USER_ID@.
+
+Den ledende process for sessionen er @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Session @SESSION_ID@ er blevet lukket ned
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+En session med ID @SESSION_ID@ er blevet lukket ned.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: En ny arbejdsstation $SEAT_ID@ er nu tilgængelig
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+En ny arbejdsstation @SEAT_ID@ er blevet konfigureret og er nu tilgængelig.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Arbejdsstation @SEAT_ID@ er nu blevet fjernet
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+En arbejdsstation @SEAT_ID@ er blevet fjernet og er ikke længere tilgængelig.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Tidsændring
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemtiden er blevet ændret til @REALTIME@ mikrosekunder efter d. 1. Januar 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Tidszoneændring til @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Tidszonen for systemet er blevet ændret til @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Opstart af systemet er nu fuldført
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Alle system services i kø til at køre ved opstart, er blevet startet
+med success. Bemærk at dette ikke betyder at maskinen er i dvale, da
+services stadig kan være i gang med at færdiggøre deres opstart.
+
+Opstart af kernel tog @KERNEL_USEC@ mikrosekunder.
+
+Opstart af initrd tog @INITRD_USEC@ mikrosekunder.
+
+Opstart af userspace tog @USERSPACE_USEC@ mikrosekunder.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: System slumretilstand @SLEEP@ trådt i kraft
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+System er nu gået i @SLEEP@ slumretilstand.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: System slumretilstand @SLEEP@ forladt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemet har nu forladt @SLEEP@ slumretilstand.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Systemnedlukning påbegyndt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemnedlukning er blevet påbegyndt. Nedlukningen er nu begyndt og
+alle system services er blevet afbrudt og alle filsystemer afmonteret.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Enhed @UNIT@ har påbegyndt opstart
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ er begyndt at starte op.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Enhed @UNIT har færdiggjort opstart
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ er færdig med at starte op.
+
+Resultat for opstart er @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Enhed @UNIT@ har påbegyndt nedlukning
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ har påbegyndt nedlukning.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Enhed @UNIT@ har færdiggjort nedlukning
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ har færdiggjort nedlukning.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Enhed @UNIT@ har fejlet
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ har fejlet.
+
+Resultatet er @RESULT@
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Enhed @UNIT@ har påbegyndt genindlæsning af sin konfiguration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ er begyndt at genindlæse sin konfiguration
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Enhed @UNIT@ har færdiggjort genindlæsning af sin konfiguration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Enhed @UNIT@ er færdig med at genindlæse sin konfiguration
+
+Resultatet er: @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Process @EXECUTABLE@ kunne ikke eksekveres
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Processen @EXECUTABLE@ kunne ikke eksekveres og fejlede.
+
+Processens returnerede fejlkode er @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Èn eller flere beskeder kunne ikke videresendes til syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Èn eller flere beskeder kunne ikke videresendes til syslog servicen
+der kører side-om-side med journald. Dette indikerer typisk at syslog
+implementationen ikke har kunnet følge med mængden af ventende beskeder.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Monteringspunkt er ikke tomt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Folderen @WHERE@ er specificeret som monteringspunkt (andet felt i
+/etc/fstab eller Where= feltet i systemd enhedsfil) men er ikke tom.
+Dette forstyrrer ikke monteringen, men de pre-eksisterende filer i folderen
+bliver utilgængelige. For at se de over-monterede filer; montér det
+underlæggende filsystem til en anden lokation.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: En virtuel maskine eller container er blevet startet
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Den virtuelle maskine @NAME@ med dens leder PID @LEADER@ er blevet
+startet og er klar til brug.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: En virtuel maskine eller container er blevet afbrudt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Den virtuelle maskine @NAME@ med dens leder PID @LEADER@ er blevet
+nedlukket.
diff --git a/src/journal/catalog/systemd.fr.catalog b/src/journal/catalog/systemd.fr.catalog
new file mode 100644
index 0000000000..03a457786f
--- /dev/null
+++ b/src/journal/catalog/systemd.fr.catalog
@@ -0,0 +1,260 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2013-2015 Sylvain Plantefève
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# French translation
+
+# Le format du catalogue de messages est décrit (en anglais) içi :
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Le journal a été démarré
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le processus du journal système a démarré, ouvert ses fichiers en écriture
+et est prêt à traiter les requêtes.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Le journal a été arrêté
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le processus du journal système a été arrêté et tous ses fichiers actifs
+ont été fermés.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Des messages d'un service ont été supprimés
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Un service a essayé d'enregistrer un trop grand nombre de messages sur un
+intervalle de temps donné. Des messages de ce service ont été évincés.
+
+Notez que seuls des messages de ce service ont été évincés, les messages des
+autres services ne sont pas affectés.
+
+Les limites définissant ce comportement peuvent être configurées avec les
+paramètres RateLimitInterval= et RateLimitBurst= dans le fichier
+/etc/systemd/journald.conf. Voir journald.conf(5) pour plus de détails.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Des messages du journal ont été manqués
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Des messages du noyau ont été manqués car le journal système n'a pas été
+capable de les traiter suffisamment vite.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Le processus @COREDUMP_PID@ (@COREDUMP_COMM@) a généré un fichier « core »
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Le processus @COREDUMP_PID@ (@COREDUMP_COMM@) a planté et généré un fichier « core ».
+
+Cela indique généralement une erreur de programmation dans le programme
+incriminé, et cela devrait être notifié à son concepteur comme un défaut (bug).
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Une nouvelle session @SESSION_ID@ a été créée pour l'utilisateur @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Une nouvelle session a été créée pour l'utilisateur @USER_ID@ avec
+l'identifiant (ID) @SESSION_ID@.
+
+Le processus maître de la session est @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: La session @SESSION_ID@ s'est terminée
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+La session d'identifiant (ID) @SESSION_ID@ s'est terminée.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Un nouveau poste (seat) @SEAT_ID@ est disponible
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Un nouveau poste (seat) @SEAT_ID@ a été configuré et est maintenant disponible.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Le poste (seat) @SEAT_ID@ a été retiré
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Le poste (seat) @SEAT_ID@ a été retiré et n'est plus disponible.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Changement d'heure
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'horloge système a été modifiée et positionnée à @REALTIME@ microsecondes
+après le 1er janvier 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Fuseau horaire modifié en @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le fuseau horaire du système a été modifié et positionné à @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Le démarrage du système est terminé
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Tous les services nécessaires au démarrage du système ont été lancés avec
+succès. Notez que cela ne signifie pas que le système est maintenant au
+repos, car des services peuvent encore être en train de terminer leur
+démarrage.
+
+Le chargement du noyau a nécessité @KERNEL_USEC@ microsecondes.
+
+Le chargement du « RAM disk » initial a nécessité @INITRD_USEC@ microsecondes.
+
+Le chargement de l'espace utilisateur a nécessité @USERSPACE_USEC@ microsecondes.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Le système entre dans l'état de repos (sleep state) @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le système est maintenant à l'état de repos (sleep state) @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Le système sorti de l'état de repos (sleep state) @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le système est maintenant sorti de l'état de repos (sleep state) @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Arrêt du système amorcé
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'arrêt du système a été amorcé. L'arrêt a maintenant commencé, tous les
+services du système sont terminés et tous les systèmes de fichiers sont
+démontés.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: L'unité (unit) @UNIT@ a commencé à démarrer
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a commencé à démarrer.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: L'unité (unit) @UNIT@ a terminé son démarrage
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a terminé son démarrage, avec le résultat @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: L'unité (unit) @UNIT@ a commencé à s'arrêter
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a commencé à s'arrêter.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: L'unité (unit) @UNIT@ a terminé son arrêt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a terminé son arrêt.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: L'unité (unit) @UNIT@ a échoué
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a échoué, avec le résultat @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: L'unité (unit) @UNIT@ a commencé à recharger sa configuration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a commencé à recharger sa configuration.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: L'unité (unit) @UNIT@ a terminé de recharger configuration
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unité (unit) @UNIT@ a terminé de recharger configuration,
+avec le résultat @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Le processus @EXECUTABLE@ n'a pas pu être exécuté
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le processus @EXECUTABLE@ n'a pas pu être exécuté, et a donc échoué.
+
+Le code d'erreur renvoyé est @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Un ou plusieurs messages n'ont pas pu être transmis à syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Un ou plusieurs messages n'ont pas pu être transmis au service syslog
+s'exécutant conjointement avec journald. Cela indique généralement que
+l'implémentation de syslog utilisée n'a pas été capable de suivre la cadence
+du flux de messages.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Le point de montage n'est pas vide
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Le répertoire @WHERE@ est spécifié comme point de montage (second champ du
+fichier /etc/fstab, ou champ Where= dans une unité (unit) systemd) et n'est pas
+vide.
+Cela ne perturbe pas le montage du système de fichiers, mais les fichiers
+préalablement présents dans ce répertoire sont devenus inaccessibles.
+Pour atteindre ces fichiers, veuillez monter manuellement le système de
+fichiers sous-jacent à un autre emplacement.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Une machine virtuelle ou un conteneur (container) a été démarré
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+La machine virtuelle @NAME@ a été démarrée avec le PID maître @LEADER@,
+et est maintenant prête à l'emploi.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Une machine virtuelle ou un conteneur (container) a été arrêté
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+La machine virtuelle @NAME@ avec le PID maître @LEADER@ a été arrêtée.
diff --git a/src/journal/catalog/systemd.hu.catalog b/src/journal/catalog/systemd.hu.catalog
new file mode 100644
index 0000000000..30d76916cc
--- /dev/null
+++ b/src/journal/catalog/systemd.hu.catalog
@@ -0,0 +1,262 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2016 Gabor Kelemen
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+
+# The catalog format is documented on
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: A napló elindult
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszernapló folyamat elindult, megnyitotta írásra a naplófájlokat,
+és most készen áll kérések feldolgozására.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: A napló leállt
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszernapló folyamat leállt, és bezárt minden jelenleg aktív naplófájlt.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Egy szolgáltatás üzenetei elnémítva
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Egy szolgáltatás túl sok üzenetet naplózott adott idő alatt. A
+szolgáltatástól származó üzenetek eldobásra kerültek.
+
+Ne feledje, hogy csak a kérdéses szolgáltatás üzenetei kerültek eldobásra,
+ más szolgáltatások üzeneteit ez nem befolyásolja.
+
+Az üzenetek eldobását vezérlő korlátok az /etc/systemd/journald.conf
+RateLimitInterval= és RateLimitBurst= beállításaival adhatók meg.
+Részletekért lásd a journald.conf(5) man oldalt.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Naplóüzenetek vesztek el
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Kernelüzenetek vesztek el, mert a naplózó rendszer nem tudta elég gyorsan
+feldolgozni azokat.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Egy folyamat összeomlott: @COREDUMP_PID@ (@COREDUMP_COMM@)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Ez a folyamat: @COREDUMP_PID@ (@COREDUMP_COMM@) összeomlott, és core fájlt
+ írt ki.
+
+Ez általában programozási hibát jelez az összeomló programban, és
+a szállítója felé kell bejelenteni.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Új munkamenet (@SESSION_ID@) létrehozva, felhasználója: @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Létrejött egy új munkamenet @SESSION_ID@ azonosítóval ezen felhasználóhoz:
+@USER_ID@.
+
+A munkamenet vezető folyamata: @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Munkamenet (@SESSION_ID@) befejezve
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A következő azonosítójú munkamenet befejeződött: @SESSION_ID@.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Elérhető egy új munkaállomás: @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Beállításra kerül és használható egy új munkaállomás: @SEAT_ID@.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: A munkaállomás eltávolítva: @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+A munkaállomás el lett távolítva, és már nem érhető el: @SEAT_ID@
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Időmódosítás
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszeróra beállítva @REALTIME@ ezredmásodpercre 1970. január 1. után.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Időzóna-módosítás erre: @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszer időzónája módosítva lett erre: @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: A rendszer indítása kész
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszerindításkor szükséges indításhoz sorba állított összes
+rendszerszolgáltatás elindult. Ne feledje, hogy ez nem jelenti, hogy a
+gép üresjáratban van, mivel egyes szolgáltatások még az indítás
+befejezésével lehetnek elfoglalva.
+
+A kernel indítása @KERNEL_USEC@ ezredmásodpercet igényelt.
+
+A kiinduló RAM lemez indítása @INITRD_USEC@ ezredmásodpercet igényelt.
+
+A felhasználói programok indítása @USERSPACE_USEC@ ezredmásodpercet igényelt.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: A rendszer „@SLEEP@” alvási állapotba lépett
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszer belépett ebbe az alvási állapotba: @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: A rendszer „@SLEEP@” alvási állapotból kilépett
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A rendszer kilépett ebből az alvási állapotból: @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Rendszer leállítása kezdeményezve
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A systemd leállítása kezdeményezve. A leállítás megkezdődött, minden
+rendszerszolgáltatás befejeződik, minden fájlrendszer leválasztásra kerül.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: A(z) @UNIT@ egység indítása megkezdődött
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység megkezdte az indulást.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: A(z) @UNIT@ egység befejezte az indulást
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység befejezte az indulást
+
+Az indítás eredménye: @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: A(z) @UNIT@ egység megkezdte a leállást
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység megkezdte a leállást.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: A(z) @UNIT@ egység befejezte a leállást
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység befejezte a leállást.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: A(z) @UNIT@ egység hibát jelzett
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység hibát jelzett.
+
+Az eredmény: @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: A(z) @UNIT@ egység megkezdte a beállításainak újratöltését
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység megkezdte a beállításainak újratöltését.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: A(z) @UNIT@ egység befejezte a beállításainak újratöltését
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @UNIT@ egység befejezte a beállításainak újratöltését.
+
+Az eredmény: @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: A folyamat végrehajtása sikertelen: @EXECUTABLE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A folyamat végrehajtása sikertelen volt, és hibát jelzett: @EXECUTABLE@.
+
+A folyamat által visszaadott hibaszám: @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Legalább egy üzenet nem továbbítható a rendszernaplónak
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Legalább egy üzenet nem volt továbbítható a journald-vel párhuzamosan futó
+syslog szolgáltatásnak. Ez általában azt jelenti, hogy a syslog
+megvalósítás nem volt képes lépést tartani a sorba állított
+üzenetek sebességével.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: A csatolási pont nem üres
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A csatolási pontként megadott @WHERE@ könyvtár (második mező az /etc/fstab
+fájlban, vagy a Where= sor a systemd egységfájlban) nem üres. Ez nem
+akadályozza meg a csatolást, de a könyvtárban már meglévő fájlok
+elérhetetlenné válnak. A fájlok láthatóvá tételéhez csatolja
+az azokat tartalmazó fájlrendszert egy másodlagos helyre.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Egy virtuális gép vagy konténer elindult
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @NAME@ nevű virtuális gép (vezető PID: @LEADER@) elindult, és
+használatra kész.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Egy virtuális gép vagy konténer befejeződött
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A(z) @NAME@ nevű virtuális gép (vezető PID: @LEADER@) leállt.
diff --git a/src/journal/catalog/systemd.it.catalog b/src/journal/catalog/systemd.it.catalog
new file mode 100644
index 0000000000..861b92b74a
--- /dev/null
+++ b/src/journal/catalog/systemd.it.catalog
@@ -0,0 +1,254 @@
+# This file is part of systemd.
+#
+# Copyright 2013 Daniele Medri
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Il registro è stato avviato
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il processo relativo al registro di sistema è stato avviato, ha aperto i
+file in scrittura ed è ora pronto a gestire richieste.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Il registro è stato terminato
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il processo relativo al registro di sistema è stato terminato e ha chiuso
+tutti i file attivi.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: I messaggi di un servizio sono stati soppressi
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Un servizio ha registrato troppi messaggi in un dato periodo di tempo.
+I messaggi del servizio sono stati eliminati.
+
+Solo i messaggi del servizio indicato sono stati
+eliminati, i messaggi degli altri servizi rimangono invariati.
+
+I limiti oltre i quali i messaggi si eliminano si configurano
+con RateLimitInterval= e RateLimitBurst= in
+/etc/systemd/journald.conf. Vedi journald.conf(5) per maggiori informazioni.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: I messaggi di un servizio sono stati perduti
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+I messaggi del kernel sono stati perduti perché, il registro di sistema
+non è stato in grado di gestirli abbastanza velocemente.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Il processo @COREDUMP_PID@ (@COREDUMP_COMM@) ha generato un dump.
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Il processo @COREDUMP_PID@ (@COREDUMP_COMM@) si è bloccato generando un dump.
+
+Questo di solito capita per un errore di programmazione nell'applicazione e
+dovrebbe essere segnalato al vendor come un bug.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: La nuova sessione @SESSION_ID@ è stata creata per l'utente @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Una nuova sessione con ID @SESSION_ID@ è stata creata per l'utente @USER_ID@.
+
+Il processo primario della sessione è @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: La sessione @SESSION_ID@ è terminata
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+La sessione con ID @SESSION_ID@ è terminata.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: La nuova postazione @SEAT_ID@ è ora disponibile
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+La nuova postazione @SEAT_ID@ è stata configurata ed è ora disponibile.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: La postazione @SEAT_ID@ è stata rimossa
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+La postazione @SEAT_ID@ è stata rimossa e non è più disponibile.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Cambio d'orario
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'orologio di sistema è cambiato in @REALTIME@ microsecondi dal 1 gennaio, 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Il fuso orario è cambiato in @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il fuso orario di sistema è cambiato in @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Avvio del sistema completato.
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Tutti i servizi di sistema richiesti per la fase di avvio sono stati eseguiti
+con successo. Nota che la macchina potrebbe non essere ancora pronta in quanto
+i servizi attivati sono in fase di completamento.
+
+L'avvio del kernel ha richiesto @KERNEL_USEC@ microsecondi.
+
+L'avvio del disco RAM ha richiesto @INITRD_USEC@ microsecondi.
+
+L'avvio dello userspace ha richiesto @USERSPACE_USEC@ microsecondi.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Il sistema è entrato in fase di pausa @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il sistema è entrato nello stato di pausa @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Il sistema è uscito dalla fase di pausa @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il sistema è uscito dallo stato di pausa @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Il sistema è in fase di spegnimento
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemd è in fase di spegnimento. Tutti i servizi di sistema
+saranno terminati e tutti i file systems smontati.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: L'unità @UNIT@ inizia la fase di avvio
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ ha iniziato la fase di avvio.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: L'unità @UNIT@ termina la fase di avvio
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ ha terminato la fase di avvio.
+
+La fase di avvio è @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: L'unità @UNIT@ inizia la fase di spegnimento
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ ha iniziato la fase di spegnimento.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: L'unità @UNIT@ termina la fase di spegnimento
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ ha terminato la fase di spegnimento.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: L'unità @UNIT@ è fallita
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ è fallita.
+
+Il risultato è @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: L'unità @UNIT@ inizia a caricare la propria configurazione
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ è iniziata ricaricando la propria configurazione
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: L'unità @UNIT@ termina il caricamento della propria configurazione
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+L'unità @UNIT@ è terminata ricaricando la propria configurazione
+
+Il risultato è @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Il processo @EXECUTABLE@ non può essere eseguito
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Il processo @EXECUTABLE@ non può essere eseguito e termina.
+
+Il numero di errore restituito durante l'esecuzione del processo è @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Uno o più messaggi non possono essere inoltrati a syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Uno o più messaggi non possono essere inviati al servizio syslog
+eseguito in parallelo a journald. Questo di solito capita perché,
+l'implementazione di syslog non sta al passo con la
+velocità dei messaggi accodati.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Il punto di montaggio non è vuoto
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+La directory @WHERE@ è specificata come punto di montaggio (secondo campo
+in /etc/fstab o nel campo Where= del file unità di systemd) e non è vuoto.
+Questo non interferisce con il montaggio, ma i file pre-esistenti in questa
+directory diventano inaccessibili. Per visualizzare i file, si suggerisce
+di montare manualmente il file system indicato in una posizione secondaria.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Avviata macchina virtuale o container
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+La macchina virtuale @NAME@ con PID primario @LEADER@ è stata
+avviata ed è pronta all'uso.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Terminata macchina virtuale o container
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+La macchina virtuale @NAME@ con PID primario @LEADER@ è stata spenta.
diff --git a/src/journal/catalog/systemd.ko.catalog b/src/journal/catalog/systemd.ko.catalog
new file mode 100644
index 0000000000..3c3535a94c
--- /dev/null
+++ b/src/journal/catalog/systemd.ko.catalog
@@ -0,0 +1,264 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Korean translation
+
+# The catalog format is documented on
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+#
+# Translator :
+# Seong-ho Cho <darkcircle.0426@gmail.com>, 2015.
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: 저널 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+시스템 저널 프로세스를 시작했고 기록목적으로 저널 파일을 열었으며,
+프로세스 요청을 기다리고 있습니다.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: 저널 멈춤
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+시스템 저널 프로세스를 껐고 현재 활성화 중인 저널 파일을 모두
+닫았습니다.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: 서비스의 메시지를 거절함
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+일정 시간동안 서비스에서 너무 많은 메시지를 기록했습니다.
+서비스에서 오는 메시지를 거절했습니다.
+
+의문점이 있는 서비스로부터 오는 메시지만 거절했음을 참고하십시오
+다른 서비스의 메시지에는 영향을 주지 않습니다.
+
+메시지 거절 제어 제한 값은 /etc/systemd/journald.conf 의
+RateLimitInterval= 변수와 RateLimitBurst= 변수로 설정합니다.
+자세한 내용은 ournald.conf(5)를 살펴보십시오.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: 저널 메시지 놓침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+저널 시스템에서 커널 메시지를 충분히 빠르게 처리할 수 없어 커널
+ 메시지를 잃었습니다.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: 프로세스 @COREDUMP_PID@번 코어 덤프(@COREDUMP_COMM@) 생성함
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+프로세스 @COREDUMP_PID@번 (@COREDUMP_COMM@)이 비정상적으로 끝나
+코어 덤프를 생성했습니다.
+
+보통 비정상 종료 관리 프로그램에서 프로그래밍 오류를 나타내며,
+제작자에게 버그로 보고해야합니다.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: @USER_ID@ 사용자의 새 @SESSION_ID@ 세션 만듦
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+@USER_ID@ 사용자의 새 @SESSION_ID@ 세션을 만들었습니다.
+
+이 세션의 관리 프로세스는 @LEADER@ 입니다.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: @SESSION_ID@ 세션 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+@SESSION_ID@ 세션을 끝냈습니다.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: 새 @SEAT_ID@ 시트 사용할 수 있음
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+새 @SEAT_ID@ 시트를 설정했고 사용할 수 있습니다.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: @SEAT_ID@ 시트 제거함
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+@SEAT_ID@ 시트를 제거했으며 더이상 사용할 수 없습니다.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: 시간 바꿈
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+시스템 시계를 1970년 1월 1일 이후로 @REALTIME@ 마이크로초 지난 값으로
+설정했습니다.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: @TIMEZONE@ 시간대로 시간대 바꿈
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+시스템 시간대를 @TIMEZONE@ 시간대로 바꾸었습니다.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: 시스템 시동 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+부팅 과정에 시작하려고 준비한 모든 시스템 서비스를 성공적으로
+ 시작했습니다. 머신이 서비스처럼 대기중이라는 의미는 아니며
+지동을 완전히 마칠 때까지 사용중일 수도 있는 점 참고하십시오.
+
+커널 시동에 @KERNEL_USEC@ 마이크로초가 걸립니다.
+
+초기 램 디스크 시동에 @INITRD_USEC@ 마이크로초가 걸립니다.
+
+사용자 영역 시동에 @USERSPACE_USEC@ 마이크로초가 걸립니다.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: @SLEEP@ 대기 상태 진입
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@SLEEP@ 대기 상태로 진입했습니다.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: @SLEEP@ 대기 상태 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@SLEEP@ 대기 상태를 마쳤습니다.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: 컴퓨터 끄기 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+컴퓨터 끄기 동작을 시작했습니다. 모든 시스템 동작을 멈추고
+모든 파일 시스템의 마운트를 해제합니다.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: @UNIT@ 유닛 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛을 시작했습니다.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: @UNIT@ 유닛 시동 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛 시동을 마쳤습니다.
+
+시동 결과는 @RESULT@ 입니다.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: @UNIT@ 유닛 끝내기 동작 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛 끝내기 동작을 시작했습니다.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: @UNIT@ 유닛 끝내기 동작 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛 끝내기 동작을 마쳤습니다.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: @UNIT@ 유닛 동작 실패
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛 동작에 실패했습니다.
+
+결과는 @RESULT@ 입니다.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: @UNIT@ 유닛 설정 다시 읽기 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛의 설정 다시 읽기를 시작했습니다
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: @UNIT@ 유닛 설정 다시 읽기 완료
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 유닛의 설정 다시 읽기 동작을 끝냈습니다.
+
+결과는 @RESULT@ 입니다.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: @EXECUTABLE@ 프로세스 시작할 수 없음
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@EXECUTABLE@ 프로세스를 시작할 수 없어 실행에 실패했습니다.
+
+이 프로세스에서 반환한 오류 번호는 @ERRNO@번 입니다.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: 하나 이상의 메시지를 syslog에 전달할 수 없음
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+journald 서비스와 동시에 실행중인 syslog 서비스에 하나 이상의 메시지를
+전달할 수 없습니다. 보통 순차적으로 오는 메시지의 속도를 syslog 구현체가
+따라가지 못함을 의미합니다.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: 마운트 지점 비어있지 않음
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@WHERE@ 디렉터리를 마운트 지점으로 지정했으며 (/etc/fstab 파일의
+ 두번째 필드 또는 systemd 유닛 파일의 Where= 필드) 비어있지 않습니다.
+마운트 과정에 방해가 되진 않지만 이전에 이 디렉터리에 존재하는 파일에
+ 접근할 수 없게 됩니다. 중복으로 마운트한 파일을 보려면, 근본 파일
+시스템의 다음 위치에 직접 마운트하십시오.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: 가상 머신 또는 컨테이너 시작
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@LEADER@ 프로세스 ID로 동작하는 @NAME@ 가상 머신을 시작했으며,
+이제부터 사용할 수 있습니다.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: 가상 머신 또는 컨테이너 마침
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@LEADER@ 프로세스 ID로 동작하는 @NAME@ 가상 머신을 껐습니다.
diff --git a/src/journal/catalog/systemd.pl.catalog b/src/journal/catalog/systemd.pl.catalog
new file mode 100644
index 0000000000..6b8a31d8c4
--- /dev/null
+++ b/src/journal/catalog/systemd.pl.catalog
@@ -0,0 +1,261 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2014, 2015 Piotr Drąg
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Polish translation
+
+# The catalog format is documented on
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Uruchomiono dziennik
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemowy proces dziennika został uruchomiony, otworzył pliki dziennika do
+zapisu i jest gotowy do przetwarzania żądań.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Zatrzymano dziennik
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemowy proces dziennika został wyłączony i zamknął wszystkie obecnie
+aktywne pliki dziennika.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Ograniczono komunikaty z usługi
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Usługa zapisała za dużo komunikatów w określonym czasie. Komunikaty z usługi
+zostały pominięte.
+
+Proszę zauważyć, że tylko komunikaty z danej usługi zostały pominięte. Nie ma
+to wpływu na komunikaty innych usług.
+
+Ograniczenia kontrolujące pomijanie komunikatów mogą być konfigurowane
+za pomocą opcji RateLimitInterval= i RateLimitBurst= w pliku
+/etc/systemd/journald.conf. Strona journald.conf(5) zawiera więcej informacji.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Utracono komunikaty dziennika
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Komunikaty jądra zostały utracone, ponieważ system dziennika nie mógł
+przetworzyć ich odpowiednio szybko.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Proces @COREDUMP_PID@ (@COREDUMP_COMM@) zrzucił plik core
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Proces @COREDUMP_PID@ (@COREDUMP_COMM@) uległ awarii i zrzucił plik core.
+
+Zwykle wskazuje to na błąd programistyczny w danym programie i powinno zostać zgłoszone jego producentowi jako błąd.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Utworzono nową sesję @SESSION_ID@ dla użytkownika @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Nowa sesja o identyfikatorze @SESSION_ID@ została utworzona dla użytkownika
+@USER_ID@.
+
+Proces prowadzący sesji: @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Zakończono sesję @SESSION_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Sesja o identyfikatorze @SESSION_ID@ została zakończona.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Dostępne jest nowe stanowisko @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Nowe stanowisko @SEAT_ID@ zostało skonfigurowane i jest teraz dostępne.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Usunięto stanowisko @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Stanowisko @SEAT_ID@ zostało usunięte i nie jest już dostępne.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Zmiana czasu
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Zegar systemowy został zmieniony na @REALTIME@ μs po 1 stycznia 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Zmiana strefy czasowej na @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemowa strefa czasowa została zmieniona na @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Ukończono uruchamianie systemu
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Wszystkie usługi systemowe obowiązkowo zakolejkowane do włączenia podczas
+uruchamiania systemu zostały pomyślnie uruchomione. Proszę zauważyć, że nie
+oznacza to, że komputer jest bezczynny, jako że usługi mogą wciąż kończyć
+proces uruchamiania.
+
+Uruchamianie jądra zajęło @KERNEL_USEC@ μs.
+
+Uruchamianie początkowego dysku RAM zajęło @INITRD_USEC@ μs.
+
+Uruchamianie przestrzeni użytkownika zajęło @USERSPACE_USEC@ μs.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Przejście do stanu uśpienia @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+System przeszedł do stanu uśpienia @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Wyjście ze stanu uśpienia @SLEEP@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+System wyszedł ze stanu uśpienia @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Zainicjowano wyłączenie systemu
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Zainicjowano wyłączenie systemd. Wyłączenie zostało rozpoczęte i wszystkie
+usługi systemowe zostały zakończone, a wszystkie systemy plików odmontowane.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Rozpoczęto uruchamianie jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ rozpoczęła uruchamianie.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Ukończono uruchamianie jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ ukończyła uruchamianie.
+
+Wynik uruchamiania: @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Rozpoczęto wyłączanie jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ rozpoczęła wyłączanie.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Ukończono wyłączanie jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ ukończyła wyłączanie.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Jednostka @UNIT@ się nie powiodła
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ się nie powiodła.
+
+Wynik: @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Rozpoczęto ponowne wczytywanie konfiguracji jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ rozpoczęła ponowne wczytywanie swojej konfiguracji.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Ukończono ponowne wczytywanie konfiguracji jednostki @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jednostka @UNIT@ ukończyła ponowne wczytywanie swojej konfiguracji.
+
+Wynik: @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Nie można wykonać procesu @EXECUTABLE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Proces @EXECUTABLE@ nie mógł zostać wykonany i się nie powiódł.
+
+Numer błędu zwrócony przez ten proces: @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Nie można przekazać jednego lub więcej komunikatów do syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Jeden lub więcej komunikatów nie może zostać przekazanych do usługi syslog
+uruchomionej obok journald. Zwykle oznacza to, że implementacja syslog nie
+jest w stanie nadążyć za prędkością kolejki komunikatów.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Punkt montowania nie jest pusty
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Katalog @WHERE@ został podany jako punkt montowania (drugie pole w pliku
+/etc/fstab lub pole Where= w pliku jednostki systemd) i nie jest pusty. Nie
+wpływa to na montowanie, ale wcześniej istniejące pliki w tym katalogu stają
+się niedostępne. Aby zobaczyć te pliki, proszę ręcznie zamontować system
+plików w innym położeniu.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Uruchomiono maszynę wirtualną lub kontener
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Maszyna wirtualna @NAME@ (PID prowadzący @LEADER@) została uruchomiona i jest
+gotowa do użycia.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Zakończono maszynę wirtualną lub kontener
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Maszyna wirtualna @NAME@ (PID prowadzący @LEADER@) została wyłączona.
diff --git a/src/journal/catalog/systemd.pt_BR.catalog b/src/journal/catalog/systemd.pt_BR.catalog
new file mode 100644
index 0000000000..d9716e30f7
--- /dev/null
+++ b/src/journal/catalog/systemd.pt_BR.catalog
@@ -0,0 +1,264 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2015 Rafael Ferreira (translation)
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Catálogo de mensagens para as mensagens do próprio systemd
+
+# O formato do catálogo está documentado em
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# Para uma explicação do porquê de fazermos tudo isso, veja
+# https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: O jornal foi inciado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O processo jornal do sistema foi iniciado, arquivos foram abertos e está
+pronto para processar requisições.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: O jornal foi interrompido
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O processo do jornal do sistema foi desligado e todos os arquivos de jornal
+do sistema foram fechados.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Mensagens de um serviço foram suprimidas
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Um serviço registrou no log um número excessivo de mensagens dentro de um
+período de tempo. Mensagens do serviço foram descartadas.
+
+Note que apenas mensagens de um serviço em questão foram descartadas; outras
+mensagens dos serviços não foram afetadas.
+
+Os controles de limites de quando as mensagens são descartadas pode ser
+configurado com RateLimitInterval= e RateLimitBurst= no
+/etc/systemd/journald.conf. Veja journald.conf(5) para detalhes.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Mensagens do jornal foram perdidas
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Mensagens do kernel foram perdidas pois o sistema do jornal não pôde
+processá-las em velocidade suficiente para a demanda.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Processo @COREDUMP_PID@ (@COREDUMP_COMM@) despejou núcleo
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Processo @COREDUMP_PID@ (@COREDUMP_COMM@) travou e despejou o núcleo.
+
+Isso normalmente indica um erro de programação no programa que travou e
+deveria ser relatado para seu fabricante como um erro.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: A nova sessão @SESSION_ID@ foi criada para usuário o @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Uma nova sessão com o ID @SESSION_ID@ foi criada para o usuário @USER_ID@.
+
+O processo originador da sessão é @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Sessão @SESSION_ID@ foi terminada
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Um sessão com o ID @SESSION_ID@ foi terminada.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Um novo seat @SEAT_ID@ está disponível
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Um novo seat @SEAT_ID@ foi configurado e está disponível.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Seat @SEAT_ID@ foi removido agora
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Um seat @SEAT_ID@ foi removido e não está mais disponível.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Time change
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O relógio do sistema foi alterado para @REALTIME@ microssegundos após 1º de
+janeiro de 1970.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Fuso horário alterado para @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O fuso horário do sistema foi alterado para @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Inicialização do sistema foi concluída
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Todos os serviços do sistema necessários que estão enfileirados para
+executar na inicialização do sistema, foram iniciados com sucesso. Note
+que isso não significa que a máquina está ociosa, pois os serviços podem
+ainda estar ocupados com a inicialização completa.
+
+Inicialização do kernel precisou @KERNEL_USEC@ microssegundos.
+
+Disco de RAM inicial precisou de @INITRD_USEC@ microssegundos.
+
+Inicialização do espaço do usuário precisou de @USERSPACE_USEC@ microssegundos.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Estado de suspensão do sistema @SLEEP@ iniciado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O sistema entrou agora no estado de suspensão @SLEEP@.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Estado de suspensão do sistema @SLEEP@ finalizado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O sistema saiu agora do estado de suspensão @SLEEP@.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Desligamento do sistema iniciado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Desligamento do sistema foi inicializado. O desligamento se iniciou e todos
+os serviços do sistema foram terminados e todos os sistemas desmontados.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Unidade @UNIT@ sendo iniciado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ está sendo iniciada.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Unidade @UNIT@ concluiu a inicialização
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ concluiu a inicialização.
+
+The start-up result is @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Unidade @UNIT@ sendo desligado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ está sendo desligada.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: A unidade @UNIT@ concluiu o desligamento
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ concluiu o desligamento.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: A unidade @UNIT@ falhou
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ falhou.
+
+O resultado é @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Unidade @UNIT@ iniciou recarregamento de sua configuração
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ iniciou o recarregamento de sua configuração.
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Unidade @UNIT@ concluiu recarregamento de sua configuração
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A unidade @UNIT@ concluiu o recarregamento de sua configuração.
+
+O resultado é @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Processo @EXECUTABLE@ não pôde ser executado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O processo @EXECUTABLE@ não pôde ser executado e falhou.
+
+O número de erro retornado por este processo é @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Uma ou mais mensagens não puderam ser encaminhadas para o syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Uma ou mais mensagens não puderam ser encaminhadas para o serviço do syslog
+em execução paralela ao journald. Isso normalmente indica que a implementação
+do syslog não foi capaz de se manter com a velocidade das mensagens
+enfileiradas.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Ponto de montagem não está vazio
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+O diretório @WHERE@ está especificado como ponto de montagem (o segundo campo
+no /etc/fstab ou campo Where= no arquivo de unidade do systemd) e não está
+vazio. Isso não interfere com a montagem, mas os arquivos pré-existentes
+neste diretório se tornaram inacessívels. Para ver aqueles arquivos, sobre os
+quais foi realizada a montagem, por favor monte manualmente o sistema de
+arquivos subjacente para uma localização secundária.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Uma máquina virtual ou contêiner foi iniciado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A máquina virtual @NAME@ com seu PID @LEADER@ incial foi iniciada e está
+pronto para ser usad.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Uma máquina virtual ou contêiner foi terminado
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+A máquina virtual @NAME@ com seu PID @LEADER@ incial foi desligada.
diff --git a/src/journal/catalog/systemd.ru.catalog b/src/journal/catalog/systemd.ru.catalog
new file mode 100644
index 0000000000..eedbb8aa9c
--- /dev/null
+++ b/src/journal/catalog/systemd.ru.catalog
@@ -0,0 +1,354 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2013-2016 Sergey Ptashnick
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Russian translation
+
+# Формат каталога сообщений описан по ссылке
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# Перед каждым элементом в комментарии указан Subject исходного
+# сообщения (на английском).
+
+# Subject: The Journal has been started
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Запущена служба журналирования
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Процесс, отвечающий за журналирование системных событий, успешно запустился,
+открыл для записи файлы журнала, и готов обрабатывать запросы.
+
+# Subject: The Journal has been stopped
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Служба журналирования остановлена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Процесс, отвечающий за журналирование системных событий, завершил работу и
+закрыл все свои файлы.
+
+# Subject: Disk space used by the journal
+-- ec387f577b844b8fa948f33cad9a75e6
+Subject: Место на диске, занятое журналом
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@JOURNAL_NAME@ (@JOURNAL_PATH@) сейчас занимает @CURRENT_USE_PRETTY@.
+Максимальный разрешенный размер составляет @MAX_USE_PRETTY@.
+Оставляем свободными как минимум @DISK_KEEP_FREE_PRETTY@ (сейчас на диске
+свободно @DISK_AVAILABLE_PRETTY@).
+Таким образом, предел использования составляет @LIMIT_PRETTY@, из которых
+@AVAILABLE_PRETTY@ пока свободно.
+
+Ограничения на размер журнала настраиваются при помощи параметров
+SystemMaxUse=, SystemKeepFree=, SystemMaxFileSize=, RuntimeMaxUse=,
+RuntimeKeepFree=, RuntimeMaxFileSize= в файле /etc/systemd/journald.conf.
+Более подробные сведения вы можете получить на справочной странице
+journald.conf(5).
+
+# Subject: Messages from a service have been suppressed
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Часть сообщений от службы пропущена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Служба отправила слишком много сообщений за короткий промежуток времени.
+Часть сообщений была пропущена.
+
+Обратите внимание, что были пропущены сообщения только от этой службы,
+сообщения других служб не затронуты.
+
+Предел, после которого служба журнала начинает игнорировать сообщения,
+настраивается параметрами RateLimitInterval= и RateLimitBurst= в файле
+/etc/systemd/journald.conf. Подробности смотрите на странице руководства
+journald.conf(5).
+
+# Subject: Journal messages have been missed
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Часть сообщений ядра пропущена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Часть сообщений, поступивших от ядра, была потеряна, так как служба
+журналирования не успела их обработать.
+
+# Subject: Process @COREDUMP_PID@ (@COREDUMP_COMM@) dumped core
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Процесс @COREDUMP_PID@ (@COREDUMP_COMM@) сбросил дамп памяти
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Процесс @COREDUMP_PID@ (@COREDUMP_COMM@) завершился из-за критической ошибки.
+Записан дамп памяти.
+
+Вероятно, это произошло из-за ошибки, допущенной в коде программы.
+Рекомендуется сообщить её разработчикам о возникшей проблеме.
+
+# Subject: A new session @SESSION_ID@ has been created for user @USER_ID@
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Для пользователя @USER_ID@ создан новый сеанс @SESSION_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Для пользователя @USER_ID@ создан новый сеанс с идентификатором @SESSION_ID@.
+
+Главный процесс нового сеанса имеет индентификатор @LEADER@.
+
+# Subject: A session @SESSION_ID@ has been terminated
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Сеанс @SESSION_ID@ завершен
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Сеанс с идентификатором @SESSION_ID@ завершился.
+
+# Subject: A new seat @SEAT_ID@ is now available
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Добавлено новое рабочее место @SEAT_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Новое рабочее место (seat) @SEAT_ID@ полностью настроено и готово к
+использованию.
+
+# Subject: A seat @SEAT_ID@ has now been removed
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Рабочее место @SEAT_ID@ отключено
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Рабочее место (seat) @SEAT_ID@ было отключено.
+
+# Subject: Time change
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Переведены системные часы
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Системные часы были переведены. Сейчас они показывают @REALTIME@ микросекунд
+с момента 00:00:00 1 января 1970 года.
+
+# Subject: Time zone change to @TIMEZONE@
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Часовой пояс изменен на @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Системный часовой пояс был изменен. Новое значение: @TIMEZONE@.
+
+# Subject: System start-up is now complete
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Запуск системы завершен
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Все системные службы, запуск которых предписан настройками, были запущены.
+Впрочем, это ещё не означает, что система в данный момент ничем не занята,
+так как некоторые службы могут продолжать инициализацию даже после того, как
+отчитались о своем запуске.
+
+Запуск ядра занял @KERNEL_USEC@ микросекунд.
+
+Процессы начального RAM-диска (initrd) отработали за @INITRD_USEC@ микросекунд.
+
+Запуск системных служб занял @USERSPACE_USEC@ микросекунд.
+
+# Subject: System sleep state @SLEEP@ entered
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Система перешла в состояние сна (@SLEEP@)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Система была переведена в состояние сна (@SLEEP@).
+
+# Subject: System sleep state @SLEEP@ left
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Система вышла из состояния сна (@SLEEP@)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Система была выведена из состояния сна (@SLEEP@).
+
+# Subject: System shutdown initiated
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Подготовка системы к выключению
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Начат процесс подготовки к выключению компьютера. Останавливаются все системные
+службы, отмонтируются все файловые системы.
+
+# Subject: Unit @UNIT@ has begun with start-up
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Начинается запуск юнита @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Начат процесс запуска юнита @UNIT@.
+
+# Subject: Unit @UNIT@ has finished start-up
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Запуск юнита @UNIT@ завершен
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Процесс запуска юнита @UNIT@ был завершен.
+
+Результат: @RESULT@.
+
+# Subject: Unit @UNIT@ has begun shutting down
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Начинается остановка юнита @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Начат процесс остановки юнита @UNIT@.
+
+# Subject: Unit @UNIT@ has finished shutting down
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Завершена остановка юнита @UNIT@.
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Процесс остановки юнита @UNIT@ был завершен.
+
+# Subject: Unit @UNIT@ has failed
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Ошибка юнита @UNIT@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Произошел сбой юнита @UNIT@.
+
+Результат: @RESULT@.
+
+# Subject: Unit @UNIT@ has begun with reloading its configuration
+-- d34d037fff1847e6ae669a370e694725
+Subject: Юнит @UNIT@ начал перечитывать свои настройки
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Юнит @UNIT@ начал процесс перечитывания своей конфигурации.
+
+# Subject: Unit @UNIT@ has finished reloading its configuration
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Юнит @UNIT@ завершил перечитывание своих настроек
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Юнит @UNIT@ завершил процесс перечитывания своей конфигурации.
+
+Результат: @RESULT@.
+
+# Subject: Process @EXECUTABLE@ could not be executed
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Не удалось запустить процесс @EXECUTABLE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Сбой: не удалось запустить процесс @EXECUTABLE@.
+
+Код ошибки: @ERRNO@.
+
+# Subject: One or more messages could not be forwarded to syslog
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Часть сообщений не удалось передать процессу syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Не удалось передать некоторые сообщения демону системного лога (syslog),
+дублирующему работу службы системного журнала. Скорее всего, причина в том, что
+используемая реализация syslog не успевает обрабатывать сообщения с достаточной
+скоростью.
+
+# Subject: Mount point is not empty
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Каталог, являющийся точкой монтирования, не пуст
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Каталог @WHERE@, который был указан в качестве точки монтирования (во втором
+столбце файла /etc/fstab, либо в параметре Where= файла конфигурации юнита),
+не является пустым. Это никак не мешает монтированию, однако ранее находившиеся
+в нем файлы будут недоступны. Чтобы получить к ним доступ, вы можете вручную
+перемонтировать эту файловую систему в другую точку.
+
+# Subject: A virtual machine or container has been started
+-- 24d8d4452573402496068381a6312df2
+Subject: Запущена виртуальная машина/контейнер
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Виртуальная машина @NAME@ (идентификатор главного процесса: @LEADER@) запущена и
+готова к работе.
+
+# Subject: A virtual machine or container has been terminated
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Остановлена виртуальная машина/контейнер
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Виртуальная машина @NAME@ (идентификатор главного процесса: @LEADER@) выключена.
+
+# Subject: DNSSEC mode has been turned off, as server doesn't support it
+-- 36db2dfa5a9045e1bd4af5f93e1cf057
+Subject: Механизм DNSSEC был отключен, так как DNS-сервер его не поддерживает
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8) resolved.conf(5)
+
+Служба разрешения имен хостов (systemd-resolved.service) определила, что
+указанный в настойках DNS-сервер не поддерживает технологию DNSSEC, и
+автоматически отключила DNSSEC-проверки.
+
+Данное событие возникает, если в файле resolved.conf указан параметр
+DNSSEC=allow-downgrade, и вышестоящий DNS-сервер не поддерживает DNSSEC.
+Обратите внимание, что режим allow-downgrade допускает возможность атаки
+"DNSSEC downgrade", в ходе которой атакующий хакер блокирует проверки DNSSEC
+путем отправки ложных сообщений от имени DNS-сервера.
+
+Возникновение данного события может свидетельствовать как о том, что ваш
+DNS-сервер не поддерживает DNSSEC, так и о том, что некий хакер успешно провел
+против вас атаку, направленную на блокировку DNSSEC-проверок.
+
+# Subject: DNSSEC validation failed
+-- 1675d7f172174098b1108bf8c7dc8f5d
+Subject: Проверка DNSSEC провалена
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8)
+
+DNS-запрос или отдельная ресурсная запись не прошла проверку DNSSEC.
+Как правило, это свидетельствует о постороннем вмешательстве в канал связи.
+
+# Subject: A DNSSEC trust anchor has been revoked
+-- 4d4408cfd0d144859184d1e65d7c8a65
+Subject: Открытый ключ DNSSEC был отозван
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:systemd-resolved.service(8)
+
+Открытый ключ (trust ahcnor) DNSSEC был отозван. Необходимо настроить новый
+открытый ключ, либо обновить систему, чтобы получить обновленный открытый ключ.
diff --git a/src/journal/catalog/systemd.sr.catalog b/src/journal/catalog/systemd.sr.catalog
new file mode 100644
index 0000000000..cf700c477b
--- /dev/null
+++ b/src/journal/catalog/systemd.sr.catalog
@@ -0,0 +1,262 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Serbian translation
+
+# Формат каталога је документован на
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# Да бисте видели зашто ово радимо, погледајте https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: Журнал је покренут
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Системски журналски процес се покренуо, отворио журналске
+датотеке за упис и спреман је за обраду захтева.
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: Журнал је заустављен
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Системски журналски процес се зауставио и затворио све тренутно
+отворене журналске датотеке.
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: Поруке од услуге су утишане
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+Услуга је уписала сувише порука за једно време. Поруке
+од услуге су одбачене.
+
+Знајте да су само поруке од ове услуге одбачене, друге
+услуге нису захваћене овим.
+
+Ограничења која подешавају начин на који се поруке одбацују се могу подесити
+помоћу „RateLimitInterval=“ и „RateLimitBurst=“ параметара унутар датотеке
+/etc/systemd/journald.conf. Погледајте journald.conf(5) за појединости.
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: Журналске поруке су изгубљене
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Поруке кернела су изгубљене јер журналски систем није могао да их
+обради довољно брзо.
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: Процес @COREDUMP_PID@ (@COREDUMP_COMM@) је избацио своје језгро
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+Процес @COREDUMP_PID@ (@COREDUMP_COMM@) је пао и избацио своје језгро.
+
+Ово обично значи да постоји грешка у програму који је пао и ова
+грешка треба да се пријави продавцу.
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: Нова сесија @SESSION_ID@ је направљена за корисника @USER_ID@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Нова сесија са ИБ-ом @SESSION_ID@ је направљена за корисника @USER_ID@.
+
+Водећи процес сесије је @LEADER@.
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: Сесија @SESSION_ID@ је окончана
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Сесија са ИБ-ом @SESSION_ID@ је окончана.
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: Ново седиште @SEAT_ID@ је сада доступно
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Ново седиште @SEAT_ID@ је исподешавано и сада је доступно.
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: Седиште @SEAT_ID@ је сада уклоњено
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+Седиште @SEAT_ID@ је сада уклоњено и више није доступно.
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: Време је промењено
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Системски сат је сада подешен на @REALTIME@ микросекунде након 1. јануара 1970. године.
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: Временска зона је промењена на @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Временска зона је промењена на @TIMEZONE@.
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: Подизање система је сада готово
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Све системске услуге које су заказане за подизање су успешно покренуте.
+Знајте да ово не значи да је машина сада беспослена јер услуге могу
+и даље бити заузете завршавањем покретања система.
+
+Подизање кернела је трајало @KERNEL_USEC@ микросекунде.
+
+Подизање почетног РАМ диска је трајало @INITRD_USEC@ микросекунде.
+
+Подизање корисничких програма је трајало @USERSPACE_USEC@ микросекунде.
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: Системско стање спавања @SLEEP@ започето
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Систем је сада ушао у @SLEEP@ стање спавања.
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: Системско стање спавања @SLEEP@ напуштено
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Систем је изашао из @SLEEP@ стања спавања.
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: Гашење система започето
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Систем-де гашење је започето. Гашење је сада почело и све
+системске услуге су окончане и сви системи датотека откачени.
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: Јединица @UNIT@ је почела са покретањем
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је почела са покретањем.
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: Јединица @UNIT@ је завршила са покретањем
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је завршила са покретањем.
+
+Исход покретања је @RESULT@.
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: Јединица @UNIT@ је почела са гашењем
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је почела са гашењем.
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: Јединица @UNIT@ је завршила са гашењем
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је завршила са гашењем.
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: Јединица @UNIT@ је пукла
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је пукла.
+
+Исход је @RESULT@.
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: Јединица @UNIT@ је почела са поновним учитавањем свог подешавања
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је почела са поновним учитавањем свог подешавања
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: Јединица @UNIT@ је завршила са поновним учитавањем свог подешавања
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Јединица @UNIT@ је завршила са поновним учитавањем свог подешавања
+
+Исход је @RESULT@.
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: Процес @EXECUTABLE@ није могао бити извршен
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Процес @EXECUTABLE@ није могао бити извршен и пукао је.
+
+Овај процес је вратио број грешке @ERRNO@.
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: Једна или више порука није могло бити прослеђено системском записнику
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Једна или више порука није могло бити прослеђено „syslog“ услузи
+која ради упоредно са журнал-деом. Ово обично значи да спроведена
+„syslog“ услуга није могла да издржи брзину свих надолазећих
+порука у реду.
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: Тачка качења није празна
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Директоријум @WHERE@ је наведен као тачка качења (друго поље у
+/etc/fstab датотеци или у „Where=“ пољу систем-де јединичне датотеке)
+и он није празан. Ово не утиче на качење али ће већ постојеће датотеке у
+овом директоријуму постати недоступне. Да бисте видели ове недоступне
+датотеке, ручно прикачите основни систем датотека у другу
+путању.
+
+-- 24d8d4452573402496068381a6312df2
+Subject: Виртуелна машина или контејнер је покренут(а)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Виртуелна машина @NAME@ са водећим ПИБ-ом @LEADER@ је
+покренута и сада је спремна за коришћење.
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: Виртуелна машина или контејнер је окончан(а)
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Виртуелна машина @NAME@ са водећим ПИБ-ом @LEADER@ је
+угашена.
diff --git a/src/journal/catalog/systemd.zh_CN.catalog b/src/journal/catalog/systemd.zh_CN.catalog
new file mode 100644
index 0000000000..38639109e4
--- /dev/null
+++ b/src/journal/catalog/systemd.zh_CN.catalog
@@ -0,0 +1,253 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2015 Boyuan Yang
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Simplified Chinese translation
+
+# 本 catalog 文档格式被记载在
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# 如需了解我们为什么做这些工作,请见 https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: 日志已开始
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统日志进程已启动,已打开供写入的日志文件并准备好处理请求。
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: 日志已停止
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统日志进程已终止,并已关闭所有当前活动的日志文件。
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: 由某个服务而来的消息已被抑制
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+某个服务在一个时间周期内记录了太多消息。
+从该服务而来的消息已被丢弃。
+
+请注意只有由有问题的服务传来的消息被丢弃,
+其它服务的消息不受影响。
+
+可以在 /etc/systemd/journald.conf 中设定 RateLimitInterval=
+以及 RateLimitBurst = 的值以控制丢弃信息的限制。
+请参见 journald.conf(5) 以了解详情。
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: 日志消息已遗失
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+因日志系统对内核消息的处理速度不够快,
+部分信息已经遗失。
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: 进程 @COREDUMP_PID@ (@COREDUMP_COMM@) 核心已转储
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+进程 @COREDUMP_PID@ (@COREDUMP_COMM@) 已崩溃并进行核心转储。
+
+这通常意味着崩溃程序中存在编程错误,并应当将此错误向其开发者报告。
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: 一个新会话 @SESSION_ID@ 已为用户 @USER_ID@ 建立
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一个 ID 为 @SESSION_ID@ 的新会话已为用户 @USER_ID@ 建立。
+
+该会话的首进程为 @LEADER@。
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: 会话 @SESSION_ID@ 已终止
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一个 ID 为 @SESSION_ID@ 的会话已终止。
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: 一个新的座位 @SEAT_ID@ 可用
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一个新的座位 @SEAT_ID@ 已被配置并已可用。
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: 座位 @SEAT_ID@ 已被移除
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+座位 @SEAT_ID@ 已被移除并不再可用。
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: 时间已变更
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统时钟已变更为1970年1月1日后 @REALTIME@ 微秒。
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: 时区变更为 @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统时区已变更为 @TIMEZONE@。
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: 系统启动已完成
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+所有系统启动时需要的系统服务均已成功启动。
+请注意这并不代表现在机器已经空闲,因为某些服务可能仍处于完成启动的过程中。
+
+内核启动使用了 @KERNEL_USEC@ 毫秒。
+
+初始内存盘启动使用了 @INITRD_USEC@ 毫秒。
+
+用户空间启动使用了 @USERSPACE_USEC@ 毫秒。
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: 系统已进入 @SLEEP@ 睡眠状态
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-deve
+
+系统现已进入 @SLEEP@ 睡眠状态。
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: 系统已离开 @SLEEP@ 睡眠状态
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统现已离开 @SLEEP@ 睡眠状态。
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: 系统关机已开始
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系统关机操作已初始化。
+关机已开始,所有系统服务均已结束,所有文件系统已卸载。
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: @UNIT@ 单元已开始启动
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已开始启动。
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: @UNIT@ 单元已结束启动
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已结束启动。
+
+启动结果为“@RESULT@”。
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: @UNIT@ 单元已开始停止操作
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已开始停止操作。
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: @UNIT@ 单元已结束停止操作
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已结束停止操作。
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: @UNIT@ 单元已失败
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已失败。
+
+结果为“@RESULT@”。
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: @UNIT@ 单元已开始重新载入其配置
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已开始重新载入其配置。
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: @UNIT@ 单元已结束配置重载入
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+@UNIT@ 单元已结束配置重载入操作。
+
+结果为“@RESULT@”。
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: 进程 @EXECUTABLE@ 无法执行
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+进程 @EXECUTABLE@ 无法被执行并已失败。
+
+该进程返回的错误代码为 @ERRNO@。
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: 一个或更多消息无法被转发至 syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+有一条或更多的消息无法被转发至与 journald 同时运行的 syslog 服务。
+这通常意味着 syslog 实现无法跟上队列中消息进入的速度。
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: 挂载点不为空
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+目录 @WHERE@ 被指定为挂载点(即 /etc/fstab 文件的第二栏,或 systemd 单元
+文件的 Where= 字段),且该目录非空。
+这并不会影响挂载行为,但该目录中先前已存在的文件将无法被访问。
+如需查看这些文件,请手动将其下的文件系统挂载到另一个位置。
+
+-- 24d8d4452573402496068381a6312df2
+Subject: 一个虚拟机或容器已启动
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+虚拟机 @NAME@,以及其首进程 PID @LEADER@,已被启动并可被使用。
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: 一个虚拟机或容器已被终止
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+虚拟机 @NAME@,以及其首进程 PID @LEADER@,已被关闭并停止。
diff --git a/src/journal/catalog/systemd.zh_TW.catalog b/src/journal/catalog/systemd.zh_TW.catalog
new file mode 100644
index 0000000000..027ffe44e5
--- /dev/null
+++ b/src/journal/catalog/systemd.zh_TW.catalog
@@ -0,0 +1,263 @@
+# This file is part of systemd.
+#
+# Copyright 2012 Lennart Poettering
+# Copyright 2015 Jeff Huang
+#
+# systemd is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation; either version 2.1 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with systemd; If not, see <http://www.gnu.org/licenses/>.
+
+# Message catalog for systemd's own messages
+# Traditional Chinese translation
+
+# Catalog 的格式記錄於
+# http://www.freedesktop.org/wiki/Software/systemd/catalog
+
+# For an explanation why we do all this, see https://xkcd.com/1024/
+
+-- f77379a8490b408bbe5f6940505a777b
+Subject: 日誌已開始
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統日誌行程已啟動,已開啟日誌
+檔案供寫入並準備好對行程的要求做出回應。
+
+-- d93fb3c9c24d451a97cea615ce59c00b
+Subject: 日誌已停止
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統日誌行程已關閉,且關閉所有目前
+活躍的日誌檔案。
+
+-- a596d6fe7bfa4994828e72309e95d61e
+Subject: 從服務而來的訊息已被抑制
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:journald.conf(5)
+
+有一個服務在一個時間週期內記錄了太多訊息。
+從該服務而來的訊息已被丟棄。
+
+注意,只有有問題的服務之訊息被丟棄,
+其他服務的訊息則不受影響。
+
+可以在 /etc/systemd/journald.conf 中設定
+RateLimitInterval= 以及 RateLimitBurst=
+來控制當訊息要開始被丟棄時的限制。參見 journald.conf(5) 以獲得更多資訊。
+
+-- e9bf28e6e834481bb6f48f548ad13606
+Subject: 日誌訊息已遺失
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+因日誌系統對核心訊息的處理不夠快速,
+部份訊息已遺失。
+
+-- fc2e22bc6ee647b6b90729ab34a250b1
+Subject: 行程 @COREDUMP_PID@ (@COREDUMP_COMM@) 核心傾印
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: man:core(5)
+
+行程 @COREDUMP_PID@ (@COREDUMP_COMM@) 當掉並核心傾印。
+
+這通常代表了在當掉的程式中的一個程式錯誤
+並需要回報錯誤給其開發者。
+
+-- 8d45620c1a4348dbb17410da57c60c66
+Subject: 新的工作階段 @SESSION_ID@ 已為使用者 @USER_ID@ 建立
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一個新的工作階段,ID @SESSION_ID@ 已為使用者 @USER_ID@ 建立。
+
+這個工作階段的領導行程為 @LEADER@。
+
+-- 3354939424b4456d9802ca8333ed424a
+Subject: 工作階段 @SESSION_ID@ 已結束
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一個工作階段,ID @SESSION_ID@ 已結束。
+
+-- fcbefc5da23d428093f97c82a9290f7b
+Subject: 新的座位 @SEAT_ID@ 可用
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+一個新的座位 @SEAT_ID@ 已被設定且現在可用。
+
+-- e7852bfe46784ed0accde04bc864c2d5
+Subject: 座位 @SEAT_ID@ 已被移除
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+Documentation: http://www.freedesktop.org/wiki/Software/systemd/multiseat
+
+座位 @SEAT_ID@ 已被移除且不再可用。
+
+-- c7a787079b354eaaa9e77b371893cd27
+Subject: 時間變更
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統時間已變更為1970年1月1日後 @REALTIME@ 微秒。
+
+-- 45f82f4aef7a4bbf942ce861d1f20990
+Subject: 時區變更為 @TIMEZONE@
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統時區已變更為 @TIMEZONE@。
+
+-- b07a249cd024414a82dd00cd181378ff
+Subject: 系統啟動已完成
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+所有開機所必要的系統服務都已成功啟動。
+注意這並不代表這臺機器有空閒的時間
+可以服務,可能仍忙於完成啟動。
+
+核心啟動需要 @KERNEL_USEC@ 微秒。
+
+初始 RAM 磁碟啟動需要 @INITRD_USEC@ 微秒。
+
+使用者空間啟動需要 @USERSPACE_USEC@ 微秒。
+
+-- 6bbd95ee977941e497c48be27c254128
+Subject: 系統進入 @SLEEP@ 睡眠狀態
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統現在已進入 @SLEEP@ 睡眠狀態。
+
+-- 8811e6df2a8e40f58a94cea26f8ebf14
+Subject: 系統離開 @SLEEP@ 睡眠狀態
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+系統現在已離開 @SLEEP@ 睡眠狀態。
+
+-- 98268866d1d54a499c4e98921d93bc40
+Subject: 系統關機開始
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+Systemd 關閉已經開始。關閉已開始且所有系統服務
+都已結束,所有的檔案系統也都已被卸載。
+
+-- 7d4958e842da4a758f6c1cdc7b36dcc5
+Subject: 單位 @UNIT@ 已開始啟動
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已開始啟動。
+
+-- 39f53479d3a045ac8e11786248231fbf
+Subject: 單位 @UNIT@ 啟動已結束
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 啟動已結束。
+
+啟動結果為 @RESULT@。
+
+-- de5b426a63be47a7b6ac3eaac82e2f6f
+Subject: 單位 @UNIT@ 已開始關閉
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已開始關閉。
+
+-- 9d1aaa27d60140bd96365438aad20286
+Subject: 單位 @UNIT@ 已關閉結束
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已關閉結束。
+
+-- be02cf6855d2428ba40df7e9d022f03d
+Subject: 單位 @UNIT@ 已失敗
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已失敗。
+
+結果為 @RESULT@。
+
+-- d34d037fff1847e6ae669a370e694725
+Subject: 單位 @UNIT@ 已開始重新載入其設定
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已開始重新載入其設定
+
+-- 7b05ebc668384222baa8881179cfda54
+Subject: 單位 @UNIT@ 已結束重新載入其設定
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+單位 @UNIT@ 已結束重新載入其設定
+
+結果為 @RESULT@。
+
+-- 641257651c1b4ec9a8624d7a40a9e1e7
+Subject: 行程 @EXECUTABLE@ 無法執行
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+行程 @EXECUTABLE@ 無法執行且失敗。
+
+由該行程所回傳的錯誤碼為 @ERRNO@。
+
+-- 0027229ca0644181a76c4e92458afa2e
+Subject: 一個或更多訊息無法被轉發到 syslog
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+一個或更多訊息無法被轉發到 syslog 服務
+以及並行執行的 journald。這通常代表著
+syslog 實作並無未跟上佇列中訊息
+的速度。
+
+-- 1dee0369c7fc4736b7099b38ecb46ee7
+Subject: 掛載點不為空
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+目錄 @WHERE@ 被指定為掛載點(在 /etc/fstab 中的
+第二欄或是在 systemd 單位檔案中的 Where= 欄位)且其不為空。
+這並不會干擾掛載,但在此目錄中已存在的檔案
+會變成無法存取的狀態。要檢視這些 over-mounted 的檔案,
+請手動掛載下面的檔案系統到次要
+位置。
+
+-- 24d8d4452573402496068381a6312df2
+Subject: 虛擬機器或容器已啟動
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+虛擬機器 @NAME@ 包含它的領導 PID @LEADER@ 現在
+已經開始並已經可以使用。
+
+-- 58432bd3bace477cb514b56381b8a758
+Subject: 虛擬機器或容器已結束
+Defined-By: systemd
+Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
+
+虛擬機器 @NAME@ 包含它的領導 PID @LEADER@ 已經
+關閉。
diff --git a/src/journal/compress.c b/src/journal/compress.c
deleted file mode 100644
index 1933b87b00..0000000000
--- a/src/journal/compress.c
+++ /dev/null
@@ -1,682 +0,0 @@
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#ifdef HAVE_XZ
-#include <lzma.h>
-#endif
-
-#ifdef HAVE_LZ4
-#include <lz4.h>
-#include <lz4frame.h>
-#endif
-
-#include "alloc-util.h"
-#include "compress.h"
-#include "fd-util.h"
-#include "io-util.h"
-#include "journal-def.h"
-#include "macro.h"
-#include "sparse-endian.h"
-#include "string-table.h"
-#include "string-util.h"
-#include "util.h"
-
-#ifdef HAVE_LZ4
-DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_compressionContext_t, LZ4F_freeCompressionContext);
-DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_decompressionContext_t, LZ4F_freeDecompressionContext);
-#endif
-
-#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t))
-
-static const char* const object_compressed_table[_OBJECT_COMPRESSED_MAX] = {
- [OBJECT_COMPRESSED_XZ] = "XZ",
- [OBJECT_COMPRESSED_LZ4] = "LZ4",
-};
-
-DEFINE_STRING_TABLE_LOOKUP(object_compressed, int);
-
-int compress_blob_xz(const void *src, uint64_t src_size,
- void *dst, size_t dst_alloc_size, size_t *dst_size) {
-#ifdef HAVE_XZ
- static const lzma_options_lzma opt = {
- 1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT,
- LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4
- };
- static const lzma_filter filters[] = {
- { LZMA_FILTER_LZMA2, (lzma_options_lzma*) &opt },
- { LZMA_VLI_UNKNOWN, NULL }
- };
- lzma_ret ret;
- size_t out_pos = 0;
-
- assert(src);
- assert(src_size > 0);
- assert(dst);
- assert(dst_alloc_size > 0);
- assert(dst_size);
-
- /* Returns < 0 if we couldn't compress the data or the
- * compressed result is longer than the original */
-
- if (src_size < 80)
- return -ENOBUFS;
-
- ret = lzma_stream_buffer_encode((lzma_filter*) filters, LZMA_CHECK_NONE, NULL,
- src, src_size, dst, &out_pos, dst_alloc_size);
- if (ret != LZMA_OK)
- return -ENOBUFS;
-
- *dst_size = out_pos;
- return 0;
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int compress_blob_lz4(const void *src, uint64_t src_size,
- void *dst, size_t dst_alloc_size, size_t *dst_size) {
-#ifdef HAVE_LZ4
- int r;
-
- assert(src);
- assert(src_size > 0);
- assert(dst);
- assert(dst_alloc_size > 0);
- assert(dst_size);
-
- /* Returns < 0 if we couldn't compress the data or the
- * compressed result is longer than the original */
-
- if (src_size < 9)
- return -ENOBUFS;
-
- r = LZ4_compress_limitedOutput(src, dst + 8, src_size, (int) dst_alloc_size - 8);
- if (r <= 0)
- return -ENOBUFS;
-
- *(le64_t*) dst = htole64(src_size);
- *dst_size = r + 8;
-
- return 0;
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-
-int decompress_blob_xz(const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
-
-#ifdef HAVE_XZ
- _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
- lzma_ret ret;
- size_t space;
-
- assert(src);
- assert(src_size > 0);
- assert(dst);
- assert(dst_alloc_size);
- assert(dst_size);
- assert(*dst_alloc_size == 0 || *dst);
-
- ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
- if (ret != LZMA_OK)
- return -ENOMEM;
-
- space = MIN(src_size * 2, dst_max ?: (size_t) -1);
- if (!greedy_realloc(dst, dst_alloc_size, space, 1))
- return -ENOMEM;
-
- s.next_in = src;
- s.avail_in = src_size;
-
- s.next_out = *dst;
- s.avail_out = space;
-
- for (;;) {
- size_t used;
-
- ret = lzma_code(&s, LZMA_FINISH);
-
- if (ret == LZMA_STREAM_END)
- break;
- else if (ret != LZMA_OK)
- return -ENOMEM;
-
- if (dst_max > 0 && (space - s.avail_out) >= dst_max)
- break;
- else if (dst_max > 0 && space == dst_max)
- return -ENOBUFS;
-
- used = space - s.avail_out;
- space = MIN(2 * space, dst_max ?: (size_t) -1);
- if (!greedy_realloc(dst, dst_alloc_size, space, 1))
- return -ENOMEM;
-
- s.avail_out = space - used;
- s.next_out = *dst + used;
- }
-
- *dst_size = space - s.avail_out;
- return 0;
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_blob_lz4(const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
-
-#ifdef HAVE_LZ4
- char* out;
- int r, size; /* LZ4 uses int for size */
-
- assert(src);
- assert(src_size > 0);
- assert(dst);
- assert(dst_alloc_size);
- assert(dst_size);
- assert(*dst_alloc_size == 0 || *dst);
-
- if (src_size <= 8)
- return -EBADMSG;
-
- size = le64toh( *(le64_t*)src );
- if (size < 0 || (unsigned) size != le64toh(*(le64_t*)src))
- return -EFBIG;
- if ((size_t) size > *dst_alloc_size) {
- out = realloc(*dst, size);
- if (!out)
- return -ENOMEM;
- *dst = out;
- *dst_alloc_size = size;
- } else
- out = *dst;
-
- r = LZ4_decompress_safe(src + 8, out, src_size - 8, size);
- if (r < 0 || r != size)
- return -EBADMSG;
-
- *dst_size = size;
- return 0;
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_blob(int compression,
- const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
- if (compression == OBJECT_COMPRESSED_XZ)
- return decompress_blob_xz(src, src_size,
- dst, dst_alloc_size, dst_size, dst_max);
- else if (compression == OBJECT_COMPRESSED_LZ4)
- return decompress_blob_lz4(src, src_size,
- dst, dst_alloc_size, dst_size, dst_max);
- else
- return -EBADMSG;
-}
-
-
-int decompress_startswith_xz(const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra) {
-
-#ifdef HAVE_XZ
- _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
- lzma_ret ret;
-
- /* Checks whether the decompressed blob starts with the
- * mentioned prefix. The byte extra needs to follow the
- * prefix */
-
- assert(src);
- assert(src_size > 0);
- assert(buffer);
- assert(buffer_size);
- assert(prefix);
- assert(*buffer_size == 0 || *buffer);
-
- ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
- if (ret != LZMA_OK)
- return -EBADMSG;
-
- if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1)))
- return -ENOMEM;
-
- s.next_in = src;
- s.avail_in = src_size;
-
- s.next_out = *buffer;
- s.avail_out = *buffer_size;
-
- for (;;) {
- ret = lzma_code(&s, LZMA_FINISH);
-
- if (ret != LZMA_STREAM_END && ret != LZMA_OK)
- return -EBADMSG;
-
- if (*buffer_size - s.avail_out >= prefix_len + 1)
- return memcmp(*buffer, prefix, prefix_len) == 0 &&
- ((const uint8_t*) *buffer)[prefix_len] == extra;
-
- if (ret == LZMA_STREAM_END)
- return 0;
-
- s.avail_out += *buffer_size;
-
- if (!(greedy_realloc(buffer, buffer_size, *buffer_size * 2, 1)))
- return -ENOMEM;
-
- s.next_out = *buffer + *buffer_size - s.avail_out;
- }
-
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_startswith_lz4(const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra) {
-#ifdef HAVE_LZ4
- /* Checks whether the decompressed blob starts with the
- * mentioned prefix. The byte extra needs to follow the
- * prefix */
-
- int r;
- size_t size;
-
- assert(src);
- assert(src_size > 0);
- assert(buffer);
- assert(buffer_size);
- assert(prefix);
- assert(*buffer_size == 0 || *buffer);
-
- if (src_size <= 8)
- return -EBADMSG;
-
- if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1)))
- return -ENOMEM;
-
- r = LZ4_decompress_safe_partial(src + 8, *buffer, src_size - 8,
- prefix_len + 1, *buffer_size);
- if (r >= 0)
- size = (unsigned) r;
- else {
- /* lz4 always tries to decode full "sequence", so in
- * pathological cases might need to decompress the
- * full field. */
- r = decompress_blob_lz4(src, src_size, buffer, buffer_size, &size, 0);
- if (r < 0)
- return r;
- }
-
- if (size >= prefix_len + 1)
- return memcmp(*buffer, prefix, prefix_len) == 0 &&
- ((const uint8_t*) *buffer)[prefix_len] == extra;
- else
- return 0;
-
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_startswith(int compression,
- const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra) {
- if (compression == OBJECT_COMPRESSED_XZ)
- return decompress_startswith_xz(src, src_size,
- buffer, buffer_size,
- prefix, prefix_len,
- extra);
- else if (compression == OBJECT_COMPRESSED_LZ4)
- return decompress_startswith_lz4(src, src_size,
- buffer, buffer_size,
- prefix, prefix_len,
- extra);
- else
- return -EBADMSG;
-}
-
-int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
-#ifdef HAVE_XZ
- _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
- lzma_ret ret;
- uint8_t buf[BUFSIZ], out[BUFSIZ];
- lzma_action action = LZMA_RUN;
-
- assert(fdf >= 0);
- assert(fdt >= 0);
-
- ret = lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64);
- if (ret != LZMA_OK) {
- log_error("Failed to initialize XZ encoder: code %u", ret);
- return -EINVAL;
- }
-
- for (;;) {
- if (s.avail_in == 0 && action == LZMA_RUN) {
- size_t m = sizeof(buf);
- ssize_t n;
-
- if (max_bytes != (uint64_t) -1 && (uint64_t) m > max_bytes)
- m = (size_t) max_bytes;
-
- n = read(fdf, buf, m);
- if (n < 0)
- return -errno;
- if (n == 0)
- action = LZMA_FINISH;
- else {
- s.next_in = buf;
- s.avail_in = n;
-
- if (max_bytes != (uint64_t) -1) {
- assert(max_bytes >= (uint64_t) n);
- max_bytes -= n;
- }
- }
- }
-
- if (s.avail_out == 0) {
- s.next_out = out;
- s.avail_out = sizeof(out);
- }
-
- ret = lzma_code(&s, action);
- if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
- log_error("Compression failed: code %u", ret);
- return -EBADMSG;
- }
-
- if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
- ssize_t n, k;
-
- n = sizeof(out) - s.avail_out;
-
- k = loop_write(fdt, out, n, false);
- if (k < 0)
- return k;
-
- if (ret == LZMA_STREAM_END) {
- log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
- s.total_in, s.total_out,
- (double) s.total_out / s.total_in * 100);
-
- return 0;
- }
- }
- }
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-#define LZ4_BUFSIZE (512*1024u)
-
-int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) {
-
-#ifdef HAVE_LZ4
- LZ4F_errorCode_t c;
- _cleanup_(LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL;
- _cleanup_free_ char *buf = NULL;
- char *src = NULL;
- size_t size, n, total_in = 0, total_out, offset = 0, frame_size;
- struct stat st;
- int r;
- static const LZ4F_compressOptions_t options = {
- .stableSrc = 1,
- };
- static const LZ4F_preferences_t preferences = {
- .frameInfo.blockSizeID = 5,
- };
-
- c = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
- if (LZ4F_isError(c))
- return -ENOMEM;
-
- if (fstat(fdf, &st) < 0)
- return log_debug_errno(errno, "fstat() failed: %m");
-
- frame_size = LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
- size = frame_size + 64*1024; /* add some space for header and trailer */
- buf = malloc(size);
- if (!buf)
- return -ENOMEM;
-
- n = offset = total_out = LZ4F_compressBegin(ctx, buf, size, &preferences);
- if (LZ4F_isError(n))
- return -EINVAL;
-
- src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
- if (src == MAP_FAILED)
- return -errno;
-
- log_debug("Buffer size is %zu bytes, header size %zu bytes.", size, n);
-
- while (total_in < (size_t) st.st_size) {
- ssize_t k;
-
- k = MIN(LZ4_BUFSIZE, st.st_size - total_in);
- n = LZ4F_compressUpdate(ctx, buf + offset, size - offset,
- src + total_in, k, &options);
- if (LZ4F_isError(n)) {
- r = -ENOTRECOVERABLE;
- goto cleanup;
- }
-
- total_in += k;
- offset += n;
- total_out += n;
-
- if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) {
- log_debug("Compressed stream longer than %zd bytes", max_bytes);
- return -EFBIG;
- }
-
- if (size - offset < frame_size + 4) {
- k = loop_write(fdt, buf, offset, false);
- if (k < 0) {
- r = k;
- goto cleanup;
- }
- offset = 0;
- }
- }
-
- n = LZ4F_compressEnd(ctx, buf + offset, size - offset, &options);
- if (LZ4F_isError(n)) {
- r = -ENOTRECOVERABLE;
- goto cleanup;
- }
-
- offset += n;
- total_out += n;
- r = loop_write(fdt, buf, offset, false);
- if (r < 0)
- goto cleanup;
-
- log_debug("LZ4 compression finished (%zu -> %zu bytes, %.1f%%)",
- total_in, total_out,
- (double) total_out / total_in * 100);
- cleanup:
- munmap(src, st.st_size);
- return r;
-#else
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
-
-#ifdef HAVE_XZ
- _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
- lzma_ret ret;
-
- uint8_t buf[BUFSIZ], out[BUFSIZ];
- lzma_action action = LZMA_RUN;
-
- assert(fdf >= 0);
- assert(fdt >= 0);
-
- ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
- if (ret != LZMA_OK) {
- log_debug("Failed to initialize XZ decoder: code %u", ret);
- return -ENOMEM;
- }
-
- for (;;) {
- if (s.avail_in == 0 && action == LZMA_RUN) {
- ssize_t n;
-
- n = read(fdf, buf, sizeof(buf));
- if (n < 0)
- return -errno;
- if (n == 0)
- action = LZMA_FINISH;
- else {
- s.next_in = buf;
- s.avail_in = n;
- }
- }
-
- if (s.avail_out == 0) {
- s.next_out = out;
- s.avail_out = sizeof(out);
- }
-
- ret = lzma_code(&s, action);
- if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
- log_debug("Decompression failed: code %u", ret);
- return -EBADMSG;
- }
-
- if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
- ssize_t n, k;
-
- n = sizeof(out) - s.avail_out;
-
- if (max_bytes != (uint64_t) -1) {
- if (max_bytes < (uint64_t) n)
- return -EFBIG;
-
- max_bytes -= n;
- }
-
- k = loop_write(fdt, out, n, false);
- if (k < 0)
- return k;
-
- if (ret == LZMA_STREAM_END) {
- log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
- s.total_in, s.total_out,
- (double) s.total_out / s.total_in * 100);
-
- return 0;
- }
- }
- }
-#else
- log_debug("Cannot decompress file. Compiled without XZ support.");
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_stream_lz4(int in, int out, uint64_t max_bytes) {
-#ifdef HAVE_LZ4
- size_t c;
- _cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
- _cleanup_free_ char *buf = NULL;
- char *src;
- struct stat st;
- int r = 0;
- size_t total_in = 0, total_out = 0;
-
- c = LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
- if (LZ4F_isError(c))
- return -ENOMEM;
-
- if (fstat(in, &st) < 0)
- return log_debug_errno(errno, "fstat() failed: %m");
-
- buf = malloc(LZ4_BUFSIZE);
- if (!buf)
- return -ENOMEM;
-
- src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, in, 0);
- if (src == MAP_FAILED)
- return -errno;
-
- while (total_in < (size_t) st.st_size) {
- size_t produced = LZ4_BUFSIZE;
- size_t used = st.st_size - total_in;
-
- c = LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
- if (LZ4F_isError(c)) {
- r = -EBADMSG;
- goto cleanup;
- }
-
- total_in += used;
- total_out += produced;
-
- if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) {
- log_debug("Decompressed stream longer than %zd bytes", max_bytes);
- r = -EFBIG;
- goto cleanup;
- }
-
- r = loop_write(out, buf, produced, false);
- if (r < 0)
- goto cleanup;
- }
-
- log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
- total_in, total_out,
- (double) total_out / total_in * 100);
- cleanup:
- munmap(src, st.st_size);
- return r;
-#else
- log_debug("Cannot decompress file. Compiled without LZ4 support.");
- return -EPROTONOSUPPORT;
-#endif
-}
-
-int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes) {
-
- if (endswith(filename, ".lz4"))
- return decompress_stream_lz4(fdf, fdt, max_bytes);
- else if (endswith(filename, ".xz"))
- return decompress_stream_xz(fdf, fdt, max_bytes);
- else
- return -EPROTONOSUPPORT;
-}
diff --git a/src/journal/compress.h b/src/journal/compress.h
deleted file mode 100644
index c138099d9a..0000000000
--- a/src/journal/compress.h
+++ /dev/null
@@ -1,85 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <unistd.h>
-
-#include "journal-def.h"
-
-const char* object_compressed_to_string(int compression);
-int object_compressed_from_string(const char *compression);
-
-int compress_blob_xz(const void *src, uint64_t src_size,
- void *dst, size_t dst_alloc_size, size_t *dst_size);
-int compress_blob_lz4(const void *src, uint64_t src_size,
- void *dst, size_t dst_alloc_size, size_t *dst_size);
-
-static inline int compress_blob(const void *src, uint64_t src_size,
- void *dst, size_t dst_alloc_size, size_t *dst_size) {
- int r;
-#ifdef HAVE_LZ4
- r = compress_blob_lz4(src, src_size, dst, dst_alloc_size, dst_size);
- if (r == 0)
- return OBJECT_COMPRESSED_LZ4;
-#else
- r = compress_blob_xz(src, src_size, dst, dst_alloc_size, dst_size);
- if (r == 0)
- return OBJECT_COMPRESSED_XZ;
-#endif
- return r;
-}
-
-int decompress_blob_xz(const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max);
-int decompress_blob_lz4(const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max);
-int decompress_blob(int compression,
- const void *src, uint64_t src_size,
- void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max);
-
-int decompress_startswith_xz(const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra);
-int decompress_startswith_lz4(const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra);
-int decompress_startswith(int compression,
- const void *src, uint64_t src_size,
- void **buffer, size_t *buffer_size,
- const void *prefix, size_t prefix_len,
- uint8_t extra);
-
-int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes);
-int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes);
-
-int decompress_stream_xz(int fdf, int fdt, uint64_t max_size);
-int decompress_stream_lz4(int fdf, int fdt, uint64_t max_size);
-
-#ifdef HAVE_LZ4
-# define compress_stream compress_stream_lz4
-# define COMPRESSED_EXT ".lz4"
-#else
-# define compress_stream compress_stream_xz
-# define COMPRESSED_EXT ".xz"
-#endif
-
-int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes);
diff --git a/src/journal/fsprg.c b/src/journal/fsprg.c
deleted file mode 100644
index 8f7e137e74..0000000000
--- a/src/journal/fsprg.c
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * fsprg v0.1 - (seekable) forward-secure pseudorandom generator
- * Copyright (C) 2012 B. Poettering
- * Contact: fsprg@point-at-infinity.org
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA
- */
-
-/*
- * See "Practical Secure Logging: Seekable Sequential Key Generators"
- * by G. A. Marson, B. Poettering for details:
- *
- * http://eprint.iacr.org/2013/397
- */
-
-#include <gcrypt.h>
-#include <string.h>
-
-#include "fsprg.h"
-
-#define ISVALID_SECPAR(secpar) (((secpar) % 16 == 0) && ((secpar) >= 16) && ((secpar) <= 16384))
-#define VALIDATE_SECPAR(secpar) assert(ISVALID_SECPAR(secpar));
-
-#define RND_HASH GCRY_MD_SHA256
-#define RND_GEN_P 0x01
-#define RND_GEN_Q 0x02
-#define RND_GEN_X 0x03
-
-/******************************************************************************/
-
-static void mpi_export(void *buf, size_t buflen, const gcry_mpi_t x) {
- unsigned len;
- size_t nwritten;
-
- assert(gcry_mpi_cmp_ui(x, 0) >= 0);
- len = (gcry_mpi_get_nbits(x) + 7) / 8;
- assert(len <= buflen);
- memzero(buf, buflen);
- gcry_mpi_print(GCRYMPI_FMT_USG, buf + (buflen - len), len, &nwritten, x);
- assert(nwritten == len);
-}
-
-static gcry_mpi_t mpi_import(const void *buf, size_t buflen) {
- gcry_mpi_t h;
- unsigned len;
-
- gcry_mpi_scan(&h, GCRYMPI_FMT_USG, buf, buflen, NULL);
- len = (gcry_mpi_get_nbits(h) + 7) / 8;
- assert(len <= buflen);
- assert(gcry_mpi_cmp_ui(h, 0) >= 0);
-
- return h;
-}
-
-static void uint64_export(void *buf, size_t buflen, uint64_t x) {
- assert(buflen == 8);
- ((uint8_t*) buf)[0] = (x >> 56) & 0xff;
- ((uint8_t*) buf)[1] = (x >> 48) & 0xff;
- ((uint8_t*) buf)[2] = (x >> 40) & 0xff;
- ((uint8_t*) buf)[3] = (x >> 32) & 0xff;
- ((uint8_t*) buf)[4] = (x >> 24) & 0xff;
- ((uint8_t*) buf)[5] = (x >> 16) & 0xff;
- ((uint8_t*) buf)[6] = (x >> 8) & 0xff;
- ((uint8_t*) buf)[7] = (x >> 0) & 0xff;
-}
-
-_pure_ static uint64_t uint64_import(const void *buf, size_t buflen) {
- assert(buflen == 8);
- return
- (uint64_t)(((uint8_t*) buf)[0]) << 56 |
- (uint64_t)(((uint8_t*) buf)[1]) << 48 |
- (uint64_t)(((uint8_t*) buf)[2]) << 40 |
- (uint64_t)(((uint8_t*) buf)[3]) << 32 |
- (uint64_t)(((uint8_t*) buf)[4]) << 24 |
- (uint64_t)(((uint8_t*) buf)[5]) << 16 |
- (uint64_t)(((uint8_t*) buf)[6]) << 8 |
- (uint64_t)(((uint8_t*) buf)[7]) << 0;
-}
-
-/* deterministically generate from seed/idx a string of buflen pseudorandom bytes */
-static void det_randomize(void *buf, size_t buflen, const void *seed, size_t seedlen, uint32_t idx) {
- gcry_md_hd_t hd, hd2;
- size_t olen, cpylen;
- uint32_t ctr;
-
- olen = gcry_md_get_algo_dlen(RND_HASH);
- gcry_md_open(&hd, RND_HASH, 0);
- gcry_md_write(hd, seed, seedlen);
- gcry_md_putc(hd, (idx >> 24) & 0xff);
- gcry_md_putc(hd, (idx >> 16) & 0xff);
- gcry_md_putc(hd, (idx >> 8) & 0xff);
- gcry_md_putc(hd, (idx >> 0) & 0xff);
-
- for (ctr = 0; buflen; ctr++) {
- gcry_md_copy(&hd2, hd);
- gcry_md_putc(hd2, (ctr >> 24) & 0xff);
- gcry_md_putc(hd2, (ctr >> 16) & 0xff);
- gcry_md_putc(hd2, (ctr >> 8) & 0xff);
- gcry_md_putc(hd2, (ctr >> 0) & 0xff);
- gcry_md_final(hd2);
- cpylen = (buflen < olen) ? buflen : olen;
- memcpy(buf, gcry_md_read(hd2, RND_HASH), cpylen);
- gcry_md_close(hd2);
- buf += cpylen;
- buflen -= cpylen;
- }
- gcry_md_close(hd);
-}
-
-/* deterministically generate from seed/idx a prime of length `bits' that is 3 (mod 4) */
-static gcry_mpi_t genprime3mod4(int bits, const void *seed, size_t seedlen, uint32_t idx) {
- size_t buflen = bits / 8;
- uint8_t buf[buflen];
- gcry_mpi_t p;
-
- assert(bits % 8 == 0);
- assert(buflen > 0);
-
- det_randomize(buf, buflen, seed, seedlen, idx);
- buf[0] |= 0xc0; /* set upper two bits, so that n=pq has maximum size */
- buf[buflen - 1] |= 0x03; /* set lower two bits, to have result 3 (mod 4) */
-
- p = mpi_import(buf, buflen);
- while (gcry_prime_check(p, 0))
- gcry_mpi_add_ui(p, p, 4);
-
- return p;
-}
-
-/* deterministically generate from seed/idx a quadratic residue (mod n) */
-static gcry_mpi_t gensquare(const gcry_mpi_t n, const void *seed, size_t seedlen, uint32_t idx, unsigned secpar) {
- size_t buflen = secpar / 8;
- uint8_t buf[buflen];
- gcry_mpi_t x;
-
- det_randomize(buf, buflen, seed, seedlen, idx);
- buf[0] &= 0x7f; /* clear upper bit, so that we have x < n */
- x = mpi_import(buf, buflen);
- assert(gcry_mpi_cmp(x, n) < 0);
- gcry_mpi_mulm(x, x, x, n);
- return x;
-}
-
-/* compute 2^m (mod phi(p)), for a prime p */
-static gcry_mpi_t twopowmodphi(uint64_t m, const gcry_mpi_t p) {
- gcry_mpi_t phi, r;
- int n;
-
- phi = gcry_mpi_new(0);
- gcry_mpi_sub_ui(phi, p, 1);
-
- /* count number of used bits in m */
- for (n = 0; (1ULL << n) <= m; n++)
- ;
-
- r = gcry_mpi_new(0);
- gcry_mpi_set_ui(r, 1);
- while (n) { /* square and multiply algorithm for fast exponentiation */
- n--;
- gcry_mpi_mulm(r, r, r, phi);
- if (m & ((uint64_t)1 << n)) {
- gcry_mpi_add(r, r, r);
- if (gcry_mpi_cmp(r, phi) >= 0)
- gcry_mpi_sub(r, r, phi);
- }
- }
-
- gcry_mpi_release(phi);
- return r;
-}
-
-/* Decompose $x \in Z_n$ into $(xp,xq) \in Z_p \times Z_q$ using Chinese Remainder Theorem */
-static void CRT_decompose(gcry_mpi_t *xp, gcry_mpi_t *xq, const gcry_mpi_t x, const gcry_mpi_t p, const gcry_mpi_t q) {
- *xp = gcry_mpi_new(0);
- *xq = gcry_mpi_new(0);
- gcry_mpi_mod(*xp, x, p);
- gcry_mpi_mod(*xq, x, q);
-}
-
-/* Compose $(xp,xq) \in Z_p \times Z_q$ into $x \in Z_n$ using Chinese Remainder Theorem */
-static void CRT_compose(gcry_mpi_t *x, const gcry_mpi_t xp, const gcry_mpi_t xq, const gcry_mpi_t p, const gcry_mpi_t q) {
- gcry_mpi_t a, u;
-
- a = gcry_mpi_new(0);
- u = gcry_mpi_new(0);
- *x = gcry_mpi_new(0);
- gcry_mpi_subm(a, xq, xp, q);
- gcry_mpi_invm(u, p, q);
- gcry_mpi_mulm(a, a, u, q); /* a = (xq - xp) / p (mod q) */
- gcry_mpi_mul(*x, p, a);
- gcry_mpi_add(*x, *x, xp); /* x = p * ((xq - xp) / p mod q) + xp */
- gcry_mpi_release(a);
- gcry_mpi_release(u);
-}
-
-static void initialize_libgcrypt(void) {
- const char *p;
- if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
- return;
-
- p = gcry_check_version("1.4.5");
- assert(p);
-
- /* Turn off "secmem". Clients which whish to make use of this
- * feature should initialize the library manually */
- gcry_control(GCRYCTL_DISABLE_SECMEM);
- gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
-}
-
-/******************************************************************************/
-
-size_t FSPRG_mskinbytes(unsigned _secpar) {
- VALIDATE_SECPAR(_secpar);
- return 2 + 2 * (_secpar / 2) / 8; /* to store header,p,q */
-}
-
-size_t FSPRG_mpkinbytes(unsigned _secpar) {
- VALIDATE_SECPAR(_secpar);
- return 2 + _secpar / 8; /* to store header,n */
-}
-
-size_t FSPRG_stateinbytes(unsigned _secpar) {
- VALIDATE_SECPAR(_secpar);
- return 2 + 2 * _secpar / 8 + 8; /* to store header,n,x,epoch */
-}
-
-static void store_secpar(void *buf, uint16_t secpar) {
- secpar = secpar / 16 - 1;
- ((uint8_t*) buf)[0] = (secpar >> 8) & 0xff;
- ((uint8_t*) buf)[1] = (secpar >> 0) & 0xff;
-}
-
-static uint16_t read_secpar(const void *buf) {
- uint16_t secpar;
- secpar =
- (uint16_t)(((uint8_t*) buf)[0]) << 8 |
- (uint16_t)(((uint8_t*) buf)[1]) << 0;
- return 16 * (secpar + 1);
-}
-
-void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned _secpar) {
- uint8_t iseed[FSPRG_RECOMMENDED_SEEDLEN];
- gcry_mpi_t n, p, q;
- uint16_t secpar;
-
- VALIDATE_SECPAR(_secpar);
- secpar = _secpar;
-
- initialize_libgcrypt();
-
- if (!seed) {
- gcry_randomize(iseed, FSPRG_RECOMMENDED_SEEDLEN, GCRY_STRONG_RANDOM);
- seed = iseed;
- seedlen = FSPRG_RECOMMENDED_SEEDLEN;
- }
-
- p = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_P);
- q = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_Q);
-
- if (msk) {
- store_secpar(msk + 0, secpar);
- mpi_export(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8, p);
- mpi_export(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8, q);
- }
-
- if (mpk) {
- n = gcry_mpi_new(0);
- gcry_mpi_mul(n, p, q);
- assert(gcry_mpi_get_nbits(n) == secpar);
-
- store_secpar(mpk + 0, secpar);
- mpi_export(mpk + 2, secpar / 8, n);
-
- gcry_mpi_release(n);
- }
-
- gcry_mpi_release(p);
- gcry_mpi_release(q);
-}
-
-void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen) {
- gcry_mpi_t n, x;
- uint16_t secpar;
-
- initialize_libgcrypt();
-
- secpar = read_secpar(mpk + 0);
- n = mpi_import(mpk + 2, secpar / 8);
- x = gensquare(n, seed, seedlen, RND_GEN_X, secpar);
-
- memcpy(state, mpk, 2 + secpar / 8);
- mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x);
- memzero(state + 2 + 2 * secpar / 8, 8);
-
- gcry_mpi_release(n);
- gcry_mpi_release(x);
-}
-
-void FSPRG_Evolve(void *state) {
- gcry_mpi_t n, x;
- uint16_t secpar;
- uint64_t epoch;
-
- initialize_libgcrypt();
-
- secpar = read_secpar(state + 0);
- n = mpi_import(state + 2 + 0 * secpar / 8, secpar / 8);
- x = mpi_import(state + 2 + 1 * secpar / 8, secpar / 8);
- epoch = uint64_import(state + 2 + 2 * secpar / 8, 8);
-
- gcry_mpi_mulm(x, x, x, n);
- epoch++;
-
- mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x);
- uint64_export(state + 2 + 2 * secpar / 8, 8, epoch);
-
- gcry_mpi_release(n);
- gcry_mpi_release(x);
-}
-
-uint64_t FSPRG_GetEpoch(const void *state) {
- uint16_t secpar;
- secpar = read_secpar(state + 0);
- return uint64_import(state + 2 + 2 * secpar / 8, 8);
-}
-
-void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen) {
- gcry_mpi_t p, q, n, x, xp, xq, kp, kq, xm;
- uint16_t secpar;
-
- initialize_libgcrypt();
-
- secpar = read_secpar(msk + 0);
- p = mpi_import(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8);
- q = mpi_import(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8);
-
- n = gcry_mpi_new(0);
- gcry_mpi_mul(n, p, q);
-
- x = gensquare(n, seed, seedlen, RND_GEN_X, secpar);
- CRT_decompose(&xp, &xq, x, p, q); /* split (mod n) into (mod p) and (mod q) using CRT */
-
- kp = twopowmodphi(epoch, p); /* compute 2^epoch (mod phi(p)) */
- kq = twopowmodphi(epoch, q); /* compute 2^epoch (mod phi(q)) */
-
- gcry_mpi_powm(xp, xp, kp, p); /* compute x^(2^epoch) (mod p) */
- gcry_mpi_powm(xq, xq, kq, q); /* compute x^(2^epoch) (mod q) */
-
- CRT_compose(&xm, xp, xq, p, q); /* combine (mod p) and (mod q) to (mod n) using CRT */
-
- store_secpar(state + 0, secpar);
- mpi_export(state + 2 + 0 * secpar / 8, secpar / 8, n);
- mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, xm);
- uint64_export(state + 2 + 2 * secpar / 8, 8, epoch);
-
- gcry_mpi_release(p);
- gcry_mpi_release(q);
- gcry_mpi_release(n);
- gcry_mpi_release(x);
- gcry_mpi_release(xp);
- gcry_mpi_release(xq);
- gcry_mpi_release(kp);
- gcry_mpi_release(kq);
- gcry_mpi_release(xm);
-}
-
-void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx) {
- uint16_t secpar;
-
- initialize_libgcrypt();
-
- secpar = read_secpar(state + 0);
- det_randomize(key, keylen, state + 2, 2 * secpar / 8 + 8, idx);
-}
diff --git a/src/journal/fsprg.h b/src/journal/fsprg.h
deleted file mode 100644
index 829b56e240..0000000000
--- a/src/journal/fsprg.h
+++ /dev/null
@@ -1,65 +0,0 @@
-#ifndef __fsprgh__
-#define __fsprgh__
-
-/*
- * fsprg v0.1 - (seekable) forward-secure pseudorandom generator
- * Copyright (C) 2012 B. Poettering
- * Contact: fsprg@point-at-infinity.org
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA
- *
- */
-
-#include <inttypes.h>
-#include <sys/types.h>
-
-#include "macro.h"
-#include "util.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define FSPRG_RECOMMENDED_SECPAR 1536
-#define FSPRG_RECOMMENDED_SEEDLEN (96/8)
-
-size_t FSPRG_mskinbytes(unsigned secpar) _const_;
-size_t FSPRG_mpkinbytes(unsigned secpar) _const_;
-size_t FSPRG_stateinbytes(unsigned secpar) _const_;
-
-/* Setup msk and mpk. Providing seed != NULL makes this algorithm deterministic. */
-void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned secpar);
-
-/* Initialize state deterministically in dependence on seed. */
-/* Note: in case one wants to run only one GenState0 per GenMK it is safe to use
- the same seed for both GenMK and GenState0.
-*/
-void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen);
-
-void FSPRG_Evolve(void *state);
-
-uint64_t FSPRG_GetEpoch(const void *state) _pure_;
-
-/* Seek to any arbitrary state (by providing msk together with seed from GenState0). */
-void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen);
-
-void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/src/journal/journal-authenticate.c b/src/journal/journal-authenticate.c
deleted file mode 100644
index 49f3c8f0f4..0000000000
--- a/src/journal/journal-authenticate.c
+++ /dev/null
@@ -1,562 +0,0 @@
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <fcntl.h>
-#include <sys/mman.h>
-
-#include "fd-util.h"
-#include "fsprg.h"
-#include "hexdecoct.h"
-#include "journal-authenticate.h"
-#include "journal-def.h"
-#include "journal-file.h"
-
-static uint64_t journal_file_tag_seqnum(JournalFile *f) {
- uint64_t r;
-
- assert(f);
-
- r = le64toh(f->header->n_tags) + 1;
- f->header->n_tags = htole64(r);
-
- return r;
-}
-
-int journal_file_append_tag(JournalFile *f) {
- Object *o;
- uint64_t p;
- int r;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- if (!f->hmac_running)
- return 0;
-
- assert(f->hmac);
-
- r = journal_file_append_object(f, OBJECT_TAG, sizeof(struct TagObject), &o, &p);
- if (r < 0)
- return r;
-
- o->tag.seqnum = htole64(journal_file_tag_seqnum(f));
- o->tag.epoch = htole64(FSPRG_GetEpoch(f->fsprg_state));
-
- log_debug("Writing tag %"PRIu64" for epoch %"PRIu64"",
- le64toh(o->tag.seqnum),
- FSPRG_GetEpoch(f->fsprg_state));
-
- /* Add the tag object itself, so that we can protect its
- * header. This will exclude the actual hash value in it */
- r = journal_file_hmac_put_object(f, OBJECT_TAG, o, p);
- if (r < 0)
- return r;
-
- /* Get the HMAC tag and store it in the object */
- memcpy(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH);
- f->hmac_running = false;
-
- return 0;
-}
-
-int journal_file_hmac_start(JournalFile *f) {
- uint8_t key[256 / 8]; /* Let's pass 256 bit from FSPRG to HMAC */
- assert(f);
-
- if (!f->seal)
- return 0;
-
- if (f->hmac_running)
- return 0;
-
- /* Prepare HMAC for next cycle */
- gcry_md_reset(f->hmac);
- FSPRG_GetKey(f->fsprg_state, key, sizeof(key), 0);
- gcry_md_setkey(f->hmac, key, sizeof(key));
-
- f->hmac_running = true;
-
- return 0;
-}
-
-static int journal_file_get_epoch(JournalFile *f, uint64_t realtime, uint64_t *epoch) {
- uint64_t t;
-
- assert(f);
- assert(epoch);
- assert(f->seal);
-
- if (f->fss_start_usec == 0 ||
- f->fss_interval_usec == 0)
- return -EOPNOTSUPP;
-
- if (realtime < f->fss_start_usec)
- return -ESTALE;
-
- t = realtime - f->fss_start_usec;
- t = t / f->fss_interval_usec;
-
- *epoch = t;
- return 0;
-}
-
-static int journal_file_fsprg_need_evolve(JournalFile *f, uint64_t realtime) {
- uint64_t goal, epoch;
- int r;
- assert(f);
-
- if (!f->seal)
- return 0;
-
- r = journal_file_get_epoch(f, realtime, &goal);
- if (r < 0)
- return r;
-
- epoch = FSPRG_GetEpoch(f->fsprg_state);
- if (epoch > goal)
- return -ESTALE;
-
- return epoch != goal;
-}
-
-int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime) {
- uint64_t goal, epoch;
- int r;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- r = journal_file_get_epoch(f, realtime, &goal);
- if (r < 0)
- return r;
-
- epoch = FSPRG_GetEpoch(f->fsprg_state);
- if (epoch < goal)
- log_debug("Evolving FSPRG key from epoch %"PRIu64" to %"PRIu64".", epoch, goal);
-
- for (;;) {
- if (epoch > goal)
- return -ESTALE;
- if (epoch == goal)
- return 0;
-
- FSPRG_Evolve(f->fsprg_state);
- epoch = FSPRG_GetEpoch(f->fsprg_state);
- }
-}
-
-int journal_file_fsprg_seek(JournalFile *f, uint64_t goal) {
- void *msk;
- uint64_t epoch;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- assert(f->fsprg_seed);
-
- if (f->fsprg_state) {
- /* Cheaper... */
-
- epoch = FSPRG_GetEpoch(f->fsprg_state);
- if (goal == epoch)
- return 0;
-
- if (goal == epoch+1) {
- FSPRG_Evolve(f->fsprg_state);
- return 0;
- }
- } else {
- f->fsprg_state_size = FSPRG_stateinbytes(FSPRG_RECOMMENDED_SECPAR);
- f->fsprg_state = malloc(f->fsprg_state_size);
-
- if (!f->fsprg_state)
- return -ENOMEM;
- }
-
- log_debug("Seeking FSPRG key to %"PRIu64".", goal);
-
- msk = alloca(FSPRG_mskinbytes(FSPRG_RECOMMENDED_SECPAR));
- FSPRG_GenMK(msk, NULL, f->fsprg_seed, f->fsprg_seed_size, FSPRG_RECOMMENDED_SECPAR);
- FSPRG_Seek(f->fsprg_state, goal, msk, f->fsprg_seed, f->fsprg_seed_size);
- return 0;
-}
-
-int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime) {
- int r;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- if (realtime <= 0)
- realtime = now(CLOCK_REALTIME);
-
- r = journal_file_fsprg_need_evolve(f, realtime);
- if (r <= 0)
- return 0;
-
- r = journal_file_append_tag(f);
- if (r < 0)
- return r;
-
- r = journal_file_fsprg_evolve(f, realtime);
- if (r < 0)
- return r;
-
- return 0;
-}
-
-int journal_file_hmac_put_object(JournalFile *f, ObjectType type, Object *o, uint64_t p) {
- int r;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- r = journal_file_hmac_start(f);
- if (r < 0)
- return r;
-
- if (!o) {
- r = journal_file_move_to_object(f, type, p, &o);
- if (r < 0)
- return r;
- } else {
- if (type > OBJECT_UNUSED && o->object.type != type)
- return -EBADMSG;
- }
-
- gcry_md_write(f->hmac, o, offsetof(ObjectHeader, payload));
-
- switch (o->object.type) {
-
- case OBJECT_DATA:
- /* All but hash and payload are mutable */
- gcry_md_write(f->hmac, &o->data.hash, sizeof(o->data.hash));
- gcry_md_write(f->hmac, o->data.payload, le64toh(o->object.size) - offsetof(DataObject, payload));
- break;
-
- case OBJECT_FIELD:
- /* Same here */
- gcry_md_write(f->hmac, &o->field.hash, sizeof(o->field.hash));
- gcry_md_write(f->hmac, o->field.payload, le64toh(o->object.size) - offsetof(FieldObject, payload));
- break;
-
- case OBJECT_ENTRY:
- /* All */
- gcry_md_write(f->hmac, &o->entry.seqnum, le64toh(o->object.size) - offsetof(EntryObject, seqnum));
- break;
-
- case OBJECT_FIELD_HASH_TABLE:
- case OBJECT_DATA_HASH_TABLE:
- case OBJECT_ENTRY_ARRAY:
- /* Nothing: everything is mutable */
- break;
-
- case OBJECT_TAG:
- /* All but the tag itself */
- gcry_md_write(f->hmac, &o->tag.seqnum, sizeof(o->tag.seqnum));
- gcry_md_write(f->hmac, &o->tag.epoch, sizeof(o->tag.epoch));
- break;
- default:
- return -EINVAL;
- }
-
- return 0;
-}
-
-int journal_file_hmac_put_header(JournalFile *f) {
- int r;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- r = journal_file_hmac_start(f);
- if (r < 0)
- return r;
-
- /* All but state+reserved, boot_id, arena_size,
- * tail_object_offset, n_objects, n_entries,
- * tail_entry_seqnum, head_entry_seqnum, entry_array_offset,
- * head_entry_realtime, tail_entry_realtime,
- * tail_entry_monotonic, n_data, n_fields, n_tags,
- * n_entry_arrays. */
-
- gcry_md_write(f->hmac, f->header->signature, offsetof(Header, state) - offsetof(Header, signature));
- gcry_md_write(f->hmac, &f->header->file_id, offsetof(Header, boot_id) - offsetof(Header, file_id));
- gcry_md_write(f->hmac, &f->header->seqnum_id, offsetof(Header, arena_size) - offsetof(Header, seqnum_id));
- gcry_md_write(f->hmac, &f->header->data_hash_table_offset, offsetof(Header, tail_object_offset) - offsetof(Header, data_hash_table_offset));
-
- return 0;
-}
-
-int journal_file_fss_load(JournalFile *f) {
- int r, fd = -1;
- char *p = NULL;
- struct stat st;
- FSSHeader *m = NULL;
- sd_id128_t machine;
-
- assert(f);
-
- if (!f->seal)
- return 0;
-
- r = sd_id128_get_machine(&machine);
- if (r < 0)
- return r;
-
- if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss",
- SD_ID128_FORMAT_VAL(machine)) < 0)
- return -ENOMEM;
-
- fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY, 0600);
- if (fd < 0) {
- if (errno != ENOENT)
- log_error_errno(errno, "Failed to open %s: %m", p);
-
- r = -errno;
- goto finish;
- }
-
- if (fstat(fd, &st) < 0) {
- r = -errno;
- goto finish;
- }
-
- if (st.st_size < (off_t) sizeof(FSSHeader)) {
- r = -ENODATA;
- goto finish;
- }
-
- m = mmap(NULL, PAGE_ALIGN(sizeof(FSSHeader)), PROT_READ, MAP_SHARED, fd, 0);
- if (m == MAP_FAILED) {
- m = NULL;
- r = -errno;
- goto finish;
- }
-
- if (memcmp(m->signature, FSS_HEADER_SIGNATURE, 8) != 0) {
- r = -EBADMSG;
- goto finish;
- }
-
- if (m->incompatible_flags != 0) {
- r = -EPROTONOSUPPORT;
- goto finish;
- }
-
- if (le64toh(m->header_size) < sizeof(FSSHeader)) {
- r = -EBADMSG;
- goto finish;
- }
-
- if (le64toh(m->fsprg_state_size) != FSPRG_stateinbytes(le16toh(m->fsprg_secpar))) {
- r = -EBADMSG;
- goto finish;
- }
-
- f->fss_file_size = le64toh(m->header_size) + le64toh(m->fsprg_state_size);
- if ((uint64_t) st.st_size < f->fss_file_size) {
- r = -ENODATA;
- goto finish;
- }
-
- if (!sd_id128_equal(machine, m->machine_id)) {
- r = -EHOSTDOWN;
- goto finish;
- }
-
- if (le64toh(m->start_usec) <= 0 ||
- le64toh(m->interval_usec) <= 0) {
- r = -EBADMSG;
- goto finish;
- }
-
- f->fss_file = mmap(NULL, PAGE_ALIGN(f->fss_file_size), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
- if (f->fss_file == MAP_FAILED) {
- f->fss_file = NULL;
- r = -errno;
- goto finish;
- }
-
- f->fss_start_usec = le64toh(f->fss_file->start_usec);
- f->fss_interval_usec = le64toh(f->fss_file->interval_usec);
-
- f->fsprg_state = (uint8_t*) f->fss_file + le64toh(f->fss_file->header_size);
- f->fsprg_state_size = le64toh(f->fss_file->fsprg_state_size);
-
- r = 0;
-
-finish:
- if (m)
- munmap(m, PAGE_ALIGN(sizeof(FSSHeader)));
-
- safe_close(fd);
- free(p);
-
- return r;
-}
-
-static void initialize_libgcrypt(void) {
- const char *p;
-
- if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
- return;
-
- p = gcry_check_version("1.4.5");
- assert(p);
-
- gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
-}
-
-int journal_file_hmac_setup(JournalFile *f) {
- gcry_error_t e;
-
- if (!f->seal)
- return 0;
-
- initialize_libgcrypt();
-
- e = gcry_md_open(&f->hmac, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
- if (e != 0)
- return -EOPNOTSUPP;
-
- return 0;
-}
-
-int journal_file_append_first_tag(JournalFile *f) {
- int r;
- uint64_t p;
-
- if (!f->seal)
- return 0;
-
- log_debug("Calculating first tag...");
-
- r = journal_file_hmac_put_header(f);
- if (r < 0)
- return r;
-
- p = le64toh(f->header->field_hash_table_offset);
- if (p < offsetof(Object, hash_table.items))
- return -EINVAL;
- p -= offsetof(Object, hash_table.items);
-
- r = journal_file_hmac_put_object(f, OBJECT_FIELD_HASH_TABLE, NULL, p);
- if (r < 0)
- return r;
-
- p = le64toh(f->header->data_hash_table_offset);
- if (p < offsetof(Object, hash_table.items))
- return -EINVAL;
- p -= offsetof(Object, hash_table.items);
-
- r = journal_file_hmac_put_object(f, OBJECT_DATA_HASH_TABLE, NULL, p);
- if (r < 0)
- return r;
-
- r = journal_file_append_tag(f);
- if (r < 0)
- return r;
-
- return 0;
-}
-
-int journal_file_parse_verification_key(JournalFile *f, const char *key) {
- uint8_t *seed;
- size_t seed_size, c;
- const char *k;
- int r;
- unsigned long long start, interval;
-
- seed_size = FSPRG_RECOMMENDED_SEEDLEN;
- seed = malloc(seed_size);
- if (!seed)
- return -ENOMEM;
-
- k = key;
- for (c = 0; c < seed_size; c++) {
- int x, y;
-
- while (*k == '-')
- k++;
-
- x = unhexchar(*k);
- if (x < 0) {
- free(seed);
- return -EINVAL;
- }
- k++;
- y = unhexchar(*k);
- if (y < 0) {
- free(seed);
- return -EINVAL;
- }
- k++;
-
- seed[c] = (uint8_t) (x * 16 + y);
- }
-
- if (*k != '/') {
- free(seed);
- return -EINVAL;
- }
- k++;
-
- r = sscanf(k, "%llx-%llx", &start, &interval);
- if (r != 2) {
- free(seed);
- return -EINVAL;
- }
-
- f->fsprg_seed = seed;
- f->fsprg_seed_size = seed_size;
-
- f->fss_start_usec = start * interval;
- f->fss_interval_usec = interval;
-
- return 0;
-}
-
-bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u) {
- uint64_t epoch;
-
- assert(f);
- assert(u);
-
- if (!f->seal)
- return false;
-
- epoch = FSPRG_GetEpoch(f->fsprg_state);
-
- *u = (usec_t) (f->fss_start_usec + f->fss_interval_usec * epoch + f->fss_interval_usec);
-
- return true;
-}
diff --git a/src/journal/journal-authenticate.h b/src/journal/journal-authenticate.h
deleted file mode 100644
index 6c87319ede..0000000000
--- a/src/journal/journal-authenticate.h
+++ /dev/null
@@ -1,41 +0,0 @@
-#pragma once
-
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <stdbool.h>
-
-#include "journal-file.h"
-
-int journal_file_append_tag(JournalFile *f);
-int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime);
-int journal_file_append_first_tag(JournalFile *f);
-
-int journal_file_hmac_setup(JournalFile *f);
-int journal_file_hmac_start(JournalFile *f);
-int journal_file_hmac_put_header(JournalFile *f);
-int journal_file_hmac_put_object(JournalFile *f, ObjectType type, Object *o, uint64_t p);
-
-int journal_file_fss_load(JournalFile *f);
-int journal_file_parse_verification_key(JournalFile *f, const char *key);
-
-int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime);
-int journal_file_fsprg_seek(JournalFile *f, uint64_t epoch);
-
-bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u);
diff --git a/src/journal/journal-def.h b/src/journal/journal-def.h
deleted file mode 100644
index 67edb43960..0000000000
--- a/src/journal/journal-def.h
+++ /dev/null
@@ -1,237 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include "sd-id128.h"
-
-#include "macro.h"
-#include "sparse-endian.h"
-
-/*
- * If you change this file you probably should also change its documentation:
- *
- * http://www.freedesktop.org/wiki/Software/systemd/journal-files
- *
- */
-
-typedef struct Header Header;
-
-typedef struct ObjectHeader ObjectHeader;
-typedef union Object Object;
-
-typedef struct DataObject DataObject;
-typedef struct FieldObject FieldObject;
-typedef struct EntryObject EntryObject;
-typedef struct HashTableObject HashTableObject;
-typedef struct EntryArrayObject EntryArrayObject;
-typedef struct TagObject TagObject;
-
-typedef struct EntryItem EntryItem;
-typedef struct HashItem HashItem;
-
-typedef struct FSSHeader FSSHeader;
-
-/* Object types */
-typedef enum ObjectType {
- OBJECT_UNUSED, /* also serves as "any type" or "additional context" */
- OBJECT_DATA,
- OBJECT_FIELD,
- OBJECT_ENTRY,
- OBJECT_DATA_HASH_TABLE,
- OBJECT_FIELD_HASH_TABLE,
- OBJECT_ENTRY_ARRAY,
- OBJECT_TAG,
- _OBJECT_TYPE_MAX
-} ObjectType;
-
-/* Object flags */
-enum {
- OBJECT_COMPRESSED_XZ = 1 << 0,
- OBJECT_COMPRESSED_LZ4 = 1 << 1,
- _OBJECT_COMPRESSED_MAX
-};
-
-#define OBJECT_COMPRESSION_MASK (OBJECT_COMPRESSED_XZ | OBJECT_COMPRESSED_LZ4)
-
-struct ObjectHeader {
- uint8_t type;
- uint8_t flags;
- uint8_t reserved[6];
- le64_t size;
- uint8_t payload[];
-} _packed_;
-
-struct DataObject {
- ObjectHeader object;
- le64_t hash;
- le64_t next_hash_offset;
- le64_t next_field_offset;
- le64_t entry_offset; /* the first array entry we store inline */
- le64_t entry_array_offset;
- le64_t n_entries;
- uint8_t payload[];
-} _packed_;
-
-struct FieldObject {
- ObjectHeader object;
- le64_t hash;
- le64_t next_hash_offset;
- le64_t head_data_offset;
- uint8_t payload[];
-} _packed_;
-
-struct EntryItem {
- le64_t object_offset;
- le64_t hash;
-} _packed_;
-
-struct EntryObject {
- ObjectHeader object;
- le64_t seqnum;
- le64_t realtime;
- le64_t monotonic;
- sd_id128_t boot_id;
- le64_t xor_hash;
- EntryItem items[];
-} _packed_;
-
-struct HashItem {
- le64_t head_hash_offset;
- le64_t tail_hash_offset;
-} _packed_;
-
-struct HashTableObject {
- ObjectHeader object;
- HashItem items[];
-} _packed_;
-
-struct EntryArrayObject {
- ObjectHeader object;
- le64_t next_entry_array_offset;
- le64_t items[];
-} _packed_;
-
-#define TAG_LENGTH (256/8)
-
-struct TagObject {
- ObjectHeader object;
- le64_t seqnum;
- le64_t epoch;
- uint8_t tag[TAG_LENGTH]; /* SHA-256 HMAC */
-} _packed_;
-
-union Object {
- ObjectHeader object;
- DataObject data;
- FieldObject field;
- EntryObject entry;
- HashTableObject hash_table;
- EntryArrayObject entry_array;
- TagObject tag;
-};
-
-enum {
- STATE_OFFLINE = 0,
- STATE_ONLINE = 1,
- STATE_ARCHIVED = 2,
- _STATE_MAX
-};
-
-/* Header flags */
-enum {
- HEADER_INCOMPATIBLE_COMPRESSED_XZ = 1 << 0,
- HEADER_INCOMPATIBLE_COMPRESSED_LZ4 = 1 << 1,
-};
-
-#define HEADER_INCOMPATIBLE_ANY (HEADER_INCOMPATIBLE_COMPRESSED_XZ|HEADER_INCOMPATIBLE_COMPRESSED_LZ4)
-
-#if defined(HAVE_XZ) && defined(HAVE_LZ4)
-# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_ANY
-#elif defined(HAVE_XZ)
-# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_COMPRESSED_XZ
-#elif defined(HAVE_LZ4)
-# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_COMPRESSED_LZ4
-#else
-# define HEADER_INCOMPATIBLE_SUPPORTED 0
-#endif
-
-enum {
- HEADER_COMPATIBLE_SEALED = 1
-};
-
-#define HEADER_COMPATIBLE_ANY HEADER_COMPATIBLE_SEALED
-#ifdef HAVE_GCRYPT
-# define HEADER_COMPATIBLE_SUPPORTED HEADER_COMPATIBLE_SEALED
-#else
-# define HEADER_COMPATIBLE_SUPPORTED 0
-#endif
-
-#define HEADER_SIGNATURE ((char[]) { 'L', 'P', 'K', 'S', 'H', 'H', 'R', 'H' })
-
-struct Header {
- uint8_t signature[8]; /* "LPKSHHRH" */
- le32_t compatible_flags;
- le32_t incompatible_flags;
- uint8_t state;
- uint8_t reserved[7];
- sd_id128_t file_id;
- sd_id128_t machine_id;
- sd_id128_t boot_id; /* last writer */
- sd_id128_t seqnum_id;
- le64_t header_size;
- le64_t arena_size;
- le64_t data_hash_table_offset;
- le64_t data_hash_table_size;
- le64_t field_hash_table_offset;
- le64_t field_hash_table_size;
- le64_t tail_object_offset;
- le64_t n_objects;
- le64_t n_entries;
- le64_t tail_entry_seqnum;
- le64_t head_entry_seqnum;
- le64_t entry_array_offset;
- le64_t head_entry_realtime;
- le64_t tail_entry_realtime;
- le64_t tail_entry_monotonic;
- /* Added in 187 */
- le64_t n_data;
- le64_t n_fields;
- /* Added in 189 */
- le64_t n_tags;
- le64_t n_entry_arrays;
-
- /* Size: 240 */
-} _packed_;
-
-#define FSS_HEADER_SIGNATURE ((char[]) { 'K', 'S', 'H', 'H', 'R', 'H', 'L', 'P' })
-
-struct FSSHeader {
- uint8_t signature[8]; /* "KSHHRHLP" */
- le32_t compatible_flags;
- le32_t incompatible_flags;
- sd_id128_t machine_id;
- sd_id128_t boot_id; /* last writer */
- le64_t header_size;
- le64_t start_usec;
- le64_t interval_usec;
- le16_t fsprg_secpar;
- le16_t reserved[3];
- le64_t fsprg_state_size;
-} _packed_;
diff --git a/src/journal/journal-file.c b/src/journal/journal-file.c
deleted file mode 100644
index 912eb94d0a..0000000000
--- a/src/journal/journal-file.c
+++ /dev/null
@@ -1,3324 +0,0 @@
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/fs.h>
-#include <stddef.h>
-#include <sys/mman.h>
-#include <sys/statvfs.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include "alloc-util.h"
-#include "btrfs-util.h"
-#include "chattr-util.h"
-#include "compress.h"
-#include "fd-util.h"
-#include "journal-authenticate.h"
-#include "journal-def.h"
-#include "journal-file.h"
-#include "lookup3.h"
-#include "parse-util.h"
-#include "random-util.h"
-#include "sd-event.h"
-#include "string-util.h"
-#include "xattr-util.h"
-
-#define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
-#define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
-
-#define COMPRESSION_SIZE_THRESHOLD (512ULL)
-
-/* This is the minimum journal file size */
-#define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */
-
-/* These are the lower and upper bounds if we deduce the max_use value
- * from the file system size */
-#define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */
-#define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
-
-/* This is the default minimal use limit, how much we'll use even if keep_free suggests otherwise. */
-#define DEFAULT_MIN_USE (1ULL*1024ULL*1024ULL) /* 1 MiB */
-
-/* This is the upper bound if we deduce max_size from max_use */
-#define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */
-
-/* This is the upper bound if we deduce the keep_free value from the
- * file system size */
-#define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */
-
-/* This is the keep_free value when we can't determine the system
- * size */
-#define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */
-
-/* This is the default maximum number of journal files to keep around. */
-#define DEFAULT_N_MAX_FILES (100)
-
-/* n_data was the first entry we added after the initial file format design */
-#define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
-
-/* How many entries to keep in the entry array chain cache at max */
-#define CHAIN_CACHE_MAX 20
-
-/* How much to increase the journal file size at once each time we allocate something new. */
-#define FILE_SIZE_INCREASE (8ULL*1024ULL*1024ULL) /* 8MB */
-
-/* Reread fstat() of the file for detecting deletions at least this often */
-#define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
-
-/* The mmap context to use for the header we pick as one above the last defined typed */
-#define CONTEXT_HEADER _OBJECT_TYPE_MAX
-
-static int journal_file_set_online(JournalFile *f) {
- assert(f);
-
- if (!f->writable)
- return -EPERM;
-
- if (!(f->fd >= 0 && f->header))
- return -EINVAL;
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd))
- return -EIO;
-
- switch (f->header->state) {
- case STATE_ONLINE:
- return 0;
-
- case STATE_OFFLINE:
- f->header->state = STATE_ONLINE;
- fsync(f->fd);
- return 0;
-
- default:
- return -EINVAL;
- }
-}
-
-int journal_file_set_offline(JournalFile *f) {
- assert(f);
-
- if (!f->writable)
- return -EPERM;
-
- if (!(f->fd >= 0 && f->header))
- return -EINVAL;
-
- if (f->header->state != STATE_ONLINE)
- return 0;
-
- fsync(f->fd);
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd))
- return -EIO;
-
- f->header->state = STATE_OFFLINE;
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd))
- return -EIO;
-
- fsync(f->fd);
-
- return 0;
-}
-
-JournalFile* journal_file_close(JournalFile *f) {
- assert(f);
-
-#ifdef HAVE_GCRYPT
- /* Write the final tag */
- if (f->seal && f->writable)
- journal_file_append_tag(f);
-#endif
-
- if (f->post_change_timer) {
- int enabled;
-
- if (sd_event_source_get_enabled(f->post_change_timer, &enabled) >= 0)
- if (enabled == SD_EVENT_ONESHOT)
- journal_file_post_change(f);
-
- (void) sd_event_source_set_enabled(f->post_change_timer, SD_EVENT_OFF);
- sd_event_source_unref(f->post_change_timer);
- }
-
- journal_file_set_offline(f);
-
- if (f->mmap && f->fd >= 0)
- mmap_cache_close_fd(f->mmap, f->fd);
-
- if (f->fd >= 0 && f->defrag_on_close) {
-
- /* Be friendly to btrfs: turn COW back on again now,
- * and defragment the file. We won't write to the file
- * ever again, hence remove all fragmentation, and
- * reenable all the good bits COW usually provides
- * (such as data checksumming). */
-
- (void) chattr_fd(f->fd, 0, FS_NOCOW_FL);
- (void) btrfs_defrag_fd(f->fd);
- }
-
- safe_close(f->fd);
- free(f->path);
-
- mmap_cache_unref(f->mmap);
-
- ordered_hashmap_free_free(f->chain_cache);
-
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- free(f->compress_buffer);
-#endif
-
-#ifdef HAVE_GCRYPT
- if (f->fss_file)
- munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size));
- else
- free(f->fsprg_state);
-
- free(f->fsprg_seed);
-
- if (f->hmac)
- gcry_md_close(f->hmac);
-#endif
-
- free(f);
- return NULL;
-}
-
-static int journal_file_init_header(JournalFile *f, JournalFile *template) {
- Header h = {};
- ssize_t k;
- int r;
-
- assert(f);
-
- memcpy(h.signature, HEADER_SIGNATURE, 8);
- h.header_size = htole64(ALIGN64(sizeof(h)));
-
- h.incompatible_flags |= htole32(
- f->compress_xz * HEADER_INCOMPATIBLE_COMPRESSED_XZ |
- f->compress_lz4 * HEADER_INCOMPATIBLE_COMPRESSED_LZ4);
-
- h.compatible_flags = htole32(
- f->seal * HEADER_COMPATIBLE_SEALED);
-
- r = sd_id128_randomize(&h.file_id);
- if (r < 0)
- return r;
-
- if (template) {
- h.seqnum_id = template->header->seqnum_id;
- h.tail_entry_seqnum = template->header->tail_entry_seqnum;
- } else
- h.seqnum_id = h.file_id;
-
- 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) {
- sd_id128_t boot_id;
- int r;
-
- assert(f);
- assert(f->header);
-
- r = sd_id128_get_machine(&f->header->machine_id);
- if (r < 0)
- return r;
-
- r = sd_id128_get_boot(&boot_id);
- if (r < 0)
- return r;
-
- if (sd_id128_equal(boot_id, f->header->boot_id))
- f->tail_entry_monotonic_valid = true;
-
- f->header->boot_id = boot_id;
-
- r = journal_file_set_online(f);
-
- /* Sync the online state to disk */
- fsync(f->fd);
-
- return r;
-}
-
-static int journal_file_verify_header(JournalFile *f) {
- uint32_t flags;
-
- assert(f);
- assert(f->header);
-
- if (memcmp(f->header->signature, HEADER_SIGNATURE, 8))
- return -EBADMSG;
-
- /* In both read and write mode we refuse to open files with
- * incompatible flags we don't know */
- flags = le32toh(f->header->incompatible_flags);
- if (flags & ~HEADER_INCOMPATIBLE_SUPPORTED) {
- if (flags & ~HEADER_INCOMPATIBLE_ANY)
- log_debug("Journal file %s has unknown incompatible flags %"PRIx32,
- f->path, flags & ~HEADER_INCOMPATIBLE_ANY);
- flags = (flags & HEADER_INCOMPATIBLE_ANY) & ~HEADER_INCOMPATIBLE_SUPPORTED;
- if (flags)
- log_debug("Journal file %s uses incompatible flags %"PRIx32
- " disabled at compilation time.", f->path, flags);
- return -EPROTONOSUPPORT;
- }
-
- /* When open for writing we refuse to open files with
- * compatible flags, too */
- flags = le32toh(f->header->compatible_flags);
- if (f->writable && (flags & ~HEADER_COMPATIBLE_SUPPORTED)) {
- if (flags & ~HEADER_COMPATIBLE_ANY)
- log_debug("Journal file %s has unknown compatible flags %"PRIx32,
- f->path, flags & ~HEADER_COMPATIBLE_ANY);
- flags = (flags & HEADER_COMPATIBLE_ANY) & ~HEADER_COMPATIBLE_SUPPORTED;
- if (flags)
- log_debug("Journal file %s uses compatible flags %"PRIx32
- " disabled at compilation time.", f->path, flags);
- return -EPROTONOSUPPORT;
- }
-
- if (f->header->state >= _STATE_MAX)
- return -EBADMSG;
-
- /* The first addition was n_data, so check that we are at least this large */
- if (le64toh(f->header->header_size) < HEADER_SIZE_MIN)
- return -EBADMSG;
-
- if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
- return -EBADMSG;
-
- if ((le64toh(f->header->header_size) + le64toh(f->header->arena_size)) > (uint64_t) f->last_stat.st_size)
- return -ENODATA;
-
- if (le64toh(f->header->tail_object_offset) > (le64toh(f->header->header_size) + le64toh(f->header->arena_size)))
- return -ENODATA;
-
- if (!VALID64(le64toh(f->header->data_hash_table_offset)) ||
- !VALID64(le64toh(f->header->field_hash_table_offset)) ||
- !VALID64(le64toh(f->header->tail_object_offset)) ||
- !VALID64(le64toh(f->header->entry_array_offset)))
- return -ENODATA;
-
- if (f->writable) {
- uint8_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 = f->header->state;
-
- if (state == STATE_ONLINE) {
- log_debug("Journal file %s is already online. Assuming unclean closing.", f->path);
- return -EBUSY;
- } else if (state == STATE_ARCHIVED)
- return -ESHUTDOWN;
- else if (state != STATE_OFFLINE) {
- log_debug("Journal file %s has unknown state %i.", f->path, state);
- return -EBUSY;
- }
- }
-
- f->compress_xz = JOURNAL_HEADER_COMPRESSED_XZ(f->header);
- f->compress_lz4 = JOURNAL_HEADER_COMPRESSED_LZ4(f->header);
-
- f->seal = JOURNAL_HEADER_SEALED(f->header);
-
- return 0;
-}
-
-static int journal_file_fstat(JournalFile *f) {
- assert(f);
- assert(f->fd >= 0);
-
- if (fstat(f->fd, &f->last_stat) < 0)
- return -errno;
-
- f->last_stat_usec = now(CLOCK_MONOTONIC);
-
- /* Refuse appending to files that are already deleted */
- if (f->last_stat.st_nlink <= 0)
- return -EIDRM;
-
- return 0;
-}
-
-static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
- uint64_t old_size, new_size;
- int r;
-
- assert(f);
- assert(f->header);
-
- /* We assume that this file is not sparse, and we know that
- * for sure, since we always call posix_fallocate()
- * ourselves */
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd))
- return -EIO;
-
- old_size =
- le64toh(f->header->header_size) +
- le64toh(f->header->arena_size);
-
- new_size = PAGE_ALIGN(offset + size);
- if (new_size < le64toh(f->header->header_size))
- new_size = le64toh(f->header->header_size);
-
- if (new_size <= old_size) {
-
- /* We already pre-allocated enough space, but before
- * we write to it, let's check with fstat() if the
- * file got deleted, in order make sure we don't throw
- * away the data immediately. Don't check fstat() for
- * all writes though, but only once ever 10s. */
-
- if (f->last_stat_usec + LAST_STAT_REFRESH_USEC > now(CLOCK_MONOTONIC))
- return 0;
-
- return journal_file_fstat(f);
- }
-
- /* Allocate more space. */
-
- if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
- return -E2BIG;
-
- if (new_size > f->metrics.min_size && f->metrics.keep_free > 0) {
- struct statvfs svfs;
-
- if (fstatvfs(f->fd, &svfs) >= 0) {
- uint64_t available;
-
- available = LESS_BY((uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize, f->metrics.keep_free);
-
- if (new_size - old_size > available)
- return -E2BIG;
- }
- }
-
- /* Increase by larger blocks at once */
- new_size = ((new_size+FILE_SIZE_INCREASE-1) / FILE_SIZE_INCREASE) * FILE_SIZE_INCREASE;
- if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
- new_size = f->metrics.max_size;
-
- /* Note that the glibc fallocate() fallback is very
- inefficient, hence we try to minimize the allocation area
- as we can. */
- r = posix_fallocate(f->fd, old_size, new_size - old_size);
- if (r != 0)
- return -r;
-
- f->header->arena_size = htole64(new_size - le64toh(f->header->header_size));
-
- return journal_file_fstat(f);
-}
-
-static unsigned type_to_context(ObjectType type) {
- /* One context for each type, plus one catch-all for the rest */
- assert_cc(_OBJECT_TYPE_MAX <= MMAP_CACHE_MAX_CONTEXTS);
- assert_cc(CONTEXT_HEADER < MMAP_CACHE_MAX_CONTEXTS);
- return type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX ? type : 0;
-}
-
-static int journal_file_move_to(JournalFile *f, ObjectType type, bool keep_always, uint64_t offset, uint64_t size, void **ret) {
- int r;
-
- assert(f);
- assert(ret);
-
- if (size <= 0)
- return -EINVAL;
-
- /* Avoid SIGBUS on invalid accesses */
- if (offset + size > (uint64_t) f->last_stat.st_size) {
- /* Hmm, out of range? Let's refresh the fstat() data
- * first, before we trust that check. */
-
- r = journal_file_fstat(f);
- if (r < 0)
- return r;
-
- if (offset + size > (uint64_t) f->last_stat.st_size)
- return -EADDRNOTAVAIL;
- }
-
- return mmap_cache_get(f->mmap, f->fd, f->prot, type_to_context(type), keep_always, offset, size, &f->last_stat, ret);
-}
-
-static uint64_t minimum_header_size(Object *o) {
-
- static const uint64_t table[] = {
- [OBJECT_DATA] = sizeof(DataObject),
- [OBJECT_FIELD] = sizeof(FieldObject),
- [OBJECT_ENTRY] = sizeof(EntryObject),
- [OBJECT_DATA_HASH_TABLE] = sizeof(HashTableObject),
- [OBJECT_FIELD_HASH_TABLE] = sizeof(HashTableObject),
- [OBJECT_ENTRY_ARRAY] = sizeof(EntryArrayObject),
- [OBJECT_TAG] = sizeof(TagObject),
- };
-
- if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0)
- return sizeof(ObjectHeader);
-
- return table[o->object.type];
-}
-
-int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret) {
- int r;
- void *t;
- Object *o;
- uint64_t s;
-
- assert(f);
- assert(ret);
-
- /* Objects may only be located at multiple of 64 bit */
- if (!VALID64(offset))
- return -EFAULT;
-
- r = journal_file_move_to(f, type, false, offset, sizeof(ObjectHeader), &t);
- if (r < 0)
- return r;
-
- o = (Object*) t;
- s = le64toh(o->object.size);
-
- if (s < sizeof(ObjectHeader))
- return -EBADMSG;
-
- if (o->object.type <= OBJECT_UNUSED)
- return -EBADMSG;
-
- if (s < minimum_header_size(o))
- return -EBADMSG;
-
- if (type > OBJECT_UNUSED && o->object.type != type)
- return -EBADMSG;
-
- if (s > sizeof(ObjectHeader)) {
- r = journal_file_move_to(f, type, false, offset, s, &t);
- if (r < 0)
- return r;
-
- o = (Object*) t;
- }
-
- *ret = o;
- return 0;
-}
-
-static uint64_t journal_file_entry_seqnum(JournalFile *f, uint64_t *seqnum) {
- uint64_t r;
-
- assert(f);
- assert(f->header);
-
- r = le64toh(f->header->tail_entry_seqnum) + 1;
-
- if (seqnum) {
- /* If an external seqnum counter was passed, we update
- * both the local and the external one, and set it to
- * the maximum of both */
-
- if (*seqnum + 1 > r)
- r = *seqnum + 1;
-
- *seqnum = r;
- }
-
- f->header->tail_entry_seqnum = htole64(r);
-
- if (f->header->head_entry_seqnum == 0)
- f->header->head_entry_seqnum = htole64(r);
-
- return r;
-}
-
-int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset) {
- int r;
- uint64_t p;
- Object *tail, *o;
- void *t;
-
- assert(f);
- assert(f->header);
- assert(type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX);
- assert(size >= sizeof(ObjectHeader));
- assert(offset);
- assert(ret);
-
- r = journal_file_set_online(f);
- if (r < 0)
- return r;
-
- p = le64toh(f->header->tail_object_offset);
- if (p == 0)
- p = le64toh(f->header->header_size);
- else {
- r = journal_file_move_to_object(f, OBJECT_UNUSED, 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, type, false, p, size, &t);
- if (r < 0)
- return r;
-
- o = (Object*) t;
-
- zero(o->object);
- o->object.type = type;
- o->object.size = htole64(size);
-
- f->header->tail_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_data_hash_table(JournalFile *f) {
- uint64_t s, p;
- Object *o;
- int r;
-
- assert(f);
- assert(f->header);
-
- /* We estimate that we need 1 hash table entry per 768 bytes
- of journal file and we want to make sure we never get
- beyond 75% fill level. Calculate the hash table size for
- the maximum file size based on these metrics. */
-
- s = (f->metrics.max_size * 4 / 768 / 3) * sizeof(HashItem);
- if (s < DEFAULT_DATA_HASH_TABLE_SIZE)
- s = DEFAULT_DATA_HASH_TABLE_SIZE;
-
- log_debug("Reserving %"PRIu64" entries in hash table.", s / sizeof(HashItem));
-
- r = journal_file_append_object(f,
- OBJECT_DATA_HASH_TABLE,
- offsetof(Object, hash_table.items) + s,
- &o, &p);
- if (r < 0)
- return r;
-
- memzero(o->hash_table.items, s);
-
- f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
- f->header->data_hash_table_size = htole64(s);
-
- return 0;
-}
-
-static int journal_file_setup_field_hash_table(JournalFile *f) {
- uint64_t s, p;
- Object *o;
- int r;
-
- assert(f);
- assert(f->header);
-
- /* We use a fixed size hash table for the fields as this
- * number should grow very slowly only */
-
- s = DEFAULT_FIELD_HASH_TABLE_SIZE;
- r = journal_file_append_object(f,
- OBJECT_FIELD_HASH_TABLE,
- offsetof(Object, hash_table.items) + s,
- &o, &p);
- if (r < 0)
- return r;
-
- memzero(o->hash_table.items, s);
-
- f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
- f->header->field_hash_table_size = htole64(s);
-
- return 0;
-}
-
-int journal_file_map_data_hash_table(JournalFile *f) {
- uint64_t s, p;
- void *t;
- int r;
-
- assert(f);
- assert(f->header);
-
- if (f->data_hash_table)
- return 0;
-
- p = le64toh(f->header->data_hash_table_offset);
- s = le64toh(f->header->data_hash_table_size);
-
- r = journal_file_move_to(f,
- OBJECT_DATA_HASH_TABLE,
- true,
- p, s,
- &t);
- if (r < 0)
- return r;
-
- f->data_hash_table = t;
- return 0;
-}
-
-int journal_file_map_field_hash_table(JournalFile *f) {
- uint64_t s, p;
- void *t;
- int r;
-
- assert(f);
- assert(f->header);
-
- if (f->field_hash_table)
- return 0;
-
- p = le64toh(f->header->field_hash_table_offset);
- s = le64toh(f->header->field_hash_table_size);
-
- r = journal_file_move_to(f,
- OBJECT_FIELD_HASH_TABLE,
- true,
- p, s,
- &t);
- if (r < 0)
- return r;
-
- f->field_hash_table = t;
- return 0;
-}
-
-static int journal_file_link_field(
- JournalFile *f,
- Object *o,
- uint64_t offset,
- uint64_t hash) {
-
- uint64_t p, h, m;
- int r;
-
- assert(f);
- assert(f->header);
- assert(f->field_hash_table);
- assert(o);
- assert(offset > 0);
-
- if (o->object.type != OBJECT_FIELD)
- return -EINVAL;
-
- m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
- if (m <= 0)
- return -EBADMSG;
-
- /* This might alter the window we are looking at */
- o->field.next_hash_offset = o->field.head_data_offset = 0;
-
- h = hash % m;
- p = le64toh(f->field_hash_table[h].tail_hash_offset);
- if (p == 0)
- f->field_hash_table[h].head_hash_offset = htole64(offset);
- else {
- r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
- if (r < 0)
- return r;
-
- o->field.next_hash_offset = htole64(offset);
- }
-
- f->field_hash_table[h].tail_hash_offset = htole64(offset);
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
- f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1);
-
- return 0;
-}
-
-static int journal_file_link_data(
- JournalFile *f,
- Object *o,
- uint64_t offset,
- uint64_t hash) {
-
- uint64_t p, h, m;
- int r;
-
- assert(f);
- assert(f->header);
- assert(f->data_hash_table);
- assert(o);
- assert(offset > 0);
-
- if (o->object.type != OBJECT_DATA)
- return -EINVAL;
-
- m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
- if (m <= 0)
- return -EBADMSG;
-
- /* This might alter the window we are looking at */
- o->data.next_hash_offset = o->data.next_field_offset = 0;
- o->data.entry_offset = o->data.entry_array_offset = 0;
- o->data.n_entries = 0;
-
- h = hash % m;
- p = le64toh(f->data_hash_table[h].tail_hash_offset);
- if (p == 0)
- /* Only entry in the hash table is easy */
- f->data_hash_table[h].head_hash_offset = htole64(offset);
- else {
- /* Move back to the previous data object, to patch in
- * pointer */
-
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- o->data.next_hash_offset = htole64(offset);
- }
-
- f->data_hash_table[h].tail_hash_offset = htole64(offset);
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
- f->header->n_data = htole64(le64toh(f->header->n_data) + 1);
-
- return 0;
-}
-
-int journal_file_find_field_object_with_hash(
- JournalFile *f,
- const void *field, uint64_t size, uint64_t hash,
- Object **ret, uint64_t *offset) {
-
- uint64_t p, osize, h, m;
- int r;
-
- assert(f);
- assert(f->header);
- assert(field && size > 0);
-
- /* If the field hash table is empty, we can't find anything */
- if (le64toh(f->header->field_hash_table_size) <= 0)
- return 0;
-
- /* Map the field hash table, if it isn't mapped yet. */
- r = journal_file_map_field_hash_table(f);
- if (r < 0)
- return r;
-
- osize = offsetof(Object, field.payload) + size;
-
- m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
- if (m <= 0)
- return -EBADMSG;
-
- h = hash % m;
- p = le64toh(f->field_hash_table[h].head_hash_offset);
-
- while (p > 0) {
- Object *o;
-
- r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
- if (r < 0)
- return r;
-
- if (le64toh(o->field.hash) == hash &&
- le64toh(o->object.size) == osize &&
- memcmp(o->field.payload, field, size) == 0) {
-
- if (ret)
- *ret = o;
- if (offset)
- *offset = p;
-
- return 1;
- }
-
- p = le64toh(o->field.next_hash_offset);
- }
-
- return 0;
-}
-
-int journal_file_find_field_object(
- JournalFile *f,
- const void *field, uint64_t size,
- Object **ret, uint64_t *offset) {
-
- uint64_t hash;
-
- assert(f);
- assert(field && size > 0);
-
- hash = hash64(field, size);
-
- return journal_file_find_field_object_with_hash(f,
- field, size, hash,
- ret, offset);
-}
-
-int journal_file_find_data_object_with_hash(
- JournalFile *f,
- const void *data, uint64_t size, uint64_t hash,
- Object **ret, uint64_t *offset) {
-
- uint64_t p, osize, h, m;
- int r;
-
- assert(f);
- assert(f->header);
- assert(data || size == 0);
-
- /* If there's no data hash table, then there's no entry. */
- if (le64toh(f->header->data_hash_table_size) <= 0)
- return 0;
-
- /* Map the data hash table, if it isn't mapped yet. */
- r = journal_file_map_data_hash_table(f);
- if (r < 0)
- return r;
-
- osize = offsetof(Object, data.payload) + size;
-
- m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
- if (m <= 0)
- return -EBADMSG;
-
- h = hash % m;
- p = le64toh(f->data_hash_table[h].head_hash_offset);
-
- while (p > 0) {
- Object *o;
-
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- if (le64toh(o->data.hash) != hash)
- goto next;
-
- if (o->object.flags & OBJECT_COMPRESSION_MASK) {
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- uint64_t l;
- size_t rsize = 0;
-
- l = le64toh(o->object.size);
- if (l <= offsetof(Object, data.payload))
- return -EBADMSG;
-
- l -= offsetof(Object, data.payload);
-
- r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
- o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0);
- if (r < 0)
- return r;
-
- if (rsize == size &&
- memcmp(f->compress_buffer, data, size) == 0) {
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 1;
- }
-#else
- return -EPROTONOSUPPORT;
-#endif
- } else if (le64toh(o->object.size) == osize &&
- memcmp(o->data.payload, data, size) == 0) {
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 1;
- }
-
- next:
- p = le64toh(o->data.next_hash_offset);
- }
-
- return 0;
-}
-
-int journal_file_find_data_object(
- JournalFile *f,
- const void *data, uint64_t size,
- Object **ret, uint64_t *offset) {
-
- uint64_t hash;
-
- assert(f);
- assert(data || size == 0);
-
- hash = hash64(data, size);
-
- return journal_file_find_data_object_with_hash(f,
- data, size, hash,
- ret, offset);
-}
-
-static int journal_file_append_field(
- JournalFile *f,
- const void *field, uint64_t size,
- Object **ret, uint64_t *offset) {
-
- uint64_t hash, p;
- uint64_t osize;
- Object *o;
- int r;
-
- assert(f);
- assert(field && size > 0);
-
- hash = hash64(field, size);
-
- r = journal_file_find_field_object_with_hash(f, field, size, hash, &o, &p);
- if (r < 0)
- return r;
- else if (r > 0) {
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 0;
- }
-
- osize = offsetof(Object, field.payload) + size;
- r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
- if (r < 0)
- return r;
-
- o->field.hash = htole64(hash);
- memcpy(o->field.payload, field, size);
-
- r = journal_file_link_field(f, o, p, hash);
- if (r < 0)
- return r;
-
- /* The linking might have altered the window, so let's
- * refresh our pointer */
- r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
- if (r < 0)
- return r;
-
-#ifdef HAVE_GCRYPT
- r = journal_file_hmac_put_object(f, OBJECT_FIELD, o, p);
- if (r < 0)
- return r;
-#endif
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 0;
-}
-
-static int journal_file_append_data(
- JournalFile *f,
- const void *data, uint64_t size,
- Object **ret, uint64_t *offset) {
-
- uint64_t hash, p;
- uint64_t osize;
- Object *o;
- int r, compression = 0;
- const void *eq;
-
- assert(f);
- assert(data || size == 0);
-
- hash = hash64(data, size);
-
- r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p);
- if (r < 0)
- return r;
- if (r > 0) {
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 0;
- }
-
- osize = offsetof(Object, data.payload) + size;
- r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
- if (r < 0)
- return r;
-
- o->data.hash = htole64(hash);
-
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- if (JOURNAL_FILE_COMPRESS(f) && size >= COMPRESSION_SIZE_THRESHOLD) {
- size_t rsize = 0;
-
- compression = compress_blob(data, size, o->data.payload, size - 1, &rsize);
-
- if (compression >= 0) {
- o->object.size = htole64(offsetof(Object, data.payload) + rsize);
- o->object.flags |= compression;
-
- log_debug("Compressed data object %"PRIu64" -> %zu using %s",
- size, rsize, object_compressed_to_string(compression));
- } else
- /* Compression didn't work, we don't really care why, let's continue without compression */
- compression = 0;
- }
-#endif
-
- if (compression == 0 && size > 0)
- memcpy(o->data.payload, data, size);
-
- r = journal_file_link_data(f, o, p, hash);
- if (r < 0)
- return r;
-
- /* The linking might have altered the window, so let's
- * refresh our pointer */
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- if (!data)
- eq = NULL;
- else
- eq = memchr(data, '=', size);
- if (eq && eq > data) {
- Object *fo = NULL;
- uint64_t fp;
-
- /* Create field object ... */
- r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, &fp);
- if (r < 0)
- return r;
-
- /* ... and link it in. */
- o->data.next_field_offset = fo->field.head_data_offset;
- fo->field.head_data_offset = le64toh(p);
- }
-
-#ifdef HAVE_GCRYPT
- r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p);
- if (r < 0)
- return r;
-#endif
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 0;
-}
-
-uint64_t journal_file_entry_n_items(Object *o) {
- assert(o);
-
- if (o->object.type != OBJECT_ENTRY)
- return 0;
-
- return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem);
-}
-
-uint64_t journal_file_entry_array_n_items(Object *o) {
- assert(o);
-
- if (o->object.type != OBJECT_ENTRY_ARRAY)
- return 0;
-
- return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t);
-}
-
-uint64_t journal_file_hash_table_n_items(Object *o) {
- assert(o);
-
- if (o->object.type != OBJECT_DATA_HASH_TABLE &&
- o->object.type != OBJECT_FIELD_HASH_TABLE)
- return 0;
-
- return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem);
-}
-
-static int link_entry_into_array(JournalFile *f,
- le64_t *first,
- le64_t *idx,
- uint64_t p) {
- int r;
- uint64_t n = 0, ap = 0, q, i, a, hidx;
- Object *o;
-
- assert(f);
- assert(f->header);
- assert(first);
- assert(idx);
- assert(p > 0);
-
- a = le64toh(*first);
- i = hidx = le64toh(*idx);
- while (a > 0) {
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
-
- n = journal_file_entry_array_n_items(o);
- if (i < n) {
- o->entry_array.items[i] = htole64(p);
- *idx = htole64(hidx + 1);
- return 0;
- }
-
- i -= n;
- ap = a;
- a = le64toh(o->entry_array.next_entry_array_offset);
- }
-
- if (hidx > n)
- n = (hidx+1) * 2;
- else
- n = n * 2;
-
- if (n < 4)
- n = 4;
-
- r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
- offsetof(Object, entry_array.items) + n * sizeof(uint64_t),
- &o, &q);
- if (r < 0)
- return r;
-
-#ifdef HAVE_GCRYPT
- r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
- if (r < 0)
- return r;
-#endif
-
- o->entry_array.items[i] = htole64(p);
-
- if (ap == 0)
- *first = htole64(q);
- else {
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
- if (r < 0)
- return r;
-
- o->entry_array.next_entry_array_offset = htole64(q);
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
- f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
-
- *idx = htole64(hidx + 1);
-
- return 0;
-}
-
-static int link_entry_into_array_plus_one(JournalFile *f,
- le64_t *extra,
- le64_t *first,
- le64_t *idx,
- uint64_t p) {
-
- int r;
-
- assert(f);
- assert(extra);
- assert(first);
- assert(idx);
- assert(p > 0);
-
- if (*idx == 0)
- *extra = htole64(p);
- else {
- le64_t i;
-
- i = htole64(le64toh(*idx) - 1);
- r = link_entry_into_array(f, first, &i, p);
- if (r < 0)
- return r;
- }
-
- *idx = htole64(le64toh(*idx) + 1);
- return 0;
-}
-
-static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) {
- uint64_t p;
- int r;
- assert(f);
- assert(o);
- assert(offset > 0);
-
- p = le64toh(o->entry.items[i].object_offset);
- if (p == 0)
- return -EINVAL;
-
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- return link_entry_into_array_plus_one(f,
- &o->data.entry_offset,
- &o->data.entry_array_offset,
- &o->data.n_entries,
- offset);
-}
-
-static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) {
- uint64_t n, i;
- int r;
-
- assert(f);
- assert(f->header);
- assert(o);
- assert(offset > 0);
-
- if (o->object.type != OBJECT_ENTRY)
- return -EINVAL;
-
- __sync_synchronize();
-
- /* Link up the entry itself */
- r = link_entry_into_array(f,
- &f->header->entry_array_offset,
- &f->header->n_entries,
- offset);
- if (r < 0)
- return r;
-
- /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
-
- if (f->header->head_entry_realtime == 0)
- f->header->head_entry_realtime = o->entry.realtime;
-
- f->header->tail_entry_realtime = o->entry.realtime;
- f->header->tail_entry_monotonic = o->entry.monotonic;
-
- f->tail_entry_monotonic_valid = true;
-
- /* 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;
- }
-
- return 0;
-}
-
-static int journal_file_append_entry_internal(
- JournalFile *f,
- const dual_timestamp *ts,
- uint64_t xor_hash,
- const EntryItem items[], unsigned n_items,
- uint64_t *seqnum,
- Object **ret, uint64_t *offset) {
- uint64_t np;
- uint64_t osize;
- Object *o;
- int r;
-
- assert(f);
- assert(f->header);
- assert(items || n_items == 0);
- assert(ts);
-
- osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem));
-
- r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
- if (r < 0)
- return r;
-
- o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum));
- memcpy(o->entry.items, items, n_items * sizeof(EntryItem));
- o->entry.realtime = htole64(ts->realtime);
- o->entry.monotonic = htole64(ts->monotonic);
- o->entry.xor_hash = htole64(xor_hash);
- o->entry.boot_id = f->header->boot_id;
-
-#ifdef HAVE_GCRYPT
- r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
- if (r < 0)
- return r;
-#endif
-
- r = journal_file_link_entry(f, o, np);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = np;
-
- return 0;
-}
-
-void journal_file_post_change(JournalFile *f) {
- assert(f);
-
- /* inotify() does not receive IN_MODIFY events from file
- * accesses done via mmap(). After each access we hence
- * trigger IN_MODIFY by truncating the journal file to its
- * current size which triggers IN_MODIFY. */
-
- __sync_synchronize();
-
- if (ftruncate(f->fd, f->last_stat.st_size) < 0)
- log_debug_errno(errno, "Failed to truncate file to its own size: %m");
-}
-
-static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) {
- assert(userdata);
-
- journal_file_post_change(userdata);
-
- return 1;
-}
-
-static void schedule_post_change(JournalFile *f) {
- sd_event_source *timer;
- int enabled, r;
- uint64_t now;
-
- assert(f);
- assert(f->post_change_timer);
-
- timer = f->post_change_timer;
-
- r = sd_event_source_get_enabled(timer, &enabled);
- if (r < 0) {
- log_debug_errno(r, "Failed to get ftruncate timer state: %m");
- goto fail;
- }
-
- if (enabled == SD_EVENT_ONESHOT)
- return;
-
- r = sd_event_now(sd_event_source_get_event(timer), CLOCK_MONOTONIC, &now);
- if (r < 0) {
- log_debug_errno(r, "Failed to get clock's now for scheduling ftruncate: %m");
- goto fail;
- }
-
- r = sd_event_source_set_time(timer, now+f->post_change_timer_period);
- if (r < 0) {
- log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m");
- goto fail;
- }
-
- r = sd_event_source_set_enabled(timer, SD_EVENT_ONESHOT);
- if (r < 0) {
- log_debug_errno(r, "Failed to enable scheduled ftruncate: %m");
- goto fail;
- }
-
- return;
-
-fail:
- /* On failure, let's simply post the change immediately. */
- journal_file_post_change(f);
-}
-
-/* Enable coalesced change posting in a timer on the provided sd_event instance */
-int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t) {
- _cleanup_(sd_event_source_unrefp) sd_event_source *timer = NULL;
- int r;
-
- assert(f);
- assert_return(!f->post_change_timer, -EINVAL);
- assert(e);
- assert(t);
-
- r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f);
- if (r < 0)
- return r;
-
- r = sd_event_source_set_enabled(timer, SD_EVENT_OFF);
- if (r < 0)
- return r;
-
- f->post_change_timer = timer;
- timer = NULL;
- f->post_change_timer_period = t;
-
- return r;
-}
-
-static int entry_item_cmp(const void *_a, const void *_b) {
- const EntryItem *a = _a, *b = _b;
-
- if (le64toh(a->object_offset) < le64toh(b->object_offset))
- return -1;
- if (le64toh(a->object_offset) > le64toh(b->object_offset))
- return 1;
- return 0;
-}
-
-int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqnum, Object **ret, uint64_t *offset) {
- unsigned i;
- EntryItem *items;
- int r;
- uint64_t xor_hash = 0;
- struct dual_timestamp _ts;
-
- assert(f);
- assert(f->header);
- assert(iovec || n_iovec == 0);
-
- if (!ts) {
- dual_timestamp_get(&_ts);
- ts = &_ts;
- }
-
-#ifdef HAVE_GCRYPT
- r = journal_file_maybe_append_tag(f, ts->realtime);
- if (r < 0)
- return r;
-#endif
-
- /* alloca() can't take 0, hence let's allocate at least one */
- items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec));
-
- for (i = 0; i < n_iovec; i++) {
- uint64_t p;
- Object *o;
-
- r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
- if (r < 0)
- return r;
-
- xor_hash ^= le64toh(o->data.hash);
- items[i].object_offset = htole64(p);
- items[i].hash = o->data.hash;
- }
-
- /* Order by the position on disk, in order to improve seek
- * times for rotating media. */
- qsort_safe(items, n_iovec, sizeof(EntryItem), entry_item_cmp);
-
- r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset);
-
- /* If the memory mapping triggered a SIGBUS then we return an
- * IO error and ignore the error code passed down to us, since
- * it is very likely just an effect of a nullified replacement
- * mapping page */
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd))
- r = -EIO;
-
- if (f->post_change_timer)
- schedule_post_change(f);
- else
- journal_file_post_change(f);
-
- return r;
-}
-
-typedef struct ChainCacheItem {
- uint64_t first; /* the array at the beginning of the chain */
- uint64_t array; /* the cached array */
- uint64_t begin; /* the first item in the cached array */
- uint64_t total; /* the total number of items in all arrays before this one in the chain */
- uint64_t last_index; /* the last index we looked at, to optimize locality when bisecting */
-} ChainCacheItem;
-
-static void chain_cache_put(
- OrderedHashmap *h,
- ChainCacheItem *ci,
- uint64_t first,
- uint64_t array,
- uint64_t begin,
- uint64_t total,
- uint64_t last_index) {
-
- if (!ci) {
- /* If the chain item to cache for this chain is the
- * first one it's not worth caching anything */
- if (array == first)
- return;
-
- if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) {
- ci = ordered_hashmap_steal_first(h);
- assert(ci);
- } else {
- ci = new(ChainCacheItem, 1);
- if (!ci)
- return;
- }
-
- ci->first = first;
-
- if (ordered_hashmap_put(h, &ci->first, ci) < 0) {
- free(ci);
- return;
- }
- } else
- assert(ci->first == first);
-
- ci->array = array;
- ci->begin = begin;
- ci->total = total;
- ci->last_index = last_index;
-}
-
-static int generic_array_get(
- JournalFile *f,
- uint64_t first,
- uint64_t i,
- Object **ret, uint64_t *offset) {
-
- Object *o;
- uint64_t p = 0, a, t = 0;
- int r;
- ChainCacheItem *ci;
-
- assert(f);
-
- a = first;
-
- /* Try the chain cache first */
- ci = ordered_hashmap_get(f->chain_cache, &first);
- if (ci && i > ci->total) {
- a = ci->array;
- i -= ci->total;
- t = ci->total;
- }
-
- while (a > 0) {
- uint64_t k;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
-
- k = journal_file_entry_array_n_items(o);
- if (i < k) {
- p = le64toh(o->entry_array.items[i]);
- goto found;
- }
-
- i -= k;
- t += k;
- a = le64toh(o->entry_array.next_entry_array_offset);
- }
-
- return 0;
-
-found:
- /* Let's cache this item for the next invocation */
- chain_cache_put(f->chain_cache, ci, first, a, le64toh(o->entry_array.items[0]), t, i);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- return 1;
-}
-
-static int generic_array_get_plus_one(
- JournalFile *f,
- uint64_t extra,
- uint64_t first,
- uint64_t i,
- Object **ret, uint64_t *offset) {
-
- Object *o;
-
- assert(f);
-
- if (i == 0) {
- int r;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = extra;
-
- return 1;
- }
-
- return generic_array_get(f, first, i-1, ret, offset);
-}
-
-enum {
- TEST_FOUND,
- TEST_LEFT,
- TEST_RIGHT
-};
-
-static int generic_array_bisect(
- JournalFile *f,
- uint64_t first,
- uint64_t n,
- uint64_t needle,
- int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
- direction_t direction,
- Object **ret,
- uint64_t *offset,
- uint64_t *idx) {
-
- uint64_t a, p, t = 0, i = 0, last_p = 0, last_index = (uint64_t) -1;
- bool subtract_one = false;
- Object *o, *array = NULL;
- int r;
- ChainCacheItem *ci;
-
- assert(f);
- assert(test_object);
-
- /* Start with the first array in the chain */
- a = first;
-
- ci = ordered_hashmap_get(f->chain_cache, &first);
- if (ci && n > ci->total) {
- /* Ah, we have iterated this bisection array chain
- * previously! Let's see if we can skip ahead in the
- * chain, as far as the last time. But we can't jump
- * backwards in the chain, so let's check that
- * first. */
-
- r = test_object(f, ci->begin, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_LEFT) {
- /* OK, what we are looking for is right of the
- * begin of this EntryArray, so let's jump
- * straight to previously cached array in the
- * chain */
-
- a = ci->array;
- n -= ci->total;
- t = ci->total;
- last_index = ci->last_index;
- }
- }
-
- while (a > 0) {
- uint64_t left, right, k, lp;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
- if (r < 0)
- return r;
-
- k = journal_file_entry_array_n_items(array);
- right = MIN(k, n);
- if (right <= 0)
- return 0;
-
- i = right - 1;
- lp = p = le64toh(array->entry_array.items[i]);
- if (p <= 0)
- return -EBADMSG;
-
- r = test_object(f, p, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_FOUND)
- r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
-
- if (r == TEST_RIGHT) {
- left = 0;
- right -= 1;
-
- if (last_index != (uint64_t) -1) {
- assert(last_index <= right);
-
- /* If we cached the last index we
- * looked at, let's try to not to jump
- * too wildly around and see if we can
- * limit the range to look at early to
- * the immediate neighbors of the last
- * index we looked at. */
-
- if (last_index > 0) {
- uint64_t x = last_index - 1;
-
- p = le64toh(array->entry_array.items[x]);
- if (p <= 0)
- return -EBADMSG;
-
- r = test_object(f, p, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_FOUND)
- r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
-
- if (r == TEST_RIGHT)
- right = x;
- else
- left = x + 1;
- }
-
- if (last_index < right) {
- uint64_t y = last_index + 1;
-
- p = le64toh(array->entry_array.items[y]);
- if (p <= 0)
- return -EBADMSG;
-
- r = test_object(f, p, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_FOUND)
- r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
-
- if (r == TEST_RIGHT)
- right = y;
- else
- left = y + 1;
- }
- }
-
- for (;;) {
- if (left == right) {
- if (direction == DIRECTION_UP)
- subtract_one = true;
-
- i = left;
- goto found;
- }
-
- assert(left < right);
- i = (left + right) / 2;
-
- p = le64toh(array->entry_array.items[i]);
- if (p <= 0)
- return -EBADMSG;
-
- r = test_object(f, p, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_FOUND)
- r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
-
- if (r == TEST_RIGHT)
- right = i;
- else
- left = i + 1;
- }
- }
-
- if (k >= n) {
- if (direction == DIRECTION_UP) {
- i = n;
- subtract_one = true;
- goto found;
- }
-
- return 0;
- }
-
- last_p = lp;
-
- n -= k;
- t += k;
- last_index = (uint64_t) -1;
- a = le64toh(array->entry_array.next_entry_array_offset);
- }
-
- return 0;
-
-found:
- if (subtract_one && t == 0 && i == 0)
- return 0;
-
- /* Let's cache this item for the next invocation */
- chain_cache_put(f->chain_cache, ci, first, a, le64toh(array->entry_array.items[0]), t, subtract_one ? (i > 0 ? i-1 : (uint64_t) -1) : i);
-
- if (subtract_one && i == 0)
- p = last_p;
- else if (subtract_one)
- p = le64toh(array->entry_array.items[i-1]);
- else
- p = le64toh(array->entry_array.items[i]);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = p;
-
- if (idx)
- *idx = t + i + (subtract_one ? -1 : 0);
-
- return 1;
-}
-
-static int generic_array_bisect_plus_one(
- JournalFile *f,
- uint64_t extra,
- uint64_t first,
- uint64_t n,
- uint64_t needle,
- int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
- direction_t direction,
- Object **ret,
- uint64_t *offset,
- uint64_t *idx) {
-
- int r;
- bool step_back = false;
- Object *o;
-
- assert(f);
- assert(test_object);
-
- if (n <= 0)
- return 0;
-
- /* This bisects the array in object 'first', but first checks
- * an extra */
- r = test_object(f, extra, needle);
- if (r < 0)
- return r;
-
- if (r == TEST_FOUND)
- r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
-
- /* if we are looking with DIRECTION_UP then we need to first
- see if in the actual array there is a matching entry, and
- return the last one of that. But if there isn't any we need
- to return this one. Hence remember this, and return it
- below. */
- if (r == TEST_LEFT)
- step_back = direction == DIRECTION_UP;
-
- if (r == TEST_RIGHT) {
- if (direction == DIRECTION_DOWN)
- goto found;
- else
- return 0;
- }
-
- r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx);
-
- if (r == 0 && step_back)
- goto found;
-
- if (r > 0 && idx)
- (*idx) ++;
-
- return r;
-
-found:
- r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = o;
-
- if (offset)
- *offset = extra;
-
- if (idx)
- *idx = 0;
-
- return 1;
-}
-
-_pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
- assert(f);
- assert(p > 0);
-
- if (p == needle)
- return TEST_FOUND;
- else if (p < needle)
- return TEST_LEFT;
- else
- return TEST_RIGHT;
-}
-
-static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
- Object *o;
- int r;
-
- assert(f);
- assert(p > 0);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- if (le64toh(o->entry.seqnum) == needle)
- return TEST_FOUND;
- else if (le64toh(o->entry.seqnum) < needle)
- return TEST_LEFT;
- else
- return TEST_RIGHT;
-}
-
-int journal_file_move_to_entry_by_seqnum(
- JournalFile *f,
- uint64_t seqnum,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
- assert(f);
- assert(f->header);
-
- return generic_array_bisect(f,
- le64toh(f->header->entry_array_offset),
- le64toh(f->header->n_entries),
- seqnum,
- test_object_seqnum,
- direction,
- ret, offset, NULL);
-}
-
-static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
- Object *o;
- int r;
-
- assert(f);
- assert(p > 0);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- if (le64toh(o->entry.realtime) == needle)
- return TEST_FOUND;
- else if (le64toh(o->entry.realtime) < needle)
- return TEST_LEFT;
- else
- return TEST_RIGHT;
-}
-
-int journal_file_move_to_entry_by_realtime(
- JournalFile *f,
- uint64_t realtime,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
- assert(f);
- assert(f->header);
-
- return generic_array_bisect(f,
- le64toh(f->header->entry_array_offset),
- le64toh(f->header->n_entries),
- realtime,
- test_object_realtime,
- direction,
- ret, offset, NULL);
-}
-
-static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
- Object *o;
- int r;
-
- assert(f);
- assert(p > 0);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- if (le64toh(o->entry.monotonic) == needle)
- return TEST_FOUND;
- else if (le64toh(o->entry.monotonic) < needle)
- return TEST_LEFT;
- else
- return TEST_RIGHT;
-}
-
-static int find_data_object_by_boot_id(
- JournalFile *f,
- sd_id128_t boot_id,
- Object **o,
- uint64_t *b) {
-
- char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID=";
-
- sd_id128_to_string(boot_id, t + 9);
- return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b);
-}
-
-int journal_file_move_to_entry_by_monotonic(
- JournalFile *f,
- sd_id128_t boot_id,
- uint64_t monotonic,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
-
- Object *o;
- int r;
-
- assert(f);
-
- r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
- if (r < 0)
- return r;
- if (r == 0)
- return -ENOENT;
-
- return generic_array_bisect_plus_one(f,
- le64toh(o->data.entry_offset),
- le64toh(o->data.entry_array_offset),
- le64toh(o->data.n_entries),
- monotonic,
- test_object_monotonic,
- direction,
- ret, offset, NULL);
-}
-
-void journal_file_reset_location(JournalFile *f) {
- f->location_type = LOCATION_HEAD;
- f->current_offset = 0;
- f->current_seqnum = 0;
- f->current_realtime = 0;
- f->current_monotonic = 0;
- zero(f->current_boot_id);
- f->current_xor_hash = 0;
-}
-
-void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset) {
- f->location_type = LOCATION_SEEK;
- f->current_offset = offset;
- f->current_seqnum = le64toh(o->entry.seqnum);
- f->current_realtime = le64toh(o->entry.realtime);
- f->current_monotonic = le64toh(o->entry.monotonic);
- f->current_boot_id = o->entry.boot_id;
- f->current_xor_hash = le64toh(o->entry.xor_hash);
-}
-
-int journal_file_compare_locations(JournalFile *af, JournalFile *bf) {
- assert(af);
- assert(af->header);
- assert(bf);
- assert(bf->header);
- assert(af->location_type == LOCATION_SEEK);
- assert(bf->location_type == LOCATION_SEEK);
-
- /* If contents and timestamps match, these entries are
- * identical, even if the seqnum does not match */
- if (sd_id128_equal(af->current_boot_id, bf->current_boot_id) &&
- af->current_monotonic == bf->current_monotonic &&
- af->current_realtime == bf->current_realtime &&
- af->current_xor_hash == bf->current_xor_hash)
- return 0;
-
- if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
-
- /* If this is from the same seqnum source, compare
- * seqnums */
- if (af->current_seqnum < bf->current_seqnum)
- return -1;
- if (af->current_seqnum > bf->current_seqnum)
- return 1;
-
- /* Wow! This is weird, different data but the same
- * seqnums? Something is borked, but let's make the
- * best of it and compare by time. */
- }
-
- if (sd_id128_equal(af->current_boot_id, bf->current_boot_id)) {
-
- /* If the boot id matches, compare monotonic time */
- if (af->current_monotonic < bf->current_monotonic)
- return -1;
- if (af->current_monotonic > bf->current_monotonic)
- return 1;
- }
-
- /* Otherwise, compare UTC time */
- if (af->current_realtime < bf->current_realtime)
- return -1;
- if (af->current_realtime > bf->current_realtime)
- return 1;
-
- /* Finally, compare by contents */
- if (af->current_xor_hash < bf->current_xor_hash)
- return -1;
- if (af->current_xor_hash > bf->current_xor_hash)
- return 1;
-
- return 0;
-}
-
-int journal_file_next_entry(
- JournalFile *f,
- uint64_t p,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- uint64_t i, n, ofs;
- int r;
-
- assert(f);
- assert(f->header);
-
- n = le64toh(f->header->n_entries);
- if (n <= 0)
- return 0;
-
- if (p == 0)
- i = direction == DIRECTION_DOWN ? 0 : n - 1;
- else {
- r = generic_array_bisect(f,
- le64toh(f->header->entry_array_offset),
- le64toh(f->header->n_entries),
- p,
- test_object_offset,
- DIRECTION_DOWN,
- NULL, NULL,
- &i);
- if (r <= 0)
- return r;
-
- if (direction == DIRECTION_DOWN) {
- if (i >= n - 1)
- return 0;
-
- i++;
- } else {
- if (i <= 0)
- return 0;
-
- i--;
- }
- }
-
- /* And jump to it */
- r = generic_array_get(f,
- le64toh(f->header->entry_array_offset),
- i,
- ret, &ofs);
- if (r <= 0)
- return r;
-
- if (p > 0 &&
- (direction == DIRECTION_DOWN ? ofs <= p : ofs >= p)) {
- log_debug("%s: entry array corrupted at entry %"PRIu64,
- f->path, i);
- return -EBADMSG;
- }
-
- if (offset)
- *offset = ofs;
-
- return 1;
-}
-
-int journal_file_next_entry_for_data(
- JournalFile *f,
- Object *o, uint64_t p,
- uint64_t data_offset,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- uint64_t n, i;
- int r;
- Object *d;
-
- assert(f);
- assert(p > 0 || !o);
-
- r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
- if (r < 0)
- return r;
-
- n = le64toh(d->data.n_entries);
- if (n <= 0)
- return n;
-
- if (!o)
- i = direction == DIRECTION_DOWN ? 0 : n - 1;
- else {
- if (o->object.type != OBJECT_ENTRY)
- return -EINVAL;
-
- r = generic_array_bisect_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- le64toh(d->data.n_entries),
- p,
- test_object_offset,
- DIRECTION_DOWN,
- NULL, NULL,
- &i);
-
- if (r <= 0)
- return r;
-
- if (direction == DIRECTION_DOWN) {
- if (i >= n - 1)
- return 0;
-
- i++;
- } else {
- if (i <= 0)
- return 0;
-
- i--;
- }
-
- }
-
- return generic_array_get_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- i,
- ret, offset);
-}
-
-int journal_file_move_to_entry_by_offset_for_data(
- JournalFile *f,
- uint64_t data_offset,
- uint64_t p,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- int r;
- Object *d;
-
- assert(f);
-
- r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
- if (r < 0)
- return r;
-
- return generic_array_bisect_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- le64toh(d->data.n_entries),
- p,
- test_object_offset,
- direction,
- ret, offset, NULL);
-}
-
-int journal_file_move_to_entry_by_monotonic_for_data(
- JournalFile *f,
- uint64_t data_offset,
- sd_id128_t boot_id,
- uint64_t monotonic,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- Object *o, *d;
- int r;
- uint64_t b, z;
-
- assert(f);
-
- /* First, seek by time */
- r = find_data_object_by_boot_id(f, boot_id, &o, &b);
- if (r < 0)
- return r;
- if (r == 0)
- return -ENOENT;
-
- r = generic_array_bisect_plus_one(f,
- le64toh(o->data.entry_offset),
- le64toh(o->data.entry_array_offset),
- le64toh(o->data.n_entries),
- monotonic,
- test_object_monotonic,
- direction,
- NULL, &z, NULL);
- if (r <= 0)
- return r;
-
- /* And now, continue seeking until we find an entry that
- * exists in both bisection arrays */
-
- for (;;) {
- Object *qo;
- uint64_t p, q;
-
- r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
- if (r < 0)
- return r;
-
- r = generic_array_bisect_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- le64toh(d->data.n_entries),
- z,
- test_object_offset,
- direction,
- NULL, &p, NULL);
- if (r <= 0)
- return r;
-
- r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
- if (r < 0)
- return r;
-
- r = generic_array_bisect_plus_one(f,
- le64toh(o->data.entry_offset),
- le64toh(o->data.entry_array_offset),
- le64toh(o->data.n_entries),
- p,
- test_object_offset,
- direction,
- &qo, &q, NULL);
-
- if (r <= 0)
- return r;
-
- if (p == q) {
- if (ret)
- *ret = qo;
- if (offset)
- *offset = q;
-
- return 1;
- }
-
- z = q;
- }
-}
-
-int journal_file_move_to_entry_by_seqnum_for_data(
- JournalFile *f,
- uint64_t data_offset,
- uint64_t seqnum,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- Object *d;
- int r;
-
- assert(f);
-
- r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
- if (r < 0)
- return r;
-
- return generic_array_bisect_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- le64toh(d->data.n_entries),
- seqnum,
- test_object_seqnum,
- direction,
- ret, offset, NULL);
-}
-
-int journal_file_move_to_entry_by_realtime_for_data(
- JournalFile *f,
- uint64_t data_offset,
- uint64_t realtime,
- direction_t direction,
- Object **ret, uint64_t *offset) {
-
- Object *d;
- int r;
-
- assert(f);
-
- r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d);
- if (r < 0)
- return r;
-
- return generic_array_bisect_plus_one(f,
- le64toh(d->data.entry_offset),
- le64toh(d->data.entry_array_offset),
- le64toh(d->data.n_entries),
- realtime,
- test_object_realtime,
- direction,
- ret, offset, NULL);
-}
-
-void journal_file_dump(JournalFile *f) {
- Object *o;
- int r;
- uint64_t p;
-
- assert(f);
- assert(f->header);
-
- journal_file_print_header(f);
-
- p = le64toh(f->header->header_size);
- while (p != 0) {
- r = journal_file_move_to_object(f, OBJECT_UNUSED, 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_FIELD:
- printf("Type: OBJECT_FIELD\n");
- break;
-
- case OBJECT_ENTRY:
- printf("Type: OBJECT_ENTRY seqnum=%"PRIu64" monotonic=%"PRIu64" realtime=%"PRIu64"\n",
- le64toh(o->entry.seqnum),
- le64toh(o->entry.monotonic),
- le64toh(o->entry.realtime));
- break;
-
- case OBJECT_FIELD_HASH_TABLE:
- printf("Type: OBJECT_FIELD_HASH_TABLE\n");
- break;
-
- case OBJECT_DATA_HASH_TABLE:
- printf("Type: OBJECT_DATA_HASH_TABLE\n");
- break;
-
- case OBJECT_ENTRY_ARRAY:
- printf("Type: OBJECT_ENTRY_ARRAY\n");
- break;
-
- case OBJECT_TAG:
- printf("Type: OBJECT_TAG seqnum=%"PRIu64" epoch=%"PRIu64"\n",
- le64toh(o->tag.seqnum),
- le64toh(o->tag.epoch));
- break;
-
- default:
- printf("Type: unknown (%i)\n", o->object.type);
- break;
- }
-
- if (o->object.flags & OBJECT_COMPRESSION_MASK)
- printf("Flags: %s\n",
- object_compressed_to_string(o->object.flags & OBJECT_COMPRESSION_MASK));
-
- if (p == le64toh(f->header->tail_object_offset))
- p = 0;
- else
- p = p + ALIGN64(le64toh(o->object.size));
- }
-
- return;
-fail:
- log_error("File corrupt");
-}
-
-static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) {
- const char *x;
-
- x = format_timestamp(buf, l, t);
- if (x)
- return x;
- return " --- ";
-}
-
-void journal_file_print_header(JournalFile *f) {
- char a[33], b[33], c[33], d[33];
- char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX];
- struct stat st;
- char bytes[FORMAT_BYTES_MAX];
-
- assert(f);
- assert(f->header);
-
- printf("File Path: %s\n"
- "File ID: %s\n"
- "Machine ID: %s\n"
- "Boot ID: %s\n"
- "Sequential Number ID: %s\n"
- "State: %s\n"
- "Compatible Flags:%s%s\n"
- "Incompatible Flags:%s%s%s\n"
- "Header size: %"PRIu64"\n"
- "Arena size: %"PRIu64"\n"
- "Data Hash Table Size: %"PRIu64"\n"
- "Field Hash Table Size: %"PRIu64"\n"
- "Rotate Suggested: %s\n"
- "Head Sequential Number: %"PRIu64"\n"
- "Tail Sequential Number: %"PRIu64"\n"
- "Head Realtime Timestamp: %s\n"
- "Tail Realtime Timestamp: %s\n"
- "Tail Monotonic Timestamp: %s\n"
- "Objects: %"PRIu64"\n"
- "Entry Objects: %"PRIu64"\n",
- f->path,
- 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),
- sd_id128_to_string(f->header->seqnum_id, d),
- f->header->state == STATE_OFFLINE ? "OFFLINE" :
- f->header->state == STATE_ONLINE ? "ONLINE" :
- f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN",
- JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "",
- (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_ANY) ? " ???" : "",
- JOURNAL_HEADER_COMPRESSED_XZ(f->header) ? " COMPRESSED-XZ" : "",
- JOURNAL_HEADER_COMPRESSED_LZ4(f->header) ? " COMPRESSED-LZ4" : "",
- (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_ANY) ? " ???" : "",
- le64toh(f->header->header_size),
- le64toh(f->header->arena_size),
- le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
- le64toh(f->header->field_hash_table_size) / sizeof(HashItem),
- yes_no(journal_file_rotate_suggested(f, 0)),
- le64toh(f->header->head_entry_seqnum),
- le64toh(f->header->tail_entry_seqnum),
- format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)),
- format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)),
- format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC),
- le64toh(f->header->n_objects),
- le64toh(f->header->n_entries));
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
- printf("Data Objects: %"PRIu64"\n"
- "Data Hash Table Fill: %.1f%%\n",
- le64toh(f->header->n_data),
- 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))));
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
- printf("Field Objects: %"PRIu64"\n"
- "Field Hash Table Fill: %.1f%%\n",
- le64toh(f->header->n_fields),
- 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))));
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_tags))
- printf("Tag Objects: %"PRIu64"\n",
- le64toh(f->header->n_tags));
- if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
- printf("Entry Array Objects: %"PRIu64"\n",
- le64toh(f->header->n_entry_arrays));
-
- if (fstat(f->fd, &st) >= 0)
- printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL));
-}
-
-static int journal_file_warn_btrfs(JournalFile *f) {
- unsigned attrs;
- int r;
-
- assert(f);
-
- /* Before we write anything, check if the COW logic is turned
- * off on btrfs. Given our write pattern that is quite
- * unfriendly to COW file systems this should greatly improve
- * performance on COW file systems, such as btrfs, at the
- * expense of data integrity features (which shouldn't be too
- * bad, given that we do our own checksumming). */
-
- r = btrfs_is_filesystem(f->fd);
- if (r < 0)
- return log_warning_errno(r, "Failed to determine if journal is on btrfs: %m");
- if (!r)
- return 0;
-
- r = read_attr_fd(f->fd, &attrs);
- if (r < 0)
- return log_warning_errno(r, "Failed to read file attributes: %m");
-
- if (attrs & FS_NOCOW_FL) {
- log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
- return 0;
- }
-
- log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
- "This is likely to slow down journal access substantially, please consider turning "
- "off the copy-on-write file attribute on the journal directory, using chattr +C.", f->path);
-
- return 1;
-}
-
-int journal_file_open(
- const char *fname,
- int flags,
- mode_t mode,
- bool compress,
- bool seal,
- JournalMetrics *metrics,
- MMapCache *mmap_cache,
- JournalFile *template,
- JournalFile **ret) {
-
- bool newly_created = false;
- JournalFile *f;
- void *h;
- int r;
-
- assert(fname);
- assert(ret);
-
- if ((flags & O_ACCMODE) != O_RDONLY &&
- (flags & O_ACCMODE) != O_RDWR)
- return -EINVAL;
-
- if (!endswith(fname, ".journal") &&
- !endswith(fname, ".journal~"))
- return -EINVAL;
-
- f = new0(JournalFile, 1);
- if (!f)
- return -ENOMEM;
-
- f->fd = -1;
- f->mode = mode;
-
- f->flags = flags;
- f->prot = prot_from_flags(flags);
- f->writable = (flags & O_ACCMODE) != O_RDONLY;
-#if defined(HAVE_LZ4)
- f->compress_lz4 = compress;
-#elif defined(HAVE_XZ)
- f->compress_xz = compress;
-#endif
-#ifdef HAVE_GCRYPT
- f->seal = seal;
-#endif
-
- if (mmap_cache)
- f->mmap = mmap_cache_ref(mmap_cache);
- else {
- f->mmap = mmap_cache_new();
- if (!f->mmap) {
- r = -ENOMEM;
- goto fail;
- }
- }
-
- f->path = strdup(fname);
- if (!f->path) {
- r = -ENOMEM;
- goto fail;
- }
-
- f->chain_cache = ordered_hashmap_new(&uint64_hash_ops);
- if (!f->chain_cache) {
- r = -ENOMEM;
- goto fail;
- }
-
- f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode);
- if (f->fd < 0) {
- r = -errno;
- goto fail;
- }
-
- r = journal_file_fstat(f);
- if (r < 0)
- goto fail;
-
- if (f->last_stat.st_size == 0 && f->writable) {
-
- (void) journal_file_warn_btrfs(f);
-
- /* Let's attach the creation time to the journal file,
- * so that the vacuuming code knows the age of this
- * file even if the file might end up corrupted one
- * day... Ideally we'd just use the creation time many
- * file systems maintain for each file, but there is
- * currently no usable API to query this, hence let's
- * emulate this via extended attributes. If extended
- * attributes are not supported we'll just skip this,
- * and rely solely on mtime/atime/ctime of the file. */
-
- fd_setcrtime(f->fd, 0);
-
-#ifdef HAVE_GCRYPT
- /* Try to load the FSPRG state, and if we can't, then
- * just don't do sealing */
- if (f->seal) {
- r = journal_file_fss_load(f);
- if (r < 0)
- f->seal = false;
- }
-#endif
-
- r = journal_file_init_header(f, template);
- if (r < 0)
- goto fail;
-
- r = journal_file_fstat(f);
- if (r < 0)
- goto fail;
-
- newly_created = true;
- }
-
- if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
- r = -ENODATA;
- goto fail;
- }
-
- r = mmap_cache_get(f->mmap, f->fd, f->prot, CONTEXT_HEADER, true, 0, PAGE_ALIGN(sizeof(Header)), &f->last_stat, &h);
- if (r < 0)
- goto fail;
-
- f->header = h;
-
- if (!newly_created) {
- r = journal_file_verify_header(f);
- if (r < 0)
- goto fail;
- }
-
-#ifdef HAVE_GCRYPT
- if (!newly_created && f->writable) {
- r = journal_file_fss_load(f);
- if (r < 0)
- goto fail;
- }
-#endif
-
- if (f->writable) {
- if (metrics) {
- journal_default_metrics(metrics, f->fd);
- f->metrics = *metrics;
- } else if (template)
- f->metrics = template->metrics;
-
- r = journal_file_refresh_header(f);
- if (r < 0)
- goto fail;
- }
-
-#ifdef HAVE_GCRYPT
- r = journal_file_hmac_setup(f);
- if (r < 0)
- goto fail;
-#endif
-
- if (newly_created) {
- r = journal_file_setup_field_hash_table(f);
- if (r < 0)
- goto fail;
-
- r = journal_file_setup_data_hash_table(f);
- if (r < 0)
- goto fail;
-
-#ifdef HAVE_GCRYPT
- r = journal_file_append_first_tag(f);
- if (r < 0)
- goto fail;
-#endif
- }
-
- if (mmap_cache_got_sigbus(f->mmap, f->fd)) {
- r = -EIO;
- goto fail;
- }
-
- if (template && template->post_change_timer) {
- r = journal_file_enable_post_change_timer(
- f,
- sd_event_source_get_event(template->post_change_timer),
- template->post_change_timer_period);
-
- if (r < 0)
- goto fail;
- }
-
- *ret = f;
- return 0;
-
-fail:
- if (f->fd >= 0 && mmap_cache_got_sigbus(f->mmap, f->fd))
- r = -EIO;
-
- journal_file_close(f);
-
- return r;
-}
-
-int journal_file_rotate(JournalFile **f, bool compress, bool seal) {
- _cleanup_free_ char *p = NULL;
- size_t l;
- JournalFile *old_file, *new_file = NULL;
- int r;
-
- assert(f);
- assert(*f);
-
- old_file = *f;
-
- if (!old_file->writable)
- return -EINVAL;
-
- if (!endswith(old_file->path, ".journal"))
- return -EINVAL;
-
- l = strlen(old_file->path);
- r = asprintf(&p, "%.*s@" SD_ID128_FORMAT_STR "-%016"PRIx64"-%016"PRIx64".journal",
- (int) l - 8, old_file->path,
- SD_ID128_FORMAT_VAL(old_file->header->seqnum_id),
- le64toh((*f)->header->head_entry_seqnum),
- le64toh((*f)->header->head_entry_realtime));
- if (r < 0)
- return -ENOMEM;
-
- /* Try to rename the file to the archived version. If the file
- * already was deleted, we'll get ENOENT, let's ignore that
- * case. */
- r = rename(old_file->path, p);
- if (r < 0 && errno != ENOENT)
- return -errno;
-
- old_file->header->state = STATE_ARCHIVED;
-
- /* Currently, btrfs is not very good with out write patterns
- * and fragments heavily. Let's defrag our journal files when
- * we archive them */
- old_file->defrag_on_close = true;
-
- r = journal_file_open(old_file->path, old_file->flags, old_file->mode, compress, seal, NULL, old_file->mmap, old_file, &new_file);
- journal_file_close(old_file);
-
- *f = new_file;
- return r;
-}
-
-int journal_file_open_reliably(
- const char *fname,
- int flags,
- mode_t mode,
- bool compress,
- bool seal,
- JournalMetrics *metrics,
- MMapCache *mmap_cache,
- JournalFile *template,
- JournalFile **ret) {
-
- int r;
- size_t l;
- _cleanup_free_ char *p = NULL;
-
- r = journal_file_open(fname, flags, mode, compress, seal, metrics, mmap_cache, template, ret);
- if (!IN_SET(r,
- -EBADMSG, /* corrupted */
- -ENODATA, /* truncated */
- -EHOSTDOWN, /* other machine */
- -EPROTONOSUPPORT, /* incompatible feature */
- -EBUSY, /* unclean shutdown */
- -ESHUTDOWN, /* already archived */
- -EIO, /* IO error, including SIGBUS on mmap */
- -EIDRM /* File has been deleted */))
- return r;
-
- if ((flags & O_ACCMODE) == O_RDONLY)
- return r;
-
- if (!(flags & O_CREAT))
- return r;
-
- if (!endswith(fname, ".journal"))
- return r;
-
- /* The file is corrupted. Rotate it away and try it again (but only once) */
-
- l = strlen(fname);
- if (asprintf(&p, "%.*s@%016"PRIx64 "-%016"PRIx64 ".journal~",
- (int) l - 8, fname,
- now(CLOCK_REALTIME),
- random_u64()) < 0)
- return -ENOMEM;
-
- if (rename(fname, p) < 0)
- return -errno;
-
- /* btrfs doesn't cope well with our write pattern and
- * fragments heavily. Let's defrag all files we rotate */
-
- (void) chattr_path(p, false, FS_NOCOW_FL);
- (void) btrfs_defrag(p);
-
- log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname);
-
- return journal_file_open(fname, flags, mode, compress, seal, metrics, mmap_cache, template, ret);
-}
-
-int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) {
- uint64_t i, n;
- uint64_t q, xor_hash = 0;
- int r;
- EntryItem *items;
- dual_timestamp ts;
-
- assert(from);
- assert(to);
- assert(o);
- assert(p);
-
- if (!to->writable)
- return -EPERM;
-
- ts.monotonic = le64toh(o->entry.monotonic);
- ts.realtime = le64toh(o->entry.realtime);
-
- n = journal_file_entry_n_items(o);
- /* alloca() can't take 0, hence let's allocate at least one */
- items = alloca(sizeof(EntryItem) * MAX(1u, n));
-
- for (i = 0; i < n; i++) {
- uint64_t l, h;
- le64_t le_hash;
- size_t t;
- void *data;
- Object *u;
-
- q = le64toh(o->entry.items[i].object_offset);
- le_hash = o->entry.items[i].hash;
-
- r = journal_file_move_to_object(from, OBJECT_DATA, q, &o);
- if (r < 0)
- return r;
-
- if (le_hash != o->data.hash)
- return -EBADMSG;
-
- l = le64toh(o->object.size) - offsetof(Object, data.payload);
- t = (size_t) l;
-
- /* We hit the limit on 32bit machines */
- if ((uint64_t) t != l)
- return -E2BIG;
-
- if (o->object.flags & OBJECT_COMPRESSION_MASK) {
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- size_t rsize = 0;
-
- r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK,
- o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0);
- if (r < 0)
- return r;
-
- data = from->compress_buffer;
- l = rsize;
-#else
- return -EPROTONOSUPPORT;
-#endif
- } else
- data = o->data.payload;
-
- r = journal_file_append_data(to, data, l, &u, &h);
- if (r < 0)
- return r;
-
- xor_hash ^= le64toh(u->data.hash);
- items[i].object_offset = htole64(h);
- items[i].hash = u->data.hash;
-
- r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
- }
-
- r = journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset);
-
- if (mmap_cache_got_sigbus(to->mmap, to->fd))
- return -EIO;
-
- return r;
-}
-
-void journal_reset_metrics(JournalMetrics *m) {
- assert(m);
-
- /* Set everything to "pick automatic values". */
-
- *m = (JournalMetrics) {
- .min_use = (uint64_t) -1,
- .max_use = (uint64_t) -1,
- .min_size = (uint64_t) -1,
- .max_size = (uint64_t) -1,
- .keep_free = (uint64_t) -1,
- .n_max_files = (uint64_t) -1,
- };
-}
-
-void journal_default_metrics(JournalMetrics *m, int fd) {
- char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX];
- struct statvfs ss;
- uint64_t fs_size;
-
- assert(m);
- assert(fd >= 0);
-
- if (fstatvfs(fd, &ss) >= 0)
- fs_size = ss.f_frsize * ss.f_blocks;
- else {
- log_debug_errno(errno, "Failed to detremine disk size: %m");
- fs_size = 0;
- }
-
- if (m->max_use == (uint64_t) -1) {
-
- if (fs_size > 0) {
- m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */
-
- if (m->max_use > DEFAULT_MAX_USE_UPPER)
- m->max_use = DEFAULT_MAX_USE_UPPER;
-
- if (m->max_use < DEFAULT_MAX_USE_LOWER)
- m->max_use = DEFAULT_MAX_USE_LOWER;
- } else
- m->max_use = DEFAULT_MAX_USE_LOWER;
- } else {
- m->max_use = PAGE_ALIGN(m->max_use);
-
- if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2)
- m->max_use = JOURNAL_FILE_SIZE_MIN*2;
- }
-
- if (m->min_use == (uint64_t) -1)
- m->min_use = DEFAULT_MIN_USE;
-
- if (m->min_use > m->max_use)
- m->min_use = m->max_use;
-
- if (m->max_size == (uint64_t) -1) {
- m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */
-
- if (m->max_size > DEFAULT_MAX_SIZE_UPPER)
- m->max_size = DEFAULT_MAX_SIZE_UPPER;
- } else
- m->max_size = PAGE_ALIGN(m->max_size);
-
- if (m->max_size != 0) {
- if (m->max_size < JOURNAL_FILE_SIZE_MIN)
- m->max_size = JOURNAL_FILE_SIZE_MIN;
-
- if (m->max_use != 0 && m->max_size*2 > m->max_use)
- m->max_use = m->max_size*2;
- }
-
- if (m->min_size == (uint64_t) -1)
- m->min_size = JOURNAL_FILE_SIZE_MIN;
- else {
- m->min_size = PAGE_ALIGN(m->min_size);
-
- if (m->min_size < JOURNAL_FILE_SIZE_MIN)
- m->min_size = JOURNAL_FILE_SIZE_MIN;
-
- if (m->max_size != 0 && m->min_size > m->max_size)
- m->max_size = m->min_size;
- }
-
- if (m->keep_free == (uint64_t) -1) {
-
- if (fs_size > 0) {
- m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */
-
- if (m->keep_free > DEFAULT_KEEP_FREE_UPPER)
- m->keep_free = DEFAULT_KEEP_FREE_UPPER;
-
- } else
- m->keep_free = DEFAULT_KEEP_FREE;
- }
-
- if (m->n_max_files == (uint64_t) -1)
- m->n_max_files = DEFAULT_N_MAX_FILES;
-
- log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64,
- format_bytes(a, sizeof(a), m->min_use),
- format_bytes(b, sizeof(b), m->max_use),
- format_bytes(c, sizeof(c), m->max_size),
- format_bytes(d, sizeof(d), m->min_size),
- format_bytes(e, sizeof(e), m->keep_free),
- m->n_max_files);
-}
-
-int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) {
- assert(f);
- assert(f->header);
- assert(from || to);
-
- if (from) {
- if (f->header->head_entry_realtime == 0)
- return -ENOENT;
-
- *from = le64toh(f->header->head_entry_realtime);
- }
-
- if (to) {
- if (f->header->tail_entry_realtime == 0)
- return -ENOENT;
-
- *to = le64toh(f->header->tail_entry_realtime);
- }
-
- return 1;
-}
-
-int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) {
- Object *o;
- uint64_t p;
- int r;
-
- assert(f);
- assert(from || to);
-
- r = find_data_object_by_boot_id(f, boot_id, &o, &p);
- if (r <= 0)
- return r;
-
- if (le64toh(o->data.n_entries) <= 0)
- return 0;
-
- if (from) {
- r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
- if (r < 0)
- return r;
-
- *from = le64toh(o->entry.monotonic);
- }
-
- if (to) {
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- r = generic_array_get_plus_one(f,
- le64toh(o->data.entry_offset),
- le64toh(o->data.entry_array_offset),
- le64toh(o->data.n_entries)-1,
- &o, NULL);
- if (r <= 0)
- return r;
-
- *to = le64toh(o->entry.monotonic);
- }
-
- return 1;
-}
-
-bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) {
- assert(f);
- assert(f->header);
-
- /* If we gained new header fields we gained new features,
- * hence suggest a rotation */
- if (le64toh(f->header->header_size) < sizeof(Header)) {
- log_debug("%s uses an outdated header, suggesting rotation.", f->path);
- return true;
- }
-
- /* Let's check if the hash tables grew over a certain fill
- * level (75%, borrowing this value from Java's hash table
- * implementation), and if so suggest a rotation. To calculate
- * the fill level we need the n_data field, which only exists
- * in newer versions. */
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
- if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) {
- log_debug("Data hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items, %llu file size, %"PRIu64" bytes per hash table item), suggesting rotation.",
- f->path,
- 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))),
- le64toh(f->header->n_data),
- le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
- (unsigned long long) f->last_stat.st_size,
- f->last_stat.st_size / le64toh(f->header->n_data));
- return true;
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
- if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) {
- log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items), suggesting rotation.",
- f->path,
- 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))),
- le64toh(f->header->n_fields),
- le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
- return true;
- }
-
- /* Are the data objects properly indexed by field objects? */
- if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
- JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
- le64toh(f->header->n_data) > 0 &&
- le64toh(f->header->n_fields) == 0)
- return true;
-
- if (max_file_usec > 0) {
- usec_t t, h;
-
- h = le64toh(f->header->head_entry_realtime);
- t = now(CLOCK_REALTIME);
-
- if (h > 0 && t > h + max_file_usec)
- return true;
- }
-
- return false;
-}
diff --git a/src/journal/journal-file.h b/src/journal/journal-file.h
deleted file mode 100644
index 07b9561b8a..0000000000
--- a/src/journal/journal-file.h
+++ /dev/null
@@ -1,245 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <inttypes.h>
-
-#ifdef HAVE_GCRYPT
-#include <gcrypt.h>
-#endif
-
-#include "sd-id128.h"
-
-#include "hashmap.h"
-#include "journal-def.h"
-#include "macro.h"
-#include "mmap-cache.h"
-#include "sd-event.h"
-#include "sparse-endian.h"
-
-typedef struct JournalMetrics {
- /* For all these: -1 means "pick automatically", and 0 means "no limit enforced" */
- uint64_t max_size; /* how large journal files grow at max */
- uint64_t min_size; /* how large journal files grow at least */
- uint64_t max_use; /* how much disk space to use in total at max, keep_free permitting */
- uint64_t min_use; /* how much disk space to use in total at least, even if keep_free says not to */
- uint64_t keep_free; /* how much to keep free on disk */
- uint64_t n_max_files; /* how many files to keep around at max */
-} JournalMetrics;
-
-typedef enum direction {
- DIRECTION_UP,
- DIRECTION_DOWN
-} direction_t;
-
-typedef enum LocationType {
- /* The first and last entries, resp. */
- LOCATION_HEAD,
- LOCATION_TAIL,
-
- /* We already read the entry we currently point to, and the
- * next one to read should probably not be this one again. */
- LOCATION_DISCRETE,
-
- /* We should seek to the precise location specified, and
- * return it, as we haven't read it yet. */
- LOCATION_SEEK
-} LocationType;
-
-typedef struct JournalFile {
- int fd;
-
- mode_t mode;
-
- int flags;
- int prot;
- bool writable:1;
- bool compress_xz:1;
- bool compress_lz4:1;
- bool seal:1;
- bool defrag_on_close:1;
-
- bool tail_entry_monotonic_valid:1;
-
- direction_t last_direction;
- LocationType location_type;
- uint64_t last_n_entries;
-
- char *path;
- struct stat last_stat;
- usec_t last_stat_usec;
-
- Header *header;
- HashItem *data_hash_table;
- HashItem *field_hash_table;
-
- uint64_t current_offset;
- uint64_t current_seqnum;
- uint64_t current_realtime;
- uint64_t current_monotonic;
- sd_id128_t current_boot_id;
- uint64_t current_xor_hash;
-
- JournalMetrics metrics;
- MMapCache *mmap;
-
- sd_event_source *post_change_timer;
- usec_t post_change_timer_period;
-
- OrderedHashmap *chain_cache;
-
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- void *compress_buffer;
- size_t compress_buffer_size;
-#endif
-
-#ifdef HAVE_GCRYPT
- gcry_md_hd_t hmac;
- bool hmac_running;
-
- FSSHeader *fss_file;
- size_t fss_file_size;
-
- uint64_t fss_start_usec;
- uint64_t fss_interval_usec;
-
- void *fsprg_state;
- size_t fsprg_state_size;
-
- void *fsprg_seed;
- size_t fsprg_seed_size;
-#endif
-} JournalFile;
-
-int journal_file_open(
- const char *fname,
- int flags,
- mode_t mode,
- bool compress,
- bool seal,
- JournalMetrics *metrics,
- MMapCache *mmap_cache,
- JournalFile *template,
- JournalFile **ret);
-
-int journal_file_set_offline(JournalFile *f);
-JournalFile* journal_file_close(JournalFile *j);
-
-int journal_file_open_reliably(
- const char *fname,
- int flags,
- mode_t mode,
- bool compress,
- bool seal,
- JournalMetrics *metrics,
- MMapCache *mmap_cache,
- JournalFile *template,
- JournalFile **ret);
-
-#define ALIGN64(x) (((x) + 7ULL) & ~7ULL)
-#define VALID64(x) (((x) & 7ULL) == 0ULL)
-
-/* Use six characters to cover the offsets common in smallish journal
- * files without adding too many zeros. */
-#define OFSfmt "%06"PRIx64
-
-static inline bool VALID_REALTIME(uint64_t u) {
- /* This considers timestamps until the year 3112 valid. That should be plenty room... */
- return u > 0 && u < (1ULL << 55);
-}
-
-static inline bool VALID_MONOTONIC(uint64_t u) {
- /* This considers timestamps until 1142 years of runtime valid. */
- return u < (1ULL << 55);
-}
-
-static inline bool VALID_EPOCH(uint64_t u) {
- /* This allows changing the key for 1142 years, every usec. */
- return u < (1ULL << 55);
-}
-
-#define JOURNAL_HEADER_CONTAINS(h, field) \
- (le64toh((h)->header_size) >= offsetof(Header, field) + sizeof((h)->field))
-
-#define JOURNAL_HEADER_SEALED(h) \
- (!!(le32toh((h)->compatible_flags) & HEADER_COMPATIBLE_SEALED))
-
-#define JOURNAL_HEADER_COMPRESSED_XZ(h) \
- (!!(le32toh((h)->incompatible_flags) & HEADER_INCOMPATIBLE_COMPRESSED_XZ))
-
-#define JOURNAL_HEADER_COMPRESSED_LZ4(h) \
- (!!(le32toh((h)->incompatible_flags) & HEADER_INCOMPATIBLE_COMPRESSED_LZ4))
-
-int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret);
-
-uint64_t journal_file_entry_n_items(Object *o) _pure_;
-uint64_t journal_file_entry_array_n_items(Object *o) _pure_;
-uint64_t journal_file_hash_table_n_items(Object *o) _pure_;
-
-int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset);
-int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqno, Object **ret, uint64_t *offset);
-
-int journal_file_find_data_object(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset);
-int journal_file_find_data_object_with_hash(JournalFile *f, const void *data, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset);
-
-int journal_file_find_field_object(JournalFile *f, const void *field, uint64_t size, Object **ret, uint64_t *offset);
-int journal_file_find_field_object_with_hash(JournalFile *f, const void *field, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset);
-
-void journal_file_reset_location(JournalFile *f);
-void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset);
-int journal_file_compare_locations(JournalFile *af, JournalFile *bf);
-int journal_file_next_entry(JournalFile *f, uint64_t p, direction_t direction, Object **ret, uint64_t *offset);
-
-int journal_file_next_entry_for_data(JournalFile *f, Object *o, uint64_t p, uint64_t data_offset, direction_t direction, Object **ret, uint64_t *offset);
-
-int journal_file_move_to_entry_by_seqnum(JournalFile *f, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset);
-int journal_file_move_to_entry_by_realtime(JournalFile *f, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset);
-int journal_file_move_to_entry_by_monotonic(JournalFile *f, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset);
-
-int journal_file_move_to_entry_by_offset_for_data(JournalFile *f, uint64_t data_offset, uint64_t p, direction_t direction, Object **ret, uint64_t *offset);
-int journal_file_move_to_entry_by_seqnum_for_data(JournalFile *f, uint64_t data_offset, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset);
-int journal_file_move_to_entry_by_realtime_for_data(JournalFile *f, uint64_t data_offset, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset);
-int journal_file_move_to_entry_by_monotonic_for_data(JournalFile *f, uint64_t data_offset, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset);
-
-int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset);
-
-void journal_file_dump(JournalFile *f);
-void journal_file_print_header(JournalFile *f);
-
-int journal_file_rotate(JournalFile **f, bool compress, bool seal);
-
-void journal_file_post_change(JournalFile *f);
-int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t);
-
-void journal_reset_metrics(JournalMetrics *m);
-void journal_default_metrics(JournalMetrics *m, int fd);
-
-int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to);
-int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot, usec_t *from, usec_t *to);
-
-bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec);
-
-int journal_file_map_data_hash_table(JournalFile *f);
-int journal_file_map_field_hash_table(JournalFile *f);
-
-static inline bool JOURNAL_FILE_COMPRESS(JournalFile *f) {
- assert(f);
- return f->compress_xz || f->compress_lz4;
-}
diff --git a/src/journal/journal-internal.h b/src/journal/journal-internal.h
deleted file mode 100644
index 7639325acf..0000000000
--- a/src/journal/journal-internal.h
+++ /dev/null
@@ -1,140 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <inttypes.h>
-#include <stdbool.h>
-#include <sys/types.h>
-
-#include "sd-id128.h"
-#include "sd-journal.h"
-
-#include "hashmap.h"
-#include "journal-def.h"
-#include "journal-file.h"
-#include "list.h"
-#include "set.h"
-
-typedef struct Match Match;
-typedef struct Location Location;
-typedef struct Directory Directory;
-
-typedef enum MatchType {
- MATCH_DISCRETE,
- MATCH_OR_TERM,
- MATCH_AND_TERM
-} MatchType;
-
-struct Match {
- MatchType type;
- Match *parent;
- LIST_FIELDS(Match, matches);
-
- /* For concrete matches */
- char *data;
- size_t size;
- le64_t le_hash;
-
- /* For terms */
- LIST_HEAD(Match, matches);
-};
-
-struct Location {
- LocationType type;
-
- bool seqnum_set;
- bool realtime_set;
- bool monotonic_set;
- bool xor_hash_set;
-
- uint64_t seqnum;
- sd_id128_t seqnum_id;
-
- uint64_t realtime;
-
- uint64_t monotonic;
- sd_id128_t boot_id;
-
- uint64_t xor_hash;
-};
-
-struct Directory {
- char *path;
- int wd;
- bool is_root;
-};
-
-struct sd_journal {
- char *path;
- char *prefix;
-
- OrderedHashmap *files;
- MMapCache *mmap;
-
- Location current_location;
-
- JournalFile *current_file;
- uint64_t current_field;
-
- Match *level0, *level1, *level2;
-
- pid_t original_pid;
-
- int inotify_fd;
- unsigned current_invalidate_counter, last_invalidate_counter;
- usec_t last_process_usec;
-
- /* Iterating through unique fields and their data values */
- char *unique_field;
- JournalFile *unique_file;
- uint64_t unique_offset;
-
- /* Iterating through known fields */
- JournalFile *fields_file;
- uint64_t fields_offset;
- uint64_t fields_hash_table_index;
- char *fields_buffer;
- size_t fields_buffer_allocated;
-
- int flags;
-
- bool on_network:1;
- bool no_new_files:1;
- bool unique_file_lost:1; /* File we were iterating over got
- removed, and there were no more
- files, so sd_j_enumerate_unique
- will return a value equal to 0. */
- bool fields_file_lost:1;
- bool has_runtime_files:1;
- bool has_persistent_files:1;
-
- size_t data_threshold;
-
- Hashmap *directories_by_path;
- Hashmap *directories_by_wd;
-
- Hashmap *errors;
-};
-
-char *journal_make_match_string(sd_journal *j);
-void journal_print_header(sd_journal *j);
-
-#define JOURNAL_FOREACH_DATA_RETVAL(j, data, l, retval) \
- for (sd_journal_restart_data(j); ((retval) = sd_journal_enumerate_data((j), &(data), &(l))) > 0; )
diff --git a/src/journal/journal-qrcode.h b/src/journal/journal-qrcode.h
index ef39085561..34a779d5be 100644
--- a/src/journal/journal-qrcode.h
+++ b/src/journal/journal-qrcode.h
@@ -22,6 +22,6 @@
#include <inttypes.h>
#include <stdio.h>
-#include "sd-id128.h"
+#include <systemd/sd-id128.h>
int print_qr_code(FILE *f, const void *seed, size_t seed_size, uint64_t start, uint64_t interval, const char *hn, sd_id128_t machine);
diff --git a/src/journal/journal-send.c b/src/journal/journal-send.c
deleted file mode 100644
index c7d670f4ff..0000000000
--- a/src/journal/journal-send.c
+++ /dev/null
@@ -1,559 +0,0 @@
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <errno.h>
-#include <fcntl.h>
-#include <printf.h>
-#include <stddef.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <unistd.h>
-
-#define SD_JOURNAL_SUPPRESS_LOCATION
-
-#include "sd-journal.h"
-
-#include "alloc-util.h"
-#include "fd-util.h"
-#include "fileio.h"
-#include "io-util.h"
-#include "memfd-util.h"
-#include "socket-util.h"
-#include "stdio-util.h"
-#include "string-util.h"
-#include "util.h"
-
-#define SNDBUF_SIZE (8*1024*1024)
-
-#define ALLOCA_CODE_FUNC(f, func) \
- do { \
- size_t _fl; \
- const char *_func = (func); \
- char **_f = &(f); \
- _fl = strlen(_func) + 1; \
- *_f = alloca(_fl + 10); \
- memcpy(*_f, "CODE_FUNC=", 10); \
- memcpy(*_f + 10, _func, _fl); \
- } while(false)
-
-/* We open a single fd, and we'll share it with the current process,
- * all its threads, and all its subprocesses. This means we need to
- * initialize it atomically, and need to operate on it atomically
- * never assuming we are the only user */
-
-static int journal_fd(void) {
- int fd;
- static int fd_plus_one = 0;
-
-retry:
- if (fd_plus_one > 0)
- return fd_plus_one - 1;
-
- fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
- if (fd < 0)
- return -errno;
-
- fd_inc_sndbuf(fd, SNDBUF_SIZE);
-
- if (!__sync_bool_compare_and_swap(&fd_plus_one, 0, fd+1)) {
- safe_close(fd);
- goto retry;
- }
-
- return fd;
-}
-
-_public_ int sd_journal_print(int priority, const char *format, ...) {
- int r;
- va_list ap;
-
- va_start(ap, format);
- r = sd_journal_printv(priority, format, ap);
- va_end(ap);
-
- return r;
-}
-
-_public_ int sd_journal_printv(int priority, const char *format, va_list ap) {
-
- /* FIXME: Instead of limiting things to LINE_MAX we could do a
- C99 variable-length array on the stack here in a loop. */
-
- char buffer[8 + LINE_MAX], p[sizeof("PRIORITY=")-1 + DECIMAL_STR_MAX(int) + 1];
- struct iovec iov[2];
-
- assert_return(priority >= 0, -EINVAL);
- assert_return(priority <= 7, -EINVAL);
- assert_return(format, -EINVAL);
-
- xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK);
-
- memcpy(buffer, "MESSAGE=", 8);
- vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap);
-
- zero(iov);
- IOVEC_SET_STRING(iov[0], buffer);
- IOVEC_SET_STRING(iov[1], p);
-
- return sd_journal_sendv(iov, 2);
-}
-
-_printf_(1, 0) static int fill_iovec_sprintf(const char *format, va_list ap, int extra, struct iovec **_iov) {
- PROTECT_ERRNO;
- int r, n = 0, i = 0, j;
- struct iovec *iov = NULL;
-
- assert(_iov);
-
- if (extra > 0) {
- n = MAX(extra * 2, extra + 4);
- iov = malloc0(n * sizeof(struct iovec));
- if (!iov) {
- r = -ENOMEM;
- goto fail;
- }
-
- i = extra;
- }
-
- while (format) {
- struct iovec *c;
- char *buffer;
- va_list aq;
-
- if (i >= n) {
- n = MAX(i*2, 4);
- c = realloc(iov, n * sizeof(struct iovec));
- if (!c) {
- r = -ENOMEM;
- goto fail;
- }
-
- iov = c;
- }
-
- va_copy(aq, ap);
- if (vasprintf(&buffer, format, aq) < 0) {
- va_end(aq);
- r = -ENOMEM;
- goto fail;
- }
- va_end(aq);
-
- VA_FORMAT_ADVANCE(format, ap);
-
- IOVEC_SET_STRING(iov[i++], buffer);
-
- format = va_arg(ap, char *);
- }
-
- *_iov = iov;
-
- return i;
-
-fail:
- for (j = 0; j < i; j++)
- free(iov[j].iov_base);
-
- free(iov);
-
- return r;
-}
-
-_public_ int sd_journal_send(const char *format, ...) {
- int r, i, j;
- va_list ap;
- struct iovec *iov = NULL;
-
- va_start(ap, format);
- i = fill_iovec_sprintf(format, ap, 0, &iov);
- va_end(ap);
-
- if (_unlikely_(i < 0)) {
- r = i;
- goto finish;
- }
-
- r = sd_journal_sendv(iov, i);
-
-finish:
- for (j = 0; j < i; j++)
- free(iov[j].iov_base);
-
- free(iov);
-
- return r;
-}
-
-_public_ int sd_journal_sendv(const struct iovec *iov, int n) {
- PROTECT_ERRNO;
- int fd, r;
- _cleanup_close_ int buffer_fd = -1;
- struct iovec *w;
- uint64_t *l;
- int i, j = 0;
- struct sockaddr_un sa = {
- .sun_family = AF_UNIX,
- .sun_path = "/run/systemd/journal/socket",
- };
- struct msghdr mh = {
- .msg_name = &sa,
- .msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(sa.sun_path),
- };
- ssize_t k;
- bool have_syslog_identifier = false;
- bool seal = true;
-
- assert_return(iov, -EINVAL);
- assert_return(n > 0, -EINVAL);
-
- w = newa(struct iovec, n * 5 + 3);
- l = newa(uint64_t, n);
-
- for (i = 0; i < n; i++) {
- char *c, *nl;
-
- if (_unlikely_(!iov[i].iov_base || iov[i].iov_len <= 1))
- return -EINVAL;
-
- c = memchr(iov[i].iov_base, '=', iov[i].iov_len);
- if (_unlikely_(!c || c == iov[i].iov_base))
- return -EINVAL;
-
- have_syslog_identifier = have_syslog_identifier ||
- (c == (char *) iov[i].iov_base + 17 &&
- startswith(iov[i].iov_base, "SYSLOG_IDENTIFIER"));
-
- nl = memchr(iov[i].iov_base, '\n', iov[i].iov_len);
- if (nl) {
- if (_unlikely_(nl < c))
- return -EINVAL;
-
- /* Already includes a newline? Bummer, then
- * let's write the variable name, then a
- * newline, then the size (64bit LE), followed
- * by the data and a final newline */
-
- w[j].iov_base = iov[i].iov_base;
- w[j].iov_len = c - (char*) iov[i].iov_base;
- j++;
-
- IOVEC_SET_STRING(w[j++], "\n");
-
- l[i] = htole64(iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1);
- w[j].iov_base = &l[i];
- w[j].iov_len = sizeof(uint64_t);
- j++;
-
- w[j].iov_base = c + 1;
- w[j].iov_len = iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1;
- j++;
-
- } else
- /* Nothing special? Then just add the line and
- * append a newline */
- w[j++] = iov[i];
-
- IOVEC_SET_STRING(w[j++], "\n");
- }
-
- if (!have_syslog_identifier &&
- string_is_safe(program_invocation_short_name)) {
-
- /* Implicitly add program_invocation_short_name, if it
- * is not set explicitly. We only do this for
- * program_invocation_short_name, and nothing else
- * since everything else is much nicer to retrieve
- * from the outside. */
-
- IOVEC_SET_STRING(w[j++], "SYSLOG_IDENTIFIER=");
- IOVEC_SET_STRING(w[j++], program_invocation_short_name);
- IOVEC_SET_STRING(w[j++], "\n");
- }
-
- fd = journal_fd();
- if (_unlikely_(fd < 0))
- return fd;
-
- mh.msg_iov = w;
- mh.msg_iovlen = j;
-
- k = sendmsg(fd, &mh, MSG_NOSIGNAL);
- if (k >= 0)
- return 0;
-
- /* Fail silently if the journal is not available */
- if (errno == ENOENT)
- return 0;
-
- if (errno != EMSGSIZE && errno != ENOBUFS)
- return -errno;
-
- /* Message doesn't fit... Let's dump the data in a memfd or
- * temporary file and just pass a file descriptor of it to the
- * other side.
- *
- * For the temporary files we use /dev/shm instead of /tmp
- * here, since we want this to be a tmpfs, and one that is
- * available from early boot on and where unprivileged users
- * can create files. */
- buffer_fd = memfd_new(NULL);
- if (buffer_fd < 0) {
- if (buffer_fd == -ENOSYS) {
- buffer_fd = open_tmpfile("/dev/shm", O_RDWR | O_CLOEXEC);
- if (buffer_fd < 0)
- return buffer_fd;
-
- seal = false;
- } else
- return buffer_fd;
- }
-
- n = writev(buffer_fd, w, j);
- if (n < 0)
- return -errno;
-
- if (seal) {
- r = memfd_set_sealed(buffer_fd);
- if (r < 0)
- return r;
- }
-
- r = send_one_fd_sa(fd, buffer_fd, mh.msg_name, mh.msg_namelen, 0);
- if (r == -ENOENT)
- /* Fail silently if the journal is not available */
- return 0;
- return r;
-}
-
-static int fill_iovec_perror_and_send(const char *message, int skip, struct iovec iov[]) {
- PROTECT_ERRNO;
- size_t n, k;
-
- k = isempty(message) ? 0 : strlen(message) + 2;
- n = 8 + k + 256 + 1;
-
- for (;;) {
- char buffer[n];
- char* j;
-
- errno = 0;
- j = strerror_r(_saved_errno_, buffer + 8 + k, n - 8 - k);
- if (errno == 0) {
- char error[sizeof("ERRNO=")-1 + DECIMAL_STR_MAX(int) + 1];
-
- if (j != buffer + 8 + k)
- memmove(buffer + 8 + k, j, strlen(j)+1);
-
- memcpy(buffer, "MESSAGE=", 8);
-
- if (k > 0) {
- memcpy(buffer + 8, message, k - 2);
- memcpy(buffer + 8 + k - 2, ": ", 2);
- }
-
- xsprintf(error, "ERRNO=%i", _saved_errno_);
-
- assert_cc(3 == LOG_ERR);
- IOVEC_SET_STRING(iov[skip+0], "PRIORITY=3");
- IOVEC_SET_STRING(iov[skip+1], buffer);
- IOVEC_SET_STRING(iov[skip+2], error);
-
- return sd_journal_sendv(iov, skip + 3);
- }
-
- if (errno != ERANGE)
- return -errno;
-
- n *= 2;
- }
-}
-
-_public_ int sd_journal_perror(const char *message) {
- struct iovec iovec[3];
-
- return fill_iovec_perror_and_send(message, 0, iovec);
-}
-
-_public_ int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix) {
- union sockaddr_union sa = {
- .un.sun_family = AF_UNIX,
- .un.sun_path = "/run/systemd/journal/stdout",
- };
- _cleanup_close_ int fd = -1;
- char *header;
- size_t l;
- int r;
-
- assert_return(priority >= 0, -EINVAL);
- assert_return(priority <= 7, -EINVAL);
-
- fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
- if (fd < 0)
- return -errno;
-
- r = connect(fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path));
- if (r < 0)
- return -errno;
-
- if (shutdown(fd, SHUT_RD) < 0)
- return -errno;
-
- fd_inc_sndbuf(fd, SNDBUF_SIZE);
-
- if (!identifier)
- identifier = "";
-
- l = strlen(identifier);
- header = alloca(l + 1 + 1 + 2 + 2 + 2 + 2 + 2);
-
- memcpy(header, identifier, l);
- header[l++] = '\n';
- header[l++] = '\n'; /* unit id */
- header[l++] = '0' + priority;
- header[l++] = '\n';
- header[l++] = '0' + !!level_prefix;
- header[l++] = '\n';
- header[l++] = '0';
- header[l++] = '\n';
- header[l++] = '0';
- header[l++] = '\n';
- header[l++] = '0';
- header[l++] = '\n';
-
- r = loop_write(fd, header, l, false);
- if (r < 0)
- return r;
-
- r = fd;
- fd = -1;
- return r;
-}
-
-_public_ int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) {
- int r;
- va_list ap;
-
- va_start(ap, format);
- r = sd_journal_printv_with_location(priority, file, line, func, format, ap);
- va_end(ap);
-
- return r;
-}
-
-_public_ int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) {
- char buffer[8 + LINE_MAX], p[sizeof("PRIORITY=")-1 + DECIMAL_STR_MAX(int) + 1];
- struct iovec iov[5];
- char *f;
-
- assert_return(priority >= 0, -EINVAL);
- assert_return(priority <= 7, -EINVAL);
- assert_return(format, -EINVAL);
-
- xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK);
-
- memcpy(buffer, "MESSAGE=", 8);
- vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap);
-
- /* func is initialized from __func__ which is not a macro, but
- * a static const char[], hence cannot easily be prefixed with
- * CODE_FUNC=, hence let's do it manually here. */
- ALLOCA_CODE_FUNC(f, func);
-
- zero(iov);
- IOVEC_SET_STRING(iov[0], buffer);
- IOVEC_SET_STRING(iov[1], p);
- IOVEC_SET_STRING(iov[2], file);
- IOVEC_SET_STRING(iov[3], line);
- IOVEC_SET_STRING(iov[4], f);
-
- return sd_journal_sendv(iov, ELEMENTSOF(iov));
-}
-
-_public_ int sd_journal_send_with_location(const char *file, const char *line, const char *func, const char *format, ...) {
- int r, i, j;
- va_list ap;
- struct iovec *iov = NULL;
- char *f;
-
- va_start(ap, format);
- i = fill_iovec_sprintf(format, ap, 3, &iov);
- va_end(ap);
-
- if (_unlikely_(i < 0)) {
- r = i;
- goto finish;
- }
-
- ALLOCA_CODE_FUNC(f, func);
-
- IOVEC_SET_STRING(iov[0], file);
- IOVEC_SET_STRING(iov[1], line);
- IOVEC_SET_STRING(iov[2], f);
-
- r = sd_journal_sendv(iov, i);
-
-finish:
- for (j = 3; j < i; j++)
- free(iov[j].iov_base);
-
- free(iov);
-
- return r;
-}
-
-_public_ int sd_journal_sendv_with_location(
- const char *file, const char *line,
- const char *func,
- const struct iovec *iov, int n) {
-
- struct iovec *niov;
- char *f;
-
- assert_return(iov, -EINVAL);
- assert_return(n > 0, -EINVAL);
-
- niov = alloca(sizeof(struct iovec) * (n + 3));
- memcpy(niov, iov, sizeof(struct iovec) * n);
-
- ALLOCA_CODE_FUNC(f, func);
-
- IOVEC_SET_STRING(niov[n++], file);
- IOVEC_SET_STRING(niov[n++], line);
- IOVEC_SET_STRING(niov[n++], f);
-
- return sd_journal_sendv(niov, n);
-}
-
-_public_ int sd_journal_perror_with_location(
- const char *file, const char *line,
- const char *func,
- const char *message) {
-
- struct iovec iov[6];
- char *f;
-
- ALLOCA_CODE_FUNC(f, func);
-
- IOVEC_SET_STRING(iov[0], file);
- IOVEC_SET_STRING(iov[1], line);
- IOVEC_SET_STRING(iov[2], f);
-
- return fill_iovec_perror_and_send(message, 3, iov);
-}
diff --git a/src/journal/journal-vacuum.c b/src/journal/journal-vacuum.c
deleted file mode 100644
index 05e97620ae..0000000000
--- a/src/journal/journal-vacuum.c
+++ /dev/null
@@ -1,349 +0,0 @@
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include "sd-id128.h"
-
-#include "alloc-util.h"
-#include "dirent-util.h"
-#include "fd-util.h"
-#include "journal-def.h"
-#include "journal-file.h"
-#include "journal-vacuum.h"
-#include "parse-util.h"
-#include "string-util.h"
-#include "util.h"
-#include "xattr-util.h"
-
-struct vacuum_info {
- uint64_t usage;
- char *filename;
-
- uint64_t realtime;
-
- sd_id128_t seqnum_id;
- uint64_t seqnum;
- bool have_seqnum;
-};
-
-static int vacuum_compare(const void *_a, const void *_b) {
- const struct vacuum_info *a, *b;
-
- a = _a;
- b = _b;
-
- if (a->have_seqnum && b->have_seqnum &&
- sd_id128_equal(a->seqnum_id, b->seqnum_id)) {
- if (a->seqnum < b->seqnum)
- return -1;
- else if (a->seqnum > b->seqnum)
- return 1;
- else
- return 0;
- }
-
- if (a->realtime < b->realtime)
- return -1;
- else if (a->realtime > b->realtime)
- return 1;
- else if (a->have_seqnum && b->have_seqnum)
- return memcmp(&a->seqnum_id, &b->seqnum_id, 16);
- else
- return strcmp(a->filename, b->filename);
-}
-
-static void patch_realtime(
- int fd,
- const char *fn,
- const struct stat *st,
- unsigned long long *realtime) {
-
- usec_t x, crtime = 0;
-
- /* The timestamp was determined by the file name, but let's
- * see if the file might actually be older than the file name
- * suggested... */
-
- assert(fd >= 0);
- assert(fn);
- assert(st);
- assert(realtime);
-
- x = timespec_load(&st->st_ctim);
- if (x > 0 && x != USEC_INFINITY && x < *realtime)
- *realtime = x;
-
- x = timespec_load(&st->st_atim);
- if (x > 0 && x != USEC_INFINITY && x < *realtime)
- *realtime = x;
-
- x = timespec_load(&st->st_mtim);
- if (x > 0 && x != USEC_INFINITY && x < *realtime)
- *realtime = x;
-
- /* Let's read the original creation time, if possible. Ideally
- * we'd just query the creation time the FS might provide, but
- * unfortunately there's currently no sane API to query
- * it. Hence let's implement this manually... */
-
- if (fd_getcrtime_at(fd, fn, &crtime, 0) >= 0) {
- if (crtime < *realtime)
- *realtime = crtime;
- }
-}
-
-static int journal_file_empty(int dir_fd, const char *name) {
- _cleanup_close_ int fd;
- struct stat st;
- le64_t n_entries;
- ssize_t n;
-
- fd = openat(dir_fd, name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK|O_NOATIME);
- if (fd < 0) {
- /* Maybe failed due to O_NOATIME and lack of privileges? */
- fd = openat(dir_fd, name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);
- if (fd < 0)
- return -errno;
- }
-
- if (fstat(fd, &st) < 0)
- return -errno;
-
- /* If an offline file doesn't even have a header we consider it empty */
- if (st.st_size < (off_t) sizeof(Header))
- return 1;
-
- /* If the number of entries is empty, we consider it empty, too */
- n = pread(fd, &n_entries, sizeof(n_entries), offsetof(Header, n_entries));
- if (n < 0)
- return -errno;
- if (n != sizeof(n_entries))
- return -EIO;
-
- return le64toh(n_entries) <= 0;
-}
-
-int journal_directory_vacuum(
- const char *directory,
- uint64_t max_use,
- uint64_t n_max_files,
- usec_t max_retention_usec,
- usec_t *oldest_usec,
- bool verbose) {
-
- _cleanup_closedir_ DIR *d = NULL;
- struct vacuum_info *list = NULL;
- unsigned n_list = 0, i, n_active_files = 0;
- size_t n_allocated = 0;
- uint64_t sum = 0, freed = 0;
- usec_t retention_limit = 0;
- char sbytes[FORMAT_BYTES_MAX];
- struct dirent *de;
- int r;
-
- assert(directory);
-
- if (max_use <= 0 && max_retention_usec <= 0 && n_max_files <= 0)
- return 0;
-
- if (max_retention_usec > 0) {
- retention_limit = now(CLOCK_REALTIME);
- if (retention_limit > max_retention_usec)
- retention_limit -= max_retention_usec;
- else
- max_retention_usec = retention_limit = 0;
- }
-
- d = opendir(directory);
- if (!d)
- return -errno;
-
- FOREACH_DIRENT_ALL(de, d, r = -errno; goto finish) {
-
- unsigned long long seqnum = 0, realtime;
- _cleanup_free_ char *p = NULL;
- sd_id128_t seqnum_id;
- bool have_seqnum;
- uint64_t size;
- struct stat st;
- size_t q;
-
- if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
- log_debug_errno(errno, "Failed to stat file %s while vacuuming, ignoring: %m", de->d_name);
- continue;
- }
-
- if (!S_ISREG(st.st_mode))
- continue;
-
- q = strlen(de->d_name);
-
- if (endswith(de->d_name, ".journal")) {
-
- /* Vacuum archived files. Active files are
- * left around */
-
- if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8) {
- n_active_files++;
- continue;
- }
-
- if (de->d_name[q-8-16-1] != '-' ||
- de->d_name[q-8-16-1-16-1] != '-' ||
- de->d_name[q-8-16-1-16-1-32-1] != '@') {
- n_active_files++;
- continue;
- }
-
- p = strdup(de->d_name);
- if (!p) {
- r = -ENOMEM;
- goto finish;
- }
-
- de->d_name[q-8-16-1-16-1] = 0;
- if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) {
- n_active_files++;
- continue;
- }
-
- if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) {
- n_active_files++;
- continue;
- }
-
- have_seqnum = true;
-
- } else if (endswith(de->d_name, ".journal~")) {
- unsigned long long tmp;
-
- /* Vacuum corrupted files */
-
- if (q < 1 + 16 + 1 + 16 + 8 + 1) {
- n_active_files ++;
- continue;
- }
-
- if (de->d_name[q-1-8-16-1] != '-' ||
- de->d_name[q-1-8-16-1-16-1] != '@') {
- n_active_files ++;
- continue;
- }
-
- p = strdup(de->d_name);
- if (!p) {
- r = -ENOMEM;
- goto finish;
- }
-
- if (sscanf(de->d_name + q-1-8-16-1-16, "%16llx-%16llx.journal~", &realtime, &tmp) != 2) {
- n_active_files ++;
- continue;
- }
-
- have_seqnum = false;
- } else {
- /* We do not vacuum unknown files! */
- log_debug("Not vacuuming unknown file %s.", de->d_name);
- continue;
- }
-
- size = 512UL * (uint64_t) st.st_blocks;
-
- r = journal_file_empty(dirfd(d), p);
- if (r < 0) {
- log_debug_errno(r, "Failed check if %s is empty, ignoring: %m", p);
- continue;
- }
- if (r > 0) {
- /* Always vacuum empty non-online files. */
-
- if (unlinkat(dirfd(d), p, 0) >= 0) {
-
- log_full(verbose ? LOG_INFO : LOG_DEBUG,
- "Deleted empty archived journal %s/%s (%s).", directory, p, format_bytes(sbytes, sizeof(sbytes), size));
-
- freed += size;
- } else if (errno != ENOENT)
- log_warning_errno(errno, "Failed to delete empty archived journal %s/%s: %m", directory, p);
-
- continue;
- }
-
- patch_realtime(dirfd(d), p, &st, &realtime);
-
- if (!GREEDY_REALLOC(list, n_allocated, n_list + 1)) {
- r = -ENOMEM;
- goto finish;
- }
-
- list[n_list].filename = p;
- list[n_list].usage = size;
- list[n_list].seqnum = seqnum;
- list[n_list].realtime = realtime;
- list[n_list].seqnum_id = seqnum_id;
- list[n_list].have_seqnum = have_seqnum;
- n_list ++;
-
- p = NULL;
- sum += size;
- }
-
- qsort_safe(list, n_list, sizeof(struct vacuum_info), vacuum_compare);
-
- for (i = 0; i < n_list; i++) {
- unsigned left;
-
- left = n_active_files + n_list - i;
-
- if ((max_retention_usec <= 0 || list[i].realtime >= retention_limit) &&
- (max_use <= 0 || sum <= max_use) &&
- (n_max_files <= 0 || left <= n_max_files))
- break;
-
- if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) {
- log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).", directory, list[i].filename, format_bytes(sbytes, sizeof(sbytes), list[i].usage));
- freed += list[i].usage;
-
- if (list[i].usage < sum)
- sum -= list[i].usage;
- else
- sum = 0;
-
- } else if (errno != ENOENT)
- log_warning_errno(errno, "Failed to delete archived journal %s/%s: %m", directory, list[i].filename);
- }
-
- if (oldest_usec && i < n_list && (*oldest_usec == 0 || list[i].realtime < *oldest_usec))
- *oldest_usec = list[i].realtime;
-
- r = 0;
-
-finish:
- for (i = 0; i < n_list; i++)
- free(list[i].filename);
- free(list);
-
- log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals on disk.", format_bytes(sbytes, sizeof(sbytes), freed));
-
- return r;
-}
diff --git a/src/journal/journal-vacuum.h b/src/journal/journal-vacuum.h
deleted file mode 100644
index 1e750a2170..0000000000
--- a/src/journal/journal-vacuum.h
+++ /dev/null
@@ -1,27 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <inttypes.h>
-#include <stdbool.h>
-
-#include "time-util.h"
-
-int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t n_max_files, usec_t max_retention_usec, usec_t *oldest_usec, bool verbose);
diff --git a/src/journal/journal-verify.c b/src/journal/journal-verify.c
deleted file mode 100644
index b968e89bb8..0000000000
--- a/src/journal/journal-verify.c
+++ /dev/null
@@ -1,1294 +0,0 @@
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <fcntl.h>
-#include <stddef.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#include "alloc-util.h"
-#include "compress.h"
-#include "fd-util.h"
-#include "fileio.h"
-#include "journal-authenticate.h"
-#include "journal-def.h"
-#include "journal-file.h"
-#include "journal-verify.h"
-#include "lookup3.h"
-#include "macro.h"
-#include "terminal-util.h"
-#include "util.h"
-
-static void draw_progress(uint64_t p, usec_t *last_usec) {
- unsigned n, i, j, k;
- usec_t z, x;
-
- if (!on_tty())
- return;
-
- z = now(CLOCK_MONOTONIC);
- x = *last_usec;
-
- if (x != 0 && x + 40 * USEC_PER_MSEC > z)
- return;
-
- *last_usec = z;
-
- n = (3 * columns()) / 4;
- j = (n * (unsigned) p) / 65535ULL;
- k = n - j;
-
- fputs("\r\x1B[?25l" ANSI_HIGHLIGHT_GREEN, stdout);
-
- for (i = 0; i < j; i++)
- fputs("\xe2\x96\x88", stdout);
-
- fputs(ANSI_NORMAL, stdout);
-
- for (i = 0; i < k; i++)
- fputs("\xe2\x96\x91", stdout);
-
- printf(" %3"PRIu64"%%", 100U * p / 65535U);
-
- fputs("\r\x1B[?25h", stdout);
- fflush(stdout);
-}
-
-static uint64_t scale_progress(uint64_t scale, uint64_t p, uint64_t m) {
-
- /* Calculates scale * p / m, but handles m == 0 safely, and saturates */
-
- if (p >= m || m == 0)
- return scale;
-
- return scale * p / m;
-}
-
-static void flush_progress(void) {
- unsigned n, i;
-
- if (!on_tty())
- return;
-
- n = (3 * columns()) / 4;
-
- putchar('\r');
-
- for (i = 0; i < n + 5; i++)
- putchar(' ');
-
- putchar('\r');
- fflush(stdout);
-}
-
-#define debug(_offset, _fmt, ...) do{ \
- flush_progress(); \
- log_debug(OFSfmt": " _fmt, _offset, ##__VA_ARGS__); \
- } while(0)
-
-#define warning(_offset, _fmt, ...) do{ \
- flush_progress(); \
- log_warning(OFSfmt": " _fmt, _offset, ##__VA_ARGS__); \
- } while(0)
-
-#define error(_offset, _fmt, ...) do{ \
- flush_progress(); \
- log_error(OFSfmt": " _fmt, (uint64_t)_offset, ##__VA_ARGS__); \
- } while(0)
-
-static int journal_file_object_verify(JournalFile *f, uint64_t offset, Object *o) {
- uint64_t i;
-
- assert(f);
- assert(offset);
- assert(o);
-
- /* This does various superficial tests about the length an
- * possible field values. It does not follow any references to
- * other objects. */
-
- if ((o->object.flags & OBJECT_COMPRESSED_XZ) &&
- o->object.type != OBJECT_DATA) {
- error(offset, "Found compressed object that isn't of type DATA, which is not allowed.");
- return -EBADMSG;
- }
-
- switch (o->object.type) {
-
- case OBJECT_DATA: {
- uint64_t h1, h2;
- int compression, r;
-
- if (le64toh(o->data.entry_offset) == 0)
- warning(offset, "Unused data (entry_offset==0)");
-
- if ((le64toh(o->data.entry_offset) == 0) ^ (le64toh(o->data.n_entries) == 0)) {
- error(offset, "Bad n_entries: %"PRIu64, o->data.n_entries);
- return -EBADMSG;
- }
-
- if (le64toh(o->object.size) - offsetof(DataObject, payload) <= 0) {
- error(offset, "Bad object size (<= %zu): %"PRIu64,
- offsetof(DataObject, payload),
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- h1 = le64toh(o->data.hash);
-
- compression = o->object.flags & OBJECT_COMPRESSION_MASK;
- if (compression) {
- _cleanup_free_ void *b = NULL;
- size_t alloc = 0, b_size;
-
- r = decompress_blob(compression,
- o->data.payload,
- le64toh(o->object.size) - offsetof(Object, data.payload),
- &b, &alloc, &b_size, 0);
- if (r < 0) {
- error(offset, "%s decompression failed: %s",
- object_compressed_to_string(compression), strerror(-r));
- return r;
- }
-
- h2 = hash64(b, b_size);
- } else
- h2 = hash64(o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload));
-
- if (h1 != h2) {
- error(offset, "Invalid hash (%08"PRIx64" vs. %08"PRIx64, h1, h2);
- return -EBADMSG;
- }
-
- if (!VALID64(o->data.next_hash_offset) ||
- !VALID64(o->data.next_field_offset) ||
- !VALID64(o->data.entry_offset) ||
- !VALID64(o->data.entry_array_offset)) {
- error(offset, "Invalid offset (next_hash_offset="OFSfmt", next_field_offset="OFSfmt", entry_offset="OFSfmt", entry_array_offset="OFSfmt,
- o->data.next_hash_offset,
- o->data.next_field_offset,
- o->data.entry_offset,
- o->data.entry_array_offset);
- return -EBADMSG;
- }
-
- break;
- }
-
- case OBJECT_FIELD:
- if (le64toh(o->object.size) - offsetof(FieldObject, payload) <= 0) {
- error(offset,
- "Bad field size (<= %zu): %"PRIu64,
- offsetof(FieldObject, payload),
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- if (!VALID64(o->field.next_hash_offset) ||
- !VALID64(o->field.head_data_offset)) {
- error(offset,
- "Invalid offset (next_hash_offset="OFSfmt", head_data_offset="OFSfmt,
- o->field.next_hash_offset,
- o->field.head_data_offset);
- return -EBADMSG;
- }
- break;
-
- case OBJECT_ENTRY:
- if ((le64toh(o->object.size) - offsetof(EntryObject, items)) % sizeof(EntryItem) != 0) {
- error(offset,
- "Bad entry size (<= %zu): %"PRIu64,
- offsetof(EntryObject, items),
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- if ((le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem) <= 0) {
- error(offset,
- "Invalid number items in entry: %"PRIu64,
- (le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem));
- return -EBADMSG;
- }
-
- if (le64toh(o->entry.seqnum) <= 0) {
- error(offset,
- "Invalid entry seqnum: %"PRIx64,
- le64toh(o->entry.seqnum));
- return -EBADMSG;
- }
-
- if (!VALID_REALTIME(le64toh(o->entry.realtime))) {
- error(offset,
- "Invalid entry realtime timestamp: %"PRIu64,
- le64toh(o->entry.realtime));
- return -EBADMSG;
- }
-
- if (!VALID_MONOTONIC(le64toh(o->entry.monotonic))) {
- error(offset,
- "Invalid entry monotonic timestamp: %"PRIu64,
- le64toh(o->entry.monotonic));
- return -EBADMSG;
- }
-
- for (i = 0; i < journal_file_entry_n_items(o); i++) {
- if (o->entry.items[i].object_offset == 0 ||
- !VALID64(o->entry.items[i].object_offset)) {
- error(offset,
- "Invalid entry item (%"PRIu64"/%"PRIu64" offset: "OFSfmt,
- i, journal_file_entry_n_items(o),
- o->entry.items[i].object_offset);
- return -EBADMSG;
- }
- }
-
- break;
-
- case OBJECT_DATA_HASH_TABLE:
- case OBJECT_FIELD_HASH_TABLE:
- if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) % sizeof(HashItem) != 0 ||
- (le64toh(o->object.size) - offsetof(HashTableObject, items)) / sizeof(HashItem) <= 0) {
- error(offset,
- "Invalid %s hash table size: %"PRIu64,
- o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field",
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- for (i = 0; i < journal_file_hash_table_n_items(o); i++) {
- if (o->hash_table.items[i].head_hash_offset != 0 &&
- !VALID64(le64toh(o->hash_table.items[i].head_hash_offset))) {
- error(offset,
- "Invalid %s hash table item (%"PRIu64"/%"PRIu64") head_hash_offset: "OFSfmt,
- o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field",
- i, journal_file_hash_table_n_items(o),
- le64toh(o->hash_table.items[i].head_hash_offset));
- return -EBADMSG;
- }
- if (o->hash_table.items[i].tail_hash_offset != 0 &&
- !VALID64(le64toh(o->hash_table.items[i].tail_hash_offset))) {
- error(offset,
- "Invalid %s hash table item (%"PRIu64"/%"PRIu64") tail_hash_offset: "OFSfmt,
- o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field",
- i, journal_file_hash_table_n_items(o),
- le64toh(o->hash_table.items[i].tail_hash_offset));
- return -EBADMSG;
- }
-
- if ((o->hash_table.items[i].head_hash_offset != 0) !=
- (o->hash_table.items[i].tail_hash_offset != 0)) {
- error(offset,
- "Invalid %s hash table item (%"PRIu64"/%"PRIu64"): head_hash_offset="OFSfmt" tail_hash_offset="OFSfmt,
- o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field",
- i, journal_file_hash_table_n_items(o),
- le64toh(o->hash_table.items[i].head_hash_offset),
- le64toh(o->hash_table.items[i].tail_hash_offset));
- return -EBADMSG;
- }
- }
-
- break;
-
- case OBJECT_ENTRY_ARRAY:
- if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) % sizeof(le64_t) != 0 ||
- (le64toh(o->object.size) - offsetof(EntryArrayObject, items)) / sizeof(le64_t) <= 0) {
- error(offset,
- "Invalid object entry array size: %"PRIu64,
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- if (!VALID64(o->entry_array.next_entry_array_offset)) {
- error(offset,
- "Invalid object entry array next_entry_array_offset: "OFSfmt,
- o->entry_array.next_entry_array_offset);
- return -EBADMSG;
- }
-
- for (i = 0; i < journal_file_entry_array_n_items(o); i++)
- if (le64toh(o->entry_array.items[i]) != 0 &&
- !VALID64(le64toh(o->entry_array.items[i]))) {
- error(offset,
- "Invalid object entry array item (%"PRIu64"/%"PRIu64"): "OFSfmt,
- i, journal_file_entry_array_n_items(o),
- le64toh(o->entry_array.items[i]));
- return -EBADMSG;
- }
-
- break;
-
- case OBJECT_TAG:
- if (le64toh(o->object.size) != sizeof(TagObject)) {
- error(offset,
- "Invalid object tag size: %"PRIu64,
- le64toh(o->object.size));
- return -EBADMSG;
- }
-
- if (!VALID_EPOCH(o->tag.epoch)) {
- error(offset,
- "Invalid object tag epoch: %"PRIu64,
- o->tag.epoch);
- return -EBADMSG;
- }
-
- break;
- }
-
- return 0;
-}
-
-static int write_uint64(int fd, uint64_t p) {
- ssize_t k;
-
- k = write(fd, &p, sizeof(p));
- if (k < 0)
- return -errno;
- if (k != sizeof(p))
- return -EIO;
-
- return 0;
-}
-
-static int contains_uint64(MMapCache *m, int fd, uint64_t n, uint64_t p) {
- uint64_t a, b;
- int r;
-
- assert(m);
- assert(fd >= 0);
-
- /* Bisection ... */
-
- a = 0; b = n;
- while (a < b) {
- uint64_t c, *z;
-
- c = (a + b) / 2;
-
- r = mmap_cache_get(m, fd, PROT_READ|PROT_WRITE, 0, false, c * sizeof(uint64_t), sizeof(uint64_t), NULL, (void **) &z);
- if (r < 0)
- return r;
-
- if (*z == p)
- return 1;
-
- if (a + 1 >= b)
- return 0;
-
- if (p < *z)
- b = c;
- else
- a = c;
- }
-
- return 0;
-}
-
-static int entry_points_to_data(
- JournalFile *f,
- int entry_fd,
- uint64_t n_entries,
- uint64_t entry_p,
- uint64_t data_p) {
-
- int r;
- uint64_t i, n, a;
- Object *o;
- bool found = false;
-
- assert(f);
- assert(entry_fd >= 0);
-
- if (!contains_uint64(f->mmap, entry_fd, n_entries, entry_p)) {
- error(data_p, "Data object references invalid entry at "OFSfmt, entry_p);
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, entry_p, &o);
- if (r < 0)
- return r;
-
- n = journal_file_entry_n_items(o);
- for (i = 0; i < n; i++)
- if (le64toh(o->entry.items[i].object_offset) == data_p) {
- found = true;
- break;
- }
-
- if (!found) {
- error(entry_p, "Data object at "OFSfmt" not referenced by linked entry", data_p);
- return -EBADMSG;
- }
-
- /* Check if this entry is also in main entry array. Since the
- * main entry array has already been verified we can rely on
- * its consistency. */
-
- i = 0;
- n = le64toh(f->header->n_entries);
- a = le64toh(f->header->entry_array_offset);
-
- while (i < n) {
- uint64_t m, u;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
-
- m = journal_file_entry_array_n_items(o);
- u = MIN(n - i, m);
-
- if (entry_p <= le64toh(o->entry_array.items[u-1])) {
- uint64_t x, y, z;
-
- x = 0;
- y = u;
-
- while (x < y) {
- z = (x + y) / 2;
-
- if (le64toh(o->entry_array.items[z]) == entry_p)
- return 0;
-
- if (x + 1 >= y)
- break;
-
- if (entry_p < le64toh(o->entry_array.items[z]))
- y = z;
- else
- x = z;
- }
-
- error(entry_p, "Entry object doesn't exist in main entry array");
- return -EBADMSG;
- }
-
- i += u;
- a = le64toh(o->entry_array.next_entry_array_offset);
- }
-
- return 0;
-}
-
-static int verify_data(
- JournalFile *f,
- Object *o, uint64_t p,
- int entry_fd, uint64_t n_entries,
- int entry_array_fd, uint64_t n_entry_arrays) {
-
- uint64_t i, n, a, last, q;
- int r;
-
- assert(f);
- assert(o);
- assert(entry_fd >= 0);
- assert(entry_array_fd >= 0);
-
- n = le64toh(o->data.n_entries);
- a = le64toh(o->data.entry_array_offset);
-
- /* Entry array means at least two objects */
- if (a && n < 2) {
- error(p, "Entry array present (entry_array_offset="OFSfmt", but n_entries=%"PRIu64")", a, n);
- return -EBADMSG;
- }
-
- if (n == 0)
- return 0;
-
- /* We already checked that earlier */
- assert(o->data.entry_offset);
-
- last = q = le64toh(o->data.entry_offset);
- r = entry_points_to_data(f, entry_fd, n_entries, q, p);
- if (r < 0)
- return r;
-
- i = 1;
- while (i < n) {
- uint64_t next, m, j;
-
- if (a == 0) {
- error(p, "Array chain too short");
- return -EBADMSG;
- }
-
- if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) {
- error(p, "Invalid array offset "OFSfmt, a);
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
-
- next = le64toh(o->entry_array.next_entry_array_offset);
- if (next != 0 && next <= a) {
- error(p, "Array chain has cycle (jumps back from "OFSfmt" to "OFSfmt")", a, next);
- return -EBADMSG;
- }
-
- m = journal_file_entry_array_n_items(o);
- for (j = 0; i < n && j < m; i++, j++) {
-
- q = le64toh(o->entry_array.items[j]);
- if (q <= last) {
- error(p, "Data object's entry array not sorted");
- return -EBADMSG;
- }
- last = q;
-
- r = entry_points_to_data(f, entry_fd, n_entries, q, p);
- if (r < 0)
- return r;
-
- /* Pointer might have moved, reposition */
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
- }
-
- a = next;
- }
-
- return 0;
-}
-
-static int verify_hash_table(
- JournalFile *f,
- int data_fd, uint64_t n_data,
- int entry_fd, uint64_t n_entries,
- int entry_array_fd, uint64_t n_entry_arrays,
- usec_t *last_usec,
- bool show_progress) {
-
- uint64_t i, n;
- int r;
-
- assert(f);
- assert(data_fd >= 0);
- assert(entry_fd >= 0);
- assert(entry_array_fd >= 0);
- assert(last_usec);
-
- n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
- if (n <= 0)
- return 0;
-
- r = journal_file_map_data_hash_table(f);
- if (r < 0)
- return log_error_errno(r, "Failed to map data hash table: %m");
-
- for (i = 0; i < n; i++) {
- uint64_t last = 0, p;
-
- if (show_progress)
- draw_progress(0xC000 + scale_progress(0x3FFF, i, n), last_usec);
-
- p = le64toh(f->data_hash_table[i].head_hash_offset);
- while (p != 0) {
- Object *o;
- uint64_t next;
-
- if (!contains_uint64(f->mmap, data_fd, n_data, p)) {
- error(p, "Invalid data object at hash entry %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- next = le64toh(o->data.next_hash_offset);
- if (next != 0 && next <= p) {
- error(p, "Hash chain has a cycle in hash entry %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- if (le64toh(o->data.hash) % n != i) {
- error(p, "Hash value mismatch in hash entry %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- r = verify_data(f, o, p, entry_fd, n_entries, entry_array_fd, n_entry_arrays);
- if (r < 0)
- return r;
-
- last = p;
- p = next;
- }
-
- if (last != le64toh(f->data_hash_table[i].tail_hash_offset)) {
- error(p, "Tail hash pointer mismatch in hash table");
- return -EBADMSG;
- }
- }
-
- return 0;
-}
-
-static int data_object_in_hash_table(JournalFile *f, uint64_t hash, uint64_t p) {
- uint64_t n, h, q;
- int r;
- assert(f);
-
- n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem);
- if (n <= 0)
- return 0;
-
- r = journal_file_map_data_hash_table(f);
- if (r < 0)
- return log_error_errno(r, "Failed to map data hash table: %m");
-
- h = hash % n;
-
- q = le64toh(f->data_hash_table[h].head_hash_offset);
- while (q != 0) {
- Object *o;
-
- if (p == q)
- return 1;
-
- r = journal_file_move_to_object(f, OBJECT_DATA, q, &o);
- if (r < 0)
- return r;
-
- q = le64toh(o->data.next_hash_offset);
- }
-
- return 0;
-}
-
-static int verify_entry(
- JournalFile *f,
- Object *o, uint64_t p,
- int data_fd, uint64_t n_data) {
-
- uint64_t i, n;
- int r;
-
- assert(f);
- assert(o);
- assert(data_fd >= 0);
-
- n = journal_file_entry_n_items(o);
- for (i = 0; i < n; i++) {
- uint64_t q, h;
- Object *u;
-
- q = le64toh(o->entry.items[i].object_offset);
- h = le64toh(o->entry.items[i].hash);
-
- if (!contains_uint64(f->mmap, data_fd, n_data, q)) {
- error(p, "Invalid data object of entry");
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_DATA, q, &u);
- if (r < 0)
- return r;
-
- if (le64toh(u->data.hash) != h) {
- error(p, "Hash mismatch for data object of entry");
- return -EBADMSG;
- }
-
- r = data_object_in_hash_table(f, h, q);
- if (r < 0)
- return r;
- if (r == 0) {
- error(p, "Data object missing from hash table");
- return -EBADMSG;
- }
- }
-
- return 0;
-}
-
-static int verify_entry_array(
- JournalFile *f,
- int data_fd, uint64_t n_data,
- int entry_fd, uint64_t n_entries,
- int entry_array_fd, uint64_t n_entry_arrays,
- usec_t *last_usec,
- bool show_progress) {
-
- uint64_t i = 0, a, n, last = 0;
- int r;
-
- assert(f);
- assert(data_fd >= 0);
- assert(entry_fd >= 0);
- assert(entry_array_fd >= 0);
- assert(last_usec);
-
- n = le64toh(f->header->n_entries);
- a = le64toh(f->header->entry_array_offset);
- while (i < n) {
- uint64_t next, m, j;
- Object *o;
-
- if (show_progress)
- draw_progress(0x8000 + scale_progress(0x3FFF, i, n), last_usec);
-
- if (a == 0) {
- error(a, "Array chain too short at %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) {
- error(a, "Invalid array %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
-
- next = le64toh(o->entry_array.next_entry_array_offset);
- if (next != 0 && next <= a) {
- error(a, "Array chain has cycle at %"PRIu64" of %"PRIu64" (jumps back from to "OFSfmt")", i, n, next);
- return -EBADMSG;
- }
-
- m = journal_file_entry_array_n_items(o);
- for (j = 0; i < n && j < m; i++, j++) {
- uint64_t p;
-
- p = le64toh(o->entry_array.items[j]);
- if (p <= last) {
- error(a, "Entry array not sorted at %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
- last = p;
-
- if (!contains_uint64(f->mmap, entry_fd, n_entries, p)) {
- error(a, "Invalid array entry at %"PRIu64" of %"PRIu64, i, n);
- return -EBADMSG;
- }
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
- if (r < 0)
- return r;
-
- r = verify_entry(f, o, p, data_fd, n_data);
- if (r < 0)
- return r;
-
- /* Pointer might have moved, reposition */
- r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
- if (r < 0)
- return r;
- }
-
- a = next;
- }
-
- return 0;
-}
-
-int journal_file_verify(
- JournalFile *f,
- const char *key,
- usec_t *first_contained, usec_t *last_validated, usec_t *last_contained,
- bool show_progress) {
- int r;
- Object *o;
- uint64_t p = 0, last_epoch = 0, last_tag_realtime = 0, last_sealed_realtime = 0;
-
- uint64_t entry_seqnum = 0, entry_monotonic = 0, entry_realtime = 0;
- sd_id128_t entry_boot_id;
- bool entry_seqnum_set = false, entry_monotonic_set = false, entry_realtime_set = false, found_main_entry_array = false;
- uint64_t n_weird = 0, n_objects = 0, n_entries = 0, n_data = 0, n_fields = 0, n_data_hash_tables = 0, n_field_hash_tables = 0, n_entry_arrays = 0, n_tags = 0;
- usec_t last_usec = 0;
- int data_fd = -1, entry_fd = -1, entry_array_fd = -1;
- unsigned i;
- bool found_last = false;
-#ifdef HAVE_GCRYPT
- uint64_t last_tag = 0;
-#endif
- assert(f);
-
- if (key) {
-#ifdef HAVE_GCRYPT
- r = journal_file_parse_verification_key(f, key);
- if (r < 0) {
- log_error("Failed to parse seed.");
- return r;
- }
-#else
- return -EOPNOTSUPP;
-#endif
- } else if (f->seal)
- return -ENOKEY;
-
- data_fd = open_tmpfile("/var/tmp", O_RDWR | O_CLOEXEC);
- if (data_fd < 0) {
- r = log_error_errno(data_fd, "Failed to create data file: %m");
- goto fail;
- }
-
- entry_fd = open_tmpfile("/var/tmp", O_RDWR | O_CLOEXEC);
- if (entry_fd < 0) {
- r = log_error_errno(entry_fd, "Failed to create entry file: %m");
- goto fail;
- }
-
- entry_array_fd = open_tmpfile("/var/tmp", O_RDWR | O_CLOEXEC);
- if (entry_array_fd < 0) {
- r = log_error_errno(entry_array_fd,
- "Failed to create entry array file: %m");
- goto fail;
- }
-
- if (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SUPPORTED) {
- log_error("Cannot verify file with unknown extensions.");
- r = -EOPNOTSUPP;
- goto fail;
- }
-
- for (i = 0; i < sizeof(f->header->reserved); i++)
- if (f->header->reserved[i] != 0) {
- error(offsetof(Header, reserved[i]), "Reserved field is non-zero");
- r = -EBADMSG;
- goto fail;
- }
-
- /* First iteration: we go through all objects, verify the
- * superficial structure, headers, hashes. */
-
- p = le64toh(f->header->header_size);
- for (;;) {
- /* Early exit if there are no objects in the file, at all */
- if (le64toh(f->header->tail_object_offset) == 0)
- break;
-
- if (show_progress)
- draw_progress(scale_progress(0x7FFF, p, le64toh(f->header->tail_object_offset)), &last_usec);
-
- r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
- if (r < 0) {
- error(p, "Invalid object");
- goto fail;
- }
-
- if (p > le64toh(f->header->tail_object_offset)) {
- error(offsetof(Header, tail_object_offset), "Invalid tail object pointer");
- r = -EBADMSG;
- goto fail;
- }
-
- n_objects ++;
-
- r = journal_file_object_verify(f, p, o);
- if (r < 0) {
- error(p, "Invalid object contents: %s", strerror(-r));
- goto fail;
- }
-
- if ((o->object.flags & OBJECT_COMPRESSED_XZ) &&
- (o->object.flags & OBJECT_COMPRESSED_LZ4)) {
- error(p, "Objected with double compression");
- r = -EINVAL;
- goto fail;
- }
-
- if ((o->object.flags & OBJECT_COMPRESSED_XZ) && !JOURNAL_HEADER_COMPRESSED_XZ(f->header)) {
- error(p, "XZ compressed object in file without XZ compression");
- r = -EBADMSG;
- goto fail;
- }
-
- if ((o->object.flags & OBJECT_COMPRESSED_LZ4) && !JOURNAL_HEADER_COMPRESSED_LZ4(f->header)) {
- error(p, "LZ4 compressed object in file without LZ4 compression");
- r = -EBADMSG;
- goto fail;
- }
-
- switch (o->object.type) {
-
- case OBJECT_DATA:
- r = write_uint64(data_fd, p);
- if (r < 0)
- goto fail;
-
- n_data++;
- break;
-
- case OBJECT_FIELD:
- n_fields++;
- break;
-
- case OBJECT_ENTRY:
- if (JOURNAL_HEADER_SEALED(f->header) && n_tags <= 0) {
- error(p, "First entry before first tag");
- r = -EBADMSG;
- goto fail;
- }
-
- r = write_uint64(entry_fd, p);
- if (r < 0)
- goto fail;
-
- if (le64toh(o->entry.realtime) < last_tag_realtime) {
- error(p, "Older entry after newer tag");
- r = -EBADMSG;
- goto fail;
- }
-
- if (!entry_seqnum_set &&
- le64toh(o->entry.seqnum) != le64toh(f->header->head_entry_seqnum)) {
- error(p, "Head entry sequence number incorrect");
- r = -EBADMSG;
- goto fail;
- }
-
- if (entry_seqnum_set &&
- entry_seqnum >= le64toh(o->entry.seqnum)) {
- error(p, "Entry sequence number out of synchronization");
- r = -EBADMSG;
- goto fail;
- }
-
- entry_seqnum = le64toh(o->entry.seqnum);
- entry_seqnum_set = true;
-
- if (entry_monotonic_set &&
- sd_id128_equal(entry_boot_id, o->entry.boot_id) &&
- entry_monotonic > le64toh(o->entry.monotonic)) {
- error(p, "Entry timestamp out of synchronization");
- r = -EBADMSG;
- goto fail;
- }
-
- entry_monotonic = le64toh(o->entry.monotonic);
- entry_boot_id = o->entry.boot_id;
- entry_monotonic_set = true;
-
- if (!entry_realtime_set &&
- le64toh(o->entry.realtime) != le64toh(f->header->head_entry_realtime)) {
- error(p, "Head entry realtime timestamp incorrect");
- r = -EBADMSG;
- goto fail;
- }
-
- entry_realtime = le64toh(o->entry.realtime);
- entry_realtime_set = true;
-
- n_entries ++;
- break;
-
- case OBJECT_DATA_HASH_TABLE:
- if (n_data_hash_tables > 1) {
- error(p, "More than one data hash table");
- r = -EBADMSG;
- goto fail;
- }
-
- if (le64toh(f->header->data_hash_table_offset) != p + offsetof(HashTableObject, items) ||
- le64toh(f->header->data_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
- error(p, "header fields for data hash table invalid");
- r = -EBADMSG;
- goto fail;
- }
-
- n_data_hash_tables++;
- break;
-
- case OBJECT_FIELD_HASH_TABLE:
- if (n_field_hash_tables > 1) {
- error(p, "More than one field hash table");
- r = -EBADMSG;
- goto fail;
- }
-
- if (le64toh(f->header->field_hash_table_offset) != p + offsetof(HashTableObject, items) ||
- le64toh(f->header->field_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
- error(p, "Header fields for field hash table invalid");
- r = -EBADMSG;
- goto fail;
- }
-
- n_field_hash_tables++;
- break;
-
- case OBJECT_ENTRY_ARRAY:
- r = write_uint64(entry_array_fd, p);
- if (r < 0)
- goto fail;
-
- if (p == le64toh(f->header->entry_array_offset)) {
- if (found_main_entry_array) {
- error(p, "More than one main entry array");
- r = -EBADMSG;
- goto fail;
- }
-
- found_main_entry_array = true;
- }
-
- n_entry_arrays++;
- break;
-
- case OBJECT_TAG:
- if (!JOURNAL_HEADER_SEALED(f->header)) {
- error(p, "Tag object in file without sealing");
- r = -EBADMSG;
- goto fail;
- }
-
- if (le64toh(o->tag.seqnum) != n_tags + 1) {
- error(p, "Tag sequence number out of synchronization");
- r = -EBADMSG;
- goto fail;
- }
-
- if (le64toh(o->tag.epoch) < last_epoch) {
- error(p, "Epoch sequence out of synchronization");
- r = -EBADMSG;
- goto fail;
- }
-
-#ifdef HAVE_GCRYPT
- if (f->seal) {
- uint64_t q, rt;
-
- debug(p, "Checking tag %"PRIu64"...", le64toh(o->tag.seqnum));
-
- rt = f->fss_start_usec + o->tag.epoch * f->fss_interval_usec;
- if (entry_realtime_set && entry_realtime >= rt + f->fss_interval_usec) {
- error(p, "tag/entry realtime timestamp out of synchronization");
- r = -EBADMSG;
- goto fail;
- }
-
- /* OK, now we know the epoch. So let's now set
- * it, and calculate the HMAC for everything
- * since the last tag. */
- r = journal_file_fsprg_seek(f, le64toh(o->tag.epoch));
- if (r < 0)
- goto fail;
-
- r = journal_file_hmac_start(f);
- if (r < 0)
- goto fail;
-
- if (last_tag == 0) {
- r = journal_file_hmac_put_header(f);
- if (r < 0)
- goto fail;
-
- q = le64toh(f->header->header_size);
- } else
- q = last_tag;
-
- while (q <= p) {
- r = journal_file_move_to_object(f, OBJECT_UNUSED, q, &o);
- if (r < 0)
- goto fail;
-
- r = journal_file_hmac_put_object(f, OBJECT_UNUSED, o, q);
- if (r < 0)
- goto fail;
-
- q = q + ALIGN64(le64toh(o->object.size));
- }
-
- /* Position might have changed, let's reposition things */
- r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
- if (r < 0)
- goto fail;
-
- if (memcmp(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH) != 0) {
- error(p, "Tag failed verification");
- r = -EBADMSG;
- goto fail;
- }
-
- f->hmac_running = false;
- last_tag_realtime = rt;
- last_sealed_realtime = entry_realtime;
- }
-
- last_tag = p + ALIGN64(le64toh(o->object.size));
-#endif
-
- last_epoch = le64toh(o->tag.epoch);
-
- n_tags ++;
- break;
-
- default:
- n_weird ++;
- }
-
- if (p == le64toh(f->header->tail_object_offset)) {
- found_last = true;
- break;
- }
-
- p = p + ALIGN64(le64toh(o->object.size));
- };
-
- if (!found_last && le64toh(f->header->tail_object_offset) != 0) {
- error(le64toh(f->header->tail_object_offset), "Tail object pointer dead");
- r = -EBADMSG;
- goto fail;
- }
-
- if (n_objects != le64toh(f->header->n_objects)) {
- error(offsetof(Header, n_objects), "Object number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (n_entries != le64toh(f->header->n_entries)) {
- error(offsetof(Header, n_entries), "Entry number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
- n_data != le64toh(f->header->n_data)) {
- error(offsetof(Header, n_data), "Data number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
- n_fields != le64toh(f->header->n_fields)) {
- error(offsetof(Header, n_fields), "Field number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_tags) &&
- n_tags != le64toh(f->header->n_tags)) {
- error(offsetof(Header, n_tags), "Tag number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays) &&
- n_entry_arrays != le64toh(f->header->n_entry_arrays)) {
- error(offsetof(Header, n_entry_arrays), "Entry array number mismatch");
- r = -EBADMSG;
- goto fail;
- }
-
- if (!found_main_entry_array && le64toh(f->header->entry_array_offset) != 0) {
- error(0, "Missing entry array");
- r = -EBADMSG;
- goto fail;
- }
-
- if (entry_seqnum_set &&
- entry_seqnum != le64toh(f->header->tail_entry_seqnum)) {
- error(offsetof(Header, tail_entry_seqnum), "Invalid tail seqnum");
- r = -EBADMSG;
- goto fail;
- }
-
- if (entry_monotonic_set &&
- (!sd_id128_equal(entry_boot_id, f->header->boot_id) ||
- entry_monotonic != le64toh(f->header->tail_entry_monotonic))) {
- error(0, "Invalid tail monotonic timestamp");
- r = -EBADMSG;
- goto fail;
- }
-
- if (entry_realtime_set && entry_realtime != le64toh(f->header->tail_entry_realtime)) {
- error(0, "Invalid tail realtime timestamp");
- r = -EBADMSG;
- goto fail;
- }
-
- /* Second iteration: we follow all objects referenced from the
- * two entry points: the object hash table and the entry
- * array. We also check that everything referenced (directly
- * or indirectly) in the data hash table also exists in the
- * entry array, and vice versa. Note that we do not care for
- * unreferenced objects. We only care that everything that is
- * referenced is consistent. */
-
- r = verify_entry_array(f,
- data_fd, n_data,
- entry_fd, n_entries,
- entry_array_fd, n_entry_arrays,
- &last_usec,
- show_progress);
- if (r < 0)
- goto fail;
-
- r = verify_hash_table(f,
- data_fd, n_data,
- entry_fd, n_entries,
- entry_array_fd, n_entry_arrays,
- &last_usec,
- show_progress);
- if (r < 0)
- goto fail;
-
- if (show_progress)
- flush_progress();
-
- mmap_cache_close_fd(f->mmap, data_fd);
- mmap_cache_close_fd(f->mmap, entry_fd);
- mmap_cache_close_fd(f->mmap, entry_array_fd);
-
- safe_close(data_fd);
- safe_close(entry_fd);
- safe_close(entry_array_fd);
-
- if (first_contained)
- *first_contained = le64toh(f->header->head_entry_realtime);
- if (last_validated)
- *last_validated = last_sealed_realtime;
- if (last_contained)
- *last_contained = le64toh(f->header->tail_entry_realtime);
-
- return 0;
-
-fail:
- if (show_progress)
- flush_progress();
-
- log_error("File corruption detected at %s:"OFSfmt" (of %llu bytes, %"PRIu64"%%).",
- f->path,
- p,
- (unsigned long long) f->last_stat.st_size,
- 100 * p / f->last_stat.st_size);
-
- if (data_fd >= 0) {
- mmap_cache_close_fd(f->mmap, data_fd);
- safe_close(data_fd);
- }
-
- if (entry_fd >= 0) {
- mmap_cache_close_fd(f->mmap, entry_fd);
- safe_close(entry_fd);
- }
-
- if (entry_array_fd >= 0) {
- mmap_cache_close_fd(f->mmap, entry_array_fd);
- safe_close(entry_array_fd);
- }
-
- return r;
-}
diff --git a/src/journal/journal-verify.h b/src/journal/journal-verify.h
deleted file mode 100644
index 8f0eaf6daa..0000000000
--- a/src/journal/journal-verify.h
+++ /dev/null
@@ -1,24 +0,0 @@
-#pragma once
-
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include "journal-file.h"
-
-int journal_file_verify(JournalFile *f, const char *key, usec_t *first_contained, usec_t *last_validated, usec_t *last_contained, bool show_progress);
diff --git a/src/journal/journalctl.c b/src/journal/journalctl.c
index 273242bea6..1670978466 100644
--- a/src/journal/journalctl.c
+++ b/src/journal/journalctl.c
@@ -33,8 +33,8 @@
#include <sys/stat.h>
#include <unistd.h>
-#include "sd-bus.h"
-#include "sd-journal.h"
+#include <systemd/sd-bus.h>
+#include <systemd/sd-journal.h>
#include "acl-util.h"
#include "alloc-util.h"
diff --git a/src/journal/journald-kmsg.c b/src/journal/journald-kmsg.c
index eb1ac90e98..1ac57bb361 100644
--- a/src/journal/journald-kmsg.c
+++ b/src/journal/journald-kmsg.c
@@ -24,7 +24,7 @@
#include <unistd.h>
#include "libudev.h"
-#include "sd-messages.h"
+#include <systemd/sd-messages.h>
#include "escape.h"
#include "fd-util.h"
diff --git a/src/journal/journald-server.c b/src/journal/journald-server.c
index ee2db8d29f..4f53bf01c3 100644
--- a/src/journal/journald-server.c
+++ b/src/journal/journald-server.c
@@ -27,9 +27,9 @@
#include <linux/sockios.h>
#include "libudev.h"
-#include "sd-daemon.h"
-#include "sd-journal.h"
-#include "sd-messages.h"
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-journal.h>
+#include <systemd/sd-messages.h>
#include "acl-util.h"
#include "alloc-util.h"
diff --git a/src/journal/journald-server.h b/src/journal/journald-server.h
index b9551dda1b..cb8a5bbe9b 100644
--- a/src/journal/journald-server.h
+++ b/src/journal/journald-server.h
@@ -22,7 +22,7 @@
#include <stdbool.h>
#include <sys/types.h>
-#include "sd-event.h"
+#include <systemd/sd-event.h>
typedef struct Server Server;
diff --git a/src/journal/journald-stream.c b/src/journal/journald-stream.c
index 6e8b405b53..583b1305ae 100644
--- a/src/journal/journald-stream.c
+++ b/src/journal/journald-stream.c
@@ -24,8 +24,8 @@
#include <selinux/selinux.h>
#endif
-#include "sd-daemon.h"
-#include "sd-event.h"
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-event.h>
#include "alloc-util.h"
#include "dirent-util.h"
diff --git a/src/journal/journald-syslog.c b/src/journal/journald-syslog.c
index 5153fd0cce..480a1cc405 100644
--- a/src/journal/journald-syslog.c
+++ b/src/journal/journald-syslog.c
@@ -21,7 +21,7 @@
#include <sys/epoll.h>
#include <unistd.h>
-#include "sd-messages.h"
+#include <systemd/sd-messages.h>
#include "alloc-util.h"
#include "fd-util.h"
diff --git a/src/journal/journald.c b/src/journal/journald.c
index 272acb71c4..1afe44fa8e 100644
--- a/src/journal/journald.c
+++ b/src/journal/journald.c
@@ -19,8 +19,8 @@
#include <unistd.h>
-#include "sd-daemon.h"
-#include "sd-messages.h"
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-messages.h>
#include "formats-util.h"
#include "journal-authenticate.h"
diff --git a/src/journal/lookup3.c b/src/journal/lookup3.c
deleted file mode 100644
index 3d791234f4..0000000000
--- a/src/journal/lookup3.c
+++ /dev/null
@@ -1,1009 +0,0 @@
-/* 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 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 <stdint.h> /* defines uint32_t etc */
-#include <stdio.h> /* defines printf for tests */
-#include <sys/param.h> /* attempt to define endianness */
-#include <time.h> /* defines time_t for timings in the test */
-#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
- * noticeably 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 */
- {
- const uint8_t *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
- * noticeably 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 */
-
- {
- const uint8_t *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
- * noticeably 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 */
-
- {
- const uint8_t *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
deleted file mode 100644
index 787921ffbf..0000000000
--- a/src/journal/lookup3.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#pragma once
-
-#include <inttypes.h>
-#include <sys/types.h>
-
-#include "macro.h"
-
-uint32_t jenkins_hashword(const uint32_t *k, size_t length, uint32_t initval) _pure_;
-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) _pure_;
-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) _pure_;
-
-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;
-}
diff --git a/src/journal/mmap-cache.c b/src/journal/mmap-cache.c
deleted file mode 100644
index 9c0ce8ccbf..0000000000
--- a/src/journal/mmap-cache.c
+++ /dev/null
@@ -1,725 +0,0 @@
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-
-#include "alloc-util.h"
-#include "fd-util.h"
-#include "hashmap.h"
-#include "list.h"
-#include "log.h"
-#include "macro.h"
-#include "mmap-cache.h"
-#include "sigbus.h"
-#include "util.h"
-
-typedef struct Window Window;
-typedef struct Context Context;
-typedef struct FileDescriptor FileDescriptor;
-
-struct Window {
- MMapCache *cache;
-
- bool invalidated:1;
- bool keep_always:1;
- bool in_unused:1;
-
- int prot;
- void *ptr;
- uint64_t offset;
- size_t size;
-
- FileDescriptor *fd;
-
- LIST_FIELDS(Window, by_fd);
- LIST_FIELDS(Window, unused);
-
- LIST_HEAD(Context, contexts);
-};
-
-struct Context {
- MMapCache *cache;
- unsigned id;
- Window *window;
-
- LIST_FIELDS(Context, by_window);
-};
-
-struct FileDescriptor {
- MMapCache *cache;
- int fd;
- bool sigbus;
- LIST_HEAD(Window, windows);
-};
-
-struct MMapCache {
- int n_ref;
- unsigned n_windows;
-
- unsigned n_hit, n_missed;
-
- Hashmap *fds;
- Context *contexts[MMAP_CACHE_MAX_CONTEXTS];
-
- LIST_HEAD(Window, unused);
- Window *last_unused;
-};
-
-#define WINDOWS_MIN 64
-
-#ifdef ENABLE_DEBUG_MMAP_CACHE
-/* Tiny windows increase mmap activity and the chance of exposing unsafe use. */
-# define WINDOW_SIZE (page_size())
-#else
-# define WINDOW_SIZE (8ULL*1024ULL*1024ULL)
-#endif
-
-MMapCache* mmap_cache_new(void) {
- MMapCache *m;
-
- m = new0(MMapCache, 1);
- if (!m)
- return NULL;
-
- m->n_ref = 1;
- return m;
-}
-
-MMapCache* mmap_cache_ref(MMapCache *m) {
- assert(m);
- assert(m->n_ref > 0);
-
- m->n_ref ++;
- return m;
-}
-
-static void window_unlink(Window *w) {
- Context *c;
-
- assert(w);
-
- if (w->ptr)
- munmap(w->ptr, w->size);
-
- if (w->fd)
- LIST_REMOVE(by_fd, w->fd->windows, w);
-
- if (w->in_unused) {
- if (w->cache->last_unused == w)
- w->cache->last_unused = w->unused_prev;
-
- LIST_REMOVE(unused, w->cache->unused, w);
- }
-
- LIST_FOREACH(by_window, c, w->contexts) {
- assert(c->window == w);
- c->window = NULL;
- }
-}
-
-static void window_invalidate(Window *w) {
- assert(w);
-
- if (w->invalidated)
- return;
-
- /* Replace the window with anonymous pages. This is useful
- * when we hit a SIGBUS and want to make sure the file cannot
- * trigger any further SIGBUS, possibly overrunning the sigbus
- * queue. */
-
- assert_se(mmap(w->ptr, w->size, w->prot, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == w->ptr);
- w->invalidated = true;
-}
-
-static void window_free(Window *w) {
- assert(w);
-
- window_unlink(w);
- w->cache->n_windows--;
- free(w);
-}
-
-_pure_ static bool window_matches(Window *w, int fd, int prot, uint64_t offset, size_t size) {
- assert(w);
- assert(fd >= 0);
- assert(size > 0);
-
- return
- w->fd &&
- fd == w->fd->fd &&
- prot == w->prot &&
- offset >= w->offset &&
- offset + size <= w->offset + w->size;
-}
-
-static Window *window_add(MMapCache *m, FileDescriptor *fd, int prot, bool keep_always, uint64_t offset, size_t size, void *ptr) {
- Window *w;
-
- assert(m);
- assert(fd);
-
- if (!m->last_unused || m->n_windows <= WINDOWS_MIN) {
-
- /* Allocate a new window */
- w = new0(Window, 1);
- if (!w)
- return NULL;
- m->n_windows++;
- } else {
-
- /* Reuse an existing one */
- w = m->last_unused;
- window_unlink(w);
- zero(*w);
- }
-
- w->cache = m;
- w->fd = fd;
- w->prot = prot;
- w->keep_always = keep_always;
- w->offset = offset;
- w->size = size;
- w->ptr = ptr;
-
- LIST_PREPEND(by_fd, fd->windows, w);
-
- return w;
-}
-
-static void context_detach_window(Context *c) {
- Window *w;
-
- assert(c);
-
- if (!c->window)
- return;
-
- w = c->window;
- c->window = NULL;
- LIST_REMOVE(by_window, w->contexts, c);
-
- if (!w->contexts && !w->keep_always) {
- /* Not used anymore? */
-#ifdef ENABLE_DEBUG_MMAP_CACHE
- /* Unmap unused windows immediately to expose use-after-unmap
- * by SIGSEGV. */
- window_free(w);
-#else
- LIST_PREPEND(unused, c->cache->unused, w);
- if (!c->cache->last_unused)
- c->cache->last_unused = w;
-
- w->in_unused = true;
-#endif
- }
-}
-
-static void context_attach_window(Context *c, Window *w) {
- assert(c);
- assert(w);
-
- if (c->window == w)
- return;
-
- context_detach_window(c);
-
- if (w->in_unused) {
- /* Used again? */
- LIST_REMOVE(unused, c->cache->unused, w);
- if (c->cache->last_unused == w)
- c->cache->last_unused = w->unused_prev;
-
- w->in_unused = false;
- }
-
- c->window = w;
- LIST_PREPEND(by_window, w->contexts, c);
-}
-
-static Context *context_add(MMapCache *m, unsigned id) {
- Context *c;
-
- assert(m);
-
- c = m->contexts[id];
- if (c)
- return c;
-
- c = new0(Context, 1);
- if (!c)
- return NULL;
-
- c->cache = m;
- c->id = id;
-
- assert(!m->contexts[id]);
- m->contexts[id] = c;
-
- return c;
-}
-
-static void context_free(Context *c) {
- assert(c);
-
- context_detach_window(c);
-
- if (c->cache) {
- assert(c->cache->contexts[c->id] == c);
- c->cache->contexts[c->id] = NULL;
- }
-
- free(c);
-}
-
-static void fd_free(FileDescriptor *f) {
- assert(f);
-
- while (f->windows)
- window_free(f->windows);
-
- if (f->cache)
- assert_se(hashmap_remove(f->cache->fds, FD_TO_PTR(f->fd)));
-
- free(f);
-}
-
-static FileDescriptor* fd_add(MMapCache *m, int fd) {
- FileDescriptor *f;
- int r;
-
- assert(m);
- assert(fd >= 0);
-
- f = hashmap_get(m->fds, FD_TO_PTR(fd));
- if (f)
- return f;
-
- r = hashmap_ensure_allocated(&m->fds, NULL);
- if (r < 0)
- return NULL;
-
- f = new0(FileDescriptor, 1);
- if (!f)
- return NULL;
-
- f->cache = m;
- f->fd = fd;
-
- r = hashmap_put(m->fds, FD_TO_PTR(fd), f);
- if (r < 0) {
- free(f);
- return NULL;
- }
-
- return f;
-}
-
-static void mmap_cache_free(MMapCache *m) {
- FileDescriptor *f;
- int i;
-
- assert(m);
-
- for (i = 0; i < MMAP_CACHE_MAX_CONTEXTS; i++)
- if (m->contexts[i])
- context_free(m->contexts[i]);
-
- while ((f = hashmap_first(m->fds)))
- fd_free(f);
-
- hashmap_free(m->fds);
-
- while (m->unused)
- window_free(m->unused);
-
- free(m);
-}
-
-MMapCache* mmap_cache_unref(MMapCache *m) {
-
- if (!m)
- return NULL;
-
- assert(m->n_ref > 0);
-
- m->n_ref --;
- if (m->n_ref == 0)
- mmap_cache_free(m);
-
- return NULL;
-}
-
-static int make_room(MMapCache *m) {
- assert(m);
-
- if (!m->last_unused)
- return 0;
-
- window_free(m->last_unused);
- return 1;
-}
-
-static int try_context(
- MMapCache *m,
- int fd,
- int prot,
- unsigned context,
- bool keep_always,
- uint64_t offset,
- size_t size,
- void **ret) {
-
- Context *c;
-
- assert(m);
- assert(m->n_ref > 0);
- assert(fd >= 0);
- assert(size > 0);
- assert(ret);
-
- c = m->contexts[context];
- if (!c)
- return 0;
-
- assert(c->id == context);
-
- if (!c->window)
- return 0;
-
- if (!window_matches(c->window, fd, prot, offset, size)) {
-
- /* Drop the reference to the window, since it's unnecessary now */
- context_detach_window(c);
- return 0;
- }
-
- if (c->window->fd->sigbus)
- return -EIO;
-
- c->window->keep_always = c->window->keep_always || keep_always;
-
- *ret = (uint8_t*) c->window->ptr + (offset - c->window->offset);
- return 1;
-}
-
-static int find_mmap(
- MMapCache *m,
- int fd,
- int prot,
- unsigned context,
- bool keep_always,
- uint64_t offset,
- size_t size,
- void **ret) {
-
- FileDescriptor *f;
- Window *w;
- Context *c;
-
- assert(m);
- assert(m->n_ref > 0);
- assert(fd >= 0);
- assert(size > 0);
-
- f = hashmap_get(m->fds, FD_TO_PTR(fd));
- if (!f)
- return 0;
-
- assert(f->fd == fd);
-
- if (f->sigbus)
- return -EIO;
-
- LIST_FOREACH(by_fd, w, f->windows)
- if (window_matches(w, fd, prot, offset, size))
- break;
-
- if (!w)
- return 0;
-
- c = context_add(m, context);
- if (!c)
- return -ENOMEM;
-
- context_attach_window(c, w);
- w->keep_always = w->keep_always || keep_always;
-
- *ret = (uint8_t*) w->ptr + (offset - w->offset);
- return 1;
-}
-
-static int mmap_try_harder(MMapCache *m, void *addr, int fd, int prot, int flags, uint64_t offset, size_t size, void **res) {
- void *ptr;
-
- assert(m);
- assert(fd >= 0);
- assert(res);
-
- for (;;) {
- int r;
-
- ptr = mmap(addr, size, prot, flags, fd, offset);
- if (ptr != MAP_FAILED)
- break;
- if (errno != ENOMEM)
- return -errno;
-
- r = make_room(m);
- if (r < 0)
- return r;
- if (r == 0)
- return -ENOMEM;
- }
-
- *res = ptr;
- return 0;
-}
-
-static int add_mmap(
- MMapCache *m,
- int fd,
- int prot,
- unsigned context,
- bool keep_always,
- uint64_t offset,
- size_t size,
- struct stat *st,
- void **ret) {
-
- uint64_t woffset, wsize;
- Context *c;
- FileDescriptor *f;
- Window *w;
- void *d;
- int r;
-
- assert(m);
- assert(m->n_ref > 0);
- assert(fd >= 0);
- assert(size > 0);
- assert(ret);
-
- woffset = offset & ~((uint64_t) page_size() - 1ULL);
- wsize = size + (offset - woffset);
- wsize = PAGE_ALIGN(wsize);
-
- if (wsize < WINDOW_SIZE) {
- uint64_t delta;
-
- delta = PAGE_ALIGN((WINDOW_SIZE - wsize) / 2);
-
- if (delta > offset)
- woffset = 0;
- else
- woffset -= delta;
-
- wsize = WINDOW_SIZE;
- }
-
- if (st) {
- /* Memory maps that are larger then the files
- underneath have undefined behavior. Hence, clamp
- things to the file size if we know it */
-
- if (woffset >= (uint64_t) st->st_size)
- return -EADDRNOTAVAIL;
-
- if (woffset + wsize > (uint64_t) st->st_size)
- wsize = PAGE_ALIGN(st->st_size - woffset);
- }
-
- r = mmap_try_harder(m, NULL, fd, prot, MAP_SHARED, woffset, wsize, &d);
- if (r < 0)
- return r;
-
- c = context_add(m, context);
- if (!c)
- goto outofmem;
-
- f = fd_add(m, fd);
- if (!f)
- goto outofmem;
-
- w = window_add(m, f, prot, keep_always, woffset, wsize, d);
- if (!w)
- goto outofmem;
-
- context_detach_window(c);
- c->window = w;
- LIST_PREPEND(by_window, w->contexts, c);
-
- *ret = (uint8_t*) w->ptr + (offset - w->offset);
- return 1;
-
-outofmem:
- munmap(d, wsize);
- return -ENOMEM;
-}
-
-int mmap_cache_get(
- MMapCache *m,
- int fd,
- int prot,
- unsigned context,
- bool keep_always,
- uint64_t offset,
- size_t size,
- struct stat *st,
- void **ret) {
-
- int r;
-
- assert(m);
- assert(m->n_ref > 0);
- assert(fd >= 0);
- assert(size > 0);
- assert(ret);
- assert(context < MMAP_CACHE_MAX_CONTEXTS);
-
- /* Check whether the current context is the right one already */
- r = try_context(m, fd, prot, context, keep_always, offset, size, ret);
- if (r != 0) {
- m->n_hit ++;
- return r;
- }
-
- /* Search for a matching mmap */
- r = find_mmap(m, fd, prot, context, keep_always, offset, size, ret);
- if (r != 0) {
- m->n_hit ++;
- return r;
- }
-
- m->n_missed++;
-
- /* Create a new mmap */
- return add_mmap(m, fd, prot, context, keep_always, offset, size, st, ret);
-}
-
-unsigned mmap_cache_get_hit(MMapCache *m) {
- assert(m);
-
- return m->n_hit;
-}
-
-unsigned mmap_cache_get_missed(MMapCache *m) {
- assert(m);
-
- return m->n_missed;
-}
-
-static void mmap_cache_process_sigbus(MMapCache *m) {
- bool found = false;
- FileDescriptor *f;
- Iterator i;
- int r;
-
- assert(m);
-
- /* Iterate through all triggered pages and mark their files as
- * invalidated */
- for (;;) {
- bool ours;
- void *addr;
-
- r = sigbus_pop(&addr);
- if (_likely_(r == 0))
- break;
- if (r < 0) {
- log_error_errno(r, "SIGBUS handling failed: %m");
- abort();
- }
-
- ours = false;
- HASHMAP_FOREACH(f, m->fds, i) {
- Window *w;
-
- LIST_FOREACH(by_fd, w, f->windows) {
- if ((uint8_t*) addr >= (uint8_t*) w->ptr &&
- (uint8_t*) addr < (uint8_t*) w->ptr + w->size) {
- found = ours = f->sigbus = true;
- break;
- }
- }
-
- if (ours)
- break;
- }
-
- /* Didn't find a matching window, give up */
- if (!ours) {
- log_error("Unknown SIGBUS page, aborting.");
- abort();
- }
- }
-
- /* The list of triggered pages is now empty. Now, let's remap
- * all windows of the triggered file to anonymous maps, so
- * that no page of the file in question is triggered again, so
- * that we can be sure not to hit the queue size limit. */
- if (_likely_(!found))
- return;
-
- HASHMAP_FOREACH(f, m->fds, i) {
- Window *w;
-
- if (!f->sigbus)
- continue;
-
- LIST_FOREACH(by_fd, w, f->windows)
- window_invalidate(w);
- }
-}
-
-bool mmap_cache_got_sigbus(MMapCache *m, int fd) {
- FileDescriptor *f;
-
- assert(m);
- assert(fd >= 0);
-
- mmap_cache_process_sigbus(m);
-
- f = hashmap_get(m->fds, FD_TO_PTR(fd));
- if (!f)
- return false;
-
- return f->sigbus;
-}
-
-void mmap_cache_close_fd(MMapCache *m, int fd) {
- FileDescriptor *f;
-
- assert(m);
- assert(fd >= 0);
-
- /* Make sure that any queued SIGBUS are first dispatched, so
- * that we don't end up with a SIGBUS entry we cannot relate
- * to any existing memory map */
-
- mmap_cache_process_sigbus(m);
-
- f = hashmap_get(m->fds, FD_TO_PTR(fd));
- if (!f)
- return;
-
- fd_free(f);
-}
diff --git a/src/journal/mmap-cache.h b/src/journal/mmap-cache.h
deleted file mode 100644
index 199d944647..0000000000
--- a/src/journal/mmap-cache.h
+++ /dev/null
@@ -1,49 +0,0 @@
-#pragma once
-
-/***
- This file is part of systemd.
-
- Copyright 2012 Lennart Poettering
-
- systemd is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <stdbool.h>
-#include <sys/stat.h>
-
-/* One context per object type, plus one of the header, plus one "additional" one */
-#define MMAP_CACHE_MAX_CONTEXTS 9
-
-typedef struct MMapCache MMapCache;
-
-MMapCache* mmap_cache_new(void);
-MMapCache* mmap_cache_ref(MMapCache *m);
-MMapCache* mmap_cache_unref(MMapCache *m);
-
-int mmap_cache_get(
- MMapCache *m,
- int fd,
- int prot,
- unsigned context,
- bool keep_always,
- uint64_t offset,
- size_t size,
- struct stat *st,
- void **ret);
-void mmap_cache_close_fd(MMapCache *m, int fd);
-
-unsigned mmap_cache_get_hit(MMapCache *m);
-unsigned mmap_cache_get_missed(MMapCache *m);
-
-bool mmap_cache_got_sigbus(MMapCache *m, int fd);
diff --git a/src/journal/sd-journal.c b/src/journal/sd-journal.c
deleted file mode 100644
index 5a2a28a8d4..0000000000
--- a/src/journal/sd-journal.c
+++ /dev/null
@@ -1,2800 +0,0 @@
-/***
- 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 Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with systemd; If not, see <http://www.gnu.org/licenses/>.
-***/
-
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/magic.h>
-#include <poll.h>
-#include <stddef.h>
-#include <sys/inotify.h>
-#include <sys/vfs.h>
-#include <unistd.h>
-
-#include "sd-journal.h"
-
-#include "alloc-util.h"
-#include "catalog.h"
-#include "compress.h"
-#include "dirent-util.h"
-#include "fd-util.h"
-#include "fileio.h"
-#include "formats-util.h"
-#include "fs-util.h"
-#include "hashmap.h"
-#include "hostname-util.h"
-#include "io-util.h"
-#include "journal-def.h"
-#include "journal-file.h"
-#include "journal-internal.h"
-#include "list.h"
-#include "lookup3.h"
-#include "missing.h"
-#include "path-util.h"
-#include "replace-var.h"
-#include "stat-util.h"
-#include "stdio-util.h"
-#include "string-util.h"
-#include "strv.h"
-
-#define JOURNAL_FILES_MAX 7168
-
-#define JOURNAL_FILES_RECHECK_USEC (2 * USEC_PER_SEC)
-
-#define REPLACE_VAR_MAX 256
-
-#define DEFAULT_DATA_THRESHOLD (64*1024)
-
-static void remove_file_real(sd_journal *j, JournalFile *f);
-
-static bool journal_pid_changed(sd_journal *j) {
- assert(j);
-
- /* We don't support people creating a journal object and
- * keeping it around over a fork(). Let's complain. */
-
- return j->original_pid != getpid();
-}
-
-static int journal_put_error(sd_journal *j, int r, const char *path) {
- char *copy;
- int k;
-
- /* Memorize an error we encountered, and store which
- * file/directory it was generated from. Note that we store
- * only *one* path per error code, as the error code is the
- * key into the hashmap, and the path is the value. This means
- * we keep track only of all error kinds, but not of all error
- * locations. This has the benefit that the hashmap cannot
- * grow beyond bounds.
- *
- * We return an error here only if we didn't manage to
- * memorize the real error. */
-
- if (r >= 0)
- return r;
-
- k = hashmap_ensure_allocated(&j->errors, NULL);
- if (k < 0)
- return k;
-
- if (path) {
- copy = strdup(path);
- if (!copy)
- return -ENOMEM;
- } else
- copy = NULL;
-
- k = hashmap_put(j->errors, INT_TO_PTR(r), copy);
- if (k < 0) {
- free(copy);
-
- if (k == -EEXIST)
- return 0;
-
- return k;
- }
-
- return 0;
-}
-
-static void detach_location(sd_journal *j) {
- Iterator i;
- JournalFile *f;
-
- assert(j);
-
- j->current_file = NULL;
- j->current_field = 0;
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i)
- journal_file_reset_location(f);
-}
-
-static void reset_location(sd_journal *j) {
- assert(j);
-
- detach_location(j);
- zero(j->current_location);
-}
-
-static void init_location(Location *l, LocationType type, JournalFile *f, Object *o) {
- assert(l);
- assert(type == LOCATION_DISCRETE || type == LOCATION_SEEK);
- assert(f);
- assert(o->object.type == OBJECT_ENTRY);
-
- l->type = type;
- l->seqnum = le64toh(o->entry.seqnum);
- l->seqnum_id = f->header->seqnum_id;
- l->realtime = le64toh(o->entry.realtime);
- l->monotonic = le64toh(o->entry.monotonic);
- l->boot_id = o->entry.boot_id;
- l->xor_hash = le64toh(o->entry.xor_hash);
-
- l->seqnum_set = l->realtime_set = l->monotonic_set = l->xor_hash_set = true;
-}
-
-static void set_location(sd_journal *j, JournalFile *f, Object *o) {
- assert(j);
- assert(f);
- assert(o);
-
- init_location(&j->current_location, LOCATION_DISCRETE, f, o);
-
- j->current_file = f;
- j->current_field = 0;
-
- /* Let f know its candidate entry was picked. */
- assert(f->location_type == LOCATION_SEEK);
- f->location_type = LOCATION_DISCRETE;
-}
-
-static int match_is_valid(const void *data, size_t size) {
- const char *b, *p;
-
- assert(data);
-
- if (size < 2)
- return false;
-
- if (startswith(data, "__"))
- return false;
-
- b = data;
- for (p = b; p < b + size; p++) {
-
- if (*p == '=')
- return p > b;
-
- if (*p == '_')
- continue;
-
- if (*p >= 'A' && *p <= 'Z')
- continue;
-
- if (*p >= '0' && *p <= '9')
- continue;
-
- return false;
- }
-
- return false;
-}
-
-static bool same_field(const void *_a, size_t s, const void *_b, size_t t) {
- const uint8_t *a = _a, *b = _b;
- size_t j;
-
- for (j = 0; j < s && j < t; j++) {
-
- if (a[j] != b[j])
- return false;
-
- if (a[j] == '=')
- return true;
- }
-
- assert_not_reached("\"=\" not found");
-}
-
-static Match *match_new(Match *p, MatchType t) {
- Match *m;
-
- m = new0(Match, 1);
- if (!m)
- return NULL;
-
- m->type = t;
-
- if (p) {
- m->parent = p;
- LIST_PREPEND(matches, p->matches, m);
- }
-
- return m;
-}
-
-static void match_free(Match *m) {
- assert(m);
-
- while (m->matches)
- match_free(m->matches);
-
- if (m->parent)
- LIST_REMOVE(matches, m->parent->matches, m);
-
- free(m->data);
- free(m);
-}
-
-static void match_free_if_empty(Match *m) {
- if (!m || m->matches)
- return;
-
- match_free(m);
-}
-
-_public_ int sd_journal_add_match(sd_journal *j, const void *data, size_t size) {
- Match *l3, *l4, *add_here = NULL, *m;
- le64_t le_hash;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(data, -EINVAL);
-
- if (size == 0)
- size = strlen(data);
-
- assert_return(match_is_valid(data, size), -EINVAL);
-
- /* level 0: AND term
- * level 1: OR terms
- * level 2: AND terms
- * level 3: OR terms
- * level 4: concrete matches */
-
- if (!j->level0) {
- j->level0 = match_new(NULL, MATCH_AND_TERM);
- if (!j->level0)
- return -ENOMEM;
- }
-
- if (!j->level1) {
- j->level1 = match_new(j->level0, MATCH_OR_TERM);
- if (!j->level1)
- return -ENOMEM;
- }
-
- if (!j->level2) {
- j->level2 = match_new(j->level1, MATCH_AND_TERM);
- if (!j->level2)
- return -ENOMEM;
- }
-
- assert(j->level0->type == MATCH_AND_TERM);
- assert(j->level1->type == MATCH_OR_TERM);
- assert(j->level2->type == MATCH_AND_TERM);
-
- le_hash = htole64(hash64(data, size));
-
- LIST_FOREACH(matches, l3, j->level2->matches) {
- assert(l3->type == MATCH_OR_TERM);
-
- LIST_FOREACH(matches, l4, l3->matches) {
- assert(l4->type == MATCH_DISCRETE);
-
- /* Exactly the same match already? Then ignore
- * this addition */
- if (l4->le_hash == le_hash &&
- l4->size == size &&
- memcmp(l4->data, data, size) == 0)
- return 0;
-
- /* Same field? Then let's add this to this OR term */
- if (same_field(data, size, l4->data, l4->size)) {
- add_here = l3;
- break;
- }
- }
-
- if (add_here)
- break;
- }
-
- if (!add_here) {
- add_here = match_new(j->level2, MATCH_OR_TERM);
- if (!add_here)
- goto fail;
- }
-
- m = match_new(add_here, MATCH_DISCRETE);
- if (!m)
- goto fail;
-
- m->le_hash = le_hash;
- m->size = size;
- m->data = memdup(data, size);
- if (!m->data)
- goto fail;
-
- detach_location(j);
-
- return 0;
-
-fail:
- match_free_if_empty(add_here);
- match_free_if_empty(j->level2);
- match_free_if_empty(j->level1);
- match_free_if_empty(j->level0);
-
- return -ENOMEM;
-}
-
-_public_ int sd_journal_add_conjunction(sd_journal *j) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- if (!j->level0)
- return 0;
-
- if (!j->level1)
- return 0;
-
- if (!j->level1->matches)
- return 0;
-
- j->level1 = NULL;
- j->level2 = NULL;
-
- return 0;
-}
-
-_public_ int sd_journal_add_disjunction(sd_journal *j) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- if (!j->level0)
- return 0;
-
- if (!j->level1)
- return 0;
-
- if (!j->level2)
- return 0;
-
- if (!j->level2->matches)
- return 0;
-
- j->level2 = NULL;
- return 0;
-}
-
-static char *match_make_string(Match *m) {
- char *p, *r;
- Match *i;
- bool enclose = false;
-
- if (!m)
- return strdup("none");
-
- if (m->type == MATCH_DISCRETE)
- return strndup(m->data, m->size);
-
- p = NULL;
- LIST_FOREACH(matches, i, m->matches) {
- char *t, *k;
-
- t = match_make_string(i);
- if (!t) {
- free(p);
- return NULL;
- }
-
- if (p) {
- k = strjoin(p, m->type == MATCH_OR_TERM ? " OR " : " AND ", t, NULL);
- free(p);
- free(t);
-
- if (!k)
- return NULL;
-
- p = k;
-
- enclose = true;
- } else
- p = t;
- }
-
- if (enclose) {
- r = strjoin("(", p, ")", NULL);
- free(p);
- return r;
- }
-
- return p;
-}
-
-char *journal_make_match_string(sd_journal *j) {
- assert(j);
-
- return match_make_string(j->level0);
-}
-
-_public_ void sd_journal_flush_matches(sd_journal *j) {
- if (!j)
- return;
-
- if (j->level0)
- match_free(j->level0);
-
- j->level0 = j->level1 = j->level2 = NULL;
-
- detach_location(j);
-}
-
-_pure_ static int compare_with_location(JournalFile *f, Location *l) {
- assert(f);
- assert(l);
- assert(f->location_type == LOCATION_SEEK);
- assert(l->type == LOCATION_DISCRETE || l->type == LOCATION_SEEK);
-
- if (l->monotonic_set &&
- sd_id128_equal(f->current_boot_id, l->boot_id) &&
- l->realtime_set &&
- f->current_realtime == l->realtime &&
- l->xor_hash_set &&
- f->current_xor_hash == l->xor_hash)
- return 0;
-
- if (l->seqnum_set &&
- sd_id128_equal(f->header->seqnum_id, l->seqnum_id)) {
-
- if (f->current_seqnum < l->seqnum)
- return -1;
- if (f->current_seqnum > l->seqnum)
- return 1;
- }
-
- if (l->monotonic_set &&
- sd_id128_equal(f->current_boot_id, l->boot_id)) {
-
- if (f->current_monotonic < l->monotonic)
- return -1;
- if (f->current_monotonic > l->monotonic)
- return 1;
- }
-
- if (l->realtime_set) {
-
- if (f->current_realtime < l->realtime)
- return -1;
- if (f->current_realtime > l->realtime)
- return 1;
- }
-
- if (l->xor_hash_set) {
-
- if (f->current_xor_hash < l->xor_hash)
- return -1;
- if (f->current_xor_hash > l->xor_hash)
- return 1;
- }
-
- return 0;
-}
-
-static int next_for_match(
- sd_journal *j,
- Match *m,
- JournalFile *f,
- uint64_t after_offset,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
-
- int r;
- uint64_t np = 0;
- Object *n;
-
- assert(j);
- assert(m);
- assert(f);
-
- if (m->type == MATCH_DISCRETE) {
- uint64_t dp;
-
- r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp);
- if (r <= 0)
- return r;
-
- return journal_file_move_to_entry_by_offset_for_data(f, dp, after_offset, direction, ret, offset);
-
- } else if (m->type == MATCH_OR_TERM) {
- Match *i;
-
- /* Find the earliest match beyond after_offset */
-
- LIST_FOREACH(matches, i, m->matches) {
- uint64_t cp;
-
- r = next_for_match(j, i, f, after_offset, direction, NULL, &cp);
- if (r < 0)
- return r;
- else if (r > 0) {
- if (np == 0 || (direction == DIRECTION_DOWN ? cp < np : cp > np))
- np = cp;
- }
- }
-
- if (np == 0)
- return 0;
-
- } else if (m->type == MATCH_AND_TERM) {
- Match *i, *last_moved;
-
- /* Always jump to the next matching entry and repeat
- * this until we find an offset that matches for all
- * matches. */
-
- if (!m->matches)
- return 0;
-
- r = next_for_match(j, m->matches, f, after_offset, direction, NULL, &np);
- if (r <= 0)
- return r;
-
- assert(direction == DIRECTION_DOWN ? np >= after_offset : np <= after_offset);
- last_moved = m->matches;
-
- LIST_LOOP_BUT_ONE(matches, i, m->matches, last_moved) {
- uint64_t cp;
-
- r = next_for_match(j, i, f, np, direction, NULL, &cp);
- if (r <= 0)
- return r;
-
- assert(direction == DIRECTION_DOWN ? cp >= np : cp <= np);
- if (direction == DIRECTION_DOWN ? cp > np : cp < np) {
- np = cp;
- last_moved = i;
- }
- }
- }
-
- assert(np > 0);
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = n;
- if (offset)
- *offset = np;
-
- return 1;
-}
-
-static int find_location_for_match(
- sd_journal *j,
- Match *m,
- JournalFile *f,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
-
- int r;
-
- assert(j);
- assert(m);
- assert(f);
-
- if (m->type == MATCH_DISCRETE) {
- uint64_t dp;
-
- r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp);
- if (r <= 0)
- return r;
-
- /* FIXME: missing: find by monotonic */
-
- if (j->current_location.type == LOCATION_HEAD)
- return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_DOWN, ret, offset);
- if (j->current_location.type == LOCATION_TAIL)
- return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_UP, ret, offset);
- if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
- return journal_file_move_to_entry_by_seqnum_for_data(f, dp, j->current_location.seqnum, direction, ret, offset);
- if (j->current_location.monotonic_set) {
- r = journal_file_move_to_entry_by_monotonic_for_data(f, dp, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
- if (r != -ENOENT)
- return r;
- }
- if (j->current_location.realtime_set)
- return journal_file_move_to_entry_by_realtime_for_data(f, dp, j->current_location.realtime, direction, ret, offset);
-
- return journal_file_next_entry_for_data(f, NULL, 0, dp, direction, ret, offset);
-
- } else if (m->type == MATCH_OR_TERM) {
- uint64_t np = 0;
- Object *n;
- Match *i;
-
- /* Find the earliest match */
-
- LIST_FOREACH(matches, i, m->matches) {
- uint64_t cp;
-
- r = find_location_for_match(j, i, f, direction, NULL, &cp);
- if (r < 0)
- return r;
- else if (r > 0) {
- if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp))
- np = cp;
- }
- }
-
- if (np == 0)
- return 0;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
- if (r < 0)
- return r;
-
- if (ret)
- *ret = n;
- if (offset)
- *offset = np;
-
- return 1;
-
- } else {
- Match *i;
- uint64_t np = 0;
-
- assert(m->type == MATCH_AND_TERM);
-
- /* First jump to the last match, and then find the
- * next one where all matches match */
-
- if (!m->matches)
- return 0;
-
- LIST_FOREACH(matches, i, m->matches) {
- uint64_t cp;
-
- r = find_location_for_match(j, i, f, direction, NULL, &cp);
- if (r <= 0)
- return r;
-
- if (np == 0 || (direction == DIRECTION_DOWN ? cp > np : cp < np))
- np = cp;
- }
-
- return next_for_match(j, m, f, np, direction, ret, offset);
- }
-}
-
-static int find_location_with_matches(
- sd_journal *j,
- JournalFile *f,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
-
- int r;
-
- assert(j);
- assert(f);
- assert(ret);
- assert(offset);
-
- if (!j->level0) {
- /* No matches is simple */
-
- if (j->current_location.type == LOCATION_HEAD)
- return journal_file_next_entry(f, 0, DIRECTION_DOWN, ret, offset);
- if (j->current_location.type == LOCATION_TAIL)
- return journal_file_next_entry(f, 0, DIRECTION_UP, ret, offset);
- if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
- return journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, ret, offset);
- if (j->current_location.monotonic_set) {
- r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
- if (r != -ENOENT)
- return r;
- }
- if (j->current_location.realtime_set)
- return journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, ret, offset);
-
- return journal_file_next_entry(f, 0, direction, ret, offset);
- } else
- return find_location_for_match(j, j->level0, f, direction, ret, offset);
-}
-
-static int next_with_matches(
- sd_journal *j,
- JournalFile *f,
- direction_t direction,
- Object **ret,
- uint64_t *offset) {
-
- assert(j);
- assert(f);
- assert(ret);
- assert(offset);
-
- /* No matches is easy. We simple advance the file
- * pointer by one. */
- if (!j->level0)
- return journal_file_next_entry(f, f->current_offset, direction, ret, offset);
-
- /* If we have a match then we look for the next matching entry
- * with an offset at least one step larger */
- return next_for_match(j, j->level0, f,
- direction == DIRECTION_DOWN ? f->current_offset + 1
- : f->current_offset - 1,
- direction, ret, offset);
-}
-
-static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction) {
- Object *c;
- uint64_t cp, n_entries;
- int r;
-
- assert(j);
- assert(f);
-
- n_entries = le64toh(f->header->n_entries);
-
- /* If we hit EOF before, we don't need to look into this file again
- * unless direction changed or new entries appeared. */
- if (f->last_direction == direction && f->location_type == LOCATION_TAIL &&
- n_entries == f->last_n_entries)
- return 0;
-
- f->last_n_entries = n_entries;
-
- if (f->last_direction == direction && f->current_offset > 0) {
- /* LOCATION_SEEK here means we did the work in a previous
- * iteration and the current location already points to a
- * candidate entry. */
- if (f->location_type != LOCATION_SEEK) {
- r = next_with_matches(j, f, direction, &c, &cp);
- if (r <= 0)
- return r;
-
- journal_file_save_location(f, c, cp);
- }
- } else {
- f->last_direction = direction;
-
- r = find_location_with_matches(j, f, direction, &c, &cp);
- if (r <= 0)
- return r;
-
- journal_file_save_location(f, c, cp);
- }
-
- /* OK, we found the spot, now let's advance until an entry
- * that is actually different from what we were previously
- * looking at. This is necessary to handle entries which exist
- * in two (or more) journal files, and which shall all be
- * suppressed but one. */
-
- for (;;) {
- bool found;
-
- if (j->current_location.type == LOCATION_DISCRETE) {
- int k;
-
- k = compare_with_location(f, &j->current_location);
-
- found = direction == DIRECTION_DOWN ? k > 0 : k < 0;
- } else
- found = true;
-
- if (found)
- return 1;
-
- r = next_with_matches(j, f, direction, &c, &cp);
- if (r <= 0)
- return r;
-
- journal_file_save_location(f, c, cp);
- }
-}
-
-static int real_journal_next(sd_journal *j, direction_t direction) {
- JournalFile *f, *new_file = NULL;
- Iterator i;
- Object *o;
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- bool found;
-
- r = next_beyond_location(j, f, direction);
- if (r < 0) {
- log_debug_errno(r, "Can't iterate through %s, ignoring: %m", f->path);
- remove_file_real(j, f);
- continue;
- } else if (r == 0) {
- f->location_type = LOCATION_TAIL;
- continue;
- }
-
- if (!new_file)
- found = true;
- else {
- int k;
-
- k = journal_file_compare_locations(f, new_file);
-
- found = direction == DIRECTION_DOWN ? k < 0 : k > 0;
- }
-
- if (found)
- new_file = f;
- }
-
- if (!new_file)
- return 0;
-
- r = journal_file_move_to_object(new_file, OBJECT_ENTRY, new_file->current_offset, &o);
- if (r < 0)
- return r;
-
- set_location(j, new_file, o);
-
- return 1;
-}
-
-_public_ int sd_journal_next(sd_journal *j) {
- return real_journal_next(j, DIRECTION_DOWN);
-}
-
-_public_ int sd_journal_previous(sd_journal *j) {
- return real_journal_next(j, DIRECTION_UP);
-}
-
-static int real_journal_next_skip(sd_journal *j, direction_t direction, uint64_t skip) {
- int c = 0, r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- if (skip == 0) {
- /* If this is not a discrete skip, then at least
- * resolve the current location */
- if (j->current_location.type != LOCATION_DISCRETE)
- return real_journal_next(j, direction);
-
- return 0;
- }
-
- do {
- r = real_journal_next(j, direction);
- if (r < 0)
- return r;
-
- if (r == 0)
- return c;
-
- skip--;
- c++;
- } while (skip > 0);
-
- return c;
-}
-
-_public_ int sd_journal_next_skip(sd_journal *j, uint64_t skip) {
- return real_journal_next_skip(j, DIRECTION_DOWN, skip);
-}
-
-_public_ int sd_journal_previous_skip(sd_journal *j, uint64_t skip) {
- return real_journal_next_skip(j, DIRECTION_UP, skip);
-}
-
-_public_ int sd_journal_get_cursor(sd_journal *j, char **cursor) {
- Object *o;
- int r;
- char bid[33], sid[33];
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(cursor, -EINVAL);
-
- if (!j->current_file || j->current_file->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
- if (r < 0)
- return r;
-
- sd_id128_to_string(j->current_file->header->seqnum_id, sid);
- sd_id128_to_string(o->entry.boot_id, bid);
-
- if (asprintf(cursor,
- "s=%s;i=%"PRIx64";b=%s;m=%"PRIx64";t=%"PRIx64";x=%"PRIx64,
- sid, le64toh(o->entry.seqnum),
- bid, le64toh(o->entry.monotonic),
- le64toh(o->entry.realtime),
- le64toh(o->entry.xor_hash)) < 0)
- return -ENOMEM;
-
- return 0;
-}
-
-_public_ int sd_journal_seek_cursor(sd_journal *j, const char *cursor) {
- const char *word, *state;
- size_t l;
- unsigned long long seqnum, monotonic, realtime, xor_hash;
- bool
- seqnum_id_set = false,
- seqnum_set = false,
- boot_id_set = false,
- monotonic_set = false,
- realtime_set = false,
- xor_hash_set = false;
- sd_id128_t seqnum_id, boot_id;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(!isempty(cursor), -EINVAL);
-
- FOREACH_WORD_SEPARATOR(word, l, cursor, ";", state) {
- char *item;
- int k = 0;
-
- if (l < 2 || word[1] != '=')
- return -EINVAL;
-
- item = strndup(word, l);
- if (!item)
- return -ENOMEM;
-
- switch (word[0]) {
-
- case 's':
- seqnum_id_set = true;
- k = sd_id128_from_string(item+2, &seqnum_id);
- break;
-
- case 'i':
- seqnum_set = true;
- if (sscanf(item+2, "%llx", &seqnum) != 1)
- k = -EINVAL;
- break;
-
- case 'b':
- boot_id_set = true;
- k = sd_id128_from_string(item+2, &boot_id);
- break;
-
- case 'm':
- monotonic_set = true;
- if (sscanf(item+2, "%llx", &monotonic) != 1)
- k = -EINVAL;
- break;
-
- case 't':
- realtime_set = true;
- if (sscanf(item+2, "%llx", &realtime) != 1)
- k = -EINVAL;
- break;
-
- case 'x':
- xor_hash_set = true;
- if (sscanf(item+2, "%llx", &xor_hash) != 1)
- k = -EINVAL;
- break;
- }
-
- free(item);
-
- if (k < 0)
- return k;
- }
-
- if ((!seqnum_set || !seqnum_id_set) &&
- (!monotonic_set || !boot_id_set) &&
- !realtime_set)
- return -EINVAL;
-
- reset_location(j);
-
- j->current_location.type = LOCATION_SEEK;
-
- if (realtime_set) {
- j->current_location.realtime = (uint64_t) realtime;
- j->current_location.realtime_set = true;
- }
-
- if (seqnum_set && seqnum_id_set) {
- j->current_location.seqnum = (uint64_t) seqnum;
- j->current_location.seqnum_id = seqnum_id;
- j->current_location.seqnum_set = true;
- }
-
- if (monotonic_set && boot_id_set) {
- j->current_location.monotonic = (uint64_t) monotonic;
- j->current_location.boot_id = boot_id;
- j->current_location.monotonic_set = true;
- }
-
- if (xor_hash_set) {
- j->current_location.xor_hash = (uint64_t) xor_hash;
- j->current_location.xor_hash_set = true;
- }
-
- return 0;
-}
-
-_public_ int sd_journal_test_cursor(sd_journal *j, const char *cursor) {
- int r;
- Object *o;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(!isempty(cursor), -EINVAL);
-
- if (!j->current_file || j->current_file->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
- if (r < 0)
- return r;
-
- for(;;) {
- _cleanup_free_ char *item = NULL;
- unsigned long long ll;
- sd_id128_t id;
- int k = 0;
-
- r = extract_first_word(&cursor, &item, ";", EXTRACT_DONT_COALESCE_SEPARATORS);
- if (r < 0)
- return r;
-
- if (r == 0)
- break;
-
- if (strlen(item) < 2 || item[1] != '=')
- return -EINVAL;
-
- switch (item[0]) {
-
- case 's':
- k = sd_id128_from_string(item+2, &id);
- if (k < 0)
- return k;
- if (!sd_id128_equal(id, j->current_file->header->seqnum_id))
- return 0;
- break;
-
- case 'i':
- if (sscanf(item+2, "%llx", &ll) != 1)
- return -EINVAL;
- if (ll != le64toh(o->entry.seqnum))
- return 0;
- break;
-
- case 'b':
- k = sd_id128_from_string(item+2, &id);
- if (k < 0)
- return k;
- if (!sd_id128_equal(id, o->entry.boot_id))
- return 0;
- break;
-
- case 'm':
- if (sscanf(item+2, "%llx", &ll) != 1)
- return -EINVAL;
- if (ll != le64toh(o->entry.monotonic))
- return 0;
- break;
-
- case 't':
- if (sscanf(item+2, "%llx", &ll) != 1)
- return -EINVAL;
- if (ll != le64toh(o->entry.realtime))
- return 0;
- break;
-
- case 'x':
- if (sscanf(item+2, "%llx", &ll) != 1)
- return -EINVAL;
- if (ll != le64toh(o->entry.xor_hash))
- return 0;
- break;
- }
- }
-
- return 1;
-}
-
-
-_public_ int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- reset_location(j);
- j->current_location.type = LOCATION_SEEK;
- j->current_location.boot_id = boot_id;
- j->current_location.monotonic = usec;
- j->current_location.monotonic_set = true;
-
- return 0;
-}
-
-_public_ int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- reset_location(j);
- j->current_location.type = LOCATION_SEEK;
- j->current_location.realtime = usec;
- j->current_location.realtime_set = true;
-
- return 0;
-}
-
-_public_ int sd_journal_seek_head(sd_journal *j) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- reset_location(j);
- j->current_location.type = LOCATION_HEAD;
-
- return 0;
-}
-
-_public_ int sd_journal_seek_tail(sd_journal *j) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- reset_location(j);
- j->current_location.type = LOCATION_TAIL;
-
- return 0;
-}
-
-static void check_network(sd_journal *j, int fd) {
- struct statfs sfs;
-
- assert(j);
-
- if (j->on_network)
- return;
-
- if (fstatfs(fd, &sfs) < 0)
- return;
-
- j->on_network =
- F_TYPE_EQUAL(sfs.f_type, CIFS_MAGIC_NUMBER) ||
- F_TYPE_EQUAL(sfs.f_type, CODA_SUPER_MAGIC) ||
- F_TYPE_EQUAL(sfs.f_type, NCP_SUPER_MAGIC) ||
- F_TYPE_EQUAL(sfs.f_type, NFS_SUPER_MAGIC) ||
- F_TYPE_EQUAL(sfs.f_type, SMB_SUPER_MAGIC);
-}
-
-static bool file_has_type_prefix(const char *prefix, const char *filename) {
- const char *full, *tilded, *atted;
-
- full = strjoina(prefix, ".journal");
- tilded = strjoina(full, "~");
- atted = strjoina(prefix, "@");
-
- return streq(filename, full) ||
- streq(filename, tilded) ||
- startswith(filename, atted);
-}
-
-static bool file_type_wanted(int flags, const char *filename) {
- assert(filename);
-
- if (!endswith(filename, ".journal") && !endswith(filename, ".journal~"))
- return false;
-
- /* no flags set → every type is OK */
- if (!(flags & (SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER)))
- return true;
-
- if (flags & SD_JOURNAL_SYSTEM && file_has_type_prefix("system", filename))
- return true;
-
- if (flags & SD_JOURNAL_CURRENT_USER) {
- char prefix[5 + DECIMAL_STR_MAX(uid_t) + 1];
-
- xsprintf(prefix, "user-"UID_FMT, getuid());
-
- if (file_has_type_prefix(prefix, filename))
- return true;
- }
-
- return false;
-}
-
-static int add_any_file(sd_journal *j, const char *path) {
- JournalFile *f = NULL;
- int r, k;
-
- assert(j);
- assert(path);
-
- if (ordered_hashmap_get(j->files, path))
- return 0;
-
- if (ordered_hashmap_size(j->files) >= JOURNAL_FILES_MAX) {
- log_debug("Too many open journal files, not adding %s.", path);
- r = -ETOOMANYREFS;
- goto fail;
- }
-
- r = journal_file_open(path, O_RDONLY, 0, false, false, NULL, j->mmap, NULL, &f);
- if (r < 0) {
- log_debug_errno(r, "Failed to open journal file %s: %m", path);
- goto fail;
- }
-
- /* journal_file_dump(f); */
-
- r = ordered_hashmap_put(j->files, f->path, f);
- if (r < 0) {
- journal_file_close(f);
- goto fail;
- }
-
- log_debug("File %s added.", f->path);
-
- check_network(j, f->fd);
-
- j->current_invalidate_counter ++;
-
- return 0;
-
-fail:
- k = journal_put_error(j, r, path);
- if (k < 0)
- return k;
-
- return r;
-}
-
-static int add_file(sd_journal *j, const char *prefix, const char *filename) {
- const char *path;
-
- assert(j);
- assert(prefix);
- assert(filename);
-
- if (j->no_new_files ||
- !file_type_wanted(j->flags, filename))
- return 0;
-
- path = strjoina(prefix, "/", filename);
-
- if (!j->has_runtime_files && path_startswith(path, "/run/log/journal"))
- j->has_runtime_files = true;
- else if (!j->has_persistent_files && path_startswith(path, "/var/log/journal"))
- j->has_persistent_files = true;
-
- return add_any_file(j, path);
-}
-
-static void remove_file(sd_journal *j, const char *prefix, const char *filename) {
- const char *path;
- JournalFile *f;
-
- assert(j);
- assert(prefix);
- assert(filename);
-
- path = strjoina(prefix, "/", filename);
- f = ordered_hashmap_get(j->files, path);
- if (!f)
- return;
-
- remove_file_real(j, f);
-}
-
-static void remove_file_real(sd_journal *j, JournalFile *f) {
- assert(j);
- assert(f);
-
- ordered_hashmap_remove(j->files, f->path);
-
- log_debug("File %s removed.", f->path);
-
- if (j->current_file == f) {
- j->current_file = NULL;
- j->current_field = 0;
- }
-
- if (j->unique_file == f) {
- /* Jump to the next unique_file or NULL if that one was last */
- j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
- j->unique_offset = 0;
- if (!j->unique_file)
- j->unique_file_lost = true;
- }
-
- if (j->fields_file == f) {
- j->fields_file = ordered_hashmap_next(j->files, j->fields_file->path);
- j->fields_offset = 0;
- if (!j->fields_file)
- j->fields_file_lost = true;
- }
-
- journal_file_close(f);
-
- j->current_invalidate_counter ++;
-}
-
-static int dirname_is_machine_id(const char *fn) {
- sd_id128_t id, machine;
- int r;
-
- r = sd_id128_get_machine(&machine);
- if (r < 0)
- return r;
-
- r = sd_id128_from_string(fn, &id);
- if (r < 0)
- return r;
-
- return sd_id128_equal(id, machine);
-}
-
-static int add_directory(sd_journal *j, const char *prefix, const char *dirname) {
- _cleanup_free_ char *path = NULL;
- _cleanup_closedir_ DIR *d = NULL;
- struct dirent *de = NULL;
- Directory *m;
- int r, k;
-
- assert(j);
- assert(prefix);
- assert(dirname);
-
- log_debug("Considering %s/%s.", prefix, dirname);
-
- if ((j->flags & SD_JOURNAL_LOCAL_ONLY) &&
- !(dirname_is_machine_id(dirname) > 0 || path_startswith(prefix, "/run")))
- return 0;
-
- path = strjoin(prefix, "/", dirname, NULL);
- if (!path) {
- r = -ENOMEM;
- goto fail;
- }
-
- d = opendir(path);
- if (!d) {
- r = log_debug_errno(errno, "Failed to open directory %s: %m", path);
- goto fail;
- }
-
- m = hashmap_get(j->directories_by_path, path);
- if (!m) {
- m = new0(Directory, 1);
- if (!m) {
- r = -ENOMEM;
- goto fail;
- }
-
- m->is_root = false;
- m->path = path;
-
- if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
- free(m);
- r = -ENOMEM;
- goto fail;
- }
-
- path = NULL; /* avoid freeing in cleanup */
- j->current_invalidate_counter ++;
-
- log_debug("Directory %s added.", m->path);
-
- } else if (m->is_root)
- return 0;
-
- if (m->wd <= 0 && j->inotify_fd >= 0) {
-
- m->wd = inotify_add_watch(j->inotify_fd, m->path,
- IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
- IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|IN_MOVED_FROM|
- IN_ONLYDIR);
-
- if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0)
- inotify_rm_watch(j->inotify_fd, m->wd);
- }
-
- FOREACH_DIRENT_ALL(de, d, return log_debug_errno(errno, "Failed to read directory %s: %m", m->path)) {
-
- if (dirent_is_file_with_suffix(de, ".journal") ||
- dirent_is_file_with_suffix(de, ".journal~"))
- (void) add_file(j, m->path, de->d_name);
- }
-
- check_network(j, dirfd(d));
-
- return 0;
-
-fail:
- k = journal_put_error(j, r, path ?: dirname);
- if (k < 0)
- return k;
-
- return r;
-}
-
-static int add_root_directory(sd_journal *j, const char *p, bool missing_ok) {
- _cleanup_closedir_ DIR *d = NULL;
- struct dirent *de;
- Directory *m;
- int r, k;
-
- assert(j);
- assert(p);
-
- if ((j->flags & SD_JOURNAL_RUNTIME_ONLY) &&
- !path_startswith(p, "/run"))
- return -EINVAL;
-
- if (j->prefix)
- p = strjoina(j->prefix, p);
-
- d = opendir(p);
- if (!d) {
- if (errno == ENOENT && missing_ok)
- return 0;
-
- r = log_debug_errno(errno, "Failed to open root directory %s: %m", p);
- goto fail;
- }
-
- m = hashmap_get(j->directories_by_path, p);
- if (!m) {
- m = new0(Directory, 1);
- if (!m) {
- r = -ENOMEM;
- goto fail;
- }
-
- m->is_root = true;
- m->path = strdup(p);
- if (!m->path) {
- free(m);
- r = -ENOMEM;
- goto fail;
- }
-
- if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
- free(m->path);
- free(m);
- r = -ENOMEM;
- goto fail;
- }
-
- j->current_invalidate_counter ++;
-
- log_debug("Root directory %s added.", m->path);
-
- } else if (!m->is_root)
- return 0;
-
- if (m->wd <= 0 && j->inotify_fd >= 0) {
-
- m->wd = inotify_add_watch(j->inotify_fd, m->path,
- IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
- IN_ONLYDIR);
-
- if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0)
- inotify_rm_watch(j->inotify_fd, m->wd);
- }
-
- if (j->no_new_files)
- return 0;
-
- FOREACH_DIRENT_ALL(de, d, return log_debug_errno(errno, "Failed to read directory %s: %m", m->path)) {
- sd_id128_t id;
-
- if (dirent_is_file_with_suffix(de, ".journal") ||
- dirent_is_file_with_suffix(de, ".journal~"))
- (void) add_file(j, m->path, de->d_name);
- else if (IN_SET(de->d_type, DT_DIR, DT_LNK, DT_UNKNOWN) &&
- sd_id128_from_string(de->d_name, &id) >= 0)
- (void) add_directory(j, m->path, de->d_name);
- }
-
- check_network(j, dirfd(d));
-
- return 0;
-
-fail:
- k = journal_put_error(j, r, p);
- if (k < 0)
- return k;
-
- return r;
-}
-
-static void remove_directory(sd_journal *j, Directory *d) {
- assert(j);
-
- if (d->wd > 0) {
- hashmap_remove(j->directories_by_wd, INT_TO_PTR(d->wd));
-
- if (j->inotify_fd >= 0)
- inotify_rm_watch(j->inotify_fd, d->wd);
- }
-
- hashmap_remove(j->directories_by_path, d->path);
-
- if (d->is_root)
- log_debug("Root directory %s removed.", d->path);
- else
- log_debug("Directory %s removed.", d->path);
-
- free(d->path);
- free(d);
-}
-
-static int add_search_paths(sd_journal *j) {
-
- static const char search_paths[] =
- "/run/log/journal\0"
- "/var/log/journal\0";
- const char *p;
-
- assert(j);
-
- /* We ignore most errors here, since the idea is to only open
- * what's actually accessible, and ignore the rest. */
-
- NULSTR_FOREACH(p, search_paths)
- (void) add_root_directory(j, p, true);
-
- return 0;
-}
-
-static int add_current_paths(sd_journal *j) {
- Iterator i;
- JournalFile *f;
-
- assert(j);
- assert(j->no_new_files);
-
- /* Simply adds all directories for files we have open as
- * "root" directories. We don't expect errors here, so we
- * treat them as fatal. */
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- _cleanup_free_ char *dir;
- int r;
-
- dir = dirname_malloc(f->path);
- if (!dir)
- return -ENOMEM;
-
- r = add_root_directory(j, dir, true);
- if (r < 0)
- return r;
- }
-
- return 0;
-}
-
-static int allocate_inotify(sd_journal *j) {
- assert(j);
-
- if (j->inotify_fd < 0) {
- j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
- if (j->inotify_fd < 0)
- return -errno;
- }
-
- if (!j->directories_by_wd) {
- j->directories_by_wd = hashmap_new(NULL);
- if (!j->directories_by_wd)
- return -ENOMEM;
- }
-
- return 0;
-}
-
-static sd_journal *journal_new(int flags, const char *path) {
- sd_journal *j;
-
- j = new0(sd_journal, 1);
- if (!j)
- return NULL;
-
- j->original_pid = getpid();
- j->inotify_fd = -1;
- j->flags = flags;
- j->data_threshold = DEFAULT_DATA_THRESHOLD;
-
- if (path) {
- j->path = strdup(path);
- if (!j->path)
- goto fail;
- }
-
- j->files = ordered_hashmap_new(&string_hash_ops);
- j->directories_by_path = hashmap_new(&string_hash_ops);
- j->mmap = mmap_cache_new();
- if (!j->files || !j->directories_by_path || !j->mmap)
- goto fail;
-
- return j;
-
-fail:
- sd_journal_close(j);
- return NULL;
-}
-
-_public_ int sd_journal_open(sd_journal **ret, int flags) {
- sd_journal *j;
- int r;
-
- assert_return(ret, -EINVAL);
- assert_return((flags & ~(SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_RUNTIME_ONLY|SD_JOURNAL_SYSTEM|SD_JOURNAL_CURRENT_USER)) == 0, -EINVAL);
-
- j = journal_new(flags, NULL);
- if (!j)
- return -ENOMEM;
-
- r = add_search_paths(j);
- if (r < 0)
- goto fail;
-
- *ret = j;
- return 0;
-
-fail:
- sd_journal_close(j);
-
- return r;
-}
-
-_public_ int sd_journal_open_container(sd_journal **ret, const char *machine, int flags) {
- _cleanup_free_ char *root = NULL, *class = NULL;
- sd_journal *j;
- char *p;
- int r;
-
- assert_return(machine, -EINVAL);
- assert_return(ret, -EINVAL);
- assert_return((flags & ~(SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM)) == 0, -EINVAL);
- assert_return(machine_name_is_valid(machine), -EINVAL);
-
- p = strjoina("/run/systemd/machines/", machine);
- r = parse_env_file(p, NEWLINE, "ROOT", &root, "CLASS", &class, NULL);
- if (r == -ENOENT)
- return -EHOSTDOWN;
- if (r < 0)
- return r;
- if (!root)
- return -ENODATA;
-
- if (!streq_ptr(class, "container"))
- return -EIO;
-
- j = journal_new(flags, NULL);
- if (!j)
- return -ENOMEM;
-
- j->prefix = root;
- root = NULL;
-
- r = add_search_paths(j);
- if (r < 0)
- goto fail;
-
- *ret = j;
- return 0;
-
-fail:
- sd_journal_close(j);
- return r;
-}
-
-_public_ int sd_journal_open_directory(sd_journal **ret, const char *path, int flags) {
- sd_journal *j;
- int r;
-
- assert_return(ret, -EINVAL);
- assert_return(path, -EINVAL);
- assert_return(flags == 0, -EINVAL);
-
- j = journal_new(flags, path);
- if (!j)
- return -ENOMEM;
-
- r = add_root_directory(j, path, false);
- if (r < 0)
- goto fail;
-
- *ret = j;
- return 0;
-
-fail:
- sd_journal_close(j);
-
- return r;
-}
-
-_public_ int sd_journal_open_files(sd_journal **ret, const char **paths, int flags) {
- sd_journal *j;
- const char **path;
- int r;
-
- assert_return(ret, -EINVAL);
- assert_return(flags == 0, -EINVAL);
-
- j = journal_new(flags, NULL);
- if (!j)
- return -ENOMEM;
-
- STRV_FOREACH(path, paths) {
- r = add_any_file(j, *path);
- if (r < 0)
- goto fail;
- }
-
- j->no_new_files = true;
-
- *ret = j;
- return 0;
-
-fail:
- sd_journal_close(j);
-
- return r;
-}
-
-_public_ void sd_journal_close(sd_journal *j) {
- Directory *d;
- JournalFile *f;
- char *p;
-
- if (!j)
- return;
-
- sd_journal_flush_matches(j);
-
- while ((f = ordered_hashmap_steal_first(j->files)))
- journal_file_close(f);
-
- ordered_hashmap_free(j->files);
-
- while ((d = hashmap_first(j->directories_by_path)))
- remove_directory(j, d);
-
- while ((d = hashmap_first(j->directories_by_wd)))
- remove_directory(j, d);
-
- hashmap_free(j->directories_by_path);
- hashmap_free(j->directories_by_wd);
-
- safe_close(j->inotify_fd);
-
- if (j->mmap) {
- log_debug("mmap cache statistics: %u hit, %u miss", mmap_cache_get_hit(j->mmap), mmap_cache_get_missed(j->mmap));
- mmap_cache_unref(j->mmap);
- }
-
- while ((p = hashmap_steal_first(j->errors)))
- free(p);
- hashmap_free(j->errors);
-
- free(j->path);
- free(j->prefix);
- free(j->unique_field);
- free(j->fields_buffer);
- free(j);
-}
-
-_public_ int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) {
- Object *o;
- JournalFile *f;
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(ret, -EINVAL);
-
- f = j->current_file;
- if (!f)
- return -EADDRNOTAVAIL;
-
- if (f->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
- if (r < 0)
- return r;
-
- *ret = le64toh(o->entry.realtime);
- return 0;
-}
-
-_public_ int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) {
- Object *o;
- JournalFile *f;
- int r;
- sd_id128_t id;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- f = j->current_file;
- if (!f)
- return -EADDRNOTAVAIL;
-
- if (f->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
- if (r < 0)
- return r;
-
- if (ret_boot_id)
- *ret_boot_id = o->entry.boot_id;
- else {
- r = sd_id128_get_boot(&id);
- if (r < 0)
- return r;
-
- if (!sd_id128_equal(id, o->entry.boot_id))
- return -ESTALE;
- }
-
- if (ret)
- *ret = le64toh(o->entry.monotonic);
-
- return 0;
-}
-
-static bool field_is_valid(const char *field) {
- const char *p;
-
- assert(field);
-
- if (isempty(field))
- return false;
-
- if (startswith(field, "__"))
- return false;
-
- for (p = field; *p; p++) {
-
- if (*p == '_')
- continue;
-
- if (*p >= 'A' && *p <= 'Z')
- continue;
-
- if (*p >= '0' && *p <= '9')
- continue;
-
- return false;
- }
-
- return true;
-}
-
-_public_ int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) {
- JournalFile *f;
- uint64_t i, n;
- size_t field_length;
- int r;
- Object *o;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(field, -EINVAL);
- assert_return(data, -EINVAL);
- assert_return(size, -EINVAL);
- assert_return(field_is_valid(field), -EINVAL);
-
- f = j->current_file;
- if (!f)
- return -EADDRNOTAVAIL;
-
- if (f->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
- if (r < 0)
- return r;
-
- field_length = strlen(field);
-
- n = journal_file_entry_n_items(o);
- for (i = 0; i < n; i++) {
- uint64_t p, l;
- le64_t le_hash;
- size_t t;
- int compression;
-
- p = le64toh(o->entry.items[i].object_offset);
- le_hash = o->entry.items[i].hash;
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- if (le_hash != o->data.hash)
- return -EBADMSG;
-
- l = le64toh(o->object.size) - offsetof(Object, data.payload);
-
- compression = o->object.flags & OBJECT_COMPRESSION_MASK;
- if (compression) {
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- r = decompress_startswith(compression,
- o->data.payload, l,
- &f->compress_buffer, &f->compress_buffer_size,
- field, field_length, '=');
- if (r < 0)
- log_debug_errno(r, "Cannot decompress %s object of length %zu at offset "OFSfmt": %m",
- object_compressed_to_string(compression), l, p);
- else if (r > 0) {
-
- size_t rsize;
-
- r = decompress_blob(compression,
- o->data.payload, l,
- &f->compress_buffer, &f->compress_buffer_size, &rsize,
- j->data_threshold);
- if (r < 0)
- return r;
-
- *data = f->compress_buffer;
- *size = (size_t) rsize;
-
- return 0;
- }
-#else
- return -EPROTONOSUPPORT;
-#endif
- } else if (l >= field_length+1 &&
- memcmp(o->data.payload, field, field_length) == 0 &&
- o->data.payload[field_length] == '=') {
-
- t = (size_t) l;
-
- if ((uint64_t) t != l)
- return -E2BIG;
-
- *data = o->data.payload;
- *size = t;
-
- return 0;
- }
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
- if (r < 0)
- return r;
- }
-
- return -ENOENT;
-}
-
-static int return_data(sd_journal *j, JournalFile *f, Object *o, const void **data, size_t *size) {
- size_t t;
- uint64_t l;
- int compression;
-
- l = le64toh(o->object.size) - offsetof(Object, data.payload);
- t = (size_t) l;
-
- /* We can't read objects larger than 4G on a 32bit machine */
- if ((uint64_t) t != l)
- return -E2BIG;
-
- compression = o->object.flags & OBJECT_COMPRESSION_MASK;
- if (compression) {
-#if defined(HAVE_XZ) || defined(HAVE_LZ4)
- size_t rsize;
- int r;
-
- r = decompress_blob(compression,
- o->data.payload, l, &f->compress_buffer,
- &f->compress_buffer_size, &rsize, j->data_threshold);
- if (r < 0)
- return r;
-
- *data = f->compress_buffer;
- *size = (size_t) rsize;
-#else
- return -EPROTONOSUPPORT;
-#endif
- } else {
- *data = o->data.payload;
- *size = t;
- }
-
- return 0;
-}
-
-_public_ int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) {
- JournalFile *f;
- uint64_t p, n;
- le64_t le_hash;
- int r;
- Object *o;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(data, -EINVAL);
- assert_return(size, -EINVAL);
-
- f = j->current_file;
- if (!f)
- return -EADDRNOTAVAIL;
-
- if (f->current_offset <= 0)
- return -EADDRNOTAVAIL;
-
- r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
- if (r < 0)
- return r;
-
- n = journal_file_entry_n_items(o);
- if (j->current_field >= n)
- return 0;
-
- p = le64toh(o->entry.items[j->current_field].object_offset);
- le_hash = o->entry.items[j->current_field].hash;
- r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
- if (r < 0)
- return r;
-
- if (le_hash != o->data.hash)
- return -EBADMSG;
-
- r = return_data(j, f, o, data, size);
- if (r < 0)
- return r;
-
- j->current_field ++;
-
- return 1;
-}
-
-_public_ void sd_journal_restart_data(sd_journal *j) {
- if (!j)
- return;
-
- j->current_field = 0;
-}
-
-_public_ int sd_journal_get_fd(sd_journal *j) {
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- if (j->inotify_fd >= 0)
- return j->inotify_fd;
-
- r = allocate_inotify(j);
- if (r < 0)
- return r;
-
- /* Iterate through all dirs again, to add them to the
- * inotify */
- if (j->no_new_files)
- r = add_current_paths(j);
- else if (j->path)
- r = add_root_directory(j, j->path, true);
- else
- r = add_search_paths(j);
- if (r < 0)
- return r;
-
- return j->inotify_fd;
-}
-
-_public_ int sd_journal_get_events(sd_journal *j) {
- int fd;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- fd = sd_journal_get_fd(j);
- if (fd < 0)
- return fd;
-
- return POLLIN;
-}
-
-_public_ int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec) {
- int fd;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(timeout_usec, -EINVAL);
-
- fd = sd_journal_get_fd(j);
- if (fd < 0)
- return fd;
-
- if (!j->on_network) {
- *timeout_usec = (uint64_t) -1;
- return 0;
- }
-
- /* If we are on the network we need to regularly check for
- * changes manually */
-
- *timeout_usec = j->last_process_usec + JOURNAL_FILES_RECHECK_USEC;
- return 1;
-}
-
-static void process_inotify_event(sd_journal *j, struct inotify_event *e) {
- Directory *d;
-
- assert(j);
- assert(e);
-
- /* Is this a subdirectory we watch? */
- d = hashmap_get(j->directories_by_wd, INT_TO_PTR(e->wd));
- if (d) {
- sd_id128_t id;
-
- if (!(e->mask & IN_ISDIR) && e->len > 0 &&
- (endswith(e->name, ".journal") ||
- endswith(e->name, ".journal~"))) {
-
- /* Event for a journal file */
-
- if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
- (void) add_file(j, d->path, e->name);
- else if (e->mask & (IN_DELETE|IN_MOVED_FROM|IN_UNMOUNT))
- remove_file(j, d->path, e->name);
-
- } else if (!d->is_root && e->len == 0) {
-
- /* Event for a subdirectory */
-
- if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT))
- remove_directory(j, d);
-
- } else if (d->is_root && (e->mask & IN_ISDIR) && e->len > 0 && sd_id128_from_string(e->name, &id) >= 0) {
-
- /* Event for root directory */
-
- if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
- (void) add_directory(j, d->path, e->name);
- }
-
- return;
- }
-
- if (e->mask & IN_IGNORED)
- return;
-
- log_debug("Unknown inotify event.");
-}
-
-static int determine_change(sd_journal *j) {
- bool b;
-
- assert(j);
-
- b = j->current_invalidate_counter != j->last_invalidate_counter;
- j->last_invalidate_counter = j->current_invalidate_counter;
-
- return b ? SD_JOURNAL_INVALIDATE : SD_JOURNAL_APPEND;
-}
-
-_public_ int sd_journal_process(sd_journal *j) {
- bool got_something = false;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- j->last_process_usec = now(CLOCK_MONOTONIC);
-
- for (;;) {
- union inotify_event_buffer buffer;
- struct inotify_event *e;
- ssize_t l;
-
- l = read(j->inotify_fd, &buffer, sizeof(buffer));
- if (l < 0) {
- if (errno == EAGAIN || errno == EINTR)
- return got_something ? determine_change(j) : SD_JOURNAL_NOP;
-
- return -errno;
- }
-
- got_something = true;
-
- FOREACH_INOTIFY_EVENT(e, buffer, l)
- process_inotify_event(j, e);
- }
-}
-
-_public_ int sd_journal_wait(sd_journal *j, uint64_t timeout_usec) {
- int r;
- uint64_t t;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- if (j->inotify_fd < 0) {
-
- /* This is the first invocation, hence create the
- * inotify watch */
- r = sd_journal_get_fd(j);
- if (r < 0)
- return r;
-
- /* The journal might have changed since the context
- * object was created and we weren't watching before,
- * hence don't wait for anything, and return
- * immediately. */
- return determine_change(j);
- }
-
- r = sd_journal_get_timeout(j, &t);
- if (r < 0)
- return r;
-
- if (t != (uint64_t) -1) {
- usec_t n;
-
- n = now(CLOCK_MONOTONIC);
- t = t > n ? t - n : 0;
-
- if (timeout_usec == (uint64_t) -1 || timeout_usec > t)
- timeout_usec = t;
- }
-
- do {
- r = fd_wait_for_event(j->inotify_fd, POLLIN, timeout_usec);
- } while (r == -EINTR);
-
- if (r < 0)
- return r;
-
- return sd_journal_process(j);
-}
-
-_public_ int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to) {
- Iterator i;
- JournalFile *f;
- bool first = true;
- uint64_t fmin = 0, tmax = 0;
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(from || to, -EINVAL);
- assert_return(from != to, -EINVAL);
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- usec_t fr, t;
-
- r = journal_file_get_cutoff_realtime_usec(f, &fr, &t);
- if (r == -ENOENT)
- continue;
- if (r < 0)
- return r;
- if (r == 0)
- continue;
-
- if (first) {
- fmin = fr;
- tmax = t;
- first = false;
- } else {
- fmin = MIN(fr, fmin);
- tmax = MAX(t, tmax);
- }
- }
-
- if (from)
- *from = fmin;
- if (to)
- *to = tmax;
-
- return first ? 0 : 1;
-}
-
-_public_ int sd_journal_get_cutoff_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t *from, uint64_t *to) {
- Iterator i;
- JournalFile *f;
- bool found = false;
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(from || to, -EINVAL);
- assert_return(from != to, -EINVAL);
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- usec_t fr, t;
-
- r = journal_file_get_cutoff_monotonic_usec(f, boot_id, &fr, &t);
- if (r == -ENOENT)
- continue;
- if (r < 0)
- return r;
- if (r == 0)
- continue;
-
- if (found) {
- if (from)
- *from = MIN(fr, *from);
- if (to)
- *to = MAX(t, *to);
- } else {
- if (from)
- *from = fr;
- if (to)
- *to = t;
- found = true;
- }
- }
-
- return found;
-}
-
-void journal_print_header(sd_journal *j) {
- Iterator i;
- JournalFile *f;
- bool newline = false;
-
- assert(j);
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- if (newline)
- putchar('\n');
- else
- newline = true;
-
- journal_file_print_header(f);
- }
-}
-
-_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *bytes) {
- Iterator i;
- JournalFile *f;
- uint64_t sum = 0;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(bytes, -EINVAL);
-
- ORDERED_HASHMAP_FOREACH(f, j->files, i) {
- struct stat st;
-
- if (fstat(f->fd, &st) < 0)
- return -errno;
-
- sum += (uint64_t) st.st_blocks * 512ULL;
- }
-
- *bytes = sum;
- return 0;
-}
-
-_public_ int sd_journal_query_unique(sd_journal *j, const char *field) {
- char *f;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(!isempty(field), -EINVAL);
- assert_return(field_is_valid(field), -EINVAL);
-
- f = strdup(field);
- if (!f)
- return -ENOMEM;
-
- free(j->unique_field);
- j->unique_field = f;
- j->unique_file = NULL;
- j->unique_offset = 0;
- j->unique_file_lost = false;
-
- return 0;
-}
-
-_public_ int sd_journal_enumerate_unique(sd_journal *j, const void **data, size_t *l) {
- size_t k;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(data, -EINVAL);
- assert_return(l, -EINVAL);
- assert_return(j->unique_field, -EINVAL);
-
- k = strlen(j->unique_field);
-
- if (!j->unique_file) {
- if (j->unique_file_lost)
- return 0;
-
- j->unique_file = ordered_hashmap_first(j->files);
- if (!j->unique_file)
- return 0;
-
- j->unique_offset = 0;
- }
-
- for (;;) {
- JournalFile *of;
- Iterator i;
- Object *o;
- const void *odata;
- size_t ol;
- bool found;
- int r;
-
- /* Proceed to next data object in the field's linked list */
- if (j->unique_offset == 0) {
- r = journal_file_find_field_object(j->unique_file, j->unique_field, k, &o, NULL);
- if (r < 0)
- return r;
-
- j->unique_offset = r > 0 ? le64toh(o->field.head_data_offset) : 0;
- } else {
- r = journal_file_move_to_object(j->unique_file, OBJECT_DATA, j->unique_offset, &o);
- if (r < 0)
- return r;
-
- j->unique_offset = le64toh(o->data.next_field_offset);
- }
-
- /* We reached the end of the list? Then start again, with the next file */
- if (j->unique_offset == 0) {
- j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
- if (!j->unique_file)
- return 0;
-
- continue;
- }
-
- /* We do not use OBJECT_DATA context here, but OBJECT_UNUSED
- * instead, so that we can look at this data object at the same
- * time as one on another file */
- r = journal_file_move_to_object(j->unique_file, OBJECT_UNUSED, j->unique_offset, &o);
- if (r < 0)
- return r;
-
- /* Let's do the type check by hand, since we used 0 context above. */
- if (o->object.type != OBJECT_DATA) {
- log_debug("%s:offset " OFSfmt ": object has type %d, expected %d",
- j->unique_file->path, j->unique_offset,
- o->object.type, OBJECT_DATA);
- return -EBADMSG;
- }
-
- r = return_data(j, j->unique_file, o, &odata, &ol);
- if (r < 0)
- return r;
-
- /* Check if we have at least the field name and "=". */
- if (ol <= k) {
- log_debug("%s:offset " OFSfmt ": object has size %zu, expected at least %zu",
- j->unique_file->path, j->unique_offset,
- ol, k + 1);
- return -EBADMSG;
- }
-
- if (memcmp(odata, j->unique_field, k) || ((const char*) odata)[k] != '=') {
- log_debug("%s:offset " OFSfmt ": object does not start with \"%s=\"",
- j->unique_file->path, j->unique_offset,
- j->unique_field);
- return -EBADMSG;
- }
-
- /* OK, now let's see if we already returned this data
- * object by checking if it exists in the earlier
- * traversed files. */
- found = false;
- ORDERED_HASHMAP_FOREACH(of, j->files, i) {
- if (of == j->unique_file)
- break;
-
- /* Skip this file it didn't have any fields indexed */
- if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
- continue;
-
- r = journal_file_find_data_object_with_hash(of, odata, ol, le64toh(o->data.hash), NULL, NULL);
- if (r < 0)
- return r;
- if (r > 0) {
- found = true;
- break;
- }
- }
-
- if (found)
- continue;
-
- r = return_data(j, j->unique_file, o, data, l);
- if (r < 0)
- return r;
-
- return 1;
- }
-}
-
-_public_ void sd_journal_restart_unique(sd_journal *j) {
- if (!j)
- return;
-
- j->unique_file = NULL;
- j->unique_offset = 0;
- j->unique_file_lost = false;
-}
-
-_public_ int sd_journal_enumerate_fields(sd_journal *j, const char **field) {
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(field, -EINVAL);
-
- if (!j->fields_file) {
- if (j->fields_file_lost)
- return 0;
-
- j->fields_file = ordered_hashmap_first(j->files);
- if (!j->fields_file)
- return 0;
-
- j->fields_hash_table_index = 0;
- j->fields_offset = 0;
- }
-
- for (;;) {
- JournalFile *f, *of;
- Iterator i;
- uint64_t m;
- Object *o;
- size_t sz;
- bool found;
-
- f = j->fields_file;
-
- if (j->fields_offset == 0) {
- bool eof = false;
-
- /* We are not yet positioned at any field. Let's pick the first one */
- r = journal_file_map_field_hash_table(f);
- if (r < 0)
- return r;
-
- m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
- for (;;) {
- if (j->fields_hash_table_index >= m) {
- /* Reached the end of the hash table, go to the next file. */
- eof = true;
- break;
- }
-
- j->fields_offset = le64toh(f->field_hash_table[j->fields_hash_table_index].head_hash_offset);
-
- if (j->fields_offset != 0)
- break;
-
- /* Empty hash table bucket, go to next one */
- j->fields_hash_table_index++;
- }
-
- if (eof) {
- /* Proceed with next file */
- j->fields_file = ordered_hashmap_next(j->files, f->path);
- if (!j->fields_file) {
- *field = NULL;
- return 0;
- }
-
- j->fields_offset = 0;
- j->fields_hash_table_index = 0;
- continue;
- }
-
- } else {
- /* We are already positioned at a field. If so, let's figure out the next field from it */
-
- r = journal_file_move_to_object(f, OBJECT_FIELD, j->fields_offset, &o);
- if (r < 0)
- return r;
-
- j->fields_offset = le64toh(o->field.next_hash_offset);
- if (j->fields_offset == 0) {
- /* Reached the end of the hash table chain */
- j->fields_hash_table_index++;
- continue;
- }
- }
-
- /* We use OBJECT_UNUSED here, so that the iterator below doesn't remove our mmap window */
- r = journal_file_move_to_object(f, OBJECT_UNUSED, j->fields_offset, &o);
- if (r < 0)
- return r;
-
- /* Because we used OBJECT_UNUSED above, we need to do our type check manually */
- if (o->object.type != OBJECT_FIELD) {
- log_debug("%s:offset " OFSfmt ": object has type %i, expected %i", f->path, j->fields_offset, o->object.type, OBJECT_FIELD);
- return -EBADMSG;
- }
-
- sz = le64toh(o->object.size) - offsetof(Object, field.payload);
-
- /* Let's see if we already returned this field name before. */
- found = false;
- ORDERED_HASHMAP_FOREACH(of, j->files, i) {
- if (of == f)
- break;
-
- /* Skip this file it didn't have any fields indexed */
- if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
- continue;
-
- r = journal_file_find_field_object_with_hash(of, o->field.payload, sz, le64toh(o->field.hash), NULL, NULL);
- if (r < 0)
- return r;
- if (r > 0) {
- found = true;
- break;
- }
- }
-
- if (found)
- continue;
-
- /* Check if this is really a valid string containing no NUL byte */
- if (memchr(o->field.payload, 0, sz))
- return -EBADMSG;
-
- if (sz > j->data_threshold)
- sz = j->data_threshold;
-
- if (!GREEDY_REALLOC(j->fields_buffer, j->fields_buffer_allocated, sz + 1))
- return -ENOMEM;
-
- memcpy(j->fields_buffer, o->field.payload, sz);
- j->fields_buffer[sz] = 0;
-
- if (!field_is_valid(j->fields_buffer))
- return -EBADMSG;
-
- *field = j->fields_buffer;
- return 1;
- }
-}
-
-_public_ void sd_journal_restart_fields(sd_journal *j) {
- if (!j)
- return;
-
- j->fields_file = NULL;
- j->fields_hash_table_index = 0;
- j->fields_offset = 0;
- j->fields_file_lost = false;
-}
-
-_public_ int sd_journal_reliable_fd(sd_journal *j) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- return !j->on_network;
-}
-
-static char *lookup_field(const char *field, void *userdata) {
- sd_journal *j = userdata;
- const void *data;
- size_t size, d;
- int r;
-
- assert(field);
- assert(j);
-
- r = sd_journal_get_data(j, field, &data, &size);
- if (r < 0 ||
- size > REPLACE_VAR_MAX)
- return strdup(field);
-
- d = strlen(field) + 1;
-
- return strndup((const char*) data + d, size - d);
-}
-
-_public_ int sd_journal_get_catalog(sd_journal *j, char **ret) {
- const void *data;
- size_t size;
- sd_id128_t id;
- _cleanup_free_ char *text = NULL, *cid = NULL;
- char *t;
- int r;
-
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(ret, -EINVAL);
-
- r = sd_journal_get_data(j, "MESSAGE_ID", &data, &size);
- if (r < 0)
- return r;
-
- cid = strndup((const char*) data + 11, size - 11);
- if (!cid)
- return -ENOMEM;
-
- r = sd_id128_from_string(cid, &id);
- if (r < 0)
- return r;
-
- r = catalog_get(CATALOG_DATABASE, id, &text);
- if (r < 0)
- return r;
-
- t = replace_var(text, lookup_field, j);
- if (!t)
- return -ENOMEM;
-
- *ret = t;
- return 0;
-}
-
-_public_ int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret) {
- assert_return(ret, -EINVAL);
-
- return catalog_get(CATALOG_DATABASE, id, ret);
-}
-
-_public_ int sd_journal_set_data_threshold(sd_journal *j, size_t sz) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
-
- j->data_threshold = sz;
- return 0;
-}
-
-_public_ int sd_journal_get_data_threshold(sd_journal *j, size_t *sz) {
- assert_return(j, -EINVAL);
- assert_return(!journal_pid_changed(j), -ECHILD);
- assert_return(sz, -EINVAL);
-
- *sz = j->data_threshold;
- return 0;
-}
-
-_public_ int sd_journal_has_runtime_files(sd_journal *j) {
- assert_return(j, -EINVAL);
-
- return j->has_runtime_files;
-}
-
-_public_ int sd_journal_has_persistent_files(sd_journal *j) {
- assert_return(j, -EINVAL);
-
- return j->has_persistent_files;
-}
diff --git a/src/journal/test-catalog.c b/src/journal/test-catalog.c
index da6fcbca4d..6f2f9f5561 100644
--- a/src/journal/test-catalog.c
+++ b/src/journal/test-catalog.c
@@ -23,7 +23,7 @@
#include <locale.h>
#include <unistd.h>
-#include "sd-messages.h"
+#include <systemd/sd-messages.h>
#include "alloc-util.h"
#include "catalog.h"
diff --git a/src/journal/test-journal-enum.c b/src/journal/test-journal-enum.c
index e5e9d9dcb3..ffdc317e1d 100644
--- a/src/journal/test-journal-enum.c
+++ b/src/journal/test-journal-enum.c
@@ -19,7 +19,7 @@
#include <stdio.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "journal-internal.h"
#include "log.h"
diff --git a/src/journal/test-journal-flush.c b/src/journal/test-journal-flush.c
index 7bd9c40366..3dee462e74 100644
--- a/src/journal/test-journal-flush.c
+++ b/src/journal/test-journal-flush.c
@@ -19,7 +19,7 @@
#include <fcntl.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "alloc-util.h"
#include "journal-file.h"
diff --git a/src/journal/test-journal-init.c b/src/journal/test-journal-init.c
index ef21e2d05f..e6713034dd 100644
--- a/src/journal/test-journal-init.c
+++ b/src/journal/test-journal-init.c
@@ -17,7 +17,7 @@
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "log.h"
#include "parse-util.h"
diff --git a/src/journal/test-journal-interleaving.c b/src/journal/test-journal-interleaving.c
index 7f94990888..b47182dbfd 100644
--- a/src/journal/test-journal-interleaving.c
+++ b/src/journal/test-journal-interleaving.c
@@ -21,7 +21,7 @@
#include <fcntl.h>
#include <unistd.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "alloc-util.h"
#include "journal-file.h"
diff --git a/src/journal/test-journal-match.c b/src/journal/test-journal-match.c
index 3ab554b9b0..5ee2adb827 100644
--- a/src/journal/test-journal-match.c
+++ b/src/journal/test-journal-match.c
@@ -19,7 +19,7 @@
#include <stdio.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "alloc-util.h"
#include "journal-internal.h"
diff --git a/src/journal/test-journal-send.c b/src/journal/test-journal-send.c
index d70f0b0bc8..169082f9a4 100644
--- a/src/journal/test-journal-send.c
+++ b/src/journal/test-journal-send.c
@@ -21,7 +21,7 @@
#include <stdlib.h>
#include <unistd.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "macro.h"
diff --git a/src/journal/test-journal-stream.c b/src/journal/test-journal-stream.c
index 4e6f8c0f7b..57c6c0872d 100644
--- a/src/journal/test-journal-stream.c
+++ b/src/journal/test-journal-stream.c
@@ -20,7 +20,7 @@
#include <fcntl.h>
#include <unistd.h>
-#include "sd-journal.h"
+#include <systemd/sd-journal.h>
#include "alloc-util.h"
#include "journal-file.h"