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