1/*
2 * Copyright (C) 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 <fcntl.h>
18
19#include "JNIHelp.h"
20#include "core_jni_helpers.h"
21#include "jni.h"
22#include "log/logger.h"
23
24// The size of the tag number comes out of the payload size.
25#define MAX_EVENT_PAYLOAD (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(int32_t))
26
27namespace android {
28
29static jclass gCollectionClass;
30static jmethodID gCollectionAddID;
31
32static jclass gEventClass;
33static jmethodID gEventInitID;
34
35static jclass gIntegerClass;
36static jfieldID gIntegerValueID;
37
38static jclass gLongClass;
39static jfieldID gLongValueID;
40
41static jclass gFloatClass;
42static jfieldID gFloatValueID;
43
44static jclass gStringClass;
45
46
47static jboolean android_app_admin_SecurityLog_isLoggingEnabled(JNIEnv* env,
48                                                    jobject /* clazz */) {
49    return (bool)__android_log_security();
50}
51
52static jint android_app_admin_SecurityLog_writeEvent_String(JNIEnv* env,
53                                                    jobject /* clazz */,
54                                                    jint tag, jstring value) {
55    uint8_t buf[MAX_EVENT_PAYLOAD];
56
57    // Don't throw NPE -- I feel like it's sort of mean for a logging function
58    // to be all crashy if you pass in NULL -- but make the NULL value explicit.
59    const char *str = value != NULL ? env->GetStringUTFChars(value, NULL) : "NULL";
60    uint32_t len = strlen(str);
61    size_t max = sizeof(buf) - sizeof(len) - 2;  // Type byte, final newline
62    if (len > max) len = max;
63
64    buf[0] = EVENT_TYPE_STRING;
65    memcpy(&buf[1], &len, sizeof(len));
66    memcpy(&buf[1 + sizeof(len)], str, len);
67    buf[1 + sizeof(len) + len] = '\n';
68
69    if (value != NULL) env->ReleaseStringUTFChars(value, str);
70    return __android_log_security_bwrite(tag, buf, 2 + sizeof(len) + len);
71}
72
73static jint android_app_admin_SecurityLog_writeEvent_Array(JNIEnv* env, jobject clazz,
74                                                   jint tag, jobjectArray value) {
75    if (value == NULL) {
76        return android_app_admin_SecurityLog_writeEvent_String(env, clazz, tag, NULL);
77    }
78
79    uint8_t buf[MAX_EVENT_PAYLOAD];
80    const size_t max = sizeof(buf) - 1;  // leave room for final newline
81    size_t pos = 2;  // Save room for type tag & array count
82
83    jsize copied = 0, num = env->GetArrayLength(value);
84    for (; copied < num && copied < 255; ++copied) {
85        jobject item = env->GetObjectArrayElement(value, copied);
86        if (item == NULL || env->IsInstanceOf(item, gStringClass)) {
87            if (pos + 1 + sizeof(jint) > max) break;
88            const char *str = item != NULL ? env->GetStringUTFChars((jstring) item, NULL) : "NULL";
89            jint len = strlen(str);
90            if (pos + 1 + sizeof(len) + len > max) len = max - pos - 1 - sizeof(len);
91            buf[pos++] = EVENT_TYPE_STRING;
92            memcpy(&buf[pos], &len, sizeof(len));
93            memcpy(&buf[pos + sizeof(len)], str, len);
94            pos += sizeof(len) + len;
95            if (item != NULL) env->ReleaseStringUTFChars((jstring) item, str);
96        } else if (env->IsInstanceOf(item, gIntegerClass)) {
97            jint intVal = env->GetIntField(item, gIntegerValueID);
98            if (pos + 1 + sizeof(intVal) > max) break;
99            buf[pos++] = EVENT_TYPE_INT;
100            memcpy(&buf[pos], &intVal, sizeof(intVal));
101            pos += sizeof(intVal);
102        } else if (env->IsInstanceOf(item, gLongClass)) {
103            jlong longVal = env->GetLongField(item, gLongValueID);
104            if (pos + 1 + sizeof(longVal) > max) break;
105            buf[pos++] = EVENT_TYPE_LONG;
106            memcpy(&buf[pos], &longVal, sizeof(longVal));
107            pos += sizeof(longVal);
108        } else if (env->IsInstanceOf(item, gFloatClass)) {
109            jfloat floatVal = env->GetFloatField(item, gFloatValueID);
110            if (pos + 1 + sizeof(floatVal) > max) break;
111            buf[pos++] = EVENT_TYPE_FLOAT;
112            memcpy(&buf[pos], &floatVal, sizeof(floatVal));
113            pos += sizeof(floatVal);
114        } else {
115            jniThrowException(env,
116                    "java/lang/IllegalArgumentException",
117                    "Invalid payload item type");
118            return -1;
119        }
120        env->DeleteLocalRef(item);
121    }
122
123    buf[0] = EVENT_TYPE_LIST;
124    buf[1] = copied;
125    buf[pos++] = '\n';
126    return __android_log_security_bwrite(tag, buf, pos);
127}
128
129static void readEvents(JNIEnv* env, int loggerMode, jlong startTime, jobject out) {
130    struct logger_list *logger_list;
131    if (startTime) {
132        logger_list = android_logger_list_alloc_time(loggerMode,
133                log_time(startTime / NS_PER_SEC, startTime % NS_PER_SEC), 0);
134    } else {
135        logger_list = android_logger_list_alloc(loggerMode, 0, 0);
136    }
137    if (!logger_list) {
138        jniThrowIOException(env, errno);
139        return;
140    }
141
142    if (!android_logger_open(logger_list, LOG_ID_SECURITY)) {
143        jniThrowIOException(env, errno);
144        android_logger_list_free(logger_list);
145        return;
146    }
147
148    while (1) {
149        log_msg log_msg;
150        int ret = android_logger_list_read(logger_list, &log_msg);
151
152        if (ret == 0) {
153            break;
154        }
155        if (ret < 0) {
156            if (ret == -EINTR) {
157                continue;
158            }
159            if (ret == -EINVAL) {
160                jniThrowException(env, "java/io/IOException", "Event too short");
161            } else if (ret != -EAGAIN) {
162                jniThrowIOException(env, -ret);  // Will throw on return
163            }
164            break;
165        }
166
167        if (log_msg.id() != LOG_ID_SECURITY) {
168            continue;
169        }
170
171        jsize len = ret;
172        jbyteArray array = env->NewByteArray(len);
173        if (array == NULL) {
174            break;
175        }
176
177        jbyte *bytes = env->GetByteArrayElements(array, NULL);
178        memcpy(bytes, log_msg.buf, len);
179        env->ReleaseByteArrayElements(array, bytes, 0);
180
181        jobject event = env->NewObject(gEventClass, gEventInitID, array);
182        if (event == NULL) {
183            break;
184        }
185
186        env->CallBooleanMethod(out, gCollectionAddID, event);
187        env->DeleteLocalRef(event);
188        env->DeleteLocalRef(array);
189    }
190
191    android_logger_list_close(logger_list);
192}
193
194static void android_app_admin_SecurityLog_readEvents(JNIEnv* env, jobject /* clazz */,
195                                             jobject out) {
196
197    if (out == NULL) {
198        jniThrowNullPointerException(env, NULL);
199        return;
200    }
201    readEvents(env, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, out);
202}
203
204static void android_app_admin_SecurityLog_readEventsSince(JNIEnv* env, jobject /* clazz */,
205                                             jlong timestamp,
206                                             jobject out) {
207
208    if (out == NULL) {
209        jniThrowNullPointerException(env, NULL);
210        return;
211    }
212    readEvents(env, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, timestamp, out);
213}
214
215static void android_app_admin_SecurityLog_readPreviousEvents(JNIEnv* env, jobject /* clazz */,
216                                             jobject out) {
217
218    if (out == NULL) {
219        jniThrowNullPointerException(env, NULL);
220        return;
221    }
222    readEvents(env, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK | ANDROID_LOG_PSTORE, 0, out);
223}
224
225static void android_app_admin_SecurityLog_readEventsOnWrapping(JNIEnv* env, jobject /* clazz */,
226                                             jlong timestamp,
227                                             jobject out) {
228    if (out == NULL) {
229        jniThrowNullPointerException(env, NULL);
230        return;
231    }
232    readEvents(env, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK | ANDROID_LOG_WRAP, timestamp, out);
233}
234
235/*
236 * JNI registration.
237 */
238static const JNINativeMethod gRegisterMethods[] = {
239    /* name, signature, funcPtr */
240    { "isLoggingEnabled",
241      "()Z",
242      (void*) android_app_admin_SecurityLog_isLoggingEnabled
243    },
244    { "writeEvent",
245      "(ILjava/lang/String;)I",
246      (void*) android_app_admin_SecurityLog_writeEvent_String
247    },
248    { "writeEvent",
249      "(I[Ljava/lang/Object;)I",
250      (void*) android_app_admin_SecurityLog_writeEvent_Array
251    },
252    { "readEvents",
253      "(Ljava/util/Collection;)V",
254      (void*) android_app_admin_SecurityLog_readEvents
255    },
256    { "readEventsSince",
257      "(JLjava/util/Collection;)V",
258      (void*) android_app_admin_SecurityLog_readEventsSince
259    },
260    { "readPreviousEvents",
261      "(Ljava/util/Collection;)V",
262      (void*) android_app_admin_SecurityLog_readPreviousEvents
263    },
264    { "readEventsOnWrapping",
265      "(JLjava/util/Collection;)V",
266      (void*) android_app_admin_SecurityLog_readEventsOnWrapping
267    },
268};
269
270static struct { const char *name; jclass *clazz; } gClasses[] = {
271    { "android/app/admin/SecurityLog$SecurityEvent", &gEventClass },
272    { "java/lang/Integer", &gIntegerClass },
273    { "java/lang/Long", &gLongClass },
274    { "java/lang/Float", &gFloatClass },
275    { "java/lang/String", &gStringClass },
276    { "java/util/Collection", &gCollectionClass },
277};
278
279static struct { jclass *c; const char *name, *ft; jfieldID *id; } gFields[] = {
280    { &gIntegerClass, "value", "I", &gIntegerValueID },
281    { &gLongClass, "value", "J", &gLongValueID },
282    { &gFloatClass, "value", "F", &gFloatValueID },
283};
284
285static struct { jclass *c; const char *name, *mt; jmethodID *id; } gMethods[] = {
286    { &gEventClass, "<init>", "([B)V", &gEventInitID },
287    { &gCollectionClass, "add", "(Ljava/lang/Object;)Z", &gCollectionAddID },
288};
289
290int register_android_app_admin_SecurityLog(JNIEnv* env) {
291    for (int i = 0; i < NELEM(gClasses); ++i) {
292        jclass clazz = FindClassOrDie(env, gClasses[i].name);
293        *gClasses[i].clazz = MakeGlobalRefOrDie(env, clazz);
294    }
295
296    for (int i = 0; i < NELEM(gFields); ++i) {
297        *gFields[i].id = GetFieldIDOrDie(env,
298                *gFields[i].c, gFields[i].name, gFields[i].ft);
299    }
300
301    for (int i = 0; i < NELEM(gMethods); ++i) {
302        *gMethods[i].id = GetMethodIDOrDie(env,
303                *gMethods[i].c, gMethods[i].name, gMethods[i].mt);
304    }
305
306    return RegisterMethodsOrDie(
307            env,
308            "android/app/admin/SecurityLog",
309            gRegisterMethods, NELEM(gRegisterMethods));
310}
311
312}; // namespace android
313