SocketClient.cpp revision db017545796747115b8797f03e662b0f398a7c7b
1#include <alloca.h>
2#include <errno.h>
3#include <sys/types.h>
4#include <pthread.h>
5#include <string.h>
6
7#define LOG_TAG "SocketClient"
8#include <cutils/log.h>
9
10#include <sysutils/SocketClient.h>
11
12SocketClient::SocketClient(int socket) {
13    mSocket = socket;
14    pthread_mutex_init(&mWriteMutex, NULL);
15}
16
17int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
18    char *buf;
19
20    if (addErrno) {
21        buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8);
22        sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno));
23    } else {
24        buf = (char *) alloca(strlen(msg) + strlen("XXX "));
25        sprintf(buf, "%.3d %s", code, msg);
26    }
27    return sendMsg(buf);
28}
29
30int SocketClient::sendMsg(const char *msg) {
31    if (mSocket < 0) {
32        errno = EHOSTUNREACH;
33        return -1;
34    }
35
36    char *tmp;
37    const char *bp = msg;
38
39    if (msg[strlen(msg)] != '\n') {
40        tmp = (char *) alloca(strlen(msg) + 1);
41        strcpy(tmp, msg);
42        strcat(tmp, "\n");
43        bp = tmp;
44    }
45
46    int rc = 0;
47    const char *p = bp;
48    int brtw = strlen(bp);
49
50    pthread_mutex_lock(&mWriteMutex);
51    while(brtw) {
52        if ((rc = write(mSocket,p, brtw)) < 0) {
53            LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
54            pthread_mutex_unlock(&mWriteMutex);
55            return -1;
56        } else if (!rc) {
57            LOGW("0 length write :(");
58            errno = EIO;
59            pthread_mutex_unlock(&mWriteMutex);
60            return -1;
61        }
62        p += rc;
63        brtw -= rc;
64    }
65    pthread_mutex_unlock(&mWriteMutex);
66    return 0;
67}
68