1 /*
2  * Copyright (C) 2007-2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "pmsg_reader.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 
26 #include <cutils/list.h>
27 #include <private/android_logger.h>
28 
29 #include "logger.h"
30 
PmsgRead(struct logger_list * logger_list,struct log_msg * log_msg)31 int PmsgRead(struct logger_list* logger_list, struct log_msg* log_msg) {
32   ssize_t ret;
33   off_t current, next;
34   struct __attribute__((__packed__)) {
35     android_pmsg_log_header_t p;
36     android_log_header_t l;
37     uint8_t prio;
38   } buf;
39   static uint8_t preread_count;
40 
41   memset(log_msg, 0, sizeof(*log_msg));
42 
43   if (atomic_load(&logger_list->fd) <= 0) {
44     int i, fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
45 
46     if (fd < 0) {
47       return -errno;
48     }
49     if (fd == 0) { /* Argggg */
50       fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
51       close(0);
52       if (fd < 0) {
53         return -errno;
54       }
55     }
56     i = atomic_exchange(&logger_list->fd, fd);
57     if ((i > 0) && (i != fd)) {
58       close(i);
59     }
60     preread_count = 0;
61   }
62 
63   while (1) {
64     int fd;
65 
66     if (preread_count < sizeof(buf)) {
67       fd = atomic_load(&logger_list->fd);
68       if (fd <= 0) {
69         return -EBADF;
70       }
71       ret = TEMP_FAILURE_RETRY(read(fd, &buf.p.magic + preread_count, sizeof(buf) - preread_count));
72       if (ret < 0) {
73         return -errno;
74       }
75       preread_count += ret;
76     }
77     if (preread_count != sizeof(buf)) {
78       return preread_count ? -EIO : -EAGAIN;
79     }
80     if ((buf.p.magic != LOGGER_MAGIC) || (buf.p.len <= sizeof(buf)) ||
81         (buf.p.len > (sizeof(buf) + LOGGER_ENTRY_MAX_PAYLOAD)) || (buf.l.id >= LOG_ID_MAX) ||
82         (buf.l.realtime.tv_nsec >= NS_PER_SEC) ||
83         ((buf.l.id != LOG_ID_EVENTS) && (buf.l.id != LOG_ID_SECURITY) &&
84          ((buf.prio == ANDROID_LOG_UNKNOWN) || (buf.prio == ANDROID_LOG_DEFAULT) ||
85           (buf.prio >= ANDROID_LOG_SILENT)))) {
86       do {
87         memmove(&buf.p.magic, &buf.p.magic + 1, --preread_count);
88       } while (preread_count && (buf.p.magic != LOGGER_MAGIC));
89       continue;
90     }
91     preread_count = 0;
92 
93     if ((logger_list->log_mask & (1 << buf.l.id)) &&
94         ((!logger_list->start.tv_sec && !logger_list->start.tv_nsec) ||
95          ((logger_list->start.tv_sec <= buf.l.realtime.tv_sec) &&
96           ((logger_list->start.tv_sec != buf.l.realtime.tv_sec) ||
97            (logger_list->start.tv_nsec <= buf.l.realtime.tv_nsec)))) &&
98         (!logger_list->pid || (logger_list->pid == buf.p.pid))) {
99       char* msg = reinterpret_cast<char*>(&log_msg->entry) + sizeof(log_msg->entry);
100       *msg = buf.prio;
101       fd = atomic_load(&logger_list->fd);
102       if (fd <= 0) {
103         return -EBADF;
104       }
105       ret = TEMP_FAILURE_RETRY(read(fd, msg + sizeof(buf.prio), buf.p.len - sizeof(buf)));
106       if (ret < 0) {
107         return -errno;
108       }
109       if (ret != (ssize_t)(buf.p.len - sizeof(buf))) {
110         return -EIO;
111       }
112 
113       log_msg->entry.len = buf.p.len - sizeof(buf) + sizeof(buf.prio);
114       log_msg->entry.hdr_size = sizeof(log_msg->entry);
115       log_msg->entry.pid = buf.p.pid;
116       log_msg->entry.tid = buf.l.tid;
117       log_msg->entry.sec = buf.l.realtime.tv_sec;
118       log_msg->entry.nsec = buf.l.realtime.tv_nsec;
119       log_msg->entry.lid = buf.l.id;
120       log_msg->entry.uid = buf.p.uid;
121 
122       return ret + sizeof(buf.prio) + log_msg->entry.hdr_size;
123     }
124 
125     fd = atomic_load(&logger_list->fd);
126     if (fd <= 0) {
127       return -EBADF;
128     }
129     current = TEMP_FAILURE_RETRY(lseek(fd, (off_t)0, SEEK_CUR));
130     if (current < 0) {
131       return -errno;
132     }
133     fd = atomic_load(&logger_list->fd);
134     if (fd <= 0) {
135       return -EBADF;
136     }
137     next = TEMP_FAILURE_RETRY(lseek(fd, (off_t)(buf.p.len - sizeof(buf)), SEEK_CUR));
138     if (next < 0) {
139       return -errno;
140     }
141     if ((next - current) != (ssize_t)(buf.p.len - sizeof(buf))) {
142       return -EIO;
143     }
144   }
145 }
146 
PmsgClose(struct logger_list * logger_list)147 void PmsgClose(struct logger_list* logger_list) {
148   int fd = atomic_exchange(&logger_list->fd, 0);
149   if (fd > 0) {
150     close(fd);
151   }
152 }
153 
realloc_or_free(void * ptr,size_t new_size)154 static void* realloc_or_free(void* ptr, size_t new_size) {
155   void* result = realloc(ptr, new_size);
156   if (!result) {
157     free(ptr);
158   }
159   return result;
160 }
161 
__android_log_pmsg_file_read(log_id_t logId,char prio,const char * prefix,__android_log_pmsg_file_read_fn fn,void * arg)162 ssize_t __android_log_pmsg_file_read(log_id_t logId, char prio, const char* prefix,
163                                      __android_log_pmsg_file_read_fn fn, void* arg) {
164   ssize_t ret;
165   struct logger_list logger_list;
166   struct content {
167     struct listnode node;
168     struct logger_entry entry;
169   } * content;
170   struct names {
171     struct listnode node;
172     struct listnode content;
173     log_id_t id;
174     char prio;
175     char name[];
176   } * names;
177   struct listnode name_list;
178   struct listnode *node, *n;
179   size_t len, prefix_len;
180 
181   if (!fn) {
182     return -EINVAL;
183   }
184 
185   /* Add just enough clues in logger_list and transp to make API function */
186   memset(&logger_list, 0, sizeof(logger_list));
187 
188   logger_list.mode = ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK;
189   logger_list.log_mask = (unsigned)-1;
190   if (logId != LOG_ID_ANY) {
191     logger_list.log_mask = (1 << logId);
192   }
193   logger_list.log_mask &= ~((1 << LOG_ID_KERNEL) | (1 << LOG_ID_EVENTS) | (1 << LOG_ID_SECURITY));
194   if (!logger_list.log_mask) {
195     return -EINVAL;
196   }
197 
198   /* Initialize name list */
199   list_init(&name_list);
200 
201   ret = SSIZE_MAX;
202 
203   /* Validate incoming prefix, shift until it contains only 0 or 1 : or / */
204   prefix_len = 0;
205   if (prefix) {
206     const char *prev = NULL, *last = NULL, *cp = prefix;
207     while ((cp = strpbrk(cp, "/:"))) {
208       prev = last;
209       last = cp;
210       cp = cp + 1;
211     }
212     if (prev) {
213       prefix = prev + 1;
214     }
215     prefix_len = strlen(prefix);
216   }
217 
218   /* Read the file content */
219   log_msg log_msg;
220   while (PmsgRead(&logger_list, &log_msg) > 0) {
221     const char* cp;
222     size_t hdr_size = log_msg.entry.hdr_size;
223 
224     char* msg = (char*)&log_msg + hdr_size;
225     const char* split = NULL;
226 
227     if (hdr_size != sizeof(log_msg.entry)) {
228       continue;
229     }
230     /* Check for invalid sequence number */
231     if (log_msg.entry.nsec % ANDROID_LOG_PMSG_FILE_SEQUENCE ||
232         (log_msg.entry.nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
233             ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE) {
234       continue;
235     }
236 
237     /* Determine if it has <dirbase>:<filebase> format for tag */
238     len = log_msg.entry.len - sizeof(prio);
239     for (cp = msg + sizeof(prio); *cp && isprint(*cp) && !isspace(*cp) && --len; ++cp) {
240       if (*cp == ':') {
241         if (split) {
242           break;
243         }
244         split = cp;
245       }
246     }
247     if (*cp || !split) {
248       continue;
249     }
250 
251     /* Filters */
252     if (prefix_len && strncmp(msg + sizeof(prio), prefix, prefix_len)) {
253       size_t offset;
254       /*
255        *   Allow : to be a synonym for /
256        * Things we do dealing with const char * and do not alloc
257        */
258       split = strchr(prefix, ':');
259       if (split) {
260         continue;
261       }
262       split = strchr(prefix, '/');
263       if (!split) {
264         continue;
265       }
266       offset = split - prefix;
267       if ((msg[offset + sizeof(prio)] != ':') || strncmp(msg + sizeof(prio), prefix, offset)) {
268         continue;
269       }
270       ++offset;
271       if ((prefix_len > offset) &&
272           strncmp(&msg[offset + sizeof(prio)], split + 1, prefix_len - offset)) {
273         continue;
274       }
275     }
276 
277     if ((prio != ANDROID_LOG_ANY) && (*msg < prio)) {
278       continue;
279     }
280 
281     /* check if there is an existing entry */
282     list_for_each(node, &name_list) {
283       names = node_to_item(node, struct names, node);
284       if (!strcmp(names->name, msg + sizeof(prio)) && names->id == log_msg.entry.lid &&
285           names->prio == *msg) {
286         break;
287       }
288     }
289 
290     /* We do not have an existing entry, create and add one */
291     if (node == &name_list) {
292       static const char numbers[] = "0123456789";
293       unsigned long long nl;
294 
295       len = strlen(msg + sizeof(prio)) + 1;
296       names = static_cast<struct names*>(calloc(1, sizeof(*names) + len));
297       if (!names) {
298         ret = -ENOMEM;
299         break;
300       }
301       strcpy(names->name, msg + sizeof(prio));
302       names->id = static_cast<log_id_t>(log_msg.entry.lid);
303       names->prio = *msg;
304       list_init(&names->content);
305       /*
306        * Insert in reverse numeric _then_ alpha sorted order as
307        * representative of log rotation:
308        *
309        *   log.10
310        *   klog.10
311        *   . . .
312        *   log.2
313        *   klog.2
314        *   log.1
315        *   klog.1
316        *   log
317        *   klog
318        *
319        * thus when we present the content, we are provided the oldest
320        * first, which when 'refreshed' could spill off the end of the
321        * pmsg FIFO but retaining the newest data for last with best
322        * chances to survive.
323        */
324       nl = 0;
325       cp = strpbrk(names->name, numbers);
326       if (cp) {
327         nl = strtoull(cp, NULL, 10);
328       }
329       list_for_each_reverse(node, &name_list) {
330         struct names* a_name = node_to_item(node, struct names, node);
331         const char* r = a_name->name;
332         int compare = 0;
333 
334         unsigned long long nr = 0;
335         cp = strpbrk(r, numbers);
336         if (cp) {
337           nr = strtoull(cp, NULL, 10);
338         }
339         if (nr != nl) {
340           compare = (nl > nr) ? 1 : -1;
341         }
342         if (compare == 0) {
343           compare = strcmp(names->name, r);
344         }
345         if (compare <= 0) {
346           break;
347         }
348       }
349       list_add_head(node, &names->node);
350     }
351 
352     /* Remove any file fragments that match our sequence number */
353     list_for_each_safe(node, n, &names->content) {
354       content = node_to_item(node, struct content, node);
355       if (log_msg.entry.nsec == content->entry.nsec) {
356         list_remove(&content->node);
357         free(content);
358       }
359     }
360 
361     /* Add content */
362     content = static_cast<struct content*>(
363         calloc(1, sizeof(content->node) + hdr_size + log_msg.entry.len));
364     if (!content) {
365       ret = -ENOMEM;
366       break;
367     }
368     memcpy(&content->entry, &log_msg.entry, hdr_size + log_msg.entry.len);
369 
370     /* Insert in sequence number sorted order, to ease reconstruction */
371     list_for_each_reverse(node, &names->content) {
372       if ((node_to_item(node, struct content, node))->entry.nsec < log_msg.entry.nsec) {
373         break;
374       }
375     }
376     list_add_head(node, &content->node);
377   }
378   PmsgClose(&logger_list);
379 
380   /* Progress through all the collected files */
381   list_for_each_safe(node, n, &name_list) {
382     struct listnode *content_node, *m;
383     char* buf;
384     size_t sequence, tag_len;
385 
386     names = node_to_item(node, struct names, node);
387 
388     /* Construct content into a linear buffer */
389     buf = NULL;
390     len = 0;
391     sequence = 0;
392     tag_len = strlen(names->name) + sizeof(char); /* tag + nul */
393     list_for_each_safe(content_node, m, &names->content) {
394       ssize_t add_len;
395 
396       content = node_to_item(content_node, struct content, node);
397       add_len = content->entry.len - tag_len - sizeof(prio);
398       if (add_len <= 0) {
399         list_remove(content_node);
400         free(content);
401         continue;
402       }
403 
404       if (!buf) {
405         buf = static_cast<char*>(malloc(sizeof(char)));
406         if (!buf) {
407           ret = -ENOMEM;
408           list_remove(content_node);
409           free(content);
410           continue;
411         }
412         *buf = '\0';
413       }
414 
415       /* Missing sequence numbers */
416       while (sequence < content->entry.nsec) {
417         /* plus space for enforced nul */
418         buf = static_cast<char*>(realloc_or_free(buf, len + sizeof(char) + sizeof(char)));
419         if (!buf) {
420           break;
421         }
422         buf[len] = '\f'; /* Mark missing content with a form feed */
423         buf[++len] = '\0';
424         sequence += ANDROID_LOG_PMSG_FILE_SEQUENCE;
425       }
426       if (!buf) {
427         ret = -ENOMEM;
428         list_remove(content_node);
429         free(content);
430         continue;
431       }
432       /* plus space for enforced nul */
433       buf = static_cast<char*>(realloc_or_free(buf, len + add_len + sizeof(char)));
434       if (!buf) {
435         ret = -ENOMEM;
436         list_remove(content_node);
437         free(content);
438         continue;
439       }
440       memcpy(buf + len, (char*)&content->entry + content->entry.hdr_size + tag_len + sizeof(prio),
441              add_len);
442       len += add_len;
443       buf[len] = '\0'; /* enforce trailing hidden nul */
444       sequence = content->entry.nsec + ANDROID_LOG_PMSG_FILE_SEQUENCE;
445 
446       list_remove(content_node);
447       free(content);
448     }
449     if (buf) {
450       if (len) {
451         /* Buffer contains enforced trailing nul just beyond length */
452         ssize_t r;
453         *strchr(names->name, ':') = '/'; /* Convert back to filename */
454         r = (*fn)(names->id, names->prio, names->name, buf, len, arg);
455         if ((ret >= 0) && (r > 0)) {
456           if (ret == SSIZE_MAX) {
457             ret = r;
458           } else {
459             ret += r;
460           }
461         } else if (r < ret) {
462           ret = r;
463         }
464       }
465       free(buf);
466     }
467     list_remove(node);
468     free(names);
469   }
470   return (ret == SSIZE_MAX) ? -ENOENT : ret;
471 }
472