Coverage Report

Created: 2023-06-07 07:02

/src/curl/lib/transfer.c
Line
Count
Source (jump to first uncovered line)
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
#include "strtoofft.h"
27
28
#ifdef HAVE_NETINET_IN_H
29
#include <netinet/in.h>
30
#endif
31
#ifdef HAVE_NETDB_H
32
#include <netdb.h>
33
#endif
34
#ifdef HAVE_ARPA_INET_H
35
#include <arpa/inet.h>
36
#endif
37
#ifdef HAVE_NET_IF_H
38
#include <net/if.h>
39
#endif
40
#ifdef HAVE_SYS_IOCTL_H
41
#include <sys/ioctl.h>
42
#endif
43
#ifdef HAVE_SIGNAL_H
44
#include <signal.h>
45
#endif
46
47
#ifdef HAVE_SYS_PARAM_H
48
#include <sys/param.h>
49
#endif
50
51
#ifdef HAVE_SYS_SELECT_H
52
#include <sys/select.h>
53
#elif defined(HAVE_UNISTD_H)
54
#include <unistd.h>
55
#endif
56
57
#ifndef HAVE_SOCKET
58
#error "We can't compile without socket() support!"
59
#endif
60
61
#include "urldata.h"
62
#include <curl/curl.h>
63
#include "netrc.h"
64
65
#include "content_encoding.h"
66
#include "hostip.h"
67
#include "cfilters.h"
68
#include "transfer.h"
69
#include "sendf.h"
70
#include "speedcheck.h"
71
#include "progress.h"
72
#include "http.h"
73
#include "url.h"
74
#include "getinfo.h"
75
#include "vtls/vtls.h"
76
#include "vquic/vquic.h"
77
#include "select.h"
78
#include "multiif.h"
79
#include "connect.h"
80
#include "http2.h"
81
#include "mime.h"
82
#include "strcase.h"
83
#include "urlapi-int.h"
84
#include "hsts.h"
85
#include "setopt.h"
86
#include "headers.h"
87
88
/* The last 3 #include files should be in this order */
89
#include "curl_printf.h"
90
#include "curl_memory.h"
91
#include "memdebug.h"
92
93
#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
94
    !defined(CURL_DISABLE_IMAP)
95
/*
96
 * checkheaders() checks the linked list of custom headers for a
97
 * particular header (prefix). Provide the prefix without colon!
98
 *
99
 * Returns a pointer to the first matching header or NULL if none matched.
100
 */
101
char *Curl_checkheaders(const struct Curl_easy *data,
102
                        const char *thisheader,
103
                        const size_t thislen)
104
0
{
105
0
  struct curl_slist *head;
106
0
  DEBUGASSERT(thislen);
107
0
  DEBUGASSERT(thisheader[thislen-1] != ':');
108
109
0
  for(head = data->set.headers; head; head = head->next) {
110
0
    if(strncasecompare(head->data, thisheader, thislen) &&
111
0
       Curl_headersep(head->data[thislen]) )
112
0
      return head->data;
113
0
  }
114
115
0
  return NULL;
116
0
}
117
#endif
118
119
CURLcode Curl_get_upload_buffer(struct Curl_easy *data)
120
0
{
121
0
  if(!data->state.ulbuf) {
122
0
    data->state.ulbuf = malloc(data->set.upload_buffer_size);
123
0
    if(!data->state.ulbuf)
124
0
      return CURLE_OUT_OF_MEMORY;
125
0
  }
126
0
  return CURLE_OK;
127
0
}
128
129
#ifndef CURL_DISABLE_HTTP
130
/*
131
 * This function will be called to loop through the trailers buffer
132
 * until no more data is available for sending.
133
 */
134
static size_t trailers_read(char *buffer, size_t size, size_t nitems,
135
                            void *raw)
136
0
{
137
0
  struct Curl_easy *data = (struct Curl_easy *)raw;
138
0
  struct dynbuf *trailers_buf = &data->state.trailers_buf;
139
0
  size_t bytes_left = Curl_dyn_len(trailers_buf) -
140
0
    data->state.trailers_bytes_sent;
141
0
  size_t to_copy = (size*nitems < bytes_left) ? size*nitems : bytes_left;
142
0
  if(to_copy) {
143
0
    memcpy(buffer,
144
0
           Curl_dyn_ptr(trailers_buf) + data->state.trailers_bytes_sent,
145
0
           to_copy);
146
0
    data->state.trailers_bytes_sent += to_copy;
147
0
  }
148
0
  return to_copy;
149
0
}
150
151
static size_t trailers_left(void *raw)
152
0
{
153
0
  struct Curl_easy *data = (struct Curl_easy *)raw;
154
0
  struct dynbuf *trailers_buf = &data->state.trailers_buf;
155
0
  return Curl_dyn_len(trailers_buf) - data->state.trailers_bytes_sent;
156
0
}
157
#endif
158
159
/*
160
 * This function will call the read callback to fill our buffer with data
161
 * to upload.
162
 */
163
CURLcode Curl_fillreadbuffer(struct Curl_easy *data, size_t bytes,
164
                             size_t *nreadp)
165
0
{
166
0
  size_t buffersize = bytes;
167
0
  size_t nread;
168
169
0
  curl_read_callback readfunc = NULL;
170
0
  void *extra_data = NULL;
171
172
0
#ifndef CURL_DISABLE_HTTP
173
0
  if(data->state.trailers_state == TRAILERS_INITIALIZED) {
174
0
    struct curl_slist *trailers = NULL;
175
0
    CURLcode result;
176
0
    int trailers_ret_code;
177
178
    /* at this point we already verified that the callback exists
179
       so we compile and store the trailers buffer, then proceed */
180
0
    infof(data,
181
0
          "Moving trailers state machine from initialized to sending.");
182
0
    data->state.trailers_state = TRAILERS_SENDING;
183
0
    Curl_dyn_init(&data->state.trailers_buf, DYN_TRAILERS);
184
185
0
    data->state.trailers_bytes_sent = 0;
186
0
    Curl_set_in_callback(data, true);
187
0
    trailers_ret_code = data->set.trailer_callback(&trailers,
188
0
                                                   data->set.trailer_data);
189
0
    Curl_set_in_callback(data, false);
190
0
    if(trailers_ret_code == CURL_TRAILERFUNC_OK) {
191
0
      result = Curl_http_compile_trailers(trailers, &data->state.trailers_buf,
192
0
                                          data);
193
0
    }
194
0
    else {
195
0
      failf(data, "operation aborted by trailing headers callback");
196
0
      *nreadp = 0;
197
0
      result = CURLE_ABORTED_BY_CALLBACK;
198
0
    }
199
0
    if(result) {
200
0
      Curl_dyn_free(&data->state.trailers_buf);
201
0
      curl_slist_free_all(trailers);
202
0
      return result;
203
0
    }
204
0
    infof(data, "Successfully compiled trailers.");
205
0
    curl_slist_free_all(trailers);
206
0
  }
207
0
#endif
208
209
0
#ifndef CURL_DISABLE_HTTP
210
  /* if we are transmitting trailing data, we don't need to write
211
     a chunk size so we skip this */
212
0
  if(data->req.upload_chunky &&
213
0
     data->state.trailers_state == TRAILERS_NONE) {
214
    /* if chunked Transfer-Encoding */
215
0
    buffersize -= (8 + 2 + 2);   /* 32bit hex + CRLF + CRLF */
216
0
    data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
217
0
  }
218
219
0
  if(data->state.trailers_state == TRAILERS_SENDING) {
220
    /* if we're here then that means that we already sent the last empty chunk
221
       but we didn't send a final CR LF, so we sent 0 CR LF. We then start
222
       pulling trailing data until we have no more at which point we
223
       simply return to the previous point in the state machine as if
224
       nothing happened.
225
       */
226
0
    readfunc = trailers_read;
227
0
    extra_data = (void *)data;
228
0
  }
229
0
  else
230
0
#endif
231
0
  {
232
0
    readfunc = data->state.fread_func;
233
0
    extra_data = data->state.in;
234
0
  }
235
236
0
  Curl_set_in_callback(data, true);
237
0
  nread = readfunc(data->req.upload_fromhere, 1,
238
0
                   buffersize, extra_data);
239
0
  Curl_set_in_callback(data, false);
240
241
0
  if(nread == CURL_READFUNC_ABORT) {
242
0
    failf(data, "operation aborted by callback");
243
0
    *nreadp = 0;
244
0
    return CURLE_ABORTED_BY_CALLBACK;
245
0
  }
246
0
  if(nread == CURL_READFUNC_PAUSE) {
247
0
    struct SingleRequest *k = &data->req;
248
249
0
    if(data->conn->handler->flags & PROTOPT_NONETWORK) {
250
      /* protocols that work without network cannot be paused. This is
251
         actually only FILE:// just now, and it can't pause since the transfer
252
         isn't done using the "normal" procedure. */
253
0
      failf(data, "Read callback asked for PAUSE when not supported");
254
0
      return CURLE_READ_ERROR;
255
0
    }
256
257
    /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
258
0
    k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
259
0
    if(data->req.upload_chunky) {
260
        /* Back out the preallocation done above */
261
0
      data->req.upload_fromhere -= (8 + 2);
262
0
    }
263
0
    *nreadp = 0;
264
265
0
    return CURLE_OK; /* nothing was read */
266
0
  }
267
0
  else if(nread > buffersize) {
268
    /* the read function returned a too large value */
269
0
    *nreadp = 0;
270
0
    failf(data, "read function returned funny value");
271
0
    return CURLE_READ_ERROR;
272
0
  }
273
274
0
#ifndef CURL_DISABLE_HTTP
275
0
  if(!data->req.forbidchunk && data->req.upload_chunky) {
276
    /* if chunked Transfer-Encoding
277
     *    build chunk:
278
     *
279
     *        <HEX SIZE> CRLF
280
     *        <DATA> CRLF
281
     */
282
    /* On non-ASCII platforms the <DATA> may or may not be
283
       translated based on state.prefer_ascii while the protocol
284
       portion must always be translated to the network encoding.
285
       To further complicate matters, line end conversion might be
286
       done later on, so we need to prevent CRLFs from becoming
287
       CRCRLFs if that's the case.  To do this we use bare LFs
288
       here, knowing they'll become CRLFs later on.
289
     */
290
291
0
    bool added_crlf = FALSE;
292
0
    int hexlen = 0;
293
0
    const char *endofline_native;
294
0
    const char *endofline_network;
295
296
0
    if(
297
0
#ifdef CURL_DO_LINEEND_CONV
298
0
       (data->state.prefer_ascii) ||
299
0
#endif
300
0
       (data->set.crlf)) {
301
      /* \n will become \r\n later on */
302
0
      endofline_native  = "\n";
303
0
      endofline_network = "\x0a";
304
0
    }
305
0
    else {
306
0
      endofline_native  = "\r\n";
307
0
      endofline_network = "\x0d\x0a";
308
0
    }
309
310
    /* if we're not handling trailing data, proceed as usual */
311
0
    if(data->state.trailers_state != TRAILERS_SENDING) {
312
0
      char hexbuffer[11] = "";
313
0
      hexlen = msnprintf(hexbuffer, sizeof(hexbuffer),
314
0
                         "%zx%s", nread, endofline_native);
315
316
      /* move buffer pointer */
317
0
      data->req.upload_fromhere -= hexlen;
318
0
      nread += hexlen;
319
320
      /* copy the prefix to the buffer, leaving out the NUL */
321
0
      memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
322
323
      /* always append ASCII CRLF to the data unless
324
         we have a valid trailer callback */
325
0
      if((nread-hexlen) == 0 &&
326
0
          data->set.trailer_callback != NULL &&
327
0
          data->state.trailers_state == TRAILERS_NONE) {
328
0
        data->state.trailers_state = TRAILERS_INITIALIZED;
329
0
      }
330
0
      else {
331
0
        memcpy(data->req.upload_fromhere + nread,
332
0
               endofline_network,
333
0
               strlen(endofline_network));
334
0
        added_crlf = TRUE;
335
0
      }
336
0
    }
337
338
0
    if(data->state.trailers_state == TRAILERS_SENDING &&
339
0
       !trailers_left(data)) {
340
0
      Curl_dyn_free(&data->state.trailers_buf);
341
0
      data->state.trailers_state = TRAILERS_DONE;
342
0
      data->set.trailer_data = NULL;
343
0
      data->set.trailer_callback = NULL;
344
      /* mark the transfer as done */
345
0
      data->req.upload_done = TRUE;
346
0
      infof(data, "Signaling end of chunked upload after trailers.");
347
0
    }
348
0
    else
349
0
      if((nread - hexlen) == 0 &&
350
0
         data->state.trailers_state != TRAILERS_INITIALIZED) {
351
        /* mark this as done once this chunk is transferred */
352
0
        data->req.upload_done = TRUE;
353
0
        infof(data,
354
0
              "Signaling end of chunked upload via terminating chunk.");
355
0
      }
356
357
0
    if(added_crlf)
358
0
      nread += strlen(endofline_network); /* for the added end of line */
359
0
  }
360
0
#endif
361
362
0
  *nreadp = nread;
363
364
0
  return CURLE_OK;
365
0
}
366
367
static int data_pending(struct Curl_easy *data)
368
0
{
369
0
  struct connectdata *conn = data->conn;
370
371
0
  if(conn->handler->protocol&PROTO_FAMILY_FTP)
372
0
    return Curl_conn_data_pending(data, SECONDARYSOCKET);
373
374
  /* in the case of libssh2, we can never be really sure that we have emptied
375
     its internal buffers so we MUST always try until we get EAGAIN back */
376
0
  return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
377
0
    Curl_conn_data_pending(data, FIRSTSOCKET);
378
0
}
379
380
/*
381
 * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
382
 * remote document with the time provided by CURLOPT_TIMEVAL
383
 */
384
bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
385
0
{
386
0
  if((timeofdoc == 0) || (data->set.timevalue == 0))
387
0
    return TRUE;
388
389
0
  switch(data->set.timecondition) {
390
0
  case CURL_TIMECOND_IFMODSINCE:
391
0
  default:
392
0
    if(timeofdoc <= data->set.timevalue) {
393
0
      infof(data,
394
0
            "The requested document is not new enough");
395
0
      data->info.timecond = TRUE;
396
0
      return FALSE;
397
0
    }
398
0
    break;
399
0
  case CURL_TIMECOND_IFUNMODSINCE:
400
0
    if(timeofdoc >= data->set.timevalue) {
401
0
      infof(data,
402
0
            "The requested document is not old enough");
403
0
      data->info.timecond = TRUE;
404
0
      return FALSE;
405
0
    }
406
0
    break;
407
0
  }
408
409
0
  return TRUE;
410
0
}
411
412
/*
413
 * Go ahead and do a read if we have a readable socket or if
414
 * the stream was rewound (in which case we have data in a
415
 * buffer)
416
 *
417
 * return '*comeback' TRUE if we didn't properly drain the socket so this
418
 * function should get called again without select() or similar in between!
419
 */
420
static CURLcode readwrite_data(struct Curl_easy *data,
421
                               struct connectdata *conn,
422
                               struct SingleRequest *k,
423
                               int *didwhat, bool *done,
424
                               bool *comeback)
425
0
{
426
0
  CURLcode result = CURLE_OK;
427
0
  ssize_t nread; /* number of bytes read */
428
0
  size_t excess = 0; /* excess bytes read */
429
0
  bool readmore = FALSE; /* used by RTP to signal for more data */
430
0
  int maxloops = 100;
431
0
  curl_off_t max_recv = data->set.max_recv_speed?
432
0
                        data->set.max_recv_speed : CURL_OFF_T_MAX;
433
0
  char *buf = data->state.buffer;
434
0
  DEBUGASSERT(buf);
435
436
0
  *done = FALSE;
437
0
  *comeback = FALSE;
438
439
  /* This is where we loop until we have read everything there is to
440
     read or we get a CURLE_AGAIN */
441
0
  do {
442
0
    bool is_empty_data = FALSE;
443
0
    size_t buffersize = data->set.buffer_size;
444
0
    size_t bytestoread = buffersize;
445
    /* For HTTP/2 and HTTP/3, read data without caring about the content
446
       length. This is safe because body in HTTP/2 is always segmented
447
       thanks to its framing layer. Meanwhile, we have to call Curl_read
448
       to ensure that http2_handle_stream_close is called when we read all
449
       incoming bytes for a particular stream. */
450
0
    bool is_http3 = Curl_conn_is_http3(data, conn, FIRSTSOCKET);
451
0
    bool data_eof_handled = is_http3
452
0
                            || Curl_conn_is_http2(data, conn, FIRSTSOCKET);
453
454
0
    if(!data_eof_handled && k->size != -1 && !k->header) {
455
      /* make sure we don't read too much */
456
0
      curl_off_t totalleft = k->size - k->bytecount;
457
0
      if(totalleft < (curl_off_t)bytestoread)
458
0
        bytestoread = (size_t)totalleft;
459
0
    }
460
461
0
    if(bytestoread) {
462
      /* receive data from the network! */
463
0
      result = Curl_read(data, conn->sockfd, buf, bytestoread, &nread);
464
465
      /* read would've blocked */
466
0
      if(CURLE_AGAIN == result) {
467
0
        result = CURLE_OK;
468
0
        break; /* get out of loop */
469
0
      }
470
471
0
      if(result>0)
472
0
        goto out;
473
0
    }
474
0
    else {
475
      /* read nothing but since we wanted nothing we consider this an OK
476
         situation to proceed from */
477
0
      DEBUGF(infof(data, DMSG(data, "readwrite_data: we're done")));
478
0
      nread = 0;
479
0
    }
480
481
0
    if(!k->bytecount) {
482
0
      Curl_pgrsTime(data, TIMER_STARTTRANSFER);
483
0
      if(k->exp100 > EXP100_SEND_DATA)
484
        /* set time stamp to compare with when waiting for the 100 */
485
0
        k->start100 = Curl_now();
486
0
    }
487
488
0
    *didwhat |= KEEP_RECV;
489
    /* indicates data of zero size, i.e. empty file */
490
0
    is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
491
492
0
    if(0 < nread || is_empty_data) {
493
0
      buf[nread] = 0;
494
0
    }
495
0
    else {
496
      /* if we receive 0 or less here, either the data transfer is done or the
497
         server closed the connection and we bail out from this! */
498
0
      if(data_eof_handled)
499
0
        DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
500
0
      else
501
0
        DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
502
0
      k->keepon &= ~KEEP_RECV;
503
0
      break;
504
0
    }
505
506
    /* Default buffer to use when we write the buffer, it may be changed
507
       in the flow below before the actual storing is done. */
508
0
    k->str = buf;
509
510
0
    if(conn->handler->readwrite) {
511
0
      result = conn->handler->readwrite(data, conn, &nread, &readmore);
512
0
      if(result)
513
0
        goto out;
514
0
      if(readmore)
515
0
        break;
516
0
    }
517
518
0
#ifndef CURL_DISABLE_HTTP
519
    /* Since this is a two-state thing, we check if we are parsing
520
       headers at the moment or not. */
521
0
    if(k->header) {
522
      /* we are in parse-the-header-mode */
523
0
      bool stop_reading = FALSE;
524
0
      result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
525
0
      if(result)
526
0
        goto out;
527
528
0
      if(conn->handler->readwrite &&
529
0
         (k->maxdownload <= 0 && nread > 0)) {
530
0
        result = conn->handler->readwrite(data, conn, &nread, &readmore);
531
0
        if(result)
532
0
          goto out;
533
0
        if(readmore)
534
0
          break;
535
0
      }
536
537
0
      if(stop_reading) {
538
        /* We've stopped dealing with input, get out of the do-while loop */
539
540
0
        if(nread > 0) {
541
0
          infof(data,
542
0
                "Excess found:"
543
0
                " excess = %zd"
544
0
                " url = %s (zero-length body)",
545
0
                nread, data->state.up.path);
546
0
        }
547
548
0
        break;
549
0
      }
550
0
    }
551
0
#endif /* CURL_DISABLE_HTTP */
552
553
554
    /* This is not an 'else if' since it may be a rest from the header
555
       parsing, where the beginning of the buffer is headers and the end
556
       is non-headers. */
557
0
    if(!k->header && (nread > 0 || is_empty_data)) {
558
559
0
      if(data->req.no_body) {
560
        /* data arrives although we want none, bail out */
561
0
        streamclose(conn, "ignoring body");
562
0
        *done = TRUE;
563
0
        result = CURLE_WEIRD_SERVER_REPLY;
564
0
        goto out;
565
0
      }
566
567
0
#ifndef CURL_DISABLE_HTTP
568
0
      if(0 == k->bodywrites && !is_empty_data) {
569
        /* These checks are only made the first time we are about to
570
           write a piece of the body */
571
0
        if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
572
          /* HTTP-only checks */
573
0
          result = Curl_http_firstwrite(data, conn, done);
574
0
          if(result || *done)
575
0
            goto out;
576
0
        }
577
0
      } /* this is the first time we write a body part */
578
0
#endif /* CURL_DISABLE_HTTP */
579
580
0
      k->bodywrites++;
581
582
      /* pass data to the debug function before it gets "dechunked" */
583
0
      if(data->set.verbose) {
584
0
        if(k->badheader) {
585
0
          Curl_debug(data, CURLINFO_DATA_IN,
586
0
                     Curl_dyn_ptr(&data->state.headerb),
587
0
                     Curl_dyn_len(&data->state.headerb));
588
0
          if(k->badheader == HEADER_PARTHEADER)
589
0
            Curl_debug(data, CURLINFO_DATA_IN,
590
0
                       k->str, (size_t)nread);
591
0
        }
592
0
        else
593
0
          Curl_debug(data, CURLINFO_DATA_IN,
594
0
                     k->str, (size_t)nread);
595
0
      }
596
597
0
#ifndef CURL_DISABLE_HTTP
598
0
      if(k->chunk) {
599
        /*
600
         * Here comes a chunked transfer flying and we need to decode this
601
         * properly.  While the name says read, this function both reads
602
         * and writes away the data. The returned 'nread' holds the number
603
         * of actual data it wrote to the client.
604
         */
605
0
        CURLcode extra;
606
0
        CHUNKcode res =
607
0
          Curl_httpchunk_read(data, k->str, nread, &nread, &extra);
608
609
0
        if(CHUNKE_OK < res) {
610
0
          if(CHUNKE_PASSTHRU_ERROR == res) {
611
0
            failf(data, "Failed reading the chunked-encoded stream");
612
0
            result = extra;
613
0
            goto out;
614
0
          }
615
0
          failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res));
616
0
          result = CURLE_RECV_ERROR;
617
0
          goto out;
618
0
        }
619
0
        if(CHUNKE_STOP == res) {
620
          /* we're done reading chunks! */
621
0
          k->keepon &= ~KEEP_RECV; /* read no more */
622
623
          /* N number of bytes at the end of the str buffer that weren't
624
             written to the client. */
625
0
          if(conn->chunk.datasize) {
626
0
            infof(data, "Leftovers after chunking: % "
627
0
                  CURL_FORMAT_CURL_OFF_T "u bytes",
628
0
                  conn->chunk.datasize);
629
0
          }
630
0
        }
631
        /* If it returned OK, we just keep going */
632
0
      }
633
0
#endif   /* CURL_DISABLE_HTTP */
634
635
      /* Account for body content stored in the header buffer */
636
0
      if((k->badheader == HEADER_PARTHEADER) && !k->ignorebody) {
637
0
        size_t headlen = Curl_dyn_len(&data->state.headerb);
638
0
        DEBUGF(infof(data, "Increasing bytecount by %zu", headlen));
639
0
        k->bytecount += headlen;
640
0
      }
641
642
0
      if((-1 != k->maxdownload) &&
643
0
         (k->bytecount + nread >= k->maxdownload)) {
644
645
0
        excess = (size_t)(k->bytecount + nread - k->maxdownload);
646
0
        if(excess > 0 && !k->ignorebody) {
647
0
          infof(data,
648
0
                "Excess found in a read:"
649
0
                " excess = %zu"
650
0
                ", size = %" CURL_FORMAT_CURL_OFF_T
651
0
                ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
652
0
                ", bytecount = %" CURL_FORMAT_CURL_OFF_T,
653
0
                excess, k->size, k->maxdownload, k->bytecount);
654
0
          connclose(conn, "excess found in a read");
655
0
        }
656
657
0
        nread = (ssize_t) (k->maxdownload - k->bytecount);
658
0
        if(nread < 0) /* this should be unusual */
659
0
          nread = 0;
660
661
        /* HTTP/3 over QUIC should keep reading until QUIC connection
662
           is closed.  In contrast to HTTP/2 which can stop reading
663
           from TCP connection, HTTP/3 over QUIC needs ACK from server
664
           to ensure stream closure.  It should keep reading. */
665
0
        if(!is_http3) {
666
0
          k->keepon &= ~KEEP_RECV; /* we're done reading */
667
0
        }
668
0
      }
669
670
0
      k->bytecount += nread;
671
0
      max_recv -= nread;
672
673
0
      Curl_pgrsSetDownloadCounter(data, k->bytecount);
674
675
0
      if(!k->chunk && (nread || k->badheader || is_empty_data)) {
676
        /* If this is chunky transfer, it was already written */
677
678
0
        if(k->badheader && !k->ignorebody) {
679
          /* we parsed a piece of data wrongly assuming it was a header
680
             and now we output it as body instead */
681
0
          size_t headlen = Curl_dyn_len(&data->state.headerb);
682
683
          /* Don't let excess data pollute body writes */
684
0
          if(k->maxdownload == -1 || (curl_off_t)headlen <= k->maxdownload)
685
0
            result = Curl_client_write(data, CLIENTWRITE_BODY,
686
0
                                       Curl_dyn_ptr(&data->state.headerb),
687
0
                                       headlen);
688
0
          else
689
0
            result = Curl_client_write(data, CLIENTWRITE_BODY,
690
0
                                       Curl_dyn_ptr(&data->state.headerb),
691
0
                                       (size_t)k->maxdownload);
692
693
0
          if(result)
694
0
            goto out;
695
0
        }
696
0
        if(k->badheader < HEADER_ALLBAD) {
697
          /* This switch handles various content encodings. If there's an
698
             error here, be sure to check over the almost identical code
699
             in http_chunks.c.
700
             Make sure that ALL_CONTENT_ENCODINGS contains all the
701
             encodings handled here. */
702
0
          if(data->set.http_ce_skip || !k->writer_stack) {
703
0
            if(!k->ignorebody && nread) {
704
0
#ifndef CURL_DISABLE_POP3
705
0
              if(conn->handler->protocol & PROTO_FAMILY_POP3)
706
0
                result = Curl_pop3_write(data, k->str, nread);
707
0
              else
708
0
#endif /* CURL_DISABLE_POP3 */
709
0
                result = Curl_client_write(data, CLIENTWRITE_BODY, k->str,
710
0
                                           nread);
711
0
            }
712
0
          }
713
0
          else if(!k->ignorebody && nread)
714
0
            result = Curl_unencode_write(data, k->writer_stack, k->str, nread);
715
0
        }
716
0
        k->badheader = HEADER_NORMAL; /* taken care of now */
717
718
0
        if(result)
719
0
          goto out;
720
0
      }
721
722
0
    } /* if(!header and data to read) */
723
724
0
    if(conn->handler->readwrite && excess) {
725
      /* Parse the excess data */
726
0
      k->str += nread;
727
728
0
      if(&k->str[excess] > &buf[data->set.buffer_size]) {
729
        /* the excess amount was too excessive(!), make sure
730
           it doesn't read out of buffer */
731
0
        excess = &buf[data->set.buffer_size] - k->str;
732
0
      }
733
0
      nread = (ssize_t)excess;
734
735
0
      result = conn->handler->readwrite(data, conn, &nread, &readmore);
736
0
      if(result)
737
0
        goto out;
738
739
0
      if(readmore)
740
0
        k->keepon |= KEEP_RECV; /* we're not done reading */
741
0
      break;
742
0
    }
743
744
0
    if(is_empty_data) {
745
      /* if we received nothing, the server closed the connection and we
746
         are done */
747
0
      k->keepon &= ~KEEP_RECV;
748
0
    }
749
750
0
    if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV)) {
751
      /* this is a paused or stopped transfer */
752
0
      break;
753
0
    }
754
755
0
  } while((max_recv > 0) && data_pending(data) && maxloops--);
756
757
0
  if(maxloops <= 0 || max_recv <= 0) {
758
    /* we mark it as read-again-please */
759
0
    data->state.dselect_bits = CURL_CSELECT_IN;
760
0
    *comeback = TRUE;
761
0
  }
762
763
0
  if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
764
0
     conn->bits.close) {
765
    /* When we've read the entire thing and the close bit is set, the server
766
       may now close the connection. If there's now any kind of sending going
767
       on from our side, we need to stop that immediately. */
768
0
    infof(data, "we are done reading and this is set to close, stop send");
769
0
    k->keepon &= ~KEEP_SEND; /* no writing anymore either */
770
0
  }
771
772
0
out:
773
0
  if(result)
774
0
    DEBUGF(infof(data, DMSG(data, "readwrite_data() -> %d"), result));
775
0
  return result;
776
0
}
777
778
CURLcode Curl_done_sending(struct Curl_easy *data,
779
                           struct SingleRequest *k)
780
0
{
781
0
  k->keepon &= ~KEEP_SEND; /* we're done writing */
782
783
  /* These functions should be moved into the handler struct! */
784
0
  Curl_conn_ev_data_done_send(data);
785
786
0
  return CURLE_OK;
787
0
}
788
789
#if defined(WIN32) && defined(USE_WINSOCK)
790
#ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
791
#define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
792
#endif
793
794
static void win_update_buffer_size(curl_socket_t sockfd)
795
{
796
  int result;
797
  ULONG ideal;
798
  DWORD ideallen;
799
  result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
800
                    &ideal, sizeof(ideal), &ideallen, 0, 0);
801
  if(result == 0) {
802
    setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
803
               (const char *)&ideal, sizeof(ideal));
804
  }
805
}
806
#else
807
#define win_update_buffer_size(x)
808
#endif
809
810
#define curl_upload_refill_watermark(data) \
811
0
        ((ssize_t)((data)->set.upload_buffer_size >> 5))
812
813
/*
814
 * Send data to upload to the server, when the socket is writable.
815
 */
816
static CURLcode readwrite_upload(struct Curl_easy *data,
817
                                 struct connectdata *conn,
818
                                 int *didwhat)
819
0
{
820
0
  ssize_t i, si;
821
0
  ssize_t bytes_written;
822
0
  CURLcode result;
823
0
  ssize_t nread; /* number of bytes read */
824
0
  bool sending_http_headers = FALSE;
825
0
  struct SingleRequest *k = &data->req;
826
827
0
  if((k->bytecount == 0) && (k->writebytecount == 0))
828
0
    Curl_pgrsTime(data, TIMER_STARTTRANSFER);
829
830
0
  *didwhat |= KEEP_SEND;
831
832
0
  do {
833
0
    curl_off_t nbody;
834
0
    ssize_t offset = 0;
835
836
0
    if(0 != k->upload_present &&
837
0
       k->upload_present < curl_upload_refill_watermark(data) &&
838
0
       !k->upload_chunky &&/*(variable sized chunked header; append not safe)*/
839
0
       !k->upload_done &&  /*!(k->upload_done once k->upload_present sent)*/
840
0
       !(k->writebytecount + k->upload_present - k->pendingheader ==
841
0
         data->state.infilesize)) {
842
0
      offset = k->upload_present;
843
0
    }
844
845
    /* only read more data if there's no upload data already
846
       present in the upload buffer, or if appending to upload buffer */
847
0
    if(0 == k->upload_present || offset) {
848
0
      result = Curl_get_upload_buffer(data);
849
0
      if(result)
850
0
        return result;
851
0
      if(offset && k->upload_fromhere != data->state.ulbuf)
852
0
        memmove(data->state.ulbuf, k->upload_fromhere, offset);
853
      /* init the "upload from here" pointer */
854
0
      k->upload_fromhere = data->state.ulbuf;
855
856
0
      if(!k->upload_done) {
857
        /* HTTP pollution, this should be written nicer to become more
858
           protocol agnostic. */
859
0
        size_t fillcount;
860
0
        struct HTTP *http = k->p.http;
861
862
0
        if((k->exp100 == EXP100_SENDING_REQUEST) &&
863
0
           (http->sending == HTTPSEND_BODY)) {
864
          /* If this call is to send body data, we must take some action:
865
             We have sent off the full HTTP 1.1 request, and we shall now
866
             go into the Expect: 100 state and await such a header */
867
0
          k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
868
0
          k->keepon &= ~KEEP_SEND;         /* disable writing */
869
0
          k->start100 = Curl_now();       /* timeout count starts now */
870
0
          *didwhat &= ~KEEP_SEND;  /* we didn't write anything actually */
871
          /* set a timeout for the multi interface */
872
0
          Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
873
0
          break;
874
0
        }
875
876
0
        if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
877
0
          if(http->sending == HTTPSEND_REQUEST)
878
            /* We're sending the HTTP request headers, not the data.
879
               Remember that so we don't change the line endings. */
880
0
            sending_http_headers = TRUE;
881
0
          else
882
0
            sending_http_headers = FALSE;
883
0
        }
884
885
0
        k->upload_fromhere += offset;
886
0
        result = Curl_fillreadbuffer(data, data->set.upload_buffer_size-offset,
887
0
                                     &fillcount);
888
0
        k->upload_fromhere -= offset;
889
0
        if(result)
890
0
          return result;
891
892
0
        nread = offset + fillcount;
893
0
      }
894
0
      else
895
0
        nread = 0; /* we're done uploading/reading */
896
897
0
      if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
898
        /* this is a paused transfer */
899
0
        break;
900
0
      }
901
0
      if(nread <= 0) {
902
0
        result = Curl_done_sending(data, k);
903
0
        if(result)
904
0
          return result;
905
0
        break;
906
0
      }
907
908
      /* store number of bytes available for upload */
909
0
      k->upload_present = nread;
910
911
      /* convert LF to CRLF if so asked */
912
0
      if((!sending_http_headers) && (
913
0
#ifdef CURL_DO_LINEEND_CONV
914
         /* always convert if we're FTPing in ASCII mode */
915
0
         (data->state.prefer_ascii) ||
916
0
#endif
917
0
         (data->set.crlf))) {
918
        /* Do we need to allocate a scratch buffer? */
919
0
        if(!data->state.scratch) {
920
0
          data->state.scratch = malloc(2 * data->set.upload_buffer_size);
921
0
          if(!data->state.scratch) {
922
0
            failf(data, "Failed to alloc scratch buffer");
923
924
0
            return CURLE_OUT_OF_MEMORY;
925
0
          }
926
0
        }
927
928
        /*
929
         * ASCII/EBCDIC Note: This is presumably a text (not binary)
930
         * transfer so the data should already be in ASCII.
931
         * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
932
         * must be used instead of the escape sequences \r & \n.
933
         */
934
0
        if(offset)
935
0
          memcpy(data->state.scratch, k->upload_fromhere, offset);
936
0
        for(i = offset, si = offset; i < nread; i++, si++) {
937
0
          if(k->upload_fromhere[i] == 0x0a) {
938
0
            data->state.scratch[si++] = 0x0d;
939
0
            data->state.scratch[si] = 0x0a;
940
0
            if(!data->set.crlf) {
941
              /* we're here only because FTP is in ASCII mode...
942
                 bump infilesize for the LF we just added */
943
0
              if(data->state.infilesize != -1)
944
0
                data->state.infilesize++;
945
0
            }
946
0
          }
947
0
          else
948
0
            data->state.scratch[si] = k->upload_fromhere[i];
949
0
        }
950
951
0
        if(si != nread) {
952
          /* only perform the special operation if we really did replace
953
             anything */
954
0
          nread = si;
955
956
          /* upload from the new (replaced) buffer instead */
957
0
          k->upload_fromhere = data->state.scratch;
958
959
          /* set the new amount too */
960
0
          k->upload_present = nread;
961
0
        }
962
0
      }
963
964
0
#ifndef CURL_DISABLE_SMTP
965
0
      if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
966
0
        result = Curl_smtp_escape_eob(data, nread, offset);
967
0
        if(result)
968
0
          return result;
969
0
      }
970
0
#endif /* CURL_DISABLE_SMTP */
971
0
    } /* if 0 == k->upload_present or appended to upload buffer */
972
0
    else {
973
      /* We have a partial buffer left from a previous "round". Use
974
         that instead of reading more data */
975
0
    }
976
977
    /* write to socket (send away data) */
978
0
    result = Curl_write(data,
979
0
                        conn->writesockfd,  /* socket to send to */
980
0
                        k->upload_fromhere, /* buffer pointer */
981
0
                        k->upload_present,  /* buffer size */
982
0
                        &bytes_written);    /* actually sent */
983
0
    if(result)
984
0
      return result;
985
986
#if defined(WIN32) && defined(USE_WINSOCK)
987
    {
988
      struct curltime n = Curl_now();
989
      if(Curl_timediff(n, k->last_sndbuf_update) > 1000) {
990
        win_update_buffer_size(conn->writesockfd);
991
        k->last_sndbuf_update = n;
992
      }
993
    }
994
#endif
995
996
0
    if(k->pendingheader) {
997
      /* parts of what was sent was header */
998
0
      curl_off_t n = CURLMIN(k->pendingheader, bytes_written);
999
      /* show the data before we change the pointer upload_fromhere */
1000
0
      Curl_debug(data, CURLINFO_HEADER_OUT, k->upload_fromhere, (size_t)n);
1001
0
      k->pendingheader -= n;
1002
0
      nbody = bytes_written - n; /* size of the written body part */
1003
0
    }
1004
0
    else
1005
0
      nbody = bytes_written;
1006
1007
0
    if(nbody) {
1008
      /* show the data before we change the pointer upload_fromhere */
1009
0
      Curl_debug(data, CURLINFO_DATA_OUT,
1010
0
                 &k->upload_fromhere[bytes_written - nbody],
1011
0
                 (size_t)nbody);
1012
1013
0
      k->writebytecount += nbody;
1014
0
      Curl_pgrsSetUploadCounter(data, k->writebytecount);
1015
0
    }
1016
1017
0
    if((!k->upload_chunky || k->forbidchunk) &&
1018
0
       (k->writebytecount == data->state.infilesize)) {
1019
      /* we have sent all data we were supposed to */
1020
0
      k->upload_done = TRUE;
1021
0
      infof(data, "We are completely uploaded and fine");
1022
0
    }
1023
1024
0
    if(k->upload_present != bytes_written) {
1025
      /* we only wrote a part of the buffer (if anything), deal with it! */
1026
1027
      /* store the amount of bytes left in the buffer to write */
1028
0
      k->upload_present -= bytes_written;
1029
1030
      /* advance the pointer where to find the buffer when the next send
1031
         is to happen */
1032
0
      k->upload_fromhere += bytes_written;
1033
0
    }
1034
0
    else {
1035
      /* we've uploaded that buffer now */
1036
0
      result = Curl_get_upload_buffer(data);
1037
0
      if(result)
1038
0
        return result;
1039
0
      k->upload_fromhere = data->state.ulbuf;
1040
0
      k->upload_present = 0; /* no more bytes left */
1041
1042
0
      if(k->upload_done) {
1043
0
        result = Curl_done_sending(data, k);
1044
0
        if(result)
1045
0
          return result;
1046
0
      }
1047
0
    }
1048
1049
1050
0
  } while(0); /* just to break out from! */
1051
1052
0
  return CURLE_OK;
1053
0
}
1054
1055
/*
1056
 * Curl_readwrite() is the low-level function to be called when data is to
1057
 * be read and written to/from the connection.
1058
 *
1059
 * return '*comeback' TRUE if we didn't properly drain the socket so this
1060
 * function should get called again without select() or similar in between!
1061
 */
1062
CURLcode Curl_readwrite(struct connectdata *conn,
1063
                        struct Curl_easy *data,
1064
                        bool *done,
1065
                        bool *comeback)
1066
0
{
1067
0
  struct SingleRequest *k = &data->req;
1068
0
  CURLcode result;
1069
0
  struct curltime now;
1070
0
  int didwhat = 0;
1071
0
  int select_bits;
1072
1073
1074
0
  if(data->state.dselect_bits) {
1075
0
    select_bits = data->state.dselect_bits;
1076
0
    data->state.dselect_bits = 0;
1077
0
  }
1078
0
  else if(conn->cselect_bits) {
1079
0
    select_bits = conn->cselect_bits;
1080
0
    conn->cselect_bits = 0;
1081
0
  }
1082
0
  else {
1083
0
    curl_socket_t fd_read;
1084
0
    curl_socket_t fd_write;
1085
    /* only use the proper socket if the *_HOLD bit is not set simultaneously
1086
       as then we are in rate limiting state in that transfer direction */
1087
0
    if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
1088
0
      fd_read = conn->sockfd;
1089
0
    else
1090
0
      fd_read = CURL_SOCKET_BAD;
1091
1092
0
    if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
1093
0
      fd_write = conn->writesockfd;
1094
0
    else
1095
0
      fd_write = CURL_SOCKET_BAD;
1096
1097
0
    select_bits = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
1098
0
  }
1099
1100
0
  if(select_bits == CURL_CSELECT_ERR) {
1101
0
    failf(data, "select/poll returned error");
1102
0
    result = CURLE_SEND_ERROR;
1103
0
    goto out;
1104
0
  }
1105
1106
#ifdef USE_HYPER
1107
  if(conn->datastream) {
1108
    result = conn->datastream(data, conn, &didwhat, done, select_bits);
1109
    if(result || *done)
1110
      goto out;
1111
  }
1112
  else {
1113
#endif
1114
  /* We go ahead and do a read if we have a readable socket or if
1115
     the stream was rewound (in which case we have data in a
1116
     buffer) */
1117
0
  if((k->keepon & KEEP_RECV) && (select_bits & CURL_CSELECT_IN)) {
1118
0
    result = readwrite_data(data, conn, k, &didwhat, done, comeback);
1119
0
    if(result || *done)
1120
0
      goto out;
1121
0
  }
1122
1123
  /* If we still have writing to do, we check if we have a writable socket. */
1124
0
  if((k->keepon & KEEP_SEND) && (select_bits & CURL_CSELECT_OUT)) {
1125
    /* write */
1126
1127
0
    result = readwrite_upload(data, conn, &didwhat);
1128
0
    if(result)
1129
0
      goto out;
1130
0
  }
1131
#ifdef USE_HYPER
1132
  }
1133
#endif
1134
1135
0
  now = Curl_now();
1136
0
  if(!didwhat) {
1137
    /* no read no write, this is a timeout? */
1138
0
    if(k->exp100 == EXP100_AWAITING_CONTINUE) {
1139
      /* This should allow some time for the header to arrive, but only a
1140
         very short time as otherwise it'll be too much wasted time too
1141
         often. */
1142
1143
      /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
1144
1145
         Therefore, when a client sends this header field to an origin server
1146
         (possibly via a proxy) from which it has never seen a 100 (Continue)
1147
         status, the client SHOULD NOT wait for an indefinite period before
1148
         sending the request body.
1149
1150
      */
1151
1152
0
      timediff_t ms = Curl_timediff(now, k->start100);
1153
0
      if(ms >= data->set.expect_100_timeout) {
1154
        /* we've waited long enough, continue anyway */
1155
0
        k->exp100 = EXP100_SEND_DATA;
1156
0
        k->keepon |= KEEP_SEND;
1157
0
        Curl_expire_done(data, EXPIRE_100_TIMEOUT);
1158
0
        infof(data, "Done waiting for 100-continue");
1159
0
      }
1160
0
    }
1161
1162
0
    result = Curl_conn_ev_data_idle(data);
1163
0
    if(result)
1164
0
      goto out;
1165
0
  }
1166
1167
0
  if(Curl_pgrsUpdate(data))
1168
0
    result = CURLE_ABORTED_BY_CALLBACK;
1169
0
  else
1170
0
    result = Curl_speedcheck(data, now);
1171
0
  if(result)
1172
0
    goto out;
1173
1174
0
  if(k->keepon) {
1175
0
    if(0 > Curl_timeleft(data, &now, FALSE)) {
1176
0
      if(k->size != -1) {
1177
0
        failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
1178
0
              " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
1179
0
              CURL_FORMAT_CURL_OFF_T " bytes received",
1180
0
              Curl_timediff(now, data->progress.t_startsingle),
1181
0
              k->bytecount, k->size);
1182
0
      }
1183
0
      else {
1184
0
        failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
1185
0
              " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received",
1186
0
              Curl_timediff(now, data->progress.t_startsingle),
1187
0
              k->bytecount);
1188
0
      }
1189
0
      result = CURLE_OPERATION_TIMEDOUT;
1190
0
      goto out;
1191
0
    }
1192
0
  }
1193
0
  else {
1194
    /*
1195
     * The transfer has been performed. Just make some general checks before
1196
     * returning.
1197
     */
1198
1199
0
    if(!(data->req.no_body) && (k->size != -1) &&
1200
0
       (k->bytecount != k->size) &&
1201
0
#ifdef CURL_DO_LINEEND_CONV
1202
       /* Most FTP servers don't adjust their file SIZE response for CRLFs,
1203
          so we'll check to see if the discrepancy can be explained
1204
          by the number of CRLFs we've changed to LFs.
1205
       */
1206
0
       (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1207
0
#endif /* CURL_DO_LINEEND_CONV */
1208
0
       !k->newurl) {
1209
0
      failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
1210
0
            " bytes remaining to read", k->size - k->bytecount);
1211
0
      result = CURLE_PARTIAL_FILE;
1212
0
      goto out;
1213
0
    }
1214
0
    if(!(data->req.no_body) && k->chunk &&
1215
0
       (conn->chunk.state != CHUNK_STOP)) {
1216
      /*
1217
       * In chunked mode, return an error if the connection is closed prior to
1218
       * the empty (terminating) chunk is read.
1219
       *
1220
       * The condition above used to check for
1221
       * conn->proto.http->chunk.datasize != 0 which is true after reading
1222
       * *any* chunk, not just the empty chunk.
1223
       *
1224
       */
1225
0
      failf(data, "transfer closed with outstanding read data remaining");
1226
0
      result = CURLE_PARTIAL_FILE;
1227
0
      goto out;
1228
0
    }
1229
0
    if(Curl_pgrsUpdate(data)) {
1230
0
      result = CURLE_ABORTED_BY_CALLBACK;
1231
0
      goto out;
1232
0
    }
1233
0
  }
1234
1235
  /* Now update the "done" boolean we return */
1236
0
  *done = (0 == (k->keepon&(KEEP_RECVBITS|KEEP_SENDBITS))) ? TRUE : FALSE;
1237
0
out:
1238
0
  if(result)
1239
0
    DEBUGF(infof(data, DMSG(data, "Curl_readwrite() -> %d"), result));
1240
0
  return result;
1241
0
}
1242
1243
/*
1244
 * Curl_single_getsock() gets called by the multi interface code when the app
1245
 * has requested to get the sockets for the current connection. This function
1246
 * will then be called once for every connection that the multi interface
1247
 * keeps track of. This function will only be called for connections that are
1248
 * in the proper state to have this information available.
1249
 */
1250
int Curl_single_getsock(struct Curl_easy *data,
1251
                        struct connectdata *conn,
1252
                        curl_socket_t *sock)
1253
0
{
1254
0
  int bitmap = GETSOCK_BLANK;
1255
0
  unsigned sockindex = 0;
1256
1257
0
  if(conn->handler->perform_getsock)
1258
0
    return conn->handler->perform_getsock(data, conn, sock);
1259
1260
  /* don't include HOLD and PAUSE connections */
1261
0
  if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
1262
1263
0
    DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1264
1265
0
    bitmap |= GETSOCK_READSOCK(sockindex);
1266
0
    sock[sockindex] = conn->sockfd;
1267
0
  }
1268
1269
  /* don't include HOLD and PAUSE connections */
1270
0
  if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
1271
0
    if((conn->sockfd != conn->writesockfd) ||
1272
0
       bitmap == GETSOCK_BLANK) {
1273
      /* only if they are not the same socket and we have a readable
1274
         one, we increase index */
1275
0
      if(bitmap != GETSOCK_BLANK)
1276
0
        sockindex++; /* increase index if we need two entries */
1277
1278
0
      DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1279
1280
0
      sock[sockindex] = conn->writesockfd;
1281
0
    }
1282
1283
0
    bitmap |= GETSOCK_WRITESOCK(sockindex);
1284
0
  }
1285
1286
0
  return bitmap;
1287
0
}
1288
1289
/* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
1290
   which means this gets called once for each subsequent redirect etc */
1291
void Curl_init_CONNECT(struct Curl_easy *data)
1292
0
{
1293
0
  data->state.fread_func = data->set.fread_func_set;
1294
0
  data->state.in = data->set.in_set;
1295
0
  data->state.upload = (data->state.httpreq == HTTPREQ_PUT);
1296
0
}
1297
1298
/*
1299
 * Curl_pretransfer() is called immediately before a transfer starts, and only
1300
 * once for one transfer no matter if it has redirects or do multi-pass
1301
 * authentication etc.
1302
 */
1303
CURLcode Curl_pretransfer(struct Curl_easy *data)
1304
0
{
1305
0
  CURLcode result;
1306
1307
0
  if(!data->state.url && !data->set.uh) {
1308
    /* we can't do anything without URL */
1309
0
    failf(data, "No URL set");
1310
0
    return CURLE_URL_MALFORMAT;
1311
0
  }
1312
1313
  /* since the URL may have been redirected in a previous use of this handle */
1314
0
  if(data->state.url_alloc) {
1315
    /* the already set URL is allocated, free it first! */
1316
0
    Curl_safefree(data->state.url);
1317
0
    data->state.url_alloc = FALSE;
1318
0
  }
1319
1320
0
  if(!data->state.url && data->set.uh) {
1321
0
    CURLUcode uc;
1322
0
    free(data->set.str[STRING_SET_URL]);
1323
0
    uc = curl_url_get(data->set.uh,
1324
0
                      CURLUPART_URL, &data->set.str[STRING_SET_URL], 0);
1325
0
    if(uc) {
1326
0
      failf(data, "No URL set");
1327
0
      return CURLE_URL_MALFORMAT;
1328
0
    }
1329
0
  }
1330
1331
0
  if(data->set.postfields && data->set.set_resume_from) {
1332
    /* we can't */
1333
0
    failf(data, "cannot mix POSTFIELDS with RESUME_FROM");
1334
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1335
0
  }
1336
1337
0
  data->state.prefer_ascii = data->set.prefer_ascii;
1338
0
  data->state.list_only = data->set.list_only;
1339
0
  data->state.httpreq = data->set.method;
1340
0
  data->state.url = data->set.str[STRING_SET_URL];
1341
1342
  /* Init the SSL session ID cache here. We do it here since we want to do it
1343
     after the *_setopt() calls (that could specify the size of the cache) but
1344
     before any transfer takes place. */
1345
0
  result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
1346
0
  if(result)
1347
0
    return result;
1348
1349
0
  data->state.requests = 0;
1350
0
  data->state.followlocation = 0; /* reset the location-follow counter */
1351
0
  data->state.this_is_a_follow = FALSE; /* reset this */
1352
0
  data->state.errorbuf = FALSE; /* no error has occurred */
1353
0
  data->state.httpwant = data->set.httpwant;
1354
0
  data->state.httpversion = 0;
1355
0
  data->state.authproblem = FALSE;
1356
0
  data->state.authhost.want = data->set.httpauth;
1357
0
  data->state.authproxy.want = data->set.proxyauth;
1358
0
  Curl_safefree(data->info.wouldredirect);
1359
0
  Curl_data_priority_clear_state(data);
1360
1361
0
  if(data->state.httpreq == HTTPREQ_PUT)
1362
0
    data->state.infilesize = data->set.filesize;
1363
0
  else if((data->state.httpreq != HTTPREQ_GET) &&
1364
0
          (data->state.httpreq != HTTPREQ_HEAD)) {
1365
0
    data->state.infilesize = data->set.postfieldsize;
1366
0
    if(data->set.postfields && (data->state.infilesize == -1))
1367
0
      data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
1368
0
  }
1369
0
  else
1370
0
    data->state.infilesize = 0;
1371
1372
  /* If there is a list of cookie files to read, do it now! */
1373
0
  Curl_cookie_loadfiles(data);
1374
1375
  /* If there is a list of host pairs to deal with */
1376
0
  if(data->state.resolve)
1377
0
    result = Curl_loadhostpairs(data);
1378
1379
  /* If there is a list of hsts files to read */
1380
0
  Curl_hsts_loadfiles(data);
1381
1382
0
  if(!result) {
1383
    /* Allow data->set.use_port to set which port to use. This needs to be
1384
     * disabled for example when we follow Location: headers to URLs using
1385
     * different ports! */
1386
0
    data->state.allow_port = TRUE;
1387
1388
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1389
    /*************************************************************
1390
     * Tell signal handler to ignore SIGPIPE
1391
     *************************************************************/
1392
    if(!data->set.no_signal)
1393
      data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
1394
#endif
1395
1396
0
    Curl_initinfo(data); /* reset session-specific information "variables" */
1397
0
    Curl_pgrsResetTransferSizes(data);
1398
0
    Curl_pgrsStartNow(data);
1399
1400
    /* In case the handle is re-used and an authentication method was picked
1401
       in the session we need to make sure we only use the one(s) we now
1402
       consider to be fine */
1403
0
    data->state.authhost.picked &= data->state.authhost.want;
1404
0
    data->state.authproxy.picked &= data->state.authproxy.want;
1405
1406
0
#ifndef CURL_DISABLE_FTP
1407
0
    data->state.wildcardmatch = data->set.wildcard_enabled;
1408
0
    if(data->state.wildcardmatch) {
1409
0
      struct WildcardData *wc;
1410
0
      if(!data->wildcard) {
1411
0
        data->wildcard = calloc(1, sizeof(struct WildcardData));
1412
0
        if(!data->wildcard)
1413
0
          return CURLE_OUT_OF_MEMORY;
1414
0
      }
1415
0
      wc = data->wildcard;
1416
0
      if((wc->state < CURLWC_INIT) ||
1417
0
         (wc->state >= CURLWC_CLEAN)) {
1418
0
        if(wc->ftpwc)
1419
0
          wc->dtor(wc->ftpwc);
1420
0
        Curl_safefree(wc->pattern);
1421
0
        Curl_safefree(wc->path);
1422
0
        result = Curl_wildcard_init(wc); /* init wildcard structures */
1423
0
        if(result)
1424
0
          return CURLE_OUT_OF_MEMORY;
1425
0
      }
1426
0
    }
1427
0
#endif
1428
0
    result = Curl_hsts_loadcb(data, data->hsts);
1429
0
  }
1430
1431
  /*
1432
   * Set user-agent. Used for HTTP, but since we can attempt to tunnel
1433
   * basically anything through an HTTP proxy we can't limit this based on
1434
   * protocol.
1435
   */
1436
0
  if(data->set.str[STRING_USERAGENT]) {
1437
0
    Curl_safefree(data->state.aptr.uagent);
1438
0
    data->state.aptr.uagent =
1439
0
      aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
1440
0
    if(!data->state.aptr.uagent)
1441
0
      return CURLE_OUT_OF_MEMORY;
1442
0
  }
1443
1444
0
  if(!result)
1445
0
    result = Curl_setstropt(&data->state.aptr.user,
1446
0
                            data->set.str[STRING_USERNAME]);
1447
0
  if(!result)
1448
0
    result = Curl_setstropt(&data->state.aptr.passwd,
1449
0
                            data->set.str[STRING_PASSWORD]);
1450
0
  if(!result)
1451
0
    result = Curl_setstropt(&data->state.aptr.proxyuser,
1452
0
                            data->set.str[STRING_PROXYUSERNAME]);
1453
0
  if(!result)
1454
0
    result = Curl_setstropt(&data->state.aptr.proxypasswd,
1455
0
                            data->set.str[STRING_PROXYPASSWORD]);
1456
1457
0
  data->req.headerbytecount = 0;
1458
0
  Curl_headers_cleanup(data);
1459
0
  return result;
1460
0
}
1461
1462
/*
1463
 * Curl_posttransfer() is called immediately after a transfer ends
1464
 */
1465
CURLcode Curl_posttransfer(struct Curl_easy *data)
1466
0
{
1467
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1468
  /* restore the signal handler for SIGPIPE before we get back */
1469
  if(!data->set.no_signal)
1470
    signal(SIGPIPE, data->state.prev_signal);
1471
#else
1472
0
  (void)data; /* unused parameter */
1473
0
#endif
1474
1475
0
  return CURLE_OK;
1476
0
}
1477
1478
/*
1479
 * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
1480
 * as given by the remote server and set up the new URL to request.
1481
 *
1482
 * This function DOES NOT FREE the given url.
1483
 */
1484
CURLcode Curl_follow(struct Curl_easy *data,
1485
                     char *newurl,    /* the Location: string */
1486
                     followtype type) /* see transfer.h */
1487
0
{
1488
#ifdef CURL_DISABLE_HTTP
1489
  (void)data;
1490
  (void)newurl;
1491
  (void)type;
1492
  /* Location: following will not happen when HTTP is disabled */
1493
  return CURLE_TOO_MANY_REDIRECTS;
1494
#else
1495
1496
  /* Location: redirect */
1497
0
  bool disallowport = FALSE;
1498
0
  bool reachedmax = FALSE;
1499
0
  CURLUcode uc;
1500
1501
0
  DEBUGASSERT(type != FOLLOW_NONE);
1502
1503
0
  if(type != FOLLOW_FAKE)
1504
0
    data->state.requests++; /* count all real follows */
1505
0
  if(type == FOLLOW_REDIR) {
1506
0
    if((data->set.maxredirs != -1) &&
1507
0
       (data->state.followlocation >= data->set.maxredirs)) {
1508
0
      reachedmax = TRUE;
1509
0
      type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
1510
                             to URL */
1511
0
    }
1512
0
    else {
1513
0
      data->state.followlocation++; /* count redirect-followings, including
1514
                                       auth reloads */
1515
1516
0
      if(data->set.http_auto_referer) {
1517
0
        CURLU *u;
1518
0
        char *referer = NULL;
1519
1520
        /* We are asked to automatically set the previous URL as the referer
1521
           when we get the next URL. We pick the ->url field, which may or may
1522
           not be 100% correct */
1523
1524
0
        if(data->state.referer_alloc) {
1525
0
          Curl_safefree(data->state.referer);
1526
0
          data->state.referer_alloc = FALSE;
1527
0
        }
1528
1529
        /* Make a copy of the URL without credentials and fragment */
1530
0
        u = curl_url();
1531
0
        if(!u)
1532
0
          return CURLE_OUT_OF_MEMORY;
1533
1534
0
        uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
1535
0
        if(!uc)
1536
0
          uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
1537
0
        if(!uc)
1538
0
          uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
1539
0
        if(!uc)
1540
0
          uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
1541
0
        if(!uc)
1542
0
          uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
1543
1544
0
        curl_url_cleanup(u);
1545
1546
0
        if(uc || !referer)
1547
0
          return CURLE_OUT_OF_MEMORY;
1548
1549
0
        data->state.referer = referer;
1550
0
        data->state.referer_alloc = TRUE; /* yes, free this later */
1551
0
      }
1552
0
    }
1553
0
  }
1554
1555
0
  if((type != FOLLOW_RETRY) &&
1556
0
     (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
1557
0
     Curl_is_absolute_url(newurl, NULL, 0, FALSE))
1558
    /* If this is not redirect due to a 401 or 407 response and an absolute
1559
       URL: don't allow a custom port number */
1560
0
    disallowport = TRUE;
1561
1562
0
  DEBUGASSERT(data->state.uh);
1563
0
  uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
1564
0
                    (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
1565
0
                    ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
1566
0
                    CURLU_ALLOW_SPACE |
1567
0
                    (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
1568
0
  if(uc) {
1569
0
    if(type != FOLLOW_FAKE) {
1570
0
      failf(data, "The redirect target URL could not be parsed: %s",
1571
0
            curl_url_strerror(uc));
1572
0
      return Curl_uc_to_curlcode(uc);
1573
0
    }
1574
1575
    /* the URL could not be parsed for some reason, but since this is FAKE
1576
       mode, just duplicate the field as-is */
1577
0
    newurl = strdup(newurl);
1578
0
    if(!newurl)
1579
0
      return CURLE_OUT_OF_MEMORY;
1580
0
  }
1581
0
  else {
1582
0
    uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
1583
0
    if(uc)
1584
0
      return Curl_uc_to_curlcode(uc);
1585
1586
    /* Clear auth if this redirects to a different port number or protocol,
1587
       unless permitted */
1588
0
    if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
1589
0
      char *portnum;
1590
0
      int port;
1591
0
      bool clear = FALSE;
1592
1593
0
      if(data->set.use_port && data->state.allow_port)
1594
        /* a custom port is used */
1595
0
        port = (int)data->set.use_port;
1596
0
      else {
1597
0
        uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
1598
0
                          CURLU_DEFAULT_PORT);
1599
0
        if(uc) {
1600
0
          free(newurl);
1601
0
          return Curl_uc_to_curlcode(uc);
1602
0
        }
1603
0
        port = atoi(portnum);
1604
0
        free(portnum);
1605
0
      }
1606
0
      if(port != data->info.conn_remote_port) {
1607
0
        infof(data, "Clear auth, redirects to port from %u to %u",
1608
0
              data->info.conn_remote_port, port);
1609
0
        clear = TRUE;
1610
0
      }
1611
0
      else {
1612
0
        char *scheme;
1613
0
        const struct Curl_handler *p;
1614
0
        uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
1615
0
        if(uc) {
1616
0
          free(newurl);
1617
0
          return Curl_uc_to_curlcode(uc);
1618
0
        }
1619
1620
0
        p = Curl_builtin_scheme(scheme, CURL_ZERO_TERMINATED);
1621
0
        if(p && (p->protocol != data->info.conn_protocol)) {
1622
0
          infof(data, "Clear auth, redirects scheme from %s to %s",
1623
0
                data->info.conn_scheme, scheme);
1624
0
          clear = TRUE;
1625
0
        }
1626
0
        free(scheme);
1627
0
      }
1628
0
      if(clear) {
1629
0
        Curl_safefree(data->state.aptr.user);
1630
0
        Curl_safefree(data->state.aptr.passwd);
1631
0
      }
1632
0
    }
1633
0
  }
1634
1635
0
  if(type == FOLLOW_FAKE) {
1636
    /* we're only figuring out the new url if we would've followed locations
1637
       but now we're done so we can get out! */
1638
0
    data->info.wouldredirect = newurl;
1639
1640
0
    if(reachedmax) {
1641
0
      failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
1642
0
      return CURLE_TOO_MANY_REDIRECTS;
1643
0
    }
1644
0
    return CURLE_OK;
1645
0
  }
1646
1647
0
  if(disallowport)
1648
0
    data->state.allow_port = FALSE;
1649
1650
0
  if(data->state.url_alloc)
1651
0
    Curl_safefree(data->state.url);
1652
1653
0
  data->state.url = newurl;
1654
0
  data->state.url_alloc = TRUE;
1655
1656
0
  infof(data, "Issue another request to this URL: '%s'", data->state.url);
1657
1658
  /*
1659
   * We get here when the HTTP code is 300-399 (and 401). We need to perform
1660
   * differently based on exactly what return code there was.
1661
   *
1662
   * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
1663
   * an HTTP (proxy-) authentication scheme other than Basic.
1664
   */
1665
0
  switch(data->info.httpcode) {
1666
    /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
1667
       Authorization: XXXX header in the HTTP request code snippet */
1668
    /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
1669
       Proxy-Authorization: XXXX header in the HTTP request code snippet */
1670
    /* 300 - Multiple Choices */
1671
    /* 306 - Not used */
1672
    /* 307 - Temporary Redirect */
1673
0
  default:  /* for all above (and the unknown ones) */
1674
    /* Some codes are explicitly mentioned since I've checked RFC2616 and they
1675
     * seem to be OK to POST to.
1676
     */
1677
0
    break;
1678
0
  case 301: /* Moved Permanently */
1679
    /* (quote from RFC7231, section 6.4.2)
1680
     *
1681
     * Note: For historical reasons, a user agent MAY change the request
1682
     * method from POST to GET for the subsequent request.  If this
1683
     * behavior is undesired, the 307 (Temporary Redirect) status code
1684
     * can be used instead.
1685
     *
1686
     * ----
1687
     *
1688
     * Many webservers expect this, so these servers often answers to a POST
1689
     * request with an error page. To be sure that libcurl gets the page that
1690
     * most user agents would get, libcurl has to force GET.
1691
     *
1692
     * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1693
     * can be overridden with CURLOPT_POSTREDIR.
1694
     */
1695
0
    if((data->state.httpreq == HTTPREQ_POST
1696
0
        || data->state.httpreq == HTTPREQ_POST_FORM
1697
0
        || data->state.httpreq == HTTPREQ_POST_MIME)
1698
0
       && !(data->set.keep_post & CURL_REDIR_POST_301)) {
1699
0
      infof(data, "Switch from POST to GET");
1700
0
      data->state.httpreq = HTTPREQ_GET;
1701
0
    }
1702
0
    break;
1703
0
  case 302: /* Found */
1704
    /* (quote from RFC7231, section 6.4.3)
1705
     *
1706
     * Note: For historical reasons, a user agent MAY change the request
1707
     * method from POST to GET for the subsequent request.  If this
1708
     * behavior is undesired, the 307 (Temporary Redirect) status code
1709
     * can be used instead.
1710
     *
1711
     * ----
1712
     *
1713
     * Many webservers expect this, so these servers often answers to a POST
1714
     * request with an error page. To be sure that libcurl gets the page that
1715
     * most user agents would get, libcurl has to force GET.
1716
     *
1717
     * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1718
     * can be overridden with CURLOPT_POSTREDIR.
1719
     */
1720
0
    if((data->state.httpreq == HTTPREQ_POST
1721
0
        || data->state.httpreq == HTTPREQ_POST_FORM
1722
0
        || data->state.httpreq == HTTPREQ_POST_MIME)
1723
0
       && !(data->set.keep_post & CURL_REDIR_POST_302)) {
1724
0
      infof(data, "Switch from POST to GET");
1725
0
      data->state.httpreq = HTTPREQ_GET;
1726
0
    }
1727
0
    break;
1728
1729
0
  case 303: /* See Other */
1730
    /* 'See Other' location is not the resource but a substitute for the
1731
     * resource. In this case we switch the method to GET/HEAD, unless the
1732
     * method is POST and the user specified to keep it as POST.
1733
     * https://github.com/curl/curl/issues/5237#issuecomment-614641049
1734
     */
1735
0
    if(data->state.httpreq != HTTPREQ_GET &&
1736
0
       ((data->state.httpreq != HTTPREQ_POST &&
1737
0
         data->state.httpreq != HTTPREQ_POST_FORM &&
1738
0
         data->state.httpreq != HTTPREQ_POST_MIME) ||
1739
0
        !(data->set.keep_post & CURL_REDIR_POST_303))) {
1740
0
      data->state.httpreq = HTTPREQ_GET;
1741
0
      infof(data, "Switch to %s",
1742
0
            data->req.no_body?"HEAD":"GET");
1743
0
    }
1744
0
    break;
1745
0
  case 304: /* Not Modified */
1746
    /* 304 means we did a conditional request and it was "Not modified".
1747
     * We shouldn't get any Location: header in this response!
1748
     */
1749
0
    break;
1750
0
  case 305: /* Use Proxy */
1751
    /* (quote from RFC2616, section 10.3.6):
1752
     * "The requested resource MUST be accessed through the proxy given
1753
     * by the Location field. The Location field gives the URI of the
1754
     * proxy.  The recipient is expected to repeat this single request
1755
     * via the proxy. 305 responses MUST only be generated by origin
1756
     * servers."
1757
     */
1758
0
    break;
1759
0
  }
1760
0
  Curl_pgrsTime(data, TIMER_REDIRECT);
1761
0
  Curl_pgrsResetTransferSizes(data);
1762
1763
0
  return CURLE_OK;
1764
0
#endif /* CURL_DISABLE_HTTP */
1765
0
}
1766
1767
/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
1768
1769
   NOTE: that the *url is malloc()ed. */
1770
CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
1771
0
{
1772
0
  struct connectdata *conn = data->conn;
1773
0
  bool retry = FALSE;
1774
0
  *url = NULL;
1775
1776
  /* if we're talking upload, we can't do the checks below, unless the protocol
1777
     is HTTP as when uploading over HTTP we will still get a response */
1778
0
  if(data->state.upload &&
1779
0
     !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
1780
0
    return CURLE_OK;
1781
1782
0
  if((data->req.bytecount + data->req.headerbytecount == 0) &&
1783
0
     conn->bits.reuse &&
1784
0
     (!data->req.no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP))
1785
0
#ifndef CURL_DISABLE_RTSP
1786
0
     && (data->set.rtspreq != RTSPREQ_RECEIVE)
1787
0
#endif
1788
0
    )
1789
    /* We got no data, we attempted to re-use a connection. For HTTP this
1790
       can be a retry so we try again regardless if we expected a body.
1791
       For other protocols we only try again only if we expected a body.
1792
1793
       This might happen if the connection was left alive when we were
1794
       done using it before, but that was closed when we wanted to read from
1795
       it again. Bad luck. Retry the same request on a fresh connect! */
1796
0
    retry = TRUE;
1797
0
  else if(data->state.refused_stream &&
1798
0
          (data->req.bytecount + data->req.headerbytecount == 0) ) {
1799
    /* This was sent on a refused stream, safe to rerun. A refused stream
1800
       error can typically only happen on HTTP/2 level if the stream is safe
1801
       to issue again, but the nghttp2 API can deliver the message to other
1802
       streams as well, which is why this adds the check the data counters
1803
       too. */
1804
0
    infof(data, "REFUSED_STREAM, retrying a fresh connect");
1805
0
    data->state.refused_stream = FALSE; /* clear again */
1806
0
    retry = TRUE;
1807
0
  }
1808
0
  if(retry) {
1809
0
#define CONN_MAX_RETRIES 5
1810
0
    if(data->state.retrycount++ >= CONN_MAX_RETRIES) {
1811
0
      failf(data, "Connection died, tried %d times before giving up",
1812
0
            CONN_MAX_RETRIES);
1813
0
      data->state.retrycount = 0;
1814
0
      return CURLE_SEND_ERROR;
1815
0
    }
1816
0
    infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
1817
0
          data->state.retrycount);
1818
0
    *url = strdup(data->state.url);
1819
0
    if(!*url)
1820
0
      return CURLE_OUT_OF_MEMORY;
1821
1822
0
    connclose(conn, "retry"); /* close this connection */
1823
0
    conn->bits.retry = TRUE; /* mark this as a connection we're about
1824
                                to retry. Marking it this way should
1825
                                prevent i.e HTTP transfers to return
1826
                                error just because nothing has been
1827
                                transferred! */
1828
1829
1830
0
    if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
1831
0
       data->req.writebytecount) {
1832
0
      data->state.rewindbeforesend = TRUE;
1833
0
      infof(data, "state.rewindbeforesend = TRUE");
1834
0
    }
1835
0
  }
1836
0
  return CURLE_OK;
1837
0
}
1838
1839
/*
1840
 * Curl_setup_transfer() is called to setup some basic properties for the
1841
 * upcoming transfer.
1842
 */
1843
void
1844
Curl_setup_transfer(
1845
  struct Curl_easy *data,   /* transfer */
1846
  int sockindex,            /* socket index to read from or -1 */
1847
  curl_off_t size,          /* -1 if unknown at this point */
1848
  bool getheader,           /* TRUE if header parsing is wanted */
1849
  int writesockindex        /* socket index to write to, it may very well be
1850
                               the same we read from. -1 disables */
1851
  )
1852
0
{
1853
0
  struct SingleRequest *k = &data->req;
1854
0
  struct connectdata *conn = data->conn;
1855
0
  struct HTTP *http = data->req.p.http;
1856
0
  bool httpsending;
1857
1858
0
  DEBUGASSERT(conn != NULL);
1859
0
  DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
1860
1861
0
  httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
1862
0
                 (http->sending == HTTPSEND_REQUEST));
1863
1864
0
  if(conn->bits.multiplex || conn->httpversion >= 20 || httpsending) {
1865
    /* when multiplexing, the read/write sockets need to be the same! */
1866
0
    conn->sockfd = sockindex == -1 ?
1867
0
      ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) :
1868
0
      conn->sock[sockindex];
1869
0
    conn->writesockfd = conn->sockfd;
1870
0
    if(httpsending)
1871
      /* special and very HTTP-specific */
1872
0
      writesockindex = FIRSTSOCKET;
1873
0
  }
1874
0
  else {
1875
0
    conn->sockfd = sockindex == -1 ?
1876
0
      CURL_SOCKET_BAD : conn->sock[sockindex];
1877
0
    conn->writesockfd = writesockindex == -1 ?
1878
0
      CURL_SOCKET_BAD:conn->sock[writesockindex];
1879
0
  }
1880
0
  k->getheader = getheader;
1881
1882
0
  k->size = size;
1883
1884
  /* The code sequence below is placed in this function just because all
1885
     necessary input is not always known in do_complete() as this function may
1886
     be called after that */
1887
1888
0
  if(!k->getheader) {
1889
0
    k->header = FALSE;
1890
0
    if(size > 0)
1891
0
      Curl_pgrsSetDownloadSize(data, size);
1892
0
  }
1893
  /* we want header and/or body, if neither then don't do this! */
1894
0
  if(k->getheader || !data->req.no_body) {
1895
1896
0
    if(sockindex != -1)
1897
0
      k->keepon |= KEEP_RECV;
1898
1899
0
    if(writesockindex != -1) {
1900
      /* HTTP 1.1 magic:
1901
1902
         Even if we require a 100-return code before uploading data, we might
1903
         need to write data before that since the REQUEST may not have been
1904
         finished sent off just yet.
1905
1906
         Thus, we must check if the request has been sent before we set the
1907
         state info where we wait for the 100-return code
1908
      */
1909
0
      if((data->state.expect100header) &&
1910
0
         (conn->handler->protocol&PROTO_FAMILY_HTTP) &&
1911
0
         (http->sending == HTTPSEND_BODY)) {
1912
        /* wait with write until we either got 100-continue or a timeout */
1913
0
        k->exp100 = EXP100_AWAITING_CONTINUE;
1914
0
        k->start100 = Curl_now();
1915
1916
        /* Set a timeout for the multi interface. Add the inaccuracy margin so
1917
           that we don't fire slightly too early and get denied to run. */
1918
0
        Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
1919
0
      }
1920
0
      else {
1921
0
        if(data->state.expect100header)
1922
          /* when we've sent off the rest of the headers, we must await a
1923
             100-continue but first finish sending the request */
1924
0
          k->exp100 = EXP100_SENDING_REQUEST;
1925
1926
        /* enable the write bit when we're not waiting for continue */
1927
0
        k->keepon |= KEEP_SEND;
1928
0
      }
1929
0
    } /* if(writesockindex != -1) */
1930
0
  } /* if(k->getheader || !data->req.no_body) */
1931
1932
0
}