blob: 7b1d356167cad6ede6e52ee0f349873cb3541ede [file] [log] [blame]
David Reissea2cba82009-03-30 21:35:00 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Mark Slee9f0c6512007-02-28 23:58:26 +000019
Marc Slemkoe03da182006-07-21 21:32:36 +000020#include <config.h>
David Reissc88eb8c2008-06-11 01:18:54 +000021#include <cstring>
22#include <sstream>
Mark Sleee8540632006-05-30 09:24:40 +000023#include <sys/socket.h>
Bryan Duxburya18364a2010-09-28 14:36:07 +000024#include <sys/un.h>
David Reiss22b18862008-04-08 06:25:45 +000025#include <sys/poll.h>
Mark Sleedd564972007-08-21 02:39:57 +000026#include <sys/types.h>
Mark Sleee8540632006-05-30 09:24:40 +000027#include <arpa/inet.h>
28#include <netinet/in.h>
29#include <netinet/tcp.h>
30#include <netdb.h>
31#include <unistd.h>
32#include <errno.h>
Mark Slee29050782006-09-29 00:12:30 +000033#include <fcntl.h>
Mark Sleee8540632006-05-30 09:24:40 +000034
Mark Slee29050782006-09-29 00:12:30 +000035#include "concurrency/Monitor.h"
Marc Slemkod42a2c22006-08-10 03:30:18 +000036#include "TSocket.h"
37#include "TTransportException.h"
Mark Sleee8540632006-05-30 09:24:40 +000038
T Jake Lucianib5e62212009-01-31 22:36:20 +000039namespace apache { namespace thrift { namespace transport {
Marc Slemko6f038a72006-08-03 18:58:09 +000040
Mark Sleee8540632006-05-30 09:24:40 +000041using namespace std;
42
Mark Slee29050782006-09-29 00:12:30 +000043// Global var to track total socket sys calls
Mark Slee8d7e1f62006-06-07 06:48:56 +000044uint32_t g_socket_syscalls = 0;
45
46/**
47 * TSocket implementation.
48 *
Mark Slee8d7e1f62006-06-07 06:48:56 +000049 */
50
Mark Slee256bdc42007-11-27 08:42:19 +000051TSocket::TSocket(string host, int port) :
Mark Slee29050782006-09-29 00:12:30 +000052 host_(host),
53 port_(port),
Bryan Duxburya18364a2010-09-28 14:36:07 +000054 path_(""),
55 socket_(-1),
56 connTimeout_(0),
57 sendTimeout_(0),
58 recvTimeout_(0),
59 lingerOn_(1),
60 lingerVal_(0),
61 noDelay_(1),
62 maxRecvRetries_(5) {
63 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
64 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
65}
66
67TSocket::TSocket(string path) :
68 host_(""),
69 port_(0),
70 path_(path),
Martin Kraemeree341cb2007-02-05 21:40:38 +000071 socket_(-1),
Mark Slee29050782006-09-29 00:12:30 +000072 connTimeout_(0),
73 sendTimeout_(0),
74 recvTimeout_(0),
75 lingerOn_(1),
76 lingerVal_(0),
Aditya Agarwale04475b2007-05-23 02:14:58 +000077 noDelay_(1),
78 maxRecvRetries_(5) {
Mark Sleeb9ff32a2006-11-16 01:00:24 +000079 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
80 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
David Reiss23248712010-10-06 17:10:08 +000081 cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
Mark Sleee8540632006-05-30 09:24:40 +000082}
83
Mark Slee256bdc42007-11-27 08:42:19 +000084TSocket::TSocket() :
Aditya Agarwalebc99e02007-01-15 23:14:58 +000085 host_(""),
86 port_(0),
Bryan Duxburya18364a2010-09-28 14:36:07 +000087 path_(""),
Martin Kraemeree341cb2007-02-05 21:40:38 +000088 socket_(-1),
Aditya Agarwalebc99e02007-01-15 23:14:58 +000089 connTimeout_(0),
90 sendTimeout_(0),
91 recvTimeout_(0),
92 lingerOn_(1),
93 lingerVal_(0),
Aditya Agarwale04475b2007-05-23 02:14:58 +000094 noDelay_(1),
95 maxRecvRetries_(5) {
Aditya Agarwalebc99e02007-01-15 23:14:58 +000096 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
97 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
David Reiss23248712010-10-06 17:10:08 +000098 cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
Aditya Agarwalebc99e02007-01-15 23:14:58 +000099}
100
Mark Slee29050782006-09-29 00:12:30 +0000101TSocket::TSocket(int socket) :
102 host_(""),
103 port_(0),
Bryan Duxburya18364a2010-09-28 14:36:07 +0000104 path_(""),
Mark Slee29050782006-09-29 00:12:30 +0000105 socket_(socket),
106 connTimeout_(0),
107 sendTimeout_(0),
108 recvTimeout_(0),
109 lingerOn_(1),
110 lingerVal_(0),
Aditya Agarwale04475b2007-05-23 02:14:58 +0000111 noDelay_(1),
112 maxRecvRetries_(5) {
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000113 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
114 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
David Reiss23248712010-10-06 17:10:08 +0000115 cachedPeerAddr_.ipv4.sin_family = AF_UNSPEC;
Mark Slee29050782006-09-29 00:12:30 +0000116}
Mark Slee256bdc42007-11-27 08:42:19 +0000117
Mark Sleee8540632006-05-30 09:24:40 +0000118TSocket::~TSocket() {
119 close();
120}
121
Mark Slee256bdc42007-11-27 08:42:19 +0000122bool TSocket::isOpen() {
123 return (socket_ >= 0);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000124}
125
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000126bool TSocket::peek() {
127 if (!isOpen()) {
128 return false;
129 }
130 uint8_t buf;
131 int r = recv(socket_, &buf, 1, MSG_PEEK);
132 if (r == -1) {
David Reissbc3dddb2007-08-22 23:20:24 +0000133 int errno_copy = errno;
David Reiss840e7522009-06-04 00:10:50 +0000134 #if defined __FreeBSD__ || defined __MACH__
Kevin Clark022b2242009-03-05 21:05:37 +0000135 /* shigin:
136 * freebsd returns -1 and ECONNRESET if socket was closed by
137 * the other side
138 */
139 if (errno_copy == ECONNRESET)
140 {
141 close();
142 return false;
143 }
144 #endif
David Reiss01e55c12008-07-13 22:18:51 +0000145 GlobalOutput.perror("TSocket::peek() recv() " + getSocketInfo(), errno_copy);
David Reissbc3dddb2007-08-22 23:20:24 +0000146 throw TTransportException(TTransportException::UNKNOWN, "recv()", errno_copy);
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000147 }
148 return (r > 0);
149}
150
Mark Slee6d56eb92007-07-06 22:28:15 +0000151void TSocket::openConnection(struct addrinfo *res) {
Mark Sleea9848d72007-02-21 04:54:05 +0000152 if (isOpen()) {
Bryan Duxbury010f1e02010-09-02 00:56:53 +0000153 return;
Mark Sleea9848d72007-02-21 04:54:05 +0000154 }
Aditya Agarwal4529c4b2007-09-05 01:01:15 +0000155
Bryan Duxburya18364a2010-09-28 14:36:07 +0000156 if (! path_.empty()) {
157 socket_ = socket(PF_UNIX, SOCK_STREAM, IPPROTO_IP);
158 } else {
159 socket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
160 }
161
Mark Sleee8540632006-05-30 09:24:40 +0000162 if (socket_ == -1) {
David Reissbc3dddb2007-08-22 23:20:24 +0000163 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000164 GlobalOutput.perror("TSocket::open() socket() " + getSocketInfo(), errno_copy);
David Reissbc3dddb2007-08-22 23:20:24 +0000165 throw TTransportException(TTransportException::NOT_OPEN, "socket()", errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000166 }
Mark Slee29050782006-09-29 00:12:30 +0000167
168 // Send timeout
169 if (sendTimeout_ > 0) {
170 setSendTimeout(sendTimeout_);
171 }
172
173 // Recv timeout
174 if (recvTimeout_ > 0) {
175 setRecvTimeout(recvTimeout_);
176 }
177
178 // Linger
179 setLinger(lingerOn_, lingerVal_);
180
181 // No delay
182 setNoDelay(noDelay_);
183
David Reiss1c20c872010-03-09 05:20:14 +0000184 // Uses a low min RTO if asked to.
185#ifdef TCP_LOW_MIN_RTO
186 if (getUseLowMinRto()) {
187 int one = 1;
188 setsockopt(socket_, IPPROTO_TCP, TCP_LOW_MIN_RTO, &one, sizeof(one));
189 }
190#endif
191
192
Mark Slee29050782006-09-29 00:12:30 +0000193 // Set the socket to be non blocking for connect if a timeout exists
Mark Slee256bdc42007-11-27 08:42:19 +0000194 int flags = fcntl(socket_, F_GETFL, 0);
Mark Slee29050782006-09-29 00:12:30 +0000195 if (connTimeout_ > 0) {
Mark Sleea5a783f2007-03-02 19:41:08 +0000196 if (-1 == fcntl(socket_, F_SETFL, flags | O_NONBLOCK)) {
David Reiss9b209552008-04-08 06:26:05 +0000197 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000198 GlobalOutput.perror("TSocket::open() fcntl() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000199 throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy);
Mark Sleea5a783f2007-03-02 19:41:08 +0000200 }
Mark Slee29050782006-09-29 00:12:30 +0000201 } else {
Mark Sleea5a783f2007-03-02 19:41:08 +0000202 if (-1 == fcntl(socket_, F_SETFL, flags & ~O_NONBLOCK)) {
David Reiss9b209552008-04-08 06:26:05 +0000203 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000204 GlobalOutput.perror("TSocket::open() fcntl " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000205 throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy);
Mark Sleea5a783f2007-03-02 19:41:08 +0000206 }
Mark Slee29050782006-09-29 00:12:30 +0000207 }
208
Mark Sleee8540632006-05-30 09:24:40 +0000209 // Connect the socket
Bryan Duxburya18364a2010-09-28 14:36:07 +0000210 int ret;
211 if (! path_.empty()) {
212 struct sockaddr_un address;
213 socklen_t len;
214
215 if (path_.length() > sizeof(address.sun_path)) {
216 int errno_copy = errno;
217 GlobalOutput.perror("TSocket::open() Unix Domain socket path too long", errno_copy);
218 throw TTransportException(TTransportException::NOT_OPEN, " Unix Domain socket path too long");
219 }
220
221 address.sun_family = AF_UNIX;
Roger Meierd11ca5a2010-10-18 08:22:57 +0000222 snprintf(address.sun_path, sizeof(address.sun_path), "%s", path_.c_str());
Bryan Duxburya18364a2010-09-28 14:36:07 +0000223 len = sizeof(address);
224 ret = connect(socket_, (struct sockaddr *) &address, len);
225 } else {
226 ret = connect(socket_, res->ai_addr, res->ai_addrlen);
227 }
Mark Slee256bdc42007-11-27 08:42:19 +0000228
David Reiss9b209552008-04-08 06:26:05 +0000229 // success case
Mark Slee29050782006-09-29 00:12:30 +0000230 if (ret == 0) {
231 goto done;
232 }
233
234 if (errno != EINPROGRESS) {
David Reissbc3dddb2007-08-22 23:20:24 +0000235 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000236 GlobalOutput.perror("TSocket::open() connect() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000237 throw TTransportException(TTransportException::NOT_OPEN, "connect() failed", errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000238 }
239
David Reiss22b18862008-04-08 06:25:45 +0000240
241 struct pollfd fds[1];
David Reissc88eb8c2008-06-11 01:18:54 +0000242 std::memset(fds, 0 , sizeof(fds));
David Reiss22b18862008-04-08 06:25:45 +0000243 fds[0].fd = socket_;
244 fds[0].events = POLLOUT;
245 ret = poll(fds, 1, connTimeout_);
Mark Slee29050782006-09-29 00:12:30 +0000246
247 if (ret > 0) {
David Reiss9b209552008-04-08 06:26:05 +0000248 // Ensure the socket is connected and that there are no errors set
Mark Slee29050782006-09-29 00:12:30 +0000249 int val;
250 socklen_t lon;
251 lon = sizeof(int);
252 int ret2 = getsockopt(socket_, SOL_SOCKET, SO_ERROR, (void *)&val, &lon);
253 if (ret2 == -1) {
David Reissbc3dddb2007-08-22 23:20:24 +0000254 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000255 GlobalOutput.perror("TSocket::open() getsockopt() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000256 throw TTransportException(TTransportException::NOT_OPEN, "getsockopt()", errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000257 }
David Reiss9b209552008-04-08 06:26:05 +0000258 // no errors on socket, go to town
Mark Slee29050782006-09-29 00:12:30 +0000259 if (val == 0) {
260 goto done;
261 }
David Reiss01e55c12008-07-13 22:18:51 +0000262 GlobalOutput.perror("TSocket::open() error on socket (after poll) " + getSocketInfo(), val);
David Reiss9b209552008-04-08 06:26:05 +0000263 throw TTransportException(TTransportException::NOT_OPEN, "socket open() error", val);
Mark Slee29050782006-09-29 00:12:30 +0000264 } else if (ret == 0) {
David Reiss9b209552008-04-08 06:26:05 +0000265 // socket timed out
Aditya Agarwal4529c4b2007-09-05 01:01:15 +0000266 string errStr = "TSocket::open() timed out " + getSocketInfo();
267 GlobalOutput(errStr.c_str());
David Reiss9b209552008-04-08 06:26:05 +0000268 throw TTransportException(TTransportException::NOT_OPEN, "open() timed out");
Mark Slee29050782006-09-29 00:12:30 +0000269 } else {
David Reiss9b209552008-04-08 06:26:05 +0000270 // error on poll()
David Reissbc3dddb2007-08-22 23:20:24 +0000271 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000272 GlobalOutput.perror("TSocket::open() poll() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000273 throw TTransportException(TTransportException::NOT_OPEN, "poll() failed", errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000274 }
275
276 done:
277 // Set socket back to normal mode (blocking)
278 fcntl(socket_, F_SETFL, flags);
David Reiss23248712010-10-06 17:10:08 +0000279
Roger Meier18f10502011-06-04 08:57:43 +0000280 if (path_.empty()) {
281 setCachedAddress(res->ai_addr, res->ai_addrlen);
282 }
Mark Sleee8540632006-05-30 09:24:40 +0000283}
284
Mark Slee6d56eb92007-07-06 22:28:15 +0000285void TSocket::open() {
286 if (isOpen()) {
Bryan Duxbury010f1e02010-09-02 00:56:53 +0000287 return;
Mark Slee6d56eb92007-07-06 22:28:15 +0000288 }
Bryan Duxburya18364a2010-09-28 14:36:07 +0000289 if (! path_.empty()) {
290 unix_open();
291 } else {
292 local_open();
293 }
294}
295
296void TSocket::unix_open(){
297 if (! path_.empty()) {
298 // Unix Domain SOcket does not need addrinfo struct, so we pass NULL
299 openConnection(NULL);
300 }
301}
302
303void TSocket::local_open(){
304 if (isOpen()) {
305 return;
306 }
Mark Slee6d56eb92007-07-06 22:28:15 +0000307
308 // Validate port number
David Reiss450e35d2010-03-09 05:19:41 +0000309 if (port_ < 0 || port_ > 0xFFFF) {
Mark Slee6d56eb92007-07-06 22:28:15 +0000310 throw TTransportException(TTransportException::NOT_OPEN, "Specified port is invalid");
311 }
312
313 struct addrinfo hints, *res, *res0;
David Reiss9b209552008-04-08 06:26:05 +0000314 res = NULL;
315 res0 = NULL;
Mark Slee6d56eb92007-07-06 22:28:15 +0000316 int error;
David Reiss450e35d2010-03-09 05:19:41 +0000317 char port[sizeof("65535")];
David Reissc88eb8c2008-06-11 01:18:54 +0000318 std::memset(&hints, 0, sizeof(hints));
Mark Slee6d56eb92007-07-06 22:28:15 +0000319 hints.ai_family = PF_UNSPEC;
320 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000321 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Slee6d56eb92007-07-06 22:28:15 +0000322 sprintf(port, "%d", port_);
Mark Slee256bdc42007-11-27 08:42:19 +0000323
Mark Sleec37b4c52007-12-05 23:03:37 +0000324 error = getaddrinfo(host_.c_str(), port, &hints, &res0);
325
Mark Slee6d56eb92007-07-06 22:28:15 +0000326 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000327 string errStr = "TSocket::open() getaddrinfo() " + getSocketInfo() + string(gai_strerror(error));
328 GlobalOutput(errStr.c_str());
Mark Slee6d56eb92007-07-06 22:28:15 +0000329 close();
330 throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for client socket.");
331 }
Mark Slee256bdc42007-11-27 08:42:19 +0000332
Mark Slee6d56eb92007-07-06 22:28:15 +0000333 // Cycle through all the returned addresses until one
334 // connects or push the exception up.
335 for (res = res0; res; res = res->ai_next) {
336 try {
337 openConnection(res);
338 break;
339 } catch (TTransportException& ttx) {
340 if (res->ai_next) {
341 close();
342 } else {
343 close();
Mark Slee85287d32007-07-09 19:50:30 +0000344 freeaddrinfo(res0); // cleanup on failure
Mark Slee6d56eb92007-07-06 22:28:15 +0000345 throw;
346 }
347 }
348 }
Mark Slee85287d32007-07-09 19:50:30 +0000349
350 // Free address structure memory
351 freeaddrinfo(res0);
Mark Slee6d56eb92007-07-06 22:28:15 +0000352}
353
Mark Sleee8540632006-05-30 09:24:40 +0000354void TSocket::close() {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000355 if (socket_ >= 0) {
Mark Sleee8540632006-05-30 09:24:40 +0000356 shutdown(socket_, SHUT_RDWR);
357 ::close(socket_);
358 }
Martin Kraemeree341cb2007-02-05 21:40:38 +0000359 socket_ = -1;
Mark Sleee8540632006-05-30 09:24:40 +0000360}
361
David Reiss105961d2010-10-06 17:10:17 +0000362void TSocket::setSocketFD(int socket) {
363 if (socket_ >= 0) {
364 close();
365 }
366 socket_ = socket;
367}
368
Mark Slee8d7e1f62006-06-07 06:48:56 +0000369uint32_t TSocket::read(uint8_t* buf, uint32_t len) {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000370 if (socket_ < 0) {
Mark Sleef9831082007-02-20 20:59:21 +0000371 throw TTransportException(TTransportException::NOT_OPEN, "Called read on non-open socket");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000372 }
Mark Sleee8540632006-05-30 09:24:40 +0000373
Aditya Agarwale04475b2007-05-23 02:14:58 +0000374 int32_t retries = 0;
375
376 // EAGAIN can be signalled both when a timeout has occurred and when
377 // the system is out of resources (an awesome undocumented feature).
378 // The following is an approximation of the time interval under which
379 // EAGAIN is taken to indicate an out of resources error.
380 uint32_t eagainThresholdMicros = 0;
381 if (recvTimeout_) {
Mark Slee256bdc42007-11-27 08:42:19 +0000382 // if a readTimeout is specified along with a max number of recv retries, then
Aditya Agarwale04475b2007-05-23 02:14:58 +0000383 // the threshold will ensure that the read timeout is not exceeded even in the
384 // case of resource errors
385 eagainThresholdMicros = (recvTimeout_*1000)/ ((maxRecvRetries_>0) ? maxRecvRetries_ : 2);
386 }
387
Mark Slee256bdc42007-11-27 08:42:19 +0000388 try_again:
Mark Slee8d7e1f62006-06-07 06:48:56 +0000389 // Read from the socket
Aditya Agarwale04475b2007-05-23 02:14:58 +0000390 struct timeval begin;
David Reiss105961d2010-10-06 17:10:17 +0000391 if (recvTimeout_ > 0) {
392 gettimeofday(&begin, NULL);
393 } else {
394 // if there is no read timeout we don't need the TOD to determine whether
395 // an EAGAIN is due to a timeout or an out-of-resource condition.
396 begin.tv_sec = begin.tv_usec = 0;
397 }
Mark Slee8d7e1f62006-06-07 06:48:56 +0000398 int got = recv(socket_, buf, len, 0);
Kevin Clark022b2242009-03-05 21:05:37 +0000399 int errno_copy = errno; //gettimeofday can change errno
Mark Slee8d7e1f62006-06-07 06:48:56 +0000400 ++g_socket_syscalls;
Aditya Agarwale04475b2007-05-23 02:14:58 +0000401
Mark Slee8d7e1f62006-06-07 06:48:56 +0000402 // Check for error on read
Mark Slee256bdc42007-11-27 08:42:19 +0000403 if (got < 0) {
Kevin Clark022b2242009-03-05 21:05:37 +0000404 if (errno_copy == EAGAIN) {
David Reiss105961d2010-10-06 17:10:17 +0000405 // if no timeout we can assume that resource exhaustion has occurred.
406 if (recvTimeout_ == 0) {
407 throw TTransportException(TTransportException::TIMED_OUT,
408 "EAGAIN (unavailable resources)");
409 }
Aditya Agarwale04475b2007-05-23 02:14:58 +0000410 // check if this is the lack of resources or timeout case
David Reissa1a15112010-03-09 05:19:54 +0000411 struct timeval end;
412 gettimeofday(&end, NULL);
413 uint32_t readElapsedMicros = (((end.tv_sec - begin.tv_sec) * 1000 * 1000)
414 + (((uint64_t)(end.tv_usec - begin.tv_usec))));
415
Aditya Agarwale04475b2007-05-23 02:14:58 +0000416 if (!eagainThresholdMicros || (readElapsedMicros < eagainThresholdMicros)) {
417 if (retries++ < maxRecvRetries_) {
418 usleep(50);
419 goto try_again;
420 } else {
Mark Slee256bdc42007-11-27 08:42:19 +0000421 throw TTransportException(TTransportException::TIMED_OUT,
Aditya Agarwale04475b2007-05-23 02:14:58 +0000422 "EAGAIN (unavailable resources)");
423 }
424 } else {
425 // infer that timeout has been hit
Mark Slee256bdc42007-11-27 08:42:19 +0000426 throw TTransportException(TTransportException::TIMED_OUT,
Aditya Agarwale04475b2007-05-23 02:14:58 +0000427 "EAGAIN (timed out)");
428 }
Mark Sleee8540632006-05-30 09:24:40 +0000429 }
Mark Slee256bdc42007-11-27 08:42:19 +0000430
Mark Slee8d7e1f62006-06-07 06:48:56 +0000431 // If interrupted, try again
Kevin Clark022b2242009-03-05 21:05:37 +0000432 if (errno_copy == EINTR && retries++ < maxRecvRetries_) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000433 goto try_again;
Mark Sleee8540632006-05-30 09:24:40 +0000434 }
Mark Slee256bdc42007-11-27 08:42:19 +0000435
David Reiss840e7522009-06-04 00:10:50 +0000436 #if defined __FreeBSD__ || defined __MACH__
Kevin Clark022b2242009-03-05 21:05:37 +0000437 if (errno_copy == ECONNRESET) {
Kevin Clark022b2242009-03-05 21:05:37 +0000438 /* shigin: freebsd doesn't follow POSIX semantic of recv and fails with
439 * ECONNRESET if peer performed shutdown
David Reiss105961d2010-10-06 17:10:17 +0000440 * edhall: eliminated close() since we do that in the destructor.
Kevin Clark022b2242009-03-05 21:05:37 +0000441 */
Kevin Clark022b2242009-03-05 21:05:37 +0000442 return 0;
David Reiss840e7522009-06-04 00:10:50 +0000443 }
444 #endif
445
446 // Now it's not a try again case, but a real probblez
447 GlobalOutput.perror("TSocket::read() recv() " + getSocketInfo(), errno_copy);
448
449 // If we disconnect with no linger time
450 if (errno_copy == ECONNRESET) {
Mark Sleef9831082007-02-20 20:59:21 +0000451 throw TTransportException(TTransportException::NOT_OPEN, "ECONNRESET");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000452 }
Mark Slee256bdc42007-11-27 08:42:19 +0000453
Mark Slee8d7e1f62006-06-07 06:48:56 +0000454 // This ish isn't open
Kevin Clark022b2242009-03-05 21:05:37 +0000455 if (errno_copy == ENOTCONN) {
Mark Sleef9831082007-02-20 20:59:21 +0000456 throw TTransportException(TTransportException::NOT_OPEN, "ENOTCONN");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000457 }
Mark Slee256bdc42007-11-27 08:42:19 +0000458
Mark Slee8d7e1f62006-06-07 06:48:56 +0000459 // Timed out!
Kevin Clark022b2242009-03-05 21:05:37 +0000460 if (errno_copy == ETIMEDOUT) {
Mark Sleef9831082007-02-20 20:59:21 +0000461 throw TTransportException(TTransportException::TIMED_OUT, "ETIMEDOUT");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000462 }
Mark Slee256bdc42007-11-27 08:42:19 +0000463
Mark Slee8d7e1f62006-06-07 06:48:56 +0000464 // Some other error, whatevz
David Reiss01e55c12008-07-13 22:18:51 +0000465 throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000466 }
Mark Slee256bdc42007-11-27 08:42:19 +0000467
Mark Slee8d7e1f62006-06-07 06:48:56 +0000468 // The remote host has closed the socket
469 if (got == 0) {
David Reiss105961d2010-10-06 17:10:17 +0000470 // edhall: we used to call close() here, but our caller may want to deal
471 // with the socket fd and we'll close() in our destructor in any case.
Mark Slee8d7e1f62006-06-07 06:48:56 +0000472 return 0;
Mark Sleee8540632006-05-30 09:24:40 +0000473 }
Mark Slee256bdc42007-11-27 08:42:19 +0000474
Mark Sleee8540632006-05-30 09:24:40 +0000475 // Pack data into string
Mark Slee8d7e1f62006-06-07 06:48:56 +0000476 return got;
Mark Sleee8540632006-05-30 09:24:40 +0000477}
478
Mark Slee8d7e1f62006-06-07 06:48:56 +0000479void TSocket::write(const uint8_t* buf, uint32_t len) {
David Reiss105961d2010-10-06 17:10:17 +0000480 uint32_t sent = 0;
481
482 while (sent < len) {
483 uint32_t b = write_partial(buf + sent, len - sent);
484 if (b == 0) {
485 // We assume that we got 0 because send() errored with EAGAIN due to
486 // lack of system resources; release the CPU for a bit.
487 usleep(50);
488 }
489 sent += b;
490 }
491}
492
493uint32_t TSocket::write_partial(const uint8_t* buf, uint32_t len) {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000494 if (socket_ < 0) {
Mark Sleef9831082007-02-20 20:59:21 +0000495 throw TTransportException(TTransportException::NOT_OPEN, "Called write on non-open socket");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000496 }
497
Mark Sleee8540632006-05-30 09:24:40 +0000498 uint32_t sent = 0;
Mark Slee256bdc42007-11-27 08:42:19 +0000499
David Reiss105961d2010-10-06 17:10:17 +0000500 int flags = 0;
501#ifdef MSG_NOSIGNAL
502 // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
503 // check for the EPIPE return condition and close the socket in that case
504 flags |= MSG_NOSIGNAL;
505#endif // ifdef MSG_NOSIGNAL
Marc Slemko9d4a3e22006-07-21 19:53:48 +0000506
David Reiss105961d2010-10-06 17:10:17 +0000507 int b = send(socket_, buf + sent, len - sent, flags);
508 ++g_socket_syscalls;
Marc Slemko9d4a3e22006-07-21 19:53:48 +0000509
David Reiss105961d2010-10-06 17:10:17 +0000510 if (b < 0) {
511 if (errno == EWOULDBLOCK || errno == EAGAIN) {
512 return 0;
513 }
Mark Sleee8540632006-05-30 09:24:40 +0000514 // Fail on a send error
David Reiss105961d2010-10-06 17:10:17 +0000515 int errno_copy = errno;
516 GlobalOutput.perror("TSocket::write_partial() send() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000517
David Reiss105961d2010-10-06 17:10:17 +0000518 if (errno_copy == EPIPE || errno_copy == ECONNRESET || errno_copy == ENOTCONN) {
519 close();
520 throw TTransportException(TTransportException::NOT_OPEN, "write() send()", errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000521 }
Mark Slee256bdc42007-11-27 08:42:19 +0000522
David Reiss105961d2010-10-06 17:10:17 +0000523 throw TTransportException(TTransportException::UNKNOWN, "write() send()", errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000524 }
David Reiss105961d2010-10-06 17:10:17 +0000525
526 // Fail on blocked send
527 if (b == 0) {
528 throw TTransportException(TTransportException::NOT_OPEN, "Socket send returned 0.");
529 }
530 return b;
Mark Sleee8540632006-05-30 09:24:40 +0000531}
532
dweatherford14b0ed62007-10-19 01:03:32 +0000533std::string TSocket::getHost() {
534 return host_;
535}
536
537int TSocket::getPort() {
538 return port_;
539}
540
Aditya Agarwalebc99e02007-01-15 23:14:58 +0000541void TSocket::setHost(string host) {
542 host_ = host;
543}
544
545void TSocket::setPort(int port) {
546 port_ = port;
547}
548
Mark Slee8d7e1f62006-06-07 06:48:56 +0000549void TSocket::setLinger(bool on, int linger) {
Mark Slee29050782006-09-29 00:12:30 +0000550 lingerOn_ = on;
551 lingerVal_ = linger;
Martin Kraemeree341cb2007-02-05 21:40:38 +0000552 if (socket_ < 0) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000553 return;
554 }
555
Mark Slee29050782006-09-29 00:12:30 +0000556 struct linger l = {(lingerOn_ ? 1 : 0), lingerVal_};
557 int ret = setsockopt(socket_, SOL_SOCKET, SO_LINGER, &l, sizeof(l));
558 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000559 int errno_copy = errno; // Copy errno because we're allocating memory.
560 GlobalOutput.perror("TSocket::setLinger() setsockopt() " + getSocketInfo(), errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000561 }
Mark Sleee8540632006-05-30 09:24:40 +0000562}
563
Mark Slee8d7e1f62006-06-07 06:48:56 +0000564void TSocket::setNoDelay(bool noDelay) {
Mark Slee29050782006-09-29 00:12:30 +0000565 noDelay_ = noDelay;
Roger Meier18f10502011-06-04 08:57:43 +0000566 if (socket_ < 0 || !path_.empty()) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000567 return;
568 }
569
Mark Sleee8540632006-05-30 09:24:40 +0000570 // Set socket to NODELAY
Mark Slee29050782006-09-29 00:12:30 +0000571 int v = noDelay_ ? 1 : 0;
572 int ret = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
573 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000574 int errno_copy = errno; // Copy errno because we're allocating memory.
575 GlobalOutput.perror("TSocket::setNoDelay() setsockopt() " + getSocketInfo(), errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000576 }
Mark Sleee8540632006-05-30 09:24:40 +0000577}
Mark Slee29050782006-09-29 00:12:30 +0000578
579void TSocket::setConnTimeout(int ms) {
580 connTimeout_ = ms;
581}
582
583void TSocket::setRecvTimeout(int ms) {
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000584 if (ms < 0) {
585 char errBuf[512];
586 sprintf(errBuf, "TSocket::setRecvTimeout with negative input: %d\n", ms);
587 GlobalOutput(errBuf);
588 return;
589 }
Mark Slee29050782006-09-29 00:12:30 +0000590 recvTimeout_ = ms;
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000591
Martin Kraemeree341cb2007-02-05 21:40:38 +0000592 if (socket_ < 0) {
Mark Slee29050782006-09-29 00:12:30 +0000593 return;
594 }
595
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000596 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
597 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
598
David Reiss22b18862008-04-08 06:25:45 +0000599 // Copy because poll may modify
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000600 struct timeval r = recvTimeval_;
Mark Slee29050782006-09-29 00:12:30 +0000601 int ret = setsockopt(socket_, SOL_SOCKET, SO_RCVTIMEO, &r, sizeof(r));
602 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000603 int errno_copy = errno; // Copy errno because we're allocating memory.
604 GlobalOutput.perror("TSocket::setRecvTimeout() setsockopt() " + getSocketInfo(), errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000605 }
606}
607
608void TSocket::setSendTimeout(int ms) {
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000609 if (ms < 0) {
610 char errBuf[512];
611 sprintf(errBuf, "TSocket::setSendTimeout with negative input: %d\n", ms);
612 GlobalOutput(errBuf);
613 return;
614 }
Mark Slee29050782006-09-29 00:12:30 +0000615 sendTimeout_ = ms;
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000616
Martin Kraemeree341cb2007-02-05 21:40:38 +0000617 if (socket_ < 0) {
Mark Slee29050782006-09-29 00:12:30 +0000618 return;
619 }
Mark Slee256bdc42007-11-27 08:42:19 +0000620
Mark Slee29050782006-09-29 00:12:30 +0000621 struct timeval s = {(int)(sendTimeout_/1000),
622 (int)((sendTimeout_%1000)*1000)};
623 int ret = setsockopt(socket_, SOL_SOCKET, SO_SNDTIMEO, &s, sizeof(s));
624 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000625 int errno_copy = errno; // Copy errno because we're allocating memory.
626 GlobalOutput.perror("TSocket::setSendTimeout() setsockopt() " + getSocketInfo(), errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000627 }
628}
629
Aditya Agarwale04475b2007-05-23 02:14:58 +0000630void TSocket::setMaxRecvRetries(int maxRecvRetries) {
631 maxRecvRetries_ = maxRecvRetries;
632}
633
Aditya Agarwal4529c4b2007-09-05 01:01:15 +0000634string TSocket::getSocketInfo() {
635 std::ostringstream oss;
David Reiss105961d2010-10-06 17:10:17 +0000636 if (host_.empty() || port_ == 0) {
637 oss << "<Host: " << getPeerAddress();
638 oss << " Port: " << getPeerPort() << ">";
639 } else {
640 oss << "<Host: " << host_ << " Port: " << port_ << ">";
641 }
Aditya Agarwal4529c4b2007-09-05 01:01:15 +0000642 return oss.str();
643}
644
Mark Sleeb4552922007-11-28 00:12:11 +0000645std::string TSocket::getPeerHost() {
Roger Meier18f10502011-06-04 08:57:43 +0000646 if (peerHost_.empty() && path_.empty()) {
Mark Sleeb4552922007-11-28 00:12:11 +0000647 struct sockaddr_storage addr;
David Reiss23248712010-10-06 17:10:08 +0000648 struct sockaddr* addrPtr;
649 socklen_t addrLen;
Mark Sleeb4552922007-11-28 00:12:11 +0000650
651 if (socket_ < 0) {
652 return host_;
653 }
654
David Reiss23248712010-10-06 17:10:08 +0000655 addrPtr = getCachedAddress(&addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000656
David Reiss23248712010-10-06 17:10:08 +0000657 if (addrPtr == NULL) {
658 addrLen = sizeof(addr);
659 if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
660 return peerHost_;
661 }
662 addrPtr = (sockaddr*)&addr;
663
664 setCachedAddress(addrPtr, addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000665 }
666
667 char clienthost[NI_MAXHOST];
668 char clientservice[NI_MAXSERV];
669
David Reiss23248712010-10-06 17:10:08 +0000670 getnameinfo((sockaddr*) addrPtr, addrLen,
Mark Sleeb4552922007-11-28 00:12:11 +0000671 clienthost, sizeof(clienthost),
672 clientservice, sizeof(clientservice), 0);
673
674 peerHost_ = clienthost;
675 }
676 return peerHost_;
677}
678
679std::string TSocket::getPeerAddress() {
Roger Meier18f10502011-06-04 08:57:43 +0000680 if (peerAddress_.empty() && path_.empty()) {
Mark Sleeb4552922007-11-28 00:12:11 +0000681 struct sockaddr_storage addr;
David Reiss23248712010-10-06 17:10:08 +0000682 struct sockaddr* addrPtr;
683 socklen_t addrLen;
Mark Sleeb4552922007-11-28 00:12:11 +0000684
685 if (socket_ < 0) {
686 return peerAddress_;
687 }
688
David Reiss23248712010-10-06 17:10:08 +0000689 addrPtr = getCachedAddress(&addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000690
David Reiss23248712010-10-06 17:10:08 +0000691 if (addrPtr == NULL) {
692 addrLen = sizeof(addr);
693 if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
694 return peerAddress_;
695 }
696 addrPtr = (sockaddr*)&addr;
697
698 setCachedAddress(addrPtr, addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000699 }
700
701 char clienthost[NI_MAXHOST];
702 char clientservice[NI_MAXSERV];
703
David Reiss23248712010-10-06 17:10:08 +0000704 getnameinfo(addrPtr, addrLen,
Mark Sleeb4552922007-11-28 00:12:11 +0000705 clienthost, sizeof(clienthost),
706 clientservice, sizeof(clientservice),
707 NI_NUMERICHOST|NI_NUMERICSERV);
708
709 peerAddress_ = clienthost;
710 peerPort_ = std::atoi(clientservice);
711 }
712 return peerAddress_;
713}
714
715int TSocket::getPeerPort() {
716 getPeerAddress();
717 return peerPort_;
718}
719
David Reiss23248712010-10-06 17:10:08 +0000720void TSocket::setCachedAddress(const sockaddr* addr, socklen_t len) {
Roger Meier18f10502011-06-04 08:57:43 +0000721 if (!path_.empty()) {
722 return;
723 }
724
David Reiss23248712010-10-06 17:10:08 +0000725 switch (addr->sa_family) {
726 case AF_INET:
727 if (len == sizeof(sockaddr_in)) {
728 memcpy((void*)&cachedPeerAddr_.ipv4, (void*)addr, len);
729 }
730 break;
731
732 case AF_INET6:
733 if (len == sizeof(sockaddr_in6)) {
734 memcpy((void*)&cachedPeerAddr_.ipv6, (void*)addr, len);
735 }
736 break;
737 }
738}
739
740sockaddr* TSocket::getCachedAddress(socklen_t* len) const {
741 switch (cachedPeerAddr_.ipv4.sin_family) {
742 case AF_INET:
743 *len = sizeof(sockaddr_in);
744 return (sockaddr*) &cachedPeerAddr_.ipv4;
745
746 case AF_INET6:
747 *len = sizeof(sockaddr_in6);
748 return (sockaddr*) &cachedPeerAddr_.ipv6;
749
750 default:
751 return NULL;
752 }
753}
754
David Reiss1c20c872010-03-09 05:20:14 +0000755bool TSocket::useLowMinRto_ = false;
756void TSocket::setUseLowMinRto(bool useLowMinRto) {
757 useLowMinRto_ = useLowMinRto;
758}
759bool TSocket::getUseLowMinRto() {
760 return useLowMinRto_;
761}
762
T Jake Lucianib5e62212009-01-31 22:36:20 +0000763}}} // apache::thrift::transport