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