~ubuntu-branches/ubuntu/wily/openvswitch/wily

« back to all changes in this revision

Viewing changes to lib/socket-util.c

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2015-08-10 11:35:15 UTC
  • mfrom: (1.1.30)
  • Revision ID: package-import@ubuntu.com-20150810113515-575vj06oq29emxsn
Tags: 2.4.0~git20150810.97bab95-0ubuntu1
* New upstream snapshot from 2.4 branch:
  - d/*: Align any relevant packaging changes with upstream.
* d/*: wrap-and-sort.
* d/openvswitch-{common,vswitch}.install: Correct install location for
  bash completion files.
* d/tests/openflow.py: Explicitly use ovs-testcontroller as provided
  by 2.4.0 release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
#include <fcntl.h>
22
22
#include <net/if.h>
23
23
#include <netdb.h>
 
24
#include <netinet/tcp.h>
24
25
#include <poll.h>
25
26
#include <stddef.h>
26
27
#include <stdio.h>
27
28
#include <stdlib.h>
28
29
#include <string.h>
29
 
#include <sys/ioctl.h>
30
30
#include <sys/socket.h>
31
31
#include <sys/stat.h>
32
32
#include <sys/uio.h>
33
33
#include <sys/un.h>
34
34
#include <unistd.h>
35
35
#include "dynamic-string.h"
36
 
#include "fatal-signal.h"
37
36
#include "ovs-thread.h"
38
37
#include "packets.h"
39
38
#include "poll-loop.h"
40
39
#include "util.h"
41
 
#include "vlog.h"
 
40
#include "openvswitch/vlog.h"
42
41
#ifdef __linux__
43
42
#include <linux/if_packet.h>
44
43
#endif
49
48
 
50
49
VLOG_DEFINE_THIS_MODULE(socket_util);
51
50
 
52
 
/* #ifdefs make it a pain to maintain code: you have to try to build both ways.
53
 
 * Thus, this file compiles all of the code regardless of the target, by
54
 
 * writing "if (LINUX)" instead of "#ifdef __linux__". */
55
 
#ifdef __linux__
56
 
#define LINUX 1
57
 
#else
58
 
#define LINUX 0
59
 
#endif
60
 
 
61
 
#ifndef O_DIRECTORY
62
 
#define O_DIRECTORY 0
63
 
#endif
64
 
 
65
 
/* Maximum length of the sun_path member in a struct sockaddr_un, excluding
66
 
 * space for a null terminator. */
67
 
#define MAX_UN_LEN (sizeof(((struct sockaddr_un *) 0)->sun_path) - 1)
68
 
 
69
51
static int getsockopt_int(int fd, int level, int option, const char *optname,
70
52
                          int *valuep);
71
53
 
106
88
    }
107
89
}
108
90
 
 
91
void
 
92
setsockopt_tcp_nodelay(int fd)
 
93
{
 
94
    int on = 1;
 
95
    int retval;
 
96
 
 
97
    retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
 
98
    if (retval) {
 
99
        retval = sock_errno();
 
100
        VLOG_ERR("setsockopt(TCP_NODELAY): %s", sock_strerror(retval));
 
101
    }
 
102
}
 
103
 
109
104
/* Sets the DSCP value of socket 'fd' to 'dscp', which must be 63 or less.
110
105
 * 'family' must indicate the socket's address family (AF_INET or AF_INET6, to
111
106
 * do anything useful). */
115
110
    int retval;
116
111
    int val;
117
112
 
 
113
#ifdef _WIN32
 
114
    /* XXX: Consider using QoS2 APIs for Windows to set dscp. */
 
115
    return 0;
 
116
#endif
 
117
 
118
118
    if (dscp > 63) {
119
119
        return EINVAL;
120
120
    }
265
265
    }
266
266
}
267
267
 
268
 
#ifndef _WIN32
269
 
/* Drain all the data currently in the receive queue of a datagram socket (and
270
 
 * possibly additional data).  There is no way to know how many packets are in
271
 
 * the receive queue, but we do know that the total number of bytes queued does
272
 
 * not exceed the receive buffer size, so we pull packets until none are left
273
 
 * or we've read that many bytes. */
274
 
int
275
 
drain_rcvbuf(int fd)
276
 
{
277
 
    int rcvbuf;
278
 
 
279
 
    rcvbuf = get_socket_rcvbuf(fd);
280
 
    if (rcvbuf < 0) {
281
 
        return -rcvbuf;
282
 
    }
283
 
 
284
 
    while (rcvbuf > 0) {
285
 
        /* In Linux, specifying MSG_TRUNC in the flags argument causes the
286
 
         * datagram length to be returned, even if that is longer than the
287
 
         * buffer provided.  Thus, we can use a 1-byte buffer to discard the
288
 
         * incoming datagram and still be able to account how many bytes were
289
 
         * removed from the receive buffer.
290
 
         *
291
 
         * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
292
 
         * argument. */
293
 
        char buffer[LINUX ? 1 : 2048];
294
 
        ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
295
 
                               MSG_TRUNC | MSG_DONTWAIT);
296
 
        if (n_bytes <= 0 || n_bytes >= rcvbuf) {
297
 
            break;
298
 
        }
299
 
        rcvbuf -= n_bytes;
300
 
    }
301
 
    return 0;
302
 
}
303
 
#endif
304
 
 
305
268
/* Returns the size of socket 'sock''s receive buffer (SO_RCVBUF), or a
306
269
 * negative errno value if an error occurs. */
307
270
int
332
295
    }
333
296
}
334
297
 
335
 
#ifndef _WIN32
336
 
/* Attempts to shorten 'name' by opening a file descriptor for the directory
337
 
 * part of the name and indirecting through /proc/self/fd/<dirfd>/<basename>.
338
 
 * On systems with Linux-like /proc, this works as long as <basename> isn't too
339
 
 * long.
340
 
 *
341
 
 * On success, returns 0 and stores the short name in 'short_name' and a
342
 
 * directory file descriptor to eventually be closed in '*dirfpd'. */
343
 
static int
344
 
shorten_name_via_proc(const char *name, char short_name[MAX_UN_LEN + 1],
345
 
                      int *dirfdp)
346
 
{
347
 
    char *dir, *base;
348
 
    int dirfd;
349
 
    int len;
350
 
 
351
 
    if (!LINUX) {
352
 
        return ENAMETOOLONG;
353
 
    }
354
 
 
355
 
    dir = dir_name(name);
356
 
    dirfd = open(dir, O_DIRECTORY | O_RDONLY);
357
 
    if (dirfd < 0) {
358
 
        static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
359
 
        int error = errno;
360
 
 
361
 
        VLOG_WARN_RL(&rl, "%s: open failed (%s)", dir, ovs_strerror(error));
362
 
        free(dir);
363
 
 
364
 
        return error;
365
 
    }
366
 
    free(dir);
367
 
 
368
 
    base = base_name(name);
369
 
    len = snprintf(short_name, MAX_UN_LEN + 1,
370
 
                   "/proc/self/fd/%d/%s", dirfd, base);
371
 
    free(base);
372
 
 
373
 
    if (len >= 0 && len <= MAX_UN_LEN) {
374
 
        *dirfdp = dirfd;
375
 
        return 0;
376
 
    } else {
377
 
        close(dirfd);
378
 
        return ENAMETOOLONG;
379
 
    }
380
 
}
381
 
 
382
 
/* Attempts to shorten 'name' by creating a symlink for the directory part of
383
 
 * the name and indirecting through <symlink>/<basename>.  This works on
384
 
 * systems that support symlinks, as long as <basename> isn't too long.
385
 
 *
386
 
 * On success, returns 0 and stores the short name in 'short_name' and the
387
 
 * symbolic link to eventually delete in 'linkname'. */
388
 
static int
389
 
shorten_name_via_symlink(const char *name, char short_name[MAX_UN_LEN + 1],
390
 
                         char linkname[MAX_UN_LEN + 1])
391
 
{
392
 
    char *abs, *dir, *base;
393
 
    const char *tmpdir;
394
 
    int error;
395
 
    int i;
396
 
 
397
 
    abs = abs_file_name(NULL, name);
398
 
    dir = dir_name(abs);
399
 
    base = base_name(abs);
400
 
    free(abs);
401
 
 
402
 
    tmpdir = getenv("TMPDIR");
403
 
    if (tmpdir == NULL) {
404
 
        tmpdir = "/tmp";
405
 
    }
406
 
 
407
 
    for (i = 0; i < 1000; i++) {
408
 
        int len;
409
 
 
410
 
        len = snprintf(linkname, MAX_UN_LEN + 1,
411
 
                       "%s/ovs-un-c-%"PRIu32, tmpdir, random_uint32());
412
 
        error = (len < 0 || len > MAX_UN_LEN ? ENAMETOOLONG
413
 
                 : symlink(dir, linkname) ? errno
414
 
                 : 0);
415
 
        if (error != EEXIST) {
416
 
            break;
417
 
        }
418
 
    }
419
 
 
420
 
    if (!error) {
421
 
        int len;
422
 
 
423
 
        fatal_signal_add_file_to_unlink(linkname);
424
 
 
425
 
        len = snprintf(short_name, MAX_UN_LEN + 1, "%s/%s", linkname, base);
426
 
        if (len < 0 || len > MAX_UN_LEN) {
427
 
            fatal_signal_unlink_file_now(linkname);
428
 
            error = ENAMETOOLONG;
429
 
        }
430
 
    }
431
 
 
432
 
    if (error) {
433
 
        linkname[0] = '\0';
434
 
    }
435
 
    free(dir);
436
 
    free(base);
437
 
 
438
 
    return error;
439
 
}
440
 
 
441
 
/* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
442
 
 * '*un_len' the size of the sockaddr_un.
443
 
 *
444
 
 * Returns 0 on success, otherwise a positive errno value.
445
 
 *
446
 
 * Uses '*dirfdp' and 'linkname' to store references to data when the caller no
447
 
 * longer needs to use 'un'.  On success, freeing these references with
448
 
 * free_sockaddr_un() is mandatory to avoid a leak; on failure, freeing them is
449
 
 * unnecessary but harmless. */
450
 
static int
451
 
make_sockaddr_un(const char *name, struct sockaddr_un *un, socklen_t *un_len,
452
 
                 int *dirfdp, char linkname[MAX_UN_LEN + 1])
453
 
{
454
 
    char short_name[MAX_UN_LEN + 1];
455
 
 
456
 
    *dirfdp = -1;
457
 
    linkname[0] = '\0';
458
 
    if (strlen(name) > MAX_UN_LEN) {
459
 
        /* 'name' is too long to fit in a sockaddr_un.  Try a workaround. */
460
 
        int error = shorten_name_via_proc(name, short_name, dirfdp);
461
 
        if (error == ENAMETOOLONG) {
462
 
            error = shorten_name_via_symlink(name, short_name, linkname);
463
 
        }
464
 
        if (error) {
465
 
            static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
466
 
 
467
 
            VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
468
 
                         "%"PRIuSIZE" bytes", name, MAX_UN_LEN);
469
 
            return error;
470
 
        }
471
 
 
472
 
        name = short_name;
473
 
    }
474
 
 
475
 
    un->sun_family = AF_UNIX;
476
 
    ovs_strzcpy(un->sun_path, name, sizeof un->sun_path);
477
 
    *un_len = (offsetof(struct sockaddr_un, sun_path)
478
 
                + strlen (un->sun_path) + 1);
479
 
    return 0;
480
 
}
481
 
 
482
 
/* Clean up after make_sockaddr_un(). */
483
 
static void
484
 
free_sockaddr_un(int dirfd, const char *linkname)
485
 
{
486
 
    if (dirfd >= 0) {
487
 
        close(dirfd);
488
 
    }
489
 
    if (linkname[0]) {
490
 
        fatal_signal_unlink_file_now(linkname);
491
 
    }
492
 
}
493
 
 
494
 
/* Binds Unix domain socket 'fd' to a file with permissions 0700. */
495
 
static int
496
 
bind_unix_socket(int fd, struct sockaddr *sun, socklen_t sun_len)
497
 
{
498
 
    /* According to _Unix Network Programming_, umask should affect bind(). */
499
 
    mode_t old_umask = umask(0077);
500
 
    int error = bind(fd, sun, sun_len) ? errno : 0;
501
 
    umask(old_umask);
502
 
    return error;
503
 
}
504
 
 
505
 
/* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
506
 
 * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
507
 
 * connected to '*connect_path' (if 'connect_path' is non-null).  If 'nonblock'
508
 
 * is true, the socket is made non-blocking.
509
 
 *
510
 
 * Returns the socket's fd if successful, otherwise a negative errno value. */
511
 
int
512
 
make_unix_socket(int style, bool nonblock,
513
 
                 const char *bind_path, const char *connect_path)
514
 
{
515
 
    int error;
516
 
    int fd;
517
 
 
518
 
    fd = socket(PF_UNIX, style, 0);
519
 
    if (fd < 0) {
520
 
        return -errno;
521
 
    }
522
 
 
523
 
    /* Set nonblocking mode right away, if we want it.  This prevents blocking
524
 
     * in connect(), if connect_path != NULL.  (In turn, that's a corner case:
525
 
     * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
526
 
     * if a backlog of un-accepted connections has built up in the kernel.)  */
527
 
    if (nonblock) {
528
 
        error = set_nonblocking(fd);
529
 
        if (error) {
530
 
            goto error;
531
 
        }
532
 
    }
533
 
 
534
 
    if (bind_path) {
535
 
        char linkname[MAX_UN_LEN + 1];
536
 
        struct sockaddr_un un;
537
 
        socklen_t un_len;
538
 
        int dirfd;
539
 
 
540
 
        if (unlink(bind_path) && errno != ENOENT) {
541
 
            VLOG_WARN("unlinking \"%s\": %s\n",
542
 
                      bind_path, ovs_strerror(errno));
543
 
        }
544
 
        fatal_signal_add_file_to_unlink(bind_path);
545
 
 
546
 
        error = make_sockaddr_un(bind_path, &un, &un_len, &dirfd, linkname);
547
 
        if (!error) {
548
 
            error = bind_unix_socket(fd, (struct sockaddr *) &un, un_len);
549
 
        }
550
 
        free_sockaddr_un(dirfd, linkname);
551
 
 
552
 
        if (error) {
553
 
            goto error;
554
 
        }
555
 
    }
556
 
 
557
 
    if (connect_path) {
558
 
        char linkname[MAX_UN_LEN + 1];
559
 
        struct sockaddr_un un;
560
 
        socklen_t un_len;
561
 
        int dirfd;
562
 
 
563
 
        error = make_sockaddr_un(connect_path, &un, &un_len, &dirfd, linkname);
564
 
        if (!error
565
 
            && connect(fd, (struct sockaddr*) &un, un_len)
566
 
            && errno != EINPROGRESS) {
567
 
            error = errno;
568
 
        }
569
 
        free_sockaddr_un(dirfd, linkname);
570
 
 
571
 
        if (error) {
572
 
            goto error;
573
 
        }
574
 
    }
575
 
 
576
 
    return fd;
577
 
 
578
 
error:
579
 
    if (error == EAGAIN) {
580
 
        error = EPROTO;
581
 
    }
582
 
    if (bind_path) {
583
 
        fatal_signal_unlink_file_now(bind_path);
584
 
    }
585
 
    close(fd);
586
 
    return -error;
587
 
}
588
 
 
589
 
int
590
 
get_unix_name_len(socklen_t sun_len)
591
 
{
592
 
    return (sun_len >= offsetof(struct sockaddr_un, sun_path)
593
 
            ? sun_len - offsetof(struct sockaddr_un, sun_path)
594
 
            : 0);
595
 
}
596
 
#endif /* _WIN32 */
597
 
 
598
298
ovs_be32
599
299
guess_netmask(ovs_be32 ip_)
600
300
{
859
559
 *
860
560
 * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
861
561
 * should be in the range [0, 63] and will automatically be shifted to the
862
 
 * appropriately place in the IP tos field. */
 
562
 * appropriately place in the IP tos field.
 
563
 *
 
564
 * If 'kernel_print_port' is true and the port is dynamically assigned by
 
565
 * the kernel, print the chosen port. */
863
566
int
864
567
inet_open_passive(int style, const char *target, int default_port,
865
 
                  struct sockaddr_storage *ssp, uint8_t dscp)
 
568
                  struct sockaddr_storage *ssp, uint8_t dscp,
 
569
                  bool kernel_print_port)
866
570
{
867
571
    bool kernel_chooses_port;
868
572
    struct sockaddr_storage ss;
923
627
            VLOG_ERR("%s: getsockname: %s", target, sock_strerror(error));
924
628
            goto error;
925
629
        }
926
 
        if (kernel_chooses_port) {
 
630
        if (kernel_chooses_port && kernel_print_port) {
927
631
            VLOG_INFO("%s: listening on port %"PRIu16,
928
632
                      target, ss_get_port(&ss));
929
633
        }
1045
749
    }
1046
750
}
1047
751
 
1048
 
#ifndef _WIN32
1049
 
void
1050
 
xpipe(int fds[2])
1051
 
{
1052
 
    if (pipe(fds)) {
1053
 
        VLOG_FATAL("failed to create pipe (%s)", ovs_strerror(errno));
1054
 
    }
1055
 
}
1056
 
 
1057
 
void
1058
 
xpipe_nonblocking(int fds[2])
1059
 
{
1060
 
    xpipe(fds);
1061
 
    xset_nonblocking(fds[0]);
1062
 
    xset_nonblocking(fds[1]);
1063
 
}
1064
 
#endif
1065
 
 
1066
752
static int
1067
753
getsockopt_int(int fd, int level, int option, const char *optname, int *valuep)
1068
754
{
1229
915
    return ds_steal_cstr(&string);
1230
916
}
1231
917
 
1232
 
#ifndef _WIN32
1233
 
/* Calls ioctl() on an AF_INET sock, passing the specified 'command' and
1234
 
 * 'arg'.  Returns 0 if successful, otherwise a positive errno value. */
1235
 
int
1236
 
af_inet_ioctl(unsigned long int command, const void *arg)
1237
 
{
1238
 
    static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1239
 
    static int sock;
1240
 
 
1241
 
    if (ovsthread_once_start(&once)) {
1242
 
        sock = socket(AF_INET, SOCK_DGRAM, 0);
1243
 
        if (sock < 0) {
1244
 
            int error = sock_errno();
1245
 
            VLOG_ERR("failed to create inet socket: %s", sock_strerror(error));
1246
 
            sock = -error;
1247
 
        }
1248
 
        ovsthread_once_done(&once);
1249
 
    }
1250
 
 
1251
 
    return (sock < 0 ? -sock
1252
 
            : ioctl(sock, command, arg) == -1 ? errno
1253
 
            : 0);
1254
 
}
1255
 
 
1256
 
int
1257
 
af_inet_ifreq_ioctl(const char *name, struct ifreq *ifr, unsigned long int cmd,
1258
 
                    const char *cmd_name)
1259
 
{
1260
 
    int error;
1261
 
 
1262
 
    ovs_strzcpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
1263
 
    error = af_inet_ioctl(cmd, ifr);
1264
 
    if (error) {
1265
 
        static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1266
 
        VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
1267
 
                    ovs_strerror(error));
1268
 
    }
1269
 
    return error;
1270
 
}
1271
 
#endif
1272
918
 
1273
919
/* sockaddr_storage helpers. */
1274
920