logd_writer.c revision db8a266aea6c12b0fb8ee3587d72333662b05266
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 <endian.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <inttypes.h>
21#include <poll.h>
22#include <stdarg.h>
23#include <stdatomic.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include <sys/socket.h>
30#include <sys/un.h>
31#include <time.h>
32#include <unistd.h>
33
34#include <cutils/sockets.h>
35#include <log/logger.h>
36#include <private/android_filesystem_config.h>
37#include <private/android_logger.h>
38
39#include "config_write.h"
40#include "log_portability.h"
41#include "logger.h"
42
43/* branchless on many architectures. */
44#define min(x,y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
45
46static int logdAvailable(log_id_t LogId);
47static int logdOpen();
48static void logdClose();
49static int logdWrite(log_id_t logId, struct timespec *ts,
50                     struct iovec *vec, size_t nr);
51
52LIBLOG_HIDDEN struct android_log_transport_write logdLoggerWrite = {
53    .node = { &logdLoggerWrite.node, &logdLoggerWrite.node },
54    .context.sock = -1,
55    .name = "logd",
56    .available = logdAvailable,
57    .open = logdOpen,
58    .close = logdClose,
59    .write = logdWrite,
60};
61
62/* log_init_lock assumed */
63static int logdOpen()
64{
65    int i, ret = 0;
66
67    i = atomic_load(&logdLoggerWrite.context.sock);
68    if (i < 0) {
69        i = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
70        if (i < 0) {
71            ret = -errno;
72        } else {
73            struct sockaddr_un un;
74            memset(&un, 0, sizeof(struct sockaddr_un));
75            un.sun_family = AF_UNIX;
76            strcpy(un.sun_path, "/dev/socket/logdw");
77
78            if (TEMP_FAILURE_RETRY(connect(i, (struct sockaddr *)&un,
79                                           sizeof(struct sockaddr_un))) < 0) {
80                ret = -errno;
81                close(i);
82            } else {
83                ret = atomic_exchange(&logdLoggerWrite.context.sock, i);
84                if ((ret >= 0) && (ret != i)) {
85                    close(ret);
86                }
87                ret = 0;
88            }
89        }
90    }
91
92    return ret;
93}
94
95static void logdClose()
96{
97    int sock = atomic_exchange(&logdLoggerWrite.context.sock, -1);
98    if (sock >= 0) {
99        close(sock);
100    }
101}
102
103static int logdAvailable(log_id_t logId)
104{
105    if (logId > LOG_ID_SECURITY) {
106        return -EINVAL;
107    }
108    if (atomic_load(&logdLoggerWrite.context.sock) < 0) {
109        if (access("/dev/socket/logdw", W_OK) == 0) {
110            return 0;
111        }
112        return -EBADF;
113    }
114    return 1;
115}
116
117static int logdWrite(log_id_t logId, struct timespec *ts,
118                     struct iovec *vec, size_t nr)
119{
120    ssize_t ret;
121    static const unsigned headerLength = 1;
122    struct iovec newVec[nr + headerLength];
123    android_log_header_t header;
124    size_t i, payloadSize;
125    static atomic_int_fast32_t dropped;
126    static atomic_int_fast32_t droppedSecurity;
127
128    if (atomic_load(&logdLoggerWrite.context.sock) < 0) {
129        return -EBADF;
130    }
131
132    /* logd, after initialization and priv drop */
133    if (__android_log_uid() == AID_LOGD) {
134        /*
135         * ignore log messages we send to ourself (logd).
136         * Such log messages are often generated by libraries we depend on
137         * which use standard Android logging.
138         */
139        return 0;
140    }
141
142    /*
143     *  struct {
144     *      // what we provide to socket
145     *      android_log_header_t header;
146     *      // caller provides
147     *      union {
148     *          struct {
149     *              char     prio;
150     *              char     payload[];
151     *          } string;
152     *          struct {
153     *              uint32_t tag
154     *              char     payload[];
155     *          } binary;
156     *      };
157     *  };
158     */
159
160    header.tid = gettid();
161    header.realtime.tv_sec = ts->tv_sec;
162    header.realtime.tv_nsec = ts->tv_nsec;
163
164    newVec[0].iov_base = (unsigned char *)&header;
165    newVec[0].iov_len  = sizeof(header);
166
167    if (atomic_load(&logdLoggerWrite.context.sock) > 0) {
168        int32_t snapshot = atomic_exchange_explicit(&droppedSecurity, 0,
169                                                    memory_order_relaxed);
170        if (snapshot) {
171            android_log_event_int_t buffer;
172
173            header.id = LOG_ID_SECURITY;
174            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
175            buffer.payload.type = EVENT_TYPE_INT;
176            buffer.payload.data = htole32(snapshot);
177
178            newVec[headerLength].iov_base = &buffer;
179            newVec[headerLength].iov_len  = sizeof(buffer);
180
181            ret = TEMP_FAILURE_RETRY(writev(
182                    atomic_load(&logdLoggerWrite.context.sock), newVec, 2));
183            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
184                atomic_fetch_add_explicit(&droppedSecurity, snapshot,
185                                          memory_order_relaxed);
186            }
187        }
188        snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
189        if (snapshot && __android_log_is_loggable_len(ANDROID_LOG_INFO,
190                                                      "liblog", strlen("liblog"),
191                                                      ANDROID_LOG_VERBOSE)) {
192            android_log_event_int_t buffer;
193
194            header.id = LOG_ID_EVENTS;
195            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
196            buffer.payload.type = EVENT_TYPE_INT;
197            buffer.payload.data = htole32(snapshot);
198
199            newVec[headerLength].iov_base = &buffer;
200            newVec[headerLength].iov_len  = sizeof(buffer);
201
202            ret = TEMP_FAILURE_RETRY(writev(
203                      atomic_load(&logdLoggerWrite.context.sock), newVec, 2));
204            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
205                atomic_fetch_add_explicit(&dropped, snapshot,
206                                          memory_order_relaxed);
207            }
208        }
209    }
210
211    header.id = logId;
212
213    for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
214        newVec[i].iov_base = vec[i - headerLength].iov_base;
215        payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
216
217        if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
218            newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
219            if (newVec[i].iov_len) {
220                ++i;
221            }
222            break;
223        }
224    }
225
226    /*
227     * The write below could be lost, but will never block.
228     *
229     * ENOTCONN occurs if logd dies.
230     * EAGAIN occurs if logd is overloaded.
231     */
232    ret = TEMP_FAILURE_RETRY(writev(
233            atomic_load(&logdLoggerWrite.context.sock), newVec, i));
234    if (ret < 0) {
235        ret = -errno;
236        if (ret == -ENOTCONN) {
237            __android_log_lock();
238            logdClose();
239            ret = logdOpen();
240            __android_log_unlock();
241
242            if (ret < 0) {
243                return ret;
244            }
245
246            ret = TEMP_FAILURE_RETRY(writev(
247                    atomic_load(&logdLoggerWrite.context.sock), newVec, i));
248            if (ret < 0) {
249                ret = -errno;
250            }
251        }
252    }
253
254    if (ret > (ssize_t)sizeof(header)) {
255        ret -= sizeof(header);
256    } else if (ret == -EAGAIN) {
257        atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
258        if (logId == LOG_ID_SECURITY) {
259            atomic_fetch_add_explicit(&droppedSecurity, 1,
260                                      memory_order_relaxed);
261        }
262    }
263
264    return ret;
265}
266