easy.c 30 KB

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