1 /** @file safesyssocket.h
2 * @brief #include <sys/socket.h> with portability workarounds.
4 /* Copyright (C) 2012,2013,2014 Olly Betts
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #ifndef XAPIAN_INCLUDED_SAFESYSSOCKET_H
22 #define XAPIAN_INCLUDED_SAFESYSSOCKET_H
25 // Some older BSDs require sys/types.h to be included first.
26 # include <sys/types.h>
27 # include <sys/socket.h>
29 # include "safewinsock2.h"
33 # define SOCK_CLOEXEC 0
35 // On Linux at least, sometimes SOCK_CLOEXEC is defined but the kernel doesn't
36 // handle it in socket() or socketpair():
38 # include "safeerrno.h"
40 inline int socket_(int domain
, int type
, int protocol
) {
41 // Usually type is passed a constant, so we'll collapse to one branch or
42 // the other here. The case where SOCK_CLOEXEC == 0 is handled suitably.
43 if (type
& SOCK_CLOEXEC
) {
44 int save_errno
= errno
;
45 int r
= socket(domain
, type
, protocol
);
46 if (r
!= 0 && errno
== EINVAL
) {
48 r
= socket(domain
, type
&~ SOCK_CLOEXEC
, protocol
);
52 return socket(domain
, type
, protocol
);
56 inline int socketpair_(int domain
, int type
, int protocol
, int *sv
) {
57 // Usually type is passed a constant, so we'll collapse to one branch or
58 // the other here. The case where SOCK_CLOEXEC == 0 is handled suitably.
59 if (type
& SOCK_CLOEXEC
) {
60 int save_errno
= errno
;
61 int r
= socketpair(domain
, type
, protocol
, sv
);
62 if (r
!= 0 && errno
== EINVAL
) {
64 r
= socketpair(domain
, type
&~ SOCK_CLOEXEC
, protocol
, sv
);
68 return socketpair(domain
, type
, protocol
, sv
);
75 # define socket(D,T,P) socket_(D,T,P)
79 # define socketpair(D,T,P,S) socketpair_(D,T,P,S)
82 #endif // XAPIAN_INCLUDED_SAFESYSSOCKET_H