关键词搜索

源码搜索 ×
×

漫话Redis源码之八十

发布2022-02-13浏览451次

详情内容

socke相关的操作,需要搞清楚阻塞socket和非阻塞socket的用途哦:

  1. #include "anet.h"
  2. static void anetSetError(char *err, const char *fmt, ...)
  3. {
  4. va_list ap;
  5. if (!err) return;
  6. va_start(ap, fmt);
  7. vsnprintf(err, ANET_ERR_LEN, fmt, ap);
  8. va_end(ap);
  9. }
  10. int anetSetBlock(char *err, int fd, int non_block) {
  11. int flags;
  12. /* Set the socket blocking (if non_block is zero) or non-blocking.
  13. * Note that fcntl(2) for F_GETFL and F_SETFL can't be
  14. * interrupted by a signal. */
  15. if ((flags = fcntl(fd, F_GETFL)) == -1) {
  16. anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
  17. return ANET_ERR;
  18. }
  19. /* Check if this flag has been set or unset, if so,
  20. * then there is no need to call fcntl to set/unset it again. */
  21. if (!!(flags & O_NONBLOCK) == !!non_block)
  22. return ANET_OK;
  23. if (non_block)
  24. flags |= O_NONBLOCK;
  25. else
  26. flags &= ~O_NONBLOCK;
  27. if (fcntl(fd, F_SETFL, flags) == -1) {
  28. anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
  29. return ANET_ERR;
  30. }
  31. return ANET_OK;
  32. }
  33. int anetNonBlock(char *err, int fd) {
  34. return anetSetBlock(err,fd,1);
  35. }
  36. int anetBlock(char *err, int fd) {
  37. return anetSetBlock(err,fd,0);
  38. }
  39. /* Enable the FD_CLOEXEC on the given fd to avoid fd leaks.
  40. * This function should be invoked for fd's on specific places
  41. * where fork + execve system calls are called. */
  42. int anetCloexec(int fd) {
  43. int r;
  44. int flags;
  45. do {
  46. r = fcntl(fd, F_GETFD);
  47. } while (r == -1 && errno == EINTR);
  48. if (r == -1 || (r & FD_CLOEXEC))
  49. return r;
  50. flags = r | FD_CLOEXEC;
  51. do {
  52. r = fcntl(fd, F_SETFD, flags);
  53. } while (r == -1 && errno == EINTR);
  54. return r;
  55. }
  56. /* Set TCP keep alive option to detect dead peers. The interval option
  57. * is only used for Linux as we are using Linux-specific APIs to set
  58. * the probe send time, interval, and count. */
  59. int anetKeepAlive(char *err, int fd, int interval)
  60. {
  61. int val = 1;
  62. if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1)
  63. {
  64. anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
  65. return ANET_ERR;
  66. }
  67. #ifdef __linux__
  68. /* Default settings are more or less garbage, with the keepalive time
  69. * set to 7200 by default on Linux. Modify settings to make the feature
  70. * actually useful. */
  71. /* Send first probe after interval. */
  72. val = interval;
  73. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
  74. anetSetError(err, "setsockopt TCP_KEEPIDLE: %s\n", strerror(errno));
  75. return ANET_ERR;
  76. }
  77. /* Send next probes after the specified interval. Note that we set the
  78. * delay as interval / 3, as we send three probes before detecting
  79. * an error (see the next setsockopt call). */
  80. val = interval/3;
  81. if (val == 0) val = 1;
  82. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
  83. anetSetError(err, "setsockopt TCP_KEEPINTVL: %s\n", strerror(errno));
  84. return ANET_ERR;
  85. }
  86. /* Consider the socket in error state after three we send three ACK
  87. * probes without getting a reply. */
  88. val = 3;
  89. if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
  90. anetSetError(err, "setsockopt TCP_KEEPCNT: %s\n", strerror(errno));
  91. return ANET_ERR;
  92. }
  93. #else
  94. ((void) interval); /* Avoid unused var warning for non Linux systems. */
  95. #endif
  96. return ANET_OK;
  97. }
  98. static int anetSetTcpNoDelay(char *err, int fd, int val)
  99. {
  100. if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) == -1)
  101. {
  102. anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno));
  103. return ANET_ERR;
  104. }
  105. return ANET_OK;
  106. }
  107. int anetEnableTcpNoDelay(char *err, int fd)
  108. {
  109. return anetSetTcpNoDelay(err, fd, 1);
  110. }
  111. int anetDisableTcpNoDelay(char *err, int fd)
  112. {
  113. return anetSetTcpNoDelay(err, fd, 0);
  114. }
  115. /* Set the socket send timeout (SO_SNDTIMEO socket option) to the specified
  116. * number of milliseconds, or disable it if the 'ms' argument is zero. */
  117. int anetSendTimeout(char *err, int fd, long long ms) {
  118. struct timeval tv;
  119. tv.tv_sec = ms/1000;
  120. tv.tv_usec = (ms%1000)*1000;
  121. if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
  122. anetSetError(err, "setsockopt SO_SNDTIMEO: %s", strerror(errno));
  123. return ANET_ERR;
  124. }
  125. return ANET_OK;
  126. }
  127. /* Set the socket receive timeout (SO_RCVTIMEO socket option) to the specified
  128. * number of milliseconds, or disable it if the 'ms' argument is zero. */
  129. int anetRecvTimeout(char *err, int fd, long long ms) {
  130. struct timeval tv;
  131. tv.tv_sec = ms/1000;
  132. tv.tv_usec = (ms%1000)*1000;
  133. if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
  134. anetSetError(err, "setsockopt SO_RCVTIMEO: %s", strerror(errno));
  135. return ANET_ERR;
  136. }
  137. return ANET_OK;
  138. }
  139. /* Resolve the hostname "host" and set the string representation of the
  140. * IP address into the buffer pointed by "ipbuf".
  141. *
  142. * If flags is set to ANET_IP_ONLY the function only resolves hostnames
  143. * that are actually already IPv4 or IPv6 addresses. This turns the function
  144. * into a validating / normalizing function. */
  145. int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len,
  146. int flags)
  147. {
  148. struct addrinfo hints, *info;
  149. int rv;
  150. memset(&hints,0,sizeof(hints));
  151. if (flags & ANET_IP_ONLY) hints.ai_flags = AI_NUMERICHOST;
  152. hints.ai_family = AF_UNSPEC;
  153. hints.ai_socktype = SOCK_STREAM; /* specify socktype to avoid dups */
  154. if ((rv = getaddrinfo(host, NULL, &hints, &info)) != 0) {
  155. anetSetError(err, "%s", gai_strerror(rv));
  156. return ANET_ERR;
  157. }
  158. if (info->ai_family == AF_INET) {
  159. struct sockaddr_in *sa = (struct sockaddr_in *)info->ai_addr;
  160. inet_ntop(AF_INET, &(sa->sin_addr), ipbuf, ipbuf_len);
  161. } else {
  162. struct sockaddr_in6 *sa = (struct sockaddr_in6 *)info->ai_addr;
  163. inet_ntop(AF_INET6, &(sa->sin6_addr), ipbuf, ipbuf_len);
  164. }
  165. freeaddrinfo(info);
  166. return ANET_OK;
  167. }
  168. static int anetSetReuseAddr(char *err, int fd) {
  169. int yes = 1;
  170. /* Make sure connection-intensive things like the redis benchmark
  171. * will be able to close/open sockets a zillion of times */
  172. if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
  173. anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno));
  174. return ANET_ERR;
  175. }
  176. return ANET_OK;
  177. }
  178. static int anetCreateSocket(char *err, int domain) {
  179. int s;
  180. if ((s = socket(domain, SOCK_STREAM, 0)) == -1) {
  181. anetSetError(err, "creating socket: %s", strerror(errno));
  182. return ANET_ERR;
  183. }
  184. /* Make sure connection-intensive things like the redis benchmark
  185. * will be able to close/open sockets a zillion of times */
  186. if (anetSetReuseAddr(err,s) == ANET_ERR) {
  187. close(s);
  188. return ANET_ERR;
  189. }
  190. return s;
  191. }
  192. #define ANET_CONNECT_NONE 0
  193. #define ANET_CONNECT_NONBLOCK 1
  194. #define ANET_CONNECT_BE_BINDING 2 /* Best effort binding. */
  195. static int anetTcpGenericConnect(char *err, const char *addr, int port,
  196. const char *source_addr, int flags)
  197. {
  198. int s = ANET_ERR, rv;
  199. char portstr[6]; /* strlen("65535") + 1; */
  200. struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
  201. snprintf(portstr,sizeof(portstr),"%d",port);
  202. memset(&hints,0,sizeof(hints));
  203. hints.ai_family = AF_UNSPEC;
  204. hints.ai_socktype = SOCK_STREAM;
  205. if ((rv = getaddrinfo(addr,portstr,&hints,&servinfo)) != 0) {
  206. anetSetError(err, "%s", gai_strerror(rv));
  207. return ANET_ERR;
  208. }
  209. for (p = servinfo; p != NULL; p = p->ai_next) {
  210. /* Try to create the socket and to connect it.
  211. * If we fail in the socket() call, or on connect(), we retry with
  212. * the next entry in servinfo. */
  213. if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
  214. continue;
  215. if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
  216. if (flags & ANET_CONNECT_NONBLOCK && anetNonBlock(err,s) != ANET_OK)
  217. goto error;
  218. if (source_addr) {
  219. int bound = 0;
  220. /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
  221. if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0)
  222. {
  223. anetSetError(err, "%s", gai_strerror(rv));
  224. goto error;
  225. }
  226. for (b = bservinfo; b != NULL; b = b->ai_next) {
  227. if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
  228. bound = 1;
  229. break;
  230. }
  231. }
  232. freeaddrinfo(bservinfo);
  233. if (!bound) {
  234. anetSetError(err, "bind: %s", strerror(errno));
  235. goto error;
  236. }
  237. }
  238. if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
  239. /* If the socket is non-blocking, it is ok for connect() to
  240. * return an EINPROGRESS error here. */
  241. if (errno == EINPROGRESS && flags & ANET_CONNECT_NONBLOCK)
  242. goto end;
  243. close(s);
  244. s = ANET_ERR;
  245. continue;
  246. }
  247. /* If we ended an iteration of the for loop without errors, we
  248. * have a connected socket. Let's return to the caller. */
  249. goto end;
  250. }
  251. if (p == NULL)
  252. anetSetError(err, "creating socket: %s", strerror(errno));
  253. error:
  254. if (s != ANET_ERR) {
  255. close(s);
  256. s = ANET_ERR;
  257. }
  258. end:
  259. freeaddrinfo(servinfo);
  260. /* Handle best effort binding: if a binding address was used, but it is
  261. * not possible to create a socket, try again without a binding address. */
  262. if (s == ANET_ERR && source_addr && (flags & ANET_CONNECT_BE_BINDING)) {
  263. return anetTcpGenericConnect(err,addr,port,NULL,flags);
  264. } else {
  265. return s;
  266. }
  267. }
  268. int anetTcpNonBlockConnect(char *err, const char *addr, int port)
  269. {
  270. return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONBLOCK);
  271. }
  272. int anetTcpNonBlockBestEffortBindConnect(char *err, const char *addr, int port,
  273. const char *source_addr)
  274. {
  275. return anetTcpGenericConnect(err,addr,port,source_addr,
  276. ANET_CONNECT_NONBLOCK|ANET_CONNECT_BE_BINDING);
  277. }
  278. int anetUnixGenericConnect(char *err, const char *path, int flags)
  279. {
  280. int s;
  281. struct sockaddr_un sa;
  282. if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
  283. return ANET_ERR;
  284. sa.sun_family = AF_LOCAL;
  285. strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
  286. if (flags & ANET_CONNECT_NONBLOCK) {
  287. if (anetNonBlock(err,s) != ANET_OK) {
  288. close(s);
  289. return ANET_ERR;
  290. }
  291. }
  292. if (connect(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) {
  293. if (errno == EINPROGRESS &&
  294. flags & ANET_CONNECT_NONBLOCK)
  295. return s;
  296. anetSetError(err, "connect: %s", strerror(errno));
  297. close(s);
  298. return ANET_ERR;
  299. }
  300. return s;
  301. }
  302. static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len, int backlog) {
  303. if (bind(s,sa,len) == -1) {
  304. anetSetError(err, "bind: %s", strerror(errno));
  305. close(s);
  306. return ANET_ERR;
  307. }
  308. if (listen(s, backlog) == -1) {
  309. anetSetError(err, "listen: %s", strerror(errno));
  310. close(s);
  311. return ANET_ERR;
  312. }
  313. return ANET_OK;
  314. }
  315. static int anetV6Only(char *err, int s) {
  316. int yes = 1;
  317. if (setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&yes,sizeof(yes)) == -1) {
  318. anetSetError(err, "setsockopt: %s", strerror(errno));
  319. return ANET_ERR;
  320. }
  321. return ANET_OK;
  322. }
  323. static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog)
  324. {
  325. int s = -1, rv;
  326. char _port[6]; /* strlen("65535") */
  327. struct addrinfo hints, *servinfo, *p;
  328. snprintf(_port,6,"%d",port);
  329. memset(&hints,0,sizeof(hints));
  330. hints.ai_family = af;
  331. hints.ai_socktype = SOCK_STREAM;
  332. hints.ai_flags = AI_PASSIVE; /* No effect if bindaddr != NULL */
  333. if (bindaddr && !strcmp("*", bindaddr))
  334. bindaddr = NULL;
  335. if (af == AF_INET6 && bindaddr && !strcmp("::*", bindaddr))
  336. bindaddr = NULL;
  337. if ((rv = getaddrinfo(bindaddr,_port,&hints,&servinfo)) != 0) {
  338. anetSetError(err, "%s", gai_strerror(rv));
  339. return ANET_ERR;
  340. }
  341. for (p = servinfo; p != NULL; p = p->ai_next) {
  342. if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
  343. continue;
  344. if (af == AF_INET6 && anetV6Only(err,s) == ANET_ERR) goto error;
  345. if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
  346. if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) s = ANET_ERR;
  347. goto end;
  348. }
  349. if (p == NULL) {
  350. anetSetError(err, "unable to bind socket, errno: %d", errno);
  351. goto error;
  352. }
  353. error:
  354. if (s != -1) close(s);
  355. s = ANET_ERR;
  356. end:
  357. freeaddrinfo(servinfo);
  358. return s;
  359. }
  360. int anetTcpServer(char *err, int port, char *bindaddr, int backlog)
  361. {
  362. return _anetTcpServer(err, port, bindaddr, AF_INET, backlog);
  363. }
  364. int anetTcp6Server(char *err, int port, char *bindaddr, int backlog)
  365. {
  366. return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog);
  367. }
  368. int anetUnixServer(char *err, char *path, mode_t perm, int backlog)
  369. {
  370. int s;
  371. struct sockaddr_un sa;
  372. if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
  373. return ANET_ERR;
  374. memset(&sa,0,sizeof(sa));
  375. sa.sun_family = AF_LOCAL;
  376. strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
  377. if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa),backlog) == ANET_ERR)
  378. return ANET_ERR;
  379. if (perm)
  380. chmod(sa.sun_path, perm);
  381. return s;
  382. }
  383. static int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len) {
  384. int fd;
  385. while(1) {
  386. fd = accept(s,sa,len);
  387. if (fd == -1) {
  388. if (errno == EINTR)
  389. continue;
  390. else {
  391. anetSetError(err, "accept: %s", strerror(errno));
  392. return ANET_ERR;
  393. }
  394. }
  395. break;
  396. }
  397. return fd;
  398. }
  399. int anetTcpAccept(char *err, int s, char *ip, size_t ip_len, int *port) {
  400. int fd;
  401. struct sockaddr_storage sa;
  402. socklen_t salen = sizeof(sa);
  403. if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
  404. return ANET_ERR;
  405. if (sa.ss_family == AF_INET) {
  406. struct sockaddr_in *s = (struct sockaddr_in *)&sa;
  407. if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
  408. if (port) *port = ntohs(s->sin_port);
  409. } else {
  410. struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
  411. if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
  412. if (port) *port = ntohs(s->sin6_port);
  413. }
  414. return fd;
  415. }
  416. int anetUnixAccept(char *err, int s) {
  417. int fd;
  418. struct sockaddr_un sa;
  419. socklen_t salen = sizeof(sa);
  420. if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
  421. return ANET_ERR;
  422. return fd;
  423. }
  424. int anetFdToString(int fd, char *ip, size_t ip_len, int *port, int fd_to_str_type) {
  425. struct sockaddr_storage sa;
  426. socklen_t salen = sizeof(sa);
  427. if (fd_to_str_type == FD_TO_PEER_NAME) {
  428. if (getpeername(fd, (struct sockaddr *)&sa, &salen) == -1) goto error;
  429. } else {
  430. if (getsockname(fd, (struct sockaddr *)&sa, &salen) == -1) goto error;
  431. }
  432. if (ip_len == 0) goto error;
  433. if (sa.ss_family == AF_INET) {
  434. struct sockaddr_in *s = (struct sockaddr_in *)&sa;
  435. if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
  436. if (port) *port = ntohs(s->sin_port);
  437. } else if (sa.ss_family == AF_INET6) {
  438. struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
  439. if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
  440. if (port) *port = ntohs(s->sin6_port);
  441. } else if (sa.ss_family == AF_UNIX) {
  442. if (ip) snprintf(ip, ip_len, "/unixsocket");
  443. if (port) *port = 0;
  444. } else {
  445. goto error;
  446. }
  447. return 0;
  448. error:
  449. if (ip) {
  450. if (ip_len >= 2) {
  451. ip[0] = '?';
  452. ip[1] = '\0';
  453. } else if (ip_len == 1) {
  454. ip[0] = '\0';
  455. }
  456. }
  457. if (port) *port = 0;
  458. return -1;
  459. }
  460. /* Format an IP,port pair into something easy to parse. If IP is IPv6
  461. * (matches for ":"), the ip is surrounded by []. IP and port are just
  462. * separated by colons. This the standard to display addresses within Redis. */
  463. int anetFormatAddr(char *buf, size_t buf_len, char *ip, int port) {
  464. return snprintf(buf,buf_len, strchr(ip,':') ?
  465. "[%s]:%d" : "%s:%d", ip, port);
  466. }
  467. /* Like anetFormatAddr() but extract ip and port from the socket's peer/sockname. */
  468. int anetFormatFdAddr(int fd, char *buf, size_t buf_len, int fd_to_str_type) {
  469. char ip[INET6_ADDRSTRLEN];
  470. int port;
  471. anetFdToString(fd,ip,sizeof(ip),&port,fd_to_str_type);
  472. return anetFormatAddr(buf, buf_len, ip, port);
  473. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载