2 * Copyright (c) 2014 Nicira, Inc.
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"
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
27 #include "fatal-signal.h"
32 VLOG_DEFINE_THIS_MODULE(socket_util_unix);
34 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
35 * Thus, this file compiles all of the code regardless of the target, by
36 * writing "if (LINUX)" instead of "#ifdef __linux__". */
47 /* Maximum length of the sun_path member in a struct sockaddr_un, excluding
48 * space for a null terminator. */
49 #define MAX_UN_LEN (sizeof(((struct sockaddr_un *) 0)->sun_path) - 1)
55 VLOG_FATAL("failed to create pipe (%s)", ovs_strerror(errno));
60 xpipe_nonblocking(int fds[2])
63 xset_nonblocking(fds[0]);
64 xset_nonblocking(fds[1]);
67 /* Drain all the data currently in the receive queue of a datagram socket (and
68 * possibly additional data). There is no way to know how many packets are in
69 * the receive queue, but we do know that the total number of bytes queued does
70 * not exceed the receive buffer size, so we pull packets until none are left
71 * or we've read that many bytes. */
77 rcvbuf = get_socket_rcvbuf(fd);
83 /* In Linux, specifying MSG_TRUNC in the flags argument causes the
84 * datagram length to be returned, even if that is longer than the
85 * buffer provided. Thus, we can use a 1-byte buffer to discard the
86 * incoming datagram and still be able to account how many bytes were
87 * removed from the receive buffer.
89 * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
91 char buffer[LINUX ? 1 : 2048];
92 ssize_t n_bytes = recv(fd, buffer, sizeof buffer,
93 MSG_TRUNC | MSG_DONTWAIT);
94 if (n_bytes <= 0 || n_bytes >= rcvbuf) {
102 /* Attempts to shorten 'name' by opening a file descriptor for the directory
103 * part of the name and indirecting through /proc/self/fd/<dirfd>/<basename>.
104 * On systems with Linux-like /proc, this works as long as <basename> isn't too
107 * On success, returns 0 and stores the short name in 'short_name' and a
108 * directory file descriptor to eventually be closed in '*dirfpd'. */
110 shorten_name_via_proc(const char *name, char short_name[MAX_UN_LEN + 1],
121 dir = dir_name(name);
122 dirfd = open(dir, O_DIRECTORY | O_RDONLY);
124 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
127 VLOG_WARN_RL(&rl, "%s: open failed (%s)", dir, ovs_strerror(error));
134 base = base_name(name);
135 len = snprintf(short_name, MAX_UN_LEN + 1,
136 "/proc/self/fd/%d/%s", dirfd, base);
139 if (len >= 0 && len <= MAX_UN_LEN) {
148 /* Attempts to shorten 'name' by creating a symlink for the directory part of
149 * the name and indirecting through <symlink>/<basename>. This works on
150 * systems that support symlinks, as long as <basename> isn't too long.
152 * On success, returns 0 and stores the short name in 'short_name' and the
153 * symbolic link to eventually delete in 'linkname'. */
155 shorten_name_via_symlink(const char *name, char short_name[MAX_UN_LEN + 1],
156 char linkname[MAX_UN_LEN + 1])
158 char *abs, *dir, *base;
163 abs = abs_file_name(NULL, name);
165 base = base_name(abs);
168 tmpdir = getenv("TMPDIR");
169 if (tmpdir == NULL) {
173 for (i = 0; i < 1000; i++) {
176 len = snprintf(linkname, MAX_UN_LEN + 1,
177 "%s/ovs-un-c-%"PRIu32, tmpdir, random_uint32());
178 error = (len < 0 || len > MAX_UN_LEN ? ENAMETOOLONG
179 : symlink(dir, linkname) ? errno
181 if (error != EEXIST) {
189 fatal_signal_add_file_to_unlink(linkname);
191 len = snprintf(short_name, MAX_UN_LEN + 1, "%s/%s", linkname, base);
192 if (len < 0 || len > MAX_UN_LEN) {
193 fatal_signal_unlink_file_now(linkname);
194 error = ENAMETOOLONG;
207 /* Stores in '*un' a sockaddr_un that refers to file 'name'. Stores in
208 * '*un_len' the size of the sockaddr_un.
210 * Returns 0 on success, otherwise a positive errno value.
212 * Uses '*dirfdp' and 'linkname' to store references to data when the caller no
213 * longer needs to use 'un'. On success, freeing these references with
214 * free_sockaddr_un() is mandatory to avoid a leak; on failure, freeing them is
215 * unnecessary but harmless. */
217 make_sockaddr_un(const char *name, struct sockaddr_un *un, socklen_t *un_len,
218 int *dirfdp, char linkname[MAX_UN_LEN + 1])
220 char short_name[MAX_UN_LEN + 1];
224 if (strlen(name) > MAX_UN_LEN) {
225 /* 'name' is too long to fit in a sockaddr_un. Try a workaround. */
226 int error = shorten_name_via_proc(name, short_name, dirfdp);
227 if (error == ENAMETOOLONG) {
228 error = shorten_name_via_symlink(name, short_name, linkname);
231 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
233 VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
234 "%"PRIuSIZE" bytes", name, MAX_UN_LEN);
241 un->sun_family = AF_UNIX;
242 ovs_strzcpy(un->sun_path, name, sizeof un->sun_path);
243 *un_len = (offsetof(struct sockaddr_un, sun_path)
244 + strlen (un->sun_path) + 1);
248 /* Clean up after make_sockaddr_un(). */
250 free_sockaddr_un(int dirfd, const char *linkname)
256 fatal_signal_unlink_file_now(linkname);
260 /* Binds Unix domain socket 'fd' to a file with permissions 0700. */
262 bind_unix_socket(int fd, struct sockaddr *sun, socklen_t sun_len)
264 /* According to _Unix Network Programming_, umask should affect bind(). */
265 mode_t old_umask = umask(0077);
266 int error = bind(fd, sun, sun_len) ? errno : 0;
271 /* Creates a Unix domain socket in the given 'style' (either SOCK_DGRAM or
272 * SOCK_STREAM) that is bound to '*bind_path' (if 'bind_path' is non-null) and
273 * connected to '*connect_path' (if 'connect_path' is non-null). If 'nonblock'
274 * is true, the socket is made non-blocking.
276 * Returns the socket's fd if successful, otherwise a negative errno value. */
278 make_unix_socket(int style, bool nonblock,
279 const char *bind_path, const char *connect_path)
284 fd = socket(PF_UNIX, style, 0);
289 /* Set nonblocking mode right away, if we want it. This prevents blocking
290 * in connect(), if connect_path != NULL. (In turn, that's a corner case:
291 * it will only happen if style is SOCK_STREAM or SOCK_SEQPACKET, and only
292 * if a backlog of un-accepted connections has built up in the kernel.) */
294 error = set_nonblocking(fd);
301 char linkname[MAX_UN_LEN + 1];
302 struct sockaddr_un un;
306 if (unlink(bind_path) && errno != ENOENT) {
307 VLOG_WARN("unlinking \"%s\": %s\n",
308 bind_path, ovs_strerror(errno));
310 fatal_signal_add_file_to_unlink(bind_path);
312 error = make_sockaddr_un(bind_path, &un, &un_len, &dirfd, linkname);
314 error = bind_unix_socket(fd, (struct sockaddr *) &un, un_len);
316 free_sockaddr_un(dirfd, linkname);
324 char linkname[MAX_UN_LEN + 1];
325 struct sockaddr_un un;
329 error = make_sockaddr_un(connect_path, &un, &un_len, &dirfd, linkname);
331 && connect(fd, (struct sockaddr*) &un, un_len)
332 && errno != EINPROGRESS) {
335 free_sockaddr_un(dirfd, linkname);
345 if (error == EAGAIN) {
349 fatal_signal_unlink_file_now(bind_path);
356 get_unix_name_len(socklen_t sun_len)
358 return (sun_len >= offsetof(struct sockaddr_un, sun_path)
359 ? sun_len - offsetof(struct sockaddr_un, sun_path)
363 /* Calls ioctl() on an AF_INET sock, passing the specified 'command' and
364 * 'arg'. Returns 0 if successful, otherwise a positive errno value. */
366 af_inet_ioctl(unsigned long int command, const void *arg)
368 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
371 if (ovsthread_once_start(&once)) {
372 sock = socket(AF_INET, SOCK_DGRAM, 0);
374 int error = sock_errno();
375 VLOG_ERR("failed to create inet socket: %s", sock_strerror(error));
378 ovsthread_once_done(&once);
381 return (sock < 0 ? -sock
382 : ioctl(sock, command, arg) == -1 ? errno
387 af_inet_ifreq_ioctl(const char *name, struct ifreq *ifr, unsigned long int cmd,
388 const char *cmd_name)
392 ovs_strzcpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
393 error = af_inet_ioctl(cmd, ifr);
395 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
396 VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
397 ovs_strerror(error));