winnet.c 57 KB

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