• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "dbinder_databus_invoker.h"
17 
18 #include <cinttypes>
19 #include "string_ex.h"
20 #include "securec.h"
21 #include "sys_binder.h"
22 
23 #include "databus_socket_listener.h"
24 #include "dbinder_error_code.h"
25 #include "ipc_object_stub.h"
26 #include "ipc_object_proxy.h"
27 #include "ipc_process_skeleton.h"
28 #include "ipc_thread_skeleton.h"
29 #include "ipc_debug.h"
30 #include "log_tags.h"
31 
32 namespace OHOS {
33 using namespace OHOS::HiviewDFX;
34 
DBinderDatabusInvoker()35 DBinderDatabusInvoker::DBinderDatabusInvoker()
36     : stopWorkThread_(false), callerPid_(getpid()), callerUid_(getuid()), callerDeviceID_(""),
37     callerTokenID_(0), firstTokenID_(0), status_(0)
38 {
39 }
40 
~DBinderDatabusInvoker()41 DBinderDatabusInvoker::~DBinderDatabusInvoker()
42 {
43 }
44 
AcquireHandle(int32_t handle)45 bool DBinderDatabusInvoker::AcquireHandle(int32_t handle)
46 {
47     ZLOGI(LOG_LABEL, "handle:%{public}d", handle);
48     return true;
49 }
50 
ReleaseHandle(int32_t handle)51 bool DBinderDatabusInvoker::ReleaseHandle(int32_t handle)
52 {
53     ZLOGI(LOG_LABEL, "handle:%{public}d", handle);
54     return true;
55 }
56 
NewSessionOfBinderProxy(uint32_t handle,std::shared_ptr<DBinderSessionObject> session)57 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::NewSessionOfBinderProxy(uint32_t handle,
58     std::shared_ptr<DBinderSessionObject> session)
59 {
60     if (session == nullptr) {
61         ZLOGE(LOG_LABEL, "remote session is nullptr");
62         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_ERR_INVALID_DATA, __FUNCTION__);
63         return nullptr;
64     }
65 
66     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
67     if (current == nullptr) {
68         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
69         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_IPC_PROCESS_SKELETON_NULL, __FUNCTION__);
70         return nullptr;
71     }
72     sptr<IPCObjectProxy> ipcProxy = reinterpret_cast<IPCObjectProxy *>(current->FindOrNewObject(handle).GetRefPtr());
73     if (ipcProxy == nullptr) {
74         ZLOGE(LOG_LABEL, "attempt to send a invalid handle:%{public}u", handle);
75         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_SEND_INVALID_HANDLE, __FUNCTION__);
76         return nullptr;
77     }
78 
79     if (ipcProxy->GetProto() != IRemoteObject::IF_PROT_BINDER) {
80         ZLOGE(LOG_LABEL, "attempt to send a distributed proxy, handle:%{public}u", handle);
81         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_SEND_DISTRIBUTED_PROXY, __FUNCTION__);
82         return nullptr;
83     }
84 
85     std::string localDeviceID = current->GetLocalDeviceID();
86     if (localDeviceID.empty()) {
87         ZLOGE(LOG_LABEL, "get localDeviceID error, handle:%{public}u", handle);
88     }
89 
90     return GetSessionForProxy(ipcProxy, session, localDeviceID);
91 }
92 
GetSessionForProxy(sptr<IPCObjectProxy> ipcProxy,std::shared_ptr<DBinderSessionObject> session,const std::string & localDeviceID)93 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::GetSessionForProxy(sptr<IPCObjectProxy> ipcProxy,
94     std::shared_ptr<DBinderSessionObject> session, const std::string &localDeviceID)
95 {
96     uint32_t handle = ipcProxy->GetHandle();
97     std::string sessionName = ipcProxy->GetSessionName();
98     if (sessionName.empty()) {
99         ZLOGE(LOG_LABEL, "get bus name error, handle:%{public}u", handle);
100         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_GET_SESSION_NAME_FAIL, __FUNCTION__);
101         return nullptr;
102     }
103     MessageParcel data;
104     MessageParcel reply;
105     if (!data.WriteUint32(IRemoteObject::DATABUS_TYPE) || !data.WriteString(localDeviceID) ||
106         !data.WriteUint32(session->GetPeerPid()) || !data.WriteUint32(session->GetPeerUid()) ||
107         !data.WriteString(session->GetDeviceId()) || !data.WriteString(sessionName) ||
108         !data.WriteUint32(session->GetTokenId())) {
109         ZLOGE(LOG_LABEL, "write to parcel fail, handle:%{public}u", handle);
110         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_WRITE_TO_PARCEL_FAIL, __FUNCTION__);
111         return nullptr;
112     }
113     int err = ipcProxy->InvokeListenThread(data, reply);
114     if (err != ERR_NONE) {
115         ZLOGE(LOG_LABEL, "start service listen error:%{public}d handle:%{public}u", err, handle);
116         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_START_LISTEN_FAIL, __FUNCTION__);
117         return nullptr;
118     }
119 
120     uint64_t stubIndex = reply.ReadUint64();
121     if (stubIndex == 0) {
122         ZLOGE(LOG_LABEL, "stubindex error:%{public}" PRIu64 " handle:%{public}u", stubIndex, handle);
123         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_STUB_INVALID, __FUNCTION__);
124         return nullptr;
125     }
126     std::string serverName = reply.ReadString();
127     std::string deviceId = reply.ReadString();
128     uint32_t peerTokenId = reply.ReadUint32();
129 
130     ZLOGI(LOG_LABEL, "serverName:%{public}s stubIndex:%{public}" PRIu64 " peerTokenId:%{public}u deviceId:%{public}s",
131         serverName.c_str(), stubIndex, peerTokenId, IPCProcessSkeleton::ConvertToSecureString(deviceId).c_str());
132     std::shared_ptr<DBinderSessionObject> connectSession =
133         std::make_shared<DBinderSessionObject>(serverName, deviceId, stubIndex, nullptr, peerTokenId);
134     if (connectSession == nullptr) {
135         ZLOGE(LOG_LABEL, "new server session fail, handle:%{public}u", handle);
136         DfxReportFailHandleEvent(DbinderErrorCode::RPC_DRIVER, handle, RADAR_NEW_SERVER_SESSION_FAIL, __FUNCTION__);
137         return nullptr;
138     }
139 
140     return connectSession;
141 }
142 
AuthSession2Proxy(uint32_t handle,const std::shared_ptr<DBinderSessionObject> session)143 bool DBinderDatabusInvoker::AuthSession2Proxy(uint32_t handle, const std::shared_ptr<DBinderSessionObject> session)
144 {
145     if (session == nullptr) {
146         ZLOGE(LOG_LABEL, "remote session is nullptr, handle:%{public}u", handle);
147         return false;
148     }
149 
150     MessageParcel data;
151     MessageParcel reply;
152     MessageOption option;
153 
154     if (!data.WriteUint32(session->GetPeerPid()) || !data.WriteUint32(session->GetPeerUid()) ||
155         !data.WriteString(session->GetDeviceId()) || !data.WriteUint64(session->GetStubIndex()) ||
156         !data.WriteUint32(session->GetTokenId())) {
157         ZLOGE(LOG_LABEL, "write to MessageParcel fail, handle:%{public}u", handle);
158         return false;
159     }
160 
161     int err = SendRequest(handle, DBINDER_ADD_COMMAUTH, data, reply, option);
162     if (err != ERR_NONE) {
163         ZLOGE(LOG_LABEL, "send auth info to remote fail, handle:%{public}u", handle);
164         return false;
165     }
166     return true;
167 }
168 
QuerySessionOfBinderProxy(uint32_t handle,std::shared_ptr<DBinderSessionObject> session)169 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::QuerySessionOfBinderProxy(uint32_t handle,
170     std::shared_ptr<DBinderSessionObject> session)
171 {
172     if (AuthSession2Proxy(handle, session) != true) {
173         ZLOGE(LOG_LABEL, "auth handle:%{public}u to socketId failed, socketId:%{public}d", handle,
174             session->GetSocketId());
175         return nullptr;
176     }
177     return QueryServerSessionObject(handle);
178 }
179 
QueryClientSessionObject(uint32_t databusHandle)180 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::QueryClientSessionObject(uint32_t databusHandle)
181 {
182     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
183     if (current == nullptr) {
184         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
185         return nullptr;
186     }
187     std::shared_ptr<DBinderSessionObject> sessionOfPeer = current->StubQueryDBinderSession(databusHandle);
188     if (sessionOfPeer == nullptr) {
189         ZLOGE(LOG_LABEL, "no session attach to this proxy:%{public}u", databusHandle);
190         return nullptr;
191     }
192     ZLOGI(LOG_LABEL, "socketId:%{public}d", sessionOfPeer->GetSocketId());
193     return sessionOfPeer;
194 }
195 
QueryServerSessionObject(uint32_t handle)196 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::QueryServerSessionObject(uint32_t handle)
197 {
198     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
199     if (current == nullptr) {
200         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
201         return nullptr;
202     }
203 
204     std::shared_ptr<DBinderSessionObject> sessionOfPeer = current->ProxyQueryDBinderSession(handle);
205     if (sessionOfPeer == nullptr) {
206         ZLOGI(LOG_LABEL, "no session attach to this handle:%{public}u", handle);
207         return nullptr;
208     }
209 
210     return sessionOfPeer;
211 }
212 
OnReceiveNewConnection(int32_t socketId,int peerPid,int peerUid,std::string peerName,std::string networkId)213 bool DBinderDatabusInvoker::OnReceiveNewConnection(int32_t socketId, int peerPid, int peerUid,
214     std::string peerName, std::string networkId)
215 {
216     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
217     if (current == nullptr) {
218         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
219         return false;
220     }
221 
222     AppAuthInfo appAuthInfo = { peerPid, peerUid, 0, socketId, 0, nullptr, networkId };
223     if (!current->QueryCommAuthInfo(appAuthInfo)) {
224         ZLOGE(LOG_LABEL, "remote device is not auth, socket:%{public}d, peerName:%{public}s",
225             socketId, peerName.c_str());
226         return false;
227     }
228     uint32_t peerTokenId = appAuthInfo.tokenId;
229     uint32_t oldTokenId = 0;
230     if (current->StubDetachDBinderSession(socketId, oldTokenId)) {
231         ZLOGI(LOG_LABEL, "delete left socketId:%{public}d device:%{public}s oldTokenId:%{public}u", socketId,
232             IPCProcessSkeleton::ConvertToSecureString(networkId).c_str(), oldTokenId);
233     }
234     std::shared_ptr<DBinderSessionObject> sessionObject = std::make_shared<DBinderSessionObject>(
235         peerName, networkId, 0, nullptr, peerTokenId);
236     sessionObject->SetSocketId(socketId);
237     sessionObject->SetPeerPid(peerPid);
238     sessionObject->SetPeerUid(peerUid);
239     if (!current->StubAttachDBinderSession(socketId, sessionObject)) {
240         ZLOGE(LOG_LABEL, "attach session to process skeleton failed, socketId:%{public}d", socketId);
241         return false;
242     }
243     ZLOGI(LOG_LABEL, "pid:%{public}u uid:%{public}u deviceId:%{public}s tokenId:%{public}u "
244         "oldTokenId:%{public}u socketId:%{public}d", peerPid, peerUid,
245         IPCProcessSkeleton::ConvertToSecureString(networkId).c_str(),
246         peerTokenId, oldTokenId, socketId);
247     // update socketId
248     current->AttachOrUpdateAppAuthInfo(appAuthInfo);
249     return true;
250 }
251 
CreateProcessThread()252 bool DBinderDatabusInvoker::CreateProcessThread()
253 {
254     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
255     if (current == nullptr) {
256         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
257         return false;
258     }
259     /*  epoll thread obtained one thread, so idle thread must more than 1 */
260     if (current->GetSocketIdleThreadNum() > 0) {
261         current->SpawnThread(IPCWorkThread::PROCESS_PASSIVE, IRemoteObject::IF_PROT_DATABUS);
262         ZLOGI(LOG_LABEL, "success");
263         return true;
264     }
265 
266     ZLOGE(LOG_LABEL, "failed, no idle socket thread left");
267     return false;
268 }
269 
OnRawDataAvailable(int32_t socketId,const char * data,uint32_t dataSize)270 void DBinderDatabusInvoker::OnRawDataAvailable(int32_t socketId, const char *data, uint32_t dataSize)
271 {
272     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
273     if (current == nullptr) {
274         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
275         return;
276     }
277 
278     bool isSucc = false;
279     uint32_t rawDataSize = dataSize - sizeof(dbinder_transaction_data);
280     if (rawDataSize > 0 && rawDataSize <= MAX_RAWDATA_SIZE - sizeof(dbinder_transaction_data)) {
281         std::shared_ptr<InvokerRawData> invokerRawData = std::make_shared<InvokerRawData>(rawDataSize);
282         if (memcpy_s(invokerRawData->GetData().get(), rawDataSize, data + sizeof(dbinder_transaction_data),
283             rawDataSize) != EOK) {
284             ZLOGE(LOG_LABEL, "memcpy_s failed, socketId:%{public}d size:%{public}u", socketId, rawDataSize);
285             return;
286         }
287         if (!current->AttachRawData(socketId, invokerRawData)) {
288             ZLOGE(LOG_LABEL, "AttachRawData failed, socketId:%{public}d size:%{public}u", socketId, rawDataSize);
289             return;
290         }
291         isSucc = true;
292     }
293     ZLOGI(LOG_LABEL, "%{public}s, socketId:%{public}d size:%{public}u", isSucc ? "succ" : "fail",
294         socketId, rawDataSize);
295     return;
296 }
297 
298 /*
299  * Write             64K=SOCKET_BUFF_SIZE
300  * +------------------+-------------------------+----------------|
301  * |0<---processed--->|Read <----need process-->|<--idle buffer-->
302  * -cursor
303  *
304  * when idle buffer less 1k, move need process to buffer head, then update R/W cursor
305  * when idle buffer can not put a full package, also move need process package to buffer head
306  */
OnMessageAvailable(int32_t socketId,const char * data,ssize_t len)307 void DBinderDatabusInvoker::OnMessageAvailable(int32_t socketId, const char *data, ssize_t len)
308 {
309     if (socketId <= 0 || data == nullptr || len > static_cast<ssize_t>(MAX_RAWDATA_SIZE) ||
310         len < static_cast<ssize_t>(sizeof(dbinder_transaction_data))) {
311         ZLOGE(LOG_LABEL, "wrong inputs, data length:%{public}zd(expected size:%{public}zu) "
312             " socketId:%{public}d", len, sizeof(dbinder_transaction_data), socketId);
313         return;
314     }
315 
316     uint32_t packageSize = HasRawDataPackage(data, len);
317     if (packageSize > 0) {
318         // Only one set of big data can be transferred at a time.
319         return OnRawDataAvailable(socketId, data, packageSize);
320     }
321 
322     uint32_t readSize = 0;
323     do {
324         packageSize = HasCompletePackage(data, readSize, len);
325         if (packageSize > 0) {
326             StartProcessLoop(socketId, data + readSize, packageSize);
327             readSize += packageSize;
328         } else {
329             // If the current is abnormal, the subsequent is no longer processed.
330             ZLOGE(LOG_LABEL, "not complete message, socketId:%{public}d", socketId);
331             break;
332         }
333     } while (readSize + sizeof(dbinder_transaction_data) < static_cast<uint32_t>(len));
334 }
335 
OnSendMessage(std::shared_ptr<DBinderSessionObject> sessionOfPeer)336 int DBinderDatabusInvoker::OnSendMessage(std::shared_ptr<DBinderSessionObject> sessionOfPeer)
337 {
338     if (sessionOfPeer == nullptr) {
339         ZLOGE(LOG_LABEL, "sessionOfPeer is null");
340         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
341     }
342 
343     int32_t socketId = sessionOfPeer->GetSocketId();
344     if (socketId <= 0) {
345         ZLOGE(LOG_LABEL, "socket id is invalid");
346         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
347     }
348 
349     std::shared_ptr<BufferObject> sessionBuff = sessionOfPeer->GetSessionBuff();
350     if (sessionBuff == nullptr) {
351         ZLOGE(LOG_LABEL, "databus session buff is null");
352         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
353     }
354 
355     return SendData(sessionBuff, socketId);
356 }
357 
SendData(std::shared_ptr<BufferObject> sessionBuff,int32_t socketId)358 int DBinderDatabusInvoker::SendData(std::shared_ptr<BufferObject> sessionBuff, int32_t socketId)
359 {
360     char *sendBuffer = sessionBuff->GetSendBufferAndLock(SOCKET_DEFAULT_BUFF_SIZE);
361     /* session buffer contain mutex, need release mutex */
362     if (sendBuffer == nullptr) {
363         ZLOGE(LOG_LABEL, "buffer alloc failed in session");
364         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
365     }
366     sessionBuff->UpdateSendBuffer(0); // 0 means do not expand buffer when send it
367     ssize_t writeCursor = sessionBuff->GetSendBufferWriteCursor();
368     ssize_t readCursor = sessionBuff->GetSendBufferReadCursor();
369     if (writeCursor < readCursor) {
370         ZLOGE(LOG_LABEL, "no data to send, write cursor:%{public}zu, read cursor:%{public}zu",
371             writeCursor, readCursor);
372         sessionBuff->ReleaseSendBufferLock();
373         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
374     }
375     if (writeCursor == readCursor) {
376         ZLOGE(LOG_LABEL, "no data to send, write cursor:%{public}zu, read cursor:%{public}zu",
377             writeCursor, readCursor);
378         sessionBuff->ReleaseSendBufferLock();
379         return ERR_NONE;
380     }
381     ssize_t size = writeCursor - readCursor;
382 
383     int32_t ret = DBinderSoftbusClient::GetInstance().SendBytes(
384         socketId, static_cast<const void *>(sendBuffer + readCursor), size);
385     if (ret != 0) {
386         ZLOGE(LOG_LABEL, "SendBytes fail, ret:%{public}d seq:%{public}" PRIu64
387             " size:%{public}zd, socketId:%{public}d", ret, seqNumber_, size, socketId);
388         DfxReportFailEvent(DbinderErrorCode::RPC_DRIVER, RADAR_SEND_BYTES_FAIL, __FUNCTION__);
389         sessionBuff->ReleaseSendBufferLock();
390         return ret;
391     }
392 
393     readCursor += size;
394     sessionBuff->SetSendBufferReadCursor(readCursor);
395     sessionBuff->SetSendBufferWriteCursor(writeCursor);
396     ZLOGI(LOG_LABEL, "succ, seq:%{public}" PRIu64 " size:%{public}zd, socketId:%{public}d",
397         seqNumber_, size, socketId);
398 
399     sessionBuff->ReleaseSendBufferLock();
400     return ret;
401 }
402 
OnSendRawData(std::shared_ptr<DBinderSessionObject> session,const void * data,size_t size)403 int DBinderDatabusInvoker::OnSendRawData(std::shared_ptr<DBinderSessionObject> session, const void *data, size_t size)
404 {
405     if (session == nullptr) {
406         ZLOGE(LOG_LABEL, "sessionOfPeer is null");
407         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
408     }
409 
410     int32_t socketId = session->GetSocketId();
411     if (socketId <= 0) {
412         ZLOGE(LOG_LABEL, "socketId is invalid");
413         return -RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
414     }
415 
416     int ret = DBinderSoftbusClient::GetInstance().SendBytes(socketId, data, size);
417     if (ret != 0) {
418         ZLOGE(LOG_LABEL, "fail, ret:%{public}d seq:%{public}" PRIu64 " size:%{public}zu socketId:%{public}d",
419             ret, seqNumber_, size, socketId);
420         return ret;
421     }
422 
423     ZLOGI(LOG_LABEL, "succ, seq:%{public}" PRIu64 " size:%{public}zu, socketId:%{public}d",
424         seqNumber_, size, socketId);
425 
426     return ret;
427 }
428 
JoinThread(bool initiative)429 void DBinderDatabusInvoker::JoinThread(bool initiative) {}
430 
JoinProcessThread(bool initiative)431 void DBinderDatabusInvoker::JoinProcessThread(bool initiative)
432 {
433     std::thread::id threadId = std::this_thread::get_id();
434     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
435     if (current == nullptr) {
436         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
437         return;
438     }
439 
440     std::shared_ptr<ThreadProcessInfo> processInfo = nullptr;
441     do {
442         current->AddDataThreadInWait(threadId);
443         while ((processInfo = current->PopDataInfoFromThread(threadId)) != nullptr) {
444             OnTransaction(processInfo);
445             processInfo = nullptr;
446         }
447     } while (!stopWorkThread_);
448 }
449 
StopWorkThread()450 void DBinderDatabusInvoker::StopWorkThread()
451 {
452     stopWorkThread_ = true;
453 }
454 
FlattenSession(unsigned char * sessionOffset,const std::shared_ptr<DBinderSessionObject> connectSession,uint32_t binderVersion)455 uint32_t DBinderDatabusInvoker::FlattenSession(unsigned char *sessionOffset,
456     const std::shared_ptr<DBinderSessionObject> connectSession, uint32_t binderVersion)
457 {
458     FlatDBinderSession *flatSession = reinterpret_cast<FlatDBinderSession *>(sessionOffset);
459     (void)memset_s(flatSession, sizeof(struct FlatDBinderSession), 0, sizeof(struct FlatDBinderSession));
460 
461     flatSession->stubIndex = connectSession->GetStubIndex();
462     flatSession->version = binderVersion;
463     flatSession->magic = TOKENID_MAGIC;
464     flatSession->tokenId = connectSession->GetTokenId();
465     flatSession->deviceIdLength = connectSession->GetDeviceId().length();
466     if (flatSession->deviceIdLength == 0 || flatSession->deviceIdLength > DEVICEID_LENGTH) {
467         ZLOGE(LOG_LABEL, "wrong devices id length:%{public}u", flatSession->deviceIdLength);
468         return 0;
469     }
470     int memcpyResult = memcpy_s(flatSession->deviceId, DEVICEID_LENGTH, connectSession->GetDeviceId().data(),
471         flatSession->deviceIdLength);
472     if (memcpyResult != 0) {
473         ZLOGE(LOG_LABEL, "memcpy_s failed , devices id length:%{public}hu", flatSession->deviceIdLength);
474         return 0;
475     }
476     flatSession->deviceId[flatSession->deviceIdLength] = '\0';
477 
478     flatSession->serviceNameLength = connectSession->GetServiceName().length();
479     if (flatSession->serviceNameLength == 0 || flatSession->serviceNameLength > SUPPORT_TOKENID_SERVICENAME_LENGTH) {
480         ZLOGE(LOG_LABEL, "wrong service name length:%{public}u", flatSession->serviceNameLength);
481         return 0;
482     }
483     memcpyResult = memcpy_s(flatSession->serviceName, SUPPORT_TOKENID_SERVICENAME_LENGTH,
484         connectSession->GetServiceName().data(), flatSession->serviceNameLength);
485     if (memcpyResult != 0) {
486         ZLOGE(LOG_LABEL, "memcpy_s failed , service name length:%{public}u", flatSession->serviceNameLength);
487         return 0;
488     }
489     flatSession->serviceName[flatSession->serviceNameLength] = '\0';
490 
491     ZLOGI(LOG_LABEL, "serviceName:%{public}s stubIndex:%{public}" PRIu64 " tokenId:%{public}u",
492         flatSession->serviceName, flatSession->stubIndex, flatSession->tokenId);
493 
494     return sizeof(struct FlatDBinderSession);
495 }
496 
UnFlattenSession(unsigned char * sessionOffset,uint32_t binderVersion)497 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::UnFlattenSession(unsigned char *sessionOffset,
498     uint32_t binderVersion)
499 {
500     FlatDBinderSession *flatSession = reinterpret_cast<FlatDBinderSession *>(sessionOffset);
501     if (flatSession->stubIndex == 0) {
502         ZLOGE(LOG_LABEL, "stubIndex err");
503         return nullptr;
504     }
505 
506     uint32_t tokenId = 0;
507     if (binderVersion >= SUPPORT_TOKENID_VERSION_NUM && flatSession->version >= SUPPORT_TOKENID_VERSION_NUM &&
508         flatSession->magic == TOKENID_MAGIC) {
509         tokenId = flatSession->tokenId;
510     }
511     /* makes sure end with a null terminator */
512     flatSession->deviceId[DEVICEID_LENGTH] = '\0';
513     flatSession->serviceName[SUPPORT_TOKENID_SERVICENAME_LENGTH] = '\0';
514     ZLOGI(LOG_LABEL, "serviceName:%{public}s stubIndex:%{public}" PRIu64 " tokenId:%{public}u",
515         flatSession->serviceName, flatSession->stubIndex, tokenId);
516 
517     return std::make_shared<DBinderSessionObject>(
518         flatSession->serviceName, flatSession->deviceId, flatSession->stubIndex, nullptr, tokenId);
519 }
520 
FlattenObject(Parcel & parcel,const IRemoteObject * object) const521 bool DBinderDatabusInvoker::FlattenObject(Parcel &parcel, const IRemoteObject *object) const
522 {
523     return true;
524 }
525 
UnflattenObject(Parcel & parcel)526 sptr<IRemoteObject> DBinderDatabusInvoker::UnflattenObject(Parcel &parcel)
527 {
528     return nullptr;
529 }
530 
ReadFileDescriptor(Parcel & parcel)531 int DBinderDatabusInvoker::ReadFileDescriptor(Parcel &parcel)
532 {
533     return -1;
534 }
535 
WriteFileDescriptor(Parcel & parcel,int fd,bool takeOwnership)536 bool DBinderDatabusInvoker::WriteFileDescriptor(Parcel &parcel, int fd, bool takeOwnership)
537 {
538     return true;
539 }
540 
UpdateClientSession(std::shared_ptr<DBinderSessionObject> sessionObject)541 bool DBinderDatabusInvoker::UpdateClientSession(std::shared_ptr<DBinderSessionObject> sessionObject)
542 {
543     ZLOGI(LOG_LABEL, "enter");
544     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
545     if (current == nullptr) {
546         ZLOGE(LOG_LABEL, "current process skeleton is nullptr");
547         return false;
548     }
549 
550     std::string ownName = current->GetDatabusName();
551     if (ownName.empty()) {
552         ZLOGE(LOG_LABEL, "fail to get session name");
553         return false;
554     }
555 
556     std::shared_ptr<DatabusSocketListener> listener =
557         DelayedSingleton<DatabusSocketListener>::GetInstance();
558     if (listener == nullptr) {
559         ZLOGE(LOG_LABEL, "listener is nullptr");
560         return false;
561     }
562 
563     std::string serviceName = sessionObject->GetServiceName();
564     std::string str = serviceName.substr(DBINDER_SOCKET_NAME_PREFIX.length());
565     std::string::size_type pos = str.find("_");
566     std::string peerUid = str.substr(0, pos);
567     std::string peerPid = str.substr(pos + 1);
568     if ((peerUid.length() > INT_STRING_MAX_LEN) || (peerPid.length() > INT_STRING_MAX_LEN) ||
569         !ProcessSkeleton::IsNumStr(peerUid) || !ProcessSkeleton::IsNumStr(peerPid)) {
570         ZLOGE(LOG_LABEL, "peerUid:%{public}s or peerPid:%{public}s is invalid", peerUid.c_str(), peerPid.c_str());
571         return false;
572     }
573     int32_t socketId = listener->CreateClientSocket(ownName, serviceName, sessionObject->GetDeviceId());
574     if (socketId <= 0) {
575         ZLOGE(LOG_LABEL, "fail to creat client Socket");
576         return false;
577     }
578     sessionObject->SetSocketId(socketId);
579     sessionObject->SetPeerPid(std::stoi(peerPid));
580     sessionObject->SetPeerUid(std::stoi(peerUid));
581 
582     ZLOGI(LOG_LABEL, "create socket succ, ownName:%{public}s peerName:%{public}s deviceId:%{public}s "
583         "socketId:%{public}d", ownName.c_str(), serviceName.c_str(),
584         IPCProcessSkeleton::ConvertToSecureString(sessionObject->GetDeviceId()).c_str(),
585         socketId);
586     return true;
587 }
588 
OnDatabusSessionClientSideClosed(int32_t socketId)589 void DBinderDatabusInvoker::OnDatabusSessionClientSideClosed(int32_t socketId)
590 {
591     std::vector<uint32_t> proxyHandle;
592     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
593     if (current == nullptr) {
594         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
595         return;
596     }
597     if (!current->QueryProxyBySocketId(socketId, proxyHandle)) {
598         ZLOGE(LOG_LABEL, "session id:%{public}d is invalid", socketId);
599         return;
600     }
601     if (proxyHandle.empty()) {
602         ZLOGE(LOG_LABEL, "proxy handle is empty");
603         return;
604     }
605     for (auto it = proxyHandle.begin(); it != proxyHandle.end(); ++it) {
606         std::u16string descriptor = current->MakeHandleDescriptor(*it);
607         const std::string descStr8 = Str16ToStr8(descriptor);
608         sptr<IRemoteObject> remoteObject = current->QueryObject(descriptor);
609         if (remoteObject != nullptr) {
610             IPCObjectProxy *remoteProxy = reinterpret_cast<IPCObjectProxy *>(remoteObject.GetRefPtr());
611             // No need to close session again here. First erase session and then notify user session has been closed.
612             current->ProxyDetachDBinderSession(*it, remoteProxy);
613             if (remoteProxy->IsSubscribeDeathNotice()) {
614                 ZLOGD(LOG_LABEL, "SendObituary begin, desc:%{public}s", descStr8.c_str());
615                 remoteProxy->SendObituary();
616                 ZLOGD(LOG_LABEL, "SendObituary end, desc:%{public}s", descStr8.c_str());
617             } else {
618                 remoteProxy->SetObjectDied(true);
619                 ZLOGW(LOG_LABEL, "desc:%{public}s does not subscribe death notice", descStr8.c_str());
620             }
621         } else {
622             ZLOGE(LOG_LABEL, "cannot find proxy with desc:%{public}s", descStr8.c_str());
623         }
624     }
625     ZLOGI(LOG_LABEL, "close:%{public}d sussess", socketId);
626     return;
627 }
628 
OnDatabusSessionServerSideClosed(int32_t socketId)629 void DBinderDatabusInvoker::OnDatabusSessionServerSideClosed(int32_t socketId)
630 {
631     uint32_t tokenId = 0;
632     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
633     if (current == nullptr) {
634         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
635         return;
636     }
637     bool ret = current->StubDetachDBinderSession(socketId, tokenId);
638     // detach info whose socketId equals the given one
639     std::list<uint64_t> stubIndexs = current->DetachAppAuthInfoBySocketId(socketId);
640     std::lock_guard<std::mutex> lockGuard(GetObjectMutex());
641     for (auto it = stubIndexs.begin(); it != stubIndexs.end(); it++) {
642         // note that we canont remove mapping from stub to index here because other session may still be used
643         IRemoteObject *stub = current->QueryStubByIndex(*it);
644         if (stub == nullptr) {
645             continue;
646         }
647         // a proxy doesn't refers this stub, we need to dec ref
648         stub->DecStrongRef(this);
649     }
650     ZLOGI(LOG_LABEL, "socketId:%{public}d ret:%{public}d", socketId, ret);
651 }
652 
QueryHandleBySession(std::shared_ptr<DBinderSessionObject> session)653 uint32_t DBinderDatabusInvoker::QueryHandleBySession(std::shared_ptr<DBinderSessionObject> session)
654 {
655     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
656     if (current == nullptr) {
657         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
658         return 0;
659     }
660     return current->QueryHandleByDatabusSession(session->GetServiceName(), session->GetDeviceId(),
661         session->GetStubIndex());
662 }
663 
GetSeqNum() const664 uint64_t DBinderDatabusInvoker::GetSeqNum() const
665 {
666     return seqNumber_;
667 }
668 
SetSeqNum(uint64_t seq)669 void DBinderDatabusInvoker::SetSeqNum(uint64_t seq)
670 {
671     seqNumber_ = seq;
672 }
673 
GetClientFd() const674 int32_t DBinderDatabusInvoker::GetClientFd() const
675 {
676     return clientFd_;
677 }
678 
SetClientFd(int32_t fd)679 void DBinderDatabusInvoker::SetClientFd(int32_t fd)
680 {
681     clientFd_ = fd;
682 }
683 
GetCallerSid() const684 std::string DBinderDatabusInvoker::GetCallerSid() const
685 {
686     return "";
687 }
688 
GetCallerPid() const689 pid_t DBinderDatabusInvoker::GetCallerPid() const
690 {
691     return callerPid_;
692 }
693 
GetCallerRealPid() const694 pid_t DBinderDatabusInvoker::GetCallerRealPid() const
695 {
696     return callerPid_;
697 }
698 
SetStatus(uint32_t status)699 void DBinderDatabusInvoker::SetStatus(uint32_t status)
700 {
701     status_ = status;
702 }
703 
GetStatus()704 uint32_t DBinderDatabusInvoker::GetStatus()
705 {
706     return status_;
707 }
708 
SetCallerPid(pid_t pid)709 void DBinderDatabusInvoker::SetCallerPid(pid_t pid)
710 {
711     callerPid_ = pid;
712 }
713 
GetCallerUid() const714 uid_t DBinderDatabusInvoker::GetCallerUid() const
715 {
716     return callerUid_;
717 }
718 
SetCallerUid(pid_t uid)719 void DBinderDatabusInvoker::SetCallerUid(pid_t uid)
720 {
721     callerUid_ = uid;
722 }
723 
GetCallerTokenID() const724 uint64_t DBinderDatabusInvoker::GetCallerTokenID() const
725 {
726     return callerTokenID_;
727 }
728 
GetFirstCallerTokenID() const729 uint64_t DBinderDatabusInvoker::GetFirstCallerTokenID() const
730 {
731     return firstTokenID_;
732 }
733 
GetSelfTokenID() const734 uint64_t DBinderDatabusInvoker::GetSelfTokenID() const
735 {
736     IRemoteInvoker *invoker = IPCThreadSkeleton::GetDefaultInvoker();
737     if (invoker != nullptr) {
738         return invoker->GetSelfTokenID();
739     }
740     return 0;
741 }
742 
GetSelfFirstCallerTokenID() const743 uint64_t DBinderDatabusInvoker::GetSelfFirstCallerTokenID() const
744 {
745     IRemoteInvoker *invoker = IPCThreadSkeleton::GetDefaultInvoker();
746     if (invoker != nullptr) {
747         return invoker->GetSelfFirstCallerTokenID();
748     }
749     return 0;
750 }
751 
SetCallerDeviceID(const std::string & deviceId)752 void DBinderDatabusInvoker::SetCallerDeviceID(const std::string &deviceId)
753 {
754     callerDeviceID_ = deviceId;
755 }
756 
SetCallerTokenID(const uint32_t tokenId)757 void DBinderDatabusInvoker::SetCallerTokenID(const uint32_t tokenId)
758 {
759     callerTokenID_ = tokenId;
760     firstTokenID_ = tokenId;
761 }
762 
IsLocalCalling()763 bool DBinderDatabusInvoker::IsLocalCalling()
764 {
765     return false;
766 }
767 
CheckAndSetCallerInfo(int32_t socketId,uint64_t stubIndex)768 int DBinderDatabusInvoker::CheckAndSetCallerInfo(int32_t socketId, uint64_t stubIndex)
769 {
770     std::shared_ptr<DBinderSessionObject> session = QueryClientSessionObject(socketId);
771     if (session == nullptr) {
772         ZLOGE(LOG_LABEL, "get databus session fail");
773         return RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
774     }
775 
776     int pid = static_cast<int>(session->GetPeerPid());
777     int uid = static_cast<int>(session->GetPeerUid());
778     std::string deviceId = session->GetDeviceId();
779     if (uid < 0 || deviceId.length() > DEVICEID_LENGTH) {
780         ZLOGE(LOG_LABEL, "user id and device id error");
781         return RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
782     }
783 
784     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
785     if (current == nullptr) {
786         ZLOGE(LOG_LABEL, "current process skeleton is nullptr");
787         return IPC_SKELETON_ERR;
788     }
789     uint32_t callerTokenId = session->GetTokenId();
790     AppAuthInfo appAuthInfo = { pid, uid, callerTokenId, socketId, stubIndex, nullptr, deviceId };
791     if (current->QueryAppInfoToStubIndex(appAuthInfo) == false) {
792         ZLOGE(LOG_LABEL, "stubIndex:%{public}" PRIu64 " is NOT belong to caller, pid:%{public}d uid:%{public}d"
793             " deviceId:%{public}s socketId:%{public}d callerTokenId:%{public}u", stubIndex, pid, uid,
794             IPCProcessSkeleton::ConvertToSecureString(deviceId).c_str(), socketId, callerTokenId);
795         return RPC_DATABUS_INVOKER_INVALID_STUB_INDEX;
796     }
797     DBinderCallerInfo callerInfo = { pid, uid, socketId, callerTokenId, callerTokenId, deviceId };
798     SetCallerInfo(callerInfo);
799     return ERR_NONE;
800 }
801 
SetCallerInfo(DBinderCallerInfo & callerInfo)802 void DBinderDatabusInvoker::SetCallerInfo(DBinderCallerInfo &callerInfo)
803 {
804     callerPid_ = callerInfo.callerPid;
805     callerUid_ = callerInfo.callerUid;
806     callerDeviceID_ = callerInfo.callerDeviceID;
807     clientFd_ = callerInfo.clientFd;
808     callerTokenID_ = callerInfo.callerTokenID;
809     firstTokenID_ = callerInfo.firstTokenID;
810 }
811 
GetCallerInfo(DBinderCallerInfo & callerInfo)812 void DBinderDatabusInvoker::GetCallerInfo(DBinderCallerInfo &callerInfo)
813 {
814     callerInfo.callerPid = callerPid_;
815     callerInfo.callerUid = callerUid_;
816     callerInfo.callerDeviceID = callerDeviceID_;
817     callerInfo.clientFd = clientFd_;
818     callerInfo.callerTokenID = callerTokenID_;
819     callerInfo.firstTokenID = firstTokenID_;
820 }
821 
GetLocalDeviceID()822 std::string DBinderDatabusInvoker::GetLocalDeviceID()
823 {
824     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
825     if (current == nullptr) {
826         ZLOGE(LOG_LABEL, "current process skeleton is nullptr");
827         return "";
828     }
829 
830     return current->GetLocalDeviceID();
831 }
832 
GetCallerDeviceID() const833 std::string DBinderDatabusInvoker::GetCallerDeviceID() const
834 {
835     return callerDeviceID_;
836 }
837 
MakeStubIndexByRemoteObject(IRemoteObject * stubObject)838 uint64_t DBinderDatabusInvoker::MakeStubIndexByRemoteObject(IRemoteObject *stubObject)
839 {
840     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
841     if (current == nullptr) {
842         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
843         return 0;
844     }
845 
846     if (!current->IsContainsObject(stubObject)) {
847         ZLOGE(LOG_LABEL, "fail to find stub");
848         return 0;
849     }
850 
851     uint64_t stubIndex = current->AddStubByIndex(stubObject);
852     if (!stubIndex) {
853         ZLOGE(LOG_LABEL, "fail to add stub");
854         return 0;
855     }
856     return stubIndex;
857 }
858 
MakeDefaultServerSessionObject(uint64_t stubIndex,const std::shared_ptr<DBinderSessionObject> sessionObject)859 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::MakeDefaultServerSessionObject(uint64_t stubIndex,
860     const std::shared_ptr<DBinderSessionObject> sessionObject)
861 {
862     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
863     if (current == nullptr) {
864         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
865         return nullptr;
866     }
867     std::string serviceName = current->GetDatabusName();
868     std::string deviceId = current->GetLocalDeviceID();
869     if (serviceName.empty() || deviceId.empty()) {
870         ZLOGE(LOG_LABEL, "fail to get databus name:%{public}s or deviceId length:%{public}zu",
871             serviceName.c_str(), deviceId.length());
872         return nullptr;
873     }
874 
875     auto session = std::make_shared<DBinderSessionObject>(serviceName, deviceId, stubIndex, nullptr,
876         sessionObject->GetTokenId());
877     if (session == nullptr) {
878         ZLOGE(LOG_LABEL, "new server session fail, service:%{public}s deviceId:%{public}s stubIndex:%{public}" PRIu64,
879             serviceName.c_str(), IPCProcessSkeleton::ConvertToSecureString(deviceId).c_str(), stubIndex);
880         return nullptr;
881     }
882     return session;
883 }
884 
ConnectRemoteObject2Session(IRemoteObject * stubObject,uint64_t stubIndex,const std::shared_ptr<DBinderSessionObject> sessionObject)885 bool DBinderDatabusInvoker::ConnectRemoteObject2Session(IRemoteObject *stubObject, uint64_t stubIndex,
886     const std::shared_ptr<DBinderSessionObject> sessionObject)
887 {
888     if (sessionObject == nullptr) {
889         ZLOGE(LOG_LABEL, "session object is nullptr");
890         return false;
891     }
892     IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
893     if (current == nullptr) {
894         ZLOGE(LOG_LABEL, "IPCProcessSkeleton is nullptr");
895         return false;
896     }
897 
898     int peerPid = sessionObject->GetPeerPid();
899     int peerUid = sessionObject->GetPeerUid();
900     uint32_t tokenId = sessionObject->GetTokenId();
901     std::string deviceId = sessionObject->GetDeviceId();
902     ZLOGI(LOG_LABEL, "pid:%{public}d uid:%{public}d deviceId:%{public}s tokenId:%{public}u "
903         "stubIndex:%{public}" PRIu64, peerPid, peerUid, IPCProcessSkeleton::ConvertToSecureString(deviceId).c_str(),
904         tokenId, stubIndex);
905     // mark socketId as 0
906     AppAuthInfo appAuthInfo = { peerPid, peerUid, tokenId, 0, stubIndex, stubObject, deviceId };
907     if (current->AttachOrUpdateAppAuthInfo(appAuthInfo)) {
908         // first time send this stub to proxy indicating by deviceId, pid, uid
909         stubObject->IncStrongRef(this);
910     }
911     return true;
912 }
913 
CreateServerSessionObject(binder_uintptr_t binder,std::shared_ptr<DBinderSessionObject> sessionObject)914 std::shared_ptr<DBinderSessionObject> DBinderDatabusInvoker::CreateServerSessionObject(binder_uintptr_t binder,
915     std::shared_ptr<DBinderSessionObject> sessionObject)
916 {
917     IRemoteObject *stubObject = reinterpret_cast<IPCObjectStub *>(binder);
918     if (stubObject == nullptr) {
919         ZLOGE(LOG_LABEL, "binder is nullptr");
920         return nullptr;
921     }
922 
923     uint64_t stubIndex = MakeStubIndexByRemoteObject(stubObject);
924     if (stubIndex == 0) {
925         ZLOGE(LOG_LABEL, "fail to add stub");
926         return nullptr;
927     }
928     if (ConnectRemoteObject2Session(stubObject, stubIndex, sessionObject) != true) {
929         ZLOGE(LOG_LABEL, "fail to connect stub to session, stubIndex:%{public}" PRIu64, stubIndex);
930         return nullptr;
931     }
932     return MakeDefaultServerSessionObject(stubIndex, sessionObject);
933 }
934 
FlushCommands(IRemoteObject * object)935 int DBinderDatabusInvoker::FlushCommands(IRemoteObject *object)
936 {
937     if (object == nullptr || !object->IsProxyObject()) {
938         ZLOGE(LOG_LABEL, "proxy is invalid");
939         return RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
940     }
941 
942     IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(object);
943 
944     std::shared_ptr<DBinderSessionObject> session = QueryServerSessionObject(proxy->GetHandle());
945     if (session == nullptr) {
946         ZLOGE(LOG_LABEL, "session is nullptr");
947         return RPC_DATABUS_INVOKER_INVALID_DATA_ERR;
948     }
949 
950     (void)OnSendMessage(session);
951     return ERR_NONE;
952 }
953 
ResetCallingIdentity()954 std::string DBinderDatabusInvoker::ResetCallingIdentity()
955 {
956     std::string token = std::to_string(((static_cast<uint64_t>(callerUid_) << PID_LEN)
957         | static_cast<uint64_t>(callerPid_)));
958     std::string identity = callerDeviceID_ + token;
959     char buf[ACCESS_TOKEN_MAX_LEN + 1] = {0};
960     int ret = sprintf_s(buf, ACCESS_TOKEN_MAX_LEN + 1, "%010" PRIu64, callerTokenID_);
961     if (ret < 0) {
962         ZLOGE(LOG_LABEL, "sprintf callerTokenID:%{public}" PRIu64 " failed", callerTokenID_);
963         return "";
964     }
965     std::string accessToken(buf);
966     callerUid_ = (pid_t)getuid();
967     callerPid_ = getpid();
968     callerDeviceID_ = GetLocalDeviceID();
969     callerTokenID_ = GetSelfTokenID();
970     return accessToken + identity;
971 }
972 
SetCallingIdentity(std::string & identity,bool flag)973 bool DBinderDatabusInvoker::SetCallingIdentity(std::string &identity, bool flag)
974 {
975     (void)flag;
976     if (identity.empty() || identity.length() <= DEVICEID_LENGTH) {
977         return false;
978     }
979     std::string tokenIdStr;
980     uint64_t tokenId = 0;
981     if (!ProcessSkeleton::GetSubStr(identity, tokenIdStr, 0, ACCESS_TOKEN_MAX_LEN) ||
982         !ProcessSkeleton::StrToUint64(tokenIdStr, tokenId)) {
983         ZLOGE(LOG_LABEL, "Identity param tokenId is invalid");
984         return false;
985     }
986     std::string deviceId;
987     if (!ProcessSkeleton::GetSubStr(identity, deviceId, ACCESS_TOKEN_MAX_LEN, DEVICEID_LENGTH)) {
988         ZLOGE(LOG_LABEL, "Identity param deviceId is invalid");
989         return false;
990     }
991     std::string tokenStr;
992     size_t offset = ACCESS_TOKEN_MAX_LEN + DEVICEID_LENGTH;
993     if (identity.length() <= offset) {
994         ZLOGE(LOG_LABEL, "Identity param no token, len:%{public}zu, offset:%{public}zu", identity.length(), offset);
995         return false;
996     }
997     size_t subLen = identity.length() - offset;
998     uint64_t token = 0;
999     if (!ProcessSkeleton::GetSubStr(identity, tokenStr, offset, subLen) ||
1000         !ProcessSkeleton::StrToUint64(tokenStr, token)) {
1001         ZLOGE(LOG_LABEL, "Identity param token is invalid");
1002         return false;
1003     }
1004     callerUid_ = static_cast<pid_t>(token >> PID_LEN);
1005     callerPid_ = static_cast<pid_t>(token);
1006     callerDeviceID_ = deviceId;
1007     callerTokenID_ = tokenId;
1008     return true;
1009 }
1010 
TriggerSystemIPCThreadReclaim()1011 bool DBinderDatabusInvoker::TriggerSystemIPCThreadReclaim()
1012 {
1013     ZLOGD(LOG_LABEL, "do not support");
1014     return false;
1015 }
1016 
EnableIPCThreadReclaim(bool enable)1017 bool DBinderDatabusInvoker::EnableIPCThreadReclaim(bool enable)
1018 {
1019     (void)enable;
1020     ZLOGD(LOG_LABEL, "do not support");
1021     return false;
1022 }
1023 
TranslateIRemoteObject(int32_t cmd,const sptr<IRemoteObject> & obj)1024 int DBinderDatabusInvoker::TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj)
1025 {
1026     return -IPC_INVOKER_TRANSLATE_ERR;
1027 }
1028 
HasRawDataPackage(const char * data,ssize_t len)1029 uint32_t DBinderDatabusInvoker::HasRawDataPackage(const char *data, ssize_t len)
1030 {
1031     const dbinder_transaction_data *tr = reinterpret_cast<const dbinder_transaction_data *>(data);
1032     if ((tr->magic == DBINDER_MAGICWORD) && (tr->cmd == BC_SEND_RAWDATA) &&
1033         (tr->sizeOfSelf == static_cast<uint32_t>(len))) {
1034         if (tr->sizeOfSelf > MAX_RAWDATA_SIZE) {
1035             return MAX_RAWDATA_SIZE;
1036         }
1037         return tr->sizeOfSelf;
1038     }
1039     return 0;
1040 }
1041 
HasCompletePackage(const char * data,uint32_t readCursor,ssize_t len)1042 uint32_t DBinderDatabusInvoker::HasCompletePackage(const char *data, uint32_t readCursor, ssize_t len)
1043 {
1044     const dbinder_transaction_data *tr = reinterpret_cast<const dbinder_transaction_data *>(data + readCursor);
1045     if ((tr->magic == DBINDER_MAGICWORD) &&
1046         (tr->sizeOfSelf <= SOCKET_MAX_BUFF_SIZE + sizeof(dbinder_transaction_data)) &&
1047         (readCursor + tr->sizeOfSelf <= static_cast<uint32_t>(len)) && CheckTransactionData(tr)) {
1048         return tr->sizeOfSelf;
1049     }
1050     return 0;
1051 }
1052 } // namespace OHOS
1053