cf-socket.c 56 KB

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