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