Coverage Report

Created: 2025-11-23 06:13

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
0
{
101
0
  struct curl_slist *head;
102
0
  DEBUGASSERT(thislen);
103
0
  DEBUGASSERT(thisheader[thislen-1] != ':');
104
105
0
  for(head = data->set.headers; head; head = head->next) {
106
0
    if(curl_strnequal(head->data, thisheader, thislen) &&
107
0
       Curl_headersep(head->data[thislen]) )
108
0
      return head->data;
109
0
  }
110
111
0
  return NULL;
112
0
}
113
#endif
114
115
static int data_pending(struct Curl_easy *data, bool rcvd_eagain)
116
0
{
117
0
  struct connectdata *conn = data->conn;
118
119
0
  if(conn->handler->protocol&PROTO_FAMILY_FTP)
120
0
    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
0
  return (!rcvd_eagain &&
125
0
          conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP)) ||
126
0
         Curl_conn_data_pending(data, FIRSTSOCKET);
127
0
}
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
0
{
135
0
  if((timeofdoc == 0) || (data->set.timevalue == 0))
136
0
    return TRUE;
137
138
0
  switch(data->set.timecondition) {
139
0
  case CURL_TIMECOND_IFMODSINCE:
140
0
  default:
141
0
    if(timeofdoc <= data->set.timevalue) {
142
0
      infof(data,
143
0
            "The requested document is not new enough");
144
0
      data->info.timecond = TRUE;
145
0
      return FALSE;
146
0
    }
147
0
    break;
148
0
  case CURL_TIMECOND_IFUNMODSINCE:
149
0
    if(timeofdoc >= data->set.timevalue) {
150
0
      infof(data,
151
0
            "The requested document is not old enough");
152
0
      data->info.timecond = TRUE;
153
0
      return FALSE;
154
0
    }
155
0
    break;
156
0
  }
157
158
0
  return TRUE;
159
0
}
160
161
static CURLcode xfer_recv_shutdown(struct Curl_easy *data, bool *done)
162
0
{
163
0
  if(!data || !data->conn)
164
0
    return CURLE_FAILED_INIT;
165
0
  return Curl_conn_shutdown(data, data->conn->recv_idx, done);
166
0
}
167
168
static bool xfer_recv_shutdown_started(struct Curl_easy *data)
169
0
{
170
0
  if(!data || !data->conn)
171
0
    return FALSE;
172
0
  return Curl_shutdown_started(data, data->conn->recv_idx);
173
0
}
174
175
CURLcode Curl_xfer_send_shutdown(struct Curl_easy *data, bool *done)
176
0
{
177
0
  if(!data || !data->conn)
178
0
    return CURLE_FAILED_INIT;
179
0
  return Curl_conn_shutdown(data, data->conn->send_idx, done);
180
0
}
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
0
{
196
0
  CURLcode result;
197
198
0
  DEBUGASSERT(blen > 0);
199
0
  *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
0
  if(!eos_reliable && !data->req.header && data->req.size != -1) {
203
0
    blen = curlx_sotouz_range(data->req.size - data->req.bytecount, 0, blen);
204
0
  }
205
0
  else if(xfer_recv_shutdown_started(data)) {
206
    /* we already received everything. Do not try more. */
207
0
    blen = 0;
208
0
  }
209
210
0
  if(blen) {
211
0
    result = Curl_xfer_recv(data, buf, blen, pnread);
212
0
    if(result)
213
0
      return result;
214
0
  }
215
216
0
  if(*pnread == 0) {
217
0
    if(data->req.shutdown) {
218
0
      bool done;
219
0
      result = xfer_recv_shutdown(data, &done);
220
0
      if(result)
221
0
        return result;
222
0
      if(!done) {
223
0
        return CURLE_AGAIN;
224
0
      }
225
0
    }
226
0
    DEBUGF(infof(data, "sendrecv_dl: we are done"));
227
0
  }
228
0
  return CURLE_OK;
229
0
}
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
0
{
239
0
  struct connectdata *conn = data->conn;
240
0
  CURLcode result = CURLE_OK;
241
0
  char *buf, *xfer_buf;
242
0
  size_t blen, xfer_blen;
243
0
  int maxloops = 10;
244
0
  curl_off_t total_received = 0;
245
0
  bool is_multiplex = FALSE;
246
0
  bool rcvd_eagain = FALSE;
247
0
  bool is_eos = FALSE;
248
249
0
  result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen);
250
0
  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
0
  do {
256
0
    size_t bytestoread;
257
258
0
    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
0
      is_multiplex = Curl_conn_is_multiplex(conn, FIRSTSOCKET);
263
0
    }
264
265
0
    buf = xfer_buf;
266
0
    bytestoread = xfer_blen;
267
268
0
    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
0
      if(total_received && (total_received >= (data->set.max_recv_speed / 4)))
274
0
        break;
275
0
      if(data->set.max_recv_speed < (curl_off_t)bytestoread)
276
0
        bytestoread = (size_t)data->set.max_recv_speed;
277
0
    }
278
279
0
    rcvd_eagain = FALSE;
280
0
    result = xfer_recv_resp(data, buf, bytestoread, is_multiplex, &blen);
281
0
    if(result) {
282
0
      if(result != CURLE_AGAIN)
283
0
        goto out; /* real error */
284
0
      rcvd_eagain = TRUE;
285
0
      result = CURLE_OK;
286
0
      if(data->req.download_done && data->req.no_body &&
287
0
         !data->req.resp_trailer) {
288
0
        DEBUGF(infof(data, "EAGAIN, download done, no trailer announced, "
289
0
               "not waiting for EOS"));
290
0
        blen = 0;
291
        /* continue as if we received the EOS */
292
0
      }
293
0
      else
294
0
        break; /* get out of loop */
295
0
    }
296
297
    /* We only get a 0-length receive at the end of the response */
298
0
    is_eos = (blen == 0);
299
300
0
    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
0
      if(is_multiplex)
309
0
        DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
310
0
      else
311
0
        DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
312
0
      result = Curl_req_stop_send_recv(data);
313
0
      if(result)
314
0
        goto out;
315
0
      if(k->eos_written) /* already did write this to client, leave */
316
0
        break;
317
0
    }
318
0
    total_received += blen;
319
320
0
    result = Curl_xfer_write_resp(data, buf, blen, is_eos);
321
0
    if(result || data->req.done)
322
0
      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
0
    if((!is_multiplex && data->req.download_done) || is_eos) {
328
0
      data->req.keepon &= ~KEEP_RECV;
329
0
    }
330
    /* if we are PAUSEd or stopped receiving, leave the loop */
331
0
    if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV))
332
0
      break;
333
334
0
  } while(maxloops--);
335
336
0
  if(!is_eos && !Curl_xfer_is_blocked(data) &&
337
0
     (!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
0
    Curl_multi_mark_dirty(data);
341
0
    CURL_TRC_M(data, "sendrecv_dl() no EAGAIN/pending data, mark as dirty");
342
0
  }
343
344
0
  if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
345
0
     (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
0
    infof(data, "we are done reading and this is set to close, stop send");
350
0
    Curl_req_abort_sending(data);
351
0
  }
352
353
0
out:
354
0
  Curl_multi_xfer_buf_release(data, xfer_buf);
355
0
  if(result)
356
0
    DEBUGF(infof(data, "sendrecv_dl() -> %d", result));
357
0
  return result;
358
0
}
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
0
{
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
0
  DEBUGASSERT(!Curl_req_done_sending(data));
369
370
0
  if(!Curl_req_done_sending(data))
371
0
    return Curl_req_send_more(data);
372
0
  return CURLE_OK;
373
0
}
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
0
{
381
0
  struct SingleRequest *k = &data->req;
382
0
  CURLcode result = CURLE_OK;
383
384
0
  DEBUGASSERT(nowp);
385
0
  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
0
  if(k->keepon & KEEP_RECV) {
393
0
    result = sendrecv_dl(data, k);
394
0
    if(result || data->req.done)
395
0
      goto out;
396
0
  }
397
398
  /* If we still have writing to do, we check if we have a writable socket. */
399
0
  if(Curl_req_want_send(data) || (data->req.keepon & KEEP_SEND_TIMED)) {
400
0
    result = sendrecv_ul(data);
401
0
    if(result)
402
0
      goto out;
403
0
  }
404
405
0
  if(Curl_pgrsUpdate(data))
406
0
    result = CURLE_ABORTED_BY_CALLBACK;
407
0
  else
408
0
    result = Curl_speedcheck(data, *nowp);
409
0
  if(result)
410
0
    goto out;
411
412
0
  if(k->keepon) {
413
0
    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
0
  }
431
0
  else {
432
    /*
433
     * The transfer has been performed. Just make some general checks before
434
     * returning.
435
     */
436
0
    if(!(data->req.no_body) && (k->size != -1) &&
437
0
       (k->bytecount != k->size) && !k->newurl) {
438
0
      failf(data, "transfer closed with %" FMT_OFF_T
439
0
            " bytes remaining to read", k->size - k->bytecount);
440
0
      result = CURLE_PARTIAL_FILE;
441
0
      goto out;
442
0
    }
443
0
    if(Curl_pgrsUpdate(data)) {
444
0
      result = CURLE_ABORTED_BY_CALLBACK;
445
0
      goto out;
446
0
    }
447
0
  }
448
449
  /* If there is nothing more to send/recv, the request is done */
450
0
  if((k->keepon & (KEEP_RECVBITS|KEEP_SENDBITS)) == 0)
451
0
    data->req.done = TRUE;
452
453
0
out:
454
0
  if(result)
455
0
    DEBUGF(infof(data, "Curl_sendrecv() -> %d", result));
456
0
  return result;
457
0
}
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
0
{
463
0
  data->state.fread_func = data->set.fread_func_set;
464
0
  data->state.in = data->set.in_set;
465
0
  data->state.upload = (data->state.httpreq == HTTPREQ_PUT);
466
0
}
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
0
{
475
0
  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
0
  data->state.retrycount = 0;
484
485
0
  if(!data->set.str[STRING_SET_URL] && !data->set.uh) {
486
    /* we cannot do anything without URL */
487
0
    failf(data, "No URL set");
488
0
    return CURLE_URL_MALFORMAT;
489
0
  }
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
0
  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
0
  if(data->state.url_alloc) {
506
0
    Curl_safefree(data->state.url);
507
0
    data->state.url_alloc = FALSE;
508
0
  }
509
510
0
  data->state.url = data->set.str[STRING_SET_URL];
511
512
0
  if(data->set.postfields && data->set.set_resume_from) {
513
    /* we cannot */
514
0
    failf(data, "cannot mix POSTFIELDS with RESUME_FROM");
515
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
516
0
  }
517
518
0
  data->state.prefer_ascii = data->set.prefer_ascii;
519
0
#ifdef CURL_LIST_ONLY_PROTOCOL
520
0
  data->state.list_only = data->set.list_only;
521
0
#endif
522
0
  data->state.httpreq = data->set.method;
523
524
0
  data->state.requests = 0;
525
0
  data->state.followlocation = 0; /* reset the location-follow counter */
526
0
  data->state.this_is_a_follow = FALSE; /* reset this */
527
0
  data->state.errorbuf = FALSE; /* no error has occurred */
528
0
#ifndef CURL_DISABLE_HTTP
529
0
  Curl_http_neg_init(data, &data->state.http_neg);
530
0
#endif
531
0
  data->state.authproblem = FALSE;
532
0
  data->state.authhost.want = data->set.httpauth;
533
0
  data->state.authproxy.want = data->set.proxyauth;
534
0
  Curl_safefree(data->info.wouldredirect);
535
0
  Curl_data_priority_clear_state(data);
536
537
0
  if(data->state.httpreq == HTTPREQ_PUT)
538
0
    data->state.infilesize = data->set.filesize;
539
0
  else if((data->state.httpreq != HTTPREQ_GET) &&
540
0
          (data->state.httpreq != HTTPREQ_HEAD)) {
541
0
    data->state.infilesize = data->set.postfieldsize;
542
0
    if(data->set.postfields && (data->state.infilesize == -1))
543
0
      data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
544
0
  }
545
0
  else
546
0
    data->state.infilesize = 0;
547
548
  /* If there is a list of cookie files to read, do it now! */
549
0
  result = Curl_cookie_loadfiles(data);
550
0
  if(!result)
551
0
    Curl_cookie_run(data); /* activate */
552
553
  /* If there is a list of host pairs to deal with */
554
0
  if(!result && data->state.resolve)
555
0
    result = Curl_loadhostpairs(data);
556
557
0
  if(!result)
558
    /* If there is a list of hsts files to read */
559
0
    result = Curl_hsts_loadfiles(data);
560
561
0
  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
0
    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
0
    Curl_initinfo(data); /* reset session-specific information "variables" */
576
0
    Curl_pgrsResetTransferSizes(data);
577
0
    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
0
    data->state.authhost.picked &= data->state.authhost.want;
583
0
    data->state.authproxy.picked &= data->state.authproxy.want;
584
585
0
#ifndef CURL_DISABLE_FTP
586
0
    data->state.wildcardmatch = data->set.wildcard_enabled;
587
0
    if(data->state.wildcardmatch) {
588
0
      struct WildcardData *wc;
589
0
      if(!data->wildcard) {
590
0
        data->wildcard = calloc(1, sizeof(struct WildcardData));
591
0
        if(!data->wildcard)
592
0
          return CURLE_OUT_OF_MEMORY;
593
0
      }
594
0
      wc = data->wildcard;
595
0
      if(wc->state < CURLWC_INIT) {
596
0
        if(wc->ftpwc)
597
0
          wc->dtor(wc->ftpwc);
598
0
        Curl_safefree(wc->pattern);
599
0
        Curl_safefree(wc->path);
600
0
        Curl_wildcard_init(wc); /* init wildcard structures */
601
0
      }
602
0
    }
603
0
#endif
604
0
    result = Curl_hsts_loadcb(data, data->hsts);
605
0
  }
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
0
  if(!result && data->set.str[STRING_USERAGENT]) {
613
0
    free(data->state.aptr.uagent);
614
0
    data->state.aptr.uagent =
615
0
      curl_maprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
616
0
    if(!data->state.aptr.uagent)
617
0
      return CURLE_OUT_OF_MEMORY;
618
0
  }
619
620
0
  if(data->set.str[STRING_USERNAME] ||
621
0
     data->set.str[STRING_PASSWORD])
622
0
    data->state.creds_from = CREDS_OPTION;
623
0
  if(!result)
624
0
    result = Curl_setstropt(&data->state.aptr.user,
625
0
                            data->set.str[STRING_USERNAME]);
626
0
  if(!result)
627
0
    result = Curl_setstropt(&data->state.aptr.passwd,
628
0
                            data->set.str[STRING_PASSWORD]);
629
0
#ifndef CURL_DISABLE_PROXY
630
0
  if(!result)
631
0
    result = Curl_setstropt(&data->state.aptr.proxyuser,
632
0
                            data->set.str[STRING_PROXYUSERNAME]);
633
0
  if(!result)
634
0
    result = Curl_setstropt(&data->state.aptr.proxypasswd,
635
0
                            data->set.str[STRING_PROXYPASSWORD]);
636
0
#endif
637
638
0
  data->req.headerbytecount = 0;
639
0
  Curl_headers_cleanup(data);
640
0
  return result;
641
0
}
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
0
{
648
0
  struct connectdata *conn = data->conn;
649
0
  bool retry = FALSE;
650
0
  *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
0
  if(data->state.upload &&
656
0
     !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
657
0
    return CURLE_OK;
658
659
0
  if(conn->bits.reuse &&
660
0
     (data->req.bytecount + data->req.headerbytecount == 0) &&
661
0
     ((!data->req.no_body && !data->req.done) ||
662
0
      (conn->handler->protocol & PROTO_FAMILY_HTTP))
663
0
#ifndef CURL_DISABLE_RTSP
664
0
     && (data->set.rtspreq != RTSPREQ_RECEIVE)
665
0
#endif
666
0
    )
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
0
    retry = TRUE;
675
0
  else if(data->state.refused_stream &&
676
0
          (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
0
    infof(data, "REFUSED_STREAM, retrying a fresh connect");
683
0
    data->state.refused_stream = FALSE; /* clear again */
684
0
    retry = TRUE;
685
0
  }
686
0
  if(retry) {
687
0
#define CONN_MAX_RETRIES 5
688
0
    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
0
    infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
695
0
          data->state.retrycount);
696
0
    *url = strdup(data->state.url);
697
0
    if(!*url)
698
0
      return CURLE_OUT_OF_MEMORY;
699
700
0
    connclose(conn, "retry"); /* close this connection */
701
0
    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
0
    Curl_creader_set_rewind(data, TRUE);
707
0
  }
708
0
  return CURLE_OK;
709
0
}
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
0
{
718
0
  struct SingleRequest *k = &data->req;
719
0
  struct connectdata *conn = data->conn;
720
721
0
  DEBUGASSERT(conn != NULL);
722
  /* indexes are in range */
723
0
  DEBUGASSERT((send_idx <= 1) && (send_idx >= -1));
724
0
  DEBUGASSERT((recv_idx <= 1) && (recv_idx >= -1));
725
  /* if request wants to send, switching off the send direction is wrong */
726
0
  DEBUGASSERT((send_idx >= 0) || !Curl_req_want_send(data));
727
728
0
  conn->send_idx = send_idx;
729
0
  conn->recv_idx = recv_idx;
730
731
  /* without receiving, there should be not recv_size */
732
0
  DEBUGASSERT((conn->recv_idx >= 0) || (recv_size == -1));
733
0
  k->size = recv_size;
734
0
  k->header = !!conn->handler->write_resp_hd;
735
  /* by default, we do not shutdown at the end of the transfer */
736
0
  k->shutdown = FALSE;
737
0
  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
0
  if(!k->header && (recv_size > 0))
743
0
    Curl_pgrsSetDownloadSize(data, recv_size);
744
745
  /* we want header and/or body, if neither then do not do this! */
746
0
  if(conn->handler->write_resp_hd || !data->req.no_body) {
747
748
0
    if(conn->recv_idx != -1)
749
0
      k->keepon |= KEEP_RECV;
750
751
0
    if(conn->send_idx != -1)
752
0
      k->keepon |= KEEP_SEND;
753
0
  }
754
755
0
  CURL_TRC_M(data, "xfer_setup: recv_idx=%d, send_idx=%d",
756
0
             conn->recv_idx, conn->send_idx);
757
0
}
758
759
void Curl_xfer_setup_nop(struct Curl_easy *data)
760
0
{
761
0
  xfer_setup(data, -1, -1, -1);
762
0
}
763
764
void Curl_xfer_setup_sendrecv(struct Curl_easy *data,
765
                              int sockindex,
766
                              curl_off_t recv_size)
767
0
{
768
0
  xfer_setup(data, sockindex, sockindex, recv_size);
769
0
}
770
771
void Curl_xfer_setup_send(struct Curl_easy *data,
772
                          int sockindex)
773
0
{
774
0
  xfer_setup(data, sockindex, -1, -1);
775
0
}
776
777
void Curl_xfer_setup_recv(struct Curl_easy *data,
778
                          int sockindex,
779
                          curl_off_t recv_size)
780
0
{
781
0
  xfer_setup(data, -1, sockindex, recv_size);
782
0
}
783
784
void Curl_xfer_set_shutdown(struct Curl_easy *data,
785
                            bool shutdown,
786
                            bool ignore_errors)
787
0
{
788
  /* Shutdown should only be set when the transfer only sends or receives. */
789
0
  DEBUGASSERT(!shutdown ||
790
0
              (data->conn->send_idx < 0) || (data->conn->recv_idx < 0));
791
0
  data->req.shutdown = shutdown;
792
0
  data->req.shutdown_err_ignore = ignore_errors;
793
0
}
794
795
CURLcode Curl_xfer_write_resp(struct Curl_easy *data,
796
                              const char *buf, size_t blen,
797
                              bool is_eos)
798
0
{
799
0
  CURLcode result = CURLE_OK;
800
801
0
  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
0
    result = data->conn->handler->write_resp(data, buf, blen, is_eos);
805
0
  }
806
0
  else {
807
    /* No special handling by protocol handler, write all received data
808
     * as BODY to the client. */
809
0
    if(blen || is_eos) {
810
0
      int cwtype = CLIENTWRITE_BODY;
811
0
      if(is_eos)
812
0
        cwtype |= CLIENTWRITE_EOS;
813
0
      result = Curl_client_write(data, cwtype, buf, blen);
814
0
    }
815
0
  }
816
817
0
  if(!result && is_eos) {
818
    /* If we wrote the EOS, we are definitely done */
819
0
    data->req.eos_written = TRUE;
820
0
    data->req.download_done = TRUE;
821
0
  }
822
0
  CURL_TRC_WRITE(data, "xfer_write_resp(len=%zu, eos=%d) -> %d",
823
0
                 blen, is_eos, result);
824
0
  return result;
825
0
}
826
827
bool Curl_xfer_write_is_paused(struct Curl_easy *data)
828
0
{
829
0
  return Curl_cwriter_is_paused(data);
830
0
}
831
832
CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data,
833
                                 const char *hd0, size_t hdlen, bool is_eos)
834
0
{
835
0
  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
0
    return data->conn->handler->write_resp_hd(data, hd0, hdlen, is_eos);
839
0
  }
840
  /* No special handling by protocol handler, write as response bytes */
841
0
  return Curl_xfer_write_resp(data, hd0, hdlen, is_eos);
842
0
}
843
844
CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature)
845
0
{
846
0
  (void)premature;
847
0
  return Curl_cw_out_done(data);
848
0
}
849
850
bool Curl_xfer_needs_flush(struct Curl_easy *data)
851
0
{
852
0
  return Curl_conn_needs_flush(data, data->conn->send_idx);
853
0
}
854
855
CURLcode Curl_xfer_flush(struct Curl_easy *data)
856
0
{
857
0
  return Curl_conn_flush(data, data->conn->send_idx);
858
0
}
859
860
CURLcode Curl_xfer_send(struct Curl_easy *data,
861
                        const void *buf, size_t blen, bool eos,
862
                        size_t *pnwritten)
863
0
{
864
0
  CURLcode result;
865
866
0
  DEBUGASSERT(data);
867
0
  DEBUGASSERT(data->conn);
868
869
0
  result = Curl_conn_send(data, data->conn->send_idx,
870
0
                          buf, blen, eos, pnwritten);
871
0
  if(result == CURLE_AGAIN) {
872
0
    result = CURLE_OK;
873
0
    *pnwritten = 0;
874
0
  }
875
0
  else if(!result && *pnwritten)
876
0
    data->info.request_size += *pnwritten;
877
878
0
  DEBUGF(infof(data, "Curl_xfer_send(len=%zu, eos=%d) -> %d, %zu",
879
0
               blen, eos, result, *pnwritten));
880
0
  return result;
881
0
}
882
883
CURLcode Curl_xfer_recv(struct Curl_easy *data,
884
                        char *buf, size_t blen,
885
                        size_t *pnrcvd)
886
0
{
887
0
  DEBUGASSERT(data);
888
0
  DEBUGASSERT(data->conn);
889
0
  DEBUGASSERT(data->set.buffer_size > 0);
890
891
0
  if(curlx_uitouz(data->set.buffer_size) < blen)
892
0
    blen = curlx_uitouz(data->set.buffer_size);
893
0
  return Curl_conn_recv(data, data->conn->recv_idx, buf, blen, pnrcvd);
894
0
}
895
896
CURLcode Curl_xfer_send_close(struct Curl_easy *data)
897
0
{
898
0
  Curl_conn_ev_data_done_send(data);
899
0
  return CURLE_OK;
900
0
}
901
902
bool Curl_xfer_is_blocked(struct Curl_easy *data)
903
0
{
904
0
  bool want_send = ((data)->req.keepon & KEEP_SEND);
905
0
  bool want_recv = ((data)->req.keepon & KEEP_RECV);
906
0
  if(!want_send)
907
0
    return want_recv && Curl_xfer_recv_is_paused(data);
908
0
  else if(!want_recv)
909
0
    return want_send && Curl_xfer_send_is_paused(data);
910
0
  else
911
0
    return Curl_xfer_recv_is_paused(data) && Curl_xfer_send_is_paused(data);
912
0
}
913
914
bool Curl_xfer_send_is_paused(struct Curl_easy *data)
915
0
{
916
0
  return (data->req.keepon & KEEP_SEND_PAUSE);
917
0
}
918
919
bool Curl_xfer_recv_is_paused(struct Curl_easy *data)
920
0
{
921
0
  return (data->req.keepon & KEEP_RECV_PAUSE);
922
0
}
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
0
{
955
0
  struct Curl_llist_node *e = Curl_llist_head(&data->state.timeoutlist);
956
0
  while(e) {
957
0
    struct time_node *n = Curl_node_elem(e);
958
0
    e = Curl_node_next(e);
959
0
    if(n->eid == EXPIRE_TOOFAST)
960
0
      return TRUE;
961
0
  }
962
0
  return FALSE;
963
0
}