• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <errno.h>
18 #include <stdatomic.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/time.h>
22 
23 #ifdef __BIONIC__
24 #include <android/set_abort_message.h>
25 #endif
26 
27 #include <log/event_tag_map.h>
28 #include <log/log_transport.h>
29 #include <private/android_filesystem_config.h>
30 #include <private/android_logger.h>
31 
32 #include "config_read.h" /* __android_log_config_read_close() definition */
33 #include "config_write.h"
34 #include "log_portability.h"
35 #include "logger.h"
36 
37 #define LOG_BUF_SIZE 1024
38 
39 static int __write_to_log_init(log_id_t, struct iovec* vec, size_t nr);
40 static int (*write_to_log)(log_id_t, struct iovec* vec,
41                            size_t nr) = __write_to_log_init;
42 
43 /*
44  * This is used by the C++ code to decide if it should write logs through
45  * the C code.  Basically, if /dev/socket/logd is available, we're running in
46  * the simulator rather than a desktop tool and want to use the device.
47  */
48 static enum {
49   kLogUninitialized,
50   kLogNotAvailable,
51   kLogAvailable
52 } g_log_status = kLogUninitialized;
53 
check_log_uid_permissions()54 static int check_log_uid_permissions() {
55 #if defined(__ANDROID__)
56   uid_t uid = __android_log_uid();
57 
58   /* Matches clientHasLogCredentials() in logd */
59   if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
60     uid = geteuid();
61     if ((uid != AID_SYSTEM) && (uid != AID_ROOT) && (uid != AID_LOG)) {
62       gid_t gid = getgid();
63       if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
64         gid = getegid();
65         if ((gid != AID_SYSTEM) && (gid != AID_ROOT) && (gid != AID_LOG)) {
66           int num_groups;
67           gid_t* groups;
68 
69           num_groups = getgroups(0, NULL);
70           if (num_groups <= 0) {
71             return -EPERM;
72           }
73           groups = calloc(num_groups, sizeof(gid_t));
74           if (!groups) {
75             return -ENOMEM;
76           }
77           num_groups = getgroups(num_groups, groups);
78           while (num_groups > 0) {
79             if (groups[num_groups - 1] == AID_LOG) {
80               break;
81             }
82             --num_groups;
83           }
84           free(groups);
85           if (num_groups <= 0) {
86             return -EPERM;
87           }
88         }
89       }
90     }
91   }
92 #endif
93   return 0;
94 }
95 
__android_log_cache_available(struct android_log_transport_write * node)96 static void __android_log_cache_available(
97     struct android_log_transport_write* node) {
98   size_t i;
99 
100   if (node->logMask) {
101     return;
102   }
103 
104   for (i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
105     if (node->write && (i != LOG_ID_KERNEL) &&
106         ((i != LOG_ID_SECURITY) || (check_log_uid_permissions() == 0)) &&
107         (!node->available || ((*node->available)(i) >= 0))) {
108       node->logMask |= 1 << i;
109     }
110   }
111 }
112 
__android_log_dev_available()113 LIBLOG_ABI_PUBLIC int __android_log_dev_available() {
114   struct android_log_transport_write* node;
115 
116   if (list_empty(&__android_log_transport_write)) {
117     return kLogUninitialized;
118   }
119 
120   write_transport_for_each(node, &__android_log_transport_write) {
121     __android_log_cache_available(node);
122     if (node->logMask) {
123       return kLogAvailable;
124     }
125   }
126   return kLogNotAvailable;
127 }
128 
129 #if defined(__ANDROID__)
130 static atomic_uintptr_t tagMap;
131 #endif
132 
133 /*
134  * Release any logger resources. A new log write will immediately re-acquire.
135  */
__android_log_close()136 LIBLOG_ABI_PUBLIC void __android_log_close() {
137   struct android_log_transport_write* transport;
138 #if defined(__ANDROID__)
139   EventTagMap* m;
140 #endif
141 
142   __android_log_lock();
143 
144   write_to_log = __write_to_log_init;
145 
146   /*
147    * Threads that are actively writing at this point are not held back
148    * by a lock and are at risk of dropping the messages with a return code
149    * -EBADF. Prefer to return error code than add the overhead of a lock to
150    * each log writing call to guarantee delivery. In addition, anyone
151    * calling this is doing so to release the logging resources and shut down,
152    * for them to do so with outstanding log requests in other threads is a
153    * disengenuous use of this function.
154    */
155 
156   write_transport_for_each(transport, &__android_log_persist_write) {
157     if (transport->close) {
158       (*transport->close)();
159     }
160   }
161 
162   write_transport_for_each(transport, &__android_log_transport_write) {
163     if (transport->close) {
164       (*transport->close)();
165     }
166   }
167 
168   __android_log_config_write_close();
169 
170 #if defined(__ANDROID__)
171   /*
172    * Additional risk here somewhat mitigated by immediately unlock flushing
173    * the processor cache. The multi-threaded race that we choose to accept,
174    * to minimize locking, is an atomic_load in a writer picking up a value
175    * just prior to entering this routine. There will be an use after free.
176    *
177    * Again, anyone calling this is doing so to release the logging resources
178    * is most probably going to quiesce then shut down; or to restart after
179    * a fork so the risk should be non-existent. For this reason we
180    * choose a mitigation stance for efficiency instead of incuring the cost
181    * of a lock for every log write.
182    */
183   m = (EventTagMap*)atomic_exchange(&tagMap, (uintptr_t)0);
184 #endif
185 
186   __android_log_unlock();
187 
188 #if defined(__ANDROID__)
189   if (m != (EventTagMap*)(uintptr_t)-1LL) android_closeEventTagMap(m);
190 #endif
191 }
192 
193 /* log_init_lock assumed */
__write_to_log_initialize()194 static int __write_to_log_initialize() {
195   struct android_log_transport_write* transport;
196   struct listnode* n;
197   int i = 0, ret = 0;
198 
199   __android_log_config_write();
200   write_transport_for_each_safe(transport, n, &__android_log_transport_write) {
201     __android_log_cache_available(transport);
202     if (!transport->logMask) {
203       list_remove(&transport->node);
204       continue;
205     }
206     if (!transport->open || ((*transport->open)() < 0)) {
207       if (transport->close) {
208         (*transport->close)();
209       }
210       list_remove(&transport->node);
211       continue;
212     }
213     ++ret;
214   }
215   write_transport_for_each_safe(transport, n, &__android_log_persist_write) {
216     __android_log_cache_available(transport);
217     if (!transport->logMask) {
218       list_remove(&transport->node);
219       continue;
220     }
221     if (!transport->open || ((*transport->open)() < 0)) {
222       if (transport->close) {
223         (*transport->close)();
224       }
225       list_remove(&transport->node);
226       continue;
227     }
228     ++i;
229   }
230   if (!ret && !i) {
231     return -ENODEV;
232   }
233 
234   return ret;
235 }
236 
237 /*
238  * Extract a 4-byte value from a byte stream. le32toh open coded
239  */
get4LE(const uint8_t * src)240 static inline uint32_t get4LE(const uint8_t* src) {
241   return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
242 }
243 
__write_to_log_daemon(log_id_t log_id,struct iovec * vec,size_t nr)244 static int __write_to_log_daemon(log_id_t log_id, struct iovec* vec, size_t nr) {
245   struct android_log_transport_write* node;
246   int ret;
247   struct timespec ts;
248   size_t len, i;
249 
250   for (len = i = 0; i < nr; ++i) {
251     len += vec[i].iov_len;
252   }
253   if (!len) {
254     return -EINVAL;
255   }
256 
257 #if defined(__ANDROID__)
258   clock_gettime(android_log_clockid(), &ts);
259 
260   if (log_id == LOG_ID_SECURITY) {
261     if (vec[0].iov_len < 4) {
262       return -EINVAL;
263     }
264 
265     ret = check_log_uid_permissions();
266     if (ret < 0) {
267       return ret;
268     }
269     if (!__android_log_security()) {
270       /* If only we could reset downstream logd counter */
271       return -EPERM;
272     }
273   } else if (log_id == LOG_ID_EVENTS) {
274     const char* tag;
275     size_t len;
276     EventTagMap *m, *f;
277 
278     if (vec[0].iov_len < 4) {
279       return -EINVAL;
280     }
281 
282     tag = NULL;
283     len = 0;
284     f = NULL;
285     m = (EventTagMap*)atomic_load(&tagMap);
286 
287     if (!m) {
288       ret = __android_log_trylock();
289       m = (EventTagMap*)atomic_load(&tagMap); /* trylock flush cache */
290       if (!m) {
291         m = android_openEventTagMap(NULL);
292         if (ret) { /* trylock failed, use local copy, mark for close */
293           f = m;
294         } else {
295           if (!m) { /* One chance to open map file */
296             m = (EventTagMap*)(uintptr_t)-1LL;
297           }
298           atomic_store(&tagMap, (uintptr_t)m);
299         }
300       }
301       if (!ret) { /* trylock succeeded, unlock */
302         __android_log_unlock();
303       }
304     }
305     if (m && (m != (EventTagMap*)(uintptr_t)-1LL)) {
306       tag = android_lookupEventTag_len(m, &len, get4LE(vec[0].iov_base));
307     }
308     ret = __android_log_is_loggable_len(ANDROID_LOG_INFO, tag, len,
309                                         ANDROID_LOG_VERBOSE);
310     if (f) { /* local copy marked for close */
311       android_closeEventTagMap(f);
312     }
313     if (!ret) {
314       return -EPERM;
315     }
316   } else {
317     /* Validate the incoming tag, tag content can not split across iovec */
318     char prio = ANDROID_LOG_VERBOSE;
319     const char* tag = vec[0].iov_base;
320     size_t len = vec[0].iov_len;
321     if (!tag) {
322       len = 0;
323     }
324     if (len > 0) {
325       prio = *tag;
326       if (len > 1) {
327         --len;
328         ++tag;
329       } else {
330         len = vec[1].iov_len;
331         tag = ((const char*)vec[1].iov_base);
332         if (!tag) {
333           len = 0;
334         }
335       }
336     }
337     /* tag must be nul terminated */
338     if (tag && strnlen(tag, len) >= len) {
339       tag = NULL;
340     }
341 
342     if (!__android_log_is_loggable_len(prio, tag, len - 1, ANDROID_LOG_VERBOSE)) {
343       return -EPERM;
344     }
345   }
346 #else
347   /* simulate clock_gettime(CLOCK_REALTIME, &ts); */
348   {
349     struct timeval tv;
350     gettimeofday(&tv, NULL);
351     ts.tv_sec = tv.tv_sec;
352     ts.tv_nsec = tv.tv_usec * 1000;
353   }
354 #endif
355 
356   ret = 0;
357   i = 1 << log_id;
358   write_transport_for_each(node, &__android_log_transport_write) {
359     if (node->logMask & i) {
360       ssize_t retval;
361       retval = (*node->write)(log_id, &ts, vec, nr);
362       if (ret >= 0) {
363         ret = retval;
364       }
365     }
366   }
367 
368   write_transport_for_each(node, &__android_log_persist_write) {
369     if (node->logMask & i) {
370       (void)(*node->write)(log_id, &ts, vec, nr);
371     }
372   }
373 
374   return ret;
375 }
376 
__write_to_log_init(log_id_t log_id,struct iovec * vec,size_t nr)377 static int __write_to_log_init(log_id_t log_id, struct iovec* vec, size_t nr) {
378   __android_log_lock();
379 
380   if (write_to_log == __write_to_log_init) {
381     int ret;
382 
383     ret = __write_to_log_initialize();
384     if (ret < 0) {
385       __android_log_unlock();
386       if (!list_empty(&__android_log_persist_write)) {
387         __write_to_log_daemon(log_id, vec, nr);
388       }
389       return ret;
390     }
391 
392     write_to_log = __write_to_log_daemon;
393   }
394 
395   __android_log_unlock();
396 
397   return write_to_log(log_id, vec, nr);
398 }
399 
__android_log_write(int prio,const char * tag,const char * msg)400 LIBLOG_ABI_PUBLIC int __android_log_write(int prio, const char* tag,
401                                           const char* msg) {
402   return __android_log_buf_write(LOG_ID_MAIN, prio, tag, msg);
403 }
404 
__android_log_buf_write(int bufID,int prio,const char * tag,const char * msg)405 LIBLOG_ABI_PUBLIC int __android_log_buf_write(int bufID, int prio,
406                                               const char* tag, const char* msg) {
407   struct iovec vec[3];
408   char tmp_tag[32];
409 
410   if (!tag) tag = "";
411 
412   /* XXX: This needs to go! */
413   if (bufID != LOG_ID_RADIO) {
414     switch (tag[0]) {
415       case 'H':
416         if (strcmp(tag + 1, "HTC_RIL" + 1)) break;
417         goto inform;
418       case 'R':
419         /* Any log tag with "RIL" as the prefix */
420         if (strncmp(tag + 1, "RIL" + 1, strlen("RIL") - 1)) break;
421         goto inform;
422       case 'Q':
423         /* Any log tag with "QC_RIL" as the prefix */
424         if (strncmp(tag + 1, "QC_RIL" + 1, strlen("QC_RIL") - 1)) break;
425         goto inform;
426       case 'I':
427         /* Any log tag with "IMS" as the prefix */
428         if (strncmp(tag + 1, "IMS" + 1, strlen("IMS") - 1)) break;
429         goto inform;
430       case 'A':
431         if (strcmp(tag + 1, "AT" + 1)) break;
432         goto inform;
433       case 'G':
434         if (strcmp(tag + 1, "GSM" + 1)) break;
435         goto inform;
436       case 'S':
437         if (strcmp(tag + 1, "STK" + 1) && strcmp(tag + 1, "SMS" + 1)) break;
438         goto inform;
439       case 'C':
440         if (strcmp(tag + 1, "CDMA" + 1)) break;
441         goto inform;
442       case 'P':
443         if (strcmp(tag + 1, "PHONE" + 1)) break;
444       /* FALLTHRU */
445       inform:
446         bufID = LOG_ID_RADIO;
447         snprintf(tmp_tag, sizeof(tmp_tag), "use-Rlog/RLOG-%s", tag);
448         tag = tmp_tag;
449       /* FALLTHRU */
450       default:
451         break;
452     }
453   }
454 
455 #if __BIONIC__
456   if (prio == ANDROID_LOG_FATAL) {
457     android_set_abort_message(msg);
458   }
459 #endif
460 
461   vec[0].iov_base = (unsigned char*)&prio;
462   vec[0].iov_len = 1;
463   vec[1].iov_base = (void*)tag;
464   vec[1].iov_len = strlen(tag) + 1;
465   vec[2].iov_base = (void*)msg;
466   vec[2].iov_len = strlen(msg) + 1;
467 
468   return write_to_log(bufID, vec, 3);
469 }
470 
__android_log_vprint(int prio,const char * tag,const char * fmt,va_list ap)471 LIBLOG_ABI_PUBLIC int __android_log_vprint(int prio, const char* tag,
472                                            const char* fmt, va_list ap) {
473   char buf[LOG_BUF_SIZE];
474 
475   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
476 
477   return __android_log_write(prio, tag, buf);
478 }
479 
__android_log_print(int prio,const char * tag,const char * fmt,...)480 LIBLOG_ABI_PUBLIC int __android_log_print(int prio, const char* tag,
481                                           const char* fmt, ...) {
482   va_list ap;
483   char buf[LOG_BUF_SIZE];
484 
485   va_start(ap, fmt);
486   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
487   va_end(ap);
488 
489   return __android_log_write(prio, tag, buf);
490 }
491 
__android_log_buf_print(int bufID,int prio,const char * tag,const char * fmt,...)492 LIBLOG_ABI_PUBLIC int __android_log_buf_print(int bufID, int prio,
493                                               const char* tag, const char* fmt,
494                                               ...) {
495   va_list ap;
496   char buf[LOG_BUF_SIZE];
497 
498   va_start(ap, fmt);
499   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
500   va_end(ap);
501 
502   return __android_log_buf_write(bufID, prio, tag, buf);
503 }
504 
__android_log_assert(const char * cond,const char * tag,const char * fmt,...)505 LIBLOG_ABI_PUBLIC void __android_log_assert(const char* cond, const char* tag,
506                                             const char* fmt, ...) {
507   char buf[LOG_BUF_SIZE];
508 
509   if (fmt) {
510     va_list ap;
511     va_start(ap, fmt);
512     vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
513     va_end(ap);
514   } else {
515     /* Msg not provided, log condition.  N.B. Do not use cond directly as
516      * format string as it could contain spurious '%' syntax (e.g.
517      * "%d" in "blocks%devs == 0").
518      */
519     if (cond)
520       snprintf(buf, LOG_BUF_SIZE, "Assertion failed: %s", cond);
521     else
522       strcpy(buf, "Unspecified assertion failed");
523   }
524 
525   // Log assertion failures to stderr for the benefit of "adb shell" users
526   // and gtests (http://b/23675822).
527   struct iovec iov[2] = {
528     { buf, strlen(buf) }, { (char*)"\n", 1 },
529   };
530   TEMP_FAILURE_RETRY(writev(2, iov, 2));
531 
532   __android_log_write(ANDROID_LOG_FATAL, tag, buf);
533   abort(); /* abort so we have a chance to debug the situation */
534            /* NOTREACHED */
535 }
536 
__android_log_bwrite(int32_t tag,const void * payload,size_t len)537 LIBLOG_ABI_PUBLIC int __android_log_bwrite(int32_t tag, const void* payload,
538                                            size_t len) {
539   struct iovec vec[2];
540 
541   vec[0].iov_base = &tag;
542   vec[0].iov_len = sizeof(tag);
543   vec[1].iov_base = (void*)payload;
544   vec[1].iov_len = len;
545 
546   return write_to_log(LOG_ID_EVENTS, vec, 2);
547 }
548 
__android_log_security_bwrite(int32_t tag,const void * payload,size_t len)549 LIBLOG_ABI_PUBLIC int __android_log_security_bwrite(int32_t tag,
550                                                     const void* payload,
551                                                     size_t len) {
552   struct iovec vec[2];
553 
554   vec[0].iov_base = &tag;
555   vec[0].iov_len = sizeof(tag);
556   vec[1].iov_base = (void*)payload;
557   vec[1].iov_len = len;
558 
559   return write_to_log(LOG_ID_SECURITY, vec, 2);
560 }
561 
562 /*
563  * Like __android_log_bwrite, but takes the type as well.  Doesn't work
564  * for the general case where we're generating lists of stuff, but very
565  * handy if we just want to dump an integer into the log.
566  */
__android_log_btwrite(int32_t tag,char type,const void * payload,size_t len)567 LIBLOG_ABI_PUBLIC int __android_log_btwrite(int32_t tag, char type,
568                                             const void* payload, size_t len) {
569   struct iovec vec[3];
570 
571   vec[0].iov_base = &tag;
572   vec[0].iov_len = sizeof(tag);
573   vec[1].iov_base = &type;
574   vec[1].iov_len = sizeof(type);
575   vec[2].iov_base = (void*)payload;
576   vec[2].iov_len = len;
577 
578   return write_to_log(LOG_ID_EVENTS, vec, 3);
579 }
580 
581 /*
582  * Like __android_log_bwrite, but used for writing strings to the
583  * event log.
584  */
__android_log_bswrite(int32_t tag,const char * payload)585 LIBLOG_ABI_PUBLIC int __android_log_bswrite(int32_t tag, const char* payload) {
586   struct iovec vec[4];
587   char type = EVENT_TYPE_STRING;
588   uint32_t len = strlen(payload);
589 
590   vec[0].iov_base = &tag;
591   vec[0].iov_len = sizeof(tag);
592   vec[1].iov_base = &type;
593   vec[1].iov_len = sizeof(type);
594   vec[2].iov_base = &len;
595   vec[2].iov_len = sizeof(len);
596   vec[3].iov_base = (void*)payload;
597   vec[3].iov_len = len;
598 
599   return write_to_log(LOG_ID_EVENTS, vec, 4);
600 }
601 
602 /*
603  * Like __android_log_security_bwrite, but used for writing strings to the
604  * security log.
605  */
__android_log_security_bswrite(int32_t tag,const char * payload)606 LIBLOG_ABI_PUBLIC int __android_log_security_bswrite(int32_t tag,
607                                                      const char* payload) {
608   struct iovec vec[4];
609   char type = EVENT_TYPE_STRING;
610   uint32_t len = strlen(payload);
611 
612   vec[0].iov_base = &tag;
613   vec[0].iov_len = sizeof(tag);
614   vec[1].iov_base = &type;
615   vec[1].iov_len = sizeof(type);
616   vec[2].iov_base = &len;
617   vec[2].iov_len = sizeof(len);
618   vec[3].iov_base = (void*)payload;
619   vec[3].iov_len = len;
620 
621   return write_to_log(LOG_ID_SECURITY, vec, 4);
622 }
623 
__write_to_log_null(log_id_t log_id,struct iovec * vec,size_t nr)624 static int __write_to_log_null(log_id_t log_id, struct iovec* vec, size_t nr) {
625   size_t len, i;
626 
627   if ((log_id < LOG_ID_MIN) || (log_id >= LOG_ID_MAX)) {
628     return -EINVAL;
629   }
630 
631   for (len = i = 0; i < nr; ++i) {
632     len += vec[i].iov_len;
633   }
634   if (!len) {
635     return -EINVAL;
636   }
637   return len;
638 }
639 
640 /* Following functions need access to our internal write_to_log status */
641 
642 LIBLOG_HIDDEN int __android_log_transport;
643 
android_set_log_transport(int transport_flag)644 LIBLOG_ABI_PUBLIC int android_set_log_transport(int transport_flag) {
645   int retval;
646 
647   if (transport_flag < 0) {
648     return -EINVAL;
649   }
650 
651   retval = LOGGER_NULL;
652 
653   __android_log_lock();
654 
655   if (transport_flag & LOGGER_NULL) {
656     write_to_log = __write_to_log_null;
657 
658     __android_log_unlock();
659 
660     return retval;
661   }
662 
663   __android_log_transport &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
664 
665   transport_flag &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
666 
667   if (__android_log_transport != transport_flag) {
668     __android_log_transport = transport_flag;
669     __android_log_config_write_close();
670     __android_log_config_read_close();
671 
672     write_to_log = __write_to_log_init;
673     /* generically we only expect these two values for write_to_log */
674   } else if ((write_to_log != __write_to_log_init) &&
675              (write_to_log != __write_to_log_daemon)) {
676     write_to_log = __write_to_log_init;
677   }
678 
679   retval = __android_log_transport;
680 
681   __android_log_unlock();
682 
683   return retval;
684 }
685 
android_get_log_transport()686 LIBLOG_ABI_PUBLIC int android_get_log_transport() {
687   int ret = LOGGER_DEFAULT;
688 
689   __android_log_lock();
690   if (write_to_log == __write_to_log_null) {
691     ret = LOGGER_NULL;
692   } else {
693     __android_log_transport &= LOGGER_LOCAL | LOGGER_LOGD | LOGGER_STDERR;
694     ret = __android_log_transport;
695     if ((write_to_log != __write_to_log_init) &&
696         (write_to_log != __write_to_log_daemon)) {
697       ret = -EINVAL;
698     }
699   }
700   __android_log_unlock();
701 
702   return ret;
703 }
704