Coverage Report

Created: 2025-11-23 06:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/transfer.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
25
#include "curl_setup.h"
26
27
#ifdef HAVE_NETINET_IN_H
28
#include <netinet/in.h>
29
#endif
30
#ifdef HAVE_NETDB_H
31
#include <netdb.h>
32
#endif
33
#ifdef HAVE_ARPA_INET_H
34
#include <arpa/inet.h>
35
#endif
36
#ifdef HAVE_NET_IF_H
37
#include <net/if.h>
38
#endif
39
#ifdef HAVE_SYS_IOCTL_H
40
#include <sys/ioctl.h>
41
#endif
42
#include <signal.h>
43
44
#ifdef HAVE_SYS_PARAM_H
45
#include <sys/param.h>
46
#endif
47
48
#ifdef HAVE_SYS_SELECT_H
49
#include <sys/select.h>
50
#elif defined(HAVE_UNISTD_H)
51
#include <unistd.h>
52
#endif
53
54
#ifndef HAVE_SOCKET
55
#error "We cannot compile without socket() support!"
56
#endif
57
58
#include "urldata.h"
59
#include <curl/curl.h>
60
#include "netrc.h"
61
62
#include "content_encoding.h"
63
#include "hostip.h"
64
#include "cfilters.h"
65
#include "cw-out.h"
66
#include "transfer.h"
67
#include "sendf.h"
68
#include "speedcheck.h"
69
#include "progress.h"
70
#include "http.h"
71
#include "url.h"
72
#include "getinfo.h"
73
#include "vtls/vtls.h"
74
#include "vquic/vquic.h"
75
#include "select.h"
76
#include "multiif.h"
77
#include "connect.h"
78
#include "http2.h"
79
#include "mime.h"
80
#include "hsts.h"
81
#include "setopt.h"
82
#include "headers.h"
83
#include "curlx/warnless.h"
84
85
/* The last 2 #include files should be in this order */
86
#include "curl_memory.h"
87
#include "memdebug.h"
88
89
#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
90
    !defined(CURL_DISABLE_IMAP)
91
/*
92
 * checkheaders() checks the linked list of custom headers for a
93
 * particular header (prefix). Provide the prefix without colon!
94
 *
95
 * Returns a pointer to the first matching header or NULL if none matched.
96
 */
97
char *Curl_checkheaders(const struct Curl_easy *data,
98
                        const char *thisheader,
99
                        const size_t thislen)
100
407k
{
101
407k
  struct curl_slist *head;
102
407k
  DEBUGASSERT(thislen);
103
407k
  DEBUGASSERT(thisheader[thislen-1] != ':');
104
105
1.44M
  for(head = data->set.headers; head; head = head->next) {
106
1.03M
    if(curl_strnequal(head->data, thisheader, thislen) &&
107
8.08k
       Curl_headersep(head->data[thislen]) )
108
3.51k
      return head->data;
109
1.03M
  }
110
111
403k
  return NULL;
112
407k
}
113
#endif
114
115
static int data_pending(struct Curl_easy *data, bool rcvd_eagain)
116
3.09M
{
117
3.09M
  struct connectdata *conn = data->conn;
118
119
3.09M
  if(conn->handler->protocol&PROTO_FAMILY_FTP)
120
17
    return Curl_conn_data_pending(data, SECONDARYSOCKET);
121
122
  /* in the case of libssh2, we can never be really sure that we have emptied
123
     its internal buffers so we MUST always try until we get EAGAIN back */
124
3.09M
  return (!rcvd_eagain &&
125
0
          conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP)) ||
126
3.09M
         Curl_conn_data_pending(data, FIRSTSOCKET);
127
3.09M
}
128
129
/*
130
 * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
131
 * remote document with the time provided by CURLOPT_TIMEVAL
132
 */
133
bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
134
406
{
135
406
  if((timeofdoc == 0) || (data->set.timevalue == 0))
136
349
    return TRUE;
137
138
57
  switch(data->set.timecondition) {
139
9
  case CURL_TIMECOND_IFMODSINCE:
140
30
  default:
141
30
    if(timeofdoc <= data->set.timevalue) {
142
11
      infof(data,
143
11
            "The requested document is not new enough");
144
11
      data->info.timecond = TRUE;
145
11
      return FALSE;
146
11
    }
147
19
    break;
148
27
  case CURL_TIMECOND_IFUNMODSINCE:
149
27
    if(timeofdoc >= data->set.timevalue) {
150
14
      infof(data,
151
14
            "The requested document is not old enough");
152
14
      data->info.timecond = TRUE;
153
14
      return FALSE;
154
14
    }
155
13
    break;
156
57
  }
157
158
32
  return TRUE;
159
57
}
160
161
static CURLcode xfer_recv_shutdown(struct Curl_easy *data, bool *done)
162
569
{
163
569
  if(!data || !data->conn)
164
0
    return CURLE_FAILED_INIT;
165
569
  return Curl_conn_shutdown(data, data->conn->recv_idx, done);
166
569
}
167
168
static bool xfer_recv_shutdown_started(struct Curl_easy *data)
169
3.96M
{
170
3.96M
  if(!data || !data->conn)
171
0
    return FALSE;
172
3.96M
  return Curl_shutdown_started(data, data->conn->recv_idx);
173
3.96M
}
174
175
CURLcode Curl_xfer_send_shutdown(struct Curl_easy *data, bool *done)
176
18
{
177
18
  if(!data || !data->conn)
178
0
    return CURLE_FAILED_INIT;
179
18
  return Curl_conn_shutdown(data, data->conn->send_idx, done);
180
18
}
181
182
/**
183
 * Receive raw response data for the transfer.
184
 * @param data         the transfer
185
 * @param buf          buffer to keep response data received
186
 * @param blen         length of `buf`
187
 * @param eos_reliable if EOS detection in underlying connection is reliable
188
 * @param err error    code in case of -1 return
189
 * @return number of bytes read or -1 for error
190
 */
191
static CURLcode xfer_recv_resp(struct Curl_easy *data,
192
                               char *buf, size_t blen,
193
                               bool eos_reliable,
194
                               size_t *pnread)
195
3.96M
{
196
3.96M
  CURLcode result;
197
198
3.96M
  DEBUGASSERT(blen > 0);
199
3.96M
  *pnread = 0;
200
  /* If we are reading BODY data and the connection does NOT handle EOF
201
   * and we know the size of the BODY data, limit the read amount */
202
3.96M
  if(!eos_reliable && !data->req.header && data->req.size != -1) {
203
2.72k
    blen = curlx_sotouz_range(data->req.size - data->req.bytecount, 0, blen);
204
2.72k
  }
205
3.96M
  else if(xfer_recv_shutdown_started(data)) {
206
    /* we already received everything. Do not try more. */
207
0
    blen = 0;
208
0
  }
209
210
3.96M
  if(blen) {
211
3.96M
    result = Curl_xfer_recv(data, buf, blen, pnread);
212
3.96M
    if(result)
213
3.10M
      return result;
214
3.96M
  }
215
216
857k
  if(*pnread == 0) {
217
18.0k
    if(data->req.shutdown) {
218
569
      bool done;
219
569
      result = xfer_recv_shutdown(data, &done);
220
569
      if(result)
221
0
        return result;
222
569
      if(!done) {
223
0
        return CURLE_AGAIN;
224
0
      }
225
569
    }
226
18.0k
    DEBUGF(infof(data, "sendrecv_dl: we are done"));
227
18.0k
  }
228
857k
  return CURLE_OK;
229
857k
}
230
231
/*
232
 * Go ahead and do a read if we have a readable socket or if
233
 * the stream was rewound (in which case we have data in a
234
 * buffer)
235
 */
236
static CURLcode sendrecv_dl(struct Curl_easy *data,
237
                            struct SingleRequest *k)
238
3.95M
{
239
3.95M
  struct connectdata *conn = data->conn;
240
3.95M
  CURLcode result = CURLE_OK;
241
3.95M
  char *buf, *xfer_buf;
242
3.95M
  size_t blen, xfer_blen;
243
3.95M
  int maxloops = 10;
244
3.95M
  curl_off_t total_received = 0;
245
3.95M
  bool is_multiplex = FALSE;
246
3.95M
  bool rcvd_eagain = FALSE;
247
3.95M
  bool is_eos = FALSE;
248
249
3.95M
  result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen);
250
3.95M
  if(result)
251
0
    goto out;
252
253
  /* This is where we loop until we have read everything there is to
254
     read or we get a CURLE_AGAIN */
255
4.77M
  do {
256
4.77M
    size_t bytestoread;
257
258
4.77M
    if(!is_multiplex) {
259
      /* Multiplexed connection have inherent handling of EOF and we do not
260
       * have to carefully restrict the amount we try to read.
261
       * Multiplexed changes only in one direction. */
262
4.77M
      is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET);
263
4.77M
    }
264
265
4.77M
    buf = xfer_buf;
266
4.77M
    bytestoread = xfer_blen;
267
268
4.77M
    if(bytestoread && data->set.max_recv_speed > 0) {
269
      /* In case of speed limit on receiving: if this loop already got
270
       * a quarter of the quota, break out. We want to stutter a bit
271
       * to keep in the limit, but too small receives will just cost
272
       * cpu unnecessarily. */
273
1.98M
      if(total_received && (total_received >= (data->set.max_recv_speed / 4)))
274
807k
        break;
275
1.17M
      if(data->set.max_recv_speed < (curl_off_t)bytestoread)
276
918k
        bytestoread = (size_t)data->set.max_recv_speed;
277
1.17M
    }
278
279
3.96M
    rcvd_eagain = FALSE;
280
3.96M
    result = xfer_recv_resp(data, buf, bytestoread, is_multiplex, &blen);
281
3.96M
    if(result) {
282
3.10M
      if(result != CURLE_AGAIN)
283
17.8k
        goto out; /* real error */
284
3.09M
      rcvd_eagain = TRUE;
285
3.09M
      result = CURLE_OK;
286
3.09M
      if(data->req.download_done && data->req.no_body &&
287
6
         !data->req.resp_trailer) {
288
6
        DEBUGF(infof(data, "EAGAIN, download done, no trailer announced, "
289
6
               "not waiting for EOS"));
290
6
        blen = 0;
291
        /* continue as if we received the EOS */
292
6
      }
293
3.09M
      else
294
3.09M
        break; /* get out of loop */
295
3.09M
    }
296
297
    /* We only get a 0-length receive at the end of the response */
298
857k
    is_eos = (blen == 0);
299
300
857k
    if(!blen && (conn->recv[FIRSTSOCKET] == Curl_cf_recv)) {
301
      /* if we receive 0 or less here and the protocol handler did not
302
         replace the connection's `recv` callback, either the data transfer
303
         is done or the server closed the connection and
304
         we bail out from this!
305
         With a `recv` replacement, we assume the protocol handler knows
306
         what it is doing and a 0-length receive is fine. For example,
307
         SFTP downloads of an empty file would show this. See #19165. */
308
18.0k
      if(is_multiplex)
309
286
        DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
310
17.7k
      else
311
17.7k
        DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
312
18.0k
      result = Curl_req_stop_send_recv(data);
313
18.0k
      if(result)
314
0
        goto out;
315
18.0k
      if(k->eos_written) /* already did write this to client, leave */
316
0
        break;
317
18.0k
    }
318
857k
    total_received += blen;
319
320
857k
    result = Curl_xfer_write_resp(data, buf, blen, is_eos);
321
857k
    if(result || data->req.done)
322
5.62k
      goto out;
323
324
    /* if we are done, we stop receiving. On multiplexed connections,
325
     * we should read the EOS. Which may arrive as meta data after
326
     * the bytes. Not taking it in might lead to RST of streams. */
327
851k
    if((!is_multiplex && data->req.download_done) || is_eos) {
328
30.8k
      data->req.keepon &= ~KEEP_RECV;
329
30.8k
    }
330
    /* if we are PAUSEd or stopped receiving, leave the loop */
331
851k
    if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV))
332
30.8k
      break;
333
334
851k
  } while(maxloops--);
335
336
3.93M
  if(!is_eos && !Curl_xfer_is_blocked(data) &&
337
3.91M
     (!rcvd_eagain || data_pending(data, rcvd_eagain))) {
338
    /* Did not read until EAGAIN/EOS or there is still data pending
339
     * in buffers. Mark as read-again via simulated SELECT results. */
340
821k
    Curl_multi_mark_dirty(data);
341
821k
    CURL_TRC_M(data, "sendrecv_dl() no EAGAIN/pending data, mark as dirty");
342
821k
  }
343
344
3.93M
  if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
345
2.34k
     (conn->bits.close || is_multiplex)) {
346
    /* When we have read the entire thing and the close bit is set, the server
347
       may now close the connection. If there is now any kind of sending going
348
       on from our side, we need to stop that immediately. */
349
136
    infof(data, "we are done reading and this is set to close, stop send");
350
136
    Curl_req_abort_sending(data);
351
136
  }
352
353
3.95M
out:
354
3.95M
  Curl_multi_xfer_buf_release(data, xfer_buf);
355
3.95M
  if(result)
356
23.1k
    DEBUGF(infof(data, "sendrecv_dl() -> %d", result));
357
3.95M
  return result;
358
3.93M
}
359
360
/*
361
 * Send data to upload to the server, when the socket is writable.
362
 */
363
static CURLcode sendrecv_ul(struct Curl_easy *data)
364
3.10M
{
365
  /* We should not get here when the sending is already done. It
366
   * probably means that someone set `data-req.keepon |= KEEP_SEND`
367
   * when it should not. */
368
3.10M
  DEBUGASSERT(!Curl_req_done_sending(data));
369
370
3.10M
  if(!Curl_req_done_sending(data))
371
3.10M
    return Curl_req_send_more(data);
372
0
  return CURLE_OK;
373
3.10M
}
374
375
/*
376
 * Curl_sendrecv() is the low-level function to be called when data is to
377
 * be read and written to/from the connection.
378
 */
379
CURLcode Curl_sendrecv(struct Curl_easy *data, struct curltime *nowp)
380
3.95M
{
381
3.95M
  struct SingleRequest *k = &data->req;
382
3.95M
  CURLcode result = CURLE_OK;
383
384
3.95M
  DEBUGASSERT(nowp);
385
3.95M
  if(Curl_xfer_is_blocked(data)) {
386
0
    result = CURLE_OK;
387
0
    goto out;
388
0
  }
389
390
  /* We go ahead and do a read if we have a readable socket or if the stream
391
     was rewound (in which case we have data in a buffer) */
392
3.95M
  if(k->keepon & KEEP_RECV) {
393
3.95M
    result = sendrecv_dl(data, k);
394
3.95M
    if(result || data->req.done)
395
23.4k
      goto out;
396
3.95M
  }
397
398
  /* If we still have writing to do, we check if we have a writable socket. */
399
3.93M
  if(Curl_req_want_send(data) || (data->req.keepon & KEEP_SEND_TIMED)) {
400
3.10M
    result = sendrecv_ul(data);
401
3.10M
    if(result)
402
58
      goto out;
403
3.10M
  }
404
405
3.93M
  if(Curl_pgrsUpdate(data))
406
0
    result = CURLE_ABORTED_BY_CALLBACK;
407
3.93M
  else
408
3.93M
    result = Curl_speedcheck(data, *nowp);
409
3.93M
  if(result)
410
0
    goto out;
411
412
3.93M
  if(k->keepon) {
413
3.90M
    if(Curl_timeleft_ms(data, nowp, FALSE) < 0) {
414
0
      if(k->size != -1) {
415
0
        failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
416
0
              " milliseconds with %" FMT_OFF_T " out of %"
417
0
              FMT_OFF_T " bytes received",
418
0
              curlx_timediff_ms(*nowp, data->progress.t_startsingle),
419
0
              k->bytecount, k->size);
420
0
      }
421
0
      else {
422
0
        failf(data, "Operation timed out after %" FMT_TIMEDIFF_T
423
0
              " milliseconds with %" FMT_OFF_T " bytes received",
424
0
              curlx_timediff_ms(*nowp, data->progress.t_startsingle),
425
0
              k->bytecount);
426
0
      }
427
0
      result = CURLE_OPERATION_TIMEDOUT;
428
0
      goto out;
429
0
    }
430
3.90M
  }
431
32.1k
  else {
432
    /*
433
     * The transfer has been performed. Just make some general checks before
434
     * returning.
435
     */
436
32.1k
    if(!(data->req.no_body) && (k->size != -1) &&
437
5.54k
       (k->bytecount != k->size) && !k->newurl) {
438
719
      failf(data, "transfer closed with %" FMT_OFF_T
439
719
            " bytes remaining to read", k->size - k->bytecount);
440
719
      result = CURLE_PARTIAL_FILE;
441
719
      goto out;
442
719
    }
443
31.4k
    if(Curl_pgrsUpdate(data)) {
444
0
      result = CURLE_ABORTED_BY_CALLBACK;
445
0
      goto out;
446
0
    }
447
31.4k
  }
448
449
  /* If there is nothing more to send/recv, the request is done */
450
3.93M
  if((k->keepon & (KEEP_RECVBITS|KEEP_SENDBITS)) == 0)
451
31.4k
    data->req.done = TRUE;
452
453
3.95M
out:
454
3.95M
  if(result)
455
23.9k
    DEBUGF(infof(data, "Curl_sendrecv() -> %d", result));
456
3.95M
  return result;
457
3.93M
}
458
459
/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
460
   which means this gets called once for each subsequent redirect etc */
461
void Curl_init_CONNECT(struct Curl_easy *data)
462
148k
{
463
148k
  data->state.fread_func = data->set.fread_func_set;
464
148k
  data->state.in = data->set.in_set;
465
148k
  data->state.upload = (data->state.httpreq == HTTPREQ_PUT);
466
148k
}
467
468
/*
469
 * Curl_pretransfer() is called immediately before a transfer starts, and only
470
 * once for one transfer no matter if it has redirects or do multi-pass
471
 * authentication etc.
472
 */
473
CURLcode Curl_pretransfer(struct Curl_easy *data)
474
166k
{
475
166k
  CURLcode result = CURLE_OK;
476
477
  /* Reset the retry count at the start of each request.
478
   * If the retry count is not reset, when the connection drops,
479
   * it will not enter the retry mechanism on CONN_MAX_RETRIES + 1 attempts
480
   * and will immediately throw
481
   * "Connection died, tried CONN_MAX_RETRIES times before giving up".
482
   * By resetting it here, we ensure each new request starts fresh. */
483
166k
  data->state.retrycount = 0;
484
485
166k
  if(!data->set.str[STRING_SET_URL] && !data->set.uh) {
486
    /* we cannot do anything without URL */
487
39.1k
    failf(data, "No URL set");
488
39.1k
    return CURLE_URL_MALFORMAT;
489
39.1k
  }
490
491
  /* CURLOPT_CURLU overrides CURLOPT_URL and the contents of the CURLU handle
492
     is allowed to be changed by the user between transfers */
493
127k
  if(data->set.uh) {
494
0
    CURLUcode uc;
495
0
    free(data->set.str[STRING_SET_URL]);
496
0
    uc = curl_url_get(data->set.uh,
497
0
                      CURLUPART_URL, &data->set.str[STRING_SET_URL], 0);
498
0
    if(uc) {
499
0
      failf(data, "No URL set");
500
0
      return CURLE_URL_MALFORMAT;
501
0
    }
502
0
  }
503
504
  /* since the URL may have been redirected in a previous use of this handle */
505
127k
  if(data->state.url_alloc) {
506
81
    Curl_safefree(data->state.url);
507
81
    data->state.url_alloc = FALSE;
508
81
  }
509
510
127k
  data->state.url = data->set.str[STRING_SET_URL];
511
512
127k
  if(data->set.postfields && data->set.set_resume_from) {
513
    /* we cannot */
514
146
    failf(data, "cannot mix POSTFIELDS with RESUME_FROM");
515
146
    return CURLE_BAD_FUNCTION_ARGUMENT;
516
146
  }
517
518
127k
  data->state.prefer_ascii = data->set.prefer_ascii;
519
127k
#ifdef CURL_LIST_ONLY_PROTOCOL
520
127k
  data->state.list_only = data->set.list_only;
521
127k
#endif
522
127k
  data->state.httpreq = data->set.method;
523
524
127k
  data->state.requests = 0;
525
127k
  data->state.followlocation = 0; /* reset the location-follow counter */
526
127k
  data->state.this_is_a_follow = FALSE; /* reset this */
527
127k
  data->state.errorbuf = FALSE; /* no error has occurred */
528
127k
#ifndef CURL_DISABLE_HTTP
529
127k
  Curl_http_neg_init(data, &data->state.http_neg);
530
127k
#endif
531
127k
  data->state.authproblem = FALSE;
532
127k
  data->state.authhost.want = data->set.httpauth;
533
127k
  data->state.authproxy.want = data->set.proxyauth;
534
127k
  Curl_safefree(data->info.wouldredirect);
535
127k
  Curl_data_priority_clear_state(data);
536
537
127k
  if(data->state.httpreq == HTTPREQ_PUT)
538
1.19k
    data->state.infilesize = data->set.filesize;
539
126k
  else if((data->state.httpreq != HTTPREQ_GET) &&
540
15.9k
          (data->state.httpreq != HTTPREQ_HEAD)) {
541
15.1k
    data->state.infilesize = data->set.postfieldsize;
542
15.1k
    if(data->set.postfields && (data->state.infilesize == -1))
543
1.40k
      data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
544
15.1k
  }
545
111k
  else
546
111k
    data->state.infilesize = 0;
547
548
  /* If there is a list of cookie files to read, do it now! */
549
127k
  result = Curl_cookie_loadfiles(data);
550
127k
  if(!result)
551
127k
    Curl_cookie_run(data); /* activate */
552
553
  /* If there is a list of host pairs to deal with */
554
127k
  if(!result && data->state.resolve)
555
0
    result = Curl_loadhostpairs(data);
556
557
127k
  if(!result)
558
    /* If there is a list of hsts files to read */
559
127k
    result = Curl_hsts_loadfiles(data);
560
561
127k
  if(!result) {
562
    /* Allow data->set.use_port to set which port to use. This needs to be
563
     * disabled for example when we follow Location: headers to URLs using
564
     * different ports! */
565
127k
    data->state.allow_port = TRUE;
566
567
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
568
    /*************************************************************
569
     * Tell signal handler to ignore SIGPIPE
570
     *************************************************************/
571
    if(!data->set.no_signal)
572
      data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
573
#endif
574
575
127k
    Curl_initinfo(data); /* reset session-specific information "variables" */
576
127k
    Curl_pgrsResetTransferSizes(data);
577
127k
    Curl_pgrsStartNow(data);
578
579
    /* In case the handle is reused and an authentication method was picked
580
       in the session we need to make sure we only use the one(s) we now
581
       consider to be fine */
582
127k
    data->state.authhost.picked &= data->state.authhost.want;
583
127k
    data->state.authproxy.picked &= data->state.authproxy.want;
584
585
127k
#ifndef CURL_DISABLE_FTP
586
127k
    data->state.wildcardmatch = data->set.wildcard_enabled;
587
127k
    if(data->state.wildcardmatch) {
588
539
      struct WildcardData *wc;
589
539
      if(!data->wildcard) {
590
458
        data->wildcard = calloc(1, sizeof(struct WildcardData));
591
458
        if(!data->wildcard)
592
0
          return CURLE_OUT_OF_MEMORY;
593
458
      }
594
539
      wc = data->wildcard;
595
539
      if(wc->state < CURLWC_INIT) {
596
458
        if(wc->ftpwc)
597
0
          wc->dtor(wc->ftpwc);
598
458
        Curl_safefree(wc->pattern);
599
458
        Curl_safefree(wc->path);
600
458
        Curl_wildcard_init(wc); /* init wildcard structures */
601
458
      }
602
539
    }
603
127k
#endif
604
127k
    result = Curl_hsts_loadcb(data, data->hsts);
605
127k
  }
606
607
  /*
608
   * Set user-agent. Used for HTTP, but since we can attempt to tunnel
609
   * basically anything through an HTTP proxy we cannot limit this based on
610
   * protocol.
611
   */
612
127k
  if(!result && data->set.str[STRING_USERAGENT]) {
613
1.32k
    free(data->state.aptr.uagent);
614
1.32k
    data->state.aptr.uagent =
615
1.32k
      curl_maprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
616
1.32k
    if(!data->state.aptr.uagent)
617
0
      return CURLE_OUT_OF_MEMORY;
618
1.32k
  }
619
620
127k
  if(data->set.str[STRING_USERNAME] ||
621
124k
     data->set.str[STRING_PASSWORD])
622
3.88k
    data->state.creds_from = CREDS_OPTION;
623
127k
  if(!result)
624
127k
    result = Curl_setstropt(&data->state.aptr.user,
625
127k
                            data->set.str[STRING_USERNAME]);
626
127k
  if(!result)
627
127k
    result = Curl_setstropt(&data->state.aptr.passwd,
628
127k
                            data->set.str[STRING_PASSWORD]);
629
127k
#ifndef CURL_DISABLE_PROXY
630
127k
  if(!result)
631
127k
    result = Curl_setstropt(&data->state.aptr.proxyuser,
632
127k
                            data->set.str[STRING_PROXYUSERNAME]);
633
127k
  if(!result)
634
127k
    result = Curl_setstropt(&data->state.aptr.proxypasswd,
635
127k
                            data->set.str[STRING_PROXYPASSWORD]);
636
127k
#endif
637
638
127k
  data->req.headerbytecount = 0;
639
127k
  Curl_headers_cleanup(data);
640
127k
  return result;
641
127k
}
642
643
/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
644
645
   NOTE: that the *url is malloc()ed. */
646
CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
647
34.3k
{
648
34.3k
  struct connectdata *conn = data->conn;
649
34.3k
  bool retry = FALSE;
650
34.3k
  *url = NULL;
651
652
  /* if we are talking upload, we cannot do the checks below, unless the
653
     protocol is HTTP as when uploading over HTTP we will still get a
654
     response */
655
34.3k
  if(data->state.upload &&
656
1.64k
     !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
657
157
    return CURLE_OK;
658
659
34.2k
  if(conn->bits.reuse &&
660
13.4k
     (data->req.bytecount + data->req.headerbytecount == 0) &&
661
1.48k
     ((!data->req.no_body && !data->req.done) ||
662
1.40k
      (conn->handler->protocol & PROTO_FAMILY_HTTP))
663
958
#ifndef CURL_DISABLE_RTSP
664
958
     && (data->set.rtspreq != RTSPREQ_RECEIVE)
665
34.2k
#endif
666
34.2k
    )
667
    /* We got no data, we attempted to reuse a connection. For HTTP this
668
       can be a retry so we try again regardless if we expected a body.
669
       For other protocols we only try again only if we expected a body.
670
671
       This might happen if the connection was left alive when we were
672
       done using it before, but that was closed when we wanted to read from
673
       it again. Bad luck. Retry the same request on a fresh connect! */
674
957
    retry = TRUE;
675
33.2k
  else if(data->state.refused_stream &&
676
1.70k
          (data->req.bytecount + data->req.headerbytecount == 0) ) {
677
    /* This was sent on a refused stream, safe to rerun. A refused stream
678
       error can typically only happen on HTTP/2 level if the stream is safe
679
       to issue again, but the nghttp2 API can deliver the message to other
680
       streams as well, which is why this adds the check the data counters
681
       too. */
682
1.69k
    infof(data, "REFUSED_STREAM, retrying a fresh connect");
683
1.69k
    data->state.refused_stream = FALSE; /* clear again */
684
1.69k
    retry = TRUE;
685
1.69k
  }
686
34.2k
  if(retry) {
687
2.65k
#define CONN_MAX_RETRIES 5
688
2.65k
    if(data->state.retrycount++ >= CONN_MAX_RETRIES) {
689
0
      failf(data, "Connection died, tried %d times before giving up",
690
0
            CONN_MAX_RETRIES);
691
0
      data->state.retrycount = 0;
692
0
      return CURLE_SEND_ERROR;
693
0
    }
694
2.65k
    infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
695
2.65k
          data->state.retrycount);
696
2.65k
    *url = strdup(data->state.url);
697
2.65k
    if(!*url)
698
0
      return CURLE_OUT_OF_MEMORY;
699
700
2.65k
    connclose(conn, "retry"); /* close this connection */
701
2.65k
    conn->bits.retry = TRUE; /* mark this as a connection we are about
702
                                to retry. Marking it this way should
703
                                prevent i.e HTTP transfers to return
704
                                error just because nothing has been
705
                                transferred! */
706
2.65k
    Curl_creader_set_rewind(data, TRUE);
707
2.65k
  }
708
34.2k
  return CURLE_OK;
709
34.2k
}
710
711
static void xfer_setup(
712
  struct Curl_easy *data,   /* transfer */
713
  int send_idx,             /* sockindex to send on or -1 */
714
  int recv_idx,             /* sockindex to receive on or -1 */
715
  curl_off_t recv_size      /* how much to receive, -1 if unknown */
716
  )
717
58.3k
{
718
58.3k
  struct SingleRequest *k = &data->req;
719
58.3k
  struct connectdata *conn = data->conn;
720
721
58.3k
  DEBUGASSERT(conn != NULL);
722
  /* indexes are in range */
723
58.3k
  DEBUGASSERT((send_idx <= 1) && (send_idx >= -1));
724
58.3k
  DEBUGASSERT((recv_idx <= 1) && (recv_idx >= -1));
725
  /* if request wants to send, switching off the send direction is wrong */
726
58.3k
  DEBUGASSERT((send_idx >= 0) || !Curl_req_want_send(data));
727
728
58.3k
  conn->send_idx = send_idx;
729
58.3k
  conn->recv_idx = recv_idx;
730
731
  /* without receiving, there should be not recv_size */
732
58.3k
  DEBUGASSERT((conn->recv_idx >= 0) || (recv_size == -1));
733
58.3k
  k->size = recv_size;
734
58.3k
  k->header = !!conn->handler->write_resp_hd;
735
  /* by default, we do not shutdown at the end of the transfer */
736
58.3k
  k->shutdown = FALSE;
737
58.3k
  k->shutdown_err_ignore = FALSE;
738
739
  /* The code sequence below is placed in this function just because all
740
     necessary input is not always known in do_complete() as this function may
741
     be called after that */
742
58.3k
  if(!k->header && (recv_size > 0))
743
619
    Curl_pgrsSetDownloadSize(data, recv_size);
744
745
  /* we want header and/or body, if neither then do not do this! */
746
58.3k
  if(conn->handler->write_resp_hd || !data->req.no_body) {
747
748
58.2k
    if(conn->recv_idx != -1)
749
55.5k
      k->keepon |= KEEP_RECV;
750
751
58.2k
    if(conn->send_idx != -1)
752
53.6k
      k->keepon |= KEEP_SEND;
753
58.2k
  }
754
755
58.3k
  CURL_TRC_M(data, "xfer_setup: recv_idx=%d, send_idx=%d",
756
58.3k
             conn->recv_idx, conn->send_idx);
757
58.3k
}
758
759
void Curl_xfer_setup_nop(struct Curl_easy *data)
760
1.55k
{
761
1.55k
  xfer_setup(data, -1, -1, -1);
762
1.55k
}
763
764
void Curl_xfer_setup_sendrecv(struct Curl_easy *data,
765
                              int sockindex,
766
                              curl_off_t recv_size)
767
52.3k
{
768
52.3k
  xfer_setup(data, sockindex, sockindex, recv_size);
769
52.3k
}
770
771
void Curl_xfer_setup_send(struct Curl_easy *data,
772
                          int sockindex)
773
1.24k
{
774
1.24k
  xfer_setup(data, sockindex, -1, -1);
775
1.24k
}
776
777
void Curl_xfer_setup_recv(struct Curl_easy *data,
778
                          int sockindex,
779
                          curl_off_t recv_size)
780
3.19k
{
781
3.19k
  xfer_setup(data, -1, sockindex, recv_size);
782
3.19k
}
783
784
void Curl_xfer_set_shutdown(struct Curl_easy *data,
785
                            bool shutdown,
786
                            bool ignore_errors)
787
602
{
788
  /* Shutdown should only be set when the transfer only sends or receives. */
789
602
  DEBUGASSERT(!shutdown ||
790
602
              (data->conn->send_idx < 0) || (data->conn->recv_idx < 0));
791
602
  data->req.shutdown = shutdown;
792
602
  data->req.shutdown_err_ignore = ignore_errors;
793
602
}
794
795
CURLcode Curl_xfer_write_resp(struct Curl_easy *data,
796
                              const char *buf, size_t blen,
797
                              bool is_eos)
798
857k
{
799
857k
  CURLcode result = CURLE_OK;
800
801
857k
  if(data->conn->handler->write_resp) {
802
    /* protocol handlers offering this function take full responsibility
803
     * for writing all received download data to the client. */
804
853k
    result = data->conn->handler->write_resp(data, buf, blen, is_eos);
805
853k
  }
806
3.61k
  else {
807
    /* No special handling by protocol handler, write all received data
808
     * as BODY to the client. */
809
3.61k
    if(blen || is_eos) {
810
3.61k
      int cwtype = CLIENTWRITE_BODY;
811
3.61k
      if(is_eos)
812
1.84k
        cwtype |= CLIENTWRITE_EOS;
813
3.61k
      result = Curl_client_write(data, cwtype, buf, blen);
814
3.61k
    }
815
3.61k
  }
816
817
857k
  if(!result && is_eos) {
818
    /* If we wrote the EOS, we are definitely done */
819
16.9k
    data->req.eos_written = TRUE;
820
16.9k
    data->req.download_done = TRUE;
821
16.9k
  }
822
857k
  CURL_TRC_WRITE(data, "xfer_write_resp(len=%zu, eos=%d) -> %d",
823
857k
                 blen, is_eos, result);
824
857k
  return result;
825
857k
}
826
827
bool Curl_xfer_write_is_paused(struct Curl_easy *data)
828
378
{
829
378
  return Curl_cwriter_is_paused(data);
830
378
}
831
832
CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data,
833
                                 const char *hd0, size_t hdlen, bool is_eos)
834
154k
{
835
154k
  if(data->conn->handler->write_resp_hd) {
836
    /* protocol handlers offering this function take full responsibility
837
     * for writing all received download data to the client. */
838
154k
    return data->conn->handler->write_resp_hd(data, hd0, hdlen, is_eos);
839
154k
  }
840
  /* No special handling by protocol handler, write as response bytes */
841
0
  return Curl_xfer_write_resp(data, hd0, hdlen, is_eos);
842
154k
}
843
844
CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature)
845
119k
{
846
119k
  (void)premature;
847
119k
  return Curl_cw_out_done(data);
848
119k
}
849
850
bool Curl_xfer_needs_flush(struct Curl_easy *data)
851
6.96M
{
852
6.96M
  return Curl_conn_needs_flush(data, data->conn->send_idx);
853
6.96M
}
854
855
CURLcode Curl_xfer_flush(struct Curl_easy *data)
856
2.77M
{
857
2.77M
  return Curl_conn_flush(data, data->conn->send_idx);
858
2.77M
}
859
860
CURLcode Curl_xfer_send(struct Curl_easy *data,
861
                        const void *buf, size_t blen, bool eos,
862
                        size_t *pnwritten)
863
368k
{
864
368k
  CURLcode result;
865
866
368k
  DEBUGASSERT(data);
867
368k
  DEBUGASSERT(data->conn);
868
869
368k
  result = Curl_conn_send(data, data->conn->send_idx,
870
368k
                          buf, blen, eos, pnwritten);
871
368k
  if(result == CURLE_AGAIN) {
872
307k
    result = CURLE_OK;
873
307k
    *pnwritten = 0;
874
307k
  }
875
61.0k
  else if(!result && *pnwritten)
876
60.6k
    data->info.request_size += *pnwritten;
877
878
368k
  DEBUGF(infof(data, "Curl_xfer_send(len=%zu, eos=%d) -> %d, %zu",
879
368k
               blen, eos, result, *pnwritten));
880
368k
  return result;
881
368k
}
882
883
CURLcode Curl_xfer_recv(struct Curl_easy *data,
884
                        char *buf, size_t blen,
885
                        size_t *pnrcvd)
886
17.5M
{
887
17.5M
  DEBUGASSERT(data);
888
17.5M
  DEBUGASSERT(data->conn);
889
17.5M
  DEBUGASSERT(data->set.buffer_size > 0);
890
891
17.5M
  if(curlx_uitouz(data->set.buffer_size) < blen)
892
10.6M
    blen = curlx_uitouz(data->set.buffer_size);
893
17.5M
  return Curl_conn_recv(data, data->conn->recv_idx, buf, blen, pnrcvd);
894
17.5M
}
895
896
CURLcode Curl_xfer_send_close(struct Curl_easy *data)
897
44.3k
{
898
44.3k
  Curl_conn_ev_data_done_send(data);
899
44.3k
  return CURLE_OK;
900
44.3k
}
901
902
bool Curl_xfer_is_blocked(struct Curl_easy *data)
903
27.8M
{
904
27.8M
  bool want_send = ((data)->req.keepon & KEEP_SEND);
905
27.8M
  bool want_recv = ((data)->req.keepon & KEEP_RECV);
906
27.8M
  if(!want_send)
907
20.4M
    return want_recv && Curl_xfer_recv_is_paused(data);
908
7.44M
  else if(!want_recv)
909
6.51k
    return want_send && Curl_xfer_send_is_paused(data);
910
7.43M
  else
911
7.43M
    return Curl_xfer_recv_is_paused(data) && Curl_xfer_send_is_paused(data);
912
27.8M
}
913
914
bool Curl_xfer_send_is_paused(struct Curl_easy *data)
915
110k
{
916
110k
  return (data->req.keepon & KEEP_SEND_PAUSE);
917
110k
}
918
919
bool Curl_xfer_recv_is_paused(struct Curl_easy *data)
920
28.9M
{
921
28.9M
  return (data->req.keepon & KEEP_RECV_PAUSE);
922
28.9M
}
923
924
CURLcode Curl_xfer_pause_send(struct Curl_easy *data, bool enable)
925
0
{
926
0
  CURLcode result = CURLE_OK;
927
0
  if(enable) {
928
0
    data->req.keepon |= KEEP_SEND_PAUSE;
929
0
  }
930
0
  else {
931
0
    data->req.keepon &= ~KEEP_SEND_PAUSE;
932
0
    if(Curl_creader_is_paused(data))
933
0
      result = Curl_creader_unpause(data);
934
0
  }
935
0
  return result;
936
0
}
937
938
CURLcode Curl_xfer_pause_recv(struct Curl_easy *data, bool enable)
939
0
{
940
0
  CURLcode result = CURLE_OK;
941
0
  if(enable) {
942
0
    data->req.keepon |= KEEP_RECV_PAUSE;
943
0
  }
944
0
  else {
945
0
    data->req.keepon &= ~KEEP_RECV_PAUSE;
946
0
    if(Curl_cwriter_is_paused(data))
947
0
      result = Curl_cwriter_unpause(data);
948
0
  }
949
0
  Curl_conn_ev_data_pause(data, enable);
950
0
  return result;
951
0
}
952
953
bool Curl_xfer_is_too_fast(struct Curl_easy *data)
954
19.9M
{
955
19.9M
  struct Curl_llist_node *e = Curl_llist_head(&data->state.timeoutlist);
956
41.7M
  while(e) {
957
21.7M
    struct time_node *n = Curl_node_elem(e);
958
21.7M
    e = Curl_node_next(e);
959
21.7M
    if(n->eid == EXPIRE_TOOFAST)
960
2.13k
      return TRUE;
961
21.7M
  }
962
19.9M
  return FALSE;
963
19.9M
}