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