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 = 0xD002F02;
24 static const char* LOG_TAG = "Selinux";
25
26 #define MAX_LOG_BUFF_LEN 1024
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 if (vsnprintf_s(buf, MAX_LOG_BUFF_LEN, MAX_LOG_BUFF_LEN - 1, fmt, ap) < 0) {
51 HILOG_ERROR(LOG_CORE, "selinux log concatenate error.");
52 free(buf);
53 buf = NULL;
54 va_end(ap);
55 return -1;
56 }
57 va_end(ap);
58
59 switch (logLevel) {
60 case SELINUX_HILOG_INFO:
61 HILOG_INFO(LOG_CORE, "%{public}s\n", buf);
62 break;
63 case SELINUX_HILOG_WARN:
64 HILOG_WARN(LOG_CORE, "%{public}s\n", buf);
65 break;
66 case SELINUX_HILOG_ERROR:
67 case SELINUX_HILOG_AVC:
68 HILOG_ERROR(LOG_CORE, "%{public}s\n", buf);
69 break;
70 default:
71 free(buf);
72 buf = NULL;
73 return -1;
74 }
75
76 free(buf);
77 buf = NULL;
78 return 0;
79 }
80