network.c 61 KB

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