1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
31 #ifdef HAVE_ARPA_INET_H
32 #include <arpa/inet.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 #include <sys/ioctl.h>
41 #ifdef HAVE_SYS_PARAM_H
42 #include <sys/param.h>
47 #include <curl/curl.h>
55 #include "curl_memory.h"
59 #include "sendf.h" /* for failf function prototype */
60 #include "curl_ntlm.h"
61 #include "connect.h" /* for Curl_getconnectinfo */
64 #include "curl_rand.h"
65 #include "non-ascii.h"
67 #include "conncache.h"
69 #define _MPRINTF_REPLACE /* use our functions only */
70 #include <curl/mprintf.h>
72 /* The last #include file should be: */
75 /* win32_cleanup() is for win32 socket cleanup functionality, the opposite
77 static void win32_cleanup(void)
82 #ifdef USE_WINDOWS_SSPI
83 Curl_sspi_global_cleanup();
87 /* win32_init() performs win32 socket initialization to properly setup the
88 stack to allow networking */
89 static CURLcode win32_init(void)
92 WORD wVersionRequested;
96 #if defined(ENABLE_IPV6) && (USE_WINSOCK < 2)
97 Error IPV6_requires_winsock2
100 wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK);
102 res = WSAStartup(wVersionRequested, &wsaData);
105 /* Tell the user that we couldn't find a useable */
107 return CURLE_FAILED_INIT;
109 /* Confirm that the Windows Sockets DLL supports what we need.*/
110 /* Note that if the DLL supports versions greater */
111 /* than wVersionRequested, it will still return */
112 /* wVersionRequested in wVersion. wHighVersion contains the */
113 /* highest supported version. */
115 if(LOBYTE( wsaData.wVersion ) != LOBYTE(wVersionRequested) ||
116 HIBYTE( wsaData.wVersion ) != HIBYTE(wVersionRequested) ) {
117 /* Tell the user that we couldn't find a useable */
121 return CURLE_FAILED_INIT;
123 /* The Windows Sockets DLL is acceptable. Proceed. */
124 #elif defined(USE_LWIPSOCK)
128 #ifdef USE_WINDOWS_SSPI
130 CURLcode err = Curl_sspi_global_init();
141 * Initialise use of IDNA library.
142 * It falls back to ASCII if $CHARSET isn't defined. This doesn't work for
143 * idna_to_ascii_lz().
145 static void idna_init (void)
151 if(!getenv("CHARSET") && cp > 0) {
152 snprintf(buf, sizeof(buf), "CHARSET=cp%u", cp);
159 #endif /* USE_LIBIDN */
161 /* true globals -- for curl_global_init() and curl_global_cleanup() */
162 static unsigned int initialized;
163 static long init_flags;
166 * strdup (and other memory functions) is redefined in complicated
167 * ways, but at this point it must be defined as the system-supplied strdup
168 * so the callback pointer is initialized correctly.
170 #if defined(_WIN32_WCE)
171 #define system_strdup _strdup
172 #elif !defined(HAVE_STRDUP)
173 #define system_strdup curlx_strdup
175 #define system_strdup strdup
178 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
179 # pragma warning(disable:4232) /* MSVC extension, dllimport identity */
182 #ifndef __SYMBIAN32__
184 * If a memory-using function (like curl_getenv) is used before
185 * curl_global_init() is called, we need to have these pointers set already.
187 curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
188 curl_free_callback Curl_cfree = (curl_free_callback)free;
189 curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
190 curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
191 curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
194 * Symbian OS doesn't support initialization to code in writeable static data.
195 * Initialization will occur in the curl_global_init() call.
197 curl_malloc_callback Curl_cmalloc;
198 curl_free_callback Curl_cfree;
199 curl_realloc_callback Curl_crealloc;
200 curl_strdup_callback Curl_cstrdup;
201 curl_calloc_callback Curl_ccalloc;
204 #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
205 # pragma warning(default:4232) /* MSVC extension, dllimport identity */
209 * curl_global_init() globally initializes cURL given a bitwise set of the
210 * different features of what to initialize.
212 CURLcode curl_global_init(long flags)
217 /* Setup the default memory functions here (again) */
218 Curl_cmalloc = (curl_malloc_callback)malloc;
219 Curl_cfree = (curl_free_callback)free;
220 Curl_crealloc = (curl_realloc_callback)realloc;
221 Curl_cstrdup = (curl_strdup_callback)system_strdup;
222 Curl_ccalloc = (curl_calloc_callback)calloc;
224 if(flags & CURL_GLOBAL_SSL)
225 if(!Curl_ssl_init()) {
226 DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
227 return CURLE_FAILED_INIT;
230 if(flags & CURL_GLOBAL_WIN32)
231 if(win32_init() != CURLE_OK) {
232 DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
233 return CURLE_FAILED_INIT;
237 if(!Curl_amiga_init()) {
238 DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
239 return CURLE_FAILED_INIT;
245 DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
253 if(Curl_resolver_global_init() != CURLE_OK) {
254 DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
255 return CURLE_FAILED_INIT;
258 #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_INIT)
259 if(libssh2_init(0)) {
260 DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n"));
261 return CURLE_FAILED_INIT;
267 /* Preset pseudo-random number sequence. */
275 * curl_global_init_mem() globally initializes cURL and also registers the
276 * user provided callback routines.
278 CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
279 curl_free_callback f, curl_realloc_callback r,
280 curl_strdup_callback s, curl_calloc_callback c)
282 CURLcode code = CURLE_OK;
284 /* Invalid input, return immediately */
285 if(!m || !f || !r || !s || !c)
286 return CURLE_FAILED_INIT;
288 /* Already initialized, don't do it again */
292 /* Call the actual init function first */
293 code = curl_global_init(flags);
294 if(code == CURLE_OK) {
306 * curl_global_cleanup() globally cleanups cURL, uses the value of
307 * "init_flags" to determine what needs to be cleaned up and what doesn't.
309 void curl_global_cleanup(void)
317 Curl_global_host_cache_dtor();
319 if(init_flags & CURL_GLOBAL_SSL)
322 Curl_resolver_global_cleanup();
324 if(init_flags & CURL_GLOBAL_WIN32)
327 Curl_amiga_cleanup();
329 #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_EXIT)
330 (void)libssh2_exit();
337 * curl_easy_init() is the external interface to alloc, setup and init an
338 * easy handle that is returned. If anything goes wrong, NULL is returned.
340 CURL *curl_easy_init(void)
343 struct SessionHandle *data;
345 /* Make sure we inited the global SSL stuff */
347 res = curl_global_init(CURL_GLOBAL_DEFAULT);
349 /* something in the global init failed, return nothing */
350 DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
355 /* We use curl_open() with undefined URL so far */
356 res = Curl_open(&data);
357 if(res != CURLE_OK) {
358 DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
366 * curl_easy_setopt() is the external interface for setting options on an
370 #undef curl_easy_setopt
371 CURLcode curl_easy_setopt(CURL *curl, CURLoption tag, ...)
374 struct SessionHandle *data = curl;
378 return CURLE_BAD_FUNCTION_ARGUMENT;
382 ret = Curl_setopt(data, tag, arg);
389 * curl_easy_perform() is the external interface that performs a blocking
390 * transfer as previously setup.
392 * CONCEPT: This function creates a multi handle, adds the easy handle to it,
393 * runs curl_multi_perform() until the transfer is done, then detaches the
394 * easy handle, destroys the multi handle and returns the easy handle's return
397 * REALITY: it can't just create and destroy the multi handle that easily. It
398 * needs to keep it around since if this easy handle is used again by this
399 * function, the same multi handle must be re-used so that the same pools and
400 * caches can be used.
402 CURLcode curl_easy_perform(CURL *easy)
406 CURLcode code = CURLE_OK;
410 struct SessionHandle *data = easy;
413 return CURLE_BAD_FUNCTION_ARGUMENT;
416 failf(data, "easy handled already used in multi handle");
417 return CURLE_FAILED_INIT;
421 multi = data->multi_easy;
423 multi = curl_multi_init();
425 return CURLE_OUT_OF_MEMORY;
426 data->multi_easy = multi;
429 mcode = curl_multi_add_handle(multi, easy);
431 curl_multi_cleanup(multi);
432 if(mcode == CURLM_OUT_OF_MEMORY)
433 return CURLE_OUT_OF_MEMORY;
435 return CURLE_FAILED_INIT;
438 /* assign this after curl_multi_add_handle() since that function checks for
439 it and rejects this handle otherwise */
442 while(!done && !mcode) {
445 mcode = curl_multi_wait(multi, NULL, 0, 1000, NULL);
447 if(mcode == CURLM_OK)
448 mcode = curl_multi_perform(multi, &still_running);
450 /* only read 'still_running' if curl_multi_perform() return OK */
451 if((mcode == CURLM_OK) && !still_running) {
452 msg = curl_multi_info_read(multi, &rc);
454 code = msg->data.result;
460 mcode = curl_multi_remove_handle(multi, easy);
462 /* The multi handle is kept alive, owned by the easy handle */
467 * curl_easy_cleanup() is the external interface to cleaning/freeing the given
470 void curl_easy_cleanup(CURL *curl)
472 struct SessionHandle *data = (struct SessionHandle *)curl;
481 * Store a pointed to the multi handle within the easy handle's data struct.
483 void Curl_easy_addmulti(struct SessionHandle *data,
489 void Curl_easy_initHandleData(struct SessionHandle *data)
491 memset(&data->req, 0, sizeof(struct SingleRequest));
493 data->req.maxdownload = -1;
497 * curl_easy_getinfo() is an external interface that allows an app to retrieve
498 * information from a performed transfer and similar.
500 #undef curl_easy_getinfo
501 CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...)
505 struct SessionHandle *data = (struct SessionHandle *)curl;
508 paramp = va_arg(arg, void *);
510 return Curl_getinfo(data, info, paramp);
514 * curl_easy_duphandle() is an external interface to allow duplication of a
515 * given input easy handle. The returned handle will be a new working handle
516 * with all options set exactly as the input source handle.
518 CURL *curl_easy_duphandle(CURL *incurl)
520 struct SessionHandle *data=(struct SessionHandle *)incurl;
522 struct SessionHandle *outcurl = calloc(1, sizeof(struct SessionHandle));
527 * We setup a few buffers we need. We should probably make them
528 * get setup on-demand in the code, as that would probably decrease
529 * the likeliness of us forgetting to init a buffer here in the future.
531 outcurl->state.headerbuff = malloc(HEADERSIZE);
532 if(!outcurl->state.headerbuff)
534 outcurl->state.headersize = HEADERSIZE;
536 /* copy all userdefined values */
537 if(Curl_dupset(outcurl, data) != CURLE_OK)
540 /* the connection cache is setup on demand */
541 outcurl->state.conn_cache = NULL;
543 outcurl->state.lastconnect = NULL;
545 outcurl->progress.flags = data->progress.flags;
546 outcurl->progress.callback = data->progress.callback;
549 /* If cookies are enabled in the parent handle, we enable them
550 in the clone as well! */
551 outcurl->cookies = Curl_cookie_init(data,
552 data->cookies->filename,
554 data->set.cookiesession);
555 if(!outcurl->cookies)
559 /* duplicate all values in 'change' */
560 if(data->change.cookielist) {
561 outcurl->change.cookielist =
562 Curl_slist_duplicate(data->change.cookielist);
563 if(!outcurl->change.cookielist)
567 if(data->change.url) {
568 outcurl->change.url = strdup(data->change.url);
569 if(!outcurl->change.url)
571 outcurl->change.url_alloc = TRUE;
574 if(data->change.referer) {
575 outcurl->change.referer = strdup(data->change.referer);
576 if(!outcurl->change.referer)
578 outcurl->change.referer_alloc = TRUE;
581 /* Clone the resolver handle, if present, for the new handle */
582 if(Curl_resolver_duphandle(&outcurl->state.resolver,
583 data->state.resolver) != CURLE_OK)
586 Curl_convert_setup(outcurl);
588 Curl_easy_initHandleData(outcurl);
590 outcurl->magic = CURLEASY_MAGIC_NUMBER;
592 /* we reach this point and thus we are OK */
599 curl_slist_free_all(outcurl->change.cookielist);
600 outcurl->change.cookielist = NULL;
601 Curl_safefree(outcurl->state.headerbuff);
602 Curl_safefree(outcurl->change.url);
603 Curl_safefree(outcurl->change.referer);
604 Curl_freeset(outcurl);
612 * curl_easy_reset() is an external interface that allows an app to re-
613 * initialize a session handle to the default values.
615 void curl_easy_reset(CURL *curl)
617 struct SessionHandle *data = (struct SessionHandle *)curl;
619 Curl_safefree(data->state.pathbuffer);
621 data->state.path = NULL;
623 Curl_safefree(data->state.proto.generic);
625 /* zero out UserDefined data: */
627 memset(&data->set, 0, sizeof(struct UserDefined));
628 (void)Curl_init_userdefined(&data->set);
630 /* zero out Progress data: */
631 memset(&data->progress, 0, sizeof(struct Progress));
633 /* init Handle data */
634 Curl_easy_initHandleData(data);
636 data->progress.flags |= PGRS_HIDE;
637 data->state.current_speed = -1; /* init to negative == impossible */
641 * curl_easy_pause() allows an application to pause or unpause a specific
642 * transfer and direction. This function sets the full new state for the
643 * current connection this easy handle operates on.
645 * NOTE: if you have the receiving paused and you call this function to remove
646 * the pausing, you may get your write callback called at this point.
648 * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
650 CURLcode curl_easy_pause(CURL *curl, int action)
652 struct SessionHandle *data = (struct SessionHandle *)curl;
653 struct SingleRequest *k = &data->req;
654 CURLcode result = CURLE_OK;
656 /* first switch off both pause bits */
657 int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
659 /* set the new desired pause bits */
660 newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
661 ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
663 /* put it back in the keepon */
664 k->keepon = newstate;
666 if(!(newstate & KEEP_RECV_PAUSE) && data->state.tempwrite) {
667 /* we have a buffer for sending that we now seem to be able to deliver
668 since the receive pausing is lifted! */
670 /* get the pointer, type and length in local copies since the function may
671 return PAUSE again and then we'll get a new copy allocted and stored in
672 the tempwrite variables */
673 char *tempwrite = data->state.tempwrite;
674 char *freewrite = tempwrite; /* store this pointer to free it later */
675 size_t tempsize = data->state.tempwritesize;
676 int temptype = data->state.tempwritetype;
679 /* clear tempwrite here just to make sure it gets cleared if there's no
680 further use of it, and make sure we don't clear it after the function
681 invoke as it may have been set to a new value by then */
682 data->state.tempwrite = NULL;
684 /* since the write callback API is define to never exceed
685 CURL_MAX_WRITE_SIZE bytes in a single call, and since we may in fact
686 have more data than that in our buffer here, we must loop sending the
687 data in multiple calls until there's no data left or we get another
690 A tricky part is that the function we call will "buffer" the data
691 itself when it pauses on a particular buffer, so we may need to do some
692 extra trickery if we get a pause return here.
695 chunklen = (tempsize > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:tempsize;
697 result = Curl_client_write(data->state.current_conn,
698 temptype, tempwrite, chunklen);
700 /* failures abort the loop at once */
703 if(data->state.tempwrite && (tempsize - chunklen)) {
704 /* Ouch, the reading is again paused and the block we send is now
705 "cached". If this is the final chunk we can leave it like this, but
706 if we have more chunks that are cached after this, we need to free
707 the newly cached one and put back a version that is truly the entire
708 contents that is saved for later
712 /* note that tempsize is still the size as before the callback was
713 used, and thus the whole piece of data to keep */
714 newptr = realloc(data->state.tempwrite, tempsize);
717 free(data->state.tempwrite); /* free old area */
718 data->state.tempwrite = NULL;
719 result = CURLE_OUT_OF_MEMORY;
720 /* tempwrite will be freed further down */
723 data->state.tempwrite = newptr; /* store new pointer */
724 memcpy(newptr, tempwrite, tempsize);
725 data->state.tempwritesize = tempsize; /* store new size */
726 /* tempwrite will be freed further down */
727 break; /* go back to pausing until further notice */
730 tempsize -= chunklen; /* left after the call above */
731 tempwrite += chunklen; /* advance the pointer */
734 } while((result == CURLE_OK) && tempsize);
736 free(freewrite); /* this is unconditionally no longer used */
743 static CURLcode easy_connection(struct SessionHandle *data,
745 struct connectdata **connp)
748 return CURLE_BAD_FUNCTION_ARGUMENT;
750 /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
751 if(!data->set.connect_only) {
752 failf(data, "CONNECT_ONLY is required!");
753 return CURLE_UNSUPPORTED_PROTOCOL;
756 *sfd = Curl_getconnectinfo(data, connp);
758 if(*sfd == CURL_SOCKET_BAD) {
759 failf(data, "Failed to get recent socket");
760 return CURLE_UNSUPPORTED_PROTOCOL;
767 * Receives data from the connected socket. Use after successful
768 * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
769 * Returns CURLE_OK on success, error code on error.
771 CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n)
776 struct connectdata *c;
777 struct SessionHandle *data = (struct SessionHandle *)curl;
779 ret = easy_connection(data, &sfd, &c);
784 ret = Curl_read(c, sfd, buffer, buflen, &n1);
795 * Sends data over the connected socket. Use after successful
796 * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
798 CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen,
804 struct connectdata *c = NULL;
805 struct SessionHandle *data = (struct SessionHandle *)curl;
807 ret = easy_connection(data, &sfd, &c);
812 ret = Curl_write(c, sfd, buffer, buflen, &n1);
815 return CURLE_SEND_ERROR;
818 if((CURLE_OK == ret) && (0 == n1))