You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net.c 14KB

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