cf-socket.c 68 KB

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