cf-socket.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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 https://curl.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifdef HAVE_NETINET_IN_H
  26. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  27. #endif
  28. #ifdef HAVE_SYS_UN_H
  29. #include <sys/un.h> /* for sockaddr_un */
  30. #endif
  31. #ifdef HAVE_LINUX_TCP_H
  32. #include <linux/tcp.h>
  33. #elif defined(HAVE_NETINET_TCP_H)
  34. #include <netinet/tcp.h>
  35. #endif
  36. #ifdef HAVE_SYS_IOCTL_H
  37. #include <sys/ioctl.h>
  38. #endif
  39. #ifdef HAVE_NETDB_H
  40. #include <netdb.h>
  41. #endif
  42. #ifdef HAVE_FCNTL_H
  43. #include <fcntl.h>
  44. #endif
  45. #ifdef HAVE_ARPA_INET_H
  46. #include <arpa/inet.h>
  47. #endif
  48. #ifdef __VMS
  49. #include <in.h>
  50. #include <inet.h>
  51. #endif
  52. #include "urldata.h"
  53. #include "bufq.h"
  54. #include "sendf.h"
  55. #include "if2ip.h"
  56. #include "strerror.h"
  57. #include "cfilters.h"
  58. #include "cf-socket.h"
  59. #include "connect.h"
  60. #include "select.h"
  61. #include "url.h" /* for Curl_safefree() */
  62. #include "multiif.h"
  63. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  64. #include "inet_ntop.h"
  65. #include "inet_pton.h"
  66. #include "progress.h"
  67. #include "warnless.h"
  68. #include "conncache.h"
  69. #include "multihandle.h"
  70. #include "rand.h"
  71. #include "share.h"
  72. #include "version_win32.h"
  73. /* The last 3 #include files should be in this order */
  74. #include "curl_printf.h"
  75. #include "curl_memory.h"
  76. #include "memdebug.h"
  77. #if defined(USE_IPV6) && defined(IPV6_V6ONLY) && defined(_WIN32)
  78. /* It makes support for IPv4-mapped IPv6 addresses.
  79. * Linux kernel, NetBSD, FreeBSD and Darwin: default is off;
  80. * Windows Vista and later: default is on;
  81. * DragonFly BSD: acts like off, and dummy setting;
  82. * OpenBSD and earlier Windows: unsupported.
  83. * Linux: controlled by /proc/sys/net/ipv6/bindv6only.
  84. */
  85. static void set_ipv6_v6only(curl_socket_t sockfd, int on)
  86. {
  87. (void)setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(on));
  88. }
  89. #else
  90. #define set_ipv6_v6only(x,y)
  91. #endif
  92. static void tcpnodelay(struct Curl_easy *data, curl_socket_t sockfd)
  93. {
  94. #if defined(TCP_NODELAY)
  95. curl_socklen_t onoff = (curl_socklen_t) 1;
  96. int level = IPPROTO_TCP;
  97. char buffer[STRERROR_LEN];
  98. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  99. sizeof(onoff)) < 0)
  100. infof(data, "Could not set TCP_NODELAY: %s",
  101. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  102. #else
  103. (void)data;
  104. (void)sockfd;
  105. #endif
  106. }
  107. #ifdef SO_NOSIGPIPE
  108. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  109. sending data to a dead peer (instead of relying on the 4th argument to send
  110. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  111. systems? */
  112. static void nosigpipe(struct Curl_easy *data,
  113. curl_socket_t sockfd)
  114. {
  115. int onoff = 1;
  116. (void)data;
  117. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  118. sizeof(onoff)) < 0) {
  119. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  120. char buffer[STRERROR_LEN];
  121. infof(data, "Could not set SO_NOSIGPIPE: %s",
  122. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  123. #endif
  124. }
  125. }
  126. #else
  127. #define nosigpipe(x,y) Curl_nop_stmt
  128. #endif
  129. #if defined(__DragonFly__) || defined(USE_WINSOCK)
  130. /* DragonFlyBSD and Windows use millisecond units */
  131. #define KEEPALIVE_FACTOR(x) (x *= 1000)
  132. #else
  133. #define KEEPALIVE_FACTOR(x)
  134. #endif
  135. #if defined(USE_WINSOCK) && !defined(SIO_KEEPALIVE_VALS)
  136. #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
  137. struct tcp_keepalive {
  138. u_long onoff;
  139. u_long keepalivetime;
  140. u_long keepaliveinterval;
  141. };
  142. #endif
  143. static void
  144. tcpkeepalive(struct Curl_easy *data,
  145. curl_socket_t sockfd)
  146. {
  147. int optval = data->set.tcp_keepalive?1:0;
  148. /* only set IDLE and INTVL if setting KEEPALIVE is successful */
  149. if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
  150. (void *)&optval, sizeof(optval)) < 0) {
  151. infof(data, "Failed to set SO_KEEPALIVE on fd "
  152. "%" CURL_FORMAT_SOCKET_T ": errno %d",
  153. sockfd, SOCKERRNO);
  154. }
  155. else {
  156. #if defined(SIO_KEEPALIVE_VALS)
  157. struct tcp_keepalive vals;
  158. DWORD dummy;
  159. vals.onoff = 1;
  160. optval = curlx_sltosi(data->set.tcp_keepidle);
  161. KEEPALIVE_FACTOR(optval);
  162. vals.keepalivetime = optval;
  163. optval = curlx_sltosi(data->set.tcp_keepintvl);
  164. KEEPALIVE_FACTOR(optval);
  165. vals.keepaliveinterval = optval;
  166. if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
  167. NULL, 0, &dummy, NULL, NULL) != 0) {
  168. infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd "
  169. "%" CURL_FORMAT_SOCKET_T ": errno %d",
  170. sockfd, SOCKERRNO);
  171. }
  172. #else
  173. #ifdef TCP_KEEPIDLE
  174. optval = curlx_sltosi(data->set.tcp_keepidle);
  175. KEEPALIVE_FACTOR(optval);
  176. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
  177. (void *)&optval, sizeof(optval)) < 0) {
  178. infof(data, "Failed to set TCP_KEEPIDLE on fd "
  179. "%" CURL_FORMAT_SOCKET_T ": errno %d",
  180. sockfd, SOCKERRNO);
  181. }
  182. #elif defined(TCP_KEEPALIVE)
  183. /* Mac OS X style */
  184. optval = curlx_sltosi(data->set.tcp_keepidle);
  185. KEEPALIVE_FACTOR(optval);
  186. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
  187. (void *)&optval, sizeof(optval)) < 0) {
  188. infof(data, "Failed to set TCP_KEEPALIVE on fd "
  189. "%" CURL_FORMAT_SOCKET_T ": errno %d",
  190. sockfd, SOCKERRNO);
  191. }
  192. #endif
  193. #ifdef TCP_KEEPINTVL
  194. optval = curlx_sltosi(data->set.tcp_keepintvl);
  195. KEEPALIVE_FACTOR(optval);
  196. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
  197. (void *)&optval, sizeof(optval)) < 0) {
  198. infof(data, "Failed to set TCP_KEEPINTVL on fd "
  199. "%" CURL_FORMAT_SOCKET_T ": errno %d",
  200. sockfd, SOCKERRNO);
  201. }
  202. #endif
  203. #endif
  204. }
  205. }
  206. /**
  207. * Assign the address `ai` to the Curl_sockaddr_ex `dest` and
  208. * set the transport used.
  209. */
  210. void Curl_sock_assign_addr(struct Curl_sockaddr_ex *dest,
  211. const struct Curl_addrinfo *ai,
  212. int transport)
  213. {
  214. /*
  215. * The Curl_sockaddr_ex structure is basically libcurl's external API
  216. * curl_sockaddr structure with enough space available to directly hold
  217. * any protocol-specific address structures. The variable declared here
  218. * will be used to pass / receive data to/from the fopensocket callback
  219. * if this has been set, before that, it is initialized from parameters.
  220. */
  221. dest->family = ai->ai_family;
  222. switch(transport) {
  223. case TRNSPRT_TCP:
  224. dest->socktype = SOCK_STREAM;
  225. dest->protocol = IPPROTO_TCP;
  226. break;
  227. case TRNSPRT_UNIX:
  228. dest->socktype = SOCK_STREAM;
  229. dest->protocol = IPPROTO_IP;
  230. break;
  231. default: /* UDP and QUIC */
  232. dest->socktype = SOCK_DGRAM;
  233. dest->protocol = IPPROTO_UDP;
  234. break;
  235. }
  236. dest->addrlen = ai->ai_addrlen;
  237. if(dest->addrlen > sizeof(struct Curl_sockaddr_storage))
  238. dest->addrlen = sizeof(struct Curl_sockaddr_storage);
  239. memcpy(&dest->sa_addr, ai->ai_addr, dest->addrlen);
  240. }
  241. static CURLcode socket_open(struct Curl_easy *data,
  242. struct Curl_sockaddr_ex *addr,
  243. curl_socket_t *sockfd)
  244. {
  245. DEBUGASSERT(data);
  246. DEBUGASSERT(data->conn);
  247. if(data->set.fopensocket) {
  248. /*
  249. * If the opensocket callback is set, all the destination address
  250. * information is passed to the callback. Depending on this information the
  251. * callback may opt to abort the connection, this is indicated returning
  252. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  253. * the callback returns a valid socket the destination address information
  254. * might have been changed and this 'new' address will actually be used
  255. * here to connect.
  256. */
  257. Curl_set_in_callback(data, true);
  258. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  259. CURLSOCKTYPE_IPCXN,
  260. (struct curl_sockaddr *)addr);
  261. Curl_set_in_callback(data, false);
  262. }
  263. else {
  264. /* opensocket callback not set, so simply create the socket now */
  265. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  266. }
  267. if(*sockfd == CURL_SOCKET_BAD)
  268. /* no socket, no connection */
  269. return CURLE_COULDNT_CONNECT;
  270. #if defined(USE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  271. if(data->conn->scope_id && (addr->family == AF_INET6)) {
  272. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  273. sa6->sin6_scope_id = data->conn->scope_id;
  274. }
  275. #endif
  276. return CURLE_OK;
  277. }
  278. /*
  279. * Create a socket based on info from 'conn' and 'ai'.
  280. *
  281. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  282. * 'sockfd' must be a pointer to a socket descriptor.
  283. *
  284. * If the open socket callback is set, used that!
  285. *
  286. */
  287. CURLcode Curl_socket_open(struct Curl_easy *data,
  288. const struct Curl_addrinfo *ai,
  289. struct Curl_sockaddr_ex *addr,
  290. int transport,
  291. curl_socket_t *sockfd)
  292. {
  293. struct Curl_sockaddr_ex dummy;
  294. if(!addr)
  295. /* if the caller doesn't want info back, use a local temp copy */
  296. addr = &dummy;
  297. Curl_sock_assign_addr(addr, ai, transport);
  298. return socket_open(data, addr, sockfd);
  299. }
  300. static int socket_close(struct Curl_easy *data, struct connectdata *conn,
  301. int use_callback, curl_socket_t sock)
  302. {
  303. if(use_callback && conn && conn->fclosesocket) {
  304. int rc;
  305. Curl_multi_closed(data, sock);
  306. Curl_set_in_callback(data, true);
  307. rc = conn->fclosesocket(conn->closesocket_client, sock);
  308. Curl_set_in_callback(data, false);
  309. return rc;
  310. }
  311. if(conn)
  312. /* tell the multi-socket code about this */
  313. Curl_multi_closed(data, sock);
  314. sclose(sock);
  315. return 0;
  316. }
  317. /*
  318. * Close a socket.
  319. *
  320. * 'conn' can be NULL, beware!
  321. */
  322. int Curl_socket_close(struct Curl_easy *data, struct connectdata *conn,
  323. curl_socket_t sock)
  324. {
  325. return socket_close(data, conn, FALSE, sock);
  326. }
  327. #ifdef USE_WINSOCK
  328. /* When you run a program that uses the Windows Sockets API, you may
  329. experience slow performance when you copy data to a TCP server.
  330. https://support.microsoft.com/kb/823764
  331. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  332. Buffer Size
  333. The problem described in this knowledge-base is applied only to pre-Vista
  334. Windows. Following function trying to detect OS version and skips
  335. SO_SNDBUF adjustment for Windows Vista and above.
  336. */
  337. #define DETECT_OS_NONE 0
  338. #define DETECT_OS_PREVISTA 1
  339. #define DETECT_OS_VISTA_OR_LATER 2
  340. void Curl_sndbufset(curl_socket_t sockfd)
  341. {
  342. int val = CURL_MAX_WRITE_SIZE + 32;
  343. int curval = 0;
  344. int curlen = sizeof(curval);
  345. static int detectOsState = DETECT_OS_NONE;
  346. if(detectOsState == DETECT_OS_NONE) {
  347. if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT,
  348. VERSION_GREATER_THAN_EQUAL))
  349. detectOsState = DETECT_OS_VISTA_OR_LATER;
  350. else
  351. detectOsState = DETECT_OS_PREVISTA;
  352. }
  353. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  354. return;
  355. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  356. if(curval > val)
  357. return;
  358. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  359. }
  360. #endif
  361. #ifndef CURL_DISABLE_BINDLOCAL
  362. static CURLcode bindlocal(struct Curl_easy *data, struct connectdata *conn,
  363. curl_socket_t sockfd, int af, unsigned int scope)
  364. {
  365. struct Curl_sockaddr_storage sa;
  366. struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
  367. curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
  368. struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
  369. #ifdef USE_IPV6
  370. struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
  371. #endif
  372. struct Curl_dns_entry *h = NULL;
  373. unsigned short port = data->set.localport; /* use this port number, 0 for
  374. "random" */
  375. /* how many port numbers to try to bind to, increasing one at a time */
  376. int portnum = data->set.localportrange;
  377. const char *dev = data->set.str[STRING_DEVICE];
  378. int error;
  379. #ifdef IP_BIND_ADDRESS_NO_PORT
  380. int on = 1;
  381. #endif
  382. #ifndef USE_IPV6
  383. (void)scope;
  384. #endif
  385. /*************************************************************
  386. * Select device to bind socket to
  387. *************************************************************/
  388. if(!dev && !port)
  389. /* no local kind of binding was requested */
  390. return CURLE_OK;
  391. memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
  392. if(dev && (strlen(dev)<255) ) {
  393. char myhost[256] = "";
  394. int done = 0; /* -1 for error, 1 for address found */
  395. bool is_interface = FALSE;
  396. bool is_host = FALSE;
  397. static const char *if_prefix = "if!";
  398. static const char *host_prefix = "host!";
  399. if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
  400. dev += strlen(if_prefix);
  401. is_interface = TRUE;
  402. }
  403. else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
  404. dev += strlen(host_prefix);
  405. is_host = TRUE;
  406. }
  407. /* interface */
  408. if(!is_host) {
  409. #ifdef SO_BINDTODEVICE
  410. /*
  411. * This binds the local socket to a particular interface. This will
  412. * force even requests to other local interfaces to go out the external
  413. * interface. Only bind to the interface when specified as interface,
  414. * not just as a hostname or ip address.
  415. *
  416. * The interface might be a VRF, eg: vrf-blue, which means it cannot be
  417. * converted to an IP address and would fail Curl_if2ip. Simply try to
  418. * use it straight away.
  419. */
  420. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  421. dev, (curl_socklen_t)strlen(dev) + 1) == 0) {
  422. /* This is often "errno 1, error: Operation not permitted" if you're
  423. * not running as root or another suitable privileged user. If it
  424. * succeeds it means the parameter was a valid interface and not an IP
  425. * address. Return immediately.
  426. */
  427. infof(data, "socket successfully bound to interface '%s'", dev);
  428. return CURLE_OK;
  429. }
  430. #endif
  431. switch(Curl_if2ip(af,
  432. #ifdef USE_IPV6
  433. scope, conn->scope_id,
  434. #endif
  435. dev, myhost, sizeof(myhost))) {
  436. case IF2IP_NOT_FOUND:
  437. if(is_interface) {
  438. /* Do not fall back to treating it as a host name */
  439. failf(data, "Couldn't bind to interface '%s'", dev);
  440. return CURLE_INTERFACE_FAILED;
  441. }
  442. break;
  443. case IF2IP_AF_NOT_SUPPORTED:
  444. /* Signal the caller to try another address family if available */
  445. return CURLE_UNSUPPORTED_PROTOCOL;
  446. case IF2IP_FOUND:
  447. is_interface = TRUE;
  448. /*
  449. * We now have the numerical IP address in the 'myhost' buffer
  450. */
  451. infof(data, "Local Interface %s is ip %s using address family %i",
  452. dev, myhost, af);
  453. done = 1;
  454. break;
  455. }
  456. }
  457. if(!is_interface) {
  458. /*
  459. * This was not an interface, resolve the name as a host name
  460. * or IP number
  461. *
  462. * Temporarily force name resolution to use only the address type
  463. * of the connection. The resolve functions should really be changed
  464. * to take a type parameter instead.
  465. */
  466. unsigned char ipver = conn->ip_version;
  467. int rc;
  468. if(af == AF_INET)
  469. conn->ip_version = CURL_IPRESOLVE_V4;
  470. #ifdef USE_IPV6
  471. else if(af == AF_INET6)
  472. conn->ip_version = CURL_IPRESOLVE_V6;
  473. #endif
  474. rc = Curl_resolv(data, dev, 80, FALSE, &h);
  475. if(rc == CURLRESOLV_PENDING)
  476. (void)Curl_resolver_wait_resolv(data, &h);
  477. conn->ip_version = ipver;
  478. if(h) {
  479. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  480. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  481. infof(data, "Name '%s' family %i resolved to '%s' family %i",
  482. dev, af, myhost, h->addr->ai_family);
  483. Curl_resolv_unlock(data, h);
  484. if(af != h->addr->ai_family) {
  485. /* bad IP version combo, signal the caller to try another address
  486. family if available */
  487. return CURLE_UNSUPPORTED_PROTOCOL;
  488. }
  489. done = 1;
  490. }
  491. else {
  492. /*
  493. * provided dev was no interface (or interfaces are not supported
  494. * e.g. solaris) no ip address and no domain we fail here
  495. */
  496. done = -1;
  497. }
  498. }
  499. if(done > 0) {
  500. #ifdef USE_IPV6
  501. /* IPv6 address */
  502. if(af == AF_INET6) {
  503. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  504. char *scope_ptr = strchr(myhost, '%');
  505. if(scope_ptr)
  506. *(scope_ptr++) = '\0';
  507. #endif
  508. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  509. si6->sin6_family = AF_INET6;
  510. si6->sin6_port = htons(port);
  511. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  512. if(scope_ptr) {
  513. /* The "myhost" string either comes from Curl_if2ip or from
  514. Curl_printable_address. The latter returns only numeric scope
  515. IDs and the former returns none at all. So the scope ID, if
  516. present, is known to be numeric */
  517. unsigned long scope_id = strtoul(scope_ptr, NULL, 10);
  518. if(scope_id > UINT_MAX)
  519. return CURLE_UNSUPPORTED_PROTOCOL;
  520. si6->sin6_scope_id = (unsigned int)scope_id;
  521. }
  522. #endif
  523. }
  524. sizeof_sa = sizeof(struct sockaddr_in6);
  525. }
  526. else
  527. #endif
  528. /* IPv4 address */
  529. if((af == AF_INET) &&
  530. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  531. si4->sin_family = AF_INET;
  532. si4->sin_port = htons(port);
  533. sizeof_sa = sizeof(struct sockaddr_in);
  534. }
  535. }
  536. if(done < 1) {
  537. /* errorbuf is set false so failf will overwrite any message already in
  538. the error buffer, so the user receives this error message instead of a
  539. generic resolve error. */
  540. data->state.errorbuf = FALSE;
  541. failf(data, "Couldn't bind to '%s'", dev);
  542. return CURLE_INTERFACE_FAILED;
  543. }
  544. }
  545. else {
  546. /* no device was given, prepare sa to match af's needs */
  547. #ifdef USE_IPV6
  548. if(af == AF_INET6) {
  549. si6->sin6_family = AF_INET6;
  550. si6->sin6_port = htons(port);
  551. sizeof_sa = sizeof(struct sockaddr_in6);
  552. }
  553. else
  554. #endif
  555. if(af == AF_INET) {
  556. si4->sin_family = AF_INET;
  557. si4->sin_port = htons(port);
  558. sizeof_sa = sizeof(struct sockaddr_in);
  559. }
  560. }
  561. #ifdef IP_BIND_ADDRESS_NO_PORT
  562. (void)setsockopt(sockfd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &on, sizeof(on));
  563. #endif
  564. for(;;) {
  565. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  566. /* we succeeded to bind */
  567. struct Curl_sockaddr_storage add;
  568. curl_socklen_t size = sizeof(add);
  569. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  570. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  571. char buffer[STRERROR_LEN];
  572. data->state.os_errno = error = SOCKERRNO;
  573. failf(data, "getsockname() failed with errno %d: %s",
  574. error, Curl_strerror(error, buffer, sizeof(buffer)));
  575. return CURLE_INTERFACE_FAILED;
  576. }
  577. infof(data, "Local port: %hu", port);
  578. conn->bits.bound = TRUE;
  579. return CURLE_OK;
  580. }
  581. if(--portnum > 0) {
  582. port++; /* try next port */
  583. if(port == 0)
  584. break;
  585. infof(data, "Bind to local port %d failed, trying next", port - 1);
  586. /* We reuse/clobber the port variable here below */
  587. if(sock->sa_family == AF_INET)
  588. si4->sin_port = ntohs(port);
  589. #ifdef USE_IPV6
  590. else
  591. si6->sin6_port = ntohs(port);
  592. #endif
  593. }
  594. else
  595. break;
  596. }
  597. {
  598. char buffer[STRERROR_LEN];
  599. data->state.os_errno = error = SOCKERRNO;
  600. failf(data, "bind failed with errno %d: %s",
  601. error, Curl_strerror(error, buffer, sizeof(buffer)));
  602. }
  603. return CURLE_INTERFACE_FAILED;
  604. }
  605. #endif
  606. /*
  607. * verifyconnect() returns TRUE if the connect really has happened.
  608. */
  609. static bool verifyconnect(curl_socket_t sockfd, int *error)
  610. {
  611. bool rc = TRUE;
  612. #ifdef SO_ERROR
  613. int err = 0;
  614. curl_socklen_t errSize = sizeof(err);
  615. #ifdef _WIN32
  616. /*
  617. * In October 2003 we effectively nullified this function on Windows due to
  618. * problems with it using all CPU in multi-threaded cases.
  619. *
  620. * In May 2004, we bring it back to offer more info back on connect failures.
  621. * Gisle Vanem could reproduce the former problems with this function, but
  622. * could avoid them by adding this SleepEx() call below:
  623. *
  624. * "I don't have Rational Quantify, but the hint from his post was
  625. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  626. * just Sleep(0) would be enough?) would release whatever
  627. * mutex/critical-section the ntdll call is waiting on.
  628. *
  629. * Someone got to verify this on Win-NT 4.0, 2000."
  630. */
  631. #ifdef _WIN32_WCE
  632. Sleep(0);
  633. #else
  634. SleepEx(0, FALSE);
  635. #endif
  636. #endif
  637. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  638. err = SOCKERRNO;
  639. #ifdef _WIN32_WCE
  640. /* Old WinCE versions don't support SO_ERROR */
  641. if(WSAENOPROTOOPT == err) {
  642. SET_SOCKERRNO(0);
  643. err = 0;
  644. }
  645. #endif
  646. #if defined(EBADIOCTL) && defined(__minix)
  647. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  648. if(EBADIOCTL == err) {
  649. SET_SOCKERRNO(0);
  650. err = 0;
  651. }
  652. #endif
  653. if((0 == err) || (EISCONN == err))
  654. /* we are connected, awesome! */
  655. rc = TRUE;
  656. else
  657. /* This wasn't a successful connect */
  658. rc = FALSE;
  659. if(error)
  660. *error = err;
  661. #else
  662. (void)sockfd;
  663. if(error)
  664. *error = SOCKERRNO;
  665. #endif
  666. return rc;
  667. }
  668. /**
  669. * Determine the curl code for a socket connect() == -1 with errno.
  670. */
  671. static CURLcode socket_connect_result(struct Curl_easy *data,
  672. const char *ipaddress, int error)
  673. {
  674. switch(error) {
  675. case EINPROGRESS:
  676. case EWOULDBLOCK:
  677. #if defined(EAGAIN)
  678. #if (EAGAIN) != (EWOULDBLOCK)
  679. /* On some platforms EAGAIN and EWOULDBLOCK are the
  680. * same value, and on others they are different, hence
  681. * the odd #if
  682. */
  683. case EAGAIN:
  684. #endif
  685. #endif
  686. return CURLE_OK;
  687. default:
  688. /* unknown error, fallthrough and try another address! */
  689. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  690. (void)ipaddress;
  691. #else
  692. {
  693. char buffer[STRERROR_LEN];
  694. infof(data, "Immediate connect fail for %s: %s",
  695. ipaddress, Curl_strerror(error, buffer, sizeof(buffer)));
  696. }
  697. #endif
  698. data->state.os_errno = error;
  699. /* connect failed */
  700. return CURLE_COULDNT_CONNECT;
  701. }
  702. }
  703. /* We have a recv buffer to enhance reads with len < NW_SMALL_READS.
  704. * This happens often on TLS connections where the TLS implementation
  705. * tries to read the head of a TLS record, determine the length of the
  706. * full record and then make a subsequent read for that.
  707. * On large reads, we will not fill the buffer to avoid the double copy. */
  708. #define NW_RECV_CHUNK_SIZE (64 * 1024)
  709. #define NW_RECV_CHUNKS 1
  710. #define NW_SMALL_READS (1024)
  711. struct cf_socket_ctx {
  712. int transport;
  713. struct Curl_sockaddr_ex addr; /* address to connect to */
  714. curl_socket_t sock; /* current attempt socket */
  715. struct bufq recvbuf; /* used when `buffer_recv` is set */
  716. struct ip_quadruple ip; /* The IP quadruple 2x(addr+port) */
  717. struct curltime started_at; /* when socket was created */
  718. struct curltime connected_at; /* when socket connected/got first byte */
  719. struct curltime first_byte_at; /* when first byte was recvd */
  720. int error; /* errno of last failure or 0 */
  721. #ifdef DEBUGBUILD
  722. int wblock_percent; /* percent of writes doing EAGAIN */
  723. int wpartial_percent; /* percent of bytes written in send */
  724. int rblock_percent; /* percent of reads doing EAGAIN */
  725. size_t recv_max; /* max enforced read size */
  726. #endif
  727. BIT(got_first_byte); /* if first byte was received */
  728. BIT(accepted); /* socket was accepted, not connected */
  729. BIT(sock_connected); /* socket is "connected", e.g. in UDP */
  730. BIT(active);
  731. BIT(buffer_recv);
  732. };
  733. static void cf_socket_ctx_init(struct cf_socket_ctx *ctx,
  734. const struct Curl_addrinfo *ai,
  735. int transport)
  736. {
  737. memset(ctx, 0, sizeof(*ctx));
  738. ctx->sock = CURL_SOCKET_BAD;
  739. ctx->transport = transport;
  740. Curl_sock_assign_addr(&ctx->addr, ai, transport);
  741. Curl_bufq_init(&ctx->recvbuf, NW_RECV_CHUNK_SIZE, NW_RECV_CHUNKS);
  742. #ifdef DEBUGBUILD
  743. {
  744. char *p = getenv("CURL_DBG_SOCK_WBLOCK");
  745. if(p) {
  746. long l = strtol(p, NULL, 10);
  747. if(l >= 0 && l <= 100)
  748. ctx->wblock_percent = (int)l;
  749. }
  750. p = getenv("CURL_DBG_SOCK_WPARTIAL");
  751. if(p) {
  752. long l = strtol(p, NULL, 10);
  753. if(l >= 0 && l <= 100)
  754. ctx->wpartial_percent = (int)l;
  755. }
  756. p = getenv("CURL_DBG_SOCK_RBLOCK");
  757. if(p) {
  758. long l = strtol(p, NULL, 10);
  759. if(l >= 0 && l <= 100)
  760. ctx->rblock_percent = (int)l;
  761. }
  762. p = getenv("CURL_DBG_SOCK_RMAX");
  763. if(p) {
  764. long l = strtol(p, NULL, 10);
  765. if(l >= 0)
  766. ctx->recv_max = (size_t)l;
  767. }
  768. }
  769. #endif
  770. }
  771. struct reader_ctx {
  772. struct Curl_cfilter *cf;
  773. struct Curl_easy *data;
  774. };
  775. static ssize_t nw_in_read(void *reader_ctx,
  776. unsigned char *buf, size_t len,
  777. CURLcode *err)
  778. {
  779. struct reader_ctx *rctx = reader_ctx;
  780. struct cf_socket_ctx *ctx = rctx->cf->ctx;
  781. ssize_t nread;
  782. *err = CURLE_OK;
  783. nread = sread(ctx->sock, buf, len);
  784. if(-1 == nread) {
  785. int sockerr = SOCKERRNO;
  786. if(
  787. #ifdef WSAEWOULDBLOCK
  788. /* This is how Windows does it */
  789. (WSAEWOULDBLOCK == sockerr)
  790. #else
  791. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  792. due to its inability to send off data without blocking. We therefore
  793. treat both error codes the same here */
  794. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr)
  795. #endif
  796. ) {
  797. /* this is just a case of EWOULDBLOCK */
  798. *err = CURLE_AGAIN;
  799. nread = -1;
  800. }
  801. else {
  802. char buffer[STRERROR_LEN];
  803. failf(rctx->data, "Recv failure: %s",
  804. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  805. rctx->data->state.os_errno = sockerr;
  806. *err = CURLE_RECV_ERROR;
  807. nread = -1;
  808. }
  809. }
  810. CURL_TRC_CF(rctx->data, rctx->cf, "nw_in_read(len=%zu, fd=%"
  811. CURL_FORMAT_SOCKET_T ") -> %d, err=%d",
  812. len, ctx->sock, (int)nread, *err);
  813. return nread;
  814. }
  815. static void cf_socket_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  816. {
  817. struct cf_socket_ctx *ctx = cf->ctx;
  818. if(ctx && CURL_SOCKET_BAD != ctx->sock) {
  819. CURL_TRC_CF(data, cf, "cf_socket_close(%" CURL_FORMAT_SOCKET_T
  820. ")", ctx->sock);
  821. if(ctx->sock == cf->conn->sock[cf->sockindex])
  822. cf->conn->sock[cf->sockindex] = CURL_SOCKET_BAD;
  823. socket_close(data, cf->conn, !ctx->accepted, ctx->sock);
  824. ctx->sock = CURL_SOCKET_BAD;
  825. if(ctx->active && cf->sockindex == FIRSTSOCKET)
  826. cf->conn->remote_addr = NULL;
  827. Curl_bufq_reset(&ctx->recvbuf);
  828. ctx->active = FALSE;
  829. ctx->buffer_recv = FALSE;
  830. memset(&ctx->started_at, 0, sizeof(ctx->started_at));
  831. memset(&ctx->connected_at, 0, sizeof(ctx->connected_at));
  832. }
  833. cf->connected = FALSE;
  834. }
  835. static void cf_socket_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
  836. {
  837. struct cf_socket_ctx *ctx = cf->ctx;
  838. cf_socket_close(cf, data);
  839. CURL_TRC_CF(data, cf, "destroy");
  840. Curl_bufq_free(&ctx->recvbuf);
  841. free(ctx);
  842. cf->ctx = NULL;
  843. }
  844. static CURLcode set_local_ip(struct Curl_cfilter *cf,
  845. struct Curl_easy *data)
  846. {
  847. struct cf_socket_ctx *ctx = cf->ctx;
  848. #ifdef HAVE_GETSOCKNAME
  849. if((ctx->sock != CURL_SOCKET_BAD) &&
  850. !(data->conn->handler->protocol & CURLPROTO_TFTP)) {
  851. /* TFTP does not connect, so it cannot get the IP like this */
  852. char buffer[STRERROR_LEN];
  853. struct Curl_sockaddr_storage ssloc;
  854. curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage);
  855. memset(&ssloc, 0, sizeof(ssloc));
  856. if(getsockname(ctx->sock, (struct sockaddr*) &ssloc, &slen)) {
  857. int error = SOCKERRNO;
  858. failf(data, "getsockname() failed with errno %d: %s",
  859. error, Curl_strerror(error, buffer, sizeof(buffer)));
  860. return CURLE_FAILED_INIT;
  861. }
  862. if(!Curl_addr2string((struct sockaddr*)&ssloc, slen,
  863. ctx->ip.local_ip, &ctx->ip.local_port)) {
  864. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  865. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  866. return CURLE_FAILED_INIT;
  867. }
  868. }
  869. #else
  870. (void)data;
  871. ctx->ip.local_ip[0] = 0;
  872. ctx->ip.local_port = -1;
  873. #endif
  874. return CURLE_OK;
  875. }
  876. static CURLcode set_remote_ip(struct Curl_cfilter *cf,
  877. struct Curl_easy *data)
  878. {
  879. struct cf_socket_ctx *ctx = cf->ctx;
  880. /* store remote address and port used in this connection attempt */
  881. if(!Curl_addr2string(&ctx->addr.sa_addr, ctx->addr.addrlen,
  882. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  883. char buffer[STRERROR_LEN];
  884. ctx->error = errno;
  885. /* malformed address or bug in inet_ntop, try next address */
  886. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  887. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  888. return CURLE_FAILED_INIT;
  889. }
  890. return CURLE_OK;
  891. }
  892. static CURLcode cf_socket_open(struct Curl_cfilter *cf,
  893. struct Curl_easy *data)
  894. {
  895. struct cf_socket_ctx *ctx = cf->ctx;
  896. int error = 0;
  897. bool isconnected = FALSE;
  898. CURLcode result = CURLE_COULDNT_CONNECT;
  899. bool is_tcp;
  900. (void)data;
  901. DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD);
  902. ctx->started_at = Curl_now();
  903. result = socket_open(data, &ctx->addr, &ctx->sock);
  904. if(result)
  905. goto out;
  906. result = set_remote_ip(cf, data);
  907. if(result)
  908. goto out;
  909. #ifdef USE_IPV6
  910. if(ctx->addr.family == AF_INET6) {
  911. set_ipv6_v6only(ctx->sock, 0);
  912. infof(data, " Trying [%s]:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  913. }
  914. else
  915. #endif
  916. infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  917. #ifdef USE_IPV6
  918. is_tcp = (ctx->addr.family == AF_INET
  919. || ctx->addr.family == AF_INET6) &&
  920. ctx->addr.socktype == SOCK_STREAM;
  921. #else
  922. is_tcp = (ctx->addr.family == AF_INET) &&
  923. ctx->addr.socktype == SOCK_STREAM;
  924. #endif
  925. if(is_tcp && data->set.tcp_nodelay)
  926. tcpnodelay(data, ctx->sock);
  927. nosigpipe(data, ctx->sock);
  928. Curl_sndbufset(ctx->sock);
  929. if(is_tcp && data->set.tcp_keepalive)
  930. tcpkeepalive(data, ctx->sock);
  931. if(data->set.fsockopt) {
  932. /* activate callback for setting socket options */
  933. Curl_set_in_callback(data, true);
  934. error = data->set.fsockopt(data->set.sockopt_client,
  935. ctx->sock,
  936. CURLSOCKTYPE_IPCXN);
  937. Curl_set_in_callback(data, false);
  938. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  939. isconnected = TRUE;
  940. else if(error) {
  941. result = CURLE_ABORTED_BY_CALLBACK;
  942. goto out;
  943. }
  944. }
  945. #ifndef CURL_DISABLE_BINDLOCAL
  946. /* possibly bind the local end to an IP, interface or port */
  947. if(ctx->addr.family == AF_INET
  948. #ifdef USE_IPV6
  949. || ctx->addr.family == AF_INET6
  950. #endif
  951. ) {
  952. result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family,
  953. Curl_ipv6_scope(&ctx->addr.sa_addr));
  954. if(result) {
  955. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  956. /* The address family is not supported on this interface.
  957. We can continue trying addresses */
  958. result = CURLE_COULDNT_CONNECT;
  959. }
  960. goto out;
  961. }
  962. }
  963. #endif
  964. /* set socket non-blocking */
  965. (void)curlx_nonblock(ctx->sock, TRUE);
  966. ctx->sock_connected = (ctx->addr.socktype != SOCK_DGRAM);
  967. out:
  968. if(result) {
  969. if(ctx->sock != CURL_SOCKET_BAD) {
  970. socket_close(data, cf->conn, TRUE, ctx->sock);
  971. ctx->sock = CURL_SOCKET_BAD;
  972. }
  973. }
  974. else if(isconnected) {
  975. set_local_ip(cf, data);
  976. ctx->connected_at = Curl_now();
  977. cf->connected = TRUE;
  978. }
  979. CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" CURL_FORMAT_SOCKET_T,
  980. result, ctx->sock);
  981. return result;
  982. }
  983. static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data,
  984. bool is_tcp_fastopen)
  985. {
  986. struct cf_socket_ctx *ctx = cf->ctx;
  987. #ifdef TCP_FASTOPEN_CONNECT
  988. int optval = 1;
  989. #endif
  990. int rc = -1;
  991. (void)data;
  992. if(is_tcp_fastopen) {
  993. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  994. # if defined(HAVE_BUILTIN_AVAILABLE)
  995. /* while connectx function is available since macOS 10.11 / iOS 9,
  996. it did not have the interface declared correctly until
  997. Xcode 9 / macOS SDK 10.13 */
  998. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  999. sa_endpoints_t endpoints;
  1000. endpoints.sae_srcif = 0;
  1001. endpoints.sae_srcaddr = NULL;
  1002. endpoints.sae_srcaddrlen = 0;
  1003. endpoints.sae_dstaddr = &ctx->addr.sa_addr;
  1004. endpoints.sae_dstaddrlen = ctx->addr.addrlen;
  1005. rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY,
  1006. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  1007. NULL, 0, NULL, NULL);
  1008. }
  1009. else {
  1010. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1011. }
  1012. # else
  1013. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1014. # endif /* HAVE_BUILTIN_AVAILABLE */
  1015. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  1016. if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  1017. (void *)&optval, sizeof(optval)) < 0)
  1018. infof(data, "Failed to enable TCP Fast Open on fd %"
  1019. CURL_FORMAT_SOCKET_T, ctx->sock);
  1020. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1021. #elif defined(MSG_FASTOPEN) /* old Linux */
  1022. if(cf->conn->given->flags & PROTOPT_SSL)
  1023. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1024. else
  1025. rc = 0; /* Do nothing */
  1026. #endif
  1027. }
  1028. else {
  1029. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1030. }
  1031. return rc;
  1032. }
  1033. static CURLcode cf_tcp_connect(struct Curl_cfilter *cf,
  1034. struct Curl_easy *data,
  1035. bool blocking, bool *done)
  1036. {
  1037. struct cf_socket_ctx *ctx = cf->ctx;
  1038. CURLcode result = CURLE_COULDNT_CONNECT;
  1039. int rc = 0;
  1040. (void)data;
  1041. if(cf->connected) {
  1042. *done = TRUE;
  1043. return CURLE_OK;
  1044. }
  1045. /* TODO: need to support blocking connect? */
  1046. if(blocking)
  1047. return CURLE_UNSUPPORTED_PROTOCOL;
  1048. *done = FALSE; /* a very negative world view is best */
  1049. if(ctx->sock == CURL_SOCKET_BAD) {
  1050. int error;
  1051. result = cf_socket_open(cf, data);
  1052. if(result)
  1053. goto out;
  1054. if(cf->connected) {
  1055. *done = TRUE;
  1056. return CURLE_OK;
  1057. }
  1058. /* Connect TCP socket */
  1059. rc = do_connect(cf, data, cf->conn->bits.tcp_fastopen);
  1060. error = SOCKERRNO;
  1061. set_local_ip(cf, data);
  1062. CURL_TRC_CF(data, cf, "local address %s port %d...",
  1063. ctx->ip.local_ip, ctx->ip.local_port);
  1064. if(-1 == rc) {
  1065. result = socket_connect_result(data, ctx->ip.remote_ip, error);
  1066. goto out;
  1067. }
  1068. }
  1069. #ifdef mpeix
  1070. /* Call this function once now, and ignore the results. We do this to
  1071. "clear" the error state on the socket so that we can later read it
  1072. reliably. This is reported necessary on the MPE/iX operating
  1073. system. */
  1074. (void)verifyconnect(ctx->sock, NULL);
  1075. #endif
  1076. /* check socket for connect */
  1077. rc = SOCKET_WRITABLE(ctx->sock, 0);
  1078. if(rc == 0) { /* no connection yet */
  1079. CURL_TRC_CF(data, cf, "not connected yet");
  1080. return CURLE_OK;
  1081. }
  1082. else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) {
  1083. if(verifyconnect(ctx->sock, &ctx->error)) {
  1084. /* we are connected with TCP, awesome! */
  1085. ctx->connected_at = Curl_now();
  1086. set_local_ip(cf, data);
  1087. *done = TRUE;
  1088. cf->connected = TRUE;
  1089. CURL_TRC_CF(data, cf, "connected");
  1090. return CURLE_OK;
  1091. }
  1092. }
  1093. else if(rc & CURL_CSELECT_ERR) {
  1094. (void)verifyconnect(ctx->sock, &ctx->error);
  1095. result = CURLE_COULDNT_CONNECT;
  1096. }
  1097. out:
  1098. if(result) {
  1099. if(ctx->error) {
  1100. set_local_ip(cf, data);
  1101. data->state.os_errno = ctx->error;
  1102. SET_SOCKERRNO(ctx->error);
  1103. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1104. {
  1105. char buffer[STRERROR_LEN];
  1106. infof(data, "connect to %s port %u from %s port %d failed: %s",
  1107. ctx->ip.remote_ip, ctx->ip.remote_port,
  1108. ctx->ip.local_ip, ctx->ip.local_port,
  1109. Curl_strerror(ctx->error, buffer, sizeof(buffer)));
  1110. }
  1111. #endif
  1112. }
  1113. if(ctx->sock != CURL_SOCKET_BAD) {
  1114. socket_close(data, cf->conn, TRUE, ctx->sock);
  1115. ctx->sock = CURL_SOCKET_BAD;
  1116. }
  1117. *done = FALSE;
  1118. }
  1119. return result;
  1120. }
  1121. static void cf_socket_get_host(struct Curl_cfilter *cf,
  1122. struct Curl_easy *data,
  1123. const char **phost,
  1124. const char **pdisplay_host,
  1125. int *pport)
  1126. {
  1127. struct cf_socket_ctx *ctx = cf->ctx;
  1128. (void)data;
  1129. *phost = cf->conn->host.name;
  1130. *pdisplay_host = cf->conn->host.dispname;
  1131. *pport = ctx->ip.remote_port;
  1132. }
  1133. static void cf_socket_adjust_pollset(struct Curl_cfilter *cf,
  1134. struct Curl_easy *data,
  1135. struct easy_pollset *ps)
  1136. {
  1137. struct cf_socket_ctx *ctx = cf->ctx;
  1138. if(ctx->sock != CURL_SOCKET_BAD) {
  1139. if(!cf->connected) {
  1140. Curl_pollset_set_out_only(data, ps, ctx->sock);
  1141. CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%"
  1142. CURL_FORMAT_SOCKET_T, ctx->sock);
  1143. }
  1144. else if(!ctx->active) {
  1145. Curl_pollset_add_in(data, ps, ctx->sock);
  1146. CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%"
  1147. CURL_FORMAT_SOCKET_T, ctx->sock);
  1148. }
  1149. }
  1150. }
  1151. static bool cf_socket_data_pending(struct Curl_cfilter *cf,
  1152. const struct Curl_easy *data)
  1153. {
  1154. struct cf_socket_ctx *ctx = cf->ctx;
  1155. int readable;
  1156. (void)data;
  1157. if(!Curl_bufq_is_empty(&ctx->recvbuf))
  1158. return TRUE;
  1159. readable = SOCKET_READABLE(ctx->sock, 0);
  1160. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1161. }
  1162. static ssize_t cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1163. const void *buf, size_t len, CURLcode *err)
  1164. {
  1165. struct cf_socket_ctx *ctx = cf->ctx;
  1166. curl_socket_t fdsave;
  1167. ssize_t nwritten;
  1168. size_t orig_len = len;
  1169. *err = CURLE_OK;
  1170. fdsave = cf->conn->sock[cf->sockindex];
  1171. cf->conn->sock[cf->sockindex] = ctx->sock;
  1172. #ifdef DEBUGBUILD
  1173. /* simulate network blocking/partial writes */
  1174. if(ctx->wblock_percent > 0) {
  1175. unsigned char c;
  1176. Curl_rand(data, &c, 1);
  1177. if(c >= ((100-ctx->wblock_percent)*256/100)) {
  1178. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len);
  1179. *err = CURLE_AGAIN;
  1180. nwritten = -1;
  1181. cf->conn->sock[cf->sockindex] = fdsave;
  1182. return nwritten;
  1183. }
  1184. }
  1185. if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) {
  1186. len = len * ctx->wpartial_percent / 100;
  1187. if(!len)
  1188. len = 1;
  1189. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes",
  1190. orig_len, len);
  1191. }
  1192. #endif
  1193. #if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
  1194. if(cf->conn->bits.tcp_fastopen) {
  1195. nwritten = sendto(ctx->sock, buf, len, MSG_FASTOPEN,
  1196. &cf->conn->remote_addr->sa_addr,
  1197. cf->conn->remote_addr->addrlen);
  1198. cf->conn->bits.tcp_fastopen = FALSE;
  1199. }
  1200. else
  1201. #endif
  1202. nwritten = swrite(ctx->sock, buf, len);
  1203. if(-1 == nwritten) {
  1204. int sockerr = SOCKERRNO;
  1205. if(
  1206. #ifdef WSAEWOULDBLOCK
  1207. /* This is how Windows does it */
  1208. (WSAEWOULDBLOCK == sockerr)
  1209. #else
  1210. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  1211. due to its inability to send off data without blocking. We therefore
  1212. treat both error codes the same here */
  1213. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) ||
  1214. (EINPROGRESS == sockerr)
  1215. #endif
  1216. ) {
  1217. /* this is just a case of EWOULDBLOCK */
  1218. *err = CURLE_AGAIN;
  1219. }
  1220. else {
  1221. char buffer[STRERROR_LEN];
  1222. failf(data, "Send failure: %s",
  1223. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  1224. data->state.os_errno = sockerr;
  1225. *err = CURLE_SEND_ERROR;
  1226. }
  1227. }
  1228. CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, err=%d",
  1229. orig_len, (int)nwritten, *err);
  1230. cf->conn->sock[cf->sockindex] = fdsave;
  1231. return nwritten;
  1232. }
  1233. static ssize_t cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1234. char *buf, size_t len, CURLcode *err)
  1235. {
  1236. struct cf_socket_ctx *ctx = cf->ctx;
  1237. curl_socket_t fdsave;
  1238. ssize_t nread;
  1239. *err = CURLE_OK;
  1240. fdsave = cf->conn->sock[cf->sockindex];
  1241. cf->conn->sock[cf->sockindex] = ctx->sock;
  1242. #ifdef DEBUGBUILD
  1243. /* simulate network blocking/partial reads */
  1244. if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) {
  1245. unsigned char c;
  1246. Curl_rand(data, &c, 1);
  1247. if(c >= ((100-ctx->rblock_percent)*256/100)) {
  1248. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len);
  1249. *err = CURLE_AGAIN;
  1250. nread = -1;
  1251. cf->conn->sock[cf->sockindex] = fdsave;
  1252. return nread;
  1253. }
  1254. }
  1255. if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) {
  1256. size_t orig_len = len;
  1257. len = ctx->recv_max;
  1258. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes",
  1259. orig_len, len);
  1260. }
  1261. #endif
  1262. if(ctx->buffer_recv && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1263. CURL_TRC_CF(data, cf, "recv from buffer");
  1264. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1265. }
  1266. else {
  1267. struct reader_ctx rctx;
  1268. rctx.cf = cf;
  1269. rctx.data = data;
  1270. /* "small" reads may trigger filling our buffer, "large" reads
  1271. * are probably not worth the additional copy */
  1272. if(ctx->buffer_recv && len < NW_SMALL_READS) {
  1273. ssize_t nwritten;
  1274. nwritten = Curl_bufq_slurp(&ctx->recvbuf, nw_in_read, &rctx, err);
  1275. if(nwritten < 0 && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1276. /* we have a partial read with an error. need to deliver
  1277. * what we got, return the error later. */
  1278. CURL_TRC_CF(data, cf, "partial read: empty buffer first");
  1279. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1280. }
  1281. else if(nwritten < 0) {
  1282. nread = -1;
  1283. goto out;
  1284. }
  1285. else if(nwritten == 0) {
  1286. /* eof */
  1287. *err = CURLE_OK;
  1288. nread = 0;
  1289. }
  1290. else {
  1291. CURL_TRC_CF(data, cf, "buffered %zd additional bytes", nwritten);
  1292. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1293. }
  1294. }
  1295. else {
  1296. nread = nw_in_read(&rctx, (unsigned char *)buf, len, err);
  1297. }
  1298. }
  1299. out:
  1300. CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, err=%d", len, (int)nread,
  1301. *err);
  1302. if(nread > 0 && !ctx->got_first_byte) {
  1303. ctx->first_byte_at = Curl_now();
  1304. ctx->got_first_byte = TRUE;
  1305. }
  1306. cf->conn->sock[cf->sockindex] = fdsave;
  1307. return nread;
  1308. }
  1309. static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data)
  1310. {
  1311. struct cf_socket_ctx *ctx = cf->ctx;
  1312. /* use this socket from now on */
  1313. cf->conn->sock[cf->sockindex] = ctx->sock;
  1314. set_local_ip(cf, data);
  1315. if(cf->sockindex == SECONDARYSOCKET)
  1316. cf->conn->secondary = ctx->ip;
  1317. else
  1318. cf->conn->primary = ctx->ip;
  1319. /* the first socket info gets some specials */
  1320. if(cf->sockindex == FIRSTSOCKET) {
  1321. cf->conn->remote_addr = &ctx->addr;
  1322. #ifdef USE_IPV6
  1323. cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6)? TRUE : FALSE;
  1324. #endif
  1325. Curl_persistconninfo(data, cf->conn, &ctx->ip);
  1326. /* buffering is currently disabled by default because we have stalls
  1327. * in parallel transfers where not all buffered data is consumed and no
  1328. * socket events happen.
  1329. */
  1330. ctx->buffer_recv = FALSE;
  1331. }
  1332. ctx->active = TRUE;
  1333. }
  1334. static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf,
  1335. struct Curl_easy *data,
  1336. int event, int arg1, void *arg2)
  1337. {
  1338. struct cf_socket_ctx *ctx = cf->ctx;
  1339. (void)arg1;
  1340. (void)arg2;
  1341. switch(event) {
  1342. case CF_CTRL_CONN_INFO_UPDATE:
  1343. cf_socket_active(cf, data);
  1344. break;
  1345. case CF_CTRL_DATA_SETUP:
  1346. Curl_persistconninfo(data, cf->conn, &ctx->ip);
  1347. break;
  1348. case CF_CTRL_FORGET_SOCKET:
  1349. ctx->sock = CURL_SOCKET_BAD;
  1350. break;
  1351. }
  1352. return CURLE_OK;
  1353. }
  1354. static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf,
  1355. struct Curl_easy *data,
  1356. bool *input_pending)
  1357. {
  1358. struct cf_socket_ctx *ctx = cf->ctx;
  1359. struct pollfd pfd[1];
  1360. int r;
  1361. *input_pending = FALSE;
  1362. (void)data;
  1363. if(!ctx || ctx->sock == CURL_SOCKET_BAD)
  1364. return FALSE;
  1365. /* Check with 0 timeout if there are any events pending on the socket */
  1366. pfd[0].fd = ctx->sock;
  1367. pfd[0].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
  1368. pfd[0].revents = 0;
  1369. r = Curl_poll(pfd, 1, 0);
  1370. if(r < 0) {
  1371. CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead");
  1372. return FALSE;
  1373. }
  1374. else if(r == 0) {
  1375. CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive");
  1376. return TRUE;
  1377. }
  1378. else if(pfd[0].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) {
  1379. CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead");
  1380. return FALSE;
  1381. }
  1382. CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive");
  1383. *input_pending = TRUE;
  1384. return TRUE;
  1385. }
  1386. static CURLcode cf_socket_query(struct Curl_cfilter *cf,
  1387. struct Curl_easy *data,
  1388. int query, int *pres1, void *pres2)
  1389. {
  1390. struct cf_socket_ctx *ctx = cf->ctx;
  1391. switch(query) {
  1392. case CF_QUERY_SOCKET:
  1393. DEBUGASSERT(pres2);
  1394. *((curl_socket_t *)pres2) = ctx->sock;
  1395. return CURLE_OK;
  1396. case CF_QUERY_CONNECT_REPLY_MS:
  1397. if(ctx->got_first_byte) {
  1398. timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at);
  1399. *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX;
  1400. }
  1401. else
  1402. *pres1 = -1;
  1403. return CURLE_OK;
  1404. case CF_QUERY_TIMER_CONNECT: {
  1405. struct curltime *when = pres2;
  1406. switch(ctx->transport) {
  1407. case TRNSPRT_UDP:
  1408. case TRNSPRT_QUIC:
  1409. /* Since UDP connected sockets work different from TCP, we use the
  1410. * time of the first byte from the peer as the "connect" time. */
  1411. if(ctx->got_first_byte) {
  1412. *when = ctx->first_byte_at;
  1413. break;
  1414. }
  1415. FALLTHROUGH();
  1416. default:
  1417. *when = ctx->connected_at;
  1418. break;
  1419. }
  1420. return CURLE_OK;
  1421. }
  1422. default:
  1423. break;
  1424. }
  1425. return cf->next?
  1426. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  1427. CURLE_UNKNOWN_OPTION;
  1428. }
  1429. struct Curl_cftype Curl_cft_tcp = {
  1430. "TCP",
  1431. CF_TYPE_IP_CONNECT,
  1432. CURL_LOG_LVL_NONE,
  1433. cf_socket_destroy,
  1434. cf_tcp_connect,
  1435. cf_socket_close,
  1436. cf_socket_get_host,
  1437. cf_socket_adjust_pollset,
  1438. cf_socket_data_pending,
  1439. cf_socket_send,
  1440. cf_socket_recv,
  1441. cf_socket_cntrl,
  1442. cf_socket_conn_is_alive,
  1443. Curl_cf_def_conn_keep_alive,
  1444. cf_socket_query,
  1445. };
  1446. CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
  1447. struct Curl_easy *data,
  1448. struct connectdata *conn,
  1449. const struct Curl_addrinfo *ai,
  1450. int transport)
  1451. {
  1452. struct cf_socket_ctx *ctx = NULL;
  1453. struct Curl_cfilter *cf = NULL;
  1454. CURLcode result;
  1455. (void)data;
  1456. (void)conn;
  1457. DEBUGASSERT(transport == TRNSPRT_TCP);
  1458. ctx = calloc(1, sizeof(*ctx));
  1459. if(!ctx) {
  1460. result = CURLE_OUT_OF_MEMORY;
  1461. goto out;
  1462. }
  1463. cf_socket_ctx_init(ctx, ai, transport);
  1464. result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx);
  1465. out:
  1466. *pcf = (!result)? cf : NULL;
  1467. if(result) {
  1468. Curl_safefree(cf);
  1469. Curl_safefree(ctx);
  1470. }
  1471. return result;
  1472. }
  1473. static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf,
  1474. struct Curl_easy *data)
  1475. {
  1476. struct cf_socket_ctx *ctx = cf->ctx;
  1477. int rc;
  1478. /* QUIC needs a connected socket, nonblocking */
  1479. DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD);
  1480. #if defined(__APPLE__) && defined(USE_OPENSSL_QUIC)
  1481. (void)rc;
  1482. /* On macOS OpenSSL QUIC fails on connected sockets.
  1483. * see: <https://github.com/openssl/openssl/issues/23251> */
  1484. #else
  1485. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1486. if(-1 == rc) {
  1487. return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO);
  1488. }
  1489. ctx->sock_connected = TRUE;
  1490. #endif
  1491. set_local_ip(cf, data);
  1492. CURL_TRC_CF(data, cf, "%s socket %" CURL_FORMAT_SOCKET_T
  1493. " connected: [%s:%d] -> [%s:%d]",
  1494. (ctx->transport == TRNSPRT_QUIC)? "QUIC" : "UDP",
  1495. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port,
  1496. ctx->ip.remote_ip, ctx->ip.remote_port);
  1497. (void)curlx_nonblock(ctx->sock, TRUE);
  1498. switch(ctx->addr.family) {
  1499. #if defined(__linux__) && defined(IP_MTU_DISCOVER)
  1500. case AF_INET: {
  1501. int val = IP_PMTUDISC_DO;
  1502. (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val,
  1503. sizeof(val));
  1504. break;
  1505. }
  1506. #endif
  1507. #if defined(__linux__) && defined(IPV6_MTU_DISCOVER)
  1508. case AF_INET6: {
  1509. int val = IPV6_PMTUDISC_DO;
  1510. (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
  1511. sizeof(val));
  1512. break;
  1513. }
  1514. #endif
  1515. }
  1516. return CURLE_OK;
  1517. }
  1518. static CURLcode cf_udp_connect(struct Curl_cfilter *cf,
  1519. struct Curl_easy *data,
  1520. bool blocking, bool *done)
  1521. {
  1522. struct cf_socket_ctx *ctx = cf->ctx;
  1523. CURLcode result = CURLE_COULDNT_CONNECT;
  1524. (void)blocking;
  1525. if(cf->connected) {
  1526. *done = TRUE;
  1527. return CURLE_OK;
  1528. }
  1529. *done = FALSE;
  1530. if(ctx->sock == CURL_SOCKET_BAD) {
  1531. result = cf_socket_open(cf, data);
  1532. if(result) {
  1533. CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", result);
  1534. goto out;
  1535. }
  1536. if(ctx->transport == TRNSPRT_QUIC) {
  1537. result = cf_udp_setup_quic(cf, data);
  1538. if(result)
  1539. goto out;
  1540. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1541. CURL_FORMAT_SOCKET_T " (%s:%d)",
  1542. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port);
  1543. }
  1544. else {
  1545. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1546. CURL_FORMAT_SOCKET_T " (unconnected)", ctx->sock);
  1547. }
  1548. *done = TRUE;
  1549. cf->connected = TRUE;
  1550. }
  1551. out:
  1552. return result;
  1553. }
  1554. struct Curl_cftype Curl_cft_udp = {
  1555. "UDP",
  1556. CF_TYPE_IP_CONNECT,
  1557. CURL_LOG_LVL_NONE,
  1558. cf_socket_destroy,
  1559. cf_udp_connect,
  1560. cf_socket_close,
  1561. cf_socket_get_host,
  1562. cf_socket_adjust_pollset,
  1563. cf_socket_data_pending,
  1564. cf_socket_send,
  1565. cf_socket_recv,
  1566. cf_socket_cntrl,
  1567. cf_socket_conn_is_alive,
  1568. Curl_cf_def_conn_keep_alive,
  1569. cf_socket_query,
  1570. };
  1571. CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
  1572. struct Curl_easy *data,
  1573. struct connectdata *conn,
  1574. const struct Curl_addrinfo *ai,
  1575. int transport)
  1576. {
  1577. struct cf_socket_ctx *ctx = NULL;
  1578. struct Curl_cfilter *cf = NULL;
  1579. CURLcode result;
  1580. (void)data;
  1581. (void)conn;
  1582. DEBUGASSERT(transport == TRNSPRT_UDP || transport == TRNSPRT_QUIC);
  1583. ctx = calloc(1, sizeof(*ctx));
  1584. if(!ctx) {
  1585. result = CURLE_OUT_OF_MEMORY;
  1586. goto out;
  1587. }
  1588. cf_socket_ctx_init(ctx, ai, transport);
  1589. result = Curl_cf_create(&cf, &Curl_cft_udp, ctx);
  1590. out:
  1591. *pcf = (!result)? cf : NULL;
  1592. if(result) {
  1593. Curl_safefree(cf);
  1594. Curl_safefree(ctx);
  1595. }
  1596. return result;
  1597. }
  1598. /* this is the TCP filter which can also handle this case */
  1599. struct Curl_cftype Curl_cft_unix = {
  1600. "UNIX",
  1601. CF_TYPE_IP_CONNECT,
  1602. CURL_LOG_LVL_NONE,
  1603. cf_socket_destroy,
  1604. cf_tcp_connect,
  1605. cf_socket_close,
  1606. cf_socket_get_host,
  1607. cf_socket_adjust_pollset,
  1608. cf_socket_data_pending,
  1609. cf_socket_send,
  1610. cf_socket_recv,
  1611. cf_socket_cntrl,
  1612. cf_socket_conn_is_alive,
  1613. Curl_cf_def_conn_keep_alive,
  1614. cf_socket_query,
  1615. };
  1616. CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
  1617. struct Curl_easy *data,
  1618. struct connectdata *conn,
  1619. const struct Curl_addrinfo *ai,
  1620. int transport)
  1621. {
  1622. struct cf_socket_ctx *ctx = NULL;
  1623. struct Curl_cfilter *cf = NULL;
  1624. CURLcode result;
  1625. (void)data;
  1626. (void)conn;
  1627. DEBUGASSERT(transport == TRNSPRT_UNIX);
  1628. ctx = calloc(1, sizeof(*ctx));
  1629. if(!ctx) {
  1630. result = CURLE_OUT_OF_MEMORY;
  1631. goto out;
  1632. }
  1633. cf_socket_ctx_init(ctx, ai, transport);
  1634. result = Curl_cf_create(&cf, &Curl_cft_unix, ctx);
  1635. out:
  1636. *pcf = (!result)? cf : NULL;
  1637. if(result) {
  1638. Curl_safefree(cf);
  1639. Curl_safefree(ctx);
  1640. }
  1641. return result;
  1642. }
  1643. static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
  1644. struct Curl_easy *data,
  1645. bool blocking, bool *done)
  1646. {
  1647. /* we start accepted, if we ever close, we cannot go on */
  1648. (void)data;
  1649. (void)blocking;
  1650. if(cf->connected) {
  1651. *done = TRUE;
  1652. return CURLE_OK;
  1653. }
  1654. return CURLE_FAILED_INIT;
  1655. }
  1656. struct Curl_cftype Curl_cft_tcp_accept = {
  1657. "TCP-ACCEPT",
  1658. CF_TYPE_IP_CONNECT,
  1659. CURL_LOG_LVL_NONE,
  1660. cf_socket_destroy,
  1661. cf_tcp_accept_connect,
  1662. cf_socket_close,
  1663. cf_socket_get_host, /* TODO: not accurate */
  1664. cf_socket_adjust_pollset,
  1665. cf_socket_data_pending,
  1666. cf_socket_send,
  1667. cf_socket_recv,
  1668. cf_socket_cntrl,
  1669. cf_socket_conn_is_alive,
  1670. Curl_cf_def_conn_keep_alive,
  1671. cf_socket_query,
  1672. };
  1673. CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
  1674. struct connectdata *conn,
  1675. int sockindex, curl_socket_t *s)
  1676. {
  1677. CURLcode result;
  1678. struct Curl_cfilter *cf = NULL;
  1679. struct cf_socket_ctx *ctx = NULL;
  1680. /* replace any existing */
  1681. Curl_conn_cf_discard_all(data, conn, sockindex);
  1682. DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD);
  1683. ctx = calloc(1, sizeof(*ctx));
  1684. if(!ctx) {
  1685. result = CURLE_OUT_OF_MEMORY;
  1686. goto out;
  1687. }
  1688. ctx->transport = conn->transport;
  1689. ctx->sock = *s;
  1690. ctx->accepted = FALSE;
  1691. result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx);
  1692. if(result)
  1693. goto out;
  1694. Curl_conn_cf_add(data, conn, sockindex, cf);
  1695. conn->sock[sockindex] = ctx->sock;
  1696. set_local_ip(cf, data);
  1697. ctx->active = TRUE;
  1698. ctx->connected_at = Curl_now();
  1699. cf->connected = TRUE;
  1700. CURL_TRC_CF(data, cf, "Curl_conn_tcp_listen_set(%"
  1701. CURL_FORMAT_SOCKET_T ")", ctx->sock);
  1702. out:
  1703. if(result) {
  1704. Curl_safefree(cf);
  1705. Curl_safefree(ctx);
  1706. }
  1707. return result;
  1708. }
  1709. static void set_accepted_remote_ip(struct Curl_cfilter *cf,
  1710. struct Curl_easy *data)
  1711. {
  1712. struct cf_socket_ctx *ctx = cf->ctx;
  1713. #ifdef HAVE_GETPEERNAME
  1714. char buffer[STRERROR_LEN];
  1715. struct Curl_sockaddr_storage ssrem;
  1716. curl_socklen_t plen;
  1717. ctx->ip.remote_ip[0] = 0;
  1718. ctx->ip.remote_port = 0;
  1719. plen = sizeof(ssrem);
  1720. memset(&ssrem, 0, plen);
  1721. if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) {
  1722. int error = SOCKERRNO;
  1723. failf(data, "getpeername() failed with errno %d: %s",
  1724. error, Curl_strerror(error, buffer, sizeof(buffer)));
  1725. return;
  1726. }
  1727. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  1728. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  1729. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  1730. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1731. return;
  1732. }
  1733. #else
  1734. ctx->ip.remote_ip[0] = 0;
  1735. ctx->ip.remote_port = 0;
  1736. (void)data;
  1737. #endif
  1738. }
  1739. CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data,
  1740. struct connectdata *conn,
  1741. int sockindex, curl_socket_t *s)
  1742. {
  1743. struct Curl_cfilter *cf = NULL;
  1744. struct cf_socket_ctx *ctx = NULL;
  1745. cf = conn->cfilter[sockindex];
  1746. if(!cf || cf->cft != &Curl_cft_tcp_accept)
  1747. return CURLE_FAILED_INIT;
  1748. ctx = cf->ctx;
  1749. /* discard the listen socket */
  1750. socket_close(data, conn, TRUE, ctx->sock);
  1751. ctx->sock = *s;
  1752. conn->sock[sockindex] = ctx->sock;
  1753. set_accepted_remote_ip(cf, data);
  1754. set_local_ip(cf, data);
  1755. ctx->active = TRUE;
  1756. ctx->accepted = TRUE;
  1757. ctx->connected_at = Curl_now();
  1758. cf->connected = TRUE;
  1759. CURL_TRC_CF(data, cf, "accepted_set(sock=%" CURL_FORMAT_SOCKET_T
  1760. ", remote=%s port=%d)",
  1761. ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port);
  1762. return CURLE_OK;
  1763. }
  1764. /**
  1765. * Return TRUE iff `cf` is a socket filter.
  1766. */
  1767. static bool cf_is_socket(struct Curl_cfilter *cf)
  1768. {
  1769. return cf && (cf->cft == &Curl_cft_tcp ||
  1770. cf->cft == &Curl_cft_udp ||
  1771. cf->cft == &Curl_cft_unix ||
  1772. cf->cft == &Curl_cft_tcp_accept);
  1773. }
  1774. CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
  1775. struct Curl_easy *data,
  1776. curl_socket_t *psock,
  1777. const struct Curl_sockaddr_ex **paddr,
  1778. struct ip_quadruple *pip)
  1779. {
  1780. (void)data;
  1781. if(cf_is_socket(cf) && cf->ctx) {
  1782. struct cf_socket_ctx *ctx = cf->ctx;
  1783. if(psock)
  1784. *psock = ctx->sock;
  1785. if(paddr)
  1786. *paddr = &ctx->addr;
  1787. if(pip)
  1788. *pip = ctx->ip;
  1789. return CURLE_OK;
  1790. }
  1791. return CURLE_FAILED_INIT;
  1792. }