Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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