easy.c 30 KB

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