1
0

winnet.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  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. size_t 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 size_t sk_net_write(Socket *s, const void *data, size_t len);
  769. static size_t sk_net_write_oob(Socket *s, const void *data, size_t 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. bufchain_clear(&s->output_data);
  1211. del234(sktree, s);
  1212. do_select(s->s, false);
  1213. p_closesocket(s->s);
  1214. if (s->addr)
  1215. sk_addr_free(s->addr);
  1216. sfree(s);
  1217. }
  1218. /*
  1219. * Deal with socket errors detected in try_send().
  1220. */
  1221. static void socket_error_callback(void *vs)
  1222. {
  1223. NetSocket *s = (NetSocket *)vs;
  1224. /*
  1225. * Just in case other socket work has caused this socket to vanish
  1226. * or become somehow non-erroneous before this callback arrived...
  1227. */
  1228. if (!find234(sktree, s, NULL) || !s->pending_error)
  1229. return;
  1230. /*
  1231. * An error has occurred on this socket. Pass it to the plug.
  1232. */
  1233. plug_closing(s->plug, winsock_error_string(s->pending_error),
  1234. s->pending_error, 0);
  1235. }
  1236. /*
  1237. * The function which tries to send on a socket once it's deemed
  1238. * writable.
  1239. */
  1240. void try_send(NetSocket *s)
  1241. {
  1242. while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
  1243. int nsent;
  1244. DWORD err;
  1245. const void *data;
  1246. size_t len;
  1247. int urgentflag;
  1248. if (s->sending_oob) {
  1249. urgentflag = MSG_OOB;
  1250. len = s->sending_oob;
  1251. data = &s->oobdata;
  1252. } else {
  1253. urgentflag = 0;
  1254. ptrlen bufdata = bufchain_prefix(&s->output_data);
  1255. data = bufdata.ptr;
  1256. len = bufdata.len;
  1257. }
  1258. len = min(len, INT_MAX); /* WinSock send() takes an int */
  1259. nsent = p_send(s->s, data, len, urgentflag);
  1260. noise_ultralight(NOISE_SOURCE_IOLEN, nsent);
  1261. if (nsent <= 0) {
  1262. err = (nsent < 0 ? p_WSAGetLastError() : 0);
  1263. if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
  1264. /*
  1265. * Perfectly normal: we've sent all we can for the moment.
  1266. *
  1267. * (Some WinSock send() implementations can return
  1268. * <0 but leave no sensible error indication -
  1269. * WSAGetLastError() is called but returns zero or
  1270. * a small number - so we check that case and treat
  1271. * it just like WSAEWOULDBLOCK.)
  1272. */
  1273. s->writable = false;
  1274. return;
  1275. } else {
  1276. /*
  1277. * If send() returns a socket error, we unfortunately
  1278. * can't just call plug_closing(), because it's quite
  1279. * likely that we're currently _in_ a call from the
  1280. * code we'd be calling back to, so we'd have to make
  1281. * half the SSH code reentrant. Instead we flag a
  1282. * pending error on the socket, to be dealt with (by
  1283. * calling plug_closing()) at some suitable future
  1284. * moment.
  1285. */
  1286. s->pending_error = err;
  1287. queue_toplevel_callback(socket_error_callback, s);
  1288. return;
  1289. }
  1290. } else {
  1291. if (s->sending_oob) {
  1292. if (nsent < len) {
  1293. memmove(s->oobdata, s->oobdata+nsent, len-nsent);
  1294. s->sending_oob = len - nsent;
  1295. } else {
  1296. s->sending_oob = 0;
  1297. }
  1298. } else {
  1299. bufchain_consume(&s->output_data, nsent);
  1300. }
  1301. }
  1302. }
  1303. /*
  1304. * If we reach here, we've finished sending everything we might
  1305. * have needed to send. Send EOF, if we need to.
  1306. */
  1307. if (s->outgoingeof == EOF_PENDING) {
  1308. p_shutdown(s->s, SD_SEND);
  1309. s->outgoingeof = EOF_SENT;
  1310. }
  1311. }
  1312. static size_t sk_net_write(Socket *sock, const void *buf, size_t len)
  1313. {
  1314. NetSocket *s = container_of(sock, NetSocket, sock);
  1315. assert(s->outgoingeof == EOF_NO);
  1316. /*
  1317. * Add the data to the buffer list on the socket.
  1318. */
  1319. bufchain_add(&s->output_data, buf, len);
  1320. /*
  1321. * Now try sending from the start of the buffer list.
  1322. */
  1323. if (s->writable)
  1324. try_send(s);
  1325. return bufchain_size(&s->output_data);
  1326. }
  1327. static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len)
  1328. {
  1329. NetSocket *s = container_of(sock, NetSocket, sock);
  1330. assert(s->outgoingeof == EOF_NO);
  1331. /*
  1332. * Replace the buffer list on the socket with the data.
  1333. */
  1334. bufchain_clear(&s->output_data);
  1335. assert(len <= sizeof(s->oobdata));
  1336. memcpy(s->oobdata, buf, len);
  1337. s->sending_oob = len;
  1338. /*
  1339. * Now try sending from the start of the buffer list.
  1340. */
  1341. if (s->writable)
  1342. try_send(s);
  1343. return s->sending_oob;
  1344. }
  1345. static void sk_net_write_eof(Socket *sock)
  1346. {
  1347. NetSocket *s = container_of(sock, NetSocket, sock);
  1348. assert(s->outgoingeof == EOF_NO);
  1349. /*
  1350. * Mark the socket as pending outgoing EOF.
  1351. */
  1352. s->outgoingeof = EOF_PENDING;
  1353. /*
  1354. * Now try sending from the start of the buffer list.
  1355. */
  1356. if (s->writable)
  1357. try_send(s);
  1358. }
  1359. void select_result(WPARAM wParam, LPARAM lParam)
  1360. {
  1361. int ret;
  1362. DWORD err;
  1363. char buf[20480]; /* nice big buffer for plenty of speed */
  1364. NetSocket *s;
  1365. bool atmark;
  1366. /* wParam is the socket itself */
  1367. if (wParam == 0)
  1368. return; /* boggle */
  1369. s = find234(sktree, (void *) wParam, cmpforsearch);
  1370. if (!s)
  1371. return; /* boggle */
  1372. if ((err = WSAGETSELECTERROR(lParam)) != 0) {
  1373. /*
  1374. * An error has occurred on this socket. Pass it to the
  1375. * plug.
  1376. */
  1377. if (s->addr) {
  1378. SockAddr thisaddr = sk_extractaddr_tmp(
  1379. s->addr, &s->step);
  1380. plug_log(s->plug, 1, &thisaddr, s->port,
  1381. winsock_error_string(err), err);
  1382. while (err && s->addr && sk_nextaddr(s->addr, &s->step)) {
  1383. err = try_connect(s);
  1384. }
  1385. }
  1386. if (err != 0)
  1387. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1388. return;
  1389. }
  1390. noise_ultralight(NOISE_SOURCE_IOID, wParam);
  1391. switch (WSAGETSELECTEVENT(lParam)) {
  1392. case FD_CONNECT:
  1393. s->connected = true;
  1394. s->writable = true;
  1395. /*
  1396. * Once a socket is connected, we can stop falling
  1397. * back through the candidate addresses to connect
  1398. * to.
  1399. */
  1400. if (s->addr) {
  1401. sk_addr_free(s->addr);
  1402. s->addr = NULL;
  1403. }
  1404. break;
  1405. case FD_READ:
  1406. /* In the case the socket is still frozen, we don't even bother */
  1407. if (s->frozen) {
  1408. s->frozen_readable = true;
  1409. break;
  1410. }
  1411. /*
  1412. * We have received data on the socket. For an oobinline
  1413. * socket, this might be data _before_ an urgent pointer,
  1414. * in which case we send it to the back end with type==1
  1415. * (data prior to urgent).
  1416. */
  1417. if (s->oobinline) {
  1418. u_long atmark_from_ioctl = 1;
  1419. p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl);
  1420. /*
  1421. * Avoid checking the return value from ioctlsocket(),
  1422. * on the grounds that some WinSock wrappers don't
  1423. * support it. If it does nothing, we get atmark==1,
  1424. * which is equivalent to `no OOB pending', so the
  1425. * effect will be to non-OOB-ify any OOB data.
  1426. */
  1427. atmark = atmark_from_ioctl;
  1428. } else
  1429. atmark = true;
  1430. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1431. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1432. if (ret < 0) {
  1433. err = p_WSAGetLastError();
  1434. if (err == WSAEWOULDBLOCK) {
  1435. break;
  1436. }
  1437. }
  1438. if (ret < 0) {
  1439. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1440. } else if (0 == ret) {
  1441. plug_closing(s->plug, NULL, 0, 0);
  1442. } else {
  1443. plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
  1444. }
  1445. break;
  1446. case FD_OOB:
  1447. /*
  1448. * This will only happen on a non-oobinline socket. It
  1449. * indicates that we can immediately perform an OOB read
  1450. * and get back OOB data, which we will send to the back
  1451. * end with type==2 (urgent data).
  1452. */
  1453. ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
  1454. noise_ultralight(NOISE_SOURCE_IOLEN, ret);
  1455. if (ret <= 0) {
  1456. int err = p_WSAGetLastError();
  1457. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1458. } else {
  1459. plug_receive(s->plug, 2, buf, ret);
  1460. }
  1461. break;
  1462. case FD_WRITE:
  1463. {
  1464. int bufsize_before, bufsize_after;
  1465. s->writable = true;
  1466. bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
  1467. try_send(s);
  1468. bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
  1469. if (bufsize_after < bufsize_before)
  1470. plug_sent(s->plug, bufsize_after);
  1471. }
  1472. break;
  1473. case FD_CLOSE:
  1474. /* Signal a close on the socket. First read any outstanding data. */
  1475. do {
  1476. ret = p_recv(s->s, buf, sizeof(buf), 0);
  1477. if (ret < 0) {
  1478. err = p_WSAGetLastError();
  1479. if (err == WSAEWOULDBLOCK)
  1480. break;
  1481. plug_closing(s->plug, winsock_error_string(err), err, 0);
  1482. } else {
  1483. if (ret)
  1484. plug_receive(s->plug, 0, buf, ret);
  1485. else
  1486. plug_closing(s->plug, NULL, 0, 0);
  1487. }
  1488. } while (ret > 0);
  1489. return;
  1490. case FD_ACCEPT:
  1491. {
  1492. #ifdef NO_IPV6
  1493. struct sockaddr_in isa;
  1494. #else
  1495. struct sockaddr_storage isa;
  1496. #endif
  1497. int addrlen = sizeof(isa);
  1498. SOCKET t; /* socket of connection */
  1499. accept_ctx_t actx;
  1500. memset(&isa, 0, sizeof(isa));
  1501. err = 0;
  1502. t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
  1503. if (t == INVALID_SOCKET)
  1504. {
  1505. err = p_WSAGetLastError();
  1506. if (err == WSATRY_AGAIN)
  1507. break;
  1508. }
  1509. actx.p = (void *)t;
  1510. #ifndef NO_IPV6
  1511. if (isa.ss_family == AF_INET &&
  1512. s->localhost_only &&
  1513. !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr))
  1514. #else
  1515. if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr))
  1516. #endif
  1517. {
  1518. p_closesocket(t); /* dodgy WinSock let nonlocal through */
  1519. } else if (plug_accepting(s->plug, sk_net_accept, actx)) {
  1520. p_closesocket(t); /* denied or error */
  1521. }
  1522. }
  1523. }
  1524. }
  1525. /*
  1526. * Special error values are returned from sk_namelookup and sk_new
  1527. * if there's a problem. These functions extract an error message,
  1528. * or return NULL if there's no problem.
  1529. */
  1530. const char *sk_addr_error(SockAddr *addr)
  1531. {
  1532. return addr->error;
  1533. }
  1534. static const char *sk_net_socket_error(Socket *sock)
  1535. {
  1536. NetSocket *s = container_of(sock, NetSocket, sock);
  1537. return s->error;
  1538. }
  1539. static SocketPeerInfo *sk_net_peer_info(Socket *sock)
  1540. {
  1541. NetSocket *s = container_of(sock, NetSocket, sock);
  1542. #ifdef NO_IPV6
  1543. struct sockaddr_in addr;
  1544. #else
  1545. struct sockaddr_storage addr;
  1546. char buf[INET6_ADDRSTRLEN];
  1547. #endif
  1548. int addrlen = sizeof(addr);
  1549. SocketPeerInfo *pi;
  1550. if (p_getpeername(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
  1551. return NULL;
  1552. pi = snew(SocketPeerInfo);
  1553. pi->addressfamily = ADDRTYPE_UNSPEC;
  1554. pi->addr_text = NULL;
  1555. pi->port = -1;
  1556. pi->log_text = NULL;
  1557. if (((struct sockaddr *)&addr)->sa_family == AF_INET) {
  1558. pi->addressfamily = ADDRTYPE_IPV4;
  1559. memcpy(pi->addr_bin.ipv4, &((struct sockaddr_in *)&addr)->sin_addr, 4);
  1560. pi->port = p_ntohs(((struct sockaddr_in *)&addr)->sin_port);
  1561. pi->addr_text = dupstr(
  1562. p_inet_ntoa(((struct sockaddr_in *)&addr)->sin_addr));
  1563. pi->log_text = dupprintf("%s:%d", pi->addr_text, pi->port);
  1564. #ifndef NO_IPV6
  1565. } else if (((struct sockaddr *)&addr)->sa_family == AF_INET6) {
  1566. pi->addressfamily = ADDRTYPE_IPV6;
  1567. memcpy(pi->addr_bin.ipv6,
  1568. &((struct sockaddr_in6 *)&addr)->sin6_addr, 16);
  1569. pi->port = p_ntohs(((struct sockaddr_in6 *)&addr)->sin6_port);
  1570. pi->addr_text = dupstr(
  1571. p_inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr,
  1572. buf, sizeof(buf)));
  1573. pi->log_text = dupprintf("[%s]:%d", pi->addr_text, pi->port);
  1574. #endif
  1575. } else {
  1576. sfree(pi);
  1577. return NULL;
  1578. }
  1579. return pi;
  1580. }
  1581. static void sk_net_set_frozen(Socket *sock, bool is_frozen)
  1582. {
  1583. NetSocket *s = container_of(sock, NetSocket, sock);
  1584. if (s->frozen == is_frozen)
  1585. return;
  1586. s->frozen = is_frozen;
  1587. if (!is_frozen) {
  1588. do_select(s->s, true);
  1589. if (s->frozen_readable) {
  1590. char c;
  1591. p_recv(s->s, &c, 1, MSG_PEEK);
  1592. }
  1593. }
  1594. s->frozen_readable = false;
  1595. }
  1596. void socket_reselect_all(void)
  1597. {
  1598. NetSocket *s;
  1599. int i;
  1600. for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
  1601. if (!s->frozen)
  1602. do_select(s->s, true);
  1603. }
  1604. }
  1605. /*
  1606. * For Plink: enumerate all sockets currently active.
  1607. */
  1608. SOCKET first_socket(int *state)
  1609. {
  1610. NetSocket *s;
  1611. *state = 0;
  1612. s = index234(sktree, (*state)++);
  1613. return s ? s->s : INVALID_SOCKET;
  1614. }
  1615. SOCKET next_socket(int *state)
  1616. {
  1617. NetSocket *s = index234(sktree, (*state)++);
  1618. return s ? s->s : INVALID_SOCKET;
  1619. }
  1620. bool socket_writable(SOCKET skt)
  1621. {
  1622. NetSocket *s = find234(sktree, (void *)skt, cmpforsearch);
  1623. if (s)
  1624. return bufchain_size(&s->output_data) > 0;
  1625. else
  1626. return false;
  1627. }
  1628. int net_service_lookup(char *service)
  1629. {
  1630. struct servent *se;
  1631. se = p_getservbyname(service, NULL);
  1632. if (se != NULL)
  1633. return p_ntohs(se->s_port);
  1634. else
  1635. return 0;
  1636. }
  1637. char *get_hostname(void)
  1638. {
  1639. char hostbuf[256]; /* MSDN docs for gethostname() promise this is enough */
  1640. if (p_gethostname(hostbuf, sizeof(hostbuf)) < 0)
  1641. return NULL;
  1642. return dupstr(hostbuf);
  1643. }
  1644. SockAddr *platform_get_x11_unix_address(const char *display, int displaynum,
  1645. char **canonicalname)
  1646. {
  1647. SockAddr *ret = snew(SockAddr);
  1648. memset(ret, 0, sizeof(SockAddr));
  1649. ret->error = "unix sockets not supported on this platform";
  1650. ret->refcount = 1;
  1651. return ret;
  1652. }