2
0

net.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /* Extracted from anet.c to work properly with Hiredis error reporting.
  2. *
  3. * Copyright (c) 2006-2011, Salvatore Sanfilippo <antirez at gmail dot com>
  4. * Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  5. *
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions are met:
  10. *
  11. * * Redistributions of source code must retain the above copyright notice,
  12. * this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * * Neither the name of Redis nor the names of its contributors may be used
  17. * to endorse or promote products derived from this software without
  18. * specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  21. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  24. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. * POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include "fmacros.h"
  33. #include <sys/types.h>
  34. #include <sys/socket.h>
  35. #include <sys/select.h>
  36. #include <sys/un.h>
  37. #include <netinet/in.h>
  38. #include <netinet/tcp.h>
  39. #include <arpa/inet.h>
  40. #include <unistd.h>
  41. #include <fcntl.h>
  42. #include <string.h>
  43. #include <netdb.h>
  44. #include <errno.h>
  45. #include <stdarg.h>
  46. #include <stdio.h>
  47. #include <poll.h>
  48. #include <limits.h>
  49. #include "net.h"
  50. #include "sds.h"
  51. /* Defined in hiredis.c */
  52. void __redisSetError(redisContext *c, int type, const char *str);
  53. static void redisContextCloseFd(redisContext *c) {
  54. if (c && c->fd >= 0) {
  55. close(c->fd);
  56. c->fd = -1;
  57. }
  58. }
  59. static void __redisSetErrorFromErrno(redisContext *c, int type, const char *prefix) {
  60. char buf[128] = { 0 };
  61. size_t len = 0;
  62. if (prefix != NULL)
  63. len = snprintf(buf,sizeof(buf),"%s: ",prefix);
  64. strerror_r(errno,buf+len,sizeof(buf)-len);
  65. __redisSetError(c,type,buf);
  66. }
  67. static int redisSetReuseAddr(redisContext *c) {
  68. int on = 1;
  69. if (setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
  70. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  71. redisContextCloseFd(c);
  72. return REDIS_ERR;
  73. }
  74. return REDIS_OK;
  75. }
  76. static int redisCreateSocket(redisContext *c, int type) {
  77. int s;
  78. if ((s = socket(type, SOCK_STREAM, 0)) == -1) {
  79. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  80. return REDIS_ERR;
  81. }
  82. c->fd = s;
  83. if (type == AF_INET) {
  84. if (redisSetReuseAddr(c) == REDIS_ERR) {
  85. return REDIS_ERR;
  86. }
  87. }
  88. return REDIS_OK;
  89. }
  90. static int redisSetBlocking(redisContext *c, int blocking) {
  91. int flags;
  92. /* Set the socket nonblocking.
  93. * Note that fcntl(2) for F_GETFL and F_SETFL can't be
  94. * interrupted by a signal. */
  95. if ((flags = fcntl(c->fd, F_GETFL)) == -1) {
  96. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_GETFL)");
  97. redisContextCloseFd(c);
  98. return REDIS_ERR;
  99. }
  100. if (blocking)
  101. flags &= ~O_NONBLOCK;
  102. else
  103. flags |= O_NONBLOCK;
  104. if (fcntl(c->fd, F_SETFL, flags) == -1) {
  105. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_SETFL)");
  106. redisContextCloseFd(c);
  107. return REDIS_ERR;
  108. }
  109. return REDIS_OK;
  110. }
  111. int redisKeepAlive(redisContext *c, int interval) {
  112. int val = 1;
  113. int fd = c->fd;
  114. if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1){
  115. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  116. return REDIS_ERR;
  117. }
  118. val = interval;
  119. #ifdef _OSX
  120. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0) {
  121. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  122. return REDIS_ERR;
  123. }
  124. #else
  125. #ifndef __sun
  126. val = interval;
  127. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
  128. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  129. return REDIS_ERR;
  130. }
  131. val = interval/3;
  132. if (val == 0) val = 1;
  133. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
  134. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  135. return REDIS_ERR;
  136. }
  137. val = 3;
  138. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
  139. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  140. return REDIS_ERR;
  141. }
  142. #endif
  143. #endif
  144. return REDIS_OK;
  145. }
  146. static int redisSetTcpNoDelay(redisContext *c) {
  147. int yes = 1;
  148. if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
  149. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(TCP_NODELAY)");
  150. redisContextCloseFd(c);
  151. return REDIS_ERR;
  152. }
  153. return REDIS_OK;
  154. }
  155. #define __MAX_MSEC (((LONG_MAX) - 999) / 1000)
  156. static int redisContextWaitReady(redisContext *c, const struct timeval *timeout) {
  157. struct pollfd wfd[1];
  158. long msec;
  159. msec = -1;
  160. wfd[0].fd = c->fd;
  161. wfd[0].events = POLLOUT;
  162. /* Only use timeout when not NULL. */
  163. if (timeout != NULL) {
  164. if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
  165. __redisSetErrorFromErrno(c, REDIS_ERR_IO, NULL);
  166. redisContextCloseFd(c);
  167. return REDIS_ERR;
  168. }
  169. msec = (timeout->tv_sec * 1000) + ((timeout->tv_usec + 999) / 1000);
  170. if (msec < 0 || msec > INT_MAX) {
  171. msec = INT_MAX;
  172. }
  173. }
  174. if (errno == EINPROGRESS) {
  175. int res;
  176. if ((res = poll(wfd, 1, msec)) == -1) {
  177. __redisSetErrorFromErrno(c, REDIS_ERR_IO, "poll(2)");
  178. redisContextCloseFd(c);
  179. return REDIS_ERR;
  180. } else if (res == 0) {
  181. errno = ETIMEDOUT;
  182. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  183. redisContextCloseFd(c);
  184. return REDIS_ERR;
  185. }
  186. if (redisCheckSocketError(c) != REDIS_OK)
  187. return REDIS_ERR;
  188. return REDIS_OK;
  189. }
  190. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  191. redisContextCloseFd(c);
  192. return REDIS_ERR;
  193. }
  194. int redisCheckSocketError(redisContext *c) {
  195. int err = 0;
  196. socklen_t errlen = sizeof(err);
  197. if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  198. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"getsockopt(SO_ERROR)");
  199. return REDIS_ERR;
  200. }
  201. if (err) {
  202. errno = err;
  203. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  204. return REDIS_ERR;
  205. }
  206. return REDIS_OK;
  207. }
  208. int redisContextSetTimeout(redisContext *c, const struct timeval tv) {
  209. if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) {
  210. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_RCVTIMEO)");
  211. return REDIS_ERR;
  212. }
  213. if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1) {
  214. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_SNDTIMEO)");
  215. return REDIS_ERR;
  216. }
  217. return REDIS_OK;
  218. }
  219. static int _redisContextConnectTcp(redisContext *c, const char *addr, int port,
  220. const struct timeval *timeout,
  221. const char *source_addr) {
  222. int s, rv;
  223. char _port[6]; /* strlen("65535"); */
  224. struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
  225. int blocking = (c->flags & REDIS_BLOCK);
  226. snprintf(_port, 6, "%d", port);
  227. memset(&hints,0,sizeof(hints));
  228. hints.ai_family = AF_INET;
  229. hints.ai_socktype = SOCK_STREAM;
  230. /* Try with IPv6 if no IPv4 address was found. We do it in this order since
  231. * in a Redis client you can't afford to test if you have IPv6 connectivity
  232. * as this would add latency to every connect. Otherwise a more sensible
  233. * route could be: Use IPv6 if both addresses are available and there is IPv6
  234. * connectivity. */
  235. if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
  236. hints.ai_family = AF_INET6;
  237. if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
  238. __redisSetError(c,REDIS_ERR_OTHER,gai_strerror(rv));
  239. return REDIS_ERR;
  240. }
  241. }
  242. for (p = servinfo; p != NULL; p = p->ai_next) {
  243. if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
  244. continue;
  245. c->fd = s;
  246. if (redisSetBlocking(c,0) != REDIS_OK)
  247. goto error;
  248. if (source_addr) {
  249. int bound = 0;
  250. /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
  251. if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0) {
  252. char buf[128];
  253. snprintf(buf,sizeof(buf),"Can't get addr: %s",gai_strerror(rv));
  254. __redisSetError(c,REDIS_ERR_OTHER,buf);
  255. goto error;
  256. }
  257. for (b = bservinfo; b != NULL; b = b->ai_next) {
  258. if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
  259. bound = 1;
  260. break;
  261. }
  262. }
  263. if (!bound) {
  264. char buf[128];
  265. snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno));
  266. __redisSetError(c,REDIS_ERR_OTHER,buf);
  267. goto error;
  268. }
  269. }
  270. if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
  271. if (errno == EHOSTUNREACH) {
  272. redisContextCloseFd(c);
  273. continue;
  274. } else if (errno == EINPROGRESS && !blocking) {
  275. /* This is ok. */
  276. } else {
  277. if (redisContextWaitReady(c,timeout) != REDIS_OK)
  278. goto error;
  279. }
  280. }
  281. if (blocking && redisSetBlocking(c,1) != REDIS_OK)
  282. goto error;
  283. if (redisSetTcpNoDelay(c) != REDIS_OK)
  284. goto error;
  285. c->flags |= REDIS_CONNECTED;
  286. rv = REDIS_OK;
  287. goto end;
  288. }
  289. if (p == NULL) {
  290. char buf[128];
  291. snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno));
  292. __redisSetError(c,REDIS_ERR_OTHER,buf);
  293. goto error;
  294. }
  295. error:
  296. rv = REDIS_ERR;
  297. end:
  298. freeaddrinfo(servinfo);
  299. return rv; // Need to return REDIS_OK if alright
  300. }
  301. int redisContextConnectTcp(redisContext *c, const char *addr, int port,
  302. const struct timeval *timeout) {
  303. return _redisContextConnectTcp(c, addr, port, timeout, NULL);
  304. }
  305. int redisContextConnectBindTcp(redisContext *c, const char *addr, int port,
  306. const struct timeval *timeout,
  307. const char *source_addr) {
  308. return _redisContextConnectTcp(c, addr, port, timeout, source_addr);
  309. }
  310. int redisContextConnectUnix(redisContext *c, const char *path, const struct timeval *timeout) {
  311. int blocking = (c->flags & REDIS_BLOCK);
  312. struct sockaddr_un sa;
  313. if (redisCreateSocket(c,AF_LOCAL) < 0)
  314. return REDIS_ERR;
  315. if (redisSetBlocking(c,0) != REDIS_OK)
  316. return REDIS_ERR;
  317. sa.sun_family = AF_LOCAL;
  318. strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
  319. if (connect(c->fd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
  320. if (errno == EINPROGRESS && !blocking) {
  321. /* This is ok. */
  322. } else {
  323. if (redisContextWaitReady(c,timeout) != REDIS_OK)
  324. return REDIS_ERR;
  325. }
  326. }
  327. /* Reset socket to be blocking after connect(2). */
  328. if (blocking && redisSetBlocking(c,1) != REDIS_OK)
  329. return REDIS_ERR;
  330. c->flags |= REDIS_CONNECTED;
  331. return REDIS_OK;
  332. }