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