winnet.c 56 KB

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