blob: e9ae23a900e6dbbc3a97833a0316b5674229e311 [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;
San Mehat03f0d272009-05-26 15:18:25 -070019
San Mehatd7680662009-05-12 11:16:59 -070020 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 Mehatc73a3a52009-06-15 14:06:03 -070036 // Send the message including null character
San Mehatd7680662009-05-12 11:16:59 -070037 int rc = 0;
San Mehatc73a3a52009-06-15 14:06:03 -070038 const char *p = msg;
39 int brtw = strlen(msg) + 1;
San Mehatd7680662009-05-12 11:16:59 -070040
San Mehatfa644ff2009-05-08 11:15:53 -070041 pthread_mutex_lock(&mWriteMutex);
San Mehatd7680662009-05-12 11:16:59 -070042 while(brtw) {
43 if ((rc = write(mSocket,p, brtw)) < 0) {
San Mehat7e8529a2010-03-25 09:31:42 -070044 SLOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
San Mehatd7680662009-05-12 11:16:59 -070045 pthread_mutex_unlock(&mWriteMutex);
46 return -1;
47 } else if (!rc) {
San Mehat7e8529a2010-03-25 09:31:42 -070048 SLOGW("0 length write :(");
San Mehatd7680662009-05-12 11:16:59 -070049 errno = EIO;
50 pthread_mutex_unlock(&mWriteMutex);
51 return -1;
52 }
53 p += rc;
54 brtw -= rc;
San Mehatfa644ff2009-05-08 11:15:53 -070055 }
56 pthread_mutex_unlock(&mWriteMutex);
57 return 0;
58}