blob: b229627ff0899d227bbfe83d0cf3f5c1137502ae [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 Mehatdb017542009-05-20 15:27:14 -070017int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
San Mehatd7680662009-05-12 11:16:59 -070018 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 Mehatdb017542009-05-20 15:27:14 -070030int SocketClient::sendMsg(const char *msg) {
San Mehatfa644ff2009-05-08 11:15:53 -070031 if (mSocket < 0) {
32 errno = EHOSTUNREACH;
33 return -1;
34 }
35
San Mehatdb017542009-05-20 15:27:14 -070036 char *tmp;
37 const char *bp = msg;
38
San Mehatd7680662009-05-12 11:16:59 -070039 if (msg[strlen(msg)] != '\n') {
San Mehatdb017542009-05-20 15:27:14 -070040 tmp = (char *) alloca(strlen(msg) + 1);
41 strcpy(tmp, msg);
42 strcat(tmp, "\n");
43 bp = tmp;
44 }
San Mehatd7680662009-05-12 11:16:59 -070045
46 int rc = 0;
San Mehatdb017542009-05-20 15:27:14 -070047 const char *p = bp;
San Mehatd7680662009-05-12 11:16:59 -070048 int brtw = strlen(bp);
49
San Mehatfa644ff2009-05-08 11:15:53 -070050 pthread_mutex_lock(&mWriteMutex);
San Mehatd7680662009-05-12 11:16:59 -070051 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;
San Mehatfa644ff2009-05-08 11:15:53 -070064 }
65 pthread_mutex_unlock(&mWriteMutex);
66 return 0;
67}