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 <sys/time.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <arpa/inet.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <string.h>
44 #include <netdb.h>
45 #include <errno.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <sys/ioctl.h>
49
50 #include "anet.h"
51
anetSetError(char * err,const char * fmt,...)52 static void anetSetError(char *err, const char *fmt, ...)
53 {
54 va_list ap;
55
56 if (!err) return;
57 va_start(ap, fmt);
58 vsnprintf(err, ANET_ERR_LEN, fmt, ap);
59 va_end(ap);
60 }
61
anetSetBlock(char * err,int fd,int non_block)62 int anetSetBlock(char *err, int fd, int non_block) {
63 #ifdef HAVE_FF_KQUEUE
64 if (ioctl(fd, FIONBIO, &non_block) == -1) {
65 anetSetError(err, "ioctl FIONBIO : %s", strerror(errno));
66 return ANET_ERR;
67 }
68 return ANET_OK;
69 #else
70 int flags;
71
72 /* Set the socket blocking (if non_block is zero) or non-blocking.
73 * Note that fcntl(2) for F_GETFL and F_SETFL can't be
74 * interrupted by a signal. */
75 if ((flags = fcntl(fd, F_GETFL)) == -1) {
76 anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
77 return ANET_ERR;
78 }
79
80 if (non_block)
81 flags |= O_NONBLOCK;
82 else
83 flags &= ~O_NONBLOCK;
84
85 if (fcntl(fd, F_SETFL, flags) == -1) {
86 anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
87 return ANET_ERR;
88 }
89 return ANET_OK;
90 #endif
91 }
92
anetNonBlock(char * err,int fd)93 int anetNonBlock(char *err, int fd) {
94 return anetSetBlock(err,fd,1);
95 }
96
anetBlock(char * err,int fd)97 int anetBlock(char *err, int fd) {
98 return anetSetBlock(err,fd,0);
99 }
100
101 /* Set TCP keep alive option to detect dead peers. The interval option
102 * is only used for Linux as we are using Linux-specific APIs to set
103 * the probe send time, interval, and count. */
anetKeepAlive(char * err,int fd,int interval)104 int anetKeepAlive(char *err, int fd, int interval)
105 {
106 int val = 1;
107
108 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1)
109 {
110 anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
111 return ANET_ERR;
112 }
113
114 #ifdef __linux__
115 /* Default settings are more or less garbage, with the keepalive time
116 * set to 7200 by default on Linux. Modify settings to make the feature
117 * actually useful. */
118
119 /* Send first probe after interval. */
120 val = interval;
121 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
122 anetSetError(err, "setsockopt TCP_KEEPIDLE: %s\n", strerror(errno));
123 return ANET_ERR;
124 }
125
126 /* Send next probes after the specified interval. Note that we set the
127 * delay as interval / 3, as we send three probes before detecting
128 * an error (see the next setsockopt call). */
129 val = interval/3;
130 if (val == 0) val = 1;
131 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
132 anetSetError(err, "setsockopt TCP_KEEPINTVL: %s\n", strerror(errno));
133 return ANET_ERR;
134 }
135
136 /* Consider the socket in error state after three we send three ACK
137 * probes without getting a reply. */
138 val = 3;
139 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
140 anetSetError(err, "setsockopt TCP_KEEPCNT: %s\n", strerror(errno));
141 return ANET_ERR;
142 }
143 #else
144 ((void) interval); /* Avoid unused var warning for non Linux systems. */
145 #endif
146
147 return ANET_OK;
148 }
149
anetSetTcpNoDelay(char * err,int fd,int val)150 static int anetSetTcpNoDelay(char *err, int fd, int val)
151 {
152 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) == -1)
153 {
154 anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno));
155 return ANET_ERR;
156 }
157 return ANET_OK;
158 }
159
anetEnableTcpNoDelay(char * err,int fd)160 int anetEnableTcpNoDelay(char *err, int fd)
161 {
162 return anetSetTcpNoDelay(err, fd, 1);
163 }
164
anetDisableTcpNoDelay(char * err,int fd)165 int anetDisableTcpNoDelay(char *err, int fd)
166 {
167 return anetSetTcpNoDelay(err, fd, 0);
168 }
169
170
anetSetSendBuffer(char * err,int fd,int buffsize)171 int anetSetSendBuffer(char *err, int fd, int buffsize)
172 {
173 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize)) == -1)
174 {
175 anetSetError(err, "setsockopt SO_SNDBUF: %s", strerror(errno));
176 return ANET_ERR;
177 }
178 return ANET_OK;
179 }
180
anetTcpKeepAlive(char * err,int fd)181 int anetTcpKeepAlive(char *err, int fd)
182 {
183 int yes = 1;
184 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) == -1) {
185 anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
186 return ANET_ERR;
187 }
188 return ANET_OK;
189 }
190
191 /* Set the socket send timeout (SO_SNDTIMEO socket option) to the specified
192 * number of milliseconds, or disable it if the 'ms' argument is zero. */
anetSendTimeout(char * err,int fd,long long ms)193 int anetSendTimeout(char *err, int fd, long long ms) {
194 struct timeval tv;
195
196 tv.tv_sec = ms/1000;
197 tv.tv_usec = (ms%1000)*1000;
198 if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
199 anetSetError(err, "setsockopt SO_SNDTIMEO: %s", strerror(errno));
200 return ANET_ERR;
201 }
202 return ANET_OK;
203 }
204
205 /* anetGenericResolve() is called by anetResolve() and anetResolveIP() to
206 * do the actual work. It resolves the hostname "host" and set the string
207 * representation of the IP address into the buffer pointed by "ipbuf".
208 *
209 * If flags is set to ANET_IP_ONLY the function only resolves hostnames
210 * that are actually already IPv4 or IPv6 addresses. This turns the function
211 * into a validating / normalizing function. */
anetGenericResolve(char * err,char * host,char * ipbuf,size_t ipbuf_len,int flags)212 int anetGenericResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len,
213 int flags)
214 {
215 struct addrinfo hints, *info;
216 int rv;
217
218 memset(&hints,0,sizeof(hints));
219 if (flags & ANET_IP_ONLY) hints.ai_flags = AI_NUMERICHOST;
220 hints.ai_family = AF_UNSPEC;
221 hints.ai_socktype = SOCK_STREAM; /* specify socktype to avoid dups */
222
223 if ((rv = getaddrinfo(host, NULL, &hints, &info)) != 0) {
224 anetSetError(err, "%s", gai_strerror(rv));
225 return ANET_ERR;
226 }
227 if (info->ai_family == AF_INET) {
228 struct sockaddr_in *sa = (struct sockaddr_in *)info->ai_addr;
229 inet_ntop(AF_INET, &(sa->sin_addr), ipbuf, ipbuf_len);
230 } else {
231 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)info->ai_addr;
232 inet_ntop(AF_INET6, &(sa->sin6_addr), ipbuf, ipbuf_len);
233 }
234
235 freeaddrinfo(info);
236 return ANET_OK;
237 }
238
anetResolve(char * err,char * host,char * ipbuf,size_t ipbuf_len)239 int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len) {
240 return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_NONE);
241 }
242
anetResolveIP(char * err,char * host,char * ipbuf,size_t ipbuf_len)243 int anetResolveIP(char *err, char *host, char *ipbuf, size_t ipbuf_len) {
244 return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_IP_ONLY);
245 }
246
anetSetReuseAddr(char * err,int fd)247 static int anetSetReuseAddr(char *err, int fd) {
248 int yes = 1;
249 /* Make sure connection-intensive things like the redis benchmark
250 * will be able to close/open sockets a zillion of times */
251 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
252 anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno));
253 return ANET_ERR;
254 }
255 return ANET_OK;
256 }
257
anetCreateSocket(char * err,int domain)258 static int anetCreateSocket(char *err, int domain) {
259 int s;
260 if ((s = socket(domain, SOCK_STREAM, 0)) == -1) {
261 anetSetError(err, "creating socket: %s", strerror(errno));
262 return ANET_ERR;
263 }
264
265 /* Make sure connection-intensive things like the redis benchmark
266 * will be able to close/open sockets a zillion of times */
267 if (anetSetReuseAddr(err,s) == ANET_ERR) {
268 close(s);
269 return ANET_ERR;
270 }
271 return s;
272 }
273
274 #define ANET_CONNECT_NONE 0
275 #define ANET_CONNECT_NONBLOCK 1
276 #define ANET_CONNECT_BE_BINDING 2 /* Best effort binding. */
anetTcpGenericConnect(char * err,char * addr,int port,char * source_addr,int flags)277 static int anetTcpGenericConnect(char *err, char *addr, int port,
278 char *source_addr, int flags)
279 {
280 int s = ANET_ERR, rv;
281 char portstr[6]; /* strlen("65535") + 1; */
282 struct addrinfo hints, *servinfo, *bservinfo, *p, *b;
283
284 snprintf(portstr,sizeof(portstr),"%d",port);
285 memset(&hints,0,sizeof(hints));
286 hints.ai_family = AF_UNSPEC;
287 hints.ai_socktype = SOCK_STREAM;
288
289 if ((rv = getaddrinfo(addr,portstr,&hints,&servinfo)) != 0) {
290 anetSetError(err, "%s", gai_strerror(rv));
291 return ANET_ERR;
292 }
293 for (p = servinfo; p != NULL; p = p->ai_next) {
294 /* Try to create the socket and to connect it.
295 * If we fail in the socket() call, or on connect(), we retry with
296 * the next entry in servinfo. */
297 if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
298 continue;
299 if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
300 if (flags & ANET_CONNECT_NONBLOCK && anetNonBlock(err,s) != ANET_OK)
301 goto error;
302 if (source_addr) {
303 int bound = 0;
304 /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
305 if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0)
306 {
307 anetSetError(err, "%s", gai_strerror(rv));
308 goto error;
309 }
310 for (b = bservinfo; b != NULL; b = b->ai_next) {
311 if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
312 bound = 1;
313 break;
314 }
315 }
316 freeaddrinfo(bservinfo);
317 if (!bound) {
318 anetSetError(err, "bind: %s", strerror(errno));
319 goto error;
320 }
321 }
322 if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
323 /* If the socket is non-blocking, it is ok for connect() to
324 * return an EINPROGRESS error here. */
325 if (errno == EINPROGRESS && flags & ANET_CONNECT_NONBLOCK)
326 goto end;
327 close(s);
328 s = ANET_ERR;
329 continue;
330 }
331
332 /* If we ended an iteration of the for loop without errors, we
333 * have a connected socket. Let's return to the caller. */
334 goto end;
335 }
336 if (p == NULL)
337 anetSetError(err, "creating socket: %s", strerror(errno));
338
339 error:
340 if (s != ANET_ERR) {
341 close(s);
342 s = ANET_ERR;
343 }
344
345 end:
346 freeaddrinfo(servinfo);
347
348 /* Handle best effort binding: if a binding address was used, but it is
349 * not possible to create a socket, try again without a binding address. */
350 if (s == ANET_ERR && source_addr && (flags & ANET_CONNECT_BE_BINDING)) {
351 return anetTcpGenericConnect(err,addr,port,NULL,flags);
352 } else {
353 return s;
354 }
355 }
356
anetTcpConnect(char * err,char * addr,int port)357 int anetTcpConnect(char *err, char *addr, int port)
358 {
359 return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONE);
360 }
361
anetTcpNonBlockConnect(char * err,char * addr,int port)362 int anetTcpNonBlockConnect(char *err, char *addr, int port)
363 {
364 return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONBLOCK);
365 }
366
anetTcpNonBlockBindConnect(char * err,char * addr,int port,char * source_addr)367 int anetTcpNonBlockBindConnect(char *err, char *addr, int port,
368 char *source_addr)
369 {
370 return anetTcpGenericConnect(err,addr,port,source_addr,
371 ANET_CONNECT_NONBLOCK);
372 }
373
anetTcpNonBlockBestEffortBindConnect(char * err,char * addr,int port,char * source_addr)374 int anetTcpNonBlockBestEffortBindConnect(char *err, char *addr, int port,
375 char *source_addr)
376 {
377 return anetTcpGenericConnect(err,addr,port,source_addr,
378 ANET_CONNECT_NONBLOCK|ANET_CONNECT_BE_BINDING);
379 }
380
anetUnixGenericConnect(char * err,char * path,int flags)381 int anetUnixGenericConnect(char *err, char *path, int flags)
382 {
383 int s;
384 struct sockaddr_un sa;
385
386 if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
387 return ANET_ERR;
388
389 sa.sun_family = AF_LOCAL;
390 strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
391 if (flags & ANET_CONNECT_NONBLOCK) {
392 if (anetNonBlock(err,s) != ANET_OK) {
393 close(s);
394 return ANET_ERR;
395 }
396 }
397 if (connect(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) {
398 if (errno == EINPROGRESS &&
399 flags & ANET_CONNECT_NONBLOCK)
400 return s;
401
402 anetSetError(err, "connect: %s", strerror(errno));
403 close(s);
404 return ANET_ERR;
405 }
406 return s;
407 }
408
anetUnixConnect(char * err,char * path)409 int anetUnixConnect(char *err, char *path)
410 {
411 return anetUnixGenericConnect(err,path,ANET_CONNECT_NONE);
412 }
413
anetUnixNonBlockConnect(char * err,char * path)414 int anetUnixNonBlockConnect(char *err, char *path)
415 {
416 return anetUnixGenericConnect(err,path,ANET_CONNECT_NONBLOCK);
417 }
418
419 /* Like read(2) but make sure 'count' is read before to return
420 * (unless error or EOF condition is encountered) */
anetRead(int fd,char * buf,int count)421 int anetRead(int fd, char *buf, int count)
422 {
423 ssize_t nread, totlen = 0;
424 while(totlen != count) {
425 nread = read(fd,buf,count-totlen);
426 if (nread == 0) return totlen;
427 if (nread == -1) return -1;
428 totlen += nread;
429 buf += nread;
430 }
431 return totlen;
432 }
433
434 /* Like write(2) but make sure 'count' is written before to return
435 * (unless error is encountered) */
anetWrite(int fd,char * buf,int count)436 int anetWrite(int fd, char *buf, int count)
437 {
438 ssize_t nwritten, totlen = 0;
439 while(totlen != count) {
440 nwritten = write(fd,buf,count-totlen);
441 if (nwritten == 0) return totlen;
442 if (nwritten == -1) return -1;
443 totlen += nwritten;
444 buf += nwritten;
445 }
446 return totlen;
447 }
448
anetListen(char * err,int s,struct sockaddr * sa,socklen_t len,int backlog)449 static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len, int backlog) {
450 if (bind(s,sa,len) == -1) {
451 anetSetError(err, "bind: %s", strerror(errno));
452 close(s);
453 return ANET_ERR;
454 }
455
456 if (listen(s, backlog) == -1) {
457 anetSetError(err, "listen: %s", strerror(errno));
458 close(s);
459 return ANET_ERR;
460 }
461 return ANET_OK;
462 }
463
anetV6Only(char * err,int s)464 static int anetV6Only(char *err, int s) {
465 int yes = 1;
466 if (setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&yes,sizeof(yes)) == -1) {
467 anetSetError(err, "setsockopt: %s", strerror(errno));
468 close(s);
469 return ANET_ERR;
470 }
471 return ANET_OK;
472 }
473
_anetTcpServer(char * err,int port,char * bindaddr,int af,int backlog)474 static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog)
475 {
476 int s = -1, rv;
477 char _port[6]; /* strlen("65535") */
478 struct addrinfo hints, *servinfo, *p;
479
480 snprintf(_port,6,"%d",port);
481 memset(&hints,0,sizeof(hints));
482 hints.ai_family = af;
483 hints.ai_socktype = SOCK_STREAM;
484 hints.ai_flags = AI_PASSIVE; /* No effect if bindaddr != NULL */
485
486 if ((rv = getaddrinfo(bindaddr,_port,&hints,&servinfo)) != 0) {
487 anetSetError(err, "%s", gai_strerror(rv));
488 return ANET_ERR;
489 }
490 for (p = servinfo; p != NULL; p = p->ai_next) {
491 if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
492 continue;
493
494 if (af == AF_INET6 && anetV6Only(err,s) == ANET_ERR) goto error;
495 if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
496 if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) s = ANET_ERR;
497 goto end;
498 }
499 if (p == NULL) {
500 anetSetError(err, "unable to bind socket, errno: %d", errno);
501 goto error;
502 }
503
504 error:
505 if (s != -1) close(s);
506 s = ANET_ERR;
507 end:
508 freeaddrinfo(servinfo);
509 return s;
510 }
511
anetTcpServer(char * err,int port,char * bindaddr,int backlog)512 int anetTcpServer(char *err, int port, char *bindaddr, int backlog)
513 {
514 return _anetTcpServer(err, port, bindaddr, AF_INET, backlog);
515 }
516
anetTcp6Server(char * err,int port,char * bindaddr,int backlog)517 int anetTcp6Server(char *err, int port, char *bindaddr, int backlog)
518 {
519 return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog);
520 }
521
anetUnixServer(char * err,char * path,mode_t perm,int backlog)522 int anetUnixServer(char *err, char *path, mode_t perm, int backlog)
523 {
524 int s;
525 struct sockaddr_un sa;
526
527 if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
528 return ANET_ERR;
529
530 memset(&sa,0,sizeof(sa));
531 sa.sun_family = AF_LOCAL;
532 strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
533 if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa),backlog) == ANET_ERR)
534 return ANET_ERR;
535 if (perm)
536 chmod(sa.sun_path, perm);
537 return s;
538 }
539
anetGenericAccept(char * err,int s,struct sockaddr * sa,socklen_t * len)540 static int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len) {
541 int fd;
542 while(1) {
543 fd = accept(s,sa,len);
544 if (fd == -1) {
545 if (errno == EINTR)
546 continue;
547 else {
548 anetSetError(err, "accept: %s", strerror(errno));
549 return ANET_ERR;
550 }
551 }
552 break;
553 }
554 return fd;
555 }
556
anetTcpAccept(char * err,int s,char * ip,size_t ip_len,int * port)557 int anetTcpAccept(char *err, int s, char *ip, size_t ip_len, int *port) {
558 int fd;
559 struct sockaddr_storage sa;
560 socklen_t salen = sizeof(sa);
561 if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
562 return ANET_ERR;
563
564 if (sa.ss_family == AF_INET) {
565 struct sockaddr_in *s = (struct sockaddr_in *)&sa;
566 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
567 if (port) *port = ntohs(s->sin_port);
568 } else {
569 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
570 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
571 if (port) *port = ntohs(s->sin6_port);
572 }
573 return fd;
574 }
575
anetUnixAccept(char * err,int s)576 int anetUnixAccept(char *err, int s) {
577 int fd;
578 struct sockaddr_un sa;
579 socklen_t salen = sizeof(sa);
580 if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
581 return ANET_ERR;
582
583 return fd;
584 }
585
anetPeerToString(int fd,char * ip,size_t ip_len,int * port)586 int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) {
587 struct sockaddr_storage sa;
588 socklen_t salen = sizeof(sa);
589
590 if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) goto error;
591 if (ip_len == 0) goto error;
592
593 if (sa.ss_family == AF_INET) {
594 struct sockaddr_in *s = (struct sockaddr_in *)&sa;
595 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
596 if (port) *port = ntohs(s->sin_port);
597 } else if (sa.ss_family == AF_INET6) {
598 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
599 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
600 if (port) *port = ntohs(s->sin6_port);
601 } else if (sa.ss_family == AF_UNIX) {
602 if (ip) strncpy(ip,"/unixsocket",ip_len);
603 if (port) *port = 0;
604 } else {
605 goto error;
606 }
607 return 0;
608
609 error:
610 if (ip) {
611 if (ip_len >= 2) {
612 ip[0] = '?';
613 ip[1] = '\0';
614 } else if (ip_len == 1) {
615 ip[0] = '\0';
616 }
617 }
618 if (port) *port = 0;
619 return -1;
620 }
621
622 /* Format an IP,port pair into something easy to parse. If IP is IPv6
623 * (matches for ":"), the ip is surrounded by []. IP and port are just
624 * separated by colons. This the standard to display addresses within Redis. */
anetFormatAddr(char * buf,size_t buf_len,char * ip,int port)625 int anetFormatAddr(char *buf, size_t buf_len, char *ip, int port) {
626 return snprintf(buf,buf_len, strchr(ip,':') ?
627 "[%s]:%d" : "%s:%d", ip, port);
628 }
629
630 /* Like anetFormatAddr() but extract ip and port from the socket's peer. */
anetFormatPeer(int fd,char * buf,size_t buf_len)631 int anetFormatPeer(int fd, char *buf, size_t buf_len) {
632 char ip[INET6_ADDRSTRLEN];
633 int port;
634
635 anetPeerToString(fd,ip,sizeof(ip),&port);
636 return anetFormatAddr(buf, buf_len, ip, port);
637 }
638
anetSockName(int fd,char * ip,size_t ip_len,int * port)639 int anetSockName(int fd, char *ip, size_t ip_len, int *port) {
640 struct sockaddr_storage sa;
641 socklen_t salen = sizeof(sa);
642
643 if (getsockname(fd,(struct sockaddr*)&sa,&salen) == -1) {
644 if (port) *port = 0;
645 ip[0] = '?';
646 ip[1] = '\0';
647 return -1;
648 }
649 if (sa.ss_family == AF_INET) {
650 struct sockaddr_in *s = (struct sockaddr_in *)&sa;
651 if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
652 if (port) *port = ntohs(s->sin_port);
653 } else {
654 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
655 if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
656 if (port) *port = ntohs(s->sin6_port);
657 }
658 return 0;
659 }
660
anetFormatSock(int fd,char * fmt,size_t fmt_len)661 int anetFormatSock(int fd, char *fmt, size_t fmt_len) {
662 char ip[INET6_ADDRSTRLEN];
663 int port;
664
665 anetSockName(fd,ip,sizeof(ip),&port);
666 return anetFormatAddr(fmt, fmt_len, ip, port);
667 }
668