winnet.c 55 KB

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