PageRenderTime 30ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/windows/winnet.c

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