easy.c 30 KB

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