Imported Upstream version 7.48.0
[platform/upstream/curl.git] / lib / easy.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2016, 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 /*
26  * See comment in curl_memory.h for the explanation of this sanity check.
27  */
28
29 #ifdef CURLX_NO_MEMORY_CALLBACKS
30 #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
31 #endif
32
33 #ifdef HAVE_NETINET_IN_H
34 #include <netinet/in.h>
35 #endif
36 #ifdef HAVE_NETDB_H
37 #include <netdb.h>
38 #endif
39 #ifdef HAVE_ARPA_INET_H
40 #include <arpa/inet.h>
41 #endif
42 #ifdef HAVE_NET_IF_H
43 #include <net/if.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52
53 #include "strequal.h"
54 #include "urldata.h"
55 #include <curl/curl.h>
56 #include "transfer.h"
57 #include "vtls/vtls.h"
58 #include "url.h"
59 #include "getinfo.h"
60 #include "hostip.h"
61 #include "share.h"
62 #include "strdup.h"
63 #include "progress.h"
64 #include "easyif.h"
65 #include "select.h"
66 #include "sendf.h" /* for failf function prototype */
67 #include "connect.h" /* for Curl_getconnectinfo */
68 #include "slist.h"
69 #include "amigaos.h"
70 #include "non-ascii.h"
71 #include "warnless.h"
72 #include "conncache.h"
73 #include "multiif.h"
74 #include "sigpipe.h"
75 #include "ssh.h"
76 #include "curl_printf.h"
77
78 /* The last #include files should be: */
79 #include "curl_memory.h"
80 #include "memdebug.h"
81
82 void Curl_version_init(void);
83
84 /* win32_cleanup() is for win32 socket cleanup functionality, the opposite
85    of win32_init() */
86 static void win32_cleanup(void)
87 {
88 #ifdef USE_WINSOCK
89   WSACleanup();
90 #endif
91 #ifdef USE_WINDOWS_SSPI
92   Curl_sspi_global_cleanup();
93 #endif
94 }
95
96 /* win32_init() performs win32 socket initialization to properly setup the
97    stack to allow networking */
98 static CURLcode win32_init(void)
99 {
100 #ifdef USE_WINSOCK
101   WORD wVersionRequested;
102   WSADATA wsaData;
103   int res;
104
105 #if defined(ENABLE_IPV6) && (USE_WINSOCK < 2)
106   Error IPV6_requires_winsock2
107 #endif
108
109   wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK);
110
111   res = WSAStartup(wVersionRequested, &wsaData);
112
113   if(res != 0)
114     /* Tell the user that we couldn't find a useable */
115     /* winsock.dll.     */
116     return CURLE_FAILED_INIT;
117
118   /* Confirm that the Windows Sockets DLL supports what we need.*/
119   /* Note that if the DLL supports versions greater */
120   /* than wVersionRequested, it will still return */
121   /* wVersionRequested in wVersion. wHighVersion contains the */
122   /* highest supported version. */
123
124   if(LOBYTE( wsaData.wVersion ) != LOBYTE(wVersionRequested) ||
125      HIBYTE( wsaData.wVersion ) != HIBYTE(wVersionRequested) ) {
126     /* Tell the user that we couldn't find a useable */
127
128     /* winsock.dll. */
129     WSACleanup();
130     return CURLE_FAILED_INIT;
131   }
132   /* The Windows Sockets DLL is acceptable. Proceed. */
133 #elif defined(USE_LWIPSOCK)
134   lwip_init();
135 #endif
136
137 #ifdef USE_WINDOWS_SSPI
138   {
139     CURLcode result = Curl_sspi_global_init();
140     if(result)
141       return result;
142   }
143 #endif
144
145   return CURLE_OK;
146 }
147
148 #ifdef USE_LIBIDN
149 /*
150  * Initialise use of IDNA library.
151  * It falls back to ASCII if $CHARSET isn't defined. This doesn't work for
152  * idna_to_ascii_lz().
153  */
154 static void idna_init (void)
155 {
156 #ifdef WIN32
157   char buf[60];
158   UINT cp = GetACP();
159
160   if(!getenv("CHARSET") && cp > 0) {
161     snprintf(buf, sizeof(buf), "CHARSET=cp%u", cp);
162     putenv(buf);
163   }
164 #else
165   /* to do? */
166 #endif
167 }
168 #endif  /* USE_LIBIDN */
169
170 /* true globals -- for curl_global_init() and curl_global_cleanup() */
171 static unsigned int  initialized;
172 static long          init_flags;
173
174 /*
175  * strdup (and other memory functions) is redefined in complicated
176  * ways, but at this point it must be defined as the system-supplied strdup
177  * so the callback pointer is initialized correctly.
178  */
179 #if defined(_WIN32_WCE)
180 #define system_strdup _strdup
181 #elif !defined(HAVE_STRDUP)
182 #define system_strdup curlx_strdup
183 #else
184 #define system_strdup strdup
185 #endif
186
187 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
188 #  pragma warning(disable:4232) /* MSVC extension, dllimport identity */
189 #endif
190
191 #ifndef __SYMBIAN32__
192 /*
193  * If a memory-using function (like curl_getenv) is used before
194  * curl_global_init() is called, we need to have these pointers set already.
195  */
196 curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
197 curl_free_callback Curl_cfree = (curl_free_callback)free;
198 curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
199 curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
200 curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
201 #if defined(WIN32) && defined(UNICODE)
202 curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
203 #endif
204 #else
205 /*
206  * Symbian OS doesn't support initialization to code in writeable static data.
207  * Initialization will occur in the curl_global_init() call.
208  */
209 curl_malloc_callback Curl_cmalloc;
210 curl_free_callback Curl_cfree;
211 curl_realloc_callback Curl_crealloc;
212 curl_strdup_callback Curl_cstrdup;
213 curl_calloc_callback Curl_ccalloc;
214 #endif
215
216 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
217 #  pragma warning(default:4232) /* MSVC extension, dllimport identity */
218 #endif
219
220 /**
221  * curl_global_init() globally initializes cURL given a bitwise set of the
222  * different features of what to initialize.
223  */
224 static CURLcode global_init(long flags, bool memoryfuncs)
225 {
226   if(initialized++)
227     return CURLE_OK;
228
229   if(memoryfuncs) {
230     /* Setup the default memory functions here (again) */
231     Curl_cmalloc = (curl_malloc_callback)malloc;
232     Curl_cfree = (curl_free_callback)free;
233     Curl_crealloc = (curl_realloc_callback)realloc;
234     Curl_cstrdup = (curl_strdup_callback)system_strdup;
235     Curl_ccalloc = (curl_calloc_callback)calloc;
236 #if defined(WIN32) && defined(UNICODE)
237     Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
238 #endif
239   }
240
241   if(flags & CURL_GLOBAL_SSL)
242     if(!Curl_ssl_init()) {
243       DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
244       return CURLE_FAILED_INIT;
245     }
246
247   if(flags & CURL_GLOBAL_WIN32)
248     if(win32_init()) {
249       DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
250       return CURLE_FAILED_INIT;
251     }
252
253 #ifdef __AMIGA__
254   if(!Curl_amiga_init()) {
255     DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
256     return CURLE_FAILED_INIT;
257   }
258 #endif
259
260 #ifdef NETWARE
261   if(netware_init()) {
262     DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
263   }
264 #endif
265
266 #ifdef USE_LIBIDN
267   idna_init();
268 #endif
269
270   if(Curl_resolver_global_init()) {
271     DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
272     return CURLE_FAILED_INIT;
273   }
274
275 #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_INIT)
276   if(libssh2_init(0)) {
277     DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n"));
278     return CURLE_FAILED_INIT;
279   }
280 #endif
281
282   if(flags & CURL_GLOBAL_ACK_EINTR)
283     Curl_ack_eintr = 1;
284
285   init_flags = flags;
286
287   Curl_version_init();
288
289   return CURLE_OK;
290 }
291
292
293 /**
294  * curl_global_init() globally initializes cURL given a bitwise set of the
295  * different features of what to initialize.
296  */
297 CURLcode curl_global_init(long flags)
298 {
299   return global_init(flags, TRUE);
300 }
301
302 /*
303  * curl_global_init_mem() globally initializes cURL and also registers the
304  * user provided callback routines.
305  */
306 CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
307                               curl_free_callback f, curl_realloc_callback r,
308                               curl_strdup_callback s, curl_calloc_callback c)
309 {
310   /* Invalid input, return immediately */
311   if(!m || !f || !r || !s || !c)
312     return CURLE_FAILED_INIT;
313
314   if(initialized) {
315     /* Already initialized, don't do it again, but bump the variable anyway to
316        work like curl_global_init() and require the same amount of cleanup
317        calls. */
318     initialized++;
319     return CURLE_OK;
320   }
321
322   /* set memory functions before global_init() in case it wants memory
323      functions */
324   Curl_cmalloc = m;
325   Curl_cfree = f;
326   Curl_cstrdup = s;
327   Curl_crealloc = r;
328   Curl_ccalloc = c;
329
330   /* Call the actual init function, but without setting */
331   return global_init(flags, FALSE);
332 }
333
334 /**
335  * curl_global_cleanup() globally cleanups cURL, uses the value of
336  * "init_flags" to determine what needs to be cleaned up and what doesn't.
337  */
338 void curl_global_cleanup(void)
339 {
340   if(!initialized)
341     return;
342
343   if(--initialized)
344     return;
345
346   Curl_global_host_cache_dtor();
347
348   if(init_flags & CURL_GLOBAL_SSL)
349     Curl_ssl_cleanup();
350
351   Curl_resolver_global_cleanup();
352
353   if(init_flags & CURL_GLOBAL_WIN32)
354     win32_cleanup();
355
356   Curl_amiga_cleanup();
357
358 #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_EXIT)
359   (void)libssh2_exit();
360 #endif
361
362   init_flags  = 0;
363 }
364
365 /*
366  * curl_easy_init() is the external interface to alloc, setup and init an
367  * easy handle that is returned. If anything goes wrong, NULL is returned.
368  */
369 CURL *curl_easy_init(void)
370 {
371   CURLcode result;
372   struct SessionHandle *data;
373
374   /* Make sure we inited the global SSL stuff */
375   if(!initialized) {
376     result = curl_global_init(CURL_GLOBAL_DEFAULT);
377     if(result) {
378       /* something in the global init failed, return nothing */
379       DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
380       return NULL;
381     }
382   }
383
384   /* We use curl_open() with undefined URL so far */
385   result = Curl_open(&data);
386   if(result) {
387     DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
388     return NULL;
389   }
390
391   return data;
392 }
393
394 /*
395  * curl_easy_setopt() is the external interface for setting options on an
396  * easy handle.
397  */
398
399 #undef curl_easy_setopt
400 CURLcode curl_easy_setopt(CURL *curl, CURLoption tag, ...)
401 {
402   va_list arg;
403   struct SessionHandle *data = curl;
404   CURLcode result;
405
406   if(!curl)
407     return CURLE_BAD_FUNCTION_ARGUMENT;
408
409   va_start(arg, tag);
410
411   result = Curl_setopt(data, tag, arg);
412
413   va_end(arg);
414   return result;
415 }
416
417 #ifdef CURLDEBUG
418
419 struct socketmonitor {
420   struct socketmonitor *next; /* the next node in the list or NULL */
421   struct pollfd socket; /* socket info of what to monitor */
422 };
423
424 struct events {
425   long ms;              /* timeout, run the timeout function when reached */
426   bool msbump;          /* set TRUE when timeout is set by callback */
427   int num_sockets;      /* number of nodes in the monitor list */
428   struct socketmonitor *list; /* list of sockets to monitor */
429   int running_handles;  /* store the returned number */
430 };
431
432 /* events_timer
433  *
434  * Callback that gets called with a new value when the timeout should be
435  * updated.
436  */
437
438 static int events_timer(CURLM *multi,    /* multi handle */
439                         long timeout_ms, /* see above */
440                         void *userp)    /* private callback pointer */
441 {
442   struct events *ev = userp;
443   (void)multi;
444   if(timeout_ms == -1)
445     /* timeout removed */
446     timeout_ms = 0;
447   else if(timeout_ms == 0)
448     /* timeout is already reached! */
449     timeout_ms = 1; /* trigger asap */
450
451   ev->ms = timeout_ms;
452   ev->msbump = TRUE;
453   return 0;
454 }
455
456
457 /* poll2cselect
458  *
459  * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
460  */
461 static int poll2cselect(int pollmask)
462 {
463   int omask=0;
464   if(pollmask & POLLIN)
465     omask |= CURL_CSELECT_IN;
466   if(pollmask & POLLOUT)
467     omask |= CURL_CSELECT_OUT;
468   if(pollmask & POLLERR)
469     omask |= CURL_CSELECT_ERR;
470   return omask;
471 }
472
473
474 /* socketcb2poll
475  *
476  * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
477  */
478 static short socketcb2poll(int pollmask)
479 {
480   short omask=0;
481   if(pollmask & CURL_POLL_IN)
482     omask |= POLLIN;
483   if(pollmask & CURL_POLL_OUT)
484     omask |= POLLOUT;
485   return omask;
486 }
487
488 /* events_socket
489  *
490  * Callback that gets called with information about socket activity to
491  * monitor.
492  */
493 static int events_socket(CURL *easy,      /* easy handle */
494                          curl_socket_t s, /* socket */
495                          int what,        /* see above */
496                          void *userp,     /* private callback
497                                              pointer */
498                          void *socketp)   /* private socket
499                                              pointer */
500 {
501   struct events *ev = userp;
502   struct socketmonitor *m;
503   struct socketmonitor *prev=NULL;
504
505 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
506   (void) easy;
507 #endif
508   (void)socketp;
509
510   m = ev->list;
511   while(m) {
512     if(m->socket.fd == s) {
513
514       if(what == CURL_POLL_REMOVE) {
515         struct socketmonitor *nxt = m->next;
516         /* remove this node from the list of monitored sockets */
517         if(prev)
518           prev->next = nxt;
519         else
520           ev->list = nxt;
521         free(m);
522         m = nxt;
523         infof(easy, "socket cb: socket %d REMOVED\n", s);
524       }
525       else {
526         /* The socket 's' is already being monitored, update the activity
527            mask. Convert from libcurl bitmask to the poll one. */
528         m->socket.events = socketcb2poll(what);
529         infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s,
530               what&CURL_POLL_IN?"IN":"",
531               what&CURL_POLL_OUT?"OUT":"");
532       }
533       break;
534     }
535     prev = m;
536     m = m->next; /* move to next node */
537   }
538   if(!m) {
539     if(what == CURL_POLL_REMOVE) {
540       /* this happens a bit too often, libcurl fix perhaps? */
541       /* fprintf(stderr,
542          "%s: socket %d asked to be REMOVED but not present!\n",
543                  __func__, s); */
544     }
545     else {
546       m = malloc(sizeof(struct socketmonitor));
547       if(m) {
548         m->next = ev->list;
549         m->socket.fd = s;
550         m->socket.events = socketcb2poll(what);
551         m->socket.revents = 0;
552         ev->list = m;
553         infof(easy, "socket cb: socket %d ADDED as %s%s\n", s,
554               what&CURL_POLL_IN?"IN":"",
555               what&CURL_POLL_OUT?"OUT":"");
556       }
557       else
558         return CURLE_OUT_OF_MEMORY;
559     }
560   }
561
562   return 0;
563 }
564
565
566 /*
567  * events_setup()
568  *
569  * Do the multi handle setups that only event-based transfers need.
570  */
571 static void events_setup(CURLM *multi, struct events *ev)
572 {
573   /* timer callback */
574   curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
575   curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
576
577   /* socket callback */
578   curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
579   curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
580 }
581
582
583 /* wait_or_timeout()
584  *
585  * waits for activity on any of the given sockets, or the timeout to trigger.
586  */
587
588 static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
589 {
590   bool done = FALSE;
591   CURLMcode mcode;
592   CURLcode result = CURLE_OK;
593
594   while(!done) {
595     CURLMsg *msg;
596     struct socketmonitor *m;
597     struct pollfd *f;
598     struct pollfd fds[4];
599     int numfds=0;
600     int pollrc;
601     int i;
602     struct timeval before;
603     struct timeval after;
604
605     /* populate the fds[] array */
606     for(m = ev->list, f=&fds[0]; m; m = m->next) {
607       f->fd = m->socket.fd;
608       f->events = m->socket.events;
609       f->revents = 0;
610       /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
611       f++;
612       numfds++;
613     }
614
615     /* get the time stamp to use to figure out how long poll takes */
616     before = curlx_tvnow();
617
618     /* wait for activity or timeout */
619     pollrc = Curl_poll(fds, numfds, (int)ev->ms);
620
621     after = curlx_tvnow();
622
623     ev->msbump = FALSE; /* reset here */
624
625     if(0 == pollrc) {
626       /* timeout! */
627       ev->ms = 0;
628       /* fprintf(stderr, "call curl_multi_socket_action( TIMEOUT )\n"); */
629       mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
630                                        &ev->running_handles);
631     }
632     else if(pollrc > 0) {
633       /* loop over the monitored sockets to see which ones had activity */
634       for(i = 0; i< numfds; i++) {
635         if(fds[i].revents) {
636           /* socket activity, tell libcurl */
637           int act = poll2cselect(fds[i].revents); /* convert */
638           infof(multi->easyp, "call curl_multi_socket_action( socket %d )\n",
639                 fds[i].fd);
640           mcode = curl_multi_socket_action(multi, fds[i].fd, act,
641                                            &ev->running_handles);
642         }
643       }
644
645       if(!ev->msbump)
646         /* If nothing updated the timeout, we decrease it by the spent time.
647          * If it was updated, it has the new timeout time stored already.
648          */
649         ev->ms += curlx_tvdiff(after, before);
650
651     }
652     else
653       return CURLE_RECV_ERROR;
654
655     if(mcode)
656       return CURLE_URL_MALFORMAT; /* TODO: return a proper error! */
657
658     /* we don't really care about the "msgs_in_queue" value returned in the
659        second argument */
660     msg = curl_multi_info_read(multi, &pollrc);
661     if(msg) {
662       result = msg->data.result;
663       done = TRUE;
664     }
665   }
666
667   return result;
668 }
669
670
671 /* easy_events()
672  *
673  * Runs a transfer in a blocking manner using the events-based API
674  */
675 static CURLcode easy_events(CURLM *multi)
676 {
677   struct events evs= {2, FALSE, 0, NULL, 0};
678
679   /* if running event-based, do some further multi inits */
680   events_setup(multi, &evs);
681
682   return wait_or_timeout(multi, &evs);
683 }
684 #else /* CURLDEBUG */
685 /* when not built with debug, this function doesn't exist */
686 #define easy_events(x) CURLE_NOT_BUILT_IN
687 #endif
688
689 static CURLcode easy_transfer(CURLM *multi)
690 {
691   bool done = FALSE;
692   CURLMcode mcode = CURLM_OK;
693   CURLcode result = CURLE_OK;
694   struct timeval before;
695   int without_fds = 0;  /* count number of consecutive returns from
696                            curl_multi_wait() without any filedescriptors */
697
698   while(!done && !mcode) {
699     int still_running = 0;
700     int rc;
701
702     before = curlx_tvnow();
703     mcode = curl_multi_wait(multi, NULL, 0, 1000, &rc);
704
705     if(!mcode) {
706       if(!rc) {
707         struct timeval after = curlx_tvnow();
708
709         /* If it returns without any filedescriptor instantly, we need to
710            avoid busy-looping during periods where it has nothing particular
711            to wait for */
712         if(curlx_tvdiff(after, before) <= 10) {
713           without_fds++;
714           if(without_fds > 2) {
715             int sleep_ms = without_fds < 10 ? (1 << (without_fds - 1)) : 1000;
716             Curl_wait_ms(sleep_ms);
717           }
718         }
719         else
720           /* it wasn't "instant", restart counter */
721           without_fds = 0;
722       }
723       else
724         /* got file descriptor, restart counter */
725         without_fds = 0;
726
727       mcode = curl_multi_perform(multi, &still_running);
728     }
729
730     /* only read 'still_running' if curl_multi_perform() return OK */
731     if(!mcode && !still_running) {
732       CURLMsg *msg = curl_multi_info_read(multi, &rc);
733       if(msg) {
734         result = msg->data.result;
735         done = TRUE;
736       }
737     }
738   }
739
740   /* Make sure to return some kind of error if there was a multi problem */
741   if(mcode) {
742     result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY :
743               /* The other multi errors should never happen, so return
744                  something suitably generic */
745               CURLE_BAD_FUNCTION_ARGUMENT;
746   }
747
748   return result;
749 }
750
751
752 /*
753  * easy_perform() is the external interface that performs a blocking
754  * transfer as previously setup.
755  *
756  * CONCEPT: This function creates a multi handle, adds the easy handle to it,
757  * runs curl_multi_perform() until the transfer is done, then detaches the
758  * easy handle, destroys the multi handle and returns the easy handle's return
759  * code.
760  *
761  * REALITY: it can't just create and destroy the multi handle that easily. It
762  * needs to keep it around since if this easy handle is used again by this
763  * function, the same multi handle must be re-used so that the same pools and
764  * caches can be used.
765  *
766  * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
767  * instead of curl_multi_perform() and use curl_multi_socket_action().
768  */
769 static CURLcode easy_perform(struct SessionHandle *data, bool events)
770 {
771   CURLM *multi;
772   CURLMcode mcode;
773   CURLcode result = CURLE_OK;
774   SIGPIPE_VARIABLE(pipe_st);
775
776   if(!data)
777     return CURLE_BAD_FUNCTION_ARGUMENT;
778
779   if(data->multi) {
780     failf(data, "easy handle already used in multi handle");
781     return CURLE_FAILED_INIT;
782   }
783
784   if(data->multi_easy)
785     multi = data->multi_easy;
786   else {
787     /* this multi handle will only ever have a single easy handled attached
788        to it, so make it use minimal hashes */
789     multi = Curl_multi_handle(1, 3);
790     if(!multi)
791       return CURLE_OUT_OF_MEMORY;
792     data->multi_easy = multi;
793   }
794
795   /* Copy the MAXCONNECTS option to the multi handle */
796   curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
797
798   mcode = curl_multi_add_handle(multi, data);
799   if(mcode) {
800     curl_multi_cleanup(multi);
801     if(mcode == CURLM_OUT_OF_MEMORY)
802       return CURLE_OUT_OF_MEMORY;
803     else
804       return CURLE_FAILED_INIT;
805   }
806
807   sigpipe_ignore(data, &pipe_st);
808
809   /* assign this after curl_multi_add_handle() since that function checks for
810      it and rejects this handle otherwise */
811   data->multi = multi;
812
813   /* run the transfer */
814   result = events ? easy_events(multi) : easy_transfer(multi);
815
816   /* ignoring the return code isn't nice, but atm we can't really handle
817      a failure here, room for future improvement! */
818   (void)curl_multi_remove_handle(multi, data);
819
820   sigpipe_restore(&pipe_st);
821
822   /* The multi handle is kept alive, owned by the easy handle */
823   return result;
824 }
825
826
827 /*
828  * curl_easy_perform() is the external interface that performs a blocking
829  * transfer as previously setup.
830  */
831 CURLcode curl_easy_perform(CURL *easy)
832 {
833   return easy_perform(easy, FALSE);
834 }
835
836 #ifdef CURLDEBUG
837 /*
838  * curl_easy_perform_ev() is the external interface that performs a blocking
839  * transfer using the event-based API internally.
840  */
841 CURLcode curl_easy_perform_ev(CURL *easy)
842 {
843   return easy_perform(easy, TRUE);
844 }
845
846 #endif
847
848 /*
849  * curl_easy_cleanup() is the external interface to cleaning/freeing the given
850  * easy handle.
851  */
852 void curl_easy_cleanup(CURL *curl)
853 {
854   struct SessionHandle *data = (struct SessionHandle *)curl;
855   SIGPIPE_VARIABLE(pipe_st);
856
857   if(!data)
858     return;
859
860   sigpipe_ignore(data, &pipe_st);
861   Curl_close(data);
862   sigpipe_restore(&pipe_st);
863 }
864
865 /*
866  * curl_easy_getinfo() is an external interface that allows an app to retrieve
867  * information from a performed transfer and similar.
868  */
869 #undef curl_easy_getinfo
870 CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...)
871 {
872   va_list arg;
873   void *paramp;
874   CURLcode result;
875   struct SessionHandle *data = (struct SessionHandle *)curl;
876
877   va_start(arg, info);
878   paramp = va_arg(arg, void *);
879
880   result = Curl_getinfo(data, info, paramp);
881
882   va_end(arg);
883   return result;
884 }
885
886 /*
887  * curl_easy_duphandle() is an external interface to allow duplication of a
888  * given input easy handle. The returned handle will be a new working handle
889  * with all options set exactly as the input source handle.
890  */
891 CURL *curl_easy_duphandle(CURL *incurl)
892 {
893   struct SessionHandle *data=(struct SessionHandle *)incurl;
894
895   struct SessionHandle *outcurl = calloc(1, sizeof(struct SessionHandle));
896   if(NULL == outcurl)
897     goto fail;
898
899   /*
900    * We setup a few buffers we need. We should probably make them
901    * get setup on-demand in the code, as that would probably decrease
902    * the likeliness of us forgetting to init a buffer here in the future.
903    */
904   outcurl->state.headerbuff = malloc(HEADERSIZE);
905   if(!outcurl->state.headerbuff)
906     goto fail;
907   outcurl->state.headersize = HEADERSIZE;
908
909   /* copy all userdefined values */
910   if(Curl_dupset(outcurl, data))
911     goto fail;
912
913   /* the connection cache is setup on demand */
914   outcurl->state.conn_cache = NULL;
915
916   outcurl->state.lastconnect = NULL;
917
918   outcurl->progress.flags    = data->progress.flags;
919   outcurl->progress.callback = data->progress.callback;
920
921   if(data->cookies) {
922     /* If cookies are enabled in the parent handle, we enable them
923        in the clone as well! */
924     outcurl->cookies = Curl_cookie_init(data,
925                                         data->cookies->filename,
926                                         outcurl->cookies,
927                                         data->set.cookiesession);
928     if(!outcurl->cookies)
929       goto fail;
930   }
931
932   /* duplicate all values in 'change' */
933   if(data->change.cookielist) {
934     outcurl->change.cookielist =
935       Curl_slist_duplicate(data->change.cookielist);
936     if(!outcurl->change.cookielist)
937       goto fail;
938   }
939
940   if(data->change.url) {
941     outcurl->change.url = strdup(data->change.url);
942     if(!outcurl->change.url)
943       goto fail;
944     outcurl->change.url_alloc = TRUE;
945   }
946
947   if(data->change.referer) {
948     outcurl->change.referer = strdup(data->change.referer);
949     if(!outcurl->change.referer)
950       goto fail;
951     outcurl->change.referer_alloc = TRUE;
952   }
953
954   /* Clone the resolver handle, if present, for the new handle */
955   if(Curl_resolver_duphandle(&outcurl->state.resolver,
956                              data->state.resolver))
957     goto fail;
958
959   Curl_convert_setup(outcurl);
960
961   outcurl->magic = CURLEASY_MAGIC_NUMBER;
962
963   /* we reach this point and thus we are OK */
964
965   return outcurl;
966
967   fail:
968
969   if(outcurl) {
970     curl_slist_free_all(outcurl->change.cookielist);
971     outcurl->change.cookielist = NULL;
972     Curl_safefree(outcurl->state.headerbuff);
973     Curl_safefree(outcurl->change.url);
974     Curl_safefree(outcurl->change.referer);
975     Curl_freeset(outcurl);
976     free(outcurl);
977   }
978
979   return NULL;
980 }
981
982 /*
983  * curl_easy_reset() is an external interface that allows an app to re-
984  * initialize a session handle to the default values.
985  */
986 void curl_easy_reset(CURL *curl)
987 {
988   struct SessionHandle *data = (struct SessionHandle *)curl;
989
990   Curl_safefree(data->state.pathbuffer);
991
992   data->state.path = NULL;
993
994   Curl_free_request_state(data);
995
996   /* zero out UserDefined data: */
997   Curl_freeset(data);
998   memset(&data->set, 0, sizeof(struct UserDefined));
999   (void)Curl_init_userdefined(&data->set);
1000
1001   /* zero out Progress data: */
1002   memset(&data->progress, 0, sizeof(struct Progress));
1003
1004   data->progress.flags |= PGRS_HIDE;
1005   data->state.current_speed = -1; /* init to negative == impossible */
1006 }
1007
1008 /*
1009  * curl_easy_pause() allows an application to pause or unpause a specific
1010  * transfer and direction. This function sets the full new state for the
1011  * current connection this easy handle operates on.
1012  *
1013  * NOTE: if you have the receiving paused and you call this function to remove
1014  * the pausing, you may get your write callback called at this point.
1015  *
1016  * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
1017  */
1018 CURLcode curl_easy_pause(CURL *curl, int action)
1019 {
1020   struct SessionHandle *data = (struct SessionHandle *)curl;
1021   struct SingleRequest *k = &data->req;
1022   CURLcode result = CURLE_OK;
1023
1024   /* first switch off both pause bits */
1025   int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
1026
1027   /* set the new desired pause bits */
1028   newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
1029     ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
1030
1031   /* put it back in the keepon */
1032   k->keepon = newstate;
1033
1034   if(!(newstate & KEEP_RECV_PAUSE) && data->state.tempwrite) {
1035     /* we have a buffer for sending that we now seem to be able to deliver
1036        since the receive pausing is lifted! */
1037
1038     /* get the pointer in local copy since the function may return PAUSE
1039        again and then we'll get a new copy allocted and stored in
1040        the tempwrite variables */
1041     char *tempwrite = data->state.tempwrite;
1042
1043     data->state.tempwrite = NULL;
1044     result = Curl_client_chop_write(data->easy_conn, data->state.tempwritetype,
1045                                     tempwrite, data->state.tempwritesize);
1046     free(tempwrite);
1047   }
1048
1049   /* if there's no error and we're not pausing both directions, we want
1050      to have this handle checked soon */
1051   if(!result &&
1052      ((newstate&(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
1053       (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) )
1054     Curl_expire(data, 1); /* get this handle going again */
1055
1056   return result;
1057 }
1058
1059
1060 static CURLcode easy_connection(struct SessionHandle *data,
1061                                 curl_socket_t *sfd,
1062                                 struct connectdata **connp)
1063 {
1064   if(data == NULL)
1065     return CURLE_BAD_FUNCTION_ARGUMENT;
1066
1067   /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
1068   if(!data->set.connect_only) {
1069     failf(data, "CONNECT_ONLY is required!");
1070     return CURLE_UNSUPPORTED_PROTOCOL;
1071   }
1072
1073   *sfd = Curl_getconnectinfo(data, connp);
1074
1075   if(*sfd == CURL_SOCKET_BAD) {
1076     failf(data, "Failed to get recent socket");
1077     return CURLE_UNSUPPORTED_PROTOCOL;
1078   }
1079
1080   return CURLE_OK;
1081 }
1082
1083 /*
1084  * Receives data from the connected socket. Use after successful
1085  * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
1086  * Returns CURLE_OK on success, error code on error.
1087  */
1088 CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n)
1089 {
1090   curl_socket_t sfd;
1091   CURLcode result;
1092   ssize_t n1;
1093   struct connectdata *c;
1094   struct SessionHandle *data = (struct SessionHandle *)curl;
1095
1096   result = easy_connection(data, &sfd, &c);
1097   if(result)
1098     return result;
1099
1100   *n = 0;
1101   result = Curl_read(c, sfd, buffer, buflen, &n1);
1102
1103   if(result)
1104     return result;
1105
1106   *n = (size_t)n1;
1107
1108   return CURLE_OK;
1109 }
1110
1111 /*
1112  * Sends data over the connected socket. Use after successful
1113  * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
1114  */
1115 CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen,
1116                         size_t *n)
1117 {
1118   curl_socket_t sfd;
1119   CURLcode result;
1120   ssize_t n1;
1121   struct connectdata *c = NULL;
1122   struct SessionHandle *data = (struct SessionHandle *)curl;
1123
1124   result = easy_connection(data, &sfd, &c);
1125   if(result)
1126     return result;
1127
1128   *n = 0;
1129   result = Curl_write(c, sfd, buffer, buflen, &n1);
1130
1131   if(n1 == -1)
1132     return CURLE_SEND_ERROR;
1133
1134   /* detect EAGAIN */
1135   if(!result && !n1)
1136     return CURLE_AGAIN;
1137
1138   *n = (size_t)n1;
1139
1140   return result;
1141 }