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 
parse_config(void)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_entries;
105 } PStoreList;
106 
pstore_entries_reset(PStoreList * list)107 static void pstore_entries_reset(PStoreList *list) {
108         for (size_t i = 0; i < list->n_entries; i++)
109                 free(list->entries[i].content);
110         free(list->entries);
111         list->n_entries = 0;
112 }
113 
compare_pstore_entries(const PStoreEntry * a,const PStoreEntry * b)114 static int compare_pstore_entries(const PStoreEntry *a, const PStoreEntry *b) {
115         return strcmp(a->dirent.d_name, b->dirent.d_name);
116 }
117 
move_file(PStoreEntry * pe,const char * subdir)118 static int move_file(PStoreEntry *pe, const char *subdir) {
119         _cleanup_free_ char *ifd_path = NULL, *ofd_path = NULL;
120         _cleanup_free_ void *field = NULL;
121         const char *suffix, *message;
122         struct iovec iovec[2];
123         int n_iovec = 0, r;
124 
125         if (pe->handled)
126                 return 0;
127 
128         ifd_path = path_join(arg_sourcedir, pe->dirent.d_name);
129         if (!ifd_path)
130                 return log_oom();
131 
132         ofd_path = path_join(arg_archivedir, subdir, pe->dirent.d_name);
133         if (!ofd_path)
134                 return log_oom();
135 
136         /* Always log to the journal */
137         suffix = arg_storage == PSTORE_STORAGE_EXTERNAL ? strjoina(" moved to ", ofd_path) : (char *)".";
138         message = strjoina("MESSAGE=PStore ", pe->dirent.d_name, suffix);
139         iovec[n_iovec++] = IOVEC_MAKE_STRING(message);
140 
141         if (pe->content_size > 0) {
142                 size_t field_size;
143 
144                 field_size = strlen("FILE=") + pe->content_size;
145                 field = malloc(field_size);
146                 if (!field)
147                         return log_oom();
148                 memcpy(stpcpy(field, "FILE="), pe->content, pe->content_size);
149                 iovec[n_iovec++] = IOVEC_MAKE(field, field_size);
150         }
151 
152         r = sd_journal_sendv(iovec, n_iovec);
153         if (r < 0)
154                 return log_error_errno(r, "Failed to log pstore entry: %m");
155 
156         if (arg_storage == PSTORE_STORAGE_EXTERNAL) {
157                 /* Move file from pstore to external storage */
158                 r = mkdir_parents(ofd_path, 0755);
159                 if (r < 0)
160                         return log_error_errno(r, "Failed to create directory %s: %m", ofd_path);
161                 r = copy_file_atomic(ifd_path, ofd_path, 0600, 0, 0, COPY_REPLACE);
162                 if (r < 0)
163                         return log_error_errno(r, "Failed to copy_file_atomic: %s to %s", ifd_path, ofd_path);
164         }
165 
166         /* If file copied properly, remove it from pstore */
167         if (arg_unlink)
168                 (void) unlink(ifd_path);
169 
170         pe->handled = true;
171 
172         return 0;
173 }
174 
write_dmesg(const char * dmesg,size_t size,const char * id)175 static int write_dmesg(const char *dmesg, size_t size, const char *id) {
176         _cleanup_(unlink_and_freep) char *tmp_path = NULL;
177         _cleanup_free_ char *ofd_path = NULL;
178         _cleanup_close_ int ofd = -1;
179         ssize_t wr;
180         int r;
181 
182         if (size == 0)
183                 return 0;
184 
185         assert(dmesg);
186 
187         ofd_path = path_join(arg_archivedir, id, "dmesg.txt");
188         if (!ofd_path)
189                 return log_oom();
190 
191         ofd = open_tmpfile_linkable(ofd_path, O_CLOEXEC|O_CREAT|O_TRUNC|O_WRONLY, &tmp_path);
192         if (ofd < 0)
193                 return log_error_errno(ofd, "Failed to open temporary file %s: %m", ofd_path);
194         wr = write(ofd, dmesg, size);
195         if (wr < 0)
196                 return log_error_errno(errno, "Failed to store dmesg to %s: %m", ofd_path);
197         if (wr != (ssize_t)size)
198                 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to store dmesg to %s. %zu bytes are lost.", ofd_path, size - wr);
199         r = link_tmpfile(ofd, tmp_path, ofd_path);
200         if (r < 0)
201                 return log_error_errno(r, "Failed to write temporary file %s: %m", ofd_path);
202         tmp_path = mfree(tmp_path);
203 
204         return 0;
205 }
206 
process_dmesg_files(PStoreList * list)207 static void process_dmesg_files(PStoreList *list) {
208         /* Move files, reconstruct dmesg.txt */
209         _cleanup_free_ char *dmesg = NULL, *dmesg_id = NULL;
210         size_t dmesg_size = 0;
211         bool dmesg_bad = false;
212         PStoreEntry *pe;
213 
214         /* Handle each dmesg file: files processed in reverse
215          * order so as to properly reconstruct original dmesg */
216         for (size_t n = list->n_entries; n > 0; n--) {
217                 bool move_file_and_continue = false;
218                 _cleanup_free_ char *pe_id = NULL;
219                 char *p;
220                 size_t plen;
221 
222                 pe = &list->entries[n-1];
223 
224                 if (pe->handled)
225                         continue;
226                 if (!startswith(pe->dirent.d_name, "dmesg-"))
227                         continue;
228 
229                 if (endswith(pe->dirent.d_name, ".enc.z")) /* indicates a problem */
230                         move_file_and_continue = true;
231                 p = strrchr(pe->dirent.d_name, '-');
232                 if (!p)
233                         move_file_and_continue = true;
234 
235                 if (move_file_and_continue) {
236                         /* A dmesg file on which we do NO additional processing */
237                         (void) move_file(pe, NULL);
238                         continue;
239                 }
240 
241                 /* See if this file is one of a related group of files
242                  * in order to reconstruct dmesg */
243 
244                 /* When dmesg is written into pstore, it is done so in
245                  * small chunks, whatever the exchange buffer size is
246                  * with the underlying pstore backend (ie. EFI may be
247                  * ~2KiB), which means an example pstore with approximately
248                  * 64KB of storage may have up to roughly 32 dmesg files
249                  * that could be related, depending upon the size of the
250                  * original dmesg.
251                  *
252                  * Here we look at the dmesg filename and try to discern
253                  * if files are part of a related group, meaning the same
254                  * original dmesg.
255                  *
256                  * The two known pstore backends are EFI and ERST. These
257                  * backends store data in the Common Platform Error
258                  * Record, CPER, format. The dmesg- filename contains the
259                  * CPER record id, a 64bit number (in decimal notation).
260                  * In Linux, the record id is encoded with two digits for
261                  * the dmesg part (chunk) number and 3 digits for the
262                  * count number. So allowing an additional digit to
263                  * compensate for advancing time, this code ignores the
264                  * last six digits of the filename in determining the
265                  * record id.
266                  *
267                  * For the EFI backend, the record id encodes an id in the
268                  * upper 32 bits, and a timestamp in the lower 32-bits.
269                  * So ignoring the least significant 6 digits has proven
270                  * to generally identify related dmesg entries.  */
271 #define PSTORE_FILENAME_IGNORE 6
272 
273                 /* determine common portion of record id */
274                 ++p; /* move beyond dmesg- */
275                 plen = strlen(p);
276                 if (plen > PSTORE_FILENAME_IGNORE) {
277                         pe_id = memdup_suffix0(p, plen - PSTORE_FILENAME_IGNORE);
278                         if (!pe_id) {
279                                 log_oom();
280                                 return;
281                         }
282                 } else
283                         pe_id = mfree(pe_id);
284 
285                 /* Now move file from pstore to archive storage */
286                 move_file(pe, pe_id);
287 
288                 if (dmesg_bad)
289                         continue;
290 
291                 /* If the current record id is NOT the same as the
292                  * previous record id, then start a new dmesg.txt file */
293                 if (!streq_ptr(pe_id, dmesg_id)) {
294                         /* Encountered a new dmesg group, close out old one, open new one */
295                         (void) write_dmesg(dmesg, dmesg_size, dmesg_id);
296                         dmesg_size = 0;
297 
298                         /* now point dmesg_id to storage of pe_id */
299                         free_and_replace(dmesg_id, pe_id);
300                 }
301 
302                 /* Reconstruction of dmesg is done as a useful courtesy: do not fail, but don't write garbled
303                  * output either. */
304                 size_t needed = strlen(pe->dirent.d_name) + strlen(":\n") + pe->content_size + 1;
305                 if (!GREEDY_REALLOC(dmesg, dmesg_size + needed)) {
306                         log_oom();
307                         dmesg_bad = true;
308                         continue;
309                 }
310 
311                 dmesg_size += sprintf(dmesg + dmesg_size, "%s:\n", pe->dirent.d_name);
312                 if (pe->content) {
313                         memcpy(dmesg + dmesg_size, pe->content, pe->content_size);
314                         dmesg_size += pe->content_size;
315                 }
316 
317                 pe_id = mfree(pe_id);
318         }
319 
320         if (!dmesg_bad)
321                 (void) write_dmesg(dmesg, dmesg_size, dmesg_id);
322 }
323 
list_files(PStoreList * list,const char * sourcepath)324 static int list_files(PStoreList *list, const char *sourcepath) {
325         _cleanup_(closedirp) DIR *dirp = NULL;
326         int r;
327 
328         dirp = opendir(sourcepath);
329         if (!dirp)
330                 return log_error_errno(errno, "Failed to opendir %s: %m", sourcepath);
331 
332         FOREACH_DIRENT(de, dirp, return log_error_errno(errno, "Failed to iterate through %s: %m", sourcepath)) {
333                 _cleanup_free_ char *ifd_path = NULL;
334 
335                 ifd_path = path_join(sourcepath, de->d_name);
336                 if (!ifd_path)
337                         return log_oom();
338 
339                 _cleanup_free_ char *buf = NULL;
340                 size_t buf_size;
341 
342                 /* Now read contents of pstore file */
343                 r = read_full_virtual_file(ifd_path, &buf, &buf_size);
344                 if (r < 0) {
345                         log_warning_errno(r, "Failed to read file %s, skipping: %m", ifd_path);
346                         continue;
347                 }
348 
349                 if (!GREEDY_REALLOC(list->entries, list->n_entries + 1))
350                         return log_oom();
351 
352                 list->entries[list->n_entries++] = (PStoreEntry) {
353                         .dirent = *de,
354                         .content = TAKE_PTR(buf),
355                         .content_size = buf_size,
356                         .is_binary = true,
357                         .handled = false,
358                 };
359         }
360 
361         return 0;
362 }
363 
run(int argc,char * argv[])364 static int run(int argc, char *argv[]) {
365         _cleanup_(pstore_entries_reset) PStoreList list = {};
366         int r;
367 
368         log_setup();
369 
370         if (argc == 3) {
371                 arg_sourcedir = argv[1];
372                 arg_archivedir = argv[2];
373         } else if (argc > 1)
374                 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
375                                        "This program takes zero or two arguments.");
376 
377         /* Ignore all parse errors */
378         (void) parse_config();
379 
380         log_debug("Selected storage: %s.", pstore_storage_to_string(arg_storage));
381         log_debug("Selected unlink: %s.", yes_no(arg_unlink));
382 
383         if (arg_storage == PSTORE_STORAGE_NONE)
384                 /* Do nothing, intentionally, leaving pstore untouched */
385                 return 0;
386 
387         /* Obtain list of files in pstore */
388         r = list_files(&list, arg_sourcedir);
389         if (r < 0)
390                 return r;
391 
392         /* Handle each pstore file */
393         /* Sort files lexigraphically ascending, generally needed by all */
394         typesafe_qsort(list.entries, list.n_entries, compare_pstore_entries);
395 
396         /* Process known file types */
397         process_dmesg_files(&list);
398 
399         /* Move left over files out of pstore */
400         for (size_t n = 0; n < list.n_entries; n++)
401                 move_file(&list.entries[n], NULL);
402 
403         return 0;
404 }
405 
406 DEFINE_MAIN_FUNCTION(run);
407