Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Utilities / cmcurl / lib / easy.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2022, 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
27 /*
28  * See comment in curl_memory.h for the explanation of this sanity check.
29  */
30
31 #ifdef CURLX_NO_MEMORY_CALLBACKS
32 #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
33 #endif
34
35 #ifdef HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38 #ifdef HAVE_NETDB_H
39 #include <netdb.h>
40 #endif
41 #ifdef HAVE_ARPA_INET_H
42 #include <arpa/inet.h>
43 #endif
44 #ifdef HAVE_NET_IF_H
45 #include <net/if.h>
46 #endif
47 #ifdef HAVE_SYS_IOCTL_H
48 #include <sys/ioctl.h>
49 #endif
50
51 #ifdef HAVE_SYS_PARAM_H
52 #include <sys/param.h>
53 #endif
54
55 #include "urldata.h"
56 #include <curl/curl.h>
57 #include "transfer.h"
58 #include "vtls/vtls.h"
59 #include "url.h"
60 #include "getinfo.h"
61 #include "hostip.h"
62 #include "share.h"
63 #include "strdup.h"
64 #include "progress.h"
65 #include "easyif.h"
66 #include "multiif.h"
67 #include "select.h"
68 #include "sendf.h" /* for failf function prototype */
69 #include "connect.h" /* for Curl_getconnectinfo */
70 #include "slist.h"
71 #include "mime.h"
72 #include "amigaos.h"
73 #include "warnless.h"
74 #include "multiif.h"
75 #include "sigpipe.h"
76 #include "vssh/ssh.h"
77 #include "setopt.h"
78 #include "http_digest.h"
79 #include "system_win32.h"
80 #include "http2.h"
81 #include "dynbuf.h"
82 #include "altsvc.h"
83 #include "hsts.h"
84
85 #include "easy_lock.h"
86
87 /* The last 3 #include files should be in this order */
88 #include "curl_printf.h"
89 #include "curl_memory.h"
90 #include "memdebug.h"
91
92 /* true globals -- for curl_global_init() and curl_global_cleanup() */
93 static unsigned int  initialized;
94 static long          init_flags;
95
96 #ifdef GLOBAL_INIT_IS_THREADSAFE
97
98 static curl_simple_lock s_lock = CURL_SIMPLE_LOCK_INIT;
99 #define global_init_lock() curl_simple_lock_lock(&s_lock)
100 #define global_init_unlock() curl_simple_lock_unlock(&s_lock)
101
102 #else
103
104 #define global_init_lock()
105 #define global_init_unlock()
106
107 #endif
108
109 /*
110  * strdup (and other memory functions) is redefined in complicated
111  * ways, but at this point it must be defined as the system-supplied strdup
112  * so the callback pointer is initialized correctly.
113  */
114 #if defined(_WIN32_WCE)
115 #define system_strdup _strdup
116 #elif !defined(HAVE_STRDUP)
117 #define system_strdup curlx_strdup
118 #else
119 #define system_strdup strdup
120 #endif
121
122 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
123 #  pragma warning(disable:4232) /* MSVC extension, dllimport identity */
124 #endif
125
126 /*
127  * If a memory-using function (like curl_getenv) is used before
128  * curl_global_init() is called, we need to have these pointers set already.
129  */
130 curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
131 curl_free_callback Curl_cfree = (curl_free_callback)free;
132 curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
133 curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
134 curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
135 #if defined(WIN32) && defined(UNICODE)
136 curl_wcsdup_callback Curl_cwcsdup = Curl_wcsdup;
137 #endif
138
139 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
140 #  pragma warning(default:4232) /* MSVC extension, dllimport identity */
141 #endif
142
143 #ifdef DEBUGBUILD
144 static char *leakpointer;
145 #endif
146
147 /**
148  * curl_global_init() globally initializes curl given a bitwise set of the
149  * different features of what to initialize.
150  */
151 static CURLcode global_init(long flags, bool memoryfuncs)
152 {
153   if(initialized++)
154     return CURLE_OK;
155
156   if(memoryfuncs) {
157     /* Setup the default memory functions here (again) */
158     Curl_cmalloc = (curl_malloc_callback)malloc;
159     Curl_cfree = (curl_free_callback)free;
160     Curl_crealloc = (curl_realloc_callback)realloc;
161     Curl_cstrdup = (curl_strdup_callback)system_strdup;
162     Curl_ccalloc = (curl_calloc_callback)calloc;
163 #if defined(WIN32) && defined(UNICODE)
164     Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
165 #endif
166   }
167
168   if(!Curl_ssl_init()) {
169     DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
170     goto fail;
171   }
172
173 #ifdef WIN32
174   if(Curl_win32_init(flags)) {
175     DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
176     goto fail;
177   }
178 #endif
179
180 #ifdef __AMIGA__
181   if(Curl_amiga_init()) {
182     DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
183     goto fail;
184   }
185 #endif
186
187   if(Curl_resolver_global_init()) {
188     DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
189     goto fail;
190   }
191
192 #if defined(USE_SSH)
193   if(Curl_ssh_init()) {
194     goto fail;
195   }
196 #endif
197
198 #ifdef USE_WOLFSSH
199   if(WS_SUCCESS != wolfSSH_Init()) {
200     DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n"));
201     return CURLE_FAILED_INIT;
202   }
203 #endif
204
205   init_flags = flags;
206
207 #ifdef DEBUGBUILD
208   if(getenv("CURL_GLOBAL_INIT"))
209     /* alloc data that will leak if *cleanup() is not called! */
210     leakpointer = malloc(1);
211 #endif
212
213   return CURLE_OK;
214
215   fail:
216   initialized--; /* undo the increase */
217   return CURLE_FAILED_INIT;
218 }
219
220
221 /**
222  * curl_global_init() globally initializes curl given a bitwise set of the
223  * different features of what to initialize.
224  */
225 CURLcode curl_global_init(long flags)
226 {
227   CURLcode result;
228   global_init_lock();
229
230   result = global_init(flags, TRUE);
231
232   global_init_unlock();
233
234   return result;
235 }
236
237 /*
238  * curl_global_init_mem() globally initializes curl and also registers the
239  * user provided callback routines.
240  */
241 CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
242                               curl_free_callback f, curl_realloc_callback r,
243                               curl_strdup_callback s, curl_calloc_callback c)
244 {
245   CURLcode result;
246
247   /* Invalid input, return immediately */
248   if(!m || !f || !r || !s || !c)
249     return CURLE_FAILED_INIT;
250
251   global_init_lock();
252
253   if(initialized) {
254     /* Already initialized, don't do it again, but bump the variable anyway to
255        work like curl_global_init() and require the same amount of cleanup
256        calls. */
257     initialized++;
258     global_init_unlock();
259     return CURLE_OK;
260   }
261
262   /* set memory functions before global_init() in case it wants memory
263      functions */
264   Curl_cmalloc = m;
265   Curl_cfree = f;
266   Curl_cstrdup = s;
267   Curl_crealloc = r;
268   Curl_ccalloc = c;
269
270   /* Call the actual init function, but without setting */
271   result = global_init(flags, FALSE);
272
273   global_init_unlock();
274
275   return result;
276 }
277
278 /**
279  * curl_global_cleanup() globally cleanups curl, uses the value of
280  * "init_flags" to determine what needs to be cleaned up and what doesn't.
281  */
282 void curl_global_cleanup(void)
283 {
284   global_init_lock();
285
286   if(!initialized) {
287     global_init_unlock();
288     return;
289   }
290
291   if(--initialized) {
292     global_init_unlock();
293     return;
294   }
295
296   Curl_ssl_cleanup();
297   Curl_resolver_global_cleanup();
298
299 #ifdef WIN32
300   Curl_win32_cleanup(init_flags);
301 #endif
302
303   Curl_amiga_cleanup();
304
305   Curl_ssh_cleanup();
306
307 #ifdef USE_WOLFSSH
308   (void)wolfSSH_Cleanup();
309 #endif
310 #ifdef DEBUGBUILD
311   free(leakpointer);
312 #endif
313
314   init_flags  = 0;
315
316   global_init_unlock();
317 }
318
319 /*
320  * curl_global_sslset() globally initializes the SSL backend to use.
321  */
322 CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
323                               const curl_ssl_backend ***avail)
324 {
325   CURLsslset rc;
326
327   global_init_lock();
328
329   rc = Curl_init_sslset_nolock(id, name, avail);
330
331   global_init_unlock();
332
333   return rc;
334 }
335
336 /*
337  * curl_easy_init() is the external interface to alloc, setup and init an
338  * easy handle that is returned. If anything goes wrong, NULL is returned.
339  */
340 struct Curl_easy *curl_easy_init(void)
341 {
342   CURLcode result;
343   struct Curl_easy *data;
344
345   /* Make sure we inited the global SSL stuff */
346   global_init_lock();
347
348   if(!initialized) {
349     result = global_init(CURL_GLOBAL_DEFAULT, TRUE);
350     if(result) {
351       /* something in the global init failed, return nothing */
352       DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
353       global_init_unlock();
354       return NULL;
355     }
356   }
357   global_init_unlock();
358
359   /* We use curl_open() with undefined URL so far */
360   result = Curl_open(&data);
361   if(result) {
362     DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
363     return NULL;
364   }
365
366   return data;
367 }
368
369 #ifdef CURLDEBUG
370
371 struct socketmonitor {
372   struct socketmonitor *next; /* the next node in the list or NULL */
373   struct pollfd socket; /* socket info of what to monitor */
374 };
375
376 struct events {
377   long ms;              /* timeout, run the timeout function when reached */
378   bool msbump;          /* set TRUE when timeout is set by callback */
379   int num_sockets;      /* number of nodes in the monitor list */
380   struct socketmonitor *list; /* list of sockets to monitor */
381   int running_handles;  /* store the returned number */
382 };
383
384 /* events_timer
385  *
386  * Callback that gets called with a new value when the timeout should be
387  * updated.
388  */
389
390 static int events_timer(struct Curl_multi *multi,    /* multi handle */
391                         long timeout_ms, /* see above */
392                         void *userp)    /* private callback pointer */
393 {
394   struct events *ev = userp;
395   (void)multi;
396   if(timeout_ms == -1)
397     /* timeout removed */
398     timeout_ms = 0;
399   else if(timeout_ms == 0)
400     /* timeout is already reached! */
401     timeout_ms = 1; /* trigger asap */
402
403   ev->ms = timeout_ms;
404   ev->msbump = TRUE;
405   return 0;
406 }
407
408
409 /* poll2cselect
410  *
411  * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
412  */
413 static int poll2cselect(int pollmask)
414 {
415   int omask = 0;
416   if(pollmask & POLLIN)
417     omask |= CURL_CSELECT_IN;
418   if(pollmask & POLLOUT)
419     omask |= CURL_CSELECT_OUT;
420   if(pollmask & POLLERR)
421     omask |= CURL_CSELECT_ERR;
422   return omask;
423 }
424
425
426 /* socketcb2poll
427  *
428  * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
429  */
430 static short socketcb2poll(int pollmask)
431 {
432   short omask = 0;
433   if(pollmask & CURL_POLL_IN)
434     omask |= POLLIN;
435   if(pollmask & CURL_POLL_OUT)
436     omask |= POLLOUT;
437   return omask;
438 }
439
440 /* events_socket
441  *
442  * Callback that gets called with information about socket activity to
443  * monitor.
444  */
445 static int events_socket(struct Curl_easy *easy,      /* easy handle */
446                          curl_socket_t s, /* socket */
447                          int what,        /* see above */
448                          void *userp,     /* private callback
449                                              pointer */
450                          void *socketp)   /* private socket
451                                              pointer */
452 {
453   struct events *ev = userp;
454   struct socketmonitor *m;
455   struct socketmonitor *prev = NULL;
456
457 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
458   (void) easy;
459 #endif
460   (void)socketp;
461
462   m = ev->list;
463   while(m) {
464     if(m->socket.fd == s) {
465
466       if(what == CURL_POLL_REMOVE) {
467         struct socketmonitor *nxt = m->next;
468         /* remove this node from the list of monitored sockets */
469         if(prev)
470           prev->next = nxt;
471         else
472           ev->list = nxt;
473         free(m);
474         m = nxt;
475         infof(easy, "socket cb: socket %d REMOVED", s);
476       }
477       else {
478         /* The socket 's' is already being monitored, update the activity
479            mask. Convert from libcurl bitmask to the poll one. */
480         m->socket.events = socketcb2poll(what);
481         infof(easy, "socket cb: socket %d UPDATED as %s%s", s,
482               (what&CURL_POLL_IN)?"IN":"",
483               (what&CURL_POLL_OUT)?"OUT":"");
484       }
485       break;
486     }
487     prev = m;
488     m = m->next; /* move to next node */
489   }
490   if(!m) {
491     if(what == CURL_POLL_REMOVE) {
492       /* this happens a bit too often, libcurl fix perhaps? */
493       /* fprintf(stderr,
494          "%s: socket %d asked to be REMOVED but not present!\n",
495                  __func__, s); */
496     }
497     else {
498       m = malloc(sizeof(struct socketmonitor));
499       if(m) {
500         m->next = ev->list;
501         m->socket.fd = s;
502         m->socket.events = socketcb2poll(what);
503         m->socket.revents = 0;
504         ev->list = m;
505         infof(easy, "socket cb: socket %d ADDED as %s%s", s,
506               (what&CURL_POLL_IN)?"IN":"",
507               (what&CURL_POLL_OUT)?"OUT":"");
508       }
509       else
510         return CURLE_OUT_OF_MEMORY;
511     }
512   }
513
514   return 0;
515 }
516
517
518 /*
519  * events_setup()
520  *
521  * Do the multi handle setups that only event-based transfers need.
522  */
523 static void events_setup(struct Curl_multi *multi, struct events *ev)
524 {
525   /* timer callback */
526   curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
527   curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
528
529   /* socket callback */
530   curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
531   curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
532 }
533
534
535 /* wait_or_timeout()
536  *
537  * waits for activity on any of the given sockets, or the timeout to trigger.
538  */
539
540 static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
541 {
542   bool done = FALSE;
543   CURLMcode mcode = CURLM_OK;
544   CURLcode result = CURLE_OK;
545
546   while(!done) {
547     CURLMsg *msg;
548     struct socketmonitor *m;
549     struct pollfd *f;
550     struct pollfd fds[4];
551     int numfds = 0;
552     int pollrc;
553     int i;
554     struct curltime before;
555     struct curltime after;
556
557     /* populate the fds[] array */
558     for(m = ev->list, f = &fds[0]; m; m = m->next) {
559       f->fd = m->socket.fd;
560       f->events = m->socket.events;
561       f->revents = 0;
562       /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
563       f++;
564       numfds++;
565     }
566
567     /* get the time stamp to use to figure out how long poll takes */
568     before = Curl_now();
569
570     /* wait for activity or timeout */
571     pollrc = Curl_poll(fds, numfds, ev->ms);
572     if(pollrc < 0)
573       return CURLE_UNRECOVERABLE_POLL;
574
575     after = Curl_now();
576
577     ev->msbump = FALSE; /* reset here */
578
579     if(!pollrc) {
580       /* timeout! */
581       ev->ms = 0;
582       /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */
583       mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
584                                        &ev->running_handles);
585     }
586     else {
587       /* here pollrc is > 0 */
588
589       /* loop over the monitored sockets to see which ones had activity */
590       for(i = 0; i< numfds; i++) {
591         if(fds[i].revents) {
592           /* socket activity, tell libcurl */
593           int act = poll2cselect(fds[i].revents); /* convert */
594           infof(multi->easyp, "call curl_multi_socket_action(socket %d)",
595                 fds[i].fd);
596           mcode = curl_multi_socket_action(multi, fds[i].fd, act,
597                                            &ev->running_handles);
598         }
599       }
600
601       if(!ev->msbump) {
602         /* If nothing updated the timeout, we decrease it by the spent time.
603          * If it was updated, it has the new timeout time stored already.
604          */
605         timediff_t timediff = Curl_timediff(after, before);
606         if(timediff > 0) {
607           if(timediff > ev->ms)
608             ev->ms = 0;
609           else
610             ev->ms -= (long)timediff;
611         }
612       }
613     }
614
615     if(mcode)
616       return CURLE_URL_MALFORMAT;
617
618     /* we don't really care about the "msgs_in_queue" value returned in the
619        second argument */
620     msg = curl_multi_info_read(multi, &pollrc);
621     if(msg) {
622       result = msg->data.result;
623       done = TRUE;
624     }
625   }
626
627   return result;
628 }
629
630
631 /* easy_events()
632  *
633  * Runs a transfer in a blocking manner using the events-based API
634  */
635 static CURLcode easy_events(struct Curl_multi *multi)
636 {
637   /* this struct is made static to allow it to be used after this function
638      returns and curl_multi_remove_handle() is called */
639   static struct events evs = {2, FALSE, 0, NULL, 0};
640
641   /* if running event-based, do some further multi inits */
642   events_setup(multi, &evs);
643
644   return wait_or_timeout(multi, &evs);
645 }
646 #else /* CURLDEBUG */
647 /* when not built with debug, this function doesn't exist */
648 #define easy_events(x) CURLE_NOT_BUILT_IN
649 #endif
650
651 static CURLcode easy_transfer(struct Curl_multi *multi)
652 {
653   bool done = FALSE;
654   CURLMcode mcode = CURLM_OK;
655   CURLcode result = CURLE_OK;
656
657   while(!done && !mcode) {
658     int still_running = 0;
659
660     mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL);
661
662     if(!mcode)
663       mcode = curl_multi_perform(multi, &still_running);
664
665     /* only read 'still_running' if curl_multi_perform() return OK */
666     if(!mcode && !still_running) {
667       int rc;
668       CURLMsg *msg = curl_multi_info_read(multi, &rc);
669       if(msg) {
670         result = msg->data.result;
671         done = TRUE;
672       }
673     }
674   }
675
676   /* Make sure to return some kind of error if there was a multi problem */
677   if(mcode) {
678     result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY :
679               /* The other multi errors should never happen, so return
680                  something suitably generic */
681               CURLE_BAD_FUNCTION_ARGUMENT;
682   }
683
684   return result;
685 }
686
687
688 /*
689  * easy_perform() is the external interface that performs a blocking
690  * transfer as previously setup.
691  *
692  * CONCEPT: This function creates a multi handle, adds the easy handle to it,
693  * runs curl_multi_perform() until the transfer is done, then detaches the
694  * easy handle, destroys the multi handle and returns the easy handle's return
695  * code.
696  *
697  * REALITY: it can't just create and destroy the multi handle that easily. It
698  * needs to keep it around since if this easy handle is used again by this
699  * function, the same multi handle must be re-used so that the same pools and
700  * caches can be used.
701  *
702  * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
703  * instead of curl_multi_perform() and use curl_multi_socket_action().
704  */
705 static CURLcode easy_perform(struct Curl_easy *data, bool events)
706 {
707   struct Curl_multi *multi;
708   CURLMcode mcode;
709   CURLcode result = CURLE_OK;
710   SIGPIPE_VARIABLE(pipe_st);
711
712   if(!data)
713     return CURLE_BAD_FUNCTION_ARGUMENT;
714
715   if(data->set.errorbuffer)
716     /* clear this as early as possible */
717     data->set.errorbuffer[0] = 0;
718
719   if(data->multi) {
720     failf(data, "easy handle already used in multi handle");
721     return CURLE_FAILED_INIT;
722   }
723
724   if(data->multi_easy)
725     multi = data->multi_easy;
726   else {
727     /* this multi handle will only ever have a single easy handled attached
728        to it, so make it use minimal hashes */
729     multi = Curl_multi_handle(1, 3, 7);
730     if(!multi)
731       return CURLE_OUT_OF_MEMORY;
732     data->multi_easy = multi;
733   }
734
735   if(multi->in_callback)
736     return CURLE_RECURSIVE_API_CALL;
737
738   /* Copy the MAXCONNECTS option to the multi handle */
739   curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
740
741   mcode = curl_multi_add_handle(multi, data);
742   if(mcode) {
743     curl_multi_cleanup(multi);
744     data->multi_easy = NULL;
745     if(mcode == CURLM_OUT_OF_MEMORY)
746       return CURLE_OUT_OF_MEMORY;
747     return CURLE_FAILED_INIT;
748   }
749
750   sigpipe_ignore(data, &pipe_st);
751
752   /* run the transfer */
753   result = events ? easy_events(multi) : easy_transfer(multi);
754
755   /* ignoring the return code isn't nice, but atm we can't really handle
756      a failure here, room for future improvement! */
757   (void)curl_multi_remove_handle(multi, data);
758
759   sigpipe_restore(&pipe_st);
760
761   /* The multi handle is kept alive, owned by the easy handle */
762   return result;
763 }
764
765
766 /*
767  * curl_easy_perform() is the external interface that performs a blocking
768  * transfer as previously setup.
769  */
770 CURLcode curl_easy_perform(struct Curl_easy *data)
771 {
772   return easy_perform(data, FALSE);
773 }
774
775 #ifdef CURLDEBUG
776 /*
777  * curl_easy_perform_ev() is the external interface that performs a blocking
778  * transfer using the event-based API internally.
779  */
780 CURLcode curl_easy_perform_ev(struct Curl_easy *data)
781 {
782   return easy_perform(data, TRUE);
783 }
784
785 #endif
786
787 /*
788  * curl_easy_cleanup() is the external interface to cleaning/freeing the given
789  * easy handle.
790  */
791 void curl_easy_cleanup(struct Curl_easy *data)
792 {
793   SIGPIPE_VARIABLE(pipe_st);
794
795   if(!data)
796     return;
797
798   sigpipe_ignore(data, &pipe_st);
799   Curl_close(&data);
800   sigpipe_restore(&pipe_st);
801 }
802
803 /*
804  * curl_easy_getinfo() is an external interface that allows an app to retrieve
805  * information from a performed transfer and similar.
806  */
807 #undef curl_easy_getinfo
808 CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...)
809 {
810   va_list arg;
811   void *paramp;
812   CURLcode result;
813
814   va_start(arg, info);
815   paramp = va_arg(arg, void *);
816
817   result = Curl_getinfo(data, info, paramp);
818
819   va_end(arg);
820   return result;
821 }
822
823 static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src)
824 {
825   CURLcode result = CURLE_OK;
826   enum dupstring i;
827   enum dupblob j;
828
829   /* Copy src->set into dst->set first, then deal with the strings
830      afterwards */
831   dst->set = src->set;
832   Curl_mime_initpart(&dst->set.mimepost, dst);
833
834   /* clear all string pointers first */
835   memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
836
837   /* duplicate all strings */
838   for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
839     result = Curl_setstropt(&dst->set.str[i], src->set.str[i]);
840     if(result)
841       return result;
842   }
843
844   /* clear all blob pointers first */
845   memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *));
846   /* duplicate all blobs */
847   for(j = (enum dupblob)0; j < BLOB_LAST; j++) {
848     result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]);
849     if(result)
850       return result;
851   }
852
853   /* duplicate memory areas pointed to */
854   i = STRING_COPYPOSTFIELDS;
855   if(src->set.postfieldsize && src->set.str[i]) {
856     /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
857     dst->set.str[i] = Curl_memdup(src->set.str[i],
858                                   curlx_sotouz(src->set.postfieldsize));
859     if(!dst->set.str[i])
860       return CURLE_OUT_OF_MEMORY;
861     /* point to the new copy */
862     dst->set.postfields = dst->set.str[i];
863   }
864
865   /* Duplicate mime data. */
866   result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost);
867
868   if(src->set.resolve)
869     dst->state.resolve = dst->set.resolve;
870
871   return result;
872 }
873
874 /*
875  * curl_easy_duphandle() is an external interface to allow duplication of a
876  * given input easy handle. The returned handle will be a new working handle
877  * with all options set exactly as the input source handle.
878  */
879 struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
880 {
881   struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy));
882   if(!outcurl)
883     goto fail;
884
885   /*
886    * We setup a few buffers we need. We should probably make them
887    * get setup on-demand in the code, as that would probably decrease
888    * the likeliness of us forgetting to init a buffer here in the future.
889    */
890   outcurl->set.buffer_size = data->set.buffer_size;
891
892   /* copy all userdefined values */
893   if(dupset(outcurl, data))
894     goto fail;
895
896   Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER);
897
898   /* the connection cache is setup on demand */
899   outcurl->state.conn_cache = NULL;
900   outcurl->state.lastconnect_id = -1;
901
902   outcurl->progress.flags    = data->progress.flags;
903   outcurl->progress.callback = data->progress.callback;
904
905 #ifndef CURL_DISABLE_COOKIES
906   if(data->cookies) {
907     /* If cookies are enabled in the parent handle, we enable them
908        in the clone as well! */
909     outcurl->cookies = Curl_cookie_init(data,
910                                         data->cookies->filename,
911                                         outcurl->cookies,
912                                         data->set.cookiesession);
913     if(!outcurl->cookies)
914       goto fail;
915   }
916
917   /* duplicate all values in 'change' */
918   if(data->state.cookielist) {
919     outcurl->state.cookielist =
920       Curl_slist_duplicate(data->state.cookielist);
921     if(!outcurl->state.cookielist)
922       goto fail;
923   }
924 #endif
925
926   if(data->state.url) {
927     outcurl->state.url = strdup(data->state.url);
928     if(!outcurl->state.url)
929       goto fail;
930     outcurl->state.url_alloc = TRUE;
931   }
932
933   if(data->state.referer) {
934     outcurl->state.referer = strdup(data->state.referer);
935     if(!outcurl->state.referer)
936       goto fail;
937     outcurl->state.referer_alloc = TRUE;
938   }
939
940   /* Reinitialize an SSL engine for the new handle
941    * note: the engine name has already been copied by dupset */
942   if(outcurl->set.str[STRING_SSL_ENGINE]) {
943     if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE]))
944       goto fail;
945   }
946
947 #ifndef CURL_DISABLE_ALTSVC
948   if(data->asi) {
949     outcurl->asi = Curl_altsvc_init();
950     if(!outcurl->asi)
951       goto fail;
952     if(outcurl->set.str[STRING_ALTSVC])
953       (void)Curl_altsvc_load(outcurl->asi, outcurl->set.str[STRING_ALTSVC]);
954   }
955 #endif
956 #ifndef CURL_DISABLE_HSTS
957   if(data->hsts) {
958     outcurl->hsts = Curl_hsts_init();
959     if(!outcurl->hsts)
960       goto fail;
961     if(outcurl->set.str[STRING_HSTS])
962       (void)Curl_hsts_loadfile(outcurl,
963                                outcurl->hsts, outcurl->set.str[STRING_HSTS]);
964     (void)Curl_hsts_loadcb(outcurl, outcurl->hsts);
965   }
966 #endif
967   /* Clone the resolver handle, if present, for the new handle */
968   if(Curl_resolver_duphandle(outcurl,
969                              &outcurl->state.async.resolver,
970                              data->state.async.resolver))
971     goto fail;
972
973 #ifdef USE_ARES
974   {
975     CURLcode rc;
976
977     rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]);
978     if(rc && rc != CURLE_NOT_BUILT_IN)
979       goto fail;
980
981     rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]);
982     if(rc && rc != CURLE_NOT_BUILT_IN)
983       goto fail;
984
985     rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]);
986     if(rc && rc != CURLE_NOT_BUILT_IN)
987       goto fail;
988
989     rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]);
990     if(rc && rc != CURLE_NOT_BUILT_IN)
991       goto fail;
992   }
993 #endif /* USE_ARES */
994
995   Curl_initinfo(outcurl);
996
997   outcurl->magic = CURLEASY_MAGIC_NUMBER;
998
999   /* we reach this point and thus we are OK */
1000
1001   return outcurl;
1002
1003   fail:
1004
1005   if(outcurl) {
1006 #ifndef CURL_DISABLE_COOKIES
1007     curl_slist_free_all(outcurl->state.cookielist);
1008     outcurl->state.cookielist = NULL;
1009 #endif
1010     Curl_safefree(outcurl->state.buffer);
1011     Curl_dyn_free(&outcurl->state.headerb);
1012     Curl_safefree(outcurl->state.url);
1013     Curl_safefree(outcurl->state.referer);
1014     Curl_altsvc_cleanup(&outcurl->asi);
1015     Curl_hsts_cleanup(&outcurl->hsts);
1016     Curl_freeset(outcurl);
1017     free(outcurl);
1018   }
1019
1020   return NULL;
1021 }
1022
1023 /*
1024  * curl_easy_reset() is an external interface that allows an app to re-
1025  * initialize a session handle to the default values.
1026  */
1027 void curl_easy_reset(struct Curl_easy *data)
1028 {
1029   Curl_free_request_state(data);
1030
1031   /* zero out UserDefined data: */
1032   Curl_freeset(data);
1033   memset(&data->set, 0, sizeof(struct UserDefined));
1034   (void)Curl_init_userdefined(data);
1035
1036   /* zero out Progress data: */
1037   memset(&data->progress, 0, sizeof(struct Progress));
1038
1039   /* zero out PureInfo data: */
1040   Curl_initinfo(data);
1041
1042   data->progress.flags |= PGRS_HIDE;
1043   data->state.current_speed = -1; /* init to negative == impossible */
1044   data->state.retrycount = 0;     /* reset the retry counter */
1045
1046   /* zero out authentication data: */
1047   memset(&data->state.authhost, 0, sizeof(struct auth));
1048   memset(&data->state.authproxy, 0, sizeof(struct auth));
1049
1050 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
1051   Curl_http_auth_cleanup_digest(data);
1052 #endif
1053 }
1054
1055 /*
1056  * curl_easy_pause() allows an application to pause or unpause a specific
1057  * transfer and direction. This function sets the full new state for the
1058  * current connection this easy handle operates on.
1059  *
1060  * NOTE: if you have the receiving paused and you call this function to remove
1061  * the pausing, you may get your write callback called at this point.
1062  *
1063  * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
1064  *
1065  * NOTE: This is one of few API functions that are allowed to be called from
1066  * within a callback.
1067  */
1068 CURLcode curl_easy_pause(struct Curl_easy *data, int action)
1069 {
1070   struct SingleRequest *k;
1071   CURLcode result = CURLE_OK;
1072   int oldstate;
1073   int newstate;
1074
1075   if(!GOOD_EASY_HANDLE(data) || !data->conn)
1076     /* crazy input, don't continue */
1077     return CURLE_BAD_FUNCTION_ARGUMENT;
1078
1079   k = &data->req;
1080   oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
1081
1082   /* first switch off both pause bits then set the new pause bits */
1083   newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) |
1084     ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
1085     ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
1086
1087   if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) {
1088     /* Not changing any pause state, return */
1089     DEBUGF(infof(data, "pause: no change, early return"));
1090     return CURLE_OK;
1091   }
1092
1093   /* Unpause parts in active mime tree. */
1094   if((k->keepon & ~newstate & KEEP_SEND_PAUSE) &&
1095      (data->mstate == MSTATE_PERFORMING ||
1096       data->mstate == MSTATE_RATELIMITING) &&
1097      data->state.fread_func == (curl_read_callback) Curl_mime_read) {
1098     Curl_mime_unpause(data->state.in);
1099   }
1100
1101   /* put it back in the keepon */
1102   k->keepon = newstate;
1103
1104   if(!(newstate & KEEP_RECV_PAUSE)) {
1105     Curl_http2_stream_pause(data, FALSE);
1106
1107     if(data->state.tempcount) {
1108       /* there are buffers for sending that can be delivered as the receive
1109          pausing is lifted! */
1110       unsigned int i;
1111       unsigned int count = data->state.tempcount;
1112       struct tempbuf writebuf[3]; /* there can only be three */
1113
1114       /* copy the structs to allow for immediate re-pausing */
1115       for(i = 0; i < data->state.tempcount; i++) {
1116         writebuf[i] = data->state.tempwrite[i];
1117         Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER);
1118       }
1119       data->state.tempcount = 0;
1120
1121       for(i = 0; i < count; i++) {
1122         /* even if one function returns error, this loops through and frees
1123            all buffers */
1124         if(!result)
1125           result = Curl_client_write(data, writebuf[i].type,
1126                                      Curl_dyn_ptr(&writebuf[i].b),
1127                                      Curl_dyn_len(&writebuf[i].b));
1128         Curl_dyn_free(&writebuf[i].b);
1129       }
1130
1131       if(result)
1132         return result;
1133     }
1134   }
1135
1136 #ifdef USE_HYPER
1137   if(!(newstate & KEEP_SEND_PAUSE)) {
1138     /* need to wake the send body waker */
1139     if(data->hyp.send_body_waker) {
1140       hyper_waker_wake(data->hyp.send_body_waker);
1141       data->hyp.send_body_waker = NULL;
1142     }
1143   }
1144 #endif
1145
1146   /* if there's no error and we're not pausing both directions, we want
1147      to have this handle checked soon */
1148   if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
1149      (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) {
1150     Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */
1151
1152     /* reset the too-slow time keeper */
1153     data->state.keeps_speed.tv_sec = 0;
1154
1155     if(!data->state.tempcount)
1156       /* if not pausing again, force a recv/send check of this connection as
1157          the data might've been read off the socket already */
1158       data->conn->cselect_bits = CURL_CSELECT_IN | CURL_CSELECT_OUT;
1159     if(data->multi) {
1160       if(Curl_update_timer(data->multi))
1161         return CURLE_ABORTED_BY_CALLBACK;
1162     }
1163   }
1164
1165   if(!data->state.done)
1166     /* This transfer may have been moved in or out of the bundle, update the
1167        corresponding socket callback, if used */
1168     result = Curl_updatesocket(data);
1169
1170   return result;
1171 }
1172
1173
1174 static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd,
1175                                 struct connectdata **connp)
1176 {
1177   if(!data)
1178     return CURLE_BAD_FUNCTION_ARGUMENT;
1179
1180   /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
1181   if(!data->set.connect_only) {
1182     failf(data, "CONNECT_ONLY is required");
1183     return CURLE_UNSUPPORTED_PROTOCOL;
1184   }
1185
1186   *sfd = Curl_getconnectinfo(data, connp);
1187
1188   if(*sfd == CURL_SOCKET_BAD) {
1189     failf(data, "Failed to get recent socket");
1190     return CURLE_UNSUPPORTED_PROTOCOL;
1191   }
1192
1193   return CURLE_OK;
1194 }
1195
1196 /*
1197  * Receives data from the connected socket. Use after successful
1198  * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
1199  * Returns CURLE_OK on success, error code on error.
1200  */
1201 CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen,
1202                         size_t *n)
1203 {
1204   curl_socket_t sfd;
1205   CURLcode result;
1206   ssize_t n1;
1207   struct connectdata *c;
1208
1209   if(Curl_is_in_callback(data))
1210     return CURLE_RECURSIVE_API_CALL;
1211
1212   result = easy_connection(data, &sfd, &c);
1213   if(result)
1214     return result;
1215
1216   if(!data->conn)
1217     /* on first invoke, the transfer has been detached from the connection and
1218        needs to be reattached */
1219     Curl_attach_connection(data, c);
1220
1221   *n = 0;
1222   result = Curl_read(data, sfd, buffer, buflen, &n1);
1223
1224   if(result)
1225     return result;
1226
1227   *n = (size_t)n1;
1228
1229   return CURLE_OK;
1230 }
1231
1232 /*
1233  * Sends data over the connected socket.
1234  *
1235  * This is the private internal version of curl_easy_send()
1236  */
1237 CURLcode Curl_senddata(struct Curl_easy *data, const void *buffer,
1238                        size_t buflen, ssize_t *n)
1239 {
1240   curl_socket_t sfd;
1241   CURLcode result;
1242   ssize_t n1;
1243   struct connectdata *c = NULL;
1244   SIGPIPE_VARIABLE(pipe_st);
1245
1246   result = easy_connection(data, &sfd, &c);
1247   if(result)
1248     return result;
1249
1250   if(!data->conn)
1251     /* on first invoke, the transfer has been detached from the connection and
1252        needs to be reattached */
1253     Curl_attach_connection(data, c);
1254
1255   *n = 0;
1256   sigpipe_ignore(data, &pipe_st);
1257   result = Curl_write(data, sfd, buffer, buflen, &n1);
1258   sigpipe_restore(&pipe_st);
1259
1260   if(n1 == -1)
1261     return CURLE_SEND_ERROR;
1262
1263   /* detect EAGAIN */
1264   if(!result && !n1)
1265     return CURLE_AGAIN;
1266
1267   *n = n1;
1268
1269   return result;
1270 }
1271
1272 /*
1273  * Sends data over the connected socket. Use after successful
1274  * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
1275  */
1276 CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer,
1277                         size_t buflen, size_t *n)
1278 {
1279   ssize_t written = 0;
1280   CURLcode result;
1281   if(Curl_is_in_callback(data))
1282     return CURLE_RECURSIVE_API_CALL;
1283
1284   result = Curl_senddata(data, buffer, buflen, &written);
1285   *n = (size_t)written;
1286   return result;
1287 }
1288
1289 /*
1290  * Wrapper to call functions in Curl_conncache_foreach()
1291  *
1292  * Returns always 0.
1293  */
1294 static int conn_upkeep(struct Curl_easy *data,
1295                        struct connectdata *conn,
1296                        void *param)
1297 {
1298   /* Param is unused. */
1299   (void)param;
1300
1301   if(conn->handler->connection_check) {
1302     /* briefly attach the connection to this transfer for the purpose of
1303        checking it */
1304     Curl_attach_connection(data, conn);
1305
1306     /* Do a protocol-specific keepalive check on the connection. */
1307     conn->handler->connection_check(data, conn, CONNCHECK_KEEPALIVE);
1308     /* detach the connection again */
1309     Curl_detach_connection(data);
1310   }
1311
1312   return 0; /* continue iteration */
1313 }
1314
1315 static CURLcode upkeep(struct conncache *conn_cache, void *data)
1316 {
1317   /* Loop over every connection and make connection alive. */
1318   Curl_conncache_foreach(data,
1319                          conn_cache,
1320                          data,
1321                          conn_upkeep);
1322   return CURLE_OK;
1323 }
1324
1325 /*
1326  * Performs connection upkeep for the given session handle.
1327  */
1328 CURLcode curl_easy_upkeep(struct Curl_easy *data)
1329 {
1330   /* Verify that we got an easy handle we can work with. */
1331   if(!GOOD_EASY_HANDLE(data))
1332     return CURLE_BAD_FUNCTION_ARGUMENT;
1333
1334   if(data->multi_easy) {
1335     /* Use the common function to keep connections alive. */
1336     return upkeep(&data->multi_easy->conn_cache, data);
1337   }
1338   else {
1339     /* No connections, so just return success */
1340     return CURLE_OK;
1341   }
1342 }