blob: ee76c3fe94658312b1265a665050c7beb22e21da [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;
222 sprintf(address.sun_path, path_.c_str());
223 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
280 setCachedAddress(res->ai_addr, res->ai_addrlen);
Mark Sleee8540632006-05-30 09:24:40 +0000281}
282
Mark Slee6d56eb92007-07-06 22:28:15 +0000283void TSocket::open() {
284 if (isOpen()) {
Bryan Duxbury010f1e02010-09-02 00:56:53 +0000285 return;
Mark Slee6d56eb92007-07-06 22:28:15 +0000286 }
Bryan Duxburya18364a2010-09-28 14:36:07 +0000287 if (! path_.empty()) {
288 unix_open();
289 } else {
290 local_open();
291 }
292}
293
294void TSocket::unix_open(){
295 if (! path_.empty()) {
296 // Unix Domain SOcket does not need addrinfo struct, so we pass NULL
297 openConnection(NULL);
298 }
299}
300
301void TSocket::local_open(){
302 if (isOpen()) {
303 return;
304 }
Mark Slee6d56eb92007-07-06 22:28:15 +0000305
306 // Validate port number
David Reiss450e35d2010-03-09 05:19:41 +0000307 if (port_ < 0 || port_ > 0xFFFF) {
Mark Slee6d56eb92007-07-06 22:28:15 +0000308 throw TTransportException(TTransportException::NOT_OPEN, "Specified port is invalid");
309 }
310
311 struct addrinfo hints, *res, *res0;
David Reiss9b209552008-04-08 06:26:05 +0000312 res = NULL;
313 res0 = NULL;
Mark Slee6d56eb92007-07-06 22:28:15 +0000314 int error;
David Reiss450e35d2010-03-09 05:19:41 +0000315 char port[sizeof("65535")];
David Reissc88eb8c2008-06-11 01:18:54 +0000316 std::memset(&hints, 0, sizeof(hints));
Mark Slee6d56eb92007-07-06 22:28:15 +0000317 hints.ai_family = PF_UNSPEC;
318 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000319 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Slee6d56eb92007-07-06 22:28:15 +0000320 sprintf(port, "%d", port_);
Mark Slee256bdc42007-11-27 08:42:19 +0000321
Mark Sleec37b4c52007-12-05 23:03:37 +0000322 error = getaddrinfo(host_.c_str(), port, &hints, &res0);
323
Mark Slee6d56eb92007-07-06 22:28:15 +0000324 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000325 string errStr = "TSocket::open() getaddrinfo() " + getSocketInfo() + string(gai_strerror(error));
326 GlobalOutput(errStr.c_str());
Mark Slee6d56eb92007-07-06 22:28:15 +0000327 close();
328 throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for client socket.");
329 }
Mark Slee256bdc42007-11-27 08:42:19 +0000330
Mark Slee6d56eb92007-07-06 22:28:15 +0000331 // Cycle through all the returned addresses until one
332 // connects or push the exception up.
333 for (res = res0; res; res = res->ai_next) {
334 try {
335 openConnection(res);
336 break;
337 } catch (TTransportException& ttx) {
338 if (res->ai_next) {
339 close();
340 } else {
341 close();
Mark Slee85287d32007-07-09 19:50:30 +0000342 freeaddrinfo(res0); // cleanup on failure
Mark Slee6d56eb92007-07-06 22:28:15 +0000343 throw;
344 }
345 }
346 }
Mark Slee85287d32007-07-09 19:50:30 +0000347
348 // Free address structure memory
349 freeaddrinfo(res0);
Mark Slee6d56eb92007-07-06 22:28:15 +0000350}
351
Mark Sleee8540632006-05-30 09:24:40 +0000352void TSocket::close() {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000353 if (socket_ >= 0) {
Mark Sleee8540632006-05-30 09:24:40 +0000354 shutdown(socket_, SHUT_RDWR);
355 ::close(socket_);
356 }
Martin Kraemeree341cb2007-02-05 21:40:38 +0000357 socket_ = -1;
Mark Sleee8540632006-05-30 09:24:40 +0000358}
359
Mark Slee8d7e1f62006-06-07 06:48:56 +0000360uint32_t TSocket::read(uint8_t* buf, uint32_t len) {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000361 if (socket_ < 0) {
Mark Sleef9831082007-02-20 20:59:21 +0000362 throw TTransportException(TTransportException::NOT_OPEN, "Called read on non-open socket");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000363 }
Mark Sleee8540632006-05-30 09:24:40 +0000364
Aditya Agarwale04475b2007-05-23 02:14:58 +0000365 int32_t retries = 0;
366
367 // EAGAIN can be signalled both when a timeout has occurred and when
368 // the system is out of resources (an awesome undocumented feature).
369 // The following is an approximation of the time interval under which
370 // EAGAIN is taken to indicate an out of resources error.
371 uint32_t eagainThresholdMicros = 0;
372 if (recvTimeout_) {
Mark Slee256bdc42007-11-27 08:42:19 +0000373 // if a readTimeout is specified along with a max number of recv retries, then
Aditya Agarwale04475b2007-05-23 02:14:58 +0000374 // the threshold will ensure that the read timeout is not exceeded even in the
375 // case of resource errors
376 eagainThresholdMicros = (recvTimeout_*1000)/ ((maxRecvRetries_>0) ? maxRecvRetries_ : 2);
377 }
378
Mark Slee256bdc42007-11-27 08:42:19 +0000379 try_again:
Mark Slee8d7e1f62006-06-07 06:48:56 +0000380 // Read from the socket
Aditya Agarwale04475b2007-05-23 02:14:58 +0000381 struct timeval begin;
382 gettimeofday(&begin, NULL);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000383 int got = recv(socket_, buf, len, 0);
Kevin Clark022b2242009-03-05 21:05:37 +0000384 int errno_copy = errno; //gettimeofday can change errno
Mark Slee8d7e1f62006-06-07 06:48:56 +0000385 ++g_socket_syscalls;
Aditya Agarwale04475b2007-05-23 02:14:58 +0000386
Mark Slee8d7e1f62006-06-07 06:48:56 +0000387 // Check for error on read
Mark Slee256bdc42007-11-27 08:42:19 +0000388 if (got < 0) {
Kevin Clark022b2242009-03-05 21:05:37 +0000389 if (errno_copy == EAGAIN) {
Aditya Agarwale04475b2007-05-23 02:14:58 +0000390 // check if this is the lack of resources or timeout case
David Reissa1a15112010-03-09 05:19:54 +0000391 struct timeval end;
392 gettimeofday(&end, NULL);
393 uint32_t readElapsedMicros = (((end.tv_sec - begin.tv_sec) * 1000 * 1000)
394 + (((uint64_t)(end.tv_usec - begin.tv_usec))));
395
Aditya Agarwale04475b2007-05-23 02:14:58 +0000396 if (!eagainThresholdMicros || (readElapsedMicros < eagainThresholdMicros)) {
397 if (retries++ < maxRecvRetries_) {
398 usleep(50);
399 goto try_again;
400 } else {
Mark Slee256bdc42007-11-27 08:42:19 +0000401 throw TTransportException(TTransportException::TIMED_OUT,
Aditya Agarwale04475b2007-05-23 02:14:58 +0000402 "EAGAIN (unavailable resources)");
403 }
404 } else {
405 // infer that timeout has been hit
Mark Slee256bdc42007-11-27 08:42:19 +0000406 throw TTransportException(TTransportException::TIMED_OUT,
Aditya Agarwale04475b2007-05-23 02:14:58 +0000407 "EAGAIN (timed out)");
408 }
Mark Sleee8540632006-05-30 09:24:40 +0000409 }
Mark Slee256bdc42007-11-27 08:42:19 +0000410
Mark Slee8d7e1f62006-06-07 06:48:56 +0000411 // If interrupted, try again
Kevin Clark022b2242009-03-05 21:05:37 +0000412 if (errno_copy == EINTR && retries++ < maxRecvRetries_) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000413 goto try_again;
Mark Sleee8540632006-05-30 09:24:40 +0000414 }
Mark Slee256bdc42007-11-27 08:42:19 +0000415
David Reiss840e7522009-06-04 00:10:50 +0000416 #if defined __FreeBSD__ || defined __MACH__
Kevin Clark022b2242009-03-05 21:05:37 +0000417 if (errno_copy == ECONNRESET) {
Kevin Clark022b2242009-03-05 21:05:37 +0000418 /* shigin: freebsd doesn't follow POSIX semantic of recv and fails with
419 * ECONNRESET if peer performed shutdown
420 */
421 close();
422 return 0;
David Reiss840e7522009-06-04 00:10:50 +0000423 }
424 #endif
425
426 // Now it's not a try again case, but a real probblez
427 GlobalOutput.perror("TSocket::read() recv() " + getSocketInfo(), errno_copy);
428
429 // If we disconnect with no linger time
430 if (errno_copy == ECONNRESET) {
Mark Sleef9831082007-02-20 20:59:21 +0000431 throw TTransportException(TTransportException::NOT_OPEN, "ECONNRESET");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000432 }
Mark Slee256bdc42007-11-27 08:42:19 +0000433
Mark Slee8d7e1f62006-06-07 06:48:56 +0000434 // This ish isn't open
Kevin Clark022b2242009-03-05 21:05:37 +0000435 if (errno_copy == ENOTCONN) {
Mark Sleef9831082007-02-20 20:59:21 +0000436 throw TTransportException(TTransportException::NOT_OPEN, "ENOTCONN");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000437 }
Mark Slee256bdc42007-11-27 08:42:19 +0000438
Mark Slee8d7e1f62006-06-07 06:48:56 +0000439 // Timed out!
Kevin Clark022b2242009-03-05 21:05:37 +0000440 if (errno_copy == ETIMEDOUT) {
Mark Sleef9831082007-02-20 20:59:21 +0000441 throw TTransportException(TTransportException::TIMED_OUT, "ETIMEDOUT");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000442 }
Mark Slee256bdc42007-11-27 08:42:19 +0000443
Mark Slee8d7e1f62006-06-07 06:48:56 +0000444 // Some other error, whatevz
David Reiss01e55c12008-07-13 22:18:51 +0000445 throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000446 }
Mark Slee256bdc42007-11-27 08:42:19 +0000447
Mark Slee8d7e1f62006-06-07 06:48:56 +0000448 // The remote host has closed the socket
449 if (got == 0) {
450 close();
451 return 0;
Mark Sleee8540632006-05-30 09:24:40 +0000452 }
Mark Slee256bdc42007-11-27 08:42:19 +0000453
Mark Sleee8540632006-05-30 09:24:40 +0000454 // Pack data into string
Mark Slee8d7e1f62006-06-07 06:48:56 +0000455 return got;
Mark Sleee8540632006-05-30 09:24:40 +0000456}
457
Mark Slee8d7e1f62006-06-07 06:48:56 +0000458void TSocket::write(const uint8_t* buf, uint32_t len) {
Martin Kraemeree341cb2007-02-05 21:40:38 +0000459 if (socket_ < 0) {
Mark Sleef9831082007-02-20 20:59:21 +0000460 throw TTransportException(TTransportException::NOT_OPEN, "Called write on non-open socket");
Mark Slee8d7e1f62006-06-07 06:48:56 +0000461 }
462
Mark Sleee8540632006-05-30 09:24:40 +0000463 uint32_t sent = 0;
Mark Slee256bdc42007-11-27 08:42:19 +0000464
Mark Slee8d7e1f62006-06-07 06:48:56 +0000465 while (sent < len) {
Marc Slemko9d4a3e22006-07-21 19:53:48 +0000466
467 int flags = 0;
Mark Slee29050782006-09-29 00:12:30 +0000468 #ifdef MSG_NOSIGNAL
Mark Slee8d7e1f62006-06-07 06:48:56 +0000469 // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
470 // check for the EPIPE return condition and close the socket in that case
Marc Slemko9d4a3e22006-07-21 19:53:48 +0000471 flags |= MSG_NOSIGNAL;
Mark Slee29050782006-09-29 00:12:30 +0000472 #endif // ifdef MSG_NOSIGNAL
Marc Slemko9d4a3e22006-07-21 19:53:48 +0000473
474 int b = send(socket_, buf + sent, len - sent, flags);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000475 ++g_socket_syscalls;
476
Mark Sleee8540632006-05-30 09:24:40 +0000477 // Fail on a send error
478 if (b < 0) {
David Reiss9b209552008-04-08 06:26:05 +0000479 int errno_copy = errno;
David Reiss01e55c12008-07-13 22:18:51 +0000480 GlobalOutput.perror("TSocket::write() send() " + getSocketInfo(), errno_copy);
David Reiss9b209552008-04-08 06:26:05 +0000481
David Reissbc3dddb2007-08-22 23:20:24 +0000482 if (errno == EPIPE || errno == ECONNRESET || errno == ENOTCONN) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000483 close();
David Reiss9b209552008-04-08 06:26:05 +0000484 throw TTransportException(TTransportException::NOT_OPEN, "write() send()", errno_copy);
Mark Slee8d7e1f62006-06-07 06:48:56 +0000485 }
486
David Reiss9b209552008-04-08 06:26:05 +0000487 throw TTransportException(TTransportException::UNKNOWN, "write() send()", errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000488 }
Mark Slee256bdc42007-11-27 08:42:19 +0000489
Mark Sleee8540632006-05-30 09:24:40 +0000490 // Fail on blocked send
491 if (b == 0) {
Mark Sleef9831082007-02-20 20:59:21 +0000492 throw TTransportException(TTransportException::NOT_OPEN, "Socket send returned 0.");
Mark Sleee8540632006-05-30 09:24:40 +0000493 }
Mark Sleee8540632006-05-30 09:24:40 +0000494 sent += b;
495 }
496}
497
dweatherford14b0ed62007-10-19 01:03:32 +0000498std::string TSocket::getHost() {
499 return host_;
500}
501
502int TSocket::getPort() {
503 return port_;
504}
505
Aditya Agarwalebc99e02007-01-15 23:14:58 +0000506void TSocket::setHost(string host) {
507 host_ = host;
508}
509
510void TSocket::setPort(int port) {
511 port_ = port;
512}
513
Mark Slee8d7e1f62006-06-07 06:48:56 +0000514void TSocket::setLinger(bool on, int linger) {
Mark Slee29050782006-09-29 00:12:30 +0000515 lingerOn_ = on;
516 lingerVal_ = linger;
Martin Kraemeree341cb2007-02-05 21:40:38 +0000517 if (socket_ < 0) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000518 return;
519 }
520
Mark Slee29050782006-09-29 00:12:30 +0000521 struct linger l = {(lingerOn_ ? 1 : 0), lingerVal_};
522 int ret = setsockopt(socket_, SOL_SOCKET, SO_LINGER, &l, sizeof(l));
523 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000524 int errno_copy = errno; // Copy errno because we're allocating memory.
525 GlobalOutput.perror("TSocket::setLinger() setsockopt() " + getSocketInfo(), errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000526 }
Mark Sleee8540632006-05-30 09:24:40 +0000527}
528
Mark Slee8d7e1f62006-06-07 06:48:56 +0000529void TSocket::setNoDelay(bool noDelay) {
Mark Slee29050782006-09-29 00:12:30 +0000530 noDelay_ = noDelay;
Martin Kraemeree341cb2007-02-05 21:40:38 +0000531 if (socket_ < 0) {
Mark Slee8d7e1f62006-06-07 06:48:56 +0000532 return;
533 }
534
Mark Sleee8540632006-05-30 09:24:40 +0000535 // Set socket to NODELAY
Mark Slee29050782006-09-29 00:12:30 +0000536 int v = noDelay_ ? 1 : 0;
537 int ret = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v));
538 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000539 int errno_copy = errno; // Copy errno because we're allocating memory.
540 GlobalOutput.perror("TSocket::setNoDelay() setsockopt() " + getSocketInfo(), errno_copy);
Mark Sleee8540632006-05-30 09:24:40 +0000541 }
Mark Sleee8540632006-05-30 09:24:40 +0000542}
Mark Slee29050782006-09-29 00:12:30 +0000543
544void TSocket::setConnTimeout(int ms) {
545 connTimeout_ = ms;
546}
547
548void TSocket::setRecvTimeout(int ms) {
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000549 if (ms < 0) {
550 char errBuf[512];
551 sprintf(errBuf, "TSocket::setRecvTimeout with negative input: %d\n", ms);
552 GlobalOutput(errBuf);
553 return;
554 }
Mark Slee29050782006-09-29 00:12:30 +0000555 recvTimeout_ = ms;
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000556
Martin Kraemeree341cb2007-02-05 21:40:38 +0000557 if (socket_ < 0) {
Mark Slee29050782006-09-29 00:12:30 +0000558 return;
559 }
560
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000561 recvTimeval_.tv_sec = (int)(recvTimeout_/1000);
562 recvTimeval_.tv_usec = (int)((recvTimeout_%1000)*1000);
563
David Reiss22b18862008-04-08 06:25:45 +0000564 // Copy because poll may modify
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000565 struct timeval r = recvTimeval_;
Mark Slee29050782006-09-29 00:12:30 +0000566 int ret = setsockopt(socket_, SOL_SOCKET, SO_RCVTIMEO, &r, sizeof(r));
567 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000568 int errno_copy = errno; // Copy errno because we're allocating memory.
569 GlobalOutput.perror("TSocket::setRecvTimeout() setsockopt() " + getSocketInfo(), errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000570 }
571}
572
573void TSocket::setSendTimeout(int ms) {
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000574 if (ms < 0) {
575 char errBuf[512];
576 sprintf(errBuf, "TSocket::setSendTimeout with negative input: %d\n", ms);
577 GlobalOutput(errBuf);
578 return;
579 }
Mark Slee29050782006-09-29 00:12:30 +0000580 sendTimeout_ = ms;
Aditya Agarwalc31769c2007-12-11 22:23:51 +0000581
Martin Kraemeree341cb2007-02-05 21:40:38 +0000582 if (socket_ < 0) {
Mark Slee29050782006-09-29 00:12:30 +0000583 return;
584 }
Mark Slee256bdc42007-11-27 08:42:19 +0000585
Mark Slee29050782006-09-29 00:12:30 +0000586 struct timeval s = {(int)(sendTimeout_/1000),
587 (int)((sendTimeout_%1000)*1000)};
588 int ret = setsockopt(socket_, SOL_SOCKET, SO_SNDTIMEO, &s, sizeof(s));
589 if (ret == -1) {
David Reiss01e55c12008-07-13 22:18:51 +0000590 int errno_copy = errno; // Copy errno because we're allocating memory.
591 GlobalOutput.perror("TSocket::setSendTimeout() setsockopt() " + getSocketInfo(), errno_copy);
Mark Slee29050782006-09-29 00:12:30 +0000592 }
593}
594
Aditya Agarwale04475b2007-05-23 02:14:58 +0000595void TSocket::setMaxRecvRetries(int maxRecvRetries) {
596 maxRecvRetries_ = maxRecvRetries;
597}
598
Aditya Agarwal4529c4b2007-09-05 01:01:15 +0000599string TSocket::getSocketInfo() {
600 std::ostringstream oss;
601 oss << "<Host: " << host_ << " Port: " << port_ << ">";
602 return oss.str();
603}
604
Mark Sleeb4552922007-11-28 00:12:11 +0000605std::string TSocket::getPeerHost() {
606 if (peerHost_.empty()) {
607 struct sockaddr_storage addr;
David Reiss23248712010-10-06 17:10:08 +0000608 struct sockaddr* addrPtr;
609 socklen_t addrLen;
Mark Sleeb4552922007-11-28 00:12:11 +0000610
611 if (socket_ < 0) {
612 return host_;
613 }
614
David Reiss23248712010-10-06 17:10:08 +0000615 addrPtr = getCachedAddress(&addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000616
David Reiss23248712010-10-06 17:10:08 +0000617 if (addrPtr == NULL) {
618 addrLen = sizeof(addr);
619 if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
620 return peerHost_;
621 }
622 addrPtr = (sockaddr*)&addr;
623
624 setCachedAddress(addrPtr, addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000625 }
626
627 char clienthost[NI_MAXHOST];
628 char clientservice[NI_MAXSERV];
629
David Reiss23248712010-10-06 17:10:08 +0000630 getnameinfo((sockaddr*) addrPtr, addrLen,
Mark Sleeb4552922007-11-28 00:12:11 +0000631 clienthost, sizeof(clienthost),
632 clientservice, sizeof(clientservice), 0);
633
634 peerHost_ = clienthost;
635 }
636 return peerHost_;
637}
638
639std::string TSocket::getPeerAddress() {
640 if (peerAddress_.empty()) {
641 struct sockaddr_storage addr;
David Reiss23248712010-10-06 17:10:08 +0000642 struct sockaddr* addrPtr;
643 socklen_t addrLen;
Mark Sleeb4552922007-11-28 00:12:11 +0000644
645 if (socket_ < 0) {
646 return peerAddress_;
647 }
648
David Reiss23248712010-10-06 17:10:08 +0000649 addrPtr = getCachedAddress(&addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000650
David Reiss23248712010-10-06 17:10:08 +0000651 if (addrPtr == NULL) {
652 addrLen = sizeof(addr);
653 if (getpeername(socket_, (sockaddr*) &addr, &addrLen) != 0) {
654 return peerAddress_;
655 }
656 addrPtr = (sockaddr*)&addr;
657
658 setCachedAddress(addrPtr, addrLen);
Mark Sleeb4552922007-11-28 00:12:11 +0000659 }
660
661 char clienthost[NI_MAXHOST];
662 char clientservice[NI_MAXSERV];
663
David Reiss23248712010-10-06 17:10:08 +0000664 getnameinfo(addrPtr, addrLen,
Mark Sleeb4552922007-11-28 00:12:11 +0000665 clienthost, sizeof(clienthost),
666 clientservice, sizeof(clientservice),
667 NI_NUMERICHOST|NI_NUMERICSERV);
668
669 peerAddress_ = clienthost;
670 peerPort_ = std::atoi(clientservice);
671 }
672 return peerAddress_;
673}
674
675int TSocket::getPeerPort() {
676 getPeerAddress();
677 return peerPort_;
678}
679
David Reiss23248712010-10-06 17:10:08 +0000680void TSocket::setCachedAddress(const sockaddr* addr, socklen_t len) {
681 switch (addr->sa_family) {
682 case AF_INET:
683 if (len == sizeof(sockaddr_in)) {
684 memcpy((void*)&cachedPeerAddr_.ipv4, (void*)addr, len);
685 }
686 break;
687
688 case AF_INET6:
689 if (len == sizeof(sockaddr_in6)) {
690 memcpy((void*)&cachedPeerAddr_.ipv6, (void*)addr, len);
691 }
692 break;
693 }
694}
695
696sockaddr* TSocket::getCachedAddress(socklen_t* len) const {
697 switch (cachedPeerAddr_.ipv4.sin_family) {
698 case AF_INET:
699 *len = sizeof(sockaddr_in);
700 return (sockaddr*) &cachedPeerAddr_.ipv4;
701
702 case AF_INET6:
703 *len = sizeof(sockaddr_in6);
704 return (sockaddr*) &cachedPeerAddr_.ipv6;
705
706 default:
707 return NULL;
708 }
709}
710
David Reiss1c20c872010-03-09 05:20:14 +0000711bool TSocket::useLowMinRto_ = false;
712void TSocket::setUseLowMinRto(bool useLowMinRto) {
713 useLowMinRto_ = useLowMinRto;
714}
715bool TSocket::getUseLowMinRto() {
716 return useLowMinRto_;
717}
718
T Jake Lucianib5e62212009-01-31 22:36:20 +0000719}}} // apache::thrift::transport