SocketClient.cpp revision b9634d05cf4fedb2ee49b0a41aeb129d35337ce9
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    if (len == 0) {
66        return 0;
67    }
68
69    pthread_mutex_lock(&mWriteMutex);
70    while (brtw > 0) {
71        if ((rc = write(mSocket, p, brtw)) < 0) {
72            SLOGW("write error (%s)", strerror(errno));
73            pthread_mutex_unlock(&mWriteMutex);
74            return -1;
75        } else if (!rc) {
76            SLOGW("0 length write :(");
77            errno = EIO;
78            pthread_mutex_unlock(&mWriteMutex);
79            return -1;
80        }
81        p += rc;
82        brtw -= rc;
83    }
84    pthread_mutex_unlock(&mWriteMutex);
85    return 0;
86}
87