1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "nativetoken_klog.h"
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include "securec.h"
20 
21 #define MAX_LOG_SIZE 1024
22 #define MAX_LEVEL_SIZE 3
23 
24 static const char *LOG_LEVEL_STR[] = {"ERROR", "WARNING", "INFO"};
25 
26 #ifndef UNLIKELY
27 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
28 #endif
29 
30 static int g_fd = -1;
NativeTokenOpenLogDevice(void)31 static void NativeTokenOpenLogDevice(void)
32 {
33     int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC);
34     if (fd >= 0) {
35         g_fd = fd;
36     }
37     return;
38 }
39 
NativeTokenKmsg(int logLevel,const char * fmt,...)40 int NativeTokenKmsg(int logLevel, const char *fmt, ...)
41 {
42     if ((logLevel < 0) || (logLevel >= MAX_LEVEL_SIZE)) {
43         return -1;
44     }
45     if (UNLIKELY(g_fd < 0)) {
46         NativeTokenOpenLogDevice();
47         if (g_fd < 0) {
48             return -1;
49         }
50     }
51     va_list vargs;
52     va_start(vargs, fmt);
53     char tmpFmt[MAX_LOG_SIZE];
54     if (vsnprintf_s(tmpFmt, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, fmt, vargs) == -1) {
55         close(g_fd);
56         g_fd = -1;
57         va_end(vargs);
58         return -1;
59     }
60 
61     char logInfo[MAX_LOG_SIZE];
62     int res = snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, "[pid=%d][%s][%s] %s",
63         getpid(), "access_token", LOG_LEVEL_STR[logLevel], tmpFmt);
64     if (res == -1) {
65         close(g_fd);
66         g_fd = -1;
67         va_end(vargs);
68         return -1;
69     }
70     va_end(vargs);
71 
72     if (write(g_fd, logInfo, strlen(logInfo)) < 0) {
73         close(g_fd);
74         g_fd = -1;
75     }
76     return 0;
77 }
78