2
0

connect.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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. #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. #define _MPRINTF_REPLACE /* use our functions only */
  56. #include <curl/mprintf.h>
  57. #include "urldata.h"
  58. #include "sendf.h"
  59. #include "if2ip.h"
  60. #include "strerror.h"
  61. #include "connect.h"
  62. #include "curl_memory.h"
  63. #include "select.h"
  64. #include "url.h" /* for Curl_safefree() */
  65. #include "multiif.h"
  66. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  67. #include "inet_ntop.h"
  68. #include "inet_pton.h"
  69. #include "vtls/vtls.h" /* for Curl_ssl_check_cxn() */
  70. #include "progress.h"
  71. #include "warnless.h"
  72. #include "conncache.h"
  73. #include "multihandle.h"
  74. /* The last #include file should be: */
  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 SessionHandle *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. long Curl_timeleft(struct SessionHandle *data,
  169. struct timeval *nowp,
  170. bool duringconnect)
  171. {
  172. int timeout_set = 0;
  173. long 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)
  220. {
  221. struct SessionHandle *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, conn->scope, dev, myhost, sizeof(myhost))) {
  261. case IF2IP_NOT_FOUND:
  262. if(is_interface) {
  263. /* Do not fall back to treating it as a host name */
  264. failf(data, "Couldn't bind to interface '%s'", dev);
  265. return CURLE_INTERFACE_FAILED;
  266. }
  267. break;
  268. case IF2IP_AF_NOT_SUPPORTED:
  269. /* Signal the caller to try another address family if available */
  270. return CURLE_UNSUPPORTED_PROTOCOL;
  271. case IF2IP_FOUND:
  272. is_interface = TRUE;
  273. /*
  274. * We now have the numerical IP address in the 'myhost' buffer
  275. */
  276. infof(data, "Local Interface %s is ip %s using address family %i\n",
  277. dev, myhost, af);
  278. done = 1;
  279. #ifdef SO_BINDTODEVICE
  280. /* I am not sure any other OSs than Linux that provide this feature,
  281. * and at the least I cannot test. --Ben
  282. *
  283. * This feature allows one to tightly bind the local socket to a
  284. * particular interface. This will force even requests to other
  285. * local interfaces to go out the external interface.
  286. *
  287. *
  288. * Only bind to the interface when specified as interface, not just
  289. * as a hostname or ip address.
  290. */
  291. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  292. dev, (curl_socklen_t)strlen(dev)+1) != 0) {
  293. error = SOCKERRNO;
  294. infof(data, "SO_BINDTODEVICE %s failed with errno %d: %s;"
  295. " will do regular bind\n",
  296. dev, error, Curl_strerror(conn, error));
  297. /* This is typically "errno 1, error: Operation not permitted" if
  298. you're not running as root or another suitable privileged
  299. user */
  300. }
  301. #endif
  302. break;
  303. }
  304. }
  305. if(!is_interface) {
  306. /*
  307. * This was not an interface, resolve the name as a host name
  308. * or IP number
  309. *
  310. * Temporarily force name resolution to use only the address type
  311. * of the connection. The resolve functions should really be changed
  312. * to take a type parameter instead.
  313. */
  314. long ipver = conn->ip_version;
  315. int rc;
  316. if(af == AF_INET)
  317. conn->ip_version = CURL_IPRESOLVE_V4;
  318. #ifdef ENABLE_IPV6
  319. else if(af == AF_INET6)
  320. conn->ip_version = CURL_IPRESOLVE_V6;
  321. #endif
  322. rc = Curl_resolv(conn, dev, 0, &h);
  323. if(rc == CURLRESOLV_PENDING)
  324. (void)Curl_resolver_wait_resolv(conn, &h);
  325. conn->ip_version = ipver;
  326. if(h) {
  327. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  328. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  329. infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
  330. dev, af, myhost, h->addr->ai_family);
  331. Curl_resolv_unlock(data, h);
  332. done = 1;
  333. }
  334. else {
  335. /*
  336. * provided dev was no interface (or interfaces are not supported
  337. * e.g. solaris) no ip address and no domain we fail here
  338. */
  339. done = -1;
  340. }
  341. }
  342. if(done > 0) {
  343. #ifdef ENABLE_IPV6
  344. /* ipv6 address */
  345. if(af == AF_INET6) {
  346. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  347. char *scope_ptr = strchr(myhost, '%');
  348. if(scope_ptr)
  349. *(scope_ptr++) = 0;
  350. #endif
  351. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  352. si6->sin6_family = AF_INET6;
  353. si6->sin6_port = htons(port);
  354. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  355. if(scope_ptr)
  356. /* The "myhost" string either comes from Curl_if2ip or from
  357. Curl_printable_address. The latter returns only numeric scope
  358. IDs and the former returns none at all. So the scope ID, if
  359. present, is known to be numeric */
  360. si6->sin6_scope_id = atoi(scope_ptr);
  361. #endif
  362. }
  363. sizeof_sa = sizeof(struct sockaddr_in6);
  364. }
  365. else
  366. #endif
  367. /* ipv4 address */
  368. if((af == AF_INET) &&
  369. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  370. si4->sin_family = AF_INET;
  371. si4->sin_port = htons(port);
  372. sizeof_sa = sizeof(struct sockaddr_in);
  373. }
  374. }
  375. if(done < 1) {
  376. failf(data, "Couldn't bind to '%s'", dev);
  377. return CURLE_INTERFACE_FAILED;
  378. }
  379. }
  380. else {
  381. /* no device was given, prepare sa to match af's needs */
  382. #ifdef ENABLE_IPV6
  383. if(af == AF_INET6) {
  384. si6->sin6_family = AF_INET6;
  385. si6->sin6_port = htons(port);
  386. sizeof_sa = sizeof(struct sockaddr_in6);
  387. }
  388. else
  389. #endif
  390. if(af == AF_INET) {
  391. si4->sin_family = AF_INET;
  392. si4->sin_port = htons(port);
  393. sizeof_sa = sizeof(struct sockaddr_in);
  394. }
  395. }
  396. for(;;) {
  397. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  398. /* we succeeded to bind */
  399. struct Curl_sockaddr_storage add;
  400. curl_socklen_t size = sizeof(add);
  401. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  402. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  403. data->state.os_errno = error = SOCKERRNO;
  404. failf(data, "getsockname() failed with errno %d: %s",
  405. error, Curl_strerror(conn, error));
  406. return CURLE_INTERFACE_FAILED;
  407. }
  408. infof(data, "Local port: %hu\n", port);
  409. conn->bits.bound = TRUE;
  410. return CURLE_OK;
  411. }
  412. if(--portnum > 0) {
  413. infof(data, "Bind to local port %hu failed, trying next\n", port);
  414. port++; /* try next port */
  415. /* We re-use/clobber the port variable here below */
  416. if(sock->sa_family == AF_INET)
  417. si4->sin_port = ntohs(port);
  418. #ifdef ENABLE_IPV6
  419. else
  420. si6->sin6_port = ntohs(port);
  421. #endif
  422. }
  423. else
  424. break;
  425. }
  426. data->state.os_errno = error = SOCKERRNO;
  427. failf(data, "bind failed with errno %d: %s",
  428. error, Curl_strerror(conn, error));
  429. return CURLE_INTERFACE_FAILED;
  430. }
  431. /*
  432. * verifyconnect() returns TRUE if the connect really has happened.
  433. */
  434. static bool verifyconnect(curl_socket_t sockfd, int *error)
  435. {
  436. bool rc = TRUE;
  437. #ifdef SO_ERROR
  438. int err = 0;
  439. curl_socklen_t errSize = sizeof(err);
  440. #ifdef WIN32
  441. /*
  442. * In October 2003 we effectively nullified this function on Windows due to
  443. * problems with it using all CPU in multi-threaded cases.
  444. *
  445. * In May 2004, we bring it back to offer more info back on connect failures.
  446. * Gisle Vanem could reproduce the former problems with this function, but
  447. * could avoid them by adding this SleepEx() call below:
  448. *
  449. * "I don't have Rational Quantify, but the hint from his post was
  450. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  451. * just Sleep(0) would be enough?) would release whatever
  452. * mutex/critical-section the ntdll call is waiting on.
  453. *
  454. * Someone got to verify this on Win-NT 4.0, 2000."
  455. */
  456. #ifdef _WIN32_WCE
  457. Sleep(0);
  458. #else
  459. SleepEx(0, FALSE);
  460. #endif
  461. #endif
  462. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  463. err = SOCKERRNO;
  464. #ifdef _WIN32_WCE
  465. /* Old WinCE versions don't support SO_ERROR */
  466. if(WSAENOPROTOOPT == err) {
  467. SET_SOCKERRNO(0);
  468. err = 0;
  469. }
  470. #endif
  471. #ifdef __minix
  472. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  473. if(EBADIOCTL == err) {
  474. SET_SOCKERRNO(0);
  475. err = 0;
  476. }
  477. #endif
  478. if((0 == err) || (EISCONN == err))
  479. /* we are connected, awesome! */
  480. rc = TRUE;
  481. else
  482. /* This wasn't a successful connect */
  483. rc = FALSE;
  484. if(error)
  485. *error = err;
  486. #else
  487. (void)sockfd;
  488. if(error)
  489. *error = SOCKERRNO;
  490. #endif
  491. return rc;
  492. }
  493. /* Used within the multi interface. Try next IP address, return TRUE if no
  494. more address exists or error */
  495. static CURLcode trynextip(struct connectdata *conn,
  496. int sockindex,
  497. int tempindex)
  498. {
  499. CURLcode result = CURLE_COULDNT_CONNECT;
  500. /* First clean up after the failed socket.
  501. Don't close it yet to ensure that the next IP's socket gets a different
  502. file descriptor, which can prevent bugs when the curl_multi_socket_action
  503. interface is used with certain select() replacements such as kqueue. */
  504. curl_socket_t fd_to_close = conn->tempsock[tempindex];
  505. conn->tempsock[tempindex] = CURL_SOCKET_BAD;
  506. if(sockindex == FIRSTSOCKET) {
  507. Curl_addrinfo *ai = NULL;
  508. int family = AF_UNSPEC;
  509. if(conn->tempaddr[tempindex]) {
  510. /* find next address in the same protocol family */
  511. family = conn->tempaddr[tempindex]->ai_family;
  512. ai = conn->tempaddr[tempindex]->ai_next;
  513. }
  514. else if(conn->tempaddr[0]) {
  515. /* happy eyeballs - try the other protocol family */
  516. int firstfamily = conn->tempaddr[0]->ai_family;
  517. #ifdef ENABLE_IPV6
  518. family = (firstfamily == AF_INET) ? AF_INET6 : AF_INET;
  519. #else
  520. family = firstfamily;
  521. #endif
  522. ai = conn->tempaddr[0]->ai_next;
  523. }
  524. while(ai) {
  525. while(ai && ai->ai_family != family)
  526. ai = ai->ai_next;
  527. if(ai) {
  528. result = singleipconnect(conn, ai, &conn->tempsock[tempindex]);
  529. if(result == CURLE_COULDNT_CONNECT) {
  530. ai = ai->ai_next;
  531. continue;
  532. }
  533. conn->tempaddr[tempindex] = ai;
  534. }
  535. break;
  536. }
  537. }
  538. if(fd_to_close != CURL_SOCKET_BAD)
  539. Curl_closesocket(conn, fd_to_close);
  540. return result;
  541. }
  542. /* Copies connection info into the session handle to make it available
  543. when the session handle is no longer associated with a connection. */
  544. void Curl_persistconninfo(struct connectdata *conn)
  545. {
  546. memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
  547. memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
  548. conn->data->info.conn_primary_port = conn->primary_port;
  549. conn->data->info.conn_local_port = conn->local_port;
  550. }
  551. /* retrieves ip address and port from a sockaddr structure */
  552. static bool getaddressinfo(struct sockaddr* sa, char* addr,
  553. long* port)
  554. {
  555. unsigned short us_port;
  556. struct sockaddr_in* si = NULL;
  557. #ifdef ENABLE_IPV6
  558. struct sockaddr_in6* si6 = NULL;
  559. #endif
  560. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  561. struct sockaddr_un* su = NULL;
  562. #endif
  563. switch (sa->sa_family) {
  564. case AF_INET:
  565. si = (struct sockaddr_in*) sa;
  566. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  567. addr, MAX_IPADR_LEN)) {
  568. us_port = ntohs(si->sin_port);
  569. *port = us_port;
  570. return TRUE;
  571. }
  572. break;
  573. #ifdef ENABLE_IPV6
  574. case AF_INET6:
  575. si6 = (struct sockaddr_in6*)sa;
  576. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  577. addr, MAX_IPADR_LEN)) {
  578. us_port = ntohs(si6->sin6_port);
  579. *port = us_port;
  580. return TRUE;
  581. }
  582. break;
  583. #endif
  584. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  585. case AF_UNIX:
  586. su = (struct sockaddr_un*)sa;
  587. snprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  588. *port = 0;
  589. return TRUE;
  590. #endif
  591. default:
  592. break;
  593. }
  594. addr[0] = '\0';
  595. *port = 0;
  596. return FALSE;
  597. }
  598. /* retrieves the start/end point information of a socket of an established
  599. connection */
  600. void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
  601. {
  602. curl_socklen_t len;
  603. struct Curl_sockaddr_storage ssrem;
  604. struct Curl_sockaddr_storage ssloc;
  605. struct SessionHandle *data = conn->data;
  606. if(conn->socktype == SOCK_DGRAM)
  607. /* there's no connection! */
  608. return;
  609. if(!conn->bits.reuse) {
  610. int error;
  611. len = sizeof(struct Curl_sockaddr_storage);
  612. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
  613. error = SOCKERRNO;
  614. failf(data, "getpeername() failed with errno %d: %s",
  615. error, Curl_strerror(conn, error));
  616. return;
  617. }
  618. len = sizeof(struct Curl_sockaddr_storage);
  619. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
  620. error = SOCKERRNO;
  621. failf(data, "getsockname() failed with errno %d: %s",
  622. error, Curl_strerror(conn, error));
  623. return;
  624. }
  625. if(!getaddressinfo((struct sockaddr*)&ssrem,
  626. conn->primary_ip, &conn->primary_port)) {
  627. error = ERRNO;
  628. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  629. error, Curl_strerror(conn, error));
  630. return;
  631. }
  632. memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
  633. if(!getaddressinfo((struct sockaddr*)&ssloc,
  634. conn->local_ip, &conn->local_port)) {
  635. error = ERRNO;
  636. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  637. error, Curl_strerror(conn, error));
  638. return;
  639. }
  640. }
  641. /* persist connection info in session handle */
  642. Curl_persistconninfo(conn);
  643. }
  644. /*
  645. * Curl_is_connected() checks if the socket has connected.
  646. */
  647. CURLcode Curl_is_connected(struct connectdata *conn,
  648. int sockindex,
  649. bool *connected)
  650. {
  651. struct SessionHandle *data = conn->data;
  652. CURLcode result = CURLE_OK;
  653. long allow;
  654. int error = 0;
  655. struct timeval now;
  656. int rc;
  657. int i;
  658. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  659. *connected = FALSE; /* a very negative world view is best */
  660. if(conn->bits.tcpconnect[sockindex]) {
  661. /* we are connected already! */
  662. *connected = TRUE;
  663. return CURLE_OK;
  664. }
  665. now = Curl_tvnow();
  666. /* figure out how long time we have left to connect */
  667. allow = Curl_timeleft(data, &now, TRUE);
  668. if(allow < 0) {
  669. /* time-out, bail out, go home */
  670. failf(data, "Connection time-out");
  671. return CURLE_OPERATION_TIMEDOUT;
  672. }
  673. for(i=0; i<2; i++) {
  674. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  675. continue;
  676. #ifdef mpeix
  677. /* Call this function once now, and ignore the results. We do this to
  678. "clear" the error state on the socket so that we can later read it
  679. reliably. This is reported necessary on the MPE/iX operating system. */
  680. (void)verifyconnect(conn->tempsock[i], NULL);
  681. #endif
  682. /* check socket for connect */
  683. rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0);
  684. if(rc == 0) { /* no connection yet */
  685. if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
  686. infof(data, "After %ldms connect time, move on!\n",
  687. conn->timeoutms_per_addr);
  688. error = ETIMEDOUT;
  689. }
  690. /* should we try another protocol family? */
  691. if(i == 0 && conn->tempaddr[1] == NULL &&
  692. curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) {
  693. trynextip(conn, sockindex, 1);
  694. }
  695. }
  696. else if(rc == CURL_CSELECT_OUT) {
  697. if(verifyconnect(conn->tempsock[i], &error)) {
  698. /* we are connected with TCP, awesome! */
  699. int other = i ^ 1;
  700. /* use this socket from now on */
  701. conn->sock[sockindex] = conn->tempsock[i];
  702. conn->ip_addr = conn->tempaddr[i];
  703. conn->tempsock[i] = CURL_SOCKET_BAD;
  704. /* close the other socket, if open */
  705. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  706. Curl_closesocket(conn, conn->tempsock[other]);
  707. conn->tempsock[other] = CURL_SOCKET_BAD;
  708. }
  709. /* see if we need to do any proxy magic first once we connected */
  710. result = Curl_connected_proxy(conn, sockindex);
  711. if(result)
  712. return result;
  713. conn->bits.tcpconnect[sockindex] = TRUE;
  714. *connected = TRUE;
  715. if(sockindex == FIRSTSOCKET)
  716. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  717. Curl_updateconninfo(conn, conn->sock[sockindex]);
  718. Curl_verboseconnect(conn);
  719. return CURLE_OK;
  720. }
  721. else
  722. infof(data, "Connection failed\n");
  723. }
  724. else if(rc & CURL_CSELECT_ERR)
  725. (void)verifyconnect(conn->tempsock[i], &error);
  726. /*
  727. * The connection failed here, we should attempt to connect to the "next
  728. * address" for the given host. But first remember the latest error.
  729. */
  730. if(error) {
  731. data->state.os_errno = error;
  732. SET_SOCKERRNO(error);
  733. if(conn->tempaddr[i]) {
  734. char ipaddress[MAX_IPADR_LEN];
  735. Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
  736. infof(data, "connect to %s port %ld failed: %s\n",
  737. ipaddress, conn->port, Curl_strerror(conn, error));
  738. conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
  739. allow : allow / 2;
  740. result = trynextip(conn, sockindex, i);
  741. }
  742. }
  743. }
  744. if(result) {
  745. /* no more addresses to try */
  746. /* if the first address family runs out of addresses to try before
  747. the happy eyeball timeout, go ahead and try the next family now */
  748. if(conn->tempaddr[1] == NULL) {
  749. result = trynextip(conn, sockindex, 1);
  750. if(!result)
  751. return result;
  752. }
  753. failf(data, "Failed to connect to %s port %ld: %s",
  754. conn->bits.proxy?conn->proxy.name:conn->host.name,
  755. conn->port, Curl_strerror(conn, error));
  756. }
  757. return result;
  758. }
  759. static void tcpnodelay(struct connectdata *conn,
  760. curl_socket_t sockfd)
  761. {
  762. #ifdef TCP_NODELAY
  763. struct SessionHandle *data= conn->data;
  764. curl_socklen_t onoff = (curl_socklen_t) data->set.tcp_nodelay;
  765. int level = IPPROTO_TCP;
  766. #if 0
  767. /* The use of getprotobyname() is disabled since it isn't thread-safe on
  768. numerous systems. On these getprotobyname_r() should be used instead, but
  769. that exists in at least one 4 arg version and one 5 arg version, and
  770. since the proto number rarely changes anyway we now just use the hard
  771. coded number. The "proper" fix would need a configure check for the
  772. correct function much in the same style the gethostbyname_r versions are
  773. detected. */
  774. struct protoent *pe = getprotobyname("tcp");
  775. if(pe)
  776. level = pe->p_proto;
  777. #endif
  778. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  779. sizeof(onoff)) < 0)
  780. infof(data, "Could not set TCP_NODELAY: %s\n",
  781. Curl_strerror(conn, SOCKERRNO));
  782. else
  783. infof(data,"TCP_NODELAY set\n");
  784. #else
  785. (void)conn;
  786. (void)sockfd;
  787. #endif
  788. }
  789. #ifdef SO_NOSIGPIPE
  790. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  791. sending data to a dead peer (instead of relying on the 4th argument to send
  792. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  793. systems? */
  794. static void nosigpipe(struct connectdata *conn,
  795. curl_socket_t sockfd)
  796. {
  797. struct SessionHandle *data= conn->data;
  798. int onoff = 1;
  799. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  800. sizeof(onoff)) < 0)
  801. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  802. Curl_strerror(conn, SOCKERRNO));
  803. }
  804. #else
  805. #define nosigpipe(x,y) Curl_nop_stmt
  806. #endif
  807. #ifdef USE_WINSOCK
  808. /* When you run a program that uses the Windows Sockets API, you may
  809. experience slow performance when you copy data to a TCP server.
  810. http://support.microsoft.com/kb/823764
  811. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  812. Buffer Size
  813. The problem described in this knowledge-base is applied only to pre-Vista
  814. Windows. Following function trying to detect OS version and skips
  815. SO_SNDBUF adjustment for Windows Vista and above.
  816. */
  817. #define DETECT_OS_NONE 0
  818. #define DETECT_OS_PREVISTA 1
  819. #define DETECT_OS_VISTA_OR_LATER 2
  820. void Curl_sndbufset(curl_socket_t sockfd)
  821. {
  822. int val = CURL_MAX_WRITE_SIZE + 32;
  823. int curval = 0;
  824. int curlen = sizeof(curval);
  825. DWORD majorVersion = 6;
  826. static int detectOsState = DETECT_OS_NONE;
  827. if(detectOsState == DETECT_OS_NONE) {
  828. #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \
  829. (_WIN32_WINNT < _WIN32_WINNT_WIN2K)
  830. OSVERSIONINFO osver;
  831. memset(&osver, 0, sizeof(osver));
  832. osver.dwOSVersionInfoSize = sizeof(osver);
  833. detectOsState = DETECT_OS_PREVISTA;
  834. if(GetVersionEx(&osver)) {
  835. if(osver.dwMajorVersion >= majorVersion)
  836. detectOsState = DETECT_OS_VISTA_OR_LATER;
  837. }
  838. #else
  839. ULONGLONG majorVersionMask;
  840. OSVERSIONINFOEX osver;
  841. memset(&osver, 0, sizeof(osver));
  842. osver.dwOSVersionInfoSize = sizeof(osver);
  843. osver.dwMajorVersion = majorVersion;
  844. majorVersionMask = VerSetConditionMask(0, VER_MAJORVERSION,
  845. VER_GREATER_EQUAL);
  846. if(VerifyVersionInfo(&osver, VER_MAJORVERSION, majorVersionMask))
  847. detectOsState = DETECT_OS_VISTA_OR_LATER;
  848. else
  849. detectOsState = DETECT_OS_PREVISTA;
  850. #endif
  851. }
  852. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  853. return;
  854. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  855. if(curval > val)
  856. return;
  857. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  858. }
  859. #endif
  860. /*
  861. * singleipconnect()
  862. *
  863. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  864. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  865. *
  866. * singleipconnect() connects to the given IP only, and it may return without
  867. * having connected.
  868. */
  869. static CURLcode singleipconnect(struct connectdata *conn,
  870. const Curl_addrinfo *ai,
  871. curl_socket_t *sockp)
  872. {
  873. struct Curl_sockaddr_ex addr;
  874. int rc;
  875. int error = 0;
  876. bool isconnected = FALSE;
  877. struct SessionHandle *data = conn->data;
  878. curl_socket_t sockfd;
  879. CURLcode result;
  880. char ipaddress[MAX_IPADR_LEN];
  881. long port;
  882. *sockp = CURL_SOCKET_BAD;
  883. result = Curl_socket(conn, ai, &addr, &sockfd);
  884. if(result)
  885. /* Failed to create the socket, but still return OK since we signal the
  886. lack of socket as well. This allows the parent function to keep looping
  887. over alternative addresses/socket families etc. */
  888. return CURLE_OK;
  889. /* store remote address and port used in this connection attempt */
  890. if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
  891. ipaddress, &port)) {
  892. /* malformed address or bug in inet_ntop, try next address */
  893. error = ERRNO;
  894. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  895. error, Curl_strerror(conn, error));
  896. Curl_closesocket(conn, sockfd);
  897. return CURLE_OK;
  898. }
  899. infof(data, " Trying %s...\n", ipaddress);
  900. if(data->set.tcp_nodelay)
  901. tcpnodelay(conn, sockfd);
  902. nosigpipe(conn, sockfd);
  903. Curl_sndbufset(sockfd);
  904. if(data->set.tcp_keepalive)
  905. tcpkeepalive(data, sockfd);
  906. if(data->set.fsockopt) {
  907. /* activate callback for setting socket options */
  908. error = data->set.fsockopt(data->set.sockopt_client,
  909. sockfd,
  910. CURLSOCKTYPE_IPCXN);
  911. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  912. isconnected = TRUE;
  913. else if(error) {
  914. Curl_closesocket(conn, sockfd); /* close the socket and bail out */
  915. return CURLE_ABORTED_BY_CALLBACK;
  916. }
  917. }
  918. /* possibly bind the local end to an IP, interface or port */
  919. result = bindlocal(conn, sockfd, addr.family);
  920. if(result) {
  921. Curl_closesocket(conn, sockfd); /* close socket and bail out */
  922. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  923. /* The address family is not supported on this interface.
  924. We can continue trying addresses */
  925. return CURLE_OK;
  926. }
  927. return result;
  928. }
  929. /* set socket non-blocking */
  930. (void)curlx_nonblock(sockfd, TRUE);
  931. conn->connecttime = Curl_tvnow();
  932. if(conn->num_addr > 1)
  933. Curl_expire_latest(data, conn->timeoutms_per_addr);
  934. /* Connect TCP sockets, bind UDP */
  935. if(!isconnected && (conn->socktype == SOCK_STREAM)) {
  936. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  937. if(-1 == rc)
  938. error = SOCKERRNO;
  939. }
  940. else {
  941. *sockp = sockfd;
  942. return CURLE_OK;
  943. }
  944. #ifdef ENABLE_IPV6
  945. conn->bits.ipv6 = (addr.family == AF_INET6)?TRUE:FALSE;
  946. #endif
  947. if(-1 == rc) {
  948. switch(error) {
  949. case EINPROGRESS:
  950. case EWOULDBLOCK:
  951. #if defined(EAGAIN)
  952. #if (EAGAIN) != (EWOULDBLOCK)
  953. /* On some platforms EAGAIN and EWOULDBLOCK are the
  954. * same value, and on others they are different, hence
  955. * the odd #if
  956. */
  957. case EAGAIN:
  958. #endif
  959. #endif
  960. result = CURLE_OK;
  961. break;
  962. default:
  963. /* unknown error, fallthrough and try another address! */
  964. infof(data, "Immediate connect fail for %s: %s\n",
  965. ipaddress, Curl_strerror(conn,error));
  966. data->state.os_errno = error;
  967. /* connect failed */
  968. Curl_closesocket(conn, sockfd);
  969. result = CURLE_COULDNT_CONNECT;
  970. }
  971. }
  972. if(!result)
  973. *sockp = sockfd;
  974. return result;
  975. }
  976. /*
  977. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  978. * There might be more than one IP address to try out. Fill in the passed
  979. * pointer with the connected socket.
  980. */
  981. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  982. const struct Curl_dns_entry *remotehost)
  983. {
  984. struct SessionHandle *data = conn->data;
  985. struct timeval before = Curl_tvnow();
  986. CURLcode result = CURLE_COULDNT_CONNECT;
  987. long timeout_ms = Curl_timeleft(data, &before, TRUE);
  988. if(timeout_ms < 0) {
  989. /* a precaution, no need to continue if time already is up */
  990. failf(data, "Connection time-out");
  991. return CURLE_OPERATION_TIMEDOUT;
  992. }
  993. conn->num_addr = Curl_num_addresses(remotehost->addr);
  994. conn->tempaddr[0] = remotehost->addr;
  995. conn->tempaddr[1] = NULL;
  996. conn->tempsock[0] = CURL_SOCKET_BAD;
  997. conn->tempsock[1] = CURL_SOCKET_BAD;
  998. Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT);
  999. /* Max time for the next connection attempt */
  1000. conn->timeoutms_per_addr =
  1001. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1002. /* start connecting to first IP */
  1003. while(conn->tempaddr[0]) {
  1004. result = singleipconnect(conn, conn->tempaddr[0], &(conn->tempsock[0]));
  1005. if(!result)
  1006. break;
  1007. conn->tempaddr[0] = conn->tempaddr[0]->ai_next;
  1008. }
  1009. if(conn->tempsock[0] == CURL_SOCKET_BAD)
  1010. return result;
  1011. data->info.numconnects++; /* to track the number of connections made */
  1012. return CURLE_OK;
  1013. }
  1014. struct connfind {
  1015. struct connectdata *tofind;
  1016. bool found;
  1017. };
  1018. static int conn_is_conn(struct connectdata *conn, void *param)
  1019. {
  1020. struct connfind *f = (struct connfind *)param;
  1021. if(conn == f->tofind) {
  1022. f->found = TRUE;
  1023. return 1;
  1024. }
  1025. return 0;
  1026. }
  1027. /*
  1028. * Used to extract socket and connectdata struct for the most recent
  1029. * transfer on the given SessionHandle.
  1030. *
  1031. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1032. */
  1033. curl_socket_t Curl_getconnectinfo(struct SessionHandle *data,
  1034. struct connectdata **connp)
  1035. {
  1036. curl_socket_t sockfd;
  1037. DEBUGASSERT(data);
  1038. /* this only works for an easy handle that has been used for
  1039. curl_easy_perform()! */
  1040. if(data->state.lastconnect && data->multi_easy) {
  1041. struct connectdata *c = data->state.lastconnect;
  1042. struct connfind find;
  1043. find.tofind = data->state.lastconnect;
  1044. find.found = FALSE;
  1045. Curl_conncache_foreach(data->multi_easy->conn_cache, &find, conn_is_conn);
  1046. if(!find.found) {
  1047. data->state.lastconnect = NULL;
  1048. return CURL_SOCKET_BAD;
  1049. }
  1050. if(connp)
  1051. /* only store this if the caller cares for it */
  1052. *connp = c;
  1053. sockfd = c->sock[FIRSTSOCKET];
  1054. /* we have a socket connected, let's determine if the server shut down */
  1055. /* determine if ssl */
  1056. if(c->ssl[FIRSTSOCKET].use) {
  1057. /* use the SSL context */
  1058. if(!Curl_ssl_check_cxn(c))
  1059. return CURL_SOCKET_BAD; /* FIN received */
  1060. }
  1061. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1062. #ifdef MSG_PEEK
  1063. else {
  1064. /* use the socket */
  1065. char buf;
  1066. if(recv((RECV_TYPE_ARG1)c->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1067. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1068. return CURL_SOCKET_BAD; /* FIN received */
  1069. }
  1070. }
  1071. #endif
  1072. }
  1073. else
  1074. return CURL_SOCKET_BAD;
  1075. return sockfd;
  1076. }
  1077. /*
  1078. * Close a socket.
  1079. *
  1080. * 'conn' can be NULL, beware!
  1081. */
  1082. int Curl_closesocket(struct connectdata *conn,
  1083. curl_socket_t sock)
  1084. {
  1085. if(conn && conn->fclosesocket) {
  1086. if((sock == conn->sock[SECONDARYSOCKET]) &&
  1087. conn->sock_accepted[SECONDARYSOCKET])
  1088. /* if this socket matches the second socket, and that was created with
  1089. accept, then we MUST NOT call the callback but clear the accepted
  1090. status */
  1091. conn->sock_accepted[SECONDARYSOCKET] = FALSE;
  1092. else
  1093. return conn->fclosesocket(conn->closesocket_client, sock);
  1094. }
  1095. sclose(sock);
  1096. if(conn)
  1097. /* tell the multi-socket code about this */
  1098. Curl_multi_closed(conn, sock);
  1099. return 0;
  1100. }
  1101. /*
  1102. * Create a socket based on info from 'conn' and 'ai'.
  1103. *
  1104. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1105. * 'sockfd' must be a pointer to a socket descriptor.
  1106. *
  1107. * If the open socket callback is set, used that!
  1108. *
  1109. */
  1110. CURLcode Curl_socket(struct connectdata *conn,
  1111. const Curl_addrinfo *ai,
  1112. struct Curl_sockaddr_ex *addr,
  1113. curl_socket_t *sockfd)
  1114. {
  1115. struct SessionHandle *data = conn->data;
  1116. struct Curl_sockaddr_ex dummy;
  1117. if(!addr)
  1118. /* if the caller doesn't want info back, use a local temp copy */
  1119. addr = &dummy;
  1120. /*
  1121. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1122. * curl_sockaddr structure with enough space available to directly hold
  1123. * any protocol-specific address structures. The variable declared here
  1124. * will be used to pass / receive data to/from the fopensocket callback
  1125. * if this has been set, before that, it is initialized from parameters.
  1126. */
  1127. addr->family = ai->ai_family;
  1128. addr->socktype = conn->socktype;
  1129. addr->protocol = conn->socktype==SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
  1130. addr->addrlen = ai->ai_addrlen;
  1131. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1132. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1133. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1134. if(data->set.fopensocket)
  1135. /*
  1136. * If the opensocket callback is set, all the destination address
  1137. * information is passed to the callback. Depending on this information the
  1138. * callback may opt to abort the connection, this is indicated returning
  1139. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1140. * the callback returns a valid socket the destination address information
  1141. * might have been changed and this 'new' address will actually be used
  1142. * here to connect.
  1143. */
  1144. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1145. CURLSOCKTYPE_IPCXN,
  1146. (struct curl_sockaddr *)addr);
  1147. else
  1148. /* opensocket callback not set, so simply create the socket now */
  1149. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1150. if(*sockfd == CURL_SOCKET_BAD)
  1151. /* no socket, no connection */
  1152. return CURLE_COULDNT_CONNECT;
  1153. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1154. if(conn->scope && (addr->family == AF_INET6)) {
  1155. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1156. sa6->sin6_scope_id = conn->scope;
  1157. }
  1158. #endif
  1159. return CURLE_OK;
  1160. }
  1161. #ifdef CURLDEBUG
  1162. /*
  1163. * Curl_conncontrol() is used to set the conn->bits.close bit on or off. It
  1164. * MUST be called with the connclose() or connclose() macros with a stated
  1165. * reason. The reason is only shown in debug builds but helps to figure out
  1166. * decision paths when connections are or aren't re-used as expected.
  1167. */
  1168. void Curl_conncontrol(struct connectdata *conn, bool closeit,
  1169. const char *reason)
  1170. {
  1171. infof(conn->data, "Marked for [%s]: %s\n", closeit?"closure":"keep alive",
  1172. reason);
  1173. conn->bits.close = closeit; /* the only place in the source code that should
  1174. assign this bit */
  1175. }
  1176. #endif