]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Add TIS authentication option
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <winsock.h>
4
5 #include "putty.h"
6
7 #ifndef FALSE
8 #define FALSE 0
9 #endif
10 #ifndef TRUE
11 #define TRUE 1
12 #endif
13
14 #include "ssh.h"
15
16 #define SSH_MSG_DISCONNECT 1
17 #define SSH_SMSG_PUBLIC_KEY 2
18 #define SSH_CMSG_SESSION_KEY 3
19 #define SSH_CMSG_USER 4
20 #define SSH_CMSG_AUTH_PASSWORD 9
21 #define SSH_CMSG_REQUEST_PTY 10
22 #define SSH_CMSG_EXEC_SHELL 12
23 #define SSH_CMSG_STDIN_DATA 16
24 #define SSH_SMSG_STDOUT_DATA 17
25 #define SSH_SMSG_STDERR_DATA 18
26 #define SSH_SMSG_SUCCESS 14
27 #define SSH_SMSG_FAILURE 15
28 #define SSH_SMSG_EXITSTATUS 20
29 #define SSH_MSG_IGNORE 32
30 #define SSH_CMSG_EXIT_CONFIRMATION 33
31 #define SSH_MSG_DEBUG 36
32 #define SSH_CMSG_AUTH_TIS 39
33 #define SSH_SMSG_AUTH_TIS_CHALLENGE 40
34 #define SSH_CMSG_AUTH_TIS_RESPONSE 41
35
36 #define SSH_AUTH_TIS              5
37
38 /* Coroutine mechanics for the sillier bits of the code */
39 #define crBegin1        static int crLine = 0;
40 #define crBegin2        switch(crLine) { case 0:;
41 #define crBegin         crBegin1; crBegin2;
42 #define crFinish(z)     } crLine = 0; return (z)
43 #define crFinishV       } crLine = 0; return
44 #define crReturn(z)     \
45         do {\
46             crLine=__LINE__; return (z); case __LINE__:;\
47         } while (0)
48 #define crReturnV       \
49         do {\
50             crLine=__LINE__; return; case __LINE__:;\
51         } while (0)
52 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
53 #define crStopV         do{ crLine = 0; return; }while(0)
54
55 #ifndef FALSE
56 #define FALSE 0
57 #endif
58 #ifndef TRUE
59 #define TRUE 1
60 #endif
61
62 static SOCKET s = INVALID_SOCKET;
63
64 static unsigned char session_key[32];
65 static struct ssh_cipher *cipher = NULL;
66
67 static char *savedhost;
68
69 static enum {
70     SSH_STATE_BEFORE_SIZE,
71     SSH_STATE_INTERMED,
72     SSH_STATE_SESSION,
73     SSH_STATE_CLOSED
74 } ssh_state = SSH_STATE_BEFORE_SIZE;
75
76 static int size_needed = FALSE;
77
78 static void s_write (char *buf, int len) {
79     while (len > 0) {
80         int i = send (s, buf, len, 0);
81         if (i > 0)
82             len -= i, buf += i;
83     }
84 }
85
86 static int s_read (char *buf, int len) {
87     int ret = 0;
88     while (len > 0) {
89         int i = recv (s, buf, len, 0);
90         if (i > 0)
91             len -= i, buf += i, ret += i;
92         else
93             return i;
94     }
95     return ret;
96 }
97
98 static void c_write (char *buf, int len) {
99     while (len--) {
100         int new_head = (inbuf_head + 1) & INBUF_MASK;
101         if (new_head != inbuf_reap) {
102             inbuf[inbuf_head] = *buf++;
103             inbuf_head = new_head;
104         }
105     }
106 }
107
108 struct Packet {
109     long length;
110     int type;
111     unsigned long crc;
112     unsigned char *data;
113     unsigned char *body;
114     long maxlen;
115 };
116
117 static struct Packet pktin = { 0, 0, 0, NULL, 0 };
118 static struct Packet pktout = { 0, 0, 0, NULL, 0 };
119
120 static void ssh_protocol(unsigned char *in, int inlen, int ispkt);
121 static void ssh_size(void);
122
123 static void ssh_gotdata(unsigned char *data, int datalen) {
124     static long len, biglen, to_read;
125     static unsigned char *p;
126     static int i, pad;
127
128     crBegin;
129     while (1) {
130         for (i = len = 0; i < 4; i++) {
131             while (datalen == 0)
132                 crReturnV;
133             len = (len << 8) + *data;
134             data++, datalen--;
135         }
136
137 #ifdef FWHACK
138         if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
139             len = 0x300;               /* big enough to carry to end */
140         }
141 #endif
142
143         pad = 8 - (len%8);
144
145         biglen = len + pad;
146
147         len -= 5;                      /* type and CRC */
148
149         pktin.length = len;
150         if (pktin.maxlen < biglen) {
151             pktin.maxlen = biglen;
152             pktin.data = (pktin.data == NULL ? malloc(biglen) :
153                         realloc(pktin.data, biglen));
154             if (!pktin.data)
155                 fatalbox("Out of memory");
156         }
157
158         p = pktin.data, to_read = biglen;
159         while (to_read > 0) {
160             static int chunk;
161             chunk = to_read;
162             while (datalen == 0)
163                 crReturnV;
164             if (chunk > datalen)
165                 chunk = datalen;
166             memcpy(p, data, chunk);
167             data += chunk;
168             datalen -= chunk;
169             p += chunk;
170             to_read -= chunk;
171         }
172
173         if (cipher)
174             cipher->decrypt(pktin.data, biglen);
175
176         pktin.type = pktin.data[pad];
177         pktin.body = pktin.data+pad+1;
178
179         if (pktin.type == SSH_MSG_DEBUG) {
180             /* FIXME: log it */
181         } else if (pktin.type == SSH_MSG_IGNORE) {
182             /* do nothing */;
183         } else
184             ssh_protocol(NULL, 0, 1);
185     }
186     crFinishV;
187 }
188
189 static void s_wrpkt_start(int type, int len) {
190     int pad, biglen;
191
192     len += 5;                          /* type and CRC */
193     pad = 8 - (len%8);
194     biglen = len + pad;
195
196     pktout.length = len-5;
197     if (pktout.maxlen < biglen) {
198         pktout.maxlen = biglen;
199         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
200                        realloc(pktout.data, biglen+4));
201         if (!pktout.data)
202             fatalbox("Out of memory");
203     }
204
205     pktout.type = type;
206     pktout.body = pktout.data+4+pad+1;
207 }
208
209 static void s_wrpkt(void) {
210     int pad, len, biglen, i;
211     unsigned long crc;
212
213     len = pktout.length + 5;           /* type and CRC */
214     pad = 8 - (len%8);
215     biglen = len + pad;
216
217     pktout.body[-1] = pktout.type;
218     for (i=0; i<pad; i++)
219         pktout.data[i+4] = random_byte();
220     crc = crc32(pktout.data+4, biglen-4);
221
222     pktout.data[biglen+0] = (unsigned char) ((crc >> 24) & 0xFF);
223     pktout.data[biglen+1] = (unsigned char) ((crc >> 16) & 0xFF);
224     pktout.data[biglen+2] = (unsigned char) ((crc >> 8) & 0xFF);
225     pktout.data[biglen+3] = (unsigned char) (crc & 0xFF);
226
227     pktout.data[0] = (len >> 24) & 0xFF;
228     pktout.data[1] = (len >> 16) & 0xFF;
229     pktout.data[2] = (len >> 8) & 0xFF;
230     pktout.data[3] = len & 0xFF;
231
232     if (cipher)
233         cipher->encrypt(pktout.data+4, biglen);
234
235     s_write(pktout.data, biglen+4);
236 }
237
238 static int ssh_versioncmp(char *a, char *b) {
239     char *ae, *be;
240     unsigned long av, bv;
241
242     av = strtoul(a, &ae, 10);
243     bv = strtoul(b, &be, 10);
244     if (av != bv) return (av < bv ? -1 : +1);
245     if (*ae == '.') ae++;
246     if (*be == '.') be++;
247     av = strtoul(ae, &ae, 10);
248     bv = strtoul(be, &be, 10);
249     if (av != bv) return (av < bv ? -1 : +1);
250     return 0;
251 }
252
253 static int do_ssh_init(void) {
254     char c;
255     char version[10];
256     char vstring[40];
257     int i;
258
259 #ifdef FWHACK
260     i = 0;
261     while (s_read(&c, 1) == 1) {
262         if (c == 'S' && i < 2) i++;
263         else if (c == 'S' && i == 2) i = 2;
264         else if (c == 'H' && i == 2) break;
265         else i = 0;
266     }
267 #else
268     if (s_read(&c,1) != 1 || c != 'S') return 0;
269     if (s_read(&c,1) != 1 || c != 'S') return 0;
270     if (s_read(&c,1) != 1 || c != 'H') return 0;
271 #endif
272     if (s_read(&c,1) != 1 || c != '-') return 0;
273     i = 0;
274     while (1) {
275         if (s_read(&c,1) != 1)
276             return 0;
277         if (i >= 0) {
278             if (c == '-') {
279                 version[i] = '\0';
280                 i = -1;
281             } else if (i < sizeof(version)-1)
282                 version[i++] = c;
283         }
284         else if (c == '\n')
285             break;
286     }
287
288     sprintf(vstring, "SSH-%s-PuTTY\n",
289             (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
290     s_write(vstring, strlen(vstring));
291     return 1;
292 }
293
294 static void ssh_protocol(unsigned char *in, int inlen, int ispkt) {
295     int i, j, len;
296     unsigned char session_id[16];
297     unsigned char *rsabuf, *keystr1, *keystr2;
298     unsigned char cookie[8];
299     struct RSAKey servkey, hostkey;
300     struct MD5Context md5c;
301     static unsigned long supported_ciphers_mask, supported_auths_mask;
302     int cipher_type;
303
304     extern struct ssh_cipher ssh_3des;
305     extern struct ssh_cipher ssh_des;
306     extern struct ssh_cipher ssh_blowfish;
307
308     crBegin;
309
310     random_init();
311
312     while (!ispkt)
313         crReturnV;
314
315     if (pktin.type != SSH_SMSG_PUBLIC_KEY)
316         fatalbox("Public key packet not received");
317
318     memcpy(cookie, pktin.body, 8);
319
320     MD5Init(&md5c);
321
322     i = makekey(pktin.body+8, &servkey, &keystr1);
323
324     j = makekey(pktin.body+8+i, &hostkey, &keystr2);
325
326     supported_ciphers_mask = ((pktin.body[12+i+j] << 24) |
327                               (pktin.body[13+i+j] << 16) |
328                               (pktin.body[14+i+j] << 8) |
329                               (pktin.body[15+i+j]));
330
331     supported_auths_mask = ((pktin.body[16+i+j] << 24) |
332                             (pktin.body[17+i+j] << 16) |
333                             (pktin.body[18+i+j] << 8) |
334                             (pktin.body[19+i+j]));
335
336     MD5Update(&md5c, keystr2, hostkey.bytes);
337     MD5Update(&md5c, keystr1, servkey.bytes);
338     MD5Update(&md5c, pktin.body, 8);
339
340     MD5Final(session_id, &md5c);
341
342     for (i=0; i<32; i++)
343         session_key[i] = random_byte();
344
345     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
346
347     rsabuf = malloc(len);
348     if (!rsabuf)
349         fatalbox("Out of memory");
350
351     verify_ssh_host_key(savedhost, &hostkey);
352
353     for (i=0; i<32; i++) {
354         rsabuf[i] = session_key[i];
355         if (i < 16)
356             rsabuf[i] ^= session_id[i];
357     }
358
359     if (hostkey.bytes > servkey.bytes) {
360         rsaencrypt(rsabuf, 32, &servkey);
361         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
362     } else {
363         rsaencrypt(rsabuf, 32, &hostkey);
364         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
365     }
366
367     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
368                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
369                   SSH_CIPHER_3DES;
370     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
371         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
372         cipher_type = SSH_CIPHER_3DES;
373     }
374
375     s_wrpkt_start(SSH_CMSG_SESSION_KEY, len+15);
376     pktout.body[0] = cipher_type;
377     memcpy(pktout.body+1, cookie, 8);
378     pktout.body[9] = (len*8) >> 8;
379     pktout.body[10] = (len*8) & 0xFF;
380     memcpy(pktout.body+11, rsabuf, len);
381     pktout.body[len+11] = pktout.body[len+12] = 0;   /* protocol flags */
382     pktout.body[len+13] = pktout.body[len+14] = 0;
383     s_wrpkt();
384
385     free(rsabuf);
386
387     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish :
388              cipher_type == SSH_CIPHER_DES ? &ssh_des :
389              &ssh_3des;
390     cipher->sesskey(session_key);
391
392     do { crReturnV; } while (!ispkt);
393
394     if (pktin.type != SSH_SMSG_SUCCESS)
395         fatalbox("Encryption not successfully enabled");
396
397     fflush(stdout);
398     {
399         static char username[100];
400         static int pos = 0;
401         static char c;
402         if (!*cfg.username) {
403             c_write("login as: ", 10);
404             while (pos >= 0) {
405                 do { crReturnV; } while (ispkt);
406                 while (inlen--) switch (c = *in++) {
407                   case 10: case 13:
408                     username[pos] = 0;
409                     pos = -1;
410                     break;
411                   case 8: case 127:
412                     if (pos > 0) {
413                         c_write("\b \b", 3);
414                         pos--;
415                     }
416                     break;
417                   case 21: case 27:
418                     while (pos > 0) {
419                         c_write("\b \b", 3);
420                         pos--;
421                     }
422                     break;
423                   case 3: case 4:
424                     random_save_seed();
425                     exit(0);
426                     break;
427                   default:
428                     if (c >= ' ' && c <= '~' && pos < 40) {
429                         username[pos++] = c;
430                         c_write(&c, 1);
431                     }
432                     break;
433                 }
434             }
435             c_write("\r\n", 2);
436             username[strcspn(username, "\n\r")] = '\0';
437         } else {
438             char stuff[200];
439             strncpy(username, cfg.username, 99);
440             username[99] = '\0';
441             sprintf(stuff, "Sent username \"%s\".\r\n", username);
442             c_write(stuff, strlen(stuff));
443         }
444         s_wrpkt_start(SSH_CMSG_USER, 4+strlen(username));
445         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
446         pktout.body[3] = strlen(username);
447         memcpy(pktout.body+4, username, strlen(username));
448         s_wrpkt();
449     }
450
451     do { crReturnV; } while (!ispkt);
452
453     while (pktin.type == SSH_SMSG_FAILURE) {
454         static char password[100];
455         static int pos;
456         static char c;
457         static int pwpkt_type;
458
459         /*
460          * Show password prompt, having first obtained it via a TIS
461          * exchange if we're doing TIS authentication.
462          */
463         pwpkt_type = SSH_CMSG_AUTH_PASSWORD;
464         if (pktin.type == SSH_SMSG_FAILURE &&
465             cfg.try_tis_auth &&
466             (supported_auths_mask & (1<<SSH_AUTH_TIS))) {
467             pwpkt_type = SSH_CMSG_AUTH_TIS_RESPONSE;
468             s_wrpkt_start(SSH_CMSG_AUTH_TIS, 0);
469             s_wrpkt();
470             do { crReturnV; } while (!ispkt);
471             if (pktin.type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
472                 c_write("TIS authentication refused.\r\n", 29);
473             } else {
474                 int challengelen = ((pktin.body[0] << 24) |
475                                     (pktin.body[1] << 16) |
476                                     (pktin.body[2] << 8) |
477                                     (pktin.body[3]));
478                 c_write(pktin.body+4, challengelen);
479             }
480         }
481         if (pwpkt_type == SSH_CMSG_AUTH_PASSWORD)
482             c_write("password: ", 10);
483
484         pos = 0;
485         while (pos >= 0) {
486             do { crReturnV; } while (ispkt);
487             while (inlen--) switch (c = *in++) {
488               case 10: case 13:
489                 password[pos] = 0;
490                 pos = -1;
491                 break;
492               case 8: case 127:
493                 if (pos > 0)
494                     pos--;
495                 break;
496               case 21: case 27:
497                 pos = 0;
498                 break;
499               case 3: case 4:
500                 random_save_seed();
501                 exit(0);
502                 break;
503               default:
504                 if (c >= ' ' && c <= '~' && pos < 40)
505                     password[pos++] = c;
506                 break;
507             }
508         }
509         c_write("\r\n", 2);
510         s_wrpkt_start(pwpkt_type, 4+strlen(password));
511         pktout.body[0] = pktout.body[1] = pktout.body[2] = 0;
512         pktout.body[3] = strlen(password);
513         memcpy(pktout.body+4, password, strlen(password));
514         s_wrpkt();
515         memset(password, 0, strlen(password));
516         do { crReturnV; } while (!ispkt);
517         if (pktin.type == 15) {
518             c_write("Access denied\r\n", 15);
519         } else if (pktin.type != 14) {
520             fatalbox("Strange packet received, type %d", pktin.type);
521         }
522     }
523
524     if (!cfg.nopty) {
525         i = strlen(cfg.termtype);
526         s_wrpkt_start(SSH_CMSG_REQUEST_PTY, i+5*4+1);
527         pktout.body[0] = (i >> 24) & 0xFF;
528         pktout.body[1] = (i >> 16) & 0xFF;
529         pktout.body[2] = (i >> 8) & 0xFF;
530         pktout.body[3] = i & 0xFF;
531         memcpy(pktout.body+4, cfg.termtype, i);
532         i += 4;
533         pktout.body[i++] = (rows >> 24) & 0xFF;
534         pktout.body[i++] = (rows >> 16) & 0xFF;
535         pktout.body[i++] = (rows >> 8) & 0xFF;
536         pktout.body[i++] = rows & 0xFF;
537         pktout.body[i++] = (cols >> 24) & 0xFF;
538         pktout.body[i++] = (cols >> 16) & 0xFF;
539         pktout.body[i++] = (cols >> 8) & 0xFF;
540         pktout.body[i++] = cols & 0xFF;
541         memset(pktout.body+i, 0, 9);       /* 0 pixwidth, 0 pixheight, 0.b endofopt */
542         s_wrpkt();
543         ssh_state = SSH_STATE_INTERMED;
544         do { crReturnV; } while (!ispkt);
545         if (pktin.type != SSH_SMSG_SUCCESS && pktin.type != SSH_SMSG_FAILURE) {
546             fatalbox("Protocol confusion");
547         } else if (pktin.type == SSH_SMSG_FAILURE) {
548             c_write("Server refused to allocate pty\r\n", 32);
549         }
550     }
551
552     s_wrpkt_start(SSH_CMSG_EXEC_SHELL, 0);
553     s_wrpkt();
554
555     ssh_state = SSH_STATE_SESSION;
556     if (size_needed)
557         ssh_size();
558
559     while (1) {
560         crReturnV;
561         if (ispkt) {
562             if (pktin.type == SSH_SMSG_STDOUT_DATA ||
563                 pktin.type == SSH_SMSG_STDERR_DATA) {
564                 long len = 0;
565                 for (i = 0; i < 4; i++)
566                     len = (len << 8) + pktin.body[i];
567                 c_write(pktin.body+4, len);
568             } else if (pktin.type == SSH_MSG_DISCONNECT) {
569                 ssh_state = SSH_STATE_CLOSED;
570             } else if (pktin.type == SSH_SMSG_SUCCESS) {
571                 /* may be from EXEC_SHELL on some servers */
572             } else if (pktin.type == SSH_SMSG_FAILURE) {
573                 /* may be from EXEC_SHELL on some servers
574                  * if no pty is available or in other odd cases. Ignore */
575             } else if (pktin.type == SSH_SMSG_EXITSTATUS) {
576                 s_wrpkt_start(SSH_CMSG_EXIT_CONFIRMATION, 0);
577                 s_wrpkt();
578             } else {
579                 fatalbox("Strange packet received: type %d", pktin.type);
580             }
581         } else {
582             s_wrpkt_start(SSH_CMSG_STDIN_DATA, 4+inlen);
583             pktout.body[0] = (inlen >> 24) & 0xFF;
584             pktout.body[1] = (inlen >> 16) & 0xFF;
585             pktout.body[2] = (inlen >> 8) & 0xFF;
586             pktout.body[3] = inlen & 0xFF;
587             memcpy(pktout.body+4, in, inlen);
588             s_wrpkt();
589         }
590     }
591
592     crFinishV;
593 }
594
595 /*
596  * Called to set up the connection. Will arrange for WM_NETEVENT
597  * messages to be passed to the specified window, whose window
598  * procedure should then call telnet_msg().
599  *
600  * Returns an error message, or NULL on success.
601  *
602  * Also places the canonical host name into `realhost'.
603  */
604 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
605     SOCKADDR_IN addr;
606     struct hostent *h;
607     unsigned long a;
608 #ifdef FWHACK
609     char *FWhost;
610     int FWport;
611 #endif
612
613     savedhost = malloc(1+strlen(host));
614     if (!savedhost)
615         fatalbox("Out of memory");
616     strcpy(savedhost, host);
617
618 #ifdef FWHACK
619     FWhost = host;
620     FWport = port;
621     host = FWSTR;
622     port = 23;
623 #endif
624
625     /*
626      * Try to find host.
627      */
628     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
629         if ( (h = gethostbyname(host)) == NULL)
630             switch (WSAGetLastError()) {
631               case WSAENETDOWN: return "Network is down";
632               case WSAHOST_NOT_FOUND: case WSANO_DATA:
633                 return "Host does not exist";
634               case WSATRY_AGAIN: return "Host not found";
635               default: return "gethostbyname: unknown error";
636             }
637         memcpy (&a, h->h_addr, sizeof(a));
638         *realhost = h->h_name;
639     } else
640         *realhost = host;
641 #ifdef FWHACK
642     *realhost = FWhost;
643 #endif
644     a = ntohl(a);
645
646     if (port < 0)
647         port = 22;                     /* default ssh port */
648
649     /*
650      * Open socket.
651      */
652     s = socket(AF_INET, SOCK_STREAM, 0);
653     if (s == INVALID_SOCKET)
654         switch (WSAGetLastError()) {
655           case WSAENETDOWN: return "Network is down";
656           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
657           default: return "socket(): unknown error";
658         }
659
660     /*
661      * Bind to local address.
662      */
663     addr.sin_family = AF_INET;
664     addr.sin_addr.s_addr = htonl(INADDR_ANY);
665     addr.sin_port = htons(0);
666     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
667         switch (WSAGetLastError()) {
668           case WSAENETDOWN: return "Network is down";
669           default: return "bind(): unknown error";
670         }
671
672     /*
673      * Connect to remote address.
674      */
675     addr.sin_addr.s_addr = htonl(a);
676     addr.sin_port = htons((short)port);
677     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
678         switch (WSAGetLastError()) {
679           case WSAENETDOWN: return "Network is down";
680           case WSAECONNREFUSED: return "Connection refused";
681           case WSAENETUNREACH: return "Network is unreachable";
682           case WSAEHOSTUNREACH: return "No route to host";
683           default: return "connect(): unknown error";
684         }
685
686 #ifdef FWHACK
687     send(s, "connect ", 8, 0);
688     send(s, FWhost, strlen(FWhost), 0);
689     {
690         char buf[20];
691         sprintf(buf, " %d\n", FWport);
692         send (s, buf, strlen(buf), 0);
693     }
694 #endif
695
696     if (!do_ssh_init())
697         return "Protocol initialisation error";
698
699     if (WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
700         switch (WSAGetLastError()) {
701           case WSAENETDOWN: return "Network is down";
702           default: return "WSAAsyncSelect(): unknown error";
703         }
704
705     return NULL;
706 }
707
708 /*
709  * Process a WM_NETEVENT message. Will return 0 if the connection
710  * has closed, or <0 for a socket error.
711  */
712 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
713     int ret;
714     char buf[256];
715
716     if (s == INVALID_SOCKET)           /* how the hell did we get here?! */
717         return -5000;
718
719     if (WSAGETSELECTERROR(lParam) != 0)
720         return -WSAGETSELECTERROR(lParam);
721
722     switch (WSAGETSELECTEVENT(lParam)) {
723       case FD_READ:
724         ret = recv(s, buf, sizeof(buf), 0);
725         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
726             return 1;
727         if (ret < 0)                   /* any _other_ error */
728             return -10000-WSAGetLastError();
729         if (ret == 0) {
730             s = INVALID_SOCKET;
731             return 0;                  /* can't happen, in theory */
732         }
733         ssh_gotdata (buf, ret);
734         return 1;
735       case FD_CLOSE:
736         s = INVALID_SOCKET;
737         ssh_state = SSH_STATE_CLOSED;
738         return 0;
739     }
740     return 1;                          /* shouldn't happen, but WTF */
741 }
742
743 /*
744  * Called to send data down the Telnet connection.
745  */
746 static void ssh_send (char *buf, int len) {
747     if (s == INVALID_SOCKET)
748         return;
749
750     ssh_protocol(buf, len, 0);
751 }
752
753 /*
754  * Called to set the size of the window from Telnet's POV.
755  */
756 static void ssh_size(void) {
757     switch (ssh_state) {
758       case SSH_STATE_BEFORE_SIZE:
759       case SSH_STATE_CLOSED:
760         break;                         /* do nothing */
761       case SSH_STATE_INTERMED:
762         size_needed = TRUE;            /* buffer for later */
763         break;
764       case SSH_STATE_SESSION:
765         if (!cfg.nopty) {
766             s_wrpkt_start(11, 16);
767             pktout.body[0] = (rows >> 24) & 0xFF;
768             pktout.body[1] = (rows >> 16) & 0xFF;
769             pktout.body[2] = (rows >> 8) & 0xFF;
770             pktout.body[3] = rows & 0xFF;
771             pktout.body[4] = (cols >> 24) & 0xFF;
772             pktout.body[5] = (cols >> 16) & 0xFF;
773             pktout.body[6] = (cols >> 8) & 0xFF;
774             pktout.body[7] = cols & 0xFF;
775             memset(pktout.body+8, 0, 8);
776             s_wrpkt();
777         }
778     }
779 }
780
781 /*
782  * (Send Telnet special codes)
783  */
784 static void ssh_special (Telnet_Special code) {
785     /* do nothing */
786 }
787
788 Backend ssh_backend = {
789     ssh_init,
790     ssh_msg,
791     ssh_send,
792     ssh_size,
793     ssh_special
794 };