blob: 930fa4c3a64f58135841839b30e9572b07d3d4f2 [file] [log] [blame]
San Mehatfa644ff2009-05-08 11:15:53 -07001#include <alloca.h>
2#include <errno.h>
3#include <sys/types.h>
4#include <pthread.h>
San Mehatd7680662009-05-12 11:16:59 -07005#include <string.h>
San Mehatfa644ff2009-05-08 11:15:53 -07006
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
San Mehatd7680662009-05-12 11:16:59 -070017int 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
San Mehatfa644ff2009-05-08 11:15:53 -070030int SocketClient::sendMsg(char *msg) {
31 LOGD("SocketClient::sendMsg(%s)", msg);
San Mehatd7680662009-05-12 11:16:59 -070032
San Mehatfa644ff2009-05-08 11:15:53 -070033 if (mSocket < 0) {
34 errno = EHOSTUNREACH;
35 return -1;
36 }
37
San Mehatd7680662009-05-12 11:16:59 -070038 char *bp;
39
40 if (msg[strlen(msg)] != '\n') {
41 bp = (char *) alloca(strlen(msg) + 1);
42 strcpy(bp, msg);
43 strcat(bp, "\n");
44 } else
45 bp = msg;
46
47 int rc = 0;
48 char *p = bp;
49 int brtw = strlen(bp);
50
San Mehatfa644ff2009-05-08 11:15:53 -070051 pthread_mutex_lock(&mWriteMutex);
San Mehatd7680662009-05-12 11:16:59 -070052 while(brtw) {
53 if ((rc = write(mSocket,p, brtw)) < 0) {
54 LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
55 pthread_mutex_unlock(&mWriteMutex);
56 return -1;
57 } else if (!rc) {
58 LOGW("0 length write :(");
59 errno = EIO;
60 pthread_mutex_unlock(&mWriteMutex);
61 return -1;
62 }
63 p += rc;
64 brtw -= rc;
San Mehatfa644ff2009-05-08 11:15:53 -070065 }
66 pthread_mutex_unlock(&mWriteMutex);
67 return 0;
68}