2 * Copyright (C) 2011 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include "SocketStream.h"
17 #include <cutils/sockets.h>
25 #include <netinet/in.h>
26 #include <netinet/tcp.h>
32 SocketStream::SocketStream(size_t bufSize) :
40 SocketStream::SocketStream(int sock, size_t bufSize) :
48 SocketStream::~SocketStream()
64 void *SocketStream::allocBuffer(size_t minSize)
66 size_t allocSize = (m_bufsize < minSize ? minSize : m_bufsize);
68 m_buf = (unsigned char *)malloc(allocSize);
70 else if (m_bufsize < allocSize) {
71 unsigned char *p = (unsigned char *)realloc(m_buf, allocSize);
74 m_bufsize = allocSize;
76 ERR("%s: realloc (%zu) failed\n", __FUNCTION__, allocSize);
86 int SocketStream::commitBuffer(size_t size)
88 return writeFully(m_buf, size);
91 int SocketStream::writeFully(const void* buffer, size_t size)
93 if (!valid()) return -1;
99 ssize_t stat = ::send(m_sock, (const char *)buffer + (size - res), res, 0);
101 if (errno != EINTR) {
103 ERR("%s: failed: %s\n", __FUNCTION__, strerror(errno));
113 const unsigned char *SocketStream::readFully(void *buf, size_t len)
115 const unsigned char* ret = NULL;
116 if (!valid()) return NULL;
118 return NULL; // do not allow NULL buf in that implementation
122 ssize_t stat = ::recv(m_sock, (char *)(buf) + len - res, res, 0);
127 if (stat == 0 || errno != EINTR) { // client shutdown or error
131 return (const unsigned char *)buf;
134 const unsigned char *SocketStream::read( void *buf, size_t *inout_len)
136 if (!valid()) return NULL;
138 return NULL; // do not allow NULL buf in that implementation
143 n = recv(buf, *inout_len);
144 } while( n < 0 && errno == EINTR );
148 return (const unsigned char *)buf;
154 int SocketStream::recv(void *buf, size_t len)
156 if (!valid()) return int(ERR_INVALID_SOCKET);
159 res = ::recv(m_sock, (char *)buf, len, 0);
161 if (errno == EINTR) {