easy.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, 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 http://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 "strequal.h"
  48. #include "urldata.h"
  49. #include <curl/curl.h>
  50. #include "transfer.h"
  51. #include "vtls/vtls.h"
  52. #include "url.h"
  53. #include "getinfo.h"
  54. #include "hostip.h"
  55. #include "share.h"
  56. #include "strdup.h"
  57. #include "curl_memory.h"
  58. #include "progress.h"
  59. #include "easyif.h"
  60. #include "select.h"
  61. #include "sendf.h" /* for failf function prototype */
  62. #include "curl_ntlm.h"
  63. #include "connect.h" /* for Curl_getconnectinfo */
  64. #include "slist.h"
  65. #include "amigaos.h"
  66. #include "non-ascii.h"
  67. #include "warnless.h"
  68. #include "conncache.h"
  69. #include "multiif.h"
  70. #include "sigpipe.h"
  71. #define _MPRINTF_REPLACE /* use our functions only */
  72. #include <curl/mprintf.h>
  73. /* The last #include file should be: */
  74. #include "memdebug.h"
  75. /* win32_cleanup() is for win32 socket cleanup functionality, the opposite
  76. of win32_init() */
  77. static void win32_cleanup(void)
  78. {
  79. #ifdef USE_WINSOCK
  80. WSACleanup();
  81. #endif
  82. #ifdef USE_WINDOWS_SSPI
  83. Curl_sspi_global_cleanup();
  84. #endif
  85. }
  86. /* win32_init() performs win32 socket initialization to properly setup the
  87. stack to allow networking */
  88. static CURLcode win32_init(void)
  89. {
  90. #ifdef USE_WINSOCK
  91. WORD wVersionRequested;
  92. WSADATA wsaData;
  93. int res;
  94. #if defined(ENABLE_IPV6) && (USE_WINSOCK < 2)
  95. Error IPV6_requires_winsock2
  96. #endif
  97. wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK);
  98. res = WSAStartup(wVersionRequested, &wsaData);
  99. if(res != 0)
  100. /* Tell the user that we couldn't find a useable */
  101. /* winsock.dll. */
  102. return CURLE_FAILED_INIT;
  103. /* Confirm that the Windows Sockets DLL supports what we need.*/
  104. /* Note that if the DLL supports versions greater */
  105. /* than wVersionRequested, it will still return */
  106. /* wVersionRequested in wVersion. wHighVersion contains the */
  107. /* highest supported version. */
  108. if(LOBYTE( wsaData.wVersion ) != LOBYTE(wVersionRequested) ||
  109. HIBYTE( wsaData.wVersion ) != HIBYTE(wVersionRequested) ) {
  110. /* Tell the user that we couldn't find a useable */
  111. /* winsock.dll. */
  112. WSACleanup();
  113. return CURLE_FAILED_INIT;
  114. }
  115. /* The Windows Sockets DLL is acceptable. Proceed. */
  116. #elif defined(USE_LWIPSOCK)
  117. lwip_init();
  118. #endif
  119. #ifdef USE_WINDOWS_SSPI
  120. {
  121. CURLcode result = Curl_sspi_global_init();
  122. if(result)
  123. return result;
  124. }
  125. #endif
  126. return CURLE_OK;
  127. }
  128. #ifdef USE_LIBIDN
  129. /*
  130. * Initialise use of IDNA library.
  131. * It falls back to ASCII if $CHARSET isn't defined. This doesn't work for
  132. * idna_to_ascii_lz().
  133. */
  134. static void idna_init (void)
  135. {
  136. #ifdef WIN32
  137. char buf[60];
  138. UINT cp = GetACP();
  139. if(!getenv("CHARSET") && cp > 0) {
  140. snprintf(buf, sizeof(buf), "CHARSET=cp%u", cp);
  141. putenv(buf);
  142. }
  143. #else
  144. /* to do? */
  145. #endif
  146. }
  147. #endif /* USE_LIBIDN */
  148. /* true globals -- for curl_global_init() and curl_global_cleanup() */
  149. static unsigned int initialized;
  150. static long init_flags;
  151. /*
  152. * strdup (and other memory functions) is redefined in complicated
  153. * ways, but at this point it must be defined as the system-supplied strdup
  154. * so the callback pointer is initialized correctly.
  155. */
  156. #if defined(_WIN32_WCE)
  157. #define system_strdup _strdup
  158. #elif !defined(HAVE_STRDUP)
  159. #define system_strdup curlx_strdup
  160. #else
  161. #define system_strdup strdup
  162. #endif
  163. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  164. # pragma warning(disable:4232) /* MSVC extension, dllimport identity */
  165. #endif
  166. #ifndef __SYMBIAN32__
  167. /*
  168. * If a memory-using function (like curl_getenv) is used before
  169. * curl_global_init() is called, we need to have these pointers set already.
  170. */
  171. curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
  172. curl_free_callback Curl_cfree = (curl_free_callback)free;
  173. curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
  174. curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup;
  175. curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
  176. #if defined(WIN32) && defined(UNICODE)
  177. curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
  178. #endif
  179. #else
  180. /*
  181. * Symbian OS doesn't support initialization to code in writeable static data.
  182. * Initialization will occur in the curl_global_init() call.
  183. */
  184. curl_malloc_callback Curl_cmalloc;
  185. curl_free_callback Curl_cfree;
  186. curl_realloc_callback Curl_crealloc;
  187. curl_strdup_callback Curl_cstrdup;
  188. curl_calloc_callback Curl_ccalloc;
  189. #endif
  190. #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__)
  191. # pragma warning(default:4232) /* MSVC extension, dllimport identity */
  192. #endif
  193. /**
  194. * curl_global_init() globally initializes cURL given a bitwise set of the
  195. * different features of what to initialize.
  196. */
  197. CURLcode curl_global_init(long flags)
  198. {
  199. if(initialized++)
  200. return CURLE_OK;
  201. /* Setup the default memory functions here (again) */
  202. Curl_cmalloc = (curl_malloc_callback)malloc;
  203. Curl_cfree = (curl_free_callback)free;
  204. Curl_crealloc = (curl_realloc_callback)realloc;
  205. Curl_cstrdup = (curl_strdup_callback)system_strdup;
  206. Curl_ccalloc = (curl_calloc_callback)calloc;
  207. #if defined(WIN32) && defined(UNICODE)
  208. Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
  209. #endif
  210. if(flags & CURL_GLOBAL_SSL)
  211. if(!Curl_ssl_init()) {
  212. DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n"));
  213. return CURLE_FAILED_INIT;
  214. }
  215. if(flags & CURL_GLOBAL_WIN32)
  216. if(win32_init()) {
  217. DEBUGF(fprintf(stderr, "Error: win32_init failed\n"));
  218. return CURLE_FAILED_INIT;
  219. }
  220. #ifdef __AMIGA__
  221. if(!Curl_amiga_init()) {
  222. DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n"));
  223. return CURLE_FAILED_INIT;
  224. }
  225. #endif
  226. #ifdef NETWARE
  227. if(netware_init()) {
  228. DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n"));
  229. }
  230. #endif
  231. #ifdef USE_LIBIDN
  232. idna_init();
  233. #endif
  234. if(Curl_resolver_global_init()) {
  235. DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
  236. return CURLE_FAILED_INIT;
  237. }
  238. #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_INIT)
  239. if(libssh2_init(0)) {
  240. DEBUGF(fprintf(stderr, "Error: libssh2_init failed\n"));
  241. return CURLE_FAILED_INIT;
  242. }
  243. #endif
  244. if(flags & CURL_GLOBAL_ACK_EINTR)
  245. Curl_ack_eintr = 1;
  246. init_flags = flags;
  247. return CURLE_OK;
  248. }
  249. /*
  250. * curl_global_init_mem() globally initializes cURL and also registers the
  251. * user provided callback routines.
  252. */
  253. CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
  254. curl_free_callback f, curl_realloc_callback r,
  255. curl_strdup_callback s, curl_calloc_callback c)
  256. {
  257. CURLcode result = CURLE_OK;
  258. /* Invalid input, return immediately */
  259. if(!m || !f || !r || !s || !c)
  260. return CURLE_FAILED_INIT;
  261. if(initialized) {
  262. /* Already initialized, don't do it again, but bump the variable anyway to
  263. work like curl_global_init() and require the same amount of cleanup
  264. calls. */
  265. initialized++;
  266. return CURLE_OK;
  267. }
  268. /* Call the actual init function first */
  269. result = curl_global_init(flags);
  270. if(!result) {
  271. Curl_cmalloc = m;
  272. Curl_cfree = f;
  273. Curl_cstrdup = s;
  274. Curl_crealloc = r;
  275. Curl_ccalloc = c;
  276. }
  277. return result;
  278. }
  279. /**
  280. * curl_global_cleanup() globally cleanups cURL, uses the value of
  281. * "init_flags" to determine what needs to be cleaned up and what doesn't.
  282. */
  283. void curl_global_cleanup(void)
  284. {
  285. if(!initialized)
  286. return;
  287. if(--initialized)
  288. return;
  289. Curl_global_host_cache_dtor();
  290. if(init_flags & CURL_GLOBAL_SSL)
  291. Curl_ssl_cleanup();
  292. Curl_resolver_global_cleanup();
  293. if(init_flags & CURL_GLOBAL_WIN32)
  294. win32_cleanup();
  295. Curl_amiga_cleanup();
  296. #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_EXIT)
  297. (void)libssh2_exit();
  298. #endif
  299. init_flags = 0;
  300. }
  301. /*
  302. * curl_easy_init() is the external interface to alloc, setup and init an
  303. * easy handle that is returned. If anything goes wrong, NULL is returned.
  304. */
  305. CURL *curl_easy_init(void)
  306. {
  307. CURLcode result;
  308. struct SessionHandle *data;
  309. /* Make sure we inited the global SSL stuff */
  310. if(!initialized) {
  311. result = curl_global_init(CURL_GLOBAL_DEFAULT);
  312. if(result) {
  313. /* something in the global init failed, return nothing */
  314. DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
  315. return NULL;
  316. }
  317. }
  318. /* We use curl_open() with undefined URL so far */
  319. result = Curl_open(&data);
  320. if(result) {
  321. DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
  322. return NULL;
  323. }
  324. return data;
  325. }
  326. /*
  327. * curl_easy_setopt() is the external interface for setting options on an
  328. * easy handle.
  329. */
  330. #undef curl_easy_setopt
  331. CURLcode curl_easy_setopt(CURL *curl, CURLoption tag, ...)
  332. {
  333. va_list arg;
  334. struct SessionHandle *data = curl;
  335. CURLcode result;
  336. if(!curl)
  337. return CURLE_BAD_FUNCTION_ARGUMENT;
  338. va_start(arg, tag);
  339. result = Curl_setopt(data, tag, arg);
  340. va_end(arg);
  341. return result;
  342. }
  343. #ifdef CURLDEBUG
  344. struct socketmonitor {
  345. struct socketmonitor *next; /* the next node in the list or NULL */
  346. struct pollfd socket; /* socket info of what to monitor */
  347. };
  348. struct events {
  349. long ms; /* timeout, run the timeout function when reached */
  350. bool msbump; /* set TRUE when timeout is set by callback */
  351. int num_sockets; /* number of nodes in the monitor list */
  352. struct socketmonitor *list; /* list of sockets to monitor */
  353. int running_handles; /* store the returned number */
  354. };
  355. /* events_timer
  356. *
  357. * Callback that gets called with a new value when the timeout should be
  358. * updated.
  359. */
  360. static int events_timer(CURLM *multi, /* multi handle */
  361. long timeout_ms, /* see above */
  362. void *userp) /* private callback pointer */
  363. {
  364. struct events *ev = userp;
  365. (void)multi;
  366. if(timeout_ms == -1)
  367. /* timeout removed */
  368. timeout_ms = 0;
  369. else if(timeout_ms == 0)
  370. /* timeout is already reached! */
  371. timeout_ms = 1; /* trigger asap */
  372. ev->ms = timeout_ms;
  373. ev->msbump = TRUE;
  374. return 0;
  375. }
  376. /* poll2cselect
  377. *
  378. * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
  379. */
  380. static int poll2cselect(int pollmask)
  381. {
  382. int omask=0;
  383. if(pollmask & POLLIN)
  384. omask |= CURL_CSELECT_IN;
  385. if(pollmask & POLLOUT)
  386. omask |= CURL_CSELECT_OUT;
  387. if(pollmask & POLLERR)
  388. omask |= CURL_CSELECT_ERR;
  389. return omask;
  390. }
  391. /* socketcb2poll
  392. *
  393. * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
  394. */
  395. static short socketcb2poll(int pollmask)
  396. {
  397. short omask=0;
  398. if(pollmask & CURL_POLL_IN)
  399. omask |= POLLIN;
  400. if(pollmask & CURL_POLL_OUT)
  401. omask |= POLLOUT;
  402. return omask;
  403. }
  404. /* events_socket
  405. *
  406. * Callback that gets called with information about socket activity to
  407. * monitor.
  408. */
  409. static int events_socket(CURL *easy, /* easy handle */
  410. curl_socket_t s, /* socket */
  411. int what, /* see above */
  412. void *userp, /* private callback
  413. pointer */
  414. void *socketp) /* private socket
  415. pointer */
  416. {
  417. struct events *ev = userp;
  418. struct socketmonitor *m;
  419. struct socketmonitor *prev=NULL;
  420. (void)socketp;
  421. m = ev->list;
  422. while(m) {
  423. if(m->socket.fd == s) {
  424. if(what == CURL_POLL_REMOVE) {
  425. struct socketmonitor *nxt = m->next;
  426. /* remove this node from the list of monitored sockets */
  427. if(prev)
  428. prev->next = nxt;
  429. else
  430. ev->list = nxt;
  431. free(m);
  432. m = nxt;
  433. infof(easy, "socket cb: socket %d REMOVED\n", s);
  434. }
  435. else {
  436. /* The socket 's' is already being monitored, update the activity
  437. mask. Convert from libcurl bitmask to the poll one. */
  438. m->socket.events = socketcb2poll(what);
  439. infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s,
  440. what&CURL_POLL_IN?"IN":"",
  441. what&CURL_POLL_OUT?"OUT":"");
  442. }
  443. break;
  444. }
  445. prev = m;
  446. m = m->next; /* move to next node */
  447. }
  448. if(!m) {
  449. if(what == CURL_POLL_REMOVE) {
  450. /* this happens a bit too often, libcurl fix perhaps? */
  451. /* fprintf(stderr,
  452. "%s: socket %d asked to be REMOVED but not present!\n",
  453. __func__, s); */
  454. }
  455. else {
  456. m = malloc(sizeof(struct socketmonitor));
  457. m->next = ev->list;
  458. m->socket.fd = s;
  459. m->socket.events = socketcb2poll(what);
  460. m->socket.revents = 0;
  461. ev->list = m;
  462. infof(easy, "socket cb: socket %d ADDED as %s%s\n", s,
  463. what&CURL_POLL_IN?"IN":"",
  464. what&CURL_POLL_OUT?"OUT":"");
  465. }
  466. }
  467. return 0;
  468. }
  469. /*
  470. * events_setup()
  471. *
  472. * Do the multi handle setups that only event-based transfers need.
  473. */
  474. static void events_setup(CURLM *multi, struct events *ev)
  475. {
  476. /* timer callback */
  477. curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
  478. curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
  479. /* socket callback */
  480. curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
  481. curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
  482. }
  483. /* wait_or_timeout()
  484. *
  485. * waits for activity on any of the given sockets, or the timeout to trigger.
  486. */
  487. static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
  488. {
  489. bool done = FALSE;
  490. CURLMcode mcode;
  491. CURLcode result = CURLE_OK;
  492. while(!done) {
  493. CURLMsg *msg;
  494. struct socketmonitor *m;
  495. struct pollfd *f;
  496. struct pollfd fds[4];
  497. int numfds=0;
  498. int pollrc;
  499. int i;
  500. struct timeval before;
  501. struct timeval after;
  502. /* populate the fds[] array */
  503. for(m = ev->list, f=&fds[0]; m; m = m->next) {
  504. f->fd = m->socket.fd;
  505. f->events = m->socket.events;
  506. f->revents = 0;
  507. /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
  508. f++;
  509. numfds++;
  510. }
  511. /* get the time stamp to use to figure out how long poll takes */
  512. before = curlx_tvnow();
  513. /* wait for activity or timeout */
  514. pollrc = Curl_poll(fds, numfds, (int)ev->ms);
  515. after = curlx_tvnow();
  516. ev->msbump = FALSE; /* reset here */
  517. if(0 == pollrc) {
  518. /* timeout! */
  519. ev->ms = 0;
  520. /* fprintf(stderr, "call curl_multi_socket_action( TIMEOUT )\n"); */
  521. mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
  522. &ev->running_handles);
  523. }
  524. else if(pollrc > 0) {
  525. /* loop over the monitored sockets to see which ones had activity */
  526. for(i = 0; i< numfds; i++) {
  527. if(fds[i].revents) {
  528. /* socket activity, tell libcurl */
  529. int act = poll2cselect(fds[i].revents); /* convert */
  530. infof(multi->easyp, "call curl_multi_socket_action( socket %d )\n",
  531. fds[i].fd);
  532. mcode = curl_multi_socket_action(multi, fds[i].fd, act,
  533. &ev->running_handles);
  534. }
  535. }
  536. if(!ev->msbump)
  537. /* If nothing updated the timeout, we decrease it by the spent time.
  538. * If it was updated, it has the new timeout time stored already.
  539. */
  540. ev->ms += curlx_tvdiff(after, before);
  541. }
  542. else
  543. return CURLE_RECV_ERROR;
  544. if(mcode)
  545. return CURLE_URL_MALFORMAT; /* TODO: return a proper error! */
  546. /* we don't really care about the "msgs_in_queue" value returned in the
  547. second argument */
  548. msg = curl_multi_info_read(multi, &pollrc);
  549. if(msg) {
  550. result = msg->data.result;
  551. done = TRUE;
  552. }
  553. }
  554. return result;
  555. }
  556. /* easy_events()
  557. *
  558. * Runs a transfer in a blocking manner using the events-based API
  559. */
  560. static CURLcode easy_events(CURLM *multi)
  561. {
  562. struct events evs= {2, FALSE, 0, NULL, 0};
  563. /* if running event-based, do some further multi inits */
  564. events_setup(multi, &evs);
  565. return wait_or_timeout(multi, &evs);
  566. }
  567. #else /* CURLDEBUG */
  568. /* when not built with debug, this function doesn't exist */
  569. #define easy_events(x) CURLE_NOT_BUILT_IN
  570. #endif
  571. static CURLcode easy_transfer(CURLM *multi)
  572. {
  573. bool done = FALSE;
  574. CURLMcode mcode = CURLM_OK;
  575. CURLcode result = CURLE_OK;
  576. struct timeval before;
  577. int without_fds = 0; /* count number of consecutive returns from
  578. curl_multi_wait() without any filedescriptors */
  579. while(!done && !mcode) {
  580. int still_running = 0;
  581. int ret;
  582. before = curlx_tvnow();
  583. mcode = curl_multi_wait(multi, NULL, 0, 1000, &ret);
  584. if(mcode == CURLM_OK) {
  585. if(ret == -1) {
  586. /* poll() failed not on EINTR, indicate a network problem */
  587. result = CURLE_RECV_ERROR;
  588. break;
  589. }
  590. else if(ret == 0) {
  591. struct timeval after = curlx_tvnow();
  592. /* If it returns without any filedescriptor instantly, we need to
  593. avoid busy-looping during periods where it has nothing particular
  594. to wait for */
  595. if(curlx_tvdiff(after, before) <= 10) {
  596. without_fds++;
  597. if(without_fds > 2) {
  598. int sleep_ms = without_fds < 10 ? (1 << (without_fds-1)): 1000;
  599. Curl_wait_ms(sleep_ms);
  600. }
  601. }
  602. else
  603. /* it wasn't "instant", restart counter */
  604. without_fds = 0;
  605. }
  606. else
  607. /* got file descriptor, restart counter */
  608. without_fds = 0;
  609. mcode = curl_multi_perform(multi, &still_running);
  610. }
  611. /* only read 'still_running' if curl_multi_perform() return OK */
  612. if((mcode == CURLM_OK) && !still_running) {
  613. int rc;
  614. CURLMsg *msg = curl_multi_info_read(multi, &rc);
  615. if(msg) {
  616. result = msg->data.result;
  617. done = TRUE;
  618. }
  619. }
  620. }
  621. /* Make sure to return some kind of error if there was a multi problem */
  622. if(mcode) {
  623. return (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY :
  624. /* The other multi errors should never happen, so return
  625. something suitably generic */
  626. CURLE_BAD_FUNCTION_ARGUMENT;
  627. }
  628. return result;
  629. }
  630. /*
  631. * easy_perform() is the external interface that performs a blocking
  632. * transfer as previously setup.
  633. *
  634. * CONCEPT: This function creates a multi handle, adds the easy handle to it,
  635. * runs curl_multi_perform() until the transfer is done, then detaches the
  636. * easy handle, destroys the multi handle and returns the easy handle's return
  637. * code.
  638. *
  639. * REALITY: it can't just create and destroy the multi handle that easily. It
  640. * needs to keep it around since if this easy handle is used again by this
  641. * function, the same multi handle must be re-used so that the same pools and
  642. * caches can be used.
  643. *
  644. * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
  645. * instead of curl_multi_perform() and use curl_multi_socket_action().
  646. */
  647. static CURLcode easy_perform(struct SessionHandle *data, bool events)
  648. {
  649. CURLM *multi;
  650. CURLMcode mcode;
  651. CURLcode result = CURLE_OK;
  652. SIGPIPE_VARIABLE(pipe_st);
  653. if(!data)
  654. return CURLE_BAD_FUNCTION_ARGUMENT;
  655. if(data->multi) {
  656. failf(data, "easy handle already used in multi handle");
  657. return CURLE_FAILED_INIT;
  658. }
  659. if(data->multi_easy)
  660. multi = data->multi_easy;
  661. else {
  662. /* this multi handle will only ever have a single easy handled attached
  663. to it, so make it use minimal hashes */
  664. multi = Curl_multi_handle(1, 3);
  665. if(!multi)
  666. return CURLE_OUT_OF_MEMORY;
  667. data->multi_easy = multi;
  668. }
  669. /* Copy the MAXCONNECTS option to the multi handle */
  670. curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
  671. mcode = curl_multi_add_handle(multi, data);
  672. if(mcode) {
  673. curl_multi_cleanup(multi);
  674. if(mcode == CURLM_OUT_OF_MEMORY)
  675. return CURLE_OUT_OF_MEMORY;
  676. else
  677. return CURLE_FAILED_INIT;
  678. }
  679. sigpipe_ignore(data, &pipe_st);
  680. /* assign this after curl_multi_add_handle() since that function checks for
  681. it and rejects this handle otherwise */
  682. data->multi = multi;
  683. /* run the transfer */
  684. result = events ? easy_events(multi) : easy_transfer(multi);
  685. /* ignoring the return code isn't nice, but atm we can't really handle
  686. a failure here, room for future improvement! */
  687. (void)curl_multi_remove_handle(multi, data);
  688. sigpipe_restore(&pipe_st);
  689. /* The multi handle is kept alive, owned by the easy handle */
  690. return result;
  691. }
  692. /*
  693. * curl_easy_perform() is the external interface that performs a blocking
  694. * transfer as previously setup.
  695. */
  696. CURLcode curl_easy_perform(CURL *easy)
  697. {
  698. return easy_perform(easy, FALSE);
  699. }
  700. #ifdef CURLDEBUG
  701. /*
  702. * curl_easy_perform_ev() is the external interface that performs a blocking
  703. * transfer using the event-based API internally.
  704. */
  705. CURLcode curl_easy_perform_ev(CURL *easy)
  706. {
  707. return easy_perform(easy, TRUE);
  708. }
  709. #endif
  710. /*
  711. * curl_easy_cleanup() is the external interface to cleaning/freeing the given
  712. * easy handle.
  713. */
  714. void curl_easy_cleanup(CURL *curl)
  715. {
  716. struct SessionHandle *data = (struct SessionHandle *)curl;
  717. SIGPIPE_VARIABLE(pipe_st);
  718. if(!data)
  719. return;
  720. sigpipe_ignore(data, &pipe_st);
  721. Curl_close(data);
  722. sigpipe_restore(&pipe_st);
  723. }
  724. /*
  725. * curl_easy_getinfo() is an external interface that allows an app to retrieve
  726. * information from a performed transfer and similar.
  727. */
  728. #undef curl_easy_getinfo
  729. CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...)
  730. {
  731. va_list arg;
  732. void *paramp;
  733. CURLcode result;
  734. struct SessionHandle *data = (struct SessionHandle *)curl;
  735. va_start(arg, info);
  736. paramp = va_arg(arg, void *);
  737. result = Curl_getinfo(data, info, paramp);
  738. va_end(arg);
  739. return result;
  740. }
  741. /*
  742. * curl_easy_duphandle() is an external interface to allow duplication of a
  743. * given input easy handle. The returned handle will be a new working handle
  744. * with all options set exactly as the input source handle.
  745. */
  746. CURL *curl_easy_duphandle(CURL *incurl)
  747. {
  748. struct SessionHandle *data=(struct SessionHandle *)incurl;
  749. struct SessionHandle *outcurl = calloc(1, sizeof(struct SessionHandle));
  750. if(NULL == outcurl)
  751. goto fail;
  752. /*
  753. * We setup a few buffers we need. We should probably make them
  754. * get setup on-demand in the code, as that would probably decrease
  755. * the likeliness of us forgetting to init a buffer here in the future.
  756. */
  757. outcurl->state.headerbuff = malloc(HEADERSIZE);
  758. if(!outcurl->state.headerbuff)
  759. goto fail;
  760. outcurl->state.headersize = HEADERSIZE;
  761. /* copy all userdefined values */
  762. if(Curl_dupset(outcurl, data))
  763. goto fail;
  764. /* the connection cache is setup on demand */
  765. outcurl->state.conn_cache = NULL;
  766. outcurl->state.lastconnect = NULL;
  767. outcurl->progress.flags = data->progress.flags;
  768. outcurl->progress.callback = data->progress.callback;
  769. if(data->cookies) {
  770. /* If cookies are enabled in the parent handle, we enable them
  771. in the clone as well! */
  772. outcurl->cookies = Curl_cookie_init(data,
  773. data->cookies->filename,
  774. outcurl->cookies,
  775. data->set.cookiesession);
  776. if(!outcurl->cookies)
  777. goto fail;
  778. }
  779. /* duplicate all values in 'change' */
  780. if(data->change.cookielist) {
  781. outcurl->change.cookielist =
  782. Curl_slist_duplicate(data->change.cookielist);
  783. if(!outcurl->change.cookielist)
  784. goto fail;
  785. }
  786. if(data->change.url) {
  787. outcurl->change.url = strdup(data->change.url);
  788. if(!outcurl->change.url)
  789. goto fail;
  790. outcurl->change.url_alloc = TRUE;
  791. }
  792. if(data->change.referer) {
  793. outcurl->change.referer = strdup(data->change.referer);
  794. if(!outcurl->change.referer)
  795. goto fail;
  796. outcurl->change.referer_alloc = TRUE;
  797. }
  798. /* Clone the resolver handle, if present, for the new handle */
  799. if(Curl_resolver_duphandle(&outcurl->state.resolver,
  800. data->state.resolver))
  801. goto fail;
  802. Curl_convert_setup(outcurl);
  803. outcurl->magic = CURLEASY_MAGIC_NUMBER;
  804. /* we reach this point and thus we are OK */
  805. return outcurl;
  806. fail:
  807. if(outcurl) {
  808. curl_slist_free_all(outcurl->change.cookielist);
  809. outcurl->change.cookielist = NULL;
  810. Curl_safefree(outcurl->state.headerbuff);
  811. Curl_safefree(outcurl->change.url);
  812. Curl_safefree(outcurl->change.referer);
  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(CURL *curl)
  823. {
  824. struct SessionHandle *data = (struct SessionHandle *)curl;
  825. Curl_safefree(data->state.pathbuffer);
  826. data->state.path = NULL;
  827. Curl_free_request_state(data);
  828. /* zero out UserDefined data: */
  829. Curl_freeset(data);
  830. memset(&data->set, 0, sizeof(struct UserDefined));
  831. (void)Curl_init_userdefined(&data->set);
  832. /* zero out Progress data: */
  833. memset(&data->progress, 0, sizeof(struct Progress));
  834. data->progress.flags |= PGRS_HIDE;
  835. data->state.current_speed = -1; /* init to negative == impossible */
  836. }
  837. /*
  838. * curl_easy_pause() allows an application to pause or unpause a specific
  839. * transfer and direction. This function sets the full new state for the
  840. * current connection this easy handle operates on.
  841. *
  842. * NOTE: if you have the receiving paused and you call this function to remove
  843. * the pausing, you may get your write callback called at this point.
  844. *
  845. * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
  846. */
  847. CURLcode curl_easy_pause(CURL *curl, int action)
  848. {
  849. struct SessionHandle *data = (struct SessionHandle *)curl;
  850. struct SingleRequest *k = &data->req;
  851. CURLcode result = CURLE_OK;
  852. /* first switch off both pause bits */
  853. int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
  854. /* set the new desired pause bits */
  855. newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
  856. ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
  857. /* put it back in the keepon */
  858. k->keepon = newstate;
  859. if(!(newstate & KEEP_RECV_PAUSE) && data->state.tempwrite) {
  860. /* we have a buffer for sending that we now seem to be able to deliver
  861. since the receive pausing is lifted! */
  862. /* get the pointer, type and length in local copies since the function may
  863. return PAUSE again and then we'll get a new copy allocted and stored in
  864. the tempwrite variables */
  865. char *tempwrite = data->state.tempwrite;
  866. char *freewrite = tempwrite; /* store this pointer to free it later */
  867. size_t tempsize = data->state.tempwritesize;
  868. int temptype = data->state.tempwritetype;
  869. size_t chunklen;
  870. /* clear tempwrite here just to make sure it gets cleared if there's no
  871. further use of it, and make sure we don't clear it after the function
  872. invoke as it may have been set to a new value by then */
  873. data->state.tempwrite = NULL;
  874. /* since the write callback API is define to never exceed
  875. CURL_MAX_WRITE_SIZE bytes in a single call, and since we may in fact
  876. have more data than that in our buffer here, we must loop sending the
  877. data in multiple calls until there's no data left or we get another
  878. pause returned.
  879. A tricky part is that the function we call will "buffer" the data
  880. itself when it pauses on a particular buffer, so we may need to do some
  881. extra trickery if we get a pause return here.
  882. */
  883. do {
  884. chunklen = (tempsize > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:tempsize;
  885. result = Curl_client_write(data->easy_conn,
  886. temptype, tempwrite, chunklen);
  887. if(result)
  888. /* failures abort the loop at once */
  889. break;
  890. if(data->state.tempwrite && (tempsize - chunklen)) {
  891. /* Ouch, the reading is again paused and the block we send is now
  892. "cached". If this is the final chunk we can leave it like this, but
  893. if we have more chunks that are cached after this, we need to free
  894. the newly cached one and put back a version that is truly the entire
  895. contents that is saved for later
  896. */
  897. char *newptr;
  898. /* note that tempsize is still the size as before the callback was
  899. used, and thus the whole piece of data to keep */
  900. newptr = realloc(data->state.tempwrite, tempsize);
  901. if(!newptr) {
  902. free(data->state.tempwrite); /* free old area */
  903. data->state.tempwrite = NULL;
  904. result = CURLE_OUT_OF_MEMORY;
  905. /* tempwrite will be freed further down */
  906. break;
  907. }
  908. data->state.tempwrite = newptr; /* store new pointer */
  909. memcpy(newptr, tempwrite, tempsize);
  910. data->state.tempwritesize = tempsize; /* store new size */
  911. /* tempwrite will be freed further down */
  912. break; /* go back to pausing until further notice */
  913. }
  914. else {
  915. tempsize -= chunklen; /* left after the call above */
  916. tempwrite += chunklen; /* advance the pointer */
  917. }
  918. } while(!result && tempsize);
  919. free(freewrite); /* this is unconditionally no longer used */
  920. }
  921. /* if there's no error and we're not pausing both directions, we want
  922. to have this handle checked soon */
  923. if(!result &&
  924. ((newstate&(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
  925. (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) )
  926. Curl_expire(data, 1); /* get this handle going again */
  927. return result;
  928. }
  929. static CURLcode easy_connection(struct SessionHandle *data,
  930. curl_socket_t *sfd,
  931. struct connectdata **connp)
  932. {
  933. if(data == NULL)
  934. return CURLE_BAD_FUNCTION_ARGUMENT;
  935. /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
  936. if(!data->set.connect_only) {
  937. failf(data, "CONNECT_ONLY is required!");
  938. return CURLE_UNSUPPORTED_PROTOCOL;
  939. }
  940. *sfd = Curl_getconnectinfo(data, connp);
  941. if(*sfd == CURL_SOCKET_BAD) {
  942. failf(data, "Failed to get recent socket");
  943. return CURLE_UNSUPPORTED_PROTOCOL;
  944. }
  945. return CURLE_OK;
  946. }
  947. /*
  948. * Receives data from the connected socket. Use after successful
  949. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  950. * Returns CURLE_OK on success, error code on error.
  951. */
  952. CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n)
  953. {
  954. curl_socket_t sfd;
  955. CURLcode result;
  956. ssize_t n1;
  957. struct connectdata *c;
  958. struct SessionHandle *data = (struct SessionHandle *)curl;
  959. result = easy_connection(data, &sfd, &c);
  960. if(result)
  961. return result;
  962. *n = 0;
  963. result = Curl_read(c, sfd, buffer, buflen, &n1);
  964. if(result)
  965. return result;
  966. *n = (size_t)n1;
  967. return CURLE_OK;
  968. }
  969. /*
  970. * Sends data over the connected socket. Use after successful
  971. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  972. */
  973. CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen,
  974. size_t *n)
  975. {
  976. curl_socket_t sfd;
  977. CURLcode result;
  978. ssize_t n1;
  979. struct connectdata *c = NULL;
  980. struct SessionHandle *data = (struct SessionHandle *)curl;
  981. result = easy_connection(data, &sfd, &c);
  982. if(result)
  983. return result;
  984. *n = 0;
  985. result = Curl_write(c, sfd, buffer, buflen, &n1);
  986. if(n1 == -1)
  987. return CURLE_SEND_ERROR;
  988. /* detect EAGAIN */
  989. if(!result && !n1)
  990. return CURLE_AGAIN;
  991. *n = (size_t)n1;
  992. return result;
  993. }