connect.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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, unsigned int scope)
  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, 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. CURLcode result = CURLE_COULDNT_CONNECT;
  501. /* First clean up after the failed socket.
  502. Don't close it yet to ensure that the next IP's socket gets a different
  503. file descriptor, which can prevent bugs when the curl_multi_socket_action
  504. interface is used with certain select() replacements such as kqueue. */
  505. curl_socket_t fd_to_close = conn->tempsock[tempindex];
  506. conn->tempsock[tempindex] = CURL_SOCKET_BAD;
  507. if(sockindex == FIRSTSOCKET) {
  508. Curl_addrinfo *ai = NULL;
  509. int family = AF_UNSPEC;
  510. if(conn->tempaddr[tempindex]) {
  511. /* find next address in the same protocol family */
  512. family = conn->tempaddr[tempindex]->ai_family;
  513. ai = conn->tempaddr[tempindex]->ai_next;
  514. }
  515. else if(conn->tempaddr[0]) {
  516. /* happy eyeballs - try the other protocol family */
  517. int firstfamily = conn->tempaddr[0]->ai_family;
  518. #ifdef ENABLE_IPV6
  519. family = (firstfamily == AF_INET) ? AF_INET6 : AF_INET;
  520. #else
  521. family = firstfamily;
  522. #endif
  523. ai = conn->tempaddr[0]->ai_next;
  524. }
  525. while(ai) {
  526. while(ai && ai->ai_family != family)
  527. ai = ai->ai_next;
  528. if(ai) {
  529. result = singleipconnect(conn, ai, &conn->tempsock[tempindex]);
  530. if(result == CURLE_COULDNT_CONNECT) {
  531. ai = ai->ai_next;
  532. continue;
  533. }
  534. conn->tempaddr[tempindex] = ai;
  535. }
  536. break;
  537. }
  538. }
  539. if(fd_to_close != CURL_SOCKET_BAD)
  540. Curl_closesocket(conn, fd_to_close);
  541. return result;
  542. }
  543. /* Copies connection info into the session handle to make it available
  544. when the session handle is no longer associated with a connection. */
  545. void Curl_persistconninfo(struct connectdata *conn)
  546. {
  547. memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
  548. memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
  549. conn->data->info.conn_primary_port = conn->primary_port;
  550. conn->data->info.conn_local_port = conn->local_port;
  551. }
  552. /* retrieves ip address and port from a sockaddr structure */
  553. static bool getaddressinfo(struct sockaddr* sa, char* addr,
  554. long* port)
  555. {
  556. unsigned short us_port;
  557. struct sockaddr_in* si = NULL;
  558. #ifdef ENABLE_IPV6
  559. struct sockaddr_in6* si6 = NULL;
  560. #endif
  561. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  562. struct sockaddr_un* su = NULL;
  563. #endif
  564. switch (sa->sa_family) {
  565. case AF_INET:
  566. si = (struct sockaddr_in*) sa;
  567. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  568. addr, MAX_IPADR_LEN)) {
  569. us_port = ntohs(si->sin_port);
  570. *port = us_port;
  571. return TRUE;
  572. }
  573. break;
  574. #ifdef ENABLE_IPV6
  575. case AF_INET6:
  576. si6 = (struct sockaddr_in6*)sa;
  577. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  578. addr, MAX_IPADR_LEN)) {
  579. us_port = ntohs(si6->sin6_port);
  580. *port = us_port;
  581. return TRUE;
  582. }
  583. break;
  584. #endif
  585. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  586. case AF_UNIX:
  587. su = (struct sockaddr_un*)sa;
  588. snprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  589. *port = 0;
  590. return TRUE;
  591. #endif
  592. default:
  593. break;
  594. }
  595. addr[0] = '\0';
  596. *port = 0;
  597. return FALSE;
  598. }
  599. /* retrieves the start/end point information of a socket of an established
  600. connection */
  601. void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
  602. {
  603. curl_socklen_t len;
  604. struct Curl_sockaddr_storage ssrem;
  605. struct Curl_sockaddr_storage ssloc;
  606. struct SessionHandle *data = conn->data;
  607. if(conn->socktype == SOCK_DGRAM)
  608. /* there's no connection! */
  609. return;
  610. if(!conn->bits.reuse) {
  611. int error;
  612. len = sizeof(struct Curl_sockaddr_storage);
  613. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
  614. error = SOCKERRNO;
  615. failf(data, "getpeername() failed with errno %d: %s",
  616. error, Curl_strerror(conn, error));
  617. return;
  618. }
  619. len = sizeof(struct Curl_sockaddr_storage);
  620. memset(&ssloc, 0, sizeof(ssloc));
  621. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
  622. error = SOCKERRNO;
  623. failf(data, "getsockname() failed with errno %d: %s",
  624. error, Curl_strerror(conn, error));
  625. return;
  626. }
  627. if(!getaddressinfo((struct sockaddr*)&ssrem,
  628. conn->primary_ip, &conn->primary_port)) {
  629. error = ERRNO;
  630. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  631. error, Curl_strerror(conn, error));
  632. return;
  633. }
  634. memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
  635. if(!getaddressinfo((struct sockaddr*)&ssloc,
  636. conn->local_ip, &conn->local_port)) {
  637. error = ERRNO;
  638. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  639. error, Curl_strerror(conn, error));
  640. return;
  641. }
  642. }
  643. /* persist connection info in session handle */
  644. Curl_persistconninfo(conn);
  645. }
  646. /*
  647. * Curl_is_connected() checks if the socket has connected.
  648. */
  649. CURLcode Curl_is_connected(struct connectdata *conn,
  650. int sockindex,
  651. bool *connected)
  652. {
  653. struct SessionHandle *data = conn->data;
  654. CURLcode result = CURLE_OK;
  655. long allow;
  656. int error = 0;
  657. struct timeval now;
  658. int rc;
  659. int i;
  660. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  661. *connected = FALSE; /* a very negative world view is best */
  662. if(conn->bits.tcpconnect[sockindex]) {
  663. /* we are connected already! */
  664. *connected = TRUE;
  665. return CURLE_OK;
  666. }
  667. now = Curl_tvnow();
  668. /* figure out how long time we have left to connect */
  669. allow = Curl_timeleft(data, &now, TRUE);
  670. if(allow < 0) {
  671. /* time-out, bail out, go home */
  672. failf(data, "Connection time-out");
  673. return CURLE_OPERATION_TIMEDOUT;
  674. }
  675. for(i=0; i<2; i++) {
  676. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  677. continue;
  678. #ifdef mpeix
  679. /* Call this function once now, and ignore the results. We do this to
  680. "clear" the error state on the socket so that we can later read it
  681. reliably. This is reported necessary on the MPE/iX operating system. */
  682. (void)verifyconnect(conn->tempsock[i], NULL);
  683. #endif
  684. /* check socket for connect */
  685. rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0);
  686. if(rc == 0) { /* no connection yet */
  687. if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
  688. infof(data, "After %ldms connect time, move on!\n",
  689. conn->timeoutms_per_addr);
  690. error = ETIMEDOUT;
  691. }
  692. /* should we try another protocol family? */
  693. if(i == 0 && conn->tempaddr[1] == NULL &&
  694. curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) {
  695. trynextip(conn, sockindex, 1);
  696. }
  697. }
  698. else if(rc == CURL_CSELECT_OUT) {
  699. if(verifyconnect(conn->tempsock[i], &error)) {
  700. /* we are connected with TCP, awesome! */
  701. int other = i ^ 1;
  702. /* use this socket from now on */
  703. conn->sock[sockindex] = conn->tempsock[i];
  704. conn->ip_addr = conn->tempaddr[i];
  705. conn->tempsock[i] = CURL_SOCKET_BAD;
  706. /* close the other socket, if open */
  707. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  708. Curl_closesocket(conn, conn->tempsock[other]);
  709. conn->tempsock[other] = CURL_SOCKET_BAD;
  710. }
  711. /* see if we need to do any proxy magic first once we connected */
  712. result = Curl_connected_proxy(conn, sockindex);
  713. if(result)
  714. return result;
  715. conn->bits.tcpconnect[sockindex] = TRUE;
  716. *connected = TRUE;
  717. if(sockindex == FIRSTSOCKET)
  718. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  719. Curl_updateconninfo(conn, conn->sock[sockindex]);
  720. Curl_verboseconnect(conn);
  721. return CURLE_OK;
  722. }
  723. else
  724. infof(data, "Connection failed\n");
  725. }
  726. else if(rc & CURL_CSELECT_ERR)
  727. (void)verifyconnect(conn->tempsock[i], &error);
  728. /*
  729. * The connection failed here, we should attempt to connect to the "next
  730. * address" for the given host. But first remember the latest error.
  731. */
  732. if(error) {
  733. data->state.os_errno = error;
  734. SET_SOCKERRNO(error);
  735. if(conn->tempaddr[i]) {
  736. char ipaddress[MAX_IPADR_LEN];
  737. Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
  738. infof(data, "connect to %s port %ld failed: %s\n",
  739. ipaddress, conn->port, Curl_strerror(conn, error));
  740. conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
  741. allow : allow / 2;
  742. result = trynextip(conn, sockindex, i);
  743. }
  744. }
  745. }
  746. if(result) {
  747. /* no more addresses to try */
  748. /* if the first address family runs out of addresses to try before
  749. the happy eyeball timeout, go ahead and try the next family now */
  750. if(conn->tempaddr[1] == NULL) {
  751. result = trynextip(conn, sockindex, 1);
  752. if(!result)
  753. return result;
  754. }
  755. failf(data, "Failed to connect to %s port %ld: %s",
  756. conn->bits.proxy?conn->proxy.name:conn->host.name,
  757. conn->port, Curl_strerror(conn, error));
  758. }
  759. return result;
  760. }
  761. static void tcpnodelay(struct connectdata *conn,
  762. curl_socket_t sockfd)
  763. {
  764. #ifdef TCP_NODELAY
  765. struct SessionHandle *data= conn->data;
  766. curl_socklen_t onoff = (curl_socklen_t) data->set.tcp_nodelay;
  767. int level = IPPROTO_TCP;
  768. #if 0
  769. /* The use of getprotobyname() is disabled since it isn't thread-safe on
  770. numerous systems. On these getprotobyname_r() should be used instead, but
  771. that exists in at least one 4 arg version and one 5 arg version, and
  772. since the proto number rarely changes anyway we now just use the hard
  773. coded number. The "proper" fix would need a configure check for the
  774. correct function much in the same style the gethostbyname_r versions are
  775. detected. */
  776. struct protoent *pe = getprotobyname("tcp");
  777. if(pe)
  778. level = pe->p_proto;
  779. #endif
  780. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  781. sizeof(onoff)) < 0)
  782. infof(data, "Could not set TCP_NODELAY: %s\n",
  783. Curl_strerror(conn, SOCKERRNO));
  784. else
  785. infof(data,"TCP_NODELAY set\n");
  786. #else
  787. (void)conn;
  788. (void)sockfd;
  789. #endif
  790. }
  791. #ifdef SO_NOSIGPIPE
  792. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  793. sending data to a dead peer (instead of relying on the 4th argument to send
  794. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  795. systems? */
  796. static void nosigpipe(struct connectdata *conn,
  797. curl_socket_t sockfd)
  798. {
  799. struct SessionHandle *data= conn->data;
  800. int onoff = 1;
  801. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  802. sizeof(onoff)) < 0)
  803. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  804. Curl_strerror(conn, SOCKERRNO));
  805. }
  806. #else
  807. #define nosigpipe(x,y) Curl_nop_stmt
  808. #endif
  809. #ifdef USE_WINSOCK
  810. /* When you run a program that uses the Windows Sockets API, you may
  811. experience slow performance when you copy data to a TCP server.
  812. http://support.microsoft.com/kb/823764
  813. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  814. Buffer Size
  815. The problem described in this knowledge-base is applied only to pre-Vista
  816. Windows. Following function trying to detect OS version and skips
  817. SO_SNDBUF adjustment for Windows Vista and above.
  818. */
  819. #define DETECT_OS_NONE 0
  820. #define DETECT_OS_PREVISTA 1
  821. #define DETECT_OS_VISTA_OR_LATER 2
  822. void Curl_sndbufset(curl_socket_t sockfd)
  823. {
  824. int val = CURL_MAX_WRITE_SIZE + 32;
  825. int curval = 0;
  826. int curlen = sizeof(curval);
  827. DWORD majorVersion = 6;
  828. static int detectOsState = DETECT_OS_NONE;
  829. if(detectOsState == DETECT_OS_NONE) {
  830. #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \
  831. (_WIN32_WINNT < _WIN32_WINNT_WIN2K)
  832. OSVERSIONINFO osver;
  833. memset(&osver, 0, sizeof(osver));
  834. osver.dwOSVersionInfoSize = sizeof(osver);
  835. detectOsState = DETECT_OS_PREVISTA;
  836. if(GetVersionEx(&osver)) {
  837. if(osver.dwMajorVersion >= majorVersion)
  838. detectOsState = DETECT_OS_VISTA_OR_LATER;
  839. }
  840. #else
  841. ULONGLONG majorVersionMask;
  842. OSVERSIONINFOEX osver;
  843. memset(&osver, 0, sizeof(osver));
  844. osver.dwOSVersionInfoSize = sizeof(osver);
  845. osver.dwMajorVersion = majorVersion;
  846. majorVersionMask = VerSetConditionMask(0, VER_MAJORVERSION,
  847. VER_GREATER_EQUAL);
  848. if(VerifyVersionInfo(&osver, VER_MAJORVERSION, majorVersionMask))
  849. detectOsState = DETECT_OS_VISTA_OR_LATER;
  850. else
  851. detectOsState = DETECT_OS_PREVISTA;
  852. #endif
  853. }
  854. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  855. return;
  856. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  857. if(curval > val)
  858. return;
  859. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  860. }
  861. #endif
  862. /*
  863. * singleipconnect()
  864. *
  865. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  866. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  867. *
  868. * singleipconnect() connects to the given IP only, and it may return without
  869. * having connected.
  870. */
  871. static CURLcode singleipconnect(struct connectdata *conn,
  872. const Curl_addrinfo *ai,
  873. curl_socket_t *sockp)
  874. {
  875. struct Curl_sockaddr_ex addr;
  876. int rc;
  877. int error = 0;
  878. bool isconnected = FALSE;
  879. struct SessionHandle *data = conn->data;
  880. curl_socket_t sockfd;
  881. CURLcode result;
  882. char ipaddress[MAX_IPADR_LEN];
  883. long port;
  884. bool is_tcp;
  885. *sockp = CURL_SOCKET_BAD;
  886. result = Curl_socket(conn, ai, &addr, &sockfd);
  887. if(result)
  888. /* Failed to create the socket, but still return OK since we signal the
  889. lack of socket as well. This allows the parent function to keep looping
  890. over alternative addresses/socket families etc. */
  891. return CURLE_OK;
  892. /* store remote address and port used in this connection attempt */
  893. if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
  894. ipaddress, &port)) {
  895. /* malformed address or bug in inet_ntop, try next address */
  896. error = ERRNO;
  897. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  898. error, Curl_strerror(conn, error));
  899. Curl_closesocket(conn, sockfd);
  900. return CURLE_OK;
  901. }
  902. infof(data, " Trying %s...\n", ipaddress);
  903. is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
  904. addr.socktype == SOCK_STREAM;
  905. if(is_tcp && data->set.tcp_nodelay)
  906. tcpnodelay(conn, sockfd);
  907. nosigpipe(conn, sockfd);
  908. Curl_sndbufset(sockfd);
  909. if(is_tcp && data->set.tcp_keepalive)
  910. tcpkeepalive(data, sockfd);
  911. if(data->set.fsockopt) {
  912. /* activate callback for setting socket options */
  913. error = data->set.fsockopt(data->set.sockopt_client,
  914. sockfd,
  915. CURLSOCKTYPE_IPCXN);
  916. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  917. isconnected = TRUE;
  918. else if(error) {
  919. Curl_closesocket(conn, sockfd); /* close the socket and bail out */
  920. return CURLE_ABORTED_BY_CALLBACK;
  921. }
  922. }
  923. /* possibly bind the local end to an IP, interface or port */
  924. if(addr.family == AF_INET || addr.family == AF_INET6) {
  925. result = bindlocal(conn, sockfd, addr.family,
  926. Curl_ipv6_scope((struct sockaddr*)&addr.sa_addr));
  927. if(result) {
  928. Curl_closesocket(conn, sockfd); /* close socket and bail out */
  929. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  930. /* The address family is not supported on this interface.
  931. We can continue trying addresses */
  932. return CURLE_COULDNT_CONNECT;
  933. }
  934. return result;
  935. }
  936. }
  937. /* set socket non-blocking */
  938. (void)curlx_nonblock(sockfd, TRUE);
  939. conn->connecttime = Curl_tvnow();
  940. if(conn->num_addr > 1)
  941. Curl_expire_latest(data, conn->timeoutms_per_addr);
  942. /* Connect TCP sockets, bind UDP */
  943. if(!isconnected && (conn->socktype == SOCK_STREAM)) {
  944. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  945. if(-1 == rc)
  946. error = SOCKERRNO;
  947. }
  948. else {
  949. *sockp = sockfd;
  950. return CURLE_OK;
  951. }
  952. #ifdef ENABLE_IPV6
  953. conn->bits.ipv6 = (addr.family == AF_INET6)?TRUE:FALSE;
  954. #endif
  955. if(-1 == rc) {
  956. switch(error) {
  957. case EINPROGRESS:
  958. case EWOULDBLOCK:
  959. #if defined(EAGAIN)
  960. #if (EAGAIN) != (EWOULDBLOCK)
  961. /* On some platforms EAGAIN and EWOULDBLOCK are the
  962. * same value, and on others they are different, hence
  963. * the odd #if
  964. */
  965. case EAGAIN:
  966. #endif
  967. #endif
  968. result = CURLE_OK;
  969. break;
  970. default:
  971. /* unknown error, fallthrough and try another address! */
  972. infof(data, "Immediate connect fail for %s: %s\n",
  973. ipaddress, Curl_strerror(conn,error));
  974. data->state.os_errno = error;
  975. /* connect failed */
  976. Curl_closesocket(conn, sockfd);
  977. result = CURLE_COULDNT_CONNECT;
  978. }
  979. }
  980. if(!result)
  981. *sockp = sockfd;
  982. return result;
  983. }
  984. /*
  985. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  986. * There might be more than one IP address to try out. Fill in the passed
  987. * pointer with the connected socket.
  988. */
  989. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  990. const struct Curl_dns_entry *remotehost)
  991. {
  992. struct SessionHandle *data = conn->data;
  993. struct timeval before = Curl_tvnow();
  994. CURLcode result = CURLE_COULDNT_CONNECT;
  995. long timeout_ms = Curl_timeleft(data, &before, TRUE);
  996. if(timeout_ms < 0) {
  997. /* a precaution, no need to continue if time already is up */
  998. failf(data, "Connection time-out");
  999. return CURLE_OPERATION_TIMEDOUT;
  1000. }
  1001. conn->num_addr = Curl_num_addresses(remotehost->addr);
  1002. conn->tempaddr[0] = remotehost->addr;
  1003. conn->tempaddr[1] = NULL;
  1004. conn->tempsock[0] = CURL_SOCKET_BAD;
  1005. conn->tempsock[1] = CURL_SOCKET_BAD;
  1006. Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT);
  1007. /* Max time for the next connection attempt */
  1008. conn->timeoutms_per_addr =
  1009. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1010. /* start connecting to first IP */
  1011. while(conn->tempaddr[0]) {
  1012. result = singleipconnect(conn, conn->tempaddr[0], &(conn->tempsock[0]));
  1013. if(!result)
  1014. break;
  1015. conn->tempaddr[0] = conn->tempaddr[0]->ai_next;
  1016. }
  1017. if(conn->tempsock[0] == CURL_SOCKET_BAD)
  1018. return result;
  1019. data->info.numconnects++; /* to track the number of connections made */
  1020. return CURLE_OK;
  1021. }
  1022. struct connfind {
  1023. struct connectdata *tofind;
  1024. bool found;
  1025. };
  1026. static int conn_is_conn(struct connectdata *conn, void *param)
  1027. {
  1028. struct connfind *f = (struct connfind *)param;
  1029. if(conn == f->tofind) {
  1030. f->found = TRUE;
  1031. return 1;
  1032. }
  1033. return 0;
  1034. }
  1035. /*
  1036. * Used to extract socket and connectdata struct for the most recent
  1037. * transfer on the given SessionHandle.
  1038. *
  1039. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1040. */
  1041. curl_socket_t Curl_getconnectinfo(struct SessionHandle *data,
  1042. struct connectdata **connp)
  1043. {
  1044. curl_socket_t sockfd;
  1045. DEBUGASSERT(data);
  1046. /* this only works for an easy handle that has been used for
  1047. curl_easy_perform()! */
  1048. if(data->state.lastconnect && data->multi_easy) {
  1049. struct connectdata *c = data->state.lastconnect;
  1050. struct connfind find;
  1051. find.tofind = data->state.lastconnect;
  1052. find.found = FALSE;
  1053. Curl_conncache_foreach(data->multi_easy->conn_cache, &find, conn_is_conn);
  1054. if(!find.found) {
  1055. data->state.lastconnect = NULL;
  1056. return CURL_SOCKET_BAD;
  1057. }
  1058. if(connp)
  1059. /* only store this if the caller cares for it */
  1060. *connp = c;
  1061. sockfd = c->sock[FIRSTSOCKET];
  1062. /* we have a socket connected, let's determine if the server shut down */
  1063. /* determine if ssl */
  1064. if(c->ssl[FIRSTSOCKET].use) {
  1065. /* use the SSL context */
  1066. if(!Curl_ssl_check_cxn(c))
  1067. return CURL_SOCKET_BAD; /* FIN received */
  1068. }
  1069. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1070. #ifdef MSG_PEEK
  1071. else {
  1072. /* use the socket */
  1073. char buf;
  1074. if(recv((RECV_TYPE_ARG1)c->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1075. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1076. return CURL_SOCKET_BAD; /* FIN received */
  1077. }
  1078. }
  1079. #endif
  1080. }
  1081. else
  1082. return CURL_SOCKET_BAD;
  1083. return sockfd;
  1084. }
  1085. /*
  1086. * Close a socket.
  1087. *
  1088. * 'conn' can be NULL, beware!
  1089. */
  1090. int Curl_closesocket(struct connectdata *conn,
  1091. curl_socket_t sock)
  1092. {
  1093. if(conn && conn->fclosesocket) {
  1094. if((sock == conn->sock[SECONDARYSOCKET]) &&
  1095. conn->sock_accepted[SECONDARYSOCKET])
  1096. /* if this socket matches the second socket, and that was created with
  1097. accept, then we MUST NOT call the callback but clear the accepted
  1098. status */
  1099. conn->sock_accepted[SECONDARYSOCKET] = FALSE;
  1100. else
  1101. return conn->fclosesocket(conn->closesocket_client, sock);
  1102. }
  1103. if(conn)
  1104. /* tell the multi-socket code about this */
  1105. Curl_multi_closed(conn, sock);
  1106. sclose(sock);
  1107. return 0;
  1108. }
  1109. /*
  1110. * Create a socket based on info from 'conn' and 'ai'.
  1111. *
  1112. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1113. * 'sockfd' must be a pointer to a socket descriptor.
  1114. *
  1115. * If the open socket callback is set, used that!
  1116. *
  1117. */
  1118. CURLcode Curl_socket(struct connectdata *conn,
  1119. const Curl_addrinfo *ai,
  1120. struct Curl_sockaddr_ex *addr,
  1121. curl_socket_t *sockfd)
  1122. {
  1123. struct SessionHandle *data = conn->data;
  1124. struct Curl_sockaddr_ex dummy;
  1125. if(!addr)
  1126. /* if the caller doesn't want info back, use a local temp copy */
  1127. addr = &dummy;
  1128. /*
  1129. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1130. * curl_sockaddr structure with enough space available to directly hold
  1131. * any protocol-specific address structures. The variable declared here
  1132. * will be used to pass / receive data to/from the fopensocket callback
  1133. * if this has been set, before that, it is initialized from parameters.
  1134. */
  1135. addr->family = ai->ai_family;
  1136. addr->socktype = conn->socktype;
  1137. addr->protocol = conn->socktype==SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
  1138. addr->addrlen = ai->ai_addrlen;
  1139. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1140. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1141. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1142. if(data->set.fopensocket)
  1143. /*
  1144. * If the opensocket callback is set, all the destination address
  1145. * information is passed to the callback. Depending on this information the
  1146. * callback may opt to abort the connection, this is indicated returning
  1147. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1148. * the callback returns a valid socket the destination address information
  1149. * might have been changed and this 'new' address will actually be used
  1150. * here to connect.
  1151. */
  1152. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1153. CURLSOCKTYPE_IPCXN,
  1154. (struct curl_sockaddr *)addr);
  1155. else
  1156. /* opensocket callback not set, so simply create the socket now */
  1157. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1158. if(*sockfd == CURL_SOCKET_BAD)
  1159. /* no socket, no connection */
  1160. return CURLE_COULDNT_CONNECT;
  1161. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1162. if(conn->scope_id && (addr->family == AF_INET6)) {
  1163. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1164. sa6->sin6_scope_id = conn->scope_id;
  1165. }
  1166. #endif
  1167. return CURLE_OK;
  1168. }
  1169. #ifdef CURLDEBUG
  1170. /*
  1171. * Curl_conncontrol() is used to set the conn->bits.close bit on or off. It
  1172. * MUST be called with the connclose() or connkeep() macros with a stated
  1173. * reason. The reason is only shown in debug builds but helps to figure out
  1174. * decision paths when connections are or aren't re-used as expected.
  1175. */
  1176. void Curl_conncontrol(struct connectdata *conn, bool closeit,
  1177. const char *reason)
  1178. {
  1179. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  1180. (void) reason;
  1181. #endif
  1182. infof(conn->data, "Marked for [%s]: %s\n", closeit?"closure":"keep alive",
  1183. reason);
  1184. conn->bits.close = closeit; /* the only place in the source code that should
  1185. assign this bit */
  1186. }
  1187. #endif