SocketClient.cpp revision 8c5669f9f9a228efebf4059fd4ceace5cece578b
1#include <alloca.h>
2#include <errno.h>
3#include <sys/socket.h>
4#include <sys/types.h>
5#include <pthread.h>
6#include <string.h>
7
8#define LOG_TAG "SocketClient"
9#include <cutils/log.h>
10
11#include <sysutils/SocketClient.h>
12
13SocketClient::SocketClient(int socket)
14        : mSocket(socket)
15        , mPid(-1)
16        , mUid(-1)
17        , mGid(-1)
18{
19    pthread_mutex_init(&mWriteMutex, NULL);
20
21    struct ucred creds;
22    socklen_t szCreds = sizeof(creds);
23    memset(&creds, 0, szCreds);
24
25    int err = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
26    if (err == 0) {
27        mPid = creds.pid;
28        mUid = creds.uid;
29        mGid = creds.gid;
30    }
31}
32
33int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
34    char *buf;
35
36    if (addErrno) {
37        buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8);
38        sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno));
39    } else {
40        buf = (char *) alloca(strlen(msg) + strlen("XXX "));
41        sprintf(buf, "%.3d %s", code, msg);
42    }
43    return sendMsg(buf);
44}
45
46int SocketClient::sendMsg(const char *msg) {
47    if (mSocket < 0) {
48        errno = EHOSTUNREACH;
49        return -1;
50    }
51
52    // Send the message including null character
53    if (sendData(msg, strlen(msg) + 1) != 0) {
54        SLOGW("Unable to send msg '%s'", msg);
55        return -1;
56    }
57    return 0;
58}
59
60int SocketClient::sendData(const void* data, int len) {
61    int rc = 0;
62    const char *p = (const char*) data;
63    int brtw = len;
64
65    pthread_mutex_lock(&mWriteMutex);
66    while (brtw > 0) {
67        if ((rc = write(mSocket, p, brtw)) < 0) {
68            SLOGW("write error (%s)", strerror(errno));
69            pthread_mutex_unlock(&mWriteMutex);
70            return -1;
71        } else if (!rc) {
72            SLOGW("0 length write :(");
73            errno = EIO;
74            pthread_mutex_unlock(&mWriteMutex);
75            return -1;
76        }
77        p += rc;
78        brtw -= rc;
79    }
80    pthread_mutex_unlock(&mWriteMutex);
81    return 0;
82}
83