San Mehat | fa644ff | 2009-05-08 11:15:53 -0700 | [diff] [blame] | 1 | #include <alloca.h> |
| 2 | #include <errno.h> |
| 3 | #include <sys/types.h> |
| 4 | #include <pthread.h> |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 5 | #include <string.h> |
San Mehat | fa644ff | 2009-05-08 11:15:53 -0700 | [diff] [blame] | 6 | |
| 7 | #define LOG_TAG "SocketClient" |
| 8 | #include <cutils/log.h> |
| 9 | |
| 10 | #include <sysutils/SocketClient.h> |
| 11 | |
| 12 | SocketClient::SocketClient(int socket) { |
| 13 | mSocket = socket; |
| 14 | pthread_mutex_init(&mWriteMutex, NULL); |
| 15 | } |
| 16 | |
San Mehat | db01754 | 2009-05-20 15:27:14 -0700 | [diff] [blame] | 17 | int SocketClient::sendMsg(int code, const char *msg, bool addErrno) { |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 18 | char *buf; |
San Mehat | 03f0d27 | 2009-05-26 15:18:25 -0700 | [diff] [blame] | 19 | |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 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 Mehat | db01754 | 2009-05-20 15:27:14 -0700 | [diff] [blame] | 30 | int SocketClient::sendMsg(const char *msg) { |
San Mehat | fa644ff | 2009-05-08 11:15:53 -0700 | [diff] [blame] | 31 | if (mSocket < 0) { |
| 32 | errno = EHOSTUNREACH; |
| 33 | return -1; |
| 34 | } |
| 35 | |
San Mehat | c73a3a5 | 2009-06-15 14:06:03 -0700 | [diff] [blame] | 36 | // Send the message including null character |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 37 | int rc = 0; |
San Mehat | c73a3a5 | 2009-06-15 14:06:03 -0700 | [diff] [blame] | 38 | const char *p = msg; |
| 39 | int brtw = strlen(msg) + 1; |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 40 | |
San Mehat | fa644ff | 2009-05-08 11:15:53 -0700 | [diff] [blame] | 41 | pthread_mutex_lock(&mWriteMutex); |
San Mehat | d768066 | 2009-05-12 11:16:59 -0700 | [diff] [blame] | 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; |
San Mehat | fa644ff | 2009-05-08 11:15:53 -0700 | [diff] [blame] | 55 | } |
| 56 | pthread_mutex_unlock(&mWriteMutex); |
| 57 | return 0; |
| 58 | } |