easy.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. /*
  24. * See comment in curl_memory.h for the explanation of this sanity check.
  25. */
  26. #ifdef CURLX_NO_MEMORY_CALLBACKS
  27. #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined"
  28. #endif
  29. #ifdef HAVE_NETINET_IN_H
  30. #include <netinet/in.h>
  31. #endif
  32. #ifdef HAVE_NETDB_H
  33. #include <netdb.h>
  34. #endif
  35. #ifdef HAVE_ARPA_INET_H
  36. #include <arpa/inet.h>
  37. #endif
  38. #ifdef HAVE_NET_IF_H
  39. #include <net/if.h>
  40. #endif
  41. #ifdef HAVE_SYS_IOCTL_H
  42. #include <sys/ioctl.h>
  43. #endif
  44. #ifdef HAVE_SYS_PARAM_H
  45. #include <sys/param.h>
  46. #endif
  47. #include "urldata.h"
  48. #include <curl/curl.h>
  49. #include "transfer.h"
  50. #include "vtls/vtls.h"
  51. #include "url.h"
  52. #include "getinfo.h"
  53. #include "hostip.h"
  54. #include "share.h"
  55. #include "strdup.h"
  56. #include "progress.h"
  57. #include "easyif.h"
  58. #include "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. /* The last 3 #include files should be in this order */
  75. #include "curl_printf.h"
  76. #include "curl_memory.h"
  77. #include "memdebug.h"
  78. void Curl_version_init(void);
  79. /* true globals -- for curl_global_init() and curl_global_cleanup() */
  80. static unsigned int initialized;
  81. static long init_flags;
  82. /*
  83. * strdup (and other memory functions) is redefined in complicated
  84. * ways, but at this point it must be defined as the system-supplied strdup
  85. * so the callback pointer is initialized correctly.
  86. */
  87. #if defined(_WIN32_WCE)
  88. #define system_strdup _strdup
  89. #elif !defined(HAVE_STRDUP)
  90. #define system_strdup curlx_strdup
  91. #else
  92. #define system_strdup strdup
  93. #endif
  94. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  95. # pragma warning(disable:4232) /* MSVC extension, dllimport identity */
  96. #endif
  97. #ifndef __SYMBIAN32__
  98. /*
  99. * If a memory-using function (like curl_getenv) is used before
  100. * curl_global_init() is called, we need to have these pointers set already.
  101. */
  102. curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
  103. curl_free_callback Curl_cfree = (curl_free_callback)free;
  104. curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
  105. curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
  106. curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
  107. #if defined(WIN32) && defined(UNICODE)
  108. curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
  109. #endif
  110. #else
  111. /*
  112. * Symbian OS doesn't support initialization to code in writable static data.
  113. * Initialization will occur in the curl_global_init() call.
  114. */
  115. curl_malloc_callback Curl_cmalloc;
  116. curl_free_callback Curl_cfree;
  117. curl_realloc_callback Curl_crealloc;
  118. curl_strdup_callback Curl_cstrdup;
  119. curl_calloc_callback Curl_ccalloc;
  120. #endif
  121. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  122. # pragma warning(default:4232) /* MSVC extension, dllimport identity */
  123. #endif
  124. /**
  125. * curl_global_init() globally initializes curl given a bitwise set of the
  126. * different features of what to initialize.
  127. */
  128. static CURLcode global_init(long flags, bool memoryfuncs)
  129. {
  130. if(initialized++)
  131. return CURLE_OK;
  132. if(memoryfuncs) {
  133. /* Setup the default memory functions here (again) */
  134. Curl_cmalloc = (curl_malloc_callback)malloc;
  135. Curl_cfree = (curl_free_callback)free;
  136. Curl_crealloc = (curl_realloc_callback)realloc;
  137. Curl_cstrdup = (curl_strdup_callback)system_strdup;
  138. Curl_ccalloc = (curl_calloc_callback)calloc;
  139. #if defined(WIN32) && defined(UNICODE)
  140. Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
  141. #endif
  142. }
  143. if(!Curl_ssl_init()) {
  144. DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
  145. goto fail;
  146. }
  147. #ifdef WIN32
  148. if(Curl_win32_init(flags)) {
  149. DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
  150. goto fail;
  151. }
  152. #endif
  153. #ifdef __AMIGA__
  154. if(!Curl_amiga_init()) {
  155. DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
  156. goto fail;
  157. }
  158. #endif
  159. #ifdef NETWARE
  160. if(netware_init()) {
  161. DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
  162. }
  163. #endif
  164. if(Curl_resolver_global_init()) {
  165. DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
  166. goto fail;
  167. }
  168. #if defined(USE_SSH)
  169. if(Curl_ssh_init()) {
  170. goto fail;
  171. }
  172. #endif
  173. #ifdef USE_WOLFSSH
  174. if(WS_SUCCESS != wolfSSH_Init()) {
  175. DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n"));
  176. return CURLE_FAILED_INIT;
  177. }
  178. #endif
  179. init_flags = flags;
  180. Curl_version_init();
  181. return CURLE_OK;
  182. fail:
  183. initialized--; /* undo the increase */
  184. return CURLE_FAILED_INIT;
  185. }
  186. /**
  187. * curl_global_init() globally initializes curl given a bitwise set of the
  188. * different features of what to initialize.
  189. */
  190. CURLcode curl_global_init(long flags)
  191. {
  192. return global_init(flags, TRUE);
  193. }
  194. /*
  195. * curl_global_init_mem() globally initializes curl and also registers the
  196. * user provided callback routines.
  197. */
  198. CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
  199. curl_free_callback f, curl_realloc_callback r,
  200. curl_strdup_callback s, curl_calloc_callback c)
  201. {
  202. /* Invalid input, return immediately */
  203. if(!m || !f || !r || !s || !c)
  204. return CURLE_FAILED_INIT;
  205. if(initialized) {
  206. /* Already initialized, don't do it again, but bump the variable anyway to
  207. work like curl_global_init() and require the same amount of cleanup
  208. calls. */
  209. initialized++;
  210. return CURLE_OK;
  211. }
  212. /* set memory functions before global_init() in case it wants memory
  213. functions */
  214. Curl_cmalloc = m;
  215. Curl_cfree = f;
  216. Curl_cstrdup = s;
  217. Curl_crealloc = r;
  218. Curl_ccalloc = c;
  219. /* Call the actual init function, but without setting */
  220. return global_init(flags, FALSE);
  221. }
  222. /**
  223. * curl_global_cleanup() globally cleanups curl, uses the value of
  224. * "init_flags" to determine what needs to be cleaned up and what doesn't.
  225. */
  226. void curl_global_cleanup(void)
  227. {
  228. if(!initialized)
  229. return;
  230. if(--initialized)
  231. return;
  232. Curl_ssl_cleanup();
  233. Curl_resolver_global_cleanup();
  234. #ifdef WIN32
  235. Curl_win32_cleanup(init_flags);
  236. #endif
  237. Curl_amiga_cleanup();
  238. Curl_ssh_cleanup();
  239. #ifdef USE_WOLFSSH
  240. (void)wolfSSH_Cleanup();
  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, (int)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. if(mcode == CURLM_OUT_OF_MEMORY)
  592. return CURLE_OUT_OF_MEMORY;
  593. return CURLE_FAILED_INIT;
  594. }
  595. sigpipe_ignore(data, &pipe_st);
  596. /* run the transfer */
  597. result = events ? easy_events(multi) : easy_transfer(multi);
  598. /* ignoring the return code isn't nice, but atm we can't really handle
  599. a failure here, room for future improvement! */
  600. (void)curl_multi_remove_handle(multi, data);
  601. sigpipe_restore(&pipe_st);
  602. /* The multi handle is kept alive, owned by the easy handle */
  603. return result;
  604. }
  605. /*
  606. * curl_easy_perform() is the external interface that performs a blocking
  607. * transfer as previously setup.
  608. */
  609. CURLcode curl_easy_perform(struct Curl_easy *data)
  610. {
  611. return easy_perform(data, FALSE);
  612. }
  613. #ifdef CURLDEBUG
  614. /*
  615. * curl_easy_perform_ev() is the external interface that performs a blocking
  616. * transfer using the event-based API internally.
  617. */
  618. CURLcode curl_easy_perform_ev(struct Curl_easy *data)
  619. {
  620. return easy_perform(data, TRUE);
  621. }
  622. #endif
  623. /*
  624. * curl_easy_cleanup() is the external interface to cleaning/freeing the given
  625. * easy handle.
  626. */
  627. void curl_easy_cleanup(struct Curl_easy *data)
  628. {
  629. SIGPIPE_VARIABLE(pipe_st);
  630. if(!data)
  631. return;
  632. sigpipe_ignore(data, &pipe_st);
  633. Curl_close(&data);
  634. sigpipe_restore(&pipe_st);
  635. }
  636. /*
  637. * curl_easy_getinfo() is an external interface that allows an app to retrieve
  638. * information from a performed transfer and similar.
  639. */
  640. #undef curl_easy_getinfo
  641. CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...)
  642. {
  643. va_list arg;
  644. void *paramp;
  645. CURLcode result;
  646. va_start(arg, info);
  647. paramp = va_arg(arg, void *);
  648. result = Curl_getinfo(data, info, paramp);
  649. va_end(arg);
  650. return result;
  651. }
  652. static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src)
  653. {
  654. CURLcode result = CURLE_OK;
  655. enum dupstring i;
  656. /* Copy src->set into dst->set first, then deal with the strings
  657. afterwards */
  658. dst->set = src->set;
  659. Curl_mime_initpart(&dst->set.mimepost, dst);
  660. /* clear all string pointers first */
  661. memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
  662. /* duplicate all strings */
  663. for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
  664. result = Curl_setstropt(&dst->set.str[i], src->set.str[i]);
  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. outcurl->state.buffer = malloc(outcurl->set.buffer_size + 1);
  702. if(!outcurl->state.buffer)
  703. goto fail;
  704. outcurl->state.headerbuff = malloc(HEADERSIZE);
  705. if(!outcurl->state.headerbuff)
  706. goto fail;
  707. outcurl->state.headersize = HEADERSIZE;
  708. /* copy all userdefined values */
  709. if(dupset(outcurl, data))
  710. goto fail;
  711. /* the connection cache is setup on demand */
  712. outcurl->state.conn_cache = NULL;
  713. outcurl->state.lastconnect = NULL;
  714. outcurl->progress.flags = data->progress.flags;
  715. outcurl->progress.callback = data->progress.callback;
  716. if(data->cookies) {
  717. /* If cookies are enabled in the parent handle, we enable them
  718. in the clone as well! */
  719. outcurl->cookies = Curl_cookie_init(data,
  720. data->cookies->filename,
  721. outcurl->cookies,
  722. data->set.cookiesession);
  723. if(!outcurl->cookies)
  724. goto fail;
  725. }
  726. /* duplicate all values in 'change' */
  727. if(data->change.cookielist) {
  728. outcurl->change.cookielist =
  729. Curl_slist_duplicate(data->change.cookielist);
  730. if(!outcurl->change.cookielist)
  731. goto fail;
  732. }
  733. if(data->change.url) {
  734. outcurl->change.url = strdup(data->change.url);
  735. if(!outcurl->change.url)
  736. goto fail;
  737. outcurl->change.url_alloc = TRUE;
  738. }
  739. if(data->change.referer) {
  740. outcurl->change.referer = strdup(data->change.referer);
  741. if(!outcurl->change.referer)
  742. goto fail;
  743. outcurl->change.referer_alloc = TRUE;
  744. }
  745. /* Reinitialize an SSL engine for the new handle
  746. * note: the engine name has already been copied by dupset */
  747. if(outcurl->set.str[STRING_SSL_ENGINE]) {
  748. if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE]))
  749. goto fail;
  750. }
  751. /* Clone the resolver handle, if present, for the new handle */
  752. if(Curl_resolver_duphandle(outcurl,
  753. &outcurl->state.resolver,
  754. data->state.resolver))
  755. goto fail;
  756. Curl_convert_setup(outcurl);
  757. Curl_initinfo(outcurl);
  758. outcurl->magic = CURLEASY_MAGIC_NUMBER;
  759. /* we reach this point and thus we are OK */
  760. return outcurl;
  761. fail:
  762. if(outcurl) {
  763. curl_slist_free_all(outcurl->change.cookielist);
  764. outcurl->change.cookielist = NULL;
  765. Curl_safefree(outcurl->state.buffer);
  766. Curl_safefree(outcurl->state.headerbuff);
  767. Curl_safefree(outcurl->change.url);
  768. Curl_safefree(outcurl->change.referer);
  769. Curl_freeset(outcurl);
  770. free(outcurl);
  771. }
  772. return NULL;
  773. }
  774. /*
  775. * curl_easy_reset() is an external interface that allows an app to re-
  776. * initialize a session handle to the default values.
  777. */
  778. void curl_easy_reset(struct Curl_easy *data)
  779. {
  780. long old_buffer_size = data->set.buffer_size;
  781. Curl_free_request_state(data);
  782. /* zero out UserDefined data: */
  783. Curl_freeset(data);
  784. memset(&data->set, 0, sizeof(struct UserDefined));
  785. (void)Curl_init_userdefined(data);
  786. /* zero out Progress data: */
  787. memset(&data->progress, 0, sizeof(struct Progress));
  788. /* zero out PureInfo data: */
  789. Curl_initinfo(data);
  790. data->progress.flags |= PGRS_HIDE;
  791. data->state.current_speed = -1; /* init to negative == impossible */
  792. /* zero out authentication data: */
  793. memset(&data->state.authhost, 0, sizeof(struct auth));
  794. memset(&data->state.authproxy, 0, sizeof(struct auth));
  795. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
  796. Curl_http_auth_cleanup_digest(data);
  797. #endif
  798. /* resize receive buffer */
  799. if(old_buffer_size != data->set.buffer_size) {
  800. char *newbuff = realloc(data->state.buffer, data->set.buffer_size + 1);
  801. if(!newbuff) {
  802. DEBUGF(fprintf(stderr, "Error: realloc of buffer failed\n"));
  803. /* nothing we can do here except use the old size */
  804. data->set.buffer_size = old_buffer_size;
  805. }
  806. else
  807. data->state.buffer = newbuff;
  808. }
  809. }
  810. /*
  811. * curl_easy_pause() allows an application to pause or unpause a specific
  812. * transfer and direction. This function sets the full new state for the
  813. * current connection this easy handle operates on.
  814. *
  815. * NOTE: if you have the receiving paused and you call this function to remove
  816. * the pausing, you may get your write callback called at this point.
  817. *
  818. * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
  819. *
  820. * NOTE: This is one of few API functions that are allowed to be called from
  821. * within a callback.
  822. */
  823. CURLcode curl_easy_pause(struct Curl_easy *data, int action)
  824. {
  825. struct SingleRequest *k = &data->req;
  826. CURLcode result = CURLE_OK;
  827. /* first switch off both pause bits */
  828. int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
  829. /* set the new desired pause bits */
  830. newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
  831. ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
  832. /* put it back in the keepon */
  833. k->keepon = newstate;
  834. if(!(newstate & KEEP_RECV_PAUSE)) {
  835. Curl_http2_stream_pause(data, FALSE);
  836. if(data->state.tempcount) {
  837. /* there are buffers for sending that can be delivered as the receive
  838. pausing is lifted! */
  839. unsigned int i;
  840. unsigned int count = data->state.tempcount;
  841. struct tempbuf writebuf[3]; /* there can only be three */
  842. struct connectdata *conn = data->conn;
  843. struct Curl_easy *saved_data = NULL;
  844. /* copy the structs to allow for immediate re-pausing */
  845. for(i = 0; i < data->state.tempcount; i++) {
  846. writebuf[i] = data->state.tempwrite[i];
  847. data->state.tempwrite[i].buf = NULL;
  848. }
  849. data->state.tempcount = 0;
  850. /* set the connection's current owner */
  851. if(conn->data != data) {
  852. saved_data = conn->data;
  853. conn->data = data;
  854. }
  855. for(i = 0; i < count; i++) {
  856. /* even if one function returns error, this loops through and frees
  857. all buffers */
  858. if(!result)
  859. result = Curl_client_write(conn, writebuf[i].type, writebuf[i].buf,
  860. writebuf[i].len);
  861. free(writebuf[i].buf);
  862. }
  863. /* recover previous owner of the connection */
  864. if(saved_data)
  865. conn->data = saved_data;
  866. if(result)
  867. return result;
  868. }
  869. }
  870. /* if there's no error and we're not pausing both directions, we want
  871. to have this handle checked soon */
  872. if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
  873. (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) {
  874. data->state.drain++;
  875. Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */
  876. if(data->multi)
  877. Curl_update_timer(data->multi);
  878. }
  879. if(!data->state.done)
  880. /* This transfer may have been moved in or out of the bundle, update the
  881. corresponding socket callback, if used */
  882. Curl_updatesocket(data);
  883. return result;
  884. }
  885. static CURLcode easy_connection(struct Curl_easy *data,
  886. curl_socket_t *sfd,
  887. struct connectdata **connp)
  888. {
  889. if(data == NULL)
  890. return CURLE_BAD_FUNCTION_ARGUMENT;
  891. /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
  892. if(!data->set.connect_only) {
  893. failf(data, "CONNECT_ONLY is required!");
  894. return CURLE_UNSUPPORTED_PROTOCOL;
  895. }
  896. *sfd = Curl_getconnectinfo(data, connp);
  897. if(*sfd == CURL_SOCKET_BAD) {
  898. failf(data, "Failed to get recent socket");
  899. return CURLE_UNSUPPORTED_PROTOCOL;
  900. }
  901. return CURLE_OK;
  902. }
  903. /*
  904. * Receives data from the connected socket. Use after successful
  905. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  906. * Returns CURLE_OK on success, error code on error.
  907. */
  908. CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen,
  909. size_t *n)
  910. {
  911. curl_socket_t sfd;
  912. CURLcode result;
  913. ssize_t n1;
  914. struct connectdata *c;
  915. if(Curl_is_in_callback(data))
  916. return CURLE_RECURSIVE_API_CALL;
  917. result = easy_connection(data, &sfd, &c);
  918. if(result)
  919. return result;
  920. *n = 0;
  921. result = Curl_read(c, sfd, buffer, buflen, &n1);
  922. if(result)
  923. return result;
  924. *n = (size_t)n1;
  925. return CURLE_OK;
  926. }
  927. /*
  928. * Sends data over the connected socket. Use after successful
  929. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  930. */
  931. CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer,
  932. size_t buflen, size_t *n)
  933. {
  934. curl_socket_t sfd;
  935. CURLcode result;
  936. ssize_t n1;
  937. struct connectdata *c = NULL;
  938. if(Curl_is_in_callback(data))
  939. return CURLE_RECURSIVE_API_CALL;
  940. result = easy_connection(data, &sfd, &c);
  941. if(result)
  942. return result;
  943. *n = 0;
  944. result = Curl_write(c, sfd, buffer, buflen, &n1);
  945. if(n1 == -1)
  946. return CURLE_SEND_ERROR;
  947. /* detect EAGAIN */
  948. if(!result && !n1)
  949. return CURLE_AGAIN;
  950. *n = (size_t)n1;
  951. return result;
  952. }
  953. /*
  954. * Wrapper to call functions in Curl_conncache_foreach()
  955. *
  956. * Returns always 0.
  957. */
  958. static int conn_upkeep(struct connectdata *conn,
  959. void *param)
  960. {
  961. /* Param is unused. */
  962. (void)param;
  963. if(conn->handler->connection_check) {
  964. /* Do a protocol-specific keepalive check on the connection. */
  965. conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE);
  966. }
  967. return 0; /* continue iteration */
  968. }
  969. static CURLcode upkeep(struct conncache *conn_cache, void *data)
  970. {
  971. /* Loop over every connection and make connection alive. */
  972. Curl_conncache_foreach(data,
  973. conn_cache,
  974. data,
  975. conn_upkeep);
  976. return CURLE_OK;
  977. }
  978. /*
  979. * Performs connection upkeep for the given session handle.
  980. */
  981. CURLcode curl_easy_upkeep(struct Curl_easy *data)
  982. {
  983. /* Verify that we got an easy handle we can work with. */
  984. if(!GOOD_EASY_HANDLE(data))
  985. return CURLE_BAD_FUNCTION_ARGUMENT;
  986. if(data->multi_easy) {
  987. /* Use the common function to keep connections alive. */
  988. return upkeep(&data->multi_easy->conn_cache, data);
  989. }
  990. else {
  991. /* No connections, so just return success */
  992. return CURLE_OK;
  993. }
  994. }