]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/pstore/pstore.c
Merge pull request #18989 from yuwata/ordered-set-put-strdup
[thirdparty/systemd.git] / src / pstore / pstore.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 /* Copyright © 2019 Oracle and/or its affiliates. */
4
5 /* Generally speaking, the pstore contains a small number of files
6 * that in turn contain a small amount of data. */
7 #include <errno.h>
8 #include <stdio.h>
9 #include <stdio_ext.h>
10 #include <sys/prctl.h>
11 #include <sys/xattr.h>
12 #include <unistd.h>
13
14 #include "sd-daemon.h"
15 #include "sd-journal.h"
16 #include "sd-login.h"
17 #include "sd-messages.h"
18
19 #include "acl-util.h"
20 #include "alloc-util.h"
21 #include "capability-util.h"
22 #include "cgroup-util.h"
23 #include "compress.h"
24 #include "conf-parser.h"
25 #include "copy.h"
26 #include "dirent-util.h"
27 #include "escape.h"
28 #include "fd-util.h"
29 #include "fileio.h"
30 #include "fs-util.h"
31 #include "io-util.h"
32 #include "journal-importer.h"
33 #include "log.h"
34 #include "macro.h"
35 #include "main-func.h"
36 #include "mkdir.h"
37 #include "parse-util.h"
38 #include "process-util.h"
39 #include "signal-util.h"
40 #include "socket-util.h"
41 #include "special.h"
42 #include "sort-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
45 #include "strv.h"
46 #include "tmpfile-util.h"
47 #include "user-util.h"
48 #include "util.h"
49
50 /* Command line argument handling */
51 typedef enum PStoreStorage {
52 PSTORE_STORAGE_NONE,
53 PSTORE_STORAGE_EXTERNAL,
54 PSTORE_STORAGE_JOURNAL,
55 _PSTORE_STORAGE_MAX,
56 _PSTORE_STORAGE_INVALID = -EINVAL,
57 } PStoreStorage;
58
59 static const char* const pstore_storage_table[_PSTORE_STORAGE_MAX] = {
60 [PSTORE_STORAGE_NONE] = "none",
61 [PSTORE_STORAGE_EXTERNAL] = "external",
62 [PSTORE_STORAGE_JOURNAL] = "journal",
63 };
64
65 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(pstore_storage, PStoreStorage);
66 static DEFINE_CONFIG_PARSE_ENUM(config_parse_pstore_storage, pstore_storage, PStoreStorage, "Failed to parse storage setting");
67
68 static PStoreStorage arg_storage = PSTORE_STORAGE_EXTERNAL;
69
70 static bool arg_unlink = true;
71 static const char *arg_sourcedir = "/sys/fs/pstore";
72 static const char *arg_archivedir = "/var/lib/systemd/pstore";
73
74 static int parse_config(void) {
75 static const ConfigTableItem items[] = {
76 { "PStore", "Unlink", config_parse_bool, 0, &arg_unlink },
77 { "PStore", "Storage", config_parse_pstore_storage, 0, &arg_storage },
78 {}
79 };
80
81 return config_parse_many_nulstr(
82 PKGSYSCONFDIR "/pstore.conf",
83 CONF_PATHS_NULSTR("systemd/pstore.conf.d"),
84 "PStore\0",
85 config_item_table_lookup, items,
86 CONFIG_PARSE_WARN,
87 NULL,
88 NULL);
89 }
90
91 /* File list handling - PStoreEntry is the struct and
92 * and PStoreEntry is the type that contains all info
93 * about a pstore entry. */
94 typedef struct PStoreEntry {
95 struct dirent dirent;
96 bool is_binary;
97 bool handled;
98 char *content;
99 size_t content_size;
100 } PStoreEntry;
101
102 typedef struct PStoreList {
103 PStoreEntry *entries;
104 size_t n_allocated;
105 size_t n_entries;
106 } PStoreList;
107
108 static void pstore_entries_reset(PStoreList *list) {
109 for (size_t i = 0; i < list->n_entries; i++)
110 free(list->entries[i].content);
111 free(list->entries);
112 list->n_entries = 0;
113 }
114
115 static int compare_pstore_entries(const PStoreEntry *a, const PStoreEntry *b) {
116 return strcmp(a->dirent.d_name, b->dirent.d_name);
117 }
118
119 static int move_file(PStoreEntry *pe, const char *subdir) {
120 _cleanup_free_ char *ifd_path = NULL, *ofd_path = NULL;
121 _cleanup_free_ void *field = NULL;
122 const char *suffix, *message;
123 struct iovec iovec[2];
124 int n_iovec = 0, r;
125
126 if (pe->handled)
127 return 0;
128
129 ifd_path = path_join(arg_sourcedir, pe->dirent.d_name);
130 if (!ifd_path)
131 return log_oom();
132
133 ofd_path = path_join(arg_archivedir, subdir, pe->dirent.d_name);
134 if (!ofd_path)
135 return log_oom();
136
137 /* Always log to the journal */
138 suffix = arg_storage == PSTORE_STORAGE_EXTERNAL ? strjoina(" moved to ", ofd_path) : (char *)".";
139 message = strjoina("MESSAGE=PStore ", pe->dirent.d_name, suffix);
140 iovec[n_iovec++] = IOVEC_MAKE_STRING(message);
141
142 if (pe->content_size > 0) {
143 size_t field_size;
144
145 field_size = strlen("FILE=") + pe->content_size;
146 field = malloc(field_size);
147 if (!field)
148 return log_oom();
149 memcpy(stpcpy(field, "FILE="), pe->content, pe->content_size);
150 iovec[n_iovec++] = IOVEC_MAKE(field, field_size);
151 }
152
153 r = sd_journal_sendv(iovec, n_iovec);
154 if (r < 0)
155 return log_error_errno(r, "Failed to log pstore entry: %m");
156
157 if (arg_storage == PSTORE_STORAGE_EXTERNAL) {
158 /* Move file from pstore to external storage */
159 r = mkdir_parents(ofd_path, 0755);
160 if (r < 0)
161 return log_error_errno(r, "Failed to create directory %s: %m", ofd_path);
162 r = copy_file_atomic(ifd_path, ofd_path, 0600, 0, 0, COPY_REPLACE);
163 if (r < 0)
164 return log_error_errno(r, "Failed to copy_file_atomic: %s to %s", ifd_path, ofd_path);
165 }
166
167 /* If file copied properly, remove it from pstore */
168 if (arg_unlink)
169 (void) unlink(ifd_path);
170
171 pe->handled = true;
172
173 return 0;
174 }
175
176 static int write_dmesg(const char *dmesg, size_t size, const char *id) {
177 _cleanup_(unlink_and_freep) char *tmp_path = NULL;
178 _cleanup_free_ char *ofd_path = NULL;
179 _cleanup_close_ int ofd = -1;
180 ssize_t wr;
181 int r;
182
183 if (size == 0)
184 return 0;
185
186 assert(dmesg);
187
188 ofd_path = path_join(arg_archivedir, id, "dmesg.txt");
189 if (!ofd_path)
190 return log_oom();
191
192 ofd = open_tmpfile_linkable(ofd_path, O_CLOEXEC|O_CREAT|O_TRUNC|O_WRONLY, &tmp_path);
193 if (ofd < 0)
194 return log_error_errno(ofd, "Failed to open temporary file %s: %m", ofd_path);
195 wr = write(ofd, dmesg, size);
196 if (wr < 0)
197 return log_error_errno(errno, "Failed to store dmesg to %s: %m", ofd_path);
198 if (wr != (ssize_t)size)
199 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to store dmesg to %s. %zu bytes are lost.", ofd_path, size - wr);
200 r = link_tmpfile(ofd, tmp_path, ofd_path);
201 if (r < 0)
202 return log_error_errno(r, "Failed to write temporary file %s: %m", ofd_path);
203 tmp_path = mfree(tmp_path);
204
205 return 0;
206 }
207
208 static void process_dmesg_files(PStoreList *list) {
209 /* Move files, reconstruct dmesg.txt */
210 _cleanup_free_ char *dmesg = NULL, *dmesg_id = NULL;
211 size_t dmesg_size = 0, dmesg_allocated = 0;
212 bool dmesg_bad = false;
213 PStoreEntry *pe;
214
215 /* Handle each dmesg file: files processed in reverse
216 * order so as to properly reconstruct original dmesg */
217 for (size_t n = list->n_entries; n > 0; n--) {
218 bool move_file_and_continue = false;
219 _cleanup_free_ char *pe_id = NULL;
220 char *p;
221 size_t plen;
222
223 pe = &list->entries[n-1];
224
225 if (pe->handled)
226 continue;
227 if (!startswith(pe->dirent.d_name, "dmesg-"))
228 continue;
229
230 if (endswith(pe->dirent.d_name, ".enc.z")) /* indicates a problem */
231 move_file_and_continue = true;
232 p = strrchr(pe->dirent.d_name, '-');
233 if (!p)
234 move_file_and_continue = true;
235
236 if (move_file_and_continue) {
237 /* A dmesg file on which we do NO additional processing */
238 (void) move_file(pe, NULL);
239 continue;
240 }
241
242 /* See if this file is one of a related group of files
243 * in order to reconstruct dmesg */
244
245 /* When dmesg is written into pstore, it is done so in
246 * small chunks, whatever the exchange buffer size is
247 * with the underlying pstore backend (ie. EFI may be
248 * ~2KiB), which means an example pstore with approximately
249 * 64KB of storage may have up to roughly 32 dmesg files
250 * that could be related, depending upon the size of the
251 * original dmesg.
252 *
253 * Here we look at the dmesg filename and try to discern
254 * if files are part of a related group, meaning the same
255 * original dmesg.
256 *
257 * The two known pstore backends are EFI and ERST. These
258 * backends store data in the Common Platform Error
259 * Record, CPER, format. The dmesg- filename contains the
260 * CPER record id, a 64bit number (in decimal notation).
261 * In Linux, the record id is encoded with two digits for
262 * the dmesg part (chunk) number and 3 digits for the
263 * count number. So allowing an additional digit to
264 * compensate for advancing time, this code ignores the
265 * last six digits of the filename in determining the
266 * record id.
267 *
268 * For the EFI backend, the record id encodes an id in the
269 * upper 32 bits, and a timestamp in the lower 32-bits.
270 * So ignoring the least significant 6 digits has proven
271 * to generally identify related dmesg entries. */
272 #define PSTORE_FILENAME_IGNORE 6
273
274 /* determine common portion of record id */
275 ++p; /* move beyond dmesg- */
276 plen = strlen(p);
277 if (plen > PSTORE_FILENAME_IGNORE) {
278 pe_id = memdup_suffix0(p, plen - PSTORE_FILENAME_IGNORE);
279 if (!pe_id) {
280 log_oom();
281 return;
282 }
283 } else
284 pe_id = mfree(pe_id);
285
286 /* Now move file from pstore to archive storage */
287 move_file(pe, pe_id);
288
289 if (dmesg_bad)
290 continue;
291
292 /* If the current record id is NOT the same as the
293 * previous record id, then start a new dmesg.txt file */
294 if (!streq_ptr(pe_id, dmesg_id)) {
295 /* Encountered a new dmesg group, close out old one, open new one */
296 (void) write_dmesg(dmesg, dmesg_size, dmesg_id);
297 dmesg_size = 0;
298
299 /* now point dmesg_id to storage of pe_id */
300 free_and_replace(dmesg_id, pe_id);
301 }
302
303 /* Reconstruction of dmesg is done as a useful courtesy: do not fail, but don't write garbled
304 * output either. */
305 size_t needed = strlen(pe->dirent.d_name) + strlen(":\n") + pe->content_size + 1;
306 if (!GREEDY_REALLOC(dmesg, dmesg_allocated, dmesg_size + needed)) {
307 log_oom();
308 dmesg_bad = true;
309 continue;
310 }
311
312 dmesg_size += sprintf(dmesg + dmesg_size, "%s:\n", pe->dirent.d_name);
313 if (pe->content) {
314 memcpy(dmesg + dmesg_size, pe->content, pe->content_size);
315 dmesg_size += pe->content_size;
316 }
317
318 pe_id = mfree(pe_id);
319 }
320
321 if (!dmesg_bad)
322 (void) write_dmesg(dmesg, dmesg_size, dmesg_id);
323 }
324
325 static int list_files(PStoreList *list, const char *sourcepath) {
326 _cleanup_(closedirp) DIR *dirp = NULL;
327 struct dirent *de;
328 int r;
329
330 dirp = opendir(sourcepath);
331 if (!dirp)
332 return log_error_errno(errno, "Failed to opendir %s: %m", sourcepath);
333
334 FOREACH_DIRENT(de, dirp, return log_error_errno(errno, "Failed to iterate through %s: %m", sourcepath)) {
335 _cleanup_free_ char *ifd_path = NULL;
336
337 ifd_path = path_join(sourcepath, de->d_name);
338 if (!ifd_path)
339 return log_oom();
340
341 _cleanup_free_ char *buf = NULL;
342 size_t buf_size;
343
344 /* Now read contents of pstore file */
345 r = read_full_virtual_file(ifd_path, &buf, &buf_size);
346 if (r < 0) {
347 log_warning_errno(r, "Failed to read file %s, skipping: %m", ifd_path);
348 continue;
349 }
350
351 if (!GREEDY_REALLOC(list->entries, list->n_allocated, list->n_entries + 1))
352 return log_oom();
353
354 list->entries[list->n_entries++] = (PStoreEntry) {
355 .dirent = *de,
356 .content = TAKE_PTR(buf),
357 .content_size = buf_size,
358 .is_binary = true,
359 .handled = false,
360 };
361 }
362
363 return 0;
364 }
365
366 static int run(int argc, char *argv[]) {
367 _cleanup_(pstore_entries_reset) PStoreList list = {};
368 int r;
369
370 log_setup();
371
372 if (argc == 3) {
373 arg_sourcedir = argv[1];
374 arg_archivedir = argv[2];
375 } else if (argc > 1)
376 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
377 "This program takes zero or two arguments.");
378
379 /* Ignore all parse errors */
380 (void) parse_config();
381
382 log_debug("Selected storage: %s.", pstore_storage_to_string(arg_storage));
383 log_debug("Selected unlink: %s.", yes_no(arg_unlink));
384
385 if (arg_storage == PSTORE_STORAGE_NONE)
386 /* Do nothing, intentionally, leaving pstore untouched */
387 return 0;
388
389 /* Obtain list of files in pstore */
390 r = list_files(&list, arg_sourcedir);
391 if (r < 0)
392 return r;
393
394 /* Handle each pstore file */
395 /* Sort files lexigraphically ascending, generally needed by all */
396 typesafe_qsort(list.entries, list.n_entries, compare_pstore_entries);
397
398 /* Process known file types */
399 process_dmesg_files(&list);
400
401 /* Move left over files out of pstore */
402 for (size_t n = 0; n < list.n_entries; n++)
403 move_file(&list.entries[n], NULL);
404
405 return 0;
406 }
407
408 DEFINE_MAIN_FUNCTION(run);