Support for doing DNS at the proxy end. I've invented a new type of
[u/mdw/putty] / ssh.c
diff --git a/ssh.c b/ssh.c
index c936060..62f2a8e 100644 (file)
--- a/ssh.c
+++ b/ssh.c
@@ -1,4 +1,3 @@
-#include <windows.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
 #define TRUE 1
 #endif
 
-#define logevent(s) { logevent(s); \
-                      if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
-                      { fprintf(stderr, "%s\n", s); fflush(stderr); } }
-
-/* logevent, only printf-formatted. */
-void logeventf(char *fmt, ...)
-{
-    va_list ap;
-    char stuff[200];
-
-    va_start(ap, fmt);
-    vsprintf(stuff, fmt, ap);
-    va_end(ap);
-    logevent(stuff);
-}
-
-#define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
-                          (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
-                          logeventf msg, connection_fatal msg )
-
 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
@@ -312,15 +291,16 @@ enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
 
 typedef struct ssh_tag *Ssh;
 
-extern char *x11_init(Socket *, char *, void *);
+extern char *x11_init(Socket *, char *, void *, void *);
 extern void x11_close(Socket);
 extern int x11_send(Socket, char *, int);
-extern void x11_invent_auth(char *, int, char *, int);
+extern void *x11_invent_auth(char *, int, char *, int);
 extern void x11_unthrottle(Socket s);
 extern void x11_override_throttle(Socket s, int enable);
 
 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
-extern char *pfd_addforward(char *desthost, int destport, int port);
+extern char *pfd_addforward(char *desthost, int destport, char *srcaddr,
+                           int port, void *backhandle);
 extern void pfd_close(Socket s);
 extern int pfd_send(Socket s, char *data, int len);
 extern void pfd_confirm(Socket s);
@@ -401,23 +381,27 @@ const static struct ssh_mac *buggymacs[] = {
     &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
 };
 
-static void ssh_comp_none_init(void)
+static void *ssh_comp_none_init(void)
+{
+    return NULL;
+}
+static void ssh_comp_none_cleanup(void *handle)
 {
 }
-static int ssh_comp_none_block(unsigned char *block, int len,
+static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
                               unsigned char **outblock, int *outlen)
 {
     return 0;
 }
-static int ssh_comp_none_disable(void)
+static int ssh_comp_none_disable(void *handle)
 {
     return 0;
 }
 const static struct ssh_compress ssh_comp_none = {
     "none",
-    ssh_comp_none_init, ssh_comp_none_block,
-    ssh_comp_none_init, ssh_comp_none_block,
-    ssh_comp_none_disable
+    ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
+    ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
+    ssh_comp_none_disable, NULL
 };
 extern const struct ssh_compress ssh_zlib;
 const static struct ssh_compress *compressions[] = {
@@ -551,6 +535,9 @@ struct ssh_tag {
 
     Socket s;
 
+    void *ldisc;
+    void *logctx;
+
     unsigned char session_key[32];
     int v1_compressing;
     int v1_remote_protoflags;
@@ -566,6 +553,7 @@ struct ssh_tag {
     const struct ssh_mac *csmac, *scmac;
     void *cs_mac_ctx, *sc_mac_ctx;
     const struct ssh_compress *cscomp, *sccomp;
+    void *cs_comp_ctx, *sc_comp_ctx;
     const struct ssh_kex *kex;
     const struct ssh_signkey *hostkey;
     unsigned char v2_session_id[20];
@@ -620,6 +608,8 @@ struct ssh_tag {
     char *portfwd_strptr;
     int pkt_ctx;
 
+    void *x11auth;
+
     int version;
     int v1_throttle_count;
     int overall_bufsize;
@@ -648,6 +638,35 @@ struct ssh_tag {
     int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
 };
 
+#define logevent(s) do { \
+    logevent(ssh->frontend, s); \
+    if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) { \
+       fprintf(stderr, "%s\n", s); \
+       fflush(stderr); \
+    } \
+} while (0)
+
+/* logevent, only printf-formatted. */
+void logeventf(Ssh ssh, char *fmt, ...)
+{
+    va_list ap;
+    char *buf;
+
+    va_start(ap, fmt);
+    buf = dupvprintf(fmt, ap);
+    va_end(ap);
+    logevent(buf);
+    if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) {
+       fprintf(stderr, "%s\n", buf);
+       fflush(stderr);
+    }
+    sfree(buf);
+}
+
+#define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
+                          (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
+                          logeventf msg, connection_fatal msg )
+
 static int ssh_channelcmp(void *av, void *bv)
 {
     struct ssh_channel *a = (struct ssh_channel *) av;
@@ -813,7 +832,7 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
 
     if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
                                     st->biglen, NULL)) {
-        bombout(("Network attack (CRC compensation) detected!"));
+        bombout((ssh,"Network attack (CRC compensation) detected!"));
         crReturn(0);
     }
 
@@ -823,7 +842,7 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
     st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
     if (st->gotcrc != st->realcrc) {
-       bombout(("Incorrect CRC received on packet"));
+       bombout((ssh,"Incorrect CRC received on packet"));
        crReturn(0);
     }
 
@@ -832,7 +851,8 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     if (ssh->v1_compressing) {
        unsigned char *decompblk;
        int decomplen;
-       zlib_decompress_block(ssh->pktin.body - 1, ssh->pktin.length + 1,
+       zlib_decompress_block(ssh->sc_comp_ctx,
+                             ssh->pktin.body - 1, ssh->pktin.length + 1,
                              &decompblk, &decomplen);
 
        if (ssh->pktin.maxlen < st->pad + decomplen) {
@@ -849,8 +869,11 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
 
     ssh->pktin.type = ssh->pktin.body[-1];
 
-    log_packet(PKT_INCOMING, ssh->pktin.type, ssh1_pkt_type(ssh->pktin.type),
-              ssh->pktin.body, ssh->pktin.length);
+    if (ssh->logctx)
+       log_packet(ssh->logctx,
+                  PKT_INCOMING, ssh->pktin.type,
+                  ssh1_pkt_type(ssh->pktin.type),
+                  ssh->pktin.body, ssh->pktin.length);
 
     if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
        ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
@@ -859,7 +882,7 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
        ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
        long stringlen = GET_32BIT(ssh->pktin.body);
        if (stringlen + 4 != ssh->pktin.length) {
-           bombout(("Received data packet with bogus string length"));
+           bombout((ssh,"Received data packet with bogus string length"));
            crReturn(0);
        }
     }
@@ -892,7 +915,7 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
        memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
        buf[nowlen + msglen] = '\0';
        /* logevent(buf); (this is now done within the bombout macro) */
-       bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
+       bombout((ssh,"Server sent disconnect message:\n\"%s\"", buf+nowlen));
        crReturn(0);
     }
 
@@ -946,7 +969,7 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
      * do us any more damage.
      */
     if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
-       bombout(("Incoming packet was garbled on decryption"));
+       bombout((ssh,"Incoming packet was garbled on decryption"));
        crReturn(0);
     }
 
@@ -994,7 +1017,7 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     if (ssh->scmac
        && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
                               st->incoming_sequence)) {
-       bombout(("Incorrect MAC received on packet"));
+       bombout((ssh,"Incorrect MAC received on packet"));
        crReturn(0);
     }
     st->incoming_sequence++;          /* whether or not we MACed */
@@ -1006,7 +1029,8 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
        unsigned char *newpayload;
        int newlen;
        if (ssh->sccomp &&
-           ssh->sccomp->decompress(ssh->pktin.data + 5, ssh->pktin.length - 5,
+           ssh->sccomp->decompress(ssh->sc_comp_ctx,
+                                   ssh->pktin.data + 5, ssh->pktin.length - 5,
                                    &newpayload, &newlen)) {
            if (ssh->pktin.maxlen < newlen + 5) {
                ssh->pktin.maxlen = newlen + 5;
@@ -1022,9 +1046,10 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     ssh->pktin.savedpos = 6;
     ssh->pktin.type = ssh->pktin.data[5];
 
-    log_packet(PKT_INCOMING, ssh->pktin.type,
-              ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
-              ssh->pktin.data+6, ssh->pktin.length-6);
+    if (ssh->logctx)
+       log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
+                  ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
+                  ssh->pktin.data+6, ssh->pktin.length-6);
 
     switch (ssh->pktin.type) {
         /*
@@ -1033,30 +1058,29 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
       case SSH2_MSG_DISCONNECT:
         {
             /* log reason code in disconnect message */
-            char buf[256];
+            char *buf;
+           int nowlen;
             int reason = GET_32BIT(ssh->pktin.data + 6);
             unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
-            unsigned nowlen;
+
             if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
-                sprintf(buf, "Received disconnect message (%s)",
-                        ssh2_disconnect_reasons[reason]);
+                buf = dupprintf("Received disconnect message (%s)",
+                               ssh2_disconnect_reasons[reason]);
             } else {
-                sprintf(buf, "Received disconnect message (unknown type %d)",
-                        reason);
+                buf = dupprintf("Received disconnect message (unknown"
+                               " type %d)", reason);
             }
             logevent(buf);
-            strcpy(buf, "Disconnection message text: ");
-            nowlen = strlen(buf);
-            if (msglen > sizeof(buf) - nowlen - 1)
-                msglen = sizeof(buf) - nowlen - 1;
-            memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
-            buf[nowlen + msglen] = '\0';
+           sfree(buf);
+            buf = dupprintf("Disconnection message text: %n%.*s",
+                           &nowlen, msglen, ssh->pktin.data + 14);
             logevent(buf);
-            bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
+            bombout((ssh,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
                      reason,
                      (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
                      ssh2_disconnect_reasons[reason] : "unknown",
                      buf+nowlen));
+           sfree(buf);
             crReturn(0);
         }
         break;
@@ -1165,13 +1189,16 @@ static int s_wrpkt_prepare(Ssh ssh)
 
     ssh->pktout.body[-1] = ssh->pktout.type;
 
-    log_packet(PKT_OUTGOING, ssh->pktout.type, ssh1_pkt_type(ssh->pktout.type),
-              ssh->pktout.body, ssh->pktout.length);
+    if (ssh->logctx)
+       log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
+                  ssh1_pkt_type(ssh->pktout.type),
+                  ssh->pktout.body, ssh->pktout.length);
 
     if (ssh->v1_compressing) {
        unsigned char *compblk;
        int complen;
-       zlib_compress_block(ssh->pktout.body - 1, ssh->pktout.length + 1,
+       zlib_compress_block(ssh->cs_comp_ctx,
+                           ssh->pktout.body - 1, ssh->pktout.length + 1,
                            &compblk, &complen);
        ssh1_pktout_size(ssh, complen - 1);
        memcpy(ssh->pktout.body - 1, compblk, complen);
@@ -1234,7 +1261,7 @@ static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
            pktlen += 4;
            break;
          case PKT_CHAR:
-           (void) va_arg(ap1, char);
+           (void) va_arg(ap1, int);
            pktlen++;
            break;
          case PKT_DATA:
@@ -1267,7 +1294,7 @@ static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
            p += 4;
            break;
          case PKT_CHAR:
-           argchar = va_arg(ap2, unsigned char);
+           argchar = (unsigned char) va_arg(ap2, int);
            *p = argchar;
            p++;
            break;
@@ -1446,9 +1473,10 @@ static int ssh2_pkt_construct(Ssh ssh)
 {
     int cipherblk, maclen, padding, i;
 
-    log_packet(PKT_OUTGOING, ssh->pktout.data[5],
-              ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
-              ssh->pktout.data + 6, ssh->pktout.length - 6);
+    if (ssh->logctx)
+       log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
+                  ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
+                  ssh->pktout.data + 6, ssh->pktout.length - 6);
 
     /*
      * Compress packet payload.
@@ -1457,7 +1485,8 @@ static int ssh2_pkt_construct(Ssh ssh)
        unsigned char *newpayload;
        int newlen;
        if (ssh->cscomp &&
-           ssh->cscomp->compress(ssh->pktout.data + 5, ssh->pktout.length - 5,
+           ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
+                                 ssh->pktout.length - 5,
                                  &newpayload, &newlen)) {
            ssh->pktout.length = 5;
            ssh2_pkt_adddata(ssh, newpayload, newlen);
@@ -1591,11 +1620,15 @@ static int ssh2_pkt_getbool(Ssh ssh)
 }
 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
 {
+    int len;
     *p = NULL;
     *length = 0;
     if (ssh->pktin.length - ssh->pktin.savedpos < 4)
        return;
-    *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
+    len = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
+    if (len < 0)
+       return;
+    *length = len;
     ssh->pktin.savedpos += 4;
     if (ssh->pktin.length - ssh->pktin.savedpos < *length)
        return;
@@ -1612,7 +1645,7 @@ static Bignum ssh2_pkt_getmp(Ssh ssh)
     if (!p)
        return NULL;
     if (p[0] & 0x80) {
-       bombout(("internal error: Can't handle negative mpints"));
+       bombout((ssh,"internal error: Can't handle negative mpints"));
        return NULL;
     }
     b = bignum_from_bytes(p, length);
@@ -1743,9 +1776,9 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (cfg.sshbug_hmac2 == BUG_ON ||
        (cfg.sshbug_hmac2 == BUG_AUTO &&
-        (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
-         !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
-         !strncmp(imp, "2.1 ", 4)))) {
+        (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
+         wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
+         wc_match("2.1 *", imp)))) {
        /*
         * These versions have the HMAC bug.
         */
@@ -1755,7 +1788,7 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (cfg.sshbug_derivekey2 == BUG_ON ||
        (cfg.sshbug_derivekey2 == BUG_AUTO &&
-        (!strncmp(imp, "2.0.", 4)))) {
+        (wc_match("2.0.0*", imp) || wc_match("2.0.1[01]*", imp) ))) {
        /*
         * These versions have the key-derivation bug (failing to
         * include the literal shared secret in the hashes that
@@ -1767,8 +1800,8 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (cfg.sshbug_rsapad2 == BUG_ON ||
        (cfg.sshbug_rsapad2 == BUG_AUTO &&
-        ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
-         (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
+        (wc_match("OpenSSH_2.[5-9]*", imp) ||
+         wc_match("OpenSSH_3.[0-2]*", imp)))) {
        /*
         * These versions have the SSH2 RSA padding bug.
         */
@@ -1778,7 +1811,7 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (cfg.sshbug_dhgex2 == BUG_ON) {
        /*
-        * These versions have the SSH2 DH GEX bug.
+        * User specified the SSH2 DH GEX bug.
         */
        ssh->remote_bugs |= BUG_SSH2_DH_GEX;
        logevent("We believe remote version has SSH2 DH group exchange bug");
@@ -1864,11 +1897,11 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
     s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
 
     if (cfg.sshprot == 0 && !s->proto1) {
-       bombout(("SSH protocol version 1 required by user but not provided by server"));
+       bombout((ssh,"SSH protocol version 1 required by user but not provided by server"));
        crReturn(0);
     }
     if (cfg.sshprot == 3 && !s->proto2) {
-       bombout(("SSH protocol version 2 required by user but not provided by server"));
+       bombout((ssh,"SSH protocol version 2 required by user but not provided by server"));
        crReturn(0);
     }
 
@@ -1975,7 +2008,7 @@ static int ssh_closing(Plug plug, char *error_msg, int error_code,
     if (error_msg) {
        /* A socket error has occurred. */
        logevent(error_msg);
-       connection_fatal(error_msg);
+       connection_fatal(ssh->frontend, error_msg);
     } else {
        /* Otherwise, the remote side closed the connection normally. */
     }
@@ -2038,12 +2071,8 @@ static char *connect_to_host(Ssh ssh, char *host, int port,
     /*
      * Try to find host.
      */
-    {
-       char buf[200];
-       sprintf(buf, "Looking up host \"%.170s\"", host);
-       logevent(buf);
-    }
-    addr = sk_namelookup(host, realhost);
+    logeventf(ssh, "Looking up host \"%s\"", host);
+    addr = name_lookup(host, port, realhost);
     if ((err = sk_addr_error(addr)))
        return err;
 
@@ -2051,10 +2080,9 @@ static char *connect_to_host(Ssh ssh, char *host, int port,
      * Open socket.
      */
     {
-       char buf[200], addrbuf[100];
+       char addrbuf[100];
        sk_getaddr(addr, addrbuf, 100);
-       sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
-       logevent(buf);
+       logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
     }
     ssh->fn = &fn_table;
     ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
@@ -2224,7 +2252,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        crWaitUntil(ispkt);
 
     if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
-       bombout(("Public key packet not received"));
+       bombout((ssh,"Public key packet not received"));
        crReturn(0);
     }
 
@@ -2285,7 +2313,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            fatalbox("Out of memory");
        rsastr_fmt(keystr, &hostkey);
        rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
-       verify_ssh_host_key(ssh->savedhost, ssh->savedport, "rsa", keystr,
+       verify_ssh_host_key(ssh->frontend,
+                           ssh->savedhost, ssh->savedport, "rsa", keystr,
                            fingerprint);
        sfree(keystr);
     }
@@ -2333,17 +2362,17 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        }
        if (!cipher_chosen) {
            if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
-               bombout(("Server violates SSH 1 protocol by not "
+               bombout((ssh,"Server violates SSH 1 protocol by not "
                         "supporting 3DES encryption"));
            else
                /* shouldn't happen */
-               bombout(("No supported ciphers found"));
+               bombout((ssh,"No supported ciphers found"));
            crReturn(0);
        }
 
        /* Warn about chosen cipher if necessary. */
        if (warn)
-           askcipher(cipher_string, 0);
+           askcipher(ssh->frontend, cipher_string, 0);
     }
 
     switch (s->cipher_type) {
@@ -2374,11 +2403,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                   &ssh_3des);
     ssh->v1_cipher_ctx = ssh->cipher->make_context();
     ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
-    {
-       char buf[256];
-       sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
-       logevent(buf);
-    }
+    logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
 
     ssh->crcda_ctx = crcda_make_context();
     logevent("Installing CRC compensation attack detector");
@@ -2386,7 +2411,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     crWaitUntil(ispkt);
 
     if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
-       bombout(("Encryption not successfully enabled"));
+       bombout((ssh,"Encryption not successfully enabled"));
        crReturn(0);
     }
 
@@ -2642,8 +2667,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            char msgbuf[256];
            if (flags & FLAG_VERBOSE)
                c_write_str(ssh, "Trying public key authentication.\r\n");
-           sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
-           logevent(msgbuf);
+           logeventf(ssh, "Trying public key \"%s\"", cfg.keyfile);
            type = key_type(cfg.keyfile);
            if (type != SSH_KEYTYPE_SSH1) {
                sprintf(msgbuf, "Key is of wrong type (%s)",
@@ -2680,7 +2704,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                            PKT_STR, "No more passwords available to try",
                            PKT_END);
                logevent("Unable to authenticate");
-               connection_fatal("Unable to authenticate");
+               connection_fatal(ssh->frontend, "Unable to authenticate");
                ssh->state = SSH_STATE_CLOSED;
                crReturn(1);
            }
@@ -2736,7 +2760,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                continue;              /* go and try password */
            }
            if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
-               bombout(("Bizarre response to offer of public key"));
+               bombout((ssh,"Bizarre response to offer of public key"));
                crReturn(0);
            }
 
@@ -2772,7 +2796,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                                " our public key.\r\n");
                continue;              /* go and try password */
            } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
-               bombout(("Bizarre response to RSA authentication response"));
+               bombout((ssh,"Bizarre response to RSA authentication response"));
                crReturn(0);
            }
 
@@ -2905,7 +2929,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                c_write_str(ssh, "Access denied\r\n");
            logevent("Authentication refused");
        } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
-           bombout(("Strange packet received, type %d", ssh->pktin.type));
+           bombout((ssh,"Strange packet received, type %d", ssh->pktin.type));
            crReturn(0);
        }
     }
@@ -3005,7 +3029,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout(("Protocol confusion"));
+           bombout((ssh,"Protocol confusion"));
            crReturnV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            logevent("Agent forwarding refused");
@@ -3018,7 +3042,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (cfg.x11_forward) {
        char proto[20], data[64];
        logevent("Requesting X11 forwarding");
-       x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
+       ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
+                                      data, sizeof(data));
        if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
            send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
                        PKT_STR, proto, PKT_STR, data,
@@ -3032,7 +3057,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout(("Protocol confusion"));
+           bombout((ssh,"Protocol confusion"));
            crReturnV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            logevent("X11 forwarding refused");
@@ -3046,91 +3071,104 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        char type;
        int n;
        int sport,dport,sserv,dserv;
-       char sports[256], dports[256], host[256];
-       char buf[1024];
-       struct servent *se;
+       char sports[256], dports[256], saddr[256], host[256];
 
        ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
         /* Add port forwardings. */
        ssh->portfwd_strptr = cfg.portfwd;
        while (*ssh->portfwd_strptr) {
            type = *ssh->portfwd_strptr++;
+           saddr[0] = '\0';
            n = 0;
-           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
-               sports[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
+               if (*ssh->portfwd_strptr == ':') {
+                   /*
+                    * We've seen a colon in the middle of the
+                    * source port number. This means that
+                    * everything we've seen until now is the
+                    * source _address_, so we'll move it into
+                    * saddr and start sports from the beginning
+                    * again.
+                    */
+                   ssh->portfwd_strptr++;
+                   sports[n] = '\0';
+                   strcpy(saddr, sports);
+                   n = 0;
+               }
+               if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
+           }
            sports[n] = 0;
            if (*ssh->portfwd_strptr == '\t')
                ssh->portfwd_strptr++;
            n = 0;
-           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
-               host[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
+               if (n < 255) host[n++] = *ssh->portfwd_strptr++;
+           }
            host[n] = 0;
            if (*ssh->portfwd_strptr == ':')
                ssh->portfwd_strptr++;
            n = 0;
-           while (*ssh->portfwd_strptr)
-               dports[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr) {
+               if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
+           }
            dports[n] = 0;
            ssh->portfwd_strptr++;
            dport = atoi(dports);
            dserv = 0;
            if (dport == 0) {
                dserv = 1;
-               se = getservbyname(dports, NULL);
-               if (se != NULL) {
-                   dport = ntohs(se->s_port);
-               } else {
-                   sprintf(buf,
-                           "Service lookup failed for destination port \"%s\"",
-                           dports);
-                   logevent(buf);
+               dport = net_service_lookup(dports);
+               if (!dport) {
+                   logeventf(ssh, "Service lookup failed for"
+                             " destination port \"%s\"", dports);
                }
            }
            sport = atoi(sports);
            sserv = 0;
            if (sport == 0) {
                sserv = 1;
-               se = getservbyname(sports, NULL);
-               if (se != NULL) {
-                   sport = ntohs(se->s_port);
-               } else {
-                   sprintf(buf,
-                           "Service lookup failed for source port \"%s\"",
-                           sports);
-                   logevent(buf);
+               sport = net_service_lookup(sports);
+               if (!sport) {
+                   logeventf(ssh, "Service lookup failed for source"
+                             " port \"%s\"", sports);
                }
            }
            if (sport && dport) {
                if (type == 'L') {
-                   pfd_addforward(host, dport, sport);
-                   sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
-                           " %s:%.*s%.*s%d%.*s",
-                           sserv ? strlen(sports) : 0, sports,
-                           sserv, "(", sport, sserv, ")",
-                           host,
-                           dserv ? strlen(dports) : 0, dports,
-                           dserv, "(", dport, dserv, ")");
-                   logevent(buf);
+                   pfd_addforward(host, dport, *saddr ? saddr : NULL,
+                                  sport, ssh);
+                   logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
+                             " forwarding to %s:%.*s%.*s%d%.*s",
+                             (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
+                             (int)(*saddr?1:0), ":",
+                             (int)(sserv ? strlen(sports) : 0), sports,
+                             sserv, "(", sport, sserv, ")",
+                             host,
+                             (int)(dserv ? strlen(dports) : 0), dports,
+                             dserv, "(", dport, dserv, ")");
                } else {
                    struct ssh_rportfwd *pf;
                    pf = smalloc(sizeof(*pf));
                    strcpy(pf->dhost, host);
                    pf->dport = dport;
+                   if (saddr) {
+                       logeventf(ssh,
+                                 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
+                                 saddr, sport);
+                   }
                    if (add234(ssh->rportfwds, pf) != pf) {
-                       sprintf(buf, 
-                               "Duplicate remote port forwarding to %s:%d",
-                               host, dport);
-                       logevent(buf);
+                       logeventf(ssh, 
+                                 "Duplicate remote port forwarding to %s:%d",
+                                 host, dport);
                        sfree(pf);
                    } else {
-                       sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
-                               " forward to %s:%.*s%.*s%d%.*s",
-                           sserv ? strlen(sports) : 0, sports,
-                           sserv, "(", sport, sserv, ")",
-                           host,
-                           dserv ? strlen(dports) : 0, dports,
-                           dserv, "(", dport, dserv, ")");
-                       logevent(buf);
+                       logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
+                                 " forward to %s:%.*s%.*s%d%.*s",
+                                 (int)(sserv ? strlen(sports) : 0), sports,
+                                 sserv, "(", sport, sserv, ")",
+                                 host,
+                                 (int)(dserv ? strlen(dports) : 0), dports,
+                                 dserv, "(", dport, dserv, ")");
                        send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
                                    PKT_INT, sport,
                                    PKT_STR, host,
@@ -3141,7 +3179,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        } while (!ispkt);
                        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
                            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-                           bombout(("Protocol confusion"));
+                           bombout((ssh,"Protocol confusion"));
                            crReturnV;
                        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
                            c_write_str(ssh, "Server refused port"
@@ -3166,7 +3204,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout(("Protocol confusion"));
+           bombout((ssh,"Protocol confusion"));
            crReturnV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            c_write_str(ssh, "Server refused to allocate pty\r\n");
@@ -3184,15 +3222,17 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout(("Protocol confusion"));
+           bombout((ssh,"Protocol confusion"));
            crReturnV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            c_write_str(ssh, "Server refused to compress\r\n");
        }
        logevent("Started compression");
        ssh->v1_compressing = TRUE;
-       zlib_compress_init();
-       zlib_decompress_init();
+       ssh->cs_comp_ctx = zlib_compress_init();
+       logevent("Initialised zlib (RFC1950) compression");
+       ssh->sc_comp_ctx = zlib_decompress_init();
+       logevent("Initialised zlib (RFC1950) decompression");
     }
 
     /*
@@ -3222,7 +3262,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (ssh->eof_needed)
        ssh_special(ssh, TS_EOF);
 
-    ldisc_send(NULL, 0, 0);           /* cause ldisc to notice changes */
+    if (ssh->ldisc)
+       ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
     ssh->send_ok = 1;
     ssh->channels = newtree234(ssh_channelcmp);
     while (1) {
@@ -3258,7 +3299,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    c = smalloc(sizeof(struct ssh_channel));
                    c->ssh = ssh;
 
-                   if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
+                   if (x11_init(&c->u.x11.s, cfg.x11_display, c,
+                                ssh->x11auth) != NULL) {
                        logevent("opening X11 forward connection failed");
                        sfree(c);
                        send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
@@ -3384,7 +3426,6 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
            } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
                unsigned int remoteid = GET_32BIT(ssh->pktin.body);
-               unsigned int localid = GET_32BIT(ssh->pktin.body+4);
                struct ssh_channel *c;
 
                c = find234(ssh->channels, &remoteid, ssh_channelfind);
@@ -3431,7 +3472,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        sfree(c);
                    }
                } else {
-                   bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
+                   bombout((ssh,"Received CHANNEL_CLOSE%s for %s channel %d\n",
                             ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
                             "_CONFIRMATION", c ? "half-open" : "nonexistent",
                             i));
@@ -3533,7 +3574,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 ssh->state = SSH_STATE_CLOSED;
                 crReturnV;
            } else {
-               bombout(("Strange packet received: type %d", ssh->pktin.type));
+               bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
                crReturnV;
            }
        } else {
@@ -3555,7 +3596,10 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  */
 static int in_commasep_string(char *needle, char *haystack, int haylen)
 {
-    int needlen = strlen(needle);
+    int needlen;
+    if (!needle || !haystack)         /* protect against null pointers */
+       return 0;
+    needlen = strlen(needle);
     while (1) {
        /*
         * Is it at the start of the string?
@@ -3790,7 +3834,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
     if (!ispkt)
        crWaitUntil(ispkt);
-    sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
+    if (ssh->pktin.length > 5)
+       sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
 
     /*
      * Now examine the other side's KEXINIT to see what we're up
@@ -3801,7 +3846,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        int i, j, len;
 
        if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
-           bombout(("expected key exchange packet from server"));
+           bombout((ssh,"expected key exchange packet from server"));
            crReturn(0);
        }
        ssh->kex = NULL;
@@ -3846,12 +3891,13 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            }
            if (s->cscipher_tobe) {
                if (s->warn)
-                   askcipher(s->cscipher_tobe->name, 1);
+                   askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
                break;
            }
        }
        if (!s->cscipher_tobe) {
-           bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
+           bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)",
+                    str ? str : "(null)"));
            crReturn(0);
        }
 
@@ -3871,12 +3917,13 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            }
            if (s->sccipher_tobe) {
                if (s->warn)
-                   askcipher(s->sccipher_tobe->name, 2);
+                   askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
                break;
            }
        }
        if (!s->sccipher_tobe) {
-           bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
+           bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)",
+                    str ? str : "(null)"));
            crReturn(0);
        }
 
@@ -3949,7 +3996,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
        crWaitUntil(ispkt);
        if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
-           bombout(("expected key exchange group packet from server"));
+           bombout((ssh,"expected key exchange group packet from server"));
            crReturn(0);
        }
        s->p = ssh2_pkt_getmp(ssh);
@@ -3975,7 +4022,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
     crWaitUntil(ispkt);
     if (ssh->pktin.type != s->kex_reply_value) {
-       bombout(("expected key exchange reply packet from server"));
+       bombout((ssh,"expected key exchange reply packet from server"));
        crReturn(0);
     }
     ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
@@ -4006,7 +4053,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (!s->hkey ||
        !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
                                 s->exchange_hash, 20)) {
-       bombout(("Server's host key did not match the signature supplied"));
+       bombout((ssh,"Server's host key did not match the signature supplied"));
        crReturn(0);
     }
 
@@ -4016,7 +4063,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
      */
     s->keystr = ssh->hostkey->fmtkey(s->hkey);
     s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
-    verify_ssh_host_key(ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
+    verify_ssh_host_key(ssh->frontend,
+                       ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
                        s->keystr, s->fingerprint);
     if (s->first_kex) {                       /* don't bother logging this in rekeys */
        logevent("Host key fingerprint is:");
@@ -4037,7 +4085,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
      */
     crWaitUntil(ispkt);
     if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
-       bombout(("expected new-keys packet from server"));
+       bombout((ssh,"expected new-keys packet from server"));
        crReturn(0);
     }
 
@@ -4064,10 +4112,16 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     ssh->scmac = s->scmac_tobe;
     ssh->sc_mac_ctx = ssh->scmac->make_context();
 
+    if (ssh->cs_comp_ctx)
+       ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
     ssh->cscomp = s->cscomp_tobe;
+    ssh->cs_comp_ctx = ssh->cscomp->compress_init();
+
+    if (ssh->sc_comp_ctx)
+       ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
     ssh->sccomp = s->sccomp_tobe;
-    ssh->cscomp->compress_init();
-    ssh->sccomp->decompress_init();
+    ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
+
     /*
      * Set IVs after keys. Here we use the exchange hash from the
      * _first_ key exchange.
@@ -4090,16 +4144,16 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
        ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
     }
-    {
-       char buf[256];
-       sprintf(buf, "Initialised %.200s client->server encryption",
-               ssh->cscipher->text_name);
-       logevent(buf);
-       sprintf(buf, "Initialised %.200s server->client encryption",
-               ssh->sccipher->text_name);
-       logevent(buf);
-    }
-
+    logeventf(ssh, "Initialised %.200s client->server encryption",
+             ssh->cscipher->text_name);
+    logeventf(ssh, "Initialised %.200s server->client encryption",
+             ssh->sccipher->text_name);
+    if (ssh->cscomp->text_name)
+       logeventf(ssh, "Initialised %s compression",
+                 ssh->cscomp->text_name);
+    if (ssh->sccomp->text_name)
+       logeventf(ssh, "Initialised %s decompression",
+                 ssh->sccomp->text_name);
 
     /*
      * If this is the first key exchange phase, we must pass the
@@ -4246,7 +4300,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_send(ssh);
     crWaitUntilV(ispkt);
     if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
-       bombout(("Server refused user authentication protocol"));
+       bombout((ssh,"Server refused user authentication protocol"));
        crReturnV;
     }
 
@@ -4309,16 +4363,17 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                } while (ret == 0);
                if (ret < 0)
                    cleanup_exit(0);
+               c_write_str(ssh, "\r\n");
            }
-           c_write_str(ssh, "\r\n");
            s->username[strcspn(s->username, "\n\r")] = '\0';
        } else {
-           char stuff[200];
+           char *stuff;
            strncpy(s->username, cfg.username, sizeof(s->username));
            s->username[sizeof(s->username)-1] = '\0';
            if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
-               sprintf(stuff, "Using username \"%s\".\r\n", s->username);
+               stuff = dupprintf("Using username \"%s\".\r\n", s->username);
                c_write_str(ssh, stuff);
+               sfree(stuff);
            }
        }
        s->got_username = TRUE;
@@ -4346,19 +4401,21 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
        if (*cfg.keyfile) {
            int keytype;
-           logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
+           logeventf(ssh, "Reading private key file \"%.150s\"", cfg.keyfile);
            keytype = key_type(cfg.keyfile);
            if (keytype == SSH_KEYTYPE_SSH2) {
                s->publickey_blob =
                    ssh2_userkey_loadpub(cfg.keyfile, NULL,
                                         &s->publickey_bloblen);
            } else {
-               char msgbuf[256];
-               logeventf("Unable to use this key file (%s)",
-                       key_type_to_str(keytype));
-               sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
-                       cfg.keyfile, key_type_to_str(keytype));
+               char *msgbuf;
+               logeventf(ssh, "Unable to use this key file (%s)",
+                         key_type_to_str(keytype));
+               msgbuf = dupprintf("Unable to use key file \"%.150s\""
+                                  " (%s)\r\n", cfg.keyfile,
+                                  key_type_to_str(keytype));
                c_write_str(ssh, msgbuf);
+               sfree(msgbuf);
                s->publickey_blob = NULL;
            }
        } else
@@ -4406,7 +4463,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                if (!s->gotit)
                    s->curr_prompt = 0;
            } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
-               bombout(("Strange packet received during authentication: type %d",
+               bombout((ssh,"Strange packet received during authentication: type %d",
                         ssh->pktin.type));
                crReturnV;
            }
@@ -4795,7 +4852,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        ssh2_pkt_addstring(ssh, "en");  /* language tag */
                        ssh2_pkt_send(ssh);
                        logevent("Unable to authenticate");
-                       connection_fatal("Unable to authenticate");
+                       connection_fatal(ssh->frontend,
+                                        "Unable to authenticate");
                        ssh->state = SSH_STATE_CLOSED;
                        crReturnV;
                    }
@@ -4926,7 +4984,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                         * bytes we should adjust our string length
                         * by.
                         */
-                       stringlen -= ssh->cscomp->disable_compression();
+                       stringlen -= 
+                           ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
                    }
                    ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
                    ssh2_pkt_addstring_start(ssh);
@@ -5002,12 +5061,12 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_send(ssh);
     crWaitUntilV(ispkt);
     if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
-       bombout(("Server refused to open a session"));
+       bombout((ssh,"Server refused to open a session"));
        crReturnV;
        /* FIXME: error data comes back in FAILURE packet */
     }
     if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
-       bombout(("Server's channel confirmation cited wrong channel"));
+       bombout((ssh,"Server's channel confirmation cited wrong channel"));
        crReturnV;
     }
     ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
@@ -5025,7 +5084,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (cfg.x11_forward) {
        char proto[20], data[64];
        logevent("Requesting X11 forwarding");
-       x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
+       ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
+                                      data, sizeof(data));
        ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
        ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
        ssh2_pkt_addstring(ssh, "x11-req");
@@ -5050,7 +5110,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout(("Unexpected response to X11 forwarding request:"
+               bombout((ssh,"Unexpected response to X11 forwarding request:"
                         " packet type %d", ssh->pktin.type));
                crReturnV;
            }
@@ -5068,71 +5128,81 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        char type;
        int n;
        int sport,dport,sserv,dserv;
-       char sports[256], dports[256], host[256];
-       char buf[1024];
-       struct servent *se;
+       char sports[256], dports[256], saddr[256], host[256];
 
        ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
         /* Add port forwardings. */
        ssh->portfwd_strptr = cfg.portfwd;
        while (*ssh->portfwd_strptr) {
            type = *ssh->portfwd_strptr++;
+           saddr[0] = '\0';
            n = 0;
-           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
-               sports[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
+               if (*ssh->portfwd_strptr == ':') {
+                   /*
+                    * We've seen a colon in the middle of the
+                    * source port number. This means that
+                    * everything we've seen until now is the
+                    * source _address_, so we'll move it into
+                    * saddr and start sports from the beginning
+                    * again.
+                    */
+                   ssh->portfwd_strptr++;
+                   sports[n] = '\0';
+                   strcpy(saddr, sports);
+                   n = 0;
+               }
+               if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
+           }
            sports[n] = 0;
            if (*ssh->portfwd_strptr == '\t')
                ssh->portfwd_strptr++;
            n = 0;
-           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
-               host[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
+               if (n < 255) host[n++] = *ssh->portfwd_strptr++;
+           }
            host[n] = 0;
            if (*ssh->portfwd_strptr == ':')
                ssh->portfwd_strptr++;
            n = 0;
-           while (*ssh->portfwd_strptr)
-               dports[n++] = *ssh->portfwd_strptr++;
+           while (*ssh->portfwd_strptr) {
+               if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
+           }
            dports[n] = 0;
            ssh->portfwd_strptr++;
            dport = atoi(dports);
            dserv = 0;
            if (dport == 0) {
                dserv = 1;
-               se = getservbyname(dports, NULL);
-               if (se != NULL) {
-                   dport = ntohs(se->s_port);
-               } else {
-                   sprintf(buf,
-                           "Service lookup failed for destination port \"%s\"",
-                           dports);
-                   logevent(buf);
+               dport = net_service_lookup(dports);
+               if (!dport) {
+                   logeventf(ssh, "Service lookup failed for destination"
+                             " port \"%s\"", dports);
                }
            }
            sport = atoi(sports);
            sserv = 0;
            if (sport == 0) {
                sserv = 1;
-               se = getservbyname(sports, NULL);
-               if (se != NULL) {
-                   sport = ntohs(se->s_port);
-               } else {
-                   sprintf(buf,
-                           "Service lookup failed for source port \"%s\"",
-                           sports);
-                   logevent(buf);
+               sport = net_service_lookup(sports);
+               if (!sport) {
+                   logeventf(ssh, "Service lookup failed for source"
+                             " port \"%s\"", sports);
                }
            }
            if (sport && dport) {
                if (type == 'L') {
-                   pfd_addforward(host, dport, sport);
-                   sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
-                           " %s:%.*s%.*s%d%.*s",
-                           sserv ? strlen(sports) : 0, sports,
-                           sserv, "(", sport, sserv, ")",
-                           host,
-                           dserv ? strlen(dports) : 0, dports,
-                           dserv, "(", dport, dserv, ")");
-                   logevent(buf);
+                   pfd_addforward(host, dport, *saddr ? saddr : NULL,
+                                  sport, ssh);
+                   logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
+                             " forwarding to %s:%.*s%.*s%d%.*s",
+                             (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
+                             (int)(*saddr?1:0), ":",
+                             (int)(sserv ? strlen(sports) : 0), sports,
+                             sserv, "(", sport, sserv, ")",
+                             host,
+                             (int)(dserv ? strlen(dports) : 0), dports,
+                             dserv, "(", dport, dserv, ")");
                } else {
                    struct ssh_rportfwd *pf;
                    pf = smalloc(sizeof(*pf));
@@ -5140,23 +5210,26 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    pf->dport = dport;
                    pf->sport = sport;
                    if (add234(ssh->rportfwds, pf) != pf) {
-                       sprintf(buf, 
-                               "Duplicate remote port forwarding to %s:%d",
-                               host, dport);
-                       logevent(buf);
+                       logeventf(ssh, "Duplicate remote port forwarding"
+                                 " to %s:%d", host, dport);
                        sfree(pf);
                    } else {
-                       sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
-                               " forward to %s:%.*s%.*s%d%.*s",
-                           sserv ? strlen(sports) : 0, sports,
-                           sserv, "(", sport, sserv, ")",
-                           host,
-                           dserv ? strlen(dports) : 0, dports,
-                           dserv, "(", dport, dserv, ")");
-                       logevent(buf);
+                       logeventf(ssh, "Requesting remote port "
+                                 "%.*s%.*s%.*s%.*s%d%.*s"
+                                 " forward to %s:%.*s%.*s%d%.*s",
+                                 (int)(*saddr?strlen(saddr):0),
+                                 *saddr?saddr:NULL,
+                                 (int)(*saddr?1:0), ":",
+                                 (int)(sserv ? strlen(sports) : 0), sports,
+                                 sserv, "(", sport, sserv, ")",
+                                 host,
+                                 (int)(dserv ? strlen(dports) : 0), dports,
+                                 dserv, "(", dport, dserv, ")");
                        ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
                        ssh2_pkt_addstring(ssh, "tcpip-forward");
                        ssh2_pkt_addbool(ssh, 1);/* want reply */
+                       if (*saddr)
+                           ssh2_pkt_addstring(ssh, saddr);
                        if (cfg.rport_acceptall)
                            ssh2_pkt_addstring(ssh, "0.0.0.0");
                        else
@@ -5178,7 +5251,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
                        if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
                            if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
-                               bombout(("Unexpected response to port "
+                               bombout((ssh,"Unexpected response to port "
                                         "forwarding request: packet type %d",
                                         ssh->pktin.type));
                                crReturnV;
@@ -5218,7 +5291,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout(("Unexpected response to agent forwarding request:"
+               bombout((ssh,"Unexpected response to agent forwarding request:"
                         " packet type %d", ssh->pktin.type));
                crReturnV;
            }
@@ -5261,7 +5334,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout(("Unexpected response to pty request:"
+               bombout((ssh,"Unexpected response to pty request:"
                         " packet type %d", ssh->pktin.type));
                crReturnV;
            }
@@ -5319,7 +5392,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout(("Unexpected response to shell/command request:"
+               bombout((ssh,"Unexpected response to shell/command request:"
                         " packet type %d", ssh->pktin.type));
                crReturnV;
            }
@@ -5334,7 +5407,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                ssh->fallback_cmd = TRUE;
                continue;
            }
-           bombout(("Server refused to start a shell/command"));
+           bombout((ssh,"Server refused to start a shell/command"));
            crReturnV;
        } else {
            logevent("Started a shell/command");
@@ -5351,7 +5424,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     /*
      * Transfer data!
      */
-    ldisc_send(NULL, 0, 0);           /* cause ldisc to notice changes */
+    if (ssh->ldisc)
+       ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
     ssh->send_ok = 1;
     while (1) {
        crReturnV;
@@ -5470,7 +5544,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c || ((int)c->remoteid) == -1) {
-                   bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
+                   bombout((ssh,"Received CHANNEL_CLOSE for %s channel %d\n",
                             c ? "half-open" : "nonexistent", i));
                }
                /* Do pre-close processing on the channel. */
@@ -5670,8 +5744,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                if (typelen == 3 && !memcmp(type, "x11", 3)) {
                    if (!ssh->X11_fwd_enabled)
                        error = "X11 forwarding is not enabled";
-                   else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
-                            NULL) {
+                   else if (x11_init(&c->u.x11.s, cfg.x11_display, c,
+                                     ssh->x11auth) != NULL) {
                        error = "Unable to open an X11 connection";
                    } else {
                        c->type = CHAN_X11;
@@ -5689,13 +5763,10 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    } else {
                        char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
                                                 realpf->dport, c);
-                       char buf[1024];
-                       sprintf(buf, "Received remote port open request for %s:%d",
-                               realpf->dhost, realpf->dport);
-                       logevent(buf);
+                       logeventf(ssh, "Received remote port open request"
+                                 " for %s:%d", realpf->dhost, realpf->dport);
                        if (e != NULL) {
-                           sprintf(buf, "Port open failed: %s", e);
-                           logevent(buf);
+                           logeventf(ssh, "Port open failed: %s", e);
                            error = "Port open failed";
                        } else {
                            logevent("Forwarded port opened successfully");
@@ -5739,7 +5810,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    ssh2_pkt_send(ssh);
                }
            } else {
-               bombout(("Strange packet received: type %d", ssh->pktin.type));
+               bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
                crReturnV;
            }
        } else {
@@ -5813,17 +5884,21 @@ static char *ssh_init(void *frontend_handle, void **backend_handle,
     ssh->sccipher = NULL;
     ssh->sc_cipher_ctx = NULL;
     ssh->csmac = NULL;
-    ssh->sc_mac_ctx = NULL;
+    ssh->cs_mac_ctx = NULL;
     ssh->scmac = NULL;
     ssh->sc_mac_ctx = NULL;
     ssh->cscomp = NULL;
+    ssh->cs_comp_ctx = NULL;
     ssh->sccomp = NULL;
+    ssh->sc_comp_ctx = NULL;
     ssh->kex = NULL;
     ssh->hostkey = NULL;
     ssh->exitcode = -1;
     ssh->state = SSH_STATE_PREPACKET;
     ssh->size_needed = FALSE;
     ssh->eof_needed = FALSE;
+    ssh->ldisc = NULL;
+    ssh->logctx = NULL;
     {
        static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
        ssh->pktin = ssh->pktout = empty;
@@ -5833,6 +5908,8 @@ static char *ssh_init(void *frontend_handle, void **backend_handle,
     ssh->deferred_size = 0;
     ssh->fallback_cmd = 0;
     ssh->pkt_ctx = 0;
+    ssh->x11auth = NULL;
+    ssh->v1_compressing = FALSE;
     ssh->v2_outgoing_sequence = 0;
     ssh->ssh1_rdpkt_crstate = 0;
     ssh->ssh2_rdpkt_crstate = 0;
@@ -5846,6 +5923,9 @@ static char *ssh_init(void *frontend_handle, void **backend_handle,
     ssh->do_ssh1_login_state = NULL;
     ssh->do_ssh2_transport_state = NULL;
     ssh->do_ssh2_authconn_state = NULL;
+    ssh->mainchan = NULL;
+    ssh->throttled_all = 0;
+    ssh->v1_stdout_throttling = 0;
 
     *backend_handle = ssh;
 
@@ -5939,8 +6019,6 @@ static void ssh_size(void *handle, int width, int height)
        break;
       case SSH_STATE_SESSION:
        if (!cfg.nopty) {
-           if (!term)
-               return;
            if (ssh->version == 1) {
                send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
                            PKT_INT, ssh->term_height,
@@ -6042,15 +6120,12 @@ void ssh_unthrottle(void *handle, int bufsize)
     }
 }
 
-void ssh_send_port_open(void *handle, void *channel, char *hostname,
-                       int port, char *org)
+void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
 {
-    Ssh ssh = (Ssh) handle;
     struct ssh_channel *c = (struct ssh_channel *)channel;
-    char buf[1024];
+    Ssh ssh = c->ssh;
 
-    sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
-    logevent(buf);
+    logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
 
     if (ssh->version == 1) {
        send_packet(ssh, SSH1_MSG_PORT_OPEN,
@@ -6103,6 +6178,18 @@ static int ssh_ldisc(void *handle, int option)
     return FALSE;
 }
 
+static void ssh_provide_ldisc(void *handle, void *ldisc)
+{
+    Ssh ssh = (Ssh) handle;
+    ssh->ldisc = ldisc;
+}
+
+static void ssh_provide_logctx(void *handle, void *logctx)
+{
+    Ssh ssh = (Ssh) handle;
+    ssh->logctx = logctx;
+}
+
 static int ssh_return_exitcode(void *handle)
 {
     Ssh ssh = (Ssh) handle;
@@ -6130,6 +6217,8 @@ Backend ssh_backend = {
     ssh_return_exitcode,
     ssh_sendok,
     ssh_ldisc,
+    ssh_provide_ldisc,
+    ssh_provide_logctx,
     ssh_unthrottle,
     22
 };