Coverage Report

Created: 2026-12-01 06:28

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