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
SocketClient(int socket)12 SocketClient::SocketClient(int socket) {
13 mSocket = socket;
14 pthread_mutex_init(&mWriteMutex, NULL);
15 }
16
sendMsg(int code,const char * msg,bool addErrno)17 int SocketClient::sendMsg(int code, const 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
sendMsg(const char * msg)30 int SocketClient::sendMsg(const char *msg) {
31 if (mSocket < 0) {
32 errno = EHOSTUNREACH;
33 return -1;
34 }
35
36 // Send the message including null character
37 int rc = 0;
38 const char *p = msg;
39 int brtw = strlen(msg) + 1;
40
41 pthread_mutex_lock(&mWriteMutex);
42 while(brtw) {
43 if ((rc = write(mSocket,p, brtw)) < 0) {
44 LOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
45 pthread_mutex_unlock(&mWriteMutex);
46 return -1;
47 } else if (!rc) {
48 LOGW("0 length write :(");
49 errno = EIO;
50 pthread_mutex_unlock(&mWriteMutex);
51 return -1;
52 }
53 p += rc;
54 brtw -= rc;
55 }
56 pthread_mutex_unlock(&mWriteMutex);
57 return 0;
58 }
59