Pekka Paalanen | 51aaf64 | 2012-05-30 15:53:41 +0300 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright © 2012 Collabora, Ltd. |
| 3 | * |
| 4 | * Permission to use, copy, modify, distribute, and sell this software and its |
| 5 | * documentation for any purpose is hereby granted without fee, provided that |
| 6 | * the above copyright notice appear in all copies and that both that copyright |
| 7 | * notice and this permission notice appear in supporting documentation, and |
| 8 | * that the name of the copyright holders not be used in advertising or |
| 9 | * publicity pertaining to distribution of the software without specific, |
| 10 | * written prior permission. The copyright holders make no representations |
| 11 | * about the suitability of this software for any purpose. It is provided "as |
| 12 | * is" without express or implied warranty. |
| 13 | * |
| 14 | * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, |
| 15 | * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO |
| 16 | * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR |
| 17 | * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, |
| 18 | * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER |
| 19 | * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE |
| 20 | * OF THIS SOFTWARE. |
| 21 | */ |
| 22 | |
| 23 | #include <sys/types.h> |
| 24 | #include <sys/socket.h> |
| 25 | #include <unistd.h> |
| 26 | #include <fcntl.h> |
| 27 | #include <errno.h> |
| 28 | |
| 29 | #include "os-compatibility.h" |
| 30 | |
| 31 | static int |
| 32 | set_cloexec_or_close(int fd) |
| 33 | { |
| 34 | long flags; |
| 35 | |
| 36 | if (fd == -1) |
| 37 | return -1; |
| 38 | |
| 39 | flags = fcntl(fd, F_GETFD); |
| 40 | if (flags == -1) |
| 41 | goto err; |
| 42 | |
| 43 | if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) |
| 44 | goto err; |
| 45 | |
| 46 | return fd; |
| 47 | |
| 48 | err: |
| 49 | close(fd); |
| 50 | return -1; |
| 51 | } |
| 52 | |
| 53 | int |
| 54 | os_socketpair_cloexec(int domain, int type, int protocol, int *sv) |
| 55 | { |
| 56 | int ret; |
| 57 | |
| 58 | #ifdef SOCK_CLOEXEC |
| 59 | ret = socketpair(domain, type | SOCK_CLOEXEC, protocol, sv); |
| 60 | if (ret == 0 || errno != EINVAL) |
| 61 | return ret; |
| 62 | #endif |
| 63 | |
| 64 | ret = socketpair(domain, type, protocol, sv); |
| 65 | if (ret < 0) |
| 66 | return ret; |
| 67 | |
| 68 | sv[0] = set_cloexec_or_close(sv[0]); |
| 69 | sv[1] = set_cloexec_or_close(sv[1]); |
| 70 | |
| 71 | if (sv[0] != -1 && sv[1] != -1) |
| 72 | return 0; |
| 73 | |
| 74 | close(sv[0]); |
| 75 | close(sv[1]); |
| 76 | return -1; |
| 77 | } |
| 78 | |