socket-util: Define LINUX macro at top of file.
[sliver-openvswitch.git] / lib / socket-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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 <netdb.h>
23 #include <poll.h>
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/resource.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 #include <sys/un.h>
32 #include <unistd.h>
33 #include "fatal-signal.h"
34 #include "util.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(socket_util);
38
39 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
40  * Thus, this file compiles all of the code regardless of the target, by
41  * writing "if (LINUX)" instead of "#ifdef __linux__". */
42 #ifdef __linux__
43 #define LINUX 1
44 #else
45 #define LINUX 0
46 #endif
47
48 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
49  * positive errno value. */
50 int
51 set_nonblocking(int fd)
52 {
53     int flags = fcntl(fd, F_GETFL, 0);
54     if (flags != -1) {
55         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
56             return 0;
57         } else {
58             VLOG_ERR("fcntl(F_SETFL) failed: %s", strerror(errno));
59             return errno;
60         }
61     } else {
62         VLOG_ERR("fcntl(F_GETFL) failed: %s", strerror(errno));
63         return errno;
64     }
65 }
66
67 static bool
68 rlim_is_finite(rlim_t limit)
69 {
70     if (limit == RLIM_INFINITY) {
71         return false;
72     }
73
74 #ifdef RLIM_SAVED_CUR           /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
75     if (limit == RLIM_SAVED_CUR) {
76         return false;
77     }
78 #endif
79
80 #ifdef RLIM_SAVED_MAX           /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
81     if (limit == RLIM_SAVED_MAX) {
82         return false;
83     }
84 #endif
85
86     return true;
87 }
88
89 /* Returns the maximum valid FD value, plus 1. */
90 int
91 get_max_fds(void)
92 {
93     static int max_fds = -1;
94     if (max_fds < 0) {
95         struct rlimit r;
96         if (!getrlimit(RLIMIT_NOFILE, &r) && rlim_is_finite(r.rlim_cur)) {
97             max_fds = r.rlim_cur;
98         } else {
99             VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
100             max_fds = 1024;
101         }
102     }
103     return max_fds;
104 }
105
106 /* Translates 'host_name', which must be a string representation of an IP
107  * address, into a numeric IP address in '*addr'.  Returns 0 if successful,
108  * otherwise a positive errno value. */
109 int
110 lookup_ip(const char *host_name, struct in_addr *addr)
111 {
112     if (!inet_aton(host_name, addr)) {
113         struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
114         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IP address", host_name);
115         return ENOENT;
116     }
117     return 0;
118 }
119
120 /* Returns the error condition associated with socket 'fd' and resets the
121  * socket's error status. */
122 int
123 get_socket_error(int fd)
124 {
125     int error;
126     socklen_t len = sizeof(error);
127     if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
128         struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
129         error = errno;
130         VLOG_ERR_RL(&rl, "getsockopt(SO_ERROR): %s", strerror(error));
131     }
132     return error;
133 }
134
135 int
136 check_connection_completion(int fd)
137 {
138     struct pollfd pfd;
139     int retval;
140
141     pfd.fd = fd;
142     pfd.events = POLLOUT;
143     do {
144         retval = poll(&pfd, 1, 0);
145     } while (retval < 0 && errno == EINTR);
146     if (retval == 1) {
147         return get_socket_error(fd);
148     } else if (retval < 0) {
149         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
150         VLOG_ERR_RL(&rl, "poll: %s", strerror(errno));
151         return errno;
152     } else {
153         return EAGAIN;
154     }
155 }
156
157 /* Drain all the data currently in the receive queue of a datagram socket (and
158  * possibly additional data).  There is no way to know how many packets are in
159  * the receive queue, but we do know that the total number of bytes queued does
160  * not exceed the receive buffer size, so we pull packets until none are left
161  * or we've read that many bytes. */
162 int
163 drain_rcvbuf(int fd)
164 {
165     socklen_t rcvbuf_len;
166     size_t rcvbuf;
167
168     rcvbuf_len = sizeof rcvbuf;
169     if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
170         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
171         VLOG_ERR_RL(&rl, "getsockopt(SO_RCVBUF) failed: %s", strerror(errno));
172         return errno;
173     }
174     while (rcvbuf > 0) {
175         /* In Linux, specifying MSG_TRUNC in the flags argument causes the
176          * datagram length to be returned, even if that is longer than the
177          * buffer provided.  Thus, we can use a 1-byte buffer to discard the
178          * incoming datagram and still be able to account how many bytes were
179          * removed from the receive buffer.
180          *
181          * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
182          * argument. */
183         char buffer[LINUX ? 1 : 2048];
184         ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
185                                MSG_TRUNC | MSG_DONTWAIT);
186         if (n_bytes <= 0 || n_bytes >= rcvbuf) {
187             break;
188         }
189         rcvbuf -= n_bytes;
190     }
191     return 0;
192 }
193
194 /* Reads and discards up to 'n' datagrams from 'fd', stopping as soon as no
195  * more data can be immediately read.  ('fd' should therefore be in
196  * non-blocking mode.)*/
197 void
198 drain_fd(int fd, size_t n_packets)
199 {
200     for (; n_packets > 0; n_packets--) {
201         /* 'buffer' only needs to be 1 byte long in most circumstances.  This
202          * size is defensive against the possibility that we someday want to
203          * use a Linux tap device without TUN_NO_PI, in which case a buffer
204          * smaller than sizeof(struct tun_pi) will give EINVAL on read. */
205         char buffer[128];
206         if (read(fd, buffer, sizeof buffer) <= 0) {
207             break;
208         }
209     }
210 }
211
212 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
213  * '*un_len' the size of the sockaddr_un. */
214 static void
215 make_sockaddr_un(const char *name, struct sockaddr_un* un, socklen_t *un_len)
216 {
217     un->sun_family = AF_UNIX;
218     strncpy(un->sun_path, name, sizeof un->sun_path);
219     un->sun_path[sizeof un->sun_path - 1] = '\0';
220     *un_len = (offsetof(struct sockaddr_un, sun_path)
221                 + strlen (un->sun_path) + 1);
222 }
223
224 /* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
225  * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
226  * connected to '*connect_path' (if 'connect_path' is non-null).  If 'nonblock'
227  * is true, the socket is made non-blocking.  If 'passcred' is true, the socket
228  * is configured to receive SCM_CREDENTIALS control messages.
229  *
230  * Returns the socket's fd if successful, otherwise a negative errno value. */
231 int
232 make_unix_socket(int style, bool nonblock, bool passcred OVS_UNUSED,
233                  const char *bind_path, const char *connect_path)
234 {
235     int error;
236     int fd;
237
238     fd = socket(PF_UNIX, style, 0);
239     if (fd < 0) {
240         return -errno;
241     }
242
243     /* Set nonblocking mode right away, if we want it.  This prevents blocking
244      * in connect(), if connect_path != NULL.  (In turn, that's a corner case:
245      * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
246      * if a backlog of un-accepted connections has built up in the kernel.)  */
247     if (nonblock) {
248         int flags = fcntl(fd, F_GETFL, 0);
249         if (flags == -1) {
250             goto error;
251         }
252         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
253             goto error;
254         }
255     }
256
257     if (bind_path) {
258         struct sockaddr_un un;
259         socklen_t un_len;
260         make_sockaddr_un(bind_path, &un, &un_len);
261         if (unlink(un.sun_path) && errno != ENOENT) {
262             VLOG_WARN("unlinking \"%s\": %s\n", un.sun_path, strerror(errno));
263         }
264         fatal_signal_add_file_to_unlink(bind_path);
265         if (bind(fd, (struct sockaddr*) &un, un_len)
266             || fchmod(fd, S_IRWXU)) {
267             goto error;
268         }
269     }
270
271     if (connect_path) {
272         struct sockaddr_un un;
273         socklen_t un_len;
274         make_sockaddr_un(connect_path, &un, &un_len);
275         if (connect(fd, (struct sockaddr*) &un, un_len)
276             && errno != EINPROGRESS) {
277             goto error;
278         }
279     }
280
281 #ifdef SCM_CREDENTIALS
282     if (passcred) {
283         int enable = 1;
284         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable))) {
285             goto error;
286         }
287     }
288 #endif
289
290     return fd;
291
292 error:
293     error = errno == EAGAIN ? EPROTO : errno;
294     if (bind_path) {
295         fatal_signal_remove_file_to_unlink(bind_path);
296     }
297     close(fd);
298     return -error;
299 }
300
301 int
302 get_unix_name_len(socklen_t sun_len)
303 {
304     return (sun_len >= offsetof(struct sockaddr_un, sun_path)
305             ? sun_len - offsetof(struct sockaddr_un, sun_path)
306             : 0);
307 }
308
309 uint32_t
310 guess_netmask(uint32_t ip)
311 {
312     ip = ntohl(ip);
313     return ((ip >> 31) == 0 ? htonl(0xff000000)   /* Class A */
314             : (ip >> 30) == 2 ? htonl(0xffff0000) /* Class B */
315             : (ip >> 29) == 6 ? htonl(0xffffff00) /* Class C */
316             : htonl(0));                          /* ??? */
317 }
318
319 /* Parses 'target', which should be a string in the format "<host>[:<port>]".
320  * <host> is required.  If 'default_port' is nonzero then <port> is optional
321  * and defaults to 'default_port'.
322  *
323  * On success, returns true and stores the parsed remote address into '*sinp'.
324  * On failure, logs an error, stores zeros into '*sinp', and returns false. */
325 bool
326 inet_parse_active(const char *target_, uint16_t default_port,
327                   struct sockaddr_in *sinp)
328 {
329     char *target = xstrdup(target_);
330     char *save_ptr = NULL;
331     const char *host_name;
332     const char *port_string;
333     bool ok = false;
334
335     /* Defaults. */
336     sinp->sin_family = AF_INET;
337     sinp->sin_port = htons(default_port);
338
339     /* Tokenize. */
340     host_name = strtok_r(target, ":", &save_ptr);
341     port_string = strtok_r(NULL, ":", &save_ptr);
342     if (!host_name) {
343         VLOG_ERR("%s: bad peer name format", target_);
344         goto exit;
345     }
346
347     /* Look up IP, port. */
348     if (lookup_ip(host_name, &sinp->sin_addr)) {
349         goto exit;
350     }
351     if (port_string && atoi(port_string)) {
352         sinp->sin_port = htons(atoi(port_string));
353     } else if (!default_port) {
354         VLOG_ERR("%s: port number must be specified", target_);
355         goto exit;
356     }
357
358     ok = true;
359
360 exit:
361     if (!ok) {
362         memset(sinp, 0, sizeof *sinp);
363     }
364     free(target);
365     return ok;
366 }
367
368 /* Opens a non-blocking IPv4 socket of the specified 'style' and connects to
369  * 'target', which should be a string in the format "<host>[:<port>]".  <host>
370  * is required.  If 'default_port' is nonzero then <port> is optional and
371  * defaults to 'default_port'.
372  *
373  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
374  *
375  * On success, returns 0 (indicating connection complete) or EAGAIN (indicating
376  * connection in progress), in which case the new file descriptor is stored
377  * into '*fdp'.  On failure, returns a positive errno value other than EAGAIN
378  * and stores -1 into '*fdp'.
379  *
380  * If 'sinp' is non-null, then on success the target address is stored into
381  * '*sinp'. */
382 int
383 inet_open_active(int style, const char *target, uint16_t default_port,
384                  struct sockaddr_in *sinp, int *fdp)
385 {
386     struct sockaddr_in sin;
387     int fd = -1;
388     int error;
389
390     /* Parse. */
391     if (!inet_parse_active(target, default_port, &sin)) {
392         error = EAFNOSUPPORT;
393         goto exit;
394     }
395
396     /* Create non-blocking socket. */
397     fd = socket(AF_INET, style, 0);
398     if (fd < 0) {
399         VLOG_ERR("%s: socket: %s", target, strerror(errno));
400         error = errno;
401         goto exit;
402     }
403     error = set_nonblocking(fd);
404     if (error) {
405         goto exit_close;
406     }
407
408     /* Connect. */
409     error = connect(fd, (struct sockaddr *) &sin, sizeof sin) == 0 ? 0 : errno;
410     if (error == EINPROGRESS) {
411         error = EAGAIN;
412     } else if (error && error != EAGAIN) {
413         goto exit_close;
414     }
415
416     /* Success: error is 0 or EAGAIN. */
417     goto exit;
418
419 exit_close:
420     close(fd);
421 exit:
422     if (!error || error == EAGAIN) {
423         if (sinp) {
424             *sinp = sin;
425         }
426         *fdp = fd;
427     } else {
428         *fdp = -1;
429     }
430     return error;
431 }
432
433 /* Opens a non-blocking IPv4 socket of the specified 'style', binds to
434  * 'target', and listens for incoming connections.  'target' should be a string
435  * in the format "[<port>][:<ip>]":
436  *
437  *      - If 'default_port' is -1, then <port> is required.  Otherwise, if
438  *        <port> is omitted, then 'default_port' is used instead.
439  *
440  *      - If <port> (or 'default_port', if used) is 0, then no port is bound
441  *        and the TCP/IP stack will select a port.
442  *
443  *      - If <ip> is omitted then the IP address is wildcarded.
444  *
445  * 'style' should be SOCK_STREAM (for TCP) or SOCK_DGRAM (for UDP).
446  *
447  * For TCP, the socket will have SO_REUSEADDR turned on.
448  *
449  * On success, returns a non-negative file descriptor.  On failure, returns a
450  * negative errno value.
451  *
452  * If 'sinp' is non-null, then on success the bound address is stored into
453  * '*sinp'. */
454 int
455 inet_open_passive(int style, const char *target_, int default_port,
456                   struct sockaddr_in *sinp)
457 {
458     char *target = xstrdup(target_);
459     char *string_ptr = target;
460     struct sockaddr_in sin;
461     const char *host_name;
462     const char *port_string;
463     int fd = 0, error, port;
464     unsigned int yes  = 1;
465
466     /* Address defaults. */
467     memset(&sin, 0, sizeof sin);
468     sin.sin_family = AF_INET;
469     sin.sin_addr.s_addr = htonl(INADDR_ANY);
470     sin.sin_port = htons(default_port);
471
472     /* Parse optional port number. */
473     port_string = strsep(&string_ptr, ":");
474     if (port_string && str_to_int(port_string, 10, &port)) {
475         sin.sin_port = htons(port);
476     } else if (default_port < 0) {
477         VLOG_ERR("%s: port number must be specified", target_);
478         error = EAFNOSUPPORT;
479         goto exit;
480     }
481
482     /* Parse optional bind IP. */
483     host_name = strsep(&string_ptr, ":");
484     if (host_name && host_name[0]) {
485         error = lookup_ip(host_name, &sin.sin_addr);
486         if (error) {
487             goto exit;
488         }
489     }
490
491     /* Create non-blocking socket, set SO_REUSEADDR. */
492     fd = socket(AF_INET, style, 0);
493     if (fd < 0) {
494         error = errno;
495         VLOG_ERR("%s: socket: %s", target_, strerror(error));
496         goto exit;
497     }
498     error = set_nonblocking(fd);
499     if (error) {
500         goto exit_close;
501     }
502     if (style == SOCK_STREAM
503         && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
504         error = errno;
505         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", target_, strerror(error));
506         goto exit_close;
507     }
508
509     /* Bind. */
510     if (bind(fd, (struct sockaddr *) &sin, sizeof sin) < 0) {
511         error = errno;
512         VLOG_ERR("%s: bind: %s", target_, strerror(error));
513         goto exit_close;
514     }
515
516     /* Listen. */
517     if (listen(fd, 10) < 0) {
518         error = errno;
519         VLOG_ERR("%s: listen: %s", target_, strerror(error));
520         goto exit_close;
521     }
522
523     if (sinp) {
524         socklen_t sin_len = sizeof sin;
525         if (getsockname(fd, (struct sockaddr *) &sin, &sin_len) < 0){
526             error = errno;
527             VLOG_ERR("%s: getsockname: %s", target_, strerror(error));
528             goto exit_close;
529         }
530         if (sin.sin_family != AF_INET || sin_len != sizeof sin) {
531             VLOG_ERR("%s: getsockname: invalid socket name", target_);
532             goto exit_close;
533         }
534         *sinp = sin;
535     }
536
537     error = 0;
538     goto exit;
539
540 exit_close:
541     close(fd);
542 exit:
543     free(target);
544     return error ? -error : fd;
545 }
546
547 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
548  * a negative errno value.  The caller must not close the returned fd (because
549  * the same fd will be handed out to subsequent callers). */
550 int
551 get_null_fd(void)
552 {
553     static int null_fd = -1;
554     if (null_fd < 0) {
555         null_fd = open("/dev/null", O_RDWR);
556         if (null_fd < 0) {
557             int error = errno;
558             VLOG_ERR("could not open /dev/null: %s", strerror(error));
559             return -error;
560         }
561     }
562     return null_fd;
563 }
564
565 int
566 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
567 {
568     uint8_t *p = p_;
569
570     *bytes_read = 0;
571     while (size > 0) {
572         ssize_t retval = read(fd, p, size);
573         if (retval > 0) {
574             *bytes_read += retval;
575             size -= retval;
576             p += retval;
577         } else if (retval == 0) {
578             return EOF;
579         } else if (errno != EINTR) {
580             return errno;
581         }
582     }
583     return 0;
584 }
585
586 int
587 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
588 {
589     const uint8_t *p = p_;
590
591     *bytes_written = 0;
592     while (size > 0) {
593         ssize_t retval = write(fd, p, size);
594         if (retval > 0) {
595             *bytes_written += retval;
596             size -= retval;
597             p += retval;
598         } else if (retval == 0) {
599             VLOG_WARN("write returned 0");
600             return EPROTO;
601         } else if (errno != EINTR) {
602             return errno;
603         }
604     }
605     return 0;
606 }
607
608 /* Given file name 'file_name', fsyncs the directory in which it is contained.
609  * Returns 0 if successful, otherwise a positive errno value. */
610 int
611 fsync_parent_dir(const char *file_name)
612 {
613     int error = 0;
614     char *dir;
615     int fd;
616
617     dir = dir_name(file_name);
618     fd = open(dir, O_RDONLY);
619     if (fd >= 0) {
620         if (fsync(fd)) {
621             if (errno == EINVAL || errno == EROFS) {
622                 /* This directory does not support synchronization.  Not
623                  * really an error. */
624             } else {
625                 error = errno;
626                 VLOG_ERR("%s: fsync failed (%s)", dir, strerror(error));
627             }
628         }
629         close(fd);
630     } else {
631         error = errno;
632         VLOG_ERR("%s: open failed (%s)", dir, strerror(error));
633     }
634     free(dir);
635
636     return error;
637 }
638
639 /* Obtains the modification time of the file named 'file_name' to the greatest
640  * supported precision.  If successful, stores the mtime in '*mtime' and
641  * returns 0.  On error, returns a positive errno value and stores zeros in
642  * '*mtime'. */
643 int
644 get_mtime(const char *file_name, struct timespec *mtime)
645 {
646     struct stat s;
647
648     if (!stat(file_name, &s)) {
649         mtime->tv_sec = s.st_mtime;
650
651 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
652         mtime->tv_nsec = s.st_mtim.tv_nsec;
653 #elif HAVE_STRUCT_STAT_ST_MTIMENSEC
654         mtime->tv_nsec = s.st_mtimensec;
655 #else
656         mtime->tv_nsec = 0;
657 #endif
658
659         return 0;
660     } else {
661         mtime->tv_sec = mtime->tv_nsec = 0;
662         return errno;
663     }
664 }
665