network.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. /*
  2. * Windows networking abstraction.
  3. *
  4. * For the IPv6 code in here I am indebted to Jeroen Massar and
  5. * unfix.org.
  6. */
  7. #include <winsock2.h> /* need to put this first, for winelib builds */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <assert.h>
  11. #define NEED_DECLARATION_OF_SELECT /* in order to initialise it */
  12. #include "putty.h"
  13. #include "network.h"
  14. #include "tree234.h"
  15. #include "ssh.h"
  16. #include <ws2tcpip.h>
  17. #if HAVE_AFUNIX_H
  18. #include <afunix.h>
  19. #endif
  20. #ifndef NO_IPV6
  21. #ifdef __clang__
  22. #pragma clang diagnostic push
  23. #pragma clang diagnostic ignored "-Wmissing-braces"
  24. #endif
  25. const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
  26. const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
  27. #ifdef __clang__
  28. #pragma clang diagnostic pop
  29. #endif
  30. #endif
  31. #define ipv4_is_loopback(addr) \
  32. ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
  33. /*
  34. * Mutable state that goes with a SockAddr: stores information
  35. * about where in the list of candidate IP(v*) addresses we've
  36. * currently got to.
  37. */
  38. typedef struct SockAddrStep_tag SockAddrStep;
  39. struct SockAddrStep_tag {
  40. #ifndef NO_IPV6
  41. struct addrinfo *ai; /* steps along addr->ais */
  42. #endif
  43. int curraddr;
  44. };
  45. typedef struct NetSocket NetSocket;
  46. struct NetSocket {
  47. const char *error;
  48. SOCKET s;
  49. Plug *plug;
  50. bufchain output_data;
  51. bool connected;
  52. bool writable;
  53. bool frozen; /* this causes readability notifications to be ignored */
  54. bool frozen_readable; /* this means we missed at least one readability
  55. * notification while we were frozen */
  56. bool localhost_only; /* for listening sockets */
  57. char oobdata[1];
  58. size_t sending_oob;
  59. bool oobinline, nodelay, keepalive, privport;
  60. enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
  61. SockAddr *addr;
  62. SockAddrStep step;
  63. int port;
  64. int pending_error; /* in case send() returns error */
  65. /*
  66. * We sometimes need pairs of Socket structures to be linked:
  67. * if we are listening on the same IPv6 and v4 port, for
  68. * example. So here we define `parent' and `child' pointers to
  69. * track this link.
  70. */
  71. NetSocket *parent, *child;
  72. Socket sock;
  73. };
  74. /*
  75. * Top-level discriminator for SockAddr.
  76. *
  77. * UNRESOLVED means a host name not yet put through DNS; IP means a
  78. * resolved IP address (or list of them); UNIX indicates the AF_UNIX
  79. * network family (which Windows also has); NAMEDPIPE indicates that
  80. * this SockAddr is phony, holding a Windows named pipe pathname
  81. * instead of any address WinSock can understand.
  82. */
  83. typedef enum SuperFamily {
  84. UNRESOLVED,
  85. IP,
  86. #if HAVE_AFUNIX_H
  87. UNIX,
  88. #endif
  89. NAMEDPIPE
  90. } SuperFamily;
  91. struct SockAddr {
  92. int refcount;
  93. const char *error;
  94. SuperFamily superfamily;
  95. #ifndef NO_IPV6
  96. struct addrinfo *ais; /* Addresses IPv6 style. */
  97. #endif
  98. unsigned long *addresses; /* Addresses IPv4 style. */
  99. int naddresses;
  100. char hostname[512]; /* Store an unresolved host name. */
  101. };
  102. /*
  103. * Which address family this address belongs to. AF_INET for IPv4;
  104. * AF_INET6 for IPv6; AF_UNIX for Unix-domain sockets; AF_UNSPEC
  105. * indicates that name resolution has not been done and a simple host
  106. * name is held in this SockAddr structure.
  107. */
  108. static inline int sockaddr_family(SockAddr *addr, SockAddrStep step)
  109. {
  110. switch (addr->superfamily) {
  111. case IP:
  112. #ifndef NO_IPV6
  113. if (step.ai)
  114. return step.ai->ai_family;
  115. #endif
  116. return AF_INET;
  117. #if HAVE_AFUNIX_H
  118. case UNIX:
  119. return AF_UNIX;
  120. #endif
  121. default:
  122. return AF_UNSPEC;
  123. }
  124. }
  125. /*
  126. * Start a SockAddrStep structure to step through multiple
  127. * addresses.
  128. */
  129. #ifndef NO_IPV6
  130. #define START_STEP(addr, step) \
  131. ((step).ai = (addr)->ais, (step).curraddr = 0)
  132. #else
  133. #define START_STEP(addr, step) \
  134. ((step).curraddr = 0)
  135. #endif
  136. static tree234 *sktree;
  137. static int cmpfortree(void *av, void *bv)
  138. {
  139. NetSocket *a = (NetSocket *)av, *b = (NetSocket *)bv;
  140. uintptr_t as = (uintptr_t) a->s, bs = (uintptr_t) b->s;
  141. if (as < bs)
  142. return -1;
  143. if (as > bs)
  144. return +1;
  145. if (a < b)
  146. return -1;
  147. if (a > b)
  148. return +1;
  149. return 0;
  150. }
  151. static int cmpforsearch(void *av, void *bv)
  152. {
  153. NetSocket *b = (NetSocket *)bv;
  154. uintptr_t as = (uintptr_t) av, bs = (uintptr_t) b->s;
  155. if (as < bs)
  156. return -1;
  157. if (as > bs)
  158. return +1;
  159. return 0;
  160. }
  161. DECL_WINDOWS_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
  162. DECL_WINDOWS_FUNCTION(static, int, WSACleanup, (void));
  163. DECL_WINDOWS_FUNCTION(static, int, closesocket, (SOCKET));
  164. DECL_WINDOWS_FUNCTION(static, ULONG, ntohl, (ULONG));
  165. DECL_WINDOWS_FUNCTION(static, ULONG, htonl, (ULONG));
  166. DECL_WINDOWS_FUNCTION(static, USHORT, htons, (USHORT));
  167. DECL_WINDOWS_FUNCTION(static, USHORT, ntohs, (USHORT));
  168. DECL_WINDOWS_FUNCTION(static, int, gethostname, (char *, int));
  169. DECL_WINDOWS_FUNCTION(static, struct hostent FAR *, gethostbyname,
  170. (const char FAR *));
  171. DECL_WINDOWS_FUNCTION(static, struct servent FAR *, getservbyname,
  172. (const char FAR *, const char FAR *));
  173. DECL_WINDOWS_FUNCTION(static, ULONG, inet_addr, (const char FAR *));
  174. DECL_WINDOWS_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
  175. DECL_WINDOWS_FUNCTION(static, const char FAR *, inet_ntop,
  176. (int, void FAR *, char *, size_t));
  177. DECL_WINDOWS_FUNCTION(static, int, connect,
  178. (SOCKET, const struct sockaddr FAR *, int));
  179. DECL_WINDOWS_FUNCTION(static, int, bind,
  180. (SOCKET, const struct sockaddr FAR *, int));
  181. #ifdef MPEXT
  182. DECL_WINDOWS_FUNCTION(static, int, getsockopt,
  183. (SOCKET, int, int, char FAR *, int *));
  184. #endif
  185. DECL_WINDOWS_FUNCTION(static, int, setsockopt,
  186. (SOCKET, int, int, const char FAR *, int));
  187. DECL_WINDOWS_FUNCTION(static, SOCKET, socket, (int, int, int));
  188. DECL_WINDOWS_FUNCTION(static, int, listen, (SOCKET, int));
  189. DECL_WINDOWS_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
  190. DECL_WINDOWS_FUNCTION(static, int, shutdown, (SOCKET, int));
  191. DECL_WINDOWS_FUNCTION(static, int, ioctlsocket,
  192. (SOCKET, LONG, ULONG FAR *));
  193. DECL_WINDOWS_FUNCTION(static, SOCKET, accept,
  194. (SOCKET, struct sockaddr FAR *, int FAR *));
  195. DECL_WINDOWS_FUNCTION(static, int, getpeername,
  196. (SOCKET, struct sockaddr FAR *, int FAR *));
  197. DECL_WINDOWS_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
  198. DECL_WINDOWS_FUNCTION(static, int, WSAIoctl,
  199. (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
  200. LPDWORD, LPWSAOVERLAPPED,
  201. LPWSAOVERLAPPED_COMPLETION_ROUTINE));
  202. #ifndef NO_IPV6
  203. DECL_WINDOWS_FUNCTION(static, int, getaddrinfo,
  204. (const char *nodename, const char *servname,
  205. const struct addrinfo *hints, struct addrinfo **res));
  206. DECL_WINDOWS_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res));
  207. DECL_WINDOWS_FUNCTION(static, int, getnameinfo,
  208. (const struct sockaddr FAR *sa, socklen_t salen,
  209. char FAR *host, DWORD hostlen, char FAR *serv,
  210. DWORD servlen, int flags));
  211. DECL_WINDOWS_FUNCTION(static, int, WSAAddressToStringA,
  212. (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO,
  213. LPSTR, LPDWORD));
  214. #endif
  215. static HMODULE winsock_module = NULL;
  216. static WSADATA wsadata;
  217. #ifndef NO_IPV6
  218. static HMODULE winsock2_module = NULL;
  219. static HMODULE wship6_module = NULL;
  220. #endif
  221. static bool sk_startup(int hi, int lo)
  222. {
  223. WORD winsock_ver;
  224. winsock_ver = MAKEWORD(hi, lo);
  225. if (p_WSAStartup(winsock_ver, &wsadata)) {
  226. return false;
  227. }
  228. if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
  229. return false;
  230. }
  231. return true;
  232. }
  233. DEF_WINDOWS_FUNCTION(WSAAsyncSelect);
  234. DEF_WINDOWS_FUNCTION(WSAEventSelect);
  235. DEF_WINDOWS_FUNCTION(WSAGetLastError);
  236. DEF_WINDOWS_FUNCTION(WSAEnumNetworkEvents);
  237. DEF_WINDOWS_FUNCTION(select);
  238. void sk_init(void)
  239. {
  240. #ifndef NO_IPV6
  241. winsock2_module =
  242. #endif
  243. winsock_module = load_system32_dll("ws2_32.dll");
  244. if (!winsock_module) {
  245. winsock_module = load_system32_dll("wsock32.dll");
  246. }
  247. if (!winsock_module)
  248. {
  249. modalfatalbox("Unable to load any WinSock library");
  250. }
  251. #ifndef NO_IPV6
  252. /* Check if we have getaddrinfo in Winsock */
  253. if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) {
  254. GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo);
  255. GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo);
  256. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, getnameinfo);
  257. /* This function would fail its type-check if we did one,
  258. * because the VS header file provides an inline definition
  259. * which is __cdecl instead of WINAPI. */
  260. } else {
  261. /* Fall back to wship6.dll for Windows 2000 */
  262. wship6_module = load_system32_dll("wship6.dll");
  263. if (wship6_module) {
  264. GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo);
  265. GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo);
  266. /* See comment above about type check */
  267. GET_WINDOWS_FUNCTION_NO_TYPECHECK(wship6_module, getnameinfo);
  268. } else {
  269. }
  270. }
  271. GET_WINDOWS_FUNCTION(winsock2_module, WSAAddressToStringA);
  272. #endif
  273. GET_WINDOWS_FUNCTION(winsock_module, WSAAsyncSelect);
  274. GET_WINDOWS_FUNCTION(winsock_module, WSAEventSelect);
  275. /* We don't type-check select because at least some MinGW versions
  276. * of the Windows API headers seem to disagree with the
  277. * documentation on whether the 'struct timeval *' pointer is
  278. * const or not. */
  279. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, select);
  280. GET_WINDOWS_FUNCTION(winsock_module, WSAGetLastError);
  281. GET_WINDOWS_FUNCTION(winsock_module, WSAEnumNetworkEvents);
  282. GET_WINDOWS_FUNCTION(winsock_module, WSAStartup);
  283. GET_WINDOWS_FUNCTION(winsock_module, WSACleanup);
  284. GET_WINDOWS_FUNCTION(winsock_module, closesocket);
  285. /* Winelib maps ntohl and friends to things like
  286. * __wine_ulong_swap, which fail these type checks hopelessly */
  287. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, ntohl);
  288. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, htonl);
  289. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, htons);
  290. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, ntohs);
  291. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, gethostname);
  292. GET_WINDOWS_FUNCTION(winsock_module, gethostbyname);
  293. GET_WINDOWS_FUNCTION(winsock_module, getservbyname);
  294. GET_WINDOWS_FUNCTION(winsock_module, inet_addr);
  295. GET_WINDOWS_FUNCTION(winsock_module, inet_ntoa);
  296. /* Older Visual Studio, and MinGW as of Ubuntu 16.04, don't know
  297. * about this function at all, so can't type-check it. Also there
  298. * seems to be some disagreement in the VS headers about whether
  299. * the second argument is void * or const void *, so I omit the
  300. * type check. */
  301. GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, inet_ntop);
  302. GET_WINDOWS_FUNCTION(winsock_module, connect);
  303. GET_WINDOWS_FUNCTION(winsock_module, bind);
  304. #ifdef MPEXT
  305. GET_WINDOWS_FUNCTION(winsock_module, getsockopt);
  306. #endif
  307. GET_WINDOWS_FUNCTION(winsock_module, setsockopt);
  308. GET_WINDOWS_FUNCTION(winsock_module, socket);
  309. GET_WINDOWS_FUNCTION(winsock_module, listen);
  310. GET_WINDOWS_FUNCTION(winsock_module, send);
  311. GET_WINDOWS_FUNCTION(winsock_module, shutdown);
  312. GET_WINDOWS_FUNCTION(winsock_module, ioctlsocket);
  313. GET_WINDOWS_FUNCTION(winsock_module, accept);
  314. GET_WINDOWS_FUNCTION(winsock_module, getpeername);
  315. GET_WINDOWS_FUNCTION(winsock_module, recv);
  316. GET_WINDOWS_FUNCTION(winsock_module, WSAIoctl);
  317. /* Try to get the best WinSock version we can get */
  318. if (!sk_startup(2,2) &&
  319. !sk_startup(2,0) &&
  320. !sk_startup(1,1)) {
  321. modalfatalbox("Unable to initialise WinSock");
  322. }
  323. sktree = newtree234(cmpfortree);
  324. }
  325. void sk_cleanup(void)
  326. {
  327. NetSocket *s;
  328. int i;
  329. if (sktree) {
  330. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  331. p_closesocket(s->s);
  332. }
  333. freetree234(sktree);
  334. sktree = NULL;
  335. }
  336. if (p_WSACleanup)
  337. {
  338. p_WSACleanup();
  339. }
  340. if (winsock_module)
  341. FreeLibrary(winsock_module);
  342. #ifndef NO_IPV6
  343. if (wship6_module)
  344. FreeLibrary(wship6_module);
  345. #endif
  346. }
  347. const char *winsock_error_string(int error)
  348. {
  349. /*
  350. * Error codes we know about and have historically had reasonably
  351. * sensible error messages for.
  352. */
  353. switch (error) {
  354. case WSAEACCES:
  355. return "Network error: Permission denied";
  356. case WSAEADDRINUSE:
  357. return "Network error: Address already in use";
  358. case WSAEADDRNOTAVAIL:
  359. return "Network error: Cannot assign requested address";
  360. case WSAEAFNOSUPPORT:
  361. return
  362. "Network error: Address family not supported by protocol family";
  363. case WSAEALREADY:
  364. return "Network error: Operation already in progress";
  365. case WSAECONNABORTED:
  366. return "Network error: Software caused connection abort";
  367. case WSAECONNREFUSED:
  368. return "Network error: Connection refused";
  369. case WSAECONNRESET:
  370. return "Network error: Connection reset by peer";
  371. case WSAEDESTADDRREQ:
  372. return "Network error: Destination address required";
  373. case WSAEFAULT:
  374. return "Network error: Bad address";
  375. case WSAEHOSTDOWN:
  376. return "Network error: Host is down";
  377. case WSAEHOSTUNREACH:
  378. return "Network error: No route to host";
  379. case WSAEINPROGRESS:
  380. return "Network error: Operation now in progress";
  381. case WSAEINTR:
  382. return "Network error: Interrupted function call";
  383. case WSAEINVAL:
  384. return "Network error: Invalid argument";
  385. case WSAEISCONN:
  386. return "Network error: Socket is already connected";
  387. case WSAEMFILE:
  388. return "Network error: Too many open files";
  389. case WSAEMSGSIZE:
  390. return "Network error: Message too long";
  391. case WSAENETDOWN:
  392. return "Network error: Network is down";
  393. case WSAENETRESET:
  394. return "Network error: Network dropped connection on reset";
  395. case WSAENETUNREACH:
  396. return "Network error: Network is unreachable";
  397. case WSAENOBUFS:
  398. return "Network error: No buffer space available";
  399. case WSAENOPROTOOPT:
  400. return "Network error: Bad protocol option";
  401. case WSAENOTCONN:
  402. return "Network error: Socket is not connected";
  403. case WSAENOTSOCK:
  404. return "Network error: Socket operation on non-socket";
  405. case WSAEOPNOTSUPP:
  406. return "Network error: Operation not supported";
  407. case WSAEPFNOSUPPORT:
  408. return "Network error: Protocol family not supported";
  409. case WSAEPROCLIM:
  410. return "Network error: Too many processes";
  411. case WSAEPROTONOSUPPORT:
  412. return "Network error: Protocol not supported";
  413. case WSAEPROTOTYPE:
  414. return "Network error: Protocol wrong type for socket";
  415. case WSAESHUTDOWN:
  416. return "Network error: Cannot send after socket shutdown";
  417. case WSAESOCKTNOSUPPORT:
  418. return "Network error: Socket type not supported";
  419. case WSAETIMEDOUT:
  420. return "Network error: Connection timed out";
  421. case WSAEWOULDBLOCK:
  422. return "Network error: Resource temporarily unavailable";
  423. case WSAEDISCON:
  424. return "Network error: Graceful shutdown in progress";
  425. }
  426. /*
  427. * Handle any other error code by delegating to win_strerror.
  428. */
  429. return win_strerror(error);
  430. }
  431. static inline const char *namelookup_strerror(DWORD err)
  432. {
  433. /* PuTTY has traditionally translated a few of the likely error
  434. * messages into more concise strings than the standard Windows ones */
  435. return (err == WSAENETDOWN ? "Network is down" :
  436. err == WSAHOST_NOT_FOUND ? "Host does not exist" :
  437. err == WSATRY_AGAIN ? "Host not found" :
  438. win_strerror(err));
  439. }
  440. SockAddr *sk_namelookup(const char *host, char **canonicalname,
  441. int address_family)
  442. {
  443. *canonicalname = NULL;
  444. { // WINSCP
  445. SockAddr *addr = snew(SockAddr);
  446. memset(addr, 0, sizeof(SockAddr));
  447. addr->superfamily = UNRESOLVED;
  448. addr->refcount = 1;
  449. #ifndef NO_IPV6
  450. /*
  451. * Use getaddrinfo, as long as it's available. This should handle
  452. * both IPv4 and IPv6 address literals, and hostnames, in one
  453. * unified API.
  454. */
  455. if (p_getaddrinfo) {
  456. struct addrinfo hints;
  457. memset(&hints, 0, sizeof(hints));
  458. hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
  459. address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  460. AF_UNSPEC);
  461. hints.ai_flags = AI_CANONNAME;
  462. hints.ai_socktype = SOCK_STREAM;
  463. /* strip [] on IPv6 address literals */
  464. { // WINSCP
  465. char *trimmed_host = host_strduptrim(host);
  466. int err = p_getaddrinfo(trimmed_host, NULL, &hints, &addr->ais);
  467. sfree(trimmed_host);
  468. if (addr->ais) {
  469. addr->superfamily = IP;
  470. if (addr->ais->ai_canonname)
  471. *canonicalname = dupstr(addr->ais->ai_canonname);
  472. else
  473. *canonicalname = dupstr(host);
  474. } else {
  475. addr->error = namelookup_strerror(err);
  476. }
  477. return addr;
  478. } // WINSCP
  479. }
  480. #endif
  481. /*
  482. * Failing that (if IPv6 support was not compiled in, or if
  483. * getaddrinfo turned out to be unavailable at run time), try the
  484. * old-fashioned approach, which is to start by manually checking
  485. * for an IPv4 literal and then use gethostbyname.
  486. */
  487. { // WINSCP
  488. unsigned long a = p_inet_addr(host);
  489. if (a != (unsigned long) INADDR_NONE) {
  490. addr->addresses = snew(unsigned long);
  491. addr->naddresses = 1;
  492. addr->addresses[0] = p_ntohl(a);
  493. addr->superfamily = IP;
  494. *canonicalname = dupstr(host);
  495. return addr;
  496. }
  497. { // WINSCP
  498. struct hostent *h = p_gethostbyname(host);
  499. if (h) {
  500. addr->superfamily = IP;
  501. { // WINSCP
  502. size_t n;
  503. for (n = 0; h->h_addr_list[n]; n++);
  504. addr->addresses = snewn(n, unsigned long);
  505. addr->naddresses = n;
  506. for (n = 0; n < addr->naddresses; n++) {
  507. uint32_t a;
  508. memcpy(&a, h->h_addr_list[n], sizeof(a));
  509. addr->addresses[n] = p_ntohl(a);
  510. }
  511. *canonicalname = dupstr(h->h_name);
  512. } // WINSCP
  513. } else {
  514. DWORD err = p_WSAGetLastError();
  515. addr->error = namelookup_strerror(err);
  516. }
  517. return addr;
  518. } // WINSCP
  519. } // WINSCP
  520. } // WINSCP
  521. }
  522. static SockAddr *sk_special_addr(SuperFamily superfamily, const char *name)
  523. {
  524. SockAddr *ret = snew(SockAddr);
  525. ret->error = NULL;
  526. ret->superfamily = superfamily;
  527. #ifndef NO_IPV6
  528. ret->ais = NULL;
  529. #endif
  530. ret->addresses = NULL;
  531. ret->naddresses = 0;
  532. ret->refcount = 1;
  533. strncpy(ret->hostname, name, lenof(ret->hostname));
  534. ret->hostname[lenof(ret->hostname)-1] = '\0';
  535. return ret;
  536. }
  537. SockAddr *sk_nonamelookup(const char *host)
  538. {
  539. return sk_special_addr(UNRESOLVED, host);
  540. }
  541. SockAddr *sk_namedpipe_addr(const char *pipename)
  542. {
  543. return sk_special_addr(NAMEDPIPE, pipename);
  544. }
  545. #if HAVE_AFUNIX_H
  546. SockAddr *sk_unix_addr(const char *sockpath)
  547. {
  548. return sk_special_addr(UNIX, sockpath);
  549. }
  550. #endif
  551. static bool sk_nextaddr(SockAddr *addr, SockAddrStep *step)
  552. {
  553. #ifndef NO_IPV6
  554. if (step->ai) {
  555. if (step->ai->ai_next) {
  556. step->ai = step->ai->ai_next;
  557. return true;
  558. } else
  559. return false;
  560. }
  561. #endif
  562. if (step->curraddr+1 < addr->naddresses) {
  563. step->curraddr++;
  564. return true;
  565. } else {
  566. return false;
  567. }
  568. }
  569. void sk_getaddr(SockAddr *addr, char *buf, int buflen)
  570. {
  571. SockAddrStep step;
  572. START_STEP(addr, step);
  573. #ifndef NO_IPV6
  574. if (step.ai) {
  575. int err = 0;
  576. if (p_WSAAddressToStringA) {
  577. DWORD dwbuflen = buflen;
  578. err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen,
  579. NULL, buf, &dwbuflen);
  580. } else
  581. err = -1;
  582. if (err) {
  583. strncpy(buf, addr->hostname, buflen);
  584. if (!buf[0])
  585. strncpy(buf, "<unknown>", buflen);
  586. buf[buflen-1] = '\0';
  587. }
  588. } else
  589. #endif
  590. if (sockaddr_family(addr, step) == AF_INET) {
  591. struct in_addr a;
  592. assert(addr->addresses && step.curraddr < addr->naddresses);
  593. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  594. strncpy(buf, p_inet_ntoa(a), buflen);
  595. buf[buflen-1] = '\0';
  596. } else {
  597. strncpy(buf, addr->hostname, buflen);
  598. buf[buflen-1] = '\0';
  599. }
  600. }
  601. /*
  602. * This constructs a SockAddr that points at one specific sub-address
  603. * of a parent SockAddr. The returned SockAddr does not own all its
  604. * own memory: it points into the old one's data structures, so it
  605. * MUST NOT be used after the old one is freed, and it MUST NOT be
  606. * passed to sk_addr_free. (The latter is why it's returned by value
  607. * rather than dynamically allocated - that should clue in anyone
  608. * writing a call to it that something is weird about it.)
  609. */
  610. static SockAddr sk_extractaddr_tmp(
  611. SockAddr *addr, const SockAddrStep *step)
  612. {
  613. SockAddr toret;
  614. toret = *addr; /* structure copy */
  615. toret.refcount = 1;
  616. #ifndef NO_IPV6
  617. toret.ais = step->ai;
  618. #endif
  619. if (sockaddr_family(addr, *step) == AF_INET
  620. #ifndef NO_IPV6
  621. && !toret.ais
  622. #endif
  623. )
  624. toret.addresses += step->curraddr;
  625. return toret;
  626. }
  627. bool sk_addr_needs_port(SockAddr *addr)
  628. {
  629. return addr->superfamily != NAMEDPIPE
  630. #if HAVE_AFUNIX_H
  631. && addr->superfamily != UNIX
  632. #endif
  633. ;
  634. }
  635. bool sk_hostname_is_local(const char *name)
  636. {
  637. return !strcmp(name, "localhost") ||
  638. !strcmp(name, "::1") ||
  639. !strncmp(name, "127.", 4);
  640. }
  641. static INTERFACE_INFO local_interfaces[16];
  642. static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
  643. static bool ipv4_is_local_addr(struct in_addr addr)
  644. {
  645. if (ipv4_is_loopback(addr))
  646. return true; /* loopback addresses are local */
  647. if (!n_local_interfaces) {
  648. SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
  649. DWORD retbytes;
  650. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  651. if (p_WSAIoctl &&
  652. p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
  653. local_interfaces, sizeof(local_interfaces),
  654. &retbytes, NULL, NULL) == 0)
  655. n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
  656. else
  657. n_local_interfaces = -1;
  658. }
  659. if (n_local_interfaces > 0) {
  660. int i;
  661. for (i = 0; i < n_local_interfaces; i++) {
  662. SOCKADDR_IN *address =
  663. (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
  664. if (address->sin_addr.s_addr == addr.s_addr)
  665. return true; /* this address is local */
  666. }
  667. }
  668. return false; /* this address is not local */
  669. }
  670. bool sk_address_is_local(SockAddr *addr)
  671. {
  672. SockAddrStep step;
  673. int family;
  674. START_STEP(addr, step);
  675. family = sockaddr_family(addr, step);
  676. #ifndef NO_IPV6
  677. if (family == AF_INET6) {
  678. return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr);
  679. } else
  680. #endif
  681. if (family == AF_INET) {
  682. #ifndef NO_IPV6
  683. if (step.ai) {
  684. return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr)
  685. ->sin_addr);
  686. } else
  687. #endif
  688. {
  689. struct in_addr a;
  690. assert(addr->addresses && step.curraddr < addr->naddresses);
  691. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  692. return ipv4_is_local_addr(a);
  693. }
  694. } else {
  695. assert(family == AF_UNSPEC);
  696. return false; /* we don't know; assume not */
  697. }
  698. }
  699. bool sk_address_is_special_local(SockAddr *addr)
  700. {
  701. return false; /* no Unix-domain socket analogue here */
  702. }
  703. int sk_addrtype(SockAddr *addr)
  704. {
  705. SockAddrStep step;
  706. int family;
  707. START_STEP(addr, step);
  708. family = sockaddr_family(addr, step);
  709. return (family == AF_INET ? ADDRTYPE_IPV4 :
  710. #ifndef NO_IPV6
  711. family == AF_INET6 ? ADDRTYPE_IPV6 :
  712. #endif
  713. ADDRTYPE_NAME);
  714. }
  715. void sk_addrcopy(SockAddr *addr, char *buf)
  716. {
  717. SockAddrStep step;
  718. int family;
  719. START_STEP(addr, step);
  720. family = sockaddr_family(addr, step);
  721. assert(family != AF_UNSPEC);
  722. #ifndef NO_IPV6
  723. if (step.ai) {
  724. if (family == AF_INET)
  725. memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
  726. sizeof(struct in_addr));
  727. else if (family == AF_INET6)
  728. memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
  729. sizeof(struct in6_addr));
  730. else
  731. unreachable("bad address family in sk_addrcopy");
  732. } else
  733. #endif
  734. if (family == AF_INET) {
  735. struct in_addr a;
  736. assert(addr->addresses && step.curraddr < addr->naddresses);
  737. a.s_addr = p_htonl(addr->addresses[step.curraddr]);
  738. memcpy(buf, (char*) &a.s_addr, 4);
  739. }
  740. }
  741. void sk_addr_free(SockAddr *addr)
  742. {
  743. if (--addr->refcount > 0)
  744. return;
  745. #ifndef NO_IPV6
  746. if (addr->ais && p_freeaddrinfo)
  747. p_freeaddrinfo(addr->ais);
  748. #endif
  749. if (addr->addresses)
  750. sfree(addr->addresses);
  751. sfree(addr);
  752. }
  753. SockAddr *sk_addr_dup(SockAddr *addr)
  754. {
  755. addr->refcount++;
  756. return addr;
  757. }
  758. static Plug *sk_net_plug(Socket *sock, Plug *p)
  759. {
  760. NetSocket *s = container_of(sock, NetSocket, sock);
  761. Plug *ret = s->plug;
  762. if (p)
  763. s->plug = p;
  764. return ret;
  765. }
  766. static void sk_net_close(Socket *s);
  767. static size_t sk_net_write(Socket *s, const void *data, size_t len);
  768. static size_t sk_net_write_oob(Socket *s, const void *data, size_t len);
  769. static void sk_net_write_eof(Socket *s);
  770. static void sk_net_set_frozen(Socket *s, bool is_frozen);
  771. static const char *sk_net_socket_error(Socket *s);
  772. static SocketPeerInfo *sk_net_peer_info(Socket *s);
  773. static const SocketVtable NetSocket_sockvt = {
  774. // WINSCP
  775. /*.plug =*/ sk_net_plug,
  776. /*.close =*/ sk_net_close,
  777. /*.write =*/ sk_net_write,
  778. /*.write_oob =*/ sk_net_write_oob,
  779. /*.write_eof =*/ sk_net_write_eof,
  780. /*.set_frozen =*/ sk_net_set_frozen,
  781. /*.socket_error =*/ sk_net_socket_error,
  782. /*.peer_info =*/ sk_net_peer_info,
  783. };
  784. static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug)
  785. {
  786. DWORD err;
  787. const char *errstr;
  788. NetSocket *ret;
  789. /*
  790. * Create NetSocket structure.
  791. */
  792. ret = snew(NetSocket);
  793. ret->sock.vt = &NetSocket_sockvt;
  794. ret->error = NULL;
  795. ret->plug = plug;
  796. bufchain_init(&ret->output_data);
  797. ret->writable = true; /* to start with */
  798. ret->sending_oob = 0;
  799. ret->outgoingeof = EOF_NO;
  800. ret->frozen = true;
  801. ret->frozen_readable = false;
  802. ret->localhost_only = false; /* unused, but best init anyway */
  803. ret->pending_error = 0;
  804. ret->parent = ret->child = NULL;
  805. ret->addr = NULL;
  806. ret->s = (SOCKET)ctx.p;
  807. if (ret->s == INVALID_SOCKET) {
  808. err = p_WSAGetLastError();
  809. ret->error = winsock_error_string(err);
  810. return &ret->sock;
  811. }
  812. ret->oobinline = false;
  813. /* Set up a select mechanism. This could be an AsyncSelect on a
  814. * window, or an EventSelect on an event object. */
  815. #ifdef MPEXT
  816. errstr = do_select(plug, ret->s, true);
  817. #else
  818. #endif
  819. if (errstr) {
  820. ret->error = errstr;
  821. return &ret->sock;
  822. }
  823. add234(sktree, ret);
  824. return &ret->sock;
  825. }
  826. static DWORD try_connect(NetSocket *sock,
  827. #ifdef MPEXT
  828. int timeout,
  829. int sndbuf,
  830. const char *srcaddr
  831. #endif
  832. )
  833. {
  834. SOCKET s;
  835. #ifndef NO_IPV6
  836. SOCKADDR_IN6 a6;
  837. #endif
  838. SOCKADDR_IN a;
  839. DWORD err;
  840. const char *errstr;
  841. short localport;
  842. int family;
  843. #ifdef MPEXT
  844. struct timeval rcvtimeo;
  845. #endif
  846. if (sock->s != INVALID_SOCKET) {
  847. #ifdef MPEXT
  848. do_select(sock->plug, sock->s, false);
  849. #else
  850. do_select(sock->s, false);
  851. #endif
  852. p_closesocket(sock->s);
  853. }
  854. {
  855. SockAddr thisaddr = sk_extractaddr_tmp(
  856. sock->addr, &sock->step);
  857. plug_log(sock->plug, PLUGLOG_CONNECT_TRYING,
  858. &thisaddr, sock->port, NULL, 0);
  859. }
  860. /*
  861. * Open socket.
  862. */
  863. family = sockaddr_family(sock->addr, sock->step);
  864. /*
  865. * Remove the socket from the tree before we overwrite its
  866. * internal socket id, because that forms part of the tree's
  867. * sorting criterion. We'll add it back before exiting this
  868. * function, whether we changed anything or not.
  869. */
  870. del234(sktree, sock);
  871. s = p_socket(family, SOCK_STREAM, 0);
  872. sock->s = s;
  873. if (s == INVALID_SOCKET) {
  874. err = p_WSAGetLastError();
  875. sock->error = winsock_error_string(err);
  876. goto ret;
  877. }
  878. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  879. if (sock->oobinline) {
  880. BOOL b = true;
  881. p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
  882. }
  883. if (sock->nodelay) {
  884. BOOL b = true;
  885. p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
  886. }
  887. if (sock->keepalive) {
  888. BOOL b = true;
  889. p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
  890. }
  891. if (sndbuf > 0)
  892. {
  893. int rcvbuf = 4 * 1024 * 1024;
  894. p_setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf, sizeof(sndbuf));
  895. // For now we increase receive buffer, whenever send buffer is set.
  896. // The size is not configurable. The constant taken from FZ.
  897. p_setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*) &rcvbuf, sizeof(rcvbuf));
  898. }
  899. /*
  900. * Bind to local address.
  901. */
  902. if (sock->privport)
  903. localport = 1023; /* count from 1023 downwards */
  904. else
  905. localport = 0; /* just use port 0 (ie winsock picks) */
  906. /* Loop round trying to bind */
  907. while (1) {
  908. int sockcode;
  909. #ifndef NO_IPV6
  910. if (family == AF_INET6) {
  911. memset(&a6, 0, sizeof(a6));
  912. a6.sin6_family = AF_INET6;
  913. /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */
  914. a6.sin6_port = p_htons(localport);
  915. } else
  916. #endif
  917. {
  918. a.sin_family = AF_INET;
  919. if (srcaddr && srcaddr[0]) {
  920. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  921. } else {
  922. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  923. }
  924. a.sin_port = p_htons(localport);
  925. }
  926. #ifndef NO_IPV6
  927. sockcode = p_bind(s, (family == AF_INET6 ?
  928. (struct sockaddr *) &a6 :
  929. (struct sockaddr *) &a),
  930. (family == AF_INET6 ? sizeof(a6) : sizeof(a)));
  931. #else
  932. sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
  933. #endif
  934. if (sockcode != SOCKET_ERROR) {
  935. err = 0;
  936. break; /* done */
  937. } else {
  938. err = p_WSAGetLastError();
  939. if (err != WSAEADDRINUSE) /* failed, for a bad reason */
  940. break;
  941. }
  942. if (localport == 0)
  943. break; /* we're only looping once */
  944. localport--;
  945. if (localport == 0)
  946. break; /* we might have got to the end */
  947. }
  948. if (err) {
  949. sock->error = winsock_error_string(err);
  950. goto ret;
  951. }
  952. /*
  953. * Connect to remote address.
  954. */
  955. #ifndef NO_IPV6
  956. if (sock->step.ai) {
  957. if (family == AF_INET6) {
  958. a6.sin6_family = AF_INET6;
  959. a6.sin6_port = p_htons((short) sock->port);
  960. a6.sin6_addr =
  961. ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr;
  962. a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo;
  963. a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id;
  964. } else {
  965. a.sin_family = AF_INET;
  966. a.sin_addr =
  967. ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr;
  968. a.sin_port = p_htons((short) sock->port);
  969. }
  970. } else
  971. #endif
  972. {
  973. assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses);
  974. a.sin_family = AF_INET;
  975. a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]);
  976. a.sin_port = p_htons((short) sock->port);
  977. }
  978. #ifndef MPEXT
  979. /* Set up a select mechanism. This could be an AsyncSelect on a
  980. * window, or an EventSelect on an event object. */
  981. errstr = do_select(s, true);
  982. if (errstr) {
  983. sock->error = errstr;
  984. err = 1;
  985. goto ret;
  986. }
  987. #endif
  988. #ifdef MPEXT
  989. if (timeout > 0)
  990. {
  991. if (p_getsockopt (s, SOL_SOCKET, SO_RCVTIMEO, (char *)&rcvtimeo, &rcvtimeo) < 0)
  992. {
  993. rcvtimeo.tv_sec = -1;
  994. }
  995. else
  996. {
  997. struct timeval timeoutval;
  998. timeoutval.tv_sec = timeout / 1000;
  999. timeoutval.tv_usec = (timeout % 1000) * 1000;
  1000. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &timeoutval, sizeof(timeoutval));
  1001. }
  1002. }
  1003. #endif
  1004. if ((
  1005. #ifndef NO_IPV6
  1006. p_connect(s,
  1007. ((family == AF_INET6) ? (struct sockaddr *) &a6 :
  1008. (struct sockaddr *) &a),
  1009. (family == AF_INET6) ? sizeof(a6) : sizeof(a))
  1010. #else
  1011. p_connect(s, (struct sockaddr *) &a, sizeof(a))
  1012. #endif
  1013. ) == SOCKET_ERROR) {
  1014. err = p_WSAGetLastError();
  1015. /*
  1016. * We expect a potential EWOULDBLOCK here, because the
  1017. * chances are the front end has done a select for
  1018. * FD_CONNECT, so that connect() will complete
  1019. * asynchronously.
  1020. */
  1021. if ( err != WSAEWOULDBLOCK ) {
  1022. #ifdef MPEXT
  1023. // unselect on error
  1024. do_select(sock->plug, s, 0);
  1025. #endif
  1026. sock->error = winsock_error_string(err);
  1027. goto ret;
  1028. }
  1029. } else {
  1030. /*
  1031. * If we _don't_ get EWOULDBLOCK, the connect has completed
  1032. * and we should set the socket as writable.
  1033. */
  1034. sock->writable = true;
  1035. { // WINSCP
  1036. SockAddr thisaddr = sk_extractaddr_tmp(sock->addr, &sock->step);
  1037. plug_log(sock->plug, PLUGLOG_CONNECT_SUCCESS,
  1038. &thisaddr, sock->port, NULL, 0);
  1039. } // WINSCP
  1040. }
  1041. #ifdef MPEXT
  1042. if ((timeout > 0) && (rcvtimeo.tv_sec >= 0))
  1043. {
  1044. p_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *) &rcvtimeo, sizeof(rcvtimeo));
  1045. }
  1046. // MP: Calling EventSelect only after connect makes sure we receive FD_CLOSE.
  1047. /* Set up a select mechanism. This could be an AsyncSelect on a
  1048. * window, or an EventSelect on an event object. */
  1049. errstr = do_select(sock->plug, s, 1);
  1050. if (errstr) {
  1051. sock->error = errstr;
  1052. err = 1;
  1053. goto ret;
  1054. }
  1055. #endif
  1056. err = 0;
  1057. ret:
  1058. /*
  1059. * No matter what happened, put the socket back in the tree.
  1060. */
  1061. add234(sktree, sock);
  1062. if (err) {
  1063. SockAddr thisaddr = sk_extractaddr_tmp(
  1064. sock->addr, &sock->step);
  1065. plug_log(sock->plug, PLUGLOG_CONNECT_FAILED,
  1066. &thisaddr, sock->port, sock->error, err);
  1067. }
  1068. return err;
  1069. }
  1070. Socket *sk_new(SockAddr *addr, int port, bool privport, bool oobinline,
  1071. bool nodelay, bool keepalive, Plug *plug,
  1072. #ifdef MPEXT
  1073. int timeout,
  1074. int sndbuf,
  1075. const char *srcaddr
  1076. #endif
  1077. )
  1078. {
  1079. NetSocket *ret;
  1080. DWORD err;
  1081. /*
  1082. * Create NetSocket structure.
  1083. */
  1084. ret = snew(NetSocket);
  1085. ret->sock.vt = &NetSocket_sockvt;
  1086. ret->error = NULL;
  1087. ret->plug = plug;
  1088. bufchain_init(&ret->output_data);
  1089. ret->connected = false; /* to start with */
  1090. ret->writable = false; /* to start with */
  1091. ret->sending_oob = 0;
  1092. ret->outgoingeof = EOF_NO;
  1093. ret->frozen = false;
  1094. ret->frozen_readable = false;
  1095. ret->localhost_only = false; /* unused, but best init anyway */
  1096. ret->pending_error = 0;
  1097. ret->parent = ret->child = NULL;
  1098. ret->oobinline = oobinline;
  1099. ret->nodelay = nodelay;
  1100. ret->keepalive = keepalive;
  1101. ret->privport = privport;
  1102. ret->port = port;
  1103. ret->addr = addr;
  1104. START_STEP(ret->addr, ret->step);
  1105. ret->s = INVALID_SOCKET;
  1106. err = 0;
  1107. do {
  1108. #ifdef MPEXT
  1109. ret->error = NULL;
  1110. #endif
  1111. err = try_connect(ret
  1112. #ifdef MPEXT
  1113. , timeout, sndbuf, srcaddr
  1114. #endif
  1115. );
  1116. } while (err && sk_nextaddr(ret->addr, &ret->step));
  1117. return &ret->sock;
  1118. }
  1119. static Socket *sk_newlistener_internal(
  1120. const char *srcaddr, int port, Plug *plug,
  1121. bool local_host_only, int orig_address_family)
  1122. {
  1123. SOCKET s;
  1124. SOCKADDR_IN a;
  1125. #ifndef NO_IPV6
  1126. SOCKADDR_IN6 a6;
  1127. #endif
  1128. #if HAVE_AFUNIX_H
  1129. SOCKADDR_UN au;
  1130. #endif
  1131. struct sockaddr *bindaddr;
  1132. unsigned bindsize;
  1133. DWORD err;
  1134. const char *errstr;
  1135. NetSocket *ret;
  1136. int retcode;
  1137. int address_family = orig_address_family;
  1138. /*
  1139. * Create NetSocket structure.
  1140. */
  1141. ret = snew(NetSocket);
  1142. ret->sock.vt = &NetSocket_sockvt;
  1143. ret->error = NULL;
  1144. ret->plug = plug;
  1145. bufchain_init(&ret->output_data);
  1146. ret->writable = false; /* to start with */
  1147. ret->sending_oob = 0;
  1148. ret->outgoingeof = EOF_NO;
  1149. ret->frozen = false;
  1150. ret->frozen_readable = false;
  1151. ret->localhost_only = local_host_only;
  1152. ret->pending_error = 0;
  1153. ret->parent = ret->child = NULL;
  1154. ret->addr = NULL;
  1155. /*
  1156. * Our default, if passed the `don't care' value
  1157. * ADDRTYPE_UNSPEC, is to listen on IPv4. If IPv6 is supported,
  1158. * we will also set up a second socket listening on IPv6, but
  1159. * the v4 one is primary since that ought to work even on
  1160. * non-v6-supporting systems.
  1161. */
  1162. if (address_family == AF_UNSPEC) address_family = AF_INET;
  1163. /*
  1164. * Open socket.
  1165. */
  1166. s = p_socket(address_family, SOCK_STREAM, 0);
  1167. ret->s = s;
  1168. if (s == INVALID_SOCKET) {
  1169. err = p_WSAGetLastError();
  1170. ret->error = winsock_error_string(err);
  1171. return &ret->sock;
  1172. }
  1173. SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0);
  1174. ret->oobinline = false;
  1175. #if HAVE_AFUNIX_H
  1176. if (address_family != AF_UNIX)
  1177. #endif
  1178. {
  1179. BOOL on = true;
  1180. p_setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  1181. (const char *)&on, sizeof(on));
  1182. }
  1183. switch (address_family) {
  1184. #ifndef NO_IPV6
  1185. case AF_INET6: {
  1186. memset(&a6, 0, sizeof(a6));
  1187. a6.sin6_family = AF_INET6;
  1188. if (local_host_only)
  1189. a6.sin6_addr = in6addr_loopback;
  1190. else
  1191. a6.sin6_addr = in6addr_any;
  1192. if (srcaddr != NULL && p_getaddrinfo) {
  1193. struct addrinfo hints;
  1194. struct addrinfo *ai;
  1195. int err;
  1196. memset(&hints, 0, sizeof(hints));
  1197. hints.ai_family = AF_INET6;
  1198. hints.ai_flags = 0;
  1199. {
  1200. /* strip [] on IPv6 address literals */
  1201. char *trimmed_addr = host_strduptrim(srcaddr);
  1202. err = p_getaddrinfo(trimmed_addr, NULL, &hints, &ai);
  1203. sfree(trimmed_addr);
  1204. }
  1205. if (err == 0 && ai->ai_family == AF_INET6) {
  1206. a6.sin6_addr =
  1207. ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
  1208. }
  1209. }
  1210. a6.sin6_port = p_htons(port);
  1211. bindaddr = (struct sockaddr *)&a6;
  1212. bindsize = sizeof(a6);
  1213. break;
  1214. }
  1215. #endif
  1216. case AF_INET: {
  1217. bool got_addr = false;
  1218. a.sin_family = AF_INET;
  1219. /*
  1220. * Bind to source address. First try an explicitly
  1221. * specified one...
  1222. */
  1223. if (srcaddr) {
  1224. a.sin_addr.s_addr = p_inet_addr(srcaddr);
  1225. if (a.sin_addr.s_addr != INADDR_NONE) {
  1226. /* Override localhost_only with specified listen addr. */
  1227. ret->localhost_only = ipv4_is_loopback(a.sin_addr);
  1228. got_addr = true;
  1229. }
  1230. }
  1231. /*
  1232. * ... and failing that, go with one of the standard ones.
  1233. */
  1234. if (!got_addr) {
  1235. if (local_host_only)
  1236. a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
  1237. else
  1238. a.sin_addr.s_addr = p_htonl(INADDR_ANY);
  1239. }
  1240. a.sin_port = p_htons((short)port);
  1241. bindaddr = (struct sockaddr *)&a;
  1242. bindsize = sizeof(a);
  1243. break;
  1244. }
  1245. #if HAVE_AFUNIX_H
  1246. case AF_UNIX: {
  1247. au.sun_family = AF_UNIX;
  1248. strncpy(au.sun_path, srcaddr, sizeof(au.sun_path));
  1249. bindaddr = (struct sockaddr *)&au;
  1250. bindsize = sizeof(au);
  1251. break;
  1252. }
  1253. #endif
  1254. default:
  1255. unreachable("bad address family in sk_newlistener_internal");
  1256. }
  1257. retcode = p_bind(s, bindaddr, bindsize);
  1258. if (retcode != SOCKET_ERROR) {
  1259. err = 0;
  1260. } else {
  1261. err = p_WSAGetLastError();
  1262. }
  1263. if (err) {
  1264. p_closesocket(s);
  1265. ret->error = winsock_error_string(err);
  1266. return &ret->sock;
  1267. }
  1268. if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
  1269. p_closesocket(s);
  1270. ret->error = winsock_error_string(p_WSAGetLastError());
  1271. return &ret->sock;
  1272. }
  1273. /* Set up a select mechanism. This could be an AsyncSelect on a
  1274. * window, or an EventSelect on an event object. */
  1275. #ifdef MPEXT
  1276. errstr = do_select(plug, s, true);
  1277. #else
  1278. errstr = do_select(s, true);
  1279. #endif
  1280. if (errstr) {
  1281. p_closesocket(s);
  1282. ret->error = errstr;
  1283. return &ret->sock;
  1284. }
  1285. add234(sktree, ret);
  1286. #ifndef NO_IPV6
  1287. /*
  1288. * If we were given ADDRTYPE_UNSPEC, we must also create an
  1289. * IPv6 listening socket and link it to this one.
  1290. */
  1291. if (address_family == AF_INET && orig_address_family == AF_UNSPEC) {
  1292. Socket *other = sk_newlistener_internal(srcaddr, port, plug,
  1293. local_host_only, AF_INET6);
  1294. if (other) {
  1295. NetSocket *ns = container_of(other, NetSocket, sock);
  1296. if (!ns->error) {
  1297. ns->parent = ret;
  1298. ret->child = ns;
  1299. } else {
  1300. sfree(ns);
  1301. }
  1302. }
  1303. }
  1304. #endif
  1305. return &ret->sock;
  1306. }
  1307. Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug,
  1308. bool local_host_only, int orig_address_family)
  1309. {
  1310. /*
  1311. * Translate address_family from platform-independent constants
  1312. * into local reality.
  1313. */
  1314. int address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
  1315. #ifndef NO_IPV6
  1316. orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
  1317. #endif
  1318. AF_UNSPEC);
  1319. return sk_newlistener_internal(srcaddr, port, plug, local_host_only,
  1320. address_family);
  1321. }
  1322. Socket *sk_newlistener_unix(const char *path, Plug *plug)
  1323. {
  1324. #if HAVE_AFUNIX_H
  1325. return sk_newlistener_internal(path, 0, plug, false, AF_UNIX);
  1326. #else
  1327. return new_error_socket_fmt(
  1328. plug, "AF_UNIX support not compiled into this program");
  1329. #endif
  1330. }
  1331. static void sk_net_close(Socket *sock)
  1332. {
  1333. NetSocket *s = container_of(sock, NetSocket, sock);
  1334. if (s->child)
  1335. sk_net_close(&s->child->sock);
  1336. bufchain_clear(&s->output_data);
  1337. del234(sktree, s);
  1338. #ifdef MPEXT
  1339. do_select(s->plug, s->s, false);
  1340. #else
  1341. do_select(s->s, false);
  1342. #endif
  1343. p_closesocket(s->s);
  1344. if (s->addr)
  1345. sk_addr_free(s->addr);
  1346. delete_callbacks_for_context(get_callback_set(s->plug), s);
  1347. sfree(s);
  1348. }
  1349. void plug_closing_system_error(Plug *plug, DWORD error)
  1350. {
  1351. PlugCloseType type = PLUGCLOSE_ERROR;
  1352. if (error == ERROR_BROKEN_PIPE)
  1353. type = PLUGCLOSE_BROKEN_PIPE;
  1354. plug_closing(plug, type, win_strerror(error));
  1355. }
  1356. void plug_closing_winsock_error(Plug *plug, DWORD error)
  1357. {
  1358. plug_closing(plug, PLUGCLOSE_ERROR, winsock_error_string(error));
  1359. }
  1360. /*
  1361. * Deal with socket errors detected in try_send().
  1362. */
  1363. static void socket_error_callback(void *vs)
  1364. {
  1365. NetSocket *s = (NetSocket *)vs;
  1366. /*
  1367. * Just in case other socket work has caused this socket to vanish
  1368. * or become somehow non-erroneous before this callback arrived...
  1369. */
  1370. if (!find234(sktree, s, NULL) || !s->pending_error)
  1371. return;
  1372. /*
  1373. * An error has occurred on this socket. Pass it to the plug.
  1374. */
  1375. plug_closing_winsock_error(s->plug, s->pending_error);
  1376. }
  1377. /*
  1378. * The function which tries to send on a socket once it's deemed
  1379. * writable.
  1380. */
  1381. static void try_send(NetSocket *s)
  1382. {
  1383. while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
  1384. int nsent;
  1385. DWORD err;
  1386. const void *data;
  1387. size_t len;
  1388. int urgentflag;
  1389. if (s->sending_oob) {
  1390. urgentflag = MSG_OOB;
  1391. len = s->sending_oob;
  1392. data = &s->oobdata;
  1393. } else {
  1394. urgentflag = 0;
  1395. { // WINSCP
  1396. ptrlen bufdata = bufchain_prefix(&s->output_data);
  1397. data = bufdata.ptr;
  1398. len = bufdata.len;
  1399. } // WINSCP
  1400. }
  1401. len = min(len, INT_MAX); /* WinSock send() takes an int */
  1402. nsent = p_send(s->s, data, len, urgentflag);
  1403. noise_ultralight(NOISE_SOURCE_IOLEN, nsent);
  1404. if (nsent <= 0) {
  1405. err = (nsent < 0 ? p_WSAGetLastError() : 0);
  1406. if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
  1407. /*
  1408. * Perfectly normal: we've sent all we can for the moment.
  1409. *
  1410. * (Some WinSock send() implementations can return
  1411. * <0 but leave no sensible error indication -
  1412. * WSAGetLastError() is called but returns zero or
  1413. * a small number - so we check that case and treat
  1414. * it just like WSAEWOULDBLOCK.)
  1415. */
  1416. s->writable = false;
  1417. return;
  1418. } else {
  1419. /*
  1420. * If send() returns a socket error, we unfortunately
  1421. * can't just call plug_closing(), because it's quite
  1422. * likely that we're currently _in_ a call from the
  1423. * code we'd be calling back to, so we'd have to make
  1424. * half the SSH code reentrant. Instead we flag a
  1425. * pending error on the socket, to be dealt with (by
  1426. * calling plug_closing()) at some suitable future
  1427. * moment.
  1428. */
  1429. s->pending_error = err;
  1430. queue_toplevel_callback(get_callback_set(s->plug), socket_error_callback, s);
  1431. return;
  1432. }
  1433. } else {
  1434. if (s->sending_oob) {
  1435. if (nsent < len) {
  1436. memmove(s->oobdata, s->oobdata+nsent, len-nsent);
  1437. s->sending_oob = len - nsent;
  1438. } else {
  1439. s->sending_oob = 0;
  1440. }
  1441. } else {
  1442. bufchain_consume(&s->output_data, nsent);
  1443. }
  1444. }
  1445. }
  1446. /*
  1447. * If we reach here, we've finished sending everything we might
  1448. * have needed to send. Send EOF, if we need to.
  1449. */
  1450. if (s->outgoingeof == EOF_PENDING) {
  1451. p_shutdown(s->s, SD_SEND);
  1452. s->outgoingeof = EOF_SENT;
  1453. }
  1454. }
  1455. static size_t sk_net_write(Socket *sock, const void *buf, size_t len)
  1456. {
  1457. NetSocket *s = container_of(sock, NetSocket, sock);
  1458. assert(s->outgoingeof == EOF_NO);
  1459. /*
  1460. * Add the data to the buffer list on the socket.
  1461. */
  1462. bufchain_add(&s->output_data, buf, len);
  1463. /*
  1464. * Now try sending from the start of the buffer list.
  1465. */
  1466. if (s->writable)
  1467. try_send(s);
  1468. return bufchain_size(&s->output_data);
  1469. }
  1470. static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len)
  1471. {
  1472. NetSocket *s = container_of(sock, NetSocket, sock);
  1473. assert(s->outgoingeof == EOF_NO);
  1474. /*
  1475. * Replace the buffer list on the socket with the data.
  1476. */
  1477. bufchain_clear(&s->output_data);
  1478. assert(len <= sizeof(s->oobdata));
  1479. memcpy(s->oobdata, buf, len);
  1480. s->sending_oob = len;
  1481. /*
  1482. * Now try sending from the start of the buffer list.
  1483. */
  1484. if (s->writable)
  1485. try_send(s);
  1486. return s->sending_oob;
  1487. }
  1488. static void sk_net_write_eof(Socket *sock)
  1489. {
  1490. NetSocket *s = container_of(sock, NetSocket, sock);
  1491. assert(s->outgoingeof == EOF_NO);
  1492. /*
  1493. * Mark the socket as pending outgoing EOF.
  1494. */
  1495. s->outgoingeof = EOF_PENDING;
  1496. /*
  1497. * Now try sending from the start of the buffer list.
  1498. */
  1499. if (s->writable)
  1500. try_send(s);
  1501. }
  1502. void select_result(WPARAM wParam, LPARAM lParam)
  1503. {
  1504. int ret;
  1505. DWORD err;
  1506. char buf[20480]; /* nice big buffer for plenty of speed */
  1507. NetSocket *s;
  1508. bool atmark;
  1509. /* wParam is the socket itself */
  1510. if (wParam == 0)
  1511. return; /* boggle */
  1512. s = find234(sktree, (void *) wParam, cmpforsearch);
  1513. if (!s)
  1514. return; /* boggle */
  1515. if ((err = WSAGETSELECTERROR(lParam)) != 0) {
  1516. /*
  1517. * An error has occurred on this socket. Pass it to the
  1518. * plug.
  1519. */
  1520. if (s->addr) {
  1521. SockAddr thisaddr = sk_extractaddr_tmp(
  1522. s->addr, &s->step);
  1523. plug_log(s->plug, PLUGLOG_CONNECT_FAILED, &thisaddr, s->port,
  1524. winsock_error_string(err), err);
  1525. while (err && s->addr && sk_nextaddr(s->addr, &s->step)) {
  1526. err = try_connect(s
  1527. #ifdef MPEXT
  1528. , 0, 0, NULL
  1529. #endif
  1530. );
  1531. }
  1532. }
  1533. if (err != 0)
  1534. {
  1535. plug_closing_winsock_error(s->plug, err);
  1536. }
  1537. return;
  1538. }
  1539. noise_ultralight(NOISE_SOURCE_IOID, wParam);
  1540. switch (WSAGETSELECTEVENT(lParam)) {
  1541. case FD_CONNECT:
  1542. s->connected = true;
  1543. s->writable = true;
  1544. /*
  1545. * Once a socket is connected, we can stop falling back
  1546. * through the candidate addresses to connect to. But first,
  1547. * let the plug know we were successful.
  1548. */
  1549. if (s->addr) {
  1550. SockAddr thisaddr = sk_extractaddr_tmp(
  1551. s->addr, &s->step);
  1552. plug_log(s->plug, PLUGLOG_CONNECT_SUCCESS,
  1553. &thisaddr, s->port, NULL, 0);
  1554. sk_addr_free(s->addr);
  1555. s->addr = NULL;
  1556. }
  1557. break;
  1558. case FD_READ:
  1559. /* In the case the socket is still frozen, we don't even bother */
  1560. if (s->frozen) {
  1561. s->frozen_readable = true;
  1562. break;
  1563. }
  1564. /*
  1565. * We have received data on the socket. For an oobinline
  1566. * socket, this might be data _before_ an urgent pointer,
  1567. * in which case we send it to the back end with type==1
  1568. * (data prior to urgent).
  1569. */
  1570. if (s->oobinline) {
  1571. u_long atmark_from_ioctl = 1;
  1572. p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl);
  1573. /*
  1574. * Avoid checking the return value from ioctlsocket(),
  1575. * on the grounds that some WinSock wrappers don't
  1576. * support it. If it does nothing, we get atmark==1,
  1577. * which is equivalent to `no OOB pending', so the
  1578. * effect will be to non-OOB-ify any OOB data.
  1579. */
  1580. atmark = atmark_from_ioctl;
  1581. } else
  1582. atmark = true;
  1583. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1584. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1585. if (ret < 0) {
  1586. err = p_WSAGetLastError();
  1587. if (err == WSAEWOULDBLOCK) {
  1588. break;
  1589. }
  1590. }
  1591. if (ret < 0) {
  1592. plug_closing_winsock_error(s->plug, err);
  1593. } else if (0 == ret) {
  1594. plug_closing_normal(s->plug);
  1595. } else {
  1596. plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
  1597. }
  1598. break;
  1599. case FD_OOB:
  1600. /*
  1601. * This will only happen on a non-oobinline socket. It
  1602. * indicates that we can immediately perform an OOB read
  1603. * and get back OOB data, which we will send to the back
  1604. * end with type==2 (urgent data).
  1605. */
  1606. ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
  1607. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1608. if (ret <= 0) {
  1609. int err = p_WSAGetLastError();
  1610. plug_closing_winsock_error(s->plug, err);
  1611. } else {
  1612. plug_receive(s->plug, 2, buf, ret);
  1613. }
  1614. break;
  1615. case FD_WRITE: {
  1616. int bufsize_before, bufsize_after;
  1617. s->writable = true;
  1618. bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
  1619. try_send(s);
  1620. bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
  1621. if (bufsize_after < bufsize_before)
  1622. plug_sent(s->plug, bufsize_after);
  1623. break;
  1624. }
  1625. case FD_CLOSE:
  1626. /* Signal a close on the socket. First read any outstanding data. */
  1627. do {
  1628. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1629. if (ret < 0) {
  1630. err = p_WSAGetLastError();
  1631. if (err == WSAEWOULDBLOCK)
  1632. break;
  1633. plug_closing_winsock_error(s->plug, err);
  1634. } else {
  1635. if (ret)
  1636. plug_receive(s->plug, 0, buf, ret);
  1637. else
  1638. {
  1639. plug_closing_normal(s->plug);
  1640. }
  1641. }
  1642. } while (ret > 0);
  1643. return;
  1644. case FD_ACCEPT: {
  1645. #ifdef NO_IPV6
  1646. struct sockaddr_in isa;
  1647. #else
  1648. struct sockaddr_storage isa; // FIXME: also if Unix and no IPv6
  1649. #endif
  1650. int addrlen = sizeof(isa);
  1651. SOCKET t; /* socket of connection */
  1652. accept_ctx_t actx;
  1653. memset(&isa, 0, sizeof(isa));
  1654. err = 0;
  1655. t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
  1656. if (t == INVALID_SOCKET)
  1657. {
  1658. err = p_WSAGetLastError();
  1659. if (err == WSATRY_AGAIN)
  1660. break;
  1661. }
  1662. actx.p = (void *)t;
  1663. #ifndef NO_IPV6
  1664. if (isa.ss_family == AF_INET &&
  1665. s->localhost_only &&
  1666. !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
  1667. #else
  1668. if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
  1669. #endif
  1670. {
  1671. p_closesocket(t); /* dodgy WinSock let nonlocal through */
  1672. } else if (plug_accepting(s->plug, sk_net_accept, actx)) {
  1673. p_closesocket(t); /* denied or error */
  1674. }
  1675. break;
  1676. }
  1677. }
  1678. }
  1679. /*
  1680. * Special error values are returned from sk_namelookup and sk_new
  1681. * if there's a problem. These functions extract an error message,
  1682. * or return NULL if there's no problem.
  1683. */
  1684. const char *sk_addr_error(SockAddr *addr)
  1685. {
  1686. return addr->error;
  1687. }
  1688. static const char *sk_net_socket_error(Socket *sock)
  1689. {
  1690. NetSocket *s = container_of(sock, NetSocket, sock);
  1691. return s->error;
  1692. }
  1693. static SocketPeerInfo *sk_net_peer_info(Socket *sock)
  1694. {
  1695. NetSocket *s = container_of(sock, NetSocket, sock);
  1696. #ifdef NO_IPV6
  1697. struct sockaddr_in addr;
  1698. #else
  1699. struct sockaddr_storage addr; // FIXME: also if Unix and no IPv6
  1700. char buf[INET6_ADDRSTRLEN];
  1701. #endif
  1702. int addrlen = sizeof(addr);
  1703. SocketPeerInfo *pi;
  1704. if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
  1705. return NULL;
  1706. pi = snew(SocketPeerInfo);
  1707. pi->addressfamily = ADDRTYPE_UNSPEC;
  1708. pi->addr_text = NULL;
  1709. pi->port = -1;
  1710. pi->log_text = NULL;
  1711. if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
  1712. pi->addressfamily = ADDRTYPE_IPV4;
  1713. memcpy(pi->addr_bin.ipv4, &((struct sockaddr_in *)&addr)->sin_addr, 4);
  1714. pi->port = p_ntohs(((struct sockaddr_in *)&addr)->sin_port);
  1715. pi->addr_text = dupstr(
  1716. p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr));
  1717. pi->log_text = dupprintf("%s:%d", pi->addr_text, pi->port);
  1718. #ifndef NO_IPV6
  1719. } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
  1720. pi->addressfamily = ADDRTYPE_IPV6;
  1721. memcpy(pi->addr_bin.ipv6,
  1722. &((struct sockaddr_in6 *)&addr)->sin6_addr, 16);
  1723. pi->port = p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port);
  1724. pi->addr_text = dupstr(
  1725. p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
  1726. buf, sizeof(buf)));
  1727. pi->log_text = dupprintf("[%s]:%d", pi->addr_text, pi->port);
  1728. #endif
  1729. } else {
  1730. sfree(pi);
  1731. return NULL;
  1732. }
  1733. return pi;
  1734. }
  1735. static void sk_net_set_frozen(Socket *sock, bool is_frozen)
  1736. {
  1737. NetSocket *s = container_of(sock, NetSocket, sock);
  1738. if (s->frozen == is_frozen)
  1739. return;
  1740. s->frozen = is_frozen;
  1741. if (!is_frozen) {
  1742. #ifdef MPEXT
  1743. do_select(s->plug, s->s, true);
  1744. #else
  1745. do_select(s->s, true);
  1746. #endif
  1747. if (s->frozen_readable) {
  1748. char c;
  1749. p_recv(s->s, &c, 1, MSG_PEEK);
  1750. }
  1751. }
  1752. s->frozen_readable = false;
  1753. }
  1754. void socket_reselect_all(void)
  1755. {
  1756. NetSocket *s;
  1757. int i;
  1758. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  1759. if (!s->frozen)
  1760. #ifdef MPEXT
  1761. do_select(s->plug, s->s, true);
  1762. #else
  1763. do_select(s->s, true);
  1764. #endif
  1765. }
  1766. }
  1767. /*
  1768. * For Plink: enumerate all sockets currently active.
  1769. */
  1770. SOCKET first_socket(int *state)
  1771. {
  1772. NetSocket *s;
  1773. *state = 0;
  1774. s = index234(sktree, (*state)++);
  1775. return s ? s->s : INVALID_SOCKET;
  1776. }
  1777. SOCKET next_socket(int *state)
  1778. {
  1779. NetSocket *s = index234(sktree, (*state)++);
  1780. return s ? s->s : INVALID_SOCKET;
  1781. }
  1782. bool socket_writable(SOCKET skt)
  1783. {
  1784. NetSocket *s = find234(sktree, (void *)skt, cmpforsearch);
  1785. if (s)
  1786. return bufchain_size(&s->output_data) > 0;
  1787. else
  1788. return false;
  1789. }
  1790. int net_service_lookup(const char *service)
  1791. {
  1792. struct servent *se;
  1793. se = p_getservbyname(service, NULL);
  1794. if (se != NULL)
  1795. return p_ntohs(se->s_port);
  1796. else
  1797. return 0;
  1798. }
  1799. char *get_hostname(void)
  1800. {
  1801. char hostbuf[256]; /* MSDN docs for gethostname() promise this is enough */
  1802. if (p_gethostname(hostbuf, sizeof(hostbuf)) < 0)
  1803. return NULL;
  1804. return dupstr(hostbuf);
  1805. }
  1806. SockAddr *platform_get_x11_unix_address(const char *display, int displaynum)
  1807. {
  1808. SockAddr *ret = snew(SockAddr);
  1809. memset(ret, 0, sizeof(SockAddr));
  1810. ret->error = "unix sockets for X11 not supported on this platform";
  1811. ret->refcount = 1;
  1812. return ret;
  1813. }