Sebastian Kuschel reports that pfd_closing can be called for a socket
[u/mdw/putty] / portfwd.c
index 00132ec..00cff5e 100644 (file)
--- a/portfwd.c
+++ b/portfwd.c
@@ -1,3 +1,7 @@
+/*
+ * SSH port forwarding.
+ */
+
 #include <stdio.h>
 #include <stdlib.h>
 
 #define TRUE 1
 #endif
 
-#define GET_32BIT_LSB_FIRST(cp) \
-  (((unsigned long)(unsigned char)(cp)[0]) | \
-  ((unsigned long)(unsigned char)(cp)[1] << 8) | \
-  ((unsigned long)(unsigned char)(cp)[2] << 16) | \
-  ((unsigned long)(unsigned char)(cp)[3] << 24))
-
-#define PUT_32BIT_LSB_FIRST(cp, value) ( \
-  (cp)[0] = (value), \
-  (cp)[1] = (value) >> 8, \
-  (cp)[2] = (value) >> 16, \
-  (cp)[3] = (value) >> 24 )
-
-#define GET_16BIT_LSB_FIRST(cp) \
-  (((unsigned long)(unsigned char)(cp)[0]) | \
-  ((unsigned long)(unsigned char)(cp)[1] << 8))
-
-#define PUT_16BIT_LSB_FIRST(cp, value) ( \
-  (cp)[0] = (value), \
-  (cp)[1] = (value) >> 8 )
-
-#define GET_32BIT_MSB_FIRST(cp) \
-  (((unsigned long)(unsigned char)(cp)[0] << 24) | \
-  ((unsigned long)(unsigned char)(cp)[1] << 16) | \
-  ((unsigned long)(unsigned char)(cp)[2] << 8) | \
-  ((unsigned long)(unsigned char)(cp)[3]))
-
-#define PUT_32BIT_MSB_FIRST(cp, value) ( \
-  (cp)[0] = (value) >> 24, \
-  (cp)[1] = (value) >> 16, \
-  (cp)[2] = (value) >> 8, \
-  (cp)[3] = (value) )
-
-#define GET_16BIT_MSB_FIRST(cp) \
-  (((unsigned long)(unsigned char)(cp)[0] << 8) | \
-  ((unsigned long)(unsigned char)(cp)[1]))
-
-#define PUT_16BIT_MSB_FIRST(cp, value) ( \
-  (cp)[0] = (value) >> 8, \
-  (cp)[1] = (value) )
-
 struct PFwdPrivate {
     const struct plug_function_table *fn;
     /* the above variable absolutely *must* be the first in this structure */
@@ -69,14 +33,16 @@ struct PFwdPrivate {
     int dynamic;
     /*
      * `hostname' and `port' are the real hostname and port, once
-     * we know what we're connecting to; they're unused for this
-     * purpose while conducting a local SOCKS exchange, which means
-     * we can also use them as a buffer and pointer for reading
-     * data from the SOCKS client.
+     * we know what we're connecting to.
      */
-    char hostname[256+8];
+    char *hostname;
     int port;
     /*
+     * `socksbuf' is the buffer we use to accumulate a SOCKS request.
+     */
+    char *socksbuf;
+    int sockslen, sockssize;
+    /*
      * When doing dynamic port forwarding, we can receive
      * connection data before we are actually able to send it; so
      * we may have to temporarily hold some in a dynamically
@@ -86,19 +52,61 @@ struct PFwdPrivate {
     int buflen;
 };
 
+static struct PFwdPrivate *new_portfwd_private(void)
+{
+    struct PFwdPrivate *pr = snew(struct PFwdPrivate);
+    pr->hostname = NULL;
+    pr->socksbuf = NULL;
+    pr->sockslen = pr->sockssize = 0;
+    pr->buffer = NULL;
+    return pr;
+}
+
+static void free_portfwd_private(struct PFwdPrivate *pr)
+{
+    if (!pr)
+        return;
+    sfree(pr->hostname);
+    sfree(pr->socksbuf);
+    sfree(pr->buffer);
+    sfree(pr);
+}
+
+static void pfd_log(Plug plug, int type, SockAddr addr, int port,
+                   const char *error_msg, int error_code)
+{
+    /* we have to dump these since we have no interface to logging.c */
+}
+
 static int pfd_closing(Plug plug, const char *error_msg, int error_code,
                       int calling_back)
 {
     struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
 
-    /*
-     * We have no way to communicate down the forwarded connection,
-     * so if an error occurred on the socket, we just ignore it
-     * and treat it like a proper close.
-     */
-    if (pr->c)
-       sshfwd_close(pr->c);
-    pfd_close(pr->s);
+    if (error_msg) {
+        /*
+         * Socket error. Slam the connection instantly shut.
+         */
+        if (pr->c) {
+            sshfwd_unclean_close(pr->c);
+        } else {
+            /*
+             * We might not have an SSH channel, if a socket error
+             * occurred during SOCKS negotiation. If not, we must
+             * clean ourself up without sshfwd_unclean_close's call
+             * back to pfd_close.
+             */
+            pfd_close(pr->s);
+        }
+    } else {
+        /*
+         * Ordinary EOF received on socket. Send an EOF on the SSH
+         * channel.
+         */
+        if (pr->c)
+            sshfwd_write_eof(pr->c);
+    }
+
     return 1;
 }
 
@@ -107,32 +115,27 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
     struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
     if (pr->dynamic) {
        while (len--) {
-           if (pr->port >= lenof(pr->hostname)) {
-               if ((pr->dynamic >> 12) == 4) {
-                   /* Send back a SOCKS 4 error before closing. */
-                   char data[8];
-                   memset(data, 0, sizeof(data));
-                   data[1] = 91;      /* generic `request rejected' */
-                   sk_write(pr->s, data, 8);
-               }
-               pfd_close(pr->s);
-               return 1;
+           if (pr->sockslen >= pr->sockssize) {
+                pr->sockssize = pr->sockslen * 5 / 4 + 256;
+                pr->socksbuf = sresize(pr->socksbuf, pr->sockssize, char);
            }
-           pr->hostname[pr->port++] = *data++;
+           pr->socksbuf[pr->sockslen++] = *data++;
 
            /*
             * Now check what's in the buffer to see if it's a
             * valid and complete message in the SOCKS exchange.
             */
            if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 4) &&
-               pr->hostname[0] == 4) {
+               pr->socksbuf[0] == 4) {
                /*
                 * SOCKS 4.
                 */
                if (pr->dynamic == 1)
                    pr->dynamic = 0x4000;
-               if (pr->port < 2) continue;/* don't have command code yet */
-               if (pr->hostname[1] != 1) {
+               if (pr->sockslen < 2)
+                    continue;        /* don't have command code yet */
+               if (pr->socksbuf[1] != 1) {
+                   /* Not CONNECT. */
                    /* Send back a SOCKS 4 error before closing. */
                    char data[8];
                    memset(data, 0, sizeof(data));
@@ -141,15 +144,16 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                    pfd_close(pr->s);
                    return 1;
                }
-               if (pr->port < 8) continue;   /* haven't started username */
-               if (pr->hostname[pr->port-1] != 0)
-                   continue;          /* haven't _finished_ username */
+               if (pr->sockslen <= 8)
+                    continue;      /* haven't started user/hostname */
+               if (pr->socksbuf[pr->sockslen-1] != 0)
+                   continue;          /* haven't _finished_ user/hostname */
                /*
                 * Now we have a full SOCKS 4 request. Check it to
                 * see if it's a SOCKS 4A request.
                 */
-               if (pr->hostname[4] == 0 && pr->hostname[5] == 0 &&
-                   pr->hostname[6] == 0 && pr->hostname[7] != 0) {
+               if (pr->socksbuf[4] == 0 && pr->socksbuf[5] == 0 &&
+                   pr->socksbuf[6] == 0 && pr->socksbuf[7] != 0) {
                    /*
                     * It's SOCKS 4A. So if we haven't yet
                     * collected the host name, we should continue
@@ -159,15 +163,17 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                    int len;
                    if (pr->dynamic == 0x4000) {
                        pr->dynamic = 0x4001;
-                       pr->port = 8;      /* reset buffer to overwrite name */
+                       pr->sockslen = 8; /* reset buffer to overwrite name */
                        continue;
                    }
-                   pr->hostname[0] = 0;   /* reply version code */
-                   pr->hostname[1] = 90;   /* request granted */
-                   sk_write(pr->s, pr->hostname, 8);
-                   len= pr->port;
-                   pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
-                   memmove(pr->hostname, pr->hostname + 8, len);
+                   pr->socksbuf[0] = 0;   /* reply version code */
+                   pr->socksbuf[1] = 90;   /* request granted */
+                   sk_write(pr->s, pr->socksbuf, 8);
+                   len = pr->sockslen - 8;
+                   pr->port = GET_16BIT_MSB_FIRST(pr->socksbuf+2);
+                    pr->hostname = snewn(len+1, char);
+                    pr->hostname[len] = '\0';
+                   memcpy(pr->hostname, pr->socksbuf + 8, len);
                    goto connect;
                } else {
                    /*
@@ -175,21 +181,21 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                     * the IP address into the hostname string and
                     * then just go.
                     */
-                   pr->hostname[0] = 0;   /* reply version code */
-                   pr->hostname[1] = 90;   /* request granted */
-                   sk_write(pr->s, pr->hostname, 8);
-                   pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
-                   sprintf(pr->hostname, "%d.%d.%d.%d",
-                           (unsigned char)pr->hostname[4],
-                           (unsigned char)pr->hostname[5],
-                           (unsigned char)pr->hostname[6],
-                           (unsigned char)pr->hostname[7]);
+                   pr->socksbuf[0] = 0;   /* reply version code */
+                   pr->socksbuf[1] = 90;   /* request granted */
+                   sk_write(pr->s, pr->socksbuf, 8);
+                   pr->port = GET_16BIT_MSB_FIRST(pr->socksbuf+2);
+                   pr->hostname = dupprintf("%d.%d.%d.%d",
+                                             (unsigned char)pr->socksbuf[4],
+                                             (unsigned char)pr->socksbuf[5],
+                                             (unsigned char)pr->socksbuf[6],
+                                             (unsigned char)pr->socksbuf[7]);
                    goto connect;
                }
            }
 
            if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 5) &&
-               pr->hostname[0] == 5) {
+               pr->socksbuf[0] == 5) {
                /*
                 * SOCKS 5.
                 */
@@ -202,12 +208,13 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                    /*
                     * We're receiving a set of method identifiers.
                     */
-                   if (pr->port < 2) continue;/* no method count yet */
-                   if (pr->port < 2 + (unsigned char)pr->hostname[1])
+                   if (pr->sockslen < 2)
+                        continue;      /* no method count yet */
+                   if (pr->sockslen < 2 + (unsigned char)pr->socksbuf[1])
                        continue;      /* no methods yet */
                    method = 0xFF;     /* invalid */
-                   for (i = 0; i < (unsigned char)pr->hostname[1]; i++)
-                       if (pr->hostname[2+i] == 0) {
+                   for (i = 0; i < (unsigned char)pr->socksbuf[1]; i++)
+                       if (pr->socksbuf[2+i] == 0) {
                            method = 0;/* no auth */
                            break;
                        }
@@ -215,25 +222,41 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                    data[1] = method;
                    sk_write(pr->s, data, 2);
                    pr->dynamic = 0x5001;
-                   pr->port = 0;      /* re-empty the buffer */
+                   pr->sockslen = 0;      /* re-empty the buffer */
                    continue;
                }
 
                if (pr->dynamic == 0x5001) {
+                   /*
+                    * We're receiving a SOCKS request.
+                    */
+                   unsigned char reply[10]; /* SOCKS5 atyp=1 reply */
                    int atype, alen = 0;
-                   if (pr->port < 6) continue;
-                   atype = (unsigned char)pr->hostname[3];
+
+                   /*
+                    * Pre-fill reply packet.
+                    * In all cases, we set BND.{HOST,ADDR} to 0.0.0.0:0
+                    * (atyp=1) in the reply; if we succeed, we don't know
+                    * the right answers, and if we fail, they should be
+                    * ignored.
+                    */
+                   memset(reply, 0, lenof(reply));
+                   reply[0] = 5; /* VER */
+                   reply[3] = 1; /* ATYP = 1 (IPv4, 0.0.0.0:0) */
+
+                   if (pr->sockslen < 6) continue;
+                   atype = (unsigned char)pr->socksbuf[3];
                    if (atype == 1)    /* IPv4 address */
                        alen = 4;
                    if (atype == 4)    /* IPv6 address */
                        alen = 16;
                    if (atype == 3)    /* domain name has leading length */
-                       alen = 1 + (unsigned char)pr->hostname[4];
-                   if (pr->port < 6 + alen) continue;
-                   if (pr->hostname[1] != 1 || pr->hostname[2] != 0) {
-                       pr->hostname[1] = 1;   /* generic failure */
-                       pr->hostname[2] = 0;   /* reserved */
-                       sk_write(pr->s, pr->hostname, pr->port);
+                       alen = 1 + (unsigned char)pr->socksbuf[4];
+                   if (pr->sockslen < 6 + alen) continue;
+                   if (pr->socksbuf[1] != 1 || pr->socksbuf[2] != 0) {
+                       /* Not CONNECT or reserved field nonzero - error */
+                       reply[1] = 1;   /* generic failure */
+                       sk_write(pr->s, (char *) reply, lenof(reply));
                        pfd_close(pr->s);
                        return 1;
                    }
@@ -241,34 +264,35 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
                     * Now we have a viable connect request. Switch
                     * on atype.
                     */
-                   pr->port = GET_16BIT_MSB_FIRST(pr->hostname+4+alen);
+                   pr->port = GET_16BIT_MSB_FIRST(pr->socksbuf+4+alen);
                    if (atype == 1) {
-                       pr->hostname[1] = 0;   /* succeeded */
-                       sk_write(pr->s, pr->hostname, alen + 6);
-                       sprintf(pr->hostname, "%d.%d.%d.%d",
-                               (unsigned char)pr->hostname[4],
-                               (unsigned char)pr->hostname[5],
-                               (unsigned char)pr->hostname[6],
-                               (unsigned char)pr->hostname[7]);
+                       /* REP=0 (success) already */
+                       sk_write(pr->s, (char *) reply, lenof(reply));
+                       pr->hostname = dupprintf("%d.%d.%d.%d",
+                                                 (unsigned char)pr->socksbuf[4],
+                                                 (unsigned char)pr->socksbuf[5],
+                                                 (unsigned char)pr->socksbuf[6],
+                                                 (unsigned char)pr->socksbuf[7]);
                        goto connect;
                    } else if (atype == 3) {
-                       pr->hostname[1] = 0;   /* succeeded */
-                       sk_write(pr->s, pr->hostname, alen + 6);
-                       memmove(pr->hostname, pr->hostname + 5, alen-1);
+                       /* REP=0 (success) already */
+                       sk_write(pr->s, (char *) reply, lenof(reply));
+                        pr->hostname = snewn(alen, char);
                        pr->hostname[alen-1] = '\0';
+                       memcpy(pr->hostname, pr->socksbuf + 5, alen-1);
                        goto connect;
                    } else {
                        /*
                         * Unknown address type. (FIXME: support IPv6!)
                         */
-                       pr->hostname[1] = 8;   /* atype not supported */
-                       sk_write(pr->s, pr->hostname, pr->port);
+                       reply[1] = 8;   /* atype not supported */
+                       sk_write(pr->s, (char *) reply, lenof(reply));
                        pfd_close(pr->s);
-                       return 1;                       
+                       return 1;
                    }
                }
            }
-           
+
            /*
             * If we get here without either having done `continue'
             * or `goto connect', it must be because there is no
@@ -285,6 +309,14 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
         * connection.
         */
        connect:
+        sfree(pr->socksbuf);
+        pr->socksbuf = NULL;
+
+       /*
+        * Freeze the socket until the SSH server confirms the
+        * connection.
+        */
+       sk_set_frozen(pr->s, 1);
 
        pr->c = new_sock_channel(pr->backhandle, pr->s);
        if (pr->c == NULL) {
@@ -297,11 +329,6 @@ static int pfd_receive(Plug plug, int urgent, char *data, int len)
        pr->dynamic = 0;
 
        /*
-        * Now freeze the socket until the SSH server confirms the
-        * connection.
-        */
-       sk_set_frozen(pr->s, 1);
-       /*
         * If there's any data remaining in our current buffer,
         * save it to be sent on pfd_confirm().
         */
@@ -332,9 +359,10 @@ static void pfd_sent(Plug plug, int bufsize)
  * Called when receiving a PORT OPEN from the server
  */
 const char *pfd_newconnect(Socket *s, char *hostname, int port,
-                          void *c, const Config *cfg)
+                          void *c, Conf *conf, int addressfamily)
 {
     static const struct plug_function_table fn_table = {
+       pfd_log,
        pfd_closing,
        pfd_receive,
        pfd_sent,
@@ -349,15 +377,17 @@ const char *pfd_newconnect(Socket *s, char *hostname, int port,
     /*
      * Try to find host.
      */
-    addr = name_lookup(hostname, port, &dummy_realhost, cfg);
-    if ((err = sk_addr_error(addr)) != NULL)
+    addr = name_lookup(hostname, port, &dummy_realhost, conf, addressfamily);
+    if ((err = sk_addr_error(addr)) != NULL) {
+       sk_addr_free(addr);
+        sfree(dummy_realhost);
        return err;
+    }
 
     /*
      * Open socket.
      */
-    pr = snew(struct PFwdPrivate);
-    pr->buffer = NULL;
+    pr = new_portfwd_private();
     pr->fn = &fn_table;
     pr->throttled = pr->throttle_override = 0;
     pr->ready = 1;
@@ -366,14 +396,14 @@ const char *pfd_newconnect(Socket *s, char *hostname, int port,
     pr->dynamic = 0;
 
     pr->s = *s = new_connection(addr, dummy_realhost, port,
-                               0, 1, 0, (Plug) pr, cfg);
+                               0, 1, 0, 0, (Plug) pr, conf);
+    sfree(dummy_realhost);
     if ((err = sk_socket_error(*s)) != NULL) {
-       sfree(pr);
+       free_portfwd_private(pr);
        return err;
     }
 
     sk_set_private_ptr(*s, pr);
-    sk_addr_free(addr);
     return NULL;
 }
 
@@ -384,6 +414,7 @@ const char *pfd_newconnect(Socket *s, char *hostname, int port,
 static int pfd_accepting(Plug p, OSSocket sock)
 {
     static const struct plug_function_table fn_table = {
+       pfd_log,
        pfd_closing,
        pfd_receive,
        pfd_sent,
@@ -394,8 +425,7 @@ static int pfd_accepting(Plug p, OSSocket sock)
     const char *err;
 
     org = (struct PFwdPrivate *)p;
-    pr = snew(struct PFwdPrivate);
-    pr->buffer = NULL;
+    pr = new_portfwd_private();
     pr->fn = &fn_table;
 
     pr->c = NULL;
@@ -403,7 +433,7 @@ static int pfd_accepting(Plug p, OSSocket sock)
 
     pr->s = s = sk_register(sock, (Plug) pr);
     if ((err = sk_socket_error(s)) != NULL) {
-       sfree(pr);
+       free_portfwd_private(pr);
        return err != NULL;
     }
 
@@ -414,16 +444,16 @@ static int pfd_accepting(Plug p, OSSocket sock)
 
     if (org->dynamic) {
        pr->dynamic = 1;
-       pr->port = 0;                  /* hostname buffer is so far empty */
+       pr->port = 0;                  /* "hostname" buffer is so far empty */
        sk_set_frozen(s, 0);           /* we want to receive SOCKS _now_! */
     } else {
        pr->dynamic = 0;
-       strcpy(pr->hostname, org->hostname);
+       pr->hostname = dupstr(org->hostname);
        pr->port = org->port;   
        pr->c = new_sock_channel(org->backhandle, s);
 
        if (pr->c == NULL) {
-           sfree(pr);
+           free_portfwd_private(pr);
            return 1;
        } else {
            /* asks to forward to the specified host/port for this */
@@ -439,9 +469,11 @@ static int pfd_accepting(Plug p, OSSocket sock)
  sets up a listener on the local machine on (srcaddr:)port
  */
 const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
-                          int port, void *backhandle, const Config *cfg)
+                          int port, void *backhandle, Conf *conf,
+                          void **sockdata, int address_family)
 {
     static const struct plug_function_table fn_table = {
+       pfd_log,
        pfd_closing,
        pfd_receive,                   /* should not happen... */
        pfd_sent,                      /* also should not happen */
@@ -455,12 +487,11 @@ const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
     /*
      * Open socket.
      */
-    pr = snew(struct PFwdPrivate);
-    pr->buffer = NULL;
+    pr = new_portfwd_private();
     pr->fn = &fn_table;
     pr->c = NULL;
     if (desthost) {
-       strcpy(pr->hostname, desthost);
+       pr->hostname = dupstr(desthost);
        pr->port = destport;
        pr->dynamic = 0;
     } else
@@ -470,14 +501,17 @@ const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
     pr->backhandle = backhandle;
 
     pr->s = s = new_listener(srcaddr, port, (Plug) pr,
-                            !cfg->lport_acceptall, cfg);
+                            !conf_get_int(conf, CONF_lport_acceptall),
+                            conf, address_family);
     if ((err = sk_socket_error(s)) != NULL) {
-       sfree(pr);
+       free_portfwd_private(pr);
        return err;
     }
 
     sk_set_private_ptr(s, pr);
 
+    *sockdata = (void *)s;
+
     return NULL;
 }
 
@@ -490,12 +524,19 @@ void pfd_close(Socket s)
 
     pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
 
-    sfree(pr->buffer);
-    sfree(pr);
+    free_portfwd_private(pr);
 
     sk_close(s);
 }
 
+/*
+ * Terminate a listener.
+ */
+void pfd_terminate(void *sv)
+{
+    pfd_close((Socket)sv);
+}
+
 void pfd_unthrottle(Socket s)
 {
     struct PFwdPrivate *pr;
@@ -528,6 +569,10 @@ int pfd_send(Socket s, char *data, int len)
     return sk_write(s, data, len);
 }
 
+void pfd_send_eof(Socket s)
+{
+    sk_write_eof(s);
+}
 
 void pfd_confirm(Socket s)
 {