SocketClient.h revision 7bf4c45f842ded6d6ad6b2d80e052ddf56969723
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
10class SocketClient {
11    int             mSocket;
12    bool            mSocketOwned;
13    pthread_mutex_t mWriteMutex;
14
15    /* Peer process ID */
16    pid_t mPid;
17
18    /* Peer user ID */
19    uid_t mUid;
20
21    /* Peer group ID */
22    gid_t mGid;
23
24    /* Reference count (starts at 1) */
25    pthread_mutex_t mRefCountMutex;
26    int mRefCount;
27
28    int mCmdNum;
29
30    bool mUseCmdNum;
31
32public:
33    SocketClient(int sock, bool owned);
34    SocketClient(int sock, bool owned, bool useCmdNum);
35    virtual ~SocketClient();
36
37    int getSocket() { return mSocket; }
38    pid_t getPid() const { return mPid; }
39    uid_t getUid() const { return mUid; }
40    gid_t getGid() const { return mGid; }
41    void setCmdNum(int cmdNum) { android_atomic_release_store(cmdNum, &mCmdNum); }
42    int getCmdNum() { return mCmdNum; }
43
44    // Send null-terminated C strings:
45    int sendMsg(int code, const char *msg, bool addErrno);
46    int sendMsg(int code, const char *msg, bool addErrno, bool useCmdNum);
47
48    // Provides a mechanism to send a response code to the client. The message uses
49    // the same format as in sendMsg method above.
50    // Sends the code, a space, and a null character.
51    int sendCode(int code);
52
53    // Provides a mechanism to send binary data to client. The message uses the
54    // same format as in sendMsg method above.
55    // Sends the code, a space, 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
62    // Optional reference counting.  Reference count starts at 1.  If
63    // it's decremented to 0, it deletes itself.
64    // SocketListener creates a SocketClient (at refcount 1) and calls
65    // decRef() when it's done with the client.
66    void incRef();
67    bool decRef(); // returns true at 0 (but note: SocketClient already deleted)
68
69private:
70    // Send null-terminated C strings
71    int sendMsg(const char *msg);
72    void init(int socket, bool owned, bool useCmdNum);
73
74    // Sending binary data. The caller should use make sure this is protected
75    // from multiple threads entering simultaneously.
76    // returns 0 if successful, -1 if there is a 0 byte write and -2 if any other
77    // error occurred (use errno to get the error)
78    int sendDataLocked(const void *data, int len);
79};
80
81typedef android::sysutils::List<SocketClient *> SocketClientCollection;
82#endif
83