939cd90ff8a8eef55cb809a775c424dadad9d4ac
[openvswitch] / lib / socket-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 <assert.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <net/if.h>
24 #include <netdb.h>
25 #include <poll.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/resource.h>
31 #include <sys/socket.h>
32 #include <sys/stat.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 "util.h"
39 #include "vlog.h"
40 #if AF_PACKET && __linux__
41 #include <linux/if_packet.h>
42 #endif
43 #ifdef HAVE_NETLINK
44 #include "netlink-protocol.h"
45 #include "netlink-socket.h"
46 #endif
47
48 VLOG_DEFINE_THIS_MODULE(socket_util);
49
50 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
51  * Thus, this file compiles all of the code regardless of the target, by
52  * writing "if (LINUX)" instead of "#ifdef __linux__". */
53 #ifdef __linux__
54 #define LINUX 1
55 #else
56 #define LINUX 0
57 #endif
58
59 #ifndef O_DIRECTORY
60 #define O_DIRECTORY 0
61 #endif
62
63 static int getsockopt_int(int fd, int level, int option, const char *optname,
64                           int *valuep);
65
66 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
67  * positive errno value. */
68 int
69 set_nonblocking(int fd)
70 {
71     int flags = fcntl(fd, F_GETFL, 0);
72     if (flags != -1) {
73         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
74             return 0;
75         } else {
76             VLOG_ERR("fcntl(F_SETFL) failed: %s", strerror(errno));
77             return errno;
78         }
79     } else {
80         VLOG_ERR("fcntl(F_GETFL) failed: %s", strerror(errno));
81         return errno;
82     }
83 }
84
85 void
86 xset_nonblocking(int fd)
87 {
88     if (set_nonblocking(fd)) {
89         exit(EXIT_FAILURE);
90     }
91 }
92
93 static int
94 set_dscp(int fd, uint8_t dscp)
95 {
96     if (dscp > 63) {
97         return EINVAL;
98     }
99
100     dscp = dscp << 2;
101     if (setsockopt(fd, IPPROTO_IP, IP_TOS, &dscp, sizeof dscp)) {
102         return errno;
103     }
104
105     return 0;
106 }
107
108 static bool
109 rlim_is_finite(rlim_t limit)
110 {
111     if (limit == RLIM_INFINITY) {
112         return false;
113     }
114
115 #ifdef RLIM_SAVED_CUR           /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
116     if (limit == RLIM_SAVED_CUR) {
117         return false;
118     }
119 #endif
120
121 #ifdef RLIM_SAVED_MAX           /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
122     if (limit == RLIM_SAVED_MAX) {
123         return false;
124     }
125 #endif
126
127     return true;
128 }
129
130 /* Returns the maximum valid FD value, plus 1. */
131 int
132 get_max_fds(void)
133 {
134     static int max_fds = -1;
135     if (max_fds < 0) {
136         struct rlimit r;
137         if (!getrlimit(RLIMIT_NOFILE, &r) && rlim_is_finite(r.rlim_cur)) {
138             max_fds = r.rlim_cur;
139         } else {
140             VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
141             max_fds = 1024;
142         }
143     }
144     return max_fds;
145 }
146
147 /* Translates 'host_name', which must be a string representation of an IP
148  * address, into a numeric IP address in '*addr'.  Returns 0 if successful,
149  * otherwise a positive errno value. */
150 int
151 lookup_ip(const char *host_name, struct in_addr *addr)
152 {
153     if (!inet_aton(host_name, addr)) {
154         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
155         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IP address", host_name);
156         return ENOENT;
157     }
158     return 0;
159 }
160
161 /* Translates 'host_name', which must be a string representation of an IPv6
162  * address, into a numeric IPv6 address in '*addr'.  Returns 0 if successful,
163  * otherwise a positive errno value. */
164 int
165 lookup_ipv6(const char *host_name, struct in6_addr *addr)
166 {
167     if (inet_pton(AF_INET6, host_name, addr) != 1) {
168         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
169         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IPv6 address", host_name);
170         return ENOENT;
171     }
172     return 0;
173 }
174
175 /* Translates 'host_name', which must be a host name or a string representation
176  * of an IP address, into a numeric IP address in '*addr'.  Returns 0 if
177  * successful, otherwise a positive errno value.
178  *
179  * Most Open vSwitch code should not use this because it causes deadlocks:
180  * gethostbyname() sends out a DNS request but that starts a new flow for which
181  * OVS must set up a flow, but it can't because it's waiting for a DNS reply.
182  * The synchronous lookup also delays other activty.  (Of course we can solve
183  * this but it doesn't seem worthwhile quite yet.)  */
184 int
185 lookup_hostname(const char *host_name, struct in_addr *addr)
186 {
187     struct hostent *h;
188
189     if (inet_aton(host_name, addr)) {
190         return 0;
191     }
192
193     h = gethostbyname(host_name);
194     if (h) {
195         *addr = *(struct in_addr *) h->h_addr;
196         return 0;
197     }
198
199     return (h_errno == HOST_NOT_FOUND ? ENOENT
200             : h_errno == TRY_AGAIN ? EAGAIN
201             : h_errno == NO_RECOVERY ? EIO
202             : h_errno == NO_ADDRESS ? ENXIO
203             : EINVAL);
204 }
205
206 /* Returns the error condition associated with socket 'fd' and resets the
207  * socket's error status. */
208 int
209 get_socket_error(int fd)
210 {
211     int error;
212
213     if (getsockopt_int(fd, SOL_SOCKET, SO_ERROR, "SO_ERROR", &error)) {
214         error = errno;
215     }
216     return error;
217 }
218
219 int
220 check_connection_completion(int fd)
221 {
222     struct pollfd pfd;
223     int retval;
224
225     pfd.fd = fd;
226     pfd.events = POLLOUT;
227     do {
228         retval = poll(&pfd, 1, 0);
229     } while (retval < 0 && errno == EINTR);
230     if (retval == 1) {
231         return get_socket_error(fd);
232     } else if (retval < 0) {
233         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
234         VLOG_ERR_RL(&rl, "poll: %s", strerror(errno));
235         return errno;
236     } else {
237         return EAGAIN;
238     }
239 }
240
241 /* Drain all the data currently in the receive queue of a datagram socket (and
242  * possibly additional data).  There is no way to know how many packets are in
243  * the receive queue, but we do know that the total number of bytes queued does
244  * not exceed the receive buffer size, so we pull packets until none are left
245  * or we've read that many bytes. */
246 int
247 drain_rcvbuf(int fd)
248 {
249     int rcvbuf;
250
251     rcvbuf = get_socket_rcvbuf(fd);
252     if (rcvbuf < 0) {
253         return -rcvbuf;
254     }
255
256     while (rcvbuf > 0) {
257         /* In Linux, specifying MSG_TRUNC in the flags argument causes the
258          * datagram length to be returned, even if that is longer than the
259          * buffer provided.  Thus, we can use a 1-byte buffer to discard the
260          * incoming datagram and still be able to account how many bytes were
261          * removed from the receive buffer.
262          *
263          * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
264          * argument. */
265         char buffer[LINUX ? 1 : 2048];
266         ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
267                                MSG_TRUNC | MSG_DONTWAIT);
268         if (n_bytes <= 0 || n_bytes >= rcvbuf) {
269             break;
270         }
271         rcvbuf -= n_bytes;
272     }
273     return 0;
274 }
275
276 /* Returns the size of socket 'sock''s receive buffer (SO_RCVBUF), or a
277  * negative errno value if an error occurs. */
278 int
279 get_socket_rcvbuf(int sock)
280 {
281     int rcvbuf;
282     int error;
283
284     error = getsockopt_int(sock, SOL_SOCKET, SO_RCVBUF, "SO_RCVBUF", &rcvbuf);
285     return error ? -error : rcvbuf;
286 }
287
288 /* Reads and discards up to 'n' datagrams from 'fd', stopping as soon as no
289  * more data can be immediately read.  ('fd' should therefore be in
290  * non-blocking mode.)*/
291 void
292 drain_fd(int fd, size_t n_packets)
293 {
294     for (; n_packets > 0; n_packets--) {
295         /* 'buffer' only needs to be 1 byte long in most circumstances.  This
296          * size is defensive against the possibility that we someday want to
297          * use a Linux tap device without TUN_NO_PI, in which case a buffer
298          * smaller than sizeof(struct tun_pi) will give EINVAL on read. */
299         char buffer[128];
300         if (read(fd, buffer, sizeof buffer) <= 0) {
301             break;
302         }
303     }
304 }
305
306 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
307  * '*un_len' the size of the sockaddr_un. */
308 static void
309 make_sockaddr_un__(const char *name, struct sockaddr_un *un, socklen_t *un_len)
310 {
311     un->sun_family = AF_UNIX;
312     ovs_strzcpy(un->sun_path, name, sizeof un->sun_path);
313     *un_len = (offsetof(struct sockaddr_un, sun_path)
314                 + strlen (un->sun_path) + 1);
315 }
316
317 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
318  * '*un_len' the size of the sockaddr_un.
319  *
320  * Returns 0 on success, otherwise a positive errno value.  On success,
321  * '*dirfdp' is either -1 or a nonnegative file descriptor that the caller
322  * should close after using '*un' to bind or connect.  On failure, '*dirfdp' is
323  * -1. */
324 static int
325 make_sockaddr_un(const char *name, struct sockaddr_un *un, socklen_t *un_len,
326                  int *dirfdp)
327 {
328     enum { MAX_UN_LEN = sizeof un->sun_path - 1 };
329
330     *dirfdp = -1;
331     if (strlen(name) > MAX_UN_LEN) {
332         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
333
334         if (LINUX) {
335             /* 'name' is too long to fit in a sockaddr_un, but we have a
336              * workaround for that on Linux: shorten it by opening a file
337              * descriptor for the directory part of the name and indirecting
338              * through /proc/self/fd/<dirfd>/<basename>. */
339             char *dir, *base;
340             char *short_name;
341             int dirfd;
342
343             dir = dir_name(name);
344             base = base_name(name);
345
346             dirfd = open(dir, O_DIRECTORY | O_RDONLY);
347             if (dirfd < 0) {
348                 free(base);
349                 free(dir);
350                 return errno;
351             }
352
353             short_name = xasprintf("/proc/self/fd/%d/%s", dirfd, base);
354             free(dir);
355             free(base);
356
357             if (strlen(short_name) <= MAX_UN_LEN) {
358                 make_sockaddr_un__(short_name, un, un_len);
359                 free(short_name);
360                 *dirfdp = dirfd;
361                 return 0;
362             }
363             free(short_name);
364             close(dirfd);
365
366             VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
367                          "%d bytes (even shortened)", name, MAX_UN_LEN);
368         } else {
369             /* 'name' is too long and we have no workaround. */
370             VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
371                          "%d bytes", name, MAX_UN_LEN);
372         }
373
374         return ENAMETOOLONG;
375     } else {
376         make_sockaddr_un__(name, un, un_len);
377         return 0;
378     }
379 }
380
381 /* Binds Unix domain socket 'fd' to a file with permissions 0700. */
382 static int
383 bind_unix_socket(int fd, struct sockaddr *sun, socklen_t sun_len)
384 {
385     /* According to _Unix Network Programming_, umask should affect bind(). */
386     mode_t old_umask = umask(0077);
387     int error = bind(fd, sun, sun_len) ? errno : 0;
388     umask(old_umask);
389     return error;
390 }
391
392 /* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
393  * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
394  * connected to '*connect_path' (if 'connect_path' is non-null).  If 'nonblock'
395  * is true, the socket is made non-blocking.
396  *
397  * Returns the socket's fd if successful, otherwise a negative errno value. */
398 int
399 make_unix_socket(int style, bool nonblock,
400                  const char *bind_path, const char *connect_path)
401 {
402     int error;
403     int fd;
404
405     fd = socket(PF_UNIX, style, 0);
406     if (fd < 0) {
407         return -errno;
408     }
409
410     /* Set nonblocking mode right away, if we want it.  This prevents blocking
411      * in connect(), if connect_path != NULL.  (In turn, that's a corner case:
412      * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
413      * if a backlog of un-accepted connections has built up in the kernel.)  */
414     if (nonblock) {
415         int flags = fcntl(fd, F_GETFL, 0);
416         if (flags == -1) {
417             error = errno;
418             goto error;
419         }
420         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
421             error = errno;
422             goto error;
423         }
424     }
425
426     if (bind_path) {
427         struct sockaddr_un un;
428         socklen_t un_len;
429         int dirfd;
430
431         if (unlink(bind_path) && errno != ENOENT) {
432             VLOG_WARN("unlinking \"%s\": %s\n", bind_path, strerror(errno));
433         }
434         fatal_signal_add_file_to_unlink(bind_path);
435
436         error = make_sockaddr_un(bind_path, &un, &un_len, &dirfd);
437         if (!error) {
438             error = bind_unix_socket(fd, (struct sockaddr *) &un, un_len);
439         }
440         if (dirfd >= 0) {
441             close(dirfd);
442         }
443         if (error) {
444             goto error;
445         }
446     }
447
448     if (connect_path) {
449         struct sockaddr_un un;
450         socklen_t un_len;
451         int dirfd;
452
453         error = make_sockaddr_un(connect_path, &un, &un_len, &dirfd);
454         if (!error
455             && connect(fd, (struct sockaddr*) &un, un_len)
456             && errno != EINPROGRESS) {
457             error = errno;
458         }
459         if (dirfd >= 0) {
460             close(dirfd);
461         }
462         if (error) {
463             goto error;
464         }
465     }
466
467     return fd;
468
469 error:
470     if (error == EAGAIN) {
471         error = EPROTO;
472     }
473     if (bind_path) {
474         fatal_signal_unlink_file_now(bind_path);
475     }
476     close(fd);
477     return -error;
478 }
479
480 int
481 get_unix_name_len(socklen_t sun_len)
482 {
483     return (sun_len >= offsetof(struct sockaddr_un, sun_path)
484             ? sun_len - offsetof(struct sockaddr_un, sun_path)
485             : 0);
486 }
487
488 ovs_be32
489 guess_netmask(ovs_be32 ip_)
490 {
491     uint32_t ip = ntohl(ip_);
492     return ((ip >> 31) == 0 ? htonl(0xff000000)   /* Class A */
493             : (ip >> 30) == 2 ? htonl(0xffff0000) /* Class B */
494             : (ip >> 29) == 6 ? htonl(0xffffff00) /* Class C */
495             : htonl(0));                          /* ??? */
496 }
497
498 /* Parses 'target', which should be a string in the format "<host>[:<port>]".
499  * <host> is required.  If 'default_port' is nonzero then <port> is optional
500  * and defaults to 'default_port'.
501  *
502  * On success, returns true and stores the parsed remote address into '*sinp'.
503  * On failure, logs an error, stores zeros into '*sinp', and returns false. */
504 bool
505 inet_parse_active(const char *target_, uint16_t default_port,
506                   struct sockaddr_in *sinp)
507 {
508     char *target = xstrdup(target_);
509     char *save_ptr = NULL;
510     const char *host_name;
511     const char *port_string;
512     bool ok = false;
513
514     /* Defaults. */
515     sinp->sin_family = AF_INET;
516     sinp->sin_port = htons(default_port);
517
518     /* Tokenize. */
519     host_name = strtok_r(target, ":", &save_ptr);
520     port_string = strtok_r(NULL, ":", &save_ptr);
521     if (!host_name) {
522         VLOG_ERR("%s: bad peer name format", target_);
523         goto exit;
524     }
525
526     /* Look up IP, port. */
527     if (lookup_ip(host_name, &sinp->sin_addr)) {
528         goto exit;
529     }
530     if (port_string && atoi(port_string)) {
531         sinp->sin_port = htons(atoi(port_string));
532     } else if (!default_port) {
533         VLOG_ERR("%s: port number must be specified", target_);
534         goto exit;
535     }
536
537     ok = true;
538
539 exit:
540     if (!ok) {
541         memset(sinp, 0, sizeof *sinp);
542     }
543     free(target);
544     return ok;
545 }
546
547 /* Opens a non-blocking IPv4 socket of the specified 'style' and connects to
548  * 'target', which should be a string in the format "<host>[:<port>]".  <host>
549  * is required.  If 'default_port' is nonzero then <port> is optional and
550  * defaults to 'default_port'.
551  *
552  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
553  *
554  * On success, returns 0 (indicating connection complete) or EAGAIN (indicating
555  * connection in progress), in which case the new file descriptor is stored
556  * into '*fdp'.  On failure, returns a positive errno value other than EAGAIN
557  * and stores -1 into '*fdp'.
558  *
559  * If 'sinp' is non-null, then on success the target address is stored into
560  * '*sinp'.
561  *
562  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
563  * should be in the range [0, 63] and will automatically be shifted to the
564  * appropriately place in the IP tos field. */
565 int
566 inet_open_active(int style, const char *target, uint16_t default_port,
567                  struct sockaddr_in *sinp, int *fdp, uint8_t dscp)
568 {
569     struct sockaddr_in sin;
570     int fd = -1;
571     int error;
572
573     /* Parse. */
574     if (!inet_parse_active(target, default_port, &sin)) {
575         error = EAFNOSUPPORT;
576         goto exit;
577     }
578
579     /* Create non-blocking socket. */
580     fd = socket(AF_INET, style, 0);
581     if (fd < 0) {
582         VLOG_ERR("%s: socket: %s", target, strerror(errno));
583         error = errno;
584         goto exit;
585     }
586     error = set_nonblocking(fd);
587     if (error) {
588         goto exit;
589     }
590
591     /* The dscp bits must be configured before connect() to ensure that the TOS
592      * field is set during the connection establishment.  If set after
593      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
594     error = set_dscp(fd, dscp);
595     if (error) {
596         VLOG_ERR("%s: socket: %s", target, strerror(error));
597         goto exit;
598     }
599
600     /* Connect. */
601     error = connect(fd, (struct sockaddr *) &sin, sizeof sin) == 0 ? 0 : errno;
602     if (error == EINPROGRESS) {
603         error = EAGAIN;
604     }
605
606 exit:
607     if (!error || error == EAGAIN) {
608         if (sinp) {
609             *sinp = sin;
610         }
611     } else if (fd >= 0) {
612         close(fd);
613     }
614     *fdp = fd;
615     return error;
616 }
617
618 /* Parses 'target', which should be a string in the format "[<port>][:<ip>]":
619  *
620  *      - If 'default_port' is -1, then <port> is required.  Otherwise, if
621  *        <port> is omitted, then 'default_port' is used instead.
622  *
623  *      - If <port> (or 'default_port', if used) is 0, then no port is bound
624  *        and the TCP/IP stack will select a port.
625  *
626  *      - If <ip> is omitted then the IP address is wildcarded.
627  *
628  * If successful, stores the address into '*sinp' and returns true; otherwise
629  * zeros '*sinp' and returns false. */
630 bool
631 inet_parse_passive(const char *target_, int default_port,
632                    struct sockaddr_in *sinp)
633 {
634     char *target = xstrdup(target_);
635     char *string_ptr = target;
636     const char *host_name;
637     const char *port_string;
638     bool ok = false;
639     int port;
640
641     /* Address defaults. */
642     memset(sinp, 0, sizeof *sinp);
643     sinp->sin_family = AF_INET;
644     sinp->sin_addr.s_addr = htonl(INADDR_ANY);
645     sinp->sin_port = htons(default_port);
646
647     /* Parse optional port number. */
648     port_string = strsep(&string_ptr, ":");
649     if (port_string && str_to_int(port_string, 10, &port)) {
650         sinp->sin_port = htons(port);
651     } else if (default_port < 0) {
652         VLOG_ERR("%s: port number must be specified", target_);
653         goto exit;
654     }
655
656     /* Parse optional bind IP. */
657     host_name = strsep(&string_ptr, ":");
658     if (host_name && host_name[0] && lookup_ip(host_name, &sinp->sin_addr)) {
659         goto exit;
660     }
661
662     ok = true;
663
664 exit:
665     if (!ok) {
666         memset(sinp, 0, sizeof *sinp);
667     }
668     free(target);
669     return ok;
670 }
671
672
673 /* Opens a non-blocking IPv4 socket of the specified 'style', binds to
674  * 'target', and listens for incoming connections.  Parses 'target' in the same
675  * way was inet_parse_passive().
676  *
677  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
678  *
679  * For TCP, the socket will have SO_REUSEADDR turned on.
680  *
681  * On success, returns a non-negative file descriptor.  On failure, returns a
682  * negative errno value.
683  *
684  * If 'sinp' is non-null, then on success the bound address is stored into
685  * '*sinp'.
686  *
687  * 'dscp' becomes the DSCP bits in the IP headers for the new connection.  It
688  * should be in the range [0, 63] and will automatically be shifted to the
689  * appropriately place in the IP tos field. */
690 int
691 inet_open_passive(int style, const char *target, int default_port,
692                   struct sockaddr_in *sinp, uint8_t dscp)
693 {
694     struct sockaddr_in sin;
695     int fd = 0, error;
696     unsigned int yes = 1;
697
698     if (!inet_parse_passive(target, default_port, &sin)) {
699         return -EAFNOSUPPORT;
700     }
701
702     /* Create non-blocking socket, set SO_REUSEADDR. */
703     fd = socket(AF_INET, style, 0);
704     if (fd < 0) {
705         error = errno;
706         VLOG_ERR("%s: socket: %s", target, strerror(error));
707         return -error;
708     }
709     error = set_nonblocking(fd);
710     if (error) {
711         goto error;
712     }
713     if (style == SOCK_STREAM
714         && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
715         error = errno;
716         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", target, strerror(error));
717         goto error;
718     }
719
720     /* Bind. */
721     if (bind(fd, (struct sockaddr *) &sin, sizeof sin) < 0) {
722         error = errno;
723         VLOG_ERR("%s: bind: %s", target, strerror(error));
724         goto error;
725     }
726
727     /* The dscp bits must be configured before connect() to ensure that the TOS
728      * field is set during the connection establishment.  If set after
729      * connect(), the handshake SYN frames will be sent with a TOS of 0. */
730     error = set_dscp(fd, dscp);
731     if (error) {
732         VLOG_ERR("%s: socket: %s", target, strerror(error));
733         goto error;
734     }
735
736     /* Listen. */
737     if (style == SOCK_STREAM && listen(fd, 10) < 0) {
738         error = errno;
739         VLOG_ERR("%s: listen: %s", target, strerror(error));
740         goto error;
741     }
742
743     if (sinp) {
744         socklen_t sin_len = sizeof sin;
745         if (getsockname(fd, (struct sockaddr *) &sin, &sin_len) < 0){
746             error = errno;
747             VLOG_ERR("%s: getsockname: %s", target, strerror(error));
748             goto error;
749         }
750         if (sin.sin_family != AF_INET || sin_len != sizeof sin) {
751             error = EAFNOSUPPORT;
752             VLOG_ERR("%s: getsockname: invalid socket name", target);
753             goto error;
754         }
755         *sinp = sin;
756     }
757
758     return fd;
759
760 error:
761     close(fd);
762     return -error;
763 }
764
765 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
766  * a negative errno value.  The caller must not close the returned fd (because
767  * the same fd will be handed out to subsequent callers). */
768 int
769 get_null_fd(void)
770 {
771     static int null_fd = -1;
772     if (null_fd < 0) {
773         null_fd = open("/dev/null", O_RDWR);
774         if (null_fd < 0) {
775             int error = errno;
776             VLOG_ERR("could not open /dev/null: %s", strerror(error));
777             return -error;
778         }
779     }
780     return null_fd;
781 }
782
783 int
784 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
785 {
786     uint8_t *p = p_;
787
788     *bytes_read = 0;
789     while (size > 0) {
790         ssize_t retval = read(fd, p, size);
791         if (retval > 0) {
792             *bytes_read += retval;
793             size -= retval;
794             p += retval;
795         } else if (retval == 0) {
796             return EOF;
797         } else if (errno != EINTR) {
798             return errno;
799         }
800     }
801     return 0;
802 }
803
804 int
805 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
806 {
807     const uint8_t *p = p_;
808
809     *bytes_written = 0;
810     while (size > 0) {
811         ssize_t retval = write(fd, p, size);
812         if (retval > 0) {
813             *bytes_written += retval;
814             size -= retval;
815             p += retval;
816         } else if (retval == 0) {
817             VLOG_WARN("write returned 0");
818             return EPROTO;
819         } else if (errno != EINTR) {
820             return errno;
821         }
822     }
823     return 0;
824 }
825
826 /* Given file name 'file_name', fsyncs the directory in which it is contained.
827  * Returns 0 if successful, otherwise a positive errno value. */
828 int
829 fsync_parent_dir(const char *file_name)
830 {
831     int error = 0;
832     char *dir;
833     int fd;
834
835     dir = dir_name(file_name);
836     fd = open(dir, O_RDONLY);
837     if (fd >= 0) {
838         if (fsync(fd)) {
839             if (errno == EINVAL || errno == EROFS) {
840                 /* This directory does not support synchronization.  Not
841                  * really an error. */
842             } else {
843                 error = errno;
844                 VLOG_ERR("%s: fsync failed (%s)", dir, strerror(error));
845             }
846         }
847         close(fd);
848     } else {
849         error = errno;
850         VLOG_ERR("%s: open failed (%s)", dir, strerror(error));
851     }
852     free(dir);
853
854     return error;
855 }
856
857 /* Obtains the modification time of the file named 'file_name' to the greatest
858  * supported precision.  If successful, stores the mtime in '*mtime' and
859  * returns 0.  On error, returns a positive errno value and stores zeros in
860  * '*mtime'. */
861 int
862 get_mtime(const char *file_name, struct timespec *mtime)
863 {
864     struct stat s;
865
866     if (!stat(file_name, &s)) {
867         mtime->tv_sec = s.st_mtime;
868
869 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
870         mtime->tv_nsec = s.st_mtim.tv_nsec;
871 #elif HAVE_STRUCT_STAT_ST_MTIMENSEC
872         mtime->tv_nsec = s.st_mtimensec;
873 #else
874         mtime->tv_nsec = 0;
875 #endif
876
877         return 0;
878     } else {
879         mtime->tv_sec = mtime->tv_nsec = 0;
880         return errno;
881     }
882 }
883
884 void
885 xpipe(int fds[2])
886 {
887     if (pipe(fds)) {
888         VLOG_FATAL("failed to create pipe (%s)", strerror(errno));
889     }
890 }
891
892 static int
893 getsockopt_int(int fd, int level, int option, const char *optname, int *valuep)
894 {
895     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
896     socklen_t len;
897     int value;
898     int error;
899
900     len = sizeof value;
901     if (getsockopt(fd, level, option, &value, &len)) {
902         error = errno;
903         VLOG_ERR_RL(&rl, "getsockopt(%s): %s", optname, strerror(error));
904     } else if (len != sizeof value) {
905         error = EINVAL;
906         VLOG_ERR_RL(&rl, "getsockopt(%s): value is %u bytes (expected %zu)",
907                     optname, (unsigned int) len, sizeof value);
908     } else {
909         error = 0;
910     }
911
912     *valuep = error ? 0 : value;
913     return error;
914 }
915
916 static void
917 describe_sockaddr(struct ds *string, int fd,
918                   int (*getaddr)(int, struct sockaddr *, socklen_t *))
919 {
920     struct sockaddr_storage ss;
921     socklen_t len = sizeof ss;
922
923     if (!getaddr(fd, (struct sockaddr *) &ss, &len)) {
924         if (ss.ss_family == AF_INET) {
925             struct sockaddr_in sin;
926
927             memcpy(&sin, &ss, sizeof sin);
928             ds_put_format(string, IP_FMT":%"PRIu16,
929                           IP_ARGS(&sin.sin_addr.s_addr), ntohs(sin.sin_port));
930         } else if (ss.ss_family == AF_UNIX) {
931             struct sockaddr_un sun;
932             const char *null;
933             size_t maxlen;
934
935             memcpy(&sun, &ss, sizeof sun);
936             maxlen = len - offsetof(struct sockaddr_un, sun_path);
937             null = memchr(sun.sun_path, '\0', maxlen);
938             ds_put_buffer(string, sun.sun_path,
939                           null ? null - sun.sun_path : maxlen);
940         }
941 #ifdef HAVE_NETLINK
942         else if (ss.ss_family == AF_NETLINK) {
943             int protocol;
944
945 /* SO_PROTOCOL was introduced in 2.6.32.  Support it regardless of the version
946  * of the Linux kernel headers in use at build time. */
947 #ifndef SO_PROTOCOL
948 #define SO_PROTOCOL 38
949 #endif
950
951             if (!getsockopt_int(fd, SOL_SOCKET, SO_PROTOCOL, "SO_PROTOCOL",
952                                 &protocol)) {
953                 switch (protocol) {
954                 case NETLINK_ROUTE:
955                     ds_put_cstr(string, "NETLINK_ROUTE");
956                     break;
957
958                 case NETLINK_GENERIC:
959                     ds_put_cstr(string, "NETLINK_GENERIC");
960                     break;
961
962                 default:
963                     ds_put_format(string, "AF_NETLINK family %d", protocol);
964                     break;
965                 }
966             } else {
967                 ds_put_cstr(string, "AF_NETLINK");
968             }
969         }
970 #endif
971 #if AF_PACKET && __linux__
972         else if (ss.ss_family == AF_PACKET) {
973             struct sockaddr_ll sll;
974
975             memcpy(&sll, &ss, sizeof sll);
976             ds_put_cstr(string, "AF_PACKET");
977             if (sll.sll_ifindex) {
978                 char name[IFNAMSIZ];
979
980                 if (if_indextoname(sll.sll_ifindex, name)) {
981                     ds_put_format(string, "(%s)", name);
982                 } else {
983                     ds_put_format(string, "(ifindex=%d)", sll.sll_ifindex);
984                 }
985             }
986             if (sll.sll_protocol) {
987                 ds_put_format(string, "(protocol=0x%"PRIu16")",
988                               ntohs(sll.sll_protocol));
989             }
990         }
991 #endif
992         else if (ss.ss_family == AF_UNSPEC) {
993             ds_put_cstr(string, "AF_UNSPEC");
994         } else {
995             ds_put_format(string, "AF_%d", (int) ss.ss_family);
996         }
997     }
998 }
999
1000
1001 #ifdef __linux__
1002 static void
1003 put_fd_filename(struct ds *string, int fd)
1004 {
1005     char buf[1024];
1006     char *linkname;
1007     int n;
1008
1009     linkname = xasprintf("/proc/self/fd/%d", fd);
1010     n = readlink(linkname, buf, sizeof buf);
1011     if (n > 0) {
1012         ds_put_char(string, ' ');
1013         ds_put_buffer(string, buf, n);
1014         if (n > sizeof buf) {
1015             ds_put_cstr(string, "...");
1016         }
1017     }
1018     free(linkname);
1019 }
1020 #endif
1021
1022 /* Returns a malloc()'d string describing 'fd', for use in logging. */
1023 char *
1024 describe_fd(int fd)
1025 {
1026     struct ds string;
1027     struct stat s;
1028
1029     ds_init(&string);
1030     if (fstat(fd, &s)) {
1031         ds_put_format(&string, "fstat failed (%s)", strerror(errno));
1032     } else if (S_ISSOCK(s.st_mode)) {
1033         describe_sockaddr(&string, fd, getsockname);
1034         ds_put_cstr(&string, "<->");
1035         describe_sockaddr(&string, fd, getpeername);
1036     } else {
1037         ds_put_cstr(&string, (isatty(fd) ? "tty"
1038                               : S_ISDIR(s.st_mode) ? "directory"
1039                               : S_ISCHR(s.st_mode) ? "character device"
1040                               : S_ISBLK(s.st_mode) ? "block device"
1041                               : S_ISREG(s.st_mode) ? "file"
1042                               : S_ISFIFO(s.st_mode) ? "FIFO"
1043                               : S_ISLNK(s.st_mode) ? "symbolic link"
1044                               : "unknown"));
1045 #ifdef __linux__
1046         put_fd_filename(&string, fd);
1047 #endif
1048     }
1049     return ds_steal_cstr(&string);
1050 }