1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2019 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
24 #include "socketpair.h"
26 #if !defined(HAVE_SOCKETPAIR) && !defined(CURL_DISABLE_SOCKETPAIR)
29 * This is a socketpair() implementation for Windows.
40 #ifdef HAVE_NETINET_IN_H
41 #include <netinet/in.h> /* IPPROTO_TCP */
43 #ifdef HAVE_ARPA_INET_H
44 #include <arpa/inet.h>
46 #ifndef INADDR_LOOPBACK
47 #define INADDR_LOOPBACK 0x7f000001
48 #endif /* !INADDR_LOOPBACK */
51 /* The last 3 #include files should be in this order */
52 #include "curl_printf.h"
53 #include "curl_memory.h"
56 int Curl_socketpair(int domain, int type, int protocol,
57 curl_socket_t socks[2])
60 struct sockaddr_in inaddr;
63 curl_socket_t listener;
64 curl_socklen_t addrlen = sizeof(a.inaddr);
72 listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
73 if(listener == CURL_SOCKET_BAD)
76 memset(&a, 0, sizeof(a));
77 a.inaddr.sin_family = AF_INET;
78 a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
79 a.inaddr.sin_port = 0;
81 socks[0] = socks[1] = CURL_SOCKET_BAD;
83 if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,
84 (char *)&reuse, (curl_socklen_t)sizeof(reuse)) == -1)
86 if(bind(listener, &a.addr, sizeof(a.inaddr)) == -1)
88 if(getsockname(listener, &a.addr, &addrlen) == -1)
90 if(listen(listener, 1) == -1)
92 socks[0] = socket(AF_INET, SOCK_STREAM, 0);
93 if(socks[0] == CURL_SOCKET_BAD)
95 if(connect(socks[0], &a.addr, sizeof(a.inaddr)) == -1)
97 socks[1] = accept(listener, NULL, NULL);
98 if(socks[1] == CURL_SOCKET_BAD)
101 /* verify that nothing else connected */
102 msnprintf(data[0], sizeof(data[0]), "%p", socks);
103 dlen = strlen(data[0]);
104 if(swrite(socks[0], data[0], dlen) != dlen)
106 if(sread(socks[1], data[1], sizeof(data[1])) != dlen)
108 if(memcmp(data[0], data[1], dlen))
121 #endif /* ! HAVE_SOCKETPAIR */