net.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /* Extracted from anet.c to work properly with Hiredis error reporting.
  2. *
  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>
  7. *
  8. * All rights reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions are met:
  12. *
  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.
  21. *
  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.
  33. */
  34. #include "fmacros.h"
  35. #include <sys/types.h>
  36. #include <sys/socket.h>
  37. #include <sys/select.h>
  38. #include <sys/un.h>
  39. #include <netinet/in.h>
  40. #include <netinet/tcp.h>
  41. #include <arpa/inet.h>
  42. #include <unistd.h>
  43. #include <fcntl.h>
  44. #include <string.h>
  45. #include <netdb.h>
  46. #include <errno.h>
  47. #include <stdarg.h>
  48. #include <stdio.h>
  49. #include <poll.h>
  50. #include <limits.h>
  51. #include <stdlib.h>
  52. #include "net.h"
  53. #include "sds.h"
  54. /* Defined in hiredis.c */
  55. void __redisSetError(redisContext *c, int type, const char *str);
  56. static void redisContextCloseFd(redisContext *c) {
  57. if (c && c->fd >= 0) {
  58. close(c->fd);
  59. c->fd = -1;
  60. }
  61. }
  62. static void __redisSetErrorFromErrno(redisContext *c, int type, const char *prefix) {
  63. int errorno = errno; /* snprintf() may change errno */
  64. char buf[128] = { 0 };
  65. size_t len = 0;
  66. if (prefix != NULL)
  67. len = snprintf(buf,sizeof(buf),"%s: ",prefix);
  68. strerror_r(errorno, (char *)(buf + len), sizeof(buf) - len);
  69. __redisSetError(c,type,buf);
  70. }
  71. static int redisSetReuseAddr(redisContext *c) {
  72. int on = 1;
  73. if (setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
  74. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  75. redisContextCloseFd(c);
  76. return REDIS_ERR;
  77. }
  78. return REDIS_OK;
  79. }
  80. static int redisCreateSocket(redisContext *c, int type) {
  81. int s;
  82. if ((s = socket(type, SOCK_STREAM, 0)) == -1) {
  83. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  84. return REDIS_ERR;
  85. }
  86. c->fd = s;
  87. if (type == AF_INET) {
  88. if (redisSetReuseAddr(c) == REDIS_ERR) {
  89. return REDIS_ERR;
  90. }
  91. }
  92. return REDIS_OK;
  93. }
  94. static int redisSetBlocking(redisContext *c, int blocking) {
  95. int flags;
  96. /* Set the socket nonblocking.
  97. * Note that fcntl(2) for F_GETFL and F_SETFL can't be
  98. * interrupted by a signal. */
  99. if ((flags = fcntl(c->fd, F_GETFL)) == -1) {
  100. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_GETFL)");
  101. redisContextCloseFd(c);
  102. return REDIS_ERR;
  103. }
  104. if (blocking)
  105. flags &= ~O_NONBLOCK;
  106. else
  107. flags |= O_NONBLOCK;
  108. if (fcntl(c->fd, F_SETFL, flags) == -1) {
  109. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"fcntl(F_SETFL)");
  110. redisContextCloseFd(c);
  111. return REDIS_ERR;
  112. }
  113. return REDIS_OK;
  114. }
  115. int redisKeepAlive(redisContext *c, int interval) {
  116. int val = 1;
  117. int fd = c->fd;
  118. if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1){
  119. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  120. return REDIS_ERR;
  121. }
  122. val = interval;
  123. #if defined(__APPLE__) && defined(__MACH__)
  124. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0) {
  125. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  126. return REDIS_ERR;
  127. }
  128. #else
  129. #if defined(__GLIBC__) && !defined(__FreeBSD_kernel__)
  130. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
  131. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  132. return REDIS_ERR;
  133. }
  134. val = interval/3;
  135. if (val == 0) val = 1;
  136. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
  137. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  138. return REDIS_ERR;
  139. }
  140. val = 3;
  141. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
  142. __redisSetError(c,REDIS_ERR_OTHER,strerror(errno));
  143. return REDIS_ERR;
  144. }
  145. #endif
  146. #endif
  147. return REDIS_OK;
  148. }
  149. static int redisSetTcpNoDelay(redisContext *c) {
  150. int yes = 1;
  151. if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
  152. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(TCP_NODELAY)");
  153. redisContextCloseFd(c);
  154. return REDIS_ERR;
  155. }
  156. return REDIS_OK;
  157. }
  158. #define __MAX_MSEC (((LONG_MAX) - 999) / 1000)
  159. static int redisContextTimeoutMsec(redisContext *c, long *result)
  160. {
  161. const struct timeval *timeout = c->timeout;
  162. long msec = -1;
  163. /* Only use timeout when not NULL. */
  164. if (timeout != NULL) {
  165. if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
  166. *result = msec;
  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. *result = msec;
  175. return REDIS_OK;
  176. }
  177. static int redisContextWaitReady(redisContext *c, long msec) {
  178. struct pollfd wfd[1];
  179. wfd[0].fd = c->fd;
  180. wfd[0].events = POLLOUT;
  181. if (errno == EINPROGRESS) {
  182. int res;
  183. if ((res = poll(wfd, 1, msec)) == -1) {
  184. __redisSetErrorFromErrno(c, REDIS_ERR_IO, "poll(2)");
  185. redisContextCloseFd(c);
  186. return REDIS_ERR;
  187. } else if (res == 0) {
  188. errno = ETIMEDOUT;
  189. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  190. redisContextCloseFd(c);
  191. return REDIS_ERR;
  192. }
  193. if (redisCheckSocketError(c) != REDIS_OK)
  194. return REDIS_ERR;
  195. return REDIS_OK;
  196. }
  197. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  198. redisContextCloseFd(c);
  199. return REDIS_ERR;
  200. }
  201. int redisCheckSocketError(redisContext *c) {
  202. int err = 0;
  203. socklen_t errlen = sizeof(err);
  204. if (getsockopt(c->fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  205. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"getsockopt(SO_ERROR)");
  206. return REDIS_ERR;
  207. }
  208. if (err) {
  209. errno = err;
  210. __redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
  211. return REDIS_ERR;
  212. }
  213. return REDIS_OK;
  214. }
  215. int redisContextSetTimeout(redisContext *c, const struct timeval tv) {
  216. if (setsockopt(c->fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) {
  217. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_RCVTIMEO)");
  218. return REDIS_ERR;
  219. }
  220. if (setsockopt(c->fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1) {
  221. __redisSetErrorFromErrno(c,REDIS_ERR_IO,"setsockopt(SO_SNDTIMEO)");
  222. return REDIS_ERR;
  223. }
  224. return REDIS_OK;
  225. }
  226. static int _redisContextConnectTcp(redisContext *c, const char *addr, int port,
  227. const struct timeval *timeout,
  228. const char *source_addr) {
  229. int s, rv, n;
  230. char _port[6]; /* strlen("65535"); */
  231. struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
  232. int blocking = (c->flags & REDIS_BLOCK);
  233. int reuseaddr = (c->flags & REDIS_REUSEADDR);
  234. int reuses = 0;
  235. long timeout_msec = -1;
  236. servinfo = NULL;
  237. c->connection_type = REDIS_CONN_TCP;
  238. c->tcp.port = port;
  239. /* We need to take possession of the passed parameters
  240. * to make them reusable for a reconnect.
  241. * We also carefully check we don't free data we already own,
  242. * as in the case of the reconnect method.
  243. *
  244. * This is a bit ugly, but atleast it works and doesn't leak memory.
  245. **/
  246. if (c->tcp.host != addr) {
  247. free(c->tcp.host);
  248. c->tcp.host = hi_strdup(addr);
  249. }
  250. if (timeout) {
  251. if (c->timeout != timeout) {
  252. if (c->timeout == NULL)
  253. c->timeout = hi_malloc(sizeof(struct timeval));
  254. memcpy(c->timeout, timeout, sizeof(struct timeval));
  255. }
  256. } else {
  257. free(c->timeout);
  258. c->timeout = NULL;
  259. }
  260. if (redisContextTimeoutMsec(c, &timeout_msec) != REDIS_OK) {
  261. __redisSetError(c, REDIS_ERR_IO, "Invalid timeout specified");
  262. goto error;
  263. }
  264. if (source_addr == NULL) {
  265. free(c->tcp.source_addr);
  266. c->tcp.source_addr = NULL;
  267. } else if (c->tcp.source_addr != source_addr) {
  268. free(c->tcp.source_addr);
  269. c->tcp.source_addr = hi_strdup(source_addr);
  270. }
  271. snprintf(_port, 6, "%d", port);
  272. memset(&hints,0,sizeof(hints));
  273. hints.ai_family = AF_INET;
  274. hints.ai_socktype = SOCK_STREAM;
  275. /* Try with IPv6 if no IPv4 address was found. We do it in this order since
  276. * in a Redis client you can't afford to test if you have IPv6 connectivity
  277. * as this would add latency to every connect. Otherwise a more sensible
  278. * route could be: Use IPv6 if both addresses are available and there is IPv6
  279. * connectivity. */
  280. if ((rv = getaddrinfo(c->tcp.host,_port,&hints,&servinfo)) != 0) {
  281. hints.ai_family = AF_INET6;
  282. if ((rv = getaddrinfo(addr,_port,&hints,&servinfo)) != 0) {
  283. __redisSetError(c,REDIS_ERR_OTHER,gai_strerror(rv));
  284. return REDIS_ERR;
  285. }
  286. }
  287. for (p = servinfo; p != NULL; p = p->ai_next) {
  288. addrretry:
  289. if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
  290. continue;
  291. c->fd = s;
  292. if (redisSetBlocking(c,0) != REDIS_OK)
  293. goto error;
  294. if (c->tcp.source_addr) {
  295. int bound = 0;
  296. /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
  297. if ((rv = getaddrinfo(c->tcp.source_addr, NULL, &hints, &bservinfo)) != 0) {
  298. char buf[128];
  299. snprintf(buf,sizeof(buf),"Can't get addr: %s",gai_strerror(rv));
  300. __redisSetError(c,REDIS_ERR_OTHER,buf);
  301. goto error;
  302. }
  303. if (reuseaddr) {
  304. n = 1;
  305. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*) &n,
  306. sizeof(n)) < 0) {
  307. freeaddrinfo(bservinfo);
  308. goto error;
  309. }
  310. }
  311. for (b = bservinfo; b != NULL; b = b->ai_next) {
  312. if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
  313. bound = 1;
  314. break;
  315. }
  316. }
  317. freeaddrinfo(bservinfo);
  318. if (!bound) {
  319. char buf[128];
  320. snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno));
  321. __redisSetError(c,REDIS_ERR_OTHER,buf);
  322. goto error;
  323. }
  324. }
  325. if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
  326. if (errno == EHOSTUNREACH) {
  327. redisContextCloseFd(c);
  328. continue;
  329. } else if (errno == EINPROGRESS && !blocking) {
  330. /* This is ok. */
  331. } else if (errno == EADDRNOTAVAIL && reuseaddr) {
  332. if (++reuses >= REDIS_CONNECT_RETRIES) {
  333. goto error;
  334. } else {
  335. redisContextCloseFd(c);
  336. goto addrretry;
  337. }
  338. } else {
  339. if (redisContextWaitReady(c,timeout_msec) != REDIS_OK)
  340. goto error;
  341. }
  342. }
  343. if (blocking && redisSetBlocking(c,1) != REDIS_OK)
  344. goto error;
  345. if (redisSetTcpNoDelay(c) != REDIS_OK)
  346. goto error;
  347. c->flags |= REDIS_CONNECTED;
  348. rv = REDIS_OK;
  349. goto end;
  350. }
  351. if (p == NULL) {
  352. char buf[128];
  353. snprintf(buf,sizeof(buf),"Can't create socket: %s",strerror(errno));
  354. __redisSetError(c,REDIS_ERR_OTHER,buf);
  355. goto error;
  356. }
  357. error:
  358. rv = REDIS_ERR;
  359. end:
  360. if(servinfo) {
  361. freeaddrinfo(servinfo);
  362. }
  363. return rv; // Need to return REDIS_OK if alright
  364. }
  365. int redisContextConnectTcp(redisContext *c, const char *addr, int port,
  366. const struct timeval *timeout) {
  367. return _redisContextConnectTcp(c, addr, port, timeout, NULL);
  368. }
  369. int redisContextConnectBindTcp(redisContext *c, const char *addr, int port,
  370. const struct timeval *timeout,
  371. const char *source_addr) {
  372. return _redisContextConnectTcp(c, addr, port, timeout, source_addr);
  373. }
  374. int redisContextConnectUnix(redisContext *c, const char *path, const struct timeval *timeout) {
  375. int blocking = (c->flags & REDIS_BLOCK);
  376. struct sockaddr_un sa;
  377. long timeout_msec = -1;
  378. if (redisCreateSocket(c,AF_UNIX) < 0)
  379. return REDIS_ERR;
  380. if (redisSetBlocking(c,0) != REDIS_OK)
  381. return REDIS_ERR;
  382. c->connection_type = REDIS_CONN_UNIX;
  383. if (c->unix_sock.path != path)
  384. c->unix_sock.path = hi_strdup(path);
  385. if (timeout) {
  386. if (c->timeout != timeout) {
  387. if (c->timeout == NULL)
  388. c->timeout = hi_malloc(sizeof(struct timeval));
  389. memcpy(c->timeout, timeout, sizeof(struct timeval));
  390. }
  391. } else {
  392. free(c->timeout);
  393. c->timeout = NULL;
  394. }
  395. if (redisContextTimeoutMsec(c,&timeout_msec) != REDIS_OK)
  396. return REDIS_ERR;
  397. sa.sun_family = AF_UNIX;
  398. strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
  399. if (connect(c->fd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
  400. if (errno == EINPROGRESS && !blocking) {
  401. /* This is ok. */
  402. } else {
  403. if (redisContextWaitReady(c,timeout_msec) != REDIS_OK)
  404. return REDIS_ERR;
  405. }
  406. }
  407. /* Reset socket to be blocking after connect(2). */
  408. if (blocking && redisSetBlocking(c,1) != REDIS_OK)
  409. return REDIS_ERR;
  410. c->flags |= REDIS_CONNECTED;
  411. return REDIS_OK;
  412. }