Fix a bug which was causing occasional failed-host-key-check
[u/mdw/putty] / winnet.c
CommitLineData
2f75bae1 1/*
2 * Windows networking abstraction.
3 */
4
5#include <windows.h>
6#include <winsock.h>
7#include <stdio.h>
8
9#include "putty.h"
10#include "network.h"
11#include "tree234.h"
12
13#define BUFFER_GRANULE 512
14
15struct Socket_tag {
16 char *error;
17 SOCKET s;
18 sk_receiver_t receiver;
19 void *private_ptr;
20 struct buffer *head, *tail;
21 int writable;
22 int in_oob, sending_oob;
23};
24
25struct SockAddr_tag {
26 char *error;
27 unsigned long address;
28};
29
30struct buffer {
31 struct buffer *next;
32 int buflen, bufpos;
33 char buf[BUFFER_GRANULE];
34};
35
36static tree234 *sktree;
37
38static int cmpfortree(void *av, void *bv) {
39 Socket a = (Socket)av, b = (Socket)bv;
40 unsigned long as = (unsigned long)a->s, bs = (unsigned long)b->s;
41 if (as < bs) return -1;
42 if (as > bs) return +1;
43 return 0;
44}
45
46static int cmpforsearch(void *av, void *bv) {
47 Socket b = (Socket)bv;
48 unsigned long as = (unsigned long)av, bs = (unsigned long)b->s;
49 if (as < bs) return -1;
50 if (as > bs) return +1;
51 return 0;
52}
53
54void sk_init(void) {
55 sktree = newtree234(cmpfortree);
56}
57
58SockAddr sk_namelookup(char *host, char **canonicalname) {
59 SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
60 unsigned long a;
61 struct hostent *h;
62
63 if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
64 if ( (h = gethostbyname(host)) == NULL) {
65 DWORD err = WSAGetLastError();
66 ret->error = (err == WSAENETDOWN ? "Network is down" :
67 err == WSAHOST_NOT_FOUND ? "Host does not exist" :
68 err == WSATRY_AGAIN ? "Host not found" :
69 "gethostbyname: unknown error");
70 } else {
71 ret->error = NULL;
72 memcpy (&a, h->h_addr, sizeof(a));
73 *canonicalname = h->h_name;
74 }
75 } else {
76 *canonicalname = host;
77 }
78 ret->address = ntohl(a);
79
80 return ret;
81}
82
83void sk_addr_free(SockAddr addr) {
84 sfree(addr);
85}
86
87Socket sk_new(SockAddr addr, int port, sk_receiver_t receiver) {
88 SOCKET s;
89 SOCKADDR_IN a;
90 DWORD err;
91 char *errstr;
92 Socket ret;
93 extern char *do_select(SOCKET skt, int startup);
94
95 /*
96 * Create Socket structure.
97 */
98 ret = smalloc(sizeof(struct Socket_tag));
99 ret->error = NULL;
100 ret->receiver = receiver;
101 ret->head = ret->tail = NULL;
102 ret->writable = 1; /* to start with */
103 ret->in_oob = FALSE;
33232c8f 104 ret->sending_oob = 0;
2f75bae1 105
106 /*
107 * Open socket.
108 */
109 s = socket(AF_INET, SOCK_STREAM, 0);
110 ret->s = s;
111
112 if (s == INVALID_SOCKET) {
113 err = WSAGetLastError();
114 ret->error = (err == WSAENETDOWN ? "Network is down" :
115 err == WSAEAFNOSUPPORT ? "TCP/IP support not present" :
116 "socket(): unknown error");
117 return ret;
118 }
119
120 /*
121 * Bind to local address.
122 */
123 a.sin_family = AF_INET;
124 a.sin_addr.s_addr = htonl(INADDR_ANY);
125 a.sin_port = htons(0);
126 if (bind (s, (struct sockaddr *)&a, sizeof(a)) == SOCKET_ERROR) {
127 err = WSAGetLastError();
128 ret->error = (err == WSAENETDOWN ? "Network is down" :
129 "bind(): unknown error");
130 return ret;
131 }
132
133 /*
134 * Connect to remote address.
135 */
136 a.sin_addr.s_addr = htonl(addr->address);
137 a.sin_port = htons((short)port);
138 if (connect (s, (struct sockaddr *)&a, sizeof(a)) == SOCKET_ERROR) {
139 err = WSAGetLastError();
140 ret->error = (err == WSAENETDOWN ? "Network is down" :
141 err == WSAECONNREFUSED ? "Connection refused" :
142 err == WSAENETUNREACH ? "Network is unreachable" :
143 err == WSAEHOSTUNREACH ? "No route to host" :
144 "connect(): unknown error");
145 return ret;
146 }
147
148 /* Set up a select mechanism. This could be an AsyncSelect on a
149 * window, or an EventSelect on an event object. */
150 errstr = do_select(s, 1);
151 if (errstr) {
152 ret->error = errstr;
153 return ret;
154 }
155
156 add234(sktree, ret);
157
158 return ret;
159}
160
161void sk_close(Socket s) {
162 del234(sktree, s);
163 do_select(s->s, 0);
164 closesocket(s->s);
165 free(s);
166}
167
168char *winsock_error_string(int error) {
169 switch (error) {
170 case WSAEACCES: return "Network error: Permission denied";
171 case WSAEADDRINUSE: return "Network error: Address already in use";
172 case WSAEADDRNOTAVAIL: return "Network error: Cannot assign requested address";
173 case WSAEAFNOSUPPORT: return "Network error: Address family not supported by protocol family";
174 case WSAEALREADY: return "Network error: Operation already in progress";
175 case WSAECONNABORTED: return "Network error: Software caused connection abort";
176 case WSAECONNREFUSED: return "Network error: Connection refused";
177 case WSAECONNRESET: return "Network error: Connection reset by peer";
178 case WSAEDESTADDRREQ: return "Network error: Destination address required";
179 case WSAEFAULT: return "Network error: Bad address";
180 case WSAEHOSTDOWN: return "Network error: Host is down";
181 case WSAEHOSTUNREACH: return "Network error: No route to host";
182 case WSAEINPROGRESS: return "Network error: Operation now in progress";
183 case WSAEINTR: return "Network error: Interrupted function call";
184 case WSAEINVAL: return "Network error: Invalid argument";
185 case WSAEISCONN: return "Network error: Socket is already connected";
186 case WSAEMFILE: return "Network error: Too many open files";
187 case WSAEMSGSIZE: return "Network error: Message too long";
188 case WSAENETDOWN: return "Network error: Network is down";
189 case WSAENETRESET: return "Network error: Network dropped connection on reset";
190 case WSAENETUNREACH: return "Network error: Network is unreachable";
191 case WSAENOBUFS: return "Network error: No buffer space available";
192 case WSAENOPROTOOPT: return "Network error: Bad protocol option";
193 case WSAENOTCONN: return "Network error: Socket is not connected";
194 case WSAENOTSOCK: return "Network error: Socket operation on non-socket";
195 case WSAEOPNOTSUPP: return "Network error: Operation not supported";
196 case WSAEPFNOSUPPORT: return "Network error: Protocol family not supported";
197 case WSAEPROCLIM: return "Network error: Too many processes";
198 case WSAEPROTONOSUPPORT: return "Network error: Protocol not supported";
199 case WSAEPROTOTYPE: return "Network error: Protocol wrong type for socket";
200 case WSAESHUTDOWN: return "Network error: Cannot send after socket shutdown";
201 case WSAESOCKTNOSUPPORT: return "Network error: Socket type not supported";
202 case WSAETIMEDOUT: return "Network error: Connection timed out";
203 case WSAEWOULDBLOCK: return "Network error: Resource temporarily unavailable";
204 case WSAEDISCON: return "Network error: Graceful shutdown in progress";
205 default: return "Unknown network error";
206 }
207}
208
209/*
210 * The function which tries to send on a socket once it's deemed
211 * writable.
212 */
213void try_send(Socket s) {
214 while (s->head) {
215 int nsent;
216 DWORD err;
217 int len, urgentflag;
218
219 if (s->sending_oob) {
220 urgentflag = MSG_OOB;
221 len = s->sending_oob;
222 } else {
223 urgentflag = 0;
224 len = s->head->buflen - s->head->bufpos;
225 }
226
227 nsent = send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
228 if (nsent <= 0) {
229 err = (nsent < 0 ? WSAGetLastError() : 0);
230 if (err == WSAEWOULDBLOCK) {
231 /* Perfectly normal: we've sent all we can for the moment. */
232 s->writable = FALSE;
233 return;
234 } else if (nsent == 0 ||
235 err == WSAECONNABORTED ||
236 err == WSAECONNRESET) {
237 /*
238 * FIXME. This will have to be done better when we
239 * start managing multiple sockets (e.g. SSH port
240 * forwarding), because if we get CONNRESET while
241 * trying to write a particular forwarded socket
242 * then it isn't necessarily the end of the world.
243 * Ideally I'd like to pass the error code back to
244 * somewhere the next select_result() will see it,
245 * but that might be hard. Perhaps I should pass it
246 * back to be queued in the Windows front end bit.
247 */
248 fatalbox(winsock_error_string(err));
249 } else {
250 fatalbox(winsock_error_string(err));
251 }
252 } else {
253 s->head->bufpos += nsent;
254 if (s->sending_oob)
255 s->sending_oob -= nsent;
256 if (s->head->bufpos >= s->head->buflen) {
257 struct buffer *tmp = s->head;
258 s->head = tmp->next;
259 free(tmp);
260 if (!s->head)
261 s->tail = NULL;
262 }
263 }
264 }
265}
266
267void sk_write(Socket s, char *buf, int len) {
268 /*
269 * Add the data to the buffer list on the socket.
270 */
271 if (s->tail && s->tail->buflen < BUFFER_GRANULE) {
272 int copylen = min(len, BUFFER_GRANULE - s->tail->buflen);
273 memcpy(s->tail->buf + s->tail->buflen, buf, copylen);
274 buf += copylen;
275 len -= copylen;
276 s->tail->buflen += copylen;
277 }
278 while (len > 0) {
279 int grainlen = min(len, BUFFER_GRANULE);
280 struct buffer *newbuf;
281 newbuf = smalloc(sizeof(struct buffer));
282 newbuf->bufpos = 0;
283 newbuf->buflen = grainlen;
284 memcpy(newbuf->buf, buf, grainlen);
285 buf += grainlen;
286 len -= grainlen;
287 if (s->tail)
288 s->tail->next = newbuf;
289 else
290 s->head = s->tail = newbuf;
291 newbuf->next = NULL;
292 s->tail = newbuf;
293 }
294
295 /*
296 * Now try sending from the start of the buffer list.
297 */
298 if (s->writable)
299 try_send(s);
300}
301
302void sk_write_oob(Socket s, char *buf, int len) {
303 /*
304 * Replace the buffer list on the socket with the data.
305 */
306 if (!s->head) {
307 s->head = smalloc(sizeof(struct buffer));
308 } else {
309 struct buffer *walk = s->head->next;
310 while (walk) {
311 struct buffer *tmp = walk;
312 walk = tmp->next;
313 free(tmp);
314 }
315 }
316 s->head->next = NULL;
317 s->tail = s->head;
318 s->head->buflen = len;
319 memcpy(s->head->buf, buf, len);
320
321 /*
322 * Set the Urgent marker.
323 */
324 s->sending_oob = len;
325
326 /*
327 * Now try sending from the start of the buffer list.
328 */
329 if (s->writable)
330 try_send(s);
331}
332
333int select_result(WPARAM wParam, LPARAM lParam) {
334 int ret;
335 DWORD err;
336 char buf[BUFFER_GRANULE];
337 Socket s;
338 int atmark;
339
340 /* wParam is the socket itself */
341 s = find234(sktree, (void *)wParam, cmpforsearch);
342 if (!s)
343 return 1; /* boggle */
344
345 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
346 fatalbox(winsock_error_string(err));
347 }
348
349 switch (WSAGETSELECTEVENT(lParam)) {
350 case FD_READ:
351 ret = recv(s->s, buf, sizeof(buf), 0);
352 if (ret < 0) {
353 err = WSAGetLastError();
354 if (err == WSAEWOULDBLOCK) {
355 break;
356 }
357 }
358 if (ret < 0) {
359 fatalbox(winsock_error_string(err));
360 } else {
361 int type = s->in_oob ? 2 : 0;
362 s->in_oob = FALSE;
363 return s->receiver(s, type, buf, ret);
364 }
365 break;
366 case FD_OOB:
367 /*
368 * Read all data up to the OOB marker, and send it to the
369 * receiver with urgent==1 (OOB pending).
370 */
371 atmark = 1;
372 s->in_oob = TRUE;
373 /* Some WinSock wrappers don't support this call, so we
374 * deliberately don't check the return value. If the call
375 * fails and does nothing, we will get back atmark==1,
376 * which is good enough to keep going at least. */
377 ioctlsocket(s->s, SIOCATMARK, &atmark);
378 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
379 if (ret <= 0) {
380 fatalbox(ret == 0 ? "Internal networking trouble" :
381 winsock_error_string(WSAGetLastError()));
382 } else {
383 return s->receiver(s, atmark ? 2 : 1, buf, ret);
384 }
385 break;
386 case FD_WRITE:
387 s->writable = 1;
388 try_send(s);
389 break;
390 case FD_CLOSE:
391 /* Signal a close on the socket. */
392 return s->receiver(s, 0, NULL, 0);
393 break;
394 }
395
396 return 1;
397}
398
399/*
400 * Each socket abstraction contains a `void *' private field in
401 * which the client can keep state.
402 */
403void sk_set_private_ptr(Socket s, void *ptr) {
404 s->private_ptr = ptr;
405}
406void *sk_get_private_ptr(Socket s) {
407 return s->private_ptr;
408}
409
410/*
411 * Special error values are returned from sk_namelookup and sk_new
412 * if there's a problem. These functions extract an error message,
413 * or return NULL if there's no problem.
414 */
415char *sk_addr_error(SockAddr addr) {
416 return addr->error;
417}
418char *sk_socket_error(Socket s) {
419 return s->error;
420}
421
422/*
423 * For Plink: enumerate all sockets currently active.
424 */
425SOCKET first_socket(enum234 *e) {
426 Socket s = first234(sktree, e);
427 return s ? s->s : INVALID_SOCKET;
428}
429SOCKET next_socket(enum234 *e) {
430 Socket s = next234(e);
431 return s ? s->s : INVALID_SOCKET;
432}