winnet.c 56 KB

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