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