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 "token_setproc.h"
17
18 #include <errno.h>
19 #include <stdint.h>
20 #include <fcntl.h>
21 #include <sys/ioctl.h>
22 #include <unistd.h>
23
24 #define ACCESS_TOKENID_GET_TOKENID \
25 _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_TOKEN_ID, uint64_t)
26 #define ACCESS_TOKENID_SET_TOKENID \
27 _IOW(ACCESS_TOKEN_ID_IOCTL_BASE, SET_TOKEN_ID, uint64_t)
28 #define ACCESS_TOKENID_GET_FTOKENID \
29 _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_FTOKEN_ID, uint64_t)
30 #define ACCESS_TOKENID_SET_FTOKENID \
31 _IOW(ACCESS_TOKEN_ID_IOCTL_BASE, SET_FTOKEN_ID, uint64_t)
32
33 #define INVAL_TOKEN_ID 0x0
34 #define TOKEN_ID_LOWMASK 0xffffffff
35
GetSelfTokenID(void)36 uint64_t GetSelfTokenID(void)
37 {
38 uint64_t token = INVAL_TOKEN_ID;
39 int fd = open(TOKENID_DEVNODE, O_RDWR);
40 if (fd < 0) {
41 return INVAL_TOKEN_ID;
42 }
43 int ret = ioctl(fd, ACCESS_TOKENID_GET_TOKENID, &token);
44 if (ret) {
45 close(fd);
46 return INVAL_TOKEN_ID;
47 }
48
49 close(fd);
50 return token;
51 }
52
SetSelfTokenID(uint64_t tokenID)53 int SetSelfTokenID(uint64_t tokenID)
54 {
55 int fd = open(TOKENID_DEVNODE, O_RDWR);
56 if (fd < 0) {
57 return ACCESS_TOKEN_OPEN_ERROR;
58 }
59 int ret = ioctl(fd, ACCESS_TOKENID_SET_TOKENID, &tokenID);
60 if (ret) {
61 close(fd);
62 return ret;
63 }
64
65 close(fd);
66 return ACCESS_TOKEN_OK;
67 }
68
GetFirstCallerTokenID(void)69 uint64_t GetFirstCallerTokenID(void)
70 {
71 uint64_t token = INVAL_TOKEN_ID;
72 int fd = open(TOKENID_DEVNODE, O_RDWR);
73 if (fd < 0) {
74 return INVAL_TOKEN_ID;
75 }
76 int ret = ioctl(fd, ACCESS_TOKENID_GET_FTOKENID, &token);
77 if (ret) {
78 close(fd);
79 return INVAL_TOKEN_ID;
80 }
81
82 close(fd);
83 return token;
84 }
85
SetFirstCallerTokenID(uint64_t tokenID)86 int SetFirstCallerTokenID(uint64_t tokenID)
87 {
88 int fd = open(TOKENID_DEVNODE, O_RDWR);
89 if (fd < 0) {
90 return ACCESS_TOKEN_OPEN_ERROR;
91 }
92 int ret = ioctl(fd, ACCESS_TOKENID_SET_FTOKENID, &tokenID);
93 if (ret) {
94 close(fd);
95 return ret;
96 }
97
98 close(fd);
99 return ACCESS_TOKEN_OK;
100 }
101