cf-socket.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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(!(data->conn->handler->protocol & CURLPROTO_TFTP)) {
  850. /* TFTP does not connect, so it cannot get the IP like this */
  851. char buffer[STRERROR_LEN];
  852. struct Curl_sockaddr_storage ssloc;
  853. curl_socklen_t slen = sizeof(struct Curl_sockaddr_storage);
  854. memset(&ssloc, 0, sizeof(ssloc));
  855. if(getsockname(ctx->sock, (struct sockaddr*) &ssloc, &slen)) {
  856. int error = SOCKERRNO;
  857. failf(data, "getsockname() failed with errno %d: %s",
  858. error, Curl_strerror(error, buffer, sizeof(buffer)));
  859. return CURLE_FAILED_INIT;
  860. }
  861. if(!Curl_addr2string((struct sockaddr*)&ssloc, slen,
  862. ctx->ip.local_ip, &ctx->ip.local_port)) {
  863. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  864. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  865. return CURLE_FAILED_INIT;
  866. }
  867. }
  868. #else
  869. (void)data;
  870. ctx->ip.local_ip[0] = 0;
  871. ctx->ip.local_port = -1;
  872. #endif
  873. return CURLE_OK;
  874. }
  875. static CURLcode set_remote_ip(struct Curl_cfilter *cf,
  876. struct Curl_easy *data)
  877. {
  878. struct cf_socket_ctx *ctx = cf->ctx;
  879. /* store remote address and port used in this connection attempt */
  880. if(!Curl_addr2string(&ctx->addr.sa_addr, ctx->addr.addrlen,
  881. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  882. char buffer[STRERROR_LEN];
  883. ctx->error = errno;
  884. /* malformed address or bug in inet_ntop, try next address */
  885. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  886. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  887. return CURLE_FAILED_INIT;
  888. }
  889. return CURLE_OK;
  890. }
  891. static CURLcode cf_socket_open(struct Curl_cfilter *cf,
  892. struct Curl_easy *data)
  893. {
  894. struct cf_socket_ctx *ctx = cf->ctx;
  895. int error = 0;
  896. bool isconnected = FALSE;
  897. CURLcode result = CURLE_COULDNT_CONNECT;
  898. bool is_tcp;
  899. (void)data;
  900. DEBUGASSERT(ctx->sock == CURL_SOCKET_BAD);
  901. ctx->started_at = Curl_now();
  902. result = socket_open(data, &ctx->addr, &ctx->sock);
  903. if(result)
  904. goto out;
  905. result = set_remote_ip(cf, data);
  906. if(result)
  907. goto out;
  908. #ifdef USE_IPV6
  909. if(ctx->addr.family == AF_INET6) {
  910. set_ipv6_v6only(ctx->sock, 0);
  911. infof(data, " Trying [%s]:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  912. }
  913. else
  914. #endif
  915. infof(data, " Trying %s:%d...", ctx->ip.remote_ip, ctx->ip.remote_port);
  916. #ifdef USE_IPV6
  917. is_tcp = (ctx->addr.family == AF_INET
  918. || ctx->addr.family == AF_INET6) &&
  919. ctx->addr.socktype == SOCK_STREAM;
  920. #else
  921. is_tcp = (ctx->addr.family == AF_INET) &&
  922. ctx->addr.socktype == SOCK_STREAM;
  923. #endif
  924. if(is_tcp && data->set.tcp_nodelay)
  925. tcpnodelay(data, ctx->sock);
  926. nosigpipe(data, ctx->sock);
  927. Curl_sndbufset(ctx->sock);
  928. if(is_tcp && data->set.tcp_keepalive)
  929. tcpkeepalive(data, ctx->sock);
  930. if(data->set.fsockopt) {
  931. /* activate callback for setting socket options */
  932. Curl_set_in_callback(data, true);
  933. error = data->set.fsockopt(data->set.sockopt_client,
  934. ctx->sock,
  935. CURLSOCKTYPE_IPCXN);
  936. Curl_set_in_callback(data, false);
  937. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  938. isconnected = TRUE;
  939. else if(error) {
  940. result = CURLE_ABORTED_BY_CALLBACK;
  941. goto out;
  942. }
  943. }
  944. #ifndef CURL_DISABLE_BINDLOCAL
  945. /* possibly bind the local end to an IP, interface or port */
  946. if(ctx->addr.family == AF_INET
  947. #ifdef USE_IPV6
  948. || ctx->addr.family == AF_INET6
  949. #endif
  950. ) {
  951. result = bindlocal(data, cf->conn, ctx->sock, ctx->addr.family,
  952. Curl_ipv6_scope(&ctx->addr.sa_addr));
  953. if(result) {
  954. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  955. /* The address family is not supported on this interface.
  956. We can continue trying addresses */
  957. result = CURLE_COULDNT_CONNECT;
  958. }
  959. goto out;
  960. }
  961. }
  962. #endif
  963. /* set socket non-blocking */
  964. (void)curlx_nonblock(ctx->sock, TRUE);
  965. ctx->sock_connected = (ctx->addr.socktype != SOCK_DGRAM);
  966. out:
  967. if(result) {
  968. if(ctx->sock != CURL_SOCKET_BAD) {
  969. socket_close(data, cf->conn, TRUE, ctx->sock);
  970. ctx->sock = CURL_SOCKET_BAD;
  971. }
  972. }
  973. else if(isconnected) {
  974. set_local_ip(cf, data);
  975. ctx->connected_at = Curl_now();
  976. cf->connected = TRUE;
  977. }
  978. CURL_TRC_CF(data, cf, "cf_socket_open() -> %d, fd=%" CURL_FORMAT_SOCKET_T,
  979. result, ctx->sock);
  980. return result;
  981. }
  982. static int do_connect(struct Curl_cfilter *cf, struct Curl_easy *data,
  983. bool is_tcp_fastopen)
  984. {
  985. struct cf_socket_ctx *ctx = cf->ctx;
  986. #ifdef TCP_FASTOPEN_CONNECT
  987. int optval = 1;
  988. #endif
  989. int rc = -1;
  990. (void)data;
  991. if(is_tcp_fastopen) {
  992. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  993. # if defined(HAVE_BUILTIN_AVAILABLE)
  994. /* while connectx function is available since macOS 10.11 / iOS 9,
  995. it did not have the interface declared correctly until
  996. Xcode 9 / macOS SDK 10.13 */
  997. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  998. sa_endpoints_t endpoints;
  999. endpoints.sae_srcif = 0;
  1000. endpoints.sae_srcaddr = NULL;
  1001. endpoints.sae_srcaddrlen = 0;
  1002. endpoints.sae_dstaddr = &ctx->addr.sa_addr;
  1003. endpoints.sae_dstaddrlen = ctx->addr.addrlen;
  1004. rc = connectx(ctx->sock, &endpoints, SAE_ASSOCID_ANY,
  1005. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  1006. NULL, 0, NULL, NULL);
  1007. }
  1008. else {
  1009. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1010. }
  1011. # else
  1012. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1013. # endif /* HAVE_BUILTIN_AVAILABLE */
  1014. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  1015. if(setsockopt(ctx->sock, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  1016. (void *)&optval, sizeof(optval)) < 0)
  1017. infof(data, "Failed to enable TCP Fast Open on fd %"
  1018. CURL_FORMAT_SOCKET_T, ctx->sock);
  1019. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1020. #elif defined(MSG_FASTOPEN) /* old Linux */
  1021. if(cf->conn->given->flags & PROTOPT_SSL)
  1022. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1023. else
  1024. rc = 0; /* Do nothing */
  1025. #endif
  1026. }
  1027. else {
  1028. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1029. }
  1030. return rc;
  1031. }
  1032. static CURLcode cf_tcp_connect(struct Curl_cfilter *cf,
  1033. struct Curl_easy *data,
  1034. bool blocking, bool *done)
  1035. {
  1036. struct cf_socket_ctx *ctx = cf->ctx;
  1037. CURLcode result = CURLE_COULDNT_CONNECT;
  1038. int rc = 0;
  1039. (void)data;
  1040. if(cf->connected) {
  1041. *done = TRUE;
  1042. return CURLE_OK;
  1043. }
  1044. /* TODO: need to support blocking connect? */
  1045. if(blocking)
  1046. return CURLE_UNSUPPORTED_PROTOCOL;
  1047. *done = FALSE; /* a very negative world view is best */
  1048. if(ctx->sock == CURL_SOCKET_BAD) {
  1049. int error;
  1050. result = cf_socket_open(cf, data);
  1051. if(result)
  1052. goto out;
  1053. if(cf->connected) {
  1054. *done = TRUE;
  1055. return CURLE_OK;
  1056. }
  1057. /* Connect TCP socket */
  1058. rc = do_connect(cf, data, cf->conn->bits.tcp_fastopen);
  1059. error = SOCKERRNO;
  1060. set_local_ip(cf, data);
  1061. CURL_TRC_CF(data, cf, "local address %s port %d...",
  1062. ctx->ip.local_ip, ctx->ip.local_port);
  1063. if(-1 == rc) {
  1064. result = socket_connect_result(data, ctx->ip.remote_ip, error);
  1065. goto out;
  1066. }
  1067. }
  1068. #ifdef mpeix
  1069. /* Call this function once now, and ignore the results. We do this to
  1070. "clear" the error state on the socket so that we can later read it
  1071. reliably. This is reported necessary on the MPE/iX operating
  1072. system. */
  1073. (void)verifyconnect(ctx->sock, NULL);
  1074. #endif
  1075. /* check socket for connect */
  1076. rc = SOCKET_WRITABLE(ctx->sock, 0);
  1077. if(rc == 0) { /* no connection yet */
  1078. CURL_TRC_CF(data, cf, "not connected yet");
  1079. return CURLE_OK;
  1080. }
  1081. else if(rc == CURL_CSELECT_OUT || cf->conn->bits.tcp_fastopen) {
  1082. if(verifyconnect(ctx->sock, &ctx->error)) {
  1083. /* we are connected with TCP, awesome! */
  1084. ctx->connected_at = Curl_now();
  1085. set_local_ip(cf, data);
  1086. *done = TRUE;
  1087. cf->connected = TRUE;
  1088. CURL_TRC_CF(data, cf, "connected");
  1089. return CURLE_OK;
  1090. }
  1091. }
  1092. else if(rc & CURL_CSELECT_ERR) {
  1093. (void)verifyconnect(ctx->sock, &ctx->error);
  1094. result = CURLE_COULDNT_CONNECT;
  1095. }
  1096. out:
  1097. if(result) {
  1098. if(ctx->error) {
  1099. set_local_ip(cf, data);
  1100. data->state.os_errno = ctx->error;
  1101. SET_SOCKERRNO(ctx->error);
  1102. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1103. {
  1104. char buffer[STRERROR_LEN];
  1105. infof(data, "connect to %s port %u from %s port %d failed: %s",
  1106. ctx->ip.remote_ip, ctx->ip.remote_port,
  1107. ctx->ip.local_ip, ctx->ip.local_port,
  1108. Curl_strerror(ctx->error, buffer, sizeof(buffer)));
  1109. }
  1110. #endif
  1111. }
  1112. if(ctx->sock != CURL_SOCKET_BAD) {
  1113. socket_close(data, cf->conn, TRUE, ctx->sock);
  1114. ctx->sock = CURL_SOCKET_BAD;
  1115. }
  1116. *done = FALSE;
  1117. }
  1118. return result;
  1119. }
  1120. static void cf_socket_get_host(struct Curl_cfilter *cf,
  1121. struct Curl_easy *data,
  1122. const char **phost,
  1123. const char **pdisplay_host,
  1124. int *pport)
  1125. {
  1126. struct cf_socket_ctx *ctx = cf->ctx;
  1127. (void)data;
  1128. *phost = cf->conn->host.name;
  1129. *pdisplay_host = cf->conn->host.dispname;
  1130. *pport = ctx->ip.remote_port;
  1131. }
  1132. static void cf_socket_adjust_pollset(struct Curl_cfilter *cf,
  1133. struct Curl_easy *data,
  1134. struct easy_pollset *ps)
  1135. {
  1136. struct cf_socket_ctx *ctx = cf->ctx;
  1137. if(ctx->sock != CURL_SOCKET_BAD) {
  1138. if(!cf->connected) {
  1139. Curl_pollset_set_out_only(data, ps, ctx->sock);
  1140. CURL_TRC_CF(data, cf, "adjust_pollset, !connected, POLLOUT fd=%"
  1141. CURL_FORMAT_SOCKET_T, ctx->sock);
  1142. }
  1143. else if(!ctx->active) {
  1144. Curl_pollset_add_in(data, ps, ctx->sock);
  1145. CURL_TRC_CF(data, cf, "adjust_pollset, !active, POLLIN fd=%"
  1146. CURL_FORMAT_SOCKET_T, ctx->sock);
  1147. }
  1148. }
  1149. }
  1150. static bool cf_socket_data_pending(struct Curl_cfilter *cf,
  1151. const struct Curl_easy *data)
  1152. {
  1153. struct cf_socket_ctx *ctx = cf->ctx;
  1154. int readable;
  1155. (void)data;
  1156. if(!Curl_bufq_is_empty(&ctx->recvbuf))
  1157. return TRUE;
  1158. readable = SOCKET_READABLE(ctx->sock, 0);
  1159. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1160. }
  1161. static ssize_t cf_socket_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1162. const void *buf, size_t len, CURLcode *err)
  1163. {
  1164. struct cf_socket_ctx *ctx = cf->ctx;
  1165. curl_socket_t fdsave;
  1166. ssize_t nwritten;
  1167. size_t orig_len = len;
  1168. *err = CURLE_OK;
  1169. fdsave = cf->conn->sock[cf->sockindex];
  1170. cf->conn->sock[cf->sockindex] = ctx->sock;
  1171. #ifdef DEBUGBUILD
  1172. /* simulate network blocking/partial writes */
  1173. if(ctx->wblock_percent > 0) {
  1174. unsigned char c;
  1175. Curl_rand(data, &c, 1);
  1176. if(c >= ((100-ctx->wblock_percent)*256/100)) {
  1177. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE EWOULDBLOCK", orig_len);
  1178. *err = CURLE_AGAIN;
  1179. nwritten = -1;
  1180. cf->conn->sock[cf->sockindex] = fdsave;
  1181. return nwritten;
  1182. }
  1183. }
  1184. if(cf->cft != &Curl_cft_udp && ctx->wpartial_percent > 0 && len > 8) {
  1185. len = len * ctx->wpartial_percent / 100;
  1186. if(!len)
  1187. len = 1;
  1188. CURL_TRC_CF(data, cf, "send(len=%zu) SIMULATE partial write of %zu bytes",
  1189. orig_len, len);
  1190. }
  1191. #endif
  1192. #if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
  1193. if(cf->conn->bits.tcp_fastopen) {
  1194. nwritten = sendto(ctx->sock, buf, len, MSG_FASTOPEN,
  1195. &cf->conn->remote_addr->sa_addr,
  1196. cf->conn->remote_addr->addrlen);
  1197. cf->conn->bits.tcp_fastopen = FALSE;
  1198. }
  1199. else
  1200. #endif
  1201. nwritten = swrite(ctx->sock, buf, len);
  1202. if(-1 == nwritten) {
  1203. int sockerr = SOCKERRNO;
  1204. if(
  1205. #ifdef WSAEWOULDBLOCK
  1206. /* This is how Windows does it */
  1207. (WSAEWOULDBLOCK == sockerr)
  1208. #else
  1209. /* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
  1210. due to its inability to send off data without blocking. We therefore
  1211. treat both error codes the same here */
  1212. (EWOULDBLOCK == sockerr) || (EAGAIN == sockerr) || (EINTR == sockerr) ||
  1213. (EINPROGRESS == sockerr)
  1214. #endif
  1215. ) {
  1216. /* this is just a case of EWOULDBLOCK */
  1217. *err = CURLE_AGAIN;
  1218. }
  1219. else {
  1220. char buffer[STRERROR_LEN];
  1221. failf(data, "Send failure: %s",
  1222. Curl_strerror(sockerr, buffer, sizeof(buffer)));
  1223. data->state.os_errno = sockerr;
  1224. *err = CURLE_SEND_ERROR;
  1225. }
  1226. }
  1227. CURL_TRC_CF(data, cf, "send(len=%zu) -> %d, err=%d",
  1228. orig_len, (int)nwritten, *err);
  1229. cf->conn->sock[cf->sockindex] = fdsave;
  1230. return nwritten;
  1231. }
  1232. static ssize_t cf_socket_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1233. char *buf, size_t len, CURLcode *err)
  1234. {
  1235. struct cf_socket_ctx *ctx = cf->ctx;
  1236. curl_socket_t fdsave;
  1237. ssize_t nread;
  1238. *err = CURLE_OK;
  1239. fdsave = cf->conn->sock[cf->sockindex];
  1240. cf->conn->sock[cf->sockindex] = ctx->sock;
  1241. #ifdef DEBUGBUILD
  1242. /* simulate network blocking/partial reads */
  1243. if(cf->cft != &Curl_cft_udp && ctx->rblock_percent > 0) {
  1244. unsigned char c;
  1245. Curl_rand(data, &c, 1);
  1246. if(c >= ((100-ctx->rblock_percent)*256/100)) {
  1247. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE EWOULDBLOCK", len);
  1248. *err = CURLE_AGAIN;
  1249. nread = -1;
  1250. cf->conn->sock[cf->sockindex] = fdsave;
  1251. return nread;
  1252. }
  1253. }
  1254. if(cf->cft != &Curl_cft_udp && ctx->recv_max && ctx->recv_max < len) {
  1255. size_t orig_len = len;
  1256. len = ctx->recv_max;
  1257. CURL_TRC_CF(data, cf, "recv(len=%zu) SIMULATE max read of %zu bytes",
  1258. orig_len, len);
  1259. }
  1260. #endif
  1261. if(ctx->buffer_recv && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1262. CURL_TRC_CF(data, cf, "recv from buffer");
  1263. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1264. }
  1265. else {
  1266. struct reader_ctx rctx;
  1267. rctx.cf = cf;
  1268. rctx.data = data;
  1269. /* "small" reads may trigger filling our buffer, "large" reads
  1270. * are probably not worth the additional copy */
  1271. if(ctx->buffer_recv && len < NW_SMALL_READS) {
  1272. ssize_t nwritten;
  1273. nwritten = Curl_bufq_slurp(&ctx->recvbuf, nw_in_read, &rctx, err);
  1274. if(nwritten < 0 && !Curl_bufq_is_empty(&ctx->recvbuf)) {
  1275. /* we have a partial read with an error. need to deliver
  1276. * what we got, return the error later. */
  1277. CURL_TRC_CF(data, cf, "partial read: empty buffer first");
  1278. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1279. }
  1280. else if(nwritten < 0) {
  1281. nread = -1;
  1282. goto out;
  1283. }
  1284. else if(nwritten == 0) {
  1285. /* eof */
  1286. *err = CURLE_OK;
  1287. nread = 0;
  1288. }
  1289. else {
  1290. CURL_TRC_CF(data, cf, "buffered %zd additional bytes", nwritten);
  1291. nread = Curl_bufq_read(&ctx->recvbuf, (unsigned char *)buf, len, err);
  1292. }
  1293. }
  1294. else {
  1295. nread = nw_in_read(&rctx, (unsigned char *)buf, len, err);
  1296. }
  1297. }
  1298. out:
  1299. CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, err=%d", len, (int)nread,
  1300. *err);
  1301. if(nread > 0 && !ctx->got_first_byte) {
  1302. ctx->first_byte_at = Curl_now();
  1303. ctx->got_first_byte = TRUE;
  1304. }
  1305. cf->conn->sock[cf->sockindex] = fdsave;
  1306. return nread;
  1307. }
  1308. static void cf_socket_active(struct Curl_cfilter *cf, struct Curl_easy *data)
  1309. {
  1310. struct cf_socket_ctx *ctx = cf->ctx;
  1311. /* use this socket from now on */
  1312. cf->conn->sock[cf->sockindex] = ctx->sock;
  1313. set_local_ip(cf, data);
  1314. if(cf->sockindex == SECONDARYSOCKET)
  1315. cf->conn->secondary = ctx->ip;
  1316. else
  1317. cf->conn->primary = ctx->ip;
  1318. /* the first socket info gets some specials */
  1319. if(cf->sockindex == FIRSTSOCKET) {
  1320. cf->conn->remote_addr = &ctx->addr;
  1321. #ifdef USE_IPV6
  1322. cf->conn->bits.ipv6 = (ctx->addr.family == AF_INET6)? TRUE : FALSE;
  1323. #endif
  1324. Curl_persistconninfo(data, cf->conn, &ctx->ip);
  1325. /* buffering is currently disabled by default because we have stalls
  1326. * in parallel transfers where not all buffered data is consumed and no
  1327. * socket events happen.
  1328. */
  1329. ctx->buffer_recv = FALSE;
  1330. }
  1331. ctx->active = TRUE;
  1332. }
  1333. static CURLcode cf_socket_cntrl(struct Curl_cfilter *cf,
  1334. struct Curl_easy *data,
  1335. int event, int arg1, void *arg2)
  1336. {
  1337. struct cf_socket_ctx *ctx = cf->ctx;
  1338. (void)arg1;
  1339. (void)arg2;
  1340. switch(event) {
  1341. case CF_CTRL_CONN_INFO_UPDATE:
  1342. cf_socket_active(cf, data);
  1343. break;
  1344. case CF_CTRL_DATA_SETUP:
  1345. Curl_persistconninfo(data, cf->conn, &ctx->ip);
  1346. break;
  1347. case CF_CTRL_FORGET_SOCKET:
  1348. ctx->sock = CURL_SOCKET_BAD;
  1349. break;
  1350. }
  1351. return CURLE_OK;
  1352. }
  1353. static bool cf_socket_conn_is_alive(struct Curl_cfilter *cf,
  1354. struct Curl_easy *data,
  1355. bool *input_pending)
  1356. {
  1357. struct cf_socket_ctx *ctx = cf->ctx;
  1358. struct pollfd pfd[1];
  1359. int r;
  1360. *input_pending = FALSE;
  1361. (void)data;
  1362. if(!ctx || ctx->sock == CURL_SOCKET_BAD)
  1363. return FALSE;
  1364. /* Check with 0 timeout if there are any events pending on the socket */
  1365. pfd[0].fd = ctx->sock;
  1366. pfd[0].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
  1367. pfd[0].revents = 0;
  1368. r = Curl_poll(pfd, 1, 0);
  1369. if(r < 0) {
  1370. CURL_TRC_CF(data, cf, "is_alive: poll error, assume dead");
  1371. return FALSE;
  1372. }
  1373. else if(r == 0) {
  1374. CURL_TRC_CF(data, cf, "is_alive: poll timeout, assume alive");
  1375. return TRUE;
  1376. }
  1377. else if(pfd[0].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) {
  1378. CURL_TRC_CF(data, cf, "is_alive: err/hup/etc events, assume dead");
  1379. return FALSE;
  1380. }
  1381. CURL_TRC_CF(data, cf, "is_alive: valid events, looks alive");
  1382. *input_pending = TRUE;
  1383. return TRUE;
  1384. }
  1385. static CURLcode cf_socket_query(struct Curl_cfilter *cf,
  1386. struct Curl_easy *data,
  1387. int query, int *pres1, void *pres2)
  1388. {
  1389. struct cf_socket_ctx *ctx = cf->ctx;
  1390. switch(query) {
  1391. case CF_QUERY_SOCKET:
  1392. DEBUGASSERT(pres2);
  1393. *((curl_socket_t *)pres2) = ctx->sock;
  1394. return CURLE_OK;
  1395. case CF_QUERY_CONNECT_REPLY_MS:
  1396. if(ctx->got_first_byte) {
  1397. timediff_t ms = Curl_timediff(ctx->first_byte_at, ctx->started_at);
  1398. *pres1 = (ms < INT_MAX)? (int)ms : INT_MAX;
  1399. }
  1400. else
  1401. *pres1 = -1;
  1402. return CURLE_OK;
  1403. case CF_QUERY_TIMER_CONNECT: {
  1404. struct curltime *when = pres2;
  1405. switch(ctx->transport) {
  1406. case TRNSPRT_UDP:
  1407. case TRNSPRT_QUIC:
  1408. /* Since UDP connected sockets work different from TCP, we use the
  1409. * time of the first byte from the peer as the "connect" time. */
  1410. if(ctx->got_first_byte) {
  1411. *when = ctx->first_byte_at;
  1412. break;
  1413. }
  1414. FALLTHROUGH();
  1415. default:
  1416. *when = ctx->connected_at;
  1417. break;
  1418. }
  1419. return CURLE_OK;
  1420. }
  1421. default:
  1422. break;
  1423. }
  1424. return cf->next?
  1425. cf->next->cft->query(cf->next, data, query, pres1, pres2) :
  1426. CURLE_UNKNOWN_OPTION;
  1427. }
  1428. struct Curl_cftype Curl_cft_tcp = {
  1429. "TCP",
  1430. CF_TYPE_IP_CONNECT,
  1431. CURL_LOG_LVL_NONE,
  1432. cf_socket_destroy,
  1433. cf_tcp_connect,
  1434. cf_socket_close,
  1435. cf_socket_get_host,
  1436. cf_socket_adjust_pollset,
  1437. cf_socket_data_pending,
  1438. cf_socket_send,
  1439. cf_socket_recv,
  1440. cf_socket_cntrl,
  1441. cf_socket_conn_is_alive,
  1442. Curl_cf_def_conn_keep_alive,
  1443. cf_socket_query,
  1444. };
  1445. CURLcode Curl_cf_tcp_create(struct Curl_cfilter **pcf,
  1446. struct Curl_easy *data,
  1447. struct connectdata *conn,
  1448. const struct Curl_addrinfo *ai,
  1449. int transport)
  1450. {
  1451. struct cf_socket_ctx *ctx = NULL;
  1452. struct Curl_cfilter *cf = NULL;
  1453. CURLcode result;
  1454. (void)data;
  1455. (void)conn;
  1456. DEBUGASSERT(transport == TRNSPRT_TCP);
  1457. ctx = calloc(1, sizeof(*ctx));
  1458. if(!ctx) {
  1459. result = CURLE_OUT_OF_MEMORY;
  1460. goto out;
  1461. }
  1462. cf_socket_ctx_init(ctx, ai, transport);
  1463. result = Curl_cf_create(&cf, &Curl_cft_tcp, ctx);
  1464. out:
  1465. *pcf = (!result)? cf : NULL;
  1466. if(result) {
  1467. Curl_safefree(cf);
  1468. Curl_safefree(ctx);
  1469. }
  1470. return result;
  1471. }
  1472. static CURLcode cf_udp_setup_quic(struct Curl_cfilter *cf,
  1473. struct Curl_easy *data)
  1474. {
  1475. struct cf_socket_ctx *ctx = cf->ctx;
  1476. int rc;
  1477. /* QUIC needs a connected socket, nonblocking */
  1478. DEBUGASSERT(ctx->sock != CURL_SOCKET_BAD);
  1479. #if defined(__APPLE__) && defined(USE_OPENSSL_QUIC)
  1480. (void)rc;
  1481. /* On macOS OpenSSL QUIC fails on connected sockets.
  1482. * see: <https://github.com/openssl/openssl/issues/23251> */
  1483. #else
  1484. rc = connect(ctx->sock, &ctx->addr.sa_addr, ctx->addr.addrlen);
  1485. if(-1 == rc) {
  1486. return socket_connect_result(data, ctx->ip.remote_ip, SOCKERRNO);
  1487. }
  1488. ctx->sock_connected = TRUE;
  1489. #endif
  1490. set_local_ip(cf, data);
  1491. CURL_TRC_CF(data, cf, "%s socket %" CURL_FORMAT_SOCKET_T
  1492. " connected: [%s:%d] -> [%s:%d]",
  1493. (ctx->transport == TRNSPRT_QUIC)? "QUIC" : "UDP",
  1494. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port,
  1495. ctx->ip.remote_ip, ctx->ip.remote_port);
  1496. (void)curlx_nonblock(ctx->sock, TRUE);
  1497. switch(ctx->addr.family) {
  1498. #if defined(__linux__) && defined(IP_MTU_DISCOVER)
  1499. case AF_INET: {
  1500. int val = IP_PMTUDISC_DO;
  1501. (void)setsockopt(ctx->sock, IPPROTO_IP, IP_MTU_DISCOVER, &val,
  1502. sizeof(val));
  1503. break;
  1504. }
  1505. #endif
  1506. #if defined(__linux__) && defined(IPV6_MTU_DISCOVER)
  1507. case AF_INET6: {
  1508. int val = IPV6_PMTUDISC_DO;
  1509. (void)setsockopt(ctx->sock, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
  1510. sizeof(val));
  1511. break;
  1512. }
  1513. #endif
  1514. }
  1515. return CURLE_OK;
  1516. }
  1517. static CURLcode cf_udp_connect(struct Curl_cfilter *cf,
  1518. struct Curl_easy *data,
  1519. bool blocking, bool *done)
  1520. {
  1521. struct cf_socket_ctx *ctx = cf->ctx;
  1522. CURLcode result = CURLE_COULDNT_CONNECT;
  1523. (void)blocking;
  1524. if(cf->connected) {
  1525. *done = TRUE;
  1526. return CURLE_OK;
  1527. }
  1528. *done = FALSE;
  1529. if(ctx->sock == CURL_SOCKET_BAD) {
  1530. result = cf_socket_open(cf, data);
  1531. if(result) {
  1532. CURL_TRC_CF(data, cf, "cf_udp_connect(), open failed -> %d", result);
  1533. goto out;
  1534. }
  1535. if(ctx->transport == TRNSPRT_QUIC) {
  1536. result = cf_udp_setup_quic(cf, data);
  1537. if(result)
  1538. goto out;
  1539. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1540. CURL_FORMAT_SOCKET_T " (%s:%d)",
  1541. ctx->sock, ctx->ip.local_ip, ctx->ip.local_port);
  1542. }
  1543. else {
  1544. CURL_TRC_CF(data, cf, "cf_udp_connect(), opened socket=%"
  1545. CURL_FORMAT_SOCKET_T " (unconnected)", ctx->sock);
  1546. }
  1547. *done = TRUE;
  1548. cf->connected = TRUE;
  1549. }
  1550. out:
  1551. return result;
  1552. }
  1553. struct Curl_cftype Curl_cft_udp = {
  1554. "UDP",
  1555. CF_TYPE_IP_CONNECT,
  1556. CURL_LOG_LVL_NONE,
  1557. cf_socket_destroy,
  1558. cf_udp_connect,
  1559. cf_socket_close,
  1560. cf_socket_get_host,
  1561. cf_socket_adjust_pollset,
  1562. cf_socket_data_pending,
  1563. cf_socket_send,
  1564. cf_socket_recv,
  1565. cf_socket_cntrl,
  1566. cf_socket_conn_is_alive,
  1567. Curl_cf_def_conn_keep_alive,
  1568. cf_socket_query,
  1569. };
  1570. CURLcode Curl_cf_udp_create(struct Curl_cfilter **pcf,
  1571. struct Curl_easy *data,
  1572. struct connectdata *conn,
  1573. const struct Curl_addrinfo *ai,
  1574. int transport)
  1575. {
  1576. struct cf_socket_ctx *ctx = NULL;
  1577. struct Curl_cfilter *cf = NULL;
  1578. CURLcode result;
  1579. (void)data;
  1580. (void)conn;
  1581. DEBUGASSERT(transport == TRNSPRT_UDP || transport == TRNSPRT_QUIC);
  1582. ctx = calloc(1, sizeof(*ctx));
  1583. if(!ctx) {
  1584. result = CURLE_OUT_OF_MEMORY;
  1585. goto out;
  1586. }
  1587. cf_socket_ctx_init(ctx, ai, transport);
  1588. result = Curl_cf_create(&cf, &Curl_cft_udp, ctx);
  1589. out:
  1590. *pcf = (!result)? cf : NULL;
  1591. if(result) {
  1592. Curl_safefree(cf);
  1593. Curl_safefree(ctx);
  1594. }
  1595. return result;
  1596. }
  1597. /* this is the TCP filter which can also handle this case */
  1598. struct Curl_cftype Curl_cft_unix = {
  1599. "UNIX",
  1600. CF_TYPE_IP_CONNECT,
  1601. CURL_LOG_LVL_NONE,
  1602. cf_socket_destroy,
  1603. cf_tcp_connect,
  1604. cf_socket_close,
  1605. cf_socket_get_host,
  1606. cf_socket_adjust_pollset,
  1607. cf_socket_data_pending,
  1608. cf_socket_send,
  1609. cf_socket_recv,
  1610. cf_socket_cntrl,
  1611. cf_socket_conn_is_alive,
  1612. Curl_cf_def_conn_keep_alive,
  1613. cf_socket_query,
  1614. };
  1615. CURLcode Curl_cf_unix_create(struct Curl_cfilter **pcf,
  1616. struct Curl_easy *data,
  1617. struct connectdata *conn,
  1618. const struct Curl_addrinfo *ai,
  1619. int transport)
  1620. {
  1621. struct cf_socket_ctx *ctx = NULL;
  1622. struct Curl_cfilter *cf = NULL;
  1623. CURLcode result;
  1624. (void)data;
  1625. (void)conn;
  1626. DEBUGASSERT(transport == TRNSPRT_UNIX);
  1627. ctx = calloc(1, sizeof(*ctx));
  1628. if(!ctx) {
  1629. result = CURLE_OUT_OF_MEMORY;
  1630. goto out;
  1631. }
  1632. cf_socket_ctx_init(ctx, ai, transport);
  1633. result = Curl_cf_create(&cf, &Curl_cft_unix, ctx);
  1634. out:
  1635. *pcf = (!result)? cf : NULL;
  1636. if(result) {
  1637. Curl_safefree(cf);
  1638. Curl_safefree(ctx);
  1639. }
  1640. return result;
  1641. }
  1642. static CURLcode cf_tcp_accept_connect(struct Curl_cfilter *cf,
  1643. struct Curl_easy *data,
  1644. bool blocking, bool *done)
  1645. {
  1646. /* we start accepted, if we ever close, we cannot go on */
  1647. (void)data;
  1648. (void)blocking;
  1649. if(cf->connected) {
  1650. *done = TRUE;
  1651. return CURLE_OK;
  1652. }
  1653. return CURLE_FAILED_INIT;
  1654. }
  1655. struct Curl_cftype Curl_cft_tcp_accept = {
  1656. "TCP-ACCEPT",
  1657. CF_TYPE_IP_CONNECT,
  1658. CURL_LOG_LVL_NONE,
  1659. cf_socket_destroy,
  1660. cf_tcp_accept_connect,
  1661. cf_socket_close,
  1662. cf_socket_get_host, /* TODO: not accurate */
  1663. cf_socket_adjust_pollset,
  1664. cf_socket_data_pending,
  1665. cf_socket_send,
  1666. cf_socket_recv,
  1667. cf_socket_cntrl,
  1668. cf_socket_conn_is_alive,
  1669. Curl_cf_def_conn_keep_alive,
  1670. cf_socket_query,
  1671. };
  1672. CURLcode Curl_conn_tcp_listen_set(struct Curl_easy *data,
  1673. struct connectdata *conn,
  1674. int sockindex, curl_socket_t *s)
  1675. {
  1676. CURLcode result;
  1677. struct Curl_cfilter *cf = NULL;
  1678. struct cf_socket_ctx *ctx = NULL;
  1679. /* replace any existing */
  1680. Curl_conn_cf_discard_all(data, conn, sockindex);
  1681. DEBUGASSERT(conn->sock[sockindex] == CURL_SOCKET_BAD);
  1682. ctx = calloc(1, sizeof(*ctx));
  1683. if(!ctx) {
  1684. result = CURLE_OUT_OF_MEMORY;
  1685. goto out;
  1686. }
  1687. ctx->transport = conn->transport;
  1688. ctx->sock = *s;
  1689. ctx->accepted = FALSE;
  1690. result = Curl_cf_create(&cf, &Curl_cft_tcp_accept, ctx);
  1691. if(result)
  1692. goto out;
  1693. Curl_conn_cf_add(data, conn, sockindex, cf);
  1694. conn->sock[sockindex] = ctx->sock;
  1695. set_local_ip(cf, data);
  1696. ctx->active = TRUE;
  1697. ctx->connected_at = Curl_now();
  1698. cf->connected = TRUE;
  1699. CURL_TRC_CF(data, cf, "Curl_conn_tcp_listen_set(%"
  1700. CURL_FORMAT_SOCKET_T ")", ctx->sock);
  1701. out:
  1702. if(result) {
  1703. Curl_safefree(cf);
  1704. Curl_safefree(ctx);
  1705. }
  1706. return result;
  1707. }
  1708. static void set_accepted_remote_ip(struct Curl_cfilter *cf,
  1709. struct Curl_easy *data)
  1710. {
  1711. struct cf_socket_ctx *ctx = cf->ctx;
  1712. #ifdef HAVE_GETPEERNAME
  1713. char buffer[STRERROR_LEN];
  1714. struct Curl_sockaddr_storage ssrem;
  1715. curl_socklen_t plen;
  1716. ctx->ip.remote_ip[0] = 0;
  1717. ctx->ip.remote_port = 0;
  1718. plen = sizeof(ssrem);
  1719. memset(&ssrem, 0, plen);
  1720. if(getpeername(ctx->sock, (struct sockaddr*) &ssrem, &plen)) {
  1721. int error = SOCKERRNO;
  1722. failf(data, "getpeername() failed with errno %d: %s",
  1723. error, Curl_strerror(error, buffer, sizeof(buffer)));
  1724. return;
  1725. }
  1726. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  1727. ctx->ip.remote_ip, &ctx->ip.remote_port)) {
  1728. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  1729. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1730. return;
  1731. }
  1732. #else
  1733. ctx->ip.remote_ip[0] = 0;
  1734. ctx->ip.remote_port = 0;
  1735. (void)data;
  1736. #endif
  1737. }
  1738. CURLcode Curl_conn_tcp_accepted_set(struct Curl_easy *data,
  1739. struct connectdata *conn,
  1740. int sockindex, curl_socket_t *s)
  1741. {
  1742. struct Curl_cfilter *cf = NULL;
  1743. struct cf_socket_ctx *ctx = NULL;
  1744. cf = conn->cfilter[sockindex];
  1745. if(!cf || cf->cft != &Curl_cft_tcp_accept)
  1746. return CURLE_FAILED_INIT;
  1747. ctx = cf->ctx;
  1748. /* discard the listen socket */
  1749. socket_close(data, conn, TRUE, ctx->sock);
  1750. ctx->sock = *s;
  1751. conn->sock[sockindex] = ctx->sock;
  1752. set_accepted_remote_ip(cf, data);
  1753. set_local_ip(cf, data);
  1754. ctx->active = TRUE;
  1755. ctx->accepted = TRUE;
  1756. ctx->connected_at = Curl_now();
  1757. cf->connected = TRUE;
  1758. CURL_TRC_CF(data, cf, "accepted_set(sock=%" CURL_FORMAT_SOCKET_T
  1759. ", remote=%s port=%d)",
  1760. ctx->sock, ctx->ip.remote_ip, ctx->ip.remote_port);
  1761. return CURLE_OK;
  1762. }
  1763. /**
  1764. * Return TRUE iff `cf` is a socket filter.
  1765. */
  1766. static bool cf_is_socket(struct Curl_cfilter *cf)
  1767. {
  1768. return cf && (cf->cft == &Curl_cft_tcp ||
  1769. cf->cft == &Curl_cft_udp ||
  1770. cf->cft == &Curl_cft_unix ||
  1771. cf->cft == &Curl_cft_tcp_accept);
  1772. }
  1773. CURLcode Curl_cf_socket_peek(struct Curl_cfilter *cf,
  1774. struct Curl_easy *data,
  1775. curl_socket_t *psock,
  1776. const struct Curl_sockaddr_ex **paddr,
  1777. struct ip_quadruple *pip)
  1778. {
  1779. (void)data;
  1780. if(cf_is_socket(cf) && cf->ctx) {
  1781. struct cf_socket_ctx *ctx = cf->ctx;
  1782. if(psock)
  1783. *psock = ctx->sock;
  1784. if(paddr)
  1785. *paddr = &ctx->addr;
  1786. if(pip)
  1787. *pip = ctx->ip;
  1788. return CURLE_OK;
  1789. }
  1790. return CURLE_FAILED_INIT;
  1791. }