1 /* anet.c -- Basic TCP socket stuff made a bit less boring 2 * 3 * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com> 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions are met: 8 * 9 * * Redistributions of source code must retain the above copyright notice, 10 * this list of conditions and the following disclaimer. 11 * * Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * * Neither the name of Redis nor the names of its contributors may be used 15 * to endorse or promote products derived from this software without 16 * specific prior written permission. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 * POSSIBILITY OF SUCH DAMAGE. 29 */ 30 31 #include "fmacros.h" 32 33 #include <sys/types.h> 34 #include <sys/socket.h> 35 #include <sys/stat.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 48 #include "anet.h" 49 50 static void anetSetError(char *err, const char *fmt, ...) 51 { 52 va_list ap; 53 54 if (!err) return; 55 va_start(ap, fmt); 56 vsnprintf(err, ANET_ERR_LEN, fmt, ap); 57 va_end(ap); 58 } 59 60 int anetNonBlock(char *err, int fd) 61 { 62 int flags; 63 64 /* Set the socket non-blocking. 65 * Note that fcntl(2) for F_GETFL and F_SETFL can't be 66 * interrupted by a signal. */ 67 if ((flags = fcntl(fd, F_GETFL)) == -1) { 68 anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno)); 69 return ANET_ERR; 70 } 71 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { 72 anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno)); 73 return ANET_ERR; 74 } 75 return ANET_OK; 76 } 77 78 /* Set TCP keep alive option to detect dead peers. The interval option 79 * is only used for Linux as we are using Linux-specific APIs to set 80 * the probe send time, interval, and count. */ 81 int anetKeepAlive(char *err, int fd, int interval) 82 { 83 int val = 1; 84 85 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1) 86 { 87 anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno)); 88 return ANET_ERR; 89 } 90 91 #ifdef __linux__ 92 /* Default settings are more or less garbage, with the keepalive time 93 * set to 7200 by default on Linux. Modify settings to make the feature 94 * actually useful. */ 95 96 /* Send first probe after interval. */ 97 val = interval; 98 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) { 99 anetSetError(err, "setsockopt TCP_KEEPIDLE: %s\n", strerror(errno)); 100 return ANET_ERR; 101 } 102 103 /* Send next probes after the specified interval. Note that we set the 104 * delay as interval / 3, as we send three probes before detecting 105 * an error (see the next setsockopt call). */ 106 val = interval/3; 107 if (val == 0) val = 1; 108 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) { 109 anetSetError(err, "setsockopt TCP_KEEPINTVL: %s\n", strerror(errno)); 110 return ANET_ERR; 111 } 112 113 /* Consider the socket in error state after three we send three ACK 114 * probes without getting a reply. */ 115 val = 3; 116 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) { 117 anetSetError(err, "setsockopt TCP_KEEPCNT: %s\n", strerror(errno)); 118 return ANET_ERR; 119 } 120 #endif 121 122 return ANET_OK; 123 } 124 125 static int anetSetTcpNoDelay(char *err, int fd, int val) 126 { 127 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) == -1) 128 { 129 anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno)); 130 return ANET_ERR; 131 } 132 return ANET_OK; 133 } 134 135 int anetEnableTcpNoDelay(char *err, int fd) 136 { 137 return anetSetTcpNoDelay(err, fd, 1); 138 } 139 140 int anetDisableTcpNoDelay(char *err, int fd) 141 { 142 return anetSetTcpNoDelay(err, fd, 0); 143 } 144 145 146 int anetSetSendBuffer(char *err, int fd, int buffsize) 147 { 148 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize)) == -1) 149 { 150 anetSetError(err, "setsockopt SO_SNDBUF: %s", strerror(errno)); 151 return ANET_ERR; 152 } 153 return ANET_OK; 154 } 155 156 int anetTcpKeepAlive(char *err, int fd) 157 { 158 int yes = 1; 159 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) == -1) { 160 anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno)); 161 return ANET_ERR; 162 } 163 return ANET_OK; 164 } 165 166 /* anetGenericResolve() is called by anetResolve() and anetResolveIP() to 167 * do the actual work. It resolves the hostname "host" and set the string 168 * representation of the IP address into the buffer pointed by "ipbuf". 169 * 170 * If flags is set to ANET_IP_ONLY the function only resolves hostnames 171 * that are actually already IPv4 or IPv6 addresses. This turns the function 172 * into a validating / normalizing function. */ 173 int anetGenericResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len, 174 int flags) 175 { 176 struct addrinfo hints, *info; 177 int rv; 178 179 memset(&hints,0,sizeof(hints)); 180 if (flags & ANET_IP_ONLY) hints.ai_flags = AI_NUMERICHOST; 181 hints.ai_family = AF_UNSPEC; 182 hints.ai_socktype = SOCK_STREAM; /* specify socktype to avoid dups */ 183 184 if ((rv = getaddrinfo(host, NULL, &hints, &info)) != 0) { 185 anetSetError(err, "%s", gai_strerror(rv)); 186 return ANET_ERR; 187 } 188 if (info->ai_family == AF_INET) { 189 struct sockaddr_in *sa = (struct sockaddr_in *)info->ai_addr; 190 inet_ntop(AF_INET, &(sa->sin_addr), ipbuf, ipbuf_len); 191 } else { 192 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)info->ai_addr; 193 inet_ntop(AF_INET6, &(sa->sin6_addr), ipbuf, ipbuf_len); 194 } 195 196 freeaddrinfo(info); 197 return ANET_OK; 198 } 199 200 int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len) { 201 return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_NONE); 202 } 203 204 int anetResolveIP(char *err, char *host, char *ipbuf, size_t ipbuf_len) { 205 return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_IP_ONLY); 206 } 207 208 static int anetSetReuseAddr(char *err, int fd) { 209 int yes = 1; 210 /* Make sure connection-intensive things like the redis benckmark 211 * will be able to close/open sockets a zillion of times */ 212 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) { 213 anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno)); 214 return ANET_ERR; 215 } 216 return ANET_OK; 217 } 218 219 static int anetCreateSocket(char *err, int domain) { 220 int s; 221 if ((s = socket(domain, SOCK_STREAM, 0)) == -1) { 222 anetSetError(err, "creating socket: %s", strerror(errno)); 223 return ANET_ERR; 224 } 225 226 /* Make sure connection-intensive things like the redis benchmark 227 * will be able to close/open sockets a zillion of times */ 228 if (anetSetReuseAddr(err,s) == ANET_ERR) { 229 close(s); 230 return ANET_ERR; 231 } 232 return s; 233 } 234 235 #define ANET_CONNECT_NONE 0 236 #define ANET_CONNECT_NONBLOCK 1 237 static int anetTcpGenericConnect(char *err, char *addr, int port, 238 char *source_addr, int flags) 239 { 240 int s = ANET_ERR, rv; 241 char portstr[6]; /* strlen("65535") + 1; */ 242 struct addrinfo hints, *servinfo, *bservinfo, *p, *b; 243 244 snprintf(portstr,sizeof(portstr),"%d",port); 245 memset(&hints,0,sizeof(hints)); 246 hints.ai_family = AF_UNSPEC; 247 hints.ai_socktype = SOCK_STREAM; 248 249 if ((rv = getaddrinfo(addr,portstr,&hints,&servinfo)) != 0) { 250 anetSetError(err, "%s", gai_strerror(rv)); 251 return ANET_ERR; 252 } 253 for (p = servinfo; p != NULL; p = p->ai_next) { 254 /* Try to create the socket and to connect it. 255 * If we fail in the socket() call, or on connect(), we retry with 256 * the next entry in servinfo. */ 257 if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) 258 continue; 259 if (anetSetReuseAddr(err,s) == ANET_ERR) goto error; 260 if (flags & ANET_CONNECT_NONBLOCK && anetNonBlock(err,s) != ANET_OK) 261 goto error; 262 if (source_addr) { 263 int bound = 0; 264 /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */ 265 if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0) { 266 anetSetError(err, "%s", gai_strerror(rv)); 267 goto end; 268 } 269 for (b = bservinfo; b != NULL; b = b->ai_next) { 270 if (bind(s,b->ai_addr,b->ai_addrlen) != -1) { 271 bound = 1; 272 break; 273 } 274 } 275 if (!bound) { 276 anetSetError(err, "bind: %s", strerror(errno)); 277 goto end; 278 } 279 } 280 if (connect(s,p->ai_addr,p->ai_addrlen) == -1) { 281 /* If the socket is non-blocking, it is ok for connect() to 282 * return an EINPROGRESS error here. */ 283 if (errno == EINPROGRESS && flags & ANET_CONNECT_NONBLOCK) 284 goto end; 285 close(s); 286 s = ANET_ERR; 287 continue; 288 } 289 290 /* If we ended an iteration of the for loop without errors, we 291 * have a connected socket. Let's return to the caller. */ 292 goto end; 293 } 294 if (p == NULL) 295 anetSetError(err, "creating socket: %s", strerror(errno)); 296 297 error: 298 if (s != ANET_ERR) { 299 close(s); 300 s = ANET_ERR; 301 } 302 end: 303 freeaddrinfo(servinfo); 304 return s; 305 } 306 307 int anetTcpConnect(char *err, char *addr, int port) 308 { 309 return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONE); 310 } 311 312 int anetTcpNonBlockConnect(char *err, char *addr, int port) 313 { 314 return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONBLOCK); 315 } 316 317 int anetTcpNonBlockBindConnect(char *err, char *addr, int port, char *source_addr) 318 { 319 return anetTcpGenericConnect(err,addr,port,source_addr,ANET_CONNECT_NONBLOCK); 320 } 321 322 int anetUnixGenericConnect(char *err, char *path, int flags) 323 { 324 int s; 325 struct sockaddr_un sa; 326 327 if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR) 328 return ANET_ERR; 329 330 sa.sun_family = AF_LOCAL; 331 strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1); 332 if (flags & ANET_CONNECT_NONBLOCK) { 333 if (anetNonBlock(err,s) != ANET_OK) 334 return ANET_ERR; 335 } 336 if (connect(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) { 337 if (errno == EINPROGRESS && 338 flags & ANET_CONNECT_NONBLOCK) 339 return s; 340 341 anetSetError(err, "connect: %s", strerror(errno)); 342 close(s); 343 return ANET_ERR; 344 } 345 return s; 346 } 347 348 int anetUnixConnect(char *err, char *path) 349 { 350 return anetUnixGenericConnect(err,path,ANET_CONNECT_NONE); 351 } 352 353 int anetUnixNonBlockConnect(char *err, char *path) 354 { 355 return anetUnixGenericConnect(err,path,ANET_CONNECT_NONBLOCK); 356 } 357 358 /* Like read(2) but make sure 'count' is read before to return 359 * (unless error or EOF condition is encountered) */ 360 int anetRead(int fd, char *buf, int count) 361 { 362 int nread, totlen = 0; 363 while(totlen != count) { 364 nread = read(fd,buf,count-totlen); 365 if (nread == 0) return totlen; 366 if (nread == -1) return -1; 367 totlen += nread; 368 buf += nread; 369 } 370 return totlen; 371 } 372 373 /* Like write(2) but make sure 'count' is read before to return 374 * (unless error is encountered) */ 375 int anetWrite(int fd, char *buf, int count) 376 { 377 int nwritten, totlen = 0; 378 while(totlen != count) { 379 nwritten = write(fd,buf,count-totlen); 380 if (nwritten == 0) return totlen; 381 if (nwritten == -1) return -1; 382 totlen += nwritten; 383 buf += nwritten; 384 } 385 return totlen; 386 } 387 388 static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len, int backlog) { 389 if (bind(s,sa,len) == -1) { 390 anetSetError(err, "bind: %s", strerror(errno)); 391 close(s); 392 return ANET_ERR; 393 } 394 395 if (listen(s, backlog) == -1) { 396 anetSetError(err, "listen: %s", strerror(errno)); 397 close(s); 398 return ANET_ERR; 399 } 400 return ANET_OK; 401 } 402 403 static int anetV6Only(char *err, int s) { 404 int yes = 1; 405 if (setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&yes,sizeof(yes)) == -1) { 406 anetSetError(err, "setsockopt: %s", strerror(errno)); 407 close(s); 408 return ANET_ERR; 409 } 410 return ANET_OK; 411 } 412 413 static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog) 414 { 415 int s, rv; 416 char _port[6]; /* strlen("65535") */ 417 struct addrinfo hints, *servinfo, *p; 418 419 snprintf(_port,6,"%d",port); 420 memset(&hints,0,sizeof(hints)); 421 hints.ai_family = af; 422 hints.ai_socktype = SOCK_STREAM; 423 hints.ai_flags = AI_PASSIVE; /* No effect if bindaddr != NULL */ 424 425 if ((rv = getaddrinfo(bindaddr,_port,&hints,&servinfo)) != 0) { 426 anetSetError(err, "%s", gai_strerror(rv)); 427 return ANET_ERR; 428 } 429 for (p = servinfo; p != NULL; p = p->ai_next) { 430 if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) 431 continue; 432 433 if (af == AF_INET6 && anetV6Only(err,s) == ANET_ERR) goto error; 434 if (anetSetReuseAddr(err,s) == ANET_ERR) goto error; 435 if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) goto error; 436 goto end; 437 } 438 if (p == NULL) { 439 anetSetError(err, "unable to bind socket"); 440 goto error; 441 } 442 443 error: 444 s = ANET_ERR; 445 end: 446 freeaddrinfo(servinfo); 447 return s; 448 } 449 450 int anetTcpServer(char *err, int port, char *bindaddr, int backlog) 451 { 452 return _anetTcpServer(err, port, bindaddr, AF_INET, backlog); 453 } 454 455 int anetTcp6Server(char *err, int port, char *bindaddr, int backlog) 456 { 457 return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog); 458 } 459 460 int anetUnixServer(char *err, char *path, mode_t perm, int backlog) 461 { 462 int s; 463 struct sockaddr_un sa; 464 465 if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR) 466 return ANET_ERR; 467 468 memset(&sa,0,sizeof(sa)); 469 sa.sun_family = AF_LOCAL; 470 strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1); 471 if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa),backlog) == ANET_ERR) 472 return ANET_ERR; 473 if (perm) 474 chmod(sa.sun_path, perm); 475 return s; 476 } 477 478 static int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len) { 479 int fd; 480 while(1) { 481 fd = accept(s,sa,len); 482 if (fd == -1) { 483 if (errno == EINTR) 484 continue; 485 else { 486 anetSetError(err, "accept: %s", strerror(errno)); 487 return ANET_ERR; 488 } 489 } 490 break; 491 } 492 return fd; 493 } 494 495 int anetTcpAccept(char *err, int s, char *ip, size_t ip_len, int *port) { 496 int fd; 497 struct sockaddr_storage sa; 498 socklen_t salen = sizeof(sa); 499 if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == ANET_ERR) 500 return ANET_ERR; 501 502 if (sa.ss_family == AF_INET) { 503 struct sockaddr_in *s = (struct sockaddr_in *)&sa; 504 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len); 505 if (port) *port = ntohs(s->sin_port); 506 } else { 507 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa; 508 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len); 509 if (port) *port = ntohs(s->sin6_port); 510 } 511 return fd; 512 } 513 514 int anetUnixAccept(char *err, int s) { 515 int fd; 516 struct sockaddr_un sa; 517 socklen_t salen = sizeof(sa); 518 if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == ANET_ERR) 519 return ANET_ERR; 520 521 return fd; 522 } 523 524 int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) { 525 struct sockaddr_storage sa; 526 socklen_t salen = sizeof(sa); 527 528 if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) { 529 if (port) *port = 0; 530 ip[0] = '?'; 531 ip[1] = '\0'; 532 return -1; 533 } 534 if (sa.ss_family == AF_INET) { 535 struct sockaddr_in *s = (struct sockaddr_in *)&sa; 536 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len); 537 if (port) *port = ntohs(s->sin_port); 538 } else { 539 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa; 540 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len); 541 if (port) *port = ntohs(s->sin6_port); 542 } 543 return 0; 544 } 545 546 int anetSockName(int fd, char *ip, size_t ip_len, int *port) { 547 struct sockaddr_storage sa; 548 socklen_t salen = sizeof(sa); 549 550 if (getsockname(fd,(struct sockaddr*)&sa,&salen) == -1) { 551 if (port) *port = 0; 552 ip[0] = '?'; 553 ip[1] = '\0'; 554 return -1; 555 } 556 if (sa.ss_family == AF_INET) { 557 struct sockaddr_in *s = (struct sockaddr_in *)&sa; 558 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len); 559 if (port) *port = ntohs(s->sin_port); 560 } else { 561 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa; 562 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len); 563 if (port) *port = ntohs(s->sin6_port); 564 } 565 return 0; 566 } 567