提交 719f5513 编写于 作者: H heyingjiao

Description:sync hmos rpc code

Feature or Bugfix:Feature
Binary Source: No
Signed-off-by: Nheyingjiao <heyingjiao@huawei.com>
上级 cf93591f
......@@ -66,9 +66,10 @@ public:
int InvokeListenThread(MessageParcel &data, MessageParcel &reply);
int32_t NoticeServiceDie();
std::string GetPidAndUidInfo(int32_t systemAbilityId);
std::string GetDataBusName(int32_t systemAbilityId);
std::string TransDataBusName(uint32_t uid, uint32_t pid);
int GetPidUid(MessageParcel &reply);
std::string GetSessionName();
std::string GetSessionNameForPidUid(uint32_t uid, uint32_t pid);
std::string GetGrantedSessionName();
int GetProto() const;
void WaitForInit();
std::u16string GetInterfaceDescriptor();
......@@ -88,7 +89,7 @@ private:
int32_t IncRefToRemote();
int GetSessionFromDBinderService();
int GetProtoInfo();
bool AddDbinderDeathRecipient();
......
......@@ -80,15 +80,14 @@ public:
int32_t InvokerThread(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
int32_t NoticeServiceDie(MessageParcel &data, MessageParcel &reply, MessageOption &option);
int32_t InvokerDataBusThread(MessageParcel &data, MessageParcel &reply);
int32_t IncStubRefs(MessageParcel &data, MessageParcel &reply);
int32_t DecStubRefs(MessageParcel &data, MessageParcel &reply);
int32_t AddAuthInfo(MessageParcel &data, MessageParcel &reply, uint32_t code);
private:
int32_t GrantDataBusName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
int32_t TransDataBusName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
std::string CreateDatabusName(int uid, int pid, int systemAbilityId);
std::string GetDataBusName(int32_t systemAbilityId);
int GetPidUid(MessageParcel &data, MessageParcel &reply);
std::string GetSessionName();
int32_t GetSessionNameForPidUid(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
int32_t GetGrantedSessionName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option);
std::string CreateSessionName(int uid, int pid);
bool IsSamgrCall(uint32_t accessToken);
bool HasDumpPermission(uint32_t accessToken) const;
#endif
......
......@@ -45,6 +45,8 @@ public:
static uint64_t GetFirstFullTokenID();
static uint64_t GetSelfTokenID();
static std::string GetLocalDeviceID();
static std::string GetCallingDeviceID();
......
......@@ -35,15 +35,15 @@ enum {
SYSPROPS_TRANSACTION = ZIPC_PACK_CHARS('_', 'S', 'P', 'R'),
SYNCHRONIZE_REFERENCE = ZIPC_PACK_CHARS('_', 'S', 'Y', 'C'),
INVOKE_LISTEN_THREAD = ZIPC_PACK_CHARS('_', 'I', 'L', 'T'),
GET_PID_UID = ZIPC_PACK_CHARS('_', 'G', 'P', 'U'),
GET_PROTO_INFO = ZIPC_PACK_CHARS('_', 'G', 'R', 'I'),
GET_UIDPID_INFO = ZIPC_PACK_CHARS('_', 'G', 'U', 'I'),
GRANT_DATABUS_NAME = ZIPC_PACK_CHARS('_', 'G', 'D', 'N'),
TRANS_DATABUS_NAME = ZIPC_PACK_CHARS('_', 'T', 'D', 'N'),
GET_SESSION_NAME = ZIPC_PACK_CHARS('_', 'G', 'S', 'N'),
GET_SESSION_NAME_PID_UID = ZIPC_PACK_CHARS('_', 'G', 'S', 'P'),
GET_GRANTED_SESSION_NAME = ZIPC_PACK_CHARS('_', 'G', 'G', 'S'),
DBINDER_OBITUARY_TRANSACTION = ZIPC_PACK_CHARS('_', 'D', 'O', 'T'),
DBINDER_INCREFS_TRANSACTION = ZIPC_PACK_CHARS('_', 'D', 'I', 'T'),
DBINDER_DECREFS_TRANSACTION = ZIPC_PACK_CHARS('_', 'D', 'D', 'T'),
DBINDER_ADD_COMMAUTH = ZIPC_PACK_CHARS('_', 'D', 'A', 'C'),
DBINDER_TRANS_COMMAUTH = ZIPC_PACK_CHARS('_', 'D', 'T', 'C'),
TRANS_SYNC = 0,
TRANS_ASYNC = 1,
};
......
......@@ -29,6 +29,7 @@
#include "ipc_object_stub.h"
#include "rpc_system_ability_callback.h"
#include "Session.h"
#include "thread_pool.h"
using Communication::SoftBus::Session;
......@@ -37,13 +38,16 @@ class DBinderRemoteListener;
constexpr int DEVICEID_LENGTH = 64;
constexpr int SERVICENAME_LENGTH = 200;
constexpr int VERSION_NUM = 1;
/* version change history
* a) 1 --> 2, support transfer tokenid to peer device
*/
constexpr int RPC_TOKENID_SUPPORT_VERSION = 2;
constexpr int ENCRYPT_HEAD_LEN = 28;
constexpr int ENCRYPT_LENGTH = 4;
struct DeviceIdInfo {
uint16_t afType;
uint16_t reserved;
uint32_t tokenId;
char fromDeviceId[DEVICEID_LENGTH + 1];
char toDeviceId[DEVICEID_LENGTH + 1];
};
......@@ -57,7 +61,8 @@ struct DHandleEntryTxRx {
struct DHandleEntryHead head;
uint32_t transType;
uint32_t dBinderCode;
uint32_t rpcFeatureSet;
uint16_t fromPort;
uint16_t toPort;
uint64_t stubIndex;
uint32_t seqNumber;
binder_uintptr_t binderObject;
......@@ -72,7 +77,8 @@ struct DHandleEntryTxRx {
struct SessionInfo {
uint32_t seqNumber;
uint32_t type;
uint32_t rpcFeatureSet;
uint16_t toPort;
uint16_t fromPort;
uint64_t stubIndex;
uint32_t socketFd;
std::string serviceName;
......@@ -84,12 +90,23 @@ enum DBinderCode {
MESSAGE_AS_REPLY = 2,
MESSAGE_AS_OBITUARY = 3,
MESSAGE_AS_REMOTE_ERROR = 4,
MESSAGE_AS_REPLY_TOKENID = 5,
};
enum AfType {
IPV4_TYPE = 1,
IPV6_TYPE = 2,
DATABBUS_TYPE = 3,
enum DBinderErrorCode {
DBINDER_OK = 100,
STUB_INVALID = 101,
SEND_MESSAGE_FAILED = 102,
MAKE_THREADLOCK_FAILED = 103,
WAIT_REPLY_TIMEOUT = 104,
QUERY_REPLY_SESSION_FAILED = 105,
SA_NOT_FOUND = 106,
SA_INVOKE_FAILED = 107,
DEVICEID_INVALID = 108,
SESSION_NAME_NOT_FOUND = 109,
WRITE_PARCEL_FAILED = 110,
INVOKE_STUB_THREAD_FAILED = 111,
SESSION_NAME_INVALID = 112,
};
struct ThreadLockInfo {
......@@ -105,12 +122,14 @@ public:
virtual ~DBinderService();
public:
static sptr<DBinderService> GetInstance();
static std::string ConvertToSecureDeviceID(const std::string &deviceID);
bool StartDBinderService(std::shared_ptr<RpcSystemAbilityCallback> &callbackImpl);
sptr<DBinderServiceStub> MakeRemoteBinder(const std::u16string &serviceName,
const std::string &deviceID, binder_uintptr_t binderObject, uint32_t pid = 0, uint32_t uid = 0);
const std::string &deviceID, int32_t binderObject, uint32_t pid = 0, uint32_t uid = 0);
bool RegisterRemoteProxy(std::u16string serviceName, sptr<IRemoteObject> binderObject);
bool RegisterRemoteProxy(std::u16string serviceName, int32_t systemAbilityId);
bool OnRemoteMessageTask(const struct DHandleEntryTxRx *message);
bool OnRemoteMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message);
void AddAsynMessageTask(std::shared_ptr<struct DHandleEntryTxRx> message);
std::shared_ptr<struct SessionInfo> QuerySessionObject(binder_uintptr_t stub);
bool DetachDeathRecipient(sptr<IRemoteObject> object);
bool AttachDeathRecipient(sptr<IRemoteObject> object, sptr<IRemoteObject::DeathRecipient> deathRecipient);
......@@ -119,11 +138,8 @@ public:
bool AttachCallbackProxy(sptr<IRemoteObject> object, DBinderServiceStub *dbStub);
int32_t NoticeServiceDie(const std::u16string &serviceName, const std::string &deviceID);
int32_t NoticeDeviceDie(const std::string &deviceID);
bool AttachBusNameObject(IPCObjectProxy *proxy, const std::string &name);
bool DetachBusNameObject(IPCObjectProxy *proxy);
std::string CreateDatabusName(int uid, int pid);
bool DetachProxyObject(binder_uintptr_t binderObject);
std::string QueryBusNameObject(IPCObjectProxy *proxy);
void LoadSystemAbilityComplete(const std::string& srcNetworkId, int32_t systemAbilityId,
const sptr<IRemoteObject>& remoteObject);
bool ProcessOnSessionClosed(std::shared_ptr<Session> session);
......@@ -132,10 +148,10 @@ private:
static std::shared_ptr<DBinderRemoteListener> GetRemoteListener();
static bool StartRemoteListener();
static void StopRemoteListener();
static std::string ConvertToSecureDeviceID(const std::string &deviceID);
std::u16string GetRegisterService(binder_uintptr_t binderObject);
bool InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub, uint32_t seqNumber, uint32_t pid, uint32_t uid);
void OnRemoteReplyMessage(const struct DHandleEntryTxRx *replyMessage);
int32_t InvokerRemoteDBinder(const sptr<DBinderServiceStub> stub, uint32_t seqNumber, uint32_t pid, uint32_t uid);
bool OnRemoteReplyMessage(const struct DHandleEntryTxRx *replyMessage);
bool OnRemoteErrorMessage(const struct DHandleEntryTxRx *replyMessage);
void MakeSessionByReplyMessage(const struct DHandleEntryTxRx *replyMessage);
bool OnRemoteInvokerMessage(const struct DHandleEntryTxRx *message);
void WakeupThreadByStub(uint32_t seqNumber);
......@@ -164,23 +180,25 @@ private:
std::list<std::u16string> FindServicesByDeviceID(const std::string &deviceID);
int32_t NoticeServiceDieInner(const std::u16string &serviceName, const std::string &deviceID);
uint32_t GetRemoteTransType();
bool OnRemoteInvokerDataBusMessage(IPCObjectProxy *proxy, struct DHandleEntryTxRx *replyMessage,
std::string &remoteDeviceId, int pid, int uid);
uint32_t OnRemoteInvokerDataBusMessage(IPCObjectProxy *proxy, struct DHandleEntryTxRx *replyMessage,
std::string &remoteDeviceId, int pid, int uid, uint32_t tokenId);
bool IsDeviceIdIllegal(const std::string &deviceID);
std::string GetDatabusNameByProxy(IPCObjectProxy *proxy, int32_t systemAbilityId);
std::string GetDatabusNameByProxy(IPCObjectProxy *proxy);
uint32_t GetSeqNumber();
bool StartThreadPool();
bool StopThreadPool();
bool AddAsynTask(const ThreadPool::Task &f);
bool IsSameSession(std::shared_ptr<struct SessionInfo> oldSession, std::shared_ptr<struct SessionInfo> newSession);
bool RegisterRemoteProxyInner(std::u16string serviceName, binder_uintptr_t binder);
bool CheckSystemAbilityId(int32_t systemAbilityId);
bool IsSameSession(std::shared_ptr<struct SessionInfo> oldSession, std::shared_ptr<struct SessionInfo> nowSession);
bool HandleInvokeListenThread(IPCObjectProxy *proxy, uint64_t stubIndex, std::string serverSessionName,
struct DHandleEntryTxRx *replyMessage);
bool ReStartRemoteListener();
bool ReGrantPermission(const std::string &sessionName);
bool IsSameLoadSaItem(const std::string& srcNetworkId, int32_t systemAbilityId,
std::shared_ptr<DHandleEntryTxRx> loadSaItem);
std::shared_ptr<struct DHandleEntryTxRx> PopLoadSaItem(const std::string& srcNetworkId, int32_t systemAbilityId);
void OnRemoteErrorMessage(const struct DHandleEntryTxRx *replyMessage);
void SendMessageToRemote(uint32_t dBinderCode, std::shared_ptr<struct DHandleEntryTxRx> replyMessage);
void SendMessageToRemote(uint32_t dBinderCode, uint32_t reason,
std::shared_ptr<struct DHandleEntryTxRx> replyMessage);
private:
DISALLOW_COPY_AND_MOVE(DBinderService);
......@@ -192,7 +210,6 @@ private:
static sptr<DBinderService> instance_;
std::shared_mutex remoteBinderMutex_;
std::shared_mutex busNameMutex_;
std::shared_mutex proxyMutex_;
std::shared_mutex deathRecipientMutex_;
std::shared_mutex sessionMutex_;
......@@ -202,6 +219,7 @@ private:
std::mutex threadLockMutex_;
std::mutex callbackProxyMutex_;
std::mutex deathNotificationMutex_;
std::mutex threadPoolMutex_;
uint32_t seqNumber_ = 0; /* indicate make remote binder message sequence number, and can be overflow */
std::list<sptr<DBinderServiceStub>> DBinderStubRegisted_;
......@@ -211,7 +229,9 @@ private:
std::map<binder_uintptr_t, std::shared_ptr<struct SessionInfo>> sessionObject_;
std::map<sptr<IRemoteObject>, DBinderServiceStub *> noticeProxy_;
std::map<sptr<IRemoteObject>, sptr<IRemoteObject::DeathRecipient>> deathRecipients_;
std::map<IPCObjectProxy *, std::string> busNameObject_;
bool threadPoolStarted_ = false;
int32_t threadPoolNumber_ = 4;
std::unique_ptr<ThreadPool> threadPool_ = nullptr;
std::list<std::shared_ptr<struct DHandleEntryTxRx>> loadSaReply_;
static constexpr int32_t FIRST_SYS_ABILITY_ID = 0x00000001;
static constexpr int32_t LAST_SYS_ABILITY_ID = 0x00ffffff;
......
......@@ -21,18 +21,22 @@
#include "ipc_object_stub.h"
namespace OHOS {
#ifdef BINDER_IPC_32BIT
typedef unsigned int binder_uintptr_t;
#else
typedef unsigned long long binder_uintptr_t;
#endif
class DBinderServiceStub : public IPCObjectStub {
public:
explicit DBinderServiceStub(const std::string& serviceName, const std::string& deviceID,
explicit DBinderServiceStub(const std::string &serviceName, const std::string &deviceID,
binder_uintptr_t binderObject);
~DBinderServiceStub();
int32_t ProcessProto(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
const std::string& GetServiceName();
const std::string& GetDeviceID();
const std::string &GetServiceName();
const std::string &GetDeviceID();
binder_uintptr_t GetBinderObject() const;
private:
......
......@@ -27,7 +27,7 @@
namespace OHOS {
constexpr int SOCKET_DEFAULT_BUFF_SIZE = 4 * 1024;
constexpr int SOCKET_MAX_BUFF_SIZE = 1024 * 1024;
constexpr uint32_t SOCKET_BUFF_RESERVED_SIZE = 256;
constexpr int SOCKET_BUFF_RESERVED_SIZE = 256;
constexpr size_t MAX_RAWDATA_SIZE = 128 * 1024 * 1024; // 128M
constexpr uint32_t SOCKET_BUFF_SIZE_USER_S = 4 * 1024;
......@@ -42,7 +42,7 @@ public:
~BufferObject();
void UpdateReceiveBuffer();
void UpdateSendBuffer();
void UpdateSendBuffer(uint32_t userDataSize);
char *GetSendBufferAndLock(uint32_t size);
char *GetReceiveBufferAndLock(uint32_t size);
void ReleaseSendBufferLock();
......@@ -61,6 +61,7 @@ public:
private:
DISALLOW_COPY_AND_MOVE(BufferObject);
bool ExpandSendBuffer(uint32_t size);
ssize_t recvBufferCursorW_ = 0;
ssize_t recvBufferCursorR_ = 0;
ssize_t sendBufferCursorW_ = 0;
......
......@@ -18,26 +18,24 @@
#include "iremote_object.h"
#include "ipc_object_stub.h"
#include "rpc_feature_set.h"
namespace OHOS {
class CommAuthInfo {
public:
CommAuthInfo(IRemoteObject *stub, int pid, int uid, const std::string &deviceId,
std::shared_ptr<FeatureSetData> featureSet);
CommAuthInfo(IRemoteObject *stub, int pid, int uid, uint32_t tokenId, const std::string &deviceId);
virtual ~CommAuthInfo();
const IRemoteObject *GetStubObject() const;
IRemoteObject *GetStubObject() const;
int GetRemotePid() const;
int GetRemoteUid() const;
uint32_t GetRemoteTokenId() const;
std::string GetRemoteDeviceId() const;
std::shared_ptr<FeatureSetData> GetFeatureSet() const;
private:
IRemoteObject *stub_;
int remotePid_;
int remoteUid_;
uint32_t tokenId_;
std::string deviceId_;
std::shared_ptr<FeatureSetData> featureSet_;
};
} // namespace OHOS
#endif // OHOS_IPC_COMMAUTHINFO_H
\ No newline at end of file
......@@ -17,16 +17,13 @@
#define OHOS_IPC_DBINDER_CALLBACK_STUB_H
#include <string>
#include "ipc_object_stub.h"
#include "rpc_feature_set.h"
namespace OHOS {
class DBinderCallbackStub : public IPCObjectStub {
public:
explicit DBinderCallbackStub(const std::string &serviceName, const std::string &peerDeviceID,
const std::string &localDeviceID, uint64_t stubIndex, uint32_t handle,
std::shared_ptr<FeatureSetData> feature);
const std::string &localDeviceID, uint64_t stubIndex, uint32_t handle, uint32_t tokenId);
~DBinderCallbackStub();
int32_t ProcessProto(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
......@@ -34,10 +31,7 @@ public:
const std::string &GetServiceName();
const std::string &GetDeviceID();
uint64_t GetStubIndex() const;
std::shared_ptr<FeatureSetData> GetFeatureSet() const;
private:
uint32_t ConstructAuthData(MessageParcel &authData, uint32_t featureSet);
uint32_t GetTokenId() const;
private:
const std::string serviceName_;
......@@ -45,7 +39,7 @@ private:
const std::string localDeviceID_;
uint64_t stubIndex_;
uint32_t handle_;
std::shared_ptr<FeatureSetData> rpcFeatureSet_;
uint32_t tokenId_;
};
} // namespace OHOS
#endif // OHOS_IPC_DBINDER_CALLBACK_STUB_H
\ No newline at end of file
......@@ -16,7 +16,7 @@
#ifndef OHOS_IPC_DBINDER_ERROR_CODE_H
#define OHOS_IPC_DBINDER_ERROR_CODE_H
#include<string>
#include <string>
#ifndef BUILD_PUBLIC_VERSION
#include "hiview.h"
#include "hievent.h"
......
......@@ -20,8 +20,8 @@
#include <mutex>
#include "nocopyable.h"
#include "buffer_object.h"
#include "ipc_object_proxy.h"
#include "rpc_feature_set.h"
#include "Session.h"
#include "ISessionService.h"
......@@ -30,7 +30,9 @@ using Communication::SoftBus::Session;
namespace OHOS {
constexpr int DEVICEID_LENGTH = 64;
constexpr int SERVICENAME_LENGTH = 200;
constexpr int NOT_SUPPORT_TOKENID_SERVICENAME_LENGTH = 200;
constexpr int SUPPORT_TOKENID_SERVICENAME_LENGTH = 64;
constexpr int RESERVED_FROM_SERVICENAME_LENGTH = 125;
/* struct FlatDBinderSession is for flat DatabusSessionObject to transfer to another device */
struct FlatDBinderSession {
......@@ -38,28 +40,37 @@ struct FlatDBinderSession {
uint16_t deviceIdLength;
uint16_t serviceNameLength;
char deviceId[DEVICEID_LENGTH + 1];
char serviceName[SERVICENAME_LENGTH + 1];
char serviceName[SUPPORT_TOKENID_SERVICENAME_LENGTH + 1];
uint16_t version; // for alignment
uint32_t magic;
uint32_t tokenId;
char reserved[RESERVED_FROM_SERVICENAME_LENGTH];
// if not support tokenid, this is end of serviceName, which is '\0', this position equal to
// NOT_SUPPORT_TOKENID_SERVICENAME_LENGTH = 200 + 1
char canNotUse;
};
class DBinderSessionObject {
public:
static uint32_t GetFlatSessionLen();
explicit DBinderSessionObject(std::shared_ptr<Session> session, const std::string &serviceName,
const std::string &serverDeviceId);
const std::string &serverDeviceId, uint64_t stubIndex, IPCObjectProxy *proxy, uint32_t tokenId);
~DBinderSessionObject();
void SetBusSession(std::shared_ptr<Session> session);
void SetServiceName(const std::string &serviceName);
void SetDeviceId(const std::string &serverDeviceId);
void SetFeatureSet(std::shared_ptr<FeatureSetData> rpcFeatureSet);
void SetProxy(IPCObjectProxy *proxy);
std::shared_ptr<BufferObject> GetSessionBuff();
std::shared_ptr<Session> GetBusSession() const;
std::string GetServiceName() const;
std::string GetDeviceId() const;
std::shared_ptr<FeatureSetData> GetFeatureSet() const;
IPCObjectProxy *GetProxy() const;
uint64_t GetStubIndex() const;
uint32_t GetSessionHandle() const;
void CloseDatabusSession();
uint32_t GetTokenId() const;
private:
DISALLOW_COPY_AND_MOVE(DBinderSessionObject);
......@@ -69,7 +80,9 @@ private:
std::shared_ptr<BufferObject> buff_;
std::string serviceName_;
std::string serverDeviceId_;
std::shared_ptr<FeatureSetData> rpcFeatureSet_;
uint64_t stubIndex_;
IPCObjectProxy *proxy_;
uint32_t tokenId_;
};
} // namespace OHOS
#endif // OHOS_IPC_DBINDER_SESSION_OBJECT_H
\ No newline at end of file
......@@ -33,7 +33,6 @@
#include "comm_auth_info.h"
#include "dbinder_callback_stub.h"
#include "dbinder_session_object.h"
#include "rpc_feature_set.h"
#include "ISessionService.h"
#include "Session.h"
#include "stub_refcount_object.h"
......@@ -55,13 +54,15 @@ struct SocketThreadLockInfo {
};
struct ThreadMessageInfo {
std::thread::id threadId;
uint32_t flags;
binder_size_t bufferSize;
binder_size_t offsetsSize;
binder_uintptr_t offsets;
uint32_t socketId;
void *buffer;
std::mutex mutex;
std::condition_variable condition;
bool ready;
};
struct ThreadProcessInfo {
......@@ -113,9 +114,10 @@ public:
#ifndef CONFIG_IPC_SINGLE
sptr<IRemoteObject> GetSAMgrObject();
bool ProxyDetachDBinderSession(uint32_t handle);
std::shared_ptr<DBinderSessionObject> ProxyDetachDBinderSession(uint32_t handle, IPCObjectProxy *proxy);
bool ProxyAttachDBinderSession(uint32_t handle, std::shared_ptr<DBinderSessionObject> object);
std::shared_ptr<DBinderSessionObject> ProxyQueryDBinderSession(uint32_t handle);
bool ProxyMoveDBinderSession(uint32_t handle, IPCObjectProxy *proxy);
bool QueryProxyBySessionHandle(uint32_t handle, std::vector<uint32_t> &proxyHandle);
std::shared_ptr<DBinderSessionObject> QuerySessionByInfo(const std::string &name, const std::string &deviceId);
......@@ -134,47 +136,28 @@ public:
void WakeUpSocketIOThread(const std::thread::id &threadID);
void WakeUpThreadBySeqNumber(uint64_t seqNumber, uint32_t handle);
IRemoteObject *QueryStubByIndex(uint64_t stubIndex);
uint64_t QueryStubIndex(IRemoteObject *stubObject);
uint64_t AddStubByIndex(IRemoteObject *stubObject);
uint64_t EraseStubIndex(IRemoteObject *stubObject);
uint64_t GetSeqNumber();
uint32_t GetDBinderIdleHandle(uint64_t stubIndex);
std::shared_ptr<SocketThreadLockInfo> GetListenThreadLockInfo();
uint32_t GetDBinderIdleHandle(std::shared_ptr<DBinderSessionObject> session);
std::string GetLocalDeviceID();
bool AttachCallbackStub(IPCObjectProxy *ipcProxy, sptr<IPCObjectStub> callbackStub);
bool DetachCallbackStub(IPCObjectStub *callbackStub);
sptr<IPCObjectStub> QueryCallbackStub(IPCObjectProxy *ipcProxy);
IPCObjectProxy *QueryCallbackProxy(IPCObjectStub *callbackStub);
bool DetachCallbackStubByProxy(IPCObjectProxy *ipcProxy);
sptr<IPCObjectProxy> QueryCallbackProxy(IPCObjectStub *callbackStub);
sptr<IPCObjectStub> DetachCallbackStub(IPCObjectProxy *ipcProxy);
uint32_t QueryHandleByDatabusSession(const std::string &name, const std::string &deviceId, uint64_t stubIndex);
bool StubDetachDBinderSession(uint32_t handle);
bool StubDetachDBinderSession(uint32_t handle, uint32_t &tokenId);
std::shared_ptr<DBinderSessionObject> StubQueryDBinderSession(uint32_t handle);
bool StubAttachDBinderSession(uint32_t handle, std::shared_ptr<DBinderSessionObject> object);
std::string GetDatabusName();
bool CreateSoftbusServer(const std::string &name);
bool DetachHandleToIndex(uint32_t handle);
bool AttachHandleToIndex(uint32_t handle, uint64_t stubIndex);
uint64_t QueryHandleToIndex(uint32_t handle);
uint64_t QueryHandleToIndex(std::list<uint32_t> &handleList, uint32_t &handle);
bool AttachStubRecvRefInfo(IRemoteObject *stub, int pid, const std::string &deviceId);
void DetachStubRecvRefInfo(int pid, const std::string &deviceId);
bool DetachStubRecvRefInfo(const IRemoteObject *stub, int pid, const std::string &deviceId);
void DetachStubRecvRefInfo(const IRemoteObject *stub);
std::list<IRemoteObject *> QueryStubRecvRefInfo(int pid, const std::string &deviceId);
void DetachStubRefInfo(const int pid, const std::string &deviceId);
void DetachStubRefInfo(IRemoteObject *stub, int pid, const std::string &deviceId);
bool AttachStubSendRefInfo(IRemoteObject *stub, int pid, const std::string &deviceId);
void DetachStubSendRefInfo(int pid, const std::string &deviceId);
void DetachStubSendRefInfo(IRemoteObject *stub, int pid, const std::string &deviceId);
void DetachStubSendRefInfo(IRemoteObject *stub);
bool IncStubRefTimes(IRemoteObject *stub);
bool DecStubRefTimes(IRemoteObject *stub);
bool DetachStubRefTimes(IRemoteObject *stub);
bool AttachCommAuthInfo(IRemoteObject *stub, int pid, int uid, const std::string &deviceId,
std::shared_ptr<FeatureSetData> featureSet);
void DetachCommAuthInfo(IRemoteObject *stub, int pid, int uid, const std::string &deviceId);
bool AttachCommAuthInfo(IRemoteObject *stub, int pid, int uid, uint32_t tokenId, const std::string &deviceId);
bool DetachCommAuthInfo(IRemoteObject *stub, int pid, int uid, uint32_t tokenId, const std::string &deviceId);
void DetachCommAuthInfoByStub(IRemoteObject *stub);
std::shared_ptr<FeatureSetData> QueryIsAuth(int pid, int uid, const std::string &deviceId);
bool QueryCommAuthInfo(int pid, int uid, uint32_t &tokenId, const std::string &deviceId);
bool AddDataThreadToIdle(const std::thread::id &threadId);
bool DeleteDataThreadFromIdle(const std::thread::id &threadId);
std::thread::id GetIdleDataThread();
......@@ -182,16 +165,24 @@ public:
std::shared_ptr<ThreadProcessInfo> PopDataInfoFromThread(const std::thread::id &threadId);
void WakeUpDataThread(const std::thread::id &threadID);
void AddDataThreadInWait(const std::thread::id &threadId);
bool IsSameRemoteObject(IRemoteObject *stub, int pid, int uid, const std::string &deviceId,
bool IsSameRemoteObject(IRemoteObject *stub, int pid, int uid, uint32_t tokenId, const std::string &deviceId,
const std::shared_ptr<CommAuthInfo> &auth);
bool IsSameRemoteObject(int pid, int uid, const std::string &deviceId, const std::shared_ptr<CommAuthInfo> &auth);
uint64_t EraseStubIndex(IRemoteObject *stubObject);
bool DetachAppInfoToStubIndex(uint32_t pid, uint32_t uid, const std::string &deviceId, uint64_t stubIndex);
bool DetachAppInfoToStubIndex(uint32_t pid, uint32_t uid, uint32_t tokenId, const std::string &deviceId,
uint64_t stubIndex, uint32_t listenFd);
std::list<uint64_t> DetachAppInfoToStubIndex(uint32_t pid, uint32_t uid, uint32_t tokenId,
const std::string &deviceId, uint32_t listenFd);
void DetachAppInfoToStubIndex(uint64_t stubIndex);
bool AttachAppInfoToStubIndex(uint32_t pid, uint32_t uid, const std::string &deviceId, uint64_t stubIndex);
bool QueryAppInfoToStubIndex(uint32_t pid, uint32_t uid, const std::string &deviceId, uint64_t stubIndex);
bool AttachAppInfoToStubIndex(uint32_t pid, uint32_t uid, uint32_t tokenId, const std::string &deviceId,
uint64_t stubIndex, uint32_t listenFd);
bool AttachAppInfoToStubIndex(uint32_t pid, uint32_t uid, uint32_t tokenId, const std::string &deviceId,
uint32_t listenFd);
bool QueryAppInfoToStubIndex(uint32_t pid, uint32_t uid, uint32_t tokenId, const std::string &deviceId,
uint64_t stubIndex, uint32_t listenFd);
std::string UIntToString(uint32_t input);
bool AttachDBinderCallbackStub(sptr<IRemoteObject> rpcProxy, sptr<DBinderCallbackStub> stub);
bool DetachDBinderCallbackStubByProxy(sptr<IRemoteObject> rpcProxy);
void DetachDBinderCallbackStub(DBinderCallbackStub *stub);
sptr<DBinderCallbackStub> QueryDBinderCallbackStub(sptr<IRemoteObject> rpcProxy);
sptr<IRemoteObject> QueryDBinderCallbackProxy(sptr<IRemoteObject> stub);
#endif
......@@ -200,11 +191,6 @@ public:
static constexpr int DEFAULT_WORK_THREAD_NUM = 16;
static constexpr uint32_t DBINDER_HANDLE_BASE = 100000;
static constexpr uint32_t DBINDER_HANDLE_RANG = 100;
#ifndef CONFIG_IPC_SINGLE
std::shared_ptr<SocketThreadLockInfo> listenThreadReady_ = nullptr;
static constexpr int TRANS_TIME_INIT_VALUE = 1;
static constexpr int SEC_TO_MS = 1000;
#endif
static constexpr int ENCRYPT_LENGTH = 4;
private:
DISALLOW_COPY_AND_MOVE(IPCProcessSkeleton);
......@@ -223,8 +209,6 @@ private:
std::mutex databusProcMutex_;
std::mutex sessionNameMutex_;
std::mutex seqNumberMutex_;
std::mutex transTimesMutex_;
std::mutex stubSendRefMutex_;
std::mutex idleDataMutex_;
std::mutex dataQueueMutex_;
std::mutex findThreadMutex_;
......@@ -232,11 +216,9 @@ private:
std::recursive_mutex proxyToSessionMutex_;
std::shared_mutex databusSessionMutex_;
std::shared_mutex handleToIndexMutex_;
std::shared_mutex threadLockMutex_;
std::shared_mutex callbackStubMutex_;
std::shared_mutex stubObjectsMutex_;
std::shared_mutex stubRecvRefMutex_;
std::shared_mutex appInfoToIndexMutex_;
std::shared_mutex commAuthMutex_;
std::shared_mutex dbinderSentMutex_;
......@@ -246,16 +228,12 @@ private:
std::map<std::thread::id, std::shared_ptr<SocketThreadLockInfo>> threadLockInfo_;
std::map<uint32_t, std::shared_ptr<DBinderSessionObject>> proxyToSession_;
std::map<uint32_t, std::shared_ptr<DBinderSessionObject>> dbinderSessionObjects_;
std::map<uint32_t, uint64_t> handleToStubIndex_;
std::map<IPCObjectProxy *, sptr<IPCObjectStub>> noticeStub_;
std::map<IRemoteObject *, uint32_t> transTimes_;
std::map<std::thread::id, std::vector<std::shared_ptr<ThreadProcessInfo>>> dataInfoQueue_; // key is threadId
std::map<std::string, std::map<uint64_t, bool>> appInfoToStubIndex_;
std::map<sptr<IRemoteObject>, sptr<DBinderCallbackStub>> dbinderSentCallback;
std::map<std::string, std::map<uint64_t, uint32_t>> appInfoToStubIndex_;
std::map<sptr<IRemoteObject>, wptr<DBinderCallbackStub>> dbinderSentCallback;
std::list<std::thread::id> idleDataThreads_;
std::list<std::shared_ptr<StubRefCountObject>> stubRecvRefs_;
std::list<std::shared_ptr<StubRefCountObject>> stubSendRefs_;
std::list<std::shared_ptr<CommAuthInfo>> commAuth_;
uint32_t dBinderHandle_ = DBINDER_HANDLE_BASE; /* dbinder handle start at 100000 */
......
......@@ -16,6 +16,8 @@
#include "buffer_object.h"
#include "securec.h"
#include "sys_binder.h"
#include "ipc_debug.h"
#include "log_tags.h"
namespace OHOS {
BufferObject::BufferObject()
......@@ -35,15 +37,19 @@ BufferObject::~BufferObject()
}
/* update buffer need get mutex first */
void BufferObject::UpdateSendBuffer()
void BufferObject::UpdateSendBuffer(uint32_t userDataSize)
{
if (sendBufferCursorW_ <= sendBufferCursorR_) {
sendBufferCursorW_ = 0;
sendBufferCursorR_ = 0;
return;
}
/* buffer is not enough, means need expand buffer */
if (sendBuffSize_ - sendBufferCursorW_ <= userDataSize) {
ExpandSendBuffer(sendBuffSize_ + sendBuffSize_);
}
/* check whether buffer size is enough, if not, move write/read cursor to head */
if (sendBuffSize_ - static_cast<uint32_t>(sendBufferCursorW_) < SOCKET_BUFF_RESERVED_SIZE) {
if (sendBuffSize_ - sendBufferCursorW_ < SOCKET_BUFF_RESERVED_SIZE) {
/* writeCursor always bigger than readCursor */
if (sendBufferCursorW_ - sendBufferCursorR_ < sendBufferCursorR_) {
auto memcpyResult = memmove_s(sendBuffer_, sendBufferCursorW_ - sendBufferCursorR_,
......@@ -67,7 +73,7 @@ void BufferObject::UpdateReceiveBuffer()
return;
}
/* check whether buffer size is enough, if not, move write/read cursor to head */
if (recvBuffSize_ - static_cast<uint32_t>(recvBufferCursorW_) < SOCKET_BUFF_RESERVED_SIZE) {
if (recvBuffSize_ - recvBufferCursorW_ < SOCKET_BUFF_RESERVED_SIZE) {
/* writeCursor always bigger than readCursor */
if (recvBufferCursorW_ - recvBufferCursorR_ < recvBufferCursorR_) {
auto memcpyResult = memmove_s(receiveBuffer_, recvBufferCursorW_ - recvBufferCursorR_,
......@@ -89,29 +95,41 @@ char *BufferObject::GetSendBufferAndLock(uint32_t size)
return nullptr;
}
sendMutex_.lock();
if (!ExpandSendBuffer(size)) {
sendMutex_.unlock();
return nullptr;
}
/* attention: need unlock mutex by caller */
return sendBuffer_;
}
/* this function should be call in mutex locked */
bool BufferObject::ExpandSendBuffer(uint32_t size)
{
uint32_t needSize = GetNeedBufferSize(size);
if (needSize == 0) {
return true;
}
if (needSize > sendBuffSize_) {
char *newBuffer = new (std::nothrow) char[needSize];
if (newBuffer == nullptr) {
sendMutex_.unlock();
return nullptr;
char *newBuffer_ = new (std::nothrow) char[needSize];
if (newBuffer_ == nullptr) {
return false;
}
if ((sendBuffer_ != nullptr) && (sendBuffSize_ != 0)) {
int memcpyResult = memcpy_s(newBuffer, needSize, sendBuffer_, sendBuffSize_);
int memcpyResult = memcpy_s(newBuffer_, needSize, sendBuffer_, sendBuffSize_);
if (memcpyResult != 0) {
delete[] newBuffer;
sendMutex_.unlock();
return nullptr;
delete[] newBuffer_;
return false;
}
}
delete[] sendBuffer_;
sendBuffer_ = newBuffer;
sendBuffer_ = newBuffer_;
sendBuffSize_ = needSize;
}
/* attention: need unlock mutex by caller */
return sendBuffer_;
return true;
}
char *BufferObject::GetReceiveBufferAndLock(uint32_t size)
......@@ -122,23 +140,23 @@ char *BufferObject::GetReceiveBufferAndLock(uint32_t size)
}
recvMutex_.lock();
if (needSize > recvBuffSize_) {
char *newBuffer = new (std::nothrow) char[needSize];
if (newBuffer == nullptr) {
char *newBuffer_ = new (std::nothrow) char[needSize];
if (newBuffer_ == nullptr) {
recvMutex_.unlock();
return nullptr;
}
if ((receiveBuffer_ != nullptr) && (recvBuffSize_ != 0)) {
int memcpyResult = memcpy_s(newBuffer, needSize, receiveBuffer_, recvBuffSize_);
int memcpyResult = memcpy_s(newBuffer_, needSize, receiveBuffer_, recvBuffSize_);
if (memcpyResult != 0) {
delete[] newBuffer;
delete[] newBuffer_;
recvMutex_.unlock();
return nullptr;
}
}
delete[] receiveBuffer_;
receiveBuffer_ = newBuffer;
receiveBuffer_ = newBuffer_;
recvBuffSize_ = needSize;
}
......
......@@ -16,34 +16,37 @@
#include "comm_auth_info.h"
namespace OHOS {
CommAuthInfo::CommAuthInfo(IRemoteObject *stub, int pid, int uid,
const std::string &deviceId, std::shared_ptr<FeatureSetData> featureSet)
: stub_(stub), remotePid_(pid), remoteUid_(uid), deviceId_(deviceId), featureSet_(featureSet)
CommAuthInfo::CommAuthInfo(IRemoteObject *stub, int pid, int uid, uint32_t tokenId, const std::string &deviceId)
: stub_(stub), remotePid_(pid), remoteUid_(uid), tokenId_(tokenId), deviceId_(deviceId)
{}
CommAuthInfo::~CommAuthInfo()
{
stub_ = nullptr;
}
const IRemoteObject *CommAuthInfo::GetStubObject() const
IRemoteObject *CommAuthInfo::GetStubObject() const
{
return stub_;
}
int CommAuthInfo::GetRemotePid() const
{
return remotePid_;
}
int CommAuthInfo::GetRemoteUid() const
{
return remoteUid_;
}
std::string CommAuthInfo::GetRemoteDeviceId() const
uint32_t CommAuthInfo::GetRemoteTokenId() const
{
return deviceId_;
return tokenId_;
}
std::shared_ptr<FeatureSetData> CommAuthInfo::GetFeatureSet() const
std::string CommAuthInfo::GetRemoteDeviceId() const
{
return featureSet_;
return deviceId_;
}
} // namespace OHOS
......@@ -24,6 +24,10 @@
namespace OHOS {
int DatabusSessionCallback::OnSessionOpened(std::shared_ptr<Session> session)
{
if (session == nullptr) {
ZLOGE(LOG_LABEL, "OnSessionOpened session is nullptr");
return ERR_INVALID_DATA;
}
if (session->GetChannelId() < 0) {
ZLOGE(LOG_LABEL, "fail to open session because of wrong channel ID");
return SESSION_WRONG_FD_ERR;
......@@ -55,6 +59,7 @@ void DatabusSessionCallback::OnSessionClosed(std::shared_ptr<Session> session)
}
invoker->OnDatabusSessionClosed(session);
ZLOGI(LOG_LABEL, "end, channelId: %{public}" PRIu64, session->GetChannelId());
}
void DatabusSessionCallback::OnBytesReceived(std::shared_ptr<Session> session, const char *data, ssize_t len)
......
......@@ -30,14 +30,14 @@ namespace OHOS {
static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_ID_RPC, "DBinderCallbackStub" };
DBinderCallbackStub::DBinderCallbackStub(const std::string &service, const std::string &device,
const std::string &localDevice, uint64_t stubIndex, uint32_t handle, std::shared_ptr<FeatureSetData> feature)
const std::string &localDevice, uint64_t stubIndex, uint32_t handle, uint32_t tokenId)
: IPCObjectStub(Str8ToStr16("DBinderCallback" + device + service)),
serviceName_(service),
deviceID_(device),
localDeviceID_(localDevice),
stubIndex_(stubIndex),
handle_(handle),
rpcFeatureSet_(feature)
tokenId_(tokenId)
{
ZLOGI(LOG_LABEL, "serviceName:%{public}s, deviceId:%{public}s, handle:%{public}u, stubIndex_:%{public}" PRIu64 "",
serviceName_.c_str(), deviceID_.c_str(), handle_, stubIndex_);
......@@ -46,6 +46,7 @@ DBinderCallbackStub::DBinderCallbackStub(const std::string &service, const std::
DBinderCallbackStub::~DBinderCallbackStub()
{
ZLOGI(LOG_LABEL, "DBinderCallbackStub delete");
IPCProcessSkeleton::GetCurrent()->DetachDBinderCallbackStub(this);
}
const std::string &DBinderCallbackStub::GetServiceName()
......@@ -63,9 +64,9 @@ uint64_t DBinderCallbackStub::GetStubIndex() const
return stubIndex_;
}
std::shared_ptr<FeatureSetData> DBinderCallbackStub::GetFeatureSet() const
uint32_t DBinderCallbackStub::GetTokenId() const
{
return rpcFeatureSet_;
return tokenId_;
}
int32_t DBinderCallbackStub::ProcessProto(uint32_t code, MessageParcel &data, MessageParcel &reply,
......@@ -83,7 +84,7 @@ int32_t DBinderCallbackStub::ProcessProto(uint32_t code, MessageParcel &data, Me
return DBINDER_CALLBACK_READ_OBJECT_ERR;
}
IPCObjectProxy *samgr = reinterpret_cast<IPCObjectProxy *>(object.GetRefPtr());
std::string sessionName = samgr->TransDataBusName(uid, pid);
std::string sessionName = samgr->GetSessionNameForPidUid(uid, pid);
if (sessionName.empty()) {
ZLOGE(LOG_LABEL, "grans session name failed");
return DBINDER_SERVICE_WRONG_SESSION;
......@@ -91,9 +92,8 @@ int32_t DBinderCallbackStub::ProcessProto(uint32_t code, MessageParcel &data, Me
MessageParcel authData, authReply;
MessageOption authOption;
uint32_t featureSet = rpcFeatureSet_->featureSet;
if (!authData.WriteUint32(pid) || !authData.WriteUint32(uid) || !authData.WriteString(localDeviceID_) ||
!authData.WriteUint32(featureSet) || !authData.WriteUint64(stubIndex_)) {
!authData.WriteUint64(stubIndex_) || !authData.WriteUint32(tokenId_)) {
ZLOGE(LOG_LABEL, "write to MessageParcel fail");
return ERR_INVALID_DATA;
}
......@@ -102,18 +102,20 @@ int32_t DBinderCallbackStub::ProcessProto(uint32_t code, MessageParcel &data, Me
ZLOGE(LOG_LABEL, "no databus thread and invoker");
return RPC_DATABUS_INVOKER_ERR;
}
int err = dbinderInvoker->SendRequest(handle_, DBINDER_TRANS_COMMAUTH, authData, authReply, authOption);
int err = dbinderInvoker->SendRequest(handle_, DBINDER_ADD_COMMAUTH, authData, authReply, authOption);
if (err != ERR_NONE) {
ZLOGE(LOG_LABEL, "send auth info to remote fail");
return BINDER_CALLBACK_AUTHCOMM_ERR;
}
ZLOGI(LOG_LABEL, "send to stub ok!stubIndex:%{public}" PRIu64 ", \
peerDevice = %{public}s, localDeviceID_ = %{public}s," \
"serviceName_ = %{public}s, uid:%{public}d, pid:%{public}d, sessionName = %{public}s",\
stubIndex_, deviceID_.c_str(), localDeviceID_.c_str(), serviceName_.c_str(), uid, pid, sessionName.c_str());
ZLOGI(LOG_LABEL, "send to stub ok! stubIndex:%{public}" PRIu64 ", peerDevice = %{public}s, "
"localDeviceID_ = %{public}s, serviceName_ = %{public}s, uid:%{public}d, pid:%{public}d, "
"tokenId: %{public}u, sessionName = %{public}s",
stubIndex_, IPCProcessSkeleton::ConvertToSecureString(deviceID_).c_str(),
IPCProcessSkeleton::ConvertToSecureString(localDeviceID_).c_str(), serviceName_.c_str(), uid, pid, tokenId_,
sessionName.c_str());
if (!reply.WriteUint32(IRemoteObject::IF_PROT_DATABUS) || !reply.WriteUint64(stubIndex_) ||
!reply.WriteString(serviceName_) || !reply.WriteString(deviceID_) || !reply.WriteString(localDeviceID_) ||
!reply.WriteString(sessionName)) {
!reply.WriteString(sessionName) || !reply.WriteUint32(tokenId_)) {
ZLOGE(LOG_LABEL, "write to parcel fail");
return ERR_INVALID_DATA;
}
......
......@@ -14,6 +14,7 @@
*/
#include "dbinder_session_object.h"
#include "ipc_process_skeleton.h"
#include "ISessionService.h"
#include "ipc_debug.h"
......@@ -23,8 +24,9 @@ namespace OHOS {
static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_ID_RPC, "dbinder_session_object" };
DBinderSessionObject::DBinderSessionObject(std::shared_ptr<Session> session, const std::string &serviceName,
const std::string &serverDeviceId)
: session_(session), serviceName_(serviceName), serverDeviceId_(serverDeviceId)
const std::string &serverDeviceId, uint64_t stubIndex, IPCObjectProxy *proxy, uint32_t tokenId)
: session_(session), serviceName_(serviceName), serverDeviceId_(serverDeviceId),
stubIndex_(stubIndex), proxy_(proxy), tokenId_(tokenId)
{}
DBinderSessionObject::~DBinderSessionObject()
......@@ -80,19 +82,24 @@ void DBinderSessionObject::SetDeviceId(const std::string &serverDeviceId)
serverDeviceId_ = serverDeviceId;
}
void DBinderSessionObject::SetFeatureSet(std::shared_ptr<FeatureSetData> rpcFeatureSet)
std::string DBinderSessionObject::GetDeviceId() const
{
rpcFeatureSet_ = rpcFeatureSet;
return serverDeviceId_;
}
std::string DBinderSessionObject::GetDeviceId() const
void DBinderSessionObject::SetProxy(IPCObjectProxy *proxy)
{
return serverDeviceId_;
proxy_ = proxy;
}
std::shared_ptr<FeatureSetData> DBinderSessionObject::GetFeatureSet() const
IPCObjectProxy *DBinderSessionObject::GetProxy() const
{
return rpcFeatureSet_;
return proxy_;
}
uint64_t DBinderSessionObject::GetStubIndex() const
{
return stubIndex_;
}
uint32_t DBinderSessionObject::GetFlatSessionLen()
......@@ -107,4 +114,9 @@ uint32_t DBinderSessionObject::GetSessionHandle() const
}
return 0;
}
uint32_t DBinderSessionObject::GetTokenId() const
{
return tokenId_;
}
} // namespace OHOS
......@@ -43,7 +43,6 @@
#ifndef CONFIG_IPC_SINGLE
#include "access_token_adapter.h"
#include "dbinder_databus_invoker.h"
#include "rpc_feature_set.h"
#endif
namespace OHOS {
......@@ -134,7 +133,7 @@ std::u16string IPCObjectProxy::GetInterfaceDescriptor()
MessageParcel data, reply;
MessageOption option;
int32_t err = SendRequestInner(false, INTERFACE_TRANSACTION, data, reply, option);
int err = SendRequestInner(false, INTERFACE_TRANSACTION, data, reply, option);
if (err != ERR_NONE) {
ZLOGE(LABEL, "send INTERFACE_TRANSACTION cmd failed, error: %{public}d", err);
return std::u16string();
......@@ -144,29 +143,27 @@ std::u16string IPCObjectProxy::GetInterfaceDescriptor()
return remoteDescriptor_;
}
std::string IPCObjectProxy::GetPidAndUidInfo(int32_t systemAbilityId)
std::string IPCObjectProxy::GetSessionName()
{
MessageParcel data, reply;
MessageOption option;
data.WriteInt32(systemAbilityId);
int32_t err = SendRequestInner(false, GET_UIDPID_INFO, data, reply, option);
int err = SendRequestInner(false, GET_SESSION_NAME, data, reply, option);
if (err != ERR_NONE) {
ZLOGE(LABEL, "GetPidAndUidInfo SendRequestInner return error = %{public}d", err);
ZLOGE(LABEL, "send GET_SESSION_NAME failed, error: %{public}d", err);
return std::string("");
}
return reply.ReadString();
}
std::string IPCObjectProxy::GetDataBusName(int32_t systemAbilityId)
std::string IPCObjectProxy::GetGrantedSessionName()
{
MessageParcel data, reply;
MessageOption option;
data.WriteInt32(systemAbilityId);
int32_t err = SendRequestInner(false, GRANT_DATABUS_NAME, data, reply, option);
int err = SendRequestInner(false, GET_GRANTED_SESSION_NAME, data, reply, option);
if (err != ERR_NONE) {
ZLOGE(LABEL, "GetDataBusName transact return error = %{public}d", err);
ZLOGE(LABEL, "send GET_GRANTED_SESSION_NAME failed, error: %{public}d", err);
return std::string("");
}
......@@ -178,7 +175,7 @@ std::string IPCObjectProxy::GetDataBusName(int32_t systemAbilityId)
return reply.ReadString();
}
std::string IPCObjectProxy::TransDataBusName(uint32_t uid, uint32_t pid)
std::string IPCObjectProxy::GetSessionNameForPidUid(uint32_t uid, uint32_t pid)
{
if (pid == static_cast<uint32_t>(getpid())) {
ZLOGE(LABEL, "TransDataBusName can't write local pid. my/remotePid = %{public}u/%{public}u", getpid(), pid);
......@@ -191,7 +188,7 @@ std::string IPCObjectProxy::TransDataBusName(uint32_t uid, uint32_t pid)
ZLOGE(LABEL, "TransDataBusName write pid/uid = %{public}u/%{public}u failed", pid, uid);
return std::string("");
}
int32_t err = SendRequestInner(false, TRANS_DATABUS_NAME, data, reply, option);
int err = SendRequestInner(false, GET_SESSION_NAME_PID_UID, data, reply, option);
if (err != ERR_NONE) {
ZLOGE(LABEL, "TransDataBusName transact return error = %{public}d", err);
return std::string("");
......@@ -205,6 +202,14 @@ std::string IPCObjectProxy::TransDataBusName(uint32_t uid, uint32_t pid)
return reply.ReadString();
}
int IPCObjectProxy::GetPidUid(MessageParcel &reply)
{
MessageParcel data;
MessageOption option;
return SendRequestInner(true, GET_PID_UID, data, reply, option);
}
void IPCObjectProxy::OnFirstStrongRef(const void *objectId)
{
// IPC proxy: AcquireHandle->AttachObject
......@@ -228,8 +233,18 @@ void IPCObjectProxy::WaitForInit()
isFinishInit_ = false;
}
if (isFinishInit_) {
if (!isFinishInit_) {
#ifndef CONFIG_IPC_SINGLE
if (UpdateProto() == IRemoteObject::IF_PROT_ERROR) {
ZLOGE(LABEL, "UpdateProto get IF_PROT_ERROR");
isRemoteDead_ = true;
}
#endif
isFinishInit_ = true;
} else {
#ifndef CONFIG_IPC_SINGLE
// Anoymous rpc proxy need to update proto anyway because ownership of session
// corresponding to this handle has been marked as null in TranslateRemoteHandleType
if (proto_ == IRemoteObject::IF_PROT_DATABUS) {
if (!CheckHaveSession()) {
SetProto(IRemoteObject::IF_PROT_ERROR);
......@@ -237,20 +252,12 @@ void IPCObjectProxy::WaitForInit()
}
}
#endif
return;
}
#ifndef CONFIG_IPC_SINGLE
if (UpdateProto() == IRemoteObject::IF_PROT_ERROR) {
ZLOGE(LABEL, "UpdateProto get IF_PROT_ERROR");
isRemoteDead_ = true;
}
#endif
isFinishInit_ = true;
}
#ifndef CONFIG_IPC_SINGLE
if (proto_ == IRemoteObject::IF_PROT_DATABUS) {
int32_t errcode = IncRefToRemote();
if (errcode != ERR_NONE) {
if (IncRefToRemote() != ERR_NONE) {
SetProto(IRemoteObject::IF_PROT_ERROR);
isRemoteDead_ = true;
}
......@@ -269,10 +276,6 @@ void IPCObjectProxy::OnLastStrongRef(const void *objectId)
}
#ifndef CONFIG_IPC_SINGLE
ReleaseProto();
std::shared_ptr<DBinderSessionObject> session = nullptr;
session = current->ProxyQueryDBinderSession(handle_);
(void)current->ProxyDetachDBinderSession(handle_);
(void)current->DetachHandleToIndex(handle_);
#endif
ClearDeathRecipients();
// This proxy is going to be destroyed, so we need to decrease refcount of binder_ref.
......@@ -367,7 +370,7 @@ bool IPCObjectProxy::RemoveDeathRecipient(const sptr<DeathRecipient> &recipient)
bool dbinderStatus = true;
bool status = invoker->RemoveDeathRecipient(handle_, this);
#ifndef CONFIG_IPC_SINGLE
if (proto_ == IRemoteObject::IF_PROT_DATABUS) {
if (proto_ == IRemoteObject::IF_PROT_DATABUS || proto_ == IRemoteObject::IF_PROT_ERROR) {
dbinderStatus = RemoveDbinderDeathRecipient();
}
#endif
......@@ -378,6 +381,13 @@ bool IPCObjectProxy::RemoveDeathRecipient(const sptr<DeathRecipient> &recipient)
void IPCObjectProxy::SendObituary()
{
#ifndef CONFIG_IPC_SINGLE
if (handle_ < IPCProcessSkeleton::DBINDER_HANDLE_BASE) {
if (proto_ == IRemoteObject::IF_PROT_DATABUS || proto_ == IRemoteObject::IF_PROT_ERROR) {
RemoveDbinderDeathRecipient();
}
}
#endif
std::vector<sptr<DeathRecipient>> toBeReport;
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
......@@ -402,17 +412,6 @@ void IPCObjectProxy::SendObituary()
recipient->OnRemoteDied(this);
}
}
#ifndef CONFIG_IPC_SINGLE
if (proto_ == IRemoteObject::IF_PROT_DATABUS) {
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: get current fail", __func__);
return;
}
current->DetachCallbackStubByProxy(this);
}
#endif
}
void IPCObjectProxy::ClearDeathRecipients()
......@@ -445,7 +444,7 @@ int32_t IPCObjectProxy::NoticeServiceDie()
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
MessageOption option(MessageOption::TF_ASYNC);
data.WriteInt32(IRemoteObject::DeathRecipient::NOTICE_DEATH_RECIPIENT);
int status = SendLocalRequest(DBINDER_OBITUARY_TRANSACTION, data, reply, option);
......@@ -465,9 +464,9 @@ int IPCObjectProxy::InvokeListenThread(MessageParcel &data, MessageParcel &reply
#ifndef CONFIG_IPC_SINGLE
int IPCObjectProxy::UpdateProto()
{
int type = GetSessionFromDBinderService();
SetProto(type);
return type;
int proto = GetProtoInfo();
SetProto(proto);
return proto;
}
int32_t IPCObjectProxy::IncRefToRemote()
......@@ -486,7 +485,21 @@ int32_t IPCObjectProxy::IncRefToRemote()
void IPCObjectProxy::ReleaseProto()
{
ReleaseDatabusProto();
switch (GetProto()) {
case IRemoteObject::IF_PROT_BINDER: {
ReleaseBinderProto();
break;
}
case IRemoteObject::IF_PROT_DATABUS:
case IRemoteObject::IF_PROT_ERROR: {
ReleaseDatabusProto();
break;
}
default: {
ZLOGE(LABEL, "release invalid proto %{public}d", proto_);
break;
}
}
}
void IPCObjectProxy::SetProto(int proto)
......@@ -494,13 +507,9 @@ void IPCObjectProxy::SetProto(int proto)
proto_ = proto;
}
int IPCObjectProxy::GetSessionFromDBinderService()
int IPCObjectProxy::GetProtoInfo()
{
MessageParcel data, reply;
MessageOption option;
if (CheckHaveSession()) {
ZLOGE(LABEL, "GetSessionFromDBinderService CheckHaveSession success");
return IRemoteObject::IF_PROT_DATABUS;
}
if (handle_ >= IPCProcessSkeleton::DBINDER_HANDLE_BASE) {
......@@ -508,9 +517,11 @@ int IPCObjectProxy::GetSessionFromDBinderService()
return IRemoteObject::IF_PROT_ERROR;
}
int32_t err = SendRequestInner(true, GET_PROTO_INFO, data, reply, option);
MessageParcel data, reply;
MessageOption option;
int err = SendRequestInner(true, GET_PROTO_INFO, data, reply, option);
if (err != ERR_NONE) {
ZLOGE(LABEL, "GET_PROTO_INFO transact return error = %{public}d", err);
ZLOGW(LABEL, "GET_PROTO_INFO transact return error = %{public}d", err);
return IRemoteObject::IF_PROT_ERROR;
}
......@@ -529,7 +540,7 @@ int IPCObjectProxy::GetSessionFromDBinderService()
break;
}
default: {
ZLOGE(LABEL, "GetSessionFromDBinderService Invalid Type");
ZLOGE(LABEL, "get Invalid proto");
return IRemoteObject::IF_PROT_ERROR;
break;
}
......@@ -542,22 +553,23 @@ bool IPCObjectProxy::AddDbinderDeathRecipient()
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: get current fail", __func__);
ZLOGE(LABEL, "%{public}s: get current fail", __func__);
return false;
}
if (current->QueryCallbackStub(this) != nullptr) {
ZLOGW(LABEL, "%s: already attach callback stub", __func__);
ZLOGW(LABEL, "%{public}s: already attach callback stub", __func__);
return true;
}
sptr<IPCObjectStub> callbackStub = new (std::nothrow) IPCObjectStub(descriptor_);
//note that cannot use this proxy's descriptor
sptr<IPCObjectStub> callbackStub = new (std::nothrow) IPCObjectStub(u"DbinderDeathRecipient" + descriptor_);
if (callbackStub == nullptr) {
ZLOGE(LABEL, "create IPCObjectStub object failed");
return false;
}
if (!current->AttachCallbackStub(this, callbackStub)) {
ZLOGW(LABEL, "%s: already attach new callback stub", __func__);
ZLOGW(LABEL, "%{public}s: already attach new callback stub", __func__);
return false;
}
......@@ -566,12 +578,11 @@ bool IPCObjectProxy::AddDbinderDeathRecipient()
MessageOption option(MessageOption::TF_SYNC);
data.WriteInt32(IRemoteObject::DeathRecipient::ADD_DEATH_RECIPIENT);
data.WriteRemoteObject(callbackStub);
data.WriteString(current->GetDatabusName());
int err = SendLocalRequest(DBINDER_OBITUARY_TRANSACTION, data, reply, option);
if (err != ERR_NONE || reply.ReadInt32() != ERR_NONE) {
ZLOGE(LABEL, "%s: send local request fail, err = %d", __func__, err);
(void)current->DetachCallbackStubByProxy(this);
if (err != ERR_NONE) {
ZLOGE(LABEL, "AddDbinderDeathRecipient fail, err = %{public}d", err);
current->DetachCallbackStub(this);
return false;
}
......@@ -582,13 +593,13 @@ bool IPCObjectProxy::RemoveDbinderDeathRecipient()
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: get current fail", __func__);
ZLOGE(LABEL, "%{public}s: get current fail", __func__);
return false;
}
sptr<IPCObjectStub> callbackStub = current->QueryCallbackStub(this);
sptr<IPCObjectStub> callbackStub = current->DetachCallbackStub(this);
if (callbackStub == nullptr) {
ZLOGE(LABEL, "%s: get callbackStub fail", __func__);
ZLOGE(LABEL, "%{public}s: get callbackStub fail", __func__);
return false;
}
......@@ -599,28 +610,22 @@ bool IPCObjectProxy::RemoveDbinderDeathRecipient()
data.WriteRemoteObject(callbackStub);
int err = SendLocalRequest(DBINDER_OBITUARY_TRANSACTION, data, reply, option);
if (err != ERR_NONE || reply.ReadInt32() != ERR_NONE) {
ZLOGE(LABEL, "%s: send local request fail, err = %d", __func__, err);
if (err != ERR_NONE) {
ZLOGE(LABEL, "%{public}s: send local request fail, err = %{public}d", __func__, err);
// do nothing, even send request failed
}
return current->DetachCallbackStubByProxy(this);
return err == ERR_NONE;
}
bool IPCObjectProxy::CheckHaveSession()
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "IPCProcessSkeleton is null, set type as binder");
return false;
}
std::shared_ptr<DBinderSessionObject> session = current->ProxyQueryDBinderSession(handle_);
if (session == nullptr) {
ZLOGE(LABEL, "IPCProcessSkeleton is null");
return false;
}
return true;
return current->ProxyMoveDBinderSession(handle_, this);
}
bool IPCObjectProxy::UpdateDatabusClientSession(int handle, MessageParcel &reply)
......@@ -628,7 +633,7 @@ bool IPCObjectProxy::UpdateDatabusClientSession(int handle, MessageParcel &reply
DBinderDatabusInvoker *invoker =
reinterpret_cast<DBinderDatabusInvoker *>(IPCThreadSkeleton::GetRemoteInvoker(IRemoteObject::IF_PROT_DATABUS));
if (invoker == nullptr) {
ZLOGE(LABEL, "%s: invoker null", __func__);
ZLOGE(LABEL, "%{public}s: invoker is null", __func__);
return false;
}
......@@ -637,79 +642,70 @@ bool IPCObjectProxy::UpdateDatabusClientSession(int handle, MessageParcel &reply
std::string peerID = reply.ReadString();
std::string localID = reply.ReadString();
std::string localBusName = reply.ReadString();
uint32_t rpcFeatureSet = reply.ReadUint32();
uint32_t tokenId = 0;
if (IsATEnable(rpcFeatureSet) == true) {
tokenId = RpcGetSelfTokenID();
}
std::shared_ptr<FeatureSetData> featureSet = nullptr;
featureSet.reset(reinterpret_cast<FeatureSetData *>(::operator new(sizeof(FeatureSetData))));
if (featureSet == nullptr) {
ZLOGE(LABEL, "%s: featureSet null", __func__);
return false;
}
featureSet->featureSet = rpcFeatureSet;
featureSet->tokenId = tokenId;
uint32_t peerTokenId = reply.ReadUint32();
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s:current process skeleton is nullptr", __func__);
ZLOGE(LABEL, "%{public}s: skeleton is nullptr", __func__);
return false;
}
std::shared_ptr<DBinderSessionObject> connectSession = current->QuerySessionByInfo(serviceName, peerID);
if (connectSession == nullptr) {
connectSession = std::make_shared<DBinderSessionObject>(nullptr, serviceName, peerID);
if (connectSession == nullptr) {
ZLOGE(LABEL, "new server session fail!");
return false;
}
}
connectSession->SetFeatureSet(featureSet);
if (!current->AttachHandleToIndex((uint32_t)handle, stubIndex)) {
ZLOGE(LABEL, "add stub index err stubIndex = %" PRIu64 ", handle = %d", stubIndex, handle);
std::shared_ptr<DBinderSessionObject> dbinderSession = std::make_shared<DBinderSessionObject>(
nullptr, serviceName, peerID, stubIndex, this, peerTokenId);
if (dbinderSession == nullptr) {
ZLOGE(LABEL, "make DBinderSessionObject fail!");
return false;
}
if (!current->CreateSoftbusServer(localBusName)) {
ZLOGE(LABEL, "create bus server fail name = %s, localID = %s", localBusName.c_str(), localID.c_str());
ZLOGE(LABEL, "create softbus server fail, name = %{public}s, localID = %{public}s", localBusName.c_str(),
IPCProcessSkeleton::ConvertToSecureString(localID).c_str());
return false;
}
bool result = invoker->UpdateClientSession(handle, connectSession);
return result;
if (!invoker->UpdateClientSession(dbinderSession)) {
// no need to remove softbus server
ZLOGE(LABEL, "update server session object fail!");
return false;
}
if (!current->ProxyAttachDBinderSession(handle, dbinderSession)) {
// should not get here
ZLOGE(LABEL, "fail to attach session, handle: %{public}d", handle);
if (current->QuerySessionByInfo(serviceName, peerID) == nullptr) {
dbinderSession->CloseDatabusSession();
}
return false;
}
return true;
}
void IPCObjectProxy::ReleaseDatabusProto()
{
if (handle_ == 0) {
ZLOGD(LABEL, "%s:handle == 0, do nothing", __func__);
return;
}
if (proto_ != IRemoteObject::IF_PROT_DATABUS) {
ZLOGW(LABEL, "%{public}s: handle == 0, do nothing", __func__);
return;
}
MessageParcel data, reply;
MessageOption option = { MessageOption::TF_ASYNC };
int32_t err = SendRequestInner(false, DBINDER_DECREFS_TRANSACTION, data, reply, option);
int err = SendRequestInner(false, DBINDER_DECREFS_TRANSACTION, data, reply, option);
if (err != ERR_NONE) {
ZLOGW(LABEL, "DBINDER_DECREFS_TRANSACTION transact return error = %{public}d", err);
// do nothing
ZLOGE(LABEL, "send DBINDER_DECREFS_TRANSACTION cmd failed, error: %{public}d", err);
// do nothing, if this cmd failed, stub's refcount will be decreased when OnSessionClosed called
}
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "release proto current is null");
ZLOGE(LABEL, "release databus proto skeleton is null");
return;
}
std::shared_ptr<DBinderSessionObject> toBeDelete = current->ProxyQueryDBinderSession(handle_);
std::shared_ptr<DBinderSessionObject> toBeDelete = current->ProxyDetachDBinderSession(handle_, this);
if (toBeDelete != nullptr &&
current->QuerySessionByInfo(toBeDelete->GetServiceName(), toBeDelete->GetDeviceId()) != nullptr) {
toBeDelete->CloseDatabusSession();
}
// make sure session corresponding to this sessionName and deviceId is no longer used by other proxy
current->QuerySessionByInfo(toBeDelete->GetServiceName(), toBeDelete->GetDeviceId()) == nullptr) {
// close session in lock
toBeDelete->CloseDatabusSession();
}
}
void IPCObjectProxy::ReleaseBinderProto()
......
......@@ -43,7 +43,6 @@
#include "access_token_adapter.h"
#include "dbinder_databus_invoker.h"
#include "dbinder_error_code.h"
#include "rpc_feature_set.h"
#include "ISessionService.h"
#endif
......@@ -187,7 +186,7 @@ int IPCObjectStub::SendRequest(uint32_t code, MessageParcel &data, MessageParcel
#ifndef CONFIG_IPC_SINGLE
case INVOKE_LISTEN_THREAD: {
if (!IPCSkeleton::IsLocalCalling() || IPCSkeleton::GetCallingUid() >= ALLOWED_UID) {
ZLOGE(LABEL, "%s: INVOKE_LISTEN_THREAD unauthenticated user ", __func__);
ZLOGE(LABEL, "%{public}s: INVOKE_LISTEN_THREAD unauthenticated user ", __func__);
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
......@@ -196,40 +195,73 @@ int IPCObjectStub::SendRequest(uint32_t code, MessageParcel &data, MessageParcel
}
case DBINDER_INCREFS_TRANSACTION: {
if (IPCSkeleton::IsLocalCalling()) {
ZLOGE(LABEL, "%s: cannot be called in same device", __func__);
ZLOGE(LABEL, "dbinder incref in the same device is invalid");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = IncStubRefs(data, reply);
pid_t callerPid = IPCSkeleton::GetCallingPid();
pid_t callerUid = IPCSkeleton::GetCallingUid();
uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
std::string callerDevId = IPCSkeleton::GetCallingDeviceID();
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
uint64_t stubIndex = current->QueryStubIndex(this);
DBinderDatabusInvoker *invoker = reinterpret_cast<DBinderDatabusInvoker *>(
IPCThreadSkeleton::GetRemoteInvoker(IRemoteObject::IF_PROT_DATABUS));
if (invoker == nullptr) {
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
uint32_t listenFd = invoker->GetClientFd();
// update listenFd
ZLOGW(LABEL, "update app info listenFd: %{public}u, stubIndex: %{public}" PRIu64 ", tokenId: %{public}u",
listenFd, stubIndex, tokenId);
current->AttachAppInfoToStubIndex(callerPid, callerUid, tokenId, callerDevId, stubIndex, listenFd);
break;
}
case DBINDER_DECREFS_TRANSACTION: {
if (IPCSkeleton::IsLocalCalling()) {
ZLOGE(LABEL, "%s: cannot be called in same device", __func__);
ZLOGE(LABEL, "dbinder decref in the same device is invalid");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
// stub's refcount will be decreased either in this case or OnSessionClosed callback
// we may race with OnSessionClosed callback, thus dec refcount only when removing appInfo sucessfully
pid_t callerPid = IPCSkeleton::GetCallingPid();
pid_t callerUid = IPCSkeleton::GetCallingUid();
uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
std::string callerDevId = IPCSkeleton::GetCallingDeviceID();
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
uint64_t stubIndex = current->QueryStubIndex(this);
DBinderDatabusInvoker *invoker = reinterpret_cast<DBinderDatabusInvoker *>(
IPCThreadSkeleton::GetRemoteInvoker(IRemoteObject::IF_PROT_DATABUS));
if (invoker == nullptr) {
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = DecStubRefs(data, reply);
uint32_t listenFd = invoker->GetClientFd();
// detach info whose listen fd equals the given one
if (current->DetachAppInfoToStubIndex(callerPid, callerUid, tokenId, callerDevId, stubIndex, listenFd)) {
current->DetachCommAuthInfo(this, callerPid, callerUid, tokenId, callerDevId);
DecStrongRef(this);
}
break;
}
case DBINDER_ADD_COMMAUTH:
case DBINDER_TRANS_COMMAUTH: {
case DBINDER_ADD_COMMAUTH: {
if (IPCSkeleton::IsLocalCalling() || IPCSkeleton::GetCallingUid() >= ALLOWED_UID) {
ZLOGE(LABEL, "%s: DBINDER_ADD_COMMAUTH unauthenticated user ", __func__);
ZLOGE(LABEL, "DBINDER_ADD_COMMAUTH unauthenticated user ");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = AddAuthInfo(data, reply, code);
break;
}
case GET_UIDPID_INFO: {
case GET_SESSION_NAME: {
if (!IPCSkeleton::IsLocalCalling()) {
ZLOGE(LABEL, "GET_UIDPID_INFO message is not from sa manager");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
int32_t systemAbilityId = data.ReadInt32();
std::string sessionName = GetDataBusName(systemAbilityId);
std::string sessionName = GetSessionName();
if (sessionName.empty()) {
ZLOGE(LABEL, "sessionName is empty");
result = IPC_STUB_CREATE_BUS_SERVER_ERR;
......@@ -242,22 +274,32 @@ int IPCObjectStub::SendRequest(uint32_t code, MessageParcel &data, MessageParcel
}
break;
}
case GRANT_DATABUS_NAME: {
if (!IPCSkeleton::IsLocalCalling() || !IsSamgrCall((uint32_t)RpcGetSelfTokenID())) {
case GET_GRANTED_SESSION_NAME: {
if (!IPCSkeleton::IsLocalCalling() ||
!IsSamgrCall(static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID()))) {
ZLOGE(LABEL, "GRANT_DATABUS_NAME message is excluded in sa manager");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = GrantDataBusName(code, data, reply, option);
result = GetGrantedSessionName(code, data, reply, option);
break;
}
case TRANS_DATABUS_NAME: {
if (!IPCSkeleton::IsLocalCalling() || !IsSamgrCall((uint32_t)RpcGetSelfTokenID())) {
case GET_SESSION_NAME_PID_UID: {
if (!IPCSkeleton::IsLocalCalling() ||
!IsSamgrCall(static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID()))) {
ZLOGE(LABEL, "TRANS_DATABUS_NAME message is excluded in sa manager");
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = TransDataBusName(code, data, reply, option);
result = GetSessionNameForPidUid(code, data, reply, option);
break;
}
case GET_PID_UID: {
if (!IPCSkeleton::IsLocalCalling()) {
result = IPC_STUB_INVALID_DATA_ERR;
break;
}
result = GetPidUid(data, reply);
break;
}
#endif
......@@ -285,11 +327,11 @@ void IPCObjectStub::OnLastStrongRef(const void *objectId)
if (current != nullptr) {
current->DetachObject(this);
#ifndef CONFIG_IPC_SINGLE
current->DetachStubRecvRefInfo(this);
current->DetachStubSendRefInfo(this);
(void)current->DetachStubRefTimes(this);
// we only need to erase stub index here, commAuth and appInfo
// has already been removed either in dbinder dec refcount case
// or OnSessionClosed, we also remove commAuth and appInfo in case of leak
current->DetachCommAuthInfoByStub(this);
uint64_t stubIndex = current->EraseStubIndex(reinterpret_cast<IRemoteObject *>(this));
uint64_t stubIndex = current->EraseStubIndex(this);
current->DetachAppInfoToStubIndex(stubIndex);
#endif
}
......@@ -379,18 +421,9 @@ int32_t IPCObjectStub::InvokerDataBusThread(MessageParcel &data, MessageParcel &
uint32_t remoteUid = data.ReadUint32();
std::string remoteDeviceId = data.ReadString();
std::string sessionName = data.ReadString();
uint32_t featureSet = data.ReadUint32();
uint32_t tokenId = 0;
std::shared_ptr<FeatureSetData> feature = std::make_shared<FeatureSetData>();
if (feature == nullptr) {
ZLOGE(LABEL, "%s: feature null", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
feature->featureSet = featureSet;
feature->tokenId = tokenId;
uint32_t remoteTokenId = data.ReadUint32();
if (IsDeviceIdIllegal(deviceId) || IsDeviceIdIllegal(remoteDeviceId) || sessionName.empty()) {
ZLOGE(LABEL, "%s: device ID is invalid or session name nil", __func__);
ZLOGE(LABEL, "%{public}s: device ID is invalid or session name nil", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
......@@ -400,24 +433,35 @@ int32_t IPCObjectStub::InvokerDataBusThread(MessageParcel &data, MessageParcel &
return IPC_STUB_CURRENT_NULL_ERR;
}
if (!current->CreateSoftbusServer(sessionName)) {
ZLOGE(LABEL, "%s: fail to create databus server", __func__);
ZLOGE(LABEL, "%{public}s: fail to create databus server", __func__);
return IPC_STUB_CREATE_BUS_SERVER_ERR;
}
uint64_t stubIndex = current->AddStubByIndex(this);
if (stubIndex == 0) {
ZLOGE(LABEL, "%s: add stub fail", __func__);
ZLOGE(LABEL, "%{public}s: add stub fail", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
if (!reply.WriteUint64(stubIndex) || !reply.WriteString(sessionName) || !reply.WriteString(deviceId)) {
ZLOGE(LABEL, "%s: write to parcel fail", __func__);
uint32_t selfTokenId = static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID());
ZLOGW(LABEL,
"invoke databus thread, local deviceId: %{public}s, remotePid: %{public}u, remoteUid: %{public}u, "
"stubIndex: %{public}" PRIu64 ", remote deviceId: %{public}s, tokenId: %{public}u, selfTokenId: %{public}u",
IPCProcessSkeleton::ConvertToSecureString(deviceId).c_str(), remotePid, remoteUid, stubIndex,
IPCProcessSkeleton::ConvertToSecureString(remoteDeviceId).c_str(), remoteTokenId, selfTokenId);
if (!reply.WriteUint64(stubIndex) || !reply.WriteString(sessionName) || !reply.WriteString(deviceId) ||
!reply.WriteUint32(selfTokenId)) {
ZLOGE(LABEL, "%{public}s: write to parcel fail", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
if (!current->AttachAppInfoToStubIndex(remotePid, remoteUid, remoteDeviceId, stubIndex)) {
ZLOGE(LABEL, "fail to attach appinfo to stubIndex, maybe attach already");
// mark listen fd as 0
if (!current->AttachAppInfoToStubIndex(remotePid, remoteUid, remoteTokenId, remoteDeviceId, stubIndex, 0)) {
ZLOGW(LABEL, "app info already existed, replace with 0");
}
if (!current->AttachCommAuthInfo(this, (int32_t)remotePid, (int32_t)remoteUid, remoteDeviceId, feature)) {
ZLOGE(LABEL, "fail to attach comm auth info");
if (current->AttachCommAuthInfo(this, remotePid, remoteUid, remoteTokenId, remoteDeviceId)) {
IncStrongRef(this);
} else {
ZLOGW(LABEL, "comm auth info attached already");
}
return ERR_NONE;
......@@ -427,58 +471,17 @@ int32_t IPCObjectStub::NoticeServiceDie(MessageParcel &data, MessageParcel &repl
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: current is null", __func__);
ZLOGE(LABEL, "%{public}s: current is null", __func__);
return IPC_STUB_CURRENT_NULL_ERR;
}
IPCObjectProxy *ipcProxy = current->QueryCallbackProxy(this);
sptr<IPCObjectProxy> ipcProxy = current->QueryCallbackProxy(this);
if (ipcProxy == nullptr) {
ZLOGE(LABEL, "%s: ipc proxy is null", __func__);
ZLOGE(LABEL, "%{public}s: ipc proxy is null", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
ipcProxy->SendObituary();
if (!current->DetachCallbackStub(this)) {
ZLOGE(LABEL, "%s: fail to detach callback stub", __func__);
// do nothing, RemoveDeathRecipient can delete this too
}
return ERR_NONE;
}
int32_t IPCObjectStub::IncStubRefs(MessageParcel &data, MessageParcel &reply)
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: current is null", __func__);
return IPC_STUB_CURRENT_NULL_ERR;
}
std::string deviceId = IPCSkeleton::GetCallingDeviceID();
if (deviceId.empty()) {
ZLOGE(LABEL, "%s: calling error", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
if (!current->AttachStubRecvRefInfo(this, IPCSkeleton::GetCallingPid(), deviceId)) {
ZLOGE(LABEL, "%s: attach stub ref info err, already in", __func__);
return ERR_NONE;
}
if (!current->DecStubRefTimes(this)) {
this->IncStrongRef(this);
}
return ERR_NONE;
}
int32_t IPCObjectStub::DecStubRefs(MessageParcel &data, MessageParcel &reply)
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: current is null", __func__);
return IPC_STUB_CURRENT_NULL_ERR;
}
std::string deviceId = IPCSkeleton::GetCallingDeviceID();
current->DetachStubRefInfo(this, IPCSkeleton::GetCallingPid(), deviceId);
return ERR_NONE;
}
......@@ -487,46 +490,44 @@ int32_t IPCObjectStub::AddAuthInfo(MessageParcel &data, MessageParcel &reply, ui
uint32_t remotePid = data.ReadUint32();
uint32_t remoteUid = data.ReadUint32();
std::string remoteDeviceId = data.ReadString();
uint32_t remoteFeature = data.ReadUint32();
uint32_t tokenId = 0;
std::shared_ptr<FeatureSetData> feature = nullptr;
feature.reset(reinterpret_cast<FeatureSetData *>(::operator new(sizeof(FeatureSetData))));
if (feature == nullptr) {
ZLOGE(LABEL, "%s: feature null", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
feature->featureSet = remoteFeature;
feature->tokenId = tokenId;
uint64_t stubIndex = data.ReadUint64();
uint32_t tokenId = data.ReadUint32();
if (IsDeviceIdIllegal(remoteDeviceId)) {
ZLOGE(LABEL, "%s: remote deviceId is null", __func__);
ZLOGE(LABEL, "%{public}s: remote deviceId is null", __func__);
return IPC_STUB_INVALID_DATA_ERR;
}
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
ZLOGE(LABEL, "%s: current is null", __func__);
ZLOGE(LABEL, "%{public}s: current is null", __func__);
return IPC_STUB_CURRENT_NULL_ERR;
}
if (!current->AttachCommAuthInfo(this, (int32_t)remotePid, (int32_t)remoteUid, remoteDeviceId, feature)) {
ZLOGE(LABEL, "fail to attach comm auth info fail");
return IPC_STUB_INVALID_DATA_ERR;
}
if (code == DBINDER_TRANS_COMMAUTH) {
uint64_t stubIndex = data.ReadUint64();
if (stubIndex == 0) {
// keep compatible with proxy that doesn't write stubIndex when adding auth info to stub
stubIndex = current->QueryStubIndex(this);
if (stubIndex == 0) {
ZLOGE(LABEL, "fail to attach comm auth info fail");
ZLOGE(LABEL, "stub index is null");
return BINDER_CALLBACK_STUBINDEX_ERR;
}
if (!current->AttachAppInfoToStubIndex(remotePid, remoteUid, remoteDeviceId, stubIndex)) {
ZLOGE(LABEL, "fail to add appinfo and stubIndex, maybe attach already");
}
}
ZLOGW(LABEL, "add auth info pid: %{public}u, uid: %{public}u, devId: %{public}s, stubIndex: %{public}" PRIu64
", tokenId: %{public}u", remotePid, remoteUid,
IPCProcessSkeleton::ConvertToSecureString(remoteDeviceId).c_str(), stubIndex, tokenId);
// mark listen fd as 0
if (!current->AttachAppInfoToStubIndex(remotePid, remoteUid, tokenId, remoteDeviceId, stubIndex, 0)) {
ZLOGW(LABEL, "app info already attached, replace with 0");
}
if (current->AttachCommAuthInfo(this, remotePid, remoteUid, tokenId, remoteDeviceId)) {
IncStrongRef(this);
} else {
ZLOGW(LABEL, "comm auth info attached already");
}
return ERR_NONE;
}
std::string IPCObjectStub::GetDataBusName(int32_t systemAbilityId)
std::string IPCObjectStub::GetSessionName()
{
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (current == nullptr) {
......@@ -540,17 +541,17 @@ std::string IPCObjectStub::GetDataBusName(int32_t systemAbilityId)
}
IPCObjectProxy *samgr = reinterpret_cast<IPCObjectProxy *>(object.GetRefPtr());
return samgr->GetDataBusName(systemAbilityId);
return samgr->GetGrantedSessionName();
}
int32_t IPCObjectStub::GrantDataBusName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
int32_t IPCObjectStub::GetGrantedSessionName(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
int pid = IPCSkeleton::GetCallingPid();
int uid = IPCSkeleton::GetCallingUid();
int systemAbilityId = data.ReadInt32();
std::string sessionName = CreateDatabusName(uid, pid, systemAbilityId);
std::string sessionName = CreateSessionName(uid, pid);
if (sessionName.empty()) {
ZLOGE(LABEL, "pid/uid is invalid, pid = {public}%d, uid = {public}%d", pid, uid);
ZLOGE(LABEL, "pid/uid is invalid, pid = %{public}d, uid = %{public}d", pid, uid);
return IPC_STUB_INVALID_DATA_ERR;
}
if (!reply.WriteUint32(IRemoteObject::IF_PROT_DATABUS) || !reply.WriteString(sessionName)) {
......@@ -561,17 +562,18 @@ int32_t IPCObjectStub::GrantDataBusName(uint32_t code, MessageParcel &data, Mess
return ERR_NONE;
}
int32_t IPCObjectStub::TransDataBusName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
int32_t IPCObjectStub::GetSessionNameForPidUid(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
uint32_t remotePid = data.ReadUint32();
uint32_t remoteUid = data.ReadUint32();
if (remotePid == static_cast<uint32_t>(IPCSkeleton::GetCallingPid())) {
ZLOGE(LABEL, "pid/uid is invalid, pid = {public}%d, uid = {public}%d", remotePid, remoteUid);
ZLOGE(LABEL, "pid/uid is invalid, pid = %{public}d, uid = %{public}d", remotePid, remoteUid);
return IPC_STUB_INVALID_DATA_ERR;
}
std::string sessionName = CreateDatabusName(remoteUid, remotePid, 0);
std::string sessionName = CreateSessionName(remoteUid, remotePid);
if (sessionName.empty()) {
ZLOGE(LABEL, "pid/uid is invalid, pid = {public}%d, uid = {public}%d", remotePid, remoteUid);
ZLOGE(LABEL, "pid/uid is invalid, pid = %{public}d, uid = %{public}d", remotePid, remoteUid);
return IPC_STUB_INVALID_DATA_ERR;
}
if (!reply.WriteUint32(IRemoteObject::IF_PROT_DATABUS) || !reply.WriteString(sessionName)) {
......@@ -582,7 +584,16 @@ int32_t IPCObjectStub::TransDataBusName(uint32_t code, MessageParcel &data, Mess
return ERR_NONE;
}
std::string IPCObjectStub::CreateDatabusName(int uid, int pid, int systemAbilityId)
int IPCObjectStub::GetPidUid(MessageParcel &data, MessageParcel &reply)
{
if (!reply.WriteUint32(getpid()) || !reply.WriteUint32(getuid())) {
ZLOGE(LABEL, "write to parcel fail");
return IPC_STUB_INVALID_DATA_ERR;
}
return ERR_NONE;
}
std::string IPCObjectStub::CreateSessionName(int uid, int pid)
{
std::shared_ptr<ISessionService> softbusManager = ISessionService::GetInstance();
if (softbusManager == nullptr) {
......@@ -591,9 +602,6 @@ std::string IPCObjectStub::CreateDatabusName(int uid, int pid, int systemAbility
}
std::string sessionName = "DBinder" + std::to_string(uid) + std::string("_") + std::to_string(pid);
if (systemAbilityId > 0) {
sessionName += std::string("_") + std::to_string(systemAbilityId);
}
if (softbusManager->GrantPermission(uid, pid, sessionName) != ERR_NONE) {
ZLOGE(LABEL, "fail to Grant Permission softbus name");
return "";
......
......@@ -102,7 +102,7 @@ uint32_t IPCSkeleton::GetCallingTokenID()
if (invoker != nullptr) {
return static_cast<uint32_t>(invoker->GetCallerTokenID());
}
return static_cast<uint32_t>(RpcGetSelfTokenID());
return static_cast<uint32_t>(GetSelfTokenID());
}
uint64_t IPCSkeleton::GetCallingFullTokenID()
......@@ -111,25 +111,42 @@ uint64_t IPCSkeleton::GetCallingFullTokenID()
if (invoker != nullptr) {
return invoker->GetCallerTokenID();
}
return RpcGetSelfTokenID();
return GetSelfTokenID();
}
uint64_t IPCSkeleton::GetSelfTokenID()
{
IRemoteInvoker *invoker = IPCThreadSkeleton::GetDefaultInvoker();
if (invoker != nullptr) {
return invoker->GetSelfTokenID();
}
return 0;
}
uint32_t IPCSkeleton::GetFirstTokenID()
{
IRemoteInvoker *invoker = IPCThreadSkeleton::GetActiveInvoker();
if (invoker != nullptr) {
return static_cast<uint32_t>(invoker->GetFirstTokenID());
return static_cast<uint32_t>(invoker->GetFirstCallerTokenID());
}
return static_cast<uint32_t>(RpcGetFirstCallerTokenID());
invoker = IPCThreadSkeleton::GetDefaultInvoker();
if (invoker != nullptr) {
return static_cast<uint32_t>(invoker->GetSelfFirstCallerTokenID());
}
return 0;
}
uint64_t IPCSkeleton::GetFirstFullTokenID()
{
IRemoteInvoker *invoker = IPCThreadSkeleton::GetActiveInvoker();
if (invoker != nullptr) {
return invoker->GetFirstTokenID();
return invoker->GetFirstCallerTokenID();
}
invoker = IPCThreadSkeleton::GetDefaultInvoker();
if (invoker != nullptr) {
return invoker->GetSelfFirstCallerTokenID();
}
return RpcGetFirstCallerTokenID();
return 0;
}
std::string IPCSkeleton::GetLocalDeviceID()
......
......@@ -41,14 +41,12 @@
#ifndef CONFIG_IPC_SINGLE
#include "dbinder_callback_stub.h"
#include "dbinder_session_object.h"
#include "rpc_feature_set.h"
#endif
namespace OHOS {
#ifdef CONFIG_IPC_SINGLE
using namespace IPC_SINGLE;
#endif
static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_ID_RPC, "MessageParcel" };
void AcquireObject(flat_binder_object *flat, const void *cookie)
......@@ -137,22 +135,20 @@ bool MessageParcel::WriteDBinderProxy(const sptr<IRemoteObject> &object, uint32_
}
std::shared_ptr<DBinderSessionObject> sessionOfPeer = current->ProxyQueryDBinderSession(handle);
if (sessionOfPeer == nullptr) {
ZLOGE(LOG_LABEL, "sessionOfPeer is nullptr");
ZLOGE(LOG_LABEL, "sessionOfPeer is null, handle: %{public}u, stubIndex: %{public}" PRIu64, handle, stubIndex);
return false;
}
std::string peerName = sessionOfPeer->GetServiceName();
std::string peerId = sessionOfPeer->GetDeviceId();
std::string localId = current->GetLocalDeviceID();
std::shared_ptr<FeatureSetData> feature = sessionOfPeer->GetFeatureSet();
if (feature == nullptr) {
ZLOGE(LOG_LABEL, "feature is nullptr");
return false;
}
uint32_t tokenId = sessionOfPeer->GetTokenId();
sptr<DBinderCallbackStub> fakeStub = current->QueryDBinderCallbackStub(object);
if (fakeStub == nullptr) {
// note that cannot use this proxy's descriptor
fakeStub = new (std::nothrow) DBinderCallbackStub(peerName, peerId, localId, stubIndex, handle, feature);
// note that cannot use this proxy's descriptor, this stub is now stored and strong refered
// and need to be erased in an approprite time
fakeStub = new (std::nothrow) DBinderCallbackStub(peerName, peerId, localId, sessionOfPeer->GetStubIndex(),
handle, tokenId);
if (fakeStub == nullptr) {
ZLOGE(LOG_LABEL, "create DBinderCallbackStub object failed");
return false;
......@@ -178,15 +174,10 @@ bool MessageParcel::WriteRemoteObject(const sptr<IRemoteObject> &object)
if (object->IsProxyObject()) {
const IPCObjectProxy *proxy = reinterpret_cast<const IPCObjectProxy *>(object.GetRefPtr());
const uint32_t handle = proxy ? proxy->GetHandle() : 0;
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
if (IPCProcessSkeleton::IsHandleMadeByUser(handle) && current != nullptr) {
ZLOGI(LOG_LABEL, "send dbinder object to local devices");
if (IPCProcessSkeleton::IsHandleMadeByUser(handle)) {
/* this is a fake proxy which handle get by MakeRemoteHandle(), Not binder driver of kernel */
uint64_t stubIndex = current->QueryHandleToIndex(handle);
if (stubIndex > 0) {
ZLOGI(LOG_LABEL, "this is dbinder proxy want to send anthor process in this device");
return WriteDBinderProxy(object, handle, stubIndex);
}
ZLOGI(LOG_LABEL, "send a dbinder proxy to another process in this device");
return WriteDBinderProxy(object, handle, 0);
}
}
#endif
......
......@@ -34,6 +34,8 @@ public:
void ExitCurrentThread(unsigned long request);
bool IsDriverAlive();
bool IsAccessTokenSupported();
uint64_t GetSelfTokenID();
uint64_t GetSelfFirstCallerTokenID();
private:
static BinderConnector *instance_;
static std::mutex skeletonMutex;
......@@ -43,6 +45,7 @@ private:
const std::string deviceName_;
int32_t version_;
uint64_t featureSet_;
uint64_t selfTokenID_;
};
#ifdef CONFIG_IPC_SINGLE
} // namespace IPC_SINGLE
......
......@@ -80,7 +80,11 @@ public:
uint64_t GetCallerTokenID() const override;
uint64_t GetFirstTokenID() const override;
uint64_t GetFirstCallerTokenID() const override;
uint64_t GetSelfTokenID() const override;
uint64_t GetSelfFirstCallerTokenID() const override;
uint32_t GetStatus() const override;
......@@ -101,9 +105,7 @@ public:
void ExitCurrentThread();
#ifndef CONFIG_IPC_SINGLE
int TranslateProxy(uint32_t handle, uint32_t flag) override;
int TranslateStub(binder_uintptr_t cookie, binder_uintptr_t ptr, uint32_t flag, int cmd) override;
int TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj) override;
sptr<IRemoteObject> GetSAMgrObject() override;
#endif
......@@ -144,10 +146,15 @@ private:
int HandleReply(MessageParcel *reply);
bool TranslateDBinderProxy(int handle, MessageParcel &data);
void GetAccessToken(uint64_t &callerTokenID, uint64_t &firstTokenID);
private:
DISALLOW_COPY_AND_MOVE(BinderInvoker);
static constexpr int IPC_DEFAULT_PARCEL_SIZE = 256;
static constexpr int IPC_CMD_PROCESS_WARN_TIME = 500;
static constexpr int ACCESS_TOKEN_MAX_LEN = 10;
Parcel input_;
Parcel output_;
BinderConnector *binderConnector_;
......
......@@ -47,16 +47,19 @@ public:
pid_t GetCallerPid() const override;
uid_t GetCallerUid() const override;
uint64_t GetCallerTokenID() const override;
uint64_t GetFirstTokenID() const override;
uint64_t GetFirstCallerTokenID() const override;
uint64_t GetSelfTokenID() const override;
uint64_t GetSelfFirstCallerTokenID() const override;
uint32_t GetStatus() const override;
virtual uint32_t GetClientFd() const override;
bool IsLocalCalling() override;
std::string GetLocalDeviceID() override;
std::string GetCallerDeviceID() const override;
bool UpdateClientSession(uint32_t handle, std::shared_ptr<DBinderSessionObject> sessionObject) override;
bool UpdateClientSession(std::shared_ptr<DBinderSessionObject> sessionObject) override;
std::shared_ptr<DBinderSessionObject> QueryClientSessionObject(uint32_t databusHandle) override;
std::shared_ptr<DBinderSessionObject> QueryServerSessionObject(uint32_t handle) override;
std::shared_ptr<DBinderSessionObject> CreateServerSessionObject(binder_uintptr_t binder, uint64_t &stubIndex,
std::shared_ptr<DBinderSessionObject> CreateServerSessionObject(binder_uintptr_t binder,
std::shared_ptr<DBinderSessionObject> sessionObject) override;
int FlushCommands(IRemoteObject *object) override;
......@@ -64,8 +67,7 @@ public:
bool OnReceiveNewConnection(std::shared_ptr<Session> session);
std::string ResetCallingIdentity() override;
bool SetCallingIdentity(std::string &identity) override;
int TranslateProxy(uint32_t handle, uint32_t flag) override;
int TranslateStub(binder_uintptr_t cookie, binder_uintptr_t ptr, uint32_t flag, int cmd) override;
int TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj) override;
void OnMessageAvailable(std::shared_ptr<Session> session, const char *data, ssize_t len);
private:
......@@ -77,28 +79,29 @@ private:
std::shared_ptr<DBinderSessionObject> QuerySessionOfBinderProxy(uint32_t handle,
std::shared_ptr<DBinderSessionObject> session) override;
uint32_t FlattenSession(char *sessionOffset, const std::shared_ptr<DBinderSessionObject> connectSession,
uint64_t stubIndex) override;
std::shared_ptr<DBinderSessionObject> UnFlattenSession(char *sessionOffset, uint64_t &stubIndex) override;
uint32_t QueryHandleBySession(std::shared_ptr<DBinderSessionObject> session, uint64_t stubIndex) override;
uint64_t GetSeqNum() const override;
void SetSeqNum(uint64_t seq) override;
uint32_t GetClientFd() const override;
void SetClientFd(uint32_t fd) override;
void SetCallerPid(pid_t pid) override;
void SetCallerUid(pid_t uid) override;
void SetStatus(uint32_t status) override;
void SetCallerDeviceID(const std::string &deviceId) override;
void SetCallerTokenID(const uint32_t tokenId) override;
int CheckAndSetCallerInfo(uint32_t listenFd, uint64_t stubIndex) override;
uint32_t binderVersion) override;
std::shared_ptr<DBinderSessionObject> UnFlattenSession(char *sessionOffset, uint32_t binderVersion) override;
uint32_t QueryHandleBySession(std::shared_ptr<DBinderSessionObject> session) override;
virtual uint64_t GetSeqNum() const override;
virtual void SetSeqNum(uint64_t seq) override;
virtual void SetClientFd(uint32_t fd) override;
virtual void SetCallerPid(pid_t pid) override;
virtual void SetCallerUid(pid_t uid) override;
virtual void SetStatus(uint32_t status) override;
virtual void SetCallerDeviceID(const std::string &deviceId) override;
virtual void SetCallerTokenID(const uint32_t tokenId) override;
virtual int CheckAndSetCallerInfo(uint32_t listenFd, uint64_t stubIndex) override;
uint32_t HasRawDataPackage(const char *data, ssize_t len);
uint32_t HasCompletePackage(const char *data, uint32_t readCursor, ssize_t len);
void OnRawDataAvailable(std::shared_ptr<Session> session, const char *data, uint32_t dataSize);
uint64_t MakeStubIndexByRemoteObject(IRemoteObject *stubObject);
std::shared_ptr<DBinderSessionObject> MakeDefaultServerSessionObject();
std::shared_ptr<DBinderSessionObject> MakeDefaultServerSessionObject(uint64_t stubIndex,
const std::shared_ptr<DBinderSessionObject> sessionObject);
bool ConnectRemoteObject2Session(IRemoteObject *stubObject, uint64_t stubIndex,
const std::shared_ptr<DBinderSessionObject> sessionObject);
bool AuthSession2Proxy(uint32_t handle, const std::shared_ptr<DBinderSessionObject> Session);
bool SetTokenId(const dbinder_transaction_data *tr, std::shared_ptr<DBinderSessionObject> sessionObject) override;
bool OnDatabusSessionServerSideClosed(std::shared_ptr<Session> session);
bool OnDatabusSessionClientSideClosed(std::shared_ptr<Session> session);
private:
DISALLOW_COPY_AND_MOVE(DBinderDatabusInvoker);
......@@ -111,6 +114,7 @@ private:
uint64_t seqNumber_ = 0;
uint32_t clientFd_ = 0;
uint32_t status_;
static constexpr int ACCESS_TOKEN_MAX_LEN = 10;
static inline InvokerDelegator<DBinderDatabusInvoker> DBinderDatabusDelegator_ = { IRemoteObject::IF_PROT_DATABUS };
};
} // namespace OHOS
......
......@@ -68,7 +68,11 @@ public:
virtual uint64_t GetCallerTokenID() const = 0;
virtual uint64_t GetFirstTokenID() const = 0;
virtual uint64_t GetFirstCallerTokenID() const = 0;
virtual uint64_t GetSelfTokenID() const = 0;
virtual uint64_t GetSelfFirstCallerTokenID() const = 0;
virtual uint32_t GetStatus() const = 0;
......@@ -95,9 +99,8 @@ public:
#ifndef CONFIG_IPC_SINGLE
virtual sptr<IRemoteObject> GetSAMgrObject() = 0;
virtual int TranslateProxy(uint32_t handle, uint32_t flag) = 0;
virtual int TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj) = 0;
virtual int TranslateStub(binder_uintptr_t cookie, binder_uintptr_t ptr, uint32_t flag, int cmd) = 0;
#endif
};
#ifdef CONFIG_IPC_SINGLE
......
......@@ -43,8 +43,13 @@ enum {
FLAT_BINDER_FLAG_ACCEPTS_FDS = 0x100,
FLAT_BINDER_FLAG_TXN_SECURITY_CTX = 0x1000,
};
#ifdef BINDER_IPC_32BIT
typedef __u32 binder_size_t;
typedef __u32 binder_uintptr_t;
#else
typedef __u64 binder_size_t;
typedef __u64 binder_uintptr_t;
#endif
struct binder_object_header {
__u32 type;
};
......@@ -96,13 +101,11 @@ struct binder_write_read {
struct binder_version {
__s32 protocol_version;
};
#ifdef BINDER_IPC_32BIT
#define BINDER_CURRENT_PROTOCOL_VERSION 7
#else
#define BINDER_CURRENT_PROTOCOL_VERSION 8
struct binder_feature_set {
__u64 feature_set;
};
#define ACCESS_TOKEN_FAETURE_MASK (1 << 0)
#endif
struct binder_node_debug_info {
binder_uintptr_t ptr;
binder_uintptr_t cookie;
......@@ -119,6 +122,14 @@ struct binder_node_info_for_ref {
__u32 reserved3;
};
#define ACCESS_TOKENID_GET_TOKENID _IOR('A', 1, unsigned long long)
#define ACCESS_TOKENID_GET_FTOKENID _IOR('A', 3, unsigned long long)
#define ACCESS_TOKEN_FAETURE_MASK (1 << 0)
struct binder_feature_set {
__u64 feature_set;
};
struct access_token {
__u64 sender_tokenid;
__u64 first_tokenid;
......@@ -135,7 +146,6 @@ struct access_token {
#define BINDER_GET_NODE_DEBUG_INFO _IOWR('b', 11, struct binder_node_debug_info)
#define BINDER_GET_NODE_INFO_FOR_REF _IOWR('b', 12, struct binder_node_info_for_ref)
#define BINDER_SET_CONTEXT_MGR_EXT _IOW('b', 13, struct flat_binder_object)
#define BINDER_TRANSLATE_HANDLE _IOWR('b', 18, __u32)
#define BINDER_FEATURE_SET _IOWR('b', 30, struct binder_feature_set)
#define BINDER_GET_ACCESS_TOKEN _IOWR('b', 31, struct access_token)
......@@ -242,11 +252,13 @@ enum binder_driver_command_protocol {
};
#endif /* * _UAPI_LINUX_BINDER_H * */
static const int DBINDER_MAGICWORD = 0X4442494E;
static const int ENCRYPT_HEAD_LEN = 28;
static const int DEVICEID_LENGTH = 64;
static const int PID_LEN = 32;
static const int VERSION_NUM = 1;
static const uint32_t DBINDER_MAGICWORD = 0X4442494E;
static const uint32_t ENCRYPT_HEAD_LEN = 28;
static const uint32_t DEVICEID_LENGTH = 64;
static const uint32_t PID_LEN = 32;
static const uint32_t RPC_DEFAULT_VERSION_NUM = 1;
static const uint32_t SUPPORT_TOKENID_VERSION_NUM = 2;
static const uint32_t TOKENID_MAGIC = 0X544F4B49;
enum {
BINDER_TYPE_REMOTE_BINDER = B_PACK_CHARS('r', 'b', '*', B_TYPE_LARGE),
......
......@@ -44,10 +44,11 @@ constexpr int SZ_1_M = 1048576;
constexpr int DOUBLE = 2;
static const int IPC_MMAP_SIZE = (SZ_1_M - sysconf(_SC_PAGE_SIZE) * DOUBLE);
static const std::string DRIVER_NAME = std::string("/dev/binder");
static const std::string TOKENID_DEVNODE = std::string("/dev/access_token_id");
BinderConnector *BinderConnector::instance_ = nullptr;
BinderConnector::BinderConnector(const std::string &deviceName)
: driverFD_(-1), vmAddr_(MAP_FAILED), deviceName_(deviceName), version_(0), featureSet_(0)
: driverFD_(-1), vmAddr_(MAP_FAILED), deviceName_(deviceName), version_(0), featureSet_(0), selfTokenID_(0)
{}
BinderConnector::~BinderConnector()
......@@ -114,10 +115,10 @@ bool BinderConnector::OpenDriver()
bool BinderConnector::IsAccessTokenSupported()
{
if (driverFD_ > 0) {
return featureSet_ & ACCESS_TOKEN_FAETURE_MASK;
if (IsDriverAlive() != true) {
return false;
}
return false;
return (featureSet_ & ACCESS_TOKEN_FAETURE_MASK) != 0;
}
int BinderConnector::WriteBinder(unsigned long request, void *value)
......@@ -150,6 +151,46 @@ void BinderConnector::ExitCurrentThread(unsigned long request)
}
}
uint64_t BinderConnector::GetSelfTokenID()
{
if (IsAccessTokenSupported() != true) {
return 0;
}
if (selfTokenID_ != 0) {
return selfTokenID_;
}
int fd = open(TOKENID_DEVNODE.c_str(), O_RDWR);
if (fd < 0) {
ZLOGE(LABEL, "%{public}s: fail to open tokenId node", __func__);
return 0;
}
int ret = ioctl(fd, ACCESS_TOKENID_GET_TOKENID, &selfTokenID_);
if (ret != 0) {
selfTokenID_ = 0;
}
close(fd);
return selfTokenID_;
}
uint64_t BinderConnector::GetSelfFirstCallerTokenID()
{
if (IsAccessTokenSupported() != true) {
return 0;
}
int fd = open(TOKENID_DEVNODE.c_str(), O_RDWR);
if (fd < 0) {
ZLOGE(LABEL, "%{public}s: fail to open tokenId node", __func__);
return 0;
}
uint64_t token = 0;
int ret = ioctl(fd, ACCESS_TOKENID_GET_FTOKENID, &token);
if (ret != 0) {
token = 0;
}
close(fd);
return token;
}
BinderConnector *BinderConnector::GetInstance()
{
if (instance_ == nullptr) {
......
......@@ -45,9 +45,8 @@ enum {
BinderInvoker::BinderInvoker()
: isMainWorkThread(false), stopWorkThread(false), callerPid_(getpid()), callerUid_(getuid()),
firstTokenID_(0), status_(0)
callerTokenID_(0), firstTokenID_(0), status_(0)
{
callerTokenID_ = RpcGetSelfTokenID();
input_.SetDataCapacity(IPC_DEFAULT_PARCEL_SIZE);
binderConnector_ = BinderConnector::GetInstance();
}
......@@ -99,6 +98,9 @@ int BinderInvoker::SendRequest(int handle, uint32_t code, MessageParcel &data, M
HiTraceId traceId = HiTraceChain::GetId();
// set client send trace point if trace is enabled
HiTraceId childId = HitraceInvoker::TraceClientSend(handle, code, newData, flags, traceId);
if (!TranslateDBinderProxy(handle, data)) {
return IPC_INVOKER_WRITE_TRANS_ERR;
}
if (!WriteTransaction(BC_TRANSACTION, flags, handle, code, data, nullptr)) {
newData.RewindWrite(oldWritePosition);
ZLOGE(LABEL, "WriteTransaction ERROR");
......@@ -123,6 +125,54 @@ int BinderInvoker::SendRequest(int handle, uint32_t code, MessageParcel &data, M
return error;
}
bool BinderInvoker::TranslateDBinderProxy(int handle, MessageParcel &parcel)
{
uintptr_t dataOffset = parcel.GetData();
binder_size_t *objOffset = reinterpret_cast<binder_size_t *>(parcel.GetObjectOffsets());
for (size_t i = 0; i < parcel.GetOffsetsSize(); i++) {
auto flat = reinterpret_cast<flat_binder_object *>(dataOffset + *(objOffset + i));
#ifdef CONFIG_IPC_SINGLE
if (flat->hdr.type == BINDER_TYPE_HANDLE && flat->cookie != IRemoteObject::IF_PROT_BINDER) {
ZLOGE(LABEL, "sending a dbinder proxy in ipc_single.z.so is not allowed");
return false;
}
#else
if (flat->hdr.type == BINDER_TYPE_HANDLE && flat->cookie == IRemoteObject::IF_PROT_DATABUS
&& flat->handle < IPCProcessSkeleton::DBINDER_HANDLE_BASE) {
MessageParcel data, reply;
MessageOption option;
if (SendRequest(handle, GET_PID_UID, data, reply, option) != ERR_NONE) {
ZLOGE(LABEL, "get pid and uid failed");
return false;
}
MessageParcel data2, reply2;
MessageOption option2;
data2.WriteUint32(reply.ReadUint32()); // pid
data2.WriteUint32(reply.ReadUint32()); // uid
IPCProcessSkeleton *current = IPCProcessSkeleton::GetCurrent();
data2.WriteString(current->GetLocalDeviceID()); // deviceId
std::shared_ptr<DBinderSessionObject> session = current->ProxyQueryDBinderSession(flat->handle);
if (session == nullptr) {
ZLOGE(LABEL, "no session found for handle: %{public}d", flat->handle);
return false;
}
data2.WriteUint64(session->GetStubIndex()); // stubIndex
data2.WriteUint32(session->GetTokenId()); // tokenId
IRemoteInvoker *invoker = IPCThreadSkeleton::GetRemoteInvoker(IRemoteObject::IF_PROT_DATABUS);
if (invoker == nullptr) {
ZLOGE(LABEL, "%{public}s: invoker is null", __func__);
return false;
}
if (invoker->SendRequest(flat->handle, DBINDER_ADD_COMMAUTH, data2, reply2, option2) != ERR_NONE) {
ZLOGE(LABEL, "dbinder add auth info failed");
return false;
}
}
#endif
}
return true;
}
bool BinderInvoker::AddDeathRecipient(int32_t handle, void *cookie)
{
size_t rewindPos = output_.GetWritePosition();
......@@ -189,40 +239,33 @@ bool BinderInvoker::RemoveDeathRecipient(int32_t handle, void *cookie)
}
#ifndef CONFIG_IPC_SINGLE
int BinderInvoker::TranslateProxy(uint32_t handle, uint32_t flag)
int BinderInvoker::TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj)
{
binder_node_debug_info info {};
if ((binderConnector_ == nullptr) || (!binderConnector_->IsDriverAlive())) {
return -IPC_INVOKER_CONNECT_ERR;
}
info.has_strong_ref = handle;
info.has_weak_ref = flag;
ZLOGD(LABEL, "TranslateProxy input handle = %{public}u", info.has_strong_ref);
int error = binderConnector_->WriteBinder(BINDER_TRANSLATE_HANDLE, &info);
if (error == ERR_NONE && info.has_strong_ref > 0) {
ZLOGD(LABEL, "TranslateProxy get new handle = %{public}u", info.has_strong_ref);
return info.has_strong_ref;
size_t rewindPos = output_.GetWritePosition();
if (!output_.WriteInt32(cmd)) {
if (!output_.RewindWrite(rewindPos)) {
output_.FlushBuffer();
}
return -IPC_INVOKER_TRANSLATE_ERR;
}
ZLOGE(LABEL, "failed to translateProxy input handle = %{public}u", info.has_strong_ref);
return -IPC_INVOKER_TRANSLATE_ERR;
}
int BinderInvoker::TranslateStub(binder_uintptr_t cookie, binder_uintptr_t ptr, uint32_t flag, int cmd)
{
binder_node_debug_info info {};
if ((binderConnector_ == nullptr) || (!binderConnector_->IsDriverAlive())) {
return -IPC_INVOKER_CONNECT_ERR;
if (!FlattenObject(output_, obj.GetRefPtr())) {
if (!output_.RewindWrite(rewindPos)) {
output_.FlushBuffer();
}
return -IPC_INVOKER_TRANSLATE_ERR;
}
info.cookie = cookie;
info.ptr = ptr;
info.has_weak_ref = (uint32_t)cmd;
info.has_strong_ref = flag;
int error = binderConnector_->WriteBinder(BINDER_TRANSLATE_HANDLE, &info);
if (error == ERR_NONE && info.has_strong_ref > 0) {
ZLOGD(LABEL, "TranslateStub get new handle = %{public}u", info.has_strong_ref);
return info.has_strong_ref;
MessageParcel reply;
int error = WaitForCompletion(&reply);
if (error == ERR_NONE) {
uint32_t handle = reply.ReadUint32();
if (handle > 0) {
return handle;
}
}
ZLOGE(LABEL, "failed to TranslateStub");
ZLOGE(LABEL, "failed to TranslateIRemoteObject");
return -IPC_INVOKER_TRANSLATE_ERR;
}
......@@ -384,6 +427,18 @@ void BinderInvoker::OnReleaseObject(uint32_t cmd)
}
}
void BinderInvoker::GetAccessToken(uint64_t &callerTokenID, uint64_t &firstTokenID)
{
struct access_token token{};
int error = binderConnector_->WriteBinder(BINDER_GET_ACCESS_TOKEN, &token);
if (error != ERR_NONE) {
token.sender_tokenid = 0;
token.first_tokenid = 0;
}
callerTokenID = token.sender_tokenid;
firstTokenID = token.first_tokenid;
}
void BinderInvoker::OnTransaction(const uint8_t *buffer)
{
const binder_transaction_data *tr = reinterpret_cast<const binder_transaction_data *>(buffer);
......@@ -406,19 +461,8 @@ void BinderInvoker::OnTransaction(const uint8_t *buffer)
uint32_t oldStatus = status_;
callerPid_ = tr->sender_pid;
callerUid_ = tr->sender_euid;
if (binderConnector_->IsAccessTokenSupported()) {
struct access_token tmp;
int error = binderConnector_->WriteBinder(BINDER_GET_ACCESS_TOKEN, &tmp);
if (error != ERR_NONE) {
callerTokenID_ = 0;
firstTokenID_ = 0;
} else {
callerTokenID_ = tmp.sender_tokenid;
firstTokenID_ = tmp.first_tokenid;
}
} else {
callerTokenID_ = 0;
firstTokenID_ = 0;
if (binderConnector_ != nullptr && binderConnector_->IsAccessTokenSupported()) {
GetAccessToken(callerTokenID_, firstTokenID_);
}
SetStatus(IRemoteInvoker::ACTIVE_INVOKER);
int error = ERR_DEAD_OBJECT;
......@@ -435,7 +479,7 @@ void BinderInvoker::OnTransaction(const uint8_t *buffer)
auto *targetObject = reinterpret_cast<IPCObjectStub *>(tr->cookie);
if (targetObject != nullptr) {
error = targetObject->SendRequest(tr->code, *data, reply, option);
service = Str16ToStr8(targetObject->descriptor_);
service = Str16ToStr8(targetObject->GetObjectDescriptor());
targetObject->DecStrongRef(this);
}
}
......@@ -510,6 +554,7 @@ int BinderInvoker::HandleReply(MessageParcel *reply)
const binder_transaction_data *tr = reinterpret_cast<const binder_transaction_data *>(buffer);
if (reply == nullptr) {
ZLOGD(LABEL, "no need reply, free the buffer");
FreeBuffer(reinterpret_cast<void *>(tr->data.ptr.buffer));
return IPC_INVOKER_INVALID_REPLY_ERR;
}
......@@ -527,6 +572,7 @@ int BinderInvoker::HandleReply(MessageParcel *reply)
return IPC_INVOKER_INVALID_DATA_ERR;
}
if (!reply->SetAllocator(allocator)) {
ZLOGD(LABEL, "SetAllocator failed");
delete allocator;
FreeBuffer(reinterpret_cast<void *>(tr->data.ptr.buffer));
return IPC_INVOKER_INVALID_DATA_ERR;
......@@ -835,17 +881,36 @@ uid_t BinderInvoker::GetCallerUid() const
uint64_t BinderInvoker::GetCallerTokenID() const
{
// If a process does NOT have a tokenid, the UID should be returned accordingly.
if (callerTokenID_ == 0) {
return callerUid_;
}
return callerTokenID_;
}
uint64_t BinderInvoker::GetFirstTokenID() const
uint64_t BinderInvoker::GetFirstCallerTokenID() const
{
if (firstTokenID_ == 0) {
return RpcGetFirstCallerTokenID();
}
return firstTokenID_;
}
uint64_t BinderInvoker::GetSelfTokenID() const
{
if ((binderConnector_ == nullptr) || (!binderConnector_->IsDriverAlive())) {
return 0;
}
uint64_t selfTokenId = binderConnector_->GetSelfTokenID();
return (selfTokenId == 0) ? static_cast<uint64_t>(getuid()) : selfTokenId;
}
uint64_t BinderInvoker::GetSelfFirstCallerTokenID() const
{
if ((binderConnector_ == nullptr) || (!binderConnector_->IsDriverAlive())) {
return 0;
}
uint64_t selfFirstCallerTokenId = binderConnector_->GetSelfFirstCallerTokenID();
return (selfFirstCallerTokenId == 0) ? static_cast<uint32_t>(getuid()) : selfFirstCallerTokenId;
}
uint32_t BinderInvoker::GetStatus() const
{
return status_;
......@@ -925,7 +990,6 @@ sptr<IRemoteObject> BinderInvoker::UnflattenObject(Parcel &parcel)
}
break;
}
case BINDER_TYPE_REMOTE_HANDLE:
case BINDER_TYPE_HANDLE: {
remoteObject = current->FindOrNewObject(flat->handle);
break;
......@@ -964,7 +1028,7 @@ bool BinderInvoker::WriteFileDescriptor(Parcel &parcel, int fd, bool takeOwnersh
flat.hdr.type = BINDER_TYPE_FD;
flat.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
flat.binder = 0; // Don't pass uninitialized stack data to a remote process
flat.handle = static_cast<uint32_t>(fd);
flat.handle = static_cast<__u32>(fd);
flat.cookie = takeOwnership ? 1 : 0;
return parcel.WriteBuffer(&flat, sizeof(flat_binder_object));
......@@ -983,7 +1047,7 @@ std::string BinderInvoker::ResetCallingIdentity()
| static_cast<uint64_t>(callerPid_)));
callerUid_ = static_cast<pid_t>(getuid());
callerPid_ = getpid();
callerTokenID_ = RpcGetSelfTokenID();
callerTokenID_ = GetSelfTokenID();
return accessToken + pidUid;
}
......
......@@ -223,7 +223,8 @@ namespace OHOS {
return false;
}
BufferObject object;
object.UpdateSendBuffer();
uint32_t sendSize = *(reinterpret_cast<const uint32_t*>(data));
object.UpdateSendBuffer(sendSize);
return true;
}
}
......
......@@ -186,7 +186,7 @@ namespace OHOS {
}
DBinderDatabusInvoker invoker;
invoker.GetFirstTokenID();
invoker.GetFirstCallerTokenID();
return true;
}
......@@ -230,21 +230,6 @@ namespace OHOS {
}
return true;
}
bool TranslateProxyTest(const uint8_t* data, size_t size)
{
if (data == nullptr || size < sizeof(int32_t)) {
return false;
}
DBinderDatabusInvoker invoker;
int32_t testHandle = *(reinterpret_cast<const int32_t*>(data));
uint32_t flag = 0;
if (invoker.TranslateProxy(testHandle, flag) == 0) {
return false;
}
return true;
}
}
/* Fuzzer entry point */
......@@ -267,6 +252,5 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
OHOS::IsLocalCallingTest(data, size);
OHOS::FlushCommandsTest(data, size);
OHOS::ResetCallingIdentityTest(data, size);
OHOS::TranslateProxyTest(data, size);
return 0;
}
......@@ -246,12 +246,13 @@ ohos_unittest("IPCMockUnitTest") {
group("unittest") {
testonly = true
deps = [
":BinderConnectorTest",
":BinderInvokerUnitTest",
#":BinderConnectorTest",
#":BinderInvokerUnitTest",
":IPCFileDescOpsTest",
":IPCHiTraceUnitTest",
":IPCMockUnitTest",
":IPCNativeUnitTest",
#":IPCMockUnitTest",
#":IPCNativeUnitTest",
]
if (support_jsapi) {
deps += [ ":IPCNapiUnitTest" ]
......
......@@ -272,8 +272,8 @@ int TestServiceProxy::TestCallingUidPid()
int pid = replyParcel.ReadInt32();
IPCTestHelper helper;
int actualUid = helper.GetUid();
int actualPid = helper.GetPid();
int actualUid = static_cast<int>(helper.GetUid());
int actualPid = static_cast<int>(helper.GetPid());
ZLOGD(LABEL, "uid = %{public}d, pid = %{public}d, actualUid = %{public}d, actualPid = %{public}d",
uid, pid, actualUid, actualPid);
......
......@@ -30,6 +30,10 @@ using Communication::SoftBus::ISessionService;
using Communication::SoftBus::Session;
namespace OHOS {
struct DeviceLock {
std::mutex mutex;
};
class DBinderRemoteListener : public ISessionListener {
public:
DBinderRemoteListener(const sptr<DBinderService> &dBinderService);
......@@ -40,16 +44,21 @@ public:
void OnBytesReceived(std::shared_ptr<Session> session, const char *data, ssize_t len) override;
bool OnDataAvailable(std::shared_ptr<Session> session, uint32_t status) override
{
return true;
return false;
};
bool SendDataToRemote(const std::string &deviceId, const struct DHandleEntryTxRx *msg);
bool SendDataReply(const std::string &deviceId, const struct DHandleEntryTxRx *msg);
bool StartListener(std::shared_ptr<DBinderRemoteListener> &listener);
bool StopListener();
bool CloseDatabusSession(const std::string &deviceId);
private:
std::shared_ptr<Session> OpenSoftbusSession(const std::string &deviceId);
std::shared_ptr<Session> GetPeerSession(const std::string &peerDeviceId);
std::shared_ptr<DeviceLock> QueryOrNewDeviceLock(const std::string &deviceId);
void ClearDeviceLock();
void EraseDeviceLock(const std::string &deviceId);
const std::string OWN_SESSION_NAME = "DBinderService";
const std::string PEER_SESSION_NAME = "DBinderService";
......@@ -58,7 +67,13 @@ private:
DISALLOW_COPY_AND_MOVE(DBinderRemoteListener);
std::mutex busManagerMutex_;
std::mutex serverSessionMutex_;
std::mutex deviceMutex_;
std::shared_ptr<ISessionService> softbusManager_;
sptr<DBinderService> dBinderService_;
std::map<std::string, std::shared_ptr<Session>> clientSessionMap_;
std::map<std::string, std::shared_ptr<Session>> serverSessionMap_;
std::map<std::string, std::shared_ptr<DeviceLock>> deviceLockMap_;
};
} // namespace OHOS
#endif // OHOS_IPC_DBINDER_REMOTE_LISTENER_H
......@@ -41,18 +41,6 @@ void DbinderDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
return;
}
std::shared_ptr<ISessionService> softbusManager = ISessionService::GetInstance();
if (softbusManager == nullptr) {
DBINDER_LOGE(LOG_LABEL, "fail to get softbus service");
return;
}
std::string sessionName = dBinderService->QueryBusNameObject(callbackProxy);
if (sessionName.empty()) {
DBINDER_LOGE(LOG_LABEL, "proxy sessionName not found");
return;
}
softbusManager->RemovePermission(sessionName);
sptr<IRemoteObject::DeathRecipient> death = dBinderService->QueryDeathRecipient(object);
if (death != nullptr) {
// Continue to clear subsequent data
......
......@@ -36,28 +36,11 @@ void DbinderSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
return;
}
sptr<IRemoteObject> object = remote.promote();
IPCObjectProxy *proxy = reinterpret_cast<IPCObjectProxy *>(object.GetRefPtr());
sptr<DBinderService> dBinderService = DBinderService::GetInstance();
if (dBinderService == nullptr) {
DBINDER_LOGE(LOG_LABEL, "dBinderService is null");
return;
}
std::shared_ptr<ISessionService> softbusManager = ISessionService::GetInstance();
if (softbusManager == nullptr) {
DBINDER_LOGE(LOG_LABEL, "fail to get softbus service");
return;
}
std::string sessionName = dBinderService->QueryBusNameObject(proxy);
if (sessionName.empty()) {
DBINDER_LOGE(LOG_LABEL, "proxy sessionName not found");
return;
}
softbusManager->RemovePermission(sessionName);
(void)dBinderService->DetachBusNameObject(proxy);
(void)dBinderService->DetachProxyObject(binderObject_);
}
} // namespace OHOS
......@@ -67,7 +67,8 @@ int32_t DBinderServiceStub::ProcessProto(uint32_t code, MessageParcel &data, Mes
return DBINDER_SERVICE_PROCESS_PROTO_ERR;
}
DBINDER_LOGI(LOG_LABEL, "serviceName = %s", session->serviceName.c_str());
DBINDER_LOGI(LOG_LABEL, "serviceName = %{public}s, stubIndex = %{public}" PRIu64 ", tokenId = %{public}u",
session->serviceName.c_str(), session->stubIndex, session->deviceIdInfo.tokenId);
int uid = IPCSkeleton::GetCallingUid();
int pid = IPCSkeleton::GetCallingPid();
......@@ -87,7 +88,7 @@ int32_t DBinderServiceStub::ProcessProto(uint32_t code, MessageParcel &data, Mes
if (!reply.WriteUint32(IRemoteObject::IF_PROT_DATABUS) || !reply.WriteUint64(session->stubIndex) ||
!reply.WriteString(session->serviceName) || !reply.WriteString(session->deviceIdInfo.toDeviceId) ||
!reply.WriteString(session->deviceIdInfo.fromDeviceId) || !reply.WriteString(localBusName) ||
!reply.WriteUint32(session->rpcFeatureSet)) {
!reply.WriteUint32(session->deviceIdInfo.tokenId)) {
DBINDER_LOGE(LOG_LABEL, "write to parcel fail");
return DBINDER_SERVICE_PROCESS_PROTO_ERR;
}
......@@ -147,12 +148,6 @@ int32_t DBinderServiceStub::AddDbinderDeathRecipient(MessageParcel &data, Messag
return DBINDER_SERVICE_INVALID_DATA_ERR;
}
std::string sessionName = data.ReadString();
if (sessionName.empty()) {
DBINDER_LOGE(LOG_LABEL, "received sessionName is null");
return DBINDER_SERVICE_INVALID_DATA_ERR;
}
IPCObjectProxy *callbackProxy = reinterpret_cast<IPCObjectProxy *>(object.GetRefPtr());
sptr<IRemoteObject::DeathRecipient> death(new DbinderDeathRecipient());
......@@ -177,12 +172,6 @@ int32_t DBinderServiceStub::AddDbinderDeathRecipient(MessageParcel &data, Messag
DBINDER_LOGE(LOG_LABEL, "fail to attach callback proxy");
return DBINDER_SERVICE_ADD_DEATH_ERR;
}
if (!dBinderService->AttachBusNameObject(callbackProxy, sessionName)) {
DBINDER_LOGE(LOG_LABEL, "fail to attach sessionName for callback proxy");
return DBINDER_SERVICE_ADD_DEATH_ERR;
}
return ERR_NONE;
}
......@@ -217,12 +206,6 @@ int32_t DBinderServiceStub::RemoveDbinderDeathRecipient(MessageParcel &data, Mes
DBINDER_LOGE(LOG_LABEL, "fail to detach callback proxy");
return DBINDER_SERVICE_REMOVE_DEATH_ERR;
}
if (!dBinderService->DetachBusNameObject(callbackProxy)) {
DBINDER_LOGE(LOG_LABEL, "fail to deatch sessionName for callback proxy");
return DBINDER_SERVICE_ADD_DEATH_ERR;
}
return ERR_NONE;
}
} // namespace OHOS
......@@ -31,9 +31,11 @@ public:
int PingService(std::u16string &serviceName) override;
int TransProxyObject(int data, sptr<IRemoteObject> &transObject, int operation, int &rep,
int &withdrawRes) override;
int TransProxyObjectRefCount(sptr<IRemoteObject> &transObject, int operation) override;
int TransProxyObjectAgain(int data, sptr<IRemoteObject> &transObject, int operation, int &rep,
int &withdrawRes) override;
int TransStubObject(int data, sptr<IRemoteObject> &transObject, int &rep, int &stubRep) override;
int TransStubObjectRefCount(sptr<IRemoteObject> &transObject, int operation) override;
int TransOversizedPkt(const std::string &dataStr, std::string &repStr) override;
int ProxyTransRawData(int length) override;
int StubTransRawData(int length) override;
......
......@@ -34,7 +34,7 @@ public:
PING_SERVICE = 2,
GET_FOO_SERVICE = 3,
ONLY_DELAY = 4,
TRANS_OBJECT = 5,
TRANS_PROXY_OBJECT = 5,
TRANS_OVERSIZED_PKT = 6,
TRANS_RAW_DATA = 7,
RECEIVE_RAW_DATA = 8,
......@@ -45,6 +45,8 @@ public:
CLEAR_REMOTE_DES_TIMES = 13,
TRANS_OBJECT_OVER_DEVICE_OVER_PROCESS = 14,
TRANS_RPC_OBJECT_TO_LOCAL = 15,
TRANS_STUB_OBJECT_REFCOUNT = 16,
TRANS_PROXY_OBJECT_REFCOUNT = 17,
};
enum {
......@@ -66,9 +68,11 @@ public:
virtual int ReverseIntDelayAsync(int data, int &rep) = 0;
virtual int TransProxyObject(int data, sptr<IRemoteObject> &transObject, int operation, int &rep,
int &withdrawRes) = 0;
virtual int TransProxyObjectRefCount(sptr<IRemoteObject> &transObject, int operation) = 0;
virtual int TransProxyObjectAgain(int data, sptr<IRemoteObject> &transObject, int operation, int &rep,
int &withdrawRes) = 0;
virtual int TransStubObject(int data, sptr<IRemoteObject> &transObject, int &rep, int &stubRep) = 0;
virtual int TransStubObjectRefCount(sptr<IRemoteObject> &transObject, int operation) = 0;
virtual int TransOversizedPkt(const std::string &dataStr, std::string &repStr) = 0;
virtual int ProxyTransRawData(int lengths) = 0;
virtual int StubTransRawData(int length) = 0;
......@@ -100,8 +104,10 @@ private:
int OnPingService(MessageParcel &data, MessageParcel &reply);
int OnDelay(MessageParcel &data, MessageParcel &reply);
int OnReceivedObject(MessageParcel &data, MessageParcel &reply);
int OnReceivedProxyObjectRefCount(MessageParcel &data, MessageParcel &reply);
int OnReceivedObjectTransAgain(MessageParcel &data, MessageParcel &reply);
int OnReceivedStubObject(MessageParcel &data, MessageParcel &reply);
int OnReceivedStubObjectRefCount(MessageParcel &data, MessageParcel &reply);
int OnReceivedOversizedPkt(MessageParcel &data, MessageParcel &reply);
int OnReceivedRawData(MessageParcel &data, MessageParcel &reply);
int OnGetChildId(MessageParcel &data, MessageParcel &reply);
......@@ -127,8 +133,10 @@ public:
int &withdrawRes) override;
int TransProxyObjectAgain(int data, sptr<IRemoteObject> &transObject, int operation, int &rep,
int &withdrawRes) override;
int TransProxyObjectRefCount(sptr<IRemoteObject> &transObject, int operation) override;
int TransStubObject(int data, sptr<IRemoteObject> &transObject, int &rep, int &stubRep) override;
int TransOversizedPkt(const std::string &dataStr, std::string &repStr) override;
int TransStubObjectRefCount(sptr<IRemoteObject> &transObject, int operation) override;
int ProxyTransRawData(int length) override;
int StubTransRawData(int length) override;
int GetChildId(uint64_t &rep) override;
......
......@@ -38,6 +38,7 @@
#include "distributed_major.h"
#include "log_tags.h"
#include "dbinder_test_service.h"
#include "dbinder_log.h"
using namespace OHOS;
using namespace testing::ext;
......@@ -1473,6 +1474,115 @@ HWTEST_F(DbinderTest, DbinderRemoteCall030, TestSize.Level3)
SetCurrentTestCase(DBINDER_TEST_INIT);
}
/*
* @tc.name: DbinderRemoteCall031
* @tc.desc: Test two ways of sending stub object, GetSystemAbility and through message parcel,
* and its reference count
* @tc.type: FUNC
* @tc.require: SR000CQSAB AR000DAPPM
*/
HWTEST_F(DbinderTest, DbinderRemoteCall031, TestSize.Level3)
{
SetCurrentTestCase(DBINDER_TEST_TRANS_STUB_001);
/*
* @tc.steps: step1.Get a local stub object and a proxy pointing to remote a remote stub.
* @tc.expected: step1.Get both objects successfully.
*/
sptr<IRemoteObject> object = new DBinderTestService();
ASSERT_TRUE(object != nullptr);
EXPECT_EQ(object->GetSptrRefCount(), 1);
sptr<IRemoteObject> remoteObject = manager_->GetSystemAbility(RPC_TEST_SERVICE, serverId_);
ASSERT_TRUE(remoteObject != nullptr);
// refered by one proxy here, another in samgr process of remote device
EXPECT_EQ(remoteObject->GetObjectRefCount(), 2);
sptr<IDBinderTestService> proxy = iface_cast<IDBinderTestService>(remoteObject);
ASSERT_TRUE(proxy != nullptr);
sptr<IRemoteObject> remoteObject2 = manager_->GetSystemAbility(RPC_TEST_SERVICE2, serverId_);
ASSERT_TRUE(remoteObject2 != nullptr);
EXPECT_EQ(remoteObject2->GetObjectRefCount(), 2);
sptr<IDBinderTestService> proxy2 = iface_cast<IDBinderTestService>(remoteObject2);
ASSERT_TRUE(proxy2 != nullptr);
/*
* @tc.steps: step2.Use the proxy object to transfer stub object
* @tc.expected: step2.Remote call succeeds.
*/
int result = proxy->TransStubObjectRefCount(object, IDBinderTestService::SAVE);
EXPECT_EQ(result, 0);
EXPECT_EQ(object->GetSptrRefCount(), 2);
result = proxy2->TransStubObjectRefCount(object, IDBinderTestService::SAVE);
EXPECT_EQ(result, 0);
EXPECT_EQ(object->GetSptrRefCount(), 3);
result = proxy->TransStubObjectRefCount(object, IDBinderTestService::WITHDRAW);
EXPECT_EQ(result, 0);
EXPECT_EQ(object->GetSptrRefCount(), 2);
result = proxy2->TransStubObjectRefCount(object, IDBinderTestService::WITHDRAW);
EXPECT_EQ(result, 0);
EXPECT_EQ(object->GetSptrRefCount(), 1);
SetCurrentTestCase(DBINDER_TEST_INIT);
}
/*
* @tc.name: DbinderRemoteCall032
* @tc.desc: Test sending rpc proxy acquired from GetSystemAbility to another process
* in this device, sending ipc proxy acquired from GetSystemAbility to another device,
* and their reference count respectively.
* @tc.type: FUNC
* @tc.require: SR000CQSAB AR000DAPPM
*/
HWTEST_F(DbinderTest, DbinderRemoteCall032, TestSize.Level3)
{
SetCurrentTestCase(DBINDER_TEST_TRANS_STUB_001);
/*
* @tc.steps: step1.Get a local proxy and a remote proxy.
* @tc.expected: step1.Get both proxy successfully.
*/
sptr<IRemoteObject> remoteObject = manager_->GetSystemAbility(RPC_TEST_SERVICE, serverId_);
ASSERT_TRUE(remoteObject != nullptr);
// refered by one sptr here, another in samgr process of remote device
EXPECT_EQ(remoteObject->GetObjectRefCount(), 2);
sptr<IDBinderTestService> proxy = iface_cast<IDBinderTestService>(remoteObject);
ASSERT_TRUE(proxy != nullptr);
EXPECT_EQ(remoteObject->GetSptrRefCount(), 2);
EXPECT_EQ(remoteObject->GetObjectRefCount(), 2);
sptr<IRemoteObject> remoteObject2 = manager_->GetSystemAbility(RPC_TEST_SERVICE);
ASSERT_TRUE(remoteObject2 != nullptr);
EXPECT_EQ(remoteObject2->GetObjectRefCount(), 1);
sptr<IDBinderTestService> proxy2 = iface_cast<IDBinderTestService>(remoteObject2);
ASSERT_TRUE(proxy2 != nullptr);
EXPECT_EQ(remoteObject2->GetSptrRefCount(), 2);
EXPECT_EQ(remoteObject2->GetObjectRefCount(), 1);
/*
* @tc.steps: step2.Use the local proxy object to transfer remote proxy object
* @tc.expected: step2.Remote call succeeds.
*/
int result = proxy2->TransProxyObjectRefCount(remoteObject, IDBinderTestService::SAVE);
EXPECT_EQ(result, 0);
EXPECT_EQ(remoteObject->GetObjectRefCount(), 3);
result = proxy->TransProxyObjectRefCount(remoteObject2, IDBinderTestService::SAVE);
EXPECT_EQ(result, 0);
EXPECT_EQ(remoteObject2->GetObjectRefCount(), 2);
result = proxy2->TransProxyObjectRefCount(remoteObject, IDBinderTestService::WITHDRAW);
EXPECT_EQ(result, 0);
EXPECT_EQ(remoteObject->GetObjectRefCount(), 2);
result = proxy->TransProxyObjectRefCount(remoteObject2, IDBinderTestService::WITHDRAW);
EXPECT_EQ(result, 0);
EXPECT_EQ(remoteObject2->GetObjectRefCount(), 1);
SetCurrentTestCase(DBINDER_TEST_INIT);
}
int main(int argc, char *argv[])
{
g_pDistributetestEnv = new DistributeTestEnvironment("major.desc");
......
......@@ -66,6 +66,7 @@ pid_t GetPidByName(std::string taskName)
fclose(fp);
continue;
}
(void)memset_s(curTaskName, sizeof(curTaskName), 0, sizeof(curTaskName));
if (sscanf_s(buf, "%*s %s", curTaskName, sizeof(curTaskName)) <= EOK) {
DBINDER_LOGI(LOG_LABEL, "sscanf fail");
}
......@@ -127,8 +128,7 @@ pid_t StartExecutable(std::string name, std::string args)
std::string cmd1 = "chmod +x /data/" + name;
int res = system(cmd1.c_str());
DBINDER_LOGI(LOG_LABEL, "%{public}s res = %d, errno = %{public}d %{public}s",
cmd1.c_str(), res, errno, strerror(errno));
DBINDER_LOGI(LOG_LABEL, "%{public}s res = %d, errno = %{public}d", cmd1.c_str(), res, errno);
std::string cmd2 = "/data/" + name + " " + args + "&";
res = system(cmd2.c_str());
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册