winnet.c 54 KB

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