1 /*
2  * Copyright (C) 2021 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 "access_token_adapter.h"
17 
18 #include <fcntl.h>
19 #include <sys/ioctl.h>
20 #include <unistd.h>
21 
22 #include "bits/ioctl.h"
23 
24 #define ACCESS_TOKEN_ID_IOCTL_BASE 'A'
25 
26 enum {
27     GET_TOKEN_ID = 1,
28     SET_TOKEN_ID,
29     GET_FTOKEN_ID,
30     SET_FTOKEN_ID,
31     ACCESS_TOKENID_MAX_NR,
32 };
33 
34 #define ACCESS_TOKENID_GET_TOKENID \
35     _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_TOKEN_ID, unsigned long long)
36 #define ACCESS_TOKENID_GET_FTOKENID \
37     _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_FTOKEN_ID, unsigned long long)
38 
39 #define ACCESS_TOKEN_OK 0
40 #define ACCESS_TOKEN_ERROR (-1)
41 
42 #define INVAL_TOKEN_ID 0x0
43 #define TOKEN_ID_LOWMASK 0xffffffff
44 
45 #define TOKENID_DEVNODE "/dev/access_token_id"
46 
RpcGetSelfTokenID(void)47 uint64_t RpcGetSelfTokenID(void)
48 {
49     uint64_t token = INVAL_TOKEN_ID;
50     int fd = open(TOKENID_DEVNODE, O_RDWR);
51     if (fd < 0) {
52         return INVAL_TOKEN_ID;
53     }
54     int ret = ioctl(fd, ACCESS_TOKENID_GET_TOKENID, &token);
55     if (ret) {
56         close(fd);
57         return INVAL_TOKEN_ID;
58     }
59 
60     close(fd);
61     return token;
62 }
63 
RpcGetFirstCallerTokenID(void)64 uint64_t RpcGetFirstCallerTokenID(void)
65 {
66     uint64_t token = INVAL_TOKEN_ID;
67     int fd = open(TOKENID_DEVNODE, O_RDWR);
68     if (fd < 0) {
69         return INVAL_TOKEN_ID;
70     }
71     int ret = ioctl(fd, ACCESS_TOKENID_GET_FTOKENID, &token);
72     if (ret) {
73         close(fd);
74         return INVAL_TOKEN_ID;
75     }
76 
77     close(fd);
78     return token;
79 }