Do not try to resolve DNS for OpenFlow controllers or netflow collectors.
[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 <string.h>
27 #include <sys/resource.h>
28 #include <sys/un.h>
29 #include <unistd.h>
30 #include "fatal-signal.h"
31 #include "util.h"
32
33 #include "vlog.h"
34 #define THIS_MODULE VLM_socket_util
35
36 /* Sets 'fd' to non-blocking mode.  Returns 0 if successful, otherwise a
37  * positive errno value. */
38 int
39 set_nonblocking(int fd)
40 {
41     int flags = fcntl(fd, F_GETFL, 0);
42     if (flags != -1) {
43         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
44             return 0;
45         } else {
46             VLOG_ERR("fcntl(F_SETFL) failed: %s", strerror(errno));
47             return errno;
48         }
49     } else {
50         VLOG_ERR("fcntl(F_GETFL) failed: %s", strerror(errno));
51         return errno;
52     }
53 }
54
55 /* Returns the maximum valid FD value, plus 1. */
56 int
57 get_max_fds(void)
58 {
59     static int max_fds = -1;
60     if (max_fds < 0) {
61         struct rlimit r;
62         if (!getrlimit(RLIMIT_NOFILE, &r)
63             && r.rlim_cur != RLIM_INFINITY
64             && r.rlim_cur != RLIM_SAVED_MAX
65             && r.rlim_cur != RLIM_SAVED_CUR) {
66             max_fds = r.rlim_cur;
67         } else {
68             VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
69             max_fds = 1024;
70         }
71     }
72     return max_fds;
73 }
74
75 /* Translates 'host_name', which must be a string representation of an IP
76  * address, into a numeric IP address in '*addr'.  Returns 0 if successful,
77  * otherwise a positive errno value. */
78 int
79 lookup_ip(const char *host_name, struct in_addr *addr) 
80 {
81     if (!inet_aton(host_name, addr)) {
82         struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
83         VLOG_ERR_RL(&rl, "\"%s\" is not a valid IP address", host_name);
84         return ENOENT;
85     }
86     return 0;
87 }
88
89 /* Returns the error condition associated with socket 'fd' and resets the
90  * socket's error status. */
91 int
92 get_socket_error(int fd) 
93 {
94     int error;
95     socklen_t len = sizeof(error);
96     if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
97         struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
98         error = errno;
99         VLOG_ERR_RL(&rl, "getsockopt(SO_ERROR): %s", strerror(error));
100     }
101     return error;
102 }
103
104 int
105 check_connection_completion(int fd) 
106 {
107     struct pollfd pfd;
108     int retval;
109
110     pfd.fd = fd;
111     pfd.events = POLLOUT;
112     do {
113         retval = poll(&pfd, 1, 0);
114     } while (retval < 0 && errno == EINTR);
115     if (retval == 1) {
116         return get_socket_error(fd);
117     } else if (retval < 0) {
118         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
119         VLOG_ERR_RL(&rl, "poll: %s", strerror(errno));
120         return errno;
121     } else {
122         return EAGAIN;
123     }
124 }
125
126 /* Drain all the data currently in the receive queue of a datagram socket (and
127  * possibly additional data).  There is no way to know how many packets are in
128  * the receive queue, but we do know that the total number of bytes queued does
129  * not exceed the receive buffer size, so we pull packets until none are left
130  * or we've read that many bytes. */
131 int
132 drain_rcvbuf(int fd)
133 {
134     socklen_t rcvbuf_len;
135     size_t rcvbuf;
136
137     rcvbuf_len = sizeof rcvbuf;
138     if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
139         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 10);
140         VLOG_ERR_RL(&rl, "getsockopt(SO_RCVBUF) failed: %s", strerror(errno));
141         return errno;
142     }
143     while (rcvbuf > 0) {
144         /* In Linux, specifying MSG_TRUNC in the flags argument causes the
145          * datagram length to be returned, even if that is longer than the
146          * buffer provided.  Thus, we can use a 1-byte buffer to discard the
147          * incoming datagram and still be able to account how many bytes were
148          * removed from the receive buffer.
149          *
150          * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
151          * argument. */
152 #ifdef __linux__
153 #define BUFFER_SIZE 1
154 #else
155 #define BUFFER_SIZE 2048
156 #endif
157         char buffer[BUFFER_SIZE];
158         ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
159                                MSG_TRUNC | MSG_DONTWAIT);
160         if (n_bytes <= 0 || n_bytes >= rcvbuf) {
161             break;
162         }
163         rcvbuf -= n_bytes;
164     }
165     return 0;
166 }
167
168 /* Reads and discards up to 'n' datagrams from 'fd', stopping as soon as no
169  * more data can be immediately read.  ('fd' should therefore be in
170  * non-blocking mode.)*/
171 void
172 drain_fd(int fd, size_t n_packets)
173 {
174     for (; n_packets > 0; n_packets--) {
175         /* 'buffer' only needs to be 1 byte long in most circumstances.  This
176          * size is defensive against the possibility that we someday want to
177          * use a Linux tap device without TUN_NO_PI, in which case a buffer
178          * smaller than sizeof(struct tun_pi) will give EINVAL on read. */
179         char buffer[128];
180         if (read(fd, buffer, sizeof buffer) <= 0) {
181             break;
182         }
183     }
184 }
185
186 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
187  * '*un_len' the size of the sockaddr_un. */
188 static void
189 make_sockaddr_un(const char *name, struct sockaddr_un* un, socklen_t *un_len)
190 {
191     un->sun_family = AF_UNIX;
192     strncpy(un->sun_path, name, sizeof un->sun_path);
193     un->sun_path[sizeof un->sun_path - 1] = '\0';
194     *un_len = (offsetof(struct sockaddr_un, sun_path)
195                 + strlen (un->sun_path) + 1);
196 }
197
198 /* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
199  * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
200  * connected to '*connect_path' (if 'connect_path' is non-null).  If 'nonblock'
201  * is true, the socket is made non-blocking.  If 'passcred' is true, the socket
202  * is configured to receive SCM_CREDENTIALS control messages.
203  *
204  * Returns the socket's fd if successful, otherwise a negative errno value. */
205 int
206 make_unix_socket(int style, bool nonblock, bool passcred UNUSED,
207                  const char *bind_path, const char *connect_path)
208 {
209     int error;
210     int fd;
211
212     fd = socket(PF_UNIX, style, 0);
213     if (fd < 0) {
214         return -errno;
215     }
216
217     /* Set nonblocking mode right away, if we want it.  This prevents blocking
218      * in connect(), if connect_path != NULL.  (In turn, that's a corner case:
219      * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
220      * if a backlog of un-accepted connections has built up in the kernel.)  */
221     if (nonblock) {
222         int flags = fcntl(fd, F_GETFL, 0);
223         if (flags == -1) {
224             goto error;
225         }
226         if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
227             goto error;
228         }
229     }
230
231     if (bind_path) {
232         struct sockaddr_un un;
233         socklen_t un_len;
234         make_sockaddr_un(bind_path, &un, &un_len);
235         if (unlink(un.sun_path) && errno != ENOENT) {
236             VLOG_WARN("unlinking \"%s\": %s\n", un.sun_path, strerror(errno));
237         }
238         fatal_signal_add_file_to_unlink(bind_path);
239         if (bind(fd, (struct sockaddr*) &un, un_len)
240             || fchmod(fd, S_IRWXU)) {
241             goto error;
242         }
243     }
244
245     if (connect_path) {
246         struct sockaddr_un un;
247         socklen_t un_len;
248         make_sockaddr_un(connect_path, &un, &un_len);
249         if (connect(fd, (struct sockaddr*) &un, un_len)
250             && errno != EINPROGRESS) {
251             goto error;
252         }
253     }
254
255 #ifdef SCM_CREDENTIALS
256     if (passcred) {
257         int enable = 1;
258         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable))) {
259             goto error;
260         }
261     }
262 #endif
263
264     return fd;
265
266 error:
267     if (bind_path) {
268         fatal_signal_remove_file_to_unlink(bind_path);
269     }
270     error = errno;
271     close(fd);
272     return -error;
273 }
274
275 int
276 get_unix_name_len(socklen_t sun_len)
277 {
278     return (sun_len >= offsetof(struct sockaddr_un, sun_path)
279             ? sun_len - offsetof(struct sockaddr_un, sun_path)
280             : 0);
281 }
282
283 uint32_t
284 guess_netmask(uint32_t ip)
285 {
286     ip = ntohl(ip);
287     return ((ip >> 31) == 0 ? htonl(0xff000000)   /* Class A */
288             : (ip >> 30) == 2 ? htonl(0xffff0000) /* Class B */
289             : (ip >> 29) == 6 ? htonl(0xffffff00) /* Class C */
290             : htonl(0));                          /* ??? */
291 }
292
293 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
294  * a negative errno value.  The caller must not close the returned fd (because
295  * the same fd will be handed out to subsequent callers). */
296 int
297 get_null_fd(void)
298 {
299     static int null_fd = -1;
300     if (null_fd < 0) {
301         null_fd = open("/dev/null", O_RDWR);
302         if (null_fd < 0) {
303             int error = errno;
304             VLOG_ERR("could not open /dev/null: %s", strerror(error));
305             return -error;
306         }
307     }
308     return null_fd;
309 }
310
311 int
312 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
313 {
314     uint8_t *p = p_;
315
316     *bytes_read = 0;
317     while (size > 0) {
318         ssize_t retval = read(fd, p, size);
319         if (retval > 0) {
320             *bytes_read += retval;
321             size -= retval;
322             p += retval;
323         } else if (retval == 0) {
324             return EOF;
325         } else if (errno != EINTR) {
326             return errno;
327         }
328     }
329     return 0;
330 }
331
332 int
333 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
334 {
335     const uint8_t *p = p_;
336
337     *bytes_written = 0;
338     while (size > 0) {
339         ssize_t retval = write(fd, p, size);
340         if (retval > 0) {
341             *bytes_written += retval;
342             size -= retval;
343             p += retval;
344         } else if (retval == 0) {
345             VLOG_WARN("write returned 0");
346             return EPROTO;
347         } else if (errno != EINTR) {
348             return errno;
349         }
350     }
351     return 0;
352 }