2
0

easy.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2013, 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 err = Curl_sspi_global_init();
  122. if(err != CURLE_OK)
  123. return err;
  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() != CURLE_OK) {
  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() != CURLE_OK) {
  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 code = CURLE_OK;
  258. /* Invalid input, return immediately */
  259. if(!m || !f || !r || !s || !c)
  260. return CURLE_FAILED_INIT;
  261. /* Already initialized, don't do it again */
  262. if(initialized)
  263. return CURLE_OK;
  264. /* Call the actual init function first */
  265. code = curl_global_init(flags);
  266. if(code == CURLE_OK) {
  267. Curl_cmalloc = m;
  268. Curl_cfree = f;
  269. Curl_cstrdup = s;
  270. Curl_crealloc = r;
  271. Curl_ccalloc = c;
  272. }
  273. return code;
  274. }
  275. /**
  276. * curl_global_cleanup() globally cleanups cURL, uses the value of
  277. * "init_flags" to determine what needs to be cleaned up and what doesn't.
  278. */
  279. void curl_global_cleanup(void)
  280. {
  281. if(!initialized)
  282. return;
  283. if(--initialized)
  284. return;
  285. Curl_global_host_cache_dtor();
  286. if(init_flags & CURL_GLOBAL_SSL)
  287. Curl_ssl_cleanup();
  288. Curl_resolver_global_cleanup();
  289. if(init_flags & CURL_GLOBAL_WIN32)
  290. win32_cleanup();
  291. Curl_amiga_cleanup();
  292. #if defined(USE_LIBSSH2) && defined(HAVE_LIBSSH2_EXIT)
  293. (void)libssh2_exit();
  294. #endif
  295. init_flags = 0;
  296. }
  297. /*
  298. * curl_easy_init() is the external interface to alloc, setup and init an
  299. * easy handle that is returned. If anything goes wrong, NULL is returned.
  300. */
  301. CURL *curl_easy_init(void)
  302. {
  303. CURLcode res;
  304. struct SessionHandle *data;
  305. /* Make sure we inited the global SSL stuff */
  306. if(!initialized) {
  307. res = curl_global_init(CURL_GLOBAL_DEFAULT);
  308. if(res) {
  309. /* something in the global init failed, return nothing */
  310. DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n"));
  311. return NULL;
  312. }
  313. }
  314. /* We use curl_open() with undefined URL so far */
  315. res = Curl_open(&data);
  316. if(res != CURLE_OK) {
  317. DEBUGF(fprintf(stderr, "Error: Curl_open failed\n"));
  318. return NULL;
  319. }
  320. return data;
  321. }
  322. /*
  323. * curl_easy_setopt() is the external interface for setting options on an
  324. * easy handle.
  325. */
  326. #undef curl_easy_setopt
  327. CURLcode curl_easy_setopt(CURL *curl, CURLoption tag, ...)
  328. {
  329. va_list arg;
  330. struct SessionHandle *data = curl;
  331. CURLcode ret;
  332. if(!curl)
  333. return CURLE_BAD_FUNCTION_ARGUMENT;
  334. va_start(arg, tag);
  335. ret = Curl_setopt(data, tag, arg);
  336. va_end(arg);
  337. return ret;
  338. }
  339. #ifdef CURLDEBUG
  340. struct socketmonitor {
  341. struct socketmonitor *next; /* the next node in the list or NULL */
  342. struct pollfd socket; /* socket info of what to monitor */
  343. };
  344. struct events {
  345. long ms; /* timeout, run the timeout function when reached */
  346. bool msbump; /* set TRUE when timeout is set by callback */
  347. int num_sockets; /* number of nodes in the monitor list */
  348. struct socketmonitor *list; /* list of sockets to monitor */
  349. int running_handles; /* store the returned number */
  350. };
  351. /* events_timer
  352. *
  353. * Callback that gets called with a new value when the timeout should be
  354. * updated.
  355. */
  356. static int events_timer(CURLM *multi, /* multi handle */
  357. long timeout_ms, /* see above */
  358. void *userp) /* private callback pointer */
  359. {
  360. struct events *ev = userp;
  361. (void)multi;
  362. if(timeout_ms == -1)
  363. /* timeout removed */
  364. timeout_ms = 0;
  365. else if(timeout_ms == 0)
  366. /* timeout is already reached! */
  367. timeout_ms = 1; /* trigger asap */
  368. ev->ms = timeout_ms;
  369. ev->msbump = TRUE;
  370. return 0;
  371. }
  372. /* poll2cselect
  373. *
  374. * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones
  375. */
  376. static int poll2cselect(int pollmask)
  377. {
  378. int omask=0;
  379. if(pollmask & POLLIN)
  380. omask |= CURL_CSELECT_IN;
  381. if(pollmask & POLLOUT)
  382. omask |= CURL_CSELECT_OUT;
  383. if(pollmask & POLLERR)
  384. omask |= CURL_CSELECT_ERR;
  385. return omask;
  386. }
  387. /* socketcb2poll
  388. *
  389. * convert from libcurl' CURL_POLL_* bit definitions to poll()'s
  390. */
  391. static short socketcb2poll(int pollmask)
  392. {
  393. short omask=0;
  394. if(pollmask & CURL_POLL_IN)
  395. omask |= POLLIN;
  396. if(pollmask & CURL_POLL_OUT)
  397. omask |= POLLOUT;
  398. return omask;
  399. }
  400. /* events_socket
  401. *
  402. * Callback that gets called with information about socket activity to
  403. * monitor.
  404. */
  405. static int events_socket(CURL *easy, /* easy handle */
  406. curl_socket_t s, /* socket */
  407. int what, /* see above */
  408. void *userp, /* private callback
  409. pointer */
  410. void *socketp) /* private socket
  411. pointer */
  412. {
  413. struct events *ev = userp;
  414. struct socketmonitor *m;
  415. struct socketmonitor *prev=NULL;
  416. (void)socketp;
  417. m = ev->list;
  418. while(m) {
  419. if(m->socket.fd == s) {
  420. if(what == CURL_POLL_REMOVE) {
  421. struct socketmonitor *nxt = m->next;
  422. /* remove this node from the list of monitored sockets */
  423. if(prev)
  424. prev->next = nxt;
  425. else
  426. ev->list = nxt;
  427. free(m);
  428. m = nxt;
  429. infof(easy, "socket cb: socket %d REMOVED\n", s);
  430. }
  431. else {
  432. /* The socket 's' is already being monitored, update the activity
  433. mask. Convert from libcurl bitmask to the poll one. */
  434. m->socket.events = socketcb2poll(what);
  435. infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s,
  436. what&CURL_POLL_IN?"IN":"",
  437. what&CURL_POLL_OUT?"OUT":"");
  438. }
  439. break;
  440. }
  441. prev = m;
  442. m = m->next; /* move to next node */
  443. }
  444. if(!m) {
  445. if(what == CURL_POLL_REMOVE) {
  446. /* this happens a bit too often, libcurl fix perhaps? */
  447. /* fprintf(stderr,
  448. "%s: socket %d asked to be REMOVED but not present!\n",
  449. __func__, s); */
  450. }
  451. else {
  452. m = malloc(sizeof(struct socketmonitor));
  453. m->next = ev->list;
  454. m->socket.fd = s;
  455. m->socket.events = socketcb2poll(what);
  456. m->socket.revents = 0;
  457. ev->list = m;
  458. infof(easy, "socket cb: socket %d ADDED as %s%s\n", s,
  459. what&CURL_POLL_IN?"IN":"",
  460. what&CURL_POLL_OUT?"OUT":"");
  461. }
  462. }
  463. return 0;
  464. }
  465. /*
  466. * events_setup()
  467. *
  468. * Do the multi handle setups that only event-based transfers need.
  469. */
  470. static void events_setup(CURLM *multi, struct events *ev)
  471. {
  472. /* timer callback */
  473. curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer);
  474. curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev);
  475. /* socket callback */
  476. curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket);
  477. curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev);
  478. }
  479. /* wait_or_timeout()
  480. *
  481. * waits for activity on any of the given sockets, or the timeout to trigger.
  482. */
  483. static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
  484. {
  485. bool done = FALSE;
  486. CURLMcode mcode;
  487. CURLcode rc = CURLE_OK;
  488. while(!done) {
  489. CURLMsg *msg;
  490. struct socketmonitor *m;
  491. struct pollfd *f;
  492. struct pollfd fds[4];
  493. int numfds=0;
  494. int pollrc;
  495. int i;
  496. struct timeval before;
  497. struct timeval after;
  498. /* populate the fds[] array */
  499. for(m = ev->list, f=&fds[0]; m; m = m->next) {
  500. f->fd = m->socket.fd;
  501. f->events = m->socket.events;
  502. f->revents = 0;
  503. /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */
  504. f++;
  505. numfds++;
  506. }
  507. /* get the time stamp to use to figure out how long poll takes */
  508. before = curlx_tvnow();
  509. /* wait for activity or timeout */
  510. pollrc = Curl_poll(fds, numfds, (int)ev->ms);
  511. after = curlx_tvnow();
  512. ev->msbump = FALSE; /* reset here */
  513. if(0 == pollrc) {
  514. /* timeout! */
  515. ev->ms = 0;
  516. /* fprintf(stderr, "call curl_multi_socket_action( TIMEOUT )\n"); */
  517. mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0,
  518. &ev->running_handles);
  519. }
  520. else if(pollrc > 0) {
  521. /* loop over the monitored sockets to see which ones had activity */
  522. for(i = 0; i< numfds; i++) {
  523. if(fds[i].revents) {
  524. /* socket activity, tell libcurl */
  525. int act = poll2cselect(fds[i].revents); /* convert */
  526. infof(multi->easyp, "call curl_multi_socket_action( socket %d )\n",
  527. fds[i].fd);
  528. mcode = curl_multi_socket_action(multi, fds[i].fd, act,
  529. &ev->running_handles);
  530. }
  531. }
  532. if(!ev->msbump)
  533. /* If nothing updated the timeout, we decrease it by the spent time.
  534. * If it was updated, it has the new timeout time stored already.
  535. */
  536. ev->ms += curlx_tvdiff(after, before);
  537. }
  538. if(mcode)
  539. return CURLE_URL_MALFORMAT; /* TODO: return a proper error! */
  540. /* we don't really care about the "msgs_in_queue" value returned in the
  541. second argument */
  542. msg = curl_multi_info_read(multi, &pollrc);
  543. if(msg) {
  544. rc = msg->data.result;
  545. done = TRUE;
  546. }
  547. }
  548. return rc;
  549. }
  550. /* easy_events()
  551. *
  552. * Runs a transfer in a blocking manner using the events-based API
  553. */
  554. static CURLcode easy_events(CURLM *multi)
  555. {
  556. struct events evs= {2, FALSE, 0, NULL, 0};
  557. /* if running event-based, do some further multi inits */
  558. events_setup(multi, &evs);
  559. return wait_or_timeout(multi, &evs);
  560. }
  561. #else /* CURLDEBUG */
  562. /* when not built with debug, this function doesn't exist */
  563. #define easy_events(x) CURLE_NOT_BUILT_IN
  564. #endif
  565. static CURLcode easy_transfer(CURLM *multi)
  566. {
  567. bool done = FALSE;
  568. CURLMcode mcode = CURLM_OK;
  569. CURLcode code = CURLE_OK;
  570. struct timeval before;
  571. int without_fds = 0; /* count number of consecutive returns from
  572. curl_multi_wait() without any filedescriptors */
  573. while(!done && !mcode) {
  574. int still_running;
  575. int ret;
  576. before = curlx_tvnow();
  577. mcode = curl_multi_wait(multi, NULL, 0, 1000, &ret);
  578. if(mcode == CURLM_OK) {
  579. if(ret == -1) {
  580. /* poll() failed not on EINTR, indicate a network problem */
  581. code = CURLE_RECV_ERROR;
  582. break;
  583. }
  584. else if(ret == 0) {
  585. struct timeval after = curlx_tvnow();
  586. /* If it returns without any filedescriptor instantly, we need to
  587. avoid busy-looping during periods where it has nothing particular
  588. to wait for */
  589. if(curlx_tvdiff(after, before) <= 10) {
  590. without_fds++;
  591. if(without_fds > 2) {
  592. int sleep_ms = without_fds < 10 ? (1 << (without_fds-1)): 1000;
  593. Curl_wait_ms(sleep_ms);
  594. }
  595. }
  596. else
  597. /* it wasn't "instant", restart counter */
  598. without_fds = 0;
  599. }
  600. else
  601. /* got file descriptor, restart counter */
  602. without_fds = 0;
  603. mcode = curl_multi_perform(multi, &still_running);
  604. }
  605. /* only read 'still_running' if curl_multi_perform() return OK */
  606. if((mcode == CURLM_OK) && !still_running) {
  607. int rc;
  608. CURLMsg *msg = curl_multi_info_read(multi, &rc);
  609. if(msg) {
  610. code = msg->data.result;
  611. done = TRUE;
  612. }
  613. }
  614. }
  615. /* Make sure to return some kind of error if there was a multi problem */
  616. if(mcode) {
  617. return (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY :
  618. /* The other multi errors should never happen, so return
  619. something suitably generic */
  620. CURLE_BAD_FUNCTION_ARGUMENT;
  621. }
  622. return code;
  623. }
  624. /*
  625. * easy_perform() is the external interface that performs a blocking
  626. * transfer as previously setup.
  627. *
  628. * CONCEPT: This function creates a multi handle, adds the easy handle to it,
  629. * runs curl_multi_perform() until the transfer is done, then detaches the
  630. * easy handle, destroys the multi handle and returns the easy handle's return
  631. * code.
  632. *
  633. * REALITY: it can't just create and destroy the multi handle that easily. It
  634. * needs to keep it around since if this easy handle is used again by this
  635. * function, the same multi handle must be re-used so that the same pools and
  636. * caches can be used.
  637. *
  638. * DEBUG: if 'events' is set TRUE, this function will use a replacement engine
  639. * instead of curl_multi_perform() and use curl_multi_socket_action().
  640. */
  641. static CURLcode easy_perform(struct SessionHandle *data, bool events)
  642. {
  643. CURLM *multi;
  644. CURLMcode mcode;
  645. CURLcode code = CURLE_OK;
  646. SIGPIPE_VARIABLE(pipe_st);
  647. if(!data)
  648. return CURLE_BAD_FUNCTION_ARGUMENT;
  649. if(data->multi) {
  650. failf(data, "easy handled already used in multi handle");
  651. return CURLE_FAILED_INIT;
  652. }
  653. if(data->multi_easy)
  654. multi = data->multi_easy;
  655. else {
  656. /* this multi handle will only ever have a single easy handled attached
  657. to it, so make it use minimal hashes */
  658. multi = Curl_multi_handle(1, 3);
  659. if(!multi)
  660. return CURLE_OUT_OF_MEMORY;
  661. data->multi_easy = multi;
  662. }
  663. /* Copy the MAXCONNECTS option to the multi handle */
  664. curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects);
  665. mcode = curl_multi_add_handle(multi, data);
  666. if(mcode) {
  667. curl_multi_cleanup(multi);
  668. if(mcode == CURLM_OUT_OF_MEMORY)
  669. return CURLE_OUT_OF_MEMORY;
  670. else
  671. return CURLE_FAILED_INIT;
  672. }
  673. sigpipe_ignore(data, &pipe_st);
  674. /* assign this after curl_multi_add_handle() since that function checks for
  675. it and rejects this handle otherwise */
  676. data->multi = multi;
  677. /* run the transfer */
  678. code = events ? easy_events(multi) : easy_transfer(multi);
  679. /* ignoring the return code isn't nice, but atm we can't really handle
  680. a failure here, room for future improvement! */
  681. (void)curl_multi_remove_handle(multi, data);
  682. sigpipe_restore(&pipe_st);
  683. /* The multi handle is kept alive, owned by the easy handle */
  684. return code;
  685. }
  686. /*
  687. * curl_easy_perform() is the external interface that performs a blocking
  688. * transfer as previously setup.
  689. */
  690. CURLcode curl_easy_perform(CURL *easy)
  691. {
  692. return easy_perform(easy, FALSE);
  693. }
  694. #ifdef CURLDEBUG
  695. /*
  696. * curl_easy_perform_ev() is the external interface that performs a blocking
  697. * transfer using the event-based API internally.
  698. */
  699. CURLcode curl_easy_perform_ev(CURL *easy)
  700. {
  701. return easy_perform(easy, TRUE);
  702. }
  703. #endif
  704. /*
  705. * curl_easy_cleanup() is the external interface to cleaning/freeing the given
  706. * easy handle.
  707. */
  708. void curl_easy_cleanup(CURL *curl)
  709. {
  710. struct SessionHandle *data = (struct SessionHandle *)curl;
  711. SIGPIPE_VARIABLE(pipe_st);
  712. if(!data)
  713. return;
  714. sigpipe_ignore(data, &pipe_st);
  715. Curl_close(data);
  716. sigpipe_restore(&pipe_st);
  717. }
  718. /*
  719. * curl_easy_getinfo() is an external interface that allows an app to retrieve
  720. * information from a performed transfer and similar.
  721. */
  722. #undef curl_easy_getinfo
  723. CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...)
  724. {
  725. va_list arg;
  726. void *paramp;
  727. CURLcode ret;
  728. struct SessionHandle *data = (struct SessionHandle *)curl;
  729. va_start(arg, info);
  730. paramp = va_arg(arg, void *);
  731. ret = Curl_getinfo(data, info, paramp);
  732. va_end(arg);
  733. return ret;
  734. }
  735. /*
  736. * curl_easy_duphandle() is an external interface to allow duplication of a
  737. * given input easy handle. The returned handle will be a new working handle
  738. * with all options set exactly as the input source handle.
  739. */
  740. CURL *curl_easy_duphandle(CURL *incurl)
  741. {
  742. struct SessionHandle *data=(struct SessionHandle *)incurl;
  743. struct SessionHandle *outcurl = calloc(1, sizeof(struct SessionHandle));
  744. if(NULL == outcurl)
  745. goto fail;
  746. /*
  747. * We setup a few buffers we need. We should probably make them
  748. * get setup on-demand in the code, as that would probably decrease
  749. * the likeliness of us forgetting to init a buffer here in the future.
  750. */
  751. outcurl->state.headerbuff = malloc(HEADERSIZE);
  752. if(!outcurl->state.headerbuff)
  753. goto fail;
  754. outcurl->state.headersize = HEADERSIZE;
  755. /* copy all userdefined values */
  756. if(Curl_dupset(outcurl, data) != CURLE_OK)
  757. goto fail;
  758. /* the connection cache is setup on demand */
  759. outcurl->state.conn_cache = NULL;
  760. outcurl->state.lastconnect = NULL;
  761. outcurl->progress.flags = data->progress.flags;
  762. outcurl->progress.callback = data->progress.callback;
  763. if(data->cookies) {
  764. /* If cookies are enabled in the parent handle, we enable them
  765. in the clone as well! */
  766. outcurl->cookies = Curl_cookie_init(data,
  767. data->cookies->filename,
  768. outcurl->cookies,
  769. data->set.cookiesession);
  770. if(!outcurl->cookies)
  771. goto fail;
  772. }
  773. /* duplicate all values in 'change' */
  774. if(data->change.cookielist) {
  775. outcurl->change.cookielist =
  776. Curl_slist_duplicate(data->change.cookielist);
  777. if(!outcurl->change.cookielist)
  778. goto fail;
  779. }
  780. if(data->change.url) {
  781. outcurl->change.url = strdup(data->change.url);
  782. if(!outcurl->change.url)
  783. goto fail;
  784. outcurl->change.url_alloc = TRUE;
  785. }
  786. if(data->change.referer) {
  787. outcurl->change.referer = strdup(data->change.referer);
  788. if(!outcurl->change.referer)
  789. goto fail;
  790. outcurl->change.referer_alloc = TRUE;
  791. }
  792. /* Clone the resolver handle, if present, for the new handle */
  793. if(Curl_resolver_duphandle(&outcurl->state.resolver,
  794. data->state.resolver) != CURLE_OK)
  795. goto fail;
  796. Curl_convert_setup(outcurl);
  797. outcurl->magic = CURLEASY_MAGIC_NUMBER;
  798. /* we reach this point and thus we are OK */
  799. return outcurl;
  800. fail:
  801. if(outcurl) {
  802. curl_slist_free_all(outcurl->change.cookielist);
  803. outcurl->change.cookielist = NULL;
  804. Curl_safefree(outcurl->state.headerbuff);
  805. Curl_safefree(outcurl->change.url);
  806. Curl_safefree(outcurl->change.referer);
  807. Curl_freeset(outcurl);
  808. free(outcurl);
  809. }
  810. return NULL;
  811. }
  812. /*
  813. * curl_easy_reset() is an external interface that allows an app to re-
  814. * initialize a session handle to the default values.
  815. */
  816. void curl_easy_reset(CURL *curl)
  817. {
  818. struct SessionHandle *data = (struct SessionHandle *)curl;
  819. Curl_safefree(data->state.pathbuffer);
  820. data->state.path = NULL;
  821. Curl_free_request_state(data);
  822. /* zero out UserDefined data: */
  823. Curl_freeset(data);
  824. memset(&data->set, 0, sizeof(struct UserDefined));
  825. (void)Curl_init_userdefined(&data->set);
  826. /* zero out Progress data: */
  827. memset(&data->progress, 0, sizeof(struct Progress));
  828. data->progress.flags |= PGRS_HIDE;
  829. data->state.current_speed = -1; /* init to negative == impossible */
  830. }
  831. /*
  832. * curl_easy_pause() allows an application to pause or unpause a specific
  833. * transfer and direction. This function sets the full new state for the
  834. * current connection this easy handle operates on.
  835. *
  836. * NOTE: if you have the receiving paused and you call this function to remove
  837. * the pausing, you may get your write callback called at this point.
  838. *
  839. * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h
  840. */
  841. CURLcode curl_easy_pause(CURL *curl, int action)
  842. {
  843. struct SessionHandle *data = (struct SessionHandle *)curl;
  844. struct SingleRequest *k = &data->req;
  845. CURLcode result = CURLE_OK;
  846. /* first switch off both pause bits */
  847. int newstate = k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE);
  848. /* set the new desired pause bits */
  849. newstate |= ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) |
  850. ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0);
  851. /* put it back in the keepon */
  852. k->keepon = newstate;
  853. if(!(newstate & KEEP_RECV_PAUSE) && data->state.tempwrite) {
  854. /* we have a buffer for sending that we now seem to be able to deliver
  855. since the receive pausing is lifted! */
  856. /* get the pointer, type and length in local copies since the function may
  857. return PAUSE again and then we'll get a new copy allocted and stored in
  858. the tempwrite variables */
  859. char *tempwrite = data->state.tempwrite;
  860. char *freewrite = tempwrite; /* store this pointer to free it later */
  861. size_t tempsize = data->state.tempwritesize;
  862. int temptype = data->state.tempwritetype;
  863. size_t chunklen;
  864. /* clear tempwrite here just to make sure it gets cleared if there's no
  865. further use of it, and make sure we don't clear it after the function
  866. invoke as it may have been set to a new value by then */
  867. data->state.tempwrite = NULL;
  868. /* since the write callback API is define to never exceed
  869. CURL_MAX_WRITE_SIZE bytes in a single call, and since we may in fact
  870. have more data than that in our buffer here, we must loop sending the
  871. data in multiple calls until there's no data left or we get another
  872. pause returned.
  873. A tricky part is that the function we call will "buffer" the data
  874. itself when it pauses on a particular buffer, so we may need to do some
  875. extra trickery if we get a pause return here.
  876. */
  877. do {
  878. chunklen = (tempsize > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:tempsize;
  879. result = Curl_client_write(data->easy_conn,
  880. temptype, tempwrite, chunklen);
  881. if(result)
  882. /* failures abort the loop at once */
  883. break;
  884. if(data->state.tempwrite && (tempsize - chunklen)) {
  885. /* Ouch, the reading is again paused and the block we send is now
  886. "cached". If this is the final chunk we can leave it like this, but
  887. if we have more chunks that are cached after this, we need to free
  888. the newly cached one and put back a version that is truly the entire
  889. contents that is saved for later
  890. */
  891. char *newptr;
  892. /* note that tempsize is still the size as before the callback was
  893. used, and thus the whole piece of data to keep */
  894. newptr = realloc(data->state.tempwrite, tempsize);
  895. if(!newptr) {
  896. free(data->state.tempwrite); /* free old area */
  897. data->state.tempwrite = NULL;
  898. result = CURLE_OUT_OF_MEMORY;
  899. /* tempwrite will be freed further down */
  900. break;
  901. }
  902. data->state.tempwrite = newptr; /* store new pointer */
  903. memcpy(newptr, tempwrite, tempsize);
  904. data->state.tempwritesize = tempsize; /* store new size */
  905. /* tempwrite will be freed further down */
  906. break; /* go back to pausing until further notice */
  907. }
  908. else {
  909. tempsize -= chunklen; /* left after the call above */
  910. tempwrite += chunklen; /* advance the pointer */
  911. }
  912. } while((result == CURLE_OK) && tempsize);
  913. free(freewrite); /* this is unconditionally no longer used */
  914. }
  915. /* if there's no error and we're not pausing both directions, we want
  916. to have this handle checked soon */
  917. if(!result &&
  918. ((newstate&(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
  919. (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) )
  920. Curl_expire(data, 1); /* get this handle going again */
  921. return result;
  922. }
  923. static CURLcode easy_connection(struct SessionHandle *data,
  924. curl_socket_t *sfd,
  925. struct connectdata **connp)
  926. {
  927. if(data == NULL)
  928. return CURLE_BAD_FUNCTION_ARGUMENT;
  929. /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */
  930. if(!data->set.connect_only) {
  931. failf(data, "CONNECT_ONLY is required!");
  932. return CURLE_UNSUPPORTED_PROTOCOL;
  933. }
  934. *sfd = Curl_getconnectinfo(data, connp);
  935. if(*sfd == CURL_SOCKET_BAD) {
  936. failf(data, "Failed to get recent socket");
  937. return CURLE_UNSUPPORTED_PROTOCOL;
  938. }
  939. return CURLE_OK;
  940. }
  941. /*
  942. * Receives data from the connected socket. Use after successful
  943. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  944. * Returns CURLE_OK on success, error code on error.
  945. */
  946. CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n)
  947. {
  948. curl_socket_t sfd;
  949. CURLcode ret;
  950. ssize_t n1;
  951. struct connectdata *c;
  952. struct SessionHandle *data = (struct SessionHandle *)curl;
  953. ret = easy_connection(data, &sfd, &c);
  954. if(ret)
  955. return ret;
  956. *n = 0;
  957. ret = Curl_read(c, sfd, buffer, buflen, &n1);
  958. if(ret != CURLE_OK)
  959. return ret;
  960. *n = (size_t)n1;
  961. return CURLE_OK;
  962. }
  963. /*
  964. * Sends data over the connected socket. Use after successful
  965. * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
  966. */
  967. CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen,
  968. size_t *n)
  969. {
  970. curl_socket_t sfd;
  971. CURLcode ret;
  972. ssize_t n1;
  973. struct connectdata *c = NULL;
  974. struct SessionHandle *data = (struct SessionHandle *)curl;
  975. ret = easy_connection(data, &sfd, &c);
  976. if(ret)
  977. return ret;
  978. *n = 0;
  979. ret = Curl_write(c, sfd, buffer, buflen, &n1);
  980. if(n1 == -1)
  981. return CURLE_SEND_ERROR;
  982. /* detect EAGAIN */
  983. if((CURLE_OK == ret) && (0 == n1))
  984. return CURLE_AGAIN;
  985. *n = (size_t)n1;
  986. return ret;
  987. }