]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/pstore/pstore.c
Merge pull request #25465 from DaanDeMeyer/repart-workspace
[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
49 /* Command line argument handling */
50 typedef enum PStoreStorage {
51 PSTORE_STORAGE_NONE,
52 PSTORE_STORAGE_EXTERNAL,
53 PSTORE_STORAGE_JOURNAL,
54 _PSTORE_STORAGE_MAX,
55 _PSTORE_STORAGE_INVALID = -EINVAL,
56 } PStoreStorage;
57
58 static const char* const pstore_storage_table[_PSTORE_STORAGE_MAX] = {
59 [PSTORE_STORAGE_NONE] = "none",
60 [PSTORE_STORAGE_EXTERNAL] = "external",
61 [PSTORE_STORAGE_JOURNAL] = "journal",
62 };
63
64 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(pstore_storage, PStoreStorage);
65 static DEFINE_CONFIG_PARSE_ENUM(config_parse_pstore_storage, pstore_storage, PStoreStorage, "Failed to parse storage setting");
66
67 static PStoreStorage arg_storage = PSTORE_STORAGE_EXTERNAL;
68
69 static bool arg_unlink = true;
70 static const char *arg_sourcedir = "/sys/fs/pstore";
71 static const char *arg_archivedir = "/var/lib/systemd/pstore";
72
73 static int parse_config(void) {
74 static const ConfigTableItem items[] = {
75 { "PStore", "Unlink", config_parse_bool, 0, &arg_unlink },
76 { "PStore", "Storage", config_parse_pstore_storage, 0, &arg_storage },
77 {}
78 };
79
80 return config_parse_many_nulstr(
81 PKGSYSCONFDIR "/pstore.conf",
82 CONF_PATHS_NULSTR("systemd/pstore.conf.d"),
83 "PStore\0",
84 config_item_table_lookup, items,
85 CONFIG_PARSE_WARN,
86 NULL,
87 NULL);
88 }
89
90 /* File list handling - PStoreEntry is the struct and
91 * and PStoreEntry is the type that contains all info
92 * about a pstore entry. */
93 typedef struct PStoreEntry {
94 struct dirent dirent;
95 bool is_binary;
96 bool handled;
97 char *content;
98 size_t content_size;
99 } PStoreEntry;
100
101 typedef struct PStoreList {
102 PStoreEntry *entries;
103 size_t n_entries;
104 } PStoreList;
105
106 static void pstore_entries_reset(PStoreList *list) {
107 for (size_t i = 0; i < list->n_entries; i++)
108 free(list->entries[i].content);
109 free(list->entries);
110 list->n_entries = 0;
111 }
112
113 static int compare_pstore_entries(const PStoreEntry *a, const PStoreEntry *b) {
114 return strcmp(a->dirent.d_name, b->dirent.d_name);
115 }
116
117 static int move_file(PStoreEntry *pe, const char *subdir1, const char *subdir2) {
118 _cleanup_free_ char *ifd_path = NULL, *ofd_path = NULL;
119 _cleanup_free_ void *field = NULL;
120 const char *suffix, *message;
121 struct iovec iovec[2];
122 int n_iovec = 0, r;
123
124 if (pe->handled)
125 return 0;
126
127 ifd_path = path_join(arg_sourcedir, pe->dirent.d_name);
128 if (!ifd_path)
129 return log_oom();
130
131 ofd_path = path_join(arg_archivedir, subdir1, subdir2, pe->dirent.d_name);
132 if (!ofd_path)
133 return log_oom();
134
135 /* Always log to the journal */
136 suffix = arg_storage == PSTORE_STORAGE_EXTERNAL ? strjoina(" moved to ", ofd_path) : (char *)".";
137 message = strjoina("MESSAGE=PStore ", pe->dirent.d_name, suffix);
138 iovec[n_iovec++] = IOVEC_MAKE_STRING(message);
139
140 if (pe->content_size > 0) {
141 size_t field_size;
142
143 field_size = strlen("FILE=") + pe->content_size;
144 field = malloc(field_size);
145 if (!field)
146 return log_oom();
147 memcpy(stpcpy(field, "FILE="), pe->content, pe->content_size);
148 iovec[n_iovec++] = IOVEC_MAKE(field, field_size);
149 }
150
151 r = sd_journal_sendv(iovec, n_iovec);
152 if (r < 0)
153 return log_error_errno(r, "Failed to log pstore entry: %m");
154
155 if (arg_storage == PSTORE_STORAGE_EXTERNAL) {
156 /* Move file from pstore to external storage */
157 r = mkdir_parents(ofd_path, 0755);
158 if (r < 0)
159 return log_error_errno(r, "Failed to create directory %s: %m", ofd_path);
160 r = copy_file_atomic(ifd_path, ofd_path, 0600, 0, 0, COPY_REPLACE);
161 if (r < 0)
162 return log_error_errno(r, "Failed to copy_file_atomic: %s to %s", ifd_path, ofd_path);
163 }
164
165 /* If file copied properly, remove it from pstore */
166 if (arg_unlink)
167 (void) unlink(ifd_path);
168
169 pe->handled = true;
170
171 return 0;
172 }
173
174 static int append_dmesg(PStoreEntry *pe, const char *subdir1, const char *subdir2) {
175 /* Append dmesg chunk to end, create if needed */
176 _cleanup_free_ char *ofd_path = NULL;
177 _cleanup_close_ int ofd = -1;
178 ssize_t wr;
179
180 assert(pe);
181
182 if (pe->content_size == 0)
183 return 0;
184
185 ofd_path = path_join(arg_archivedir, subdir1, subdir2, "dmesg.txt");
186 if (!ofd_path)
187 return log_oom();
188
189 ofd = open(ofd_path, O_CREAT|O_NOFOLLOW|O_NOCTTY|O_CLOEXEC|O_APPEND|O_WRONLY, 0640);
190 if (ofd < 0)
191 return log_error_errno(ofd, "Failed to open file %s: %m", ofd_path);
192 wr = write(ofd, pe->content, pe->content_size);
193 if (wr < 0)
194 return log_error_errno(errno, "Failed to store dmesg to %s: %m", ofd_path);
195 if ((size_t)wr != pe->content_size)
196 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to store dmesg to %s. %zu bytes are lost.", ofd_path, pe->content_size - wr);
197
198 return 0;
199 }
200
201 static int process_dmesg_files(PStoreList *list) {
202 /* Move files, reconstruct dmesg.txt */
203 _cleanup_free_ char *erst_subdir = NULL;
204 uint64_t last_record_id = 0;
205
206 /* When dmesg is written into pstore, it is done so in small chunks, whatever the exchange buffer
207 * size is with the underlying pstore backend (ie. EFI may be ~2KiB), which means an example
208 * pstore with approximately 64KB of storage may have up to roughly 32 dmesg files, some likely
209 * related.
210 *
211 * Here we look at the dmesg filename and try to discern if files are part of a related group,
212 * meaning the same original dmesg.
213 *
214 * The dmesg- filename contains the backend-type and the Common Platform Error Record, CPER,
215 * record id, a 64-bit number.
216 *
217 * Files are processed in reverse lexigraphical order so as to properly reconstruct original dmesg.*/
218
219 for (size_t n = list->n_entries; n > 0; n--) {
220 PStoreEntry *pe;
221 char *p;
222
223 pe = &list->entries[n-1];
224
225 if (pe->handled)
226 continue;
227 if (endswith(pe->dirent.d_name, ".enc.z")) /* indicates a problem */
228 continue;
229 if (!startswith(pe->dirent.d_name, "dmesg-"))
230 continue;
231
232 if ((p = startswith(pe->dirent.d_name, "dmesg-efi-"))) {
233 /* For the EFI backend, the 3 least significant digits of record id encodes a
234 * "count" number, the next 2 least significant digits for the dmesg part
235 * (chunk) number, and the remaining digits as the timestamp. See
236 * linux/drivers/firmware/efi/efi-pstore.c in efi_pstore_write(). */
237 _cleanup_free_ char *subdir1 = NULL, *subdir2 = NULL;
238 size_t plen = strlen(p);
239
240 if (plen < 6)
241 continue;
242
243 /* Extract base record id */
244 subdir1 = strndup(p, plen - 5);
245 if (!subdir1)
246 return log_oom();
247 /* Extract "count" field */
248 subdir2 = strndup(p + plen - 3, 3);
249 if (!subdir2)
250 return log_oom();
251
252 /* Now move file from pstore to archive storage */
253 (void) move_file(pe, subdir1, subdir2);
254
255 /* Append to the dmesg */
256 (void) append_dmesg(pe, subdir1, subdir2);
257 } else if ((p = startswith(pe->dirent.d_name, "dmesg-erst-"))) {
258 /* For the ERST backend, the record is a monotonically increasing number, seeded as
259 * a timestamp. See linux/drivers/acpi/apei/erst.c in erst_writer(). */
260 uint64_t record_id;
261
262 if (safe_atou64(p, &record_id) < 0)
263 continue;
264 if (last_record_id - 1 != record_id)
265 /* A discontinuity in the number has been detected, this current record id
266 * will become the directory name for all pieces of the dmesg in this
267 * series. */
268 if (free_and_strdup(&erst_subdir, p) < 0)
269 return log_oom();
270
271 /* Now move file from pstore to archive storage */
272 (void) move_file(pe, erst_subdir, NULL);
273
274 /* Append to the dmesg */
275 (void) append_dmesg(pe, erst_subdir, NULL);
276
277 /* Update, but keep erst_subdir for next file */
278 last_record_id = record_id;
279 } else
280 log_debug("Unknown backend, ignoring \"%s\".", pe->dirent.d_name);
281 }
282 return 0;
283 }
284
285 static int list_files(PStoreList *list, const char *sourcepath) {
286 _cleanup_(closedirp) DIR *dirp = NULL;
287 int r;
288
289 dirp = opendir(sourcepath);
290 if (!dirp)
291 return log_error_errno(errno, "Failed to opendir %s: %m", sourcepath);
292
293 FOREACH_DIRENT(de, dirp, return log_error_errno(errno, "Failed to iterate through %s: %m", sourcepath)) {
294 _cleanup_free_ char *ifd_path = NULL;
295
296 ifd_path = path_join(sourcepath, de->d_name);
297 if (!ifd_path)
298 return log_oom();
299
300 _cleanup_free_ char *buf = NULL;
301 size_t buf_size;
302
303 /* Now read contents of pstore file */
304 r = read_full_virtual_file(ifd_path, &buf, &buf_size);
305 if (r < 0) {
306 log_warning_errno(r, "Failed to read file %s, skipping: %m", ifd_path);
307 continue;
308 }
309
310 if (!GREEDY_REALLOC(list->entries, list->n_entries + 1))
311 return log_oom();
312
313 list->entries[list->n_entries++] = (PStoreEntry) {
314 .dirent = *de,
315 .content = TAKE_PTR(buf),
316 .content_size = buf_size,
317 .is_binary = true,
318 .handled = false,
319 };
320 }
321
322 return 0;
323 }
324
325 static int run(int argc, char *argv[]) {
326 _cleanup_(pstore_entries_reset) PStoreList list = {};
327 int r;
328
329 log_setup();
330
331 if (argc == 3) {
332 arg_sourcedir = argv[1];
333 arg_archivedir = argv[2];
334 } else if (argc > 1)
335 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
336 "This program takes zero or two arguments.");
337
338 /* Ignore all parse errors */
339 (void) parse_config();
340
341 log_debug("Selected storage: %s.", pstore_storage_to_string(arg_storage));
342 log_debug("Selected unlink: %s.", yes_no(arg_unlink));
343
344 if (arg_storage == PSTORE_STORAGE_NONE)
345 /* Do nothing, intentionally, leaving pstore untouched */
346 return 0;
347
348 /* Obtain list of files in pstore */
349 r = list_files(&list, arg_sourcedir);
350 if (r < 0)
351 return r;
352
353 /* Handle each pstore file */
354 /* Sort files lexigraphically ascending, generally needed by all */
355 typesafe_qsort(list.entries, list.n_entries, compare_pstore_entries);
356
357 /* Process known file types */
358 (void) process_dmesg_files(&list);
359
360 /* Move left over files out of pstore */
361 for (size_t n = 0; n < list.n_entries; n++)
362 (void) move_file(&list.entries[n], NULL, NULL);
363
364 return 0;
365 }
366
367 DEFINE_MAIN_FUNCTION(run);