socket-util: Make get_max_fds() and get_null_fd() thread-safe.
[sliver-openvswitch.git] / lib / socket-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "socket-util.h"
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <net/if.h>
23 #include <netdb.h>
24 #include <poll.h>
25 #include <stddef.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/resource.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/uio.h>
33 #include <sys/un.h>
34 #include <unistd.h>
35 #include "dynamic-string.h"
36 #include "fatal-signal.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "util.h"
40 #include "vlog.h"
41 #if AF_PACKET && LINUX_DATAPATH
42 #include <linux/if_packet.h>
43 #endif
44 #ifdef HAVE_NETLINK
45 #include "netlink-protocol.h"
46 #include "netlink-socket.h"
47 #endif
48
49 VLOG_DEFINE_THIS_MODULE(socket_util);
50
51 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
52  * Thus, this file compiles all of the code regardless of the target, by
53  * writing "if (LINUX_DATAPATH)" instead of "#ifdef __linux__". */
54 #ifndef LINUX_DATAPATH
55 #define LINUX_DATAPATH 0
56 #endif
57
58 #ifndef O_DIRECTORY
59 #define O_DIRECTORY 0
60 #endif
61
62 static int getsockopt_int(int fd, int level, int option, const char *optname,
63                           int *valuep);
64
65 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
66  * positive errno value. */
67 int
68 set_nonblocking(int fd)
69 {
70     int flags = fcntl(fd, F_GETFL, 0);
71     if (flags != -1) {
72         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
73             return 0;
74         } else {
75             VLOG_ERR("fcntl(F_SETFL) failed: %s", ovs_strerror(errno));
76             return errno;
77         }
78     } else {
79         VLOG_ERR("fcntl(F_GETFL) failed: %s", ovs_strerror(errno));
80         return errno;
81     }
82 }
83
84 void
85 xset_nonblocking(int fd)
86 {
87     if (set_nonblocking(fd)) {
88         exit(EXIT_FAILURE);
89     }
90 }
91
92 int
93 set_dscp(int fd, uint8_t dscp)
94 {
95     int val;
96
97     if (dscp > 63) {
98         return EINVAL;
99     }
100
101     val = dscp << 2;
102     if (setsockopt(fd, IPPROTO_IP, IP_TOS, &val, sizeof val)) {
103         return errno;
104     }
105
106     return 0;
107 }
108
109 static bool
110 rlim_is_finite(rlim_t limit)
111 {
112     if (limit == RLIM_INFINITY) {
113         return false;
114     }
115
116 #ifdef RLIM_SAVED_CUR           /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
117     if (limit == RLIM_SAVED_CUR) {
118         return false;
119     }
120 #endif
121
122 #ifdef RLIM_SAVED_MAX           /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
123     if (limit == RLIM_SAVED_MAX) {
124         return false;
125     }
126 #endif
127
128     return true;
129 }
130
131 /* Returns the maximum valid FD value, plus 1. */
132 int
133 get_max_fds(void)
134 {
135     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
136     static int max_fds;
137
138     if (ovsthread_once_start(&once)) {
139         struct rlimit r;
140         if (!getrlimit(RLIMIT_NOFILE, &r) && rlim_is_finite(r.rlim_cur)) {
141             max_fds = r.rlim_cur;
142         } else {
143             VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
144             max_fds = 1024;
145         }
146         ovsthread_once_done(&once);
147     }
148
149     return max_fds;
150 }
151
152 /* Translates 'host_name', which must be a string representation of an IP
153  * address, into a numeric IP address in '*addr'.  Returns 0 if successful,
154  * otherwise a positive errno value. */
155 int
156 lookup_ip(const char *host_name, struct in_addr *addr)
157 {
158     if (!inet_aton(host_name, addr)) {
159         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
160         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IP address", host_name);
161         return ENOENT;
162     }
163     return 0;
164 }
165
166 /* Translates 'host_name', which must be a string representation of an IPv6
167  * address, into a numeric IPv6 address in '*addr'.  Returns 0 if successful,
168  * otherwise a positive errno value. */
169 int
170 lookup_ipv6(const char *host_name, struct in6_addr *addr)
171 {
172     if (inet_pton(AF_INET6, host_name, addr) != 1) {
173         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
174         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IPv6 address", host_name);
175         return ENOENT;
176     }
177     return 0;
178 }
179
180 /* Translates 'host_name', which must be a host name or a string representation
181  * of an IP address, into a numeric IP address in '*addr'.  Returns 0 if
182  * successful, otherwise a positive errno value.
183  *
184  * Most Open vSwitch code should not use this because it causes deadlocks:
185  * getaddrinfo() sends out a DNS request but that starts a new flow for which
186  * OVS must set up a flow, but it can't because it's waiting for a DNS reply.
187  * The synchronous lookup also delays other activity.  (Of course we can solve
188  * this but it doesn't seem worthwhile quite yet.)  */
189 int
190 lookup_hostname(const char *host_name, struct in_addr *addr)
191 {
192     struct addrinfo *result;
193     struct addrinfo hints;
194
195     if (inet_aton(host_name, addr)) {
196         return 0;
197     }
198
199     memset(&hints, 0, sizeof hints);
200     hints.ai_family = AF_INET;
201
202     switch (getaddrinfo(host_name, NULL, &hints, &result)) {
203     case 0:
204         *addr = ((struct sockaddr_in *) result->ai_addr)->sin_addr;
205         freeaddrinfo(result);
206         return 0;
207
208 #ifdef EAI_ADDRFAMILY
209     case EAI_ADDRFAMILY:
210 #endif
211     case EAI_NONAME:
212     case EAI_SERVICE:
213         return ENOENT;
214
215     case EAI_AGAIN:
216         return EAGAIN;
217
218     case EAI_BADFLAGS:
219     case EAI_FAMILY:
220     case EAI_SOCKTYPE:
221         return EINVAL;
222
223     case EAI_FAIL:
224         return EIO;
225
226     case EAI_MEMORY:
227         return ENOMEM;
228
229 #ifdef EAI_NODATA
230     case EAI_NODATA:
231         return ENXIO;
232 #endif
233
234     case EAI_SYSTEM:
235         return errno;
236
237     default:
238         return EPROTO;
239     }
240 }
241
242 int
243 check_connection_completion(int fd)
244 {
245     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
246     struct pollfd pfd;
247     int retval;
248
249     pfd.fd = fd;
250     pfd.events = POLLOUT;
251     do {
252         retval = poll(&pfd, 1, 0);
253     } while (retval < 0 && errno == EINTR);
254     if (retval == 1) {
255         if (pfd.revents & POLLERR) {
256             ssize_t n = send(fd, "", 1, MSG_DONTWAIT);
257             if (n < 0) {
258                 return errno;
259             } else {
260                 VLOG_ERR_RL(&rl, "poll return POLLERR but send succeeded");
261                 return EPROTO;
262             }
263         }
264         return 0;
265     } else if (retval < 0) {
266         VLOG_ERR_RL(&rl, "poll: %s", ovs_strerror(errno));
267         return errno;
268     } else {
269         return EAGAIN;
270     }
271 }
272
273 /* Drain all the data currently in the receive queue of a datagram socket (and
274  * possibly additional data).  There is no way to know how many packets are in
275  * the receive queue, but we do know that the total number of bytes queued does
276  * not exceed the receive buffer size, so we pull packets until none are left
277  * or we've read that many bytes. */
278 int
279 drain_rcvbuf(int fd)
280 {
281     int rcvbuf;
282
283     rcvbuf = get_socket_rcvbuf(fd);
284     if (rcvbuf < 0) {
285         return -rcvbuf;
286     }
287
288     while (rcvbuf > 0) {
289         /* In Linux, specifying MSG_TRUNC in the flags argument causes the
290          * datagram length to be returned, even if that is longer than the
291          * buffer provided.  Thus, we can use a 1-byte buffer to discard the
292          * incoming datagram and still be able to account how many bytes were
293          * removed from the receive buffer.
294          *
295          * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
296          * argument. */
297         char buffer[LINUX_DATAPATH ? 1 : 2048];
298         ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
299                                MSG_TRUNC | MSG_DONTWAIT);
300         if (n_bytes <= 0 || n_bytes >= rcvbuf) {
301             break;
302         }
303         rcvbuf -= n_bytes;
304     }
305     return 0;
306 }
307
308 /* Returns the size of socket 'sock''s receive buffer (SO_RCVBUF), or a
309  * negative errno value if an error occurs. */
310 int
311 get_socket_rcvbuf(int sock)
312 {
313     int rcvbuf;
314     int error;
315
316     error = getsockopt_int(sock, SOL_SOCKET, SO_RCVBUF, "SO_RCVBUF", &rcvbuf);
317     return error ? -error : rcvbuf;
318 }
319
320 /* Reads and discards up to 'n' datagrams from 'fd', stopping as soon as no
321  * more data can be immediately read.  ('fd' should therefore be in
322  * non-blocking mode.)*/
323 void
324 drain_fd(int fd, size_t n_packets)
325 {
326     for (; n_packets > 0; n_packets--) {
327         /* 'buffer' only needs to be 1 byte long in most circumstances.  This
328          * size is defensive against the possibility that we someday want to
329          * use a Linux tap device without TUN_NO_PI, in which case a buffer
330          * smaller than sizeof(struct tun_pi) will give EINVAL on read. */
331         char buffer[128];
332         if (read(fd, buffer, sizeof buffer) <= 0) {
333             break;
334         }
335     }
336 }
337
338 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
339  * '*un_len' the size of the sockaddr_un. */
340 static void
341 make_sockaddr_un__(const char *name, struct sockaddr_un *un, socklen_t *un_len)
342 {
343     un->sun_family = AF_UNIX;
344     ovs_strzcpy(un->sun_path, name, sizeof un->sun_path);
345     *un_len = (offsetof(struct sockaddr_un, sun_path)
346                 + strlen (un->sun_path) + 1);
347 }
348
349 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
350  * '*un_len' the size of the sockaddr_un.
351  *
352  * Returns 0 on success, otherwise a positive errno value.  On success,
353  * '*dirfdp' is either -1 or a nonnegative file descriptor that the caller
354  * should close after using '*un' to bind or connect.  On failure, '*dirfdp' is
355  * -1. */
356 static int
357 make_sockaddr_un(const char *name, struct sockaddr_un *un, socklen_t *un_len,
358                  int *dirfdp)
359 {
360     enum { MAX_UN_LEN = sizeof un->sun_path - 1 };
361
362     *dirfdp = -1;
363     if (strlen(name) > MAX_UN_LEN) {
364         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
365
366         if (LINUX_DATAPATH) {
367             /* 'name' is too long to fit in a sockaddr_un, but we have a
368              * workaround for that on Linux: shorten it by opening a file
369              * descriptor for the directory part of the name and indirecting
370              * through /proc/self/fd/<dirfd>/<basename>. */
371             char *dir, *base;
372             char *short_name;
373             int dirfd;
374
375             dir = dir_name(name);
376             base = base_name(name);
377
378             dirfd = open(dir, O_DIRECTORY | O_RDONLY);
379             if (dirfd < 0) {
380                 free(base);
381                 free(dir);
382                 return errno;
383             }
384
385             short_name = xasprintf("/proc/self/fd/%d/%s", dirfd, base);
386             free(dir);
387             free(base);
388
389             if (strlen(short_name) <= MAX_UN_LEN) {
390                 make_sockaddr_un__(short_name, un, un_len);
391                 free(short_name);
392                 *dirfdp = dirfd;
393                 return 0;
394             }
395             free(short_name);
396             close(dirfd);
397
398             VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
399                          "%d bytes (even shortened)", name, MAX_UN_LEN);
400         } else {
401             /* 'name' is too long and we have no workaround. */
402             VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
403                          "%d bytes", name, MAX_UN_LEN);
404         }
405
406         return ENAMETOOLONG;
407     } else {
408         make_sockaddr_un__(name, un, un_len);
409         return 0;
410     }
411 }
412
413 /* Binds Unix domain socket 'fd' to a file with permissions 0700. */
414 static int
415 bind_unix_socket(int fd, struct sockaddr *sun, socklen_t sun_len)
416 {
417     /* According to _Unix Network Programming_, umask should affect bind(). */
418     mode_t old_umask = umask(0077);
419     int error = bind(fd, sun, sun_len) ? errno : 0;
420     umask(old_umask);
421     return error;
422 }
423
424 /* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
425  * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
426  * connected to '*connect_path' (if 'connect_path' is non-null).  If 'nonblock'
427  * is true, the socket is made non-blocking.
428  *
429  * Returns the socket's fd if successful, otherwise a negative errno value. */
430 int
431 make_unix_socket(int style, bool nonblock,
432                  const char *bind_path, const char *connect_path)
433 {
434     int error;
435     int fd;
436
437     fd = socket(PF_UNIX, style, 0);
438     if (fd < 0) {
439         return -errno;
440     }
441
442     /* Set nonblocking mode right away, if we want it.  This prevents blocking
443      * in connect(), if connect_path != NULL.  (In turn, that's a corner case:
444      * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
445      * if a backlog of un-accepted connections has built up in the kernel.)  */
446     if (nonblock) {
447         error = set_nonblocking(fd);
448         if (error) {
449             goto error;
450         }
451     }
452
453     if (bind_path) {
454         struct sockaddr_un un;
455         socklen_t un_len;
456         int dirfd;
457
458         if (unlink(bind_path) && errno != ENOENT) {
459             VLOG_WARN("unlinking \"%s\": %s\n",
460                       bind_path, ovs_strerror(errno));
461         }
462         fatal_signal_add_file_to_unlink(bind_path);
463
464         error = make_sockaddr_un(bind_path, &un, &un_len, &dirfd);
465         if (!error) {
466             error = bind_unix_socket(fd, (struct sockaddr *) &un, un_len);
467         }
468         if (dirfd >= 0) {
469             close(dirfd);
470         }
471         if (error) {
472             goto error;
473         }
474     }
475
476     if (connect_path) {
477         struct sockaddr_un un;
478         socklen_t un_len;
479         int dirfd;
480
481         error = make_sockaddr_un(connect_path, &un, &un_len, &dirfd);
482         if (!error
483             && connect(fd, (struct sockaddr*) &un, un_len)
484             && errno != EINPROGRESS) {
485             error = errno;
486         }
487         if (dirfd >= 0) {
488             close(dirfd);
489         }
490         if (error) {
491             goto error;
492         }
493     }
494
495     return fd;
496
497 error:
498     if (error == EAGAIN) {
499         error = EPROTO;
500     }
501     if (bind_path) {
502         fatal_signal_unlink_file_now(bind_path);
503     }
504     close(fd);
505     return -error;
506 }
507
508 int
509 get_unix_name_len(socklen_t sun_len)
510 {
511     return (sun_len >= offsetof(struct sockaddr_un, sun_path)
512             ? sun_len - offsetof(struct sockaddr_un, sun_path)
513             : 0);
514 }
515
516 ovs_be32
517 guess_netmask(ovs_be32 ip_)
518 {
519     uint32_t ip = ntohl(ip_);
520     return ((ip >> 31) == 0 ? htonl(0xff000000)   /* Class A */
521             : (ip >> 30) == 2 ? htonl(0xffff0000) /* Class B */
522             : (ip >> 29) == 6 ? htonl(0xffffff00) /* Class C */
523             : htonl(0));                          /* ??? */
524 }
525
526 /* Parses 'target', which should be a string in the format "<host>[:<port>]".
527  * <host> is required.  If 'default_port' is nonzero then <port> is optional
528  * and defaults to 'default_port'.
529  *
530  * On success, returns true and stores the parsed remote address into '*sinp'.
531  * On failure, logs an error, stores zeros into '*sinp', and returns false. */
532 bool
533 inet_parse_active(const char *target_, uint16_t default_port,
534                   struct sockaddr_in *sinp)
535 {
536     char *target = xstrdup(target_);
537     char *save_ptr = NULL;
538     const char *host_name;
539     const char *port_string;
540     bool ok = false;
541
542     /* Defaults. */
543     sinp->sin_family = AF_INET;
544     sinp->sin_port = htons(default_port);
545
546     /* Tokenize. */
547     host_name = strtok_r(target, ":", &save_ptr);
548     port_string = strtok_r(NULL, ":", &save_ptr);
549     if (!host_name) {
550         VLOG_ERR("%s: bad peer name format", target_);
551         goto exit;
552     }
553
554     /* Look up IP, port. */
555     if (lookup_ip(host_name, &sinp->sin_addr)) {
556         goto exit;
557     }
558     if (port_string && atoi(port_string)) {
559         sinp->sin_port = htons(atoi(port_string));
560     } else if (!default_port) {
561         VLOG_ERR("%s: port number must be specified", target_);
562         goto exit;
563     }
564
565     ok = true;
566
567 exit:
568     if (!ok) {
569         memset(sinp, 0, sizeof *sinp);
570     }
571     free(target);
572     return ok;
573 }
574
575 /* Opens a non-blocking IPv4 socket of the specified 'style' and connects to
576  * 'target', which should be a string in the format "<host>[:<port>]".  <host>
577  * is required.  If 'default_port' is nonzero then <port> is optional and
578  * defaults to 'default_port'.
579  *
580  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
581  *
582  * On success, returns 0 (indicating connection complete) or EAGAIN (indicating
583  * connection in progress), in which case the new file descriptor is stored
584  * into '*fdp'.  On failure, returns a positive errno value other than EAGAIN
585  * and stores -1 into '*fdp'.
586  *
587  * If 'sinp' is non-null, then on success the target address is stored into
588  * '*sinp'.
589  *
590  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
591  * should be in the range [0, 63] and will automatically be shifted to the
592  * appropriately place in the IP tos field. */
593 int
594 inet_open_active(int style, const char *target, uint16_t default_port,
595                  struct sockaddr_in *sinp, int *fdp, uint8_t dscp)
596 {
597     struct sockaddr_in sin;
598     int fd = -1;
599     int error;
600
601     /* Parse. */
602     if (!inet_parse_active(target, default_port, &sin)) {
603         error = EAFNOSUPPORT;
604         goto exit;
605     }
606
607     /* Create non-blocking socket. */
608     fd = socket(AF_INET, style, 0);
609     if (fd < 0) {
610         VLOG_ERR("%s: socket: %s", target, ovs_strerror(errno));
611         error = errno;
612         goto exit;
613     }
614     error = set_nonblocking(fd);
615     if (error) {
616         goto exit;
617     }
618
619     /* The dscp bits must be configured before connect() to ensure that the TOS
620      * field is set during the connection establishment.  If set after
621      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
622     error = set_dscp(fd, dscp);
623     if (error) {
624         VLOG_ERR("%s: socket: %s", target, ovs_strerror(error));
625         goto exit;
626     }
627
628     /* Connect. */
629     error = connect(fd, (struct sockaddr *) &sin, sizeof sin) == 0 ? 0 : errno;
630     if (error == EINPROGRESS) {
631         error = EAGAIN;
632     }
633
634 exit:
635     if (!error || error == EAGAIN) {
636         if (sinp) {
637             *sinp = sin;
638         }
639     } else if (fd >= 0) {
640         close(fd);
641         fd = -1;
642     }
643     *fdp = fd;
644     return error;
645 }
646
647 /* Parses 'target', which should be a string in the format "[<port>][:<ip>]":
648  *
649  *      - If 'default_port' is -1, then <port> is required.  Otherwise, if
650  *        <port> is omitted, then 'default_port' is used instead.
651  *
652  *      - If <port> (or 'default_port', if used) is 0, then no port is bound
653  *        and the TCP/IP stack will select a port.
654  *
655  *      - If <ip> is omitted then the IP address is wildcarded.
656  *
657  * If successful, stores the address into '*sinp' and returns true; otherwise
658  * zeros '*sinp' and returns false. */
659 bool
660 inet_parse_passive(const char *target_, int default_port,
661                    struct sockaddr_in *sinp)
662 {
663     char *target = xstrdup(target_);
664     char *string_ptr = target;
665     const char *host_name;
666     const char *port_string;
667     bool ok = false;
668     int port;
669
670     /* Address defaults. */
671     memset(sinp, 0, sizeof *sinp);
672     sinp->sin_family = AF_INET;
673     sinp->sin_addr.s_addr = htonl(INADDR_ANY);
674     sinp->sin_port = htons(default_port);
675
676     /* Parse optional port number. */
677     port_string = strsep(&string_ptr, ":");
678     if (port_string && str_to_int(port_string, 10, &port)) {
679         sinp->sin_port = htons(port);
680     } else if (default_port < 0) {
681         VLOG_ERR("%s: port number must be specified", target_);
682         goto exit;
683     }
684
685     /* Parse optional bind IP. */
686     host_name = strsep(&string_ptr, ":");
687     if (host_name && host_name[0] && lookup_ip(host_name, &sinp->sin_addr)) {
688         goto exit;
689     }
690
691     ok = true;
692
693 exit:
694     if (!ok) {
695         memset(sinp, 0, sizeof *sinp);
696     }
697     free(target);
698     return ok;
699 }
700
701
702 /* Opens a non-blocking IPv4 socket of the specified 'style', binds to
703  * 'target', and listens for incoming connections.  Parses 'target' in the same
704  * way was inet_parse_passive().
705  *
706  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
707  *
708  * For TCP, the socket will have SO_REUSEADDR turned on.
709  *
710  * On success, returns a non-negative file descriptor.  On failure, returns a
711  * negative errno value.
712  *
713  * If 'sinp' is non-null, then on success the bound address is stored into
714  * '*sinp'.
715  *
716  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
717  * should be in the range [0, 63] and will automatically be shifted to the
718  * appropriately place in the IP tos field. */
719 int
720 inet_open_passive(int style, const char *target, int default_port,
721                   struct sockaddr_in *sinp, uint8_t dscp)
722 {
723     bool kernel_chooses_port;
724     struct sockaddr_in sin;
725     int fd = 0, error;
726     unsigned int yes = 1;
727
728     if (!inet_parse_passive(target, default_port, &sin)) {
729         return -EAFNOSUPPORT;
730     }
731
732     /* Create non-blocking socket, set SO_REUSEADDR. */
733     fd = socket(AF_INET, style, 0);
734     if (fd < 0) {
735         error = errno;
736         VLOG_ERR("%s: socket: %s", target, ovs_strerror(error));
737         return -error;
738     }
739     error = set_nonblocking(fd);
740     if (error) {
741         goto error;
742     }
743     if (style == SOCK_STREAM
744         && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
745         error = errno;
746         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s",
747                  target, ovs_strerror(error));
748         goto error;
749     }
750
751     /* Bind. */
752     if (bind(fd, (struct sockaddr *) &sin, sizeof sin) < 0) {
753         error = errno;
754         VLOG_ERR("%s: bind: %s", target, ovs_strerror(error));
755         goto error;
756     }
757
758     /* The dscp bits must be configured before connect() to ensure that the TOS
759      * field is set during the connection establishment.  If set after
760      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
761     error = set_dscp(fd, dscp);
762     if (error) {
763         VLOG_ERR("%s: socket: %s", target, ovs_strerror(error));
764         goto error;
765     }
766
767     /* Listen. */
768     if (style == SOCK_STREAM && listen(fd, 10) < 0) {
769         error = errno;
770         VLOG_ERR("%s: listen: %s", target, ovs_strerror(error));
771         goto error;
772     }
773
774     kernel_chooses_port = sin.sin_port == htons(0);
775     if (sinp || kernel_chooses_port) {
776         socklen_t sin_len = sizeof sin;
777         if (getsockname(fd, (struct sockaddr *) &sin, &sin_len) < 0) {
778             error = errno;
779             VLOG_ERR("%s: getsockname: %s", target, ovs_strerror(error));
780             goto error;
781         }
782         if (sin.sin_family != AF_INET || sin_len != sizeof sin) {
783             error = EAFNOSUPPORT;
784             VLOG_ERR("%s: getsockname: invalid socket name", target);
785             goto error;
786         }
787         if (sinp) {
788             *sinp = sin;
789         }
790         if (kernel_chooses_port) {
791             VLOG_INFO("%s: listening on port %"PRIu16,
792                       target, ntohs(sin.sin_port));
793         }
794     }
795
796     return fd;
797
798 error:
799     close(fd);
800     return -error;
801 }
802
803 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
804  * a negative errno value.  The caller must not close the returned fd (because
805  * the same fd will be handed out to subsequent callers). */
806 int
807 get_null_fd(void)
808 {
809     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
810     static int null_fd;
811
812     if (ovsthread_once_start(&once)) {
813         null_fd = open("/dev/null", O_RDWR);
814         if (null_fd < 0) {
815             int error = errno;
816             VLOG_ERR("could not open /dev/null: %s", ovs_strerror(error));
817             null_fd = -error;
818         }
819         ovsthread_once_done(&once);
820     }
821
822     return null_fd;
823 }
824
825 int
826 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
827 {
828     uint8_t *p = p_;
829
830     *bytes_read = 0;
831     while (size > 0) {
832         ssize_t retval = read(fd, p, size);
833         if (retval > 0) {
834             *bytes_read += retval;
835             size -= retval;
836             p += retval;
837         } else if (retval == 0) {
838             return EOF;
839         } else if (errno != EINTR) {
840             return errno;
841         }
842     }
843     return 0;
844 }
845
846 int
847 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
848 {
849     const uint8_t *p = p_;
850
851     *bytes_written = 0;
852     while (size > 0) {
853         ssize_t retval = write(fd, p, size);
854         if (retval > 0) {
855             *bytes_written += retval;
856             size -= retval;
857             p += retval;
858         } else if (retval == 0) {
859             VLOG_WARN("write returned 0");
860             return EPROTO;
861         } else if (errno != EINTR) {
862             return errno;
863         }
864     }
865     return 0;
866 }
867
868 /* Given file name 'file_name', fsyncs the directory in which it is contained.
869  * Returns 0 if successful, otherwise a positive errno value. */
870 int
871 fsync_parent_dir(const char *file_name)
872 {
873     int error = 0;
874     char *dir;
875     int fd;
876
877     dir = dir_name(file_name);
878     fd = open(dir, O_RDONLY);
879     if (fd >= 0) {
880         if (fsync(fd)) {
881             if (errno == EINVAL || errno == EROFS) {
882                 /* This directory does not support synchronization.  Not
883                  * really an error. */
884             } else {
885                 error = errno;
886                 VLOG_ERR("%s: fsync failed (%s)", dir, ovs_strerror(error));
887             }
888         }
889         close(fd);
890     } else {
891         error = errno;
892         VLOG_ERR("%s: open failed (%s)", dir, ovs_strerror(error));
893     }
894     free(dir);
895
896     return error;
897 }
898
899 /* Obtains the modification time of the file named 'file_name' to the greatest
900  * supported precision.  If successful, stores the mtime in '*mtime' and
901  * returns 0.  On error, returns a positive errno value and stores zeros in
902  * '*mtime'. */
903 int
904 get_mtime(const char *file_name, struct timespec *mtime)
905 {
906     struct stat s;
907
908     if (!stat(file_name, &s)) {
909         mtime->tv_sec = s.st_mtime;
910
911 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
912         mtime->tv_nsec = s.st_mtim.tv_nsec;
913 #elif HAVE_STRUCT_STAT_ST_MTIMENSEC
914         mtime->tv_nsec = s.st_mtimensec;
915 #else
916         mtime->tv_nsec = 0;
917 #endif
918
919         return 0;
920     } else {
921         mtime->tv_sec = mtime->tv_nsec = 0;
922         return errno;
923     }
924 }
925
926 void
927 xpipe(int fds[2])
928 {
929     if (pipe(fds)) {
930         VLOG_FATAL("failed to create pipe (%s)", ovs_strerror(errno));
931     }
932 }
933
934 void
935 xpipe_nonblocking(int fds[2])
936 {
937     xpipe(fds);
938     xset_nonblocking(fds[0]);
939     xset_nonblocking(fds[1]);
940 }
941
942 void
943 xsocketpair(int domain, int type, int protocol, int fds[2])
944 {
945     if (socketpair(domain, type, protocol, fds)) {
946         VLOG_FATAL("failed to create socketpair (%s)", ovs_strerror(errno));
947     }
948 }
949
950 static int
951 getsockopt_int(int fd, int level, int option, const char *optname, int *valuep)
952 {
953     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
954     socklen_t len;
955     int value;
956     int error;
957
958     len = sizeof value;
959     if (getsockopt(fd, level, option, &value, &len)) {
960         error = errno;
961         VLOG_ERR_RL(&rl, "getsockopt(%s): %s", optname, ovs_strerror(error));
962     } else if (len != sizeof value) {
963         error = EINVAL;
964         VLOG_ERR_RL(&rl, "getsockopt(%s): value is %u bytes (expected %zu)",
965                     optname, (unsigned int) len, sizeof value);
966     } else {
967         error = 0;
968     }
969
970     *valuep = error ? 0 : value;
971     return error;
972 }
973
974 static void
975 describe_sockaddr(struct ds *string, int fd,
976                   int (*getaddr)(int, struct sockaddr *, socklen_t *))
977 {
978     struct sockaddr_storage ss;
979     socklen_t len = sizeof ss;
980
981     if (!getaddr(fd, (struct sockaddr *) &ss, &len)) {
982         if (ss.ss_family == AF_INET) {
983             struct sockaddr_in sin;
984
985             memcpy(&sin, &ss, sizeof sin);
986             ds_put_format(string, IP_FMT":%"PRIu16,
987                           IP_ARGS(sin.sin_addr.s_addr), ntohs(sin.sin_port));
988         } else if (ss.ss_family == AF_UNIX) {
989             struct sockaddr_un sun;
990             const char *null;
991             size_t maxlen;
992
993             memcpy(&sun, &ss, sizeof sun);
994             maxlen = len - offsetof(struct sockaddr_un, sun_path);
995             null = memchr(sun.sun_path, '\0', maxlen);
996             ds_put_buffer(string, sun.sun_path,
997                           null ? null - sun.sun_path : maxlen);
998         }
999 #ifdef HAVE_NETLINK
1000         else if (ss.ss_family == AF_NETLINK) {
1001             int protocol;
1002
1003 /* SO_PROTOCOL was introduced in 2.6.32.  Support it regardless of the version
1004  * of the Linux kernel headers in use at build time. */
1005 #ifndef SO_PROTOCOL
1006 #define SO_PROTOCOL 38
1007 #endif
1008
1009             if (!getsockopt_int(fd, SOL_SOCKET, SO_PROTOCOL, "SO_PROTOCOL",
1010                                 &protocol)) {
1011                 switch (protocol) {
1012                 case NETLINK_ROUTE:
1013                     ds_put_cstr(string, "NETLINK_ROUTE");
1014                     break;
1015
1016                 case NETLINK_GENERIC:
1017                     ds_put_cstr(string, "NETLINK_GENERIC");
1018                     break;
1019
1020                 default:
1021                     ds_put_format(string, "AF_NETLINK family %d", protocol);
1022                     break;
1023                 }
1024             } else {
1025                 ds_put_cstr(string, "AF_NETLINK");
1026             }
1027         }
1028 #endif
1029 #if AF_PACKET && LINUX_DATAPATH
1030         else if (ss.ss_family == AF_PACKET) {
1031             struct sockaddr_ll sll;
1032
1033             memcpy(&sll, &ss, sizeof sll);
1034             ds_put_cstr(string, "AF_PACKET");
1035             if (sll.sll_ifindex) {
1036                 char name[IFNAMSIZ];
1037
1038                 if (if_indextoname(sll.sll_ifindex, name)) {
1039                     ds_put_format(string, "(%s)", name);
1040                 } else {
1041                     ds_put_format(string, "(ifindex=%d)", sll.sll_ifindex);
1042                 }
1043             }
1044             if (sll.sll_protocol) {
1045                 ds_put_format(string, "(protocol=0x%"PRIu16")",
1046                               ntohs(sll.sll_protocol));
1047             }
1048         }
1049 #endif
1050         else if (ss.ss_family == AF_UNSPEC) {
1051             ds_put_cstr(string, "AF_UNSPEC");
1052         } else {
1053             ds_put_format(string, "AF_%d", (int) ss.ss_family);
1054         }
1055     }
1056 }
1057
1058
1059 #ifdef LINUX_DATAPATH
1060 static void
1061 put_fd_filename(struct ds *string, int fd)
1062 {
1063     char buf[1024];
1064     char *linkname;
1065     int n;
1066
1067     linkname = xasprintf("/proc/self/fd/%d", fd);
1068     n = readlink(linkname, buf, sizeof buf);
1069     if (n > 0) {
1070         ds_put_char(string, ' ');
1071         ds_put_buffer(string, buf, n);
1072         if (n > sizeof buf) {
1073             ds_put_cstr(string, "...");
1074         }
1075     }
1076     free(linkname);
1077 }
1078 #endif
1079
1080 /* Returns a malloc()'d string describing 'fd', for use in logging. */
1081 char *
1082 describe_fd(int fd)
1083 {
1084     struct ds string;
1085     struct stat s;
1086
1087     ds_init(&string);
1088     if (fstat(fd, &s)) {
1089         ds_put_format(&string, "fstat failed (%s)", ovs_strerror(errno));
1090     } else if (S_ISSOCK(s.st_mode)) {
1091         describe_sockaddr(&string, fd, getsockname);
1092         ds_put_cstr(&string, "<->");
1093         describe_sockaddr(&string, fd, getpeername);
1094     } else {
1095         ds_put_cstr(&string, (isatty(fd) ? "tty"
1096                               : S_ISDIR(s.st_mode) ? "directory"
1097                               : S_ISCHR(s.st_mode) ? "character device"
1098                               : S_ISBLK(s.st_mode) ? "block device"
1099                               : S_ISREG(s.st_mode) ? "file"
1100                               : S_ISFIFO(s.st_mode) ? "FIFO"
1101                               : S_ISLNK(s.st_mode) ? "symbolic link"
1102                               : "unknown"));
1103 #ifdef LINUX_DATAPATH
1104         put_fd_filename(&string, fd);
1105 #endif
1106     }
1107     return ds_steal_cstr(&string);
1108 }
1109
1110 /* Returns the total of the 'iov_len' members of the 'n_iovs' in 'iovs'.
1111  * The caller must ensure that the total does not exceed SIZE_MAX. */
1112 size_t
1113 iovec_len(const struct iovec iovs[], size_t n_iovs)
1114 {
1115     size_t len = 0;
1116     size_t i;
1117
1118     for (i = 0; i < n_iovs; i++) {
1119         len += iovs[i].iov_len;
1120     }
1121     return len;
1122 }
1123
1124 /* Returns true if all of the 'n_iovs' iovecs in 'iovs' have length zero. */
1125 bool
1126 iovec_is_empty(const struct iovec iovs[], size_t n_iovs)
1127 {
1128     size_t i;
1129
1130     for (i = 0; i < n_iovs; i++) {
1131         if (iovs[i].iov_len) {
1132             return false;
1133         }
1134     }
1135     return true;
1136 }
1137
1138 /* Sends the 'n_iovs' iovecs of data in 'iovs' and the 'n_fds' file descriptors
1139  * in 'fds' on Unix domain socket 'sock'.  Returns the number of bytes
1140  * successfully sent or -1 if an error occurred.  On error, sets errno
1141  * appropriately.  */
1142 int
1143 send_iovec_and_fds(int sock,
1144                    const struct iovec *iovs, size_t n_iovs,
1145                    const int fds[], size_t n_fds)
1146 {
1147     ovs_assert(sock >= 0);
1148     if (n_fds > 0) {
1149         union {
1150             struct cmsghdr cm;
1151             char control[CMSG_SPACE(SOUTIL_MAX_FDS * sizeof *fds)];
1152         } cmsg;
1153         struct msghdr msg;
1154
1155         ovs_assert(!iovec_is_empty(iovs, n_iovs));
1156         ovs_assert(n_fds <= SOUTIL_MAX_FDS);
1157
1158         memset(&cmsg, 0, sizeof cmsg);
1159         cmsg.cm.cmsg_len = CMSG_LEN(n_fds * sizeof *fds);
1160         cmsg.cm.cmsg_level = SOL_SOCKET;
1161         cmsg.cm.cmsg_type = SCM_RIGHTS;
1162         memcpy(CMSG_DATA(&cmsg.cm), fds, n_fds * sizeof *fds);
1163
1164         msg.msg_name = NULL;
1165         msg.msg_namelen = 0;
1166         msg.msg_iov = CONST_CAST(struct iovec *, iovs);
1167         msg.msg_iovlen = n_iovs;
1168         msg.msg_control = &cmsg.cm;
1169         msg.msg_controllen = CMSG_SPACE(n_fds * sizeof *fds);
1170         msg.msg_flags = 0;
1171
1172         return sendmsg(sock, &msg, 0);
1173     } else {
1174         return writev(sock, iovs, n_iovs);
1175     }
1176 }
1177
1178 /* Sends the 'n_iovs' iovecs of data in 'iovs' and the 'n_fds' file descriptors
1179  * in 'fds' on Unix domain socket 'sock'.  If 'skip_bytes' is nonzero, then the
1180  * first 'skip_bytes' of data in the iovecs are not sent, and none of the file
1181  * descriptors are sent.  The function continues to retry sending until an
1182  * error (other than EINTR) occurs or all the data and fds are sent.
1183  *
1184  * Returns 0 if all the data and fds were successfully sent, otherwise a
1185  * positive errno value.  Regardless of success, stores the number of bytes
1186  * sent (always at least 'skip_bytes') in '*bytes_sent'.  (If at least one byte
1187  * is sent, then all the fds have been sent.)
1188  *
1189  * 'skip_bytes' must be less than or equal to iovec_len(iovs, n_iovs). */
1190 int
1191 send_iovec_and_fds_fully(int sock,
1192                          const struct iovec iovs[], size_t n_iovs,
1193                          const int fds[], size_t n_fds,
1194                          size_t skip_bytes, size_t *bytes_sent)
1195 {
1196     *bytes_sent = 0;
1197     while (n_iovs > 0) {
1198         int retval;
1199
1200         if (skip_bytes) {
1201             retval = skip_bytes;
1202             skip_bytes = 0;
1203         } else if (!*bytes_sent) {
1204             retval = send_iovec_and_fds(sock, iovs, n_iovs, fds, n_fds);
1205         } else {
1206             retval = writev(sock, iovs, n_iovs);
1207         }
1208
1209         if (retval > 0) {
1210             *bytes_sent += retval;
1211             while (retval > 0) {
1212                 const uint8_t *base = iovs->iov_base;
1213                 size_t len = iovs->iov_len;
1214
1215                 if (retval < len) {
1216                     size_t sent;
1217                     int error;
1218
1219                     error = write_fully(sock, base + retval, len - retval,
1220                                         &sent);
1221                     *bytes_sent += sent;
1222                     retval += sent;
1223                     if (error) {
1224                         return error;
1225                     }
1226                 }
1227                 retval -= len;
1228                 iovs++;
1229                 n_iovs--;
1230             }
1231         } else if (retval == 0) {
1232             if (iovec_is_empty(iovs, n_iovs)) {
1233                 break;
1234             }
1235             VLOG_WARN("send returned 0");
1236             return EPROTO;
1237         } else if (errno != EINTR) {
1238             return errno;
1239         }
1240     }
1241
1242     return 0;
1243 }
1244
1245 /* Sends the 'n_iovs' iovecs of data in 'iovs' and the 'n_fds' file descriptors
1246  * in 'fds' on Unix domain socket 'sock'.  The function continues to retry
1247  * sending until an error (other than EAGAIN or EINTR) occurs or all the data
1248  * and fds are sent.  Upon EAGAIN, the function blocks until the socket is
1249  * ready for more data.
1250  *
1251  * Returns 0 if all the data and fds were successfully sent, otherwise a
1252  * positive errno value. */
1253 int
1254 send_iovec_and_fds_fully_block(int sock,
1255                                const struct iovec iovs[], size_t n_iovs,
1256                                const int fds[], size_t n_fds)
1257 {
1258     size_t sent = 0;
1259
1260     for (;;) {
1261         int error;
1262
1263         error = send_iovec_and_fds_fully(sock, iovs, n_iovs,
1264                                          fds, n_fds, sent, &sent);
1265         if (error != EAGAIN) {
1266             return error;
1267         }
1268         poll_fd_wait(sock, POLLOUT);
1269         poll_block();
1270     }
1271 }
1272
1273 /* Attempts to receive from Unix domain socket 'sock' up to 'size' bytes of
1274  * data into 'data' and up to SOUTIL_MAX_FDS file descriptors into 'fds'.
1275  *
1276  *      - Upon success, returns the number of bytes of data copied into 'data'
1277  *        and stores the number of received file descriptors into '*n_fdsp'.
1278  *
1279  *      - On failure, returns a negative errno value and stores 0 in
1280  *        '*n_fdsp'.
1281  *
1282  *      - On EOF, returns 0 and stores 0 in '*n_fdsp'. */
1283 int
1284 recv_data_and_fds(int sock,
1285                   void *data, size_t size,
1286                   int fds[SOUTIL_MAX_FDS], size_t *n_fdsp)
1287 {
1288     union {
1289         struct cmsghdr cm;
1290         char control[CMSG_SPACE(SOUTIL_MAX_FDS * sizeof *fds)];
1291     } cmsg;
1292     struct msghdr msg;
1293     int retval;
1294     struct cmsghdr *p;
1295     size_t i;
1296
1297     *n_fdsp = 0;
1298
1299     do {
1300         struct iovec iov;
1301
1302         iov.iov_base = data;
1303         iov.iov_len = size;
1304
1305         msg.msg_name = NULL;
1306         msg.msg_namelen = 0;
1307         msg.msg_iov = &iov;
1308         msg.msg_iovlen = 1;
1309         msg.msg_control = &cmsg.cm;
1310         msg.msg_controllen = sizeof cmsg.control;
1311         msg.msg_flags = 0;
1312
1313         retval = recvmsg(sock, &msg, 0);
1314     } while (retval < 0 && errno == EINTR);
1315     if (retval <= 0) {
1316         return retval < 0 ? -errno : 0;
1317     }
1318
1319     for (p = CMSG_FIRSTHDR(&msg); p; p = CMSG_NXTHDR(&msg, p)) {
1320         if (p->cmsg_level != SOL_SOCKET || p->cmsg_type != SCM_RIGHTS) {
1321             VLOG_ERR("unexpected control message %d:%d",
1322                      p->cmsg_level, p->cmsg_type);
1323             goto error;
1324         } else if (*n_fdsp) {
1325             VLOG_ERR("multiple SCM_RIGHTS received");
1326             goto error;
1327         } else {
1328             size_t n_fds = (p->cmsg_len - CMSG_LEN(0)) / sizeof *fds;
1329             const int *fds_data = (const int *) CMSG_DATA(p);
1330
1331             ovs_assert(n_fds > 0);
1332             if (n_fds > SOUTIL_MAX_FDS) {
1333                 VLOG_ERR("%zu fds received but only %d supported",
1334                          n_fds, SOUTIL_MAX_FDS);
1335                 for (i = 0; i < n_fds; i++) {
1336                     close(fds_data[i]);
1337                 }
1338                 goto error;
1339             }
1340
1341             *n_fdsp = n_fds;
1342             memcpy(fds, fds_data, n_fds * sizeof *fds);
1343         }
1344     }
1345
1346     return retval;
1347
1348 error:
1349     for (i = 0; i < *n_fdsp; i++) {
1350         close(fds[i]);
1351     }
1352     *n_fdsp = 0;
1353     return EPROTO;
1354 }