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