1 #ifndef _SOCKET_CLIENT_H 2 #define _SOCKET_CLIENT_H 3 4 #include "List.h" 5 6 #include <pthread.h> 7 #include <cutils/atomic.h> 8 #include <sys/types.h> 9 #include <sys/uio.h> 10 11 class SocketClient { 12 int mSocket; 13 bool mSocketOwned; 14 pthread_mutex_t mWriteMutex; 15 16 // Peer process ID 17 pid_t mPid; 18 19 // Peer user ID 20 uid_t mUid; 21 22 // Peer group ID 23 gid_t mGid; 24 25 // Reference count (starts at 1) 26 pthread_mutex_t mRefCountMutex; 27 int mRefCount; 28 29 int mCmdNum; 30 31 bool mUseCmdNum; 32 33 public: 34 SocketClient(int sock, bool owned); 35 SocketClient(int sock, bool owned, bool useCmdNum); 36 virtual ~SocketClient(); 37 getSocket()38 int getSocket() { return mSocket; } getPid()39 pid_t getPid() const { return mPid; } getUid()40 uid_t getUid() const { return mUid; } getGid()41 gid_t getGid() const { return mGid; } setCmdNum(int cmdNum)42 void setCmdNum(int cmdNum) { 43 android_atomic_release_store(cmdNum, &mCmdNum); 44 } getCmdNum()45 int getCmdNum() { return mCmdNum; } 46 47 // Send null-terminated C strings: 48 int sendMsg(int code, const char *msg, bool addErrno); 49 int sendMsg(int code, const char *msg, bool addErrno, bool useCmdNum); 50 int sendMsg(const char *msg); 51 52 // Provides a mechanism to send a response code to the client. 53 // Sends the code and a null character. 54 int sendCode(int code); 55 56 // Provides a mechanism to send binary data to client. 57 // Sends the code and a null character, followed by 4 bytes of 58 // big-endian length, and the data. 59 int sendBinaryMsg(int code, const void *data, int len); 60 61 // Sending binary data: 62 int sendData(const void *data, int len); 63 // iovec contents not preserved through call 64 int sendDatav(struct iovec *iov, int iovcnt); 65 66 // Optional reference counting. Reference count starts at 1. If 67 // it's decremented to 0, it deletes itself. 68 // SocketListener creates a SocketClient (at refcount 1) and calls 69 // decRef() when it's done with the client. 70 void incRef(); 71 bool decRef(); // returns true at 0 (but note: SocketClient already deleted) 72 73 // return a new string in quotes with '\\' and '\"' escaped for "my arg" 74 // transmissions 75 static char *quoteArg(const char *arg); 76 77 private: 78 void init(int socket, bool owned, bool useCmdNum); 79 80 // Sending binary data. The caller should make sure this is protected 81 // from multiple threads entering simultaneously. 82 // returns 0 if successful, -1 if there is a 0 byte write or if any 83 // other error occurred (use errno to get the error) 84 int sendDataLockedv(struct iovec *iov, int iovcnt); 85 }; 86 87 typedef android::sysutils::List<SocketClient *> SocketClientCollection; 88 #endif 89