1 /* Extracted from anet.c to work properly with Hiredis error reporting.
3 * Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>
4 * Copyright (c) 2010-2014, Pieter Noordhuis <pcnoordhuis at gmail dot com>
5 * Copyright (c) 2015, Matt Stancliff <matt at genges dot com>,
6 * Jan-Erik Rediger <janerik at fnordig dot com>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
13 * * Redistributions of source code must retain the above copyright notice,
14 * this list of conditions and the following disclaimer.
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * * Neither the name of Redis nor the names of its contributors may be used
19 * to endorse or promote products derived from this software without
20 * specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <sys/select.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
57 /* Defined in hiredis.c */
58 void __redisSetError(redisContext *c, int type, const char *str);
60 static void redisContextCloseFd(redisContext *c) {
61 if (c && c->fd >= 0) {
67 static void __redisSetErrorFromErrno(redisContext *c, int type, const char *prefix) {
68 char buf[128] = { 0 };
72 len = snprintf(buf,sizeof(buf),"%s: ",prefix);
73 __redis_strerror_r(errno, (char *)(buf + len), sizeof(buf) - len);
74 __redisSetError(c,type,buf);
77 static int redisSetReuseAddr(redisContext *c) {
79 if (setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
80 __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
81 redisContextCloseFd(c);
87 static int redisCreateSocket(redisContext *c, int type) {
89 if ((s = socket(type, SOCK_STREAM, 0)) == -1) {
90 __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
94 if (type == AF_INET) {
95 if (redisSetReuseAddr(c) == REDIS_ERR) {
102 static int redisSetBlocking(redisContext *c, int blocking) {
105 /* Set the socket nonblocking.
106 * Note that fcntl(2) for F_GETFL and F_SETFL can't be
107 * interrupted by a signal. */
108 if ((flags = fcntl(c->fd, F_GETFL)) == -1) {
109 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_GETFL)");
110 redisContextCloseFd(c);
115 flags &= ~O_NONBLOCK;
119 if (fcntl(c->fd, F_SETFL, flags) == -1) {
120 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_SETFL)");
121 redisContextCloseFd(c);
127 int redisKeepAlive(redisContext *c, int interval) {
131 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1){
132 __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
139 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0) {
140 __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
144 #if defined(__GLIBC__) && !defined(__FreeBSD_kernel__)
146 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
147 __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
152 if (val == 0) val = 1;
153 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
154 __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
159 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
160 __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
169 static int redisSetTcpNoDelay(redisContext *c) {
171 if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
172 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(TCP_NODELAY)");
173 redisContextCloseFd(c);
179 #define __MAX_MSEC (((LONG_MAX) - 999) / 1000)
181 static int redisContextWaitReady(redisContext *c, const struct timeval *timeout) {
182 struct pollfd wfd[1];
187 wfd[0].events = POLLOUT;
189 /* Only use timeout when not NULL. */
190 if (timeout != NULL) {
191 if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
192 __redisSetErrorFromErrno(c, REDIS_ERR_IO, NULL);
193 redisContextCloseFd(c);
197 msec = (timeout->tv_sec * 1000) + ((timeout->tv_usec + 999) / 1000);
199 if (msec < 0 || msec > INT_MAX) {
204 if (errno == EINPROGRESS) {
207 if ((res = poll(wfd, 1, msec)) == -1) {
208 __redisSetErrorFromErrno(c, REDIS_ERR_IO, "poll(2)");
209 redisContextCloseFd(c);
211 } else if (res == 0) {
213 __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
214 redisContextCloseFd(c);
218 if (redisCheckSocketError(c) != REDIS_OK)
224 __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
225 redisContextCloseFd(c);
229 int redisCheckSocketError(redisContext *c) {
231 socklen_t errlen = sizeof(err);
233 if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
234 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"getsockopt(SO_ERROR)");
240 __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
247 int redisContextSetTimeout(redisContext *c, const struct timeval tv) {
248 if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) {
249 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_RCVTIMEO)");
252 if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1) {
253 __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_SNDTIMEO)");
259 static int _redisContextConnectTcp(redisContext *c, const char *addr, int port,
260 const struct timeval *timeout,
261 const char *source_addr) {
263 char _port[6]; /* strlen("65535"); */
264 struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
265 int blocking = (c->flags & REDIS_BLOCK);
266 int reuseaddr = (c->flags & REDIS_REUSEADDR);
269 c->connection_type = REDIS_CONN_TCP;
272 /* We need to take possession of the passed parameters
273 * to make them reusable for a reconnect.
274 * We also carefully check we don't free data we already own,
275 * as in the case of the reconnect method.
277 * This is a bit ugly, but atleast it works and doesn't leak memory.
279 if (c->tcp.host != addr) {
283 c->tcp.host = strdup(addr);
287 if (c->timeout != timeout) {
288 if (c->timeout == NULL)
289 c->timeout = malloc(sizeof(struct timeval));
291 memcpy(c->timeout, timeout, sizeof(struct timeval));
299 if (source_addr == NULL) {
300 free(c->tcp.source_addr);
301 c->tcp.source_addr = NULL;
302 } else if (c->tcp.source_addr != source_addr) {
303 free(c->tcp.source_addr);
304 c->tcp.source_addr = strdup(source_addr);
307 snprintf(_port, 6, "%d", port);
308 memset(&hints,0,sizeof(hints));
309 hints.ai_family = AF_INET;
310 hints.ai_socktype = SOCK_STREAM;
312 /* Try with IPv6 if no IPv4 address was found. We do it in this order since
313 * in a Redis client you can't afford to test if you have IPv6 connectivity
314 * as this would add latency to every connect. Otherwise a more sensible
315 * route could be: Use IPv6 if both addresses are available and there is IPv6
317 if ((rv = getaddrinfo(c->tcp.host,_port,&hints,&servinfo)) != 0) {
318 hints.ai_family = AF_INET6;
319 if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
320 __redisSetError(c,REDIS_ERR_OTHER,gai_strerror(rv));
324 for (p = servinfo; p != NULL; p = p->ai_next) {
326 if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
330 if (redisSetBlocking(c,0) != REDIS_OK)
332 if (c->tcp.source_addr) {
334 /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
335 if ((rv = getaddrinfo(c->tcp.source_addr, NULL, &hints, &bservinfo)) != 0) {
337 snprintf(buf,sizeof(buf),"Can't get addr: %s",gai_strerror(rv));
338 __redisSetError(c,REDIS_ERR_OTHER,buf);
344 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*) &n,
350 for (b = bservinfo; b != NULL; b = b->ai_next) {
351 if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
356 freeaddrinfo(bservinfo);
359 snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno));
360 __redisSetError(c,REDIS_ERR_OTHER,buf);
364 if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
365 if (errno == EHOSTUNREACH) {
366 redisContextCloseFd(c);
368 } else if (errno == EINPROGRESS && !blocking) {
370 } else if (errno == EADDRNOTAVAIL && reuseaddr) {
371 if (++reuses >= REDIS_CONNECT_RETRIES) {
377 if (redisContextWaitReady(c,c->timeout) != REDIS_OK)
381 if (blocking && redisSetBlocking(c,1) != REDIS_OK)
383 if (redisSetTcpNoDelay(c) != REDIS_OK)
386 c->flags |= REDIS_CONNECTED;
392 snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno));
393 __redisSetError(c,REDIS_ERR_OTHER,buf);
400 freeaddrinfo(servinfo);
401 return rv; // Need to return REDIS_OK if alright
404 int redisContextConnectTcp(redisContext *c, const char *addr, int port,
405 const struct timeval *timeout) {
406 return _redisContextConnectTcp(c, addr, port, timeout, NULL);
409 int redisContextConnectBindTcp(redisContext *c, const char *addr, int port,
410 const struct timeval *timeout,
411 const char *source_addr) {
412 return _redisContextConnectTcp(c, addr, port, timeout, source_addr);
415 int redisContextConnectUnix(redisContext *c, const char *path, const struct timeval *timeout) {
416 int blocking = (c->flags & REDIS_BLOCK);
417 struct sockaddr_un sa;
419 if (redisCreateSocket(c,AF_LOCAL) < 0)
421 if (redisSetBlocking(c,0) != REDIS_OK)
424 c->connection_type = REDIS_CONN_UNIX;
425 if (c->unix_sock.path != path)
426 c->unix_sock.path = strdup(path);
429 if (c->timeout != timeout) {
430 if (c->timeout == NULL)
431 c->timeout = malloc(sizeof(struct timeval));
433 memcpy(c->timeout, timeout, sizeof(struct timeval));
441 sa.sun_family = AF_LOCAL;
442 strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
443 if (connect(c->fd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
444 if (errno == EINPROGRESS && !blocking) {
447 if (redisContextWaitReady(c,c->timeout) != REDIS_OK)
452 /* Reset socket to be blocking after connect(2). */
453 if (blocking && redisSetBlocking(c,1) != REDIS_OK)
456 c->flags |= REDIS_CONNECTED;