sock.c 21.5 KB
Newer Older
1
/* -*- c-basic-offset: 4; -*- */
2
/* sock.c: General Socket Functions
Jack Moffitt's avatar
Jack Moffitt committed
3
 *
4
5
6
7
8
 * Copyright (C) 2014 Michael Smith <msmith@icecast.org>,
 *                    Brendan Cully <brendan@xiph.org>,
 *                    Karl Heyes <karl@xiph.org>,
 *                    Jack Moffitt <jack@icecast.org>,
 *                    Ed "oddsock" Zaleski <oddsock@xiph.org>
Jack Moffitt's avatar
Jack Moffitt committed
9
 *
10
11
12
13
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
Jack Moffitt's avatar
Jack Moffitt committed
14
 *
15
16
17
18
19
20
21
22
23
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
24
 *
Jack Moffitt's avatar
Jack Moffitt committed
25
26
 */

27
28
29
30
#ifdef HAVE_CONFIG_H
 #include <config.h>
#endif

Jack Moffitt's avatar
Jack Moffitt committed
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <fcntl.h>
38
#include <errno.h>
39
40
41
#ifdef HAVE_POLL
#include <poll.h>
#endif
brendan's avatar
whoops    
brendan committed
42
#ifdef HAVE_SYS_SELECT_H
43
44
#include <sys/select.h>
#endif
Jack Moffitt's avatar
Jack Moffitt committed
45
46
47
48
49

#ifndef _WIN32
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
50
#include <netinet/tcp.h>
Jack Moffitt's avatar
Jack Moffitt committed
51
52
53
54
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#else
55
#include <winsock2.h>
Jack Moffitt's avatar
Jack Moffitt committed
56
57
58
59
60
#endif

#include "sock.h"
#include "resolver.h"

61
62
/* for older C libraries */
#ifndef AI_NUMERICSERV
Karl Heyes's avatar
Karl Heyes committed
63
64
65
66
# define AI_NUMERICSERV 0
#endif
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
67
68
#endif

Jack Moffitt's avatar
Jack Moffitt committed
69
70
71
72
73
74
75
76
/* sock_initialize
**
** initializes the socket library.  you must call this
** before using the library!
*/
void sock_initialize(void)
{
#ifdef _WIN32
77
78
    WSADATA wsad;
    WSAStartup(0x0101, &wsad);
Jack Moffitt's avatar
Jack Moffitt committed
79
80
#endif

81
    resolver_initialize();
Jack Moffitt's avatar
Jack Moffitt committed
82
83
84
85
86
87
88
89
90
91
}

/* sock_shutdown
**
** shutdown the socket library.  remember to call this when you're
** through using the lib
*/
void sock_shutdown(void)
{
#ifdef _WIN32
92
    WSACleanup();
Jack Moffitt's avatar
Jack Moffitt committed
93
#endif
brendan's avatar
brendan committed
94
95

    resolver_shutdown();
Jack Moffitt's avatar
Jack Moffitt committed
96
97
98
99
100
101
102
103
104
105
106
}

/* sock_get_localip
**
** gets the local ip address for the machine
** the ip it returns *should* be on the internet.
** in any case, it's as close as we can hope to get
** unless someone has better ideas on how to do this
*/
char *sock_get_localip(char *buff, int len)
{
107
    char temp[1024];
Jack Moffitt's avatar
Jack Moffitt committed
108

109
    if (gethostname(temp, sizeof(temp)) != 0)
110
        return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
111

112
113
    if (resolver_getip(temp, buff, len))
        return buff;
Jack Moffitt's avatar
Jack Moffitt committed
114

115
    return NULL;
Jack Moffitt's avatar
Jack Moffitt committed
116
117
118
119
120
121
122
123
124
}

/* sock_error
** 
** returns the last socket error
*/
int sock_error(void)
{
#ifdef _WIN32
125
    return WSAGetLastError();
Jack Moffitt's avatar
Jack Moffitt committed
126
#else
127
    return errno;
Jack Moffitt's avatar
Jack Moffitt committed
128
129
130
#endif
}

131
void sock_set_error(int val)
132
133
134
135
136
137
138
139
{
#ifdef _WIN32
     WSASetLastError (val);
#else
     errno = val;
#endif
}

Jack Moffitt's avatar
Jack Moffitt committed
140
141
142
143
144
145
146
/* sock_recoverable
**
** determines if the socket error is recoverable
** in terms of non blocking sockets
*/
int sock_recoverable(int error)
{
147
148
149
150
151
152
153
154
155
    switch (error)
    {
    case 0:
    case EAGAIN:
    case EINTR:
    case EINPROGRESS:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
    case EWOULDBLOCK:
#endif
156
157
158
159
160
161
#if defined (WSAEWOULDBLOCK) && WSAEWOULDBLOCK != EWOULDBLOCK
    case WSAEWOULDBLOCK:
#endif
#if defined (WSAEINPROGRESS) && WSAEINPROGRESS != EINPROGRESS
    case WSAEINPROGRESS:
#endif
162
163
164
165
166
167
168
#ifdef ERESTART
    case ERESTART:
#endif
        return 1;
    default:
        return 0;
    }
169
170
171
172
}

int sock_stalled (int error)
{
173
174
175
176
177
178
179
180
    switch (error)
    {
    case EAGAIN:
    case EINPROGRESS:
    case EALREADY:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
    case EWOULDBLOCK:
#endif
181
182
183
184
185
186
#if defined (WSAEWOULDBLOCK) && WSAEWOULDBLOCK != EWOULDBLOCK
    case WSAEWOULDBLOCK:
#endif
#if defined (WSAEINPROGRESS) && WSAEINPROGRESS != EINPROGRESS
    case WSAEINPROGRESS:
#endif
187
188
189
190
191
192
193
#ifdef ERESTART
    case ERESTART:
#endif
        return 1;
    default:
        return 0;
    }
194
195
196
}


197
static int sock_connect_pending (int error)
198
199
{
    return error == EINPROGRESS || error == EALREADY;
Jack Moffitt's avatar
Jack Moffitt committed
200
201
202
203
204
205
206
207
}

/* sock_valid_socket
**
** determines if a sock_t represents a valid socket
*/
int sock_valid_socket(sock_t sock)
{
208
209
210
    int ret;
    int optval;
    socklen_t optlen;
Jack Moffitt's avatar
Jack Moffitt committed
211

212
    optlen = sizeof(int);
213
214
    /* apparently on windows getsockopt.optval is a char * */
    ret = getsockopt(sock, SOL_SOCKET, SO_TYPE, (void*) &optval, &optlen);
Jack Moffitt's avatar
Jack Moffitt committed
215

216
    return (ret == 0);
Jack Moffitt's avatar
Jack Moffitt committed
217
218
}

219
220
221
222
223
224
225
226
227
228

/* determines if the passed socket is still connected */
int sock_active (sock_t sock)
{
    char c;
    int l;

    l = recv (sock, &c, 1, MSG_PEEK);
    if (l == 0)
        return 0;
229
    if (l == SOCK_ERROR && sock_recoverable (sock_error()))
230
231
232
233
        return 1;
    return 0;
}

Jack Moffitt's avatar
Jack Moffitt committed
234
235
236
237
238
239
240
/* inet_aton
**
** turns an ascii ip address into a binary representation
*/
#ifdef _WIN32
int inet_aton(const char *s, struct in_addr *a)
{
241
    int lsb, b2, b3, msb;
Jack Moffitt's avatar
Jack Moffitt committed
242

243
244
245
    if (sscanf(s, "%d.%d.%d.%d", &lsb, &b2, &b3, &msb) < 4) {
        return 0;
    }
Jack Moffitt's avatar
Jack Moffitt committed
246

247
    a->s_addr = inet_addr(s);
Jack Moffitt's avatar
Jack Moffitt committed
248
    
249
    return (a->s_addr != INADDR_NONE);
Jack Moffitt's avatar
Jack Moffitt committed
250
251
252
253
}
#endif /* _WIN32 */

/* sock_set_blocking
254
255
256
257
258
259
 *
 * set the sock blocking or nonblocking
 * 1 for blocking
 * 0 for nonblocking
 */
int sock_set_blocking(sock_t sock, int block)
Jack Moffitt's avatar
Jack Moffitt committed
260
261
{
#ifdef _WIN32
262
#ifdef __MINGW32__
263
    u_long varblock = 1;
264
#else
265
    int varblock = 1;
266
#endif
Jack Moffitt's avatar
Jack Moffitt committed
267
268
#endif

269
270
    if ((!sock_valid_socket(sock)) || (block < 0) || (block > 1))
        return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
271
272

#ifdef _WIN32
273
    if (block) varblock = 0;
274
    return ioctlsocket(sock, FIONBIO, &varblock);
Jack Moffitt's avatar
Jack Moffitt committed
275
#else
276
    return fcntl(sock, F_SETFL, (block) ? 0 : O_NONBLOCK);
Jack Moffitt's avatar
Jack Moffitt committed
277
278
279
#endif
}

280
281
int sock_set_nolinger(sock_t sock)
{
282
283
    struct linger lin = { 0, 0 };
    return setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&lin, 
284
            sizeof(struct linger));
285
286
}

287
288
289
290
int sock_set_nodelay(sock_t sock)
{
    int nodelay = 1;

291
    return setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *)&nodelay,
292
293
294
            sizeof(int));
}

295
296
int sock_set_keepalive(sock_t sock)
{
297
298
    int keepalive = 1;
    return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, 
299
            sizeof(int));
300
301
}

Jack Moffitt's avatar
Jack Moffitt committed
302
303
304
305
306
307
308
/* sock_close
**
** close the socket
*/
int sock_close(sock_t sock)
{
#ifdef _WIN32
309
    return closesocket(sock);
Jack Moffitt's avatar
Jack Moffitt committed
310
#else
311
    return close(sock);
Jack Moffitt's avatar
Jack Moffitt committed
312
313
314
#endif
}

315
316
317
318
319
320
/* sock_writev
 *
 * write multiple buffers at once, return bytes actually written
 */
#ifdef HAVE_WRITEV

321
ssize_t sock_writev (sock_t sock, const struct iovec *iov, size_t count)
322
323
324
325
326
327
{
    return writev (sock, iov, count);
}

#else

328
ssize_t sock_writev (sock_t sock, const struct iovec *iov, size_t count)
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
{
    int i = count, accum = 0, ret;
    const struct iovec *v = iov;

    while (i)
    {
        if (v->iov_base && v->iov_len)
        {
            ret = sock_write_bytes (sock, v->iov_base, v->iov_len);
            if (ret == -1 && accum==0)
                return -1;
            if (ret == -1)
                ret = 0;
            accum += ret;
            if (ret < (int)v->iov_len)
                break;
        }
        v++;
        i--;
    }
    return accum;
}

#endif

Jack Moffitt's avatar
Jack Moffitt committed
354
355
356
/* sock_write_bytes
**
** write bytes to the socket
357
** this function will _NOT_ block
Jack Moffitt's avatar
Jack Moffitt committed
358
*/
359
int sock_write_bytes(sock_t sock, const void *buff, size_t len)
Jack Moffitt's avatar
Jack Moffitt committed
360
{
361
362
363
364
365
366
367
368
    /* sanity check */
    if (!buff) {
        return SOCK_ERROR;
    } else if (len <= 0) {
        return SOCK_ERROR;
    } /*else if (!sock_valid_socket(sock)) {
        return SOCK_ERROR;
    } */
Jack Moffitt's avatar
Jack Moffitt committed
369

370
    return send(sock, buff, len, 0);
Jack Moffitt's avatar
Jack Moffitt committed
371
372
373
374
375
}

/* sock_write_string
**
** writes a string to a socket
376
** This function must only be called with a blocking socket.
Jack Moffitt's avatar
Jack Moffitt committed
377
378
379
*/
int sock_write_string(sock_t sock, const char *buff)
{
380
    return (sock_write_bytes(sock, buff, strlen(buff)) > 0);
Jack Moffitt's avatar
Jack Moffitt committed
381
382
383
384
385
}

/* sock_write
**
** write a formatted string to the socket
386
** this function must only be called with a blocking socket.
Jack Moffitt's avatar
Jack Moffitt committed
387
388
389
390
** will truncate the string if it's greater than 1024 chars.
*/
int sock_write(sock_t sock, const char *fmt, ...)
{
391
    int rc;
392
    va_list ap;
Jack Moffitt's avatar
Jack Moffitt committed
393

394
395
396
397
398
    va_start (ap, fmt);
    rc = sock_write_fmt (sock, fmt, ap);
    va_end (ap);

    return rc;
Jack Moffitt's avatar
Jack Moffitt committed
399
400
}

401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#ifdef HAVE_OLD_VSNPRINTF
int sock_write_fmt(sock_t sock, const char *fmt, va_list ap)
{
    va_list ap_local;
    unsigned int len = 1024;
    char *buff = NULL;
    int ret;

    /* don't go infinite, but stop at some huge limit */
    while (len < 2*1024*1024)
    {
        char *tmp = realloc (buff, len);
        ret = -1;
        if (tmp == NULL)
            break;
        buff = tmp;
        va_copy (ap_local, ap);
        ret = vsnprintf (buff, len, fmt, ap_local);
        if (ret > 0)
        {
            ret = sock_write_bytes (sock, buff, ret);
            break;
        }
        len += 8192;
    }
    free (buff);
    return ret;
}
#else
430
int sock_write_fmt(sock_t sock, const char *fmt, va_list ap)
431
{
432
433
434
435
436
437
    char buffer [1024], *buff = buffer;
    int len;
    int rc = SOCK_ERROR;
    va_list ap_retry;

    va_copy (ap_retry, ap);
438

439
    len = vsnprintf (buff, sizeof (buffer), fmt, ap);
440

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    if (len > 0)
    {
        if ((size_t)len < sizeof (buffer))   /* common case */
            rc = sock_write_bytes(sock, buff, (size_t)len);
        else
        {
            /* truncated */
            buff = malloc (++len);
            if (buff)
            {
                len = vsnprintf (buff, len, fmt, ap_retry);
                if (len > 0)
                    rc = sock_write_bytes (sock, buff, len);
                free (buff);
            }
        }
    }
Karl Heyes's avatar
Karl Heyes committed
458
    va_end (ap_retry);
459
460

    return rc;
461
}
462
#endif
463

464

465
int sock_read_bytes(sock_t sock, char *buff, size_t len)
Jack Moffitt's avatar
Jack Moffitt committed
466
467
{

468
469
470
    /*if (!sock_valid_socket(sock)) return 0; */
    if (!buff) return 0;
    if (len <= 0) return 0;
Jack Moffitt's avatar
Jack Moffitt committed
471

472
    return recv(sock, buff, len, 0);
Jack Moffitt's avatar
Jack Moffitt committed
473
474
475
476
477
478
479
480
481
482
483
484
}

/* sock_read_line
**
** Read one line of at max len bytes from sock into buff.
** If ok, return 1 and nullterminate buff. Otherwize return 0.
** Terminating \n is not put into the buffer.
**
** this function will probably not work on sockets in nonblocking mode
*/
int sock_read_line(sock_t sock, char *buff, const int len)
{
485
486
    char c = '\0';
    int read_bytes, pos;
Jack Moffitt's avatar
Jack Moffitt committed
487
  
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
    /*if (!sock_valid_socket(sock)) {
        return 0;
    } else*/ if (!buff) {
        return 0;
    } else if (len <= 0) {
        return 0;
    }

    pos = 0;
    read_bytes = recv(sock, &c, 1, 0);

    if (read_bytes < 0) {
        return 0;
    }

    while ((c != '\n') && (pos < len) && (read_bytes == 1)) {
        if (c != '\r')
            buff[pos++] = c;
        read_bytes = recv(sock, &c, 1, 0);
    }
    
    if (read_bytes == 1) {
        buff[pos] = '\0';
        return 1;
    } else {
        return 0;
    }
Jack Moffitt's avatar
Jack Moffitt committed
515
516
}

517
518
/* see if a connection has been established. If timeout is < 0 then wait
 * indefinitely, else wait for the stated number of seconds.
519
520
521
522
523
 * return SOCK_TIMEOUT for timeout
 * return SOCK_ERROR for failure
 * return 0 for try again, interrupted
 * return 1 for ok 
 */
524
525
526
527
#ifdef HAVE_POLL
int sock_connected (sock_t sock, int timeout)
{
    struct pollfd check;
528
529
    int val = SOCK_ERROR;
    socklen_t size = sizeof val;
530
531
532
533
534
535

    check.fd = sock;
    check.events = POLLOUT;
    switch (poll (&check, 1, timeout*1000))
    {
        case 0: return SOCK_TIMEOUT;
536
537
538
539
540
541
542
543
544
        default:
            /* on windows getsockopt.val is defined as char* */
            if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*) &val, &size) == 0)
            {
                if (val == 0)
                    return 1;
                sock_set_error (val);
            }
            /* fall through */
545
546
547
548
549
550
551
552
553
        case -1:
            if (sock_recoverable (sock_error()))
                return 0;
            return SOCK_ERROR;
    }                                           
}

#else

554
int sock_connected (sock_t sock, int timeout)
555
556
557
558
{
    fd_set wfds;
    int val = SOCK_ERROR;
    socklen_t size = sizeof val;
559
    struct timeval tv, *timeval = NULL;
560

561
562
    /* make a timeout of <0 be indefinite */
    if (timeout >= 0)
563
564
565
566
567
    {
        tv.tv_sec = timeout;
        tv.tv_usec = 0;
        timeval = &tv;
    }
568
569
570
571

    FD_ZERO(&wfds);
    FD_SET(sock, &wfds);

572
    switch (select(sock + 1, NULL, &wfds, NULL, timeval))
573
    {
574
        case 0:
575
            return SOCK_TIMEOUT;
576
        default:
577
578
579
580
581
            /* on windows getsockopt.val is defined as char* */
            if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*) &val, &size) == 0)
            {
                if (val == 0)
                    return 1;
582
                sock_set_error (val);
583
            }
584
            /* fall through */
585
        case -1:
586
587
588
            if (sock_recoverable (sock_error()))
                return 0;
            return SOCK_ERROR;
589
590
    }
}
591
#endif
592

593
594
595
596
597
sock_t sock_connect_wto (const char *hostname, int port, int timeout)
{
    return sock_connect_wto_bind(hostname, port, NULL, timeout);
}

598
599
#ifdef HAVE_GETADDRINFO

600
sock_t sock_connect_non_blocking (const char *hostname, unsigned port)
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
{
    int sock = SOCK_ERROR;
    struct addrinfo *ai, *head, hints;
    char service[8];

    memset (&hints, 0, sizeof (hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    snprintf (service, sizeof (service), "%u", port);

    if (getaddrinfo (hostname, service, &hints, &head))
        return SOCK_ERROR;

    ai = head;
    while (ai)
    {
        if ((sock = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol)) 
                > -1)
        {
621
            sock_set_blocking (sock, 0);
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
            if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 && 
                    !sock_connect_pending(sock_error()))
            {
                sock_close (sock);
                sock = SOCK_ERROR;
            }
            else
                break;
        }
        ai = ai->ai_next;
    }
    if (head) freeaddrinfo (head);
    
    return sock;
}

638
639
640
641
/* issue a connect, but return after the timeout (seconds) is reached. If
 * timeout is 0 or less then we will wait until the OS gives up on the connect
 * The socket is returned
 */
642
sock_t sock_connect_wto_bind (const char *hostname, int port, const char *bnd, int timeout)
Jack Moffitt's avatar
Jack Moffitt committed
643
{
644
    sock_t sock = SOCK_ERROR;
645
    struct addrinfo *ai, *head, *b_head=NULL, hints;
646
647
648
649
650
651
652
653
654
655
656
657
658
    char service[8];

    memset (&hints, 0, sizeof (hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    snprintf (service, sizeof (service), "%u", port);

    if (getaddrinfo (hostname, service, &hints, &head))
        return SOCK_ERROR;

    ai = head;
    while (ai)
    {
659
        if ((sock = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol)) >= 0)
660
        {
661
            if (timeout > 0)
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
                sock_set_blocking (sock, 0);

            if (bnd)
            {
                struct addrinfo b_hints;
                memset (&b_hints, 0, sizeof(b_hints));
                b_hints.ai_family = ai->ai_family;
                b_hints.ai_socktype = ai->ai_socktype;
                b_hints.ai_protocol = ai->ai_protocol;
                if (getaddrinfo (bnd, NULL, &b_hints, &b_head) ||
                        bind (sock, b_head->ai_addr, b_head->ai_addrlen) < 0)
                {
                    sock_close (sock);
                    sock = SOCK_ERROR;
                    break;
                }
            }
679
680
681
682
683
684
685
686

            if (connect (sock, ai->ai_addr, ai->ai_addrlen) == 0)
                break;

            /* loop as the connect maybe async */
            while (sock != SOCK_ERROR)
            {
                if (sock_recoverable (sock_error()))
687
                {
688
689
690
691
                    int connected = sock_connected (sock, timeout);
                    if (connected == 0)  /* try again, interrupted */
                        continue;
                    if (connected == 1) /* connected */
692
                    {
693
                        if (timeout >= 0)
694
                            sock_set_blocking(sock, 1);
695
                        break;
696
697
                    }
                }
698
699
                sock_close (sock);
                sock = SOCK_ERROR;
700
            }
701
702
            if (sock != SOCK_ERROR)
                break;
703
704
705
        }
        ai = ai->ai_next;
    }
706
707
708
    if (b_head)
        freeaddrinfo (b_head);
    freeaddrinfo (head);
709
710
711

    return sock;
}
Jack Moffitt's avatar
Jack Moffitt committed
712

713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742

sock_t sock_get_server_socket (int port, const char *sinterface)
{
    struct sockaddr_storage sa;
    struct addrinfo hints, *res, *ai;
    char service [10];
    int sock;

    if (port < 0)
        return SOCK_ERROR;

    memset (&sa, 0, sizeof(sa));
    memset (&hints, 0, sizeof(hints));

    hints.ai_family = AF_UNSPEC;
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_NUMERICSERV | AI_NUMERICHOST;
    hints.ai_socktype = SOCK_STREAM;
    snprintf (service, sizeof (service), "%d", port);

    if (getaddrinfo (sinterface, service, &hints, &res))
        return SOCK_ERROR;
    ai = res;
    do
    {
        int on = 1;
        sock = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (sock < 0)
            continue;

        setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on));
743
        on = 0;
744
#ifdef IPV6_V6ONLY
745
        setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof on);
746
#endif
747
748
749

        if (bind (sock, ai->ai_addr, ai->ai_addrlen) < 0)
        {
Karl Heyes's avatar
Karl Heyes committed
750
            sock_close (sock);
751
752
753
754
755
756
757
758
759
760
761
762
            continue;
        }
        freeaddrinfo (res);
        return sock;

    } while ((ai = ai->ai_next));

    freeaddrinfo (res);
    return SOCK_ERROR;
}


763
#else
Jack Moffitt's avatar
Jack Moffitt committed
764

765

766
int sock_try_connection (sock_t sock, const char *hostname, unsigned int port)
767
768
{
    struct sockaddr_in sin, server;
769
    char ip[MAX_ADDR_LEN];
Jack Moffitt's avatar
Jack Moffitt committed
770

771
772
    if (!hostname || !hostname[0] || port == 0)
        return -1;
Jack Moffitt's avatar
Jack Moffitt committed
773

774
775
776
    memset(&sin, 0, sizeof(struct sockaddr_in));
    memset(&server, 0, sizeof(struct sockaddr_in));

777
    if (!resolver_getip(hostname, ip, MAX_ADDR_LEN))
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    {
        sock_close (sock);
        return -1;
    }

    if (inet_aton(ip, (struct in_addr *)&sin.sin_addr) == 0)
    {
        sock_close(sock);
        return -1;
    }

    memcpy(&server.sin_addr, &sin.sin_addr, sizeof(struct sockaddr_in));

    server.sin_family = AF_INET;
792
    server.sin_port = htons((short)port);
793
794
795
796

    return connect(sock, (struct sockaddr *)&server, sizeof(server));
}

797
sock_t sock_connect_non_blocking (const char *hostname, unsigned port)
798
{
799
    sock_t sock;
800
801

    sock = socket(AF_INET, SOCK_STREAM, 0);
802
803
    if (sock == SOCK_ERROR)
        return SOCK_ERROR;
804

805
    sock_set_blocking (sock, 0);
806
807
808
    sock_try_connection (sock, hostname, port);
    
    return sock;
Jack Moffitt's avatar
Jack Moffitt committed
809
810
}

811
sock_t sock_connect_wto_bind (const char *hostname, int port, const char *bnd, int timeout)
812
{
813
    sock_t sock;
814
815

    sock = socket(AF_INET, SOCK_STREAM, 0);
816
817
    if (sock == SOCK_ERROR)
        return SOCK_ERROR;
818

819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
    if (bnd)
    {
        struct sockaddr_in sa;

        memset(&sa, 0, sizeof(sa));
        sa.sin_family = AF_INET;

        if (inet_aton (bnd, &sa.sin_addr) == 0 ||
            bind (sock, (struct sockaddr *)&sa, sizeof(sa)) < 0)
        {
            sock_close (sock);
            return SOCK_ERROR;
        }
    }

834
835
    if (timeout)
    {
836
        sock_set_blocking (sock, 0);
837
838
839
840
841
842
843
844
845
        if (sock_try_connection (sock, hostname, port) < 0)
        {
            int ret = sock_connected (sock, timeout);
            if (ret <= 0)
            {
                sock_close (sock);
                return SOCK_ERROR;
            }
        }
846
        sock_set_blocking(sock, 1);
847
848
849
850
851
852
853
854
855
856
857
858
859
    }
    else
    {
        if (sock_try_connection (sock, hostname, port) < 0)
        {
            sock_close (sock);
            sock = SOCK_ERROR;
        }
    }
    return sock;
}


Jack Moffitt's avatar
Jack Moffitt committed
860
861
862
863
864
865
/* sock_get_server_socket
**
** create a socket for incoming requests on a specified port and
** interface.  if interface is null, listen on all interfaces.
** returns the socket, or SOCK_ERROR on failure
*/
866
sock_t sock_get_server_socket(int port, const char *sinterface)
Jack Moffitt's avatar
Jack Moffitt committed
867
{
868
    struct sockaddr_in sa;
869
    int error, opt;
870
871
    sock_t sock;
    char ip[MAX_ADDR_LEN];
Jack Moffitt's avatar
Jack Moffitt committed
872

873
874
    if (port < 0)
        return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
875

876
877
    /* defaults */
    memset(&sa, 0, sizeof(sa));
Jack Moffitt's avatar
Jack Moffitt committed
878

879
880
881
882
    /* set the interface to bind to if specified */
    if (sinterface != NULL) {
        if (!resolver_getip(sinterface, ip, sizeof (ip)))
            return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
883

884
885
886
887
        if (!inet_aton(ip, &sa.sin_addr)) {
            return SOCK_ERROR;
        } else {
            sa.sin_family = AF_INET;
888
            sa.sin_port = htons((short)port);
889
890
        }
    } else {
891
892
        sa.sin_addr.s_addr = INADDR_ANY;
        sa.sin_family = AF_INET;
893
        sa.sin_port = htons((short)port);
894
    }
Jack Moffitt's avatar
Jack Moffitt committed
895

896
    /* get a socket */
897
    sock = socket (AF_INET, SOCK_STREAM, 0);
898
899
    if (sock == -1)
        return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
900

901
902
903
    /* reuse it if we can */
    opt = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(int));
904

905
    /* bind socket to port */
906
    error = bind(sock, (struct sockaddr *)&sa, sizeof (struct sockaddr_in));
907
908
    if (error == -1)
        return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
909

910
    return sock;
Jack Moffitt's avatar
Jack Moffitt committed
911
912
}

913
914
#endif

915
916
917
918
919
void sock_set_send_buffer (sock_t sock, int win_size)
{
    setsockopt (sock, SOL_SOCKET, SO_SNDBUF, (char *) &win_size, sizeof(win_size));
}

Jack Moffitt's avatar
Jack Moffitt committed
920
921
int sock_listen(sock_t serversock, int backlog)
{
922
923
    if (!sock_valid_socket(serversock))
        return 0;
Jack Moffitt's avatar
Jack Moffitt committed
924

925
926
    if (backlog <= 0)
        backlog = 10;
Jack Moffitt's avatar
Jack Moffitt committed
927

928
    return (listen(serversock, backlog) == 0);
Jack Moffitt's avatar
Jack Moffitt committed
929
930
}

931
sock_t sock_accept(sock_t serversock, char *ip, size_t len)
Jack Moffitt's avatar
Jack Moffitt committed
932
{
933
#ifdef HAVE_GETNAMEINFO
934
935
936
    struct sockaddr_storage sa;
#else    
    struct sockaddr_in sa;
937
#endif
938
    sock_t ret;
939
    socklen_t slen;
Jack Moffitt's avatar
Jack Moffitt committed
940

941
    if (ip == NULL || len == 0 || !sock_valid_socket(serversock))
942
        return SOCK_ERROR;
Jack Moffitt's avatar
Jack Moffitt committed
943

944
945
    slen = sizeof(sa);
    ret = accept(serversock, (struct sockaddr *)&sa, &slen);
Jack Moffitt's avatar
Jack Moffitt committed
946

947
    if (ret != SOCK_ERROR)
948
949
950
951
    {
#ifdef HAVE_GETNAMEINFO
        if (getnameinfo ((struct sockaddr *)&sa, slen, ip, len, NULL, 0, NI_NUMERICHOST))
            snprintf (ip, len, "unknown");
952
#else
953
        /* inet_ntoa is not reentrant, we should protect this */
954
        strncpy(ip, inet_ntoa(sa.sin_addr), len);
955
#endif
956
957
958
        sock_set_nolinger(ret);
        sock_set_keepalive(ret);
    }
Jack Moffitt's avatar
Jack Moffitt committed
959

960
    return ret;
Jack Moffitt's avatar
Jack Moffitt committed
961
}
962