connect.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2016, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  25. #endif
  26. #ifdef HAVE_SYS_UN_H
  27. #include <sys/un.h> /* for sockaddr_un */
  28. #endif
  29. #ifdef HAVE_NETINET_TCP_H
  30. #include <netinet/tcp.h> /* for TCP_NODELAY */
  31. #endif
  32. #ifdef HAVE_SYS_IOCTL_H
  33. #include <sys/ioctl.h>
  34. #endif
  35. #ifdef HAVE_NETDB_H
  36. #include <netdb.h>
  37. #endif
  38. #ifdef HAVE_FCNTL_H
  39. #include <fcntl.h>
  40. #endif
  41. #ifdef HAVE_ARPA_INET_H
  42. #include <arpa/inet.h>
  43. #endif
  44. #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
  45. #include <sys/filio.h>
  46. #endif
  47. #ifdef NETWARE
  48. #undef in_addr_t
  49. #define in_addr_t unsigned long
  50. #endif
  51. #ifdef __VMS
  52. #include <in.h>
  53. #include <inet.h>
  54. #endif
  55. #include "urldata.h"
  56. #include "sendf.h"
  57. #include "if2ip.h"
  58. #include "strerror.h"
  59. #include "connect.h"
  60. #include "select.h"
  61. #include "url.h" /* for Curl_safefree() */
  62. #include "multiif.h"
  63. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  64. #include "inet_ntop.h"
  65. #include "inet_pton.h"
  66. #include "vtls/vtls.h" /* for Curl_ssl_check_cxn() */
  67. #include "progress.h"
  68. #include "warnless.h"
  69. #include "conncache.h"
  70. #include "multihandle.h"
  71. #include "system_win32.h"
  72. /* The last 3 #include files should be in this order */
  73. #include "curl_printf.h"
  74. #include "curl_memory.h"
  75. #include "memdebug.h"
  76. #ifdef __SYMBIAN32__
  77. /* This isn't actually supported under Symbian OS */
  78. #undef SO_NOSIGPIPE
  79. #endif
  80. static bool verifyconnect(curl_socket_t sockfd, int *error);
  81. #if defined(__DragonFly__) || defined(HAVE_WINSOCK_H)
  82. /* DragonFlyBSD and Windows use millisecond units */
  83. #define KEEPALIVE_FACTOR(x) (x *= 1000)
  84. #else
  85. #define KEEPALIVE_FACTOR(x)
  86. #endif
  87. #if defined(HAVE_WINSOCK2_H) && !defined(SIO_KEEPALIVE_VALS)
  88. #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
  89. struct tcp_keepalive {
  90. u_long onoff;
  91. u_long keepalivetime;
  92. u_long keepaliveinterval;
  93. };
  94. #endif
  95. static void
  96. tcpkeepalive(struct Curl_easy *data,
  97. curl_socket_t sockfd)
  98. {
  99. int optval = data->set.tcp_keepalive?1:0;
  100. /* only set IDLE and INTVL if setting KEEPALIVE is successful */
  101. if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
  102. (void *)&optval, sizeof(optval)) < 0) {
  103. infof(data, "Failed to set SO_KEEPALIVE on fd %d\n", sockfd);
  104. }
  105. else {
  106. #if defined(SIO_KEEPALIVE_VALS)
  107. struct tcp_keepalive vals;
  108. DWORD dummy;
  109. vals.onoff = 1;
  110. optval = curlx_sltosi(data->set.tcp_keepidle);
  111. KEEPALIVE_FACTOR(optval);
  112. vals.keepalivetime = optval;
  113. optval = curlx_sltosi(data->set.tcp_keepintvl);
  114. KEEPALIVE_FACTOR(optval);
  115. vals.keepaliveinterval = optval;
  116. if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
  117. NULL, 0, &dummy, NULL, NULL) != 0) {
  118. infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d\n",
  119. (int)sockfd, WSAGetLastError());
  120. }
  121. #else
  122. #ifdef TCP_KEEPIDLE
  123. optval = curlx_sltosi(data->set.tcp_keepidle);
  124. KEEPALIVE_FACTOR(optval);
  125. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
  126. (void *)&optval, sizeof(optval)) < 0) {
  127. infof(data, "Failed to set TCP_KEEPIDLE on fd %d\n", sockfd);
  128. }
  129. #endif
  130. #ifdef TCP_KEEPINTVL
  131. optval = curlx_sltosi(data->set.tcp_keepintvl);
  132. KEEPALIVE_FACTOR(optval);
  133. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
  134. (void *)&optval, sizeof(optval)) < 0) {
  135. infof(data, "Failed to set TCP_KEEPINTVL on fd %d\n", sockfd);
  136. }
  137. #endif
  138. #ifdef TCP_KEEPALIVE
  139. /* Mac OS X style */
  140. optval = curlx_sltosi(data->set.tcp_keepidle);
  141. KEEPALIVE_FACTOR(optval);
  142. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
  143. (void *)&optval, sizeof(optval)) < 0) {
  144. infof(data, "Failed to set TCP_KEEPALIVE on fd %d\n", sockfd);
  145. }
  146. #endif
  147. #endif
  148. }
  149. }
  150. static CURLcode
  151. singleipconnect(struct connectdata *conn,
  152. const Curl_addrinfo *ai, /* start connecting to this */
  153. curl_socket_t *sock);
  154. /*
  155. * Curl_timeleft() returns the amount of milliseconds left allowed for the
  156. * transfer/connection. If the value is negative, the timeout time has already
  157. * elapsed.
  158. *
  159. * The start time is stored in progress.t_startsingle - as set with
  160. * Curl_pgrsTime(..., TIMER_STARTSINGLE);
  161. *
  162. * If 'nowp' is non-NULL, it points to the current time.
  163. * 'duringconnect' is FALSE if not during a connect, as then of course the
  164. * connect timeout is not taken into account!
  165. *
  166. * @unittest: 1303
  167. */
  168. time_t Curl_timeleft(struct Curl_easy *data,
  169. struct timeval *nowp,
  170. bool duringconnect)
  171. {
  172. int timeout_set = 0;
  173. time_t timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
  174. struct timeval now;
  175. /* if a timeout is set, use the most restrictive one */
  176. if(data->set.timeout > 0)
  177. timeout_set |= 1;
  178. if(duringconnect && (data->set.connecttimeout > 0))
  179. timeout_set |= 2;
  180. switch(timeout_set) {
  181. case 1:
  182. timeout_ms = data->set.timeout;
  183. break;
  184. case 2:
  185. timeout_ms = data->set.connecttimeout;
  186. break;
  187. case 3:
  188. if(data->set.timeout < data->set.connecttimeout)
  189. timeout_ms = data->set.timeout;
  190. else
  191. timeout_ms = data->set.connecttimeout;
  192. break;
  193. default:
  194. /* use the default */
  195. if(!duringconnect)
  196. /* if we're not during connect, there's no default timeout so if we're
  197. at zero we better just return zero and not make it a negative number
  198. by the math below */
  199. return 0;
  200. break;
  201. }
  202. if(!nowp) {
  203. now = Curl_tvnow();
  204. nowp = &now;
  205. }
  206. /* subtract elapsed time */
  207. if(duringconnect)
  208. /* since this most recent connect started */
  209. timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startsingle);
  210. else
  211. /* since the entire operation started */
  212. timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startop);
  213. if(!timeout_ms)
  214. /* avoid returning 0 as that means no timeout! */
  215. return -1;
  216. return timeout_ms;
  217. }
  218. static CURLcode bindlocal(struct connectdata *conn,
  219. curl_socket_t sockfd, int af, unsigned int scope)
  220. {
  221. struct Curl_easy *data = conn->data;
  222. struct Curl_sockaddr_storage sa;
  223. struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
  224. curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
  225. struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
  226. #ifdef ENABLE_IPV6
  227. struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
  228. #endif
  229. struct Curl_dns_entry *h=NULL;
  230. unsigned short port = data->set.localport; /* use this port number, 0 for
  231. "random" */
  232. /* how many port numbers to try to bind to, increasing one at a time */
  233. int portnum = data->set.localportrange;
  234. const char *dev = data->set.str[STRING_DEVICE];
  235. int error;
  236. /*************************************************************
  237. * Select device to bind socket to
  238. *************************************************************/
  239. if(!dev && !port)
  240. /* no local kind of binding was requested */
  241. return CURLE_OK;
  242. memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
  243. if(dev && (strlen(dev)<255) ) {
  244. char myhost[256] = "";
  245. int done = 0; /* -1 for error, 1 for address found */
  246. bool is_interface = FALSE;
  247. bool is_host = FALSE;
  248. static const char *if_prefix = "if!";
  249. static const char *host_prefix = "host!";
  250. if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
  251. dev += strlen(if_prefix);
  252. is_interface = TRUE;
  253. }
  254. else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
  255. dev += strlen(host_prefix);
  256. is_host = TRUE;
  257. }
  258. /* interface */
  259. if(!is_host) {
  260. switch(Curl_if2ip(af, scope, conn->scope_id, dev,
  261. myhost, sizeof(myhost))) {
  262. case IF2IP_NOT_FOUND:
  263. if(is_interface) {
  264. /* Do not fall back to treating it as a host name */
  265. failf(data, "Couldn't bind to interface '%s'", dev);
  266. return CURLE_INTERFACE_FAILED;
  267. }
  268. break;
  269. case IF2IP_AF_NOT_SUPPORTED:
  270. /* Signal the caller to try another address family if available */
  271. return CURLE_UNSUPPORTED_PROTOCOL;
  272. case IF2IP_FOUND:
  273. is_interface = TRUE;
  274. /*
  275. * We now have the numerical IP address in the 'myhost' buffer
  276. */
  277. infof(data, "Local Interface %s is ip %s using address family %i\n",
  278. dev, myhost, af);
  279. done = 1;
  280. #ifdef SO_BINDTODEVICE
  281. /* I am not sure any other OSs than Linux that provide this feature,
  282. * and at the least I cannot test. --Ben
  283. *
  284. * This feature allows one to tightly bind the local socket to a
  285. * particular interface. This will force even requests to other
  286. * local interfaces to go out the external interface.
  287. *
  288. *
  289. * Only bind to the interface when specified as interface, not just
  290. * as a hostname or ip address.
  291. */
  292. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  293. dev, (curl_socklen_t)strlen(dev)+1) != 0) {
  294. error = SOCKERRNO;
  295. infof(data, "SO_BINDTODEVICE %s failed with errno %d: %s;"
  296. " will do regular bind\n",
  297. dev, error, Curl_strerror(conn, error));
  298. /* This is typically "errno 1, error: Operation not permitted" if
  299. you're not running as root or another suitable privileged
  300. user */
  301. }
  302. #endif
  303. break;
  304. }
  305. }
  306. if(!is_interface) {
  307. /*
  308. * This was not an interface, resolve the name as a host name
  309. * or IP number
  310. *
  311. * Temporarily force name resolution to use only the address type
  312. * of the connection. The resolve functions should really be changed
  313. * to take a type parameter instead.
  314. */
  315. long ipver = conn->ip_version;
  316. int rc;
  317. if(af == AF_INET)
  318. conn->ip_version = CURL_IPRESOLVE_V4;
  319. #ifdef ENABLE_IPV6
  320. else if(af == AF_INET6)
  321. conn->ip_version = CURL_IPRESOLVE_V6;
  322. #endif
  323. rc = Curl_resolv(conn, dev, 0, &h);
  324. if(rc == CURLRESOLV_PENDING)
  325. (void)Curl_resolver_wait_resolv(conn, &h);
  326. conn->ip_version = ipver;
  327. if(h) {
  328. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  329. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  330. infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
  331. dev, af, myhost, h->addr->ai_family);
  332. Curl_resolv_unlock(data, h);
  333. done = 1;
  334. }
  335. else {
  336. /*
  337. * provided dev was no interface (or interfaces are not supported
  338. * e.g. solaris) no ip address and no domain we fail here
  339. */
  340. done = -1;
  341. }
  342. }
  343. if(done > 0) {
  344. #ifdef ENABLE_IPV6
  345. /* IPv6 address */
  346. if(af == AF_INET6) {
  347. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  348. char *scope_ptr = strchr(myhost, '%');
  349. if(scope_ptr)
  350. *(scope_ptr++) = 0;
  351. #endif
  352. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  353. si6->sin6_family = AF_INET6;
  354. si6->sin6_port = htons(port);
  355. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  356. if(scope_ptr)
  357. /* The "myhost" string either comes from Curl_if2ip or from
  358. Curl_printable_address. The latter returns only numeric scope
  359. IDs and the former returns none at all. So the scope ID, if
  360. present, is known to be numeric */
  361. si6->sin6_scope_id = atoi(scope_ptr);
  362. #endif
  363. }
  364. sizeof_sa = sizeof(struct sockaddr_in6);
  365. }
  366. else
  367. #endif
  368. /* IPv4 address */
  369. if((af == AF_INET) &&
  370. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  371. si4->sin_family = AF_INET;
  372. si4->sin_port = htons(port);
  373. sizeof_sa = sizeof(struct sockaddr_in);
  374. }
  375. }
  376. if(done < 1) {
  377. failf(data, "Couldn't bind to '%s'", dev);
  378. return CURLE_INTERFACE_FAILED;
  379. }
  380. }
  381. else {
  382. /* no device was given, prepare sa to match af's needs */
  383. #ifdef ENABLE_IPV6
  384. if(af == AF_INET6) {
  385. si6->sin6_family = AF_INET6;
  386. si6->sin6_port = htons(port);
  387. sizeof_sa = sizeof(struct sockaddr_in6);
  388. }
  389. else
  390. #endif
  391. if(af == AF_INET) {
  392. si4->sin_family = AF_INET;
  393. si4->sin_port = htons(port);
  394. sizeof_sa = sizeof(struct sockaddr_in);
  395. }
  396. }
  397. for(;;) {
  398. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  399. /* we succeeded to bind */
  400. struct Curl_sockaddr_storage add;
  401. curl_socklen_t size = sizeof(add);
  402. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  403. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  404. data->state.os_errno = error = SOCKERRNO;
  405. failf(data, "getsockname() failed with errno %d: %s",
  406. error, Curl_strerror(conn, error));
  407. return CURLE_INTERFACE_FAILED;
  408. }
  409. infof(data, "Local port: %hu\n", port);
  410. conn->bits.bound = TRUE;
  411. return CURLE_OK;
  412. }
  413. if(--portnum > 0) {
  414. infof(data, "Bind to local port %hu failed, trying next\n", port);
  415. port++; /* try next port */
  416. /* We re-use/clobber the port variable here below */
  417. if(sock->sa_family == AF_INET)
  418. si4->sin_port = ntohs(port);
  419. #ifdef ENABLE_IPV6
  420. else
  421. si6->sin6_port = ntohs(port);
  422. #endif
  423. }
  424. else
  425. break;
  426. }
  427. data->state.os_errno = error = SOCKERRNO;
  428. failf(data, "bind failed with errno %d: %s",
  429. error, Curl_strerror(conn, error));
  430. return CURLE_INTERFACE_FAILED;
  431. }
  432. /*
  433. * verifyconnect() returns TRUE if the connect really has happened.
  434. */
  435. static bool verifyconnect(curl_socket_t sockfd, int *error)
  436. {
  437. bool rc = TRUE;
  438. #ifdef SO_ERROR
  439. int err = 0;
  440. curl_socklen_t errSize = sizeof(err);
  441. #ifdef WIN32
  442. /*
  443. * In October 2003 we effectively nullified this function on Windows due to
  444. * problems with it using all CPU in multi-threaded cases.
  445. *
  446. * In May 2004, we bring it back to offer more info back on connect failures.
  447. * Gisle Vanem could reproduce the former problems with this function, but
  448. * could avoid them by adding this SleepEx() call below:
  449. *
  450. * "I don't have Rational Quantify, but the hint from his post was
  451. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  452. * just Sleep(0) would be enough?) would release whatever
  453. * mutex/critical-section the ntdll call is waiting on.
  454. *
  455. * Someone got to verify this on Win-NT 4.0, 2000."
  456. */
  457. #ifdef _WIN32_WCE
  458. Sleep(0);
  459. #else
  460. SleepEx(0, FALSE);
  461. #endif
  462. #endif
  463. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  464. err = SOCKERRNO;
  465. #ifdef _WIN32_WCE
  466. /* Old WinCE versions don't support SO_ERROR */
  467. if(WSAENOPROTOOPT == err) {
  468. SET_SOCKERRNO(0);
  469. err = 0;
  470. }
  471. #endif
  472. #ifdef __minix
  473. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  474. if(EBADIOCTL == err) {
  475. SET_SOCKERRNO(0);
  476. err = 0;
  477. }
  478. #endif
  479. if((0 == err) || (EISCONN == err))
  480. /* we are connected, awesome! */
  481. rc = TRUE;
  482. else
  483. /* This wasn't a successful connect */
  484. rc = FALSE;
  485. if(error)
  486. *error = err;
  487. #else
  488. (void)sockfd;
  489. if(error)
  490. *error = SOCKERRNO;
  491. #endif
  492. return rc;
  493. }
  494. /* Used within the multi interface. Try next IP address, return TRUE if no
  495. more address exists or error */
  496. static CURLcode trynextip(struct connectdata *conn,
  497. int sockindex,
  498. int tempindex)
  499. {
  500. const int other = tempindex ^ 1;
  501. CURLcode result = CURLE_COULDNT_CONNECT;
  502. /* First clean up after the failed socket.
  503. Don't close it yet to ensure that the next IP's socket gets a different
  504. file descriptor, which can prevent bugs when the curl_multi_socket_action
  505. interface is used with certain select() replacements such as kqueue. */
  506. curl_socket_t fd_to_close = conn->tempsock[tempindex];
  507. conn->tempsock[tempindex] = CURL_SOCKET_BAD;
  508. if(sockindex == FIRSTSOCKET) {
  509. Curl_addrinfo *ai = NULL;
  510. int family = AF_UNSPEC;
  511. if(conn->tempaddr[tempindex]) {
  512. /* find next address in the same protocol family */
  513. family = conn->tempaddr[tempindex]->ai_family;
  514. ai = conn->tempaddr[tempindex]->ai_next;
  515. }
  516. #ifdef ENABLE_IPV6
  517. else if(conn->tempaddr[0]) {
  518. /* happy eyeballs - try the other protocol family */
  519. int firstfamily = conn->tempaddr[0]->ai_family;
  520. family = (firstfamily == AF_INET) ? AF_INET6 : AF_INET;
  521. ai = conn->tempaddr[0]->ai_next;
  522. }
  523. #endif
  524. while(ai) {
  525. if(conn->tempaddr[other]) {
  526. /* we can safely skip addresses of the other protocol family */
  527. while(ai && ai->ai_family != family)
  528. ai = ai->ai_next;
  529. }
  530. if(ai) {
  531. result = singleipconnect(conn, ai, &conn->tempsock[tempindex]);
  532. if(result == CURLE_COULDNT_CONNECT) {
  533. ai = ai->ai_next;
  534. continue;
  535. }
  536. conn->tempaddr[tempindex] = ai;
  537. }
  538. break;
  539. }
  540. }
  541. if(fd_to_close != CURL_SOCKET_BAD)
  542. Curl_closesocket(conn, fd_to_close);
  543. return result;
  544. }
  545. /* Copies connection info into the session handle to make it available
  546. when the session handle is no longer associated with a connection. */
  547. void Curl_persistconninfo(struct connectdata *conn)
  548. {
  549. memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
  550. memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
  551. conn->data->info.conn_scheme = conn->handler->scheme;
  552. conn->data->info.conn_protocol = conn->handler->protocol;
  553. conn->data->info.conn_primary_port = conn->primary_port;
  554. conn->data->info.conn_local_port = conn->local_port;
  555. }
  556. /* retrieves ip address and port from a sockaddr structure */
  557. static bool getaddressinfo(struct sockaddr *sa, char *addr,
  558. long *port)
  559. {
  560. unsigned short us_port;
  561. struct sockaddr_in *si = NULL;
  562. #ifdef ENABLE_IPV6
  563. struct sockaddr_in6 *si6 = NULL;
  564. #endif
  565. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  566. struct sockaddr_un *su = NULL;
  567. #endif
  568. switch(sa->sa_family) {
  569. case AF_INET:
  570. si = (struct sockaddr_in *)(void *) sa;
  571. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  572. addr, MAX_IPADR_LEN)) {
  573. us_port = ntohs(si->sin_port);
  574. *port = us_port;
  575. return TRUE;
  576. }
  577. break;
  578. #ifdef ENABLE_IPV6
  579. case AF_INET6:
  580. si6 = (struct sockaddr_in6 *)(void *) sa;
  581. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  582. addr, MAX_IPADR_LEN)) {
  583. us_port = ntohs(si6->sin6_port);
  584. *port = us_port;
  585. return TRUE;
  586. }
  587. break;
  588. #endif
  589. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  590. case AF_UNIX:
  591. su = (struct sockaddr_un*)sa;
  592. snprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  593. *port = 0;
  594. return TRUE;
  595. #endif
  596. default:
  597. break;
  598. }
  599. addr[0] = '\0';
  600. *port = 0;
  601. return FALSE;
  602. }
  603. /* retrieves the start/end point information of a socket of an established
  604. connection */
  605. void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
  606. {
  607. curl_socklen_t len;
  608. struct Curl_sockaddr_storage ssrem;
  609. struct Curl_sockaddr_storage ssloc;
  610. struct Curl_easy *data = conn->data;
  611. if(conn->socktype == SOCK_DGRAM)
  612. /* there's no connection! */
  613. return;
  614. if(!conn->bits.reuse && !conn->bits.tcp_fastopen) {
  615. int error;
  616. len = sizeof(struct Curl_sockaddr_storage);
  617. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
  618. error = SOCKERRNO;
  619. failf(data, "getpeername() failed with errno %d: %s",
  620. error, Curl_strerror(conn, error));
  621. return;
  622. }
  623. len = sizeof(struct Curl_sockaddr_storage);
  624. memset(&ssloc, 0, sizeof(ssloc));
  625. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
  626. error = SOCKERRNO;
  627. failf(data, "getsockname() failed with errno %d: %s",
  628. error, Curl_strerror(conn, error));
  629. return;
  630. }
  631. if(!getaddressinfo((struct sockaddr*)&ssrem,
  632. conn->primary_ip, &conn->primary_port)) {
  633. error = ERRNO;
  634. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  635. error, Curl_strerror(conn, error));
  636. return;
  637. }
  638. memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
  639. if(!getaddressinfo((struct sockaddr*)&ssloc,
  640. conn->local_ip, &conn->local_port)) {
  641. error = ERRNO;
  642. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  643. error, Curl_strerror(conn, error));
  644. return;
  645. }
  646. }
  647. /* persist connection info in session handle */
  648. Curl_persistconninfo(conn);
  649. }
  650. /*
  651. * Curl_is_connected() checks if the socket has connected.
  652. */
  653. CURLcode Curl_is_connected(struct connectdata *conn,
  654. int sockindex,
  655. bool *connected)
  656. {
  657. struct Curl_easy *data = conn->data;
  658. CURLcode result = CURLE_OK;
  659. time_t allow;
  660. int error = 0;
  661. struct timeval now;
  662. int rc;
  663. int i;
  664. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  665. *connected = FALSE; /* a very negative world view is best */
  666. if(conn->bits.tcpconnect[sockindex]) {
  667. /* we are connected already! */
  668. *connected = TRUE;
  669. return CURLE_OK;
  670. }
  671. now = Curl_tvnow();
  672. /* figure out how long time we have left to connect */
  673. allow = Curl_timeleft(data, &now, TRUE);
  674. if(allow < 0) {
  675. /* time-out, bail out, go home */
  676. failf(data, "Connection time-out");
  677. return CURLE_OPERATION_TIMEDOUT;
  678. }
  679. for(i=0; i<2; i++) {
  680. const int other = i ^ 1;
  681. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  682. continue;
  683. #ifdef mpeix
  684. /* Call this function once now, and ignore the results. We do this to
  685. "clear" the error state on the socket so that we can later read it
  686. reliably. This is reported necessary on the MPE/iX operating system. */
  687. (void)verifyconnect(conn->tempsock[i], NULL);
  688. #endif
  689. /* check socket for connect */
  690. rc = SOCKET_WRITABLE(conn->tempsock[i], 0);
  691. if(rc == 0) { /* no connection yet */
  692. error = 0;
  693. if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
  694. infof(data, "After %ldms connect time, move on!\n",
  695. conn->timeoutms_per_addr);
  696. error = ETIMEDOUT;
  697. }
  698. /* should we try another protocol family? */
  699. if(i == 0 && conn->tempaddr[1] == NULL &&
  700. curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) {
  701. trynextip(conn, sockindex, 1);
  702. }
  703. }
  704. else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) {
  705. if(verifyconnect(conn->tempsock[i], &error)) {
  706. /* we are connected with TCP, awesome! */
  707. /* use this socket from now on */
  708. conn->sock[sockindex] = conn->tempsock[i];
  709. conn->ip_addr = conn->tempaddr[i];
  710. conn->tempsock[i] = CURL_SOCKET_BAD;
  711. /* close the other socket, if open */
  712. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  713. Curl_closesocket(conn, conn->tempsock[other]);
  714. conn->tempsock[other] = CURL_SOCKET_BAD;
  715. }
  716. /* see if we need to do any proxy magic first once we connected */
  717. result = Curl_connected_proxy(conn, sockindex);
  718. if(result)
  719. return result;
  720. conn->bits.tcpconnect[sockindex] = TRUE;
  721. *connected = TRUE;
  722. if(sockindex == FIRSTSOCKET)
  723. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  724. Curl_updateconninfo(conn, conn->sock[sockindex]);
  725. Curl_verboseconnect(conn);
  726. return CURLE_OK;
  727. }
  728. else
  729. infof(data, "Connection failed\n");
  730. }
  731. else if(rc & CURL_CSELECT_ERR)
  732. (void)verifyconnect(conn->tempsock[i], &error);
  733. /*
  734. * The connection failed here, we should attempt to connect to the "next
  735. * address" for the given host. But first remember the latest error.
  736. */
  737. if(error) {
  738. data->state.os_errno = error;
  739. SET_SOCKERRNO(error);
  740. if(conn->tempaddr[i]) {
  741. CURLcode status;
  742. char ipaddress[MAX_IPADR_LEN];
  743. Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
  744. infof(data, "connect to %s port %ld failed: %s\n",
  745. ipaddress, conn->port, Curl_strerror(conn, error));
  746. conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
  747. allow : allow / 2;
  748. status = trynextip(conn, sockindex, i);
  749. if(status != CURLE_COULDNT_CONNECT
  750. || conn->tempsock[other] == CURL_SOCKET_BAD)
  751. /* the last attempt failed and no other sockets remain open */
  752. result = status;
  753. }
  754. }
  755. }
  756. if(result) {
  757. /* no more addresses to try */
  758. const char *hostname;
  759. /* if the first address family runs out of addresses to try before
  760. the happy eyeball timeout, go ahead and try the next family now */
  761. if(conn->tempaddr[1] == NULL) {
  762. result = trynextip(conn, sockindex, 1);
  763. if(!result)
  764. return result;
  765. }
  766. if(conn->bits.socksproxy)
  767. hostname = conn->socks_proxy.host.name;
  768. else if(conn->bits.httpproxy)
  769. hostname = conn->http_proxy.host.name;
  770. else if(conn->bits.conn_to_host)
  771. hostname = conn->conn_to_host.name;
  772. else
  773. hostname = conn->host.name;
  774. failf(data, "Failed to connect to %s port %ld: %s",
  775. hostname, conn->port, Curl_strerror(conn, error));
  776. }
  777. return result;
  778. }
  779. void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
  780. {
  781. #if defined(TCP_NODELAY)
  782. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  783. struct Curl_easy *data = conn->data;
  784. #endif
  785. curl_socklen_t onoff = (curl_socklen_t) 1;
  786. int level = IPPROTO_TCP;
  787. #if 0
  788. /* The use of getprotobyname() is disabled since it isn't thread-safe on
  789. numerous systems. On these getprotobyname_r() should be used instead, but
  790. that exists in at least one 4 arg version and one 5 arg version, and
  791. since the proto number rarely changes anyway we now just use the hard
  792. coded number. The "proper" fix would need a configure check for the
  793. correct function much in the same style the gethostbyname_r versions are
  794. detected. */
  795. struct protoent *pe = getprotobyname("tcp");
  796. if(pe)
  797. level = pe->p_proto;
  798. #endif
  799. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  800. (void) conn;
  801. #endif
  802. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  803. sizeof(onoff)) < 0)
  804. infof(data, "Could not set TCP_NODELAY: %s\n",
  805. Curl_strerror(conn, SOCKERRNO));
  806. else
  807. infof(data, "TCP_NODELAY set\n");
  808. #else
  809. (void)conn;
  810. (void)sockfd;
  811. #endif
  812. }
  813. #ifdef SO_NOSIGPIPE
  814. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  815. sending data to a dead peer (instead of relying on the 4th argument to send
  816. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  817. systems? */
  818. static void nosigpipe(struct connectdata *conn,
  819. curl_socket_t sockfd)
  820. {
  821. struct Curl_easy *data= conn->data;
  822. int onoff = 1;
  823. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  824. sizeof(onoff)) < 0)
  825. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  826. Curl_strerror(conn, SOCKERRNO));
  827. }
  828. #else
  829. #define nosigpipe(x,y) Curl_nop_stmt
  830. #endif
  831. #ifdef USE_WINSOCK
  832. /* When you run a program that uses the Windows Sockets API, you may
  833. experience slow performance when you copy data to a TCP server.
  834. https://support.microsoft.com/kb/823764
  835. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  836. Buffer Size
  837. The problem described in this knowledge-base is applied only to pre-Vista
  838. Windows. Following function trying to detect OS version and skips
  839. SO_SNDBUF adjustment for Windows Vista and above.
  840. */
  841. #define DETECT_OS_NONE 0
  842. #define DETECT_OS_PREVISTA 1
  843. #define DETECT_OS_VISTA_OR_LATER 2
  844. void Curl_sndbufset(curl_socket_t sockfd)
  845. {
  846. int val = CURL_MAX_WRITE_SIZE + 32;
  847. int curval = 0;
  848. int curlen = sizeof(curval);
  849. static int detectOsState = DETECT_OS_NONE;
  850. if(detectOsState == DETECT_OS_NONE) {
  851. if(Curl_verify_windows_version(6, 0, PLATFORM_WINNT,
  852. VERSION_GREATER_THAN_EQUAL))
  853. detectOsState = DETECT_OS_VISTA_OR_LATER;
  854. else
  855. detectOsState = DETECT_OS_PREVISTA;
  856. }
  857. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  858. return;
  859. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  860. if(curval > val)
  861. return;
  862. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  863. }
  864. #endif
  865. /*
  866. * singleipconnect()
  867. *
  868. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  869. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  870. *
  871. * singleipconnect() connects to the given IP only, and it may return without
  872. * having connected.
  873. */
  874. static CURLcode singleipconnect(struct connectdata *conn,
  875. const Curl_addrinfo *ai,
  876. curl_socket_t *sockp)
  877. {
  878. struct Curl_sockaddr_ex addr;
  879. int rc = -1;
  880. int error = 0;
  881. bool isconnected = FALSE;
  882. struct Curl_easy *data = conn->data;
  883. curl_socket_t sockfd;
  884. CURLcode result;
  885. char ipaddress[MAX_IPADR_LEN];
  886. long port;
  887. bool is_tcp;
  888. *sockp = CURL_SOCKET_BAD;
  889. result = Curl_socket(conn, ai, &addr, &sockfd);
  890. if(result)
  891. /* Failed to create the socket, but still return OK since we signal the
  892. lack of socket as well. This allows the parent function to keep looping
  893. over alternative addresses/socket families etc. */
  894. return CURLE_OK;
  895. /* store remote address and port used in this connection attempt */
  896. if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
  897. ipaddress, &port)) {
  898. /* malformed address or bug in inet_ntop, try next address */
  899. error = ERRNO;
  900. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  901. error, Curl_strerror(conn, error));
  902. Curl_closesocket(conn, sockfd);
  903. return CURLE_OK;
  904. }
  905. infof(data, " Trying %s...\n", ipaddress);
  906. #ifdef ENABLE_IPV6
  907. is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
  908. addr.socktype == SOCK_STREAM;
  909. #else
  910. is_tcp = (addr.family == AF_INET) && addr.socktype == SOCK_STREAM;
  911. #endif
  912. if(is_tcp && data->set.tcp_nodelay)
  913. Curl_tcpnodelay(conn, sockfd);
  914. nosigpipe(conn, sockfd);
  915. Curl_sndbufset(sockfd);
  916. if(is_tcp && data->set.tcp_keepalive)
  917. tcpkeepalive(data, sockfd);
  918. if(data->set.fsockopt) {
  919. /* activate callback for setting socket options */
  920. error = data->set.fsockopt(data->set.sockopt_client,
  921. sockfd,
  922. CURLSOCKTYPE_IPCXN);
  923. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  924. isconnected = TRUE;
  925. else if(error) {
  926. Curl_closesocket(conn, sockfd); /* close the socket and bail out */
  927. return CURLE_ABORTED_BY_CALLBACK;
  928. }
  929. }
  930. /* possibly bind the local end to an IP, interface or port */
  931. if(addr.family == AF_INET
  932. #ifdef ENABLE_IPV6
  933. || addr.family == AF_INET6
  934. #endif
  935. ) {
  936. result = bindlocal(conn, sockfd, addr.family,
  937. Curl_ipv6_scope((struct sockaddr*)&addr.sa_addr));
  938. if(result) {
  939. Curl_closesocket(conn, sockfd); /* close socket and bail out */
  940. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  941. /* The address family is not supported on this interface.
  942. We can continue trying addresses */
  943. return CURLE_COULDNT_CONNECT;
  944. }
  945. return result;
  946. }
  947. }
  948. /* set socket non-blocking */
  949. (void)curlx_nonblock(sockfd, TRUE);
  950. conn->connecttime = Curl_tvnow();
  951. if(conn->num_addr > 1)
  952. Curl_expire_latest(data, conn->timeoutms_per_addr);
  953. /* Connect TCP sockets, bind UDP */
  954. if(!isconnected && (conn->socktype == SOCK_STREAM)) {
  955. if(conn->bits.tcp_fastopen) {
  956. #if defined(CONNECT_DATA_IDEMPOTENT) /* OS X */
  957. sa_endpoints_t endpoints;
  958. endpoints.sae_srcif = 0;
  959. endpoints.sae_srcaddr = NULL;
  960. endpoints.sae_srcaddrlen = 0;
  961. endpoints.sae_dstaddr = &addr.sa_addr;
  962. endpoints.sae_dstaddrlen = addr.addrlen;
  963. rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
  964. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  965. NULL, 0, NULL, NULL);
  966. #elif defined(MSG_FASTOPEN) /* Linux */
  967. if(conn->given->flags & PROTOPT_SSL)
  968. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  969. else
  970. rc = 0; /* Do nothing */
  971. #endif
  972. }
  973. else {
  974. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  975. }
  976. if(-1 == rc)
  977. error = SOCKERRNO;
  978. }
  979. else {
  980. *sockp = sockfd;
  981. return CURLE_OK;
  982. }
  983. #ifdef ENABLE_IPV6
  984. conn->bits.ipv6 = (addr.family == AF_INET6)?TRUE:FALSE;
  985. #endif
  986. if(-1 == rc) {
  987. switch(error) {
  988. case EINPROGRESS:
  989. case EWOULDBLOCK:
  990. #if defined(EAGAIN)
  991. #if (EAGAIN) != (EWOULDBLOCK)
  992. /* On some platforms EAGAIN and EWOULDBLOCK are the
  993. * same value, and on others they are different, hence
  994. * the odd #if
  995. */
  996. case EAGAIN:
  997. #endif
  998. #endif
  999. result = CURLE_OK;
  1000. break;
  1001. default:
  1002. /* unknown error, fallthrough and try another address! */
  1003. infof(data, "Immediate connect fail for %s: %s\n",
  1004. ipaddress, Curl_strerror(conn, error));
  1005. data->state.os_errno = error;
  1006. /* connect failed */
  1007. Curl_closesocket(conn, sockfd);
  1008. result = CURLE_COULDNT_CONNECT;
  1009. }
  1010. }
  1011. if(!result)
  1012. *sockp = sockfd;
  1013. return result;
  1014. }
  1015. /*
  1016. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  1017. * There might be more than one IP address to try out. Fill in the passed
  1018. * pointer with the connected socket.
  1019. */
  1020. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  1021. const struct Curl_dns_entry *remotehost)
  1022. {
  1023. struct Curl_easy *data = conn->data;
  1024. struct timeval before = Curl_tvnow();
  1025. CURLcode result = CURLE_COULDNT_CONNECT;
  1026. time_t timeout_ms = Curl_timeleft(data, &before, TRUE);
  1027. if(timeout_ms < 0) {
  1028. /* a precaution, no need to continue if time already is up */
  1029. failf(data, "Connection time-out");
  1030. return CURLE_OPERATION_TIMEDOUT;
  1031. }
  1032. conn->num_addr = Curl_num_addresses(remotehost->addr);
  1033. conn->tempaddr[0] = remotehost->addr;
  1034. conn->tempaddr[1] = NULL;
  1035. conn->tempsock[0] = CURL_SOCKET_BAD;
  1036. conn->tempsock[1] = CURL_SOCKET_BAD;
  1037. Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT);
  1038. /* Max time for the next connection attempt */
  1039. conn->timeoutms_per_addr =
  1040. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1041. /* start connecting to first IP */
  1042. while(conn->tempaddr[0]) {
  1043. result = singleipconnect(conn, conn->tempaddr[0], &(conn->tempsock[0]));
  1044. if(!result)
  1045. break;
  1046. conn->tempaddr[0] = conn->tempaddr[0]->ai_next;
  1047. }
  1048. if(conn->tempsock[0] == CURL_SOCKET_BAD) {
  1049. if(!result)
  1050. result = CURLE_COULDNT_CONNECT;
  1051. return result;
  1052. }
  1053. data->info.numconnects++; /* to track the number of connections made */
  1054. return CURLE_OK;
  1055. }
  1056. struct connfind {
  1057. struct connectdata *tofind;
  1058. bool found;
  1059. };
  1060. static int conn_is_conn(struct connectdata *conn, void *param)
  1061. {
  1062. struct connfind *f = (struct connfind *)param;
  1063. if(conn == f->tofind) {
  1064. f->found = TRUE;
  1065. return 1;
  1066. }
  1067. return 0;
  1068. }
  1069. /*
  1070. * Used to extract socket and connectdata struct for the most recent
  1071. * transfer on the given Curl_easy.
  1072. *
  1073. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1074. */
  1075. curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
  1076. struct connectdata **connp)
  1077. {
  1078. curl_socket_t sockfd;
  1079. DEBUGASSERT(data);
  1080. /* this works for an easy handle:
  1081. * - that has been used for curl_easy_perform()
  1082. * - that is associated with a multi handle, and whose connection
  1083. * was detached with CURLOPT_CONNECT_ONLY
  1084. */
  1085. if(data->state.lastconnect && (data->multi_easy || data->multi)) {
  1086. struct connectdata *c = data->state.lastconnect;
  1087. struct connfind find;
  1088. find.tofind = data->state.lastconnect;
  1089. find.found = FALSE;
  1090. Curl_conncache_foreach(data->multi_easy?
  1091. &data->multi_easy->conn_cache:
  1092. &data->multi->conn_cache, &find, conn_is_conn);
  1093. if(!find.found) {
  1094. data->state.lastconnect = NULL;
  1095. return CURL_SOCKET_BAD;
  1096. }
  1097. if(connp)
  1098. /* only store this if the caller cares for it */
  1099. *connp = c;
  1100. sockfd = c->sock[FIRSTSOCKET];
  1101. }
  1102. else
  1103. return CURL_SOCKET_BAD;
  1104. return sockfd;
  1105. }
  1106. /*
  1107. * Check if a connection seems to be alive.
  1108. */
  1109. bool Curl_connalive(struct connectdata *conn)
  1110. {
  1111. /* First determine if ssl */
  1112. if(conn->ssl[FIRSTSOCKET].use) {
  1113. /* use the SSL context */
  1114. if(!Curl_ssl_check_cxn(conn))
  1115. return false; /* FIN received */
  1116. }
  1117. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1118. #ifdef MSG_PEEK
  1119. else if(conn->sock[FIRSTSOCKET] == CURL_SOCKET_BAD)
  1120. return false;
  1121. else {
  1122. /* use the socket */
  1123. char buf;
  1124. if(recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1125. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1126. return false; /* FIN received */
  1127. }
  1128. }
  1129. #endif
  1130. return true;
  1131. }
  1132. /*
  1133. * Close a socket.
  1134. *
  1135. * 'conn' can be NULL, beware!
  1136. */
  1137. int Curl_closesocket(struct connectdata *conn,
  1138. curl_socket_t sock)
  1139. {
  1140. if(conn && conn->fclosesocket) {
  1141. if((sock == conn->sock[SECONDARYSOCKET]) &&
  1142. conn->sock_accepted[SECONDARYSOCKET])
  1143. /* if this socket matches the second socket, and that was created with
  1144. accept, then we MUST NOT call the callback but clear the accepted
  1145. status */
  1146. conn->sock_accepted[SECONDARYSOCKET] = FALSE;
  1147. else {
  1148. Curl_multi_closed(conn, sock);
  1149. return conn->fclosesocket(conn->closesocket_client, sock);
  1150. }
  1151. }
  1152. if(conn)
  1153. /* tell the multi-socket code about this */
  1154. Curl_multi_closed(conn, sock);
  1155. sclose(sock);
  1156. return 0;
  1157. }
  1158. /*
  1159. * Create a socket based on info from 'conn' and 'ai'.
  1160. *
  1161. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1162. * 'sockfd' must be a pointer to a socket descriptor.
  1163. *
  1164. * If the open socket callback is set, used that!
  1165. *
  1166. */
  1167. CURLcode Curl_socket(struct connectdata *conn,
  1168. const Curl_addrinfo *ai,
  1169. struct Curl_sockaddr_ex *addr,
  1170. curl_socket_t *sockfd)
  1171. {
  1172. struct Curl_easy *data = conn->data;
  1173. struct Curl_sockaddr_ex dummy;
  1174. if(!addr)
  1175. /* if the caller doesn't want info back, use a local temp copy */
  1176. addr = &dummy;
  1177. /*
  1178. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1179. * curl_sockaddr structure with enough space available to directly hold
  1180. * any protocol-specific address structures. The variable declared here
  1181. * will be used to pass / receive data to/from the fopensocket callback
  1182. * if this has been set, before that, it is initialized from parameters.
  1183. */
  1184. addr->family = ai->ai_family;
  1185. addr->socktype = conn->socktype;
  1186. addr->protocol = conn->socktype==SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
  1187. addr->addrlen = ai->ai_addrlen;
  1188. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1189. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1190. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1191. if(data->set.fopensocket)
  1192. /*
  1193. * If the opensocket callback is set, all the destination address
  1194. * information is passed to the callback. Depending on this information the
  1195. * callback may opt to abort the connection, this is indicated returning
  1196. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1197. * the callback returns a valid socket the destination address information
  1198. * might have been changed and this 'new' address will actually be used
  1199. * here to connect.
  1200. */
  1201. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1202. CURLSOCKTYPE_IPCXN,
  1203. (struct curl_sockaddr *)addr);
  1204. else
  1205. /* opensocket callback not set, so simply create the socket now */
  1206. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1207. if(*sockfd == CURL_SOCKET_BAD)
  1208. /* no socket, no connection */
  1209. return CURLE_COULDNT_CONNECT;
  1210. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1211. if(conn->scope_id && (addr->family == AF_INET6)) {
  1212. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1213. sa6->sin6_scope_id = conn->scope_id;
  1214. }
  1215. #endif
  1216. return CURLE_OK;
  1217. }
  1218. /*
  1219. * Curl_conncontrol() marks streams or connection for closure.
  1220. */
  1221. void Curl_conncontrol(struct connectdata *conn,
  1222. int ctrl /* see defines in header */
  1223. #ifdef DEBUGBUILD
  1224. , const char *reason
  1225. #endif
  1226. )
  1227. {
  1228. /* close if a connection, or a stream that isn't multiplexed */
  1229. bool closeit = (ctrl == CONNCTRL_CONNECTION) ||
  1230. ((ctrl == CONNCTRL_STREAM) && !(conn->handler->flags & PROTOPT_STREAM));
  1231. if((ctrl == CONNCTRL_STREAM) &&
  1232. (conn->handler->flags & PROTOPT_STREAM))
  1233. DEBUGF(infof(conn->data, "Kill stream: %s\n", reason));
  1234. else if(closeit != conn->bits.close) {
  1235. DEBUGF(infof(conn->data, "Marked for [%s]: %s\n",
  1236. closeit?"closure":"keep alive", reason));
  1237. conn->bits.close = closeit; /* the only place in the source code that
  1238. should assign this bit */
  1239. }
  1240. }
  1241. /* Data received can be cached at various levels, so check them all here. */
  1242. bool Curl_conn_data_pending(struct connectdata *conn, int sockindex)
  1243. {
  1244. int readable;
  1245. if(Curl_ssl_data_pending(conn, sockindex) ||
  1246. Curl_recv_has_postponed_data(conn, sockindex))
  1247. return true;
  1248. readable = SOCKET_READABLE(conn->sock[sockindex], 0);
  1249. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1250. }