Coverage Report

Created: 2026-07-30 07:03

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