master
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
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.se/docs/copyright.html.
13 *
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.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24#include "curl_setup.h"
26#ifdef HAVE_NETINET_IN_H
27#include <netinet/in.h> /* <netinet/tcp.h> may need it */
28#endif
29#ifdef HAVE_SYS_UN_H
30#include <sys/un.h> /* for sockaddr_un */
31#endif
32#ifdef HAVE_NETINET_TCP_H
33#include <netinet/tcp.h> /* for TCP_FASTOPEN_CONNECT, TCP_NODELAY */
34#endif
35#ifdef HAVE_NETINET_UDP_H
36#include <netinet/udp.h>
37#endif
38#ifdef HAVE_NETINET_IP_H
39#include <netinet/ip.h>
40#endif
41#ifdef HAVE_SYS_IOCTL_H
42#include <sys/ioctl.h>
43#endif
44#ifdef HAVE_NETDB_H
45#include <netdb.h>
46#endif
47#ifdef HAVE_ARPA_INET_H
48#include <arpa/inet.h>
49#endif
51#ifdef HAVE_IFADDRS_H
52#include <ifaddrs.h>
53#endif
54#ifdef HAVE_NET_IF_H
55#include <net/if.h>
56#endif
57#ifdef __VMS
58#include <in.h>
59#include <inet.h>
60#endif
62#include "urldata.h"
63#include "curl_trc.h"
64#include "if2ip.h"
65#include "cfilters.h"
66#include "cf-socket.h"
67#include "connect.h"
68#include "curl_addrinfo.h"
69#include "select.h"
70#include "multiif.h"
71#include "curlx/inet_ntop.h"
72#include "curlx/inet_pton.h"
73#include "progress.h"
74#include "conncache.h"
75#include "multihandle.h"
76#include "rand.h"
77#include "sockaddr.h"
78#include "curlx/strdup.h"
79#include "curlx/nonblock.h"
80#include "curlx/strcopy.h"
81#include "curlx/version_win32.h"
82#include "curlx/strerr.h"
83#include "curlx/strparse.h"
84#include "curlx/wait.h"
85#ifdef _WIN32
86#include <mstcpip.h> /* for TCP_INITIAL_RTO_PARAMETERS */
87#endif
89/* retrieves ip address and port from a sockaddr structure. note it calls
90 * curlx_inet_ntop() and returns CURLcode.
91 * @unittest 1607
92 */
93UNITTEST CURLcode sockaddr2string(struct sockaddr *sa, curl_socklen_t salen,
94 char *addr, uint16_t *port);
95UNITTEST CURLcode sockaddr2string(struct sockaddr *sa, curl_socklen_t salen,
96 char *addr, uint16_t *port)
97{
98 CURLcode result;
99 struct sockaddr_in *si = NULL;
100#ifdef USE_IPV6
101 struct sockaddr_in6 *si6 = NULL;
102#endif
103#ifdef USE_UNIX_SOCKETS
104 struct sockaddr_un *su = NULL;
105#else
106 (void)salen;
107#endif
109 switch(sa->sa_family) {
110 case AF_INET:
111 si = (struct sockaddr_in *)(void *)sa;
112 result = curlx_inet_ntop(sa->sa_family, &si->sin_addr, addr,
113 MAX_IPADR_LEN);
114 if(!result) {
115 *port = ntohs(si->sin_port);
116 return result;
117 }
118 break;
119#ifdef USE_IPV6
120 case AF_INET6:
121 si6 = (struct sockaddr_in6 *)(void *)sa;
122 result = curlx_inet_ntop(sa->sa_family, &si6->sin6_addr, addr,
123 MAX_IPADR_LEN);
124 if(!result) {
125 *port = ntohs(si6->sin6_port);
126 return result;
127 }
128 break;
129#endif
130#ifdef USE_UNIX_SOCKETS
131 case AF_UNIX:
132 if(salen > (curl_socklen_t)sizeof(CURL_SA_FAMILY_T)) {
133 su = (struct sockaddr_un *)sa;
134 curl_msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
135 }
136 else
137 addr[0] = 0; /* socket with no name */
138 *port = 0;
139 return CURLE_OK;
140#endif
141 default:
142 result = CURLE_UNSUPPORTED_PROTOCOL;
143 break;
144 }
146 addr[0] = '\0';
147 *port = 0;
148 return result;
149}
151static void tcpnodelay(struct Curl_cfilter *cf,
152 struct Curl_easy *data,
153 curl_socket_t sockfd)
154{
155#if defined(TCP_NODELAY) && defined(CURL_TCP_NODELAY_SUPPORTED)
156 curl_socklen_t onoff = (curl_socklen_t)1;
157 int level = IPPROTO_TCP;
158 VERBOSE(char buffer[STRERROR_LEN]);
160 if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff, sizeof(onoff)) < 0)
161 CURL_TRC_CF(data, cf, "Could not set TCP_NODELAY: %s",
162 curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
163#else
164 (void)cf;
165 (void)data;
166 (void)sockfd;
167#endif
168}
170#if defined(USE_WINSOCK) || defined(TCP_KEEPIDLE) || \
171 defined(TCP_KEEPALIVE) || defined(TCP_KEEPALIVE_THRESHOLD) || \
172 defined(TCP_KEEPINTVL) || defined(TCP_KEEPALIVE_ABORT_THRESHOLD)
173#if defined(USE_WINSOCK) || \
174 (defined(__sun) && !defined(TCP_KEEPIDLE)) || \
175 (defined(__DragonFly__) && __DragonFly_version < 500702) || \
176 (defined(_WIN32) && !defined(TCP_KEEPIDLE))
177/* Solaris < 11.4, DragonFlyBSD < 500702 and Windows < 10.0.16299
178 * use millisecond units. */
179static void alive_unit(int *x)
180{
181 /* make sure this doesn't wrap */
182 if(*x < (INT_MAX / 1000))
183 *x *= 1000;
184 else
185 /* this is still almost 25 days */
186 *x = INT_MAX;
187}
188#else
189#define alive_unit(x)
190#endif
191#endif
193static void tcpkeepalive(struct Curl_cfilter *cf,
194 struct Curl_easy *data,
195 curl_socket_t sockfd)
196{
197 int optval = data->set.tcp_keepalive ? 1 : 0;
199 /* only set IDLE and INTVL if setting KEEPALIVE is successful */
200 if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
201 (void *)&optval, sizeof(optval)) < 0) {
202 CURL_TRC_CF(data, cf, "Failed to set SO_KEEPALIVE on fd "
203 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
204 }
205 else {
206#ifdef USE_WINSOCK
207 /* Windows 10, version 1709 (10.0.16299) and later versions can use
208 setsockopt() TCP_KEEP*. Older versions return with failure. */
209 if(curlx_verify_windows_version(10, 0, 16299, PLATFORM_WINNT,
210 VERSION_GREATER_THAN_EQUAL)) {
211 CURL_TRC_CF(data, cf, "Set TCP_KEEP* on fd=%" FMT_SOCKET_T, sockfd);
212 optval = curlx_sltosi(data->set.tcp_keepidle);
213/* Offered by mingw-w64 v12+, MS SDK 6.0A/VS2008+ */
214#ifndef TCP_KEEPALIVE
215#define TCP_KEEPALIVE 3
216#endif
217/* Offered by mingw-w64 v12+, MS SDK 10.0.15063.0/VS2017 15.1+ */
218#ifndef TCP_KEEPCNT
219#define TCP_KEEPCNT 16
220#endif
221/* Offered by mingw-w64 v12+, MS SDK 10.0.16299.0/VS2017 15.4+ */
222#ifndef TCP_KEEPIDLE
223#define TCP_KEEPIDLE TCP_KEEPALIVE
224#endif
225#ifndef TCP_KEEPINTVL
226#define TCP_KEEPINTVL 17
227#endif
228 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
229 (const char *)&optval, sizeof(optval)) < 0) {
230 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPIDLE on fd "
231 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
232 }
233 optval = curlx_sltosi(data->set.tcp_keepintvl);
234 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
235 (const char *)&optval, sizeof(optval)) < 0) {
236 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPINTVL on fd "
237 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
238 }
239 optval = curlx_sltosi(data->set.tcp_keepcnt);
240 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT,
241 (const char *)&optval, sizeof(optval)) < 0) {
242 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPCNT on fd "
243 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
244 }
245 }
246 else {
247/* Offered by mingw-w64 and MS SDK. Latter only when targeting Win7+. */
248#ifndef SIO_KEEPALIVE_VALS
249#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR, 4)
250 struct tcp_keepalive {
251 u_long onoff;
252 u_long keepalivetime;
253 u_long keepaliveinterval;
254 };
255#endif
256 struct tcp_keepalive vals;
257 DWORD dummy;
258 vals.onoff = 1;
259 optval = curlx_sltosi(data->set.tcp_keepidle);
260 alive_unit(&optval);
261 vals.keepalivetime = (u_long)optval;
262 optval = curlx_sltosi(data->set.tcp_keepintvl);
263 alive_unit(&optval);
264 vals.keepaliveinterval = (u_long)optval;
265 if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID)&vals, sizeof(vals),
266 NULL, 0, &dummy, NULL, NULL) != 0) {
267 CURL_TRC_CF(data, cf, "Failed to set SIO_KEEPALIVE_VALS on fd "
268 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
269 }
270 }
271#else /* !USE_WINSOCK */
272#ifdef TCP_KEEPIDLE
273 optval = curlx_sltosi(data->set.tcp_keepidle);
274 alive_unit(&optval);
275 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
276 (void *)&optval, sizeof(optval)) < 0) {
277 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPIDLE on fd "
278 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
279 }
280#elif defined(TCP_KEEPALIVE)
281 /* macOS style */
282 optval = curlx_sltosi(data->set.tcp_keepidle);
283 alive_unit(&optval);
284 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
285 (void *)&optval, sizeof(optval)) < 0) {
286 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE on fd "
287 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
288 }
289#elif defined(TCP_KEEPALIVE_THRESHOLD)
290 /* Solaris <11.4 style */
291 optval = curlx_sltosi(data->set.tcp_keepidle);
292 alive_unit(&optval);
293 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD,
294 (void *)&optval, sizeof(optval)) < 0) {
295 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE_THRESHOLD on fd "
296 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
297 }
298#endif
299#ifdef TCP_KEEPINTVL
300 optval = curlx_sltosi(data->set.tcp_keepintvl);
301 alive_unit(&optval);
302 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
303 (void *)&optval, sizeof(optval)) < 0) {
304 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPINTVL on fd "
305 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
306 }
307#elif defined(TCP_KEEPALIVE_ABORT_THRESHOLD)
308 /* Solaris <11.4 style */
309 /* TCP_KEEPALIVE_ABORT_THRESHOLD should equal to
310 * TCP_KEEPCNT * TCP_KEEPINTVL on other platforms.
311 * The default value of TCP_KEEPCNT is 9 on Linux,
312 * 8 on *BSD/macOS, 5 or 10 on Windows. We use the
313 * default config for Solaris <11.4 because there is
314 * no default value for TCP_KEEPCNT on Solaris 11.4.
315 *
316 * Note that the consequent probes will not be sent
317 * at equal intervals on Solaris, but will be sent
318 * using the exponential backoff algorithm. */
319 {
320 int keepcnt = curlx_sltosi(data->set.tcp_keepcnt);
321 int keepintvl = curlx_sltosi(data->set.tcp_keepintvl);
323 if(keepcnt > 0 && keepintvl > (INT_MAX / keepcnt))
324 optval = INT_MAX;
325 else
326 optval = keepcnt * keepintvl;
327 }
328 alive_unit(&optval);
329 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD,
330 (void *)&optval, sizeof(optval)) < 0) {
331 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPALIVE_ABORT_THRESHOLD"
332 " on fd %" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
333 }
334#endif
335#ifdef TCP_KEEPCNT
336 optval = curlx_sltosi(data->set.tcp_keepcnt);
337 if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT,
338 (void *)&optval, sizeof(optval)) < 0) {
339 CURL_TRC_CF(data, cf, "Failed to set TCP_KEEPCNT on fd "
340 "%" FMT_SOCKET_T ": errno %d", sockfd, SOCKERRNO);
341 }
342#endif
343#endif /* USE_WINSOCK */
344 }
345}
347/**
348 * Assign the addrinfo `ai` to the Curl_sockaddr_ex `addr` with
349 * transport determining socktype and protocol.
350 */
351CURLcode Curl_socket_addr_from_ai(struct Curl_sockaddr_ex *addr,
352 const struct Curl_addrinfo *ai,
353 uint8_t transport)
354{
355 /*
356 * The Curl_sockaddr_ex structure is libcurl's external API
357 * curl_sockaddr structure with enough space available to directly hold
358 * any protocol-specific address structures. The variable declared here
359 * will be used to pass / receive data to/from the fopensocket callback
360 * if this has been set, before that, it is initialized from parameters.
361 */
362 addr->family = ai->ai_family;
363 addr->socktype = Curl_socktype_for_transport(transport);
364 addr->protocol = Curl_protocol_for_transport(transport);
365 addr->addrlen = (unsigned int)ai->ai_addrlen;
367 DEBUGASSERT(addr->addrlen <= sizeof(addr->curl_sa_addrbuf));
368 if(addr->addrlen > sizeof(addr->curl_sa_addrbuf))
369 return CURLE_TOO_LARGE;
371 memcpy(&addr->curl_sa_addrbuf, ai->ai_addr, addr->addrlen);
372 return CURLE_OK;
373}
375#ifdef USE_SO_NOSIGPIPE
376int Curl_sock_nosigpipe(curl_socket_t sockfd)
377{
378 int onoff = 1;
379 return setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE,
380 (void *)&onoff, sizeof(onoff));
381}
382#endif /* USE_SO_NOSIGPIPE */
384#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
385static uint32_t get_scope_id(struct Curl_easy *data,
386 struct sockaddr_in6 *sa6)
387{
388 uint32_t scope_id = 0;
389 if(data->conn->scope_id)
390 return data->conn->scope_id;
391 /* NOLINTNEXTLINE(clang-analyzer-core.uninitialized.Assign) */
392 scope_id = sa6->sin6_scope_id;
393 if(!scope_id && IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
394 /* The resolver did not set scope_id for this link-local address.
395 * Try to determine it from the system's network interfaces.
396 * Without a scope_id, connect() to a link-local address fails
397 * with EINVAL on Linux.
398 * NOTE: On multi-homed hosts with several interfaces having
399 * link-local addresses, this picks the first one found, which
400 * may not be the correct outgoing interface. */
401#if defined(HAVE_GETIFADDRS) && defined(HAVE_NET_IF_H)
402 struct ifaddrs *ifa, *ifa_list;
403 if(getifaddrs(&ifa_list) == 0) {
404 for(ifa = ifa_list; ifa; ifa = ifa->ifa_next) {
405 if(ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6 &&
406 (ifa->ifa_flags & IFF_UP) &&
407 !(ifa->ifa_flags & IFF_LOOPBACK)) {
408 struct sockaddr_in6 *s6 = (void *)ifa->ifa_addr;
409 if(IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr) && s6->sin6_scope_id) {
410 scope_id = s6->sin6_scope_id;
411 infof(data,
412 "determined scope_id=%lu for link-local address "
413 "from local interface",
414 (unsigned long)scope_id);
415 break;
416 }
417 }
418 }
419 freeifaddrs(ifa_list);
420 }
421#endif /* HAVE_GETIFADDRS && HAVE_NET_IF_H */
422 }
423 return scope_id;
424}
425#endif
427static CURLcode socket_open(struct Curl_easy *data,
428 struct Curl_sockaddr_ex *addr,
429 curl_socket_t *sockfd)
430{
431 char errbuf[STRERROR_LEN];
433#ifdef SOCK_CLOEXEC
434 addr->socktype |= SOCK_CLOEXEC;
435#endif
437 DEBUGASSERT(data);
438 DEBUGASSERT(data->conn);
439 if(data->set.fopensocket) {
440 /*
441 * If the opensocket callback is set, all the destination address
442 * information is passed to the callback. Depending on this information the
443 * callback may opt to abort the connection, this is indicated returning
444 * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
445 * the callback returns a valid socket the destination address information
446 * might have been changed and this 'new' address will actually be used
447 * here to connect.
448 */
449 struct Curl_mapi_guard guard;
450 CURL_CBAPI_START(&guard, data, easy_fopensocket);
451 *sockfd = data->set.fopensocket(data->set.opensocket_client,
452 CURLSOCKTYPE_IPCXN,
453 (struct curl_sockaddr *)addr);
454 CURL_CBAPI_END(&guard);
455 }
456 else {
457 /* opensocket callback not set, so create the socket now */
458#ifdef DEBUGBUILD
459 if((addr->family == AF_INET6) && getenv("CURL_DBG_SOCK_FAIL_IPV6")) {
460 failf(data, "CURL_DBG_SOCK_FAIL_IPV6: failed to open socket");
461 return CURLE_COULDNT_CONNECT;
462 }
463#endif
464 *sockfd = CURL_SOCKET(addr->family, addr->socktype, addr->protocol);
465 if((*sockfd == CURL_SOCKET_BAD) && (SOCKERRNO == SOCKENOMEM))
466 return CURLE_OUT_OF_MEMORY;
467 }
469 if(*sockfd == CURL_SOCKET_BAD) {
470 /* no socket, no connection */
471 failf(data, "failed to open socket: %s",
472 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
473 return CURLE_COULDNT_CONNECT;
474 }
476#ifdef USE_SO_NOSIGPIPE
477 if(Curl_sock_nosigpipe(*sockfd) < 0) {
478 failf(data, "setsockopt enable SO_NOSIGPIPE: %s",
479 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
480 sclose(*sockfd);
481 *sockfd = CURL_SOCKET_BAD;
482 return CURLE_COULDNT_CONNECT;
483 }
484#endif /* USE_SO_NOSIGPIPE */
486#if defined(HAVE_FCNTL) && !defined(SOCK_CLOEXEC)
487 if(fcntl(*sockfd, F_SETFD, FD_CLOEXEC) < 0) {
488 failf(data, "fcntl set CLOEXEC: %s",
489 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
490 sclose(*sockfd);
491 *sockfd = CURL_SOCKET_BAD;
492 return CURLE_COULDNT_CONNECT;
493 }
494#endif
496#if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
497 if(addr->family == AF_INET6) {
498 struct sockaddr_in6 * const sa6 = (void *)&addr->curl_sa_addr;
499 sa6->sin6_scope_id = get_scope_id(data, sa6);
500 }
501#endif
502 return CURLE_OK;
503}
505/*
506 * Create a socket based on info from 'conn' and 'ai'.
507 *
508 * 'addr' should be a pointer to the correct struct to get data back, or NULL.
509 * 'sockfd' must be a pointer to a socket descriptor.
510 *
511 * If the open socket callback is set, used that!
512 *
513 */
514CURLcode Curl_socket_open(struct Curl_easy *data,
515 const struct Curl_addrinfo *ai,
516 struct Curl_sockaddr_ex *addr,
517 uint8_t transport,
518 curl_socket_t *sockfd)
519{
520 struct Curl_sockaddr_ex dummy;
521 CURLcode result;
523 if(!addr)
524 /* if the caller does not want info back, use a local temp copy */
525 addr = &dummy;
527 result = Curl_socket_addr_from_ai(addr, ai, transport);
528 if(result)
529 return result;
531 return socket_open(data, addr, sockfd);
532}
534static int socket_close(struct Curl_easy *data, struct connectdata *conn,
535 int use_callback, curl_socket_t sock)
536{
537 if(sock == CURL_SOCKET_BAD)
538 return 0;
540 if(use_callback && conn && conn->fclosesocket) {
541 struct Curl_mapi_guard guard;
542 int rc;
543 Curl_multi_will_close(data, sock);
544 CURL_CBAPI_START(&guard, data, easy_closesocket);
545 rc = conn->fclosesocket(conn->closesocket_client, sock);
546 CURL_CBAPI_END(&guard);
547 return rc;
548 }
550 if(conn)
551 /* tell the multi-socket code about this */
552 Curl_multi_will_close(data, sock);
554 sclose(sock);
556 return 0;
557}
559/*
560 * Close a socket.
561 *
562 * 'conn' can be NULL, beware!
563 */
564int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn,
565 curl_socket_t sock)
566{
567 return socket_close(data, conn, FALSE, sock);
568}
570/*
571 * Curl_parse_interface()
572 *
573 * This is used to parse interface argument in the following formats.
574 * In all the examples, `host` can be an IP address or a hostname.
575 *
576 * <iface_or_host> - can be either an interface name or a host.
577 * if!<iface> - interface name.
578 * host!<host> - hostname.
579 * ifhost!<iface>!<host> - interface name and hostname.
580 *
581 * Parameters:
582 *
583 * input [in] - input string.
584 * len [in] - length of the input string.
585 * dev [in/out] - address where a pointer to newly allocated memory
586 * holding the interface-or-host will be stored upon
587 * completion or NULL if the caller is not interested.
588 * iface [in/out] - address where a pointer to newly allocated memory
589 * holding the interface will be stored upon completion
590 * or NULL if the caller is not interested.
591 * host [in/out] - address where a pointer to newly allocated memory
592 * holding the host will be stored upon completion
593 * or NULL if the caller is not interested.
594 *
595 * Returns CURLE_OK on success.
596 */
597CURLcode Curl_parse_interface(const char *input,
598 char **dev, char **iface, char **host)
599{
600 static const char if_prefix[] = "if!";
601 static const char host_prefix[] = "host!";
602 static const char if_host_prefix[] = "ifhost!";
603 size_t len;
605 len = strlen(input);
606 if(len > 512)
607 return CURLE_BAD_FUNCTION_ARGUMENT;
609 if(dev)
610 *dev = NULL;
611 if(iface)
612 *iface = NULL;
613 if(host)
614 *host = NULL;
616 if(!strncmp(if_prefix, input, strlen(if_prefix))) {
617 input += strlen(if_prefix);
618 if(!*input)
619 return CURLE_BAD_FUNCTION_ARGUMENT;
620 if(iface) {
621 *iface = curlx_memdup0(input, len - strlen(if_prefix));
622 return *iface ? CURLE_OK : CURLE_OUT_OF_MEMORY;
623 }
624 return CURLE_OK;
625 }
626 else if(!strncmp(host_prefix, input, strlen(host_prefix))) {
627 input += strlen(host_prefix);
628 if(!*input)
629 return CURLE_BAD_FUNCTION_ARGUMENT;
630 if(host) {
631 *host = curlx_memdup0(input, len - strlen(host_prefix));
632 return *host ? CURLE_OK : CURLE_OUT_OF_MEMORY;
633 }
634 return CURLE_OK;
635 }
636 else if(!strncmp(if_host_prefix, input, strlen(if_host_prefix))) {
637 const char *host_part;
638 input += strlen(if_host_prefix);
639 len -= strlen(if_host_prefix);
640 host_part = memchr(input, '!', len);
641 if(!host_part || !*(host_part + 1))
642 return CURLE_BAD_FUNCTION_ARGUMENT;
643 if(iface) {
644 *iface = curlx_memdup0(input, host_part - input);
645 if(!*iface)
646 return CURLE_OUT_OF_MEMORY;
647 }
648 ++host_part;
649 if(host) {
650 *host = curlx_memdup0(host_part, len - (host_part - input));
651 if(!*host) {
652 if(iface)
653 curlx_safefree(*iface);
654 return CURLE_OUT_OF_MEMORY;
655 }
656 }
657 return CURLE_OK;
658 }
660 if(!*input)
661 return CURLE_BAD_FUNCTION_ARGUMENT;
662 if(dev) {
663 *dev = curlx_memdup0(input, len);
664 return *dev ? CURLE_OK : CURLE_OUT_OF_MEMORY;
665 }
666 return CURLE_OK;
667}
669#ifndef CURL_DISABLE_BINDLOCAL
670static CURLcode bindlocal(struct Curl_easy *data, struct connectdata *conn,
671 curl_socket_t sockfd, int af, unsigned int scope,
672 uint8_t transport)
673{
674 struct Curl_sockaddr_storage sa;
675 struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
676 curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
677 struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
678#ifdef USE_IPV6
679 struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
680#endif
681 struct Curl_dns_entry *h = NULL;
682 unsigned short port = data->set.localport; /* use this port number, 0 for
683 "random" */
684 /* how many port numbers to try to bind to, increasing one at a time */
685 int portnum = data->set.localportrange;
686 char *dev_in = NULL, *iface_in = NULL, *host_in = NULL;
687 const char *iface = NULL, *host = NULL;
688 int sockerr;
689#ifdef IP_BIND_ADDRESS_NO_PORT
690 int on = 1;
691#endif
692 CURLcode result = CURLE_OK;
694#ifndef USE_IPV6
695 (void)scope;
696#endif
697 if(conn->interface_opts) {
698 /*************************************************************
699 * Select device to bind socket to
700 *************************************************************/
701 result = Curl_parse_interface(conn->interface_opts,
702 &dev_in, &iface_in, &host_in);
703 if(result)
704 goto out;
705 /* This is how we use the values */
706 iface = iface_in ? iface_in : dev_in;
707 host = host_in ? host_in : dev_in;
708 }
710 if(!iface && !host && !port)
711 goto out;
713 if(iface && (strlen(iface) >= 255)) {
714 result = CURLE_BAD_FUNCTION_ARGUMENT;
715 goto out;
716 }
717 memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
719 if(iface || host) {
720 char myhost[256] = "";
721 int done = 0; /* -1 for error, 1 for address found */
722 if2ip_result_t if2ip_result = IF2IP_NOT_FOUND;
724#ifdef SO_BINDTODEVICE
725 /*
726 * This binds the local socket to a particular interface. This will
727 * force even requests to other local interfaces to go out the external
728 * interface. Only bind to the interface when specified as interface,
729 * not as a hostname or ip address.
730 *
731 * The interface might be a VRF, eg: vrf-blue, which means it cannot be
732 * converted to an IP address and would fail Curl_if2ip. Try to
733 * use it straight away.
734 */
735 if(iface &&
736 setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
737 iface, (curl_socklen_t)strlen(iface) + 1) == 0 &&
738 /* This is often "errno 1, error: Operation not permitted" if you are
739 * not running as root or another suitable privileged user. If it
740 * succeeds it means the parameter was a valid interface and not an IP
741 * address. Return immediately.
742 */
743 !host_in) {
744 infof(data, "socket successfully bound to interface '%s'", iface);
745 result = CURLE_OK;
746 goto out;
747 }
748#endif
749 if(!host_in) {
750 /* Discover IP from input device, then bind to it */
751 if2ip_result = Curl_if2ip(af,
752#ifdef USE_IPV6
753 scope, conn->scope_id,
754#endif
755 iface, myhost, sizeof(myhost));
756 }
757 switch(if2ip_result) {
758 case IF2IP_NOT_FOUND:
759 if(iface_in && !host_in) {
760 /* Do not fall back to treating it as a hostname */
761 char buffer[STRERROR_LEN];
762 data->state.os_errno = sockerr = SOCKERRNO;
763 failf(data, "Could not bind to interface '%s' with errno %d: %s",
764 iface, sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer)));
765 result = CURLE_INTERFACE_FAILED;
766 goto out;
767 }
768 break;
769 case IF2IP_AF_NOT_SUPPORTED:
770 /* Signal the caller to try another address family if available */
771 result = CURLE_UNSUPPORTED_PROTOCOL;
772 goto out;
773 case IF2IP_FOUND:
774 /*
775 * We now have the numerical IP address in the 'myhost' buffer
776 */
777 host = myhost;
778 infof(data, "Local Interface %s is ip %s using address family %d",
779 iface, host, af);
780 done = 1;
781 break;
782 }
783 if(!iface_in || host_in) {
784 /*
785 * This was not an interface, resolve the name as a hostname
786 * or IP number
787 *
788 * Temporarily force name resolution to use only the address type
789 * of the connection. The resolve functions should really be changed
790 * to take a type parameter instead.
791 */
792 uint8_t dns_queries = (af == AF_INET) ?
793 CURL_DNSQ_A : (CURL_DNSQ_A | CURL_DNSQ_AAAA);
794#ifdef USE_IPV6
795 if(af == AF_INET6)
796 dns_queries = CURL_DNSQ_AAAA;
797#endif
799 (void)Curl_resolv_blocking(data, dns_queries, host, 80, transport, &h);
800 if(h) {
801 int h_af = h->addr->ai_family;
802 /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
803 Curl_printable_address(h->addr, myhost, sizeof(myhost));
804 infof(data, "Name '%s' family %d resolved to '%s' family %d",
805 host, af, myhost, h_af);
806 Curl_dns_entry_unlink(data, &h); /* this will NULL, potential free h */
807 if(af != h_af) {
808 /* bad IP version combo, signal the caller to try another address
809 family if available */
810 result = CURLE_UNSUPPORTED_PROTOCOL;
811 goto out;
812 }
813 done = 1;
814 }
815 else {
816 /*
817 * provided dev was no interface (or interfaces are not supported
818 * e.g. Solaris) no ip address and no domain we fail here
819 */
820 done = -1;
821 }
822 }
824 if(done > 0) {
825#ifdef USE_IPV6
826 /* IPv6 address */
827 if(af == AF_INET6) {
828#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
829 char *scope_ptr = strchr(myhost, '%');
830 if(scope_ptr)
831 *(scope_ptr++) = '\0';
832#endif
833 if(curlx_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
834 si6->sin6_family = AF_INET6;
835 si6->sin6_port = htons(port);
836#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
837 if(scope_ptr) {
838 /* The "myhost" string either comes from Curl_if2ip or from
839 Curl_printable_address. The latter returns only numeric scope
840 IDs and the former returns none at all. Making the scope ID,
841 if present, known to be numeric */
842 curl_off_t scope_id;
843 if(curlx_str_number((const char **)CURL_UNCONST(&scope_ptr),
844 &scope_id, UINT_MAX)) {
845 result = CURLE_UNSUPPORTED_PROTOCOL;
846 goto out;
847 }
848 si6->sin6_scope_id = (unsigned int)scope_id;
849 }
850#endif
851 }
852 sizeof_sa = sizeof(struct sockaddr_in6);
853 }
854 else
855#endif
856 /* IPv4 address */
857 if((af == AF_INET) &&
858 (curlx_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
859 si4->sin_family = AF_INET;
860 si4->sin_port = htons(port);
861 sizeof_sa = sizeof(struct sockaddr_in);
862 }
863 }
865 if(done < 1) {
866 /* errorbuf is set false so failf will overwrite any message already in
867 the error buffer, so the user receives this error message instead of a
868 generic resolve error. */
869 char buffer[STRERROR_LEN];
870 data->state.errorbuf = FALSE;
871 data->state.os_errno = sockerr = SOCKERRNO;
872 failf(data, "Could not bind to '%s' with errno %d: %s", host,
873 sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer)));
874 result = CURLE_INTERFACE_FAILED;
875 goto out;
876 }
877 }
878 else {
879 /* no device was given, prepare sa to match af's needs */
880#ifdef USE_IPV6
881 if(af == AF_INET6) {
882 si6->sin6_family = AF_INET6;
883 si6->sin6_port = htons(port);
884 sizeof_sa = sizeof(struct sockaddr_in6);
885 }
886 else
887#endif
888 if(af == AF_INET) {
889 si4->sin_family = AF_INET;
890 si4->sin_port = htons(port);
891 sizeof_sa = sizeof(struct sockaddr_in);
892 }
893 }
894#ifdef IP_BIND_ADDRESS_NO_PORT
895 (void)setsockopt(sockfd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &on, sizeof(on));
896#endif
897 for(;;) {
898 if(bind(sockfd, sock, sizeof_sa) >= 0) {
899 /* we succeeded to bind */
900 infof(data, "Local port: %hu", port);
901 conn->bits.bound = TRUE;
902 result = CURLE_OK;
903 goto out;
904 }
906 if(--portnum > 0) {
907 port++; /* try next port */
908 if(port == 0)
909 break;
910 infof(data, "Bind to local port %d failed, trying next", port - 1);
911 /* We reuse/clobber the port variable here below */
912 if(sock->sa_family == AF_INET)
913 si4->sin_port = htons(port);
914#ifdef USE_IPV6
915 else
916 si6->sin6_port = htons(port);
917#endif
918 }
919 else
920 break;
921 }
922 {
923 char buffer[STRERROR_LEN];
924 data->state.os_errno = sockerr = SOCKERRNO;
925 failf(data, "bind failed with errno %d: %s",
926 sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer)));
927 }
929 result = CURLE_INTERFACE_FAILED;
931out:
932 curlx_free(dev_in);
933 curlx_free(iface_in);
934 curlx_free(host_in);
935 return result;
936}
937#endif
939/*
940 * verifyconnect() returns TRUE if the connect really has happened.
941 */
942static bool verifyconnect(curl_socket_t sockfd, int *psockerr)
943{
944 bool rc = TRUE;
945#ifdef SO_ERROR
946 int sockerr = 0;
947 curl_socklen_t errSize = sizeof(sockerr);
949#ifdef _WIN32
950 /*
951 * In October 2003 we effectively nullified this function on Windows due to
952 * problems with it using all CPU in multi-threaded cases.
953 *
954 * In May 2004, we brought it back to offer more info back on connect
955 * failures. We could reproduce the former problems with this function, but
956 * could avoid them by adding this SleepEx() call below:
957 *
958 * "I do not have Rational Quantify, but the hint from his post was
959 * ntdll::NtRemoveIoCompletion(). I would assume the SleepEx (or maybe
960 * Sleep(0) would be enough?) would release whatever
961 * mutex/critical-section the ntdll call is waiting on.
962 *
963 * Someone got to verify this on Win-NT 4.0, 2000."
964 */
965 SleepEx(0, FALSE);
966#endif
968 if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errSize))
969 sockerr = SOCKERRNO;
970#if defined(EBADIOCTL) && defined(__minix)
971 /* Minix 3.1.x does not support getsockopt on UDP sockets */
972 if(EBADIOCTL == sockerr) {
973 SET_SOCKERRNO(0);
974 sockerr = 0;
975 }
976#endif
977 if((sockerr == 0) || (SOCKEISCONN == sockerr))
978 /* we are connected, awesome! */
979 rc = TRUE;
980 else
981 /* This was not a successful connect */
982 rc = FALSE;
983 if(psockerr)
984 *psockerr = sockerr;
985#else
986 (void)sockfd;
987 if(psockerr)
988 *psockerr = SOCKERRNO;
989#endif
990 return rc;
991}
993/**
994 * Determine the curl code for a socket connect() == -1 with errno.
995 */
996static CURLcode socket_connect_result(struct Curl_easy *data,
997 const char *ipaddress, int sockerr)
998{
999 if(sockerr == SOCKEINPROGRESS || SOCK_EAGAIN(sockerr))
1000 return CURLE_OK;
1002 /* unknown error, fallthrough and try another address! */
1003 {
1004 VERBOSE(char buffer[STRERROR_LEN]);
1005 infof(data, "Immediate connect fail for %s: %s", ipaddress,
1006 curlx_strerror(sockerr, buffer, sizeof(buffer)));
1007 NOVERBOSE((void)ipaddress);
1008 }
1009 data->state.os_errno = sockerr;
1010 /* connect failed */
1011 return CURLE_COULDNT_CONNECT;
1012}
1014struct cf_socket_ctx {
1015 struct Curl_peer *peer;
1016 struct Curl_sockaddr_ex addr; /* address to connect to */
1017 curl_socket_t sock; /* current attempt socket */
1018 struct ip_quadruple ip; /* The IP quadruple 2x(addr+port) */
1019 struct curltime started_at; /* when socket was created */
1020 struct curltime connected_at; /* when socket connected/got first byte */
1021 struct curltime first_byte_at; /* when first byte was recvd */
1022#ifdef USE_WINSOCK
1023 struct curltime last_sndbuf_query_at; /* when SO_SNDBUF last queried */
1024 ULONG sndbuf_size; /* the last set SO_SNDBUF size */
1025#endif
1026 int sockerr; /* socket error of last failure or 0 */
1027#ifdef DEBUGBUILD
1028 int connect_wait_ms; /* ms to wait after 1st connect() */
1029 int wblock_percent; /* percent of writes doing EAGAIN */
1030 int wpartial_percent; /* percent of bytes written in send */
1031 int rblock_percent; /* percent of reads doing EAGAIN */
1032 size_t recv_max; /* max enforced read size */
1033#endif
1034 uint8_t transport;
1035 BIT(got_first_byte); /* if first byte was received */
1036 BIT(listening); /* socket is listening */
1037 BIT(accepted); /* socket was accepted, not connected */
1038 BIT(sock_connected); /* socket is "connected", e.g. in UDP */
1039 BIT(active);
1040 BIT(stats_reported);
1041};
1043static CURLcode cf_socket_ctx_init(struct cf_socket_ctx *ctx,
1044 struct Curl_peer *peer,
1045 struct Curl_sockaddr_ex *addr,
1046 uint8_t transport)
1047{
1048 memset(ctx, 0, sizeof(*ctx));
1049 Curl_peer_link(&ctx->peer, peer);
1050 ctx->sock = CURL_SOCKET_BAD;
1051 ctx->transport = transport;
1052 ctx->addr = *addr;
1054#ifdef DEBUGBUILD
1055 {
1056 const char *p = getenv("CURL_DBG_SOCK_WBLOCK");
1057 if(p) {
1058 curl_off_t l;
1059 if(!curlx_str_number(&p, &l, 100))
1060 ctx->wblock_percent = (int)l;
1061 }
1062 p = getenv("CURL_DBG_SOCK_WPARTIAL");
1063 if(p) {
1064 curl_off_t l;
1065 if(!curlx_str_number(&p, &l, 100))
1066 ctx->wpartial_percent = (int)l;
1067 }
1068 p = getenv("CURL_DBG_SOCK_RBLOCK");
1069 if(p) {
1070 curl_off_t l;
1071 if(!curlx_str_number(&p, &l, 100))
1072 ctx->rblock_percent = (int)l;
1073 }
1074 p = getenv("CURL_DBG_SOCK_RMAX");
1075 if(p) {
1076 curl_off_t l;
1077 if(!curlx_str_number(&p, &l, CURL_OFF_T_MAX))
1078 ctx->recv_max = (size_t)l;
1079 }
1080 p = getenv("CURL_DBG_SOCK_CONNECT_WAIT_MS");
1081 if(p) {
1082 curl_off_t l;
1083 if(!curlx_str_number(&p, &l, INT_MAX))
1084 ctx->connect_wait_ms = (int)l;
1085 }
1086 }
1087#endif
1089 return CURLE_OK;
1090}
1092static void cf_socket_ctx_free(struct cf_socket_ctx *ctx)
1093{
1094 if(ctx) {
1095 Curl_peer_unlink(&ctx->peer);
1096 curlx_free(ctx);
1097 }
1098}
1100static CURLcode cf_socket_shutdown(struct Curl_cfilter *cf,
1101 struct Curl_easy *data,
1102 bool *done)
1103{
1104 if(cf->connected) {
1105 struct cf_socket_ctx *ctx = cf->ctx;
1107 CURL_TRC_CF(data, cf, "cf_socket_shutdown, fd=%" FMT_SOCKET_T, ctx->sock);
1108 /* On TCP, and when the socket looks well and non-blocking mode
1109 * can be enabled, receive dangling bytes before close to avoid
1110 * entering RST states unnecessarily. */
1111 if(ctx->sock != CURL_SOCKET_BAD &&
1112 ctx->transport == TRNSPRT_TCP &&
1113 (curlx_nonblock(ctx->sock, TRUE) >= 0)) {
1114 unsigned char buf[1024];
1115 (void)sread(ctx->sock, buf, sizeof(buf));
1116 }
1117 }
1118 *done = TRUE;
1119 return CURLE_OK;
1120}
1122static void cf_socket_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
1123{
1124 struct cf_socket_ctx *ctx = cf->ctx;
1126 CURL_TRC_CF(data, cf, "destroy");
1127 if(ctx) {
1128 if(ctx->sock != CURL_SOCKET_BAD) {
1129 CURL_TRC_CF(data, cf, "cf_socket_close, fd=%" FMT_SOCKET_T, ctx->sock);
1130 if(ctx->sock == cf->conn->sock[cf->sockindex])
1131 cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD;
1132 socket_close(data, cf->conn, !ctx->accepted, ctx->sock);
1133 }
1134 cf_socket_ctx_free(ctx);
1135 }
1136}
1138static void set_local_ip(struct Curl_cfilter *cf,
1139 struct Curl_easy *data)
1140{
1141 struct cf_socket_ctx *ctx = cf->ctx;
1142 ctx->ip.local_ip[0] = 0;
1143 ctx->ip.local_port = 0;
1145#ifdef HAVE_GETSOCKNAME
1146 if((ctx->sock != CURL_SOCKET_BAD) &&
1147 !(data->conn->scheme->protocol & CURLPROTO_TFTP)) {
1148 /* TFTP does not connect, so it cannot get the IP like this */
1149 struct Curl_sockaddr_storage ssloc;
1150 curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage);
1152 memset(&ssloc, 0, sizeof(ssloc));
1153 if(getsockname(ctx->sock, (struct sockaddr *)&ssloc, &slen)) {
1154 VERBOSE(char buffer[STRERROR_LEN]);
1155 VERBOSE(int sockerr = SOCKERRNO);
1156 infof(data, "getsockname() failed with errno %d: %s",
1157 sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer)));
1158 }
1159 else {
1160 CURLcode result = sockaddr2string((struct sockaddr *)&ssloc, slen,
1161 ctx->ip.local_ip, &ctx->ip.local_port);
1162 if(result)
1163 infof(data, "ssloc inet_ntop() failed with %d", (int)result);
1164 }
1165 }
1166#else
1167 (void)data;
1168#endif
1169}
1171static CURLcode set_remote_ip(struct Curl_cfilter *cf,
1172 struct Curl_easy *data)
1173{
1174 struct cf_socket_ctx *ctx = cf->ctx;
1175 CURLcode result;
1177 /* store remote address and port used in this connection attempt */
1178 ctx->ip.transport = ctx->transport;
1179 result = sockaddr2string(&ctx->addr.curl_sa_addr,
1180 (curl_socklen_t)ctx->addr.addrlen,
1181 ctx->ip.remote_ip, &ctx->ip.remote_port);
1182 if(result) {
1183 ctx->sockerr = SOCKEAFNOSUPPORT;
1184 /* malformed address or bug in inet_ntop, try next address */
1185 failf(data, "curl_sa_addr inet_ntop() failed with %d", (int)result);
1186 return CURLE_FAILED_INIT;
1187 }
1188 return CURLE_OK;
1189}
1191/* to figure out the type of the socket safely, remove the possibly ORed
1192 bits before comparing */
1193static int cf_socktype(int x)
1194{
1195#ifdef SOCK_CLOEXEC
1196 x &= ~SOCK_CLOEXEC;
1197#endif
1198#ifdef CURL_USE_SOCK_NONBLOCK
1199 x &= ~SOCK_NONBLOCK;
1200#endif
1201 return x;
1202}
1204#ifdef _WIN32
1205/* Offered by mingw-w64 v10+, MS SDK 8.0/~VS2012+ */
1206#ifndef SIO_TCP_INITIAL_RTO
1207#define SIO_TCP_INITIAL_RTO _WSAIOW(IOC_VENDOR, 17)
1208#define TCP_INITIAL_RTO_DEFAULT_RTT 0
1210/* !checksrc! disable TYPEDEFSTRUCT 1 */
1211typedef struct _TCP_INITIAL_RTO_PARAMETERS {
1212 USHORT Rtt;
1213 UCHAR MaxSynRetransmissions;
1214} TCP_INITIAL_RTO_PARAMETERS;
1215#endif /* SIO_TCP_INITIAL_RTO */
1217#ifndef TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS
1218#define TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS 0xFE /* -2 */
1219#endif
1221static bool targets_localhost(struct cf_socket_ctx *ctx)
1222{
1223 return (((ctx->addr.family == AF_INET) &&
1224 !strcmp(ctx->ip.remote_ip, "127.0.0.1")) ||
1225 ((ctx->addr.family == AF_INET6) &&
1226 !strcmp(ctx->ip.remote_ip, "::1")));
1227}
1229/* disable TCP SYN retransmissions for localhost connection on Windows to
1230 detect problems faster */
1231static void tcplocalhost(struct Curl_cfilter *cf,
1232 curl_socket_t sockfd)
1233{
1234 if(targets_localhost(cf->ctx)) {
1235 TCP_INITIAL_RTO_PARAMETERS rto;
1236 DWORD bytes = 0;
1237 memset(&rto, 0, sizeof(rto));
1238 rto.Rtt = TCP_INITIAL_RTO_DEFAULT_RTT;
1239 /* Windows 10, version 1709 (10.0.16299) and later versions can set max
1240 retransmissions to zero, earlier versions could only set 1 */
1241 if(curlx_verify_windows_version(10, 0, 16299, PLATFORM_WINNT,
1242 VERSION_GREATER_THAN_EQUAL))
1243 rto.MaxSynRetransmissions = TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS;
1244 else
1245 rto.MaxSynRetransmissions = 1;
1246 (void)WSAIoctl(sockfd, SIO_TCP_INITIAL_RTO, &rto, sizeof(rto),
1247 NULL, 0, &bytes, NULL, NULL);
1248 }
1249}
1250#else
1251#define tcplocalhost(x, y)
1252#endif /* _WIN32 */
1254static CURLcode cf_socket_open(struct Curl_cfilter *cf,
1255 struct Curl_easy *data)
1256{
1257 struct cf_socket_ctx *ctx = cf->ctx;
1258 int error = 0;
1259 bool isconnected = FALSE;
1260 CURLcode result = CURLE_COULDNT_CONNECT;
1261 bool is_tcp;
1263 DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD);
1264 ctx->started_at = *Curl_pgrs_now(data);
1265#ifdef CURL_USE_SOCK_NONBLOCK
1266 /* Do not tuck SOCK_NONBLOCK into socktype when opensocket callback is set
1267 * because we would not know how socktype is about to be used in the
1268 * callback, SOCK_NONBLOCK might get factored out before calling socket().
1269 */
1270 if(!data->set.fopensocket)
1271 ctx->addr.socktype |= SOCK_NONBLOCK;
1272#endif
1273 result = socket_open(data, &ctx->addr, &ctx->sock);
1274#ifdef CURL_USE_SOCK_NONBLOCK
1275 /* Restore the socktype after the socket is created. */
1276 if(!data->set.fopensocket)
1277 ctx->addr.socktype &= ~SOCK_NONBLOCK;
1278#endif
1279 if(result)
1280 goto out;
1282 result = set_remote_ip(cf, data);
1283 if(result)
1284 goto out;
1286#ifdef USE_IPV6
1287 if(ctx->addr.family == AF_INET6) {
1288#ifdef USE_WINSOCK
1289 /* Turn on support for IPv4-mapped IPv6 addresses.
1290 * Linux kernel, NetBSD, FreeBSD, Darwin, lwIP: default is off;
1291 * Windows Vista and later: default is on;
1292 * DragonFly BSD: acts like off, and dummy setting;
1293 * OpenBSD and earlier Windows: unsupported.
1294 * Linux: controlled by /proc/sys/net/ipv6/bindv6only.
1295 */
1296 int on = 0;
1297 (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_V6ONLY,
1298 (void *)&on, sizeof(on));
1299#endif
1300#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
1301 {
1302 struct sockaddr_in6 *sa6 = (void *)&ctx->addr.curl_sa_addr;
1303 if(sa6->sin6_scope_id)
1304 infof(data, " Trying [%s]:%d scope_id=%lu...",
1305 ctx->ip.remote_ip, ctx->ip.remote_port,
1306 (unsigned long)sa6->sin6_scope_id);
1307 else
1308#endif
1309 infof(data, " Trying [%s]:%d...",
1310 ctx->ip.remote_ip, ctx->ip.remote_port);
1311#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
1312 }
1313#endif
1314 }
1315 else
1316#endif
1317 infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
1319#ifdef USE_IPV6
1320 is_tcp = (ctx->addr.family == AF_INET ||
1321 ctx->addr.family == AF_INET6) &&
1322 cf_socktype(ctx->addr.socktype) == SOCK_STREAM;
1323#else
1324 is_tcp = (ctx->addr.family == AF_INET) &&
1325 cf_socktype(ctx->addr.socktype) == SOCK_STREAM;
1326#endif
1327 if(is_tcp) {
1328 if(data->set.tcp_nodelay)
1329 tcpnodelay(cf, data, ctx->sock);
1331 if(data->set.tcp_keepalive)
1332 tcpkeepalive(cf, data, ctx->sock);
1334 tcplocalhost(cf, ctx->sock);
1335 }
1337 if(data->set.fsockopt) {
1338 /* activate callback for setting socket options */
1339 struct Curl_mapi_guard guard;
1340 CURL_CBAPI_START(&guard, data, easy_fsockopt);
1341 error = data->set.fsockopt(data->set.sockopt_client,
1342 ctx->sock,
1343 CURLSOCKTYPE_IPCXN);
1344 CURL_CBAPI_END(&guard);
1346 if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
1347 isconnected = TRUE;
1348 else if(error) {
1349 result = CURLE_ABORTED_BY_CALLBACK;
1350 goto out;
1351 }
1352 }
1354#ifndef CURL_DISABLE_BINDLOCAL
1355 /* possibly bind the local end to an IP, interface or port */
1356 if(ctx->addr.family == AF_INET
1357#ifdef USE_IPV6
1358 || ctx->addr.family == AF_INET6
1359#endif
1360 ) {
1361 result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family,
1362 Curl_ipv6_scope(&ctx->addr.curl_sa_addr),
1363 ctx->transport);
1364 if(result) {
1365 if(result == CURLE_UNSUPPORTED_PROTOCOL) {
1366 /* The address family is not supported on this interface.
1367 We can continue trying addresses */
1368 result = CURLE_COULDNT_CONNECT;
1369 }
1370 goto out;
1371 }
1372 }
1373#endif
1375#ifndef CURL_USE_SOCK_NONBLOCK
1376 /* Set socket non-blocking, must be a non-blocking socket for
1377 * a non-blocking connect. */
1378 error = curlx_nonblock(ctx->sock, TRUE);
1379 if(error < 0) {
1380 result = CURLE_UNSUPPORTED_PROTOCOL;
1381 ctx->sockerr = SOCKERRNO;
1382 goto out;
1383 }
1384#else
1385 if(data->set.fopensocket) {
1386 /* Set socket non-blocking, must be a non-blocking socket for
1387 * a non-blocking connect. */
1388 error = curlx_nonblock(ctx->sock, TRUE);
1389 if(error < 0) {
1390 result = CURLE_UNSUPPORTED_PROTOCOL;
1391 ctx->sockerr = SOCKERRNO;
1392 goto out;
1393 }
1394 }
1395#endif
1396 ctx->sock_connected = (cf_socktype(ctx->addr.socktype) != SOCK_DGRAM);
1397out:
1398 if(result) {
1399 if(ctx->sock != CURL_SOCKET_BAD) {
1400 socket_close(data, cf->conn, TRUE, ctx->sock);
1401 ctx->sock = CURL_SOCKET_BAD;
1402 }
1403 }
1404 else if(isconnected) {
1405 set_local_ip(cf, data);
1406 ctx->connected_at = *Curl_pgrs_now(data);
1407 cf->connected = TRUE;
1408 }
1409 CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" FMT_SOCKET_T,
1410 (int)result, ctx->sock);
1411 return result;
1412}
1414static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data,
1415 bool is_tcp_fastopen)
1416{
1417 struct cf_socket_ctx *ctx = cf->ctx;
1418#ifdef TCP_FASTOPEN_CONNECT
1419 int optval = 1;
1420#endif
1421 int rc = -1;
1423 (void)data;
1424 if(is_tcp_fastopen) {
1425#ifdef CONNECT_DATA_IDEMPOTENT /* Darwin */
1426# ifdef HAVE_BUILTIN_AVAILABLE
1427 /* while connectx function is available since macOS 10.11 / iOS 9,
1428 it did not have the interface declared correctly until
1429 Xcode 9 / macOS SDK 10.13 */
1430 if(__builtin_available(macOS 10.11, iOS 9, tvOS 9, watchOS 2, *)) {
1431 sa_endpoints_t endpoints;
1432 endpoints.sae_srcif = 0;
1433 endpoints.sae_srcaddr = NULL;
1434 endpoints.sae_srcaddrlen = 0;
1435 endpoints.sae_dstaddr = &ctx->addr.curl_sa_addr;
1436 endpoints.sae_dstaddrlen = ctx->addr.addrlen;
1438 rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY,
1439 CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
1440 NULL, 0, NULL, NULL);
1441 }
1442 else {
1443 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen);
1444 }
1445# else
1446 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen);
1447# endif /* HAVE_BUILTIN_AVAILABLE */
1448#elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
1449 if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
1450 (void *)&optval, sizeof(optval)) < 0)
1451 CURL_TRC_CF(data, cf, "Failed to enable TCP Fast Open on fd %"
1452 FMT_SOCKET_T, ctx->sock);
1454 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen);
1455#elif defined(MSG_FASTOPEN) /* old Linux */
1456 if(Curl_conn_is_ssl(cf->conn, cf->sockindex))
1457 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr, ctx->addr.addrlen);
1458 else
1459 rc = 0; /* Do nothing */
1460#endif
1461 }
1462 else {
1463 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr,
1464 (curl_socklen_t)ctx->addr.addrlen);
1465 }
1466 return rc;
1467}
1469static CURLcode cf_tcp_connect(struct Curl_cfilter *cf,
1470 struct Curl_easy *data,
1471 bool *done)
1472{
1473 struct cf_socket_ctx *ctx = cf->ctx;
1474 CURLcode result = CURLE_COULDNT_CONNECT;
1475 int rc = 0;
1477 if(cf->connected) {
1478 *done = TRUE;
1479 return CURLE_OK;
1480 }
1482 *done = FALSE; /* a negative world view is best */
1483 if(ctx->sock == CURL_SOCKET_BAD) {
1484 int sockerr;
1486 result = cf_socket_open(cf, data);
1487 if(result)
1488 goto out;
1490 if(cf->connected) {
1491 *done = TRUE;
1492 return CURLE_OK;
1493 }
1495 /* Connect TCP socket */
1496 rc = do_connect(cf, data, (bool)cf->conn->bits.tcp_fastopen);
1497 sockerr = SOCKERRNO;
1498 set_local_ip(cf, data);
1499 CURL_TRC_CF(data, cf, "local address %s port %d",
1500 ctx->ip.local_ip, ctx->ip.local_port);
1501#ifdef DEBUGBUILD
1502 if(ctx->connect_wait_ms > 0) {
1503 CURL_TRC_CF(data, cf, "debug connect wait %d ms", ctx->connect_wait_ms);
1504 curlx_wait_ms(ctx->connect_wait_ms);
1505 }
1506#endif
1507 if(rc == -1) {
1508 ctx->sockerr = sockerr;
1509 result = socket_connect_result(data, ctx->ip.remote_ip, sockerr);
1510 goto out;
1511 }
1512 }
1514#ifdef mpeix
1515 /* Call this function once now, and ignore the results. We do this to
1516 "clear" the error state on the socket so that we can later read it
1517 reliably. This is reported necessary on the MPE/iX operating
1518 system. */
1519 (void)verifyconnect(ctx->sock, NULL);
1520#endif
1521 /* check socket for connect */
1522 rc = SOCKET_WRITABLE(ctx->sock, 0);
1524 if(rc == 0) { /* no connection yet */
1525 CURL_TRC_CF(data, cf, "not connected yet on fd=%" FMT_SOCKET_T, ctx->sock);
1526 return CURLE_OK;
1527 }
1528 else if(rc == CURL_CSELECT_OUT ||
1529#ifdef __APPLE__
1530 /* macOS reports select errors when the peer already
1531 * sent us data and closed the connection normally. Do
1532 * not treat that as error. See #23482 and #23445 */
1533 (rc > 0 && (rc & CURL_CSELECT_ERR)) ||
1534#endif
1535 cf->conn->bits.tcp_fastopen) {
1536 if(verifyconnect(ctx->sock, &ctx->sockerr)) {
1537 /* we are connected with TCP, awesome! */
1538 ctx->connected_at = *Curl_pgrs_now(data);
1539 set_local_ip(cf, data);
1540 *done = TRUE;
1541 cf->connected = TRUE;
1542 CURL_TRC_CF(data, cf, "connected on fd=%" FMT_SOCKET_T, ctx->sock);
1543 return CURLE_OK;
1544 }
1545 result = CURLE_COULDNT_CONNECT;
1546 }
1547 else if(rc & CURL_CSELECT_ERR) {
1548 CURL_TRC_CF(data, cf, "poll/select error on fd=%" FMT_SOCKET_T, ctx->sock);
1549 (void)verifyconnect(ctx->sock, &ctx->sockerr);
1550 result = CURLE_COULDNT_CONNECT;
1551 }
1553out:
1554 if(result) {
1555 VERBOSE(char buffer[STRERROR_LEN]);
1556 set_local_ip(cf, data);
1557 if(ctx->sockerr) {
1558 data->state.os_errno = ctx->sockerr;
1559 SET_SOCKERRNO(ctx->sockerr);
1560 VERBOSE(curlx_strerror(ctx->sockerr, buffer, sizeof(buffer)));
1561 }
1562 else {
1563 VERBOSE(curlx_strcopy(buffer, sizeof(buffer), STRCONST("peer closed")));
1564 }
1565 if(ctx->sock != CURL_SOCKET_BAD) {
1566 socket_close(data, cf->conn, TRUE, ctx->sock);
1567 ctx->sock = CURL_SOCKET_BAD;
1568 }
1569 infof(data, "connect to %s port %u from %s port %d failed: %s",
1570 ctx->ip.remote_ip, ctx->ip.remote_port,
1571 ctx->ip.local_ip, ctx->ip.local_port,
1572 curlx_strerror(ctx->sockerr, buffer, sizeof(buffer)));
1573 *done = FALSE;
1574 }
1575 return result;
1576}
1578static CURLcode cf_socket_adjust_pollset(struct Curl_cfilter *cf,
1579 struct Curl_easy *data,
1580 struct easy_pollset *ps)
1581{
1582 struct cf_socket_ctx *ctx = cf->ctx;
1583 CURLcode result = CURLE_OK;
1585 if(ctx->sock != CURL_SOCKET_BAD) {
1586 /* A listening socket filter needs to be connected before the accept
1587 * for some weird FTP interaction. This should be rewritten, so that
1588 * FTP no longer does the socket checks and accept calls and delegates
1589 * all that to the filter. */
1590 if(ctx->listening) {
1591 result = Curl_pollset_set_in_only(data, ps, ctx->sock);
1592 CURL_TRC_CF(data, cf, "adjust_pollset, listening, POLLIN fd=%"
1593 FMT_SOCKET_T, ctx->sock);
1594 }
1595 else if(!cf->connected) {
1596 result = Curl_pollset_set_out_only(data, ps, ctx->sock);
1597 CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%"
1598 FMT_SOCKET_T, ctx->sock);
1599 }
1600 else if(!ctx->active) {
1601 result = Curl_pollset_add_in(data, ps, ctx->sock);
1602 CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%"
1603 FMT_SOCKET_T, ctx->sock);
1604 }
1605 }
1606 return result;
1607}
1609#ifdef USE_WINSOCK
1611/* Offered by mingw-w64 v13+, MS SDK 7.0A/VS2010+ */
1612#ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
1613#define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
1614#endif
1616static void win_update_sndbuf_size(struct Curl_easy *data,
1617 struct cf_socket_ctx *ctx)
1618{
1619 ULONG ideal;
1620 DWORD ideallen;
1622 if(curlx_ptimediff_ms(Curl_pgrs_now(data),
1623 &ctx->last_sndbuf_query_at) > 1000) {
1624 if(!WSAIoctl(ctx->sock, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
1625 &ideal, sizeof(ideal), &ideallen, 0, 0) &&
1626 ideal != ctx->sndbuf_size &&
1627 !setsockopt(ctx->sock, SOL_SOCKET, SO_SNDBUF,
1628 (const char *)&ideal, sizeof(ideal))) {
1629 ctx->sndbuf_size = ideal;
1630 }
1631 ctx->last_sndbuf_query_at = *Curl_pgrs_now(data);
1632 }
1633}
1635#endif /* USE_WINSOCK */
1637static CURLcode cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data,
1638 const uint8_t *buf, size_t len, bool eos,
1639 size_t *pnwritten)
1640{
1641 struct cf_socket_ctx *ctx = cf->ctx;
1642 curl_socket_t fdsave;
1643 ssize_t rv;
1644 CURLcode result = CURLE_OK;
1645 VERBOSE(size_t orig_len = len);
1647 (void)eos;
1648 *pnwritten = 0;
1649 fdsave = cf->conn->sock[cf->sockindex];
1650 cf->conn->sock[cf->sockindex] = ctx->sock;
1652#ifdef DEBUGBUILD
1653 /* simulate network blocking/partial writes */
1654 if(ctx->wblock_percent > 0) {
1655 unsigned char c = 0;
1656 Curl_rand_bytes(data, FALSE, &c, 1);
1657 if(c >= ((100 - ctx->wblock_percent) * 256 / 100)) {
1658 CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len);
1659 cf->conn->sock[cf->sockindex] = fdsave;
1660 return CURLE_AGAIN;
1661 }
1662 }
1663 if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) {
1664 len = len * ctx->wpartial_percent / 100;
1665 if(!len)
1666 len = 1;
1667 CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes",
1668 orig_len, len);
1669 }
1670#endif
1672#if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
1673 if(cf->conn->bits.tcp_fastopen) {
1674 rv = sendto(ctx->sock, buf, len, MSG_FASTOPEN,
1675 &ctx->addr.curl_sa_addr, ctx->addr.addrlen);
1676 cf->conn->bits.tcp_fastopen = FALSE;
1677 }
1678 else
1679#endif
1680 rv = swrite(ctx->sock, buf, len);
1682 if(!curlx_sztouz(rv, pnwritten)) {
1683 int sockerr = SOCKERRNO;
1684 if(SOCK_EAGAIN(sockerr)
1685#ifndef USE_WINSOCK
1686 || (sockerr == SOCKEINTR) || (sockerr == SOCKEINPROGRESS)
1687#endif
1688 ) {
1689 result = CURLE_AGAIN; /* EWOULDBLOCK */
1690 }
1691 else {
1692 char buffer[STRERROR_LEN];
1693 failf(data, "Send failure: %s",
1694 curlx_strerror(sockerr, buffer, sizeof(buffer)));
1695 data->state.os_errno = sockerr;
1696 result = CURLE_SEND_ERROR;
1697 }
1698 }
1700#ifdef USE_WINSOCK
1701 if(!result)
1702 win_update_sndbuf_size(data, ctx);
1703#endif
1705 CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, %zu",
1706 orig_len, (int)result, *pnwritten);
1707 cf->conn->sock[cf->sockindex] = fdsave;
1708 return result;
1709}
1711static CURLcode cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
1712 char *buf, size_t len, size_t *pnread)
1713{
1714 struct cf_socket_ctx *ctx = cf->ctx;
1715 CURLcode result = CURLE_OK;
1716 ssize_t rv;
1718 *pnread = 0;
1719#ifdef DEBUGBUILD
1720 /* simulate network blocking/partial reads */
1721 if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) {
1722 unsigned char c = 0;
1723 Curl_rand(data, &c, 1);
1724 if(c >= ((100 - ctx->rblock_percent) * 256 / 100)) {
1725 CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len);
1726 return CURLE_AGAIN;
1727 }
1728 }
1729 if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) {
1730 CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes",
1731 len, ctx->recv_max);
1732 len = ctx->recv_max;
1733 }
1734#endif
1736 rv = sread(ctx->sock, buf, len);
1738 if(!curlx_sztouz(rv, pnread)) {
1739 int sockerr = SOCKERRNO;
1740 if(SOCK_EAGAIN(sockerr)
1741#ifndef USE_WINSOCK
1742 || (sockerr == SOCKEINTR)
1743#endif
1744 ) {
1745 result = CURLE_AGAIN; /* EWOULDBLOCK */
1746 }
1747 else {
1748 char buffer[STRERROR_LEN];
1749 failf(data, "Recv failure: %s",
1750 curlx_strerror(sockerr, buffer, sizeof(buffer)));
1751 data->state.os_errno = sockerr;
1752 result = CURLE_RECV_ERROR;
1753 }
1754 }
1756 CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, %zu", len, (int)result, *pnread);
1757 if(!result && !ctx->got_first_byte) {
1758 ctx->first_byte_at = *Curl_pgrs_now(data);
1759 ctx->got_first_byte = TRUE;
1760 }
1761 return result;
1762}
1764static void cf_socket_update_data(struct Curl_cfilter *cf,
1765 struct Curl_easy *data)
1766{
1767 /* Update the IP info held in the transfer, if we have that. */
1768 if(cf->connected && (cf->sockindex == FIRSTSOCKET)) {
1769 struct cf_socket_ctx *ctx = cf->ctx;
1770 data->info.primary = ctx->ip;
1771 }
1772}
1774static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data)
1775{
1776 struct cf_socket_ctx *ctx = cf->ctx;
1778 /* use this socket from now on */
1779 cf->conn->sock[cf->sockindex] = ctx->sock;
1780 set_local_ip(cf, data);
1781#ifdef USE_IPV6
1782 if(cf->sockindex == FIRSTSOCKET)
1783 cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6);
1784#endif
1785 ctx->active = TRUE;
1786}
1788static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf,
1789 struct Curl_easy *data,
1790 int event, int arg1, void *arg2)
1791{
1792 struct cf_socket_ctx *ctx = cf->ctx;
1794 (void)arg1;
1795 (void)arg2;
1796 switch(event) {
1797 case CF_CTRL_CONN_INFO_UPDATE:
1798 cf_socket_active(cf, data);
1799 cf_socket_update_data(cf, data);
1800 break;
1801 case CF_CTRL_DATA_SETUP:
1802 cf_socket_update_data(cf, data);
1803 break;
1804 case CF_CTRL_FORGET_SOCKET:
1805 ctx->sock = CURL_SOCKET_BAD;
1806 break;
1807 case CF_CTRL_REPORT_STATS:
1808 if(cf->connected && !ctx->stats_reported) {
1809 struct curltime *ts = NULL;
1810 switch(ctx->transport) {
1811 case TRNSPRT_UDP:
1812 case TRNSPRT_QUIC:
1813 /* Since UDP connected sockets work different from TCP, we use the
1814 * time of the first byte from the peer as the "connect" time. */
1815 if(ctx->got_first_byte)
1816 ts = &ctx->first_byte_at;
1817 break;
1818 default:
1819 ts = &ctx->connected_at;
1820 break;
1821 }
1822 if(ts) {
1823 Curl_pgrsTimeWas(data, TIMER_CONNECT, *ts);
1824 ctx->stats_reported = TRUE;
1825 }
1826 }
1827 }
1828 return CURLE_OK;
1829}
1831static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf,
1832 struct Curl_easy *data,
1833 bool *input_pending)
1834{
1835 struct cf_socket_ctx *ctx = cf->ctx;
1836 struct pollfd pfd[1];
1837 int r;
1839 *input_pending = FALSE;
1841 if(!ctx || ctx->sock == CURL_SOCKET_BAD)
1842 return FALSE;
1844 /* Check with 0 timeout if there are any events pending on the socket */
1845 pfd[0].fd = ctx->sock;
1846 pfd[0].events = POLLRDNORM | POLLIN | POLLRDBAND | POLLPRI;
1847 pfd[0].revents = 0;
1849 r = Curl_poll(pfd, 1, 0);
1850 if(r < 0) {
1851 CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead");
1852 return FALSE;
1853 }
1854 else if(r == 0) {
1855 CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive");
1856 return TRUE;
1857 }
1858 else if(pfd[0].revents & (POLLERR | POLLHUP | POLLPRI | POLLNVAL)) {
1859 CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead");
1860 return FALSE;
1861 }
1863 CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive");
1864 *input_pending = TRUE;
1865 return TRUE;
1866}
1868static CURLcode cf_socket_query(struct Curl_cfilter *cf,
1869 struct Curl_easy *data,
1870 int query, int *pres1, void *pres2)
1871{
1872 struct cf_socket_ctx *ctx = cf->ctx;
1874 switch(query) {
1875 case CF_QUERY_SOCKET:
1876 DEBUGASSERT(pres2);
1877 *((curl_socket_t *)pres2) = ctx->sock;
1878 return CURLE_OK;
1879 case CF_QUERY_TRANSPORT:
1880 DEBUGASSERT(pres1);
1881 *pres1 = ctx->transport;
1882 return CURLE_OK;
1883 case CF_QUERY_REMOTE_ADDR:
1884 DEBUGASSERT(pres2);
1885 *((const struct Curl_sockaddr_ex **)pres2) = cf->connected ?
1886 &ctx->addr : NULL;
1887 return CURLE_OK;
1888 case CF_QUERY_CONNECT_REPLY_MS:
1889 if(ctx->got_first_byte) {
1890 timediff_t ms = curlx_ptimediff_ms(&ctx->first_byte_at,
1891 &ctx->started_at);
1892 *pres1 = (ms < INT_MAX) ? (int)ms : INT_MAX;
1893 }
1894 else
1895 *pres1 = -1;
1896 return CURLE_OK;
1897 case CF_QUERY_IP_INFO:
1898#ifdef USE_IPV6
1899 *pres1 = (ctx->addr.family == AF_INET6);
1900#else
1901 *pres1 = FALSE;
1902#endif
1903 *(struct ip_quadruple *)pres2 = ctx->ip;
1904 return CURLE_OK;
1905 case CF_QUERY_REALLY_CONNECTED:
1906 if(cf->cft != &Curl_cft_udp)
1907 *pres1 = cf->connected;
1908 else
1909 *pres1 = ctx->got_first_byte;
1910 return CURLE_OK;
1911 default:
1912 break;
1913 }
1914 return cf->next ?
1915 cf->next->cft->query(cf->next, data, query, pres1, pres2) :
1916 CURLE_UNKNOWN_OPTION;
1917}
1919struct Curl_cftype Curl_cft_tcp = {
1920 "TCP",
1921 CF_TYPE_IP_CONNECT,
1922 CURL_LOG_LVL_NONE,
1923 cf_socket_destroy,
1924 cf_tcp_connect,
1925 cf_socket_shutdown,
1926 cf_socket_adjust_pollset,
1927 Curl_cf_def_data_pending,
1928 cf_socket_send,
1929 cf_socket_recv,
1930 cf_socket_cntrl,
1931 cf_socket_conn_is_alive,
1932 Curl_cf_def_conn_keep_alive,
1933 cf_socket_query,
1934};
1936CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
1937 struct Curl_easy *data,
1938 struct Curl_peer *origin,
1939 struct Curl_peer *peer,
1940 uint8_t transport_peer,
1941 struct connectdata *conn,
1942 struct Curl_sockaddr_ex *addr,
1943 struct Curl_peer *tunnel_peer,
1944 uint8_t tunnel_transport)
1945{
1946 struct cf_socket_ctx *ctx = NULL;
1947 struct Curl_cfilter *cf = NULL;
1948 CURLcode result;
1950 (void)data;
1951 (void)origin;
1952 (void)conn;
1953 (void)tunnel_peer;
1954 (void)tunnel_transport;
1955 DEBUGASSERT(transport_peer == TRNSPRT_TCP);
1956 if(!addr) {
1957 result = CURLE_BAD_FUNCTION_ARGUMENT;
1958 goto out;
1959 }
1961 ctx = curlx_calloc(1, sizeof(*ctx));
1962 if(!ctx) {
1963 result = CURLE_OUT_OF_MEMORY;
1964 goto out;
1965 }
1967 result = cf_socket_ctx_init(ctx, peer, addr, transport_peer);
1968 if(result)
1969 goto out;
1971 result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx);
1973out:
1974 *pcf = (!result) ? cf : NULL;
1975 if(result) {
1976 curlx_safefree(cf);
1977 cf_socket_ctx_free(ctx);
1978 }
1980 return result;
1981}
1983#ifdef __linux__
1984static void linux_quic_mtu(struct cf_socket_ctx *ctx)
1985{
1986 int val;
1987 switch(ctx->addr.family) {
1988#ifdef IP_MTU_DISCOVER
1989 case AF_INET:
1990 val = IP_PMTUDISC_DO;
1991 (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val,
1992 sizeof(val));
1993 break;
1994#endif
1995#ifdef IPV6_MTU_DISCOVER
1996 case AF_INET6:
1997 val = IPV6_PMTUDISC_DO;
1998 (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
1999 sizeof(val));
2000 break;
2001#endif
2002 }
2003}
2004#else
2005#define linux_quic_mtu(x)
2006#endif
2008#if defined(UDP_GRO) && \
2009 (defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG)) && \
2010 ((defined(USE_NGTCP2) && defined(USE_NGHTTP3)) || defined(USE_QUICHE))
2011static void linux_quic_gro(struct cf_socket_ctx *ctx)
2012{
2013 int one = 1;
2014 (void)setsockopt(ctx->sock, IPPROTO_UDP, UDP_GRO, &one,
2015 (socklen_t)sizeof(one));
2016}
2017#else
2018#define linux_quic_gro(x)
2019#endif
2021#if (defined(__linux__) || defined(__APPLE__)) && defined(IP_RECVTOS)
2022static void linux_quic_ecn(struct cf_socket_ctx *ctx)
2023{
2024 unsigned int tos = 1;
2025 switch(ctx->addr.family) {
2026 case AF_INET:
2027 (void)setsockopt(ctx->sock, IPPROTO_IP, IP_RECVTOS, &tos, sizeof(tos));
2028 break;
2029#ifdef IPV6_RECVTCLASS
2030 case AF_INET6:
2031 (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_RECVTCLASS,
2032 &tos, sizeof(tos));
2033 break;
2034#endif
2035 }
2036}
2037#else
2038#define linux_quic_ecn(x)
2039#endif
2041#if (defined(__linux__) || defined(__APPLE__)) && defined(IP_DONTFRAG)
2042static void linux_ip_dontfrag(struct cf_socket_ctx *ctx)
2043{
2044 int val = 1;
2046 switch(ctx->addr.family) {
2047 case AF_INET:
2048 (void)setsockopt(ctx->sock, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val));
2049 break;
2050#ifdef IPV6_DONTFRAG
2051 case AF_INET6:
2052 (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_DONTFRAG,
2053 &val, sizeof(val));
2054 break;
2055#endif
2056 }
2057}
2058#else
2059#define linux_ip_dontfrag(x)
2060#endif
2062static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf,
2063 struct Curl_easy *data)
2064{
2065 struct cf_socket_ctx *ctx = cf->ctx;
2066 int rc;
2068 /* QUIC needs a connected socket, nonblocking */
2069 DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD);
2071 /* error: The 1st argument to 'connect' is -1 but should be >= 0
2072 NOLINTNEXTLINE(clang-analyzer-unix.StdCLibraryFunctions) */
2073 rc = connect(ctx->sock, &ctx->addr.curl_sa_addr,
2074 (curl_socklen_t)ctx->addr.addrlen);
2075 if(rc == -1) {
2076 return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO);
2077 }
2078 ctx->sock_connected = TRUE;
2079 set_local_ip(cf, data);
2080 CURL_TRC_CF(data, cf, "%s socket %" FMT_SOCKET_T
2081 " connected: [%s:%d] -> [%s:%d]",
2082 (ctx->transport == TRNSPRT_QUIC) ? "QUIC" : "UDP",
2083 ctx->sock, ctx->ip.local_ip, ctx->ip.local_port,
2084 ctx->ip.remote_ip, ctx->ip.remote_port);
2086 /* Currently, cf->ctx->sock is always non-blocking because the only
2087 * caller to cf_udp_setup_quic() is cf_udp_connect() that passes the
2088 * non-blocking socket created by cf_socket_open() to it. Thus, we
2089 * do not need to call curlx_nonblock() in cf_udp_setup_quic() anymore.
2090 */
2091 linux_quic_ecn(ctx);
2092 linux_quic_mtu(ctx);
2093 linux_ip_dontfrag(ctx);
2094 linux_quic_gro(ctx);
2096 return CURLE_OK;
2097}
2099static CURLcode cf_udp_connect(struct Curl_cfilter *cf,
2100 struct Curl_easy *data,
2101 bool *done)
2102{
2103 struct cf_socket_ctx *ctx = cf->ctx;
2104 CURLcode result = CURLE_COULDNT_CONNECT;
2106 if(cf->connected) {
2107 *done = TRUE;
2108 return CURLE_OK;
2109 }
2111 *done = FALSE;
2112 if(ctx->sock == CURL_SOCKET_BAD) {
2113 result = cf_socket_open(cf, data);
2114 if(result) {
2115 CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d",
2116 (int)result);
2117 goto out;
2118 }
2120 if(ctx->transport == TRNSPRT_QUIC) {
2121 result = cf_udp_setup_quic(cf, data);
2122 if(result)
2123 goto out;
2124 CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
2125 FMT_SOCKET_T " (%s:%d)",
2126 ctx->sock, ctx->ip.local_ip, ctx->ip.local_port);
2127 }
2128 *done = TRUE;
2129 cf->connected = TRUE;
2130 }
2131out:
2132 return result;
2133}
2135struct Curl_cftype Curl_cft_udp = {
2136 "UDP",
2137 CF_TYPE_IP_CONNECT,
2138 CURL_LOG_LVL_NONE,
2139 cf_socket_destroy,
2140 cf_udp_connect,
2141 cf_socket_shutdown,
2142 cf_socket_adjust_pollset,
2143 Curl_cf_def_data_pending,
2144 cf_socket_send,
2145 cf_socket_recv,
2146 cf_socket_cntrl,
2147 cf_socket_conn_is_alive,
2148 Curl_cf_def_conn_keep_alive,
2149 cf_socket_query,
2150};
2152CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
2153 struct Curl_easy *data,
2154 struct Curl_peer *origin,
2155 struct Curl_peer *peer,
2156 uint8_t transport_peer,
2157 struct connectdata *conn,
2158 struct Curl_sockaddr_ex *addr,
2159 struct Curl_peer *tunnel_peer,
2160 uint8_t tunnel_transport)
2161{
2162 struct cf_socket_ctx *ctx = NULL;
2163 struct Curl_cfilter *cf = NULL;
2164 CURLcode result;
2166 (void)data;
2167 (void)origin;
2168 (void)conn;
2169 (void)tunnel_peer;
2170 (void)tunnel_transport;
2171 DEBUGASSERT(transport_peer == TRNSPRT_UDP || transport_peer == TRNSPRT_QUIC);
2172 ctx = curlx_calloc(1, sizeof(*ctx));
2173 if(!ctx) {
2174 result = CURLE_OUT_OF_MEMORY;
2175 goto out;
2176 }
2178 result = cf_socket_ctx_init(ctx, peer, addr, transport_peer);
2179 if(result)
2180 goto out;
2182 result = Curl_cf_create(&cf, &Curl_cft_udp, ctx);
2184out:
2185 *pcf = (!result) ? cf : NULL;
2186 if(result) {
2187 curlx_safefree(cf);
2188 cf_socket_ctx_free(ctx);
2189 }
2191 return result;
2192}
2194/* this is the TCP filter which can also handle this case */
2195struct Curl_cftype Curl_cft_unix = {
2196 "UNIX",
2197 CF_TYPE_IP_CONNECT,
2198 CURL_LOG_LVL_NONE,
2199 cf_socket_destroy,
2200 cf_tcp_connect,
2201 cf_socket_shutdown,
2202 cf_socket_adjust_pollset,
2203 Curl_cf_def_data_pending,
2204 cf_socket_send,
2205 cf_socket_recv,
2206 cf_socket_cntrl,
2207 cf_socket_conn_is_alive,
2208 Curl_cf_def_conn_keep_alive,
2209 cf_socket_query,
2210};
2212CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
2213 struct Curl_easy *data,
2214 struct Curl_peer *origin,
2215 struct Curl_peer *peer,
2216 uint8_t transport_peer,
2217 struct connectdata *conn,
2218 struct Curl_sockaddr_ex *addr,
2219 struct Curl_peer *tunnel_peer,
2220 uint8_t tunnel_transport)
2221{
2222 struct cf_socket_ctx *ctx = NULL;
2223 struct Curl_cfilter *cf = NULL;
2224 CURLcode result;
2226 (void)data;
2227 (void)origin;
2228 (void)conn;
2229 (void)tunnel_peer;
2230 (void)tunnel_transport;
2231 DEBUGASSERT(transport_peer == TRNSPRT_UNIX);
2232 ctx = curlx_calloc(1, sizeof(*ctx));
2233 if(!ctx) {
2234 result = CURLE_OUT_OF_MEMORY;
2235 goto out;
2236 }
2238 result = cf_socket_ctx_init(ctx, peer, addr, transport_peer);
2239 if(result)
2240 goto out;
2242 result = Curl_cf_create(&cf, &Curl_cft_unix, ctx);
2244out:
2245 *pcf = (!result) ? cf : NULL;
2246 if(result) {
2247 curlx_safefree(cf);
2248 cf_socket_ctx_free(ctx);
2249 }
2251 return result;
2252}
2254static timediff_t cf_tcp_accept_timeleft(struct Curl_cfilter *cf,
2255 struct Curl_easy *data)
2256{
2257 struct cf_socket_ctx *ctx = cf->ctx;
2258 timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT;
2259 timediff_t other_ms;
2261#ifndef CURL_DISABLE_FTP
2262 if(data->set.accepttimeout > 0)
2263 timeout_ms = data->set.accepttimeout;
2264#endif
2266 /* check if the generic timeout possibly is set shorter */
2267 other_ms = Curl_timeleft_ms(data);
2268 if(other_ms && (other_ms < timeout_ms))
2269 /* note that this also works fine for when other_ms happens to be negative
2270 due to it already having elapsed */
2271 timeout_ms = other_ms;
2272 else {
2273 /* subtract elapsed time */
2274 timeout_ms -= curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->started_at);
2275 if(!timeout_ms)
2276 /* avoid returning 0 as that means no timeout! */
2277 timeout_ms = -1;
2278 }
2279 return timeout_ms;
2280}
2282static void cf_tcp_set_accepted_remote_ip(struct Curl_cfilter *cf,
2283 struct Curl_easy *data)
2284{
2285 struct cf_socket_ctx *ctx = cf->ctx;
2286#ifdef HAVE_GETPEERNAME
2287 CURLcode result;
2288 struct Curl_sockaddr_storage ssrem;
2289 curl_socklen_t plen;
2291 ctx->ip.remote_ip[0] = 0;
2292 ctx->ip.remote_port = 0;
2293 plen = sizeof(ssrem);
2294 memset(&ssrem, 0, plen);
2295 if(getpeername(ctx->sock, (struct sockaddr *)&ssrem, &plen)) {
2296 char buffer[STRERROR_LEN];
2297 int sockerr = SOCKERRNO;
2298 failf(data, "getpeername() failed with errno %d: %s",
2299 sockerr, curlx_strerror(sockerr, buffer, sizeof(buffer)));
2300 return;
2301 }
2302 result = sockaddr2string((struct sockaddr *)&ssrem, plen,
2303 ctx->ip.remote_ip, &ctx->ip.remote_port);
2304 if(result) {
2305 failf(data, "ssrem inet_ntop() failed with %d", (int)result);
2306 return;
2307 }
2308#else
2309 ctx->ip.remote_ip[0] = 0;
2310 ctx->ip.remote_port = 0;
2311 (void)data;
2312#endif
2313}
2315static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
2316 struct Curl_easy *data,
2317 bool *done)
2318{
2319 struct cf_socket_ctx *ctx = cf->ctx;
2320 char errbuf[STRERROR_LEN];
2321#ifdef USE_IPV6
2322 struct Curl_sockaddr_storage add;
2323#else
2324 struct sockaddr_in add;
2325#endif
2326 curl_socklen_t size = (curl_socklen_t)sizeof(add);
2327 curl_socket_t s_accepted = CURL_SOCKET_BAD;
2328 timediff_t timeout_ms;
2329 int socketstate = 0;
2330 bool incoming = FALSE;
2332 /* we start accepted, if we ever close, we cannot go on */
2333 (void)data;
2334 if(cf->connected) {
2335 *done = TRUE;
2336 return CURLE_OK;
2337 }
2339 *done = FALSE;
2340 timeout_ms = cf_tcp_accept_timeleft(cf, data);
2341 if(timeout_ms < 0) {
2342 /* if a timeout was already reached, bail out */
2343 failf(data, "Accept timeout occurred while waiting server connect");
2344 return CURLE_FTP_ACCEPT_TIMEOUT;
2345 }
2347 CURL_TRC_CF(data, cf, "Checking for incoming on fd=%" FMT_SOCKET_T
2348 " ip=%s:%d", ctx->sock, ctx->ip.local_ip, ctx->ip.local_port);
2349 socketstate = SOCKET_READABLE(ctx->sock, 0);
2350 CURL_TRC_CF(data, cf, "socket_check -> %x", (unsigned int)socketstate);
2351 switch(socketstate) {
2352 case -1: /* error */
2353 /* let's die here */
2354 failf(data, "Error while waiting for server connect");
2355 return CURLE_FTP_ACCEPT_FAILED;
2356 default:
2357 if(socketstate & CURL_CSELECT_IN) {
2358 infof(data, "Ready to accept data connection from server");
2359 incoming = TRUE;
2360 }
2361 break;
2362 }
2364 if(!incoming) {
2365 CURL_TRC_CF(data, cf, "nothing heard from the server yet");
2366 return CURLE_OK;
2367 }
2369 size = sizeof(add);
2370#ifdef HAVE_ACCEPT4
2371 s_accepted = CURL_ACCEPT4(ctx->sock, (struct sockaddr *)&add, &size,
2372 SOCK_NONBLOCK | SOCK_CLOEXEC);
2373#else
2374 s_accepted = CURL_ACCEPT(ctx->sock, (struct sockaddr *)&add, &size);
2375#endif
2377 if(s_accepted == CURL_SOCKET_BAD) {
2378 failf(data, "Error accept()ing server connect: %s",
2379 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
2380 return CURLE_FTP_ACCEPT_FAILED;
2381 }
2382#ifndef HAVE_ACCEPT4
2383#ifdef HAVE_FCNTL
2384 if(fcntl(s_accepted, F_SETFD, FD_CLOEXEC) < 0) {
2385 failf(data, "fcntl set CLOEXEC: %s",
2386 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
2387 Curl_socket_close(data, cf->conn, s_accepted);
2388 return CURLE_FTP_ACCEPT_FAILED;
2389 }
2390#endif /* HAVE_FCNTL */
2391 if(curlx_nonblock(s_accepted, TRUE) < 0) {
2392 failf(data, "set socket NONBLOCK: %s",
2393 curlx_strerror(SOCKERRNO, errbuf, sizeof(errbuf)));
2394 Curl_socket_close(data, cf->conn, s_accepted);
2395 return CURLE_FTP_ACCEPT_FAILED;
2396 }
2397#endif /* !HAVE_ACCEPT4 */
2398 infof(data, "Connection accepted from server");
2400 /* Replace any filter on SECONDARY with one listening on this socket */
2401 ctx->listening = FALSE;
2402 ctx->accepted = TRUE;
2403 socket_close(data, cf->conn, TRUE, ctx->sock);
2404 ctx->sock = s_accepted;
2406 cf->conn->sock[cf->sockindex] = ctx->sock;
2407 cf_tcp_set_accepted_remote_ip(cf, data);
2408 set_local_ip(cf, data);
2409 ctx->active = TRUE;
2410 ctx->connected_at = *Curl_pgrs_now(data);
2411 cf->connected = TRUE;
2412 CURL_TRC_CF(data, cf, "accepted_set(sock=%" FMT_SOCKET_T
2413 ", remote=%s port=%d)",
2414 ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port);
2416 if(data->set.fsockopt) {
2417 struct Curl_mapi_guard guard;
2418 int error = 0;
2420 /* activate callback for setting socket options */
2421 CURL_CBAPI_START(&guard, data, easy_fsockopt);
2422 error = data->set.fsockopt(data->set.sockopt_client,
2423 ctx->sock, CURLSOCKTYPE_ACCEPT);
2424 CURL_CBAPI_END(&guard);
2426 if(error)
2427 return CURLE_ABORTED_BY_CALLBACK;
2428 }
2429 *done = TRUE;
2430 return CURLE_OK;
2431}
2433struct Curl_cftype Curl_cft_tcp_accept = {
2434 "TCP-ACCEPT",
2435 CF_TYPE_IP_CONNECT,
2436 CURL_LOG_LVL_NONE,
2437 cf_socket_destroy,
2438 cf_tcp_accept_connect,
2439 cf_socket_shutdown,
2440 cf_socket_adjust_pollset,
2441 Curl_cf_def_data_pending,
2442 cf_socket_send,
2443 cf_socket_recv,
2444 cf_socket_cntrl,
2445 cf_socket_conn_is_alive,
2446 Curl_cf_def_conn_keep_alive,
2447 cf_socket_query,
2448};
2450CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
2451 struct connectdata *conn,
2452 int8_t sockindex, curl_socket_t *s)
2453{
2454 CURLcode result;
2455 struct Curl_cfilter *cf = NULL;
2456 struct cf_socket_ctx *ctx = NULL;
2458 /* replace any existing */
2459 Curl_conn_cf_discard_all(data, conn, sockindex);
2460 DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD);
2462 ctx = curlx_calloc(1, sizeof(*ctx));
2463 if(!ctx) {
2464 result = CURLE_OUT_OF_MEMORY;
2465 goto out;
2466 }
2467 ctx->transport = TRNSPRT_TCP;
2468 ctx->sock = *s;
2469 ctx->listening = TRUE;
2470 ctx->accepted = FALSE;
2471 result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx);
2472 if(result)
2473 goto out;
2474 Curl_conn_cf_add(data, conn, sockindex, cf);
2476 ctx->started_at = *Curl_pgrs_now(data);
2477 conn->sock[sockindex] = ctx->sock;
2478 set_local_ip(cf, data);
2479 CURL_TRC_CF(data, cf, "set filter for listen socket fd=%" FMT_SOCKET_T
2480 " ip=%s:%d", ctx->sock,
2481 ctx->ip.local_ip, ctx->ip.local_port);
2483out:
2484 if(result) {
2485 curlx_safefree(cf);
2486 curlx_safefree(ctx);
2487 }
2488 return result;
2489}
2491bool Curl_conn_is_tcp_listen(struct Curl_easy *data,
2492 int8_t sockindex)
2493{
2494 struct Curl_cfilter *cf = data->conn->cfilter[sockindex];
2495 while(cf) {
2496 if(cf->cft == &Curl_cft_tcp_accept)
2497 return TRUE;
2498 cf = cf->next;
2499 }
2500 return FALSE;
2501}
2503/**
2504 * Return TRUE iff `cf` is a socket filter.
2505 */
2506static bool cf_is_socket(struct Curl_cfilter *cf)
2507{
2508 return cf && (cf->cft == &Curl_cft_tcp ||
2509 cf->cft == &Curl_cft_udp ||
2510 cf->cft == &Curl_cft_unix ||
2511 cf->cft == &Curl_cft_tcp_accept);
2512}
2514CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
2515 struct Curl_easy *data,
2516 curl_socket_t *psock,
2517 const struct Curl_sockaddr_ex **paddr,
2518 struct ip_quadruple *pip)
2519{
2520 (void)data;
2521 if(cf_is_socket(cf) && cf->ctx) {
2522 struct cf_socket_ctx *ctx = cf->ctx;
2524 if(psock)
2525 *psock = ctx->sock;
2526 if(paddr)
2527 *paddr = &ctx->addr;
2528 if(pip)
2529 *pip = ctx->ip;
2530 return CURLE_OK;
2531 }
2532 return CURLE_FAILED_INIT;
2533}
Diagnostics4 git calls · 457 ms
CallStatusSizeTime0457 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=149 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=149 git.pkt.payload.max=78 git.ls_refs.count=2 git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=451 git.response.bytes=293470 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=10 git.pkt.data=8 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=293470 git.pkt.payload.max=65516 git.sideband.band1.bytes=293354 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=87 git.pack.bytes=293354 git.pack.ofs_delta=0 git.pack.ref_delta=1 git.pack.chain.max=1 git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0 git.pack.full=86Open pack map
fetch20021 KiB451 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=21658 git.response.cache=MISS git.response.duration_ms=451 git.fetch.wants=97b5fa89d2197564fa86a9cab5b239b722215449 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=21658 git.pkt.payload.max=21637 git.sideband.band1.bytes=21636 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
- Ref
- refs/heads/master
- Commit
- 31c911efe5652725e930f4d2e60c9060e5f6646d
- cf-ray
- a5e209d86d91c69c
- Request
- 5a9731af…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format