Coverage Report

Created: 2026-01-09 07:14

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