easy.c 34 KB

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