2 * Copyright (c) 2008, 2009 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "socket-util.h"
19 #include <arpa/inet.h>
27 #include <sys/resource.h>
30 #include "fatal-signal.h"
34 #define THIS_MODULE VLM_socket_util
36 /* Sets 'fd' to non-blocking mode. Returns 0 if successful, otherwise a
37 * positive errno value. */
39 set_nonblocking(int fd)
41 int flags = fcntl(fd, F_GETFL, 0);
43 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1) {
46 VLOG_ERR("fcntl(F_SETFL) failed: %s", strerror(errno));
50 VLOG_ERR("fcntl(F_GETFL) failed: %s", strerror(errno));
55 /* Returns the maximum valid FD value, plus 1. */
59 static int max_fds = -1;
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) {
68 VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
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. */
79 lookup_ip(const char *host_name, struct in_addr *addr)
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);
89 /* Returns the error condition associated with socket 'fd' and resets the
90 * socket's error status. */
92 get_socket_error(int fd)
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);
99 VLOG_ERR_RL(&rl, "getsockopt(SO_ERROR): %s", strerror(error));
105 check_connection_completion(int fd)
111 pfd.events = POLLOUT;
113 retval = poll(&pfd, 1, 0);
114 } while (retval < 0 && errno == EINTR);
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));
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. */
134 socklen_t rcvbuf_len;
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));
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.
150 * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
153 #define BUFFER_SIZE 1
155 #define BUFFER_SIZE 2048
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) {
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.)*/
172 drain_fd(int fd, size_t n_packets)
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. */
180 if (read(fd, buffer, sizeof buffer) <= 0) {
186 /* Stores in '*un' a sockaddr_un that refers to file 'name'. Stores in
187 * '*un_len' the size of the sockaddr_un. */
189 make_sockaddr_un(const char *name, struct sockaddr_un* un, socklen_t *un_len)
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);
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.
204 * Returns the socket's fd if successful, otherwise a negative errno value. */
206 make_unix_socket(int style, bool nonblock, bool passcred UNUSED,
207 const char *bind_path, const char *connect_path)
212 fd = socket(PF_UNIX, style, 0);
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.) */
222 int flags = fcntl(fd, F_GETFL, 0);
226 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
232 struct sockaddr_un un;
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));
238 fatal_signal_add_file_to_unlink(bind_path);
239 if (bind(fd, (struct sockaddr*) &un, un_len)
240 || fchmod(fd, S_IRWXU)) {
246 struct sockaddr_un un;
248 make_sockaddr_un(connect_path, &un, &un_len);
249 if (connect(fd, (struct sockaddr*) &un, un_len)
250 && errno != EINPROGRESS) {
255 #ifdef SCM_CREDENTIALS
258 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable))) {
268 fatal_signal_remove_file_to_unlink(bind_path);
276 get_unix_name_len(socklen_t sun_len)
278 return (sun_len >= offsetof(struct sockaddr_un, sun_path)
279 ? sun_len - offsetof(struct sockaddr_un, sun_path)
284 guess_netmask(uint32_t 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)); /* ??? */
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). */
299 static int null_fd = -1;
301 null_fd = open("/dev/null", O_RDWR);
304 VLOG_ERR("could not open /dev/null: %s", strerror(error));
312 read_fully(int fd, void *p_, size_t size, size_t *bytes_read)
318 ssize_t retval = read(fd, p, size);
320 *bytes_read += retval;
323 } else if (retval == 0) {
325 } else if (errno != EINTR) {
333 write_fully(int fd, const void *p_, size_t size, size_t *bytes_written)
335 const uint8_t *p = p_;
339 ssize_t retval = write(fd, p, size);
341 *bytes_written += retval;
344 } else if (retval == 0) {
345 VLOG_WARN("write returned 0");
347 } else if (errno != EINTR) {