SocketClient.cpp revision df6c1b91e3813886070f35929583c30cfaead918
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, 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(char *msg) {
31    if (mSocket < 0) {
32        errno = EHOSTUNREACH;
33        return -1;
34    }
35
36    char *bp;
37
38    if (msg[strlen(msg)] != '\n') {
39        bp = (char *) alloca(strlen(msg) + 1);
40        strcpy(bp, msg);
41        strcat(bp, "\n");
42    } else
43        bp = msg;
44
45    int rc = 0;
46    char *p = bp;
47    int brtw = strlen(bp);
48
49    pthread_mutex_lock(&mWriteMutex);
50    while(brtw) {
51        if ((rc = write(mSocket,p, brtw)) < 0) {
52            LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
53            pthread_mutex_unlock(&mWriteMutex);
54            return -1;
55        } else if (!rc) {
56            LOGW("0 length write :(");
57            errno = EIO;
58            pthread_mutex_unlock(&mWriteMutex);
59            return -1;
60        }
61        p += rc;
62        brtw -= rc;
63    }
64    pthread_mutex_unlock(&mWriteMutex);
65    return 0;
66}
67