dpif-netdev: Batch megaflow lookup.
[cascardo/ovs.git] / lib / socket-util-unix.c
1 /*
2  * Copyright (c) 2014 Nicira, Inc.
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 <errno.h>
20 #include <fcntl.h>
21 #include <net/if.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/un.h>
26 #include <unistd.h>
27 #include "fatal-signal.h"
28 #include "random.h"
29 #include "util.h"
30 #include "vlog.h"
31
32 VLOG_DEFINE_THIS_MODULE(socket_util_unix);
33
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__". */
37 #ifdef __linux__
38 #define LINUX 1
39 #else
40 #define LINUX 0
41 #endif
42
43 #ifndef O_DIRECTORY
44 #define O_DIRECTORY 0
45 #endif
46
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)
50
51 void
52 xpipe(int fds[2])
53 {
54     if (pipe(fds)) {
55         VLOG_FATAL("failed to create pipe (%s)", ovs_strerror(errno));
56     }
57 }
58
59 void
60 xpipe_nonblocking(int fds[2])
61 {
62     xpipe(fds);
63     xset_nonblocking(fds[0]);
64     xset_nonblocking(fds[1]);
65 }
66
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. */
72 int
73 drain_rcvbuf(int fd)
74 {
75     int rcvbuf;
76
77     rcvbuf = get_socket_rcvbuf(fd);
78     if (rcvbuf < 0) {
79         return -rcvbuf;
80     }
81
82     while (rcvbuf > 0) {
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.
88          *
89          * On other Unix-like OSes, MSG_TRUNC has no effect in the flags
90          * argument. */
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) {
95             break;
96         }
97         rcvbuf -= n_bytes;
98     }
99     return 0;
100 }
101
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
105  * long.
106  *
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'. */
109 static int
110 shorten_name_via_proc(const char *name, char short_name[MAX_UN_LEN + 1],
111                       int *dirfdp)
112 {
113     char *dir, *base;
114     int dirfd;
115     int len;
116
117     if (!LINUX) {
118         return ENAMETOOLONG;
119     }
120
121     dir = dir_name(name);
122     dirfd = open(dir, O_DIRECTORY | O_RDONLY);
123     if (dirfd < 0) {
124         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
125         int error = errno;
126
127         VLOG_WARN_RL(&rl, "%s: open failed (%s)", dir, ovs_strerror(error));
128         free(dir);
129
130         return error;
131     }
132     free(dir);
133
134     base = base_name(name);
135     len = snprintf(short_name, MAX_UN_LEN + 1,
136                    "/proc/self/fd/%d/%s", dirfd, base);
137     free(base);
138
139     if (len >= 0 && len <= MAX_UN_LEN) {
140         *dirfdp = dirfd;
141         return 0;
142     } else {
143         close(dirfd);
144         return ENAMETOOLONG;
145     }
146 }
147
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.
151  *
152  * On success, returns 0 and stores the short name in 'short_name' and the
153  * symbolic link to eventually delete in 'linkname'. */
154 static int
155 shorten_name_via_symlink(const char *name, char short_name[MAX_UN_LEN + 1],
156                          char linkname[MAX_UN_LEN + 1])
157 {
158     char *abs, *dir, *base;
159     const char *tmpdir;
160     int error;
161     int i;
162
163     abs = abs_file_name(NULL, name);
164     dir = dir_name(abs);
165     base = base_name(abs);
166     free(abs);
167
168     tmpdir = getenv("TMPDIR");
169     if (tmpdir == NULL) {
170         tmpdir = "/tmp";
171     }
172
173     for (i = 0; i < 1000; i++) {
174         int len;
175
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
180                  : 0);
181         if (error != EEXIST) {
182             break;
183         }
184     }
185
186     if (!error) {
187         int len;
188
189         fatal_signal_add_file_to_unlink(linkname);
190
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;
195         }
196     }
197
198     if (error) {
199         linkname[0] = '\0';
200     }
201     free(dir);
202     free(base);
203
204     return error;
205 }
206
207 /* Stores in '*un' a sockaddr_un that refers to file 'name'.  Stores in
208  * '*un_len' the size of the sockaddr_un.
209  *
210  * Returns 0 on success, otherwise a positive errno value.
211  *
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. */
216 static int
217 make_sockaddr_un(const char *name, struct sockaddr_un *un, socklen_t *un_len,
218                  int *dirfdp, char linkname[MAX_UN_LEN + 1])
219 {
220     char short_name[MAX_UN_LEN + 1];
221
222     *dirfdp = -1;
223     linkname[0] = '\0';
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);
229         }
230         if (error) {
231             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
232
233             VLOG_WARN_RL(&rl, "Unix socket name %s is longer than maximum "
234                          "%"PRIuSIZE" bytes", name, MAX_UN_LEN);
235             return error;
236         }
237
238         name = short_name;
239     }
240
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);
245     return 0;
246 }
247
248 /* Clean up after make_sockaddr_un(). */
249 static void
250 free_sockaddr_un(int dirfd, const char *linkname)
251 {
252     if (dirfd >= 0) {
253         close(dirfd);
254     }
255     if (linkname[0]) {
256         fatal_signal_unlink_file_now(linkname);
257     }
258 }
259
260 /* Binds Unix domain socket 'fd' to a file with permissions 0700. */
261 static int
262 bind_unix_socket(int fd, struct sockaddr *sun, socklen_t sun_len)
263 {
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;
267     umask(old_umask);
268     return error;
269 }
270
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.
275  *
276  * Returns the socket's fd if successful, otherwise a negative errno value. */
277 int
278 make_unix_socket(int style, bool nonblock,
279                  const char *bind_path, const char *connect_path)
280 {
281     int error;
282     int fd;
283
284     fd = socket(PF_UNIX, style, 0);
285     if (fd < 0) {
286         return -errno;
287     }
288
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.)  */
293     if (nonblock) {
294         error = set_nonblocking(fd);
295         if (error) {
296             goto error;
297         }
298     }
299
300     if (bind_path) {
301         char linkname[MAX_UN_LEN + 1];
302         struct sockaddr_un un;
303         socklen_t un_len;
304         int dirfd;
305
306         if (unlink(bind_path) && errno != ENOENT) {
307             VLOG_WARN("unlinking \"%s\": %s\n",
308                       bind_path, ovs_strerror(errno));
309         }
310         fatal_signal_add_file_to_unlink(bind_path);
311
312         error = make_sockaddr_un(bind_path, &un, &un_len, &dirfd, linkname);
313         if (!error) {
314             error = bind_unix_socket(fd, (struct sockaddr *) &un, un_len);
315         }
316         free_sockaddr_un(dirfd, linkname);
317
318         if (error) {
319             goto error;
320         }
321     }
322
323     if (connect_path) {
324         char linkname[MAX_UN_LEN + 1];
325         struct sockaddr_un un;
326         socklen_t un_len;
327         int dirfd;
328
329         error = make_sockaddr_un(connect_path, &un, &un_len, &dirfd, linkname);
330         if (!error
331             && connect(fd, (struct sockaddr*) &un, un_len)
332             && errno != EINPROGRESS) {
333             error = errno;
334         }
335         free_sockaddr_un(dirfd, linkname);
336
337         if (error) {
338             goto error;
339         }
340     }
341
342     return fd;
343
344 error:
345     if (error == EAGAIN) {
346         error = EPROTO;
347     }
348     if (bind_path) {
349         fatal_signal_unlink_file_now(bind_path);
350     }
351     close(fd);
352     return -error;
353 }
354
355 int
356 get_unix_name_len(socklen_t sun_len)
357 {
358     return (sun_len >= offsetof(struct sockaddr_un, sun_path)
359             ? sun_len - offsetof(struct sockaddr_un, sun_path)
360             : 0);
361 }
362
363 /* Calls ioctl() on an AF_INET sock, passing the specified 'command' and
364  * 'arg'.  Returns 0 if successful, otherwise a positive errno value. */
365 int
366 af_inet_ioctl(unsigned long int command, const void *arg)
367 {
368     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
369     static int sock;
370
371     if (ovsthread_once_start(&once)) {
372         sock = socket(AF_INET, SOCK_DGRAM, 0);
373         if (sock < 0) {
374             int error = sock_errno();
375             VLOG_ERR("failed to create inet socket: %s", sock_strerror(error));
376             sock = -error;
377         }
378         ovsthread_once_done(&once);
379     }
380
381     return (sock < 0 ? -sock
382             : ioctl(sock, command, arg) == -1 ? errno
383             : 0);
384 }
385
386 int
387 af_inet_ifreq_ioctl(const char *name, struct ifreq *ifr, unsigned long int cmd,
388                     const char *cmd_name)
389 {
390     int error;
391
392     ovs_strzcpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
393     error = af_inet_ioctl(cmd, ifr);
394     if (error) {
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));
398     }
399     return error;
400 }