anet.c 20.2 KB
Newer Older
A
antirez 已提交
1 2
/* anet.c -- Basic TCP socket stuff made a bit less boring
 *
3
 * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
A
antirez 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

31 32
#include "fmacros.h"

A
antirez 已提交
33 34
#include <sys/types.h>
#include <sys/socket.h>
35
#include <sys/stat.h>
36
#include <sys/un.h>
A
antirez 已提交
37
#include <sys/time.h>
A
antirez 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>

#include "anet.h"

static void anetSetError(char *err, const char *fmt, ...)
{
    va_list ap;

    if (!err) return;
    va_start(ap, fmt);
    vsnprintf(err, ANET_ERR_LEN, fmt, ap);
    va_end(ap);
}

61
int anetSetBlock(char *err, int fd, int non_block) {
A
antirez 已提交
62 63
    int flags;

64
    /* Set the socket blocking (if non_block is zero) or non-blocking.
A
antirez 已提交
65 66 67
     * Note that fcntl(2) for F_GETFL and F_SETFL can't be
     * interrupted by a signal. */
    if ((flags = fcntl(fd, F_GETFL)) == -1) {
68
        anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
A
antirez 已提交
69 70
        return ANET_ERR;
    }
71 72 73 74 75 76 77

    if (non_block)
        flags |= O_NONBLOCK;
    else
        flags &= ~O_NONBLOCK;

    if (fcntl(fd, F_SETFL, flags) == -1) {
78
        anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
A
antirez 已提交
79 80 81 82 83
        return ANET_ERR;
    }
    return ANET_OK;
}

84 85 86 87 88 89 90 91
int anetNonBlock(char *err, int fd) {
    return anetSetBlock(err,fd,1);
}

int anetBlock(char *err, int fd) {
    return anetSetBlock(err,fd,0);
}

A
antirez 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
/* Set TCP keep alive option to detect dead peers. The interval option
 * is only used for Linux as we are using Linux-specific APIs to set
 * the probe send time, interval, and count. */
int anetKeepAlive(char *err, int fd, int interval)
{
    int val = 1;

    if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1)
    {
        anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
        return ANET_ERR;
    }

#ifdef __linux__
    /* Default settings are more or less garbage, with the keepalive time
     * set to 7200 by default on Linux. Modify settings to make the feature
     * actually useful. */

    /* Send first probe after interval. */
    val = interval;
    if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
        anetSetError(err, "setsockopt TCP_KEEPIDLE: %s\n", strerror(errno));
        return ANET_ERR;
    }

117 118 119 120 121
    /* Send next probes after the specified interval. Note that we set the
     * delay as interval / 3, as we send three probes before detecting
     * an error (see the next setsockopt call). */
    val = interval/3;
    if (val == 0) val = 1;
A
antirez 已提交
122 123 124 125 126
    if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
        anetSetError(err, "setsockopt TCP_KEEPINTVL: %s\n", strerror(errno));
        return ANET_ERR;
    }

127 128 129
    /* Consider the socket in error state after three we send three ACK
     * probes without getting a reply. */
    val = 3;
A
antirez 已提交
130 131 132 133
    if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
        anetSetError(err, "setsockopt TCP_KEEPCNT: %s\n", strerror(errno));
        return ANET_ERR;
    }
134 135
#else
    ((void) interval); /* Avoid unused var warning for non Linux systems. */
A
antirez 已提交
136 137 138 139 140
#endif

    return ANET_OK;
}

141
static int anetSetTcpNoDelay(char *err, int fd, int val)
A
antirez 已提交
142
{
143
    if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) == -1)
A
antirez 已提交
144
    {
145
        anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno));
A
antirez 已提交
146 147 148 149 150
        return ANET_ERR;
    }
    return ANET_OK;
}

151
int anetEnableTcpNoDelay(char *err, int fd)
152
{
153
    return anetSetTcpNoDelay(err, fd, 1);
154 155
}

156
int anetDisableTcpNoDelay(char *err, int fd)
157
{
158
    return anetSetTcpNoDelay(err, fd, 0);
159 160 161
}


A
antirez 已提交
162 163 164 165
int anetSetSendBuffer(char *err, int fd, int buffsize)
{
    if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize)) == -1)
    {
166
        anetSetError(err, "setsockopt SO_SNDBUF: %s", strerror(errno));
A
antirez 已提交
167 168 169 170 171 172 173 174 175
        return ANET_ERR;
    }
    return ANET_OK;
}

int anetTcpKeepAlive(char *err, int fd)
{
    int yes = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) == -1) {
176
        anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
A
antirez 已提交
177 178 179 180 181
        return ANET_ERR;
    }
    return ANET_OK;
}

A
antirez 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195
/* Set the socket send timeout (SO_SNDTIMEO socket option) to the specified
 * number of milliseconds, or disable it if the 'ms' argument is zero. */
int anetSendTimeout(char *err, int fd, long long ms) {
    struct timeval tv;

    tv.tv_sec = ms/1000;
    tv.tv_usec = (ms%1000)*1000;
    if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
        anetSetError(err, "setsockopt SO_SNDTIMEO: %s", strerror(errno));
        return ANET_ERR;
    }
    return ANET_OK;
}

A
antirez 已提交
196 197 198 199 200 201 202 203 204
/* anetGenericResolve() is called by anetResolve() and anetResolveIP() to
 * do the actual work. It resolves the hostname "host" and set the string
 * representation of the IP address into the buffer pointed by "ipbuf".
 *
 * If flags is set to ANET_IP_ONLY the function only resolves hostnames
 * that are actually already IPv4 or IPv6 addresses. This turns the function
 * into a validating / normalizing function. */
int anetGenericResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len,
                       int flags)
A
antirez 已提交
205
{
206 207
    struct addrinfo hints, *info;
    int rv;
A
antirez 已提交
208

209
    memset(&hints,0,sizeof(hints));
A
antirez 已提交
210
    if (flags & ANET_IP_ONLY) hints.ai_flags = AI_NUMERICHOST;
211 212
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;  /* specify socktype to avoid dups */
213 214 215 216 217 218 219

    if ((rv = getaddrinfo(host, NULL, &hints, &info)) != 0) {
        anetSetError(err, "%s", gai_strerror(rv));
        return ANET_ERR;
    }
    if (info->ai_family == AF_INET) {
        struct sockaddr_in *sa = (struct sockaddr_in *)info->ai_addr;
220 221 222 223
        inet_ntop(AF_INET, &(sa->sin_addr), ipbuf, ipbuf_len);
    } else {
        struct sockaddr_in6 *sa = (struct sockaddr_in6 *)info->ai_addr;
        inet_ntop(AF_INET6, &(sa->sin6_addr), ipbuf, ipbuf_len);
A
antirez 已提交
224
    }
225 226

    freeaddrinfo(info);
A
antirez 已提交
227 228 229
    return ANET_OK;
}

A
antirez 已提交
230 231 232 233 234 235 236 237
int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len) {
    return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_NONE);
}

int anetResolveIP(char *err, char *host, char *ipbuf, size_t ipbuf_len) {
    return anetGenericResolve(err,host,ipbuf,ipbuf_len,ANET_IP_ONLY);
}

238 239 240 241 242 243 244 245 246 247 248
static int anetSetReuseAddr(char *err, int fd) {
    int yes = 1;
    /* Make sure connection-intensive things like the redis benckmark
     * will be able to close/open sockets a zillion of times */
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
        anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno));
        return ANET_ERR;
    }
    return ANET_OK;
}

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 254 255
        return ANET_ERR;
    }

G
guiquanz 已提交
256
    /* Make sure connection-intensive things like the redis benchmark
257
     * will be able to close/open sockets a zillion of times */
258 259
    if (anetSetReuseAddr(err,s) == ANET_ERR) {
        close(s);
260 261 262 263 264
        return ANET_ERR;
    }
    return s;
}

A
antirez 已提交
265 266
#define ANET_CONNECT_NONE 0
#define ANET_CONNECT_NONBLOCK 1
267
#define ANET_CONNECT_BE_BINDING 2 /* Best effort binding. */
268 269
static int anetTcpGenericConnect(char *err, char *addr, int port,
                                 char *source_addr, int flags)
A
antirez 已提交
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;
A
antirez 已提交
279

280
    if ((rv = getaddrinfo(addr,portstr,&hints,&servinfo)) != 0) {
281
        anetSetError(err, "%s", gai_strerror(rv));
A
antirez 已提交
282
        return ANET_ERR;
283 284
    }
    for (p = servinfo; p != NULL; p = p->ai_next) {
285 286 287
        /* Try to create the socket and to connect it.
         * If we fail in the socket() call, or on connect(), we retry with
         * the next entry in servinfo. */
288 289
        if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
            continue;
A
antirez 已提交
290 291
        if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
        if (flags & ANET_CONNECT_NONBLOCK && anetNonBlock(err,s) != ANET_OK)
292
            goto error;
293 294 295
        if (source_addr) {
            int bound = 0;
            /* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
296 297
            if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0)
            {
298
                anetSetError(err, "%s", gai_strerror(rv));
299
                goto error;
300 301 302 303 304 305 306
            }
            for (b = bservinfo; b != NULL; b = b->ai_next) {
                if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
                    bound = 1;
                    break;
                }
            }
307
            freeaddrinfo(bservinfo);
308 309
            if (!bound) {
                anetSetError(err, "bind: %s", strerror(errno));
310
                goto error;
311 312
            }
        }
313
        if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
314 315 316 317
            /* If the socket is non-blocking, it is ok for connect() to
             * return an EINPROGRESS error here. */
            if (errno == EINPROGRESS && flags & ANET_CONNECT_NONBLOCK)
                goto end;
A
antirez 已提交
318
            close(s);
319
            s = ANET_ERR;
320
            continue;
A
antirez 已提交
321
        }
322

323 324
        /* If we ended an iteration of the for loop without errors, we
         * have a connected socket. Let's return to the caller. */
325
        goto end;
A
antirez 已提交
326
    }
327
    if (p == NULL)
328
        anetSetError(err, "creating socket: %s", strerror(errno));
A
antirez 已提交
329

330
error:
331 332 333 334
    if (s != ANET_ERR) {
        close(s);
        s = ANET_ERR;
    }
335

336 337
end:
    freeaddrinfo(servinfo);
338 339 340 341 342 343 344 345

    /* Handle best effort binding: if a binding address was used, but it is
     * not possible to create a socket, try again without a binding address. */
    if (s == ANET_ERR && source_addr && (flags & ANET_CONNECT_BE_BINDING)) {
        return anetTcpGenericConnect(err,addr,port,NULL,flags);
    } else {
        return s;
    }
A
antirez 已提交
346 347 348 349
}

int anetTcpConnect(char *err, char *addr, int port)
{
350
    return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONE);
A
antirez 已提交
351 352 353 354
}

int anetTcpNonBlockConnect(char *err, char *addr, int port)
{
355 356 357
    return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONBLOCK);
}

358 359 360 361 362 363 364 365 366
int anetTcpNonBlockBindConnect(char *err, char *addr, int port,
                               char *source_addr)
{
    return anetTcpGenericConnect(err,addr,port,source_addr,
            ANET_CONNECT_NONBLOCK);
}

int anetTcpNonBlockBestEffortBindConnect(char *err, char *addr, int port,
                                         char *source_addr)
367
{
368 369
    return anetTcpGenericConnect(err,addr,port,source_addr,
            ANET_CONNECT_NONBLOCK|ANET_CONNECT_BE_BINDING);
A
antirez 已提交
370 371
}

372 373 374 375 376
int anetUnixGenericConnect(char *err, char *path, int flags)
{
    int s;
    struct sockaddr_un sa;

377
    if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
378
        return ANET_ERR;
379

380 381 382
    sa.sun_family = AF_LOCAL;
    strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
    if (flags & ANET_CONNECT_NONBLOCK) {
383 384
        if (anetNonBlock(err,s) != ANET_OK) {
            close(s);
385
            return ANET_ERR;
386
        }
387 388 389 390 391 392
    }
    if (connect(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) {
        if (errno == EINPROGRESS &&
            flags & ANET_CONNECT_NONBLOCK)
            return s;

393
        anetSetError(err, "connect: %s", strerror(errno));
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        close(s);
        return ANET_ERR;
    }
    return s;
}

int anetUnixConnect(char *err, char *path)
{
    return anetUnixGenericConnect(err,path,ANET_CONNECT_NONE);
}

int anetUnixNonBlockConnect(char *err, char *path)
{
    return anetUnixGenericConnect(err,path,ANET_CONNECT_NONBLOCK);
}

A
antirez 已提交
410 411
/* Like read(2) but make sure 'count' is read before to return
 * (unless error or EOF condition is encountered) */
A
antirez 已提交
412
int anetRead(int fd, char *buf, int count)
A
antirez 已提交
413
{
414
    ssize_t nread, totlen = 0;
A
antirez 已提交
415 416 417 418 419 420 421 422 423 424
    while(totlen != count) {
        nread = read(fd,buf,count-totlen);
        if (nread == 0) return totlen;
        if (nread == -1) return -1;
        totlen += nread;
        buf += nread;
    }
    return totlen;
}

H
Huachao Huang 已提交
425
/* Like write(2) but make sure 'count' is written before to return
A
antirez 已提交
426
 * (unless error is encountered) */
A
antirez 已提交
427
int anetWrite(int fd, char *buf, int count)
A
antirez 已提交
428
{
429
    ssize_t nwritten, totlen = 0;
A
antirez 已提交
430 431 432 433 434 435 436 437 438 439
    while(totlen != count) {
        nwritten = write(fd,buf,count-totlen);
        if (nwritten == 0) return totlen;
        if (nwritten == -1) return -1;
        totlen += nwritten;
        buf += nwritten;
    }
    return totlen;
}

440
static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len, int backlog) {
441
    if (bind(s,sa,len) == -1) {
442
        anetSetError(err, "bind: %s", strerror(errno));
443
        close(s);
A
antirez 已提交
444 445
        return ANET_ERR;
    }
446

447
    if (listen(s, backlog) == -1) {
448
        anetSetError(err, "listen: %s", strerror(errno));
A
antirez 已提交
449 450 451
        close(s);
        return ANET_ERR;
    }
452 453 454
    return ANET_OK;
}

455 456 457 458 459 460 461 462 463 464
static int anetV6Only(char *err, int s) {
    int yes = 1;
    if (setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,&yes,sizeof(yes)) == -1) {
        anetSetError(err, "setsockopt: %s", strerror(errno));
        close(s);
        return ANET_ERR;
    }
    return ANET_OK;
}

465
static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog)
466
{
467 468 469
    int s, rv;
    char _port[6];  /* strlen("65535") */
    struct addrinfo hints, *servinfo, *p;
470

471 472
    snprintf(_port,6,"%d",port);
    memset(&hints,0,sizeof(hints));
G
Geoff Garside 已提交
473
    hints.ai_family = af;
474 475
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;    /* No effect if bindaddr != NULL */
476

477 478
    if ((rv = getaddrinfo(bindaddr,_port,&hints,&servinfo)) != 0) {
        anetSetError(err, "%s", gai_strerror(rv));
479
        return ANET_ERR;
A
antirez 已提交
480
    }
481 482 483 484
    for (p = servinfo; p != NULL; p = p->ai_next) {
        if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)
            continue;

485 486
        if (af == AF_INET6 && anetV6Only(err,s) == ANET_ERR) goto error;
        if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
487
        if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) goto error;
488 489 490
        goto end;
    }
    if (p == NULL) {
491
        anetSetError(err, "unable to bind socket, errno: %d", errno);
492 493 494 495 496 497 498
        goto error;
    }

error:
    s = ANET_ERR;
end:
    freeaddrinfo(servinfo);
A
antirez 已提交
499 500 501
    return s;
}

502
int anetTcpServer(char *err, int port, char *bindaddr, int backlog)
G
Geoff Garside 已提交
503
{
504
    return _anetTcpServer(err, port, bindaddr, AF_INET, backlog);
G
Geoff Garside 已提交
505 506
}

507
int anetTcp6Server(char *err, int port, char *bindaddr, int backlog)
G
Geoff Garside 已提交
508
{
509
    return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog);
G
Geoff Garside 已提交
510 511
}

512
int anetUnixServer(char *err, char *path, mode_t perm, int backlog)
513 514 515 516
{
    int s;
    struct sockaddr_un sa;

517
    if ((s = anetCreateSocket(err,AF_LOCAL)) == ANET_ERR)
518
        return ANET_ERR;
519

520 521 522
    memset(&sa,0,sizeof(sa));
    sa.sun_family = AF_LOCAL;
    strncpy(sa.sun_path,path,sizeof(sa.sun_path)-1);
523
    if (anetListen(err,s,(struct sockaddr*)&sa,sizeof(sa),backlog) == ANET_ERR)
524
        return ANET_ERR;
525 526
    if (perm)
        chmod(sa.sun_path, perm);
527 528 529
    return s;
}

530
static int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len) {
A
antirez 已提交
531 532
    int fd;
    while(1) {
533
        fd = accept(s,sa,len);
A
antirez 已提交
534 535 536 537
        if (fd == -1) {
            if (errno == EINTR)
                continue;
            else {
538
                anetSetError(err, "accept: %s", strerror(errno));
A
antirez 已提交
539 540 541 542 543
                return ANET_ERR;
            }
        }
        break;
    }
544 545 546
    return fd;
}

547
int anetTcpAccept(char *err, int s, char *ip, size_t ip_len, int *port) {
548
    int fd;
549
    struct sockaddr_storage sa;
550
    socklen_t salen = sizeof(sa);
551
    if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
552 553
        return ANET_ERR;

554 555 556 557 558 559 560 561 562
    if (sa.ss_family == AF_INET) {
        struct sockaddr_in *s = (struct sockaddr_in *)&sa;
        if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin_port);
    } else {
        struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
        if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin6_port);
    }
A
antirez 已提交
563 564
    return fd;
}
565

566
int anetUnixAccept(char *err, int s) {
567 568 569
    int fd;
    struct sockaddr_un sa;
    socklen_t salen = sizeof(sa);
570
    if ((fd = anetGenericAccept(err,s,(struct sockaddr*)&sa,&salen)) == -1)
571 572 573 574
        return ANET_ERR;

    return fd;
}
A
antirez 已提交
575

576
int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) {
577
    struct sockaddr_storage sa;
A
antirez 已提交
578 579
    socklen_t salen = sizeof(sa);

580 581 582
    if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) goto error;
    if (ip_len == 0) goto error;

583 584 585 586
    if (sa.ss_family == AF_INET) {
        struct sockaddr_in *s = (struct sockaddr_in *)&sa;
        if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin_port);
587
    } else if (sa.ss_family == AF_INET6) {
588 589 590
        struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
        if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin6_port);
591
    } else if (sa.ss_family == AF_UNIX) {
592
        if (ip) strncpy(ip,"/unixsocket",ip_len);
593
        if (port) *port = 0;
594 595
    } else {
        goto error;
596
    }
A
antirez 已提交
597
    return 0;
598 599 600 601 602 603 604 605 606 607 608 609

error:
    if (ip) {
        if (ip_len >= 2) {
            ip[0] = '?';
            ip[1] = '\0';
        } else if (ip_len == 1) {
            ip[0] = '\0';
        }
    }
    if (port) *port = 0;
    return -1;
A
antirez 已提交
610
}
611

612 613 614 615 616 617
/* Format an IP,port pair into something easy to parse. If IP is IPv6
 * (matches for ":"), the ip is surrounded by []. IP and port are just
 * separated by colons. This the standard to display addresses within Redis. */
int anetFormatAddr(char *buf, size_t buf_len, char *ip, int port) {
    return snprintf(buf,buf_len, strchr(ip,':') ?
           "[%s]:%d" : "%s:%d", ip, port);
618 619
}

620 621
/* Like anetFormatAddr() but extract ip and port from the socket's peer. */
int anetFormatPeer(int fd, char *buf, size_t buf_len) {
622 623 624 625
    char ip[INET6_ADDRSTRLEN];
    int port;

    anetPeerToString(fd,ip,sizeof(ip),&port);
626
    return anetFormatAddr(buf, buf_len, ip, port);
627 628
}

629
int anetSockName(int fd, char *ip, size_t ip_len, int *port) {
630
    struct sockaddr_storage sa;
631 632 633
    socklen_t salen = sizeof(sa);

    if (getsockname(fd,(struct sockaddr*)&sa,&salen) == -1) {
634
        if (port) *port = 0;
635 636 637 638
        ip[0] = '?';
        ip[1] = '\0';
        return -1;
    }
639 640 641 642 643 644 645 646 647
    if (sa.ss_family == AF_INET) {
        struct sockaddr_in *s = (struct sockaddr_in *)&sa;
        if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin_port);
    } else {
        struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
        if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
        if (port) *port = ntohs(s->sin6_port);
    }
648 649
    return 0;
}
650 651 652 653 654 655

int anetFormatSock(int fd, char *fmt, size_t fmt_len) {
    char ip[INET6_ADDRSTRLEN];
    int port;

    anetSockName(fd,ip,sizeof(ip),&port);
656
    return anetFormatAddr(fmt, fmt_len, ip, port);
657
}