blob: ab020ca7b798d4297451518462d04495df1788e2 [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) {
San Mehatfa644ff2009-05-08 11:15:53 -070031 if (mSocket < 0) {
32 errno = EHOSTUNREACH;
33 return -1;
34 }
35
San Mehatd7680662009-05-12 11:16:59 -070036 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
San Mehatfa644ff2009-05-08 11:15:53 -070049 pthread_mutex_lock(&mWriteMutex);
San Mehatd7680662009-05-12 11:16:59 -070050 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;
San Mehatfa644ff2009-05-08 11:15:53 -070063 }
64 pthread_mutex_unlock(&mWriteMutex);
65 return 0;
66}