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