Coverage Report

Created: 2023-12-08 06:48

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