summaryrefslogtreecommitdiffstats
path: root/libsysutils/src/SocketClient.cpp
blob: ab020ca7b798d4297451518462d04495df1788e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <alloca.h>
#include <errno.h>
#include <sys/types.h>
#include <pthread.h>
#include <string.h>

#define LOG_TAG "SocketClient"
#include <cutils/log.h>

#include <sysutils/SocketClient.h>

SocketClient::SocketClient(int socket) {
    mSocket = socket;
    pthread_mutex_init(&mWriteMutex, NULL);
}

int SocketClient::sendMsg(int code, char *msg, bool addErrno) {
    char *buf;
    
    if (addErrno) {
        buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8);
        sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno));
    } else {
        buf = (char *) alloca(strlen(msg) + strlen("XXX "));
        sprintf(buf, "%.3d %s", code, msg);
    }
    return sendMsg(buf);
}

int SocketClient::sendMsg(char *msg) {
    if (mSocket < 0) {
        errno = EHOSTUNREACH;
        return -1;
    }

    char *bp;
  
    if (msg[strlen(msg)] != '\n') {
        bp = (char *) alloca(strlen(msg) + 1);
        strcpy(bp, msg);
        strcat(bp, "\n");
    } else
        bp = msg;
       
    int rc = 0;
    char *p = bp;
    int brtw = strlen(bp);

    pthread_mutex_lock(&mWriteMutex);
    while(brtw) {
        if ((rc = write(mSocket,p, brtw)) < 0) {
            LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
            pthread_mutex_unlock(&mWriteMutex);
            return -1;
        } else if (!rc) {
            LOGW("0 length write :(");
            errno = EIO;
            pthread_mutex_unlock(&mWriteMutex);
            return -1;
        }
        p += rc;
        brtw -= rc;
    }
    pthread_mutex_unlock(&mWriteMutex);
    return 0;
}