winnet.c 51 KB

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