easy.c 33 KB

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