1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <fcntl.h>
4 #include <sys/epoll.h>
5 #include <sys/mman.h>
6 #include <sys/socket.h>
7 #include <unistd.h>
8 
9 #include "sd-device.h"
10 #include "sd-messages.h"
11 
12 #include "alloc-util.h"
13 #include "device-util.h"
14 #include "escape.h"
15 #include "fd-util.h"
16 #include "format-util.h"
17 #include "fs-util.h"
18 #include "io-util.h"
19 #include "journald-kmsg.h"
20 #include "journald-server.h"
21 #include "journald-syslog.h"
22 #include "log.h"
23 #include "parse-util.h"
24 #include "process-util.h"
25 #include "stdio-util.h"
26 #include "string-util.h"
27 
server_forward_kmsg(Server * s,int priority,const char * identifier,const char * message,const struct ucred * ucred)28 void server_forward_kmsg(
29                 Server *s,
30                 int priority,
31                 const char *identifier,
32                 const char *message,
33                 const struct ucred *ucred) {
34 
35         _cleanup_free_ char *ident_buf = NULL;
36         struct iovec iovec[5];
37         char header_priority[DECIMAL_STR_MAX(priority) + 3],
38              header_pid[STRLEN("[]: ") + DECIMAL_STR_MAX(pid_t) + 1];
39         int n = 0;
40 
41         assert(s);
42         assert(priority >= 0);
43         assert(priority <= 999);
44         assert(message);
45 
46         if (_unlikely_(LOG_PRI(priority) > s->max_level_kmsg))
47                 return;
48 
49         if (_unlikely_(s->dev_kmsg_fd < 0))
50                 return;
51 
52         /* Never allow messages with kernel facility to be written to
53          * kmsg, regardless where the data comes from. */
54         priority = syslog_fixup_facility(priority);
55 
56         /* First: priority field */
57         xsprintf(header_priority, "<%i>", priority);
58         iovec[n++] = IOVEC_MAKE_STRING(header_priority);
59 
60         /* Second: identifier and PID */
61         if (ucred) {
62                 if (!identifier) {
63                         (void) get_process_comm(ucred->pid, &ident_buf);
64                         identifier = ident_buf;
65                 }
66 
67                 xsprintf(header_pid, "["PID_FMT"]: ", ucred->pid);
68 
69                 if (identifier)
70                         iovec[n++] = IOVEC_MAKE_STRING(identifier);
71 
72                 iovec[n++] = IOVEC_MAKE_STRING(header_pid);
73         } else if (identifier) {
74                 iovec[n++] = IOVEC_MAKE_STRING(identifier);
75                 iovec[n++] = IOVEC_MAKE_STRING(": ");
76         }
77 
78         /* Fourth: message */
79         iovec[n++] = IOVEC_MAKE_STRING(message);
80         iovec[n++] = IOVEC_MAKE_STRING("\n");
81 
82         if (writev(s->dev_kmsg_fd, iovec, n) < 0)
83                 log_debug_errno(errno, "Failed to write to /dev/kmsg for logging: %m");
84 }
85 
is_us(const char * identifier,const char * pid)86 static bool is_us(const char *identifier, const char *pid) {
87         pid_t pid_num;
88 
89         if (!identifier || !pid)
90                 return false;
91 
92         if (parse_pid(pid, &pid_num) < 0)
93                 return false;
94 
95         return pid_num == getpid_cached() &&
96                streq(identifier, program_invocation_short_name);
97 }
98 
dev_kmsg_record(Server * s,char * p,size_t l)99 void dev_kmsg_record(Server *s, char *p, size_t l) {
100 
101         _cleanup_free_ char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL, *identifier = NULL, *pid = NULL;
102         struct iovec iovec[N_IOVEC_META_FIELDS + 7 + N_IOVEC_KERNEL_FIELDS + 2 + N_IOVEC_UDEV_FIELDS];
103         char *kernel_device = NULL;
104         unsigned long long usec;
105         size_t n = 0, z = 0, j;
106         int priority, r;
107         char *e, *f, *k;
108         uint64_t serial;
109         size_t pl;
110         int saved_log_max_level = INT_MAX;
111         ClientContext *c = NULL;
112 
113         assert(s);
114         assert(p);
115 
116         if (l <= 0)
117                 return;
118 
119         e = memchr(p, ',', l);
120         if (!e)
121                 return;
122         *e = 0;
123 
124         r = safe_atoi(p, &priority);
125         if (r < 0 || priority < 0 || priority > 999)
126                 return;
127 
128         if (s->forward_to_kmsg && LOG_FAC(priority) != LOG_KERN)
129                 return;
130 
131         l -= (e - p) + 1;
132         p = e + 1;
133         e = memchr(p, ',', l);
134         if (!e)
135                 return;
136         *e = 0;
137 
138         r = safe_atou64(p, &serial);
139         if (r < 0)
140                 return;
141 
142         if (s->kernel_seqnum) {
143                 /* We already read this one? */
144                 if (serial < *s->kernel_seqnum)
145                         return;
146 
147                 /* Did we lose any? */
148                 if (serial > *s->kernel_seqnum)
149                         server_driver_message(s, 0,
150                                               "MESSAGE_ID=" SD_MESSAGE_JOURNAL_MISSED_STR,
151                                               LOG_MESSAGE("Missed %"PRIu64" kernel messages",
152                                                           serial - *s->kernel_seqnum),
153                                               NULL);
154 
155                 /* Make sure we never read this one again. Note that
156                  * we always store the next message serial we expect
157                  * here, simply because this makes handling the first
158                  * message with serial 0 easy. */
159                 *s->kernel_seqnum = serial + 1;
160         }
161 
162         l -= (e - p) + 1;
163         p = e + 1;
164         f = memchr(p, ';', l);
165         if (!f)
166                 return;
167         /* Kernel 3.6 has the flags field, kernel 3.5 lacks that */
168         e = memchr(p, ',', l);
169         if (!e || f < e)
170                 e = f;
171         *e = 0;
172 
173         r = safe_atollu(p, &usec);
174         if (r < 0)
175                 return;
176 
177         l -= (f - p) + 1;
178         p = f + 1;
179         e = memchr(p, '\n', l);
180         if (!e)
181                 return;
182         *e = 0;
183 
184         pl = e - p;
185         l -= (e - p) + 1;
186         k = e + 1;
187 
188         for (j = 0; l > 0 && j < N_IOVEC_KERNEL_FIELDS; j++) {
189                 char *m;
190                 /* Metadata fields attached */
191 
192                 if (*k != ' ')
193                         break;
194 
195                 k++, l--;
196 
197                 e = memchr(k, '\n', l);
198                 if (!e)
199                         goto finish;
200 
201                 *e = 0;
202 
203                 if (cunescape_length_with_prefix(k, e - k, "_KERNEL_", UNESCAPE_RELAX, &m) < 0)
204                         break;
205 
206                 if (startswith(m, "_KERNEL_DEVICE="))
207                         kernel_device = m + 15;
208 
209                 iovec[n++] = IOVEC_MAKE_STRING(m);
210                 z++;
211 
212                 l -= (e - k) + 1;
213                 k = e + 1;
214         }
215 
216         if (kernel_device) {
217                 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
218 
219                 if (sd_device_new_from_device_id(&d, kernel_device) >= 0) {
220                         const char *g;
221                         char *b;
222 
223                         if (sd_device_get_devname(d, &g) >= 0) {
224                                 b = strjoin("_UDEV_DEVNODE=", g);
225                                 if (b) {
226                                         iovec[n++] = IOVEC_MAKE_STRING(b);
227                                         z++;
228                                 }
229                         }
230 
231                         if (sd_device_get_sysname(d, &g) >= 0) {
232                                 b = strjoin("_UDEV_SYSNAME=", g);
233                                 if (b) {
234                                         iovec[n++] = IOVEC_MAKE_STRING(b);
235                                         z++;
236                                 }
237                         }
238 
239                         j = 0;
240                         FOREACH_DEVICE_DEVLINK(d, g) {
241 
242                                 if (j >= N_IOVEC_UDEV_FIELDS)
243                                         break;
244 
245                                 b = strjoin("_UDEV_DEVLINK=", g);
246                                 if (b) {
247                                         iovec[n++] = IOVEC_MAKE_STRING(b);
248                                         z++;
249                                 }
250 
251                                 j++;
252                         }
253                 }
254         }
255 
256         if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu", usec) >= 0)
257                 iovec[n++] = IOVEC_MAKE_STRING(source_time);
258 
259         iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=kernel");
260 
261         if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
262                 iovec[n++] = IOVEC_MAKE_STRING(syslog_priority);
263 
264         if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
265                 iovec[n++] = IOVEC_MAKE_STRING(syslog_facility);
266 
267         if (LOG_FAC(priority) == LOG_KERN)
268                 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=kernel");
269         else {
270                 pl -= syslog_parse_identifier((const char**) &p, &identifier, &pid);
271 
272                 /* Avoid logging any new messages when we're processing messages generated by ourselves via
273                  * log_info() and friends to avoid infinite loops. */
274                 if (is_us(identifier, pid)) {
275                         if (!ratelimit_below(&s->kmsg_own_ratelimit))
276                                 return;
277 
278                         saved_log_max_level = log_get_max_level();
279                         c = s->my_context;
280                         log_set_max_level(LOG_NULL);
281                 }
282 
283                 if (identifier) {
284                         syslog_identifier = strjoin("SYSLOG_IDENTIFIER=", identifier);
285                         if (syslog_identifier)
286                                 iovec[n++] = IOVEC_MAKE_STRING(syslog_identifier);
287                 }
288 
289                 if (pid) {
290                         syslog_pid = strjoin("SYSLOG_PID=", pid);
291                         if (syslog_pid)
292                                 iovec[n++] = IOVEC_MAKE_STRING(syslog_pid);
293                 }
294         }
295 
296         if (cunescape_length_with_prefix(p, pl, "MESSAGE=", UNESCAPE_RELAX, &message) >= 0)
297                 iovec[n++] = IOVEC_MAKE_STRING(message);
298 
299 
300         server_dispatch_message(s, iovec, n, ELEMENTSOF(iovec), c, NULL, priority, 0);
301 
302         if (saved_log_max_level != INT_MAX)
303                 log_set_max_level(saved_log_max_level);
304 
305 finish:
306         for (j = 0; j < z; j++)
307                 free(iovec[j].iov_base);
308 }
309 
server_read_dev_kmsg(Server * s)310 static int server_read_dev_kmsg(Server *s) {
311         char buffer[8192+1]; /* the kernel-side limit per record is 8K currently */
312         ssize_t l;
313 
314         assert(s);
315         assert(s->dev_kmsg_fd >= 0);
316 
317         l = read(s->dev_kmsg_fd, buffer, sizeof(buffer) - 1);
318         if (l == 0)
319                 return 0;
320         if (l < 0) {
321                 /* Old kernels who don't allow reading from /dev/kmsg
322                  * return EINVAL when we try. So handle this cleanly,
323                  * but don' try to ever read from it again. */
324                 if (errno == EINVAL) {
325                         s->dev_kmsg_event_source = sd_event_source_unref(s->dev_kmsg_event_source);
326                         return 0;
327                 }
328 
329                 if (ERRNO_IS_TRANSIENT(errno) || errno == EPIPE)
330                         return 0;
331 
332                 return log_error_errno(errno, "Failed to read from /dev/kmsg: %m");
333         }
334 
335         dev_kmsg_record(s, buffer, l);
336         return 1;
337 }
338 
server_flush_dev_kmsg(Server * s)339 int server_flush_dev_kmsg(Server *s) {
340         int r;
341 
342         assert(s);
343 
344         if (s->dev_kmsg_fd < 0)
345                 return 0;
346 
347         if (!s->dev_kmsg_readable)
348                 return 0;
349 
350         log_debug("Flushing /dev/kmsg...");
351 
352         for (;;) {
353                 r = server_read_dev_kmsg(s);
354                 if (r < 0)
355                         return r;
356 
357                 if (r == 0)
358                         break;
359         }
360 
361         return 0;
362 }
363 
dispatch_dev_kmsg(sd_event_source * es,int fd,uint32_t revents,void * userdata)364 static int dispatch_dev_kmsg(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
365         Server *s = userdata;
366 
367         assert(es);
368         assert(fd == s->dev_kmsg_fd);
369         assert(s);
370 
371         if (revents & EPOLLERR)
372                 log_warning("/dev/kmsg buffer overrun, some messages lost.");
373 
374         if (!(revents & EPOLLIN))
375                 log_error("Got invalid event from epoll for /dev/kmsg: %"PRIx32, revents);
376 
377         return server_read_dev_kmsg(s);
378 }
379 
server_open_dev_kmsg(Server * s)380 int server_open_dev_kmsg(Server *s) {
381         mode_t mode;
382         int r;
383 
384         assert(s);
385 
386         if (s->read_kmsg)
387                 mode = O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
388         else
389                 mode = O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY;
390 
391         s->dev_kmsg_fd = open("/dev/kmsg", mode);
392         if (s->dev_kmsg_fd < 0) {
393                 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING,
394                                errno, "Failed to open /dev/kmsg, ignoring: %m");
395                 return 0;
396         }
397 
398         if (!s->read_kmsg)
399                 return 0;
400 
401         r = sd_event_add_io(s->event, &s->dev_kmsg_event_source, s->dev_kmsg_fd, EPOLLIN, dispatch_dev_kmsg, s);
402         if (r < 0) {
403 
404                 /* This will fail with EPERM on older kernels where
405                  * /dev/kmsg is not readable. */
406                 if (r == -EPERM) {
407                         r = 0;
408                         goto fail;
409                 }
410 
411                 log_error_errno(r, "Failed to add /dev/kmsg fd to event loop: %m");
412                 goto fail;
413         }
414 
415         r = sd_event_source_set_priority(s->dev_kmsg_event_source, SD_EVENT_PRIORITY_IMPORTANT+10);
416         if (r < 0) {
417                 log_error_errno(r, "Failed to adjust priority of kmsg event source: %m");
418                 goto fail;
419         }
420 
421         s->dev_kmsg_readable = true;
422 
423         return 0;
424 
425 fail:
426         s->dev_kmsg_event_source = sd_event_source_unref(s->dev_kmsg_event_source);
427         s->dev_kmsg_fd = safe_close(s->dev_kmsg_fd);
428 
429         return r;
430 }
431 
server_open_kernel_seqnum(Server * s)432 int server_open_kernel_seqnum(Server *s) {
433         _cleanup_close_ int fd = -1;
434         const char *fn;
435         uint64_t *p;
436         int r;
437 
438         assert(s);
439 
440         /* We store the seqnum we last read in an mmapped file. That way we can just use it like a variable,
441          * but it is persistent and automatically flushed at reboot. */
442 
443         if (!s->read_kmsg)
444                 return 0;
445 
446         fn = strjoina(s->runtime_directory, "/kernel-seqnum");
447         fd = open(fn, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0644);
448         if (fd < 0) {
449                 log_error_errno(errno, "Failed to open %s, ignoring: %m", fn);
450                 return 0;
451         }
452 
453         r = posix_fallocate_loop(fd, 0, sizeof(uint64_t));
454         if (r < 0) {
455                 log_error_errno(r, "Failed to allocate sequential number file, ignoring: %m");
456                 return 0;
457         }
458 
459         p = mmap(NULL, sizeof(uint64_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
460         if (p == MAP_FAILED) {
461                 log_error_errno(errno, "Failed to map sequential number file, ignoring: %m");
462                 return 0;
463         }
464 
465         s->kernel_seqnum = p;
466 
467         return 0;
468 }
469