2
0

cf-socket.c 63 KB

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