1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2020, 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.haxx.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  ***************************************************************************/
22 
23 #include "curl_setup.h"
24 
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
27 #endif
28 
29 #ifdef HAVE_LINUX_TCP_H
30 #include <linux/tcp.h>
31 #endif
32 
33 #include <curl/curl.h>
34 
35 #include "urldata.h"
36 #include "sendf.h"
37 #include "connect.h"
38 #include "vtls/vtls.h"
39 #include "vssh/ssh.h"
40 #include "easyif.h"
41 #include "multiif.h"
42 #include "non-ascii.h"
43 #include "strerror.h"
44 #include "select.h"
45 #include "strdup.h"
46 #include "http2.h"
47 
48 /* The last 3 #include files should be in this order */
49 #include "curl_printf.h"
50 #include "curl_memory.h"
51 #include "memdebug.h"
52 
53 #ifdef CURL_DO_LINEEND_CONV
54 /*
55  * convert_lineends() changes CRLF (\r\n) end-of-line markers to a single LF
56  * (\n), with special processing for CRLF sequences that are split between two
57  * blocks of data.  Remaining, bare CRs are changed to LFs.  The possibly new
58  * size of the data is returned.
59  */
convert_lineends(struct Curl_easy * data,char * startPtr,size_t size)60 static size_t convert_lineends(struct Curl_easy *data,
61                                char *startPtr, size_t size)
62 {
63   char *inPtr, *outPtr;
64 
65   /* sanity check */
66   if((startPtr == NULL) || (size < 1)) {
67     return size;
68   }
69 
70   if(data->state.prev_block_had_trailing_cr) {
71     /* The previous block of incoming data
72        had a trailing CR, which was turned into a LF. */
73     if(*startPtr == '\n') {
74       /* This block of incoming data starts with the
75          previous block's LF so get rid of it */
76       memmove(startPtr, startPtr + 1, size-1);
77       size--;
78       /* and it wasn't a bare CR but a CRLF conversion instead */
79       data->state.crlf_conversions++;
80     }
81     data->state.prev_block_had_trailing_cr = FALSE; /* reset the flag */
82   }
83 
84   /* find 1st CR, if any */
85   inPtr = outPtr = memchr(startPtr, '\r', size);
86   if(inPtr) {
87     /* at least one CR, now look for CRLF */
88     while(inPtr < (startPtr + size-1)) {
89       /* note that it's size-1, so we'll never look past the last byte */
90       if(memcmp(inPtr, "\r\n", 2) == 0) {
91         /* CRLF found, bump past the CR and copy the NL */
92         inPtr++;
93         *outPtr = *inPtr;
94         /* keep track of how many CRLFs we converted */
95         data->state.crlf_conversions++;
96       }
97       else {
98         if(*inPtr == '\r') {
99           /* lone CR, move LF instead */
100           *outPtr = '\n';
101         }
102         else {
103           /* not a CRLF nor a CR, just copy whatever it is */
104           *outPtr = *inPtr;
105         }
106       }
107       outPtr++;
108       inPtr++;
109     } /* end of while loop */
110 
111     if(inPtr < startPtr + size) {
112       /* handle last byte */
113       if(*inPtr == '\r') {
114         /* deal with a CR at the end of the buffer */
115         *outPtr = '\n'; /* copy a NL instead */
116         /* note that a CRLF might be split across two blocks */
117         data->state.prev_block_had_trailing_cr = TRUE;
118       }
119       else {
120         /* copy last byte */
121         *outPtr = *inPtr;
122       }
123       outPtr++;
124     }
125     if(outPtr < startPtr + size)
126       /* tidy up by null terminating the now shorter data */
127       *outPtr = '\0';
128 
129     return (outPtr - startPtr);
130   }
131   return size;
132 }
133 #endif /* CURL_DO_LINEEND_CONV */
134 
135 #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
Curl_recv_has_postponed_data(struct connectdata * conn,int sockindex)136 bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
137 {
138   struct postponed_data * const psnd = &(conn->postponed[sockindex]);
139   return psnd->buffer && psnd->allocated_size &&
140          psnd->recv_size > psnd->recv_processed;
141 }
142 
pre_receive_plain(struct connectdata * conn,int num)143 static CURLcode pre_receive_plain(struct connectdata *conn, int num)
144 {
145   const curl_socket_t sockfd = conn->sock[num];
146   struct postponed_data * const psnd = &(conn->postponed[num]);
147   size_t bytestorecv = psnd->allocated_size - psnd->recv_size;
148   /* WinSock will destroy unread received data if send() is
149      failed.
150      To avoid lossage of received data, recv() must be
151      performed before every send() if any incoming data is
152      available. However, skip this, if buffer is already full. */
153   if((conn->handler->protocol&PROTO_FAMILY_HTTP) != 0 &&
154      conn->recv[num] == Curl_recv_plain &&
155      (!psnd->buffer || bytestorecv)) {
156     const int readymask = Curl_socket_check(sockfd, CURL_SOCKET_BAD,
157                                             CURL_SOCKET_BAD, 0);
158     if(readymask != -1 && (readymask & CURL_CSELECT_IN) != 0) {
159       /* Have some incoming data */
160       if(!psnd->buffer) {
161         /* Use buffer double default size for intermediate buffer */
162         psnd->allocated_size = 2 * conn->data->set.buffer_size;
163         psnd->buffer = malloc(psnd->allocated_size);
164         if(!psnd->buffer)
165           return CURLE_OUT_OF_MEMORY;
166         psnd->recv_size = 0;
167         psnd->recv_processed = 0;
168 #ifdef DEBUGBUILD
169         psnd->bindsock = sockfd; /* Used only for DEBUGASSERT */
170 #endif /* DEBUGBUILD */
171         bytestorecv = psnd->allocated_size;
172       }
173       if(psnd->buffer) {
174         ssize_t recvedbytes;
175         DEBUGASSERT(psnd->bindsock == sockfd);
176         recvedbytes = sread(sockfd, psnd->buffer + psnd->recv_size,
177                             bytestorecv);
178         if(recvedbytes > 0)
179           psnd->recv_size += recvedbytes;
180       }
181       else
182         psnd->allocated_size = 0;
183     }
184   }
185   return CURLE_OK;
186 }
187 
get_pre_recved(struct connectdata * conn,int num,char * buf,size_t len)188 static ssize_t get_pre_recved(struct connectdata *conn, int num, char *buf,
189                               size_t len)
190 {
191   struct postponed_data * const psnd = &(conn->postponed[num]);
192   size_t copysize;
193   if(!psnd->buffer)
194     return 0;
195 
196   DEBUGASSERT(psnd->allocated_size > 0);
197   DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
198   DEBUGASSERT(psnd->recv_processed <= psnd->recv_size);
199   /* Check and process data that already received and storied in internal
200      intermediate buffer */
201   if(psnd->recv_size > psnd->recv_processed) {
202     DEBUGASSERT(psnd->bindsock == conn->sock[num]);
203     copysize = CURLMIN(len, psnd->recv_size - psnd->recv_processed);
204     memcpy(buf, psnd->buffer + psnd->recv_processed, copysize);
205     psnd->recv_processed += copysize;
206   }
207   else
208     copysize = 0; /* buffer was allocated, but nothing was received */
209 
210   /* Free intermediate buffer if it has no unprocessed data */
211   if(psnd->recv_processed == psnd->recv_size) {
212     free(psnd->buffer);
213     psnd->buffer = NULL;
214     psnd->allocated_size = 0;
215     psnd->recv_size = 0;
216     psnd->recv_processed = 0;
217 #ifdef DEBUGBUILD
218     psnd->bindsock = CURL_SOCKET_BAD;
219 #endif /* DEBUGBUILD */
220   }
221   return (ssize_t)copysize;
222 }
223 #else  /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
224 /* Use "do-nothing" macros instead of functions when workaround not used */
Curl_recv_has_postponed_data(struct connectdata * conn,int sockindex)225 bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
226 {
227   (void)conn;
228   (void)sockindex;
229   return false;
230 }
231 #define pre_receive_plain(c,n) CURLE_OK
232 #define get_pre_recved(c,n,b,l) 0
233 #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
234 
235 /* Curl_infof() is for info message along the way */
236 
Curl_infof(struct Curl_easy * data,const char * fmt,...)237 void Curl_infof(struct Curl_easy *data, const char *fmt, ...)
238 {
239   if(data && data->set.verbose) {
240     va_list ap;
241     size_t len;
242     char print_buffer[2048 + 1];
243     va_start(ap, fmt);
244     len = mvsnprintf(print_buffer, sizeof(print_buffer), fmt, ap);
245     /*
246      * Indicate truncation of the input by replacing the last 3 characters
247      * with "...", and transfer the newline over in case the format had one.
248      */
249     if(len >= sizeof(print_buffer)) {
250       len = strlen(fmt);
251       if(fmt[--len] == '\n')
252         msnprintf(print_buffer + (sizeof(print_buffer) - 5), 5, "...\n");
253       else
254         msnprintf(print_buffer + (sizeof(print_buffer) - 4), 4, "...");
255     }
256     va_end(ap);
257     len = strlen(print_buffer);
258     Curl_debug(data, CURLINFO_TEXT, print_buffer, len);
259   }
260 }
261 
262 /* Curl_failf() is for messages stating why we failed.
263  * The message SHALL NOT include any LF or CR.
264  */
265 
Curl_failf(struct Curl_easy * data,const char * fmt,...)266 void Curl_failf(struct Curl_easy *data, const char *fmt, ...)
267 {
268   if(data->set.verbose || data->set.errorbuffer) {
269     va_list ap;
270     size_t len;
271     char error[CURL_ERROR_SIZE + 2];
272     va_start(ap, fmt);
273     (void)mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap);
274     len = strlen(error);
275 
276     if(data->set.errorbuffer && !data->state.errorbuf) {
277       strcpy(data->set.errorbuffer, error);
278       data->state.errorbuf = TRUE; /* wrote error string */
279     }
280     if(data->set.verbose) {
281       error[len] = '\n';
282       error[++len] = '\0';
283       Curl_debug(data, CURLINFO_TEXT, error, len);
284     }
285     va_end(ap);
286   }
287 }
288 
289 /*
290  * Curl_write() is an internal write function that sends data to the
291  * server. Works with plain sockets, SCP, SSL or kerberos.
292  *
293  * If the write would block (CURLE_AGAIN), we return CURLE_OK and
294  * (*written == 0). Otherwise we return regular CURLcode value.
295  */
Curl_write(struct connectdata * conn,curl_socket_t sockfd,const void * mem,size_t len,ssize_t * written)296 CURLcode Curl_write(struct connectdata *conn,
297                     curl_socket_t sockfd,
298                     const void *mem,
299                     size_t len,
300                     ssize_t *written)
301 {
302   ssize_t bytes_written;
303   CURLcode result = CURLE_OK;
304   int num = (sockfd == conn->sock[SECONDARYSOCKET]);
305 
306   bytes_written = conn->send[num](conn, num, mem, len, &result);
307 
308   *written = bytes_written;
309   if(bytes_written >= 0)
310     /* we completely ignore the curlcode value when subzero is not returned */
311     return CURLE_OK;
312 
313   /* handle CURLE_AGAIN or a send failure */
314   switch(result) {
315   case CURLE_AGAIN:
316     *written = 0;
317     return CURLE_OK;
318 
319   case CURLE_OK:
320     /* general send failure */
321     return CURLE_SEND_ERROR;
322 
323   default:
324     /* we got a specific curlcode, forward it */
325     return result;
326   }
327 }
328 
Curl_send_plain(struct connectdata * conn,int num,const void * mem,size_t len,CURLcode * code)329 ssize_t Curl_send_plain(struct connectdata *conn, int num,
330                         const void *mem, size_t len, CURLcode *code)
331 {
332   curl_socket_t sockfd = conn->sock[num];
333   ssize_t bytes_written;
334   /* WinSock will destroy unread received data if send() is
335      failed.
336      To avoid lossage of received data, recv() must be
337      performed before every send() if any incoming data is
338      available. */
339   if(pre_receive_plain(conn, num)) {
340     *code = CURLE_OUT_OF_MEMORY;
341     return -1;
342   }
343 
344 #if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
345   if(conn->bits.tcp_fastopen) {
346     bytes_written = sendto(sockfd, mem, len, MSG_FASTOPEN,
347                            conn->ip_addr->ai_addr, conn->ip_addr->ai_addrlen);
348     conn->bits.tcp_fastopen = FALSE;
349   }
350   else
351 #endif
352     bytes_written = swrite(sockfd, mem, len);
353 
354   *code = CURLE_OK;
355   if(-1 == bytes_written) {
356     int err = SOCKERRNO;
357 
358     if(
359 #ifdef WSAEWOULDBLOCK
360       /* This is how Windows does it */
361       (WSAEWOULDBLOCK == err)
362 #else
363       /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
364          due to its inability to send off data without blocking. We therefore
365          treat both error codes the same here */
366       (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err) ||
367       (EINPROGRESS == err)
368 #endif
369       ) {
370       /* this is just a case of EWOULDBLOCK */
371       bytes_written = 0;
372       *code = CURLE_AGAIN;
373     }
374     else {
375       char buffer[STRERROR_LEN];
376       failf(conn->data, "Send failure: %s",
377             Curl_strerror(err, buffer, sizeof(buffer)));
378       conn->data->state.os_errno = err;
379       *code = CURLE_SEND_ERROR;
380     }
381   }
382   return bytes_written;
383 }
384 
385 /*
386  * Curl_write_plain() is an internal write function that sends data to the
387  * server using plain sockets only. Otherwise meant to have the exact same
388  * proto as Curl_write()
389  */
Curl_write_plain(struct connectdata * conn,curl_socket_t sockfd,const void * mem,size_t len,ssize_t * written)390 CURLcode Curl_write_plain(struct connectdata *conn,
391                           curl_socket_t sockfd,
392                           const void *mem,
393                           size_t len,
394                           ssize_t *written)
395 {
396   ssize_t bytes_written;
397   CURLcode result;
398   int num = (sockfd == conn->sock[SECONDARYSOCKET]);
399 
400   bytes_written = Curl_send_plain(conn, num, mem, len, &result);
401 
402   *written = bytes_written;
403 
404   return result;
405 }
406 
Curl_recv_plain(struct connectdata * conn,int num,char * buf,size_t len,CURLcode * code)407 ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf,
408                         size_t len, CURLcode *code)
409 {
410   curl_socket_t sockfd = conn->sock[num];
411   ssize_t nread;
412   /* Check and return data that already received and storied in internal
413      intermediate buffer */
414   nread = get_pre_recved(conn, num, buf, len);
415   if(nread > 0) {
416     *code = CURLE_OK;
417     return nread;
418   }
419 
420   nread = sread(sockfd, buf, len);
421 
422   *code = CURLE_OK;
423   if(-1 == nread) {
424     int err = SOCKERRNO;
425 
426     if(
427 #ifdef WSAEWOULDBLOCK
428       /* This is how Windows does it */
429       (WSAEWOULDBLOCK == err)
430 #else
431       /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
432          due to its inability to send off data without blocking. We therefore
433          treat both error codes the same here */
434       (EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err)
435 #endif
436       ) {
437       /* this is just a case of EWOULDBLOCK */
438       *code = CURLE_AGAIN;
439     }
440     else {
441       char buffer[STRERROR_LEN];
442       failf(conn->data, "Recv failure: %s",
443             Curl_strerror(err, buffer, sizeof(buffer)));
444       conn->data->state.os_errno = err;
445       *code = CURLE_RECV_ERROR;
446     }
447   }
448   return nread;
449 }
450 
pausewrite(struct Curl_easy * data,int type,const char * ptr,size_t len)451 static CURLcode pausewrite(struct Curl_easy *data,
452                            int type, /* what type of data */
453                            const char *ptr,
454                            size_t len)
455 {
456   /* signalled to pause sending on this connection, but since we have data
457      we want to send we need to dup it to save a copy for when the sending
458      is again enabled */
459   struct SingleRequest *k = &data->req;
460   struct UrlState *s = &data->state;
461   unsigned int i;
462   bool newtype = TRUE;
463 
464   /* If this transfers over HTTP/2, pause the stream! */
465   Curl_http2_stream_pause(data, TRUE);
466 
467   if(s->tempcount) {
468     for(i = 0; i< s->tempcount; i++) {
469       if(s->tempwrite[i].type == type) {
470         /* data for this type exists */
471         newtype = FALSE;
472         break;
473       }
474     }
475     DEBUGASSERT(i < 3);
476   }
477   else
478     i = 0;
479 
480   if(newtype) {
481     /* store this information in the state struct for later use */
482     Curl_dyn_init(&s->tempwrite[i].b, DYN_PAUSE_BUFFER);
483     s->tempwrite[i].type = type;
484 
485     if(newtype)
486       s->tempcount++;
487   }
488 
489   if(Curl_dyn_addn(&s->tempwrite[i].b, (unsigned char *)ptr, len))
490     return CURLE_OUT_OF_MEMORY;
491 
492   /* mark the connection as RECV paused */
493   k->keepon |= KEEP_RECV_PAUSE;
494 
495   return CURLE_OK;
496 }
497 
498 
499 /* chop_write() writes chunks of data not larger than CURL_MAX_WRITE_SIZE via
500  * client write callback(s) and takes care of pause requests from the
501  * callbacks.
502  */
chop_write(struct connectdata * conn,int type,char * optr,size_t olen)503 static CURLcode chop_write(struct connectdata *conn,
504                            int type,
505                            char *optr,
506                            size_t olen)
507 {
508   struct Curl_easy *data = conn->data;
509   curl_write_callback writeheader = NULL;
510   curl_write_callback writebody = NULL;
511   char *ptr = optr;
512   size_t len = olen;
513 
514   if(!len)
515     return CURLE_OK;
516 
517   /* If reading is paused, append this data to the already held data for this
518      type. */
519   if(data->req.keepon & KEEP_RECV_PAUSE)
520     return pausewrite(data, type, ptr, len);
521 
522   /* Determine the callback(s) to use. */
523   if(type & CLIENTWRITE_BODY)
524     writebody = data->set.fwrite_func;
525   if((type & CLIENTWRITE_HEADER) &&
526      (data->set.fwrite_header || data->set.writeheader)) {
527     /*
528      * Write headers to the same callback or to the especially setup
529      * header callback function (added after version 7.7.1).
530      */
531     writeheader =
532       data->set.fwrite_header? data->set.fwrite_header: data->set.fwrite_func;
533   }
534 
535   /* Chop data, write chunks. */
536   while(len) {
537     size_t chunklen = len <= CURL_MAX_WRITE_SIZE? len: CURL_MAX_WRITE_SIZE;
538 
539     if(writebody) {
540       size_t wrote;
541       Curl_set_in_callback(data, true);
542       wrote = writebody(ptr, 1, chunklen, data->set.out);
543       Curl_set_in_callback(data, false);
544 
545       if(CURL_WRITEFUNC_PAUSE == wrote) {
546         if(conn->handler->flags & PROTOPT_NONETWORK) {
547           /* Protocols that work without network cannot be paused. This is
548              actually only FILE:// just now, and it can't pause since the
549              transfer isn't done using the "normal" procedure. */
550           failf(data, "Write callback asked for PAUSE when not supported!");
551           return CURLE_WRITE_ERROR;
552         }
553         return pausewrite(data, type, ptr, len);
554       }
555       if(wrote != chunklen) {
556         failf(data, "Failure writing output to destination");
557         return CURLE_WRITE_ERROR;
558       }
559     }
560 
561     ptr += chunklen;
562     len -= chunklen;
563   }
564 
565   if(writeheader) {
566     size_t wrote;
567     ptr = optr;
568     len = olen;
569     Curl_set_in_callback(data, true);
570     wrote = writeheader(ptr, 1, len, data->set.writeheader);
571     Curl_set_in_callback(data, false);
572 
573     if(CURL_WRITEFUNC_PAUSE == wrote)
574       /* here we pass in the HEADER bit only since if this was body as well
575          then it was passed already and clearly that didn't trigger the
576          pause, so this is saved for later with the HEADER bit only */
577       return pausewrite(data, CLIENTWRITE_HEADER, ptr, len);
578 
579     if(wrote != len) {
580       failf(data, "Failed writing header");
581       return CURLE_WRITE_ERROR;
582     }
583   }
584 
585   return CURLE_OK;
586 }
587 
588 
589 /* Curl_client_write() sends data to the write callback(s)
590 
591    The bit pattern defines to what "streams" to write to. Body and/or header.
592    The defines are in sendf.h of course.
593 
594    If CURL_DO_LINEEND_CONV is enabled, data is converted IN PLACE to the
595    local character encoding.  This is a problem and should be changed in
596    the future to leave the original data alone.
597  */
Curl_client_write(struct connectdata * conn,int type,char * ptr,size_t len)598 CURLcode Curl_client_write(struct connectdata *conn,
599                            int type,
600                            char *ptr,
601                            size_t len)
602 {
603   struct Curl_easy *data = conn->data;
604 
605   if(0 == len)
606     len = strlen(ptr);
607 
608   DEBUGASSERT(type <= 3);
609 
610   /* FTP data may need conversion. */
611   if((type & CLIENTWRITE_BODY) &&
612     (conn->handler->protocol & PROTO_FAMILY_FTP) &&
613     conn->proto.ftpc.transfertype == 'A') {
614     /* convert from the network encoding */
615     CURLcode result = Curl_convert_from_network(data, ptr, len);
616     /* Curl_convert_from_network calls failf if unsuccessful */
617     if(result)
618       return result;
619 
620 #ifdef CURL_DO_LINEEND_CONV
621     /* convert end-of-line markers */
622     len = convert_lineends(data, ptr, len);
623 #endif /* CURL_DO_LINEEND_CONV */
624     }
625 
626   return chop_write(conn, type, ptr, len);
627 }
628 
Curl_read_plain(curl_socket_t sockfd,char * buf,size_t bytesfromsocket,ssize_t * n)629 CURLcode Curl_read_plain(curl_socket_t sockfd,
630                          char *buf,
631                          size_t bytesfromsocket,
632                          ssize_t *n)
633 {
634   ssize_t nread = sread(sockfd, buf, bytesfromsocket);
635 
636   if(-1 == nread) {
637     const int err = SOCKERRNO;
638     const bool return_error =
639 #ifdef USE_WINSOCK
640       WSAEWOULDBLOCK == err
641 #else
642       EWOULDBLOCK == err || EAGAIN == err || EINTR == err
643 #endif
644       ;
645     *n = 0; /* no data returned */
646     if(return_error)
647       return CURLE_AGAIN;
648     return CURLE_RECV_ERROR;
649   }
650 
651   *n = nread;
652   return CURLE_OK;
653 }
654 
655 /*
656  * Internal read-from-socket function. This is meant to deal with plain
657  * sockets, SSL sockets and kerberos sockets.
658  *
659  * Returns a regular CURLcode value.
660  */
Curl_read(struct connectdata * conn,curl_socket_t sockfd,char * buf,size_t sizerequested,ssize_t * n)661 CURLcode Curl_read(struct connectdata *conn, /* connection data */
662                    curl_socket_t sockfd,     /* read from this socket */
663                    char *buf,                /* store read data here */
664                    size_t sizerequested,     /* max amount to read */
665                    ssize_t *n)               /* amount bytes read */
666 {
667   CURLcode result = CURLE_RECV_ERROR;
668   ssize_t nread = 0;
669   size_t bytesfromsocket = 0;
670   char *buffertofill = NULL;
671   struct Curl_easy *data = conn->data;
672 
673   /* Set 'num' to 0 or 1, depending on which socket that has been sent here.
674      If it is the second socket, we set num to 1. Otherwise to 0. This lets
675      us use the correct ssl handle. */
676   int num = (sockfd == conn->sock[SECONDARYSOCKET]);
677 
678   *n = 0; /* reset amount to zero */
679 
680   bytesfromsocket = CURLMIN(sizerequested, (size_t)data->set.buffer_size);
681   buffertofill = buf;
682 
683   nread = conn->recv[num](conn, num, buffertofill, bytesfromsocket, &result);
684   if(nread < 0)
685     return result;
686 
687   *n += nread;
688 
689   return CURLE_OK;
690 }
691 
692 /* return 0 on success */
Curl_debug(struct Curl_easy * data,curl_infotype type,char * ptr,size_t size)693 int Curl_debug(struct Curl_easy *data, curl_infotype type,
694                char *ptr, size_t size)
695 {
696   static const char s_infotype[CURLINFO_END][3] = {
697     "* ", "< ", "> ", "{ ", "} ", "{ ", "} " };
698   int rc = 0;
699 
700 #ifdef CURL_DOES_CONVERSIONS
701   char *buf = NULL;
702   size_t conv_size = 0;
703 
704   switch(type) {
705   case CURLINFO_HEADER_OUT:
706     buf = Curl_memdup(ptr, size);
707     if(!buf)
708       return 1;
709     conv_size = size;
710 
711     /* Special processing is needed for this block if it
712      * contains both headers and data (separated by CRLFCRLF).
713      * We want to convert just the headers, leaving the data as-is.
714      */
715     if(size > 4) {
716       size_t i;
717       for(i = 0; i < size-4; i++) {
718         if(memcmp(&buf[i], "\x0d\x0a\x0d\x0a", 4) == 0) {
719           /* convert everything through this CRLFCRLF but no further */
720           conv_size = i + 4;
721           break;
722         }
723       }
724     }
725 
726     Curl_convert_from_network(data, buf, conv_size);
727     /* Curl_convert_from_network calls failf if unsuccessful */
728     /* we might as well continue even if it fails...   */
729     ptr = buf; /* switch pointer to use my buffer instead */
730     break;
731   default:
732     /* leave everything else as-is */
733     break;
734   }
735 #endif /* CURL_DOES_CONVERSIONS */
736 
737   if(data->set.fdebug) {
738     Curl_set_in_callback(data, true);
739     rc = (*data->set.fdebug)(data, type, ptr, size, data->set.debugdata);
740     Curl_set_in_callback(data, false);
741   }
742   else {
743     switch(type) {
744     case CURLINFO_TEXT:
745     case CURLINFO_HEADER_OUT:
746     case CURLINFO_HEADER_IN:
747       fwrite(s_infotype[type], 2, 1, data->set.err);
748       fwrite(ptr, size, 1, data->set.err);
749 #ifdef CURL_DOES_CONVERSIONS
750       if(size != conv_size) {
751         /* we had untranslated data so we need an explicit newline */
752         fwrite("\n", 1, 1, data->set.err);
753       }
754 #endif
755       break;
756     default: /* nada */
757       break;
758     }
759   }
760 #ifdef CURL_DOES_CONVERSIONS
761   free(buf);
762 #endif
763   return rc;
764 }
765