Coverage Report

Created: 2026-07-14 07:09

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