1 /*
2 * Copyright (c) 2022-2023 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 "selinux_log.h"
17 #include "securec.h"
18 #include "hilog/log.h"
19
20
21 #undef LOG_DOMAIN
22 #undef LOG_TAG
23 static const unsigned int LOG_DOMAIN = 0xD005A03;
24 static const char* LOG_TAG = "Selinux";
25
26 #define MAX_LOG_BUFF_LEN 4096
27
28 static int g_logLevel = SELINUX_HILOG_ERROR;
29
SetSelinuxHilogLevel(int logLevel)30 void SetSelinuxHilogLevel(int logLevel)
31 {
32 g_logLevel = logLevel;
33 }
34
SelinuxHilog(int logLevel,const char * fmt,...)35 int SelinuxHilog(int logLevel, const char *fmt, ...)
36 {
37 if (logLevel != SELINUX_HILOG_AVC && logLevel > g_logLevel) {
38 return -1;
39 }
40
41 char *buf = (char *)malloc(MAX_LOG_BUFF_LEN);
42 if (buf == NULL) {
43 HILOG_ERROR(LOG_CORE, "selinux log malloc fail");
44 return -1;
45 }
46 (void)memset_s(buf, MAX_LOG_BUFF_LEN, 0, MAX_LOG_BUFF_LEN);
47
48 va_list ap;
49 va_start(ap, fmt);
50 int ret = vsnprintf_s(buf, MAX_LOG_BUFF_LEN, MAX_LOG_BUFF_LEN - 1, fmt, ap);
51 va_end(ap);
52
53 if (ret < 0) {
54 HILOG_ERROR(LOG_CORE, "selinux log truncate error: %{public}s", buf);
55 free(buf);
56 buf = NULL;
57 return -1;
58 }
59
60 switch (logLevel) {
61 case SELINUX_HILOG_INFO:
62 HILOG_INFO(LOG_CORE, "%{public}s\n", buf);
63 break;
64 case SELINUX_HILOG_WARN:
65 HILOG_WARN(LOG_CORE, "%{public}s\n", buf);
66 break;
67 case SELINUX_HILOG_ERROR:
68 case SELINUX_HILOG_AVC:
69 HILOG_ERROR(LOG_CORE, "%{public}s\n", buf);
70 break;
71 default:
72 free(buf);
73 buf = NULL;
74 return -1;
75 }
76
77 free(buf);
78 buf = NULL;
79 return 0;
80 }
81