easy.c 31 KB

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