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/logd.h>
36#include <log/logger.h>
37#include <log/log_read.h>
38#include <private/android_filesystem_config.h>
39#include <private/android_logger.h>
40
41#include "config_write.h"
42#include "log_portability.h"
43#include "logger.h"
44
45/* branchless on many architectures. */
46#define min(x,y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
47
48static int logdAvailable(log_id_t LogId);
49static int logdOpen();
50static void logdClose();
51static int logdWrite(log_id_t logId, struct timespec *ts,
52                     struct iovec *vec, size_t nr);
53
54LIBLOG_HIDDEN struct android_log_transport_write logdLoggerWrite = {
55    .node = { &logdLoggerWrite.node, &logdLoggerWrite.node },
56    .context.sock = -1,
57    .name = "logd",
58    .available = logdAvailable,
59    .open = logdOpen,
60    .close = logdClose,
61    .write = logdWrite,
62};
63
64/* log_init_lock assumed */
65static int logdOpen()
66{
67    int i, ret = 0;
68
69    if (logdLoggerWrite.context.sock < 0) {
70        i = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0));
71        if (i < 0) {
72            ret = -errno;
73        } else if (TEMP_FAILURE_RETRY(fcntl(i, F_SETFL, O_NONBLOCK)) < 0) {
74            ret = -errno;
75            close(i);
76        } else {
77            struct sockaddr_un un;
78            memset(&un, 0, sizeof(struct sockaddr_un));
79            un.sun_family = AF_UNIX;
80            strcpy(un.sun_path, "/dev/socket/logdw");
81
82            if (TEMP_FAILURE_RETRY(connect(i, (struct sockaddr *)&un,
83                                           sizeof(struct sockaddr_un))) < 0) {
84                ret = -errno;
85                close(i);
86            } else {
87                logdLoggerWrite.context.sock = i;
88            }
89        }
90    }
91
92    return ret;
93}
94
95static void logdClose()
96{
97    if (logdLoggerWrite.context.sock >= 0) {
98        close(logdLoggerWrite.context.sock);
99        logdLoggerWrite.context.sock = -1;
100    }
101}
102
103static int logdAvailable(log_id_t logId)
104{
105    if (logId > LOG_ID_SECURITY) {
106        return -EINVAL;
107    }
108    if (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 (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 (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(logdLoggerWrite.context.sock, newVec, 2));
182            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
183                atomic_fetch_add_explicit(&droppedSecurity, snapshot,
184                                          memory_order_relaxed);
185            }
186        }
187        snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed);
188        if (snapshot && __android_log_is_loggable(ANDROID_LOG_INFO,
189                                                  "liblog",
190                                                  ANDROID_LOG_VERBOSE)) {
191            android_log_event_int_t buffer;
192
193            header.id = LOG_ID_EVENTS;
194            buffer.header.tag = htole32(LIBLOG_LOG_TAG);
195            buffer.payload.type = EVENT_TYPE_INT;
196            buffer.payload.data = htole32(snapshot);
197
198            newVec[headerLength].iov_base = &buffer;
199            newVec[headerLength].iov_len  = sizeof(buffer);
200
201            ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, 2));
202            if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) {
203                atomic_fetch_add_explicit(&dropped, snapshot,
204                                          memory_order_relaxed);
205            }
206        }
207    }
208
209    header.id = logId;
210
211    for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) {
212        newVec[i].iov_base = vec[i - headerLength].iov_base;
213        payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len;
214
215        if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) {
216            newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD;
217            if (newVec[i].iov_len) {
218                ++i;
219            }
220            break;
221        }
222    }
223
224    /*
225     * The write below could be lost, but will never block.
226     *
227     * ENOTCONN occurs if logd dies.
228     * EAGAIN occurs if logd is overloaded.
229     */
230    ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, i));
231    if (ret < 0) {
232        ret = -errno;
233        if (ret == -ENOTCONN) {
234            __android_log_lock();
235            logdClose();
236            ret = logdOpen();
237            __android_log_unlock();
238
239            if (ret < 0) {
240                return ret;
241            }
242
243            ret = TEMP_FAILURE_RETRY(writev(logdLoggerWrite.context.sock, newVec, i));
244            if (ret < 0) {
245                ret = -errno;
246            }
247        }
248    }
249
250    if (ret > (ssize_t)sizeof(header)) {
251        ret -= sizeof(header);
252    } else if (ret == -EAGAIN) {
253        atomic_fetch_add_explicit(&dropped, 1, memory_order_relaxed);
254        if (logId == LOG_ID_SECURITY) {
255            atomic_fetch_add_explicit(&droppedSecurity, 1,
256                                      memory_order_relaxed);
257        }
258    }
259
260    return ret;
261}
262