easy.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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_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. #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\n", 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\n", 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\n", 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)\n",
  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. /* Curl_setstropt return CURLE_BAD_FUNCTION_ARGUMENT with blob */
  676. if(result)
  677. return result;
  678. }
  679. /* duplicate memory areas pointed to */
  680. i = STRING_COPYPOSTFIELDS;
  681. if(src->set.postfieldsize && src->set.str[i]) {
  682. /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
  683. dst->set.str[i] = Curl_memdup(src->set.str[i],
  684. curlx_sotouz(src->set.postfieldsize));
  685. if(!dst->set.str[i])
  686. return CURLE_OUT_OF_MEMORY;
  687. /* point to the new copy */
  688. dst->set.postfields = dst->set.str[i];
  689. }
  690. /* Duplicate mime data. */
  691. result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost);
  692. if(src->set.resolve)
  693. dst->change.resolve = dst->set.resolve;
  694. return result;
  695. }
  696. /*
  697. * curl_easy_duphandle() is an external interface to allow duplication of a
  698. * given input easy handle. The returned handle will be a new working handle
  699. * with all options set exactly as the input source handle.
  700. */
  701. struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data)
  702. {
  703. struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy));
  704. if(NULL == outcurl)
  705. goto fail;
  706. /*
  707. * We setup a few buffers we need. We should probably make them
  708. * get setup on-demand in the code, as that would probably decrease
  709. * the likeliness of us forgetting to init a buffer here in the future.
  710. */
  711. outcurl->set.buffer_size = data->set.buffer_size;
  712. /* copy all userdefined values */
  713. if(dupset(outcurl, data))
  714. goto fail;
  715. Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER);
  716. /* the connection cache is setup on demand */
  717. outcurl->state.conn_cache = NULL;
  718. outcurl->state.lastconnect_id = -1;
  719. outcurl->progress.flags = data->progress.flags;
  720. outcurl->progress.callback = data->progress.callback;
  721. if(data->cookies) {
  722. /* If cookies are enabled in the parent handle, we enable them
  723. in the clone as well! */
  724. outcurl->cookies = Curl_cookie_init(data,
  725. data->cookies->filename,
  726. outcurl->cookies,
  727. data->set.cookiesession);
  728. if(!outcurl->cookies)
  729. goto fail;
  730. }
  731. /* duplicate all values in 'change' */
  732. if(data->change.cookielist) {
  733. outcurl->change.cookielist =
  734. Curl_slist_duplicate(data->change.cookielist);
  735. if(!outcurl->change.cookielist)
  736. goto fail;
  737. }
  738. if(data->change.url) {
  739. outcurl->change.url = strdup(data->change.url);
  740. if(!outcurl->change.url)
  741. goto fail;
  742. outcurl->change.url_alloc = TRUE;
  743. }
  744. if(data->change.referer) {
  745. outcurl->change.referer = strdup(data->change.referer);
  746. if(!outcurl->change.referer)
  747. goto fail;
  748. outcurl->change.referer_alloc = TRUE;
  749. }
  750. /* Reinitialize an SSL engine for the new handle
  751. * note: the engine name has already been copied by dupset */
  752. if(outcurl->set.str[STRING_SSL_ENGINE]) {
  753. if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE]))
  754. goto fail;
  755. }
  756. #ifdef USE_ALTSVC
  757. if(data->asi) {
  758. outcurl->asi = Curl_altsvc_init();
  759. if(!outcurl->asi)
  760. goto fail;
  761. if(outcurl->set.str[STRING_ALTSVC])
  762. (void)Curl_altsvc_load(outcurl->asi, outcurl->set.str[STRING_ALTSVC]);
  763. }
  764. #endif
  765. #ifdef USE_HSTS
  766. if(data->hsts) {
  767. outcurl->hsts = Curl_hsts_init();
  768. if(!outcurl->hsts)
  769. goto fail;
  770. if(outcurl->set.str[STRING_HSTS])
  771. (void)Curl_hsts_loadfile(outcurl,
  772. outcurl->hsts, outcurl->set.str[STRING_HSTS]);
  773. (void)Curl_hsts_loadcb(outcurl, outcurl->hsts);
  774. }
  775. #endif
  776. /* Clone the resolver handle, if present, for the new handle */
  777. if(Curl_resolver_duphandle(outcurl,
  778. &outcurl->state.async.resolver,
  779. data->state.async.resolver))
  780. goto fail;
  781. #ifdef USE_ARES
  782. {
  783. CURLcode rc;
  784. rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]);
  785. if(rc && rc != CURLE_NOT_BUILT_IN)
  786. goto fail;
  787. rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]);
  788. if(rc && rc != CURLE_NOT_BUILT_IN)
  789. goto fail;
  790. rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]);
  791. if(rc && rc != CURLE_NOT_BUILT_IN)
  792. goto fail;
  793. rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]);
  794. if(rc && rc != CURLE_NOT_BUILT_IN)
  795. goto fail;
  796. }
  797. #endif /* USE_ARES */
  798. Curl_convert_setup(outcurl);
  799. Curl_initinfo(outcurl);
  800. outcurl->magic = CURLEASY_MAGIC_NUMBER;
  801. /* we reach this point and thus we are OK */
  802. return outcurl;
  803. fail:
  804. if(outcurl) {
  805. curl_slist_free_all(outcurl->change.cookielist);
  806. outcurl->change.cookielist = NULL;
  807. Curl_safefree(outcurl->state.buffer);
  808. Curl_dyn_free(&outcurl->state.headerb);
  809. Curl_safefree(outcurl->change.url);
  810. Curl_safefree(outcurl->change.referer);
  811. Curl_altsvc_cleanup(&outcurl->asi);
  812. Curl_hsts_cleanup(&outcurl->hsts);
  813. Curl_freeset(outcurl);
  814. free(outcurl);
  815. }
  816. return NULL;
  817. }
  818. /*
  819. * curl_easy_reset() is an external interface that allows an app to re-
  820. * initialize a session handle to the default values.
  821. */
  822. void curl_easy_reset(struct Curl_easy *data)
  823. {
  824. Curl_free_request_state(data);
  825. /* zero out UserDefined data: */
  826. Curl_freeset(data);
  827. memset(&data->set, 0, sizeof(struct UserDefined));
  828. (void)Curl_init_userdefined(data);
  829. /* zero out Progress data: */
  830. memset(&data->progress, 0, sizeof(struct Progress));
  831. /* zero out PureInfo data: */
  832. Curl_initinfo(data);
  833. data->progress.flags |= PGRS_HIDE;
  834. data->state.current_speed = -1; /* init to negative == impossible */
  835. data->state.retrycount = 0; /* reset the retry counter */
  836. /* zero out authentication data: */
  837. memset(&data->state.authhost, 0, sizeof(struct auth));
  838. memset(&data->state.authproxy, 0, sizeof(struct auth));
  839. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
  840. Curl_http_auth_cleanup_digest(data);
  841. #endif
  842. }
  843. /*
  844. * curl_easy_pause() allows an application to pause or unpause a specific
  845. * transfer and direction. This function sets the full new state for the
  846. * current connection this easy handle operates on.
  847. *
  848. * NOTE: if you have the receiving paused and you call this function to remove
  849. * the pausing, you may get your write callback called at this point.
  850. *
  851. * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
  852. *
  853. * NOTE: This is one of few API functions that are allowed to be called from
  854. * within a callback.
  855. */
  856. CURLcode curl_easy_pause(struct Curl_easy *data, int action)
  857. {
  858. struct SingleRequest *k;
  859. CURLcode result = CURLE_OK;
  860. int oldstate;
  861. int newstate;
  862. if(!GOOD_EASY_HANDLE(data) || !data->conn)
  863. /* crazy input, don't continue */
  864. return CURLE_BAD_FUNCTION_ARGUMENT;
  865. k = &data->req;
  866. oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
  867. /* first switch off both pause bits then set the new pause bits */
  868. newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) |
  869. ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
  870. ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
  871. if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) {
  872. /* Not changing any pause state, return */
  873. DEBUGF(infof(data, "pause: no change, early return\n"));
  874. return CURLE_OK;
  875. }
  876. /* Unpause parts in active mime tree. */
  877. if((k->keepon & ~newstate & KEEP_SEND_PAUSE) &&
  878. (data->mstate == CURLM_STATE_PERFORM ||
  879. data->mstate == CURLM_STATE_TOOFAST) &&
  880. data->state.fread_func == (curl_read_callback) Curl_mime_read) {
  881. Curl_mime_unpause(data->state.in);
  882. }
  883. /* put it back in the keepon */
  884. k->keepon = newstate;
  885. if(!(newstate & KEEP_RECV_PAUSE)) {
  886. Curl_http2_stream_pause(data, FALSE);
  887. if(data->state.tempcount) {
  888. /* there are buffers for sending that can be delivered as the receive
  889. pausing is lifted! */
  890. unsigned int i;
  891. unsigned int count = data->state.tempcount;
  892. struct tempbuf writebuf[3]; /* there can only be three */
  893. struct connectdata *conn = data->conn;
  894. struct Curl_easy *saved_data = NULL;
  895. /* copy the structs to allow for immediate re-pausing */
  896. for(i = 0; i < data->state.tempcount; i++) {
  897. writebuf[i] = data->state.tempwrite[i];
  898. Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER);
  899. }
  900. data->state.tempcount = 0;
  901. /* set the connection's current owner */
  902. if(conn->data != data) {
  903. saved_data = conn->data;
  904. conn->data = data;
  905. }
  906. for(i = 0; i < count; i++) {
  907. /* even if one function returns error, this loops through and frees
  908. all buffers */
  909. if(!result)
  910. result = Curl_client_write(data, writebuf[i].type,
  911. Curl_dyn_ptr(&writebuf[i].b),
  912. Curl_dyn_len(&writebuf[i].b));
  913. Curl_dyn_free(&writebuf[i].b);
  914. }
  915. /* recover previous owner of the connection */
  916. if(saved_data)
  917. conn->data = saved_data;
  918. if(result)
  919. return result;
  920. }
  921. }
  922. /* if there's no error and we're not pausing both directions, we want
  923. to have this handle checked soon */
  924. if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
  925. (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) {
  926. Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */
  927. /* reset the too-slow time keeper */
  928. data->state.keeps_speed.tv_sec = 0;
  929. if(!data->state.tempcount)
  930. /* if not pausing again, force a recv/send check of this connection as
  931. the data might've been read off the socket already */
  932. data->conn->cselect_bits = CURL_CSELECT_IN | CURL_CSELECT_OUT;
  933. if(data->multi)
  934. Curl_update_timer(data->multi);
  935. }
  936. if(!data->state.done)
  937. /* This transfer may have been moved in or out of the bundle, update the
  938. corresponding socket callback, if used */
  939. Curl_updatesocket(data);
  940. return result;
  941. }
  942. static CURLcode easy_connection(struct Curl_easy *data,
  943. curl_socket_t *sfd,
  944. struct connectdata **connp)
  945. {
  946. if(data == NULL)
  947. return CURLE_BAD_FUNCTION_ARGUMENT;
  948. /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
  949. if(!data->set.connect_only) {
  950. failf(data, "CONNECT_ONLY is required!");
  951. return CURLE_UNSUPPORTED_PROTOCOL;
  952. }
  953. *sfd = Curl_getconnectinfo(data, connp);
  954. if(*sfd == CURL_SOCKET_BAD) {
  955. failf(data, "Failed to get recent socket");
  956. return CURLE_UNSUPPORTED_PROTOCOL;
  957. }
  958. return CURLE_OK;
  959. }
  960. /*
  961. * Receives data from the connected socket. Use after successful
  962. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  963. * Returns CURLE_OK on success, error code on error.
  964. */
  965. CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen,
  966. size_t *n)
  967. {
  968. curl_socket_t sfd;
  969. CURLcode result;
  970. ssize_t n1;
  971. struct connectdata *c;
  972. if(Curl_is_in_callback(data))
  973. return CURLE_RECURSIVE_API_CALL;
  974. result = easy_connection(data, &sfd, &c);
  975. if(result)
  976. return result;
  977. if(!data->conn)
  978. /* on first invoke, the transfer has been detached from the connection and
  979. needs to be reattached */
  980. Curl_attach_connnection(data, c);
  981. *n = 0;
  982. result = Curl_read(data, sfd, buffer, buflen, &n1);
  983. if(result)
  984. return result;
  985. *n = (size_t)n1;
  986. return CURLE_OK;
  987. }
  988. /*
  989. * Sends data over the connected socket. Use after successful
  990. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  991. */
  992. CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer,
  993. size_t buflen, size_t *n)
  994. {
  995. curl_socket_t sfd;
  996. CURLcode result;
  997. ssize_t n1;
  998. struct connectdata *c = NULL;
  999. if(Curl_is_in_callback(data))
  1000. return CURLE_RECURSIVE_API_CALL;
  1001. result = easy_connection(data, &sfd, &c);
  1002. if(result)
  1003. return result;
  1004. if(!data->conn)
  1005. /* on first invoke, the transfer has been detached from the connection and
  1006. needs to be reattached */
  1007. Curl_attach_connnection(data, c);
  1008. *n = 0;
  1009. result = Curl_write(data, sfd, buffer, buflen, &n1);
  1010. if(n1 == -1)
  1011. return CURLE_SEND_ERROR;
  1012. /* detect EAGAIN */
  1013. if(!result && !n1)
  1014. return CURLE_AGAIN;
  1015. *n = (size_t)n1;
  1016. return result;
  1017. }
  1018. /*
  1019. * Wrapper to call functions in Curl_conncache_foreach()
  1020. *
  1021. * Returns always 0.
  1022. */
  1023. static int conn_upkeep(struct Curl_easy *data,
  1024. struct connectdata *conn,
  1025. void *param)
  1026. {
  1027. /* Param is unused. */
  1028. (void)param;
  1029. if(conn->handler->connection_check)
  1030. /* Do a protocol-specific keepalive check on the connection. */
  1031. conn->handler->connection_check(data, conn, CONNCHECK_KEEPALIVE);
  1032. return 0; /* continue iteration */
  1033. }
  1034. static CURLcode upkeep(struct conncache *conn_cache, void *data)
  1035. {
  1036. /* Loop over every connection and make connection alive. */
  1037. Curl_conncache_foreach(data,
  1038. conn_cache,
  1039. data,
  1040. conn_upkeep);
  1041. return CURLE_OK;
  1042. }
  1043. /*
  1044. * Performs connection upkeep for the given session handle.
  1045. */
  1046. CURLcode curl_easy_upkeep(struct Curl_easy *data)
  1047. {
  1048. /* Verify that we got an easy handle we can work with. */
  1049. if(!GOOD_EASY_HANDLE(data))
  1050. return CURLE_BAD_FUNCTION_ARGUMENT;
  1051. if(data->multi_easy) {
  1052. /* Use the common function to keep connections alive. */
  1053. return upkeep(&data->multi_easy->conn_cache, data);
  1054. }
  1055. else {
  1056. /* No connections, so just return success */
  1057. return CURLE_OK;
  1058. }
  1059. }