blob: 8e5f1545a6588cd738caa7a49136659a6982235e [file] [log] [blame]
San Mehatfa644ff2009-05-08 11:15:53 -07001#include <alloca.h>
2#include <errno.h>
Kenny Root30abb722010-09-14 14:26:12 -07003#include <sys/socket.h>
San Mehatfa644ff2009-05-08 11:15:53 -07004#include <sys/types.h>
5#include <pthread.h>
San Mehatd7680662009-05-12 11:16:59 -07006#include <string.h>
San Mehatfa644ff2009-05-08 11:15:53 -07007
8#define LOG_TAG "SocketClient"
9#include <cutils/log.h>
10
11#include <sysutils/SocketClient.h>
12
Kenny Root30abb722010-09-14 14:26:12 -070013SocketClient::SocketClient(int socket)
14 : mSocket(socket)
15 , mPid(-1)
16 , mUid(-1)
17 , mGid(-1)
18{
San Mehatfa644ff2009-05-08 11:15:53 -070019 pthread_mutex_init(&mWriteMutex, NULL);
Kenny Root30abb722010-09-14 14:26:12 -070020
21 struct ucred creds;
22 socklen_t szCreds = sizeof(creds);
23 memset(&creds, 0, szCreds);
24
25 int err = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
26 if (err == 0) {
27 mPid = creds.pid;
28 mUid = creds.uid;
29 mGid = creds.gid;
30 }
San Mehatfa644ff2009-05-08 11:15:53 -070031}
32
San Mehatdb017542009-05-20 15:27:14 -070033int SocketClient::sendMsg(int code, const char *msg, bool addErrno) {
San Mehatd7680662009-05-12 11:16:59 -070034 char *buf;
San Mehat03f0d272009-05-26 15:18:25 -070035
San Mehatd7680662009-05-12 11:16:59 -070036 if (addErrno) {
37 buf = (char *) alloca(strlen(msg) + strlen(strerror(errno)) + 8);
38 sprintf(buf, "%.3d %s (%s)", code, msg, strerror(errno));
39 } else {
40 buf = (char *) alloca(strlen(msg) + strlen("XXX "));
41 sprintf(buf, "%.3d %s", code, msg);
42 }
43 return sendMsg(buf);
44}
45
San Mehatdb017542009-05-20 15:27:14 -070046int SocketClient::sendMsg(const char *msg) {
San Mehatfa644ff2009-05-08 11:15:53 -070047 if (mSocket < 0) {
48 errno = EHOSTUNREACH;
49 return -1;
50 }
51
San Mehatc73a3a52009-06-15 14:06:03 -070052 // Send the message including null character
San Mehatd7680662009-05-12 11:16:59 -070053 int rc = 0;
San Mehatc73a3a52009-06-15 14:06:03 -070054 const char *p = msg;
55 int brtw = strlen(msg) + 1;
San Mehatd7680662009-05-12 11:16:59 -070056
San Mehatfa644ff2009-05-08 11:15:53 -070057 pthread_mutex_lock(&mWriteMutex);
San Mehatd7680662009-05-12 11:16:59 -070058 while(brtw) {
59 if ((rc = write(mSocket,p, brtw)) < 0) {
San Mehat7e8529a2010-03-25 09:31:42 -070060 SLOGW("Unable to send msg '%s' (%s)", msg, strerror(errno));
San Mehatd7680662009-05-12 11:16:59 -070061 pthread_mutex_unlock(&mWriteMutex);
62 return -1;
63 } else if (!rc) {
San Mehat7e8529a2010-03-25 09:31:42 -070064 SLOGW("0 length write :(");
San Mehatd7680662009-05-12 11:16:59 -070065 errno = EIO;
66 pthread_mutex_unlock(&mWriteMutex);
67 return -1;
68 }
69 p += rc;
70 brtw -= rc;
San Mehatfa644ff2009-05-08 11:15:53 -070071 }
72 pthread_mutex_unlock(&mWriteMutex);
73 return 0;
74}