Run entire source base through GNU indent to tidy up the varying
authorsimon <simon@cda61777-01e9-0310-a592-d414129be87e>
Sun, 6 May 2001 14:35:20 +0000 (14:35 +0000)
committersimon <simon@cda61777-01e9-0310-a592-d414129be87e>
Sun, 6 May 2001 14:35:20 +0000 (14:35 +0000)
coding styles of the various contributors! Woohoo!

git-svn-id: svn://svn.tartarus.org/sgt/putty@1098 cda61777-01e9-0310-a592-d414129be87e

52 files changed:
be_nossh.c
int64.c
ldisc.c
misc.c
misc.h
mscrypto.c
network.h
noise.c
pageant.c
pageantc.c
plink.c
psftp.c
putty.h
puttygen.c
puttymem.h
raw.c
rlogin.c
scp.c
settings.c
sftp.c
sftp.h
sizetip.c
ssh.c
ssh.h
sshaes.c
sshblowf.c
sshbn.c
sshcrc.c
sshdes.c
sshdh.c
sshdss.c
sshmd5.c
sshprime.c
sshpubk.c
sshrand.c
sshrsa.c
sshrsag.c
sshsha.c
sshzlib.c
storage.h
telnet.c
terminal.c
tree234.c
tree234.h
winctrls.c
windlg.c
window.c
winnet.c
winstore.c
winstuff.h
x11fwd.c
xlat.c

index 54e0d42..76355cb 100644 (file)
@@ -17,14 +17,18 @@ struct backend_list backends[] = {
 /*
  * Stub implementations of functions not used in non-ssh versions.
  */
-void random_save_seed(void) {
+void random_save_seed(void)
+{
 }
 
-void random_destroy_seed(void) {
+void random_destroy_seed(void)
+{
 }
 
-void noise_ultralight(DWORD data) {
+void noise_ultralight(DWORD data)
+{
 }
 
-void noise_regular(void) {
+void noise_regular(void)
+{
 }
diff --git a/int64.c b/int64.c
index b43feea..da7b4c3 100644 (file)
--- a/int64.c
+++ b/int64.c
@@ -10,7 +10,8 @@ typedef struct {
     unsigned long hi, lo;
 } uint64, int64;
 
-uint64 uint64_div10(uint64 x, int *remainder) {
+uint64 uint64_div10(uint64 x, int *remainder)
+{
     uint64 y;
     int rem, r2;
     y.hi = x.hi / 10;
@@ -30,7 +31,8 @@ uint64 uint64_div10(uint64 x, int *remainder) {
     return y;
 }
 
-void uint64_decimal(uint64 x, char *buffer) {
+void uint64_decimal(uint64 x, char *buffer)
+{
     char buf[20];
     int start = 20;
     int d;
@@ -41,24 +43,27 @@ void uint64_decimal(uint64 x, char *buffer) {
        buf[--start] = d + '0';
     }
 
-    memcpy(buffer, buf+start, sizeof(buf)-start);
-    buffer[sizeof(buf)-start] = '\0';
+    memcpy(buffer, buf + start, sizeof(buf) - start);
+    buffer[sizeof(buf) - start] = '\0';
 }
 
-uint64 uint64_make(unsigned long hi, unsigned long lo) {
+uint64 uint64_make(unsigned long hi, unsigned long lo)
+{
     uint64 y;
     y.hi = hi;
     y.lo = lo;
     return y;
 }
 
-uint64 uint64_add(uint64 x, uint64 y) {
+uint64 uint64_add(uint64 x, uint64 y)
+{
     x.lo += y.lo;
     x.hi += y.hi + (x.lo < y.lo ? 1 : 0);
     return x;
 }
 
-uint64 uint64_add32(uint64 x, unsigned long y) {
+uint64 uint64_add32(uint64 x, unsigned long y)
+{
     uint64 yy;
     yy.hi = 0;
     yy.lo = y;
diff --git a/ldisc.c b/ldisc.c
index 1ab832d..a42db93 100644 (file)
--- a/ldisc.c
+++ b/ldisc.c
                  (cfg.localedit == LD_BACKEND && \
                       (back->ldisc(LD_EDIT) || term_ldisc(LD_EDIT))))
 
-static void c_write (char *buf, int len) {
+static void c_write(char *buf, int len)
+{
     from_backend(0, buf, len);
 }
 
 static char *term_buf = NULL;
 static int term_buflen = 0, term_bufsiz = 0, term_quotenext = 0;
 
-static int plen(unsigned char c) {
-    if ((c >= 32 && c <= 126) ||
-        (c >= 160))
-        return 1;
+static int plen(unsigned char c)
+{
+    if ((c >= 32 && c <= 126) || (c >= 160))
+       return 1;
     else if (c < 128)
-        return 2;                      /* ^x for some x */
+       return 2;                      /* ^x for some x */
     else
-        return 4;                      /* <XY> for hex XY */
+       return 4;                      /* <XY> for hex XY */
 }
 
-static void pwrite(unsigned char c) {
-    if ((c >= 32 && c <= 126) ||
-        (c >= 160)) {
-        c_write(&c, 1);
+static void pwrite(unsigned char c)
+{
+    if ((c >= 32 && c <= 126) || (c >= 160)) {
+       c_write(&c, 1);
     } else if (c < 128) {
-        char cc[2];
-        cc[1] = (c == 127 ? '?' : c + 0x40);
-        cc[0] = '^';
-        c_write(cc, 2);
+       char cc[2];
+       cc[1] = (c == 127 ? '?' : c + 0x40);
+       cc[0] = '^';
+       c_write(cc, 2);
     } else {
-        char cc[5];
-        sprintf(cc, "<%02X>", c);
-        c_write(cc, 4);
+       char cc[5];
+       sprintf(cc, "<%02X>", c);
+       c_write(cc, 4);
     }
 }
 
-static void bsb(int n) {
+static void bsb(int n)
+{
     while (n--)
        c_write("\010 \010", 3);
 }
 
 #define CTRL(x) (x^'@')
 
-void ldisc_send(char *buf, int len) {
+void ldisc_send(char *buf, int len)
+{
     /*
      * Called with len=0 when the options change. We must inform
      * the front end in case it needs to know.
      */
     if (len == 0) {
-        void ldisc_update(int echo, int edit);
-        ldisc_update(ECHOING, EDITING);
+       void ldisc_update(int echo, int edit);
+       ldisc_update(ECHOING, EDITING);
     }
     /*
      * Either perform local editing, or just send characters.
      */
     if (EDITING) {
-        while (len--) {
-            char c;
-            c = *buf++;
-            switch (term_quotenext ? ' ' : c) {
-                /*
-                 * ^h/^?: delete one char and output one BSB
-                 * ^w: delete, and output BSBs, to return to last
-                 * space/nonspace boundary
-                 * ^u: delete, and output BSBs, to return to BOL
-                 * ^c: Do a ^u then send a telnet IP
-                 * ^z: Do a ^u then send a telnet SUSP
-                 * ^\: Do a ^u then send a telnet ABORT
-                 * ^r: echo "^R\n" and redraw line
-                 * ^v: quote next char
-                 * ^d: if at BOL, end of file and close connection,
-                 * else send line and reset to BOL
-                 * ^m: send line-plus-\r\n and reset to BOL
-                 */
-              case CTRL('H'): case CTRL('?'):      /* backspace/delete */
-                if (term_buflen > 0) {
-                    if (ECHOING)
-                        bsb(plen(term_buf[term_buflen-1]));
-                    term_buflen--;
-                }
-                break;
-              case CTRL('W'):                 /* delete word */
-                while (term_buflen > 0) {
-                    if (ECHOING)
-                        bsb(plen(term_buf[term_buflen-1]));
-                    term_buflen--;
-                    if (term_buflen > 0 &&
-                        isspace(term_buf[term_buflen-1]) &&
-                        !isspace(term_buf[term_buflen]))
-                        break;
-                }
-                break;
-              case CTRL('U'):         /* delete line */
-              case CTRL('C'):         /* Send IP */
-              case CTRL('\\'):        /* Quit */
-              case CTRL('Z'):         /* Suspend */
-                while (term_buflen > 0) {
-                    if (ECHOING)
-                        bsb(plen(term_buf[term_buflen-1]));
-                    term_buflen--;
-                }
-                back->special (TS_EL);
-                if( c == CTRL('C') )  back->special (TS_IP);
-                if( c == CTRL('Z') )  back->special (TS_SUSP);
-                if( c == CTRL('\\') ) back->special (TS_ABORT);
-                break;
-              case CTRL('R'):         /* redraw line */
-                if (ECHOING) {
-                    int i;
-                    c_write("^R\r\n", 4);
-                    for (i = 0; i < term_buflen; i++)
-                        pwrite(term_buf[i]);
-                }
-                break;
-              case CTRL('V'):         /* quote next char */
-                term_quotenext = TRUE;
-                break;
-              case CTRL('D'):         /* logout or send */
-                if (term_buflen == 0) {
-                    back->special (TS_EOF);
-                } else {
-                    back->send(term_buf, term_buflen);
-                    term_buflen = 0;
-                }
-                break;
-              case CTRL('M'):         /* send with newline */
-                if (term_buflen > 0)
-                    back->send(term_buf, term_buflen);
-                if (cfg.protocol == PROT_RAW)
-                    back->send("\r\n", 2);
-                else
-                    back->send("\r", 1);
-                if (ECHOING)
-                    c_write("\r\n", 2);
-                term_buflen = 0;
-                break;
-              default:                     /* get to this label from ^V handler */
-                if (term_buflen >= term_bufsiz) {
-                    term_bufsiz = term_buflen + 256;
-                    term_buf = saferealloc(term_buf, term_bufsiz);
-                }
-                term_buf[term_buflen++] = c;
-                if (ECHOING)
-                    pwrite(c);
-                term_quotenext = FALSE;
-                break;
-            }
-        }
+       while (len--) {
+           char c;
+           c = *buf++;
+           switch (term_quotenext ? ' ' : c) {
+               /*
+                * ^h/^?: delete one char and output one BSB
+                * ^w: delete, and output BSBs, to return to last
+                * space/nonspace boundary
+                * ^u: delete, and output BSBs, to return to BOL
+                * ^c: Do a ^u then send a telnet IP
+                * ^z: Do a ^u then send a telnet SUSP
+                * ^\: Do a ^u then send a telnet ABORT
+                * ^r: echo "^R\n" and redraw line
+                * ^v: quote next char
+                * ^d: if at BOL, end of file and close connection,
+                * else send line and reset to BOL
+                * ^m: send line-plus-\r\n and reset to BOL
+                */
+             case CTRL('H'):
+             case CTRL('?'):          /* backspace/delete */
+               if (term_buflen > 0) {
+                   if (ECHOING)
+                       bsb(plen(term_buf[term_buflen - 1]));
+                   term_buflen--;
+               }
+               break;
+             case CTRL('W'):          /* delete word */
+               while (term_buflen > 0) {
+                   if (ECHOING)
+                       bsb(plen(term_buf[term_buflen - 1]));
+                   term_buflen--;
+                   if (term_buflen > 0 &&
+                       isspace(term_buf[term_buflen - 1]) &&
+                       !isspace(term_buf[term_buflen]))
+                       break;
+               }
+               break;
+             case CTRL('U'):          /* delete line */
+             case CTRL('C'):          /* Send IP */
+             case CTRL('\\'):         /* Quit */
+             case CTRL('Z'):          /* Suspend */
+               while (term_buflen > 0) {
+                   if (ECHOING)
+                       bsb(plen(term_buf[term_buflen - 1]));
+                   term_buflen--;
+               }
+               back->special(TS_EL);
+               if (c == CTRL('C'))
+                   back->special(TS_IP);
+               if (c == CTRL('Z'))
+                   back->special(TS_SUSP);
+               if (c == CTRL('\\'))
+                   back->special(TS_ABORT);
+               break;
+             case CTRL('R'):          /* redraw line */
+               if (ECHOING) {
+                   int i;
+                   c_write("^R\r\n", 4);
+                   for (i = 0; i < term_buflen; i++)
+                       pwrite(term_buf[i]);
+               }
+               break;
+             case CTRL('V'):          /* quote next char */
+               term_quotenext = TRUE;
+               break;
+             case CTRL('D'):          /* logout or send */
+               if (term_buflen == 0) {
+                   back->special(TS_EOF);
+               } else {
+                   back->send(term_buf, term_buflen);
+                   term_buflen = 0;
+               }
+               break;
+             case CTRL('M'):          /* send with newline */
+               if (term_buflen > 0)
+                   back->send(term_buf, term_buflen);
+               if (cfg.protocol == PROT_RAW)
+                   back->send("\r\n", 2);
+               else
+                   back->send("\r", 1);
+               if (ECHOING)
+                   c_write("\r\n", 2);
+               term_buflen = 0;
+               break;
+             default:                 /* get to this label from ^V handler */
+               if (term_buflen >= term_bufsiz) {
+                   term_bufsiz = term_buflen + 256;
+                   term_buf = saferealloc(term_buf, term_bufsiz);
+               }
+               term_buf[term_buflen++] = c;
+               if (ECHOING)
+                   pwrite(c);
+               term_quotenext = FALSE;
+               break;
+           }
+       }
     } else {
-        if( term_buflen != 0 )
-        {
-            back->send(term_buf, term_buflen);
-            while (term_buflen > 0) {
-                bsb(plen(term_buf[term_buflen-1]));
-                term_buflen--;
-            }
-        }
-        if (len > 0) {
-            if (ECHOING)
-                c_write(buf, len);
-            back->send(buf, len);
-        }
+       if (term_buflen != 0) {
+           back->send(term_buf, term_buflen);
+           while (term_buflen > 0) {
+               bsb(plen(term_buf[term_buflen - 1]));
+               term_buflen--;
+           }
+       }
+       if (len > 0) {
+           if (ECHOING)
+               c_write(buf, len);
+           back->send(buf, len);
+       }
     }
 }
diff --git a/misc.c b/misc.c
index c398c21..2fabbb6 100644 (file)
--- a/misc.c
+++ b/misc.c
@@ -43,21 +43,23 @@ static long minefield_curpos = 0;
 static unsigned short *minefield_admin = NULL;
 static void *minefield_pages = NULL;
 
-static void minefield_admin_hide(int hide) {
+static void minefield_admin_hide(int hide)
+{
     int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
-    VirtualProtect(minefield_admin, minefield_npages*2, access, NULL);
+    VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
 }
 
-static void minefield_init(void) {
+static void minefield_init(void)
+{
     int size;
     int admin_size;
     int i;
 
-    for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) &0xFFF) {
-        minefield_region = VirtualAlloc(NULL, size,
-                                        MEM_RESERVE, PAGE_NOACCESS);
-        if (minefield_region)
-            break;
+    for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
+       minefield_region = VirtualAlloc(NULL, size,
+                                       MEM_RESERVE, PAGE_NOACCESS);
+       if (minefield_region)
+           break;
     }
     minefield_size = size;
 
@@ -67,21 +69,21 @@ static void minefield_init(void) {
      */
     minefield_admin = minefield_region;
     minefield_npages = minefield_size / PAGESIZE;
-    admin_size = (minefield_npages * 2 + PAGESIZE-1) &~ (PAGESIZE-1);
+    admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
     minefield_npages = (minefield_size - admin_size) / PAGESIZE;
-    minefield_pages = (char *)minefield_region + admin_size;
+    minefield_pages = (char *) minefield_region + admin_size;
 
     /*
      * Commit the admin region.
      */
     VirtualAlloc(minefield_admin, minefield_npages * 2,
-                 MEM_COMMIT, PAGE_READWRITE);
+                MEM_COMMIT, PAGE_READWRITE);
 
     /*
      * Mark all pages as unused (0xFFFF).
      */
     for (i = 0; i < minefield_npages; i++)
-        minefield_admin[i] = 0xFFFF;
+       minefield_admin[i] = 0xFFFF;
 
     /*
      * Hide the admin region.
@@ -91,17 +93,19 @@ static void minefield_init(void) {
     minefield_initialised = 1;
 }
 
-static void minefield_bomb(void) {
-    div(1, *(int*)minefield_pages);
+static void minefield_bomb(void)
+{
+    div(1, *(int *) minefield_pages);
 }
 
-static void *minefield_alloc(int size) {
+static void *minefield_alloc(int size)
+{
     int npages;
     int pos, lim, region_end, region_start;
     int start;
     int i;
 
-    npages = (size + PAGESIZE-1) / PAGESIZE;
+    npages = (size + PAGESIZE - 1) / PAGESIZE;
 
     minefield_admin_hide(0);
 
@@ -112,96 +116,102 @@ static void *minefield_alloc(int size) {
     pos = minefield_curpos;
     lim = minefield_npages;
     while (1) {
-        /* Skip over used pages. */
-        while (pos < lim && minefield_admin[pos] != 0xFFFF)
-            pos++;
-        /* Count unused pages. */
-        start = pos;
-        while (pos < lim && pos - start < npages+2 &&
-               minefield_admin[pos] == 0xFFFF)
-            pos++;
-        if (pos - start == npages+2)
-            break;
-        /* If we've reached the limit, reset the limit or stop. */
-        if (pos >= lim) {
-            if (lim == minefield_npages) {
-                /* go round and start again at zero */
-                lim = minefield_curpos;
-                pos = 0;
-            } else {
-                minefield_admin_hide(1);
-                return NULL;
-            }
-        }
+       /* Skip over used pages. */
+       while (pos < lim && minefield_admin[pos] != 0xFFFF)
+           pos++;
+       /* Count unused pages. */
+       start = pos;
+       while (pos < lim && pos - start < npages + 2 &&
+              minefield_admin[pos] == 0xFFFF)
+           pos++;
+       if (pos - start == npages + 2)
+           break;
+       /* If we've reached the limit, reset the limit or stop. */
+       if (pos >= lim) {
+           if (lim == minefield_npages) {
+               /* go round and start again at zero */
+               lim = minefield_curpos;
+               pos = 0;
+           } else {
+               minefield_admin_hide(1);
+               return NULL;
+           }
+       }
     }
 
-    minefield_curpos = pos-1;
+    minefield_curpos = pos - 1;
 
     /*
      * We have npages+2 unused pages starting at start. We leave
      * the first and last of these alone and use the rest.
      */
-    region_end = (start + npages+1) * PAGESIZE;
+    region_end = (start + npages + 1) * PAGESIZE;
     region_start = region_end - size;
     /* FIXME: could align here if we wanted */
 
     /*
      * Update the admin region.
      */
-    for (i = start + 2; i < start + npages-1; i++)
-        minefield_admin[i] = 0xFFFE;   /* used but no region starts here */
-    minefield_admin[start+1] = region_start % PAGESIZE;
+    for (i = start + 2; i < start + npages - 1; i++)
+       minefield_admin[i] = 0xFFFE;   /* used but no region starts here */
+    minefield_admin[start + 1] = region_start % PAGESIZE;
 
     minefield_admin_hide(1);
 
-    VirtualAlloc((char *)minefield_pages + region_start, size,
-                 MEM_COMMIT, PAGE_READWRITE);
-    return (char *)minefield_pages + region_start;
+    VirtualAlloc((char *) minefield_pages + region_start, size,
+                MEM_COMMIT, PAGE_READWRITE);
+    return (char *) minefield_pages + region_start;
 }
 
-static void minefield_free(void *ptr) {
+static void minefield_free(void *ptr)
+{
     int region_start, i, j;
 
     minefield_admin_hide(0);
 
-    region_start = (char *)ptr - (char *)minefield_pages;
+    region_start = (char *) ptr - (char *) minefield_pages;
     i = region_start / PAGESIZE;
     if (i < 0 || i >= minefield_npages ||
-        minefield_admin[i] != region_start % PAGESIZE)
-        minefield_bomb();
+       minefield_admin[i] != region_start % PAGESIZE)
+       minefield_bomb();
     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
-        minefield_admin[j] = 0xFFFF;
+       minefield_admin[j] = 0xFFFF;
     }
 
-    VirtualFree(ptr, j*PAGESIZE - region_start, MEM_DECOMMIT);
+    VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
 
     minefield_admin_hide(1);
 }
 
-static int minefield_get_size(void *ptr) {
+static int minefield_get_size(void *ptr)
+{
     int region_start, i, j;
 
     minefield_admin_hide(0);
 
-    region_start = (char *)ptr - (char *)minefield_pages;
+    region_start = (char *) ptr - (char *) minefield_pages;
     i = region_start / PAGESIZE;
     if (i < 0 || i >= minefield_npages ||
-        minefield_admin[i] != region_start % PAGESIZE)
-        minefield_bomb();
+       minefield_admin[i] != region_start % PAGESIZE)
+       minefield_bomb();
     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
 
     minefield_admin_hide(1);
 
-    return j*PAGESIZE - region_start;
+    return j * PAGESIZE - region_start;
 }
 
-static void *minefield_c_malloc(size_t size) {
-    if (!minefield_initialised) minefield_init();
+static void *minefield_c_malloc(size_t size)
+{
+    if (!minefield_initialised)
+       minefield_init();
     return minefield_alloc(size);
 }
 
-static void minefield_c_free(void *p) {
-    if (!minefield_initialised) minefield_init();
+static void minefield_c_free(void *p)
+{
+    if (!minefield_initialised)
+       minefield_init();
     minefield_free(p);
 }
 
@@ -209,10 +219,12 @@ static void minefield_c_free(void *p) {
  * realloc _always_ moves the chunk, for rapid detection of code
  * that assumes it won't.
  */
-static void *minefield_c_realloc(void *p, size_t size) {
+static void *minefield_c_realloc(void *p, size_t size)
+{
     size_t oldsize;
     void *q;
-    if (!minefield_initialised) minefield_init();
+    if (!minefield_initialised)
+       minefield_init();
     q = minefield_alloc(size);
     oldsize = minefield_get_size(p);
     memcpy(q, p, (oldsize < size ? oldsize : size));
@@ -220,27 +232,29 @@ static void *minefield_c_realloc(void *p, size_t size) {
     return q;
 }
 
-#endif /* MINEFIELD */
+#endif                         /* MINEFIELD */
 
 #ifdef MALLOC_LOG
 static FILE *fp = NULL;
 
-void mlog(char *file, int line) {
+void mlog(char *file, int line)
+{
     if (!fp) {
        fp = fopen("putty_mem.log", "w");
        setvbuf(fp, NULL, _IONBF, BUFSIZ);
     }
     if (fp)
-       fprintf (fp, "%s:%d: ", file, line);
+       fprintf(fp, "%s:%d: ", file, line);
 }
 #endif
 
-void *safemalloc(size_t size) {
+void *safemalloc(size_t size)
+{
     void *p;
 #ifdef MINEFIELD
-    p = minefield_c_malloc (size);
+    p = minefield_c_malloc(size);
 #else
-    p = malloc (size);
+    p = malloc(size);
 #endif
     if (!p) {
        MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
@@ -254,19 +268,20 @@ void *safemalloc(size_t size) {
     return p;
 }
 
-void *saferealloc(void *ptr, size_t size) {
+void *saferealloc(void *ptr, size_t size)
+{
     void *p;
     if (!ptr) {
 #ifdef MINEFIELD
-       p = minefield_c_malloc (size);
+       p = minefield_c_malloc(size);
 #else
-       p = malloc (size);
+       p = malloc(size);
 #endif
     } else {
 #ifdef MINEFIELD
-       p = minefield_c_realloc (ptr, size);
+       p = minefield_c_realloc(ptr, size);
 #else
-       p = realloc (ptr, size);
+       p = realloc(ptr, size);
 #endif
     }
     if (!p) {
@@ -281,16 +296,17 @@ void *saferealloc(void *ptr, size_t size) {
     return p;
 }
 
-void safefree(void *ptr) {
+void safefree(void *ptr)
+{
     if (ptr) {
 #ifdef MALLOC_LOG
        if (fp)
            fprintf(fp, "free(%p)\n", ptr);
 #endif
 #ifdef MINEFIELD
-       minefield_c_free (ptr);
+       minefield_c_free(ptr);
 #else
-       free (ptr);
+       free(ptr);
 #endif
     }
 #ifdef MALLOC_LOG
@@ -303,7 +319,8 @@ void safefree(void *ptr) {
 static FILE *debug_fp = NULL;
 static int debug_got_console = 0;
 
-static void dputs (char *buf) {
+static void dputs(char *buf)
+{
     DWORD dw;
 
     if (!debug_got_console) {
@@ -314,56 +331,58 @@ static void dputs (char *buf) {
        debug_fp = fopen("debug.log", "w");
     }
 
-    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw, NULL);
+    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw,
+             NULL);
     fputs(buf, debug_fp);
     fflush(debug_fp);
 }
 
 
-void dprintf(char *fmt, ...) {
+void dprintf(char *fmt, ...)
+{
     char buf[2048];
     va_list ap;
 
     va_start(ap, fmt);
     vsprintf(buf, fmt, ap);
-    dputs (buf);
+    dputs(buf);
     va_end(ap);
 }
 
 
-void debug_memdump (void *buf, int len, int L) {
+void debug_memdump(void *buf, int len, int L)
+{
     int i;
     unsigned char *p = buf;
     char foo[17];
     if (L) {
        int delta;
-        dprintf ("\t%d (0x%x) bytes:\n", len, len);
+       dprintf("\t%d (0x%x) bytes:\n", len, len);
        delta = 15 & (int) p;
        p -= delta;
        len += delta;
     }
     for (; 0 < len; p += 16, len -= 16) {
-       dputs ("  ");
-       if (L) dprintf ("%p: ", p);
-       strcpy(foo, "................");   /* sixteen dots */
+       dputs("  ");
+       if (L)
+           dprintf("%p: ", p);
+       strcpy(foo, "................");        /* sixteen dots */
        for (i = 0; i < 16 && i < len; ++i) {
            if (&p[i] < (unsigned char *) buf) {
-               dputs ("   "); /* 3 spaces */
+               dputs("   ");          /* 3 spaces */
                foo[i] = ' ';
            } else {
-               dprintf (
-                   "%c%02.2x",
-                   &p[i] != (unsigned char *) buf && i % 4 ? '.' : ' ',
-                   p[i]
-               );
+               dprintf("%c%02.2x",
+                       &p[i] != (unsigned char *) buf
+                       && i % 4 ? '.' : ' ', p[i]
+                   );
                if (p[i] >= ' ' && p[i] <= '~')
-                   foo[i] = (char)p[i];
+                   foo[i] = (char) p[i];
            }
        }
        foo[i] = '\0';
-       dprintf("%*s%s\n", (16-i)*3+2, "", foo);
+       dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
     }
 }
 
-#endif /* def DEBUG */
-
+#endif                         /* def DEBUG */
diff --git a/misc.h b/misc.h
index 37b7311..754e9fe 100644 (file)
--- a/misc.h
+++ b/misc.h
@@ -19,7 +19,7 @@
 
 #ifdef DEBUG
 void dprintf(char *fmt, ...);
-void debug_memdump (void *buf, int len, int L);
+void debug_memdump(void *buf, int len, int L);
 #define debug(x) (dprintf x)
 #define dmemdump(buf,len) debug_memdump (buf, len, 0);
 #define dmemdumpl(buf,len) debug_memdump (buf, len, 1);
index e477781..9d110ac 100644 (file)
@@ -11,15 +11,14 @@ static HCRYPTKEY create_des_key(unsigned char *key);
 
 
 HCRYPTPROV hCryptProv;
-HCRYPTKEY hDESKey[2][3] = {{0,0,0},{0,0,0}}; /* global for now */
+HCRYPTKEY hDESKey[2][3] = { {0, 0, 0}, {0, 0, 0} };    /* global for now */
 
 
 /* use Microsoft Enhanced Cryptographic Service Provider */
 #define CSP MS_ENHANCED_PROV
 
 
-static BYTE PrivateKeyWithExponentOfOne[] =
-{
+static BYTE PrivateKeyWithExponentOfOne[] = {
     0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00,
     0x52, 0x53, 0x41, 0x32, 0x00, 0x02, 0x00, 0x00,
     0x01, 0x00, 0x00, 0x00, 0xAB, 0xEF, 0xFA, 0xC6,
@@ -73,33 +72,35 @@ static BYTE PrivateKeyWithExponentOfOne[] =
  * ---------------------------------------------------------*/
 
 
-int crypto_startup() {
-    if(CryptAcquireContext(&hCryptProv, "Putty", CSP, PROV_RSA_FULL,
-                          CRYPT_NEWKEYSET) == 0) {
-       if(GetLastError() == NTE_EXISTS) {
-           if(CryptAcquireContext(&hCryptProv, "Putty", CSP,
-                                  PROV_RSA_FULL, 0) == 0) {
-               return FALSE; /* failed to acquire context - probably
-                              * don't have high encryption installed! */
+int crypto_startup()
+{
+    if (CryptAcquireContext(&hCryptProv, "Putty", CSP, PROV_RSA_FULL,
+                           CRYPT_NEWKEYSET) == 0) {
+       if (GetLastError() == NTE_EXISTS) {
+           if (CryptAcquireContext(&hCryptProv, "Putty", CSP,
+                                   PROV_RSA_FULL, 0) == 0) {
+               return FALSE;          /* failed to acquire context - probably
+                                       * don't have high encryption installed! */
            }
        } else
-           return FALSE; /* failed to acquire context - probably
-                          * don't have high encryption installed! */
+           return FALSE;              /* failed to acquire context - probably
+                                       * don't have high encryption installed! */
     }
     return TRUE;
 }
 
 
-void crypto_wrapup() {
+void crypto_wrapup()
+{
     int i, j;
-    for(i=0; i<2; i++) {
-       for(j=0; j<3; j++) {
-           if(hDESKey[i][j])
+    for (i = 0; i < 2; i++) {
+       for (j = 0; j < 3; j++) {
+           if (hDESKey[i][j])
                CryptDestroyKey(hDESKey[i][j]);
            hDESKey[i][j] = 0;
        }
     }
-    if(hCryptProv)
+    if (hCryptProv)
        CryptReleaseContext(hCryptProv, 0);
     hCryptProv = 0;
 }
@@ -109,32 +110,40 @@ void crypto_wrapup() {
  * Random number functions                                  *
  * ---------------------------------------------------------*/
 
-int random_byte(void) {
+int random_byte(void)
+{
     unsigned char b;
-    if(!CryptGenRandom(hCryptProv, 1, &b))
+    if (!CryptGenRandom(hCryptProv, 1, &b))
        fatalbox("random number generator failure!");
     return b;
 }
 
-void random_add_noise(void *noise, int length) {
+void random_add_noise(void *noise, int length)
+{
     /* do nothing */
 }
-void random_init(void) {
+void random_init(void)
+{
     /* do nothing */
 }
-void random_get_savedata(void **data, int *len) {
+void random_get_savedata(void **data, int *len)
+{
     /* do nothing */
 }
-void noise_get_heavy(void (*func) (void *, int)) {
+void noise_get_heavy(void (*func) (void *, int))
+{
     /* do nothing */
 }
-void noise_get_light(void (*func) (void *, int)) {
+void noise_get_light(void (*func) (void *, int))
+{
     /* do nothing */
 }
-void noise_ultralight(DWORD data) {
+void noise_ultralight(DWORD data)
+{
     /* do nothing */
 }
-void random_save_seed(void) {
+void random_save_seed(void)
+{
     /* do nothing */
 }
 
@@ -144,24 +153,27 @@ void random_save_seed(void) {
  * ---------------------------------------------------------*/
 
 
-void MD5Init(struct MD5Context *ctx) {
-    if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx->hHash))
+void MD5Init(struct MD5Context *ctx)
+{
+    if (!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx->hHash))
        fatalbox("Error during CryptBeginHash!\n");
 }
 
 
 void MD5Update(struct MD5Context *ctx,
-              unsigned char const *buf, unsigned len) {
-    if(CryptHashData(ctx->hHash, buf, len, 0) == 0)
+              unsigned char const *buf, unsigned len)
+{
+    if (CryptHashData(ctx->hHash, buf, len, 0) == 0)
        fatalbox("Error during CryptHashSessionKey!\n");
 }
 
 
-void MD5Final(unsigned char digest[16], struct MD5Context *ctx) {
+void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
+{
     DWORD cb = 16;
-    if(CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &cb, 0) == 0)
+    if (CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &cb, 0) == 0)
        fatalbox("Error during CryptGetHashParam!\n");
-    if(ctx->hHash)
+    if (ctx->hHash)
        CryptDestroyHash(ctx->hHash);
     ctx->hHash = 0;
 }
@@ -172,7 +184,8 @@ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) {
  * ---------------------------------------------------------*/
 
 int makekey(unsigned char *data, struct RSAKey *result,
-           unsigned char **keystr) {
+           unsigned char **keystr)
+{
 
     unsigned char *p = data;
     int i;
@@ -180,38 +193,40 @@ int makekey(unsigned char *data, struct RSAKey *result,
 
     /* get size (bits) of modulus */
     result->bits = 0;
-    for(i=0; i<4; i++)
+    for (i = 0; i < 4; i++)
        result->bits = (result->bits << 8) + *p++;
 
     /* get size (bits) of public exponent */
     w = 0;
-    for (i=0; i<2; i++)
+    for (i = 0; i < 2; i++)
        w = (w << 8) + *p++;
-    b = (w+7)/8;   /* bits -> bytes */
+    b = (w + 7) / 8;                  /* bits -> bytes */
 
     /* convert exponent to DWORD */
     result->exponent = 0;
-    for (i=0; i<b; i++)
+    for (i = 0; i < b; i++)
        result->exponent = (result->exponent << 8) + *p++;
 
     /* get size (bits) of modulus */
     w = 0;
-    for (i=0; i<2; i++)
+    for (i = 0; i < 2; i++)
        w = (w << 8) + *p++;
-    result->bytes = b = (w+7)/8;   /* bits -> bytes */
+    result->bytes = b = (w + 7) / 8;   /* bits -> bytes */
 
     /* allocate buffer for modulus & copy it */
     result->modulus = malloc(b);
     memcpy(result->modulus, p, b);
 
     /* update callers pointer */
-    if (keystr) *keystr = p;       /* point at key string, second time */
+    if (keystr)
+       *keystr = p;                   /* point at key string, second time */
 
     return (p - data) + b;
 }
 
 
-void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {
+void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey)
+{
 
     int i;
     unsigned char *pKeybuf, *pKeyin;
@@ -223,35 +238,36 @@ void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {
     DWORD bufsize;
 
     /* allocate buffer for public key blob */
-    if((pBlob = malloc(sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) +
-                      rsakey->bytes)) == NULL)
+    if ((pBlob = malloc(sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) +
+                       rsakey->bytes)) == NULL)
        fatalbox("Out of memory");
 
     /* allocate buffer for message encryption block */
     bufsize = (length + rsakey->bytes) << 1;
-    if((buf = malloc(bufsize)) == NULL)
+    if ((buf = malloc(bufsize)) == NULL)
        fatalbox("Out of memory");
 
     /* construct public key blob from host public key */
-    pKeybuf = ((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC) +
+    pKeybuf = ((unsigned char *) pBlob) + sizeof(PUBLICKEYSTRUC) +
        sizeof(RSAPUBKEY);
-    pKeyin = ((unsigned char*)rsakey->modulus);
+    pKeyin = ((unsigned char *) rsakey->modulus);
     /* change big endian to little endian */
-    for(i=0; i<rsakey->bytes; i++)
-       pKeybuf[i] = pKeyin[rsakey->bytes-i-1];
+    for (i = 0; i < rsakey->bytes; i++)
+       pKeybuf[i] = pKeyin[rsakey->bytes - i - 1];
     pBlob->bType = PUBLICKEYBLOB;
     pBlob->bVersion = 0x02;
     pBlob->reserved = 0;
     pBlob->aiKeyAlg = CALG_RSA_KEYX;
-    pRPK = (RSAPUBKEY*)(((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC));
-    pRPK->magic = 0x31415352; /* "RSA1" */
+    pRPK =
+       (RSAPUBKEY *) (((unsigned char *) pBlob) + sizeof(PUBLICKEYSTRUC));
+    pRPK->magic = 0x31415352;         /* "RSA1" */
     pRPK->bitlen = rsakey->bits;
     pRPK->pubexp = rsakey->exponent;
 
     /* import public key blob into key container */
-    if(CryptImportKey(hCryptProv, (void*)pBlob,
-                     sizeof(PUBLICKEYSTRUC)+sizeof(RSAPUBKEY)+rsakey->bytes,
-                     0, 0, &hRsaKey) == 0)
+    if (CryptImportKey(hCryptProv, (void *) pBlob,
+                      sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) +
+                      rsakey->bytes, 0, 0, &hRsaKey) == 0)
        fatalbox("Error importing RSA key!");
 
     /* copy message into buffer */
@@ -259,7 +275,7 @@ void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {
     dlen = length;
 
     /* using host public key, encrypt the message */
-    if(CryptEncrypt(hRsaKey, 0, TRUE, 0, buf, &dlen, bufsize) == 0)
+    if (CryptEncrypt(hRsaKey, 0, TRUE, 0, buf, &dlen, bufsize) == 0)
        fatalbox("Error encrypting using RSA key!");
 
     /*
@@ -267,8 +283,8 @@ void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {
      * key, returns the cyphertext in backwards (little endian)
      * order, so reverse it!
      */
-    for(i = 0; i < (int)dlen; i++)
-       data[i] = buf[dlen - i - 1]; /* make it big endian */
+    for (i = 0; i < (int) dlen; i++)
+       data[i] = buf[dlen - i - 1];   /* make it big endian */
 
     CryptDestroyKey(hRsaKey);
     free(buf);
@@ -277,22 +293,24 @@ void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {
 }
 
 
-int rsastr_len(struct RSAKey *key) {
+int rsastr_len(struct RSAKey *key)
+{
     return 2 * (sizeof(DWORD) + key->bytes) + 10;
 }
 
 
-void rsastr_fmt(char *str, struct RSAKey *key) {
+void rsastr_fmt(char *str, struct RSAKey *key)
+{
 
     int len = 0, i;
 
-    sprintf(str+len, "%04x", key->exponent);
-    len += strlen(str+len);
+    sprintf(str + len, "%04x", key->exponent);
+    len += strlen(str + len);
 
     str[len++] = '/';
-    for (i=1; i<key->bytes; i++) {
-       sprintf(str+len, "%02x", key->modulus[i]);
-       len += strlen(str+len);
+    for (i = 1; i < key->bytes; i++) {
+       sprintf(str + len, "%02x", key->modulus[i]);
+       len += strlen(str + len);
     }
     str[len] = '\0';
 }
@@ -304,39 +322,42 @@ void rsastr_fmt(char *str, struct RSAKey *key) {
  * ---------------------------------------------------------*/
 
 
-void des3_sesskey(unsigned char *key) {
+void des3_sesskey(unsigned char *key)
+{
     int i, j;
-    for(i = 0; i < 2; i++) {
-       for(j = 0; j < 3; j++) {
+    for (i = 0; i < 2; i++) {
+       for (j = 0; j < 3; j++) {
            hDESKey[i][j] = create_des_key(key + (j * 8));
        }
     }
 }
 
 
-void des3_encrypt_blk(unsigned char *blk, int len) {
+void des3_encrypt_blk(unsigned char *blk, int len)
+{
 
     DWORD dlen;
     dlen = len;
 
-    if(CryptEncrypt(hDESKey[0][0], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
+    if (CryptEncrypt(hDESKey[0][0], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
        fatalbox("Error encrypting block!\n");
-    if(CryptDecrypt(hDESKey[0][1], 0, FALSE, 0, blk, &dlen) == 0)
+    if (CryptDecrypt(hDESKey[0][1], 0, FALSE, 0, blk, &dlen) == 0)
        fatalbox("Error encrypting block!\n");
-    if(CryptEncrypt(hDESKey[0][2], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
+    if (CryptEncrypt(hDESKey[0][2], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
        fatalbox("Error encrypting block!\n");
 }
 
 
-void des3_decrypt_blk(unsigned char *blk, int len) {
+void des3_decrypt_blk(unsigned char *blk, int len)
+{
     DWORD dlen;
     dlen = len;
 
-    if(CryptDecrypt(hDESKey[1][2], 0, FALSE, 0, blk, &dlen) == 0)
+    if (CryptDecrypt(hDESKey[1][2], 0, FALSE, 0, blk, &dlen) == 0)
        fatalbox("Error decrypting block!\n");
-    if(CryptEncrypt(hDESKey[1][1], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
+    if (CryptEncrypt(hDESKey[1][1], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
        fatalbox("Error decrypting block!\n");
-    if(CryptDecrypt(hDESKey[1][0], 0, FALSE, 0, blk, &dlen) == 0)
+    if (CryptDecrypt(hDESKey[1][0], 0, FALSE, 0, blk, &dlen) == 0)
        fatalbox("Error decrypting block!\n");
 }
 
@@ -348,26 +369,29 @@ struct ssh_cipher ssh_3des = {
 };
 
 
-void des_sesskey(unsigned char *key) {
+void des_sesskey(unsigned char *key)
+{
     int i;
-    for(i = 0; i < 2; i++) {
+    for (i = 0; i < 2; i++) {
        hDESKey[i][0] = create_des_key(key);
     }
 }
 
 
-void des_encrypt_blk(unsigned char *blk, int len) {
+void des_encrypt_blk(unsigned char *blk, int len)
+{
     DWORD dlen;
     dlen = len;
-    if(CryptEncrypt(hDESKey[0][0], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
+    if (CryptEncrypt(hDESKey[0][0], 0, FALSE, 0, blk, &dlen, len + 8) == 0)
        fatalbox("Error encrypting block!\n");
 }
 
 
-void des_decrypt_blk(unsigned char *blk, int len) {
+void des_decrypt_blk(unsigned char *blk, int len)
+{
     DWORD dlen;
     dlen = len;
-    if(CryptDecrypt(hDESKey[1][0], 0, FALSE, 0, blk, &dlen) == 0)
+    if (CryptDecrypt(hDESKey[1][0], 0, FALSE, 0, blk, &dlen) == 0)
        fatalbox("Error decrypting block!\n");
 }
 
@@ -378,7 +402,8 @@ struct ssh_cipher ssh_des = {
 };
 
 
-static HCRYPTKEY create_des_key(unsigned char *key) {
+static HCRYPTKEY create_des_key(unsigned char *key)
+{
 
     HCRYPTKEY hSessionKey, hPrivateKey;
     DWORD dlen = 8;
@@ -390,33 +415,33 @@ static HCRYPTKEY create_des_key(unsigned char *key) {
      * import session key, since only encrypted session keys can be
      * imported
      */
-    if(CryptImportKey(hCryptProv, PrivateKeyWithExponentOfOne,
-                     sizeof(PrivateKeyWithExponentOfOne),
-                     0, 0, &hPrivateKey) == 0)
+    if (CryptImportKey(hCryptProv, PrivateKeyWithExponentOfOne,
+                      sizeof(PrivateKeyWithExponentOfOne),
+                      0, 0, &hPrivateKey) == 0)
        return 0;
 
     /* now encrypt session key using special private key */
     memcpy(buf + sizeof(BLOBHEADER) + sizeof(ALG_ID), key, 8);
-    if(CryptEncrypt(hPrivateKey, 0, TRUE, 0,
-                   buf + sizeof(BLOBHEADER) + sizeof(ALG_ID),
-                   &dlen, 256) == 0)
+    if (CryptEncrypt(hPrivateKey, 0, TRUE, 0,
+                    buf + sizeof(BLOBHEADER) + sizeof(ALG_ID),
+                    &dlen, 256) == 0)
        return 0;
 
     /* build session key blob */
-    pbh = (BLOBHEADER*)buf;
+    pbh = (BLOBHEADER *) buf;
     pbh->bType = SIMPLEBLOB;
     pbh->bVersion = 0x02;
     pbh->reserved = 0;
     pbh->aiKeyAlg = CALG_DES;
-    *((ALG_ID*)(buf+sizeof(BLOBHEADER))) = CALG_RSA_KEYX;
+    *((ALG_ID *) (buf + sizeof(BLOBHEADER))) = CALG_RSA_KEYX;
 
     /* import session key into key container */
-    if(CryptImportKey(hCryptProv, buf,
-                     dlen + sizeof(BLOBHEADER) + sizeof(ALG_ID),
-                     hPrivateKey, 0, &hSessionKey) == 0)
+    if (CryptImportKey(hCryptProv, buf,
+                      dlen + sizeof(BLOBHEADER) + sizeof(ALG_ID),
+                      hPrivateKey, 0, &hSessionKey) == 0)
        return 0;
 
-    if(hPrivateKey)
+    if (hPrivateKey)
        CryptDestroyKey(hPrivateKey);
 
     return hSessionKey;
index f8b81a3..e4bb578 100644 (file)
--- a/network.h
+++ b/network.h
@@ -19,35 +19,35 @@ typedef struct socket_function_table **Socket;
 typedef struct plug_function_table **Plug;
 
 struct socket_function_table {
-    Plug (*plug) (Socket s, Plug p);
-       /* use a different plug (return the old one) */
-       /* if p is NULL, it doesn't change the plug */
-       /* but it does return the one it's using */
+    Plug(*plug) (Socket s, Plug p);
+    /* use a different plug (return the old one) */
+    /* if p is NULL, it doesn't change the plug */
+    /* but it does return the one it's using */
     void (*close) (Socket s);
     void (*write) (Socket s, char *data, int len);
     void (*write_oob) (Socket s, char *data, int len);
     void (*flush) (Socket s);
-       /* ignored by tcp, but vital for ssl */
+    /* ignored by tcp, but vital for ssl */
     char *(*socket_error) (Socket s);
 };
 
 struct plug_function_table {
     int (*closing)
-       (Plug p, char *error_msg, int error_code, int calling_back);
-       /* error_msg is NULL iff it is not an error (ie it closed normally) */
-       /* calling_back != 0 iff there is a Plug function */
-       /* currently running (would cure the fixme in try_send()) */
+     (Plug p, char *error_msg, int error_code, int calling_back);
+    /* error_msg is NULL iff it is not an error (ie it closed normally) */
+    /* calling_back != 0 iff there is a Plug function */
+    /* currently running (would cure the fixme in try_send()) */
     int (*receive) (Plug p, int urgent, char *data, int len);
-       /*
-        *  - urgent==0. `data' points to `len' bytes of perfectly
-        *    ordinary data.
-        
-        *  - urgent==1. `data' points to `len' bytes of data,
-        *    which were read from before an Urgent pointer.
-        
-        *  - urgent==2. `data' points to `len' bytes of data,
-        *    the first of which was the one at the Urgent mark.
-        */
+    /*
+     *  - urgent==0. `data' points to `len' bytes of perfectly
+     *    ordinary data.
+     * 
+     *  - urgent==1. `data' points to `len' bytes of data,
+     *    which were read from before an Urgent pointer.
+     * 
+     *  - urgent==2. `data' points to `len' bytes of data,
+     *    the first of which was the one at the Urgent mark.
+     */
 };
 
 
@@ -56,7 +56,8 @@ void sk_init(void);                  /* called once at program startup */
 SockAddr sk_namelookup(char *host, char **canonicalname);
 void sk_addr_free(SockAddr addr);
 
-Socket sk_new(SockAddr addr, int port, int privport, int oobinline, Plug p);
+Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
+             Plug p);
 
 #define sk_plug(s,p) (((*s)->plug) (s, p))
 #define sk_close(s) (((*s)->close) (s))
@@ -106,24 +107,22 @@ typedef struct ssl_client_plug_function_table **SSL_Client_Plug;
 struct ssl_client_socket_function_table {
     struct socket_function_table base;
     void (*renegotiate) (SSL_Client_Socket s);
-       /* renegotiate the cipher spec */
+    /* renegotiate the cipher spec */
 };
 
 struct ssl_client_plug_function_table {
     struct plug_function_table base;
     int (*refuse_cert) (SSL_Client_Plug p, Certificate cert[]);
-       /* do we accept this certificate chain?  If not, why not? */
-       /* cert[0] is the server's certificate, cert[] is NULL-terminated */
-       /* the last certificate may or may not be the root certificate */
-    Our_Certificate (*client_cert) (SSL_Client_Plug p);
-       /* the server wants us to identify ourselves */
-       /* may return NULL if we want anonymity */
+    /* do we accept this certificate chain?  If not, why not? */
+    /* cert[0] is the server's certificate, cert[] is NULL-terminated */
+    /* the last certificate may or may not be the root certificate */
+     Our_Certificate(*client_cert) (SSL_Client_Plug p);
+    /* the server wants us to identify ourselves */
+    /* may return NULL if we want anonymity */
 };
 
-SSL_Client_Socket sk_ssl_client_over (
-    Socket s, /* pre-existing (tcp) connection */
-    SSL_Client_Plug p
-);
+SSL_Client_Socket sk_ssl_client_over(Socket s, /* pre-existing (tcp) connection */
+                                    SSL_Client_Plug p);
 
 #define sk_renegotiate(s) (((*s)->renegotiate) (s))
 
diff --git a/noise.c b/noise.c
index c5966a7..856974b 100644 (file)
--- a/noise.c
+++ b/noise.c
@@ -13,7 +13,7 @@
 /*
  * GetSystemPowerStatus function.
  */
-typedef BOOL (WINAPI *gsps_t)(LPSYSTEM_POWER_STATUS);
+typedef BOOL(WINAPI * gsps_t) (LPSYSTEM_POWER_STATUS);
 static gsps_t gsps;
 
 /*
@@ -22,10 +22,11 @@ static gsps_t gsps;
  * free space and a process snapshot.
  */
 
-void noise_get_heavy(void (*func) (void *, int)) {
+void noise_get_heavy(void (*func) (void *, int))
+{
     HANDLE srch;
     WIN32_FIND_DATA finddata;
-    char winpath[MAX_PATH+3];
+    char winpath[MAX_PATH + 3];
     HMODULE mod;
 
     GetWindowsDirectory(winpath, sizeof(winpath));
@@ -43,11 +44,12 @@ void noise_get_heavy(void (*func) (void *, int)) {
     gsps = NULL;
     mod = GetModuleHandle("KERNEL32");
     if (mod) {
-        gsps = (gsps_t)GetProcAddress(mod, "GetSystemPowerStatus");
+       gsps = (gsps_t) GetProcAddress(mod, "GetSystemPowerStatus");
     }
 }
 
-void random_save_seed(void) {
+void random_save_seed(void)
+{
     int len;
     void *data;
 
@@ -60,7 +62,8 @@ void random_save_seed(void) {
  * stirring, and will acquire the system time in all available
  * forms and the battery status.
  */
-void noise_get_light(void (*func) (void *, int)) {
+void noise_get_light(void (*func) (void *, int))
+{
     SYSTEMTIME systime;
     DWORD adjust[2];
     BOOL rubbish;
@@ -76,8 +79,8 @@ void noise_get_light(void (*func) (void *, int)) {
      * Call GetSystemPowerStatus if present.
      */
     if (gsps) {
-        if (gsps(&pwrstat))
-            func(&pwrstat, sizeof(pwrstat));
+       if (gsps(&pwrstat))
+           func(&pwrstat, sizeof(pwrstat));
     }
 }
 
@@ -87,25 +90,34 @@ void noise_get_light(void (*func) (void *, int)) {
  * virtual memory, the state of the process's message queue, which
  * window is in the foreground, which owns the clipboard, etc.
  */
-void noise_regular(void) {
+void noise_regular(void)
+{
     HWND w;
     DWORD z;
     POINT pt;
     MEMORYSTATUS memstat;
     FILETIME times[4];
 
-    w = GetForegroundWindow(); random_add_noise(&w, sizeof(w));
-    w = GetCapture(); random_add_noise(&w, sizeof(w));
-    w = GetClipboardOwner(); random_add_noise(&w, sizeof(w));
-    z = GetQueueStatus(QS_ALLEVENTS); random_add_noise(&z, sizeof(z));
+    w = GetForegroundWindow();
+    random_add_noise(&w, sizeof(w));
+    w = GetCapture();
+    random_add_noise(&w, sizeof(w));
+    w = GetClipboardOwner();
+    random_add_noise(&w, sizeof(w));
+    z = GetQueueStatus(QS_ALLEVENTS);
+    random_add_noise(&z, sizeof(z));
 
-    GetCursorPos(&pt); random_add_noise(&pt, sizeof(pt));
+    GetCursorPos(&pt);
+    random_add_noise(&pt, sizeof(pt));
 
-    GlobalMemoryStatus(&memstat); random_add_noise(&memstat, sizeof(memstat));
+    GlobalMemoryStatus(&memstat);
+    random_add_noise(&memstat, sizeof(memstat));
 
-    GetThreadTimes(GetCurrentThread(), times, times+1, times+2, times+3);
+    GetThreadTimes(GetCurrentThread(), times, times + 1, times + 2,
+                  times + 3);
     random_add_noise(&times, sizeof(times));
-    GetProcessTimes(GetCurrentProcess(), times, times+1, times+2, times+3);
+    GetProcessTimes(GetCurrentProcess(), times, times + 1, times + 2,
+                   times + 3);
     random_add_noise(&times, sizeof(times));
 }
 
@@ -115,7 +127,8 @@ void noise_regular(void) {
  * counter to the noise pool. It gets the scan code or mouse
  * position passed in.
  */
-void noise_ultralight(DWORD data) {
+void noise_ultralight(DWORD data)
+{
     DWORD wintime;
     LARGE_INTEGER perftime;
 
index 50ac337..0605b4b 100644 (file)
--- a/pageant.c
+++ b/pageant.c
@@ -48,10 +48,9 @@ static tree234 *rsakeys, *ssh2keys;
 
 static int has_security;
 #ifndef NO_SECURITY
-typedef DWORD (WINAPI *gsi_fn_t)
-    (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
-                                 PSID *, PSID *, PACL *, PACL *,
-                                 PSECURITY_DESCRIPTOR *);
+typedef DWORD(WINAPI * gsi_fn_t)
+ (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
+  PSID *, PSID *, PACL *, PACL *, PSECURITY_DESCRIPTOR *);
 static gsi_fn_t getsecurityinfo;
 #endif
 
@@ -71,7 +70,8 @@ int agent_exists(void);
  * won't generate true random numbers. So we must scream, panic,
  * and exit immediately if that should happen.
  */
-int random_byte(void) {
+int random_byte(void)
+{
     MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
     exit(0);
 }
@@ -90,7 +90,8 @@ static int cmpkeys_ssh2_asymm(void *av, void *bv);
  * This function is needed to link with the DES code. We need not
  * have it do anything at all.
  */
-void logevent(char *msg) {
+void logevent(char *msg)
+{
 }
 
 #define GET_32BIT(cp) \
@@ -115,15 +116,16 @@ struct PassphraseProcStruct {
 /*
  * Dialog-box function for the Licence box.
  */
-static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
-                                WPARAM wParam, LPARAM lParam) {
+static int CALLBACK LicenceProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
-            EndDialog(hwnd, 1);
+           EndDialog(hwnd, 1);
            return 0;
        }
        return 0;
@@ -137,29 +139,30 @@ static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
 /*
  * Dialog-box function for the About box.
  */
-static int CALLBACK AboutProc (HWND hwnd, UINT msg,
-                              WPARAM wParam, LPARAM lParam) {
+static int CALLBACK AboutProc(HWND hwnd, UINT msg,
+                             WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
-        SetDlgItemText (hwnd, 100, ver);
+       SetDlgItemText(hwnd, 100, ver);
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
            aboutbox = NULL;
-           DestroyWindow (hwnd);
+           DestroyWindow(hwnd);
            return 0;
          case 101:
            EnableWindow(hwnd, 0);
-           DialogBox (instance, MAKEINTRESOURCE(214), NULL, LicenceProc);
+           DialogBox(instance, MAKEINTRESOURCE(214), NULL, LicenceProc);
            EnableWindow(hwnd, 1);
-            SetActiveWindow(hwnd);
+           SetActiveWindow(hwnd);
            return 0;
        }
        return 0;
       case WM_CLOSE:
        aboutbox = NULL;
-       DestroyWindow (hwnd);
+       DestroyWindow(hwnd);
        return 0;
     }
     return 0;
@@ -169,7 +172,8 @@ static int CALLBACK AboutProc (HWND hwnd, UINT msg,
  * Dialog-box function for the passphrase box.
  */
 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
-                                   WPARAM wParam, LPARAM lParam) {
+                                  WPARAM wParam, LPARAM lParam)
+{
     static char *passphrase = NULL;
     struct PassphraseProcStruct *p;
 
@@ -183,43 +187,45 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        SetForegroundWindow(hwnd);
-        SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
-                      SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
-        p = (struct PassphraseProcStruct *)lParam;
-        passphrase = p->passphrase;
-        if (p->comment)
-            SetDlgItemText(hwnd, 101, p->comment);
-        *passphrase = 0;
-        SetDlgItemText (hwnd, 102, passphrase);
-        return 0;
+       SetForegroundWindow(hwnd);
+       SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
+                    SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
+       p = (struct PassphraseProcStruct *) lParam;
+       passphrase = p->passphrase;
+       if (p->comment)
+           SetDlgItemText(hwnd, 101, p->comment);
+       *passphrase = 0;
+       SetDlgItemText(hwnd, 102, passphrase);
+       return 0;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
            if (*passphrase)
-               EndDialog (hwnd, 1);
+               EndDialog(hwnd, 1);
            else
-               MessageBeep (0);
+               MessageBeep(0);
            return 0;
          case IDCANCEL:
-           EndDialog (hwnd, 0);
+           EndDialog(hwnd, 0);
            return 0;
-          case 102:                    /* edit box */
+         case 102:                    /* edit box */
            if ((HIWORD(wParam) == EN_CHANGE) && passphrase) {
-                GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
-                passphrase[PASSPHRASE_MAXLEN-1] = '\0';
-            }
-            return 0;
+               GetDlgItemText(hwnd, 102, passphrase,
+                              PASSPHRASE_MAXLEN - 1);
+               passphrase[PASSPHRASE_MAXLEN - 1] = '\0';
+           }
+           return 0;
        }
        return 0;
       case WM_CLOSE:
-       EndDialog (hwnd, 0);
+       EndDialog(hwnd, 0);
        return 0;
     }
     return 0;
@@ -228,54 +234,65 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
 /*
  * Update the visible key list.
  */
-static void keylist_update(void) {
+static void keylist_update(void)
+{
     struct RSAKey *rkey;
     struct ssh2_userkey *skey;
     int i;
 
     if (keylist) {
-        SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0);
-        for (i = 0; NULL != (rkey = index234(rsakeys, i)); i++) {
-            char listentry[512], *p;
-            /*
-             * Replace two spaces in the fingerprint with tabs, for
-             * nice alignment in the box.
-             */
+       SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0);
+       for (i = 0; NULL != (rkey = index234(rsakeys, i)); i++) {
+           char listentry[512], *p;
+           /*
+            * Replace two spaces in the fingerprint with tabs, for
+            * nice alignment in the box.
+            */
            strcpy(listentry, "ssh1\t");
-           p = listentry+strlen(listentry);
-            rsa_fingerprint(p, sizeof(listentry)-(p-listentry), rkey);
-            p = strchr(listentry, ' '); if (p) *p = '\t';
-            p = strchr(listentry, ' '); if (p) *p = '\t';
-            SendDlgItemMessage (keylist, 100, LB_ADDSTRING,
-                                0, (LPARAM)listentry);
-        }
-        for (i = 0; NULL != (skey = index234(ssh2keys, i)); i++) {
-            char listentry[512], *p;
+           p = listentry + strlen(listentry);
+           rsa_fingerprint(p, sizeof(listentry) - (p - listentry), rkey);
+           p = strchr(listentry, ' ');
+           if (p)
+               *p = '\t';
+           p = strchr(listentry, ' ');
+           if (p)
+               *p = '\t';
+           SendDlgItemMessage(keylist, 100, LB_ADDSTRING,
+                              0, (LPARAM) listentry);
+       }
+       for (i = 0; NULL != (skey = index234(ssh2keys, i)); i++) {
+           char listentry[512], *p;
            int len;
-            /*
-             * Replace two spaces in the fingerprint with tabs, for
-             * nice alignment in the box.
-             */
+           /*
+            * Replace two spaces in the fingerprint with tabs, for
+            * nice alignment in the box.
+            */
            p = skey->alg->fingerprint(skey->data);
            strncpy(listentry, p, sizeof(listentry));
-            p = strchr(listentry, ' '); if (p) *p = '\t';
-            p = strchr(listentry, ' '); if (p) *p = '\t';
+           p = strchr(listentry, ' ');
+           if (p)
+               *p = '\t';
+           p = strchr(listentry, ' ');
+           if (p)
+               *p = '\t';
            len = strlen(listentry);
-           if (len < sizeof(listentry)-2) {
+           if (len < sizeof(listentry) - 2) {
                listentry[len] = '\t';
-               strncpy(listentry+len+1, skey->comment, sizeof(listentry)-len-1);
+               strncpy(listentry + len + 1, skey->comment,
+                       sizeof(listentry) - len - 1);
            }
-            SendDlgItemMessage (keylist, 100, LB_ADDSTRING,
-                                0, (LPARAM)listentry);
-        }
-        SendDlgItemMessage (keylist, 100, LB_SETCURSEL, (WPARAM) -1, 0);
+           SendDlgItemMessage(keylist, 100, LB_ADDSTRING, 0,
+                              (LPARAM) listentry);
+       }
+       SendDlgItemMessage(keylist, 100, LB_SETCURSEL, (WPARAM) - 1, 0);
     }
 }
 
 /*
  * This function loads a key from a file and adds it.
  */
-static void add_keyfile(char *filename) {
+static void add_keyfile(char *filename)
+{
     char passphrase[PASSPHRASE_MAXLEN];
     struct RSAKey *rkey;
     struct ssh2_userkey *skey;
@@ -288,9 +305,9 @@ static void add_keyfile(char *filename) {
 
     ver = keyfile_version(filename);
     if (ver == 0) {
-        MessageBox(NULL, "Couldn't load private key.", APPNAME,
-                   MB_OK | MB_ICONERROR);
-        return;
+       MessageBox(NULL, "Couldn't load private key.", APPNAME,
+                  MB_OK | MB_ICONERROR);
+       return;
     }
 
     if (ver == 1)
@@ -303,19 +320,19 @@ static void add_keyfile(char *filename) {
     pps.passphrase = passphrase;
     pps.comment = comment;
     do {
-        if (needs_pass) {
-            int dlgret;
-            dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
-                                    NULL, PassphraseProc,
-                                    (LPARAM)&pps);
-            if (!dlgret) {
-                if (comment) sfree(comment);
-                if (ver == 1)
+       if (needs_pass) {
+           int dlgret;
+           dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
+                                   NULL, PassphraseProc, (LPARAM) & pps);
+           if (!dlgret) {
+               if (comment)
+                   sfree(comment);
+               if (ver == 1)
                    sfree(rkey);
-                return;                /* operation cancelled */
-            }
-        } else
-            *passphrase = '\0';
+               return;                /* operation cancelled */
+           }
+       } else
+           *passphrase = '\0';
        if (ver == 1)
            ret = loadrsakey(filename, rkey, passphrase);
        else {
@@ -327,15 +344,16 @@ static void add_keyfile(char *filename) {
            else
                ret = 1;
        }
-        attempts++;
+       attempts++;
     } while (ret == -1);
-    if (comment) sfree(comment);
+    if (comment)
+       sfree(comment);
     if (ret == 0) {
-        MessageBox(NULL, "Couldn't load private key.", APPNAME,
-                   MB_OK | MB_ICONERROR);
-        if (ver == 1)
+       MessageBox(NULL, "Couldn't load private key.", APPNAME,
+                  MB_OK | MB_ICONERROR);
+       if (ver == 1)
            sfree(rkey);
-        return;
+       return;
     }
     if (ver == 1) {
        if (already_running) {
@@ -351,26 +369,27 @@ static void add_keyfile(char *filename) {
                ssh1_bignum_length(rkey->private_exponent) +
                ssh1_bignum_length(rkey->iqmp) +
                ssh1_bignum_length(rkey->p) +
-               ssh1_bignum_length(rkey->q) +
-               4 + clen               /* comment */
+               ssh1_bignum_length(rkey->q) + 4 + clen  /* comment */
                ;
 
            request = smalloc(reqlen);
 
            request[4] = SSH1_AGENTC_ADD_RSA_IDENTITY;
            reqlen = 5;
-           PUT_32BIT(request+reqlen, bignum_bitcount(rkey->modulus));
+           PUT_32BIT(request + reqlen, bignum_bitcount(rkey->modulus));
            reqlen += 4;
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->modulus);
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->exponent);
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->private_exponent);
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->iqmp);
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->p);
-           reqlen += ssh1_write_bignum(request+reqlen, rkey->q);
-           PUT_32BIT(request+reqlen, clen);
-           memcpy(request+reqlen+4, rkey->comment, clen);
-           reqlen += 4+clen;
-           PUT_32BIT(request, reqlen-4);
+           reqlen += ssh1_write_bignum(request + reqlen, rkey->modulus);
+           reqlen += ssh1_write_bignum(request + reqlen, rkey->exponent);
+           reqlen +=
+               ssh1_write_bignum(request + reqlen,
+                                 rkey->private_exponent);
+           reqlen += ssh1_write_bignum(request + reqlen, rkey->iqmp);
+           reqlen += ssh1_write_bignum(request + reqlen, rkey->p);
+           reqlen += ssh1_write_bignum(request + reqlen, rkey->q);
+           PUT_32BIT(request + reqlen, clen);
+           memcpy(request + reqlen + 4, rkey->comment, clen);
+           reqlen += 4 + clen;
+           PUT_32BIT(request, reqlen - 4);
 
            agent_query(request, reqlen, &response, &resplen);
            if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS)
@@ -400,16 +419,17 @@ static void add_keyfile(char *filename) {
 
            request[4] = SSH2_AGENTC_ADD_IDENTITY;
            reqlen = 5;
-           PUT_32BIT(request+reqlen, alglen);
+           PUT_32BIT(request + reqlen, alglen);
            reqlen += 4;
-           memcpy(request+reqlen, skey->alg->name, alglen);
+           memcpy(request + reqlen, skey->alg->name, alglen);
            reqlen += alglen;
            reqlen += skey->alg->openssh_fmtkey(skey->data,
-                                               request+reqlen, keybloblen);
-           PUT_32BIT(request+reqlen, clen);
-           memcpy(request+reqlen+4, skey->comment, clen);
-           PUT_32BIT(request, reqlen-4);
-           reqlen += clen+4;
+                                               request + reqlen,
+                                               keybloblen);
+           PUT_32BIT(request + reqlen, clen);
+           memcpy(request + reqlen + 4, skey->comment, clen);
+           PUT_32BIT(request, reqlen - 4);
+           reqlen += clen + 4;
 
            agent_query(request, reqlen, &response, &resplen);
            if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS)
@@ -428,7 +448,8 @@ static void add_keyfile(char *filename) {
 /*
  * This is the main agent function that answers messages.
  */
-static void answer_msg(void *msg) {
+static void answer_msg(void *msg)
+{
     unsigned char *p = msg;
     unsigned char *ret = msg;
     int type;
@@ -441,150 +462,151 @@ static void answer_msg(void *msg) {
     p += 5;
     switch (type) {
       case SSH1_AGENTC_REQUEST_RSA_IDENTITIES:
-        /*
-         * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER.
-         */
-        {
-            struct RSAKey *key;
-            int len, nkeys;
+       /*
+        * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER.
+        */
+       {
+           struct RSAKey *key;
+           int len, nkeys;
            int i;
 
-            /*
-             * Count up the number and length of keys we hold.
-             */
-            len = nkeys = 0;
-            for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
-                nkeys++;
-                len += 4;              /* length field */
-                len += ssh1_bignum_length(key->exponent);
-                len += ssh1_bignum_length(key->modulus);
-                len += 4 + strlen(key->comment);
-            }
-
-            /*
-             * Packet header is the obvious five bytes, plus four
-             * bytes for the key count.
-             */
-            len += 5 + 4;
-            if (len > AGENT_MAX_MSGLEN)
-                goto failure;          /* aaargh! too much stuff! */
-            PUT_32BIT(ret, len-4);
-            ret[4] = SSH1_AGENT_RSA_IDENTITIES_ANSWER;
-            PUT_32BIT(ret+5, nkeys);
-            p = ret + 5 + 4;
-            for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
-                PUT_32BIT(p, bignum_bitcount(key->modulus));
-                p += 4;
-                p += ssh1_write_bignum(p, key->exponent);
-                p += ssh1_write_bignum(p, key->modulus);
-                PUT_32BIT(p, strlen(key->comment));
-                memcpy(p+4, key->comment, strlen(key->comment));
-                p += 4 + strlen(key->comment);
-            }
-        }
-        break;
+           /*
+            * Count up the number and length of keys we hold.
+            */
+           len = nkeys = 0;
+           for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
+               nkeys++;
+               len += 4;              /* length field */
+               len += ssh1_bignum_length(key->exponent);
+               len += ssh1_bignum_length(key->modulus);
+               len += 4 + strlen(key->comment);
+           }
+
+           /*
+            * Packet header is the obvious five bytes, plus four
+            * bytes for the key count.
+            */
+           len += 5 + 4;
+           if (len > AGENT_MAX_MSGLEN)
+               goto failure;          /* aaargh! too much stuff! */
+           PUT_32BIT(ret, len - 4);
+           ret[4] = SSH1_AGENT_RSA_IDENTITIES_ANSWER;
+           PUT_32BIT(ret + 5, nkeys);
+           p = ret + 5 + 4;
+           for (i = 0; NULL != (key = index234(rsakeys, i)); i++) {
+               PUT_32BIT(p, bignum_bitcount(key->modulus));
+               p += 4;
+               p += ssh1_write_bignum(p, key->exponent);
+               p += ssh1_write_bignum(p, key->modulus);
+               PUT_32BIT(p, strlen(key->comment));
+               memcpy(p + 4, key->comment, strlen(key->comment));
+               p += 4 + strlen(key->comment);
+           }
+       }
+       break;
       case SSH2_AGENTC_REQUEST_IDENTITIES:
-        /*
-         * Reply with SSH2_AGENT_IDENTITIES_ANSWER.
-         */
-        {
-            struct ssh2_userkey *key;
-            int len, nkeys;
+       /*
+        * Reply with SSH2_AGENT_IDENTITIES_ANSWER.
+        */
+       {
+           struct ssh2_userkey *key;
+           int len, nkeys;
            unsigned char *blob;
            int bloblen;
            int i;
 
-            /*
-             * Count up the number and length of keys we hold.
-             */
-            len = nkeys = 0;
-            for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
-                nkeys++;
-                len += 4;              /* length field */
+           /*
+            * Count up the number and length of keys we hold.
+            */
+           len = nkeys = 0;
+           for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
+               nkeys++;
+               len += 4;              /* length field */
                blob = key->alg->public_blob(key->data, &bloblen);
                len += bloblen;
                sfree(blob);
-                len += 4 + strlen(key->comment);
-            }
-
-            /*
-             * Packet header is the obvious five bytes, plus four
-             * bytes for the key count.
-             */
-            len += 5 + 4;
-            if (len > AGENT_MAX_MSGLEN)
-                goto failure;          /* aaargh! too much stuff! */
-            PUT_32BIT(ret, len-4);
-            ret[4] = SSH2_AGENT_IDENTITIES_ANSWER;
-            PUT_32BIT(ret+5, nkeys);
-            p = ret + 5 + 4;
-            for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
+               len += 4 + strlen(key->comment);
+           }
+
+           /*
+            * Packet header is the obvious five bytes, plus four
+            * bytes for the key count.
+            */
+           len += 5 + 4;
+           if (len > AGENT_MAX_MSGLEN)
+               goto failure;          /* aaargh! too much stuff! */
+           PUT_32BIT(ret, len - 4);
+           ret[4] = SSH2_AGENT_IDENTITIES_ANSWER;
+           PUT_32BIT(ret + 5, nkeys);
+           p = ret + 5 + 4;
+           for (i = 0; NULL != (key = index234(ssh2keys, i)); i++) {
                blob = key->alg->public_blob(key->data, &bloblen);
-                PUT_32BIT(p, bloblen);
-                p += 4;
+               PUT_32BIT(p, bloblen);
+               p += 4;
                memcpy(p, blob, bloblen);
                p += bloblen;
                sfree(blob);
-                PUT_32BIT(p, strlen(key->comment));
-                memcpy(p+4, key->comment, strlen(key->comment));
-                p += 4 + strlen(key->comment);
-            }
-        }
-        break;
+               PUT_32BIT(p, strlen(key->comment));
+               memcpy(p + 4, key->comment, strlen(key->comment));
+               p += 4 + strlen(key->comment);
+           }
+       }
+       break;
       case SSH1_AGENTC_RSA_CHALLENGE:
-        /*
-         * Reply with either SSH1_AGENT_RSA_RESPONSE or
-         * SSH_AGENT_FAILURE, depending on whether we have that key
-         * or not.
-         */
-        {
-            struct RSAKey reqkey, *key;
-            Bignum challenge, response;
-            unsigned char response_source[48], response_md5[16];
-            struct MD5Context md5c;
-            int i, len;
-
-            p += 4;
-            p += ssh1_read_bignum(p, &reqkey.exponent);
-            p += ssh1_read_bignum(p, &reqkey.modulus);
-            p += ssh1_read_bignum(p, &challenge);
-            memcpy(response_source+32, p, 16); p += 16;
-            if (GET_32BIT(p) != 1 ||
-                (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
-                freebn(reqkey.exponent);
-                freebn(reqkey.modulus);
-                freebn(challenge);
-                goto failure;
-            }
-            response = rsadecrypt(challenge, key);
-            for (i = 0; i < 32; i++)
-                response_source[i] = bignum_byte(response, 31-i);
-
-            MD5Init(&md5c);
-            MD5Update(&md5c, response_source, 48);
-            MD5Final(response_md5, &md5c);
-            memset(response_source, 0, 48);   /* burn the evidence */
-            freebn(response);          /* and that evidence */
-            freebn(challenge);         /* yes, and that evidence */
-            freebn(reqkey.exponent);   /* and free some memory ... */
-            freebn(reqkey.modulus);    /* ... while we're at it. */
-
-            /*
-             * Packet is the obvious five byte header, plus sixteen
-             * bytes of MD5.
-             */
-            len = 5 + 16;
-            PUT_32BIT(ret, len-4);
-            ret[4] = SSH1_AGENT_RSA_RESPONSE;
-            memcpy(ret+5, response_md5, 16);
-        }
-        break;
+       /*
+        * Reply with either SSH1_AGENT_RSA_RESPONSE or
+        * SSH_AGENT_FAILURE, depending on whether we have that key
+        * or not.
+        */
+       {
+           struct RSAKey reqkey, *key;
+           Bignum challenge, response;
+           unsigned char response_source[48], response_md5[16];
+           struct MD5Context md5c;
+           int i, len;
+
+           p += 4;
+           p += ssh1_read_bignum(p, &reqkey.exponent);
+           p += ssh1_read_bignum(p, &reqkey.modulus);
+           p += ssh1_read_bignum(p, &challenge);
+           memcpy(response_source + 32, p, 16);
+           p += 16;
+           if (GET_32BIT(p) != 1 ||
+               (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
+               freebn(reqkey.exponent);
+               freebn(reqkey.modulus);
+               freebn(challenge);
+               goto failure;
+           }
+           response = rsadecrypt(challenge, key);
+           for (i = 0; i < 32; i++)
+               response_source[i] = bignum_byte(response, 31 - i);
+
+           MD5Init(&md5c);
+           MD5Update(&md5c, response_source, 48);
+           MD5Final(response_md5, &md5c);
+           memset(response_source, 0, 48);     /* burn the evidence */
+           freebn(response);          /* and that evidence */
+           freebn(challenge);         /* yes, and that evidence */
+           freebn(reqkey.exponent);   /* and free some memory ... */
+           freebn(reqkey.modulus);    /* ... while we're at it. */
+
+           /*
+            * Packet is the obvious five byte header, plus sixteen
+            * bytes of MD5.
+            */
+           len = 5 + 16;
+           PUT_32BIT(ret, len - 4);
+           ret[4] = SSH1_AGENT_RSA_RESPONSE;
+           memcpy(ret + 5, response_md5, 16);
+       }
+       break;
       case SSH2_AGENTC_SIGN_REQUEST:
-        /*
-         * Reply with either SSH2_AGENT_RSA_RESPONSE or
-         * SSH_AGENT_FAILURE, depending on whether we have that key
-         * or not.
-         */
+       /*
+        * Reply with either SSH2_AGENT_RSA_RESPONSE or
+        * SSH_AGENT_FAILURE, depending on whether we have that key
+        * or not.
+        */
        {
            struct ssh2_userkey *key;
            struct blob b;
@@ -602,60 +624,62 @@ static void answer_msg(void *msg) {
            if (!key)
                goto failure;
            signature = key->alg->sign(key->data, data, datalen, &siglen);
-           len = 5+4+siglen;
-            PUT_32BIT(ret, len-4);
-            ret[4] = SSH2_AGENT_SIGN_RESPONSE;
-            PUT_32BIT(ret+5, siglen);
-           memcpy(ret+5+4, signature, siglen);
+           len = 5 + 4 + siglen;
+           PUT_32BIT(ret, len - 4);
+           ret[4] = SSH2_AGENT_SIGN_RESPONSE;
+           PUT_32BIT(ret + 5, siglen);
+           memcpy(ret + 5 + 4, signature, siglen);
            sfree(signature);
        }
        break;
       case SSH1_AGENTC_ADD_RSA_IDENTITY:
-        /*
-         * Add to the list and return SSH_AGENT_SUCCESS, or
-         * SSH_AGENT_FAILURE if the key was malformed.
-         */
-        {
-            struct RSAKey *key;
-            char *comment;
-            key = smalloc(sizeof(struct RSAKey));
-            memset(key, 0, sizeof(key));
-            p += makekey(p, key, NULL, 1);
-            p += makeprivate(p, key);
-            p += ssh1_read_bignum(p, key->iqmp); /* p^-1 mod q */
-            p += ssh1_read_bignum(p, key->p);    /* p */
-            p += ssh1_read_bignum(p, key->q);    /* q */
-            comment = smalloc(GET_32BIT(p));
-            if (comment) {
-                memcpy(comment, p+4, GET_32BIT(p));
-                key->comment = comment;
-            }
-            PUT_32BIT(ret, 1);
-            ret[4] = SSH_AGENT_FAILURE;
-            if (add234(rsakeys, key) == key) {
-                keylist_update();
-                ret[4] = SSH_AGENT_SUCCESS;
-            } else {
-                freersakey(key);
-                sfree(key);
-            }
-        }
-        break;
+       /*
+        * Add to the list and return SSH_AGENT_SUCCESS, or
+        * SSH_AGENT_FAILURE if the key was malformed.
+        */
+       {
+           struct RSAKey *key;
+           char *comment;
+           key = smalloc(sizeof(struct RSAKey));
+           memset(key, 0, sizeof(key));
+           p += makekey(p, key, NULL, 1);
+           p += makeprivate(p, key);
+           p += ssh1_read_bignum(p, key->iqmp);        /* p^-1 mod q */
+           p += ssh1_read_bignum(p, key->p);   /* p */
+           p += ssh1_read_bignum(p, key->q);   /* q */
+           comment = smalloc(GET_32BIT(p));
+           if (comment) {
+               memcpy(comment, p + 4, GET_32BIT(p));
+               key->comment = comment;
+           }
+           PUT_32BIT(ret, 1);
+           ret[4] = SSH_AGENT_FAILURE;
+           if (add234(rsakeys, key) == key) {
+               keylist_update();
+               ret[4] = SSH_AGENT_SUCCESS;
+           } else {
+               freersakey(key);
+               sfree(key);
+           }
+       }
+       break;
       case SSH2_AGENTC_ADD_IDENTITY:
-        /*
-         * Add to the list and return SSH_AGENT_SUCCESS, or
-         * SSH_AGENT_FAILURE if the key was malformed.
-         */
-        {
-            struct ssh2_userkey *key;
-            char *comment, *alg;
+       /*
+        * Add to the list and return SSH_AGENT_SUCCESS, or
+        * SSH_AGENT_FAILURE if the key was malformed.
+        */
+       {
+           struct ssh2_userkey *key;
+           char *comment, *alg;
            int alglen, commlen;
            int bloblen;
 
            key = smalloc(sizeof(struct ssh2_userkey));
 
-           alglen = GET_32BIT(p); p += 4;
-           alg = p; p += alglen;
+           alglen = GET_32BIT(p);
+           p += 4;
+           alg = p;
+           p += alglen;
            /* Add further algorithm names here. */
            if (alglen == 7 && !memcmp(alg, "ssh-rsa", 7))
                key->alg = &ssh_rsa;
@@ -664,65 +688,69 @@ static void answer_msg(void *msg) {
                goto failure;
            }
 
-           bloblen = GET_32BIT((unsigned char *)msg) - (p-(unsigned char *)msg-4);
+           bloblen =
+               GET_32BIT((unsigned char *) msg) - (p -
+                                                   (unsigned char *) msg -
+                                                   4);
            key->data = key->alg->openssh_createkey(&p, &bloblen);
            if (!key->data) {
                sfree(key);
                goto failure;
            }
-           commlen = GET_32BIT(p); p += 4;
+           commlen = GET_32BIT(p);
+           p += 4;
 
-            comment = smalloc(commlen+1);
-            if (comment) {
-                memcpy(comment, p, commlen);
+           comment = smalloc(commlen + 1);
+           if (comment) {
+               memcpy(comment, p, commlen);
                comment[commlen] = '\0';
-            }
+           }
            key->comment = comment;
 
-            PUT_32BIT(ret, 1);
-            ret[4] = SSH_AGENT_FAILURE;
-            if (add234(ssh2keys, key) == key) {
-                keylist_update();
-                ret[4] = SSH_AGENT_SUCCESS;
-            } else {
+           PUT_32BIT(ret, 1);
+           ret[4] = SSH_AGENT_FAILURE;
+           if (add234(ssh2keys, key) == key) {
+               keylist_update();
+               ret[4] = SSH_AGENT_SUCCESS;
+           } else {
                key->alg->freekey(key->data);
                sfree(key->comment);
-                sfree(key);
-            }
-        }
-        break;
+               sfree(key);
+           }
+       }
+       break;
       case SSH1_AGENTC_REMOVE_RSA_IDENTITY:
-        /*
-         * Remove from the list and return SSH_AGENT_SUCCESS, or
-         * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
-         * start with.
-         */
-        {
-            struct RSAKey reqkey, *key;
-
-            p += makekey(p, &reqkey, NULL, 0);
-            key = find234(rsakeys, &reqkey, NULL);
-            freebn(reqkey.exponent);
-            freebn(reqkey.modulus);
-            PUT_32BIT(ret, 1);
-            ret[4] = SSH_AGENT_FAILURE;
-            if (key) {
-                del234(rsakeys, key);
-                keylist_update();
-                freersakey(key);
+       /*
+        * Remove from the list and return SSH_AGENT_SUCCESS, or
+        * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
+        * start with.
+        */
+       {
+           struct RSAKey reqkey, *key;
+
+           p += makekey(p, &reqkey, NULL, 0);
+           key = find234(rsakeys, &reqkey, NULL);
+           freebn(reqkey.exponent);
+           freebn(reqkey.modulus);
+           PUT_32BIT(ret, 1);
+           ret[4] = SSH_AGENT_FAILURE;
+           if (key) {
+               del234(rsakeys, key);
+               keylist_update();
+               freersakey(key);
                sfree(key);
-                ret[4] = SSH_AGENT_SUCCESS;
-            }
-        }
-        break;
+               ret[4] = SSH_AGENT_SUCCESS;
+           }
+       }
+       break;
       case SSH2_AGENTC_REMOVE_IDENTITY:
-        /*
-         * Remove from the list and return SSH_AGENT_SUCCESS, or
-         * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
-         * start with.
-         */
-        {
-            struct ssh2_userkey *key;
+       /*
+        * Remove from the list and return SSH_AGENT_SUCCESS, or
+        * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
+        * start with.
+        */
+       {
+           struct ssh2_userkey *key;
            struct blob b;
 
            b.len = GET_32BIT(p);
@@ -733,70 +761,71 @@ static void answer_msg(void *msg) {
            if (!key)
                goto failure;
 
-            PUT_32BIT(ret, 1);
-            ret[4] = SSH_AGENT_FAILURE;
-            if (key) {
-                del234(ssh2keys, key);
-                keylist_update();
+           PUT_32BIT(ret, 1);
+           ret[4] = SSH_AGENT_FAILURE;
+           if (key) {
+               del234(ssh2keys, key);
+               keylist_update();
                key->alg->freekey(key->data);
                sfree(key);
-                ret[4] = SSH_AGENT_SUCCESS;
-            }
-        }
-        break;
+               ret[4] = SSH_AGENT_SUCCESS;
+           }
+       }
+       break;
       case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
-        /*
-         * Remove all SSH1 keys. Always returns success.
-         */
-        {
+       /*
+        * Remove all SSH1 keys. Always returns success.
+        */
+       {
            struct RSAKey *rkey;
 
-            while ( (rkey = index234(rsakeys, 0)) != NULL ) {
-                del234(rsakeys, rkey);
+           while ((rkey = index234(rsakeys, 0)) != NULL) {
+               del234(rsakeys, rkey);
                freersakey(rkey);
                sfree(rkey);
-            }
+           }
            keylist_update();
 
            PUT_32BIT(ret, 1);
            ret[4] = SSH_AGENT_SUCCESS;
-        }
-        break;
+       }
+       break;
       case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
-        /*
-         * Remove all SSH2 keys. Always returns success.
-         */
-        {
-            struct ssh2_userkey *skey;
-
-            while ( (skey = index234(ssh2keys, 0)) != NULL ) {
-                del234(ssh2keys, skey);
+       /*
+        * Remove all SSH2 keys. Always returns success.
+        */
+       {
+           struct ssh2_userkey *skey;
+
+           while ((skey = index234(ssh2keys, 0)) != NULL) {
+               del234(ssh2keys, skey);
                skey->alg->freekey(skey->data);
                sfree(skey);
-            }
+           }
            keylist_update();
 
            PUT_32BIT(ret, 1);
            ret[4] = SSH_AGENT_SUCCESS;
-        }
-        break;
+       }
+       break;
       default:
-        failure:
-        /*
-         * Unrecognised message. Return SSH_AGENT_FAILURE.
-         */
-        PUT_32BIT(ret, 1);
-        ret[4] = SSH_AGENT_FAILURE;
-        break;
+      failure:
+       /*
+        * Unrecognised message. Return SSH_AGENT_FAILURE.
+        */
+       PUT_32BIT(ret, 1);
+       ret[4] = SSH_AGENT_FAILURE;
+       break;
     }
 }
 
 /*
  * Key comparison function for the 2-3-4 tree of RSA keys.
  */
-static int cmpkeys_rsa(void *av, void *bv) {
-    struct RSAKey *a = (struct RSAKey *)av;
-    struct RSAKey *b = (struct RSAKey *)bv;
+static int cmpkeys_rsa(void *av, void *bv)
+{
+    struct RSAKey *a = (struct RSAKey *) av;
+    struct RSAKey *b = (struct RSAKey *) bv;
     Bignum am, bm;
     int alen, blen;
 
@@ -807,16 +836,22 @@ static int cmpkeys_rsa(void *av, void *bv) {
      */
     alen = bignum_bitcount(am);
     blen = bignum_bitcount(bm);
-    if (alen > blen) return +1; else if (alen < blen) return -1;
+    if (alen > blen)
+       return +1;
+    else if (alen < blen)
+       return -1;
     /*
      * Now compare by moduli themselves.
      */
-    alen = (alen + 7) / 8;             /* byte count */
+    alen = (alen + 7) / 8;            /* byte count */
     while (alen-- > 0) {
-        int abyte, bbyte;
-        abyte = bignum_byte(am, alen);
-        bbyte = bignum_byte(bm, alen);
-        if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
+       int abyte, bbyte;
+       abyte = bignum_byte(am, alen);
+       bbyte = bignum_byte(bm, alen);
+       if (abyte > bbyte)
+           return +1;
+       else if (abyte < bbyte)
+           return -1;
     }
     /*
      * Give up.
@@ -827,14 +862,15 @@ static int cmpkeys_rsa(void *av, void *bv) {
 /*
  * Key comparison function for the 2-3-4 tree of SSH2 keys.
  */
-static int cmpkeys_ssh2(void *av, void *bv) {
-    struct ssh2_userkey *a = (struct ssh2_userkey *)av;
-    struct ssh2_userkey *b = (struct ssh2_userkey *)bv;
+static int cmpkeys_ssh2(void *av, void *bv)
+{
+    struct ssh2_userkey *a = (struct ssh2_userkey *) av;
+    struct ssh2_userkey *b = (struct ssh2_userkey *) bv;
     int i;
     int alen, blen;
     unsigned char *ablob, *bblob;
     int c;
-    
+
     /*
      * Compare purely by public blob.
      */
@@ -844,13 +880,17 @@ static int cmpkeys_ssh2(void *av, void *bv) {
     c = 0;
     for (i = 0; i < alen && i < blen; i++) {
        if (ablob[i] < bblob[i]) {
-           c = -1; break;
+           c = -1;
+           break;
        } else if (ablob[i] > bblob[i]) {
-           c = +1; break;
+           c = +1;
+           break;
        }
     }
-    if (c == 0 && i < alen) c = +1;    /* a is longer */
-    if (c == 0 && i < blen) c = -1;    /* a is longer */
+    if (c == 0 && i < alen)
+       c = +1;                        /* a is longer */
+    if (c == 0 && i < blen)
+       c = -1;                        /* a is longer */
 
     sfree(ablob);
     sfree(bblob);
@@ -862,14 +902,15 @@ static int cmpkeys_ssh2(void *av, void *bv) {
  * Key comparison function for looking up a blob in the 2-3-4 tree
  * of SSH2 keys.
  */
-static int cmpkeys_ssh2_asymm(void *av, void *bv) {
-    struct blob *a = (struct blob *)av;
-    struct ssh2_userkey *b = (struct ssh2_userkey *)bv;
+static int cmpkeys_ssh2_asymm(void *av, void *bv)
+{
+    struct blob *a = (struct blob *) av;
+    struct ssh2_userkey *b = (struct ssh2_userkey *) bv;
     int i;
     int alen, blen;
     unsigned char *ablob, *bblob;
     int c;
-    
+
     /*
      * Compare purely by public blob.
      */
@@ -880,27 +921,33 @@ static int cmpkeys_ssh2_asymm(void *av, void *bv) {
     c = 0;
     for (i = 0; i < alen && i < blen; i++) {
        if (ablob[i] < bblob[i]) {
-           c = -1; break;
+           c = -1;
+           break;
        } else if (ablob[i] > bblob[i]) {
-           c = +1; break;
+           c = +1;
+           break;
        }
     }
-    if (c == 0 && i < alen) c = +1;    /* a is longer */
-    if (c == 0 && i < blen) c = -1;    /* a is longer */
+    if (c == 0 && i < alen)
+       c = +1;                        /* a is longer */
+    if (c == 0 && i < blen)
+       c = -1;                        /* a is longer */
 
     sfree(bblob);
 
     return c;
 }
 
-static void error(char *s) {
+static void error(char *s)
+{
     MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
 }
 
 /*
  * Prompt for a key file to add, and add it.
  */
-static void prompt_add_keyfile(void) {
+static void prompt_add_keyfile(void)
+{
     OPENFILENAME of;
     char filename[FILENAME_MAX];
     memset(&of, 0, sizeof(of));
@@ -913,15 +960,16 @@ static void prompt_add_keyfile(void) {
     of.lpstrFilter = "All Files\0*\0\0\0";
     of.lpstrCustomFilter = NULL;
     of.nFilterIndex = 1;
-    of.lpstrFile = filename; *filename = '\0';
+    of.lpstrFile = filename;
+    *filename = '\0';
     of.nMaxFile = sizeof(filename);
     of.lpstrFileTitle = NULL;
     of.lpstrInitialDir = NULL;
     of.lpstrTitle = "Select Private Key File";
     of.Flags = 0;
     if (GetOpenFileName(&of)) {
-        add_keyfile(filename);
-        keylist_update();
+       add_keyfile(filename);
+       keylist_update();
     }
 }
 
@@ -929,7 +977,8 @@ static void prompt_add_keyfile(void) {
  * Dialog-box function for the key list box.
  */
 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
-                                WPARAM wParam, LPARAM lParam) {
+                               WPARAM wParam, LPARAM lParam)
+{
     struct RSAKey *rkey;
     struct ssh2_userkey *skey;
 
@@ -943,52 +992,54 @@ static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        keylist = hwnd;
+       keylist = hwnd;
        {
-           static int tabs[] = {35, 60, 210};
-           SendDlgItemMessage (hwnd, 100, LB_SETTABSTOPS,
-                               sizeof(tabs)/sizeof(*tabs), (LPARAM) tabs);
+           static int tabs[] = { 35, 60, 210 };
+           SendDlgItemMessage(hwnd, 100, LB_SETTABSTOPS,
+                              sizeof(tabs) / sizeof(*tabs),
+                              (LPARAM) tabs);
        }
-        keylist_update();
-        return 0;
+       keylist_update();
+       return 0;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
          case IDCANCEL:
-            keylist = NULL;
-            DestroyWindow(hwnd);
-            return 0;
-          case 101:                    /* add key */
+           keylist = NULL;
+           DestroyWindow(hwnd);
+           return 0;
+         case 101:                    /* add key */
            if (HIWORD(wParam) == BN_CLICKED ||
                HIWORD(wParam) == BN_DOUBLECLICKED) {
-                prompt_add_keyfile();
-            }
-            return 0;
-          case 102:                    /* remove key */
+               prompt_add_keyfile();
+           }
+           return 0;
+         case 102:                    /* remove key */
            if (HIWORD(wParam) == BN_CLICKED ||
                HIWORD(wParam) == BN_DOUBLECLICKED) {
-               int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
+               int n = SendDlgItemMessage(hwnd, 100, LB_GETCURSEL, 0, 0);
                int i;
                if (n == LB_ERR) {
                    MessageBeep(0);
                    break;
                }
-                for (i = 0; NULL != (rkey = index234(rsakeys, i)); i++)
-                    if (n-- == 0)
-                        break;
+               for (i = 0; NULL != (rkey = index234(rsakeys, i)); i++)
+                   if (n-- == 0)
+                       break;
                if (rkey) {
                    del234(rsakeys, rkey);
                    freersakey(rkey);
                    sfree(rkey);
                } else {
-                   for (i = 0; NULL != (skey = index234(ssh2keys, i)); i++)
-                       if (n-- == 0)
+                   for (i = 0; NULL != (skey = index234(ssh2keys, i));
+                        i++) if (n-- == 0)
                            break;
                    if (skey) {
                        del234(ssh2keys, skey);
@@ -996,189 +1047,200 @@ static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
                        sfree(skey);
                    }
                }
-                keylist_update();
-            }
-            return 0;
+               keylist_update();
+           }
+           return 0;
        }
        return 0;
       case WM_CLOSE:
-        keylist = NULL;
-        DestroyWindow(hwnd);
+       keylist = NULL;
+       DestroyWindow(hwnd);
        return 0;
     }
     return 0;
 }
 
-static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
-                                 WPARAM wParam, LPARAM lParam) {
+static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
+                               WPARAM wParam, LPARAM lParam)
+{
     int ret;
     static int menuinprogress;
 
     switch (message) {
       case WM_SYSTRAY:
-        if (lParam == WM_RBUTTONUP) {
-            POINT cursorpos;
-            GetCursorPos(&cursorpos);
-            PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
-        } else if (lParam == WM_LBUTTONDBLCLK) {
-            /* Equivalent to IDM_VIEWKEYS. */
-            PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
-        }
-        break;
+       if (lParam == WM_RBUTTONUP) {
+           POINT cursorpos;
+           GetCursorPos(&cursorpos);
+           PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
+       } else if (lParam == WM_LBUTTONDBLCLK) {
+           /* Equivalent to IDM_VIEWKEYS. */
+           PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
+       }
+       break;
       case WM_SYSTRAY2:
-        if (!menuinprogress) {
-            menuinprogress = 1;
-            SetForegroundWindow(hwnd);
-            ret = TrackPopupMenu(systray_menu,
-                                 TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
-                                 TPM_RIGHTBUTTON,
-                                 wParam, lParam, 0, hwnd, NULL);
-            menuinprogress = 0;
-        }
-        break;
+       if (!menuinprogress) {
+           menuinprogress = 1;
+           SetForegroundWindow(hwnd);
+           ret = TrackPopupMenu(systray_menu,
+                                TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
+                                TPM_RIGHTBUTTON,
+                                wParam, lParam, 0, hwnd, NULL);
+           menuinprogress = 0;
+       }
+       break;
       case WM_COMMAND:
       case WM_SYSCOMMAND:
        switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
-          case IDM_CLOSE:
-            SendMessage(hwnd, WM_CLOSE, 0, 0);
-            break;
-          case IDM_VIEWKEYS:
-            if (!keylist) {
-                keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
-                                        NULL, KeyListProc);
-                ShowWindow (keylist, SW_SHOWNORMAL);
-                /* 
-                 * Sometimes the window comes up minimised / hidden
-                 * for no obvious reason. Prevent this.
-                 */
-                SetForegroundWindow(keylist);
-                SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
-                              SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
-            }
-            break;
-          case IDM_ADDKEY:
-            prompt_add_keyfile();
-            break;
-          case IDM_ABOUT:
-            if (!aboutbox) {
-                aboutbox = CreateDialog (instance, MAKEINTRESOURCE(213),
-                                         NULL, AboutProc);
-                ShowWindow (aboutbox, SW_SHOWNORMAL);
-                /* 
-                 * Sometimes the window comes up minimised / hidden
-                 * for no obvious reason. Prevent this.
-                 */
-                SetForegroundWindow(aboutbox);
-                SetWindowPos (aboutbox, HWND_TOP, 0, 0, 0, 0,
-                              SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
-            }
-            break;
-        }
-        break;
+         case IDM_CLOSE:
+           SendMessage(hwnd, WM_CLOSE, 0, 0);
+           break;
+         case IDM_VIEWKEYS:
+           if (!keylist) {
+               keylist = CreateDialog(instance, MAKEINTRESOURCE(211),
+                                      NULL, KeyListProc);
+               ShowWindow(keylist, SW_SHOWNORMAL);
+               /* 
+                * Sometimes the window comes up minimised / hidden
+                * for no obvious reason. Prevent this.
+                */
+               SetForegroundWindow(keylist);
+               SetWindowPos(keylist, HWND_TOP, 0, 0, 0, 0,
+                            SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
+           }
+           break;
+         case IDM_ADDKEY:
+           prompt_add_keyfile();
+           break;
+         case IDM_ABOUT:
+           if (!aboutbox) {
+               aboutbox = CreateDialog(instance, MAKEINTRESOURCE(213),
+                                       NULL, AboutProc);
+               ShowWindow(aboutbox, SW_SHOWNORMAL);
+               /* 
+                * Sometimes the window comes up minimised / hidden
+                * for no obvious reason. Prevent this.
+                */
+               SetForegroundWindow(aboutbox);
+               SetWindowPos(aboutbox, HWND_TOP, 0, 0, 0, 0,
+                            SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
+           }
+           break;
+       }
+       break;
       case WM_DESTROY:
-       PostQuitMessage (0);
+       PostQuitMessage(0);
        return 0;
       case WM_COPYDATA:
-        {
-            COPYDATASTRUCT *cds;
-            char *mapname;
-            void *p;
-            HANDLE filemap, proc;
-            PSID mapowner, procowner;
-            PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
-            int ret = 0;
-
-            cds = (COPYDATASTRUCT *)lParam;
-            if (cds->dwData != AGENT_COPYDATA_ID)
-                return 0;              /* not our message, mate */
-            mapname = (char *)cds->lpData;
-            if (mapname[cds->cbData - 1] != '\0')
-                return 0;              /* failure to be ASCIZ! */
+       {
+           COPYDATASTRUCT *cds;
+           char *mapname;
+           void *p;
+           HANDLE filemap, proc;
+           PSID mapowner, procowner;
+           PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
+           int ret = 0;
+
+           cds = (COPYDATASTRUCT *) lParam;
+           if (cds->dwData != AGENT_COPYDATA_ID)
+               return 0;              /* not our message, mate */
+           mapname = (char *) cds->lpData;
+           if (mapname[cds->cbData - 1] != '\0')
+               return 0;              /* failure to be ASCIZ! */
 #ifdef DEBUG_IPC
-            debug(("mapname is :%s:\n", mapname));
+           debug(("mapname is :%s:\n", mapname));
 #endif
-            filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
+           filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
 #ifdef DEBUG_IPC
-            debug(("filemap is %p\n", filemap));
+           debug(("filemap is %p\n", filemap));
 #endif
-            if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
-                int rc;
+           if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
+               int rc;
 #ifndef NO_SECURITY
-                if (has_security) {
-                    if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
-                                            GetCurrentProcessId())) == NULL) {
+               if (has_security) {
+                   if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
+                                           GetCurrentProcessId())) ==
+                       NULL) {
 #ifdef DEBUG_IPC
-                        debug(("couldn't get handle for process\n"));
+                       debug(("couldn't get handle for process\n"));
 #endif
-                        return 0;
-                    }
-                    if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
-                                        OWNER_SECURITY_INFORMATION,
-                                        &procowner, NULL, NULL, NULL,
-                                        &psd2) != ERROR_SUCCESS) {
+                       return 0;
+                   }
+                   if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
+                                       OWNER_SECURITY_INFORMATION,
+                                       &procowner, NULL, NULL, NULL,
+                                       &psd2) != ERROR_SUCCESS) {
 #ifdef DEBUG_IPC
-                        debug(("couldn't get owner info for process\n"));
+                       debug(("couldn't get owner info for process\n"));
 #endif
-                        CloseHandle(proc);
-                        return 0;          /* unable to get security info */
-                    }
-                    CloseHandle(proc);
-                    if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
-                                              OWNER_SECURITY_INFORMATION,
-                                              &mapowner, NULL, NULL, NULL,
-                                              &psd1) != ERROR_SUCCESS)) {
+                       CloseHandle(proc);
+                       return 0;      /* unable to get security info */
+                   }
+                   CloseHandle(proc);
+                   if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
+                                             OWNER_SECURITY_INFORMATION,
+                                             &mapowner, NULL, NULL, NULL,
+                                             &psd1) != ERROR_SUCCESS)) {
 #ifdef DEBUG_IPC
-                        debug(("couldn't get owner info for filemap: %d\n", rc));
+                       debug(
+                             ("couldn't get owner info for filemap: %d\n",
+                              rc));
 #endif
-                        return 0;
-                    }
+                       return 0;
+                   }
 #ifdef DEBUG_IPC
-                    debug(("got security stuff\n"));
+                   debug(("got security stuff\n"));
 #endif
-                    if (!EqualSid(mapowner, procowner))
-                        return 0;          /* security ID mismatch! */
+                   if (!EqualSid(mapowner, procowner))
+                       return 0;      /* security ID mismatch! */
 #ifdef DEBUG_IPC
-                    debug(("security stuff matched\n"));
+                   debug(("security stuff matched\n"));
 #endif
-                    LocalFree(psd1);
-                    LocalFree(psd2);
-                } else {
+                   LocalFree(psd1);
+                   LocalFree(psd2);
+               } else {
 #ifdef DEBUG_IPC
-                    debug(("security APIs not present\n"));
+                   debug(("security APIs not present\n"));
 #endif
-                }
+               }
 #endif
-                p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
+               p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
 #ifdef DEBUG_IPC
-                debug(("p is %p\n", p));
-                {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\n", i, ((unsigned char *)p)[i]));}
+               debug(("p is %p\n", p));
+               {
+                   int i;
+                   for (i = 0; i < 5; i++)
+                       debug(
+                             ("p[%d]=%02x\n", i,
+                              ((unsigned char *) p)[i]));}
 #endif
-                answer_msg(p);
-                ret = 1;
-                UnmapViewOfFile(p);
-            }
-            CloseHandle(filemap);
-            return ret;
-        }
+               answer_msg(p);
+               ret = 1;
+               UnmapViewOfFile(p);
+           }
+           CloseHandle(filemap);
+           return ret;
+       }
     }
 
-    return DefWindowProc (hwnd, message, wParam, lParam);
+    return DefWindowProc(hwnd, message, wParam, lParam);
 }
 
 /*
  * Fork and Exec the command in cmdline. [DBW]
  */
-void spawn_cmd(char *cmdline, int show) {
+void spawn_cmd(char *cmdline, int show)
+{
     if (ShellExecute(NULL, _T("open"), cmdline,
                     NULL, NULL, show) <= (HINSTANCE) 32) {
-        TCHAR sMsg[140];
-        sprintf(sMsg, _T("Failed to run \"%.100s\", Error: %d"), cmdline,
+       TCHAR sMsg[140];
+       sprintf(sMsg, _T("Failed to run \"%.100s\", Error: %d"), cmdline,
                GetLastError());
-        MessageBox(NULL, sMsg, APPNAME, MB_OK | MB_ICONEXCLAMATION);
+       MessageBox(NULL, sMsg, APPNAME, MB_OK | MB_ICONEXCLAMATION);
     }
 }
 
-int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
+int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
+{
     WNDCLASS wndclass;
     MSG msg;
     OSVERSIONINFO osi;
@@ -1192,25 +1254,26 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      */
     memset(&osi, 0, sizeof(OSVERSIONINFO));
     osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-    if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
-        has_security = TRUE;
+    if (GetVersionEx(&osi) && osi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
+       has_security = TRUE;
     } else
-        has_security = FALSE;
+       has_security = FALSE;
 
     if (has_security) {
 #ifndef NO_SECURITY
-        /*
-         * Attempt to get the security API we need.
-         */
-        advapi = LoadLibrary("ADVAPI32.DLL");
-        getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
-        if (!getsecurityinfo) {
-            MessageBox(NULL,
-                       "Unable to access security APIs. Pageant will\n"
-                       "not run, in case it causes a security breach.",
-                       "Pageant Fatal Error", MB_ICONERROR | MB_OK);
-            return 1;
-        }
+       /*
+        * Attempt to get the security API we need.
+        */
+       advapi = LoadLibrary("ADVAPI32.DLL");
+       getsecurityinfo =
+           (gsi_fn_t) GetProcAddress(advapi, "GetSecurityInfo");
+       if (!getsecurityinfo) {
+           MessageBox(NULL,
+                      "Unable to access security APIs. Pageant will\n"
+                      "not run, in case it causes a security breach.",
+                      "Pageant Fatal Error", MB_ICONERROR | MB_OK);
+           return 1;
+       }
 #else
        MessageBox(NULL,
                   "This program has been compiled for Win9X and will\n"
@@ -1219,7 +1282,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
        return 1;
 #endif
     } else
-        advapi = NULL;
+       advapi = NULL;
 
     instance = inst;
 
@@ -1232,27 +1295,26 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
     else {
 
        if (!prev) {
-           wndclass.style         = 0;
-           wndclass.lpfnWndProc   = WndProc;
-           wndclass.cbClsExtra    = 0;
-           wndclass.cbWndExtra    = 0;
-           wndclass.hInstance     = inst;
-           wndclass.hIcon         = LoadIcon (inst,
-                                              MAKEINTRESOURCE(IDI_MAINICON));
-           wndclass.hCursor       = LoadCursor (NULL, IDC_IBEAM);
-           wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
-           wndclass.lpszMenuName  = NULL;
+           wndclass.style = 0;
+           wndclass.lpfnWndProc = WndProc;
+           wndclass.cbClsExtra = 0;
+           wndclass.cbWndExtra = 0;
+           wndclass.hInstance = inst;
+           wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
+           wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
+           wndclass.hbrBackground = GetStockObject(BLACK_BRUSH);
+           wndclass.lpszMenuName = NULL;
            wndclass.lpszClassName = APPNAME;
 
-           RegisterClass (&wndclass);
+           RegisterClass(&wndclass);
        }
 
        hwnd = keylist = NULL;
 
-       hwnd = CreateWindow (APPNAME, APPNAME,
-                            WS_OVERLAPPEDWINDOW | WS_VSCROLL,
-                            CW_USEDEFAULT, CW_USEDEFAULT,
-                            100, 100, NULL, NULL, inst, NULL);
+       hwnd = CreateWindow(APPNAME, APPNAME,
+                           WS_OVERLAPPEDWINDOW | WS_VSCROLL,
+                           CW_USEDEFAULT, CW_USEDEFAULT,
+                           100, 100, NULL, NULL, inst, NULL);
 
        /* Set up a system tray icon */
        {
@@ -1267,10 +1329,10 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
 
            tnid.cbSize = sizeof(NOTIFYICONDATA);
            tnid.hWnd = hwnd;
-           tnid.uID = 1;                  /* unique within this systray use */
+           tnid.uID = 1;              /* unique within this systray use */
            tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
            tnid.uCallbackMessage = WM_SYSTRAY;
-           tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
+           tnid.hIcon = hicon = LoadIcon(instance, MAKEINTRESOURCE(201));
            strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
 
            res = Shell_NotifyIcon(NIM_ADD, &tnid);
@@ -1280,13 +1342,14 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
 
            systray_menu = CreatePopupMenu();
            /* accelerators used: vkxa */
-           AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "&View Keys");
-           AppendMenu (systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
-           AppendMenu (systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
-           AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
+           AppendMenu(systray_menu, MF_ENABLED, IDM_VIEWKEYS,
+                      "&View Keys");
+           AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
+           AppendMenu(systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
+           AppendMenu(systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
        }
 
-       ShowWindow (hwnd, SW_HIDE);
+       ShowWindow(hwnd, SW_HIDE);
 
        /*
         * Initialise storage for RSA keys.
@@ -1302,45 +1365,48 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      * need to ignore the first two arguments. [DBW]
      */
     {
-        char *p;
-        int inquotes = 0;
-        int ignorearg = 0;
-        p = cmdline;
-        while (*p) {
-            while (*p && isspace(*p)) p++;
-            if (*p && !isspace(*p)) {
-                char *q = p, *pp = p;
-                while (*p && (inquotes || !isspace(*p)))
-                {
-                    if (*p == '"') {
-                        inquotes = !inquotes;
-                        p++;
-                        continue;
-                    }
-                    *pp++ = *p++;
-                }
-                if (*pp) {
-                    if (*p) p++;
-                    *pp++ = '\0';
-                }
+       char *p;
+       int inquotes = 0;
+       int ignorearg = 0;
+       p = cmdline;
+       while (*p) {
+           while (*p && isspace(*p))
+               p++;
+           if (*p && !isspace(*p)) {
+               char *q = p, *pp = p;
+               while (*p && (inquotes || !isspace(*p))) {
+                   if (*p == '"') {
+                       inquotes = !inquotes;
+                       p++;
+                       continue;
+                   }
+                   *pp++ = *p++;
+               }
+               if (*pp) {
+                   if (*p)
+                       p++;
+                   *pp++ = '\0';
+               }
                if (!strcmp(q, "-c")) {
                    /*
                     * If we see `-c', then the rest of the
                     * command line should be treated as a
                     * command to be spawned.
                     */
-                   while (*p && isspace(*p)) p++;
+                   while (*p && isspace(*p))
+                       p++;
                    command = p;
                    break;
                } else {
                    add_keyfile(q);
                    added_keys = TRUE;
                }
-            }
-        }
+           }
+       }
     }
 
-    if (command) spawn_cmd (command, show);
+    if (command)
+       spawn_cmd(command, show);
 
     /*
      * If Pageant was already running, we leave now. If we haven't
@@ -1352,31 +1418,33 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
            MessageBox(NULL, "Pageant is already running", "Pageant Error",
                       MB_ICONERROR | MB_OK);
        }
-        if (advapi) FreeLibrary(advapi);
-        return 0;
+       if (advapi)
+           FreeLibrary(advapi);
+       return 0;
     }
 
     /*
      * Main message loop.
      */
     while (GetMessage(&msg, NULL, 0, 0) == 1) {
-        TranslateMessage(&msg);
-        DispatchMessage(&msg);
+       TranslateMessage(&msg);
+       DispatchMessage(&msg);
     }
 
     /* Clean up the system tray icon */
     {
-        NOTIFYICONDATA tnid;
+       NOTIFYICONDATA tnid;
 
-        tnid.cbSize = sizeof(NOTIFYICONDATA); 
-        tnid.hWnd = hwnd;
-        tnid.uID = 1;
+       tnid.cbSize = sizeof(NOTIFYICONDATA);
+       tnid.hWnd = hwnd;
+       tnid.uID = 1;
 
-        Shell_NotifyIcon(NIM_DELETE, &tnid); 
+       Shell_NotifyIcon(NIM_DELETE, &tnid);
 
-        DestroyMenu(systray_menu);
+       DestroyMenu(systray_menu);
     }
 
-    if (advapi) FreeLibrary(advapi);
+    if (advapi)
+       FreeLibrary(advapi);
     exit(msg.wParam);
 }
index 7764b6b..82cfb20 100644 (file)
     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
     ((unsigned long)(unsigned char)(cp)[3]))
 
-int agent_exists(void) {
+int agent_exists(void)
+{
     HWND hwnd;
     hwnd = FindWindow("Pageant", "Pageant");
     if (!hwnd)
-        return FALSE;
+       return FALSE;
     else
-        return TRUE;
+       return TRUE;
 }
 
-void agent_query(void *in, int inlen, void **out, int *outlen) {
+void agent_query(void *in, int inlen, void **out, int *outlen)
+{
     HWND hwnd;
     char mapname[64];
     HANDLE filemap;
@@ -46,28 +48,28 @@ void agent_query(void *in, int inlen, void **out, int *outlen) {
     hwnd = FindWindow("Pageant", "Pageant");
     debug(("hwnd is %p\n", hwnd));
     if (!hwnd)
-        return;
+       return;
     sprintf(mapname, "PageantRequest%08x", GetCurrentThreadId());
     filemap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
-                                0, AGENT_MAX_MSGLEN, mapname);
+                               0, AGENT_MAX_MSGLEN, mapname);
     if (!filemap)
-        return;
+       return;
     p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
     memcpy(p, in, inlen);
     cds.dwData = AGENT_COPYDATA_ID;
-    cds.cbData = 1+strlen(mapname);
+    cds.cbData = 1 + strlen(mapname);
     cds.lpData = mapname;
-    id = SendMessage(hwnd, WM_COPYDATA, (WPARAM)NULL, (LPARAM)&cds);
+    id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) & cds);
     debug(("return is %d\n", id));
     if (id > 0) {
-        retlen = 4 + GET_32BIT(p);
-        debug(("len is %d\n", retlen));
-        ret = smalloc(retlen);
-        if (ret) {
-            memcpy(ret, p, retlen);
-            *out = ret;
-            *outlen = retlen;
-        }
+       retlen = 4 + GET_32BIT(p);
+       debug(("len is %d\n", retlen));
+       ret = smalloc(retlen);
+       if (ret) {
+           memcpy(ret, p, retlen);
+           *out = ret;
+           *outlen = retlen;
+       }
     }
     UnmapViewOfFile(p);
     CloseHandle(filemap);
@@ -75,7 +77,8 @@ void agent_query(void *in, int inlen, void **out, int *outlen) {
 
 #ifdef TESTMODE
 
-int main(void) {
+int main(void)
+{
     void *msg;
     int len;
     int i;
@@ -83,7 +86,7 @@ int main(void) {
     agent_query("\0\0\0\1\1", 5, &msg, &len);
     debug(("%d:", len));
     for (i = 0; i < len; i++)
-        debug((" %02x", ((unsigned char *)msg)[i]));
+       debug((" %02x", ((unsigned char *) msg)[i]));
     debug(("\n"));
     return 0;
 }
diff --git a/plink.c b/plink.c
index d493c68..c9188c1 100644 (file)
--- a/plink.c
+++ b/plink.c
 #include <stdlib.h>
 #include <stdarg.h>
 
-#define PUTTY_DO_GLOBALS                      /* actually _define_ globals */
+#define PUTTY_DO_GLOBALS              /* actually _define_ globals */
 #include "putty.h"
 #include "storage.h"
 #include "tree234.h"
 
-void fatalbox (char *p, ...) {
+void fatalbox(char *p, ...)
+{
     va_list ap;
     fprintf(stderr, "FATAL ERROR: ");
     va_start(ap, p);
@@ -25,7 +26,8 @@ void fatalbox (char *p, ...) {
     WSACleanup();
     exit(1);
 }
-void connection_fatal (char *p, ...) {
+void connection_fatal(char *p, ...)
+{
     va_list ap;
     fprintf(stderr, "FATAL ERROR: ");
     va_start(ap, p);
@@ -38,43 +40,45 @@ void connection_fatal (char *p, ...) {
 
 static char *password = NULL;
 
-void logevent(char *string) { }
+void logevent(char *string)
+{
+}
 
 void verify_ssh_host_key(char *host, int port, char *keytype,
-                         char *keystr, char *fingerprint) {
+                        char *keystr, char *fingerprint)
+{
     int ret;
     HANDLE hin;
     DWORD savemode, i;
 
     static const char absentmsg[] =
-        "The server's host key is not cached in the registry. You\n"
-        "have no guarantee that the server is the computer you\n"
-        "think it is.\n"
-        "The server's key fingerprint is:\n"
-        "%s\n"
-        "If you trust this host, enter \"y\" to add the key to\n"
-        "PuTTY's cache and carry on connecting.\n"
-        "If you do not trust this host, enter \"n\" to abandon the\n"
-        "connection.\n"
-        "Continue connecting? (y/n) ";
+       "The server's host key is not cached in the registry. You\n"
+       "have no guarantee that the server is the computer you\n"
+       "think it is.\n"
+       "The server's key fingerprint is:\n"
+       "%s\n"
+       "If you trust this host, enter \"y\" to add the key to\n"
+       "PuTTY's cache and carry on connecting.\n"
+       "If you do not trust this host, enter \"n\" to abandon the\n"
+       "connection.\n" "Continue connecting? (y/n) ";
 
     static const char wrongmsg[] =
-        "WARNING - POTENTIAL SECURITY BREACH!\n"
-        "The server's host key does not match the one PuTTY has\n"
-        "cached in the registry. This means that either the\n"
-        "server administrator has changed the host key, or you\n"
-        "have actually connected to another computer pretending\n"
-        "to be the server.\n"
-        "The new key fingerprint is:\n"
-        "%s\n"
-        "If you were expecting this change and trust the new key,\n"
-        "enter \"y\" to update PuTTY's cache and continue connecting.\n"
-        "If you want to carry on connecting but without updating\n"
-        "the cache, enter \"n\".\n"
-        "If you want to abandon the connection completely, press\n"
-        "Return to cancel. Pressing Return is the ONLY guaranteed\n"
-        "safe choice.\n"
-        "Update cached key? (y/n, Return cancels connection) ";
+       "WARNING - POTENTIAL SECURITY BREACH!\n"
+       "The server's host key does not match the one PuTTY has\n"
+       "cached in the registry. This means that either the\n"
+       "server administrator has changed the host key, or you\n"
+       "have actually connected to another computer pretending\n"
+       "to be the server.\n"
+       "The new key fingerprint is:\n"
+       "%s\n"
+       "If you were expecting this change and trust the new key,\n"
+       "enter \"y\" to update PuTTY's cache and continue connecting.\n"
+       "If you want to carry on connecting but without updating\n"
+       "the cache, enter \"n\".\n"
+       "If you want to abandon the connection completely, press\n"
+       "Return to cancel. Pressing Return is the ONLY guaranteed\n"
+       "safe choice.\n"
+       "Update cached key? (y/n, Return cancels connection) ";
 
     static const char abandoned[] = "Connection abandoned.\n";
 
@@ -85,41 +89,41 @@ void verify_ssh_host_key(char *host, int port, char *keytype,
      */
     ret = verify_host_key(host, port, keytype, keystr);
 
-    if (ret == 0)                      /* success - key matched OK */
-        return;
+    if (ret == 0)                     /* success - key matched OK */
+       return;
 
     if (ret == 2) {                   /* key was different */
-        fprintf(stderr, wrongmsg, fingerprint);
+       fprintf(stderr, wrongmsg, fingerprint);
        fflush(stderr);
     }
     if (ret == 1) {                   /* key was absent */
-        fprintf(stderr, absentmsg, fingerprint);
+       fprintf(stderr, absentmsg, fingerprint);
        fflush(stderr);
     }
 
     hin = GetStdHandle(STD_INPUT_HANDLE);
     GetConsoleMode(hin, &savemode);
     SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
-                         ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
-    ReadFile(hin, line, sizeof(line)-1, &i, NULL);
+                        ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
+    ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
     SetConsoleMode(hin, savemode);
 
-    if (ret == 2) {                    /* key was different */
-        if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
-            if (line[0] == 'y' || line[0] == 'Y')
-                store_host_key(host, port, keytype, keystr);
-        } else {
-            fprintf(stderr, abandoned);
-            exit(0);
-        }
+    if (ret == 2) {                   /* key was different */
+       if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
+           if (line[0] == 'y' || line[0] == 'Y')
+               store_host_key(host, port, keytype, keystr);
+       } else {
+           fprintf(stderr, abandoned);
+           exit(0);
+       }
     }
-    if (ret == 1) {                    /* key was absent */
-        if (line[0] == 'y' || line[0] == 'Y')
-            store_host_key(host, port, keytype, keystr);
-        else {
-            fprintf(stderr, abandoned);
-            exit(0);
-        }
+    if (ret == 1) {                   /* key was absent */
+       if (line[0] == 'y' || line[0] == 'Y')
+           store_host_key(host, port, keytype, keystr);
+       else {
+           fprintf(stderr, abandoned);
+           exit(0);
+       }
     }
 }
 
@@ -128,33 +132,38 @@ DWORD orig_console_mode;
 
 WSAEVENT netevent;
 
-void from_backend(int is_stderr, char *data, int len) {
+void from_backend(int is_stderr, char *data, int len)
+{
     int pos;
     DWORD ret;
     HANDLE h = (is_stderr ? errhandle : outhandle);
 
     pos = 0;
     while (pos < len) {
-        if (!WriteFile(h, data+pos, len-pos, &ret, NULL))
-            return;                    /* give up in panic */
-        pos += ret;
+       if (!WriteFile(h, data + pos, len - pos, &ret, NULL))
+           return;                    /* give up in panic */
+       pos += ret;
     }
 }
 
-int term_ldisc(int mode) { return FALSE; }
-void ldisc_update(int echo, int edit) {
+int term_ldisc(int mode)
+{
+    return FALSE;
+}
+void ldisc_update(int echo, int edit)
+{
     /* Update stdin read mode to reflect changes in line discipline. */
     DWORD mode;
 
     mode = ENABLE_PROCESSED_INPUT;
     if (echo)
-        mode = mode | ENABLE_ECHO_INPUT;
+       mode = mode | ENABLE_ECHO_INPUT;
     else
-        mode = mode &~ ENABLE_ECHO_INPUT;
+       mode = mode & ~ENABLE_ECHO_INPUT;
     if (edit)
-        mode = mode | ENABLE_LINE_INPUT;
+       mode = mode | ENABLE_LINE_INPUT;
     else
-        mode = mode &~ ENABLE_LINE_INPUT;
+       mode = mode & ~ENABLE_LINE_INPUT;
     SetConsoleMode(inhandle, mode);
 }
 
@@ -170,57 +179,61 @@ static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
     DWORD savemode, newmode, i;
 
     if (is_pw && password) {
-        static int tried_once = 0;
-
-        if (tried_once) {
-            return 0;
-        } else {
-            strncpy(str, password, maxlen);
-            str[maxlen-1] = '\0';
-            tried_once = 1;
-            return 1;
-        }
+       static int tried_once = 0;
+
+       if (tried_once) {
+           return 0;
+       } else {
+           strncpy(str, password, maxlen);
+           str[maxlen - 1] = '\0';
+           tried_once = 1;
+           return 1;
+       }
     }
 
     hin = GetStdHandle(STD_INPUT_HANDLE);
     hout = GetStdHandle(STD_OUTPUT_HANDLE);
     if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
-        fprintf(stderr, "Cannot get standard input/output handles");
-        return 0;
+       fprintf(stderr, "Cannot get standard input/output handles");
+       return 0;
     }
 
     GetConsoleMode(hin, &savemode);
     newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
     if (is_pw)
-        newmode &= ~ENABLE_ECHO_INPUT;
+       newmode &= ~ENABLE_ECHO_INPUT;
     else
-        newmode |= ENABLE_ECHO_INPUT;
+       newmode |= ENABLE_ECHO_INPUT;
     SetConsoleMode(hin, newmode);
 
     WriteFile(hout, prompt, strlen(prompt), &i, NULL);
-    ReadFile(hin, str, maxlen-1, &i, NULL);
+    ReadFile(hin, str, maxlen - 1, &i, NULL);
 
     SetConsoleMode(hin, savemode);
 
-    if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
+    if ((int) i > maxlen)
+       i = maxlen - 1;
+    else
+       i = i - 2;
     str[i] = '\0';
 
     if (is_pw)
-        WriteFile(hout, "\r\n", 2, &i, NULL);
+       WriteFile(hout, "\r\n", 2, &i, NULL);
 
     return 1;
 }
 
-static DWORD WINAPI stdin_read_thread(void *param) {
-    struct input_data *idata = (struct input_data *)param;
+static DWORD WINAPI stdin_read_thread(void *param)
+{
+    struct input_data *idata = (struct input_data *) param;
     HANDLE inhandle;
 
     inhandle = GetStdHandle(STD_INPUT_HANDLE);
 
     while (ReadFile(inhandle, idata->buffer, sizeof(idata->buffer),
-                    &idata->len, NULL) && idata->len > 0) {
-        SetEvent(idata->event);
-        WaitForSingleObject(idata->eventback, INFINITE);
+                   &idata->len, NULL) && idata->len > 0) {
+       SetEvent(idata->event);
+       WaitForSingleObject(idata->eventback, INFINITE);
     }
 
     idata->len = 0;
@@ -246,23 +259,27 @@ static void usage(void)
     exit(1);
 }
 
-char *do_select(SOCKET skt, int startup) {
+char *do_select(SOCKET skt, int startup)
+{
     int events;
     if (startup) {
        events = FD_READ | FD_WRITE | FD_OOB | FD_CLOSE;
     } else {
        events = 0;
     }
-    if (WSAEventSelect (skt, netevent, events) == SOCKET_ERROR) {
-        switch (WSAGetLastError()) {
-          case WSAENETDOWN: return "Network is down";
-          default: return "WSAAsyncSelect(): unknown error";
-        }
+    if (WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
+       switch (WSAGetLastError()) {
+         case WSAENETDOWN:
+           return "Network is down";
+         default:
+           return "WSAAsyncSelect(): unknown error";
+       }
     }
     return NULL;
 }
 
-int main(int argc, char **argv) {
+int main(int argc, char **argv)
+{
     WSADATA wsadata;
     WORD winsock_ver;
     WSAEVENT stdinevent;
@@ -277,7 +294,8 @@ int main(int argc, char **argv) {
 
     ssh_get_line = get_line;
 
-    sklist = NULL; skcount = sksize = 0;
+    sklist = NULL;
+    skcount = sksize = 0;
 
     flags = FLAG_STDERR;
     /*
@@ -287,208 +305,220 @@ int main(int argc, char **argv) {
     default_protocol = cfg.protocol;
     default_port = cfg.port;
     {
-        /*
-         * Override the default protocol if PLINK_PROTOCOL is set.
-         */
-        char *p = getenv("PLINK_PROTOCOL");
-        int i;
-        if (p) {
-            for (i = 0; backends[i].backend != NULL; i++) {
-                if (!strcmp(backends[i].name, p)) {
-                    default_protocol = cfg.protocol = backends[i].protocol;
-                    default_port = cfg.port = backends[i].backend->default_port;
-                    break;
-                }
-            }
-        }
+       /*
+        * Override the default protocol if PLINK_PROTOCOL is set.
+        */
+       char *p = getenv("PLINK_PROTOCOL");
+       int i;
+       if (p) {
+           for (i = 0; backends[i].backend != NULL; i++) {
+               if (!strcmp(backends[i].name, p)) {
+                   default_protocol = cfg.protocol = backends[i].protocol;
+                   default_port = cfg.port =
+                       backends[i].backend->default_port;
+                   break;
+               }
+           }
+       }
     }
     while (--argc) {
-        char *p = *++argv;
-        if (*p == '-') {
-            if (!strcmp(p, "-ssh")) {
+       char *p = *++argv;
+       if (*p == '-') {
+           if (!strcmp(p, "-ssh")) {
                default_protocol = cfg.protocol = PROT_SSH;
                default_port = cfg.port = 22;
-            } else if (!strcmp(p, "-telnet")) {
+           } else if (!strcmp(p, "-telnet")) {
                default_protocol = cfg.protocol = PROT_TELNET;
                default_port = cfg.port = 23;
-            } else if (!strcmp(p, "-raw")) {
+           } else if (!strcmp(p, "-raw")) {
                default_protocol = cfg.protocol = PROT_RAW;
            } else if (!strcmp(p, "-v")) {
-                flags |= FLAG_VERBOSE;
+               flags |= FLAG_VERBOSE;
            } else if (!strcmp(p, "-log")) {
-                logfile = "putty.log";
-            } else if (!strcmp(p, "-pw") && argc > 1) {
-                --argc, password = *++argv;
-            } else if (!strcmp(p, "-l") && argc > 1) {
-                char *username;
-                --argc, username = *++argv;
-                strncpy(cfg.username, username, sizeof(cfg.username));
-                cfg.username[sizeof(cfg.username)-1] = '\0';
-            } else if (!strcmp(p, "-m") && argc > 1) {
-                char *filename, *command;
-                int cmdlen, cmdsize;
-                FILE *fp;
-                int c, d;
-
-                --argc, filename = *++argv;
-
-                cmdlen = cmdsize = 0;
-                command = NULL;
-                fp = fopen(filename, "r");
-                if (!fp) {
-                    fprintf(stderr, "plink: unable to open command "
-                            "file \"%s\"\n", filename);
-                    return 1;
-                }
-                do {
-                    c = fgetc(fp);
-                    d = c;
-                    if (c == EOF)
-                        d = 0;
-                    if (cmdlen >= cmdsize) {
-                        cmdsize = cmdlen + 512;
-                        command = srealloc(command, cmdsize);
-                    }
-                    command[cmdlen++] = d;
-                } while (c != EOF);
-                cfg.remote_cmd_ptr = command;
-                cfg.nopty = TRUE;      /* command => no terminal */
-            } else if (!strcmp(p, "-P") && argc > 1) {
-                --argc, portnumber = atoi(*++argv);
-            }
+               logfile = "putty.log";
+           } else if (!strcmp(p, "-pw") && argc > 1) {
+               --argc, password = *++argv;
+           } else if (!strcmp(p, "-l") && argc > 1) {
+               char *username;
+               --argc, username = *++argv;
+               strncpy(cfg.username, username, sizeof(cfg.username));
+               cfg.username[sizeof(cfg.username) - 1] = '\0';
+           } else if (!strcmp(p, "-m") && argc > 1) {
+               char *filename, *command;
+               int cmdlen, cmdsize;
+               FILE *fp;
+               int c, d;
+
+               --argc, filename = *++argv;
+
+               cmdlen = cmdsize = 0;
+               command = NULL;
+               fp = fopen(filename, "r");
+               if (!fp) {
+                   fprintf(stderr, "plink: unable to open command "
+                           "file \"%s\"\n", filename);
+                   return 1;
+               }
+               do {
+                   c = fgetc(fp);
+                   d = c;
+                   if (c == EOF)
+                       d = 0;
+                   if (cmdlen >= cmdsize) {
+                       cmdsize = cmdlen + 512;
+                       command = srealloc(command, cmdsize);
+                   }
+                   command[cmdlen++] = d;
+               } while (c != EOF);
+               cfg.remote_cmd_ptr = command;
+               cfg.nopty = TRUE;      /* command => no terminal */
+           } else if (!strcmp(p, "-P") && argc > 1) {
+               --argc, portnumber = atoi(*++argv);
+           }
        } else if (*p) {
-            if (!*cfg.host) {
-                char *q = p;
-                /*
-                 * If the hostname starts with "telnet:", set the
-                 * protocol to Telnet and process the string as a
-                 * Telnet URL.
-                 */
-                if (!strncmp(q, "telnet:", 7)) {
-                    char c;
-
-                    q += 7;
-                    if (q[0] == '/' && q[1] == '/')
-                        q += 2;
-                    cfg.protocol = PROT_TELNET;
-                    p = q;
-                    while (*p && *p != ':' && *p != '/') p++;
-                    c = *p;
-                    if (*p)
-                        *p++ = '\0';
-                    if (c == ':')
-                        cfg.port = atoi(p);
-                    else
-                        cfg.port = -1;
-                    strncpy (cfg.host, q, sizeof(cfg.host)-1);
-                    cfg.host[sizeof(cfg.host)-1] = '\0';
-                } else {
-                    char *r;
-                    /*
-                     * Before we process the [user@]host string, we
-                     * first check for the presence of a protocol
-                     * prefix (a protocol name followed by ",").
-                     */
-                    r = strchr(p, ',');
-                    if (r) {
-                        int i, j;
-                        for (i = 0; backends[i].backend != NULL; i++) {
-                            j = strlen(backends[i].name);
-                            if (j == r-p &&
-                                !memcmp(backends[i].name, p, j)) {
-                                default_protocol = cfg.protocol = backends[i].protocol;
-                                portnumber = backends[i].backend->default_port;
-                                p = r+1;
-                                break;
-                            }
-                        }
-                    }
-
-                    /*
-                     * Three cases. Either (a) there's a nonzero
-                     * length string followed by an @, in which
-                     * case that's user and the remainder is host.
-                     * Or (b) there's only one string, not counting
-                     * a potential initial @, and it exists in the
-                     * saved-sessions database. Or (c) only one
-                     * string and it _doesn't_ exist in the
-                     * database.
-                     */
-                    r = strrchr(p, '@');
-                    if (r == p) p++, r = NULL;   /* discount initial @ */
-                    if (r == NULL) {
-                        /*
-                         * One string.
-                         */
-                        Config cfg2;
-                        do_defaults (p, &cfg2);
-                        if (cfg2.host[0] == '\0') {
-                            /* No settings for this host; use defaults */
-                            strncpy(cfg.host, p, sizeof(cfg.host)-1);
-                            cfg.host[sizeof(cfg.host)-1] = '\0';
-                            cfg.port = default_port;
-                        } else {
-                            cfg = cfg2;
-                            cfg.remote_cmd_ptr = cfg.remote_cmd;
-                        }
-                    } else {
-                        *r++ = '\0';
-                        strncpy(cfg.username, p, sizeof(cfg.username)-1);
-                        cfg.username[sizeof(cfg.username)-1] = '\0';
-                        strncpy(cfg.host, r, sizeof(cfg.host)-1);
-                        cfg.host[sizeof(cfg.host)-1] = '\0';
-                        cfg.port = default_port;
-                    }
-                }
-            } else {
-                int len = sizeof(cfg.remote_cmd) - 1;
-                char *cp = cfg.remote_cmd;
-                int len2;
-
-                strncpy(cp, p, len); cp[len] = '\0';
-                len2 = strlen(cp); len -= len2; cp += len2;
-                while (--argc) {
-                    if (len > 0)
-                        len--, *cp++ = ' ';
-                    strncpy(cp, *++argv, len); cp[len] = '\0';
-                    len2 = strlen(cp); len -= len2; cp += len2;
-                }
-                cfg.nopty = TRUE;      /* command => no terminal */
-                break;                 /* done with cmdline */
-            }
+           if (!*cfg.host) {
+               char *q = p;
+               /*
+                * If the hostname starts with "telnet:", set the
+                * protocol to Telnet and process the string as a
+                * Telnet URL.
+                */
+               if (!strncmp(q, "telnet:", 7)) {
+                   char c;
+
+                   q += 7;
+                   if (q[0] == '/' && q[1] == '/')
+                       q += 2;
+                   cfg.protocol = PROT_TELNET;
+                   p = q;
+                   while (*p && *p != ':' && *p != '/')
+                       p++;
+                   c = *p;
+                   if (*p)
+                       *p++ = '\0';
+                   if (c == ':')
+                       cfg.port = atoi(p);
+                   else
+                       cfg.port = -1;
+                   strncpy(cfg.host, q, sizeof(cfg.host) - 1);
+                   cfg.host[sizeof(cfg.host) - 1] = '\0';
+               } else {
+                   char *r;
+                   /*
+                    * Before we process the [user@]host string, we
+                    * first check for the presence of a protocol
+                    * prefix (a protocol name followed by ",").
+                    */
+                   r = strchr(p, ',');
+                   if (r) {
+                       int i, j;
+                       for (i = 0; backends[i].backend != NULL; i++) {
+                           j = strlen(backends[i].name);
+                           if (j == r - p &&
+                               !memcmp(backends[i].name, p, j)) {
+                               default_protocol = cfg.protocol =
+                                   backends[i].protocol;
+                               portnumber =
+                                   backends[i].backend->default_port;
+                               p = r + 1;
+                               break;
+                           }
+                       }
+                   }
+
+                   /*
+                    * Three cases. Either (a) there's a nonzero
+                    * length string followed by an @, in which
+                    * case that's user and the remainder is host.
+                    * Or (b) there's only one string, not counting
+                    * a potential initial @, and it exists in the
+                    * saved-sessions database. Or (c) only one
+                    * string and it _doesn't_ exist in the
+                    * database.
+                    */
+                   r = strrchr(p, '@');
+                   if (r == p)
+                       p++, r = NULL; /* discount initial @ */
+                   if (r == NULL) {
+                       /*
+                        * One string.
+                        */
+                       Config cfg2;
+                       do_defaults(p, &cfg2);
+                       if (cfg2.host[0] == '\0') {
+                           /* No settings for this host; use defaults */
+                           strncpy(cfg.host, p, sizeof(cfg.host) - 1);
+                           cfg.host[sizeof(cfg.host) - 1] = '\0';
+                           cfg.port = default_port;
+                       } else {
+                           cfg = cfg2;
+                           cfg.remote_cmd_ptr = cfg.remote_cmd;
+                       }
+                   } else {
+                       *r++ = '\0';
+                       strncpy(cfg.username, p, sizeof(cfg.username) - 1);
+                       cfg.username[sizeof(cfg.username) - 1] = '\0';
+                       strncpy(cfg.host, r, sizeof(cfg.host) - 1);
+                       cfg.host[sizeof(cfg.host) - 1] = '\0';
+                       cfg.port = default_port;
+                   }
+               }
+           } else {
+               int len = sizeof(cfg.remote_cmd) - 1;
+               char *cp = cfg.remote_cmd;
+               int len2;
+
+               strncpy(cp, p, len);
+               cp[len] = '\0';
+               len2 = strlen(cp);
+               len -= len2;
+               cp += len2;
+               while (--argc) {
+                   if (len > 0)
+                       len--, *cp++ = ' ';
+                   strncpy(cp, *++argv, len);
+                   cp[len] = '\0';
+                   len2 = strlen(cp);
+                   len -= len2;
+                   cp += len2;
+               }
+               cfg.nopty = TRUE;      /* command => no terminal */
+               break;                 /* done with cmdline */
+           }
        }
     }
 
     if (!*cfg.host) {
-        usage();
+       usage();
     }
 
     if (!*cfg.remote_cmd_ptr)
-        flags |= FLAG_INTERACTIVE;
+       flags |= FLAG_INTERACTIVE;
 
     /*
      * Select protocol. This is farmed out into a table in a
      * separate file to enable an ssh-free variant.
      */
     {
-        int i;
-        back = NULL;
-        for (i = 0; backends[i].backend != NULL; i++)
-            if (backends[i].protocol == cfg.protocol) {
-                back = backends[i].backend;
-                break;
-            }
-        if (back == NULL) {
-            fprintf(stderr, "Internal fault: Unsupported protocol found\n");
-            return 1;
-        }
+       int i;
+       back = NULL;
+       for (i = 0; backends[i].backend != NULL; i++)
+           if (backends[i].protocol == cfg.protocol) {
+               back = backends[i].backend;
+               break;
+           }
+       if (back == NULL) {
+           fprintf(stderr,
+                   "Internal fault: Unsupported protocol found\n");
+           return 1;
+       }
     }
 
     /*
      * Select port.
      */
     if (portnumber != -1)
-        cfg.port = portnumber;
+       cfg.port = portnumber;
 
     /*
      * Initialise WinSock.
@@ -515,7 +545,7 @@ int main(int argc, char **argv) {
        char *error;
        char *realhost;
 
-       error = back->init (cfg.host, cfg.port, &realhost);
+       error = back->init(cfg.host, cfg.port, &realhost);
        if (error) {
            fprintf(stderr, "Unable to open connection:\n%s", error);
            return 1;
@@ -540,97 +570,98 @@ int main(int argc, char **argv) {
     handles[1] = stdinevent;
     sending = FALSE;
     while (1) {
-        int n;
-
-        if (!sending && back->sendok()) {
-            /*
-             * Create a separate thread to read from stdin. This is
-             * a total pain, but I can't find another way to do it:
-             *
-             *  - an overlapped ReadFile or ReadFileEx just doesn't
-             *    happen; we get failure from ReadFileEx, and
-             *    ReadFile blocks despite being given an OVERLAPPED
-             *    structure. Perhaps we can't do overlapped reads
-             *    on consoles. WHY THE HELL NOT?
-             
-             *  - WaitForMultipleObjects(netevent, console) doesn't
-             *    work, because it signals the console when
-             *    _anything_ happens, including mouse motions and
-             *    other things that don't cause data to be readable
-             *    - so we're back to ReadFile blocking.
-             */
-            idata.event = stdinevent;
-            idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
-            if (!CreateThread(NULL, 0, stdin_read_thread,
-                              &idata, 0, &threadid)) {
-                fprintf(stderr, "Unable to create second thread\n");
-                exit(1);
-            }
-            sending = TRUE;
-        }
-
-        n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
-        if (n == 0) {
-            WSANETWORKEVENTS things;
+       int n;
+
+       if (!sending && back->sendok()) {
+           /*
+            * Create a separate thread to read from stdin. This is
+            * a total pain, but I can't find another way to do it:
+            *
+            *  - an overlapped ReadFile or ReadFileEx just doesn't
+            *    happen; we get failure from ReadFileEx, and
+            *    ReadFile blocks despite being given an OVERLAPPED
+            *    structure. Perhaps we can't do overlapped reads
+            *    on consoles. WHY THE HELL NOT?
+            * 
+            *  - WaitForMultipleObjects(netevent, console) doesn't
+            *    work, because it signals the console when
+            *    _anything_ happens, including mouse motions and
+            *    other things that don't cause data to be readable
+            *    - so we're back to ReadFile blocking.
+            */
+           idata.event = stdinevent;
+           idata.eventback = CreateEvent(NULL, FALSE, FALSE, NULL);
+           if (!CreateThread(NULL, 0, stdin_read_thread,
+                             &idata, 0, &threadid)) {
+               fprintf(stderr, "Unable to create second thread\n");
+               exit(1);
+           }
+           sending = TRUE;
+       }
+
+       n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+       if (n == 0) {
+           WSANETWORKEVENTS things;
            SOCKET socket;
            extern SOCKET first_socket(int *), next_socket(int *);
            extern int select_result(WPARAM, LPARAM);
-            int i, socketstate;
-
-            /*
-             * We must not call select_result() for any socket
-             * until we have finished enumerating within the tree.
-             * This is because select_result() may close the socket
-             * and modify the tree.
-             */
-            /* Count the active sockets. */
-            i = 0;
-            for (socket = first_socket(&socketstate); socket != INVALID_SOCKET;
-                socket = next_socket(&socketstate))
-                i++;
-
-            /* Expand the buffer if necessary. */
-            if (i > sksize) {
-                sksize = i+16;
-                sklist = srealloc(sklist, sksize * sizeof(*sklist));
-            }
-
-            /* Retrieve the sockets into sklist. */
-            skcount = 0;
-           for (socket = first_socket(&socketstate); socket != INVALID_SOCKET;
+           int i, socketstate;
+
+           /*
+            * We must not call select_result() for any socket
+            * until we have finished enumerating within the tree.
+            * This is because select_result() may close the socket
+            * and modify the tree.
+            */
+           /* Count the active sockets. */
+           i = 0;
+           for (socket = first_socket(&socketstate);
+                socket != INVALID_SOCKET;
+                socket = next_socket(&socketstate)) i++;
+
+           /* Expand the buffer if necessary. */
+           if (i > sksize) {
+               sksize = i + 16;
+               sklist = srealloc(sklist, sksize * sizeof(*sklist));
+           }
+
+           /* Retrieve the sockets into sklist. */
+           skcount = 0;
+           for (socket = first_socket(&socketstate);
+                socket != INVALID_SOCKET;
                 socket = next_socket(&socketstate)) {
-                sklist[skcount++] = socket;
-            }
-
-            /* Now we're done enumerating; go through the list. */
-            for (i = 0; i < skcount; i++) {
-                WPARAM wp;
-                socket = sklist[i];
-                wp = (WPARAM)socket;
+               sklist[skcount++] = socket;
+           }
+
+           /* Now we're done enumerating; go through the list. */
+           for (i = 0; i < skcount; i++) {
+               WPARAM wp;
+               socket = sklist[i];
+               wp = (WPARAM) socket;
                if (!WSAEnumNetworkEvents(socket, NULL, &things)) {
-                    noise_ultralight(socket);
-                    noise_ultralight(things.lNetworkEvents);
+                   noise_ultralight(socket);
+                   noise_ultralight(things.lNetworkEvents);
                    if (things.lNetworkEvents & FD_READ)
-                       connopen &= select_result(wp, (LPARAM)FD_READ);
+                       connopen &= select_result(wp, (LPARAM) FD_READ);
                    if (things.lNetworkEvents & FD_CLOSE)
-                       connopen &= select_result(wp, (LPARAM)FD_CLOSE);
+                       connopen &= select_result(wp, (LPARAM) FD_CLOSE);
                    if (things.lNetworkEvents & FD_OOB)
-                       connopen &= select_result(wp, (LPARAM)FD_OOB);
+                       connopen &= select_result(wp, (LPARAM) FD_OOB);
                    if (things.lNetworkEvents & FD_WRITE)
-                        connopen &= select_result(wp, (LPARAM)FD_WRITE);
+                       connopen &= select_result(wp, (LPARAM) FD_WRITE);
                }
            }
-        } else if (n == 1) {
-            noise_ultralight(idata.len);
-            if (idata.len > 0) {
-                back->send(idata.buffer, idata.len);
-            } else {
-                back->special(TS_EOF);
-            }
-            SetEvent(idata.eventback);
-        }
-        if (!connopen || back->socket() == NULL)
-            break;                 /* we closed the connection */
+       } else if (n == 1) {
+           noise_ultralight(idata.len);
+           if (idata.len > 0) {
+               back->send(idata.buffer, idata.len);
+           } else {
+               back->special(TS_EOF);
+           }
+           SetEvent(idata.eventback);
+       }
+       if (!connopen || back->socket() == NULL)
+           break;                     /* we closed the connection */
     }
     WSACleanup();
     return 0;
diff --git a/psftp.c b/psftp.c
index 1e89575..fbf730a 100644 (file)
--- a/psftp.c
+++ b/psftp.c
  * String handling routines.
  */
 
-char *dupstr(char *s) {
+char *dupstr(char *s)
+{
     int len = strlen(s);
-    char *p = smalloc(len+1);
+    char *p = smalloc(len + 1);
     strcpy(p, s);
     return p;
 }
 
 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
-char *dupcat(char *s1, ...) {
+char *dupcat(char *s1, ...)
+{
     int len;
     char *p, *q, *sn;
     va_list ap;
@@ -43,7 +45,7 @@ char *dupcat(char *s1, ...) {
     }
     va_end(ap);
 
-    p = smalloc(len+1);
+    p = smalloc(len + 1);
     strcpy(p, s1);
     q = p + strlen(p);
 
@@ -75,14 +77,15 @@ char *pwd, *homedir;
  * canonification fails, at least fall back to returning a _valid_
  * pathname (though it may be ugly, eg /home/simon/../foobar).
  */
-char *canonify(char *name) {
+char *canonify(char *name)
+{
     char *fullname, *canonname;
 
     if (name[0] == '/') {
        fullname = dupstr(name);
     } else {
        char *slash;
-       if (pwd[strlen(pwd)-1] == '/')
+       if (pwd[strlen(pwd) - 1] == '/')
            slash = "";
        else
            slash = "/";
@@ -95,73 +98,73 @@ char *canonify(char *name) {
        sfree(fullname);
        return canonname;
     } else {
-        /*
-         * Attempt number 2. Some FXP_REALPATH implementations
-         * (glibc-based ones, in particular) require the _whole_
-         * path to point to something that exists, whereas others
-         * (BSD-based) only require all but the last component to
-         * exist. So if the first call failed, we should strip off
-         * everything from the last slash onwards and try again,
-         * then put the final component back on.
-         
-         * Special cases:
-         
-         *  - if the last component is "/." or "/..", then we don't
-         *    bother trying this because there's no way it can work.
-         
-         *  - if the thing actually ends with a "/", we remove it
-         *    before we start. Except if the string is "/" itself
-         *    (although I can't see why we'd have got here if so,
-         *    because surely "/" would have worked the first
-         *    time?), in which case we don't bother.
-         
-         *  - if there's no slash in the string at all, give up in
-         *    confusion (we expect at least one because of the way
-         *    we constructed the string).
-         */
-        
-        int i;
-        char *returnname;
-
-        i = strlen(fullname);
-        if (i > 2 && fullname[i-1] == '/')
-            fullname[--i] = '\0';      /* strip trailing / unless at pos 0 */
-        while (i > 0 && fullname[--i] != '/');
-
-        /*
-         * Give up on special cases.
-         */
-        if (fullname[i] != '/' ||      /* no slash at all */
-            !strcmp(fullname+i, "/.") ||   /* ends in /. */
-            !strcmp(fullname+i, "/..") ||   /* ends in /.. */
-            !strcmp(fullname, "/")) {
-            return fullname;
-        }
-
-        /*
-         * Now i points at the slash. Deal with the final special
-         * case i==0 (ie the whole path was "/nonexistentfile").
-         */
-        fullname[i] = '\0';            /* separate the string */
-        if (i == 0) {
-            canonname = fxp_realpath("/");
-        } else {
-            canonname = fxp_realpath(fullname);
-        }
-
-        if (!canonname)
-            return fullname;           /* even that failed; give up */
-
-        /*
-         * We have a canonical name for all but the last path
-         * component. Concatenate the last component and return.
-         */
-        returnname = dupcat(canonname,
-                            canonname[strlen(canonname)-1] == '/' ? "" : "/",
-                            fullname+i+1, NULL);
-        sfree(fullname);
-        sfree(canonname);
-        return returnname;
+       /*
+        * Attempt number 2. Some FXP_REALPATH implementations
+        * (glibc-based ones, in particular) require the _whole_
+        * path to point to something that exists, whereas others
+        * (BSD-based) only require all but the last component to
+        * exist. So if the first call failed, we should strip off
+        * everything from the last slash onwards and try again,
+        * then put the final component back on.
+        * 
+        * Special cases:
+        * 
+        *  - if the last component is "/." or "/..", then we don't
+        *    bother trying this because there's no way it can work.
+        * 
+        *  - if the thing actually ends with a "/", we remove it
+        *    before we start. Except if the string is "/" itself
+        *    (although I can't see why we'd have got here if so,
+        *    because surely "/" would have worked the first
+        *    time?), in which case we don't bother.
+        * 
+        *  - if there's no slash in the string at all, give up in
+        *    confusion (we expect at least one because of the way
+        *    we constructed the string).
+        */
+
+       int i;
+       char *returnname;
+
+       i = strlen(fullname);
+       if (i > 2 && fullname[i - 1] == '/')
+           fullname[--i] = '\0';      /* strip trailing / unless at pos 0 */
+       while (i > 0 && fullname[--i] != '/');
+
+       /*
+        * Give up on special cases.
+        */
+       if (fullname[i] != '/' ||      /* no slash at all */
+           !strcmp(fullname + i, "/.") ||      /* ends in /. */
+           !strcmp(fullname + i, "/..") ||     /* ends in /.. */
+           !strcmp(fullname, "/")) {
+           return fullname;
+       }
+
+       /*
+        * Now i points at the slash. Deal with the final special
+        * case i==0 (ie the whole path was "/nonexistentfile").
+        */
+       fullname[i] = '\0';            /* separate the string */
+       if (i == 0) {
+           canonname = fxp_realpath("/");
+       } else {
+           canonname = fxp_realpath(fullname);
+       }
+
+       if (!canonname)
+           return fullname;           /* even that failed; give up */
+
+       /*
+        * We have a canonical name for all but the last path
+        * component. Concatenate the last component and return.
+        */
+       returnname = dupcat(canonname,
+                           canonname[strlen(canonname) - 1] ==
+                           '/' ? "" : "/", fullname + i + 1, NULL);
+       sfree(fullname);
+       sfree(canonname);
+       return returnname;
     }
 }
 
@@ -171,19 +174,22 @@ char *canonify(char *name) {
 struct sftp_command {
     char **words;
     int nwords, wordssize;
-    int (*obey)(struct sftp_command *);/* returns <0 to quit */
+    int (*obey) (struct sftp_command *);       /* returns <0 to quit */
 };
 
-int sftp_cmd_null(struct sftp_command *cmd) {
+int sftp_cmd_null(struct sftp_command *cmd)
+{
     return 0;
 }
 
-int sftp_cmd_unknown(struct sftp_command *cmd) {
+int sftp_cmd_unknown(struct sftp_command *cmd)
+{
     printf("psftp: unknown command \"%s\"\n", cmd->words[0]);
     return 0;
 }
 
-int sftp_cmd_quit(struct sftp_command *cmd) {
+int sftp_cmd_quit(struct sftp_command *cmd)
+{
     return -1;
 }
 
@@ -191,12 +197,14 @@ int sftp_cmd_quit(struct sftp_command *cmd) {
  * List a directory. If no arguments are given, list pwd; otherwise
  * list the directory given in words[1].
  */
-static int sftp_ls_compare(const void *av, const void *bv) {
-    const struct fxp_name *a = (const struct fxp_name *)av;
-    const struct fxp_name *b = (const struct fxp_name *)bv;
+static int sftp_ls_compare(const void *av, const void *bv)
+{
+    const struct fxp_name *a = (const struct fxp_name *) av;
+    const struct fxp_name *b = (const struct fxp_name *) bv;
     return strcmp(a->filename, b->filename);
 }
-int sftp_cmd_ls(struct sftp_command *cmd) {
+int sftp_cmd_ls(struct sftp_command *cmd)
+{
     struct fxp_handle *dirh;
     struct fxp_names *names;
     struct fxp_name *ournames;
@@ -240,7 +248,8 @@ int sftp_cmd_ls(struct sftp_command *cmd) {
 
            if (nnames + names->nnames >= namesize) {
                namesize += names->nnames + 128;
-               ournames = srealloc(ournames, namesize * sizeof(*ournames));
+               ournames =
+                   srealloc(ournames, namesize * sizeof(*ournames));
            }
 
            for (i = 0; i < names->nnames; i++)
@@ -273,7 +282,8 @@ int sftp_cmd_ls(struct sftp_command *cmd) {
  * Change directories. We do this by canonifying the new name, then
  * trying to OPENDIR it. Only if that succeeds do we set the new pwd.
  */
-int sftp_cmd_cd(struct sftp_command *cmd) {
+int sftp_cmd_cd(struct sftp_command *cmd)
+{
     struct fxp_handle *dirh;
     char *dir;
 
@@ -306,7 +316,8 @@ int sftp_cmd_cd(struct sftp_command *cmd) {
 /*
  * Get a file and save it at the local end.
  */
-int sftp_cmd_get(struct sftp_command *cmd) {
+int sftp_cmd_get(struct sftp_command *cmd)
+{
     struct fxp_handle *fh;
     char *fname, *outfname;
     uint64 offset;
@@ -333,14 +344,14 @@ int sftp_cmd_get(struct sftp_command *cmd) {
     fp = fopen(outfname, "wb");
     if (!fp) {
        printf("local: unable to open %s\n", outfname);
-        fxp_close(fh);
+       fxp_close(fh);
        sfree(fname);
        return 0;
     }
 
     printf("remote:%s => local:%s\n", fname, outfname);
 
-    offset = uint64_make(0,0);
+    offset = uint64_make(0, 0);
 
     /*
      * FIXME: we can use FXP_FSTAT here to get the file size, and
@@ -352,17 +363,16 @@ int sftp_cmd_get(struct sftp_command *cmd) {
        int wpos, wlen;
 
        len = fxp_read(fh, buffer, offset, sizeof(buffer));
-       if ((len == -1 && fxp_error_type() == SSH_FX_EOF) ||
-           len == 0)
+       if ((len == -1 && fxp_error_type() == SSH_FX_EOF) || len == 0)
            break;
        if (len == -1) {
            printf("error while reading: %s\n", fxp_error());
            break;
        }
-       
+
        wpos = 0;
        while (wpos < len) {
-           wlen = fwrite(buffer, 1, len-wpos, fp);
+           wlen = fwrite(buffer, 1, len - wpos, fp);
            if (wlen <= 0) {
                printf("error while writing local file\n");
                break;
@@ -384,7 +394,8 @@ int sftp_cmd_get(struct sftp_command *cmd) {
 /*
  * Send a file and store it at the remote end.
  */
-int sftp_cmd_put(struct sftp_command *cmd) {
+int sftp_cmd_put(struct sftp_command *cmd)
+{
     struct fxp_handle *fh;
     char *fname, *origoutfname, *outfname;
     uint64 offset;
@@ -418,7 +429,7 @@ int sftp_cmd_put(struct sftp_command *cmd) {
 
     printf("local:%s => remote:%s\n", fname, outfname);
 
-    offset = uint64_make(0,0);
+    offset = uint64_make(0, 0);
 
     /*
      * FIXME: we can use FXP_FSTAT here to get the file size, and
@@ -451,26 +462,27 @@ int sftp_cmd_put(struct sftp_command *cmd) {
 
 static struct sftp_cmd_lookup {
     char *name;
-    int (*obey)(struct sftp_command *);
+    int (*obey) (struct sftp_command *);
 } sftp_lookup[] = {
     /*
      * List of sftp commands. This is binary-searched so it MUST be
      * in ASCII order.
      */
-    {"bye", sftp_cmd_quit},
-    {"cd", sftp_cmd_cd},
-    {"dir", sftp_cmd_ls},
-    {"exit", sftp_cmd_quit},
-    {"get", sftp_cmd_get},
-    {"ls", sftp_cmd_ls},
-    {"put", sftp_cmd_put},
-    {"quit", sftp_cmd_quit},
-};
+    {
+    "bye", sftp_cmd_quit}, {
+    "cd", sftp_cmd_cd}, {
+    "dir", sftp_cmd_ls}, {
+    "exit", sftp_cmd_quit}, {
+    "get", sftp_cmd_get}, {
+    "ls", sftp_cmd_ls}, {
+    "put", sftp_cmd_put}, {
+"quit", sftp_cmd_quit},};
 
 /* ----------------------------------------------------------------------
  * Command line reading and parsing.
  */
-struct sftp_command *sftp_getcmd(void) {
+struct sftp_command *sftp_getcmd(void)
+{
     char *line;
     int linelen, linesize;
     struct sftp_command *cmd;
@@ -493,16 +505,16 @@ struct sftp_command *sftp_getcmd(void) {
 
        linesize += 512;
        line = srealloc(line, linesize);
-       ret = fgets(line+linelen, linesize-linelen, stdin);
+       ret = fgets(line + linelen, linesize - linelen, stdin);
 
        if (!ret || (linelen == 0 && line[0] == '\0')) {
            cmd->obey = sftp_cmd_quit;
            printf("quit\n");
            return cmd;                /* eof */
        }
-       len = linelen + strlen(line+linelen);
+       len = linelen + strlen(line + linelen);
        linelen += len;
-       if (line[linelen-1] == '\n') {
+       if (line[linelen - 1] == '\n') {
            linelen--;
            line[linelen] = '\0';
            break;
@@ -528,7 +540,8 @@ struct sftp_command *sftp_getcmd(void) {
     p = line;
     while (*p) {
        /* skip whitespace */
-       while (*p && (*p == ' ' || *p == '\t')) p++;
+       while (*p && (*p == ' ' || *p == '\t'))
+           p++;
        /* mark start of word */
        q = r = p;                     /* q sits at start, r writes word */
        quoting = 0;
@@ -536,17 +549,19 @@ struct sftp_command *sftp_getcmd(void) {
            if (!quoting && (*p == ' ' || *p == '\t'))
                break;                 /* reached end of word */
            else if (*p == '"' && p[1] == '"')
-               p+=2, *r++ = '"';      /* a literal quote */
+               p += 2, *r++ = '"';    /* a literal quote */
            else if (*p == '"')
                p++, quoting = !quoting;
            else
                *r++ = *p++;
        }
-       if (*p) p++;                           /* skip over the whitespace */
+       if (*p)
+           p++;                       /* skip over the whitespace */
        *r = '\0';
        if (cmd->nwords >= cmd->wordssize) {
            cmd->wordssize = cmd->nwords + 16;
-           cmd->words = srealloc(cmd->words, cmd->wordssize*sizeof(char *));
+           cmd->words =
+               srealloc(cmd->words, cmd->wordssize * sizeof(char *));
        }
        cmd->words[cmd->nwords++] = q;
     }
@@ -581,14 +596,14 @@ struct sftp_command *sftp_getcmd(void) {
     return cmd;
 }
 
-void do_sftp(void) {
+void do_sftp(void)
+{
     /*
      * Do protocol initialisation. 
      */
     if (!fxp_init()) {
        fprintf(stderr,
-               "Fatal: unable to initialise SFTP: %s\n",
-               fxp_error());
+               "Fatal: unable to initialise SFTP: %s\n", fxp_error());
        return;
     }
 
@@ -626,38 +641,38 @@ void do_sftp(void) {
 static int verbose = 0;
 
 void verify_ssh_host_key(char *host, int port, char *keytype,
-                         char *keystr, char *fingerprint) {
+                        char *keystr, char *fingerprint)
+{
     int ret;
 
     static const char absentmsg[] =
-        "The server's host key is not cached in the registry. You\n"
-        "have no guarantee that the server is the computer you\n"
-        "think it is.\n"
-        "The server's key fingerprint is:\n"
-        "%s\n"
-        "If you trust this host, enter \"y\" to add the key to\n"
-        "PuTTY's cache and carry on connecting.\n"
-        "If you do not trust this host, enter \"n\" to abandon the\n"
-        "connection.\n"
-        "Continue connecting? (y/n) ";
+       "The server's host key is not cached in the registry. You\n"
+       "have no guarantee that the server is the computer you\n"
+       "think it is.\n"
+       "The server's key fingerprint is:\n"
+       "%s\n"
+       "If you trust this host, enter \"y\" to add the key to\n"
+       "PuTTY's cache and carry on connecting.\n"
+       "If you do not trust this host, enter \"n\" to abandon the\n"
+       "connection.\n" "Continue connecting? (y/n) ";
 
     static const char wrongmsg[] =
-        "WARNING - POTENTIAL SECURITY BREACH!\n"
-        "The server's host key does not match the one PuTTY has\n"
-        "cached in the registry. This means that either the\n"
-        "server administrator has changed the host key, or you\n"
-        "have actually connected to another computer pretending\n"
-        "to be the server.\n"
-        "The new key fingerprint is:\n"
-        "%s\n"
-        "If you were expecting this change and trust the new key,\n"
-        "enter Yes to update PuTTY's cache and continue connecting.\n"
-        "If you want to carry on connecting but without updating\n"
-        "the cache, enter No.\n"
-        "If you want to abandon the connection completely, press\n"
-        "Return to cancel. Pressing Return is the ONLY guaranteed\n"
-        "safe choice.\n"
-        "Update cached key? (y/n, Return cancels connection) ";
+       "WARNING - POTENTIAL SECURITY BREACH!\n"
+       "The server's host key does not match the one PuTTY has\n"
+       "cached in the registry. This means that either the\n"
+       "server administrator has changed the host key, or you\n"
+       "have actually connected to another computer pretending\n"
+       "to be the server.\n"
+       "The new key fingerprint is:\n"
+       "%s\n"
+       "If you were expecting this change and trust the new key,\n"
+       "enter Yes to update PuTTY's cache and continue connecting.\n"
+       "If you want to carry on connecting but without updating\n"
+       "the cache, enter No.\n"
+       "If you want to abandon the connection completely, press\n"
+       "Return to cancel. Pressing Return is the ONLY guaranteed\n"
+       "safe choice.\n"
+       "Update cached key? (y/n, Return cancels connection) ";
 
     static const char abandoned[] = "Connection abandoned.\n";
 
@@ -668,28 +683,28 @@ void verify_ssh_host_key(char *host, int port, char *keytype,
      */
     ret = verify_host_key(host, port, keytype, keystr);
 
-    if (ret == 0)                      /* success - key matched OK */
-        return;
-    if (ret == 2) {                    /* key was different */
-        fprintf(stderr, wrongmsg, fingerprint);
-        if (fgets(line, sizeof(line), stdin) &&
-            line[0] != '\0' && line[0] != '\n') {
-            if (line[0] == 'y' || line[0] == 'Y')
-                store_host_key(host, port, keytype, keystr);
-        } else {
-            fprintf(stderr, abandoned);
-            exit(0);
-        }
+    if (ret == 0)                     /* success - key matched OK */
+       return;
+    if (ret == 2) {                   /* key was different */
+       fprintf(stderr, wrongmsg, fingerprint);
+       if (fgets(line, sizeof(line), stdin) &&
+           line[0] != '\0' && line[0] != '\n') {
+           if (line[0] == 'y' || line[0] == 'Y')
+               store_host_key(host, port, keytype, keystr);
+       } else {
+           fprintf(stderr, abandoned);
+           exit(0);
+       }
     }
-    if (ret == 1) {                    /* key was absent */
-        fprintf(stderr, absentmsg, fingerprint);
-        if (fgets(line, sizeof(line), stdin) &&
-            (line[0] == 'y' || line[0] == 'Y'))
-            store_host_key(host, port, keytype, keystr);
-        else {
-            fprintf(stderr, abandoned);
-            exit(0);
-        }
+    if (ret == 1) {                   /* key was absent */
+       fprintf(stderr, absentmsg, fingerprint);
+       if (fgets(line, sizeof(line), stdin) &&
+           (line[0] == 'y' || line[0] == 'Y'))
+           store_host_key(host, port, keytype, keystr);
+       else {
+           fprintf(stderr, abandoned);
+           exit(0);
+       }
     }
 }
 
@@ -698,11 +713,11 @@ void verify_ssh_host_key(char *host, int port, char *keytype,
  */
 void fatalbox(char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     strcpy(str, "Fatal:");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     va_end(ap);
     strcat(str, "\n");
     fprintf(stderr, str);
@@ -711,11 +726,11 @@ void fatalbox(char *fmt, ...)
 }
 void connection_fatal(char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     strcpy(str, "Fatal:");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     va_end(ap);
     strcat(str, "\n");
     fprintf(stderr, str);
@@ -723,9 +738,12 @@ void connection_fatal(char *fmt, ...)
     exit(1);
 }
 
-void logevent(char *string) { }
+void logevent(char *string)
+{
+}
 
-void ldisc_send(char *buf, int len) {
+void ldisc_send(char *buf, int len)
+{
     /*
      * This is only here because of the calls to ldisc_send(NULL,
      * 0) in ssh.c. Nothing in PSFTP actually needs to use the
@@ -739,7 +757,8 @@ void ldisc_send(char *buf, int len) {
  * Be told what socket we're supposed to be using.
  */
 static SOCKET sftp_ssh_socket;
-char *do_select(SOCKET skt, int startup) {
+char *do_select(SOCKET skt, int startup)
+{
     if (startup)
        sftp_ssh_socket = skt;
     else
@@ -757,13 +776,14 @@ extern int select_result(WPARAM, LPARAM);
  * do this until we have enough data.
  */
 
-static unsigned char *outptr;          /* where to put the data */
-static unsigned outlen;                /* how much data required */
+static unsigned char *outptr;         /* where to put the data */
+static unsigned outlen;                       /* how much data required */
 static unsigned char *pending = NULL;  /* any spare data */
-static unsigned pendlen=0, pendsize=0; /* length and phys. size of buffer */
-void from_backend(int is_stderr, char *data, int datalen) {
-    unsigned char *p = (unsigned char *)data;
-    unsigned len = (unsigned)datalen;
+static unsigned pendlen = 0, pendsize = 0;     /* length and phys. size of buffer */
+void from_backend(int is_stderr, char *data, int datalen)
+{
+    unsigned char *p = (unsigned char *) data;
+    unsigned len = (unsigned) datalen;
 
     /*
      * stderr data is just spouted to local stderr and otherwise
@@ -778,30 +798,34 @@ void from_backend(int is_stderr, char *data, int datalen) {
      * If this is before the real session begins, just return.
      */
     if (!outptr)
-        return;
+       return;
 
     if (outlen > 0) {
-        unsigned used = outlen;
-        if (used > len) used = len;
-        memcpy(outptr, p, used);
-        outptr += used; outlen -= used;
-        p += used; len -= used;
+       unsigned used = outlen;
+       if (used > len)
+           used = len;
+       memcpy(outptr, p, used);
+       outptr += used;
+       outlen -= used;
+       p += used;
+       len -= used;
     }
 
     if (len > 0) {
-        if (pendsize < pendlen + len) {
-            pendsize = pendlen + len + 4096;
-            pending = (pending ? srealloc(pending, pendsize) :
-                       smalloc(pendsize));
-            if (!pending)
-                fatalbox("Out of memory");
-        }
-        memcpy(pending+pendlen, p, len);
-        pendlen += len;
+       if (pendsize < pendlen + len) {
+           pendsize = pendlen + len + 4096;
+           pending = (pending ? srealloc(pending, pendsize) :
+                      smalloc(pendsize));
+           if (!pending)
+               fatalbox("Out of memory");
+       }
+       memcpy(pending + pendlen, p, len);
+       pendlen += len;
     }
 }
-int sftp_recvdata(char *buf, int len) {
-    outptr = (unsigned char *)buf;
+int sftp_recvdata(char *buf, int len)
+{
+    outptr = (unsigned char *) buf;
     outlen = len;
 
     /*
@@ -809,53 +833,55 @@ int sftp_recvdata(char *buf, int len) {
      * need.
      */
     if (pendlen > 0) {
-        unsigned pendused = pendlen;
-        if (pendused > outlen)
-            pendused = outlen;
+       unsigned pendused = pendlen;
+       if (pendused > outlen)
+           pendused = outlen;
        memcpy(outptr, pending, pendused);
-        memmove(pending, pending+pendused, pendlen-pendused);
+       memmove(pending, pending + pendused, pendlen - pendused);
        outptr += pendused;
        outlen -= pendused;
-        pendlen -= pendused;
-        if (pendlen == 0) {
-            pendsize = 0;
-            sfree(pending);
-            pending = NULL;
-        }
-        if (outlen == 0)
-            return 1;
+       pendlen -= pendused;
+       if (pendlen == 0) {
+           pendsize = 0;
+           sfree(pending);
+           pending = NULL;
+       }
+       if (outlen == 0)
+           return 1;
     }
 
     while (outlen > 0) {
-        fd_set readfds;
+       fd_set readfds;
 
-        FD_ZERO(&readfds);
-        FD_SET(sftp_ssh_socket, &readfds);
-        if (select(1, &readfds, NULL, NULL, NULL) < 0)
-            return 0;                  /* doom */
-        select_result((WPARAM)sftp_ssh_socket, (LPARAM)FD_READ);
+       FD_ZERO(&readfds);
+       FD_SET(sftp_ssh_socket, &readfds);
+       if (select(1, &readfds, NULL, NULL, NULL) < 0)
+           return 0;                  /* doom */
+       select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
     }
 
     return 1;
 }
-int sftp_senddata(char *buf, int len) {
-    back->send((unsigned char *)buf, len);
+int sftp_senddata(char *buf, int len)
+{
+    back->send((unsigned char *) buf, len);
     return 1;
 }
 
 /*
  * Loop through the ssh connection and authentication process.
  */
-static void ssh_sftp_init(void) {
+static void ssh_sftp_init(void)
+{
     if (sftp_ssh_socket == INVALID_SOCKET)
        return;
     while (!back->sendok()) {
-        fd_set readfds;
-        FD_ZERO(&readfds);
-        FD_SET(sftp_ssh_socket, &readfds);
-        if (select(1, &readfds, NULL, NULL, NULL) < 0)
-            return;                    /* doom */
-        select_result((WPARAM)sftp_ssh_socket, (LPARAM)FD_READ);
+       fd_set readfds;
+       FD_ZERO(&readfds);
+       FD_SET(sftp_ssh_socket, &readfds);
+       if (select(1, &readfds, NULL, NULL, NULL) < 0)
+           return;                    /* doom */
+       select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
     }
 }
 
@@ -866,16 +892,16 @@ static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
     DWORD savemode, newmode, i;
 
     if (password) {
-        static int tried_once = 0;
-
-        if (tried_once) {
-            return 0;
-        } else {
-            strncpy(str, password, maxlen);
-            str[maxlen-1] = '\0';
-            tried_once = 1;
-            return 1;
-        }
+       static int tried_once = 0;
+
+       if (tried_once) {
+           return 0;
+       } else {
+           strncpy(str, password, maxlen);
+           str[maxlen - 1] = '\0';
+           tried_once = 1;
+           return 1;
+       }
     }
 
     hin = GetStdHandle(STD_INPUT_HANDLE);
@@ -888,21 +914,24 @@ static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
     GetConsoleMode(hin, &savemode);
     newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
     if (is_pw)
-        newmode &= ~ENABLE_ECHO_INPUT;
+       newmode &= ~ENABLE_ECHO_INPUT;
     else
-        newmode |= ENABLE_ECHO_INPUT;
+       newmode |= ENABLE_ECHO_INPUT;
     SetConsoleMode(hin, newmode);
 
     WriteFile(hout, prompt, strlen(prompt), &i, NULL);
-    ReadFile(hin, str, maxlen-1, &i, NULL);
+    ReadFile(hin, str, maxlen - 1, &i, NULL);
 
     SetConsoleMode(hin, savemode);
 
-    if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
+    if ((int) i > maxlen)
+       i = maxlen - 1;
+    else
+       i = i - 2;
     str[i] = '\0';
 
     if (is_pw)
-        WriteFile(hout, "\r\n", 2, &i, NULL);
+       WriteFile(hout, "\r\n", 2, &i, NULL);
 
     return 1;
 }
@@ -920,8 +949,7 @@ static void init_winsock(void)
        fprintf(stderr, "Unable to initialise WinSock");
        exit(1);
     }
-    if (LOBYTE(wsadata.wVersion) != 1 ||
-       HIBYTE(wsadata.wVersion) != 1) {
+    if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) {
        fprintf(stderr, "WinSock version is incompatible with 1.1");
        exit(1);
     }
@@ -970,11 +998,11 @@ int main(int argc, char *argv[])
        } else if (strcmp(argv[i], "-h") == 0 ||
                   strcmp(argv[i], "-?") == 0) {
            usage();
-       } else if (strcmp(argv[i], "-l") == 0 && i+1 < argc) {
+       } else if (strcmp(argv[i], "-l") == 0 && i + 1 < argc) {
            user = argv[++i];
-       } else if (strcmp(argv[i], "-P") == 0 && i+1 < argc) {
+       } else if (strcmp(argv[i], "-P") == 0 && i + 1 < argc) {
            portnumber = atoi(argv[++i]);
-       } else if (strcmp(argv[i], "-pw") == 0 && i+1 < argc) {
+       } else if (strcmp(argv[i], "-pw") == 0 && i + 1 < argc) {
            password = argv[++i];
        } else if (strcmp(argv[i], "--") == 0) {
            i++;
@@ -998,7 +1026,8 @@ int main(int argc, char *argv[])
     } else {
        *host++ = '\0';
        if (user) {
-           printf("psftp: multiple usernames specified; using \"%s\"\n", user);
+           printf("psftp: multiple usernames specified; using \"%s\"\n",
+                  user);
        } else
            user = userhost;
     }
@@ -1007,16 +1036,16 @@ int main(int argc, char *argv[])
     do_defaults(host, &cfg);
     if (cfg.host[0] == '\0') {
        /* No settings for this host; use defaults */
-        do_defaults(NULL, &cfg);
-       strncpy(cfg.host, host, sizeof(cfg.host)-1);
-       cfg.host[sizeof(cfg.host)-1] = '\0';
+       do_defaults(NULL, &cfg);
+       strncpy(cfg.host, host, sizeof(cfg.host) - 1);
+       cfg.host[sizeof(cfg.host) - 1] = '\0';
        cfg.port = 22;
     }
 
     /* Set username */
     if (user != NULL && user[0] != '\0') {
-       strncpy(cfg.username, user, sizeof(cfg.username)-1);
-       cfg.username[sizeof(cfg.username)-1] = '\0';
+       strncpy(cfg.username, user, sizeof(cfg.username) - 1);
+       cfg.username[sizeof(cfg.username) - 1] = '\0';
     }
     if (!cfg.username[0]) {
        printf("login as: ");
@@ -1025,8 +1054,8 @@ int main(int argc, char *argv[])
            exit(1);
        } else {
            int len = strlen(cfg.username);
-           if (cfg.username[len-1] == '\n')
-               cfg.username[len-1] = '\0';
+           if (cfg.username[len - 1] == '\n')
+               cfg.username[len - 1] = '\0';
        }
     }
 
diff --git a/putty.h b/putty.h
index 0bca719..de93bc2 100644 (file)
--- a/putty.h
+++ b/putty.h
@@ -83,12 +83,12 @@ GLOBAL int seen_disp_event;
 
 GLOBAL int session_closed;
 
-#define LGXF_OVR  1 /* existing logfile overwrite */
-#define LGXF_APN  0 /* existing logfile append */
-#define LGXF_ASK -1 /* existing logfile ask */
-#define LGTYP_NONE  0  /* logmode: no logging */
-#define LGTYP_ASCII 1  /* logmode: pure ascii */
-#define LGTYP_DEBUG 2  /* logmode: all chars of taffic */
+#define LGXF_OVR  1                   /* existing logfile overwrite */
+#define LGXF_APN  0                   /* existing logfile append */
+#define LGXF_ASK -1                   /* existing logfile ask */
+#define LGTYP_NONE  0                 /* logmode: no logging */
+#define LGTYP_ASCII 1                 /* logmode: pure ascii */
+#define LGTYP_DEBUG 2                 /* logmode: all chars of taffic */
 GLOBAL char *logfile;
 
 /*
@@ -136,17 +136,17 @@ enum {
     /*
      * Line discipline options which the backend might try to control.
      */
-    LD_EDIT,                           /* local line editing */
-    LD_ECHO                            /* local echo */
+    LD_EDIT,                          /* local line editing */
+    LD_ECHO                           /* local echo */
 };
 
 enum {
     /*
      * Close On Exit behaviours. (cfg.close_on_exit)
      */
-    COE_NEVER,      /* Never close the window */
-    COE_NORMAL,     /* Close window on "normal" (non-error) exits only */
-    COE_ALWAYS      /* Always close the window */
+    COE_NEVER,                        /* Never close the window */
+    COE_NORMAL,                               /* Close window on "normal" (non-error) exits only */
+    COE_ALWAYS                        /* Always close the window */
 };
 
 typedef struct {
@@ -154,7 +154,7 @@ typedef struct {
     void (*send) (char *buf, int len);
     void (*size) (void);
     void (*special) (Telnet_Special code);
-    Socket (*socket) (void);
+     Socket(*socket) (void);
     int (*sendok) (void);
     int (*ldisc) (int);
     int default_port;
@@ -175,24 +175,24 @@ typedef struct {
     enum { PROT_RAW, PROT_TELNET, PROT_RLOGIN, PROT_SSH } protocol;
     int close_on_exit;
     int warn_on_close;
-    int ping_interval;                 /* in seconds */
+    int ping_interval;                /* in seconds */
     /* SSH options */
     char remote_cmd[512];
-    char *remote_cmd_ptr;              /* might point to a larger command
-                                        * but never for loading/saving */
+    char *remote_cmd_ptr;             /* might point to a larger command
+                                       * but never for loading/saving */
     int nopty;
     int compression;
     int agentfwd;
     enum { CIPHER_3DES, CIPHER_BLOWFISH, CIPHER_DES, CIPHER_AES } cipher;
     char keyfile[FILENAME_MAX];
-    int sshprot;                       /* use v1 or v2 when both available */
-    int buggymac;                      /* MAC bug commmercial <=v2.3.x SSH2 */
+    int sshprot;                      /* use v1 or v2 when both available */
+    int buggymac;                     /* MAC bug commmercial <=v2.3.x SSH2 */
     int try_tis_auth;
     int ssh_subsys;                   /* run a subsystem rather than a command */
     /* Telnet options */
     char termtype[32];
     char termspeed[32];
-    char environmt[1024];                    /* VAR\tvalue\0VAR\tvalue\0\0 */
+    char environmt[1024];             /* VAR\tvalue\0VAR\tvalue\0\0 */
     char username[32];
     char localusername[32];
     int rfc_environ;
@@ -200,8 +200,8 @@ typedef struct {
     int bksp_is_delete;
     int rxvt_homeend;
     int funky_type;
-    int no_applic_c;                   /* totally disable app cursor keys */
-    int no_applic_k;                   /* totally disable app keypad */
+    int no_applic_c;                  /* totally disable app cursor keys */
+    int no_applic_k;                  /* totally disable app keypad */
     int app_cursor;
     int app_keypad;
     int nethack_keypad;
@@ -215,7 +215,7 @@ typedef struct {
     int scroll_on_disp;
     int compose_key;
     int ctrlaltkeys;
-    char wintitle[256];                /* initial window title */
+    char wintitle[256];                       /* initial window title */
     /* Terminal options */
     int savelines;
     int dec_om;
@@ -305,23 +305,23 @@ struct RSAKey;                           /* be a little careful of scope */
 /*
  * Exports from window.c.
  */
-void request_resize (int, int, int);
-void do_text (Context, int, int, char *, int, unsigned long, int);
-void set_title (char *);
-void set_icon (char *);
-void set_sbar (int, int, int);
+void request_resize(int, int, int);
+void do_text(Context, int, int, char *, int, unsigned long, int);
+void set_title(char *);
+void set_icon(char *);
+void set_sbar(int, int, int);
 Context get_ctx(void);
-void free_ctx (Context);
-void palette_set (int, int, int, int);
-void palette_reset (void);
-void write_clip (void *, int, int);
-void get_clip (void **, int *);
-void optimised_move (int, int, int);
+void free_ctx(Context);
+void palette_set(int, int, int, int);
+void palette_reset(void);
+void write_clip(void *, int, int);
+void get_clip(void **, int *);
+void optimised_move(int, int, int);
 void set_raw_mouse_mode(int);
 Mouse_Button translate_button(Mouse_Button b);
 void connection_fatal(char *, ...);
-void fatalbox (char *, ...);
-void beep (int);
+void fatalbox(char *, ...);
+void beep(int);
 void begin_session(void);
 void sys_cursor(int x, int y);
 #define OPTIMISE_IS_SCROLL 1
@@ -329,8 +329,8 @@ void sys_cursor(int x, int y);
 /*
  * Exports from noise.c.
  */
-void noise_get_heavy(void (*func)(void *, int));
-void noise_get_light(void (*func)(void *, int));
+void noise_get_heavy(void (*func) (void *, int));
+void noise_get_light(void (*func) (void *, int));
 void noise_regular(void);
 void noise_ultralight(DWORD data);
 void random_save_seed(void);
@@ -340,14 +340,14 @@ void random_destroy_seed(void);
  * Exports from windlg.c.
  */
 void defuse_showwindow(void);
-int do_config (void);
-int do_reconfig (HWND);
-void do_defaults (char *, Config *);
-void logevent (char *);
-void showeventlog (HWND);
-void showabout (HWND);
+int do_config(void);
+int do_reconfig(HWND);
+void do_defaults(char *, Config *);
+void logevent(char *);
+void showeventlog(HWND);
+void showabout(HWND);
 void verify_ssh_host_key(char *host, int port, char *keytype,
-                         char *keystr, char *fingerprint);
+                        char *keystr, char *fingerprint);
 int askappend(char *filename);
 void registry_cleanup(void);
 void force_normal(HWND hwnd);
@@ -358,32 +358,32 @@ GLOBAL char **sessions;
 /*
  * Exports from settings.c.
  */
-void save_settings (char *section, int do_host, Config *cfg);
-void load_settings (char *section, int do_host, Config *cfg);
+void save_settings(char *section, int do_host, Config * cfg);
+void load_settings(char *section, int do_host, Config * cfg);
 void get_sesslist(int allocate);
 
 /*
  * Exports from terminal.c.
  */
 
-void term_init (void);
-void term_size (int, int, int);
-void term_out (void);
-void term_paint (Context, int, int, int, int);
-void term_scroll (int, int);
-void term_pwron (void);
-void term_clrsb (void);
-void term_mouse (Mouse_Button, Mouse_Action, int, int, int, int);
-void term_deselect (void);
-void term_update (void);
+void term_init(void);
+void term_size(int, int, int);
+void term_out(void);
+void term_paint(Context, int, int, int, int);
+void term_scroll(int, int);
+void term_pwron(void);
+void term_clrsb(void);
+void term_mouse(Mouse_Button, Mouse_Action, int, int, int, int);
+void term_deselect(void);
+void term_update(void);
 void term_invalidate(void);
 void term_blink(int set_cursor);
 void term_paste(void);
 void term_nopaste(void);
 int term_ldisc(int option);
 void from_backend(int is_stderr, char *data, int len);
-void logfopen (void); 
-void logfclose (void);
+void logfopen(void);
+void logfclose(void);
 void term_copyall(void);
 
 /*
@@ -408,8 +408,8 @@ extern Backend telnet_backend;
  * Exports from ssh.c.
  */
 
-extern int (*ssh_get_line)(const char *prompt, char *str, int maxlen,
-                           int is_pw);
+extern int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
+                           int is_pw);
 extern Backend ssh_backend;
 
 /*
index 6f5d816..3f64ce7 100644 (file)
@@ -38,42 +38,45 @@ struct progress {
     HWND progbar;
 };
 
-static void progress_update(void *param, int phase, int iprogress) {
-    struct progress *p = (struct progress *)param;
+static void progress_update(void *param, int phase, int iprogress)
+{
+    struct progress *p = (struct progress *) param;
     unsigned progress = iprogress;
     int position;
 
     switch (phase) {
       case -1:
-        p->phase1param = 0x10000 + progress;
-        p->phase1current = 0x10000; p->phase1n = 0;
-        return;
+       p->phase1param = 0x10000 + progress;
+       p->phase1current = 0x10000;
+       p->phase1n = 0;
+       return;
       case -2:
-        p->phase2param = 0x10000 + progress;
-        p->phase2current = 0x10000; p->phase2n = 0;
-        return;
+       p->phase2param = 0x10000 + progress;
+       p->phase2current = 0x10000;
+       p->phase2n = 0;
+       return;
       case -3:
-        p->phase3mult = PHASE3TOTAL / progress;
-        return;
+       p->phase3mult = PHASE3TOTAL / progress;
+       return;
       case 1:
-        while (p->phase1n < progress) {
-            p->phase1n++;
-            p->phase1current *= p->phase1param;
-            p->phase1current /= 0x10000;
-        }
-        position = PHASE1START + 0x10000 - p->phase1current;
-        break;
+       while (p->phase1n < progress) {
+           p->phase1n++;
+           p->phase1current *= p->phase1param;
+           p->phase1current /= 0x10000;
+       }
+       position = PHASE1START + 0x10000 - p->phase1current;
+       break;
       case 2:
-        while (p->phase2n < progress) {
-            p->phase2n++;
-            p->phase2current *= p->phase2param;
-            p->phase2current /= 0x10000;
-        }
-        position = PHASE2START + 0x10000 - p->phase2current;
-        break;
+       while (p->phase2n < progress) {
+           p->phase2n++;
+           p->phase2current *= p->phase2param;
+           p->phase2current /= 0x10000;
+       }
+       position = PHASE2START + 0x10000 - p->phase2current;
+       break;
       case 3:
-        position = PHASE3START + progress * p->phase3mult;
-        break;
+       position = PHASE3START + progress * p->phase3mult;
+       break;
     }
 
     SendMessage(p->progbar, PBM_SETPOS, position / DIVISOR, 0);
@@ -92,15 +95,16 @@ struct PassphraseProcStruct {
  * Dialog-box function for the passphrase box.
  */
 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
-                                   WPARAM wParam, LPARAM lParam) {
+                                  WPARAM wParam, LPARAM lParam)
+{
     static char *passphrase = NULL;
     struct PassphraseProcStruct *p;
 
     switch (msg) {
       case WM_INITDIALOG:
-        SetForegroundWindow(hwnd);
-        SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
-                      SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
+       SetForegroundWindow(hwnd);
+       SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
+                    SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
 
        /*
         * Centre the window.
@@ -110,40 +114,42 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        p = (struct PassphraseProcStruct *)lParam;
-        passphrase = p->passphrase;
-        if (p->comment)
-            SetDlgItemText(hwnd, 101, p->comment);
-        *passphrase = 0;
-        SetDlgItemText(hwnd, 102, passphrase);
-        return 0;
+       p = (struct PassphraseProcStruct *) lParam;
+       passphrase = p->passphrase;
+       if (p->comment)
+           SetDlgItemText(hwnd, 101, p->comment);
+       *passphrase = 0;
+       SetDlgItemText(hwnd, 102, passphrase);
+       return 0;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
            if (*passphrase)
-               EndDialog (hwnd, 1);
+               EndDialog(hwnd, 1);
            else
-               MessageBeep (0);
+               MessageBeep(0);
            return 0;
          case IDCANCEL:
-           EndDialog (hwnd, 0);
+           EndDialog(hwnd, 0);
            return 0;
-          case 102:                    /* edit box */
+         case 102:                    /* edit box */
            if ((HIWORD(wParam) == EN_CHANGE) && passphrase) {
-                GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
-                passphrase[PASSPHRASE_MAXLEN-1] = '\0';
-            }
-            return 0;
+               GetDlgItemText(hwnd, 102, passphrase,
+                              PASSPHRASE_MAXLEN - 1);
+               passphrase[PASSPHRASE_MAXLEN - 1] = '\0';
+           }
+           return 0;
        }
        return 0;
       case WM_CLOSE:
-       EndDialog (hwnd, 0);
+       EndDialog(hwnd, 0);
        return 0;
     }
     return 0;
@@ -154,7 +160,8 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
  * FILENAME_MAX.
  */
 static int prompt_keyfile(HWND hwnd, char *dlgtitle,
-                          char *filename, int save) {
+                         char *filename, int save)
+{
     OPENFILENAME of;
     memset(&of, 0, sizeof(of));
 #ifdef OPENFILENAME_SIZE_VERSION_400
@@ -166,30 +173,33 @@ static int prompt_keyfile(HWND hwnd, char *dlgtitle,
     of.lpstrFilter = "All Files\0*\0\0\0";
     of.lpstrCustomFilter = NULL;
     of.nFilterIndex = 1;
-    of.lpstrFile = filename; *filename = '\0';
+    of.lpstrFile = filename;
+    *filename = '\0';
     of.nMaxFile = FILENAME_MAX;
     of.lpstrFileTitle = NULL;
     of.lpstrInitialDir = NULL;
     of.lpstrTitle = dlgtitle;
     of.Flags = 0;
     if (save)
-        return GetSaveFileName(&of);
+       return GetSaveFileName(&of);
     else
-        return GetOpenFileName(&of);
+       return GetOpenFileName(&of);
 }
 
 /*
  * This function is needed to link with the DES code. We need not
  * have it do anything at all.
  */
-void logevent(char *msg) {
+void logevent(char *msg)
+{
 }
 
 /*
  * Dialog-box function for the Licence box.
  */
-static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
-                                WPARAM wParam, LPARAM lParam) {
+static int CALLBACK LicenceProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
        /*
@@ -200,17 +210,18 @@ static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
-            EndDialog(hwnd, 1);
+           EndDialog(hwnd, 1);
            return 0;
        }
        return 0;
@@ -224,8 +235,9 @@ static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
 /*
  * Dialog-box function for the About box.
  */
-static int CALLBACK AboutProc (HWND hwnd, UINT msg,
-                              WPARAM wParam, LPARAM lParam) {
+static int CALLBACK AboutProc(HWND hwnd, UINT msg,
+                             WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
        /*
@@ -236,29 +248,30 @@ static int CALLBACK AboutProc (HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        SetDlgItemText (hwnd, 100, ver);
+       SetDlgItemText(hwnd, 100, ver);
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
-            EndDialog(hwnd, 1);
+           EndDialog(hwnd, 1);
            return 0;
          case 101:
            EnableWindow(hwnd, 0);
-           DialogBox (hinst, MAKEINTRESOURCE(214), NULL, LicenceProc);
+           DialogBox(hinst, MAKEINTRESOURCE(214), NULL, LicenceProc);
            EnableWindow(hwnd, 1);
-            SetActiveWindow(hwnd);
+           SetActiveWindow(hwnd);
            return 0;
        }
        return 0;
       case WM_CLOSE:
-        EndDialog(hwnd, 1);
+       EndDialog(hwnd, 1);
        return 0;
     }
     return 0;
@@ -268,14 +281,15 @@ static int CALLBACK AboutProc (HWND hwnd, UINT msg,
  * Thread to generate a key.
  */
 struct rsa_key_thread_params {
-    HWND progressbar;                  /* notify this with progress */
-    HWND dialog;                       /* notify this on completion */
+    HWND progressbar;                 /* notify this with progress */
+    HWND dialog;                      /* notify this on completion */
     int keysize;                      /* bits in key */
     struct RSAKey *key;
 };
-static DWORD WINAPI generate_rsa_key_thread(void *param) {
+static DWORD WINAPI generate_rsa_key_thread(void *param)
+{
     struct rsa_key_thread_params *params =
-        (struct rsa_key_thread_params *)param;
+       (struct rsa_key_thread_params *) param;
     struct progress prog;
     prog.progbar = params->progressbar;
 
@@ -300,45 +314,47 @@ struct MainDlgState {
     struct RSAKey key;
 };
 
-static void hidemany(HWND hwnd, const int *ids, int hideit) {
+static void hidemany(HWND hwnd, const int *ids, int hideit)
+{
     while (*ids) {
-        ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW));
+       ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW));
     }
 }
 
-static void setupbigedit1(HWND hwnd, int id, struct RSAKey *key) {
+static void setupbigedit1(HWND hwnd, int id, struct RSAKey *key)
+{
     char *buffer;
     char *dec1, *dec2;
 
     dec1 = bignum_decimal(key->exponent);
     dec2 = bignum_decimal(key->modulus);
-    buffer = smalloc(strlen(dec1)+strlen(dec2)+
-                     strlen(key->comment)+30);
+    buffer = smalloc(strlen(dec1) + strlen(dec2) +
+                    strlen(key->comment) + 30);
     sprintf(buffer, "%d %s %s %s",
-            bignum_bitcount(key->modulus),
-            dec1, dec2, key->comment);
+           bignum_bitcount(key->modulus), dec1, dec2, key->comment);
     SetDlgItemText(hwnd, id, buffer);
     sfree(dec1);
     sfree(dec2);
     sfree(buffer);
 }
 
-static void setupbigedit2(HWND hwnd, int id, struct ssh2_userkey *key) {
+static void setupbigedit2(HWND hwnd, int id, struct ssh2_userkey *key)
+{
     unsigned char *pub_blob;
     char *buffer, *p;
     int pub_len;
     int i;
 
     pub_blob = key->alg->public_blob(key->data, &pub_len);
-    buffer = smalloc(strlen(key->alg->name) + 4*((pub_len+2)/3) +
+    buffer = smalloc(strlen(key->alg->name) + 4 * ((pub_len + 2) / 3) +
                     strlen(key->comment) + 3);
     strcpy(buffer, key->alg->name);
     p = buffer + strlen(buffer);
     *p++ = ' ';
     i = 0;
     while (i < pub_len) {
-       int n = (pub_len-i < 3 ? pub_len-i : 3);
-       base64_encode_atom(pub_blob+i, n, p);
+       int n = (pub_len - i < 3 ? pub_len - i : 3);
+       base64_encode_atom(pub_blob + i, n, p);
        i += n;
        p += 4;
     }
@@ -346,47 +362,50 @@ static void setupbigedit2(HWND hwnd, int id, struct ssh2_userkey *key) {
     strcpy(p, key->comment);
     SetDlgItemText(hwnd, id, buffer);
     sfree(pub_blob);
-    sfree(buffer);    
+    sfree(buffer);
 }
 
 /*
  * Dialog-box function for the main PuTTYgen dialog box.
  */
-static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
-                                 WPARAM wParam, LPARAM lParam) {
+static int CALLBACK MainDlgProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     enum {
-        controlidstart = 100,
-        IDC_TITLE,
-        IDC_BOX_KEY,
-        IDC_NOKEY,
-        IDC_GENERATING,
-        IDC_PROGRESS,
-        IDC_PKSTATIC, IDC_KEYDISPLAY,
-        IDC_FPSTATIC, IDC_FINGERPRINT,
-        IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
-        IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
-        IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT,
-        IDC_BOX_ACTIONS,
-        IDC_GENSTATIC, IDC_GENERATE,
-        IDC_LOADSTATIC, IDC_LOAD,
-        IDC_SAVESTATIC, IDC_SAVE,
-        IDC_BOX_PARAMS,
+       controlidstart = 100,
+       IDC_TITLE,
+       IDC_BOX_KEY,
+       IDC_NOKEY,
+       IDC_GENERATING,
+       IDC_PROGRESS,
+       IDC_PKSTATIC, IDC_KEYDISPLAY,
+       IDC_FPSTATIC, IDC_FINGERPRINT,
+       IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
+       IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
+       IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT,
+       IDC_BOX_ACTIONS,
+       IDC_GENSTATIC, IDC_GENERATE,
+       IDC_LOADSTATIC, IDC_LOAD,
+       IDC_SAVESTATIC, IDC_SAVE,
+       IDC_BOX_PARAMS,
        IDC_TYPESTATIC, IDC_KEYSSH1, IDC_KEYSSH2RSA,
-        IDC_BITSSTATIC, IDC_BITS,
-        IDC_ABOUT,
+       IDC_BITSSTATIC, IDC_BITS,
+       IDC_ABOUT,
     };
     static const int nokey_ids[] = { IDC_NOKEY, 0 };
-    static const int generating_ids[] = { IDC_GENERATING, IDC_PROGRESS, 0 };
+    static const int generating_ids[] =
+       { IDC_GENERATING, IDC_PROGRESS, 0 };
     static const int gotkey_ids[] = {
-        IDC_PKSTATIC, IDC_KEYDISPLAY,
-        IDC_FPSTATIC, IDC_FINGERPRINT,
-        IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
-        IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
-        IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 0 };
+       IDC_PKSTATIC, IDC_KEYDISPLAY,
+       IDC_FPSTATIC, IDC_FINGERPRINT,
+       IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
+       IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
+       IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 0
+    };
     static const char generating_msg[] =
-        "Please wait while a key is generated...";
+       "Please wait while a key is generated...";
     static const char entropy_msg[] =
-        "Please generate some randomness by moving the mouse over the blank area.";
+       "Please generate some randomness by moving the mouse over the blank area.";
     struct MainDlgState *state;
 
     switch (msg) {
@@ -399,140 +418,138 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
            HWND hw;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        state = smalloc(sizeof(*state));
-        state->generation_thread_exists = FALSE;
-        state->collecting_entropy = FALSE;
-        state->entropy = NULL;
-        state->key_exists = FALSE;
-        SetWindowLong(hwnd, GWL_USERDATA, (LONG)state);
-        {
-            struct ctlpos cp, cp2;
+       state = smalloc(sizeof(*state));
+       state->generation_thread_exists = FALSE;
+       state->collecting_entropy = FALSE;
+       state->entropy = NULL;
+       state->key_exists = FALSE;
+       SetWindowLong(hwnd, GWL_USERDATA, (LONG) state);
+       {
+           struct ctlpos cp, cp2;
 
            /* Accelerators used: acglops */
 
-            ctlposinit(&cp, hwnd, 10, 10, 10);
-            bartitle(&cp, "Public and private key generation for PuTTY",
-                    IDC_TITLE);
-            beginbox(&cp, "Key",
-                     IDC_BOX_KEY);
-            cp2 = cp;
-            statictext(&cp2, "No key.", IDC_NOKEY);
-            cp2 = cp;
-            statictext(&cp2, "",
-                       IDC_GENERATING);
-            progressbar(&cp2, IDC_PROGRESS);
-            bigeditctrl(&cp,
-                        "&Public key for pasting into authorized_keys file:",
-                        IDC_PKSTATIC, IDC_KEYDISPLAY, 7);
-            SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
-            staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
-                       IDC_FINGERPRINT, 75);
-            SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1, 0);
-            staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
-                       IDC_COMMENTEDIT, 75);
-            staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
-                           IDC_PASSPHRASE1EDIT, 75);
-            staticpassedit(&cp, "C&onfirm passphrase:", IDC_PASSPHRASE2STATIC,
-                           IDC_PASSPHRASE2EDIT, 75);
-            endbox(&cp);
-            beginbox(&cp, "Actions",
-                     IDC_BOX_ACTIONS);
-            staticbtn(&cp, "Generate a public/private key pair",
-                      IDC_GENSTATIC, "&Generate", IDC_GENERATE);
-            staticbtn(&cp, "Load an existing private key file",
-                      IDC_LOADSTATIC, "&Load", IDC_LOAD);
-            staticbtn(&cp, "Save the generated key to a new file",
-                      IDC_SAVESTATIC, "&Save", IDC_SAVE);
-            endbox(&cp);
-            beginbox(&cp, "Parameters",
-                     IDC_BOX_PARAMS);
+           ctlposinit(&cp, hwnd, 10, 10, 10);
+           bartitle(&cp, "Public and private key generation for PuTTY",
+                    IDC_TITLE);
+           beginbox(&cp, "Key", IDC_BOX_KEY);
+           cp2 = cp;
+           statictext(&cp2, "No key.", IDC_NOKEY);
+           cp2 = cp;
+           statictext(&cp2, "", IDC_GENERATING);
+           progressbar(&cp2, IDC_PROGRESS);
+           bigeditctrl(&cp,
+                       "&Public key for pasting into authorized_keys file:",
+                       IDC_PKSTATIC, IDC_KEYDISPLAY, 7);
+           SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
+           staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
+                      IDC_FINGERPRINT, 75);
+           SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1,
+                              0);
+           staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
+                      IDC_COMMENTEDIT, 75);
+           staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
+                          IDC_PASSPHRASE1EDIT, 75);
+           staticpassedit(&cp, "C&onfirm passphrase:",
+                          IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 75);
+           endbox(&cp);
+           beginbox(&cp, "Actions", IDC_BOX_ACTIONS);
+           staticbtn(&cp, "Generate a public/private key pair",
+                     IDC_GENSTATIC, "&Generate", IDC_GENERATE);
+           staticbtn(&cp, "Load an existing private key file",
+                     IDC_LOADSTATIC, "&Load", IDC_LOAD);
+           staticbtn(&cp, "Save the generated key to a new file",
+                     IDC_SAVESTATIC, "&Save", IDC_SAVE);
+           endbox(&cp);
+           beginbox(&cp, "Parameters", IDC_BOX_PARAMS);
            radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 2,
-                          "SSH&1 (RSA)", IDC_KEYSSH1,
-                          "SSH2 &RSA", IDC_KEYSSH2RSA, NULL);
-            staticedit(&cp, "Number of &bits in a generated key:",
+                     "SSH&1 (RSA)", IDC_KEYSSH1,
+                     "SSH2 &RSA", IDC_KEYSSH2RSA, NULL);
+           staticedit(&cp, "Number of &bits in a generated key:",
                       IDC_BITSSTATIC, IDC_BITS, 20);
-            endbox(&cp);
-        }
+           endbox(&cp);
+       }
        CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2RSA, IDC_KEYSSH1);
        SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);
 
-        /*
-         * Initially, hide the progress bar and the key display,
-         * and show the no-key display. Also disable the Save
-         * button, because with no key we obviously can't save
-         * anything.
-         */
-        hidemany(hwnd, nokey_ids, FALSE);
-        hidemany(hwnd, generating_ids, TRUE);
-        hidemany(hwnd, gotkey_ids, TRUE);
-        EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
+       /*
+        * Initially, hide the progress bar and the key display,
+        * and show the no-key display. Also disable the Save
+        * button, because with no key we obviously can't save
+        * anything.
+        */
+       hidemany(hwnd, nokey_ids, FALSE);
+       hidemany(hwnd, generating_ids, TRUE);
+       hidemany(hwnd, gotkey_ids, TRUE);
+       EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
 
        return 1;
       case WM_MOUSEMOVE:
-        state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-        if (state->collecting_entropy &&
-            state->entropy &&
-            state->entropy_got < state->entropy_required) {
-            state->entropy[state->entropy_got++] = lParam;
-            state->entropy[state->entropy_got++] = GetMessageTime();
-            SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
-                               state->entropy_got, 0);
-            if (state->entropy_got >= state->entropy_required) {
-                struct rsa_key_thread_params *params;
-                DWORD threadid;
-
-                /*
-                 * Seed the entropy pool
-                 */
-                random_add_heavynoise(state->entropy, state->entropy_size);
-                memset(state->entropy, 0, state->entropy_size);
-                sfree(state->entropy);
-                state->collecting_entropy = FALSE;
-
-                SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
-                SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
-                                   MAKELPARAM(0, PROGRESSRANGE));
-                SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
-
-                params = smalloc(sizeof(*params));
-                params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
-                params->dialog = hwnd;
+       state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+       if (state->collecting_entropy &&
+           state->entropy && state->entropy_got < state->entropy_required) {
+           state->entropy[state->entropy_got++] = lParam;
+           state->entropy[state->entropy_got++] = GetMessageTime();
+           SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
+                              state->entropy_got, 0);
+           if (state->entropy_got >= state->entropy_required) {
+               struct rsa_key_thread_params *params;
+               DWORD threadid;
+
+               /*
+                * Seed the entropy pool
+                */
+               random_add_heavynoise(state->entropy, state->entropy_size);
+               memset(state->entropy, 0, state->entropy_size);
+               sfree(state->entropy);
+               state->collecting_entropy = FALSE;
+
+               SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
+               SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
+                                  MAKELPARAM(0, PROGRESSRANGE));
+               SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
+
+               params = smalloc(sizeof(*params));
+               params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
+               params->dialog = hwnd;
                params->keysize = state->keysize;
-                params->key = &state->key;
-
-                if (!CreateThread(NULL, 0, generate_rsa_key_thread,
-                                  params, 0, &threadid)) {
-                    MessageBox(hwnd, "Out of thread resources",
-                               "Key generation error",
-                               MB_OK | MB_ICONERROR);
-                    sfree(params);
-                } else {
-                    state->generation_thread_exists = TRUE;
-                }
-            }
-        }
-        break;
+               params->key = &state->key;
+
+               if (!CreateThread(NULL, 0, generate_rsa_key_thread,
+                                 params, 0, &threadid)) {
+                   MessageBox(hwnd, "Out of thread resources",
+                              "Key generation error",
+                              MB_OK | MB_ICONERROR);
+                   sfree(params);
+               } else {
+                   state->generation_thread_exists = TRUE;
+               }
+           }
+       }
+       break;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDC_COMMENTEDIT:
            if (HIWORD(wParam) == EN_CHANGE) {
-                state = (struct MainDlgState *)
-                    GetWindowLong(hwnd, GWL_USERDATA);
-                if (state->key_exists) {
-                    HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
-                    int len = GetWindowTextLength(editctl);
-                    if (*state->commentptr)
-                        sfree(*state->commentptr);
-                    *state->commentptr = smalloc(len+1);
-                    GetWindowText(editctl, *state->commentptr, len+1);
+               state = (struct MainDlgState *)
+                   GetWindowLong(hwnd, GWL_USERDATA);
+               if (state->key_exists) {
+                   HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
+                   int len = GetWindowTextLength(editctl);
+                   if (*state->commentptr)
+                       sfree(*state->commentptr);
+                   *state->commentptr = smalloc(len + 1);
+                   GetWindowText(editctl, *state->commentptr, len + 1);
                    if (state->ssh2) {
-                       setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
+                       setupbigedit2(hwnd, IDC_KEYDISPLAY,
+                                     &state->ssh2key);
                    } else {
                        setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
                    }
@@ -541,98 +558,99 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
            break;
          case IDC_ABOUT:
            EnableWindow(hwnd, 0);
-           DialogBox (hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
+           DialogBox(hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
            EnableWindow(hwnd, 1);
-            SetActiveWindow(hwnd);
+           SetActiveWindow(hwnd);
            return 0;
-          case IDC_GENERATE:
-            state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-            if (!state->generation_thread_exists) {
-                BOOL ok;
-                state->keysize = GetDlgItemInt(hwnd, IDC_BITS,
-                                               &ok, FALSE);
-                if (!ok) state->keysize = DEFAULT_KEYSIZE;
+         case IDC_GENERATE:
+           state =
+               (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+           if (!state->generation_thread_exists) {
+               BOOL ok;
+               state->keysize = GetDlgItemInt(hwnd, IDC_BITS, &ok, FALSE);
+               if (!ok)
+                   state->keysize = DEFAULT_KEYSIZE;
                /* If we ever introduce a new key type, check it here! */
                state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
-                if (state->keysize < 256) {
-                    int ret = MessageBox(hwnd,
-                                         "PuTTYgen will not generate a key"
-                                         " smaller than 256 bits.\n"
-                                         "Key length reset to 256. Continue?",
-                                         "PuTTYgen Warning",
-                                         MB_ICONWARNING | MB_OKCANCEL);
-                    if (ret != IDOK)
-                        break;
-                    state->keysize = 256;
-                    SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
-                }
-                hidemany(hwnd, nokey_ids, TRUE);
-                hidemany(hwnd, generating_ids, FALSE);
-                hidemany(hwnd, gotkey_ids, TRUE);
-                EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
-                EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
-                EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
-                state->key_exists = FALSE;
-                SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
-                state->collecting_entropy = TRUE;
-
-                /*
-                 * My brief statistical tests on mouse movements
-                 * suggest that there are about 2.5 bits of
-                 * randomness in the x position, 2.5 in the y
-                 * position, and 1.7 in the message time, making
-                 * 5.7 bits of unpredictability per mouse movement.
-                 * However, other people have told me it's far less
-                 * than that, so I'm going to be stupidly cautious
-                 * and knock that down to a nice round 2. With this
-                 * method, we require two words per mouse movement,
-                 * so with 2 bits per mouse movement we expect 2
-                 * bits every 2 words.
-                 */
-                state->entropy_required = (state->keysize/2) * 2;
-                state->entropy_got = 0;
-                state->entropy_size = (state->entropy_required *
-                                       sizeof(*state->entropy));
-                state->entropy = smalloc(state->entropy_size);
-
-                SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
-                                   MAKELPARAM(0, state->entropy_required));
-                SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
-            }
-            break;
-          case IDC_SAVE:
-            state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-            if (state->key_exists) {
-                char filename[FILENAME_MAX];
-                char passphrase[PASSPHRASE_MAXLEN];
-                char passphrase2[PASSPHRASE_MAXLEN];
-                GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
-                               passphrase, sizeof(passphrase));
-                GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
-                               passphrase2, sizeof(passphrase2));
+               if (state->keysize < 256) {
+                   int ret = MessageBox(hwnd,
+                                        "PuTTYgen will not generate a key"
+                                        " smaller than 256 bits.\n"
+                                        "Key length reset to 256. Continue?",
+                                        "PuTTYgen Warning",
+                                        MB_ICONWARNING | MB_OKCANCEL);
+                   if (ret != IDOK)
+                       break;
+                   state->keysize = 256;
+                   SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
+               }
+               hidemany(hwnd, nokey_ids, TRUE);
+               hidemany(hwnd, generating_ids, FALSE);
+               hidemany(hwnd, gotkey_ids, TRUE);
+               EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
+               EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
+               EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
+               state->key_exists = FALSE;
+               SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
+               state->collecting_entropy = TRUE;
+
+               /*
+                * My brief statistical tests on mouse movements
+                * suggest that there are about 2.5 bits of
+                * randomness in the x position, 2.5 in the y
+                * position, and 1.7 in the message time, making
+                * 5.7 bits of unpredictability per mouse movement.
+                * However, other people have told me it's far less
+                * than that, so I'm going to be stupidly cautious
+                * and knock that down to a nice round 2. With this
+                * method, we require two words per mouse movement,
+                * so with 2 bits per mouse movement we expect 2
+                * bits every 2 words.
+                */
+               state->entropy_required = (state->keysize / 2) * 2;
+               state->entropy_got = 0;
+               state->entropy_size = (state->entropy_required *
+                                      sizeof(*state->entropy));
+               state->entropy = smalloc(state->entropy_size);
+
+               SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
+                                  MAKELPARAM(0, state->entropy_required));
+               SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
+           }
+           break;
+         case IDC_SAVE:
+           state =
+               (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+           if (state->key_exists) {
+               char filename[FILENAME_MAX];
+               char passphrase[PASSPHRASE_MAXLEN];
+               char passphrase2[PASSPHRASE_MAXLEN];
+               GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
+                              passphrase, sizeof(passphrase));
+               GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
+                              passphrase2, sizeof(passphrase2));
                if (strcmp(passphrase, passphrase2)) {
-                    MessageBox(hwnd,
+                   MessageBox(hwnd,
                               "The two passphrases given do not match.",
-                              "PuTTYgen Error",
-                              MB_OK | MB_ICONERROR);
+                              "PuTTYgen Error", MB_OK | MB_ICONERROR);
                    break;
                }
-                if (!*passphrase) {
-                    int ret;
-                    ret = MessageBox(hwnd,
-                                     "Are you sure you want to save this key\n"
-                                     "without a passphrase to protect it?",
-                                     "PuTTYgen Warning",
-                                     MB_YESNO | MB_ICONWARNING);
-                    if (ret != IDYES)
-                        break;
-                }
-                if (prompt_keyfile(hwnd, "Save private key as:",
-                                   filename, 1)) {
+               if (!*passphrase) {
+                   int ret;
+                   ret = MessageBox(hwnd,
+                                    "Are you sure you want to save this key\n"
+                                    "without a passphrase to protect it?",
+                                    "PuTTYgen Warning",
+                                    MB_YESNO | MB_ICONWARNING);
+                   if (ret != IDYES)
+                       break;
+               }
+               if (prompt_keyfile(hwnd, "Save private key as:",
+                                  filename, 1)) {
                    int ret;
                    FILE *fp = fopen(filename, "r");
                    if (fp) {
-                       char buffer[FILENAME_MAX+80];
+                       char buffer[FILENAME_MAX + 80];
                        fclose(fp);
                        sprintf(buffer, "Overwrite existing file\n%.*s?",
                                FILENAME_MAX, filename);
@@ -643,38 +661,38 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
                    }
                    if (state->ssh2) {
                        ret = ssh2_save_userkey(filename, &state->ssh2key,
-                                               *passphrase ? passphrase : NULL);
+                                               *passphrase ? passphrase :
+                                               NULL);
                    } else {
                        ret = saversakey(filename, &state->key,
                                         *passphrase ? passphrase : NULL);
                    }
                    if (ret <= 0) {
                        MessageBox(hwnd, "Unable to save key file",
-                                  "PuTTYgen Error",
-                                  MB_OK | MB_ICONERROR);
+                                  "PuTTYgen Error", MB_OK | MB_ICONERROR);
                    }
-                }
-            }
-            break;
-          case IDC_LOAD:
-            state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-            if (!state->generation_thread_exists) {
-                char filename[FILENAME_MAX];
-                if (prompt_keyfile(hwnd, "Load private key:",
-                                   filename, 0)) {
-                    char passphrase[PASSPHRASE_MAXLEN];
-                    int needs_pass;
+               }
+           }
+           break;
+         case IDC_LOAD:
+           state =
+               (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+           if (!state->generation_thread_exists) {
+               char filename[FILENAME_MAX];
+               if (prompt_keyfile(hwnd, "Load private key:", filename, 0)) {
+                   char passphrase[PASSPHRASE_MAXLEN];
+                   int needs_pass;
                    int ver;
-                    int ret;
-                    char *comment;
-                    struct PassphraseProcStruct pps;
-                    struct RSAKey newkey1;
+                   int ret;
+                   char *comment;
+                   struct PassphraseProcStruct pps;
+                   struct RSAKey newkey1;
                    struct ssh2_userkey *newkey2;
 
                    ver = keyfile_version(filename);
                    if (ver == 0) {
-                        MessageBox(NULL, "Couldn't load private key.",
-                                   "PuTTYgen Error", MB_OK | MB_ICONERROR);
+                       MessageBox(NULL, "Couldn't load private key.",
+                                  "PuTTYgen Error", MB_OK | MB_ICONERROR);
                        break;
                    }
 
@@ -682,26 +700,29 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
                    if (ver == 1)
                        needs_pass = rsakey_encrypted(filename, &comment);
                    else
-                       needs_pass = ssh2_userkey_encrypted(filename, &comment);
-                    pps.passphrase = passphrase;
-                    pps.comment = comment;
-                    do {
-                        if (needs_pass) {
-                            int dlgret;
-                            dlgret = DialogBoxParam(hinst,
-                                                    MAKEINTRESOURCE(210),
-                                                    NULL, PassphraseProc,
-                                                    (LPARAM)&pps);
-                            if (!dlgret) {
-                                ret = -2;
-                                break;
-                            }
-                        } else
-                            *passphrase = '\0';
+                       needs_pass =
+                           ssh2_userkey_encrypted(filename, &comment);
+                   pps.passphrase = passphrase;
+                   pps.comment = comment;
+                   do {
+                       if (needs_pass) {
+                           int dlgret;
+                           dlgret = DialogBoxParam(hinst,
+                                                   MAKEINTRESOURCE(210),
+                                                   NULL, PassphraseProc,
+                                                   (LPARAM) & pps);
+                           if (!dlgret) {
+                               ret = -2;
+                               break;
+                           }
+                       } else
+                           *passphrase = '\0';
                        if (ver == 1)
-                           ret = loadrsakey(filename, &newkey1, passphrase);
+                           ret =
+                               loadrsakey(filename, &newkey1, passphrase);
                        else {
-                           newkey2 = ssh2_load_userkey(filename, passphrase);
+                           newkey2 =
+                               ssh2_load_userkey(filename, passphrase);
                            if (newkey2 == SSH2_WRONG_PASSPHRASE)
                                ret = -1;
                            else if (!newkey2)
@@ -709,24 +730,25 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
                            else
                                ret = 1;
                        }
-                    } while (ret == -1);
-                    if (comment) sfree(comment);
-                    if (ret == 0) {
-                        MessageBox(NULL, "Couldn't load private key.",
-                                   "PuTTYgen Error", MB_OK | MB_ICONERROR);
-                    } else if (ret == 1) {
-                        EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
-                        EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
-                        EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
-                        /*
-                         * Now update the key controls with all the
-                         * key data.
-                         */
-                        {
-                            SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
-                                           passphrase);
-                            SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
-                                           passphrase);
+                   } while (ret == -1);
+                   if (comment)
+                       sfree(comment);
+                   if (ret == 0) {
+                       MessageBox(NULL, "Couldn't load private key.",
+                                  "PuTTYgen Error", MB_OK | MB_ICONERROR);
+                   } else if (ret == 1) {
+                       EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
+                       EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
+                       EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
+                       /*
+                        * Now update the key controls with all the
+                        * key data.
+                        */
+                       {
+                           SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
+                                          passphrase);
+                           SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
+                                          passphrase);
                            if (ver == 1) {
                                char buf[128];
                                char *savecomment;
@@ -739,9 +761,10 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
                                 * Set the key fingerprint.
                                 */
                                savecomment = state->key.comment;
-                                state->key.comment = NULL;
-                                rsa_fingerprint(buf, sizeof(buf), &state->key);
-                                state->key.comment = savecomment;
+                               state->key.comment = NULL;
+                               rsa_fingerprint(buf, sizeof(buf),
+                                               &state->key);
+                               state->key.comment = savecomment;
 
                                SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
                                /*
@@ -749,52 +772,57 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
                                 * of the key, for pasting into
                                 * .ssh/authorized_keys on a Unix box.
                                 */
-                               setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
+                               setupbigedit1(hwnd, IDC_KEYDISPLAY,
+                                             &state->key);
                            } else {
                                char *fp;
                                char *savecomment;
 
                                state->ssh2 = TRUE;
-                               state->commentptr = &state->ssh2key.comment;
-                               state->ssh2key = *newkey2;   /* structure copy */
+                               state->commentptr =
+                                   &state->ssh2key.comment;
+                               state->ssh2key = *newkey2;      /* structure copy */
                                sfree(newkey2);
 
                                savecomment = state->ssh2key.comment;
-                                state->ssh2key.comment = NULL;
-                               fp = state->
-                                   ssh2key.alg->fingerprint(state->ssh2key.data);
-                                state->ssh2key.comment = savecomment;
+                               state->ssh2key.comment = NULL;
+                               fp =
+                                   state->ssh2key.alg->
+                                   fingerprint(state->ssh2key.data);
+                               state->ssh2key.comment = savecomment;
 
                                SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
                                sfree(fp);
 
-                               setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
+                               setupbigedit2(hwnd, IDC_KEYDISPLAY,
+                                             &state->ssh2key);
                            }
-                            SetDlgItemText(hwnd, IDC_COMMENTEDIT,
-                                           *state->commentptr);
-                        }
-                        /*
-                         * Finally, hide the progress bar and show
-                         * the key data.
-                         */
-                        hidemany(hwnd, nokey_ids, TRUE);
-                        hidemany(hwnd, generating_ids, TRUE);
-                        hidemany(hwnd, gotkey_ids, FALSE);
-                        state->key_exists = TRUE;
-                    }
-                }
-            }
-            break;
+                           SetDlgItemText(hwnd, IDC_COMMENTEDIT,
+                                          *state->commentptr);
+                       }
+                       /*
+                        * Finally, hide the progress bar and show
+                        * the key data.
+                        */
+                       hidemany(hwnd, nokey_ids, TRUE);
+                       hidemany(hwnd, generating_ids, TRUE);
+                       hidemany(hwnd, gotkey_ids, FALSE);
+                       state->key_exists = TRUE;
+                   }
+               }
+           }
+           break;
        }
        return 0;
       case WM_DONEKEY:
-        state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-        state->generation_thread_exists = FALSE;
-        state->key_exists = TRUE;
-        SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
-        EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
-        EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
-        EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
+       state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+       state->generation_thread_exists = FALSE;
+       state->key_exists = TRUE;
+       SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE,
+                          0);
+       EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
+       EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
+       EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
        if (state->ssh2) {
            state->ssh2key.data = &state->key;
            state->ssh2key.alg = &ssh_rsa;
@@ -802,82 +830,84 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
        } else {
            state->commentptr = &state->key.comment;
        }
-        /*
-         * Invent a comment for the key. We'll do this by including
-         * the date in it. This will be so horrifyingly ugly that
-         * the user will immediately want to change it, which is
-         * what we want :-)
-         */
-        *state->commentptr = smalloc(30);
-        {
-            time_t t;
-            struct tm *tm;
-            time(&t);
-            tm = localtime(&t);
-            strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
-        }
-            
-        /*
-         * Now update the key controls with all the key data.
-         */
-        {
+       /*
+        * Invent a comment for the key. We'll do this by including
+        * the date in it. This will be so horrifyingly ugly that
+        * the user will immediately want to change it, which is
+        * what we want :-)
+        */
+       *state->commentptr = smalloc(30);
+       {
+           time_t t;
+           struct tm *tm;
+           time(&t);
+           tm = localtime(&t);
+           strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
+       }
+
+       /*
+        * Now update the key controls with all the key data.
+        */
+       {
            char *savecomment;
-            /*
-             * Blank passphrase, initially. This isn't dangerous,
-             * because we will warn (Are You Sure?) before allowing
-             * the user to save an unprotected private key.
-             */
-            SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
-            SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
-            /*
-             * Set the comment.
-             */
-            SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
-            /*
-             * Set the key fingerprint.
-             */
+           /*
+            * Blank passphrase, initially. This isn't dangerous,
+            * because we will warn (Are You Sure?) before allowing
+            * the user to save an unprotected private key.
+            */
+           SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
+           SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
+           /*
+            * Set the comment.
+            */
+           SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
+           /*
+            * Set the key fingerprint.
+            */
            savecomment = *state->commentptr;
            *state->commentptr = NULL;
-            if (state->ssh2) {
+           if (state->ssh2) {
                char *fp;
-                fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
+               fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
                SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
                sfree(fp);
            } else {
                char buf[128];
-                rsa_fingerprint(buf, sizeof(buf), &state->key);
+               rsa_fingerprint(buf, sizeof(buf), &state->key);
                SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
-            }
+           }
            *state->commentptr = savecomment;
-            /*
-             * Construct a decimal representation of the key, for
-             * pasting into .ssh/authorized_keys on a Unix box.
-             */
+           /*
+            * Construct a decimal representation of the key, for
+            * pasting into .ssh/authorized_keys on a Unix box.
+            */
            if (state->ssh2) {
                setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
            } else {
                setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
            }
-        }
-        /*
-         * Finally, hide the progress bar and show the key data.
-         */
-        hidemany(hwnd, nokey_ids, TRUE);
-        hidemany(hwnd, generating_ids, TRUE);
-        hidemany(hwnd, gotkey_ids, FALSE);
-        break;
+       }
+       /*
+        * Finally, hide the progress bar and show the key data.
+        */
+       hidemany(hwnd, nokey_ids, TRUE);
+       hidemany(hwnd, generating_ids, TRUE);
+       hidemany(hwnd, gotkey_ids, FALSE);
+       break;
       case WM_CLOSE:
-        state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
-        sfree(state);
-        EndDialog(hwnd, 1);
+       state = (struct MainDlgState *) GetWindowLong(hwnd, GWL_USERDATA);
+       sfree(state);
+       EndDialog(hwnd, 1);
        return 0;
     }
     return 0;
 }
 
-int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
+int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
+{
     InitCommonControls();
     hinst = inst;
     random_init();
-    return DialogBox(hinst, MAKEINTRESOURCE(201), NULL, MainDlgProc) != IDOK;
+    return DialogBox(hinst, MAKEINTRESOURCE(201), NULL,
+                    MainDlgProc) != IDOK;
 }
index 4396592..938e340 100644 (file)
@@ -5,8 +5,8 @@
 #ifndef PUTTY_PUTTYMEM_H
 #define PUTTY_PUTTYMEM_H
 
-#include <stddef.h> /* for size_t */
-#include <string.h> /* for memcpy() */
+#include <stddef.h>                   /* for size_t */
+#include <string.h>                   /* for memcpy() */
 
 
 /* #define MALLOC_LOG  do this if you suspect putty of leaking memory */
diff --git a/raw.c b/raw.c
index 7990d1d..6106176 100644 (file)
--- a/raw.c
+++ b/raw.c
@@ -20,21 +20,25 @@ static char *sb_buf = NULL;
 static int sb_size = 0;
 #define SB_DELTA 1024
 
-static void c_write (char *buf, int len) {
+static void c_write(char *buf, int len)
+{
     from_backend(0, buf, len);
 }
 
-static int raw_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
+static int raw_closing(Plug plug, char *error_msg, int error_code,
+                      int calling_back)
+{
     sk_close(s);
     s = NULL;
     if (error_msg) {
-        /* A socket error has occurred. */
-        connection_fatal (error_msg);
-    } /* Otherwise, the remote side closed the connection normally. */
+       /* A socket error has occurred. */
+       connection_fatal(error_msg);
+    }                                 /* Otherwise, the remote side closed the connection normally. */
     return 0;
 }
 
-static int raw_receive (Plug plug, int urgent, char *data, int len) {
+static int raw_receive(Plug plug, int urgent, char *data, int len)
+{
     c_write(data, len);
     return 1;
 }
@@ -46,7 +50,8 @@ static int raw_receive (Plug plug, int urgent, char *data, int len) {
  *
  * Also places the canonical host name into `realhost'.
  */
-static char *raw_init (char *host, int port, char **realhost) {
+static char *raw_init(char *host, int port, char **realhost)
+{
     static struct plug_function_table fn_table = {
        raw_closing,
        raw_receive
@@ -59,7 +64,7 @@ static char *raw_init (char *host, int port, char **realhost) {
      * Try to find host.
      */
     addr = sk_namelookup(host, realhost);
-    if ( (err = sk_addr_error(addr)) )
+    if ((err = sk_addr_error(addr)))
        return err;
 
     if (port < 0)
@@ -69,7 +74,7 @@ static char *raw_init (char *host, int port, char **realhost) {
      * Open socket.
      */
     s = sk_new(addr, port, 0, 1, &fn_table_ptr);
-    if ( (err = sk_socket_error(s)) )
+    if ((err = sk_socket_error(s)))
        return err;
 
     sk_addr_free(addr);
@@ -80,7 +85,8 @@ static char *raw_init (char *host, int port, char **realhost) {
 /*
  * Called to send data down the raw connection.
  */
-static void raw_send (char *buf, int len) {
+static void raw_send(char *buf, int len)
+{
 
     if (s == NULL)
        return;
@@ -91,7 +97,8 @@ static void raw_send (char *buf, int len) {
 /*
  * Called to set the size of the window
  */
-static void raw_size(void) {
+static void raw_size(void)
+{
     /* Do nothing! */
     return;
 }
@@ -99,18 +106,26 @@ static void raw_size(void) {
 /*
  * Send raw special codes.
  */
-static void raw_special (Telnet_Special code) {
+static void raw_special(Telnet_Special code)
+{
     /* Do nothing! */
     return;
 }
 
-static Socket raw_socket(void) { return s; }
+static Socket raw_socket(void)
+{
+    return s;
+}
 
-static int raw_sendok(void) { return 1; }
+static int raw_sendok(void)
+{
+    return 1;
+}
 
-static int raw_ldisc(int option) {
+static int raw_ldisc(int option)
+{
     if (option == LD_EDIT || option == LD_ECHO)
-        return 1;
+       return 1;
     return 0;
 }
 
index acb27c8..688c159 100644 (file)
--- a/rlogin.c
+++ b/rlogin.c
@@ -21,48 +21,53 @@ static char *sb_buf = NULL;
 static int sb_size = 0;
 #define SB_DELTA 1024
 
-static void c_write (char *buf, int len) {
+static void c_write(char *buf, int len)
+{
     from_backend(0, buf, len);
 }
 
-static int rlogin_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
+static int rlogin_closing(Plug plug, char *error_msg, int error_code,
+                         int calling_back)
+{
     sk_close(s);
     s = NULL;
     if (error_msg) {
-        /* A socket error has occurred. */
-        connection_fatal (error_msg);
-    } /* Otherwise, the remote side closed the connection normally. */
+       /* A socket error has occurred. */
+       connection_fatal(error_msg);
+    }                                 /* Otherwise, the remote side closed the connection normally. */
     return 0;
 }
 
-static int rlogin_receive (Plug plug, int urgent, char *data, int len) {
+static int rlogin_receive(Plug plug, int urgent, char *data, int len)
+{
     if (urgent == 2) {
-        char c;
-        
-        c = *data++; len--;
-        if (c == '\x80')
-            rlogin_size();
-        /*
-         * We should flush everything (aka Telnet SYNCH) if we see
-         * 0x02, and we should turn off and on _local_ flow control
-         * on 0x10 and 0x20 respectively. I'm not convinced it's
-         * worth it...
-         */
+       char c;
+
+       c = *data++;
+       len--;
+       if (c == '\x80')
+           rlogin_size();
+       /*
+        * We should flush everything (aka Telnet SYNCH) if we see
+        * 0x02, and we should turn off and on _local_ flow control
+        * on 0x10 and 0x20 respectively. I'm not convinced it's
+        * worth it...
+        */
     } else {
-        /*
-         * Main rlogin protocol. This is really simple: the first
-         * byte is expected to be NULL and is ignored, and the rest
-         * is printed.
-         */
-        static int firstbyte = 1;
-        if (firstbyte) {
-            if (data[0] == '\0') {
-                data++;
-                len--;
-            }
-            firstbyte = 0;
-        }
-        c_write(data, len);
+       /*
+        * Main rlogin protocol. This is really simple: the first
+        * byte is expected to be NULL and is ignored, and the rest
+        * is printed.
+        */
+       static int firstbyte = 1;
+       if (firstbyte) {
+           if (data[0] == '\0') {
+               data++;
+               len--;
+           }
+           firstbyte = 0;
+       }
+       c_write(data, len);
     }
     return 1;
 }
@@ -74,7 +79,8 @@ static int rlogin_receive (Plug plug, int urgent, char *data, int len) {
  *
  * Also places the canonical host name into `realhost'.
  */
-static char *rlogin_init (char *host, int port, char **realhost) {
+static char *rlogin_init(char *host, int port, char **realhost)
+{
     static struct plug_function_table fn_table = {
        rlogin_closing,
        rlogin_receive
@@ -87,7 +93,7 @@ static char *rlogin_init (char *host, int port, char **realhost) {
      * Try to find host.
      */
     addr = sk_namelookup(host, realhost);
-    if ( (err = sk_addr_error(addr)) )
+    if ((err = sk_addr_error(addr)))
        return err;
 
     if (port < 0)
@@ -97,7 +103,7 @@ static char *rlogin_init (char *host, int port, char **realhost) {
      * Open socket.
      */
     s = sk_new(addr, port, 1, 0, &fn_table_ptr);
-    if ( (err = sk_socket_error(s)) )
+    if ((err = sk_socket_error(s)))
        return err;
 
     sk_addr_free(addr);
@@ -107,18 +113,18 @@ static char *rlogin_init (char *host, int port, char **realhost) {
      */
 
     {
-        char z = 0;
-        char *p;
-        sk_write(s, &z, 1);
-        sk_write(s, cfg.localusername, strlen(cfg.localusername));
-        sk_write(s, &z, 1);
-        sk_write(s, cfg.username, strlen(cfg.username));
-        sk_write(s, &z, 1);
-        sk_write(s, cfg.termtype, strlen(cfg.termtype));
-        sk_write(s, "/", 1);
-        for(p = cfg.termspeed; isdigit(*p); p++);
-        sk_write(s, cfg.termspeed, p - cfg.termspeed);
-        sk_write(s, &z, 1);
+       char z = 0;
+       char *p;
+       sk_write(s, &z, 1);
+       sk_write(s, cfg.localusername, strlen(cfg.localusername));
+       sk_write(s, &z, 1);
+       sk_write(s, cfg.username, strlen(cfg.username));
+       sk_write(s, &z, 1);
+       sk_write(s, cfg.termtype, strlen(cfg.termtype));
+       sk_write(s, "/", 1);
+       for (p = cfg.termspeed; isdigit(*p); p++);
+       sk_write(s, cfg.termspeed, p - cfg.termspeed);
+       sk_write(s, &z, 1);
     }
 
     return NULL;
@@ -127,7 +133,8 @@ static char *rlogin_init (char *host, int port, char **realhost) {
 /*
  * Called to send data down the rlogin connection.
  */
-static void rlogin_send (char *buf, int len) {
+static void rlogin_send(char *buf, int len)
+{
 
     if (s == NULL)
        return;
@@ -138,11 +145,14 @@ static void rlogin_send (char *buf, int len) {
 /*
  * Called to set the size of the window
  */
-static void rlogin_size(void) {
+static void rlogin_size(void)
+{
     char b[12] = { '\xFF', '\xFF', 0x73, 0x73, 0, 0, 0, 0, 0, 0, 0, 0 };
 
-    b[6] = cols >> 8; b[7] = cols & 0xFF;
-    b[4] = rows >> 8; b[5] = rows & 0xFF;
+    b[6] = cols >> 8;
+    b[7] = cols & 0xFF;
+    b[4] = rows >> 8;
+    b[5] = rows & 0xFF;
     sk_write(s, b, 12);
     return;
 }
@@ -150,16 +160,24 @@ static void rlogin_size(void) {
 /*
  * Send rlogin special codes.
  */
-static void rlogin_special (Telnet_Special code) {
+static void rlogin_special(Telnet_Special code)
+{
     /* Do nothing! */
     return;
 }
 
-static Socket rlogin_socket(void) { return s; }
+static Socket rlogin_socket(void)
+{
+    return s;
+}
 
-static int rlogin_sendok(void) { return 1; }
+static int rlogin_sendok(void)
+{
+    return 1;
+}
 
-static int rlogin_ldisc(int option) {
+static int rlogin_ldisc(int option)
+{
     return 0;
 }
 
diff --git a/scp.c b/scp.c
index 413cf4c..f414eb8 100644 (file)
--- a/scp.c
+++ b/scp.c
@@ -56,7 +56,7 @@ static char *password = NULL;
 static int errs = 0;
 /* GUI Adaptation - Sept 2000 */
 #define NAME_STR_MAX 2048
-static char statname[NAME_STR_MAX+1];
+static char statname[NAME_STR_MAX + 1];
 static unsigned long statsize = 0;
 static int statperct = 0;
 static unsigned long statelapsed = 0;
@@ -67,17 +67,20 @@ static void source(char *src);
 static void rsource(char *src);
 static void sink(char *targ, char *src);
 /* GUI Adaptation - Sept 2000 */
-static void tell_char(FILE *stream, char c);
-static void tell_str(FILE *stream, char *str);
-static void tell_user(FILE *stream, char *fmt, ...);
+static void tell_char(FILE * stream, char c);
+static void tell_str(FILE * stream, char *str);
+static void tell_user(FILE * stream, char *fmt, ...);
 static void send_char_msg(unsigned int msg_id, char c);
 static void send_str_msg(unsigned int msg_id, char *str);
 static void gui_update_stats(char *name, unsigned long size,
-                             int percentage, unsigned long elapsed);
+                            int percentage, unsigned long elapsed);
 
-void logevent(char *string) { }
+void logevent(char *string)
+{
+}
 
-void ldisc_send(char *buf, int len) {
+void ldisc_send(char *buf, int len)
+{
     /*
      * This is only here because of the calls to ldisc_send(NULL,
      * 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
@@ -88,38 +91,38 @@ void ldisc_send(char *buf, int len) {
 }
 
 void verify_ssh_host_key(char *host, int port, char *keytype,
-                         char *keystr, char *fingerprint) {
+                        char *keystr, char *fingerprint)
+{
     int ret;
 
     static const char absentmsg[] =
-        "The server's host key is not cached in the registry. You\n"
-        "have no guarantee that the server is the computer you\n"
-        "think it is.\n"
-        "The server's key fingerprint is:\n"
-        "%s\n"
-        "If you trust this host, enter \"y\" to add the key to\n"
-        "PuTTY's cache and carry on connecting.\n"
-        "If you do not trust this host, enter \"n\" to abandon the\n"
-        "connection.\n"
-        "Continue connecting? (y/n) ";
+       "The server's host key is not cached in the registry. You\n"
+       "have no guarantee that the server is the computer you\n"
+       "think it is.\n"
+       "The server's key fingerprint is:\n"
+       "%s\n"
+       "If you trust this host, enter \"y\" to add the key to\n"
+       "PuTTY's cache and carry on connecting.\n"
+       "If you do not trust this host, enter \"n\" to abandon the\n"
+       "connection.\n" "Continue connecting? (y/n) ";
 
     static const char wrongmsg[] =
-        "WARNING - POTENTIAL SECURITY BREACH!\n"
-        "The server's host key does not match the one PuTTY has\n"
-        "cached in the registry. This means that either the\n"
-        "server administrator has changed the host key, or you\n"
-        "have actually connected to another computer pretending\n"
-        "to be the server.\n"
-        "The new key fingerprint is:\n"
-        "%s\n"
-        "If you were expecting this change and trust the new key,\n"
-        "enter Yes to update PuTTY's cache and continue connecting.\n"
-        "If you want to carry on connecting but without updating\n"
-        "the cache, enter No.\n"
-        "If you want to abandon the connection completely, press\n"
-        "Return to cancel. Pressing Return is the ONLY guaranteed\n"
-        "safe choice.\n"
-        "Update cached key? (y/n, Return cancels connection) ";
+       "WARNING - POTENTIAL SECURITY BREACH!\n"
+       "The server's host key does not match the one PuTTY has\n"
+       "cached in the registry. This means that either the\n"
+       "server administrator has changed the host key, or you\n"
+       "have actually connected to another computer pretending\n"
+       "to be the server.\n"
+       "The new key fingerprint is:\n"
+       "%s\n"
+       "If you were expecting this change and trust the new key,\n"
+       "enter Yes to update PuTTY's cache and continue connecting.\n"
+       "If you want to carry on connecting but without updating\n"
+       "the cache, enter No.\n"
+       "If you want to abandon the connection completely, press\n"
+       "Return to cancel. Pressing Return is the ONLY guaranteed\n"
+       "safe choice.\n"
+       "Update cached key? (y/n, Return cancels connection) ";
 
     static const char abandoned[] = "Connection abandoned.\n";
 
@@ -130,63 +133,63 @@ void verify_ssh_host_key(char *host, int port, char *keytype,
      */
     ret = verify_host_key(host, port, keytype, keystr);
 
-    if (ret == 0)                      /* success - key matched OK */
-        return;
-    if (ret == 2) {                    /* key was different */
-        fprintf(stderr, wrongmsg, fingerprint);
+    if (ret == 0)                     /* success - key matched OK */
+       return;
+    if (ret == 2) {                   /* key was different */
+       fprintf(stderr, wrongmsg, fingerprint);
        fflush(stderr);
-        if (fgets(line, sizeof(line), stdin) &&
-            line[0] != '\0' && line[0] != '\n') {
-            if (line[0] == 'y' || line[0] == 'Y')
-                store_host_key(host, port, keytype, keystr);
-        } else {
-            fprintf(stderr, abandoned);
+       if (fgets(line, sizeof(line), stdin) &&
+           line[0] != '\0' && line[0] != '\n') {
+           if (line[0] == 'y' || line[0] == 'Y')
+               store_host_key(host, port, keytype, keystr);
+       } else {
+           fprintf(stderr, abandoned);
            fflush(stderr);
-            exit(0);
-        }
+           exit(0);
+       }
     }
-    if (ret == 1) {                    /* key was absent */
-        fprintf(stderr, absentmsg, fingerprint);
-        if (fgets(line, sizeof(line), stdin) &&
-            (line[0] == 'y' || line[0] == 'Y'))
-            store_host_key(host, port, keytype, keystr);
-        else {
-            fprintf(stderr, abandoned);
-            exit(0);
-        }
+    if (ret == 1) {                   /* key was absent */
+       fprintf(stderr, absentmsg, fingerprint);
+       if (fgets(line, sizeof(line), stdin) &&
+           (line[0] == 'y' || line[0] == 'Y'))
+           store_host_key(host, port, keytype, keystr);
+       else {
+           fprintf(stderr, abandoned);
+           exit(0);
+       }
     }
 }
 
 /* GUI Adaptation - Sept 2000 */
 static void send_msg(HWND h, UINT message, WPARAM wParam)
 {
-    while (!PostMessage( h, message, wParam, 0))
-        SleepEx(1000,TRUE);
+    while (!PostMessage(h, message, wParam, 0))
+       SleepEx(1000, TRUE);
 }
 
-static void tell_char(FILE *stream, char c)
+static void tell_char(FILE * stream, char c)
 {
     if (!gui_mode)
        fputc(c, stream);
-    else
-    {
+    else {
        unsigned int msg_id = WM_STD_OUT_CHAR;
-       if (stream == stderr) msg_id = WM_STD_ERR_CHAR;
-       send_msg( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)c );
+       if (stream == stderr)
+           msg_id = WM_STD_ERR_CHAR;
+       send_msg((HWND) atoi(gui_hwnd), msg_id, (WPARAM) c);
     }
 }
 
-static void tell_str(FILE *stream, char *str)
+static void tell_str(FILE * stream, char *str)
 {
     unsigned int i;
 
-    for( i = 0; i < strlen(str); ++i )
+    for (i = 0; i < strlen(str); ++i)
        tell_char(stream, str[i]);
 }
 
-static void tell_user(FILE *stream, char *fmt, ...)
+static void tell_user(FILE * stream, char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     vsprintf(str, fmt, ap);
@@ -195,30 +198,30 @@ static void tell_user(FILE *stream, char *fmt, ...)
     tell_str(stream, str);
 }
 
-static void gui_update_stats(char *name, unsigned long size, int percentage, unsigned long elapsed)
+static void gui_update_stats(char *name, unsigned long size,
+                            int percentage, unsigned long elapsed)
 {
     unsigned int i;
 
-    if (strcmp(name,statname) != 0)
-    {
-       for( i = 0; i < strlen(name); ++i )
-           send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)name[i]);
-       send_msg( (HWND)atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM)'\n' );
-       strcpy(statname,name);
+    if (strcmp(name, statname) != 0) {
+       for (i = 0; i < strlen(name); ++i)
+           send_msg((HWND) atoi(gui_hwnd), WM_STATS_CHAR,
+                    (WPARAM) name[i]);
+       send_msg((HWND) atoi(gui_hwnd), WM_STATS_CHAR, (WPARAM) '\n');
+       strcpy(statname, name);
     }
-    if (statsize != size)
-    {
-       send_msg( (HWND)atoi(gui_hwnd), WM_STATS_SIZE, (WPARAM)size );
+    if (statsize != size) {
+       send_msg((HWND) atoi(gui_hwnd), WM_STATS_SIZE, (WPARAM) size);
        statsize = size;
     }
-    if (statelapsed != elapsed)
-    {
-       send_msg( (HWND)atoi(gui_hwnd), WM_STATS_ELAPSED, (WPARAM)elapsed );
+    if (statelapsed != elapsed) {
+       send_msg((HWND) atoi(gui_hwnd), WM_STATS_ELAPSED,
+                (WPARAM) elapsed);
        statelapsed = elapsed;
     }
-    if (statperct != percentage)
-    {
-       send_msg( (HWND)atoi(gui_hwnd), WM_STATS_PERCENT, (WPARAM)percentage );
+    if (statperct != percentage) {
+       send_msg((HWND) atoi(gui_hwnd), WM_STATS_PERCENT,
+                (WPARAM) percentage);
        statperct = percentage;
     }
 }
@@ -228,11 +231,11 @@ static void gui_update_stats(char *name, unsigned long size, int percentage, uns
  */
 void fatalbox(char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     strcpy(str, "Fatal:");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     va_end(ap);
     strcat(str, "\n");
     tell_str(stderr, str);
@@ -241,11 +244,11 @@ void fatalbox(char *fmt, ...)
 }
 void connection_fatal(char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     strcpy(str, "Fatal:");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     va_end(ap);
     strcat(str, "\n");
     tell_str(stderr, str);
@@ -257,7 +260,8 @@ void connection_fatal(char *fmt, ...)
  * Be told what socket we're supposed to be using.
  */
 static SOCKET scp_ssh_socket;
-char *do_select(SOCKET skt, int startup) {
+char *do_select(SOCKET skt, int startup)
+{
     if (startup)
        scp_ssh_socket = skt;
     else
@@ -275,13 +279,14 @@ extern int select_result(WPARAM, LPARAM);
  * do this until we have enough data.
  */
 
-static unsigned char *outptr;          /* where to put the data */
-static unsigned outlen;                /* how much data required */
+static unsigned char *outptr;         /* where to put the data */
+static unsigned outlen;                       /* how much data required */
 static unsigned char *pending = NULL;  /* any spare data */
-static unsigned pendlen=0, pendsize=0; /* length and phys. size of buffer */
-void from_backend(int is_stderr, char *data, int datalen) {
-    unsigned char *p = (unsigned char *)data;
-    unsigned len = (unsigned)datalen;
+static unsigned pendlen = 0, pendsize = 0;     /* length and phys. size of buffer */
+void from_backend(int is_stderr, char *data, int datalen)
+{
+    unsigned char *p = (unsigned char *) data;
+    unsigned len = (unsigned) datalen;
 
     /*
      * stderr data is just spouted to local stderr and otherwise
@@ -298,29 +303,33 @@ void from_backend(int is_stderr, char *data, int datalen) {
      * If this is before the real session begins, just return.
      */
     if (!outptr)
-        return;
+       return;
 
     if (outlen > 0) {
-        unsigned used = outlen;
-        if (used > len) used = len;
-        memcpy(outptr, p, used);
-        outptr += used; outlen -= used;
-        p += used; len -= used;
+       unsigned used = outlen;
+       if (used > len)
+           used = len;
+       memcpy(outptr, p, used);
+       outptr += used;
+       outlen -= used;
+       p += used;
+       len -= used;
     }
 
     if (len > 0) {
-        if (pendsize < pendlen + len) {
-            pendsize = pendlen + len + 4096;
-            pending = (pending ? srealloc(pending, pendsize) :
-                       smalloc(pendsize));
-            if (!pending)
-                fatalbox("Out of memory");
-        }
-        memcpy(pending+pendlen, p, len);
-        pendlen += len;
+       if (pendsize < pendlen + len) {
+           pendsize = pendlen + len + 4096;
+           pending = (pending ? srealloc(pending, pendsize) :
+                      smalloc(pendsize));
+           if (!pending)
+               fatalbox("Out of memory");
+       }
+       memcpy(pending + pendlen, p, len);
+       pendlen += len;
     }
 }
-static int ssh_scp_recv(unsigned char *buf, int len) {
+static int ssh_scp_recv(unsigned char *buf, int len)
+{
     outptr = buf;
     outlen = len;
 
@@ -329,31 +338,31 @@ static int ssh_scp_recv(unsigned char *buf, int len) {
      * need.
      */
     if (pendlen > 0) {
-        unsigned pendused = pendlen;
-        if (pendused > outlen)
-            pendused = outlen;
+       unsigned pendused = pendlen;
+       if (pendused > outlen)
+           pendused = outlen;
        memcpy(outptr, pending, pendused);
-        memmove(pending, pending+pendused, pendlen-pendused);
+       memmove(pending, pending + pendused, pendlen - pendused);
        outptr += pendused;
        outlen -= pendused;
-        pendlen -= pendused;
-        if (pendlen == 0) {
-            pendsize = 0;
-            sfree(pending);
-            pending = NULL;
-        }
-        if (outlen == 0)
-            return len;
+       pendlen -= pendused;
+       if (pendlen == 0) {
+           pendsize = 0;
+           sfree(pending);
+           pending = NULL;
+       }
+       if (outlen == 0)
+           return len;
     }
 
     while (outlen > 0) {
-        fd_set readfds;
+       fd_set readfds;
 
-        FD_ZERO(&readfds);
-        FD_SET(scp_ssh_socket, &readfds);
-        if (select(1, &readfds, NULL, NULL, NULL) < 0)
-            return 0;                  /* doom */
-        select_result((WPARAM)scp_ssh_socket, (LPARAM)FD_READ);
+       FD_ZERO(&readfds);
+       FD_SET(scp_ssh_socket, &readfds);
+       if (select(1, &readfds, NULL, NULL, NULL) < 0)
+           return 0;                  /* doom */
+       select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
     }
 
     return len;
@@ -362,16 +371,17 @@ static int ssh_scp_recv(unsigned char *buf, int len) {
 /*
  * Loop through the ssh connection and authentication process.
  */
-static void ssh_scp_init(void) {
+static void ssh_scp_init(void)
+{
     if (scp_ssh_socket == INVALID_SOCKET)
        return;
     while (!back->sendok()) {
-        fd_set readfds;
-        FD_ZERO(&readfds);
-        FD_SET(scp_ssh_socket, &readfds);
-        if (select(1, &readfds, NULL, NULL, NULL) < 0)
-            return;                    /* doom */
-        select_result((WPARAM)scp_ssh_socket, (LPARAM)FD_READ);
+       fd_set readfds;
+       FD_ZERO(&readfds);
+       FD_SET(scp_ssh_socket, &readfds);
+       if (select(1, &readfds, NULL, NULL, NULL) < 0)
+           return;                    /* doom */
+       select_result((WPARAM) scp_ssh_socket, (LPARAM) FD_READ);
     }
 }
 
@@ -380,11 +390,11 @@ static void ssh_scp_init(void) {
  */
 static void bump(char *fmt, ...)
 {
-    char str[0x100]; /* Make the size big enough */
+    char str[0x100];                  /* Make the size big enough */
     va_list ap;
     va_start(ap, fmt);
     strcpy(str, "Fatal:");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     va_end(ap);
     strcat(str, "\n");
     tell_str(stderr, str);
@@ -403,21 +413,22 @@ static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
     DWORD savemode, newmode, i;
 
     if (is_pw && password) {
-        static int tried_once = 0;
-
-        if (tried_once) {
-            return 0;
-        } else {
-            strncpy(str, password, maxlen);
-            str[maxlen-1] = '\0';
-            tried_once = 1;
-            return 1;
-        }
+       static int tried_once = 0;
+
+       if (tried_once) {
+           return 0;
+       } else {
+           strncpy(str, password, maxlen);
+           str[maxlen - 1] = '\0';
+           tried_once = 1;
+           return 1;
+       }
     }
 
     /* GUI Adaptation - Sept 2000 */
     if (gui_mode) {
-       if (maxlen>0) str[0] = '\0';
+       if (maxlen > 0)
+           str[0] = '\0';
     } else {
        hin = GetStdHandle(STD_INPUT_HANDLE);
        hout = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -425,23 +436,26 @@ static int get_line(const char *prompt, char *str, int maxlen, int is_pw)
            bump("Cannot get standard input/output handles");
 
        GetConsoleMode(hin, &savemode);
-        newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
-        if (is_pw)
-            newmode &= ~ENABLE_ECHO_INPUT;
-        else
-            newmode |= ENABLE_ECHO_INPUT;
-        SetConsoleMode(hin, newmode);
+       newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
+       if (is_pw)
+           newmode &= ~ENABLE_ECHO_INPUT;
+       else
+           newmode |= ENABLE_ECHO_INPUT;
+       SetConsoleMode(hin, newmode);
 
        WriteFile(hout, prompt, strlen(prompt), &i, NULL);
-       ReadFile(hin, str, maxlen-1, &i, NULL);
+       ReadFile(hin, str, maxlen - 1, &i, NULL);
 
        SetConsoleMode(hin, savemode);
 
-       if ((int)i > maxlen) i = maxlen-1; else i = i - 2;
+       if ((int) i > maxlen)
+           i = maxlen - 1;
+       else
+           i = i - 2;
        str[i] = '\0';
 
        if (is_pw)
-            WriteFile(hout, "\r\n", 2, &i, NULL);
+           WriteFile(hout, "\r\n", 2, &i, NULL);
     }
 
     return 1;
@@ -462,25 +476,26 @@ static void do_cmd(char *host, char *user, char *cmd)
     do_defaults(host, &cfg);
     if (cfg.host[0] == '\0') {
        /* No settings for this host; use defaults */
-        do_defaults(NULL, &cfg);
-       strncpy(cfg.host, host, sizeof(cfg.host)-1);
-       cfg.host[sizeof(cfg.host)-1] = '\0';
+       do_defaults(NULL, &cfg);
+       strncpy(cfg.host, host, sizeof(cfg.host) - 1);
+       cfg.host[sizeof(cfg.host) - 1] = '\0';
        cfg.port = 22;
     }
 
     /* Set username */
     if (user != NULL && user[0] != '\0') {
-       strncpy(cfg.username, user, sizeof(cfg.username)-1);
-       cfg.username[sizeof(cfg.username)-1] = '\0';
+       strncpy(cfg.username, user, sizeof(cfg.username) - 1);
+       cfg.username[sizeof(cfg.username) - 1] = '\0';
     } else if (cfg.username[0] == '\0') {
        namelen = 0;
        if (GetUserName(user, &namelen) == FALSE)
            bump("Empty user name");
        user = smalloc(namelen * sizeof(char));
        GetUserName(user, &namelen);
-       if (verbose) tell_user(stderr, "Guessing user name: %s", user);
-       strncpy(cfg.username, user, sizeof(cfg.username)-1);
-       cfg.username[sizeof(cfg.username)-1] = '\0';
+       if (verbose)
+           tell_user(stderr, "Guessing user name: %s", user);
+       strncpy(cfg.username, user, sizeof(cfg.username) - 1);
+       cfg.username[sizeof(cfg.username) - 1] = '\0';
        free(user);
     }
 
@@ -491,7 +506,7 @@ static void do_cmd(char *host, char *user, char *cmd)
        cfg.port = portnumber;
 
     strncpy(cfg.remote_cmd, cmd, sizeof(cfg.remote_cmd));
-    cfg.remote_cmd[sizeof(cfg.remote_cmd)-1] = '\0';
+    cfg.remote_cmd[sizeof(cfg.remote_cmd) - 1] = '\0';
     cfg.nopty = TRUE;
 
     back = &ssh_backend;
@@ -508,7 +523,7 @@ static void do_cmd(char *host, char *user, char *cmd)
  *  Update statistic information about current file.
  */
 static void print_stats(char *name, unsigned long size, unsigned long done,
-                        time_t start, time_t now)
+                       time_t start, time_t now)
 {
     float ratebs;
     unsigned long eta;
@@ -517,8 +532,8 @@ static void print_stats(char *name, unsigned long size, unsigned long done,
 
     /* GUI Adaptation - Sept 2000 */
     if (gui_mode)
-       gui_update_stats(name, size, (int)(100 * (done*1.0/size)),
-                         (unsigned long)difftime(now, start));
+       gui_update_stats(name, size, (int) (100 * (done * 1.0 / size)),
+                        (unsigned long) difftime(now, start));
     else {
        if (now > start)
            ratebs = (float) done / (now - start);
@@ -535,8 +550,7 @@ static void print_stats(char *name, unsigned long size, unsigned long done,
        pct = (int) (100.0 * (float) done / size);
 
        printf("\r%-25.25s | %10ld kB | %5.1f kB/s | ETA: %8s | %3d%%",
-              name, done / 1024, ratebs / 1024.0,
-              etastr, pct);
+              name, done / 1024, ratebs / 1024.0, etastr, pct);
 
        if (done == size)
            printf("\n");
@@ -547,19 +561,14 @@ static void print_stats(char *name, unsigned long size, unsigned long done,
  *  Find a colon in str and return a pointer to the colon.
  *  This is used to separate hostname from filename.
  */
-static char * colon(char *str)
+static char *colon(char *str)
 {
     /* We ignore a leading colon, since the hostname cannot be
-     empty. We also ignore a colon as second character because
-     of filenames like f:myfile.txt. */
-    if (str[0] == '\0' ||
-       str[0] == ':' ||
-       str[1] == ':')
+       empty. We also ignore a colon as second character because
+       of filenames like f:myfile.txt. */
+    if (str[0] == '\0' || str[0] == ':' || str[1] == ':')
        return (NULL);
-    while (*str != '\0' &&
-          *str != ':' &&
-          *str != '/' &&
-          *str != '\\')
+    while (*str != '\0' && *str != ':' && *str != '/' && *str != '\\')
        str++;
     if (*str == ':')
        return (str);
@@ -581,19 +590,19 @@ static int response(void)
 
     p = 0;
     switch (resp) {
-      case 0:          /* ok */
+      case 0:                         /* ok */
        return (0);
       default:
        rbuf[p++] = resp;
        /* fallthrough */
-      case 1:          /* error */
-      case 2:          /* fatal error */
+      case 1:                         /* error */
+      case 2:                         /* fatal error */
        do {
            if (ssh_scp_recv(&ch, 1) <= 0)
                bump("Protocol error: Lost connection");
            rbuf[p++] = ch;
        } while (p < sizeof(rbuf) && ch != '\n');
-       rbuf[p-1] = '\0';
+       rbuf[p - 1] = '\0';
        if (resp == 1)
            tell_user(stderr, "%s\n", rbuf);
        else
@@ -614,11 +623,11 @@ static void run_err(const char *fmt, ...)
     va_start(ap, fmt);
     errs++;
     strcpy(str, "scp: ");
-    vsprintf(str+strlen(str), fmt, ap);
+    vsprintf(str + strlen(str), fmt, ap);
     strcat(str, "\n");
     back->send("\001", 1);            /* scp protocol error prefix */
     back->send(str, strlen(str));
-    tell_user(stderr, "%s",str);
+    tell_user(stderr, "%s", str);
     va_end(ap);
 }
 
@@ -637,31 +646,31 @@ static void source(char *src)
     time_t stat_starttime, stat_lasttime;
 
     attr = GetFileAttributes(src);
-    if (attr == (DWORD)-1) {
+    if (attr == (DWORD) - 1) {
        run_err("%s: No such file or directory", src);
        return;
     }
 
     if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
        if (recursive) {
-            /*
-             * Avoid . and .. directories.
-             */
-            char *p;
-            p = strrchr(src, '/');
-            if (!p)
-                p = strrchr(src, '\\');
-            if (!p)
-                p = src;
-            else
-                p++;
-            if (!strcmp(p, ".") || !strcmp(p, ".."))
-                /* skip . and .. */;
-            else
-                rsource(src);
-        } else {
+           /*
+            * Avoid . and .. directories.
+            */
+           char *p;
+           p = strrchr(src, '/');
+           if (!p)
+               p = strrchr(src, '\\');
+           if (!p)
+               p = src;
+           else
+               p++;
+           if (!strcmp(p, ".") || !strcmp(p, ".."))
+               /* skip . and .. */ ;
+           else
+               rsource(src);
+       } else {
            run_err("%s: not a regular file", src);
-        }
+       }
        return;
     }
 
@@ -710,16 +719,17 @@ static void source(char *src)
     for (i = 0; i < size; i += 4096) {
        char transbuf[4096];
        DWORD j, k = 4096;
-       if (i + k > size) k = size - i;
-       if (! ReadFile(f, transbuf, k, &j, NULL) || j != k) {
-           if (statistics) printf("\n");
+       if (i + k > size)
+           k = size - i;
+       if (!ReadFile(f, transbuf, k, &j, NULL) || j != k) {
+           if (statistics)
+               printf("\n");
            bump("%s: Read error", src);
        }
        back->send(transbuf, k);
        if (statistics) {
            stat_bytes += k;
-           if (time(NULL) != stat_lasttime ||
-               i + k == size) {
+           if (time(NULL) != stat_lasttime || i + k == size) {
                stat_lasttime = time(NULL);
                print_stats(last, size, stat_bytes,
                            stat_starttime, stat_lasttime);
@@ -767,8 +777,7 @@ static void rsource(char *src)
     while (ok) {
        if (strcmp(fdat.cFileName, ".") == 0 ||
            strcmp(fdat.cFileName, "..") == 0) {
-       } else if (strlen(src) + 1 + strlen(fdat.cFileName) >=
-                  sizeof(buf)) {
+       } else if (strlen(src) + 1 + strlen(fdat.cFileName) >= sizeof(buf)) {
            run_err("%s/%s: Name too long", src, fdat.cFileName);
        } else {
            sprintf(buf, "%s/%s", src, fdat.cFileName);
@@ -805,7 +814,7 @@ static void sink(char *targ, char *src)
     char *stat_name;
 
     attr = GetFileAttributes(targ);
-    if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
+    if (attr != (DWORD) - 1 && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
        targisdir = 1;
 
     if (targetshouldbedirectory && !targisdir)
@@ -814,7 +823,7 @@ static void sink(char *targ, char *src)
     back->send("", 1);
     while (1) {
        settime = 0;
-       gottime:
+      gottime:
        if (ssh_scp_recv(&ch, 1) <= 0)
            return;
        if (ch == '\n')
@@ -826,20 +835,19 @@ static void sink(char *targ, char *src)
                bump("Lost connection");
            buf[i++] = ch;
        } while (i < sizeof(buf) && ch != '\n');
-       buf[i-1] = '\0';
+       buf[i - 1] = '\0';
        switch (buf[0]) {
-         case '\01':   /* error */
-           tell_user(stderr, "%s\n", buf+1);
+         case '\01':                  /* error */
+           tell_user(stderr, "%s\n", buf + 1);
            errs++;
            continue;
-         case '\02':   /* fatal error */
-           bump("%s", buf+1);
+         case '\02':                  /* fatal error */
+           bump("%s", buf + 1);
          case 'E':
            back->send("", 1);
            return;
          case 'T':
-           if (sscanf(buf, "T%ld %*d %ld %*d",
-                      &mtime, &atime) == 2) {
+           if (sscanf(buf, "T%ld %*d %ld %*d", &mtime, &atime) == 2) {
                settime = 1;
                back->send("", 1);
                goto gottime;
@@ -852,7 +860,7 @@ static void sink(char *targ, char *src)
            bump("Protocol error: Expected control record");
        }
 
-       if (sscanf(buf+1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
+       if (sscanf(buf + 1, "%u %lu %[^\n]", &mode, &size, namebuf) != 3)
            bump("Protocol error: Illegal file descriptor format");
        /* Security fix: ensure the file ends up where we asked for it. */
        if (targisdir) {
@@ -870,7 +878,7 @@ static void sink(char *targ, char *src)
            strcpy(namebuf, targ);
        }
        attr = GetFileAttributes(namebuf);
-       exists = (attr != (DWORD)-1);
+       exists = (attr != (DWORD) - 1);
 
        if (buf[0] == 'D') {
            if (exists && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
@@ -878,9 +886,8 @@ static void sink(char *targ, char *src)
                continue;
            }
            if (!exists) {
-               if (! CreateDirectory(namebuf, NULL)) {
-                   run_err("%s: Cannot create directory",
-                           namebuf);
+               if (!CreateDirectory(namebuf, NULL)) {
+                   run_err("%s: Cannot create directory", namebuf);
                    continue;
                }
            }
@@ -913,11 +920,13 @@ static void sink(char *targ, char *src)
        for (i = 0; i < size; i += 4096) {
            char transbuf[4096];
            DWORD j, k = 4096;
-           if (i + k > size) k = size - i;
+           if (i + k > size)
+               k = size - i;
            if (ssh_scp_recv(transbuf, k) == 0)
                bump("Lost connection");
-           if (wrerror) continue;
-           if (! WriteFile(f, transbuf, k, &j, NULL) || j != k) {
+           if (wrerror)
+               continue;
+           if (!WriteFile(f, transbuf, k, &j, NULL) || j != k) {
                wrerror = 1;
                if (statistics)
                    printf("\r%-25.25s | %50s\n",
@@ -927,8 +936,7 @@ static void sink(char *targ, char *src)
            }
            if (statistics) {
                stat_bytes += k;
-               if (time(NULL) > stat_lasttime ||
-                   i + k == size) {
+               if (time(NULL) > stat_lasttime || i + k == size) {
                    stat_lasttime = time(NULL);
                    print_stats(stat_name, size, stat_bytes,
                                stat_starttime, stat_lasttime);
@@ -962,7 +970,7 @@ static void toremote(int argc, char *argv[])
     char *cmd;
     int i;
 
-    targ = argv[argc-1];
+    targ = argv[argc - 1];
 
     /* Separate host from filename */
     host = targ;
@@ -988,7 +996,7 @@ static void toremote(int argc, char *argv[])
 
     if (argc == 2) {
        /* Find out if the source filespec covers multiple files
-        if so, we should set the targetshouldbedirectory flag */
+          if so, we should set the targetshouldbedirectory flag */
        HANDLE fh;
        WIN32_FIND_DATA fdat;
        if (colon(argv[0]) != NULL)
@@ -1006,8 +1014,7 @@ static void toremote(int argc, char *argv[])
            verbose ? " -v" : "",
            recursive ? " -r" : "",
            preserve ? " -p" : "",
-           targetshouldbedirectory ? " -d" : "",
-           targ);
+           targetshouldbedirectory ? " -d" : "", targ);
     do_cmd(host, user, cmd);
     sfree(cmd);
 
@@ -1044,15 +1051,14 @@ static void toremote(int argc, char *argv[])
                 */
                int len = strlen(src), dlen = strlen(fdat.cFileName);
                if (len == dlen && !strcmp(src, fdat.cFileName)) {
-                   /* ok */;
-               } else if (len > dlen+1 && src[len-dlen-1] == '\\' &&
-                          !strcmp(src+len-dlen, fdat.cFileName)) {
-                   /* ok */;
+                   /* ok */ ;
+               } else if (len > dlen + 1 && src[len - dlen - 1] == '\\' &&
+                          !strcmp(src + len - dlen, fdat.cFileName)) {
+                   /* ok */ ;
                } else
                    continue;          /* ignore this one */
            }
-           if (strlen(src) + strlen(fdat.cFileName) >=
-               sizeof(namebuf)) {
+           if (strlen(src) + strlen(fdat.cFileName) >= sizeof(namebuf)) {
                tell_user(stderr, "%s: Name too long", src);
                continue;
            }
@@ -1113,8 +1119,7 @@ static void tolocal(int argc, char *argv[])
            verbose ? " -v" : "",
            recursive ? " -r" : "",
            preserve ? " -p" : "",
-           targetshouldbedirectory ? " -d" : "",
-           src);
+           targetshouldbedirectory ? " -d" : "", src);
     do_cmd(host, user, cmd);
     sfree(cmd);
 
@@ -1154,12 +1159,15 @@ static void get_dir_list(int argc, char *argv[])
            user = NULL;
     }
 
-    cmd = smalloc(4*strlen(src) + 100);
+    cmd = smalloc(4 * strlen(src) + 100);
     strcpy(cmd, "ls -la '");
     p = cmd + strlen(cmd);
     for (q = src; *q; q++) {
        if (*q == '\'') {
-           *p++ = '\''; *p++ = '\\'; *p++ = '\''; *p++ = '\'';
+           *p++ = '\'';
+           *p++ = '\\';
+           *p++ = '\'';
+           *p++ = '\'';
        } else {
            *p++ = *q;
        }
@@ -1185,8 +1193,7 @@ static void init_winsock(void)
     winsock_ver = MAKEWORD(1, 1);
     if (WSAStartup(winsock_ver, &wsadata))
        bump("Unable to initialise WinSock");
-    if (LOBYTE(wsadata.wVersion) != 1 ||
-       HIBYTE(wsadata.wVersion) != 1)
+    if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1)
        bump("WinSock version is incompatible with 1.1");
 }
 
@@ -1198,7 +1205,8 @@ static void usage(void)
     printf("PuTTY Secure Copy client\n");
     printf("%s\n", ver);
     printf("Usage: pscp [options] [user@]host:source target\n");
-    printf("       pscp [options] source [source...] [user@]host:target\n");
+    printf
+       ("       pscp [options] source [source...] [user@]host:target\n");
     printf("       pscp [options] -ls user@host:filespec\n");
     printf("Options:\n");
     printf("  -p        preserve file attributes\n");
@@ -1215,7 +1223,8 @@ static void usage(void)
      * the command-line help. The only people who need to know
      * about it are programmers, and they can read the source.
      */
-    printf("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
+    printf
+       ("  -gui hWnd GUI mode with the windows handle for receiving messages\n");
 #endif
     exit(1);
 }
@@ -1246,21 +1255,21 @@ int main(int argc, char *argv[])
            preserve = 1;
        else if (strcmp(argv[i], "-q") == 0)
            statistics = 0;
-       else if (strcmp(argv[i], "-h") == 0 ||
-                strcmp(argv[i], "-?") == 0)
+       else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0)
            usage();
-       else if (strcmp(argv[i], "-P") == 0 && i+1 < argc)
+       else if (strcmp(argv[i], "-P") == 0 && i + 1 < argc)
            portnumber = atoi(argv[++i]);
-       else if (strcmp(argv[i], "-pw") == 0 && i+1 < argc)
+       else if (strcmp(argv[i], "-pw") == 0 && i + 1 < argc)
            password = argv[++i];
-       else if (strcmp(argv[i], "-gui") == 0 && i+1 < argc) {
+       else if (strcmp(argv[i], "-gui") == 0 && i + 1 < argc) {
            gui_hwnd = argv[++i];
            gui_mode = 1;
        } else if (strcmp(argv[i], "-ls") == 0)
-               list = 1;
-       else if (strcmp(argv[i], "--") == 0)
-       { i++; break; }
-       else
+           list = 1;
+       else if (strcmp(argv[i], "--") == 0) {
+           i++;
+           break;
+       } else
            usage();
     }
     argc -= i;
@@ -1279,7 +1288,7 @@ int main(int argc, char *argv[])
        if (argc > 2)
            targetshouldbedirectory = 1;
 
-       if (colon(argv[argc-1]) != NULL)
+       if (colon(argv[argc - 1]) != NULL)
            toremote(argc, argv);
        else
            tolocal(argc, argv);
@@ -1296,9 +1305,11 @@ int main(int argc, char *argv[])
     /* GUI Adaptation - August 2000 */
     if (gui_mode) {
        unsigned int msg_id = WM_RET_ERR_CNT;
-       if (list) msg_id = WM_LS_RET_ERR_CNT;
-       while (!PostMessage( (HWND)atoi(gui_hwnd), msg_id, (WPARAM)errs, 0/*lParam*/ ) )
-           SleepEx(1000,TRUE);
+       if (list)
+           msg_id = WM_LS_RET_ERR_CNT;
+       while (!PostMessage
+              ((HWND) atoi(gui_hwnd), msg_id, (WPARAM) errs,
+               0 /*lParam */ ))SleepEx(1000, TRUE);
     }
     return (errs == 0 ? 0 : 1);
 }
index 164fb31..3e9ee32 100644 (file)
@@ -8,51 +8,54 @@
 #include "putty.h"
 #include "storage.h"
 
-static void gpps(void *handle, char *name, char *def, char *val, int len) {
+static void gpps(void *handle, char *name, char *def, char *val, int len)
+{
     if (!read_setting_s(handle, name, val, len)) {
        strncpy(val, def, len);
-       val[len-1] = '\0';
+       val[len - 1] = '\0';
     }
 }
 
-static void gppi(void *handle, char *name, int def, int *i) {
+static void gppi(void *handle, char *name, int def, int *i)
+{
     *i = read_setting_i(handle, name, def);
 }
 
-void save_settings (char *section, int do_host, Config *cfg) {
+void save_settings(char *section, int do_host, Config * cfg)
+{
     int i;
     char *p;
     void *sesskey;
 
     sesskey = open_settings_w(section);
     if (!sesskey)
-        return;
+       return;
 
-    write_setting_i (sesskey, "Present", 1);
+    write_setting_i(sesskey, "Present", 1);
     if (do_host) {
-       write_setting_s (sesskey, "HostName", cfg->host);
-       write_setting_i (sesskey, "PortNumber", cfg->port);
-       write_setting_s (sesskey, "LogFileName", cfg->logfilename);
-       write_setting_i (sesskey, "LogType", cfg->logtype);
-       write_setting_i (sesskey, "LogFileClash", cfg->logxfovr);
-        p = "raw";
-        for (i = 0; backends[i].name != NULL; i++)
-            if (backends[i].protocol == cfg->protocol) {
-                p = backends[i].name;
-                break;
-            }
-        write_setting_s (sesskey, "Protocol", p);
+       write_setting_s(sesskey, "HostName", cfg->host);
+       write_setting_i(sesskey, "PortNumber", cfg->port);
+       write_setting_s(sesskey, "LogFileName", cfg->logfilename);
+       write_setting_i(sesskey, "LogType", cfg->logtype);
+       write_setting_i(sesskey, "LogFileClash", cfg->logxfovr);
+       p = "raw";
+       for (i = 0; backends[i].name != NULL; i++)
+           if (backends[i].protocol == cfg->protocol) {
+               p = backends[i].name;
+               break;
+           }
+       write_setting_s(sesskey, "Protocol", p);
     }
-    write_setting_i (sesskey, "CloseOnExit", cfg->close_on_exit);
-    write_setting_i (sesskey, "WarnOnClose", !!cfg->warn_on_close);
-    write_setting_i (sesskey, "PingInterval", cfg->ping_interval / 60);     /* minutes */
-    write_setting_i (sesskey, "PingIntervalSecs", cfg->ping_interval % 60); /* seconds */
-    write_setting_s (sesskey, "TerminalType", cfg->termtype);
-    write_setting_s (sesskey, "TerminalSpeed", cfg->termspeed);
+    write_setting_i(sesskey, "CloseOnExit", cfg->close_on_exit);
+    write_setting_i(sesskey, "WarnOnClose", !!cfg->warn_on_close);
+    write_setting_i(sesskey, "PingInterval", cfg->ping_interval / 60); /* minutes */
+    write_setting_i(sesskey, "PingIntervalSecs", cfg->ping_interval % 60);     /* seconds */
+    write_setting_s(sesskey, "TerminalType", cfg->termtype);
+    write_setting_s(sesskey, "TerminalSpeed", cfg->termspeed);
     {
-      char buf[2*sizeof(cfg->environmt)], *p, *q;
+       char buf[2 * sizeof(cfg->environmt)], *p, *q;
        p = buf;
-      q = cfg->environmt;
+       q = cfg->environmt;
        while (*q) {
            while (*q) {
                int c = *q++;
@@ -66,143 +69,143 @@ void save_settings (char *section, int do_host, Config *cfg) {
            q++;
        }
        *p = '\0';
-       write_setting_s (sesskey, "Environment", buf);
+       write_setting_s(sesskey, "Environment", buf);
     }
-    write_setting_s (sesskey, "UserName", cfg->username);
-    write_setting_s (sesskey, "LocalUserName", cfg->localusername);
-    write_setting_i (sesskey, "NoPTY", cfg->nopty);
-    write_setting_i (sesskey, "Compression", cfg->compression);
-    write_setting_i (sesskey, "AgentFwd", cfg->agentfwd);
-    write_setting_s (sesskey, "Cipher",
-                     cfg->cipher == CIPHER_BLOWFISH ? "blowfish" :
-                     cfg->cipher == CIPHER_DES ? "des" :
-                     cfg->cipher == CIPHER_AES ? "aes" :
-                     "3des");
-    write_setting_i (sesskey, "AuthTIS", cfg->try_tis_auth);
-    write_setting_i (sesskey, "SshProt", cfg->sshprot);
-    write_setting_i (sesskey, "BuggyMAC", cfg->buggymac);
-    write_setting_s (sesskey, "PublicKeyFile", cfg->keyfile);
-    write_setting_s (sesskey, "RemoteCommand", cfg->remote_cmd);
-    write_setting_i (sesskey, "RFCEnviron", cfg->rfc_environ);
-    write_setting_i (sesskey, "BackspaceIsDelete", cfg->bksp_is_delete);
-    write_setting_i (sesskey, "RXVTHomeEnd", cfg->rxvt_homeend);
-    write_setting_i (sesskey, "LinuxFunctionKeys", cfg->funky_type);
-    write_setting_i (sesskey, "NoApplicationKeys", cfg->no_applic_k);
-    write_setting_i (sesskey, "NoApplicationCursors", cfg->no_applic_c);
-    write_setting_i (sesskey, "ApplicationCursorKeys", cfg->app_cursor);
-    write_setting_i (sesskey, "ApplicationKeypad", cfg->app_keypad);
-    write_setting_i (sesskey, "NetHackKeypad", cfg->nethack_keypad);
-    write_setting_i (sesskey, "AltF4", cfg->alt_f4);
-    write_setting_i (sesskey, "AltSpace", cfg->alt_space);
-    write_setting_i (sesskey, "AltOnly", cfg->alt_only);
-    write_setting_i (sesskey, "ComposeKey", cfg->compose_key);
-    write_setting_i (sesskey, "CtrlAltKeys", cfg->ctrlaltkeys);
-    write_setting_i (sesskey, "LocalEcho", cfg->localecho);
-    write_setting_i (sesskey, "LocalEdit", cfg->localedit);
-    write_setting_s (sesskey, "Answerback", cfg->answerback);
-    write_setting_i (sesskey, "AlwaysOnTop", cfg->alwaysontop);
-    write_setting_i (sesskey, "HideMousePtr", cfg->hide_mouseptr);
-    write_setting_i (sesskey, "SunkenEdge", cfg->sunken_edge);
-    write_setting_i (sesskey, "CurType", cfg->cursor_type);
-    write_setting_i (sesskey, "BlinkCur", cfg->blink_cur);
-    write_setting_i (sesskey, "Beep", cfg->beep);
-    write_setting_s (sesskey, "BellWaveFile", cfg->bell_wavefile);
-    write_setting_i (sesskey, "BellOverload", cfg->bellovl);
-    write_setting_i (sesskey, "BellOverloadN", cfg->bellovl_n);
-    write_setting_i (sesskey, "BellOverloadT", cfg->bellovl_t);
-    write_setting_i (sesskey, "BellOverloadS", cfg->bellovl_s);
-    write_setting_i (sesskey, "ScrollbackLines", cfg->savelines);
-    write_setting_i (sesskey, "DECOriginMode", cfg->dec_om);
-    write_setting_i (sesskey, "AutoWrapMode", cfg->wrap_mode);
-    write_setting_i (sesskey, "LFImpliesCR", cfg->lfhascr);
-    write_setting_i (sesskey, "WinNameAlways", cfg->win_name_always);
-    write_setting_s (sesskey, "WinTitle", cfg->wintitle);
-    write_setting_i (sesskey, "TermWidth", cfg->width);
-    write_setting_i (sesskey, "TermHeight", cfg->height);
-    write_setting_s (sesskey, "Font", cfg->font);
-    write_setting_i (sesskey, "FontIsBold", cfg->fontisbold);
-    write_setting_i (sesskey, "FontCharSet", cfg->fontcharset);
-    write_setting_i (sesskey, "FontHeight", cfg->fontheight);
-    write_setting_i (sesskey, "FontVTMode", cfg->vtmode);
-    write_setting_i (sesskey, "TryPalette", cfg->try_palette);
-    write_setting_i (sesskey, "BoldAsColour", cfg->bold_colour);
-    for (i=0; i<22; i++) {
+    write_setting_s(sesskey, "UserName", cfg->username);
+    write_setting_s(sesskey, "LocalUserName", cfg->localusername);
+    write_setting_i(sesskey, "NoPTY", cfg->nopty);
+    write_setting_i(sesskey, "Compression", cfg->compression);
+    write_setting_i(sesskey, "AgentFwd", cfg->agentfwd);
+    write_setting_s(sesskey, "Cipher",
+                   cfg->cipher == CIPHER_BLOWFISH ? "blowfish" :
+                   cfg->cipher == CIPHER_DES ? "des" :
+                   cfg->cipher == CIPHER_AES ? "aes" : "3des");
+    write_setting_i(sesskey, "AuthTIS", cfg->try_tis_auth);
+    write_setting_i(sesskey, "SshProt", cfg->sshprot);
+    write_setting_i(sesskey, "BuggyMAC", cfg->buggymac);
+    write_setting_s(sesskey, "PublicKeyFile", cfg->keyfile);
+    write_setting_s(sesskey, "RemoteCommand", cfg->remote_cmd);
+    write_setting_i(sesskey, "RFCEnviron", cfg->rfc_environ);
+    write_setting_i(sesskey, "BackspaceIsDelete", cfg->bksp_is_delete);
+    write_setting_i(sesskey, "RXVTHomeEnd", cfg->rxvt_homeend);
+    write_setting_i(sesskey, "LinuxFunctionKeys", cfg->funky_type);
+    write_setting_i(sesskey, "NoApplicationKeys", cfg->no_applic_k);
+    write_setting_i(sesskey, "NoApplicationCursors", cfg->no_applic_c);
+    write_setting_i(sesskey, "ApplicationCursorKeys", cfg->app_cursor);
+    write_setting_i(sesskey, "ApplicationKeypad", cfg->app_keypad);
+    write_setting_i(sesskey, "NetHackKeypad", cfg->nethack_keypad);
+    write_setting_i(sesskey, "AltF4", cfg->alt_f4);
+    write_setting_i(sesskey, "AltSpace", cfg->alt_space);
+    write_setting_i(sesskey, "AltOnly", cfg->alt_only);
+    write_setting_i(sesskey, "ComposeKey", cfg->compose_key);
+    write_setting_i(sesskey, "CtrlAltKeys", cfg->ctrlaltkeys);
+    write_setting_i(sesskey, "LocalEcho", cfg->localecho);
+    write_setting_i(sesskey, "LocalEdit", cfg->localedit);
+    write_setting_s(sesskey, "Answerback", cfg->answerback);
+    write_setting_i(sesskey, "AlwaysOnTop", cfg->alwaysontop);
+    write_setting_i(sesskey, "HideMousePtr", cfg->hide_mouseptr);
+    write_setting_i(sesskey, "SunkenEdge", cfg->sunken_edge);
+    write_setting_i(sesskey, "CurType", cfg->cursor_type);
+    write_setting_i(sesskey, "BlinkCur", cfg->blink_cur);
+    write_setting_i(sesskey, "Beep", cfg->beep);
+    write_setting_s(sesskey, "BellWaveFile", cfg->bell_wavefile);
+    write_setting_i(sesskey, "BellOverload", cfg->bellovl);
+    write_setting_i(sesskey, "BellOverloadN", cfg->bellovl_n);
+    write_setting_i(sesskey, "BellOverloadT", cfg->bellovl_t);
+    write_setting_i(sesskey, "BellOverloadS", cfg->bellovl_s);
+    write_setting_i(sesskey, "ScrollbackLines", cfg->savelines);
+    write_setting_i(sesskey, "DECOriginMode", cfg->dec_om);
+    write_setting_i(sesskey, "AutoWrapMode", cfg->wrap_mode);
+    write_setting_i(sesskey, "LFImpliesCR", cfg->lfhascr);
+    write_setting_i(sesskey, "WinNameAlways", cfg->win_name_always);
+    write_setting_s(sesskey, "WinTitle", cfg->wintitle);
+    write_setting_i(sesskey, "TermWidth", cfg->width);
+    write_setting_i(sesskey, "TermHeight", cfg->height);
+    write_setting_s(sesskey, "Font", cfg->font);
+    write_setting_i(sesskey, "FontIsBold", cfg->fontisbold);
+    write_setting_i(sesskey, "FontCharSet", cfg->fontcharset);
+    write_setting_i(sesskey, "FontHeight", cfg->fontheight);
+    write_setting_i(sesskey, "FontVTMode", cfg->vtmode);
+    write_setting_i(sesskey, "TryPalette", cfg->try_palette);
+    write_setting_i(sesskey, "BoldAsColour", cfg->bold_colour);
+    for (i = 0; i < 22; i++) {
        char buf[20], buf2[30];
        sprintf(buf, "Colour%d", i);
        sprintf(buf2, "%d,%d,%d", cfg->colours[i][0],
                cfg->colours[i][1], cfg->colours[i][2]);
-       write_setting_s (sesskey, buf, buf2);
+       write_setting_s(sesskey, buf, buf2);
     }
-    write_setting_i (sesskey, "RawCNP", cfg->rawcnp);
-    write_setting_i (sesskey, "MouseIsXterm", cfg->mouse_is_xterm);
-    for (i=0; i<256; i+=32) {
+    write_setting_i(sesskey, "RawCNP", cfg->rawcnp);
+    write_setting_i(sesskey, "MouseIsXterm", cfg->mouse_is_xterm);
+    for (i = 0; i < 256; i += 32) {
        char buf[20], buf2[256];
        int j;
        sprintf(buf, "Wordness%d", i);
        *buf2 = '\0';
-       for (j=i; j<i+32; j++) {
-           sprintf(buf2+strlen(buf2), "%s%d",
+       for (j = i; j < i + 32; j++) {
+           sprintf(buf2 + strlen(buf2), "%s%d",
                    (*buf2 ? "," : ""), cfg->wordness[j]);
        }
-       write_setting_s (sesskey, buf, buf2);
+       write_setting_s(sesskey, buf, buf2);
     }
-    write_setting_i (sesskey, "KoiWinXlat", cfg->xlat_enablekoiwin);
-    write_setting_i (sesskey, "88592Xlat", cfg->xlat_88592w1250);
-    write_setting_i (sesskey, "88592-CP852", cfg->xlat_88592cp852);
-    write_setting_i (sesskey, "CapsLockCyr", cfg->xlat_capslockcyr);
-    write_setting_i (sesskey, "ScrollBar", cfg->scrollbar);
-    write_setting_i (sesskey, "ScrollOnKey", cfg->scroll_on_key);
-    write_setting_i (sesskey, "ScrollOnDisp", cfg->scroll_on_disp);
-    write_setting_i (sesskey, "LockSize", cfg->locksize);
-    write_setting_i (sesskey, "BCE", cfg->bce);
-    write_setting_i (sesskey, "BlinkText", cfg->blinktext);
-    write_setting_i (sesskey, "X11Forward", cfg->x11_forward);
-    write_setting_s (sesskey, "X11Display", cfg->x11_display);
+    write_setting_i(sesskey, "KoiWinXlat", cfg->xlat_enablekoiwin);
+    write_setting_i(sesskey, "88592Xlat", cfg->xlat_88592w1250);
+    write_setting_i(sesskey, "88592-CP852", cfg->xlat_88592cp852);
+    write_setting_i(sesskey, "CapsLockCyr", cfg->xlat_capslockcyr);
+    write_setting_i(sesskey, "ScrollBar", cfg->scrollbar);
+    write_setting_i(sesskey, "ScrollOnKey", cfg->scroll_on_key);
+    write_setting_i(sesskey, "ScrollOnDisp", cfg->scroll_on_disp);
+    write_setting_i(sesskey, "LockSize", cfg->locksize);
+    write_setting_i(sesskey, "BCE", cfg->bce);
+    write_setting_i(sesskey, "BlinkText", cfg->blinktext);
+    write_setting_i(sesskey, "X11Forward", cfg->x11_forward);
+    write_setting_s(sesskey, "X11Display", cfg->x11_display);
 
     close_settings_w(sesskey);
 }
 
-void load_settings (char *section, int do_host, Config *cfg) {
+void load_settings(char *section, int do_host, Config * cfg)
+{
     int i;
     char prot[10];
     void *sesskey;
 
     sesskey = open_settings_r(section);
 
-    cfg->ssh_subsys = 0;               /* FIXME: load this properly */
+    cfg->ssh_subsys = 0;              /* FIXME: load this properly */
     cfg->remote_cmd_ptr = cfg->remote_cmd;
 
-    gpps (sesskey, "HostName", "", cfg->host, sizeof(cfg->host));
-    gppi (sesskey, "PortNumber", default_port, &cfg->port);
-    gpps (sesskey, "LogFileName", "putty.log",
-         cfg->logfilename, sizeof(cfg->logfilename));
-    gppi (sesskey, "LogType", 0, &cfg->logtype);
-    gppi (sesskey, "LogFileClash", LGXF_ASK, &cfg->logxfovr);
+    gpps(sesskey, "HostName", "", cfg->host, sizeof(cfg->host));
+    gppi(sesskey, "PortNumber", default_port, &cfg->port);
+    gpps(sesskey, "LogFileName", "putty.log",
+        cfg->logfilename, sizeof(cfg->logfilename));
+    gppi(sesskey, "LogType", 0, &cfg->logtype);
+    gppi(sesskey, "LogFileClash", LGXF_ASK, &cfg->logxfovr);
 
-    gpps (sesskey, "Protocol", "default", prot, 10);
+    gpps(sesskey, "Protocol", "default", prot, 10);
     cfg->protocol = default_protocol;
     for (i = 0; backends[i].name != NULL; i++)
-        if (!strcmp(prot, backends[i].name)) {
-            cfg->protocol = backends[i].protocol;
-            break;
-        }
+       if (!strcmp(prot, backends[i].name)) {
+           cfg->protocol = backends[i].protocol;
+           break;
+       }
 
-    gppi (sesskey, "CloseOnExit", COE_NORMAL, &cfg->close_on_exit);
-    gppi (sesskey, "WarnOnClose", 1, &cfg->warn_on_close);
+    gppi(sesskey, "CloseOnExit", COE_NORMAL, &cfg->close_on_exit);
+    gppi(sesskey, "WarnOnClose", 1, &cfg->warn_on_close);
     {
-      /* This is two values for backward compatibility with 0.50/0.51 */
-      int pingmin, pingsec;
-      gppi (sesskey, "PingInterval", 0, &pingmin);
-      gppi (sesskey, "PingIntervalSecs", 0, &pingsec);
-      cfg->ping_interval = pingmin*60 + pingsec;
+       /* This is two values for backward compatibility with 0.50/0.51 */
+       int pingmin, pingsec;
+       gppi(sesskey, "PingInterval", 0, &pingmin);
+       gppi(sesskey, "PingIntervalSecs", 0, &pingsec);
+       cfg->ping_interval = pingmin * 60 + pingsec;
     }
-    gpps (sesskey, "TerminalType", "xterm", cfg->termtype,
-         sizeof(cfg->termtype));
-    gpps (sesskey, "TerminalSpeed", "38400,38400", cfg->termspeed,
-         sizeof(cfg->termspeed));
+    gpps(sesskey, "TerminalType", "xterm", cfg->termtype,
+        sizeof(cfg->termtype));
+    gpps(sesskey, "TerminalSpeed", "38400,38400", cfg->termspeed,
+        sizeof(cfg->termspeed));
     {
-      char buf[2*sizeof(cfg->environmt)], *p, *q;
-       gpps (sesskey, "Environment", "", buf, sizeof(buf));
+       char buf[2 * sizeof(cfg->environmt)], *p, *q;
+       gpps(sesskey, "Environment", "", buf, sizeof(buf));
        p = buf;
        q = cfg->environmt;
        while (*p) {
@@ -214,19 +217,21 @@ void load_settings (char *section, int do_host, Config *cfg) {
                    c = *p++;
                *q++ = c;
            }
-           if (*p == ',') p++;
+           if (*p == ',')
+               p++;
            *q++ = '\0';
        }
        *q = '\0';
     }
-    gpps (sesskey, "UserName", "", cfg->username, sizeof(cfg->username));
-    gpps (sesskey, "LocalUserName", "", cfg->localusername, sizeof(cfg->localusername));
-    gppi (sesskey, "NoPTY", 0, &cfg->nopty);
-    gppi (sesskey, "Compression", 0, &cfg->compression);
-    gppi (sesskey, "AgentFwd", 0, &cfg->agentfwd);
+    gpps(sesskey, "UserName", "", cfg->username, sizeof(cfg->username));
+    gpps(sesskey, "LocalUserName", "", cfg->localusername,
+        sizeof(cfg->localusername));
+    gppi(sesskey, "NoPTY", 0, &cfg->nopty);
+    gppi(sesskey, "Compression", 0, &cfg->compression);
+    gppi(sesskey, "AgentFwd", 0, &cfg->agentfwd);
     {
        char cipher[10];
-       gpps (sesskey, "Cipher", "3des", cipher, 10);
+       gpps(sesskey, "Cipher", "3des", cipher, 10);
        if (!strcmp(cipher, "blowfish"))
            cfg->cipher = CIPHER_BLOWFISH;
        else if (!strcmp(cipher, "des"))
@@ -236,89 +241,90 @@ void load_settings (char *section, int do_host, Config *cfg) {
        else
            cfg->cipher = CIPHER_3DES;
     }
-    gppi (sesskey, "SshProt", 1, &cfg->sshprot);
-    gppi (sesskey, "BuggyMAC", 0, &cfg->buggymac);
-    gppi (sesskey, "AuthTIS", 0, &cfg->try_tis_auth);
-    gpps (sesskey, "PublicKeyFile", "", cfg->keyfile, sizeof(cfg->keyfile));
-    gpps (sesskey, "RemoteCommand", "", cfg->remote_cmd,
-          sizeof(cfg->remote_cmd));
-    gppi (sesskey, "RFCEnviron", 0, &cfg->rfc_environ);
-    gppi (sesskey, "BackspaceIsDelete", 1, &cfg->bksp_is_delete);
-    gppi (sesskey, "RXVTHomeEnd", 0, &cfg->rxvt_homeend);
-    gppi (sesskey, "LinuxFunctionKeys", 0, &cfg->funky_type);
-    gppi (sesskey, "NoApplicationKeys", 0, &cfg->no_applic_k);
-    gppi (sesskey, "NoApplicationCursors", 0, &cfg->no_applic_c);
-    gppi (sesskey, "ApplicationCursorKeys", 0, &cfg->app_cursor);
-    gppi (sesskey, "ApplicationKeypad", 0, &cfg->app_keypad);
-    gppi (sesskey, "NetHackKeypad", 0, &cfg->nethack_keypad);
-    gppi (sesskey, "AltF4", 1, &cfg->alt_f4);
-    gppi (sesskey, "AltSpace", 0, &cfg->alt_space);
-    gppi (sesskey, "AltOnly", 0, &cfg->alt_only);
-    gppi (sesskey, "ComposeKey", 0, &cfg->compose_key);
-    gppi (sesskey, "CtrlAltKeys", 1, &cfg->ctrlaltkeys);
-    gppi (sesskey, "LocalEcho", LD_BACKEND, &cfg->localecho);
-    gppi (sesskey, "LocalEdit", LD_BACKEND, &cfg->localedit);
-    gpps (sesskey, "Answerback", "PuTTY", cfg->answerback, sizeof(cfg->answerback));
-    gppi (sesskey, "AlwaysOnTop", 0, &cfg->alwaysontop);
-    gppi (sesskey, "HideMousePtr", 0, &cfg->hide_mouseptr);
-    gppi (sesskey, "SunkenEdge", 0, &cfg->sunken_edge);
-    gppi (sesskey, "CurType", 0, &cfg->cursor_type);
-    gppi (sesskey, "BlinkCur", 0, &cfg->blink_cur);
-    gppi (sesskey, "Beep", 1, &cfg->beep);
-    gpps (sesskey, "BellWaveFile", "", cfg->bell_wavefile,
-         sizeof(cfg->bell_wavefile));
-    gppi (sesskey, "BellOverload", 1, &cfg->bellovl);
-    gppi (sesskey, "BellOverloadN", 5, &cfg->bellovl_n);
-    gppi (sesskey, "BellOverloadT", 2000, &cfg->bellovl_t);
-    gppi (sesskey, "BellOverloadS", 5000, &cfg->bellovl_s);
-    gppi (sesskey, "ScrollbackLines", 200, &cfg->savelines);
-    gppi (sesskey, "DECOriginMode", 0, &cfg->dec_om);
-    gppi (sesskey, "AutoWrapMode", 1, &cfg->wrap_mode);
-    gppi (sesskey, "LFImpliesCR", 0, &cfg->lfhascr);
-    gppi (sesskey, "WinNameAlways", 0, &cfg->win_name_always);
-    gpps (sesskey, "WinTitle", "", cfg->wintitle, sizeof(cfg->wintitle));
-    gppi (sesskey, "TermWidth", 80, &cfg->width);
-    gppi (sesskey, "TermHeight", 24, &cfg->height);
-    gpps (sesskey, "Font", "Courier", cfg->font, sizeof(cfg->font));
-    gppi (sesskey, "FontIsBold", 0, &cfg->fontisbold);
-    gppi (sesskey, "FontCharSet", ANSI_CHARSET, &cfg->fontcharset);
-    gppi (sesskey, "FontHeight", 10, &cfg->fontheight);
+    gppi(sesskey, "SshProt", 1, &cfg->sshprot);
+    gppi(sesskey, "BuggyMAC", 0, &cfg->buggymac);
+    gppi(sesskey, "AuthTIS", 0, &cfg->try_tis_auth);
+    gpps(sesskey, "PublicKeyFile", "", cfg->keyfile, sizeof(cfg->keyfile));
+    gpps(sesskey, "RemoteCommand", "", cfg->remote_cmd,
+        sizeof(cfg->remote_cmd));
+    gppi(sesskey, "RFCEnviron", 0, &cfg->rfc_environ);
+    gppi(sesskey, "BackspaceIsDelete", 1, &cfg->bksp_is_delete);
+    gppi(sesskey, "RXVTHomeEnd", 0, &cfg->rxvt_homeend);
+    gppi(sesskey, "LinuxFunctionKeys", 0, &cfg->funky_type);
+    gppi(sesskey, "NoApplicationKeys", 0, &cfg->no_applic_k);
+    gppi(sesskey, "NoApplicationCursors", 0, &cfg->no_applic_c);
+    gppi(sesskey, "ApplicationCursorKeys", 0, &cfg->app_cursor);
+    gppi(sesskey, "ApplicationKeypad", 0, &cfg->app_keypad);
+    gppi(sesskey, "NetHackKeypad", 0, &cfg->nethack_keypad);
+    gppi(sesskey, "AltF4", 1, &cfg->alt_f4);
+    gppi(sesskey, "AltSpace", 0, &cfg->alt_space);
+    gppi(sesskey, "AltOnly", 0, &cfg->alt_only);
+    gppi(sesskey, "ComposeKey", 0, &cfg->compose_key);
+    gppi(sesskey, "CtrlAltKeys", 1, &cfg->ctrlaltkeys);
+    gppi(sesskey, "LocalEcho", LD_BACKEND, &cfg->localecho);
+    gppi(sesskey, "LocalEdit", LD_BACKEND, &cfg->localedit);
+    gpps(sesskey, "Answerback", "PuTTY", cfg->answerback,
+        sizeof(cfg->answerback));
+    gppi(sesskey, "AlwaysOnTop", 0, &cfg->alwaysontop);
+    gppi(sesskey, "HideMousePtr", 0, &cfg->hide_mouseptr);
+    gppi(sesskey, "SunkenEdge", 0, &cfg->sunken_edge);
+    gppi(sesskey, "CurType", 0, &cfg->cursor_type);
+    gppi(sesskey, "BlinkCur", 0, &cfg->blink_cur);
+    gppi(sesskey, "Beep", 1, &cfg->beep);
+    gpps(sesskey, "BellWaveFile", "", cfg->bell_wavefile,
+        sizeof(cfg->bell_wavefile));
+    gppi(sesskey, "BellOverload", 1, &cfg->bellovl);
+    gppi(sesskey, "BellOverloadN", 5, &cfg->bellovl_n);
+    gppi(sesskey, "BellOverloadT", 2000, &cfg->bellovl_t);
+    gppi(sesskey, "BellOverloadS", 5000, &cfg->bellovl_s);
+    gppi(sesskey, "ScrollbackLines", 200, &cfg->savelines);
+    gppi(sesskey, "DECOriginMode", 0, &cfg->dec_om);
+    gppi(sesskey, "AutoWrapMode", 1, &cfg->wrap_mode);
+    gppi(sesskey, "LFImpliesCR", 0, &cfg->lfhascr);
+    gppi(sesskey, "WinNameAlways", 0, &cfg->win_name_always);
+    gpps(sesskey, "WinTitle", "", cfg->wintitle, sizeof(cfg->wintitle));
+    gppi(sesskey, "TermWidth", 80, &cfg->width);
+    gppi(sesskey, "TermHeight", 24, &cfg->height);
+    gpps(sesskey, "Font", "Courier", cfg->font, sizeof(cfg->font));
+    gppi(sesskey, "FontIsBold", 0, &cfg->fontisbold);
+    gppi(sesskey, "FontCharSet", ANSI_CHARSET, &cfg->fontcharset);
+    gppi(sesskey, "FontHeight", 10, &cfg->fontheight);
     if (cfg->fontheight < 0) {
-        int oldh, newh;
-        HDC hdc = GetDC(NULL);
-        int logpix = GetDeviceCaps(hdc, LOGPIXELSY);
-        ReleaseDC(NULL, hdc);
+       int oldh, newh;
+       HDC hdc = GetDC(NULL);
+       int logpix = GetDeviceCaps(hdc, LOGPIXELSY);
+       ReleaseDC(NULL, hdc);
 
-        oldh = -cfg->fontheight;
-        newh = MulDiv(oldh, 72, logpix) + 1;
-        if (MulDiv(newh, logpix, 72) > oldh)
-            newh--;
-        cfg->fontheight = newh;
+       oldh = -cfg->fontheight;
+       newh = MulDiv(oldh, 72, logpix) + 1;
+       if (MulDiv(newh, logpix, 72) > oldh)
+           newh--;
+       cfg->fontheight = newh;
     }
-    gppi (sesskey, "FontVTMode", VT_OEMANSI, (int *)&cfg->vtmode);
-    gppi (sesskey, "TryPalette", 0, &cfg->try_palette);
-    gppi (sesskey, "BoldAsColour", 1, &cfg->bold_colour);
-    for (i=0; i<22; i++) {
+    gppi(sesskey, "FontVTMode", VT_OEMANSI, (int *) &cfg->vtmode);
+    gppi(sesskey, "TryPalette", 0, &cfg->try_palette);
+    gppi(sesskey, "BoldAsColour", 1, &cfg->bold_colour);
+    for (i = 0; i < 22; i++) {
        static char *defaults[] = {
            "187,187,187", "255,255,255", "0,0,0", "85,85,85", "0,0,0",
            "0,255,0", "0,0,0", "85,85,85", "187,0,0", "255,85,85",
            "0,187,0", "85,255,85", "187,187,0", "255,255,85", "0,0,187",
            "85,85,255", "187,0,187", "255,85,255", "0,187,187",
            "85,255,255", "187,187,187", "255,255,255"
-       };
+       };
        char buf[20], buf2[30];
        int c0, c1, c2;
        sprintf(buf, "Colour%d", i);
-       gpps (sesskey, buf, defaults[i], buf2, sizeof(buf2));
-       if(sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) {
+       gpps(sesskey, buf, defaults[i], buf2, sizeof(buf2));
+       if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) {
            cfg->colours[i][0] = c0;
            cfg->colours[i][1] = c1;
            cfg->colours[i][2] = c2;
        }
     }
-    gppi (sesskey, "RawCNP", 0, &cfg->rawcnp);
-    gppi (sesskey, "MouseIsXterm", 0, &cfg->mouse_is_xterm);
-    for (i=0; i<256; i+=32) {
+    gppi(sesskey, "RawCNP", 0, &cfg->rawcnp);
+    gppi(sesskey, "MouseIsXterm", 0, &cfg->mouse_is_xterm);
+    for (i = 0; i < 256; i += 32) {
        static char *defaults[] = {
            "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            "0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1",
@@ -332,55 +338,60 @@ void load_settings (char *section, int do_host, Config *cfg) {
        char buf[20], buf2[256], *p;
        int j;
        sprintf(buf, "Wordness%d", i);
-       gpps (sesskey, buf, defaults[i/32], buf2, sizeof(buf2));
+       gpps(sesskey, buf, defaults[i / 32], buf2, sizeof(buf2));
        p = buf2;
-       for (j=i; j<i+32; j++) {
+       for (j = i; j < i + 32; j++) {
            char *q = p;
-           while (*p && *p != ',') p++;
-           if (*p == ',') *p++ = '\0';
+           while (*p && *p != ',')
+               p++;
+           if (*p == ',')
+               *p++ = '\0';
            cfg->wordness[j] = atoi(q);
        }
     }
-    gppi (sesskey, "KoiWinXlat", 0, &cfg->xlat_enablekoiwin);
-    gppi (sesskey, "88592Xlat", 0, &cfg->xlat_88592w1250);
-    gppi (sesskey, "88592-CP852", 0, &cfg->xlat_88592cp852);
-    gppi (sesskey, "CapsLockCyr", 0, &cfg->xlat_capslockcyr);
-    gppi (sesskey, "ScrollBar", 1, &cfg->scrollbar);
-    gppi (sesskey, "ScrollOnKey", 0, &cfg->scroll_on_key);
-    gppi (sesskey, "ScrollOnDisp", 1, &cfg->scroll_on_disp);
-    gppi (sesskey, "LockSize", 0, &cfg->locksize);
-    gppi (sesskey, "BCE", 0, &cfg->bce);
-    gppi (sesskey, "BlinkText", 0, &cfg->blinktext);
-    gppi (sesskey, "X11Forward", 0, &cfg->x11_forward);
-    gpps (sesskey, "X11Display", "localhost:0", cfg->x11_display,
-          sizeof(cfg->x11_display));
+    gppi(sesskey, "KoiWinXlat", 0, &cfg->xlat_enablekoiwin);
+    gppi(sesskey, "88592Xlat", 0, &cfg->xlat_88592w1250);
+    gppi(sesskey, "88592-CP852", 0, &cfg->xlat_88592cp852);
+    gppi(sesskey, "CapsLockCyr", 0, &cfg->xlat_capslockcyr);
+    gppi(sesskey, "ScrollBar", 1, &cfg->scrollbar);
+    gppi(sesskey, "ScrollOnKey", 0, &cfg->scroll_on_key);
+    gppi(sesskey, "ScrollOnDisp", 1, &cfg->scroll_on_disp);
+    gppi(sesskey, "LockSize", 0, &cfg->locksize);
+    gppi(sesskey, "BCE", 0, &cfg->bce);
+    gppi(sesskey, "BlinkText", 0, &cfg->blinktext);
+    gppi(sesskey, "X11Forward", 0, &cfg->x11_forward);
+    gpps(sesskey, "X11Display", "localhost:0", cfg->x11_display,
+        sizeof(cfg->x11_display));
 
     close_settings_r(sesskey);
 }
 
-void do_defaults (char *session, Config *cfg) {
+void do_defaults(char *session, Config * cfg)
+{
     if (session)
-       load_settings (session, TRUE, cfg);
+       load_settings(session, TRUE, cfg);
     else
-       load_settings ("Default Settings", FALSE, cfg);
+       load_settings("Default Settings", FALSE, cfg);
 }
 
-static int sessioncmp(const void *av, const void *bv) {
-    const char *a = *(const char *const *)av;
-    const char *b = *(const char *const *)bv;
+static int sessioncmp(const void *av, const void *bv)
+{
+    const char *a = *(const char *const *) av;
+    const char *b = *(const char *const *) bv;
 
     /*
      * Alphabetical order, except that "Default Settings" is a
      * special case and comes first.
      */
     if (!strcmp(a, "Default Settings"))
-        return -1;                     /* a comes first */
+       return -1;                     /* a comes first */
     if (!strcmp(b, "Default Settings"))
-        return +1;                     /* b comes first */
-    return strcmp(a, b);               /* otherwise, compare normally */
+       return +1;                     /* b comes first */
+    return strcmp(a, b);              /* otherwise, compare normally */
 }
 
-void get_sesslist(int allocate) {
+void get_sesslist(int allocate)
+{
     static char otherbuf[2048];
     static char *buffer;
     int buflen, bufsize, i;
@@ -388,26 +399,26 @@ void get_sesslist(int allocate) {
     void *handle;
 
     if (allocate) {
-        
+
        if ((handle = enum_settings_start()) == NULL)
            return;
 
        buflen = bufsize = 0;
        buffer = NULL;
        do {
-            ret = enum_settings_next(handle, otherbuf, sizeof(otherbuf));
+           ret = enum_settings_next(handle, otherbuf, sizeof(otherbuf));
            if (ret) {
-                int len = strlen(otherbuf)+1;
-                if (bufsize < buflen+len) {
-                    bufsize = buflen + len + 2048;
-                    buffer = srealloc(buffer, bufsize);
-                }
-               strcpy(buffer+buflen, otherbuf);
-               buflen += strlen(buffer+buflen)+1;
+               int len = strlen(otherbuf) + 1;
+               if (bufsize < buflen + len) {
+                   bufsize = buflen + len + 2048;
+                   buffer = srealloc(buffer, bufsize);
+               }
+               strcpy(buffer + buflen, otherbuf);
+               buflen += strlen(buffer + buflen) + 1;
            }
        } while (ret);
-        enum_settings_finish(handle);
-       buffer = srealloc(buffer, buflen+1);
+       enum_settings_finish(handle);
+       buffer = srealloc(buffer, buflen + 1);
        buffer[buflen] = '\0';
 
        /*
@@ -419,26 +430,28 @@ void get_sesslist(int allocate) {
        p = buffer;
        nsessions = 1;                 /* "Default Settings" counts as one */
        while (*p) {
-            if (strcmp(p, "Default Settings"))
+           if (strcmp(p, "Default Settings"))
                nsessions++;
-           while (*p) p++;
+           while (*p)
+               p++;
            p++;
        }
 
-       sessions = smalloc((nsessions+1) * sizeof(char *));
+       sessions = smalloc((nsessions + 1) * sizeof(char *));
        sessions[0] = "Default Settings";
        p = buffer;
        i = 1;
        while (*p) {
-            if (strcmp(p, "Default Settings"))
+           if (strcmp(p, "Default Settings"))
                sessions[i++] = p;
-           while (*p) p++;
+           while (*p)
+               p++;
            p++;
        }
 
-        qsort(sessions, i, sizeof(char *), sessioncmp);
+       qsort(sessions, i, sizeof(char *), sessioncmp);
     } else {
-       sfree (buffer);
-       sfree (sessions);
+       sfree(buffer);
+       sfree(sessions);
     }
 }
diff --git a/sftp.c b/sftp.c
index 792678e..ff9e043 100644 (file)
--- a/sftp.c
+++ b/sftp.c
@@ -36,60 +36,70 @@ struct sftp_packet {
 /* ----------------------------------------------------------------------
  * SFTP packet construction functions.
  */
-static void sftp_pkt_ensure(struct sftp_packet *pkt, int length) {
+static void sftp_pkt_ensure(struct sftp_packet *pkt, int length)
+{
     if (pkt->maxlen < length) {
-        pkt->maxlen = length + 256;
+       pkt->maxlen = length + 256;
        pkt->data = srealloc(pkt->data, pkt->maxlen);
     }
 }
-static void sftp_pkt_adddata(struct sftp_packet *pkt, void *data, int len) {
+static void sftp_pkt_adddata(struct sftp_packet *pkt, void *data, int len)
+{
     pkt->length += len;
     sftp_pkt_ensure(pkt, pkt->length);
-    memcpy(pkt->data+pkt->length-len, data, len);
+    memcpy(pkt->data + pkt->length - len, data, len);
 }
-static void sftp_pkt_addbyte(struct sftp_packet *pkt, unsigned char byte) {
+static void sftp_pkt_addbyte(struct sftp_packet *pkt, unsigned char byte)
+{
     sftp_pkt_adddata(pkt, &byte, 1);
 }
-static struct sftp_packet *sftp_pkt_init(int pkt_type) {
+static struct sftp_packet *sftp_pkt_init(int pkt_type)
+{
     struct sftp_packet *pkt;
     pkt = smalloc(sizeof(struct sftp_packet));
     pkt->data = NULL;
     pkt->savedpos = -1;
     pkt->length = 0;
     pkt->maxlen = 0;
-    sftp_pkt_addbyte(pkt, (unsigned char)pkt_type);
+    sftp_pkt_addbyte(pkt, (unsigned char) pkt_type);
     return pkt;
 }
-static void sftp_pkt_addbool(struct sftp_packet *pkt, unsigned char value) {
+static void sftp_pkt_addbool(struct sftp_packet *pkt, unsigned char value)
+{
     sftp_pkt_adddata(pkt, &value, 1);
 }
-static void sftp_pkt_adduint32(struct sftp_packet *pkt, unsigned long value) {
+static void sftp_pkt_adduint32(struct sftp_packet *pkt,
+                              unsigned long value)
+{
     unsigned char x[4];
     PUT_32BIT(x, value);
     sftp_pkt_adddata(pkt, x, 4);
 }
-static void sftp_pkt_adduint64(struct sftp_packet *pkt, uint64 value) {
+static void sftp_pkt_adduint64(struct sftp_packet *pkt, uint64 value)
+{
     unsigned char x[8];
     PUT_32BIT(x, value.hi);
-    PUT_32BIT(x+4, value.lo);
+    PUT_32BIT(x + 4, value.lo);
     sftp_pkt_adddata(pkt, x, 8);
 }
-static void sftp_pkt_addstring_start(struct sftp_packet *pkt) {
+static void sftp_pkt_addstring_start(struct sftp_packet *pkt)
+{
     sftp_pkt_adduint32(pkt, 0);
     pkt->savedpos = pkt->length;
 }
-static void sftp_pkt_addstring_str(struct sftp_packet *pkt, char *data) {
+static void sftp_pkt_addstring_str(struct sftp_packet *pkt, char *data)
+{
     sftp_pkt_adddata(pkt, data, strlen(data));
-    PUT_32BIT(pkt->data + pkt->savedpos - 4,
-              pkt->length - pkt->savedpos);
+    PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
 }
 static void sftp_pkt_addstring_data(struct sftp_packet *pkt,
-                                   char *data, int len) {
+                                   char *data, int len)
+{
     sftp_pkt_adddata(pkt, data, len);
-    PUT_32BIT(pkt->data + pkt->savedpos - 4,
-              pkt->length - pkt->savedpos);
+    PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
 }
-static void sftp_pkt_addstring(struct sftp_packet *pkt, char *data) {
+static void sftp_pkt_addstring(struct sftp_packet *pkt, char *data)
+{
     sftp_pkt_addstring_start(pkt);
     sftp_pkt_addstring_str(pkt, data);
 }
@@ -98,35 +108,39 @@ static void sftp_pkt_addstring(struct sftp_packet *pkt, char *data) {
  * SFTP packet decode functions.
  */
 
-static unsigned char sftp_pkt_getbyte(struct sftp_packet *pkt) {
+static unsigned char sftp_pkt_getbyte(struct sftp_packet *pkt)
+{
     unsigned char value;
     if (pkt->length - pkt->savedpos < 1)
-        return 0;                      /* arrgh, no way to decline (FIXME?) */
+       return 0;                      /* arrgh, no way to decline (FIXME?) */
     value = (unsigned char) pkt->data[pkt->savedpos];
     pkt->savedpos++;
     return value;
 }
-static unsigned long sftp_pkt_getuint32(struct sftp_packet *pkt) {
+static unsigned long sftp_pkt_getuint32(struct sftp_packet *pkt)
+{
     unsigned long value;
     if (pkt->length - pkt->savedpos < 4)
-        return 0;                      /* arrgh, no way to decline (FIXME?) */
-    value = GET_32BIT(pkt->data+pkt->savedpos);
+       return 0;                      /* arrgh, no way to decline (FIXME?) */
+    value = GET_32BIT(pkt->data + pkt->savedpos);
     pkt->savedpos += 4;
     return value;
 }
 static void sftp_pkt_getstring(struct sftp_packet *pkt,
-                              char **p, int *length) {
+                              char **p, int *length)
+{
     *p = NULL;
     if (pkt->length - pkt->savedpos < 4)
-        return;
-    *length = GET_32BIT(pkt->data+pkt->savedpos);
+       return;
+    *length = GET_32BIT(pkt->data + pkt->savedpos);
     pkt->savedpos += 4;
     if (pkt->length - pkt->savedpos < *length)
-        return;
-    *p = pkt->data+pkt->savedpos;
+       return;
+    *p = pkt->data + pkt->savedpos;
     pkt->savedpos += *length;
 }
-static struct fxp_attrs sftp_pkt_getattrs(struct sftp_packet *pkt) {
+static struct fxp_attrs sftp_pkt_getattrs(struct sftp_packet *pkt)
+{
     struct fxp_attrs ret;
     ret.flags = sftp_pkt_getuint32(pkt);
     if (ret.flags & SSH_FILEXFER_ATTR_SIZE) {
@@ -162,24 +176,27 @@ static struct fxp_attrs sftp_pkt_getattrs(struct sftp_packet *pkt) {
     }
     return ret;
 }
-static void sftp_pkt_free(struct sftp_packet *pkt) {
-    if (pkt->data) sfree(pkt->data);
+static void sftp_pkt_free(struct sftp_packet *pkt)
+{
+    if (pkt->data)
+       sfree(pkt->data);
     sfree(pkt);
 }
 
 /* ----------------------------------------------------------------------
  * Send and receive packet functions.
  */
-int sftp_send(struct sftp_packet *pkt) {
+int sftp_send(struct sftp_packet *pkt)
+{
     int ret;
     char x[4];
     PUT_32BIT(x, pkt->length);
-    ret = (sftp_senddata(x, 4) &&
-          sftp_senddata(pkt->data, pkt->length));
+    ret = (sftp_senddata(x, 4) && sftp_senddata(pkt->data, pkt->length));
     sftp_pkt_free(pkt);
     return ret;
 }
-struct sftp_packet *sftp_recv(void) {
+struct sftp_packet *sftp_recv(void)
+{
     struct sftp_packet *pkt;
     char x[4];
 
@@ -205,8 +222,9 @@ struct sftp_packet *sftp_recv(void) {
  * String handling routines.
  */
 
-static char *mkstr(char *s, int len) {
-    char *p = smalloc(len+1);
+static char *mkstr(char *s, int len)
+{
+    char *p = smalloc(len + 1);
     memcpy(p, s, len);
     p[len] = '\0';
     return p;
@@ -224,7 +242,8 @@ static int fxp_errtype;
  * SSH_FX_OK, 0 if SSH_FX_EOF, and -1 for anything else (error).
  * Also place the status into fxp_errtype.
  */
-static int fxp_got_status(struct sftp_packet *pktin) {
+static int fxp_got_status(struct sftp_packet *pktin)
+{
     static const char *const messages[] = {
        /* SSH_FX_OK. The only time we will display a _message_ for this
         * is if we were expecting something other than FXP_STATUS on
@@ -246,8 +265,8 @@ static int fxp_got_status(struct sftp_packet *pktin) {
     } else {
        fxp_errtype = sftp_pkt_getuint32(pktin);
        if (fxp_errtype < 0 ||
-           fxp_errtype >= sizeof(messages)/sizeof(*messages))
-           fxp_error_message = "unknown error code";
+           fxp_errtype >= sizeof(messages) / sizeof(*messages))
+               fxp_error_message = "unknown error code";
        else
            fxp_error_message = messages[fxp_errtype];
     }
@@ -260,23 +279,27 @@ static int fxp_got_status(struct sftp_packet *pktin) {
        return -1;
 }
 
-static void fxp_internal_error(char *msg) {
+static void fxp_internal_error(char *msg)
+{
     fxp_error_message = msg;
     fxp_errtype = -1;
 }
 
-const char *fxp_error(void) {
+const char *fxp_error(void)
+{
     return fxp_error_message;
 }
 
-int fxp_error_type(void) {
+int fxp_error_type(void)
+{
     return fxp_errtype;
 }
 
 /*
  * Perform exchange of init/version packets. Return 0 on failure.
  */
-int fxp_init(void) {
+int fxp_init(void)
+{
     struct sftp_packet *pktout, *pktin;
     int remotever;
 
@@ -295,7 +318,8 @@ int fxp_init(void) {
     }
     remotever = sftp_pkt_getuint32(pktin);
     if (remotever > SFTP_PROTO_VERSION) {
-       fxp_internal_error("remote protocol is more advanced than we support");
+       fxp_internal_error
+           ("remote protocol is more advanced than we support");
        return 0;
     }
     /*
@@ -312,7 +336,8 @@ int fxp_init(void) {
 /*
  * Canonify a pathname.
  */
-char *fxp_realpath(char *path) {
+char *fxp_realpath(char *path)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -354,7 +379,8 @@ char *fxp_realpath(char *path) {
 /*
  * Open a file.
  */
-struct fxp_handle *fxp_open(char *path, int type) {
+struct fxp_handle *fxp_open(char *path, int type)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -394,7 +420,8 @@ struct fxp_handle *fxp_open(char *path, int type) {
 /*
  * Open a directory.
  */
-struct fxp_handle *fxp_opendir(char *path) {
+struct fxp_handle *fxp_opendir(char *path)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -432,7 +459,8 @@ struct fxp_handle *fxp_opendir(char *path) {
 /*
  * Close a file/dir.
  */
-void fxp_close(struct fxp_handle *handle) {
+void fxp_close(struct fxp_handle *handle)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -458,7 +486,9 @@ void fxp_close(struct fxp_handle *handle) {
  * will return 0 on EOF, or return -1 and store SSH_FX_EOF in the
  * error indicator. It might even depend on the SFTP server.)
  */
-int fxp_read(struct fxp_handle *handle, char *buffer, uint64 offset, int len) {
+int fxp_read(struct fxp_handle *handle, char *buffer, uint64 offset,
+            int len)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -498,7 +528,8 @@ int fxp_read(struct fxp_handle *handle, char *buffer, uint64 offset, int len) {
 /*
  * Read from a directory.
  */
-struct fxp_names *fxp_readdir(struct fxp_handle *handle) {
+struct fxp_names *fxp_readdir(struct fxp_handle *handle)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -538,7 +569,9 @@ struct fxp_names *fxp_readdir(struct fxp_handle *handle) {
 /*
  * Write to a file. Returns 0 on error, 1 on OK.
  */
-int fxp_write(struct fxp_handle *handle, char *buffer, uint64 offset, int len) {
+int fxp_write(struct fxp_handle *handle, char *buffer, uint64 offset,
+             int len)
+{
     struct sftp_packet *pktin, *pktout;
     int id;
 
@@ -563,7 +596,8 @@ int fxp_write(struct fxp_handle *handle, char *buffer, uint64 offset, int len) {
 /*
  * Free up an fxp_names structure.
  */
-void fxp_free_names(struct fxp_names *names) {
+void fxp_free_names(struct fxp_names *names)
+{
     int i;
 
     for (i = 0; i < names->nnames; i++) {
diff --git a/sftp.h b/sftp.h
index 43ee5b1..877b01e 100644 (file)
--- a/sftp.h
+++ b/sftp.h
@@ -4,31 +4,31 @@
 
 #include "int64.h"
 
-#define SSH_FXP_INIT                              1    /* 0x1 */
-#define SSH_FXP_VERSION                           2    /* 0x2 */
-#define SSH_FXP_OPEN                              3    /* 0x3 */
-#define SSH_FXP_CLOSE                             4    /* 0x4 */
-#define SSH_FXP_READ                              5    /* 0x5 */
-#define SSH_FXP_WRITE                             6    /* 0x6 */
-#define SSH_FXP_LSTAT                             7    /* 0x7 */
-#define SSH_FXP_FSTAT                             8    /* 0x8 */
-#define SSH_FXP_SETSTAT                           9    /* 0x9 */
-#define SSH_FXP_FSETSTAT                          10   /* 0xa */
-#define SSH_FXP_OPENDIR                           11   /* 0xb */
-#define SSH_FXP_READDIR                           12   /* 0xc */
-#define SSH_FXP_REMOVE                            13   /* 0xd */
-#define SSH_FXP_MKDIR                             14   /* 0xe */
-#define SSH_FXP_RMDIR                             15   /* 0xf */
-#define SSH_FXP_REALPATH                          16   /* 0x10 */
-#define SSH_FXP_STAT                              17   /* 0x11 */
-#define SSH_FXP_RENAME                            18   /* 0x12 */
-#define SSH_FXP_STATUS                            101  /* 0x65 */
-#define SSH_FXP_HANDLE                            102  /* 0x66 */
-#define SSH_FXP_DATA                              103  /* 0x67 */
-#define SSH_FXP_NAME                              104  /* 0x68 */
-#define SSH_FXP_ATTRS                             105  /* 0x69 */
-#define SSH_FXP_EXTENDED                          200  /* 0xc8 */
-#define SSH_FXP_EXTENDED_REPLY                    201  /* 0xc9 */
+#define SSH_FXP_INIT                              1    /* 0x1 */
+#define SSH_FXP_VERSION                           2    /* 0x2 */
+#define SSH_FXP_OPEN                              3    /* 0x3 */
+#define SSH_FXP_CLOSE                             4    /* 0x4 */
+#define SSH_FXP_READ                              5    /* 0x5 */
+#define SSH_FXP_WRITE                             6    /* 0x6 */
+#define SSH_FXP_LSTAT                             7    /* 0x7 */
+#define SSH_FXP_FSTAT                             8    /* 0x8 */
+#define SSH_FXP_SETSTAT                           9    /* 0x9 */
+#define SSH_FXP_FSETSTAT                          10   /* 0xa */
+#define SSH_FXP_OPENDIR                           11   /* 0xb */
+#define SSH_FXP_READDIR                           12   /* 0xc */
+#define SSH_FXP_REMOVE                            13   /* 0xd */
+#define SSH_FXP_MKDIR                             14   /* 0xe */
+#define SSH_FXP_RMDIR                             15   /* 0xf */
+#define SSH_FXP_REALPATH                          16   /* 0x10 */
+#define SSH_FXP_STAT                              17   /* 0x11 */
+#define SSH_FXP_RENAME                            18   /* 0x12 */
+#define SSH_FXP_STATUS                            101  /* 0x65 */
+#define SSH_FXP_HANDLE                            102  /* 0x66 */
+#define SSH_FXP_DATA                              103  /* 0x67 */
+#define SSH_FXP_NAME                              104  /* 0x68 */
+#define SSH_FXP_ATTRS                             105  /* 0x69 */
+#define SSH_FXP_EXTENDED                          200  /* 0xc8 */
+#define SSH_FXP_EXTENDED_REPLY                    201  /* 0xc9 */
 
 #define SSH_FX_OK                                 0
 #define SSH_FX_EOF                                1
@@ -124,12 +124,14 @@ void fxp_close(struct fxp_handle *handle);
 /*
  * Read from a file.
  */
-int fxp_read(struct fxp_handle *handle, char *buffer, uint64 offset, int len);
+int fxp_read(struct fxp_handle *handle, char *buffer, uint64 offset,
+            int len);
 
 /*
  * Write to a file. Returns 0 on error, 1 on OK.
  */
-int fxp_write(struct fxp_handle *handle, char *buffer, uint64 offset, int len);
+int fxp_write(struct fxp_handle *handle, char *buffer, uint64 offset,
+             int len);
 
 /*
  * Read from a directory.
index 8a37b47..c883211 100644 (file)
--- a/sizetip.c
+++ b/sizetip.c
@@ -14,75 +14,76 @@ static COLORREF tip_bg;
 static COLORREF tip_text;
 
 static LRESULT CALLBACK SizeTipWndProc(HWND hWnd, UINT nMsg,
-                                       WPARAM wParam, LPARAM lParam)
+                                      WPARAM wParam, LPARAM lParam)
 {
 
     switch (nMsg) {
       case WM_ERASEBKGND:
-        return TRUE;
+       return TRUE;
 
       case WM_PAINT:
-        {
-            HBRUSH hbr;
-            HGDIOBJ holdbr;
-            RECT cr;
-            int wtlen;
-            LPTSTR wt;
-            HDC hdc;
+       {
+           HBRUSH hbr;
+           HGDIOBJ holdbr;
+           RECT cr;
+           int wtlen;
+           LPTSTR wt;
+           HDC hdc;
 
-            PAINTSTRUCT ps;
-            hdc = BeginPaint(hWnd, &ps);
+           PAINTSTRUCT ps;
+           hdc = BeginPaint(hWnd, &ps);
 
-            SelectObject(hdc, tip_font);
-            SelectObject(hdc, GetStockObject(BLACK_PEN));
+           SelectObject(hdc, tip_font);
+           SelectObject(hdc, GetStockObject(BLACK_PEN));
 
-            hbr = CreateSolidBrush(tip_bg);
-            holdbr = SelectObject(hdc, hbr);
+           hbr = CreateSolidBrush(tip_bg);
+           holdbr = SelectObject(hdc, hbr);
 
-            GetClientRect(hWnd, &cr);
-            Rectangle(hdc, cr.left, cr.top, cr.right, cr.bottom);
+           GetClientRect(hWnd, &cr);
+           Rectangle(hdc, cr.left, cr.top, cr.right, cr.bottom);
 
-            wtlen = GetWindowTextLength(hWnd);
-            wt = (LPTSTR)smalloc((wtlen+1)*sizeof(TCHAR));
-            GetWindowText(hWnd, wt, wtlen+1);
+           wtlen = GetWindowTextLength(hWnd);
+           wt = (LPTSTR) smalloc((wtlen + 1) * sizeof(TCHAR));
+           GetWindowText(hWnd, wt, wtlen + 1);
 
-            SetTextColor(hdc, tip_text);
-            SetBkColor(hdc, tip_bg);
+           SetTextColor(hdc, tip_text);
+           SetBkColor(hdc, tip_bg);
 
-            TextOut(hdc, cr.left+3, cr.top+3, wt, wtlen);
+           TextOut(hdc, cr.left + 3, cr.top + 3, wt, wtlen);
 
-            sfree(wt);
+           sfree(wt);
 
-            SelectObject(hdc, holdbr);
-            DeleteObject(hbr);
+           SelectObject(hdc, holdbr);
+           DeleteObject(hbr);
 
-            EndPaint(hWnd, &ps);
-        }
-        return 0;
+           EndPaint(hWnd, &ps);
+       }
+       return 0;
 
       case WM_NCHITTEST:
-        return HTTRANSPARENT;
+       return HTTRANSPARENT;
 
       case WM_DESTROY:
-        DeleteObject(tip_font);
-        tip_font = NULL;
-        break;
+       DeleteObject(tip_font);
+       tip_font = NULL;
+       break;
 
       case WM_SETTEXT:
-        {
-            LPCTSTR str = (LPCTSTR)lParam;
-            SIZE sz;
-            HDC hdc = CreateCompatibleDC(NULL);
+       {
+           LPCTSTR str = (LPCTSTR) lParam;
+           SIZE sz;
+           HDC hdc = CreateCompatibleDC(NULL);
 
-            SelectObject(hdc, tip_font);
-            GetTextExtentPoint32(hdc, str, _tcslen(str), &sz);
+           SelectObject(hdc, tip_font);
+           GetTextExtentPoint32(hdc, str, _tcslen(str), &sz);
 
-            SetWindowPos(hWnd, NULL, 0, 0, sz.cx+6, sz.cy+6, SWP_NOZORDER|SWP_NOMOVE|SWP_NOACTIVATE);
-            InvalidateRect(hWnd, NULL, FALSE);
+           SetWindowPos(hWnd, NULL, 0, 0, sz.cx + 6, sz.cy + 6,
+                        SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
+           InvalidateRect(hWnd, NULL, FALSE);
 
-            DeleteDC(hdc);
-        }
-        break;
+           DeleteDC(hdc);
+       }
+       break;
     }
 
     return DefWindowProc(hWnd, nMsg, wParam, lParam);
@@ -95,46 +96,47 @@ void UpdateSizeTip(HWND src, int cx, int cy)
 {
     TCHAR str[32];
 
-    if (!tip_enabled) return;
+    if (!tip_enabled)
+       return;
 
     if (!tip_wnd) {
-        NONCLIENTMETRICS nci;
-
-        /* First make sure the window class is registered */
-
-        if (!tip_class) {
-            WNDCLASS wc;
-            wc.style = CS_HREDRAW|CS_VREDRAW;
-            wc.lpfnWndProc = SizeTipWndProc;
-            wc.cbClsExtra = 0;
-            wc.cbWndExtra = 0;
-            wc.hInstance = hinst;
-            wc.hIcon = NULL;
-            wc.hCursor = NULL;
-            wc.hbrBackground = NULL;
-            wc.lpszMenuName = NULL;
-            wc.lpszClassName = "SizeTipClass";
-
-            tip_class = RegisterClass(&wc);
-        }
-
+       NONCLIENTMETRICS nci;
+
+       /* First make sure the window class is registered */
+
+       if (!tip_class) {
+           WNDCLASS wc;
+           wc.style = CS_HREDRAW | CS_VREDRAW;
+           wc.lpfnWndProc = SizeTipWndProc;
+           wc.cbClsExtra = 0;
+           wc.cbWndExtra = 0;
+           wc.hInstance = hinst;
+           wc.hIcon = NULL;
+           wc.hCursor = NULL;
+           wc.hbrBackground = NULL;
+           wc.lpszMenuName = NULL;
+           wc.lpszClassName = "SizeTipClass";
+
+           tip_class = RegisterClass(&wc);
+       }
 #if 0
-        /* Default values based on Windows Standard color scheme */
+       /* Default values based on Windows Standard color scheme */
 
-        tip_font = GetStockObject(SYSTEM_FONT);
-        tip_bg = RGB(255, 255, 225);
-        tip_text = RGB(0, 0, 0);
+       tip_font = GetStockObject(SYSTEM_FONT);
+       tip_bg = RGB(255, 255, 225);
+       tip_text = RGB(0, 0, 0);
 #endif
 
-        /* Prepare other GDI objects and drawing info */
+       /* Prepare other GDI objects and drawing info */
 
-        tip_bg = GetSysColor(COLOR_INFOBK);
-        tip_text = GetSysColor(COLOR_INFOTEXT);
+       tip_bg = GetSysColor(COLOR_INFOBK);
+       tip_text = GetSysColor(COLOR_INFOTEXT);
 
-        memset(&nci, 0, sizeof(NONCLIENTMETRICS));
-        nci.cbSize = sizeof(NONCLIENTMETRICS);
-        SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &nci, 0);
-        tip_font = CreateFontIndirect(&nci.lfStatusFont);
+       memset(&nci, 0, sizeof(NONCLIENTMETRICS));
+       nci.cbSize = sizeof(NONCLIENTMETRICS);
+       SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
+                            sizeof(NONCLIENTMETRICS), &nci, 0);
+       tip_font = CreateFontIndirect(&nci.lfStatusFont);
     }
 
     /* Generate the tip text */
@@ -142,46 +144,49 @@ void UpdateSizeTip(HWND src, int cx, int cy)
     sprintf(str, "%dx%d", cx, cy);
 
     if (!tip_wnd) {
-        HDC hdc;
-        SIZE sz;
-        RECT wr;
-        int ix, iy;
+       HDC hdc;
+       SIZE sz;
+       RECT wr;
+       int ix, iy;
 
-        /* calculate the tip's size */
+       /* calculate the tip's size */
 
-        hdc = CreateCompatibleDC(NULL);
-        GetTextExtentPoint32(hdc, str, _tcslen(str), &sz);
-        DeleteDC(hdc);
+       hdc = CreateCompatibleDC(NULL);
+       GetTextExtentPoint32(hdc, str, _tcslen(str), &sz);
+       DeleteDC(hdc);
 
-        GetWindowRect(src, &wr);
+       GetWindowRect(src, &wr);
 
-        ix = wr.left;
-        if (ix<16) ix = 16;
+       ix = wr.left;
+       if (ix < 16)
+           ix = 16;
 
-        iy = wr.top - sz.cy;
-        if (iy<16) iy = 16;
+       iy = wr.top - sz.cy;
+       if (iy < 16)
+           iy = 16;
 
-        /* Create the tip window */
+       /* Create the tip window */
 
-        tip_wnd = CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TOPMOST, MAKEINTRESOURCE(tip_class), str, WS_POPUP,
-                                ix, iy, sz.cx, sz.cy,
-                                NULL, NULL, hinst, NULL);
+       tip_wnd =
+           CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
+                          MAKEINTRESOURCE(tip_class), str, WS_POPUP, ix,
+                          iy, sz.cx, sz.cy, NULL, NULL, hinst, NULL);
 
-        ShowWindow(tip_wnd, SW_SHOWNOACTIVATE);
+       ShowWindow(tip_wnd, SW_SHOWNOACTIVATE);
 
     } else {
 
-        /* Tip already exists, just set the text */
+       /* Tip already exists, just set the text */
 
-        SetWindowText(tip_wnd, str);
+       SetWindowText(tip_wnd, str);
     }
 }
 
 void EnableSizeTip(int bEnable)
 {
     if (tip_wnd && !bEnable) {
-        DestroyWindow(tip_wnd);
-        tip_wnd = NULL;
+       DestroyWindow(tip_wnd);
+       tip_wnd = NULL;
     }
 
     tip_enabled = bEnable;
diff --git a/ssh.c b/ssh.c
index b3be8e4..9f0fe61 100644 (file)
--- a/ssh.c
+++ b/ssh.c
                           (s ? sk_close(s), s = NULL : 0), \
                           connection_fatal msg )
 
-#define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
-#define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
-#define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
-#define SSH1_CMSG_USER                            4    /* 0x4 */
-#define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
-#define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
-#define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
-#define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
-#define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
-#define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
-#define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
-#define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
-#define SSH1_SMSG_SUCCESS                         14   /* 0xe */
-#define SSH1_SMSG_FAILURE                         15   /* 0xf */
-#define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
-#define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
-#define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
-#define SSH1_CMSG_EOF                             19   /* 0x13 */
-#define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
-#define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
-#define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
-#define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
-#define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
-#define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
-#define SSH1_SMSG_X11_OPEN                        27   /* 0x1b */
-#define SSH1_CMSG_PORT_FORWARD_REQUEST            28   /* 0x1c */
-#define SSH1_MSG_PORT_OPEN                        29   /* 0x1d */
-#define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
-#define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
-#define SSH1_MSG_IGNORE                           32   /* 0x20 */
-#define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
-#define SSH1_CMSG_X11_REQUEST_FORWARDING          34   /* 0x22 */
-#define SSH1_CMSG_AUTH_RHOSTS_RSA                 35   /* 0x23 */
-#define SSH1_MSG_DEBUG                            36   /* 0x24 */
-#define SSH1_CMSG_REQUEST_COMPRESSION             37   /* 0x25 */
-#define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
-#define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
-#define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
-#define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
-#define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
-#define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
-
-#define SSH1_AUTH_TIS                             5    /* 0x5 */
-#define SSH1_AUTH_CCARD                           16   /* 0x10 */
-
-#define SSH1_PROTOFLAG_SCREEN_NUMBER              1    /* 0x1 */
+#define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
+#define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
+#define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
+#define SSH1_CMSG_USER                            4    /* 0x4 */
+#define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
+#define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
+#define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
+#define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
+#define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
+#define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
+#define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
+#define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
+#define SSH1_SMSG_SUCCESS                         14   /* 0xe */
+#define SSH1_SMSG_FAILURE                         15   /* 0xf */
+#define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
+#define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
+#define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
+#define SSH1_CMSG_EOF                             19   /* 0x13 */
+#define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
+#define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
+#define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
+#define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
+#define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
+#define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
+#define SSH1_SMSG_X11_OPEN                        27   /* 0x1b */
+#define SSH1_CMSG_PORT_FORWARD_REQUEST            28   /* 0x1c */
+#define SSH1_MSG_PORT_OPEN                        29   /* 0x1d */
+#define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
+#define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
+#define SSH1_MSG_IGNORE                           32   /* 0x20 */
+#define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
+#define SSH1_CMSG_X11_REQUEST_FORWARDING          34   /* 0x22 */
+#define SSH1_CMSG_AUTH_RHOSTS_RSA                 35   /* 0x23 */
+#define SSH1_MSG_DEBUG                            36   /* 0x24 */
+#define SSH1_CMSG_REQUEST_COMPRESSION             37   /* 0x25 */
+#define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
+#define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
+#define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
+#define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
+#define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
+#define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
+
+#define SSH1_AUTH_TIS                             5    /* 0x5 */
+#define SSH1_AUTH_CCARD                           16   /* 0x10 */
+
+#define SSH1_PROTOFLAG_SCREEN_NUMBER              1    /* 0x1 */
 /* Mask for protoflags we will echo back to server if seen */
-#define SSH1_PROTOFLAGS_SUPPORTED                 0    /* 0x1 */
-
-#define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
-#define SSH2_MSG_IGNORE                           2    /* 0x2 */
-#define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
-#define SSH2_MSG_DEBUG                            4    /* 0x4 */
-#define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
-#define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
-#define SSH2_MSG_KEXINIT                          20   /* 0x14 */
-#define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
-#define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
-#define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
-#define SSH2_MSG_KEX_DH_GEX_REQUEST               30   /* 0x1e */
-#define SSH2_MSG_KEX_DH_GEX_GROUP                 31   /* 0x1f */
-#define SSH2_MSG_KEX_DH_GEX_INIT                  32   /* 0x20 */
-#define SSH2_MSG_KEX_DH_GEX_REPLY                 33   /* 0x21 */
-#define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
-#define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
-#define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
-#define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
-#define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
-#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
-#define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
-#define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
-#define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
-#define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
-#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
-#define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
-#define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
-#define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
-#define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
-#define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
-#define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
-#define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
-#define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
-#define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
-
-#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1  /* 0x1 */
-#define SSH2_DISCONNECT_PROTOCOL_ERROR            2    /* 0x2 */
-#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED       3    /* 0x3 */
-#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4   /* 0x4 */
-#define SSH2_DISCONNECT_MAC_ERROR                 5    /* 0x5 */
-#define SSH2_DISCONNECT_COMPRESSION_ERROR         6    /* 0x6 */
-#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE     7    /* 0x7 */
-#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
-#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE   9    /* 0x9 */
-#define SSH2_DISCONNECT_CONNECTION_LOST           10   /* 0xa */
-#define SSH2_DISCONNECT_BY_APPLICATION            11   /* 0xb */
-#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS      12   /* 0xc */
-#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER    13   /* 0xd */
-#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
-#define SSH2_DISCONNECT_ILLEGAL_USER_NAME         15   /* 0xf */
+#define SSH1_PROTOFLAGS_SUPPORTED                 0    /* 0x1 */
+
+#define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
+#define SSH2_MSG_IGNORE                           2    /* 0x2 */
+#define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
+#define SSH2_MSG_DEBUG                            4    /* 0x4 */
+#define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
+#define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
+#define SSH2_MSG_KEXINIT                          20   /* 0x14 */
+#define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
+#define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
+#define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
+#define SSH2_MSG_KEX_DH_GEX_REQUEST               30   /* 0x1e */
+#define SSH2_MSG_KEX_DH_GEX_GROUP                 31   /* 0x1f */
+#define SSH2_MSG_KEX_DH_GEX_INIT                  32   /* 0x20 */
+#define SSH2_MSG_KEX_DH_GEX_REPLY                 33   /* 0x21 */
+#define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
+#define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
+#define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
+#define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
+#define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
+#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
+#define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
+#define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
+#define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
+#define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
+#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
+#define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
+#define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
+#define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
+#define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
+#define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
+#define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
+#define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
+#define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
+#define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
+
+#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1  /* 0x1 */
+#define SSH2_DISCONNECT_PROTOCOL_ERROR            2    /* 0x2 */
+#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED       3    /* 0x3 */
+#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4   /* 0x4 */
+#define SSH2_DISCONNECT_MAC_ERROR                 5    /* 0x5 */
+#define SSH2_DISCONNECT_COMPRESSION_ERROR         6    /* 0x6 */
+#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE     7    /* 0x7 */
+#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8       /* 0x8 */
+#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE   9    /* 0x9 */
+#define SSH2_DISCONNECT_CONNECTION_LOST           10   /* 0xa */
+#define SSH2_DISCONNECT_BY_APPLICATION            11   /* 0xb */
+#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS      12   /* 0xc */
+#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER    13   /* 0xd */
+#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14      /* 0xe */
+#define SSH2_DISCONNECT_ILLEGAL_USER_NAME         15   /* 0xf */
 
 static const char *const ssh2_disconnect_reasons[] = {
     NULL,
@@ -145,12 +145,12 @@ static const char *const ssh2_disconnect_reasons[] = {
     "SSH_DISCONNECT_ILLEGAL_USER_NAME",
 };
 
-#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
-#define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
-#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
-#define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
+#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
+#define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
+#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
+#define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
 
-#define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
+#define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
 
 /*
  * Various remote-bug flags.
@@ -191,9 +191,9 @@ enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
 #define crWaitUntilV(c)        do { crReturnV; } while (!(c))
 
-extern char *x11_init (Socket *, char *, void *);
-extern void x11_close (Socket);
-extern void x11_send  (Socket , char *, int);
+extern char *x11_init(Socket *, char *, void *);
+extern void x11_close(Socket);
+extern void x11_send(Socket, char *, int);
 extern void x11_invent_auth(char *, int, char *, int);
 
 /*
@@ -210,27 +210,44 @@ const static struct ssh2_ciphers *ciphers[] = {
 
 const static struct ssh_kex *kex_algs[] = {
     &ssh_diffiehellman_gex,
-    &ssh_diffiehellman };
+    &ssh_diffiehellman
+};
 
 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
 
-static void nullmac_key(unsigned char *key) { }
-static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
-static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
+static void nullmac_key(unsigned char *key)
+{
+}
+static void nullmac_generate(unsigned char *blk, int len,
+                            unsigned long seq)
+{
+}
+static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
+{
+    return 1;
+}
 const static struct ssh_mac ssh_mac_none = {
     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
 };
 const static struct ssh_mac *macs[] = {
-    &ssh_sha1, &ssh_md5, &ssh_mac_none };
+    &ssh_sha1, &ssh_md5, &ssh_mac_none
+};
 const static struct ssh_mac *buggymacs[] = {
-    &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
+    &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
+};
 
-static void ssh_comp_none_init(void) { }
+static void ssh_comp_none_init(void)
+{
+}
 static int ssh_comp_none_block(unsigned char *block, int len,
-                              unsigned char **outblock, int *outlen) {
+                              unsigned char **outblock, int *outlen)
+{
+    return 0;
+}
+static int ssh_comp_none_disable(void)
+{
     return 0;
 }
-static int ssh_comp_none_disable(void) { return 0; }
 const static struct ssh_compress ssh_comp_none = {
     "none",
     ssh_comp_none_init, ssh_comp_none_block,
@@ -239,9 +256,10 @@ const static struct ssh_compress ssh_comp_none = {
 };
 extern const struct ssh_compress ssh_zlib;
 const static struct ssh_compress *compressions[] = {
-    &ssh_zlib, &ssh_comp_none };
+    &ssh_zlib, &ssh_comp_none
+};
 
-enum {                                 /* channel types */
+enum {                                /* channel types */
     CHAN_MAINSESSION,
     CHAN_X11,
     CHAN_AGENT,
@@ -255,19 +273,19 @@ struct ssh_channel {
     int type;
     int closes;
     struct ssh2_data_channel {
-        unsigned char *outbuffer;
-        unsigned outbuflen, outbufsize;
-        unsigned remwindow, remmaxpkt;
+       unsigned char *outbuffer;
+       unsigned outbuflen, outbufsize;
+       unsigned remwindow, remmaxpkt;
     } v2;
     union {
-        struct ssh_agent_channel {
-            unsigned char *message;
-            unsigned char msglen[4];
-            int lensofar, totallen;
-        } a;
-        struct ssh_x11_channel {
-            Socket s;
-        } x11;
+       struct ssh_agent_channel {
+           unsigned char *message;
+           unsigned char msglen[4];
+           int lensofar, totallen;
+       } a;
+       struct ssh_x11_channel {
+           Socket s;
+       } x11;
     } u;
 };
 
@@ -301,15 +319,15 @@ static const struct ssh_compress *sccomp = NULL;
 static const struct ssh_kex *kex = NULL;
 static const struct ssh_signkey *hostkey = NULL;
 static unsigned char ssh2_session_id[20];
-int (*ssh_get_line)(const char *prompt, char *str, int maxlen,
-                    int is_pw) = NULL;
+int (*ssh_get_line) (const char *prompt, char *str, int maxlen,
+                    int is_pw) = NULL;
 
 static char *savedhost;
 static int savedport;
 static int ssh_send_ok;
 static int ssh_echoing, ssh_editing;
 
-static tree234 *ssh_channels;           /* indexed by local id */
+static tree234 *ssh_channels;         /* indexed by local id */
 static struct ssh_channel *mainchan;   /* primary session channel */
 
 static enum {
@@ -328,15 +346,16 @@ static unsigned char *deferred_send_data = NULL;
 static int deferred_len = 0, deferred_size = 0;
 
 static int ssh_version;
-static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
+static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
 static void ssh_size(void);
-static void ssh_special (Telnet_Special);
+static void ssh_special(Telnet_Special);
 static void ssh2_try_send(struct ssh_channel *c);
-static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
+static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
+                                 int len);
 
-static int (*s_rdpkt)(unsigned char **data, int *datalen);
+static int (*s_rdpkt) (unsigned char **data, int *datalen);
 
 static struct rdpkt1_state_tag {
     long len, pad, biglen, to_read;
@@ -353,22 +372,29 @@ static struct rdpkt2_state_tag {
     unsigned long incoming_sequence;
 } rdpkt2_state;
 
-static int ssh_channelcmp(void *av, void *bv) {
-    struct ssh_channel *a = (struct ssh_channel *)av;
-    struct ssh_channel *b = (struct ssh_channel *)bv;
-    if (a->localid < b->localid) return -1;
-    if (a->localid > b->localid) return +1;
+static int ssh_channelcmp(void *av, void *bv)
+{
+    struct ssh_channel *a = (struct ssh_channel *) av;
+    struct ssh_channel *b = (struct ssh_channel *) bv;
+    if (a->localid < b->localid)
+       return -1;
+    if (a->localid > b->localid)
+       return +1;
     return 0;
 }
-static int ssh_channelfind(void *av, void *bv) {
-    unsigned *a = (unsigned *)av;
-    struct ssh_channel *b = (struct ssh_channel *)bv;
-    if (*a < b->localid) return -1;
-    if (*a > b->localid) return +1;
+static int ssh_channelfind(void *av, void *bv)
+{
+    unsigned *a = (unsigned *) av;
+    struct ssh_channel *b = (struct ssh_channel *) bv;
+    if (*a < b->localid)
+       return -1;
+    if (*a > b->localid)
+       return +1;
     return 0;
 }
 
-static int alloc_channel_id(void) {
+static int alloc_channel_id(void)
+{
     const unsigned CHANNEL_NUMBER_OFFSET = 256;
     unsigned low, high, mid;
     int tsize;
@@ -384,7 +410,8 @@ static int alloc_channel_id(void) {
      */
     tsize = count234(ssh_channels);
 
-    low = -1; high = tsize;
+    low = -1;
+    high = tsize;
     while (high - low > 1) {
        mid = (high + low) / 2;
        c = index234(ssh_channels, mid);
@@ -404,28 +431,31 @@ static int alloc_channel_id(void) {
     return low + 1 + CHANNEL_NUMBER_OFFSET;
 }
 
-static void c_write (char *buf, int len) {
+static void c_write(char *buf, int len)
+{
     if ((flags & FLAG_STDERR)) {
-        int i;
-        for (i = 0; i < len; i++)
-            if (buf[i] != '\r')
-                fputc(buf[i], stderr);
+       int i;
+       for (i = 0; i < len; i++)
+           if (buf[i] != '\r')
+               fputc(buf[i], stderr);
        return;
     }
     from_backend(1, buf, len);
 }
 
-static void c_write_untrusted(char *buf, int len) {
+static void c_write_untrusted(char *buf, int len)
+{
     int i;
     for (i = 0; i < len; i++) {
-        if (buf[i] == '\n')
-            c_write("\r\n", 2);
-        else if ((buf[i] & 0x60) || (buf[i] == '\r'))
-            c_write(buf+i, 1);
+       if (buf[i] == '\n')
+           c_write("\r\n", 2);
+       else if ((buf[i] & 0x60) || (buf[i] == '\r'))
+           c_write(buf + i, 1);
     }
 }
 
-static void c_write_str (char *buf) {
+static void c_write_str(char *buf)
+{
     c_write(buf, strlen(buf));
 }
 
@@ -443,21 +473,21 @@ static int ssh1_rdpkt(unsigned char **data, int *datalen)
 
     crBegin;
 
-next_packet:
+  next_packet:
 
     pktin.type = 0;
     pktin.length = 0;
 
     for (st->i = st->len = 0; st->i < 4; st->i++) {
        while ((*datalen) == 0)
-           crReturn(4-st->i);
+           crReturn(4 - st->i);
        st->len = (st->len << 8) + **data;
        (*data)++, (*datalen)--;
     }
 
 #ifdef FWHACK
-    if (st->len == 0x52656d6f) {        /* "Remo"te server has closed ... */
-        st->len = 0x300;                /* big enough to carry to end */
+    if (st->len == 0x52656d6f) {       /* "Remo"te server has closed ... */
+       st->len = 0x300;               /* big enough to carry to end */
     }
 #endif
 
@@ -467,8 +497,8 @@ next_packet:
 
     if (pktin.maxlen < st->biglen) {
        pktin.maxlen = st->biglen;
-       pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
-                     srealloc(pktin.data, st->biglen+APIEXTRA));
+       pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
+                     srealloc(pktin.data, st->biglen + APIEXTRA));
        if (!pktin.data)
            fatalbox("Out of memory");
     }
@@ -476,7 +506,7 @@ next_packet:
     st->to_read = st->biglen;
     st->p = pktin.data;
     while (st->to_read > 0) {
-        st->chunk = st->to_read;
+       st->chunk = st->to_read;
        while ((*datalen) == 0)
            crReturn(st->to_read);
        if (st->chunk > (*datalen))
@@ -495,11 +525,11 @@ next_packet:
     dmemdump(pktin.data, st->biglen);
 #endif
 
-    st->realcrc = crc32(pktin.data, st->biglen-4);
-    st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
+    st->realcrc = crc32(pktin.data, st->biglen - 4);
+    st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
     if (st->gotcrc != st->realcrc) {
        bombout(("Incorrect CRC received on packet"));
-        crReturn(0);
+       crReturn(0);
     }
 
     pktin.body = pktin.data + st->pad + 1;
@@ -509,38 +539,38 @@ next_packet:
        int decomplen;
 #ifdef DUMP_PACKETS
        debug(("Packet payload pre-decompression:\n"));
-       dmemdump(pktin.body-1, pktin.length+1);
+       dmemdump(pktin.body - 1, pktin.length + 1);
 #endif
-       zlib_decompress_block(pktin.body-1, pktin.length+1,
+       zlib_decompress_block(pktin.body - 1, pktin.length + 1,
                              &decompblk, &decomplen);
 
        if (pktin.maxlen < st->pad + decomplen) {
            pktin.maxlen = st->pad + decomplen;
-           pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
-            pktin.body = pktin.data + st->pad + 1;
+           pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
+           pktin.body = pktin.data + st->pad + 1;
            if (!pktin.data)
                fatalbox("Out of memory");
        }
 
-       memcpy(pktin.body-1, decompblk, decomplen);
+       memcpy(pktin.body - 1, decompblk, decomplen);
        sfree(decompblk);
-       pktin.length = decomplen-1;
+       pktin.length = decomplen - 1;
 #ifdef DUMP_PACKETS
        debug(("Packet payload post-decompression:\n"));
-       dmemdump(pktin.body-1, pktin.length+1);
+       dmemdump(pktin.body - 1, pktin.length + 1);
 #endif
     }
 
     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
-        pktin.type == SSH1_SMSG_STDERR_DATA ||
-        pktin.type == SSH1_MSG_DEBUG ||
-        pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
-        pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
+       pktin.type == SSH1_SMSG_STDERR_DATA ||
+       pktin.type == SSH1_MSG_DEBUG ||
+       pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
+       pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
        long strlen = GET_32BIT(pktin.body);
        if (strlen + 4 != pktin.length) {
            bombout(("Received data packet with bogus string length"));
-            crReturn(0);
-        }
+           crReturn(0);
+       }
     }
 
     pktin.type = pktin.body[-1];
@@ -550,9 +580,10 @@ next_packet:
        char buf[80];
        int strlen = GET_32BIT(pktin.body);
        strcpy(buf, "Remote: ");
-       if (strlen > 70) strlen = 70;
-       memcpy(buf+8, pktin.body+4, strlen);
-       buf[8+strlen] = '\0';
+       if (strlen > 70)
+           strlen = 70;
+       memcpy(buf + 8, pktin.body + 4, strlen);
+       buf[8 + strlen] = '\0';
        logevent(buf);
        goto next_packet;
     } else if (pktin.type == SSH1_MSG_IGNORE) {
@@ -567,10 +598,10 @@ next_packet:
        unsigned nowlen;
        strcpy(buf, "Remote sent disconnect: ");
        nowlen = strlen(buf);
-       if (msglen > sizeof(buf)-nowlen-1)
-           msglen = sizeof(buf)-nowlen-1;
-       memcpy(buf+nowlen, pktin.body+4, msglen);
-       buf[nowlen+msglen] = '\0';
+       if (msglen > sizeof(buf) - nowlen - 1)
+           msglen = sizeof(buf) - nowlen - 1;
+       memcpy(buf + nowlen, pktin.body + 4, msglen);
+       buf[nowlen + msglen] = '\0';
        logevent(buf);
     }
 
@@ -583,20 +614,24 @@ static int ssh2_rdpkt(unsigned char **data, int *datalen)
 
     crBegin;
 
-next_packet:
+  next_packet:
     pktin.type = 0;
     pktin.length = 0;
     if (sccipher)
-        st->cipherblk = sccipher->blksize;
+       st->cipherblk = sccipher->blksize;
     else
-        st->cipherblk = 8;
+       st->cipherblk = 8;
     if (st->cipherblk < 8)
-        st->cipherblk = 8;
+       st->cipherblk = 8;
 
     if (pktin.maxlen < st->cipherblk) {
        pktin.maxlen = st->cipherblk;
-       pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
-                     srealloc(pktin.data, st->cipherblk+APIEXTRA));
+       pktin.data =
+           (pktin.data ==
+            NULL ? smalloc(st->cipherblk +
+                           APIEXTRA) : srealloc(pktin.data,
+                                                st->cipherblk +
+                                                APIEXTRA));
        if (!pktin.data)
            fatalbox("Out of memory");
     }
@@ -605,19 +640,19 @@ next_packet:
      * Acquire and decrypt the first block of the packet. This will
      * contain the length and padding details.
      */
-     for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
+    for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
        while ((*datalen) == 0)
-           crReturn(st->cipherblk-st->i);
+           crReturn(st->cipherblk - st->i);
        pktin.data[st->i] = *(*data)++;
-        (*datalen)--;
+       (*datalen)--;
     }
 #ifdef FWHACK
-    if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
-        /* FIXME */
+    if (!memcmp(pktin.data, "Remo", 4)) {      /* "Remo"te server has closed ... */
+       /* FIXME */
     }
 #endif
     if (sccipher)
-        sccipher->decrypt(pktin.data, st->cipherblk);
+       sccipher->decrypt(pktin.data, st->cipherblk);
 
     /*
      * Now get the length and padding figures.
@@ -641,10 +676,14 @@ next_packet:
     /*
      * Adjust memory allocation if packet is too big.
      */
-    if (pktin.maxlen < st->packetlen+st->maclen) {
-       pktin.maxlen = st->packetlen+st->maclen;
-       pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
-                     srealloc(pktin.data, pktin.maxlen+APIEXTRA));
+    if (pktin.maxlen < st->packetlen + st->maclen) {
+       pktin.maxlen = st->packetlen + st->maclen;
+       pktin.data =
+           (pktin.data ==
+            NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
+                                                               pktin.maxlen
+                                                               +
+                                                               APIEXTRA));
        if (!pktin.data)
            fatalbox("Out of memory");
     }
@@ -652,16 +691,17 @@ next_packet:
     /*
      * Read and decrypt the remainder of the packet.
      */
-    for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
+    for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
+        st->i++) {
        while ((*datalen) == 0)
            crReturn(st->packetlen + st->maclen - st->i);
        pktin.data[st->i] = *(*data)++;
-        (*datalen)--;
+       (*datalen)--;
     }
     /* Decrypt everything _except_ the MAC. */
     if (sccipher)
-        sccipher->decrypt(pktin.data + st->cipherblk,
-                          st->packetlen - st->cipherblk);
+       sccipher->decrypt(pktin.data + st->cipherblk,
+                         st->packetlen - st->cipherblk);
 
 #ifdef DUMP_PACKETS
     debug(("Got packet len=%d pad=%d\n", st->len, st->pad));
@@ -671,11 +711,13 @@ next_packet:
     /*
      * Check the MAC.
      */
-    if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
+    if (scmac
+       && !scmac->verify(pktin.data, st->len + 4,
+                         st->incoming_sequence)) {
        bombout(("Incorrect MAC received on packet"));
-        crReturn(0);
+       crReturn(0);
     }
-    st->incoming_sequence++;               /* whether or not we MACed */
+    st->incoming_sequence++;          /* whether or not we MACed */
 
     /*
      * Decompress packet payload.
@@ -683,20 +725,24 @@ next_packet:
     {
        unsigned char *newpayload;
        int newlen;
-       if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
+       if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
                                         &newpayload, &newlen)) {
-           if (pktin.maxlen < newlen+5) {
-               pktin.maxlen = newlen+5;
-               pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
-                             srealloc(pktin.data, pktin.maxlen+APIEXTRA));
+           if (pktin.maxlen < newlen + 5) {
+               pktin.maxlen = newlen + 5;
+               pktin.data =
+                   (pktin.data ==
+                    NULL ? smalloc(pktin.maxlen +
+                                   APIEXTRA) : srealloc(pktin.data,
+                                                        pktin.maxlen +
+                                                        APIEXTRA));
                if (!pktin.data)
                    fatalbox("Out of memory");
            }
            pktin.length = 5 + newlen;
-           memcpy(pktin.data+5, newpayload, newlen);
+           memcpy(pktin.data + 5, newpayload, newlen);
 #ifdef DUMP_PACKETS
            debug(("Post-decompression payload:\n"));
-           dmemdump(pktin.data+5, newlen);
+           dmemdump(pktin.data + 5, newlen);
 #endif
 
            sfree(newpayload);
@@ -707,64 +753,68 @@ next_packet:
     pktin.type = pktin.data[5];
 
     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
-        goto next_packet;              /* FIXME: print DEBUG message */
+       goto next_packet;              /* FIXME: print DEBUG message */
 
     if (pktin.type == SSH2_MSG_DISCONNECT) {
        /* log reason code in disconnect message */
        char buf[256];
-       int reason = GET_32BIT(pktin.data+6);
-       unsigned msglen = GET_32BIT(pktin.data+10);
+       int reason = GET_32BIT(pktin.data + 6);
+       unsigned msglen = GET_32BIT(pktin.data + 10);
        unsigned nowlen;
        if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
            sprintf(buf, "Received disconnect message (%s)",
                    ssh2_disconnect_reasons[reason]);
        } else {
-           sprintf(buf, "Received disconnect message (unknown type %d)", reason);
+           sprintf(buf, "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, pktin.data+14, msglen);
-       buf[nowlen+msglen] = '\0';
+       if (msglen > sizeof(buf) - nowlen - 1)
+           msglen = sizeof(buf) - nowlen - 1;
+       memcpy(buf + nowlen, pktin.data + 14, msglen);
+       buf[nowlen + msglen] = '\0';
        logevent(buf);
     }
 
     crFinish(0);
 }
 
-static void ssh1_pktout_size(int len) {
+static void ssh1_pktout_size(int len)
+{
     int pad, biglen;
 
     len += 5;                         /* type and CRC */
-    pad = 8 - (len%8);
+    pad = 8 - (len % 8);
     biglen = len + pad;
 
-    pktout.length = len-5;
+    pktout.length = len - 5;
     if (pktout.maxlen < biglen) {
        pktout.maxlen = biglen;
 #ifdef MSCRYPTOAPI
        /* Allocate enough buffer space for extra block
         * for MS CryptEncrypt() */
-       pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
-                      srealloc(pktout.data, biglen+12));
+       pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
+                      srealloc(pktout.data, biglen + 12));
 #else
-       pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
-                      srealloc(pktout.data, biglen+4));
+       pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
+                      srealloc(pktout.data, biglen + 4));
 #endif
        if (!pktout.data)
            fatalbox("Out of memory");
     }
-    pktout.body = pktout.data+4+pad+1;
+    pktout.body = pktout.data + 4 + pad + 1;
 }
 
-static void s_wrpkt_start(int type, int len) {
+static void s_wrpkt_start(int type, int len)
+{
     ssh1_pktout_size(len);
     pktout.type = type;
 }
 
-static int s_wrpkt_prepare(void) {
+static int s_wrpkt_prepare(void)
+{
     int pad, len, biglen, i;
     unsigned long crc;
 
@@ -772,57 +822,59 @@ static int s_wrpkt_prepare(void) {
 
 #ifdef DUMP_PACKETS
     debug(("Packet payload pre-compression:\n"));
-    dmemdump(pktout.body-1, pktout.length+1);
+    dmemdump(pktout.body - 1, pktout.length + 1);
 #endif
 
     if (ssh1_compressing) {
        unsigned char *compblk;
        int complen;
-       zlib_compress_block(pktout.body-1, pktout.length+1,
+       zlib_compress_block(pktout.body - 1, pktout.length + 1,
                            &compblk, &complen);
-       ssh1_pktout_size(complen-1);
-       memcpy(pktout.body-1, compblk, complen);
+       ssh1_pktout_size(complen - 1);
+       memcpy(pktout.body - 1, compblk, complen);
        sfree(compblk);
 #ifdef DUMP_PACKETS
        debug(("Packet payload post-compression:\n"));
-       dmemdump(pktout.body-1, pktout.length+1);
+       dmemdump(pktout.body - 1, pktout.length + 1);
 #endif
     }
 
     len = pktout.length + 5;          /* type and CRC */
-    pad = 8 - (len%8);
+    pad = 8 - (len % 8);
     biglen = len + pad;
 
-    for (i=0; i<pad; i++)
-       pktout.data[i+4] = random_byte();
-    crc = crc32(pktout.data+4, biglen-4);
-    PUT_32BIT(pktout.data+biglen, crc);
+    for (i = 0; i < pad; i++)
+       pktout.data[i + 4] = random_byte();
+    crc = crc32(pktout.data + 4, biglen - 4);
+    PUT_32BIT(pktout.data + biglen, crc);
     PUT_32BIT(pktout.data, len);
 
 #ifdef DUMP_PACKETS
-    debug(("Sending packet len=%d\n", biglen+4));
-    dmemdump(pktout.data, biglen+4);
+    debug(("Sending packet len=%d\n", biglen + 4));
+    dmemdump(pktout.data, biglen + 4);
 #endif
     if (cipher)
-       cipher->encrypt(pktout.data+4, biglen);
+       cipher->encrypt(pktout.data + 4, biglen);
 
-    return biglen+4;
+    return biglen + 4;
 }
 
-static void s_wrpkt(void) {
+static void s_wrpkt(void)
+{
     int len;
     len = s_wrpkt_prepare();
     sk_write(s, pktout.data, len);
 }
 
-static void s_wrpkt_defer(void) {
+static void s_wrpkt_defer(void)
+{
     int len;
     len = s_wrpkt_prepare();
     if (deferred_len + len > deferred_size) {
-        deferred_size = deferred_len + len + 128;
-        deferred_send_data = srealloc(deferred_send_data, deferred_size);
+       deferred_size = deferred_len + len + 128;
+       deferred_send_data = srealloc(deferred_send_data, deferred_size);
     }
-    memcpy(deferred_send_data+deferred_len, pktout.data, len);
+    memcpy(deferred_send_data + deferred_len, pktout.data, len);
     deferred_len += len;
 }
 
@@ -859,7 +911,7 @@ static void construct_packet(int pkttype, va_list ap1, va_list ap2)
            break;
          case PKT_BIGNUM:
            bn = va_arg(ap1, Bignum);
-            pktlen += ssh1_bignum_length(bn);
+           pktlen += ssh1_bignum_length(bn);
            break;
          default:
            assert(0);
@@ -896,13 +948,14 @@ static void construct_packet(int pkttype, va_list ap1, va_list ap2)
            break;
          case PKT_BIGNUM:
            bn = va_arg(ap2, Bignum);
-            p += ssh1_write_bignum(p, bn);
+           p += ssh1_write_bignum(p, bn);
            break;
        }
     }
 }
 
-static void send_packet(int pkttype, ...) {
+static void send_packet(int pkttype, ...)
+{
     va_list ap1, ap2;
     va_start(ap1, pkttype);
     va_start(ap2, pkttype);
@@ -910,7 +963,8 @@ static void send_packet(int pkttype, ...) {
     s_wrpkt();
 }
 
-static void defer_packet(int pkttype, ...) {
+static void defer_packet(int pkttype, ...)
+{
     va_list ap1, ap2;
     va_start(ap1, pkttype);
     va_start(ap2, pkttype);
@@ -918,18 +972,23 @@ static void defer_packet(int pkttype, ...) {
     s_wrpkt_defer();
 }
 
-static int ssh_versioncmp(char *a, char *b) {
+static int ssh_versioncmp(char *a, char *b)
+{
     char *ae, *be;
     unsigned long av, bv;
 
     av = strtoul(a, &ae, 10);
     bv = strtoul(b, &be, 10);
-    if (av != bv) return (av < bv ? -1 : +1);
-    if (*ae == '.') ae++;
-    if (*be == '.') be++;
+    if (av != bv)
+       return (av < bv ? -1 : +1);
+    if (*ae == '.')
+       ae++;
+    if (*be == '.')
+       be++;
     av = strtoul(ae, &ae, 10);
     bv = strtoul(be, &be, 10);
-    if (av != bv) return (av < bv ? -1 : +1);
+    if (av != bv)
+       return (av < bv ? -1 : +1);
     return 0;
 }
 
@@ -939,14 +998,16 @@ static int ssh_versioncmp(char *a, char *b) {
  * `uint32' into a SHA state.
  */
 #include <stdio.h>
-static void sha_string(SHA_State *s, void *str, int len) {
+static void sha_string(SHA_State * s, void *str, int len)
+{
     unsigned char lenblk[4];
     PUT_32BIT(lenblk, len);
     SHA_Bytes(s, lenblk, 4);
     SHA_Bytes(s, str, len);
 }
 
-static void sha_uint32(SHA_State *s, unsigned i) {
+static void sha_uint32(SHA_State * s, unsigned i)
+{
     unsigned char intblk[4];
     PUT_32BIT(intblk, i);
     SHA_Bytes(s, intblk, 4);
@@ -955,70 +1016,86 @@ static void sha_uint32(SHA_State *s, unsigned i) {
 /*
  * SSH2 packet construction functions.
  */
-static void ssh2_pkt_ensure(int length) {
+static void ssh2_pkt_ensure(int length)
+{
     if (pktout.maxlen < length) {
-        pktout.maxlen = length + 256;
-       pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
-                       srealloc(pktout.data, pktout.maxlen+APIEXTRA));
-        if (!pktout.data)
-            fatalbox("Out of memory");
+       pktout.maxlen = length + 256;
+       pktout.data =
+           (pktout.data ==
+            NULL ? smalloc(pktout.maxlen +
+                           APIEXTRA) : srealloc(pktout.data,
+                                                pktout.maxlen +
+                                                APIEXTRA));
+       if (!pktout.data)
+           fatalbox("Out of memory");
     }
 }
-static void ssh2_pkt_adddata(void *data, int len) {
+static void ssh2_pkt_adddata(void *data, int len)
+{
     pktout.length += len;
     ssh2_pkt_ensure(pktout.length);
-    memcpy(pktout.data+pktout.length-len, data, len);
+    memcpy(pktout.data + pktout.length - len, data, len);
 }
-static void ssh2_pkt_addbyte(unsigned char byte) {
+static void ssh2_pkt_addbyte(unsigned char byte)
+{
     ssh2_pkt_adddata(&byte, 1);
 }
-static void ssh2_pkt_init(int pkt_type) {
+static void ssh2_pkt_init(int pkt_type)
+{
     pktout.length = 5;
-    ssh2_pkt_addbyte((unsigned char)pkt_type);
+    ssh2_pkt_addbyte((unsigned char) pkt_type);
 }
-static void ssh2_pkt_addbool(unsigned char value) {
+static void ssh2_pkt_addbool(unsigned char value)
+{
     ssh2_pkt_adddata(&value, 1);
 }
-static void ssh2_pkt_adduint32(unsigned long value) {
+static void ssh2_pkt_adduint32(unsigned long value)
+{
     unsigned char x[4];
     PUT_32BIT(x, value);
     ssh2_pkt_adddata(x, 4);
 }
-static void ssh2_pkt_addstring_start(void) {
+static void ssh2_pkt_addstring_start(void)
+{
     ssh2_pkt_adduint32(0);
     pktout.savedpos = pktout.length;
 }
-static void ssh2_pkt_addstring_str(char *data) {
+static void ssh2_pkt_addstring_str(char *data)
+{
     ssh2_pkt_adddata(data, strlen(data));
     PUT_32BIT(pktout.data + pktout.savedpos - 4,
-              pktout.length - pktout.savedpos);
+             pktout.length - pktout.savedpos);
 }
-static void ssh2_pkt_addstring_data(char *data, int len) {
+static void ssh2_pkt_addstring_data(char *data, int len)
+{
     ssh2_pkt_adddata(data, len);
     PUT_32BIT(pktout.data + pktout.savedpos - 4,
-              pktout.length - pktout.savedpos);
+             pktout.length - pktout.savedpos);
 }
-static void ssh2_pkt_addstring(char *data) {
+static void ssh2_pkt_addstring(char *data)
+{
     ssh2_pkt_addstring_start();
     ssh2_pkt_addstring_str(data);
 }
-static char *ssh2_mpint_fmt(Bignum b, int *len) {
+static char *ssh2_mpint_fmt(Bignum b, int *len)
+{
     unsigned char *p;
-    int i, n = (bignum_bitcount(b)+7)/8;
+    int i, n = (bignum_bitcount(b) + 7) / 8;
     p = smalloc(n + 1);
     if (!p)
-        fatalbox("out of memory");
+       fatalbox("out of memory");
     p[0] = 0;
     for (i = 1; i <= n; i++)
-        p[i] = bignum_byte(b, n-i);
+       p[i] = bignum_byte(b, n - i);
     i = 0;
-    while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
-        i++;
-    memmove(p, p+i, n+1-i);
-    *len = n+1-i;
+    while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
+       i++;
+    memmove(p, p + i, n + 1 - i);
+    *len = n + 1 - i;
     return p;
 }
-static void ssh2_pkt_addmp(Bignum b) {
+static void ssh2_pkt_addmp(Bignum b)
+{
     unsigned char *p;
     int len;
     p = ssh2_mpint_fmt(b, &len);
@@ -1032,7 +1109,8 @@ static void ssh2_pkt_addmp(Bignum b) {
  * put the MAC on it. Final packet, ready to be sent, is stored in
  * pktout.data. Total length is returned.
  */
-static int ssh2_pkt_construct(void) {
+static int ssh2_pkt_construct(void)
+{
     int cipherblk, maclen, padding, i;
     static unsigned long outgoing_sequence = 0;
 
@@ -1041,12 +1119,12 @@ static int ssh2_pkt_construct(void) {
      */
 #ifdef DUMP_PACKETS
     debug(("Pre-compression payload:\n"));
-    dmemdump(pktout.data+5, pktout.length-5);
+    dmemdump(pktout.data + 5, pktout.length - 5);
 #endif
     {
        unsigned char *newpayload;
        int newlen;
-       if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
+       if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
                                       &newpayload, &newlen)) {
            pktout.length = 5;
            ssh2_pkt_adddata(newpayload, newlen);
@@ -1058,28 +1136,29 @@ static int ssh2_pkt_construct(void) {
      * Add padding. At least four bytes, and must also bring total
      * length (minus MAC) up to a multiple of the block size.
      */
-    cipherblk = cscipher ? cscipher->blksize : 8;   /* block size */
-    cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
+    cipherblk = cscipher ? cscipher->blksize : 8;      /* block size */
+    cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
     padding = 4;
-    padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
+    padding +=
+       (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
     maclen = csmac ? csmac->len : 0;
     ssh2_pkt_ensure(pktout.length + padding + maclen);
     pktout.data[4] = padding;
     for (i = 0; i < padding; i++)
-        pktout.data[pktout.length + i] = random_byte();
+       pktout.data[pktout.length + i] = random_byte();
     PUT_32BIT(pktout.data, pktout.length + padding - 4);
     if (csmac)
-        csmac->generate(pktout.data, pktout.length + padding,
-                        outgoing_sequence);
-    outgoing_sequence++;               /* whether or not we MACed */
+       csmac->generate(pktout.data, pktout.length + padding,
+                       outgoing_sequence);
+    outgoing_sequence++;              /* whether or not we MACed */
 
 #ifdef DUMP_PACKETS
-    debug(("Sending packet len=%d\n", pktout.length+padding));
-    dmemdump(pktout.data, pktout.length+padding);
+    debug(("Sending packet len=%d\n", pktout.length + padding));
+    dmemdump(pktout.data, pktout.length + padding);
 #endif
 
     if (cscipher)
-        cscipher->encrypt(pktout.data, pktout.length + padding);
+       cscipher->encrypt(pktout.data, pktout.length + padding);
 
     /* Ready-to-send packet starts at pktout.data. We return length. */
     return pktout.length + padding + maclen;
@@ -1088,7 +1167,8 @@ static int ssh2_pkt_construct(void) {
 /*
  * Construct and send an SSH2 packet immediately.
  */
-static void ssh2_pkt_send(void) {
+static void ssh2_pkt_send(void)
+{
     int len = ssh2_pkt_construct();
     sk_write(s, pktout.data, len);
 }
@@ -1104,13 +1184,14 @@ static void ssh2_pkt_send(void) {
  * NOT be used as an m4-style `defer' allowing packets to be
  * constructed in one order and sent in another.
  */
-static void ssh2_pkt_defer(void) {
+static void ssh2_pkt_defer(void)
+{
     int len = ssh2_pkt_construct();
     if (deferred_len + len > deferred_size) {
-        deferred_size = deferred_len + len + 128;
-        deferred_send_data = srealloc(deferred_send_data, deferred_size);
+       deferred_size = deferred_len + len + 128;
+       deferred_send_data = srealloc(deferred_send_data, deferred_size);
     }
-    memcpy(deferred_send_data+deferred_len, pktout.data, len);
+    memcpy(deferred_send_data + deferred_len, pktout.data, len);
     deferred_len += len;
 }
 
@@ -1118,7 +1199,8 @@ static void ssh2_pkt_defer(void) {
  * Send the whole deferred data block constructed by
  * ssh2_pkt_defer() or SSH1's defer_packet().
  */
-static void ssh_pkt_defersend(void) {
+static void ssh_pkt_defersend(void)
+{
     sk_write(s, deferred_send_data, deferred_len);
     deferred_len = deferred_size = 0;
     sfree(deferred_send_data);
@@ -1126,19 +1208,21 @@ static void ssh_pkt_defersend(void) {
 }
 
 #if 0
-void bndebug(char *string, Bignum b) {
+void bndebug(char *string, Bignum b)
+{
     unsigned char *p;
     int i, len;
     p = ssh2_mpint_fmt(b, &len);
     debug(("%s", string));
     for (i = 0; i < len; i++)
-        debug((" %02x", p[i]));
+       debug((" %02x", p[i]));
     debug(("\n"));
     sfree(p);
 }
 #endif
 
-static void sha_mpint(SHA_State *s, Bignum b) {
+static void sha_mpint(SHA_State * s, Bignum b)
+{
     unsigned char *p;
     int len;
     p = ssh2_mpint_fmt(b, &len);
@@ -1149,44 +1233,48 @@ static void sha_mpint(SHA_State *s, Bignum b) {
 /*
  * SSH2 packet decode functions.
  */
-static unsigned long ssh2_pkt_getuint32(void) {
+static unsigned long ssh2_pkt_getuint32(void)
+{
     unsigned long value;
     if (pktin.length - pktin.savedpos < 4)
-        return 0;                      /* arrgh, no way to decline (FIXME?) */
-    value = GET_32BIT(pktin.data+pktin.savedpos);
+       return 0;                      /* arrgh, no way to decline (FIXME?) */
+    value = GET_32BIT(pktin.data + pktin.savedpos);
     pktin.savedpos += 4;
     return value;
 }
-static int ssh2_pkt_getbool(void) {
+static int ssh2_pkt_getbool(void)
+{
     unsigned long value;
     if (pktin.length - pktin.savedpos < 1)
-        return 0;                      /* arrgh, no way to decline (FIXME?) */
+       return 0;                      /* arrgh, no way to decline (FIXME?) */
     value = pktin.data[pktin.savedpos] != 0;
     pktin.savedpos++;
     return value;
 }
-static void ssh2_pkt_getstring(char **p, int *length) {
+static void ssh2_pkt_getstring(char **p, int *length)
+{
     *p = NULL;
     if (pktin.length - pktin.savedpos < 4)
-        return;
-    *length = GET_32BIT(pktin.data+pktin.savedpos);
+       return;
+    *length = GET_32BIT(pktin.data + pktin.savedpos);
     pktin.savedpos += 4;
     if (pktin.length - pktin.savedpos < *length)
-        return;
-    *p = pktin.data+pktin.savedpos;
+       return;
+    *p = pktin.data + pktin.savedpos;
     pktin.savedpos += *length;
 }
-static Bignum ssh2_pkt_getmp(void) {
+static Bignum ssh2_pkt_getmp(void)
+{
     char *p;
     int length;
     Bignum b;
 
     ssh2_pkt_getstring(&p, &length);
     if (!p)
-        return NULL;
+       return NULL;
     if (p[0] & 0x80) {
-        bombout(("internal error: Can't handle negative mpints"));
-        return NULL;
+       bombout(("internal error: Can't handle negative mpints"));
+       return NULL;
     }
     b = bignum_from_bytes(p, length);
     return b;
@@ -1196,40 +1284,44 @@ static Bignum ssh2_pkt_getmp(void) {
  * Examine the remote side's version string and compare it against
  * a list of known buggy implementations.
  */
-static void ssh_detect_bugs(char *vstring) {
-    char *imp;                         /* pointer to implementation part */
+static void ssh_detect_bugs(char *vstring)
+{
+    char *imp;                        /* pointer to implementation part */
     imp = vstring;
     imp += strcspn(imp, "-");
-    if (*imp) imp++;
+    if (*imp)
+       imp++;
     imp += strcspn(imp, "-");
-    if (*imp) imp++;
+    if (*imp)
+       imp++;
 
     ssh_remote_bugs = 0;
 
     if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
-        !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
-        !strcmp(imp, "1.2.22")) {
-        /*
-         * These versions don't support SSH1_MSG_IGNORE, so we have
-         * to use a different defence against password length
-         * sniffing.
-         */
-        ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
-        logevent("We believe remote version has SSH1 ignore bug");
+       !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
+       !strcmp(imp, "1.2.22")) {
+       /*
+        * These versions don't support SSH1_MSG_IGNORE, so we have
+        * to use a different defence against password length
+        * sniffing.
+        */
+       ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
+       logevent("We believe remote version has SSH1 ignore bug");
     }
 
     if (!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)) {
-        /*
-         * These versions have the HMAC bug.
-         */
-        ssh_remote_bugs |= BUG_SSH2_HMAC;
-        logevent("We believe remote version has SSH2 HMAC bug");
+       !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
+       !strncmp(imp, "2.1 ", 4)) {
+       /*
+        * These versions have the HMAC bug.
+        */
+       ssh_remote_bugs |= BUG_SSH2_HMAC;
+       logevent("We believe remote version has SSH2 HMAC bug");
     }
 }
 
-static int do_ssh_init(unsigned char c) {
+static int do_ssh_init(unsigned char c)
+{
     static char vslen;
     static char version[10];
     static char *vstring;
@@ -1245,10 +1337,14 @@ static int do_ssh_init(unsigned char c) {
        static const int transS[] = { 1, 2, 2, 1 };
        static const int transH[] = { 0, 0, 3, 0 };
        static const int transminus[] = { 0, 0, 0, -1 };
-       if (c == 'S') i = transS[i];
-       else if (c == 'H') i = transH[i];
-       else if (c == '-') i = transminus[i];
-       else i = 0;
+       if (c == 'S')
+           i = transS[i];
+       else if (c == 'H')
+           i = transH[i];
+       else if (c == '-')
+           i = transminus[i];
+       else
+           i = 0;
        if (i < 0)
            break;
        crReturn(1);                   /* get another character */
@@ -1261,19 +1357,18 @@ static int do_ssh_init(unsigned char c) {
     i = 0;
     while (1) {
        crReturn(1);                   /* get another char */
-       if (vslen >= vstrsize-1) {
-            vstrsize += 16;
-            vstring = srealloc(vstring, vstrsize);
-        }
-        vstring[vslen++] = c;
+       if (vslen >= vstrsize - 1) {
+           vstrsize += 16;
+           vstring = srealloc(vstring, vstrsize);
+       }
+       vstring[vslen++] = c;
        if (i >= 0) {
            if (c == '-') {
                version[i] = '\0';
                i = -1;
-           } else if (i < sizeof(version)-1)
+           } else if (i < sizeof(version) - 1)
                version[i++] = c;
-       }
-       else if (c == '\n')
+       } else if (c == '\n')
            break;
     }
 
@@ -1293,41 +1388,41 @@ static int do_ssh_init(unsigned char c) {
      * or v2 protocol. Choice is based on cfg.sshprot.
      */
     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
-        /*
-         * This is a v2 server. Begin v2 protocol.
-         */
-        char verstring[80], vlog[100];
-        sprintf(verstring, "SSH-2.0-%s", sshver);
-        SHA_Init(&exhashbase);
-        /*
-         * Hash our version string and their version string.
-         */
-        sha_string(&exhashbase, verstring, strlen(verstring));
-        sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
-        sprintf(vlog, "We claim version: %s", verstring);
-        logevent(vlog);
-        strcat(verstring, "\n");
-        logevent("Using SSH protocol version 2");
-        sk_write(s, verstring, strlen(verstring));
-        ssh_protocol = ssh2_protocol;
-        ssh_version = 2;
-        s_rdpkt = ssh2_rdpkt;
+       /*
+        * This is a v2 server. Begin v2 protocol.
+        */
+       char verstring[80], vlog[100];
+       sprintf(verstring, "SSH-2.0-%s", sshver);
+       SHA_Init(&exhashbase);
+       /*
+        * Hash our version string and their version string.
+        */
+       sha_string(&exhashbase, verstring, strlen(verstring));
+       sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
+       sprintf(vlog, "We claim version: %s", verstring);
+       logevent(vlog);
+       strcat(verstring, "\n");
+       logevent("Using SSH protocol version 2");
+       sk_write(s, verstring, strlen(verstring));
+       ssh_protocol = ssh2_protocol;
+       ssh_version = 2;
+       s_rdpkt = ssh2_rdpkt;
     } else {
-        /*
-         * This is a v1 server. Begin v1 protocol.
-         */
-        char verstring[80], vlog[100];
-        sprintf(verstring, "SSH-%s-%s",
-                (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
-                sshver);
-        sprintf(vlog, "We claim version: %s", verstring);
-        logevent(vlog);
-        strcat(verstring, "\n");
-        logevent("Using SSH protocol version 1");
-        sk_write(s, verstring, strlen(verstring));
-        ssh_protocol = ssh1_protocol;
-        ssh_version = 1;
-        s_rdpkt = ssh1_rdpkt;
+       /*
+        * This is a v1 server. Begin v1 protocol.
+        */
+       char verstring[80], vlog[100];
+       sprintf(verstring, "SSH-%s-%s",
+               (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
+               sshver);
+       sprintf(vlog, "We claim version: %s", verstring);
+       logevent(vlog);
+       strcat(verstring, "\n");
+       logevent("Using SSH protocol version 1");
+       sk_write(s, verstring, strlen(verstring));
+       ssh_protocol = ssh1_protocol;
+       ssh_version = 1;
+       s_rdpkt = ssh1_rdpkt;
     }
     ssh_state = SSH_STATE_BEFORE_SIZE;
 
@@ -1351,7 +1446,8 @@ static void ssh_gotdata(unsigned char *data, int datalen)
        if (datalen == 0)
            crReturnV;                 /* more data please */
        ret = do_ssh_init(*data);
-       data++; datalen--;
+       data++;
+       datalen--;
        if (ret == 0)
            break;
     }
@@ -1366,7 +1462,7 @@ static void ssh_gotdata(unsigned char *data, int datalen)
        crReturnV;
     while (1) {
        while (datalen > 0) {
-           if ( s_rdpkt(&data, &datalen) == 0 ) {
+           if (s_rdpkt(&data, &datalen) == 0) {
                ssh_protocol(NULL, 0, 1);
                if (ssh_state == SSH_STATE_CLOSED) {
                    return;
@@ -1378,27 +1474,30 @@ static void ssh_gotdata(unsigned char *data, int datalen)
     crFinishV;
 }
 
-static int ssh_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
+static int ssh_closing(Plug plug, char *error_msg, int error_code,
+                      int calling_back)
+{
     ssh_state = SSH_STATE_CLOSED;
     sk_close(s);
     s = NULL;
     if (error_msg) {
-        /* A socket error has occurred. */
-        connection_fatal (error_msg);
+       /* A socket error has occurred. */
+       connection_fatal(error_msg);
     } else {
        /* Otherwise, the remote side closed the connection normally. */
     }
     return 0;
 }
 
-static int ssh_receive(Plug plug, int urgent, char *data, int len) {
-    ssh_gotdata (data, len);
+static int ssh_receive(Plug plug, int urgent, char *data, int len)
+{
+    ssh_gotdata(data, len);
     if (ssh_state == SSH_STATE_CLOSED) {
-        if (s) {
-            sk_close(s);
-            s = NULL;
-        }
-        return 0;
+       if (s) {
+           sk_close(s);
+           s = NULL;
+       }
+       return 0;
     }
     return 1;
 }
@@ -1422,7 +1521,7 @@ static char *connect_to_host(char *host, int port, char **realhost)
     int FWport;
 #endif
 
-    savedhost = smalloc(1+strlen(host));
+    savedhost = smalloc(1 + strlen(host));
     if (!savedhost)
        fatalbox("Out of memory");
     strcpy(savedhost, host);
@@ -1442,7 +1541,7 @@ static char *connect_to_host(char *host, int port, char **realhost)
      * Try to find host.
      */
     addr = sk_namelookup(host, realhost);
-    if ( (err = sk_addr_error(addr)) )
+    if ((err = sk_addr_error(addr)))
        return err;
 
 #ifdef FWHACK
@@ -1453,7 +1552,7 @@ static char *connect_to_host(char *host, int port, char **realhost)
      * Open socket.
      */
     s = sk_new(addr, port, 0, 1, &fn_table_ptr);
-    if ( (err = sk_socket_error(s)) )
+    if ((err = sk_socket_error(s)))
        return err;
 
 #ifdef FWHACK
@@ -1487,19 +1586,20 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
 
     crBegin;
 
-    if (!ispkt) crWaitUntil(ispkt);
+    if (!ispkt)
+       crWaitUntil(ispkt);
 
     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
        bombout(("Public key packet not received"));
-        crReturn(0);
+       crReturn(0);
     }
 
     logevent("Received public keys");
 
     memcpy(cookie, pktin.body, 8);
 
-    i = makekey(pktin.body+8, &servkey, &keystr1, 0);
-    j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
+    i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
+    j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
 
     /*
      * Log the host key fingerprint.
@@ -1508,17 +1608,18 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
        char logmsg[80];
        logevent("Host key fingerprint is:");
        strcpy(logmsg, "      ");
-        hostkey.comment = NULL;
-        rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
-                        &hostkey);
+       hostkey.comment = NULL;
+       rsa_fingerprint(logmsg + strlen(logmsg),
+                       sizeof(logmsg) - strlen(logmsg), &hostkey);
        logevent(logmsg);
     }
 
-    ssh1_remote_protoflags = GET_32BIT(pktin.body+8+i+j);
-    supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
-    supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
+    ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
+    supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
+    supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
 
-    ssh1_local_protoflags = ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
+    ssh1_local_protoflags =
+       ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
     ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
 
     MD5Init(&md5c);
@@ -1527,7 +1628,7 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
     MD5Update(&md5c, pktin.body, 8);
     MD5Final(session_id, &md5c);
 
-    for (i=0; i<32; i++)
+    for (i = 0; i < 32; i++)
        session_key[i] = random_byte();
 
     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
@@ -1540,21 +1641,22 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
      * Verify the host key.
      */
     {
-        /*
-         * First format the key into a string.
-         */
-        int len = rsastr_len(&hostkey);
-        char fingerprint[100];
-        char *keystr = smalloc(len);
-        if (!keystr)
-            fatalbox("Out of memory");
-        rsastr_fmt(keystr, &hostkey);
-        rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
-        verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
-        sfree(keystr);
-    }
-
-    for (i=0; i<32; i++) {
+       /*
+        * First format the key into a string.
+        */
+       int len = rsastr_len(&hostkey);
+       char fingerprint[100];
+       char *keystr = smalloc(len);
+       if (!keystr)
+           fatalbox("Out of memory");
+       rsastr_fmt(keystr, &hostkey);
+       rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
+       verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
+                           fingerprint);
+       sfree(keystr);
+    }
+
+    for (i = 0; i < 32; i++) {
        rsabuf[i] = session_key[i];
        if (i < 16)
            rsabuf[i] ^= session_id[i];
@@ -1571,16 +1673,23 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
     logevent("Encrypted session key");
 
     switch (cfg.cipher) {
-      case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
-      case CIPHER_DES:      cipher_type = SSH_CIPHER_DES;      break;
-      case CIPHER_3DES:     cipher_type = SSH_CIPHER_3DES;     break;
+      case CIPHER_BLOWFISH:
+       cipher_type = SSH_CIPHER_BLOWFISH;
+       break;
+      case CIPHER_DES:
+       cipher_type = SSH_CIPHER_DES;
+       break;
+      case CIPHER_3DES:
+       cipher_type = SSH_CIPHER_3DES;
+       break;
       case CIPHER_AES:
-        c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
-        cipher_type = SSH_CIPHER_3DES;
-        break;
+       c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
+       cipher_type = SSH_CIPHER_3DES;
+       break;
     }
     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
-       c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
+       c_write_str
+           ("Selected cipher not supported, falling back to 3DES\r\n");
        cipher_type = SSH_CIPHER_3DES;
        if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
            bombout(("Server violates SSH 1 protocol by "
@@ -1589,33 +1698,37 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
        }
     }
     switch (cipher_type) {
-      case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
-      case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
-      case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
+      case SSH_CIPHER_3DES:
+       logevent("Using 3DES encryption");
+       break;
+      case SSH_CIPHER_DES:
+       logevent("Using single-DES encryption");
+       break;
+      case SSH_CIPHER_BLOWFISH:
+       logevent("Using Blowfish encryption");
+       break;
     }
 
     send_packet(SSH1_CMSG_SESSION_KEY,
-                PKT_CHAR, cipher_type,
-                PKT_DATA, cookie, 8,
-                PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
-                PKT_DATA, rsabuf, len,
-                PKT_INT, ssh1_local_protoflags,
-                PKT_END);
+               PKT_CHAR, cipher_type,
+               PKT_DATA, cookie, 8,
+               PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
+               PKT_DATA, rsabuf, len,
+               PKT_INT, ssh1_local_protoflags, PKT_END);
 
     logevent("Trying to enable encryption...");
 
     sfree(rsabuf);
 
     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
-             cipher_type == SSH_CIPHER_DES ? &ssh_des :
-             &ssh_3des;
+       cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
     cipher->sesskey(session_key);
 
     crWaitUntil(ispkt);
 
     if (pktin.type != SSH1_SMSG_SUCCESS) {
        bombout(("Encryption not successfully enabled"));
-        crReturn(0);
+       crReturn(0);
     }
 
     logevent("Successfully started encryption");
@@ -1625,69 +1738,74 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
        static int pos = 0;
        static char c;
        if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
-            if (ssh_get_line) {
-                if (!ssh_get_line("login as: ",
-                                  username, sizeof(username), FALSE)) {
-                    /*
-                     * get_line failed to get a username.
-                     * Terminate.
-                     */
-                    logevent("No username provided. Abandoning session.");
-                    ssh_state = SSH_STATE_CLOSED;
-                    crReturn(1);
-                }
-            } else {
-                c_write_str("login as: ");
-                ssh_send_ok = 1;
-                while (pos >= 0) {
-                    crWaitUntil(!ispkt);
-                    while (inlen--) switch (c = *in++) {
-                      case 10: case 13:
-                        username[pos] = 0;
-                        pos = -1;
-                        break;
-                      case 8: case 127:
-                        if (pos > 0) {
-                            c_write_str("\b \b");
-                            pos--;
-                        }
-                        break;
-                      case 21: case 27:
-                        while (pos > 0) {
-                            c_write_str("\b \b");
-                            pos--;
-                        }
-                        break;
-                      case 3: case 4:
-                        random_save_seed();
-                        exit(0);
-                        break;
-                      default:
-                        if (((c >= ' ' && c <= '~') ||
-                             ((unsigned char)c >= 160)) && pos < 40) {
-                            username[pos++] = c;
-                            c_write(&c, 1);
-                        }
-                        break;
-                    }
-                }
-                c_write_str("\r\n");
-                username[strcspn(username, "\n\r")] = '\0';
-            }
-        } else {
+           if (ssh_get_line) {
+               if (!ssh_get_line("login as: ",
+                                 username, sizeof(username), FALSE)) {
+                   /*
+                    * get_line failed to get a username.
+                    * Terminate.
+                    */
+                   logevent("No username provided. Abandoning session.");
+                   ssh_state = SSH_STATE_CLOSED;
+                   crReturn(1);
+               }
+           } else {
+               c_write_str("login as: ");
+               ssh_send_ok = 1;
+               while (pos >= 0) {
+                   crWaitUntil(!ispkt);
+                   while (inlen--)
+                       switch (c = *in++) {
+                         case 10:
+                         case 13:
+                           username[pos] = 0;
+                           pos = -1;
+                           break;
+                         case 8:
+                         case 127:
+                           if (pos > 0) {
+                               c_write_str("\b \b");
+                               pos--;
+                           }
+                           break;
+                         case 21:
+                         case 27:
+                           while (pos > 0) {
+                               c_write_str("\b \b");
+                               pos--;
+                           }
+                           break;
+                         case 3:
+                         case 4:
+                           random_save_seed();
+                           exit(0);
+                           break;
+                         default:
+                           if (((c >= ' ' && c <= '~') ||
+                                ((unsigned char) c >= 160)) && pos < 40) {
+                               username[pos++] = c;
+                               c_write(&c, 1);
+                           }
+                           break;
+                       }
+               }
+               c_write_str("\r\n");
+               username[strcspn(username, "\n\r")] = '\0';
+           }
+       } else {
            strncpy(username, cfg.username, 99);
            username[99] = '\0';
        }
 
        send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
        {
-           char userlog[22+sizeof(username)];
+           char userlog[22 + sizeof(username)];
            sprintf(userlog, "Sent username \"%s\"", username);
            logevent(userlog);
-            if (flags & FLAG_INTERACTIVE &&
-                (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
+           if (flags & FLAG_INTERACTIVE &&
+               (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
                strcat(userlog, "\r\n");
-                c_write_str(userlog);
+               c_write_str(userlog);
            }
        }
     }
@@ -1701,396 +1819,420 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
        static char prompt[200];
        static int pos;
        static char c;
-        static int pwpkt_type;
-        /*
-         * Show password prompt, having first obtained it via a TIS
-         * or CryptoCard exchange if we're doing TIS or CryptoCard
-         * authentication.
-         */
-        pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
-        if (agent_exists()) {
-            /*
-             * Attempt RSA authentication using Pageant.
-             */
-            static unsigned char request[5], *response, *p;
-            static int responselen;
-            static int i, nkeys;
-            static int authed = FALSE;
-            void *r;
-
-            logevent("Pageant is running. Requesting keys.");
-
-            /* Request the keys held by the agent. */
-            PUT_32BIT(request, 1);
-            request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
-            agent_query(request, 5, &r, &responselen);
-            response = (unsigned char *)r;
-            if (response && responselen >= 5 &&
-                response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
-                p = response + 5;
-                nkeys = GET_32BIT(p); p += 4;
-                { char buf[64]; sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
-                    logevent(buf); }
-                for (i = 0; i < nkeys; i++) {
-                    static struct RSAKey key;
-                    static Bignum challenge;
-                    static char *commentp;
-                    static int commentlen;
-
-                    { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
-                        logevent(buf); }
-                    p += 4;
-                    p += ssh1_read_bignum(p, &key.exponent);
-                    p += ssh1_read_bignum(p, &key.modulus);
-                    commentlen = GET_32BIT(p); p += 4;
-                    commentp = p; p += commentlen;
-                    send_packet(SSH1_CMSG_AUTH_RSA,
-                                PKT_BIGNUM, key.modulus, PKT_END);
-                    crWaitUntil(ispkt);
-                    if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
-                        logevent("Key refused");
-                        continue;
-                    }
-                    logevent("Received RSA challenge");
-                    ssh1_read_bignum(pktin.body, &challenge);
-                    {
-                        char *agentreq, *q, *ret;
-                        int len, retlen;
-                        len = 1 + 4;   /* message type, bit count */
-                        len += ssh1_bignum_length(key.exponent);
-                        len += ssh1_bignum_length(key.modulus);
-                        len += ssh1_bignum_length(challenge);
-                        len += 16;     /* session id */
-                        len += 4;      /* response format */
-                        agentreq = smalloc(4 + len);
-                        PUT_32BIT(agentreq, len);
-                        q = agentreq + 4;
-                        *q++ = SSH1_AGENTC_RSA_CHALLENGE;
-                        PUT_32BIT(q, bignum_bitcount(key.modulus));
-                        q += 4;
-                        q += ssh1_write_bignum(q, key.exponent);
-                        q += ssh1_write_bignum(q, key.modulus);
-                        q += ssh1_write_bignum(q, challenge);
-                        memcpy(q, session_id, 16); q += 16;
-                        PUT_32BIT(q, 1);   /* response format */
-                        agent_query(agentreq, len+4, &ret, &retlen);
-                        sfree(agentreq);
-                        if (ret) {
-                            if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
-                                logevent("Sending Pageant's response");
-                                send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
-                                            PKT_DATA, ret+5, 16, PKT_END);
-                                sfree(ret);
-                                crWaitUntil(ispkt);
-                                if (pktin.type == SSH1_SMSG_SUCCESS) {
-                                    logevent("Pageant's response accepted");
-                                    if (flags & FLAG_VERBOSE) {
-                                        c_write_str("Authenticated using RSA key \"");
-                                        c_write(commentp, commentlen);
-                                        c_write_str("\" from agent\r\n");
-                                    }
-                                    authed = TRUE;
-                                } else
-                                    logevent("Pageant's response not accepted");
-                            } else {
-                                logevent("Pageant failed to answer challenge");
-                                sfree(ret);
-                            }
-                        } else {
-                            logevent("No reply received from Pageant");
-                        }
-                    }
-                    freebn(key.exponent);
-                    freebn(key.modulus);
-                    freebn(challenge);
-                    if (authed)
-                        break;
-                }
-            }
-            if (authed)
-                break;
-        }
-        if (*cfg.keyfile && !tried_publickey)
-            pwpkt_type = SSH1_CMSG_AUTH_RSA;
-
-        if (pktin.type == SSH1_SMSG_FAILURE &&
-            cfg.try_tis_auth &&
-            (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
-            pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
-            logevent("Requested TIS authentication");
-            send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
-            crWaitUntil(ispkt);
-            if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
-                logevent("TIS authentication declined");
-                if (flags & FLAG_INTERACTIVE)
-                    c_write_str("TIS authentication refused.\r\n");
-            } else {
-                int challengelen = ((pktin.body[0] << 24) |
-                                    (pktin.body[1] << 16) |
-                                    (pktin.body[2] << 8) |
-                                    (pktin.body[3]));
-                logevent("Received TIS challenge");
-                if (challengelen > sizeof(prompt)-1)
-                    challengelen = sizeof(prompt)-1;   /* prevent overrun */
-                memcpy(prompt, pktin.body+4, challengelen);
-                prompt[challengelen] = '\0';
-            }
-        }
-        if (pktin.type == SSH1_SMSG_FAILURE &&
-            cfg.try_tis_auth &&
-            (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
-            pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
-            logevent("Requested CryptoCard authentication");
-            send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
-            crWaitUntil(ispkt);
-            if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
-                logevent("CryptoCard authentication declined");
-                c_write_str("CryptoCard authentication refused.\r\n");
-            } else {
-                int challengelen = ((pktin.body[0] << 24) |
-                                    (pktin.body[1] << 16) |
-                                    (pktin.body[2] << 8) |
-                                    (pktin.body[3]));
-                logevent("Received CryptoCard challenge");
-                if (challengelen > sizeof(prompt)-1)
-                    challengelen = sizeof(prompt)-1;   /* prevent overrun */
-                memcpy(prompt, pktin.body+4, challengelen);
-                strncpy(prompt + challengelen, "\r\nResponse : ",
-                        sizeof(prompt)-challengelen);
-                prompt[sizeof(prompt)-1] = '\0';
-            }
-        }
-        if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
-            sprintf(prompt, "%.90s@%.90s's password: ",
-                    username, savedhost);
-        }
-        if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
-            char *comment = NULL;
-            if (flags & FLAG_VERBOSE)
-                c_write_str("Trying public key authentication.\r\n");
-            if (!rsakey_encrypted(cfg.keyfile, &comment)) {
-                if (flags & FLAG_VERBOSE)
-                    c_write_str("No passphrase required.\r\n");
-                goto tryauth;
-            }
-            sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
-            sfree(comment);
-        }
+       static int pwpkt_type;
+       /*
+        * Show password prompt, having first obtained it via a TIS
+        * or CryptoCard exchange if we're doing TIS or CryptoCard
+        * authentication.
+        */
+       pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
+       if (agent_exists()) {
+           /*
+            * Attempt RSA authentication using Pageant.
+            */
+           static unsigned char request[5], *response, *p;
+           static int responselen;
+           static int i, nkeys;
+           static int authed = FALSE;
+           void *r;
+
+           logevent("Pageant is running. Requesting keys.");
+
+           /* Request the keys held by the agent. */
+           PUT_32BIT(request, 1);
+           request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
+           agent_query(request, 5, &r, &responselen);
+           response = (unsigned char *) r;
+           if (response && responselen >= 5 &&
+               response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
+               p = response + 5;
+               nkeys = GET_32BIT(p);
+               p += 4;
+               {
+                   char buf[64];
+                   sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
+                   logevent(buf);
+               }
+               for (i = 0; i < nkeys; i++) {
+                   static struct RSAKey key;
+                   static Bignum challenge;
+                   static char *commentp;
+                   static int commentlen;
+
+                   {
+                       char buf[64];
+                       sprintf(buf, "Trying Pageant key #%d", i);
+                       logevent(buf);
+                   }
+                   p += 4;
+                   p += ssh1_read_bignum(p, &key.exponent);
+                   p += ssh1_read_bignum(p, &key.modulus);
+                   commentlen = GET_32BIT(p);
+                   p += 4;
+                   commentp = p;
+                   p += commentlen;
+                   send_packet(SSH1_CMSG_AUTH_RSA,
+                               PKT_BIGNUM, key.modulus, PKT_END);
+                   crWaitUntil(ispkt);
+                   if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+                       logevent("Key refused");
+                       continue;
+                   }
+                   logevent("Received RSA challenge");
+                   ssh1_read_bignum(pktin.body, &challenge);
+                   {
+                       char *agentreq, *q, *ret;
+                       int len, retlen;
+                       len = 1 + 4;   /* message type, bit count */
+                       len += ssh1_bignum_length(key.exponent);
+                       len += ssh1_bignum_length(key.modulus);
+                       len += ssh1_bignum_length(challenge);
+                       len += 16;     /* session id */
+                       len += 4;      /* response format */
+                       agentreq = smalloc(4 + len);
+                       PUT_32BIT(agentreq, len);
+                       q = agentreq + 4;
+                       *q++ = SSH1_AGENTC_RSA_CHALLENGE;
+                       PUT_32BIT(q, bignum_bitcount(key.modulus));
+                       q += 4;
+                       q += ssh1_write_bignum(q, key.exponent);
+                       q += ssh1_write_bignum(q, key.modulus);
+                       q += ssh1_write_bignum(q, challenge);
+                       memcpy(q, session_id, 16);
+                       q += 16;
+                       PUT_32BIT(q, 1);        /* response format */
+                       agent_query(agentreq, len + 4, &ret, &retlen);
+                       sfree(agentreq);
+                       if (ret) {
+                           if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
+                               logevent("Sending Pageant's response");
+                               send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
+                                           PKT_DATA, ret + 5, 16,
+                                           PKT_END);
+                               sfree(ret);
+                               crWaitUntil(ispkt);
+                               if (pktin.type == SSH1_SMSG_SUCCESS) {
+                                   logevent
+                                       ("Pageant's response accepted");
+                                   if (flags & FLAG_VERBOSE) {
+                                       c_write_str
+                                           ("Authenticated using RSA key \"");
+                                       c_write(commentp, commentlen);
+                                       c_write_str("\" from agent\r\n");
+                                   }
+                                   authed = TRUE;
+                               } else
+                                   logevent
+                                       ("Pageant's response not accepted");
+                           } else {
+                               logevent
+                                   ("Pageant failed to answer challenge");
+                               sfree(ret);
+                           }
+                       } else {
+                           logevent("No reply received from Pageant");
+                       }
+                   }
+                   freebn(key.exponent);
+                   freebn(key.modulus);
+                   freebn(challenge);
+                   if (authed)
+                       break;
+               }
+           }
+           if (authed)
+               break;
+       }
+       if (*cfg.keyfile && !tried_publickey)
+           pwpkt_type = SSH1_CMSG_AUTH_RSA;
+
+       if (pktin.type == SSH1_SMSG_FAILURE &&
+           cfg.try_tis_auth &&
+           (supported_auths_mask & (1 << SSH1_AUTH_TIS))) {
+           pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
+           logevent("Requested TIS authentication");
+           send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
+           crWaitUntil(ispkt);
+           if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
+               logevent("TIS authentication declined");
+               if (flags & FLAG_INTERACTIVE)
+                   c_write_str("TIS authentication refused.\r\n");
+           } else {
+               int challengelen = ((pktin.body[0] << 24) |
+                                   (pktin.body[1] << 16) |
+                                   (pktin.body[2] << 8) |
+                                   (pktin.body[3]));
+               logevent("Received TIS challenge");
+               if (challengelen > sizeof(prompt) - 1)
+                   challengelen = sizeof(prompt) - 1;  /* prevent overrun */
+               memcpy(prompt, pktin.body + 4, challengelen);
+               prompt[challengelen] = '\0';
+           }
+       }
+       if (pktin.type == SSH1_SMSG_FAILURE &&
+           cfg.try_tis_auth &&
+           (supported_auths_mask & (1 << SSH1_AUTH_CCARD))) {
+           pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
+           logevent("Requested CryptoCard authentication");
+           send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
+           crWaitUntil(ispkt);
+           if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
+               logevent("CryptoCard authentication declined");
+               c_write_str("CryptoCard authentication refused.\r\n");
+           } else {
+               int challengelen = ((pktin.body[0] << 24) |
+                                   (pktin.body[1] << 16) |
+                                   (pktin.body[2] << 8) |
+                                   (pktin.body[3]));
+               logevent("Received CryptoCard challenge");
+               if (challengelen > sizeof(prompt) - 1)
+                   challengelen = sizeof(prompt) - 1;  /* prevent overrun */
+               memcpy(prompt, pktin.body + 4, challengelen);
+               strncpy(prompt + challengelen, "\r\nResponse : ",
+                       sizeof(prompt) - challengelen);
+               prompt[sizeof(prompt) - 1] = '\0';
+           }
+       }
+       if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
+           sprintf(prompt, "%.90s@%.90s's password: ",
+                   username, savedhost);
+       }
+       if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
+           char *comment = NULL;
+           if (flags & FLAG_VERBOSE)
+               c_write_str("Trying public key authentication.\r\n");
+           if (!rsakey_encrypted(cfg.keyfile, &comment)) {
+               if (flags & FLAG_VERBOSE)
+                   c_write_str("No passphrase required.\r\n");
+               goto tryauth;
+           }
+           sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
+           sfree(comment);
+       }
 
        if (ssh_get_line) {
            if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
-                /*
-                 * get_line failed to get a password (for example
-                 * because one was supplied on the command line
-                 * which has already failed to work). Terminate.
-                 */
-                logevent("No more passwords to try");
-                ssh_state = SSH_STATE_CLOSED;
-                crReturn(1);
-            }
+               /*
+                * get_line failed to get a password (for example
+                * because one was supplied on the command line
+                * which has already failed to work). Terminate.
+                */
+               logevent("No more passwords to try");
+               ssh_state = SSH_STATE_CLOSED;
+               crReturn(1);
+           }
        } else {
-            c_write_str(prompt);
-            pos = 0;
-            ssh_send_ok = 1;
-            while (pos >= 0) {
-                crWaitUntil(!ispkt);
-                while (inlen--) switch (c = *in++) {
-                  case 10: case 13:
-                    password[pos] = 0;
-                    pos = -1;
-                    break;
-                  case 8: case 127:
-                    if (pos > 0)
-                        pos--;
-                    break;
-                  case 21: case 27:
-                    pos = 0;
-                    break;
-                  case 3: case 4:
-                    random_save_seed();
-                    exit(0);
-                    break;
-                  default:
-                    if (((c >= ' ' && c <= '~') ||
-                         ((unsigned char)c >= 160)) && pos < sizeof(password))
-                        password[pos++] = c;
-                    break;
-                }
-            }
-            c_write_str("\r\n");
-        }
-
-        tryauth:
+           c_write_str(prompt);
+           pos = 0;
+           ssh_send_ok = 1;
+           while (pos >= 0) {
+               crWaitUntil(!ispkt);
+               while (inlen--)
+                   switch (c = *in++) {
+                     case 10:
+                     case 13:
+                       password[pos] = 0;
+                       pos = -1;
+                       break;
+                     case 8:
+                     case 127:
+                       if (pos > 0)
+                           pos--;
+                       break;
+                     case 21:
+                     case 27:
+                       pos = 0;
+                       break;
+                     case 3:
+                     case 4:
+                       random_save_seed();
+                       exit(0);
+                       break;
+                     default:
+                       if (((c >= ' ' && c <= '~') ||
+                            ((unsigned char) c >= 160))
+                           && pos < sizeof(password))
+                           password[pos++] = c;
+                       break;
+                   }
+           }
+           c_write_str("\r\n");
+       }
+
+      tryauth:
        if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
-            /*
-             * Try public key authentication with the specified
-             * key file.
-             */
-            static struct RSAKey pubkey;
-            static Bignum challenge, response;
-            static int i;
-            static unsigned char buffer[32];
-
-            tried_publickey = 1;
-            i = loadrsakey(cfg.keyfile, &pubkey, password);
-            if (i == 0) {
-                c_write_str("Couldn't load public key from ");
-                c_write_str(cfg.keyfile);
-                c_write_str(".\r\n");
-                continue;              /* go and try password */
-            }
-            if (i == -1) {
-                c_write_str("Wrong passphrase.\r\n");
-                tried_publickey = 0;
-                continue;              /* try again */
-            }
-
-            /*
-             * Send a public key attempt.
-             */
-            send_packet(SSH1_CMSG_AUTH_RSA,
-                        PKT_BIGNUM, pubkey.modulus, PKT_END);
-
-            crWaitUntil(ispkt);
-            if (pktin.type == SSH1_SMSG_FAILURE) {
-                c_write_str("Server refused our public key.\r\n");
-                continue;              /* go and try password */
-            }
-            if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
-                bombout(("Bizarre response to offer of public key"));
-                crReturn(0);
-            }
-            ssh1_read_bignum(pktin.body, &challenge);
-            response = rsadecrypt(challenge, &pubkey);
-            freebn(pubkey.private_exponent);   /* burn the evidence */
-
-            for (i = 0; i < 32; i++) {
-                buffer[i] = bignum_byte(response, 31-i);
-            }
-
-            MD5Init(&md5c);
-            MD5Update(&md5c, buffer, 32);
-            MD5Update(&md5c, session_id, 16);
-            MD5Final(buffer, &md5c);
-
-            send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
-                        PKT_DATA, buffer, 16, PKT_END);
-
-            crWaitUntil(ispkt);
-            if (pktin.type == SSH1_SMSG_FAILURE) {
-                if (flags & FLAG_VERBOSE)
-                    c_write_str("Failed to authenticate with our public key.\r\n");
-                continue;              /* go and try password */
-            } else if (pktin.type != SSH1_SMSG_SUCCESS) {
-                bombout(("Bizarre response to RSA authentication response"));
-                crReturn(0);
-            }
-
-            break;                     /* we're through! */
-        } else {
-            if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
-                /*
-                 * Defence against traffic analysis: we send a
-                 * whole bunch of packets containing strings of
-                 * different lengths. One of these strings is the
-                 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
-                 * The others are all random data in
-                 * SSH1_MSG_IGNORE packets. This way a passive
-                 * listener can't tell which is the password, and
-                 * hence can't deduce the password length.
-                 * 
-                 * Anybody with a password length greater than 16
-                 * bytes is going to have enough entropy in their
-                 * password that a listener won't find it _that_
-                 * much help to know how long it is. So what we'll
-                 * do is:
-                 * 
-                 *  - if password length < 16, we send 15 packets
-                 *    containing string lengths 1 through 15
-                 * 
-                 *  - otherwise, we let N be the nearest multiple
-                 *    of 8 below the password length, and send 8
-                 *    packets containing string lengths N through
-                 *    N+7. This won't obscure the order of
-                 *    magnitude of the password length, but it will
-                 *    introduce a bit of extra uncertainty.
-                 * 
-                 * A few servers (the old 1.2.18 through 1.2.22)
-                 * can't deal with SSH1_MSG_IGNORE. For these
-                 * servers, we need an alternative defence. We make
-                 * use of the fact that the password is interpreted
-                 * as a C string: so we can append a NUL, then some
-                 * random data.
-                 */
-                if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
-                    char string[64];
-                    char *s;
-                    int len;
-
-                    len = strlen(password);
-                    if (len < sizeof(string)) {
-                        s = string;
-                        strcpy(string, password);
-                        len++;         /* cover the zero byte */
-                        while (len < sizeof(string)) {
-                            string[len++] = (char)random_byte();
-                        }
-                    } else {
-                        s = password;
-                    }
-                    send_packet(pwpkt_type, PKT_INT, len,
-                                PKT_DATA, s, len, PKT_END);
-                } else {
-                    int bottom, top, pwlen, i;
-                    char *randomstr;
-
-                    pwlen = strlen(password);
-                    if (pwlen < 16) {
-                        bottom = 0;    /* zero length passwords are OK! :-) */
-                        top = 15;
-                    } else {
-                        bottom = pwlen &~ 7;
-                        top = bottom + 7;
-                    }
-
-                    assert(pwlen >= bottom && pwlen <= top);
-
-                    randomstr = smalloc(top+1);
-
-                    for (i = bottom; i <= top; i++) {
-                        if (i == pwlen)
-                            defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
-                        else {
-                            for (j = 0; j < i; j++) {
-                                do {
-                                    randomstr[j] = random_byte();
-                                } while (randomstr[j] == '\0');
-                            }
-                            randomstr[i] = '\0';
-                            defer_packet(SSH1_MSG_IGNORE,
-                                         PKT_STR, randomstr, PKT_END);
-                        }
-                    }
-                    ssh_pkt_defersend();
-                }
-            } else {
-                send_packet(pwpkt_type, PKT_STR, password, PKT_END);
-            }
-        }
+           /*
+            * Try public key authentication with the specified
+            * key file.
+            */
+           static struct RSAKey pubkey;
+           static Bignum challenge, response;
+           static int i;
+           static unsigned char buffer[32];
+
+           tried_publickey = 1;
+           i = loadrsakey(cfg.keyfile, &pubkey, password);
+           if (i == 0) {
+               c_write_str("Couldn't load public key from ");
+               c_write_str(cfg.keyfile);
+               c_write_str(".\r\n");
+               continue;              /* go and try password */
+           }
+           if (i == -1) {
+               c_write_str("Wrong passphrase.\r\n");
+               tried_publickey = 0;
+               continue;              /* try again */
+           }
+
+           /*
+            * Send a public key attempt.
+            */
+           send_packet(SSH1_CMSG_AUTH_RSA,
+                       PKT_BIGNUM, pubkey.modulus, PKT_END);
+
+           crWaitUntil(ispkt);
+           if (pktin.type == SSH1_SMSG_FAILURE) {
+               c_write_str("Server refused our public key.\r\n");
+               continue;              /* go and try password */
+           }
+           if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+               bombout(("Bizarre response to offer of public key"));
+               crReturn(0);
+           }
+           ssh1_read_bignum(pktin.body, &challenge);
+           response = rsadecrypt(challenge, &pubkey);
+           freebn(pubkey.private_exponent);    /* burn the evidence */
+
+           for (i = 0; i < 32; i++) {
+               buffer[i] = bignum_byte(response, 31 - i);
+           }
+
+           MD5Init(&md5c);
+           MD5Update(&md5c, buffer, 32);
+           MD5Update(&md5c, session_id, 16);
+           MD5Final(buffer, &md5c);
+
+           send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
+                       PKT_DATA, buffer, 16, PKT_END);
+
+           crWaitUntil(ispkt);
+           if (pktin.type == SSH1_SMSG_FAILURE) {
+               if (flags & FLAG_VERBOSE)
+                   c_write_str
+                       ("Failed to authenticate with our public key.\r\n");
+               continue;              /* go and try password */
+           } else if (pktin.type != SSH1_SMSG_SUCCESS) {
+               bombout(
+                       ("Bizarre response to RSA authentication response"));
+               crReturn(0);
+           }
+
+           break;                     /* we're through! */
+       } else {
+           if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
+               /*
+                * Defence against traffic analysis: we send a
+                * whole bunch of packets containing strings of
+                * different lengths. One of these strings is the
+                * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
+                * The others are all random data in
+                * SSH1_MSG_IGNORE packets. This way a passive
+                * listener can't tell which is the password, and
+                * hence can't deduce the password length.
+                * 
+                * Anybody with a password length greater than 16
+                * bytes is going to have enough entropy in their
+                * password that a listener won't find it _that_
+                * much help to know how long it is. So what we'll
+                * do is:
+                * 
+                *  - if password length < 16, we send 15 packets
+                *    containing string lengths 1 through 15
+                * 
+                *  - otherwise, we let N be the nearest multiple
+                *    of 8 below the password length, and send 8
+                *    packets containing string lengths N through
+                *    N+7. This won't obscure the order of
+                *    magnitude of the password length, but it will
+                *    introduce a bit of extra uncertainty.
+                * 
+                * A few servers (the old 1.2.18 through 1.2.22)
+                * can't deal with SSH1_MSG_IGNORE. For these
+                * servers, we need an alternative defence. We make
+                * use of the fact that the password is interpreted
+                * as a C string: so we can append a NUL, then some
+                * random data.
+                */
+               if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
+                   char string[64];
+                   char *s;
+                   int len;
+
+                   len = strlen(password);
+                   if (len < sizeof(string)) {
+                       s = string;
+                       strcpy(string, password);
+                       len++;         /* cover the zero byte */
+                       while (len < sizeof(string)) {
+                           string[len++] = (char) random_byte();
+                       }
+                   } else {
+                       s = password;
+                   }
+                   send_packet(pwpkt_type, PKT_INT, len,
+                               PKT_DATA, s, len, PKT_END);
+               } else {
+                   int bottom, top, pwlen, i;
+                   char *randomstr;
+
+                   pwlen = strlen(password);
+                   if (pwlen < 16) {
+                       bottom = 0;    /* zero length passwords are OK! :-) */
+                       top = 15;
+                   } else {
+                       bottom = pwlen & ~7;
+                       top = bottom + 7;
+                   }
+
+                   assert(pwlen >= bottom && pwlen <= top);
+
+                   randomstr = smalloc(top + 1);
+
+                   for (i = bottom; i <= top; i++) {
+                       if (i == pwlen)
+                           defer_packet(pwpkt_type, PKT_STR, password,
+                                        PKT_END);
+                       else {
+                           for (j = 0; j < i; j++) {
+                               do {
+                                   randomstr[j] = random_byte();
+                               } while (randomstr[j] == '\0');
+                           }
+                           randomstr[i] = '\0';
+                           defer_packet(SSH1_MSG_IGNORE,
+                                        PKT_STR, randomstr, PKT_END);
+                       }
+                   }
+                   ssh_pkt_defersend();
+               }
+           } else {
+               send_packet(pwpkt_type, PKT_STR, password, PKT_END);
+           }
+       }
        logevent("Sent password");
        memset(password, 0, strlen(password));
        crWaitUntil(ispkt);
        if (pktin.type == SSH1_SMSG_FAILURE) {
-            if (flags & FLAG_VERBOSE)
-                c_write_str("Access denied\r\n");
+           if (flags & FLAG_VERBOSE)
+               c_write_str("Access denied\r\n");
            logevent("Authentication refused");
        } else if (pktin.type == SSH1_MSG_DISCONNECT) {
            logevent("Received disconnect request");
-            ssh_state = SSH_STATE_CLOSED;
+           ssh_state = SSH_STATE_CLOSED;
            crReturn(1);
        } else if (pktin.type != SSH1_SMSG_SUCCESS) {
            bombout(("Strange packet received, type %d", pktin.type));
-            crReturn(0);
+           crReturn(0);
        }
     }
 
@@ -2099,37 +2241,39 @@ static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
     crFinish(1);
 }
 
-void sshfwd_close(struct ssh_channel *c) {
+void sshfwd_close(struct ssh_channel *c)
+{
     if (c && !c->closes) {
-        if (ssh_version == 1) {
-            send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
-        } else {
-            ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
-            ssh2_pkt_adduint32(c->remoteid);
-            ssh2_pkt_send();
-        }
-        c->closes = 1;
-        if (c->type == CHAN_X11) {
-            c->u.x11.s = NULL;
-            logevent("X11 connection terminated");
-        }
-    }
-}
-
-void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
+       if (ssh_version == 1) {
+           send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
+                       PKT_END);
+       } else {
+           ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
+           ssh2_pkt_adduint32(c->remoteid);
+           ssh2_pkt_send();
+       }
+       c->closes = 1;
+       if (c->type == CHAN_X11) {
+           c->u.x11.s = NULL;
+           logevent("X11 connection terminated");
+       }
+    }
+}
+
+void sshfwd_write(struct ssh_channel *c, char *buf, int len)
+{
     if (ssh_version == 1) {
-        send_packet(SSH1_MSG_CHANNEL_DATA,
-                    PKT_INT, c->remoteid,
-                    PKT_INT, len,
-                    PKT_DATA, buf, len,
-                    PKT_END);
+       send_packet(SSH1_MSG_CHANNEL_DATA,
+                   PKT_INT, c->remoteid,
+                   PKT_INT, len, PKT_DATA, buf, len, PKT_END);
     } else {
-        ssh2_add_channel_data(c, buf, len);
-        ssh2_try_send(c);
+       ssh2_add_channel_data(c, buf, len);
+       ssh2_try_send(c);
     }
 }
 
-static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
+static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
+{
     crBegin;
 
     random_init();
@@ -2138,79 +2282,87 @@ static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
        crReturnV;
     }
     if (ssh_state == SSH_STATE_CLOSED)
-        crReturnV;
+       crReturnV;
 
     if (cfg.agentfwd && agent_exists()) {
-        logevent("Requesting agent forwarding");
-        send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
-        do { crReturnV; } while (!ispkt);
-        if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
-            bombout(("Protocol confusion"));
-            crReturnV;
-        } else if (pktin.type == SSH1_SMSG_FAILURE) {
-            logevent("Agent forwarding refused");
-        } else {
-            logevent("Agent forwarding enabled");
+       logevent("Requesting agent forwarding");
+       send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
+       do {
+           crReturnV;
+       } while (!ispkt);
+       if (pktin.type != SSH1_SMSG_SUCCESS
+           && pktin.type != SSH1_SMSG_FAILURE) {
+           bombout(("Protocol confusion"));
+           crReturnV;
+       } else if (pktin.type == SSH1_SMSG_FAILURE) {
+           logevent("Agent forwarding refused");
+       } else {
+           logevent("Agent forwarding enabled");
            ssh_agentfwd_enabled = TRUE;
        }
     }
 
     if (cfg.x11_forward) {
-        char proto[20], data[64];
-        logevent("Requesting X11 forwarding");
-        x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
-        if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
-            send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
-                        PKT_STR, proto, PKT_STR, data,
-                        PKT_INT, 0,
-                        PKT_END);
-        } else {
-            send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
-                        PKT_STR, proto, PKT_STR, data,
-                        PKT_END);
-        }
-        do { crReturnV; } while (!ispkt);
-        if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
-            bombout(("Protocol confusion"));
-            crReturnV;
-        } else if (pktin.type == SSH1_SMSG_FAILURE) {
-            logevent("X11 forwarding refused");
-        } else {
-            logevent("X11 forwarding enabled");
+       char proto[20], data[64];
+       logevent("Requesting X11 forwarding");
+       x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
+       if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
+           send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
+                       PKT_STR, proto, PKT_STR, data,
+                       PKT_INT, 0, PKT_END);
+       } else {
+           send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
+                       PKT_STR, proto, PKT_STR, data, PKT_END);
+       }
+       do {
+           crReturnV;
+       } while (!ispkt);
+       if (pktin.type != SSH1_SMSG_SUCCESS
+           && pktin.type != SSH1_SMSG_FAILURE) {
+           bombout(("Protocol confusion"));
+           crReturnV;
+       } else if (pktin.type == SSH1_SMSG_FAILURE) {
+           logevent("X11 forwarding refused");
+       } else {
+           logevent("X11 forwarding enabled");
            ssh_X11_fwd_enabled = TRUE;
        }
     }
 
     if (!cfg.nopty) {
        send_packet(SSH1_CMSG_REQUEST_PTY,
-                   PKT_STR, cfg.termtype,
-                   PKT_INT, rows, PKT_INT, cols,
-                   PKT_INT, 0, PKT_INT, 0,
-                   PKT_CHAR, 0,
-                   PKT_END);
-        ssh_state = SSH_STATE_INTERMED;
-        do { crReturnV; } while (!ispkt);
-        if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
-            bombout(("Protocol confusion"));
-            crReturnV;
-        } else if (pktin.type == SSH1_SMSG_FAILURE) {
-            c_write_str("Server refused to allocate pty\r\n");
-            ssh_editing = ssh_echoing = 1;
-        }
+                   PKT_STR, cfg.termtype,
+                   PKT_INT, rows, PKT_INT, cols,
+                   PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
+       ssh_state = SSH_STATE_INTERMED;
+       do {
+           crReturnV;
+       } while (!ispkt);
+       if (pktin.type != SSH1_SMSG_SUCCESS
+           && pktin.type != SSH1_SMSG_FAILURE) {
+           bombout(("Protocol confusion"));
+           crReturnV;
+       } else if (pktin.type == SSH1_SMSG_FAILURE) {
+           c_write_str("Server refused to allocate pty\r\n");
+           ssh_editing = ssh_echoing = 1;
+       }
        logevent("Allocated pty");
     } else {
-        ssh_editing = ssh_echoing = 1;
+       ssh_editing = ssh_echoing = 1;
     }
 
     if (cfg.compression) {
-        send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
-        do { crReturnV; } while (!ispkt);
-        if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
-            bombout(("Protocol confusion"));
-            crReturnV;
-        } else if (pktin.type == SSH1_SMSG_FAILURE) {
-            c_write_str("Server refused to compress\r\n");
-        }
+       send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
+       do {
+           crReturnV;
+       } while (!ispkt);
+       if (pktin.type != SSH1_SMSG_SUCCESS
+           && pktin.type != SSH1_SMSG_FAILURE) {
+           bombout(("Protocol confusion"));
+           crReturnV;
+       } else if (pktin.type == SSH1_SMSG_FAILURE) {
+           c_write_str("Server refused to compress\r\n");
+       }
        logevent("Started compression");
        ssh1_compressing = TRUE;
        zlib_compress_init();
@@ -2218,82 +2370,82 @@ static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
     }
 
     if (*cfg.remote_cmd_ptr)
-        send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd_ptr, PKT_END);
+       send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd_ptr,
+                   PKT_END);
     else
-        send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
+       send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
     logevent("Started session");
 
     ssh_state = SSH_STATE_SESSION;
     if (size_needed)
        ssh_size();
     if (eof_needed)
-        ssh_special(TS_EOF);
+       ssh_special(TS_EOF);
 
-    ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
+    ldisc_send(NULL, 0);              /* cause ldisc to notice changes */
     ssh_send_ok = 1;
     ssh_channels = newtree234(ssh_channelcmp);
     while (1) {
        crReturnV;
        if (ispkt) {
            if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
-                pktin.type == SSH1_SMSG_STDERR_DATA) {
+               pktin.type == SSH1_SMSG_STDERR_DATA) {
                long len = GET_32BIT(pktin.body);
                from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
-                            pktin.body+4, len);
+                            pktin.body + 4, len);
            } else if (pktin.type == SSH1_MSG_DISCONNECT) {
-                ssh_state = SSH_STATE_CLOSED;
+               ssh_state = SSH_STATE_CLOSED;
                logevent("Received disconnect request");
-                crReturnV;
-            } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
-                /* Remote side is trying to open a channel to talk to our
-                 * X-Server. Give them back a local channel number. */
-                struct ssh_channel *c;
+               crReturnV;
+           } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
+               /* Remote side is trying to open a channel to talk to our
+                * X-Server. Give them back a local channel number. */
+               struct ssh_channel *c;
 
                logevent("Received X11 connect request");
                /* Refuse if X11 forwarding is disabled. */
                if (!ssh_X11_fwd_enabled) {
                    send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
-                               PKT_INT, GET_32BIT(pktin.body),
-                               PKT_END);
+                               PKT_INT, GET_32BIT(pktin.body), PKT_END);
                    logevent("Rejected X11 connect request");
                } else {
                    c = smalloc(sizeof(struct ssh_channel));
 
-                   if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
-                     logevent("opening X11 forward connection failed");
-                     sfree(c);
-                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
-                                 PKT_INT, GET_32BIT(pktin.body),
-                                 PKT_END);
+                   if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
+                       logevent("opening X11 forward connection failed");
+                       sfree(c);
+                       send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
+                                   PKT_INT, GET_32BIT(pktin.body),
+                                   PKT_END);
                    } else {
-                     logevent("opening X11 forward connection succeeded");
-                     c->remoteid = GET_32BIT(pktin.body);
-                     c->localid = alloc_channel_id();
-                     c->closes = 0;
-                     c->type = CHAN_X11;   /* identify channel type */
-                     add234(ssh_channels, c);
-                     send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
-                                 PKT_INT, c->remoteid, PKT_INT, c->localid,
-                                 PKT_END);
-                     logevent("Opened X11 forward channel");
+                       logevent
+                           ("opening X11 forward connection succeeded");
+                       c->remoteid = GET_32BIT(pktin.body);
+                       c->localid = alloc_channel_id();
+                       c->closes = 0;
+                       c->type = CHAN_X11;     /* identify channel type */
+                       add234(ssh_channels, c);
+                       send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
+                                   PKT_INT, c->remoteid, PKT_INT,
+                                   c->localid, PKT_END);
+                       logevent("Opened X11 forward channel");
                    }
                }
-            } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
-                /* Remote side is trying to open a channel to talk to our
-                 * agent. Give them back a local channel number. */
-                struct ssh_channel *c;
+           } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
+               /* Remote side is trying to open a channel to talk to our
+                * agent. Give them back a local channel number. */
+               struct ssh_channel *c;
 
                /* Refuse if agent forwarding is disabled. */
                if (!ssh_agentfwd_enabled) {
                    send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
-                               PKT_INT, GET_32BIT(pktin.body),
-                               PKT_END);
+                               PKT_INT, GET_32BIT(pktin.body), PKT_END);
                } else {
                    c = smalloc(sizeof(struct ssh_channel));
                    c->remoteid = GET_32BIT(pktin.body);
                    c->localid = alloc_channel_id();
                    c->closes = 0;
-                   c->type = CHAN_AGENT;   /* identify channel type */
+                   c->type = CHAN_AGENT;       /* identify channel type */
                    c->u.a.lensofar = 0;
                    add234(ssh_channels, c);
                    send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
@@ -2302,83 +2454,95 @@ static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
                }
            } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
                       pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
-                /* Remote side closes a channel. */
-                unsigned i = GET_32BIT(pktin.body);
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (c) {
-                    int closetype;
-                    closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
-                    if (!(c->closes & closetype))
-                        send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
+               /* Remote side closes a channel. */
+               unsigned i = GET_32BIT(pktin.body);
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (c) {
+                   int closetype;
+                   closetype =
+                       (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
+                   if (!(c->closes & closetype))
+                       send_packet(pktin.type, PKT_INT, c->remoteid,
+                                   PKT_END);
                    if ((c->closes == 0) && (c->type == CHAN_X11)) {
-                       logevent("X11 connection closed");
+                       logevent("X11 connection closed");
                        assert(c->u.x11.s != NULL);
                        x11_close(c->u.x11.s);
                        c->u.x11.s = NULL;
                    }
-                    c->closes |= closetype;
-                    if (c->closes == 3) {
-                        del234(ssh_channels, c);
-                        sfree(c);
-                    }
-                }
-            } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
-                /* Data sent down one of our channels. */
-                int i = GET_32BIT(pktin.body);
-                int len = GET_32BIT(pktin.body+4);
-                unsigned char *p = pktin.body+8;
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (c) {
-                    switch(c->type) {
-                      case CHAN_X11:
+                   c->closes |= closetype;
+                   if (c->closes == 3) {
+                       del234(ssh_channels, c);
+                       sfree(c);
+                   }
+               }
+           } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
+               /* Data sent down one of our channels. */
+               int i = GET_32BIT(pktin.body);
+               int len = GET_32BIT(pktin.body + 4);
+               unsigned char *p = pktin.body + 8;
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (c) {
+                   switch (c->type) {
+                     case CHAN_X11:
                        x11_send(c->u.x11.s, p, len);
                        break;
-                      case CHAN_AGENT:
-                        /* Data for an agent message. Buffer it. */
-                        while (len > 0) {
-                            if (c->u.a.lensofar < 4) {
-                                int l = min(4 - c->u.a.lensofar, len);
-                                memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
-                                p += l; len -= l; c->u.a.lensofar += l;
-                            }
-                            if (c->u.a.lensofar == 4) {
-                                c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
-                                c->u.a.message = smalloc(c->u.a.totallen);
-                                memcpy(c->u.a.message, c->u.a.msglen, 4);
-                            }
-                            if (c->u.a.lensofar >= 4 && len > 0) {
-                                int l = min(c->u.a.totallen - c->u.a.lensofar, len);
-                                memcpy(c->u.a.message + c->u.a.lensofar, p, l);
-                                p += l; len -= l; c->u.a.lensofar += l;
-                            }
-                            if (c->u.a.lensofar == c->u.a.totallen) {
-                                void *reply, *sentreply;
-                                int replylen;
-                                agent_query(c->u.a.message, c->u.a.totallen,
-                                            &reply, &replylen);
-                                if (reply)
-                                    sentreply = reply;
-                                else {
-                                    /* Fake SSH_AGENT_FAILURE. */
-                                    sentreply = "\0\0\0\1\5";
-                                    replylen = 5;
-                                }
-                                send_packet(SSH1_MSG_CHANNEL_DATA,
-                                            PKT_INT, c->remoteid,
-                                            PKT_INT, replylen,
-                                            PKT_DATA, sentreply, replylen,
-                                            PKT_END);
-                                if (reply)
-                                    sfree(reply);
-                                sfree(c->u.a.message);
-                                c->u.a.lensofar = 0;
-                            }
-                        }
-                        break;
-                    }
-                }                
+                     case CHAN_AGENT:
+                       /* Data for an agent message. Buffer it. */
+                       while (len > 0) {
+                           if (c->u.a.lensofar < 4) {
+                               int l = min(4 - c->u.a.lensofar, len);
+                               memcpy(c->u.a.msglen + c->u.a.lensofar, p,
+                                      l);
+                               p += l;
+                               len -= l;
+                               c->u.a.lensofar += l;
+                           }
+                           if (c->u.a.lensofar == 4) {
+                               c->u.a.totallen =
+                                   4 + GET_32BIT(c->u.a.msglen);
+                               c->u.a.message = smalloc(c->u.a.totallen);
+                               memcpy(c->u.a.message, c->u.a.msglen, 4);
+                           }
+                           if (c->u.a.lensofar >= 4 && len > 0) {
+                               int l =
+                                   min(c->u.a.totallen - c->u.a.lensofar,
+                                       len);
+                               memcpy(c->u.a.message + c->u.a.lensofar, p,
+                                      l);
+                               p += l;
+                               len -= l;
+                               c->u.a.lensofar += l;
+                           }
+                           if (c->u.a.lensofar == c->u.a.totallen) {
+                               void *reply, *sentreply;
+                               int replylen;
+                               agent_query(c->u.a.message,
+                                           c->u.a.totallen, &reply,
+                                           &replylen);
+                               if (reply)
+                                   sentreply = reply;
+                               else {
+                                   /* Fake SSH_AGENT_FAILURE. */
+                                   sentreply = "\0\0\0\1\5";
+                                   replylen = 5;
+                               }
+                               send_packet(SSH1_MSG_CHANNEL_DATA,
+                                           PKT_INT, c->remoteid,
+                                           PKT_INT, replylen,
+                                           PKT_DATA, sentreply, replylen,
+                                           PKT_END);
+                               if (reply)
+                                   sfree(reply);
+                               sfree(c->u.a.message);
+                               c->u.a.lensofar = 0;
+                           }
+                       }
+                       break;
+                   }
+               }
            } else if (pktin.type == SSH1_SMSG_SUCCESS) {
                /* may be from EXEC_SHELL on some servers */
            } else if (pktin.type == SSH1_SMSG_FAILURE) {
@@ -2388,7 +2552,7 @@ static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
                send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
            } else {
                bombout(("Strange packet received: type %d", pktin.type));
-                crReturnV;
+               crReturnV;
            }
        } else {
            while (inlen > 0) {
@@ -2407,34 +2571,37 @@ static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
 /*
  * Utility routine for decoding comma-separated strings in KEXINIT.
  */
-static int in_commasep_string(char *needle, char *haystack, int haylen) {
+static int in_commasep_string(char *needle, char *haystack, int haylen)
+{
     int needlen = strlen(needle);
     while (1) {
-        /*
-         * Is it at the start of the string?
-         */
-        if (haylen >= needlen &&       /* haystack is long enough */
-            !memcmp(needle, haystack, needlen) &&    /* initial match */
-            (haylen == needlen || haystack[needlen] == ',')
-                                       /* either , or EOS follows */
-            )
-            return 1;
-        /*
-         * If not, search for the next comma and resume after that.
-         * If no comma found, terminate.
-         */
-        while (haylen > 0 && *haystack != ',')
-            haylen--, haystack++;
-        if (haylen == 0)
-            return 0;
-        haylen--, haystack++;          /* skip over comma itself */
+       /*
+        * Is it at the start of the string?
+        */
+       if (haylen >= needlen &&       /* haystack is long enough */
+           !memcmp(needle, haystack, needlen) &&       /* initial match */
+           (haylen == needlen || haystack[needlen] == ',')
+           /* either , or EOS follows */
+           )
+           return 1;
+       /*
+        * If not, search for the next comma and resume after that.
+        * If no comma found, terminate.
+        */
+       while (haylen > 0 && *haystack != ',')
+           haylen--, haystack++;
+       if (haylen == 0)
+           return 0;
+       haylen--, haystack++;          /* skip over comma itself */
     }
 }
 
 /*
  * SSH2 key creation method.
  */
-static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
+static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
+                      char *keyspace)
+{
     SHA_State s;
     /* First 20 bytes. */
     SHA_Init(&s);
@@ -2448,7 +2615,7 @@ static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace
     sha_mpint(&s, K);
     SHA_Bytes(&s, H, 20);
     SHA_Bytes(&s, keyspace, 20);
-    SHA_Final(&s, keyspace+20);
+    SHA_Final(&s, keyspace + 20);
 }
 
 /*
@@ -2485,17 +2652,17 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      * Set up the preferred cipher and compression.
      */
     if (cfg.cipher == CIPHER_BLOWFISH) {
-        preferred_cipher = &ssh2_blowfish;
+       preferred_cipher = &ssh2_blowfish;
     } else if (cfg.cipher == CIPHER_DES) {
-        logevent("Single DES not supported in SSH2; using 3DES");
-        preferred_cipher = &ssh2_3des;
+       logevent("Single DES not supported in SSH2; using 3DES");
+       preferred_cipher = &ssh2_3des;
     } else if (cfg.cipher == CIPHER_3DES) {
-        preferred_cipher = &ssh2_3des;
+       preferred_cipher = &ssh2_3des;
     } else if (cfg.cipher == CIPHER_AES) {
-        preferred_cipher = &ssh2_aes;
+       preferred_cipher = &ssh2_aes;
     } else {
-        /* Shouldn't happen, but we do want to initialise to _something_. */
-        preferred_cipher = &ssh2_3des;
+       /* Shouldn't happen, but we do want to initialise to _something_. */
+       preferred_cipher = &ssh2_3des;
     }
     if (cfg.compression)
        preferred_comp = &ssh_zlib;
@@ -2506,80 +2673,84 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      * Be prepared to work around the buggy MAC problem.
      */
     if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
-        maclist = buggymacs, nmacs = lenof(buggymacs);
+       maclist = buggymacs, nmacs = lenof(buggymacs);
     else
-        maclist = macs, nmacs = lenof(macs);
+       maclist = macs, nmacs = lenof(macs);
 
-    begin_key_exchange:
+  begin_key_exchange:
     /*
      * Construct and send our key exchange packet.
      */
     ssh2_pkt_init(SSH2_MSG_KEXINIT);
     for (i = 0; i < 16; i++)
-        ssh2_pkt_addbyte((unsigned char)random_byte());
+       ssh2_pkt_addbyte((unsigned char) random_byte());
     /* List key exchange algorithms. */
     ssh2_pkt_addstring_start();
     for (i = 0; i < lenof(kex_algs); i++) {
-        ssh2_pkt_addstring_str(kex_algs[i]->name);
-        if (i < lenof(kex_algs)-1)
-            ssh2_pkt_addstring_str(",");
+       ssh2_pkt_addstring_str(kex_algs[i]->name);
+       if (i < lenof(kex_algs) - 1)
+           ssh2_pkt_addstring_str(",");
     }
     /* List server host key algorithms. */
     ssh2_pkt_addstring_start();
     for (i = 0; i < lenof(hostkey_algs); i++) {
-        ssh2_pkt_addstring_str(hostkey_algs[i]->name);
-        if (i < lenof(hostkey_algs)-1)
-            ssh2_pkt_addstring_str(",");
+       ssh2_pkt_addstring_str(hostkey_algs[i]->name);
+       if (i < lenof(hostkey_algs) - 1)
+           ssh2_pkt_addstring_str(",");
     }
     /* List client->server encryption algorithms. */
     ssh2_pkt_addstring_start();
-    for (i = 0; i < lenof(ciphers)+1; i++) {
-        const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
-        for (j = 0; j < c->nciphers; j++) {
-            ssh2_pkt_addstring_str(c->list[j]->name);
-            if (i < lenof(ciphers) || j < c->nciphers-1)
-                ssh2_pkt_addstring_str(",");
-        }
+    for (i = 0; i < lenof(ciphers) + 1; i++) {
+       const struct ssh2_ciphers *c =
+           i == 0 ? preferred_cipher : ciphers[i - 1];
+       for (j = 0; j < c->nciphers; j++) {
+           ssh2_pkt_addstring_str(c->list[j]->name);
+           if (i < lenof(ciphers) || j < c->nciphers - 1)
+               ssh2_pkt_addstring_str(",");
+       }
     }
     /* List server->client encryption algorithms. */
     ssh2_pkt_addstring_start();
-    for (i = 0; i < lenof(ciphers)+1; i++) {
-        const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
-        for (j = 0; j < c->nciphers; j++) {
-            ssh2_pkt_addstring_str(c->list[j]->name);
-            if (i < lenof(ciphers) || j < c->nciphers-1)
-                ssh2_pkt_addstring_str(",");
-        }
+    for (i = 0; i < lenof(ciphers) + 1; i++) {
+       const struct ssh2_ciphers *c =
+           i == 0 ? preferred_cipher : ciphers[i - 1];
+       for (j = 0; j < c->nciphers; j++) {
+           ssh2_pkt_addstring_str(c->list[j]->name);
+           if (i < lenof(ciphers) || j < c->nciphers - 1)
+               ssh2_pkt_addstring_str(",");
+       }
     }
     /* List client->server MAC algorithms. */
     ssh2_pkt_addstring_start();
     for (i = 0; i < nmacs; i++) {
-        ssh2_pkt_addstring_str(maclist[i]->name);
-        if (i < nmacs-1)
-            ssh2_pkt_addstring_str(",");
+       ssh2_pkt_addstring_str(maclist[i]->name);
+       if (i < nmacs - 1)
+           ssh2_pkt_addstring_str(",");
     }
     /* List server->client MAC algorithms. */
     ssh2_pkt_addstring_start();
     for (i = 0; i < nmacs; i++) {
-        ssh2_pkt_addstring_str(maclist[i]->name);
-        if (i < nmacs-1)
-            ssh2_pkt_addstring_str(",");
+       ssh2_pkt_addstring_str(maclist[i]->name);
+       if (i < nmacs - 1)
+           ssh2_pkt_addstring_str(",");
     }
     /* List client->server compression algorithms. */
     ssh2_pkt_addstring_start();
-    for (i = 0; i < lenof(compressions)+1; i++) {
-        const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
-        ssh2_pkt_addstring_str(c->name);
-        if (i < lenof(compressions))
-            ssh2_pkt_addstring_str(",");
+    for (i = 0; i < lenof(compressions) + 1; i++) {
+       const struct ssh_compress *c =
+           i == 0 ? preferred_comp : compressions[i - 1];
+       ssh2_pkt_addstring_str(c->name);
+       if (i < lenof(compressions))
+           ssh2_pkt_addstring_str(",");
     }
     /* List server->client compression algorithms. */
     ssh2_pkt_addstring_start();
-    for (i = 0; i < lenof(compressions)+1; i++) {
-        const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
-        ssh2_pkt_addstring_str(c->name);
-        if (i < lenof(compressions))
-            ssh2_pkt_addstring_str(",");
+    for (i = 0; i < lenof(compressions) + 1; i++) {
+       const struct ssh_compress *c =
+           i == 0 ? preferred_comp : compressions[i - 1];
+       ssh2_pkt_addstring_str(c->name);
+       if (i < lenof(compressions))
+           ssh2_pkt_addstring_str(",");
     }
     /* List client->server languages. Empty list. */
     ssh2_pkt_addstring_start();
@@ -2591,91 +2762,102 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_adduint32(0);
 
     exhash = exhashbase;
-    sha_string(&exhash, pktout.data+5, pktout.length-5);
+    sha_string(&exhash, pktout.data + 5, pktout.length - 5);
 
     ssh2_pkt_send();
 
-    if (!ispkt) crWaitUntil(ispkt);
-    sha_string(&exhash, pktin.data+5, pktin.length-5);
+    if (!ispkt)
+       crWaitUntil(ispkt);
+    sha_string(&exhash, pktin.data + 5, pktin.length - 5);
 
     /*
      * Now examine the other side's KEXINIT to see what we're up
      * to.
      */
     if (pktin.type != SSH2_MSG_KEXINIT) {
-        bombout(("expected key exchange packet from server"));
-        crReturn(0);
+       bombout(("expected key exchange packet from server"));
+       crReturn(0);
     }
-    kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
-    csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
-    pktin.savedpos += 16;              /* skip garbage cookie */
+    kex = NULL;
+    hostkey = NULL;
+    cscipher_tobe = NULL;
+    sccipher_tobe = NULL;
+    csmac_tobe = NULL;
+    scmac_tobe = NULL;
+    cscomp_tobe = NULL;
+    sccomp_tobe = NULL;
+    pktin.savedpos += 16;             /* skip garbage cookie */
     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
     for (i = 0; i < lenof(kex_algs); i++) {
-        if (in_commasep_string(kex_algs[i]->name, str, len)) {
-            kex = kex_algs[i];
-            break;
-        }
+       if (in_commasep_string(kex_algs[i]->name, str, len)) {
+           kex = kex_algs[i];
+           break;
+       }
     }
     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
     for (i = 0; i < lenof(hostkey_algs); i++) {
-        if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
-            hostkey = hostkey_algs[i];
-            break;
-        }
+       if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
+           hostkey = hostkey_algs[i];
+           break;
+       }
     }
     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
-    for (i = 0; i < lenof(ciphers)+1; i++) {
-        const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
-        for (j = 0; j < c->nciphers; j++) {
-            if (in_commasep_string(c->list[j]->name, str, len)) {
-                cscipher_tobe = c->list[j];
-                break;
-            }
-        }
-        if (cscipher_tobe)
-            break;
+    for (i = 0; i < lenof(ciphers) + 1; i++) {
+       const struct ssh2_ciphers *c =
+           i == 0 ? preferred_cipher : ciphers[i - 1];
+       for (j = 0; j < c->nciphers; j++) {
+           if (in_commasep_string(c->list[j]->name, str, len)) {
+               cscipher_tobe = c->list[j];
+               break;
+           }
+       }
+       if (cscipher_tobe)
+           break;
     }
     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
-    for (i = 0; i < lenof(ciphers)+1; i++) {
-        const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
-        for (j = 0; j < c->nciphers; j++) {
-            if (in_commasep_string(c->list[j]->name, str, len)) {
-                sccipher_tobe = c->list[j];
-                break;
-            }
-        }
-        if (sccipher_tobe)
-            break;
+    for (i = 0; i < lenof(ciphers) + 1; i++) {
+       const struct ssh2_ciphers *c =
+           i == 0 ? preferred_cipher : ciphers[i - 1];
+       for (j = 0; j < c->nciphers; j++) {
+           if (in_commasep_string(c->list[j]->name, str, len)) {
+               sccipher_tobe = c->list[j];
+               break;
+           }
+       }
+       if (sccipher_tobe)
+           break;
     }
     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
     for (i = 0; i < nmacs; i++) {
-        if (in_commasep_string(maclist[i]->name, str, len)) {
-            csmac_tobe = maclist[i];
-            break;
-        }
+       if (in_commasep_string(maclist[i]->name, str, len)) {
+           csmac_tobe = maclist[i];
+           break;
+       }
     }
     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
     for (i = 0; i < nmacs; i++) {
-        if (in_commasep_string(maclist[i]->name, str, len)) {
-            scmac_tobe = maclist[i];
-            break;
-        }
+       if (in_commasep_string(maclist[i]->name, str, len)) {
+           scmac_tobe = maclist[i];
+           break;
+       }
     }
     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
-    for (i = 0; i < lenof(compressions)+1; i++) {
-        const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
-        if (in_commasep_string(c->name, str, len)) {
-            cscomp_tobe = c;
-            break;
-        }
+    for (i = 0; i < lenof(compressions) + 1; i++) {
+       const struct ssh_compress *c =
+           i == 0 ? preferred_comp : compressions[i - 1];
+       if (in_commasep_string(c->name, str, len)) {
+           cscomp_tobe = c;
+           break;
+       }
     }
     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
-    for (i = 0; i < lenof(compressions)+1; i++) {
-        const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
-        if (in_commasep_string(c->name, str, len)) {
-            sccomp_tobe = c;
-            break;
-        }
+    for (i = 0; i < lenof(compressions) + 1; i++) {
+       const struct ssh_compress *c =
+           i == 0 ? preferred_comp : compressions[i - 1];
+       if (in_commasep_string(c->name, str, len)) {
+           sccomp_tobe = c;
+           break;
+       }
     }
 
     /*
@@ -2684,7 +2866,7 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      * cipher...
      */
     {
-        int csbits, scbits;
+       int csbits, scbits;
 
        csbits = cscipher_tobe->keylen;
        scbits = sccipher_tobe->keylen;
@@ -2692,52 +2874,53 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
     }
     /* The keys only have 160-bit entropy, since they're based on
      * a SHA-1 hash. So cap the key size at 160 bits. */
-    if (nbits > 160) nbits = 160;
+    if (nbits > 160)
+       nbits = 160;
 
     /*
      * If we're doing Diffie-Hellman group exchange, start by
      * requesting a group.
      */
     if (kex == &ssh_diffiehellman_gex) {
-        logevent("Doing Diffie-Hellman group exchange");
-        /*
-         * Work out how big a DH group we will need to allow that
-         * much data.
+       logevent("Doing Diffie-Hellman group exchange");
+       /*
+        * Work out how big a DH group we will need to allow that
+        * much data.
         */
-        pbits = 512 << ((nbits-1) / 64);
-        ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
-        ssh2_pkt_adduint32(pbits);
-        ssh2_pkt_send();
-
-        crWaitUntil(ispkt);
-        if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
-            bombout(("expected key exchange group packet from server"));
-            crReturn(0);
-        }
-        p = ssh2_pkt_getmp();
-        g = ssh2_pkt_getmp();
-        dh_setup_group(p, g);
-        kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
-        kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
+       pbits = 512 << ((nbits - 1) / 64);
+       ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
+       ssh2_pkt_adduint32(pbits);
+       ssh2_pkt_send();
+
+       crWaitUntil(ispkt);
+       if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
+           bombout(("expected key exchange group packet from server"));
+           crReturn(0);
+       }
+       p = ssh2_pkt_getmp();
+       g = ssh2_pkt_getmp();
+       dh_setup_group(p, g);
+       kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
+       kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
     } else {
-        dh_setup_group1();
-        kex_init_value = SSH2_MSG_KEXDH_INIT;
-        kex_reply_value = SSH2_MSG_KEXDH_REPLY;
+       dh_setup_group1();
+       kex_init_value = SSH2_MSG_KEXDH_INIT;
+       kex_reply_value = SSH2_MSG_KEXDH_REPLY;
     }
 
     logevent("Doing Diffie-Hellman key exchange");
     /*
      * Now generate and send e for Diffie-Hellman.
      */
-    e = dh_create_e(nbits*2);
+    e = dh_create_e(nbits * 2);
     ssh2_pkt_init(kex_init_value);
     ssh2_pkt_addmp(e);
     ssh2_pkt_send();
 
     crWaitUntil(ispkt);
     if (pktin.type != kex_reply_value) {
-        bombout(("expected key exchange reply packet from server"));
-        crReturn(0);
+       bombout(("expected key exchange reply packet from server"));
+       crReturn(0);
     }
     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
     f = ssh2_pkt_getmp();
@@ -2747,9 +2930,9 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
 
     sha_string(&exhash, hostkeydata, hostkeylen);
     if (kex == &ssh_diffiehellman_gex) {
-        sha_uint32(&exhash, pbits);
-        sha_mpint(&exhash, p);
-        sha_mpint(&exhash, g);
+       sha_uint32(&exhash, pbits);
+       sha_mpint(&exhash, p);
+       sha_mpint(&exhash, g);
     }
     sha_mpint(&exhash, e);
     sha_mpint(&exhash, f);
@@ -2765,8 +2948,8 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
 
     hkey = hostkey->newkey(hostkeydata, hostkeylen);
     if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
-        bombout(("Server failed host key check"));
-        crReturn(0);
+       bombout(("Server failed host key check"));
+       crReturn(0);
     }
 
     /*
@@ -2774,8 +2957,8 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      */
     crWaitUntil(ispkt);
     if (pktin.type != SSH2_MSG_NEWKEYS) {
-        bombout(("expected new-keys packet from server"));
-        crReturn(0);
+       bombout(("expected new-keys packet from server"));
+       crReturn(0);
     }
 
     /*
@@ -2785,8 +2968,8 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
     keystr = hostkey->fmtkey(hkey);
     fingerprint = hostkey->fingerprint(hkey);
     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
-                        keystr, fingerprint);
-    if (first_kex) {                /* don't bother logging this in rekeys */
+                       keystr, fingerprint);
+    if (first_kex) {                  /* don't bother logging this in rekeys */
        logevent("Host key fingerprint is:");
        logevent(fingerprint);
     }
@@ -2839,7 +3022,7 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      * it would only confuse the layer above.
      */
     if (!first_kex) {
-        crReturn(0);
+       crReturn(0);
     }
     first_kex = 0;
 
@@ -2850,7 +3033,7 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
      * start.
      */
     while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
-        crReturn(1);
+       crReturn(1);
     }
     logevent("Server initiated key re-exchange");
     goto begin_key_exchange;
@@ -2861,39 +3044,36 @@ static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
 /*
  * Add data to an SSH2 channel output buffer.
  */
-static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
-    if (c->v2.outbufsize <
-        c->v2.outbuflen + len) {
-        c->v2.outbufsize =
-            c->v2.outbuflen + len + 1024;
-        c->v2.outbuffer = srealloc(c->v2.outbuffer,
-                                   c->v2.outbufsize);
-    }
-    memcpy(c->v2.outbuffer + c->v2.outbuflen,
-           buf, len);
+static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
+                                 int len)
+{
+    if (c->v2.outbufsize < c->v2.outbuflen + len) {
+       c->v2.outbufsize = c->v2.outbuflen + len + 1024;
+       c->v2.outbuffer = srealloc(c->v2.outbuffer, c->v2.outbufsize);
+    }
+    memcpy(c->v2.outbuffer + c->v2.outbuflen, buf, len);
     c->v2.outbuflen += len;
 }
 
 /*
  * Attempt to send data on an SSH2 channel.
  */
-static void ssh2_try_send(struct ssh_channel *c) {
-    while (c->v2.remwindow > 0 &&
-           c->v2.outbuflen > 0) {
-        unsigned len = c->v2.remwindow;
-        if (len > c->v2.outbuflen)
-            len = c->v2.outbuflen;
-        if (len > c->v2.remmaxpkt)
-            len = c->v2.remmaxpkt;
-        ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
-        ssh2_pkt_adduint32(c->remoteid);
-        ssh2_pkt_addstring_start();
-        ssh2_pkt_addstring_data(c->v2.outbuffer, len);
-        ssh2_pkt_send();
-        c->v2.outbuflen -= len;
-        memmove(c->v2.outbuffer, c->v2.outbuffer+len,
-                c->v2.outbuflen);
-        c->v2.remwindow -= len;
+static void ssh2_try_send(struct ssh_channel *c)
+{
+    while (c->v2.remwindow > 0 && c->v2.outbuflen > 0) {
+       unsigned len = c->v2.remwindow;
+       if (len > c->v2.outbuflen)
+           len = c->v2.outbuflen;
+       if (len > c->v2.remmaxpkt)
+           len = c->v2.remmaxpkt;
+       ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
+       ssh2_pkt_adduint32(c->remoteid);
+       ssh2_pkt_addstring_start();
+       ssh2_pkt_addstring_data(c->v2.outbuffer, len);
+       ssh2_pkt_send();
+       c->v2.outbuflen -= len;
+       memmove(c->v2.outbuffer, c->v2.outbuffer + len, c->v2.outbuflen);
+       c->v2.remwindow -= len;
     }
 }
 
@@ -2905,14 +3085,15 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
     static unsigned long remote_winsize;
     static unsigned long remote_maxpkt;
     static enum {
-       AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
+       AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
+       AUTH_PASSWORD
     } method;
     static enum {
-        AUTH_TYPE_NONE,
-        AUTH_TYPE_PUBLICKEY,
-        AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
-        AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
-        AUTH_TYPE_PASSWORD
+       AUTH_TYPE_NONE,
+       AUTH_TYPE_PUBLICKEY,
+       AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
+       AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
+       AUTH_TYPE_PASSWORD
     } type;
     static int gotit, need_pw, can_pubkey, can_passwd;
     static int tried_pubkey_config, tried_agent;
@@ -2931,8 +3112,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_send();
     crWaitUntilV(ispkt);
     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
-        bombout(("Server refused user authentication protocol"));
-        crReturnV;
+       bombout(("Server refused user authentication protocol"));
+       crReturnV;
     }
 
     /*
@@ -2968,53 +3149,58 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
         */
        pos = 0;
        if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
-            if (ssh_get_line) {
-                if (!ssh_get_line("login as: ",
-                                  username, sizeof(username), FALSE)) {
-                    /*
-                     * get_line failed to get a username.
-                     * Terminate.
-                     */
-                    logevent("No username provided. Abandoning session.");
-                    ssh_state = SSH_STATE_CLOSED;
-                    crReturnV;
-                }
-            } else {
-                c_write_str("login as: ");
-                ssh_send_ok = 1;
-                while (pos >= 0) {
-                    crWaitUntilV(!ispkt);
-                    while (inlen--) switch (c = *in++) {
-                      case 10: case 13:
-                        username[pos] = 0;
-                        pos = -1;
-                        break;
-                      case 8: case 127:
-                        if (pos > 0) {
-                            c_write_str("\b \b");
-                            pos--;
-                        }
-                        break;
-                      case 21: case 27:
-                        while (pos > 0) {
-                            c_write_str("\b \b");
-                            pos--;
-                        }
-                        break;
-                      case 3: case 4:
-                        random_save_seed();
-                        exit(0);
-                        break;
-                      default:
-                        if (((c >= ' ' && c <= '~') ||
-                             ((unsigned char)c >= 160)) && pos < 40) {
-                            username[pos++] = c;
-                            c_write(&c, 1);
-                        }
-                        break;
-                    }
-                }
-            }
+           if (ssh_get_line) {
+               if (!ssh_get_line("login as: ",
+                                 username, sizeof(username), FALSE)) {
+                   /*
+                    * get_line failed to get a username.
+                    * Terminate.
+                    */
+                   logevent("No username provided. Abandoning session.");
+                   ssh_state = SSH_STATE_CLOSED;
+                   crReturnV;
+               }
+           } else {
+               c_write_str("login as: ");
+               ssh_send_ok = 1;
+               while (pos >= 0) {
+                   crWaitUntilV(!ispkt);
+                   while (inlen--)
+                       switch (c = *in++) {
+                         case 10:
+                         case 13:
+                           username[pos] = 0;
+                           pos = -1;
+                           break;
+                         case 8:
+                         case 127:
+                           if (pos > 0) {
+                               c_write_str("\b \b");
+                               pos--;
+                           }
+                           break;
+                         case 21:
+                         case 27:
+                           while (pos > 0) {
+                               c_write_str("\b \b");
+                               pos--;
+                           }
+                           break;
+                         case 3:
+                         case 4:
+                           random_save_seed();
+                           exit(0);
+                           break;
+                         default:
+                           if (((c >= ' ' && c <= '~') ||
+                                ((unsigned char) c >= 160)) && pos < 40) {
+                               username[pos++] = c;
+                               c_write(&c, 1);
+                           }
+                           break;
+                       }
+               }
+           }
            c_write_str("\r\n");
            username[strcspn(username, "\n\r")] = '\0';
        } else {
@@ -3034,7 +3220,7 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
         */
        ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
        ssh2_pkt_addstring(username);
-       ssh2_pkt_addstring("ssh-connection");   /* service requested */
+       ssh2_pkt_addstring("ssh-connection");   /* service requested */
        ssh2_pkt_addstring("none");    /* method */
        ssh2_pkt_send();
        type = AUTH_TYPE_NONE;
@@ -3051,21 +3237,21 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
            if (!gotit)
                crWaitUntilV(ispkt);
            while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
-                char *banner;
-                int size;
-                /*
-                 * Don't show the banner if we're operating in
-                 * non-verbose non-interactive mode. (It's probably
-                 * a script, which means nobody will read the
-                 * banner _anyway_, and moreover the printing of
-                 * the banner will screw up processing on the
-                 * output of (say) plink.)
-                 */
-                if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
-                    ssh2_pkt_getstring(&banner, &size);
-                    if (banner)
-                        c_write_untrusted(banner, size);
-                }
+               char *banner;
+               int size;
+               /*
+                * Don't show the banner if we're operating in
+                * non-verbose non-interactive mode. (It's probably
+                * a script, which means nobody will read the
+                * banner _anyway_, and moreover the printing of
+                * the banner will screw up processing on the
+                * output of (say) plink.)
+                */
+               if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
+                   ssh2_pkt_getstring(&banner, &size);
+                   if (banner)
+                       c_write_untrusted(banner, size);
+               }
                crWaitUntilV(ispkt);
            }
            if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
@@ -3075,7 +3261,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
            }
 
            if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
-               bombout(("Strange packet received during authentication: type %d",
+               bombout(
+                       ("Strange packet received during authentication: type %d",
                         pktin.type));
                crReturnV;
            }
@@ -3133,8 +3320,10 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                    logevent("Further authentication required");
                }
 
-               can_pubkey = in_commasep_string("publickey", methods, methlen);
-               can_passwd = in_commasep_string("password", methods, methlen);
+               can_pubkey =
+                   in_commasep_string("publickey", methods, methlen);
+               can_passwd =
+                   in_commasep_string("password", methods, methlen);
            }
 
            method = 0;
@@ -3157,32 +3346,43 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                PUT_32BIT(request, 1);
                request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
                agent_query(request, 5, &r, &responselen);
-               response = (unsigned char *)r;
+               response = (unsigned char *) r;
                if (response && responselen >= 5 &&
-                    response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
+                   response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
                    p = response + 5;
-                   nkeys = GET_32BIT(p); p += 4;
-                   { char buf[64]; sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
-                       logevent(buf); }
+                   nkeys = GET_32BIT(p);
+                   p += 4;
+                   {
+                       char buf[64];
+                       sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
+                       logevent(buf);
+                   }
                    for (i = 0; i < nkeys; i++) {
                        static char *pkblob, *alg, *commentp;
                        static int pklen, alglen, commentlen;
                        static int siglen, retlen, len;
                        static char *q, *agentreq, *ret;
 
-                       { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
-                           logevent(buf); }
-                       pklen = GET_32BIT(p); p += 4;
-                       pkblob = p; p += pklen;
+                       {
+                           char buf[64];
+                           sprintf(buf, "Trying Pageant key #%d", i);
+                           logevent(buf);
+                       }
+                       pklen = GET_32BIT(p);
+                       p += 4;
+                       pkblob = p;
+                       p += pklen;
                        alglen = GET_32BIT(pkblob);
                        alg = pkblob + 4;
-                       commentlen = GET_32BIT(p); p += 4;
-                       commentp = p; p += commentlen;
+                       commentlen = GET_32BIT(p);
+                       p += 4;
+                       commentp = p;
+                       p += commentlen;
                        ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                        ssh2_pkt_addstring(username);
-                       ssh2_pkt_addstring("ssh-connection");/* service requested */
-                       ssh2_pkt_addstring("publickey");/* method */
-                       ssh2_pkt_addbool(FALSE);   /* no signature included */
+                       ssh2_pkt_addstring("ssh-connection");   /* service requested */
+                       ssh2_pkt_addstring("publickey");        /* method */
+                       ssh2_pkt_addbool(FALSE);        /* no signature included */
                        ssh2_pkt_addstring_start();
                        ssh2_pkt_addstring_data(alg, alglen);
                        ssh2_pkt_addstring_start();
@@ -3195,11 +3395,12 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                            continue;
                        }
 
-                        if (flags & FLAG_VERBOSE) {
-                            c_write_str("Authenticating with public key \"");
-                            c_write(commentp, commentlen);
-                            c_write_str("\" from agent\r\n");
-                        }
+                       if (flags & FLAG_VERBOSE) {
+                           c_write_str
+                               ("Authenticating with public key \"");
+                           c_write(commentp, commentlen);
+                           c_write_str("\" from agent\r\n");
+                       }
 
                        /*
                         * Server is willing to accept the key.
@@ -3207,8 +3408,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                         */
                        ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                        ssh2_pkt_addstring(username);
-                       ssh2_pkt_addstring("ssh-connection");   /* service requested */
-                       ssh2_pkt_addstring("publickey");    /* method */
+                       ssh2_pkt_addstring("ssh-connection");   /* service requested */
+                       ssh2_pkt_addstring("publickey");        /* method */
                        ssh2_pkt_addbool(TRUE);
                        ssh2_pkt_addstring_start();
                        ssh2_pkt_addstring_data(alg, alglen);
@@ -3216,36 +3417,44 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                        ssh2_pkt_addstring_data(pkblob, pklen);
 
                        siglen = pktout.length - 5 + 4 + 20;
-                       len = 1;   /* message type */
-                       len += 4 + pklen;   /* key blob */
-                       len += 4 + siglen;   /* data to sign */
-                       len += 4;  /* flags */
+                       len = 1;       /* message type */
+                       len += 4 + pklen;       /* key blob */
+                       len += 4 + siglen;      /* data to sign */
+                       len += 4;      /* flags */
                        agentreq = smalloc(4 + len);
                        PUT_32BIT(agentreq, len);
                        q = agentreq + 4;
                        *q++ = SSH2_AGENTC_SIGN_REQUEST;
-                       PUT_32BIT(q, pklen); q += 4;
-                       memcpy(q, pkblob, pklen); q += pklen;
-                       PUT_32BIT(q, siglen); q += 4;
+                       PUT_32BIT(q, pklen);
+                       q += 4;
+                       memcpy(q, pkblob, pklen);
+                       q += pklen;
+                       PUT_32BIT(q, siglen);
+                       q += 4;
                        /* Now the data to be signed... */
-                       PUT_32BIT(q, 20); q += 4;
-                       memcpy(q, ssh2_session_id, 20); q += 20;
-                       memcpy(q, pktout.data+5, pktout.length-5);
-                       q += pktout.length-5;
+                       PUT_32BIT(q, 20);
+                       q += 4;
+                       memcpy(q, ssh2_session_id, 20);
+                       q += 20;
+                       memcpy(q, pktout.data + 5, pktout.length - 5);
+                       q += pktout.length - 5;
                        /* And finally the (zero) flags word. */
                        PUT_32BIT(q, 0);
-                       agent_query(agentreq, len+4, &ret, &retlen);
+                       agent_query(agentreq, len + 4, &ret, &retlen);
                        sfree(agentreq);
                        if (ret) {
                            if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
                                logevent("Sending Pageant's response");
                                ssh2_pkt_addstring_start();
-                               ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
+                               ssh2_pkt_addstring_data(ret + 9,
+                                                       GET_32BIT(ret +
+                                                                 5));
                                ssh2_pkt_send();
                                authed = TRUE;
                                break;
                            } else {
-                               logevent("Pageant failed to answer challenge");
+                               logevent
+                                   ("Pageant failed to answer challenge");
                                sfree(ret);
                            }
                        }
@@ -3255,7 +3464,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                }
            }
 
-           if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
+           if (!method && can_pubkey && *cfg.keyfile
+               && !tried_pubkey_config) {
                unsigned char *pub_blob;
                char *algorithm, *comment;
                int pub_blob_len;
@@ -3273,20 +3483,20 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                if (pub_blob) {
                    ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                    ssh2_pkt_addstring(username);
-                   ssh2_pkt_addstring("ssh-connection");   /* service requested */
-                   ssh2_pkt_addstring("publickey");/* method */
-                   ssh2_pkt_addbool(FALSE);   /* no signature included */
+                   ssh2_pkt_addstring("ssh-connection");       /* service requested */
+                   ssh2_pkt_addstring("publickey");    /* method */
+                   ssh2_pkt_addbool(FALSE);    /* no signature included */
                    ssh2_pkt_addstring(algorithm);
                    ssh2_pkt_addstring_start();
                    ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
                    ssh2_pkt_send();
-                   logevent("Offered public key"); /* FIXME */
+                   logevent("Offered public key");     /* FIXME */
 
                    crWaitUntilV(ispkt);
                    if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
                        gotit = TRUE;
                        type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
-                       continue;              /* key refused; give up on it */
+                       continue;      /* key refused; give up on it */
                    }
 
                    logevent("Offer of public key accepted");
@@ -3295,7 +3505,9 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                     * the key.
                     */
                    if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
-                       sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
+                       sprintf(pwprompt,
+                               "Passphrase for key \"%.100s\": ",
+                               comment);
                        need_pw = TRUE;
                    } else {
                        need_pw = FALSE;
@@ -3309,14 +3521,15 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
 
            if (!method && can_passwd) {
                method = AUTH_PASSWORD;
-               sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
+               sprintf(pwprompt, "%.90s@%.90s's password: ", username,
+                       savedhost);
                need_pw = TRUE;
            }
 
            if (need_pw) {
                if (ssh_get_line) {
                    if (!ssh_get_line(pwprompt, password,
-                                      sizeof(password), TRUE)) {
+                                     sizeof(password), TRUE)) {
                        /*
                         * get_line failed to get a password (for
                         * example because one was supplied on the
@@ -3337,28 +3550,34 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                    pos = 0;
                    while (pos >= 0) {
                        crWaitUntilV(!ispkt);
-                       while (inlen--) switch (c = *in++) {
-                         case 10: case 13:
-                           password[pos] = 0;
-                           pos = -1;
-                           break;
-                         case 8: case 127:
-                           if (pos > 0)
-                               pos--;
-                           break;
-                         case 21: case 27:
-                           pos = 0;
-                           break;
-                         case 3: case 4:
-                           random_save_seed();
-                           exit(0);
-                           break;
-                         default:
-                           if (((c >= ' ' && c <= '~') ||
-                                ((unsigned char)c >= 160)) && pos < 40)
-                               password[pos++] = c;
-                           break;
-                       }
+                       while (inlen--)
+                           switch (c = *in++) {
+                             case 10:
+                             case 13:
+                               password[pos] = 0;
+                               pos = -1;
+                               break;
+                             case 8:
+                             case 127:
+                               if (pos > 0)
+                                   pos--;
+                               break;
+                             case 21:
+                             case 27:
+                               pos = 0;
+                               break;
+                             case 3:
+                             case 4:
+                               random_save_seed();
+                               exit(0);
+                               break;
+                             default:
+                               if (((c >= ' ' && c <= '~') ||
+                                    ((unsigned char) c >= 160))
+                                   && pos < 40)
+                                   password[pos++] = c;
+                               break;
+                           }
                    }
                    c_write_str("\r\n");
                }
@@ -3382,8 +3601,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                    /* Send a spurious AUTH_NONE to return to the top. */
                    ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                    ssh2_pkt_addstring(username);
-                   ssh2_pkt_addstring("ssh-connection");   /* service requested */
-                   ssh2_pkt_addstring("none");    /* method */
+                   ssh2_pkt_addstring("ssh-connection");       /* service requested */
+                   ssh2_pkt_addstring("none"); /* method */
                    ssh2_pkt_send();
                    type = AUTH_TYPE_NONE;
                } else {
@@ -3397,8 +3616,8 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                     */
                    ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                    ssh2_pkt_addstring(username);
-                   ssh2_pkt_addstring("ssh-connection");   /* service requested */
-                   ssh2_pkt_addstring("publickey");    /* method */
+                   ssh2_pkt_addstring("ssh-connection");       /* service requested */
+                   ssh2_pkt_addstring("publickey");    /* method */
                    ssh2_pkt_addbool(TRUE);
                    ssh2_pkt_addstring(key->alg->name);
                    blob = key->alg->public_blob(key->data, &blob_len);
@@ -3417,9 +3636,12 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                    sigdata_len = pktout.length - 5 + 4 + 20;
                    sigdata = smalloc(sigdata_len);
                    PUT_32BIT(sigdata, 20);
-                   memcpy(sigdata+4, ssh2_session_id, 20);
-                   memcpy(sigdata+24, pktout.data+5, pktout.length-5);
-                   blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
+                   memcpy(sigdata + 4, ssh2_session_id, 20);
+                   memcpy(sigdata + 24, pktout.data + 5,
+                          pktout.length - 5);
+                   blob =
+                       key->alg->sign(key->data, sigdata, sigdata_len,
+                                      &blob_len);
                    ssh2_pkt_addstring_start();
                    ssh2_pkt_addstring_data(blob, blob_len);
                    sfree(blob);
@@ -3445,7 +3667,7 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                 */
                ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
                ssh2_pkt_addstring(username);
-               ssh2_pkt_addstring("ssh-connection");   /* service requested */
+               ssh2_pkt_addstring("ssh-connection");   /* service requested */
                ssh2_pkt_addstring("password");
                ssh2_pkt_addbool(FALSE);
                ssh2_pkt_addstring(password);
@@ -3456,29 +3678,29 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                 * reason, we don't do this trick at all because we gain
                 * nothing by it.
                 */
-                if (cscipher) {
-                    int stringlen, i;
-
-                    stringlen = (256 - deferred_len);
-                    stringlen += cscipher->blksize - 1;
-                    stringlen -= (stringlen % cscipher->blksize);
-                    if (cscomp) {
-                        /*
-                         * Temporarily disable actual compression,
-                         * so we can guarantee to get this string
-                         * exactly the length we want it. The
-                         * compression-disabling routine should
-                         * return an integer indicating how many
-                         * bytes we should adjust our string length
-                         * by.
-                         */
-                        stringlen -= cscomp->disable_compression();
-                    }
+               if (cscipher) {
+                   int stringlen, i;
+
+                   stringlen = (256 - deferred_len);
+                   stringlen += cscipher->blksize - 1;
+                   stringlen -= (stringlen % cscipher->blksize);
+                   if (cscomp) {
+                       /*
+                        * Temporarily disable actual compression,
+                        * so we can guarantee to get this string
+                        * exactly the length we want it. The
+                        * compression-disabling routine should
+                        * return an integer indicating how many
+                        * bytes we should adjust our string length
+                        * by.
+                        */
+                       stringlen -= cscomp->disable_compression();
+                   }
                    ssh2_pkt_init(SSH2_MSG_IGNORE);
                    ssh2_pkt_addstring_start();
                    for (i = 0; i < stringlen; i++) {
-                        char c = (char)random_byte();
-                        ssh2_pkt_addstring_data(&c, 1);
+                       char c = (char) random_byte();
+                       ssh2_pkt_addstring_data(&c, 1);
                    }
                    ssh2_pkt_defer();
                }
@@ -3486,12 +3708,15 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
                logevent("Sent password");
                type = AUTH_TYPE_PASSWORD;
            } else {
-               c_write_str("No supported authentication methods left to try!\r\n");
-               logevent("No supported authentications offered. Disconnecting");
+               c_write_str
+                   ("No supported authentication methods left to try!\r\n");
+               logevent
+                   ("No supported authentications offered. Disconnecting");
                ssh2_pkt_init(SSH2_MSG_DISCONNECT);
                ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
-               ssh2_pkt_addstring("No supported authentication methods available");
-               ssh2_pkt_addstring("en");   /* language tag */
+               ssh2_pkt_addstring
+                   ("No supported authentication methods available");
+               ssh2_pkt_addstring("en");       /* language tag */
                ssh2_pkt_send();
                ssh_state = SSH_STATE_CLOSED;
                crReturnV;
@@ -3514,18 +3739,18 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
     ssh2_pkt_addstring("session");
     ssh2_pkt_adduint32(mainchan->localid);
-    ssh2_pkt_adduint32(0x8000UL);  /* our window size */
-    ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
+    ssh2_pkt_adduint32(0x8000UL);      /* our window size */
+    ssh2_pkt_adduint32(0x4000UL);      /* our max pkt size */
     ssh2_pkt_send();
     crWaitUntilV(ispkt);
     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
-        bombout(("Server refused to open a session"));
-        crReturnV;
-        /* FIXME: error data comes back in FAILURE packet */
+       bombout(("Server refused to open a session"));
+       crReturnV;
+       /* FIXME: error data comes back in FAILURE packet */
     }
     if (ssh2_pkt_getuint32() != mainchan->localid) {
-        bombout(("Server's channel confirmation cited wrong channel"));
-        crReturnV;
+       bombout(("Server's channel confirmation cited wrong channel"));
+       crReturnV;
     }
     mainchan->remoteid = ssh2_pkt_getuint32();
     mainchan->type = CHAN_MAINSESSION;
@@ -3541,393 +3766,406 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
      * Potentially enable X11 forwarding.
      */
     if (cfg.x11_forward) {
-        char proto[20], data[64];
-        logevent("Requesting X11 forwarding");
-        x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
-        ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
-        ssh2_pkt_adduint32(mainchan->remoteid);
-        ssh2_pkt_addstring("x11-req");
-        ssh2_pkt_addbool(1);           /* want reply */
-        ssh2_pkt_addbool(0);           /* many connections */
-        ssh2_pkt_addstring(proto);
-        ssh2_pkt_addstring(data);
-        ssh2_pkt_adduint32(0);         /* screen number */
-        ssh2_pkt_send();
-
-        do {
-            crWaitUntilV(ispkt);
-            if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                c->v2.remwindow += ssh2_pkt_getuint32();
-            }
-        } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
-
-        if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
-            if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-                bombout(("Server got confused by X11 forwarding request"));
-                crReturnV;
-            }
-            logevent("X11 forwarding refused");
-        } else {
-            logevent("X11 forwarding enabled");
+       char proto[20], data[64];
+       logevent("Requesting X11 forwarding");
+       x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
+       ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
+       ssh2_pkt_adduint32(mainchan->remoteid);
+       ssh2_pkt_addstring("x11-req");
+       ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_addbool(0);           /* many connections */
+       ssh2_pkt_addstring(proto);
+       ssh2_pkt_addstring(data);
+       ssh2_pkt_adduint32(0);         /* screen number */
+       ssh2_pkt_send();
+
+       do {
+           crWaitUntilV(ispkt);
+           if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               c->v2.remwindow += ssh2_pkt_getuint32();
+           }
+       } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
+
+       if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
+           if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
+               bombout(("Server got confused by X11 forwarding request"));
+               crReturnV;
+           }
+           logevent("X11 forwarding refused");
+       } else {
+           logevent("X11 forwarding enabled");
            ssh_X11_fwd_enabled = TRUE;
-        }
+       }
     }
 
     /*
      * Potentially enable agent forwarding.
      */
     if (cfg.agentfwd && agent_exists()) {
-        logevent("Requesting OpenSSH-style agent forwarding");
-        ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
-        ssh2_pkt_adduint32(mainchan->remoteid);
-        ssh2_pkt_addstring("auth-agent-req@openssh.com");
-        ssh2_pkt_addbool(1);           /* want reply */
-        ssh2_pkt_send();
-
-        do {
-            crWaitUntilV(ispkt);
-            if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                c->v2.remwindow += ssh2_pkt_getuint32();
-            }
-        } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
-
-        if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
-            if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-                bombout(("Server got confused by agent forwarding request"));
-                crReturnV;
-            }
-            logevent("Agent forwarding refused");
-        } else {
-            logevent("Agent forwarding enabled");
+       logevent("Requesting OpenSSH-style agent forwarding");
+       ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
+       ssh2_pkt_adduint32(mainchan->remoteid);
+       ssh2_pkt_addstring("auth-agent-req@openssh.com");
+       ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_send();
+
+       do {
+           crWaitUntilV(ispkt);
+           if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               c->v2.remwindow += ssh2_pkt_getuint32();
+           }
+       } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
+
+       if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
+           if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
+               bombout(
+                       ("Server got confused by agent forwarding request"));
+               crReturnV;
+           }
+           logevent("Agent forwarding refused");
+       } else {
+           logevent("Agent forwarding enabled");
            ssh_agentfwd_enabled = TRUE;
-        }
+       }
     }
 
     /*
      * Now allocate a pty for the session.
      */
     if (!cfg.nopty) {
-        ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
-        ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
-        ssh2_pkt_addstring("pty-req");
-        ssh2_pkt_addbool(1);           /* want reply */
-        ssh2_pkt_addstring(cfg.termtype);
-        ssh2_pkt_adduint32(cols);
-        ssh2_pkt_adduint32(rows);
-        ssh2_pkt_adduint32(0);         /* pixel width */
-        ssh2_pkt_adduint32(0);         /* pixel height */
-        ssh2_pkt_addstring_start();
-        ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
-        ssh2_pkt_send();
-        ssh_state = SSH_STATE_INTERMED;
-
-        do {
-            crWaitUntilV(ispkt);
-            if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                c->v2.remwindow += ssh2_pkt_getuint32();
-            }
-        } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
-
-        if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
-            if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-                bombout(("Server got confused by pty request"));
-                crReturnV;
-            }
-            c_write_str("Server refused to allocate pty\r\n");
-            ssh_editing = ssh_echoing = 1;
-        } else {
-            logevent("Allocated pty");
-        }
+       ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
+       ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
+       ssh2_pkt_addstring("pty-req");
+       ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_addstring(cfg.termtype);
+       ssh2_pkt_adduint32(cols);
+       ssh2_pkt_adduint32(rows);
+       ssh2_pkt_adduint32(0);         /* pixel width */
+       ssh2_pkt_adduint32(0);         /* pixel height */
+       ssh2_pkt_addstring_start();
+       ssh2_pkt_addstring_data("\0", 1);       /* TTY_OP_END, no special options */
+       ssh2_pkt_send();
+       ssh_state = SSH_STATE_INTERMED;
+
+       do {
+           crWaitUntilV(ispkt);
+           if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               c->v2.remwindow += ssh2_pkt_getuint32();
+           }
+       } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
+
+       if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
+           if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
+               bombout(("Server got confused by pty request"));
+               crReturnV;
+           }
+           c_write_str("Server refused to allocate pty\r\n");
+           ssh_editing = ssh_echoing = 1;
+       } else {
+           logevent("Allocated pty");
+       }
     } else {
-        ssh_editing = ssh_echoing = 1;
+       ssh_editing = ssh_echoing = 1;
     }
 
     /*
      * Start a shell or a remote command.
      */
     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
-    ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
+    ssh2_pkt_adduint32(mainchan->remoteid);    /* recipient channel */
     if (cfg.ssh_subsys) {
-        ssh2_pkt_addstring("subsystem");
-        ssh2_pkt_addbool(1);           /* want reply */
-        ssh2_pkt_addstring(cfg.remote_cmd_ptr);
+       ssh2_pkt_addstring("subsystem");
+       ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_addstring(cfg.remote_cmd_ptr);
     } else if (*cfg.remote_cmd_ptr) {
-        ssh2_pkt_addstring("exec");
-        ssh2_pkt_addbool(1);           /* want reply */
-        ssh2_pkt_addstring(cfg.remote_cmd_ptr);
+       ssh2_pkt_addstring("exec");
+       ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_addstring(cfg.remote_cmd_ptr);
     } else {
-        ssh2_pkt_addstring("shell");
-        ssh2_pkt_addbool(1);           /* want reply */
+       ssh2_pkt_addstring("shell");
+       ssh2_pkt_addbool(1);           /* want reply */
     }
     ssh2_pkt_send();
     do {
-        crWaitUntilV(ispkt);
-        if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-            unsigned i = ssh2_pkt_getuint32();
-            struct ssh_channel *c;
-            c = find234(ssh_channels, &i, ssh_channelfind);
-            if (!c)
-                continue;              /* nonexistent channel */
-            c->v2.remwindow += ssh2_pkt_getuint32();
-        }
+       crWaitUntilV(ispkt);
+       if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
+           unsigned i = ssh2_pkt_getuint32();
+           struct ssh_channel *c;
+           c = find234(ssh_channels, &i, ssh_channelfind);
+           if (!c)
+               continue;              /* nonexistent channel */
+           c->v2.remwindow += ssh2_pkt_getuint32();
+       }
     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
-        if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-            bombout(("Server got confused by shell/command request"));
-            crReturnV;
-        }
-        bombout(("Server refused to start a shell/command"));
-        crReturnV;
+       if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
+           bombout(("Server got confused by shell/command request"));
+           crReturnV;
+       }
+       bombout(("Server refused to start a shell/command"));
+       crReturnV;
     } else {
-        logevent("Started a shell/command");
+       logevent("Started a shell/command");
     }
 
     ssh_state = SSH_STATE_SESSION;
     if (size_needed)
        ssh_size();
     if (eof_needed)
-        ssh_special(TS_EOF);
+       ssh_special(TS_EOF);
 
     /*
      * Transfer data!
      */
-    ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
+    ldisc_send(NULL, 0);              /* cause ldisc to notice changes */
     ssh_send_ok = 1;
     while (1) {
-        static int try_send;
+       static int try_send;
        crReturnV;
-        try_send = FALSE;
+       try_send = FALSE;
        if (ispkt) {
            if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
-                pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
-                char *data;
-                int length;
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
-                    ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
-                    continue;          /* extended but not stderr */
-                ssh2_pkt_getstring(&data, &length);
-                if (data) {
-                    switch (c->type) {
-                      case CHAN_MAINSESSION:
-                        from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
-                                     data, length);
-                        break;
-                      case CHAN_X11:
-                        x11_send(c->u.x11.s, data, length);
-                        break;
+               pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
+               char *data;
+               int length;
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
+                   ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
+                   continue;          /* extended but not stderr */
+               ssh2_pkt_getstring(&data, &length);
+               if (data) {
+                   switch (c->type) {
+                     case CHAN_MAINSESSION:
+                       from_backend(pktin.type ==
+                                    SSH2_MSG_CHANNEL_EXTENDED_DATA, data,
+                                    length);
+                       break;
+                     case CHAN_X11:
+                       x11_send(c->u.x11.s, data, length);
+                       break;
                      case CHAN_AGENT:
-                        while (length > 0) {
-                            if (c->u.a.lensofar < 4) {
-                                int l = min(4 - c->u.a.lensofar, length);
-                                memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
-                                data += l; length -= l; c->u.a.lensofar += l;
-                            }
-                            if (c->u.a.lensofar == 4) {
-                                c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
-                                c->u.a.message = smalloc(c->u.a.totallen);
-                                memcpy(c->u.a.message, c->u.a.msglen, 4);
-                            }
-                            if (c->u.a.lensofar >= 4 && length > 0) {
-                                int l = min(c->u.a.totallen - c->u.a.lensofar,
-                                           length);
-                                memcpy(c->u.a.message + c->u.a.lensofar, data, l);
-                                data += l; length -= l; c->u.a.lensofar += l;
-                            }
-                            if (c->u.a.lensofar == c->u.a.totallen) {
-                                void *reply, *sentreply;
-                                int replylen;
-                                agent_query(c->u.a.message, c->u.a.totallen,
-                                            &reply, &replylen);
-                                if (reply)
-                                    sentreply = reply;
-                                else {
-                                    /* Fake SSH_AGENT_FAILURE. */
-                                    sentreply = "\0\0\0\1\5";
-                                    replylen = 5;
-                                }
-                               ssh2_add_channel_data(c, sentreply, replylen);
+                       while (length > 0) {
+                           if (c->u.a.lensofar < 4) {
+                               int l = min(4 - c->u.a.lensofar, length);
+                               memcpy(c->u.a.msglen + c->u.a.lensofar,
+                                      data, l);
+                               data += l;
+                               length -= l;
+                               c->u.a.lensofar += l;
+                           }
+                           if (c->u.a.lensofar == 4) {
+                               c->u.a.totallen =
+                                   4 + GET_32BIT(c->u.a.msglen);
+                               c->u.a.message = smalloc(c->u.a.totallen);
+                               memcpy(c->u.a.message, c->u.a.msglen, 4);
+                           }
+                           if (c->u.a.lensofar >= 4 && length > 0) {
+                               int l =
+                                   min(c->u.a.totallen - c->u.a.lensofar,
+                                       length);
+                               memcpy(c->u.a.message + c->u.a.lensofar,
+                                      data, l);
+                               data += l;
+                               length -= l;
+                               c->u.a.lensofar += l;
+                           }
+                           if (c->u.a.lensofar == c->u.a.totallen) {
+                               void *reply, *sentreply;
+                               int replylen;
+                               agent_query(c->u.a.message,
+                                           c->u.a.totallen, &reply,
+                                           &replylen);
+                               if (reply)
+                                   sentreply = reply;
+                               else {
+                                   /* Fake SSH_AGENT_FAILURE. */
+                                   sentreply = "\0\0\0\1\5";
+                                   replylen = 5;
+                               }
+                               ssh2_add_channel_data(c, sentreply,
+                                                     replylen);
                                try_send = TRUE;
-                                if (reply)
-                                    sfree(reply);
-                                sfree(c->u.a.message);
-                                c->u.a.lensofar = 0;
-                            }
-                        }
-                        break;
-                    }
-                    /*
-                     * Enlarge the window again at the remote
-                     * side, just in case it ever runs down and
-                     * they fail to send us any more data.
-                     */
-                    ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
-                    ssh2_pkt_adduint32(c->remoteid);
-                    ssh2_pkt_adduint32(length);
-                    ssh2_pkt_send();
-                }
+                               if (reply)
+                                   sfree(reply);
+                               sfree(c->u.a.message);
+                               c->u.a.lensofar = 0;
+                           }
+                       }
+                       break;
+                   }
+                   /*
+                    * Enlarge the window again at the remote
+                    * side, just in case it ever runs down and
+                    * they fail to send us any more data.
+                    */
+                   ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
+                   ssh2_pkt_adduint32(c->remoteid);
+                   ssh2_pkt_adduint32(length);
+                   ssh2_pkt_send();
+               }
            } else if (pktin.type == SSH2_MSG_DISCONNECT) {
-                ssh_state = SSH_STATE_CLOSED;
+               ssh_state = SSH_STATE_CLOSED;
                logevent("Received disconnect message");
-                crReturnV;
+               crReturnV;
            } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
-                continue;              /* exit status et al; ignore (FIXME?) */
+               continue;              /* exit status et al; ignore (FIXME?) */
            } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                
-                if (c->type == CHAN_X11) {
-                    /*
-                     * Remote EOF on an X11 channel means we should
-                     * wrap up and close the channel ourselves.
-                     */
-                    x11_close(c->u.x11.s);
-                    sshfwd_close(c);
-                } else if (c->type == CHAN_AGENT) {
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+
+               if (c->type == CHAN_X11) {
+                   /*
+                    * Remote EOF on an X11 channel means we should
+                    * wrap up and close the channel ourselves.
+                    */
+                   x11_close(c->u.x11.s);
+                   sshfwd_close(c);
+               } else if (c->type == CHAN_AGENT) {
                    sshfwd_close(c);
                }
            } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                if (c->closes == 0) {
-                    ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
-                    ssh2_pkt_adduint32(c->remoteid);
-                    ssh2_pkt_send();
-                }
-                /* Do pre-close processing on the channel. */
-                switch (c->type) {
-                  case CHAN_MAINSESSION:
-                    break;             /* nothing to see here, move along */
-                  case CHAN_X11:
-                    break;
-                  case CHAN_AGENT:
-                    break;
-                }
-                del234(ssh_channels, c);
-                sfree(c->v2.outbuffer);
-                sfree(c);
-
-                /*
-                 * See if that was the last channel left open.
-                 */
-                if (count234(ssh_channels) == 0) {
-                    logevent("All channels closed. Disconnecting");
-                    ssh2_pkt_init(SSH2_MSG_DISCONNECT);
-                    ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
-                    ssh2_pkt_addstring("All open channels closed");
-                    ssh2_pkt_addstring("en");   /* language tag */
-                    ssh2_pkt_send();
-                    ssh_state = SSH_STATE_CLOSED;
-                    crReturnV;
-                }
-                continue;              /* remote sends close; ignore (FIXME) */
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               if (c->closes == 0) {
+                   ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
+                   ssh2_pkt_adduint32(c->remoteid);
+                   ssh2_pkt_send();
+               }
+               /* Do pre-close processing on the channel. */
+               switch (c->type) {
+                 case CHAN_MAINSESSION:
+                   break;             /* nothing to see here, move along */
+                 case CHAN_X11:
+                   break;
+                 case CHAN_AGENT:
+                   break;
+               }
+               del234(ssh_channels, c);
+               sfree(c->v2.outbuffer);
+               sfree(c);
+
+               /*
+                * See if that was the last channel left open.
+                */
+               if (count234(ssh_channels) == 0) {
+                   logevent("All channels closed. Disconnecting");
+                   ssh2_pkt_init(SSH2_MSG_DISCONNECT);
+                   ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
+                   ssh2_pkt_addstring("All open channels closed");
+                   ssh2_pkt_addstring("en");   /* language tag */
+                   ssh2_pkt_send();
+                   ssh_state = SSH_STATE_CLOSED;
+                   crReturnV;
+               }
+               continue;              /* remote sends close; ignore (FIXME) */
            } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-                unsigned i = ssh2_pkt_getuint32();
-                struct ssh_channel *c;
-                c = find234(ssh_channels, &i, ssh_channelfind);
-                if (!c)
-                    continue;          /* nonexistent channel */
-                c->v2.remwindow += ssh2_pkt_getuint32();
-                try_send = TRUE;
+               unsigned i = ssh2_pkt_getuint32();
+               struct ssh_channel *c;
+               c = find234(ssh_channels, &i, ssh_channelfind);
+               if (!c)
+                   continue;          /* nonexistent channel */
+               c->v2.remwindow += ssh2_pkt_getuint32();
+               try_send = TRUE;
            } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
-                char *type;
-                int typelen;
-                char *error = NULL;
-                struct ssh_channel *c;
-                ssh2_pkt_getstring(&type, &typelen);
-                c = smalloc(sizeof(struct ssh_channel));
-
-                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 ) {
-                        error = "Unable to open an X11 connection";
-                    } else {
-                        c->type = CHAN_X11;
-                    }
-                } else if (typelen == 22 &&
+               char *type;
+               int typelen;
+               char *error = NULL;
+               struct ssh_channel *c;
+               ssh2_pkt_getstring(&type, &typelen);
+               c = smalloc(sizeof(struct ssh_channel));
+
+               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) {
+                       error = "Unable to open an X11 connection";
+                   } else {
+                       c->type = CHAN_X11;
+                   }
+               } else if (typelen == 22 &&
                           !memcmp(type, "auth-agent@openssh.com", 3)) {
-                    if (!ssh_agentfwd_enabled)
-                        error = "Agent forwarding is not enabled";
+                   if (!ssh_agentfwd_enabled)
+                       error = "Agent forwarding is not enabled";
                    else {
-                       c->type = CHAN_AGENT;   /* identify channel type */
+                       c->type = CHAN_AGENT;   /* identify channel type */
                        c->u.a.lensofar = 0;
-                    }
-                } else {
-                    error = "Unsupported channel type requested";
-                }
-
-                c->remoteid = ssh2_pkt_getuint32();
-                if (error) {
-                    ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
-                    ssh2_pkt_adduint32(c->remoteid);
-                    ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
-                    ssh2_pkt_addstring(error);
-                    ssh2_pkt_addstring("en");   /* language tag */
-                    ssh2_pkt_send();
-                    sfree(c);
-                } else {
-                    c->localid = alloc_channel_id();
-                    c->closes = 0;
-                    c->v2.remwindow = ssh2_pkt_getuint32();
-                    c->v2.remmaxpkt = ssh2_pkt_getuint32();
-                    c->v2.outbuffer = NULL;
-                    c->v2.outbuflen = c->v2.outbufsize = 0;
-                    add234(ssh_channels, c);
-                    ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
-                    ssh2_pkt_adduint32(c->remoteid);
-                    ssh2_pkt_adduint32(c->localid);
-                    ssh2_pkt_adduint32(0x8000UL);  /* our window size */
-                    ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
-                    ssh2_pkt_send();
-                }
+                   }
+               } else {
+                   error = "Unsupported channel type requested";
+               }
+
+               c->remoteid = ssh2_pkt_getuint32();
+               if (error) {
+                   ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
+                   ssh2_pkt_adduint32(c->remoteid);
+                   ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
+                   ssh2_pkt_addstring(error);
+                   ssh2_pkt_addstring("en");   /* language tag */
+                   ssh2_pkt_send();
+                   sfree(c);
+               } else {
+                   c->localid = alloc_channel_id();
+                   c->closes = 0;
+                   c->v2.remwindow = ssh2_pkt_getuint32();
+                   c->v2.remmaxpkt = ssh2_pkt_getuint32();
+                   c->v2.outbuffer = NULL;
+                   c->v2.outbuflen = c->v2.outbufsize = 0;
+                   add234(ssh_channels, c);
+                   ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
+                   ssh2_pkt_adduint32(c->remoteid);
+                   ssh2_pkt_adduint32(c->localid);
+                   ssh2_pkt_adduint32(0x8000UL);       /* our window size */
+                   ssh2_pkt_adduint32(0x4000UL);       /* our max pkt size */
+                   ssh2_pkt_send();
+               }
            } else {
                bombout(("Strange packet received: type %d", pktin.type));
-                crReturnV;
+               crReturnV;
            }
        } else {
-            /*
-             * We have spare data. Add it to the channel buffer.
-             */
-            ssh2_add_channel_data(mainchan, in, inlen);
-            try_send = TRUE;
+           /*
+            * We have spare data. Add it to the channel buffer.
+            */
+           ssh2_add_channel_data(mainchan, in, inlen);
+           try_send = TRUE;
+       }
+       if (try_send) {
+           int i;
+           struct ssh_channel *c;
+           /*
+            * Try to send data on all channels if we can.
+            */
+           for (i = 0; NULL != (c = index234(ssh_channels, i)); i++)
+               ssh2_try_send(c);
        }
-        if (try_send) {
-            int i;
-            struct ssh_channel *c;
-            /*
-             * Try to send data on all channels if we can.
-             */
-            for (i = 0; NULL != (c = index234(ssh_channels, i)); i++)
-                ssh2_try_send(c);
-        }
     }
 
     crFinishV;
@@ -3939,7 +4177,7 @@ static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
 {
     if (do_ssh2_transport(in, inlen, ispkt) == 0)
-        return;
+       return;
     do_ssh2_authconn(in, inlen, ispkt);
 }
 
@@ -3948,11 +4186,12 @@ static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
  *
  * Returns an error message, or NULL on success.
  */
-static char *ssh_init (char *host, int port, char **realhost) {
+static char *ssh_init(char *host, int port, char **realhost)
+{
     char *p;
-       
+
 #ifdef MSCRYPTOAPI
-    if(crypto_startup() == 0)
+    if (crypto_startup() == 0)
        return "Microsoft high encryption pack not installed!";
 #endif
 
@@ -3970,7 +4209,8 @@ static char *ssh_init (char *host, int port, char **realhost) {
 /*
  * Called to send data down the Telnet connection.
  */
-static void ssh_send (char *buf, int len) {
+static void ssh_send(char *buf, int len)
+{
     if (s == NULL || ssh_protocol == NULL)
        return;
 
@@ -3980,7 +4220,8 @@ static void ssh_send (char *buf, int len) {
 /*
  * Called to set the size of the window from SSH's POV.
  */
-static void ssh_size(void) {
+static void ssh_size(void)
+{
     switch (ssh_state) {
       case SSH_STATE_BEFORE_SIZE:
       case SSH_STATE_PREPACKET:
@@ -3990,24 +4231,24 @@ static void ssh_size(void) {
        size_needed = TRUE;            /* buffer for later */
        break;
       case SSH_STATE_SESSION:
-        if (!cfg.nopty) {
-            if (ssh_version == 1) {
-                send_packet(SSH1_CMSG_WINDOW_SIZE,
-                            PKT_INT, rows, PKT_INT, cols,
-                            PKT_INT, 0, PKT_INT, 0, PKT_END);
-            } else {
-                ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
-                ssh2_pkt_adduint32(mainchan->remoteid);
-                ssh2_pkt_addstring("window-change");
-                ssh2_pkt_addbool(0);
-                ssh2_pkt_adduint32(cols);
-                ssh2_pkt_adduint32(rows);
-                ssh2_pkt_adduint32(0);
-                ssh2_pkt_adduint32(0);
-                ssh2_pkt_send();
-            }
-        }
-        break;
+       if (!cfg.nopty) {
+           if (ssh_version == 1) {
+               send_packet(SSH1_CMSG_WINDOW_SIZE,
+                           PKT_INT, rows, PKT_INT, cols,
+                           PKT_INT, 0, PKT_INT, 0, PKT_END);
+           } else {
+               ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
+               ssh2_pkt_adduint32(mainchan->remoteid);
+               ssh2_pkt_addstring("window-change");
+               ssh2_pkt_addbool(0);
+               ssh2_pkt_adduint32(cols);
+               ssh2_pkt_adduint32(rows);
+               ssh2_pkt_adduint32(0);
+               ssh2_pkt_adduint32(0);
+               ssh2_pkt_send();
+           }
+       }
+       break;
     }
 }
 
@@ -4016,47 +4257,57 @@ static void ssh_size(void) {
  * can send an EOF and collect resulting output (e.g. `plink
  * hostname sort').
  */
-static void ssh_special (Telnet_Special code) {
+static void ssh_special(Telnet_Special code)
+{
     if (code == TS_EOF) {
-        if (ssh_state != SSH_STATE_SESSION) {
-            /*
-             * Buffer the EOF in case we are pre-SESSION, so we can
-             * send it as soon as we reach SESSION.
-             */
-            if (code == TS_EOF)
-                eof_needed = TRUE;
-            return;
-        }
-        if (ssh_version == 1) {
-            send_packet(SSH1_CMSG_EOF, PKT_END);
-        } else {
-            ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
-            ssh2_pkt_adduint32(mainchan->remoteid);
-            ssh2_pkt_send();
-        }
-        logevent("Sent EOF message");
+       if (ssh_state != SSH_STATE_SESSION) {
+           /*
+            * Buffer the EOF in case we are pre-SESSION, so we can
+            * send it as soon as we reach SESSION.
+            */
+           if (code == TS_EOF)
+               eof_needed = TRUE;
+           return;
+       }
+       if (ssh_version == 1) {
+           send_packet(SSH1_CMSG_EOF, PKT_END);
+       } else {
+           ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
+           ssh2_pkt_adduint32(mainchan->remoteid);
+           ssh2_pkt_send();
+       }
+       logevent("Sent EOF message");
     } else if (code == TS_PING) {
-        if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
-            return;
-        if (ssh_version == 1) {
-            send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
-        } else {
-            ssh2_pkt_init(SSH2_MSG_IGNORE);
-            ssh2_pkt_addstring_start();
-            ssh2_pkt_send();
-        }
+       if (ssh_state == SSH_STATE_CLOSED
+           || ssh_state == SSH_STATE_PREPACKET) return;
+       if (ssh_version == 1) {
+           send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
+       } else {
+           ssh2_pkt_init(SSH2_MSG_IGNORE);
+           ssh2_pkt_addstring_start();
+           ssh2_pkt_send();
+       }
     } else {
-        /* do nothing */
+       /* do nothing */
     }
 }
 
-static Socket ssh_socket(void) { return s; }
+static Socket ssh_socket(void)
+{
+    return s;
+}
 
-static int ssh_sendok(void) { return ssh_send_ok; }
+static int ssh_sendok(void)
+{
+    return ssh_send_ok;
+}
 
-static int ssh_ldisc(int option) {
-    if (option == LD_ECHO) return ssh_echoing;
-    if (option == LD_EDIT) return ssh_editing;
+static int ssh_ldisc(int option)
+{
+    if (option == LD_ECHO)
+       return ssh_echoing;
+    if (option == LD_EDIT)
+       return ssh_editing;
     return FALSE;
 }
 
diff --git a/ssh.h b/ssh.h
index fb6392f..014c406 100644 (file)
--- a/ssh.h
+++ b/ssh.h
@@ -76,7 +76,7 @@ struct MD5Context {
 
 void MD5Init(struct MD5Context *context);
 void MD5Update(struct MD5Context *context, unsigned char const *buf,
-               unsigned len);
+              unsigned len);
 void MD5Final(unsigned char digest[16], struct MD5Context *context);
 
 typedef struct {
@@ -86,25 +86,25 @@ typedef struct {
     uint32 lenhi, lenlo;
 } SHA_State;
 
-void SHA_Init(SHA_State *s);
-void SHA_Bytes(SHA_State *s, void *p, int len);
-void SHA_Final(SHA_State *s, unsigned char *output);
+void SHA_Init(SHA_State * s);
+void SHA_Bytes(SHA_State * s, void *p, int len);
+void SHA_Final(SHA_State * s, unsigned char *output);
 void SHA_Simple(void *p, int len, unsigned char *output);
 
 struct ssh_cipher {
-    void (*sesskey)(unsigned char *key);   /* for ssh 1 */
-    void (*encrypt)(unsigned char *blk, int len);
-    void (*decrypt)(unsigned char *blk, int len);
+    void (*sesskey) (unsigned char *key);      /* for ssh 1 */
+    void (*encrypt) (unsigned char *blk, int len);
+    void (*decrypt) (unsigned char *blk, int len);
     int blksize;
 };
 
 struct ssh2_cipher {
-    void (*setcsiv)(unsigned char *key);   /* for ssh 2 */
-    void (*setcskey)(unsigned char *key);   /* for ssh 2 */
-    void (*setsciv)(unsigned char *key);   /* for ssh 2 */
-    void (*setsckey)(unsigned char *key);   /* for ssh 2 */
-    void (*encrypt)(unsigned char *blk, int len);
-    void (*decrypt)(unsigned char *blk, int len);
+    void (*setcsiv) (unsigned char *key);      /* for ssh 2 */
+    void (*setcskey) (unsigned char *key);     /* for ssh 2 */
+    void (*setsciv) (unsigned char *key);      /* for ssh 2 */
+    void (*setsckey) (unsigned char *key);     /* for ssh 2 */
+    void (*encrypt) (unsigned char *blk, int len);
+    void (*decrypt) (unsigned char *blk, int len);
     char *name;
     int blksize;
     int keylen;
@@ -116,10 +116,10 @@ struct ssh2_ciphers {
 };
 
 struct ssh_mac {
-    void (*setcskey)(unsigned char *key);
-    void (*setsckey)(unsigned char *key);
-    void (*generate)(unsigned char *blk, int len, unsigned long seq);
-    int (*verify)(unsigned char *blk, int len, unsigned long seq);
+    void (*setcskey) (unsigned char *key);
+    void (*setsckey) (unsigned char *key);
+    void (*generate) (unsigned char *blk, int len, unsigned long seq);
+    int (*verify) (unsigned char *blk, int len, unsigned long seq);
     char *name;
     int len;
 };
@@ -136,32 +136,33 @@ struct ssh_kex {
 };
 
 struct ssh_signkey {
-    void *(*newkey)(char *data, int len);
-    void (*freekey)(void *key);
-    char *(*fmtkey)(void *key);
-    unsigned char *(*public_blob)(void *key, int *len);
-    unsigned char *(*private_blob)(void *key, int *len);
-    void *(*createkey)(unsigned char *pub_blob, int pub_len,
-                      unsigned char *priv_blob, int priv_len);
-    void *(*openssh_createkey)(unsigned char **blob, int *len);
-    int (*openssh_fmtkey)(void *key, unsigned char *blob, int len);
-    char *(*fingerprint)(void *key);
-    int (*verifysig)(void *key, char *sig, int siglen,
-                    char *data, int datalen);
-    unsigned char *(*sign)(void *key, char *data, int datalen, int *siglen);
+    void *(*newkey) (char *data, int len);
+    void (*freekey) (void *key);
+    char *(*fmtkey) (void *key);
+    unsigned char *(*public_blob) (void *key, int *len);
+    unsigned char *(*private_blob) (void *key, int *len);
+    void *(*createkey) (unsigned char *pub_blob, int pub_len,
+                       unsigned char *priv_blob, int priv_len);
+    void *(*openssh_createkey) (unsigned char **blob, int *len);
+    int (*openssh_fmtkey) (void *key, unsigned char *blob, int len);
+    char *(*fingerprint) (void *key);
+    int (*verifysig) (void *key, char *sig, int siglen,
+                     char *data, int datalen);
+    unsigned char *(*sign) (void *key, char *data, int datalen,
+                           int *siglen);
     char *name;
-    char *keytype;                     /* for host key cache */
+    char *keytype;                    /* for host key cache */
 };
 
 struct ssh_compress {
     char *name;
-    void (*compress_init)(void);
-    int (*compress)(unsigned char *block, int len,
-                   unsigned char **outblock, int *outlen);
-    void (*decompress_init)(void);
-    int (*decompress)(unsigned char *block, int len,
-                     unsigned char **outblock, int *outlen);
-    int (*disable_compression)(void);
+    void (*compress_init) (void);
+    int (*compress) (unsigned char *block, int len,
+                    unsigned char **outblock, int *outlen);
+    void (*decompress_init) (void);
+    int (*decompress) (unsigned char *block, int len,
+                      unsigned char **outblock, int *outlen);
+    int (*disable_compression) (void);
 };
 
 struct ssh2_userkey {
@@ -190,14 +191,14 @@ extern const struct ssh_mac ssh_sha1_buggy;
 extern char sshver[];
 
 #ifndef MSCRYPTOAPI
-void SHATransform(word32 *digest, word32 *data);
+void SHATransform(word32 * digest, word32 * data);
 #endif
 
 int random_byte(void);
 void random_add_noise(void *noise, int length);
 void random_add_heavynoise(void *noise, int length);
 
-void logevent (char *);
+void logevent(char *);
 
 Bignum copybn(Bignum b);
 Bignum bn_power_2(int n);
@@ -209,7 +210,7 @@ Bignum modmul(Bignum a, Bignum b, Bignum mod);
 void decbn(Bignum n);
 extern Bignum Zero, One;
 Bignum bignum_from_bytes(unsigned char *data, int nbytes);
-int ssh1_read_bignum(unsigned char *data, Bignum *result);
+int ssh1_read_bignum(unsigned char *data, Bignum * result);
 int bignum_bitcount(Bignum bn);
 int ssh1_bignum_length(Bignum bn);
 int ssh2_bignum_length(Bignum bn);
@@ -246,24 +247,29 @@ extern struct ssh2_userkey ssh2_wrong_passphrase;
 
 int ssh2_userkey_encrypted(char *filename, char **comment);
 struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase);
-char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len);
-int ssh2_save_userkey(char *filename, struct ssh2_userkey *key, char *passphrase);
+char *ssh2_userkey_loadpub(char *filename, char **algorithm,
+                          int *pub_blob_len);
+int ssh2_save_userkey(char *filename, struct ssh2_userkey *key,
+                     char *passphrase);
 
 int keyfile_version(char *filename);
 
 void des3_decrypt_pubkey(unsigned char *key, unsigned char *blk, int len);
 void des3_encrypt_pubkey(unsigned char *key, unsigned char *blk, int len);
-void aes256_encrypt_pubkey(unsigned char *key, unsigned char *blk, int len);
-void aes256_decrypt_pubkey(unsigned char *key, unsigned char *blk, int len);
+void aes256_encrypt_pubkey(unsigned char *key, unsigned char *blk,
+                          int len);
+void aes256_decrypt_pubkey(unsigned char *key, unsigned char *blk,
+                          int len);
 
 /*
  * For progress updates in the key generation utility.
  */
-typedef void (*progfn_t)(void *param, int phase, int progress);
+typedef void (*progfn_t) (void *param, int phase, int progress);
 
-int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn, void *pfnparam);
-Bignum primegen(int bits, int modulus, int residue,
-                int phase, progfn_t pfn, void *pfnparam);
+int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn,
+                void *pfnparam);
+Bignum primegen(int bits, int modulus, int residue, int phase,
+               progfn_t pfn, void *pfnparam);
 
 /*
  * zlib compression.
@@ -284,7 +290,7 @@ int zlib_decompress_block(unsigned char *block, int len,
 #define SSH1_AGENT_RSA_RESPONSE               4
 #define SSH1_AGENTC_ADD_RSA_IDENTITY          7
 #define SSH1_AGENTC_REMOVE_RSA_IDENTITY       8
-#define SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9   /* openssh private? */
+#define SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9        /* openssh private? */
 
 /*
  * Messages common to SSH1 and OpenSSH's SSH2.
index 361cc64..f227c56 100644 (file)
--- a/sshaes.c
+++ b/sshaes.c
 typedef struct AESContext AESContext;
 
 struct AESContext {
-    word32 keysched[(MAX_NR+1) * MAX_NB];
-    word32 invkeysched[(MAX_NR+1) * MAX_NB];
-    void (*encrypt)(AESContext *ctx, word32 *block);
-    void (*decrypt)(AESContext *ctx, word32 *block);
+    word32 keysched[(MAX_NR + 1) * MAX_NB];
+    word32 invkeysched[(MAX_NR + 1) * MAX_NB];
+    void (*encrypt) (AESContext * ctx, word32 * block);
+    void (*decrypt) (AESContext * ctx, word32 * block);
     word32 iv[MAX_NB];
     int Nb, Nr;
 };
@@ -96,59 +96,115 @@ static const word32 D0[256], D1[256], D2[256], D3[256];
  * Core encrypt routines, expecting word32 inputs read big-endian
  * from the byte-oriented input stream.
  */
-static void aes_encrypt_nb_4(AESContext *ctx, word32 *block) {
+static void aes_encrypt_nb_4(AESContext * ctx, word32 * block)
+{
     int i;
     static const int C1 = 1, C2 = 2, C3 = 3, Nb = 4;
     word32 *keysched = ctx->keysched;
     word32 newstate[4];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_4;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2); MAKEWORD(3);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
     }
     ADD_ROUND_KEY_4;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2); LASTWORD(3);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
     ADD_ROUND_KEY_4;
 }
-static void aes_encrypt_nb_6(AESContext *ctx, word32 *block) {
+static void aes_encrypt_nb_6(AESContext * ctx, word32 * block)
+{
     int i;
     static const int C1 = 1, C2 = 2, C3 = 3, Nb = 6;
     word32 *keysched = ctx->keysched;
     word32 newstate[6];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_6;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2);
-       MAKEWORD(3); MAKEWORD(4); MAKEWORD(5);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2);
-       MOVEWORD(3); MOVEWORD(4); MOVEWORD(5);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MAKEWORD(4);
+       MAKEWORD(5);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
+       MOVEWORD(4);
+       MOVEWORD(5);
     }
     ADD_ROUND_KEY_6;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2);
-    LASTWORD(3); LASTWORD(4); LASTWORD(5);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2);
-    MOVEWORD(3); MOVEWORD(4); MOVEWORD(5);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    LASTWORD(4);
+    LASTWORD(5);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
+    MOVEWORD(4);
+    MOVEWORD(5);
     ADD_ROUND_KEY_6;
 }
-static void aes_encrypt_nb_8(AESContext *ctx, word32 *block) {
+static void aes_encrypt_nb_8(AESContext * ctx, word32 * block)
+{
     int i;
     static const int C1 = 1, C2 = 3, C3 = 4, Nb = 8;
     word32 *keysched = ctx->keysched;
     word32 newstate[8];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_8;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2); MAKEWORD(3);
-       MAKEWORD(4); MAKEWORD(5); MAKEWORD(6); MAKEWORD(7);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
-       MOVEWORD(4); MOVEWORD(5); MOVEWORD(6); MOVEWORD(7);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MAKEWORD(4);
+       MAKEWORD(5);
+       MAKEWORD(6);
+       MAKEWORD(7);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
+       MOVEWORD(4);
+       MOVEWORD(5);
+       MOVEWORD(6);
+       MOVEWORD(7);
     }
     ADD_ROUND_KEY_8;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2); LASTWORD(3);
-    LASTWORD(4); LASTWORD(5); LASTWORD(6); LASTWORD(7);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
-    MOVEWORD(4); MOVEWORD(5); MOVEWORD(6); MOVEWORD(7);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    LASTWORD(4);
+    LASTWORD(5);
+    LASTWORD(6);
+    LASTWORD(7);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
+    MOVEWORD(4);
+    MOVEWORD(5);
+    MOVEWORD(6);
+    MOVEWORD(7);
     ADD_ROUND_KEY_8;
 }
+
 #undef MAKEWORD
 #undef LASTWORD
 
@@ -169,59 +225,115 @@ static void aes_encrypt_nb_8(AESContext *ctx, word32 *block) {
  * Core decrypt routines, expecting word32 inputs read big-endian
  * from the byte-oriented input stream.
  */
-static void aes_decrypt_nb_4(AESContext *ctx, word32 *block) {
+static void aes_decrypt_nb_4(AESContext * ctx, word32 * block)
+{
     int i;
-    static const int C1 = 4-1, C2 = 4-2, C3 = 4-3, Nb = 4;
+    static const int C1 = 4 - 1, C2 = 4 - 2, C3 = 4 - 3, Nb = 4;
     word32 *keysched = ctx->invkeysched;
     word32 newstate[4];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_4;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2); MAKEWORD(3);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
     }
     ADD_ROUND_KEY_4;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2); LASTWORD(3);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
     ADD_ROUND_KEY_4;
 }
-static void aes_decrypt_nb_6(AESContext *ctx, word32 *block) {
+static void aes_decrypt_nb_6(AESContext * ctx, word32 * block)
+{
     int i;
-    static const int C1 = 6-1, C2 = 6-2, C3 = 6-3, Nb = 6;
+    static const int C1 = 6 - 1, C2 = 6 - 2, C3 = 6 - 3, Nb = 6;
     word32 *keysched = ctx->invkeysched;
     word32 newstate[6];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_6;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2);
-       MAKEWORD(3); MAKEWORD(4); MAKEWORD(5);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2);
-       MOVEWORD(3); MOVEWORD(4); MOVEWORD(5);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MAKEWORD(4);
+       MAKEWORD(5);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
+       MOVEWORD(4);
+       MOVEWORD(5);
     }
     ADD_ROUND_KEY_6;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2);
-    LASTWORD(3); LASTWORD(4); LASTWORD(5);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2);
-    MOVEWORD(3); MOVEWORD(4); MOVEWORD(5);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    LASTWORD(4);
+    LASTWORD(5);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
+    MOVEWORD(4);
+    MOVEWORD(5);
     ADD_ROUND_KEY_6;
 }
-static void aes_decrypt_nb_8(AESContext *ctx, word32 *block) {
+static void aes_decrypt_nb_8(AESContext * ctx, word32 * block)
+{
     int i;
-    static const int C1 = 8-1, C2 = 8-3, C3 = 8-4, Nb = 8;
+    static const int C1 = 8 - 1, C2 = 8 - 3, C3 = 8 - 4, Nb = 8;
     word32 *keysched = ctx->invkeysched;
     word32 newstate[8];
-    for (i = 0; i < ctx->Nr-1; i++) {
+    for (i = 0; i < ctx->Nr - 1; i++) {
        ADD_ROUND_KEY_8;
-       MAKEWORD(0); MAKEWORD(1); MAKEWORD(2); MAKEWORD(3);
-       MAKEWORD(4); MAKEWORD(5); MAKEWORD(6); MAKEWORD(7);
-       MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
-       MOVEWORD(4); MOVEWORD(5); MOVEWORD(6); MOVEWORD(7);
+       MAKEWORD(0);
+       MAKEWORD(1);
+       MAKEWORD(2);
+       MAKEWORD(3);
+       MAKEWORD(4);
+       MAKEWORD(5);
+       MAKEWORD(6);
+       MAKEWORD(7);
+       MOVEWORD(0);
+       MOVEWORD(1);
+       MOVEWORD(2);
+       MOVEWORD(3);
+       MOVEWORD(4);
+       MOVEWORD(5);
+       MOVEWORD(6);
+       MOVEWORD(7);
     }
     ADD_ROUND_KEY_8;
-    LASTWORD(0); LASTWORD(1); LASTWORD(2); LASTWORD(3);
-    LASTWORD(4); LASTWORD(5); LASTWORD(6); LASTWORD(7);
-    MOVEWORD(0); MOVEWORD(1); MOVEWORD(2); MOVEWORD(3);
-    MOVEWORD(4); MOVEWORD(5); MOVEWORD(6); MOVEWORD(7);
+    LASTWORD(0);
+    LASTWORD(1);
+    LASTWORD(2);
+    LASTWORD(3);
+    LASTWORD(4);
+    LASTWORD(5);
+    LASTWORD(6);
+    LASTWORD(7);
+    MOVEWORD(0);
+    MOVEWORD(1);
+    MOVEWORD(2);
+    MOVEWORD(3);
+    MOVEWORD(4);
+    MOVEWORD(5);
+    MOVEWORD(6);
+    MOVEWORD(7);
     ADD_ROUND_KEY_8;
 }
+
 #undef MAKEWORD
 #undef LASTWORD
 
@@ -829,8 +941,9 @@ static const word32 D3[256] = {
  * bytes; each can be either 16 (128-bit), 24 (192-bit), or 32
  * (256-bit).
  */
-void aes_setup(AESContext *ctx, int blocklen,
-              unsigned char *key, int keylen) {
+void aes_setup(AESContext * ctx, int blocklen,
+              unsigned char *key, int keylen)
+{
     int i, j, Nk, rconst;
 
     assert(blocklen == 16 || blocklen == 24 || blocklen == 32);
@@ -857,16 +970,16 @@ void aes_setup(AESContext *ctx, int blocklen,
      * Now do the key setup itself.
      */
     rconst = 1;
-    for (i = 0; i < (ctx->Nr+1) * ctx->Nb; i++) {
+    for (i = 0; i < (ctx->Nr + 1) * ctx->Nb; i++) {
        if (i < Nk)
-           ctx->keysched[i] = GET_32BIT_MSB_FIRST(key + 4*i);
+           ctx->keysched[i] = GET_32BIT_MSB_FIRST(key + 4 * i);
        else {
-           word32 temp = ctx->keysched[i-1];
+           word32 temp = ctx->keysched[i - 1];
            if (i % Nk == 0) {
                int a, b, c, d;
                a = (temp >> 16) & 0xFF;
-               b = (temp >>  8) & 0xFF;
-               c = (temp >>  0) & 0xFF;
+               b = (temp >> 8) & 0xFF;
+               c = (temp >> 0) & 0xFF;
                d = (temp >> 24) & 0xFF;
                temp = Sbox[a] ^ rconst;
                temp = (temp << 8) | Sbox[b];
@@ -877,14 +990,14 @@ void aes_setup(AESContext *ctx, int blocklen,
                int a, b, c, d;
                a = (temp >> 24) & 0xFF;
                b = (temp >> 16) & 0xFF;
-               c = (temp >>  8) & 0xFF;
-               d = (temp >>  0) & 0xFF;
+               c = (temp >> 8) & 0xFF;
+               d = (temp >> 0) & 0xFF;
                temp = Sbox[a];
                temp = (temp << 8) | Sbox[b];
                temp = (temp << 8) | Sbox[c];
-               temp = (temp << 8) | Sbox[d];           
+               temp = (temp << 8) | Sbox[d];
            }
-           ctx->keysched[i] = ctx->keysched[i-Nk] ^ temp;
+           ctx->keysched[i] = ctx->keysched[i - Nk] ^ temp;
        }
     }
 
@@ -905,8 +1018,8 @@ void aes_setup(AESContext *ctx, int blocklen,
                int a, b, c, d;
                a = (temp >> 24) & 0xFF;
                b = (temp >> 16) & 0xFF;
-               c = (temp >>  8) & 0xFF;
-               d = (temp >>  0) & 0xFF;
+               c = (temp >> 8) & 0xFF;
+               d = (temp >> 0) & 0xFF;
                temp = D0[Sbox[a]];
                temp ^= D1[Sbox[b]];
                temp ^= D2[Sbox[c]];
@@ -917,15 +1030,18 @@ void aes_setup(AESContext *ctx, int blocklen,
     }
 }
 
-static void aes_encrypt(AESContext *ctx, word32 *block) {
+static void aes_encrypt(AESContext * ctx, word32 * block)
+{
     ctx->encrypt(ctx, block);
 }
 
-static void aes_decrypt(AESContext *ctx, word32 *block) {
+static void aes_decrypt(AESContext * ctx, word32 * block)
+{
     ctx->decrypt(ctx, block);
 }
 
-static void aes_encrypt_cbc(unsigned char *blk, int len, AESContext *ctx) {
+static void aes_encrypt_cbc(unsigned char *blk, int len, AESContext * ctx)
+{
     word32 iv[4];
     int i;
 
@@ -935,18 +1051,19 @@ static void aes_encrypt_cbc(unsigned char *blk, int len, AESContext *ctx) {
 
     while (len > 0) {
        for (i = 0; i < 4; i++)
-            iv[i] ^= GET_32BIT_MSB_FIRST(blk+4*i);
+           iv[i] ^= GET_32BIT_MSB_FIRST(blk + 4 * i);
        aes_encrypt(ctx, iv);
-        for (i = 0; i < 4; i++)
-            PUT_32BIT_MSB_FIRST(blk+4*i, iv[i]);
-        blk += 16;
-        len -= 16;
+       for (i = 0; i < 4; i++)
+           PUT_32BIT_MSB_FIRST(blk + 4 * i, iv[i]);
+       blk += 16;
+       len -= 16;
     }
 
     memcpy(ctx->iv, iv, sizeof(iv));
 }
 
-static void aes_decrypt_cbc(unsigned char *blk, int len, AESContext *ctx) {
+static void aes_decrypt_cbc(unsigned char *blk, int len, AESContext * ctx)
+{
     word32 iv[4], x[4], ct[4];
     int i;
 
@@ -956,14 +1073,14 @@ static void aes_decrypt_cbc(unsigned char *blk, int len, AESContext *ctx) {
 
     while (len > 0) {
        for (i = 0; i < 4; i++)
-            x[i] = ct[i] = GET_32BIT_MSB_FIRST(blk+4*i);
+           x[i] = ct[i] = GET_32BIT_MSB_FIRST(blk + 4 * i);
        aes_decrypt(ctx, x);
        for (i = 0; i < 4; i++) {
-            PUT_32BIT_MSB_FIRST(blk+4*i, iv[i] ^ x[i]);
-            iv[i] = ct[i];
-        }
-        blk += 16;
-        len -= 16;
+           PUT_32BIT_MSB_FIRST(blk + 4 * i, iv[i] ^ x[i]);
+           iv[i] = ct[i];
+       }
+       blk += 16;
+       len -= 16;
     }
 
     memcpy(ctx->iv, iv, sizeof(iv));
@@ -971,64 +1088,76 @@ static void aes_decrypt_cbc(unsigned char *blk, int len, AESContext *ctx) {
 
 static AESContext csctx, scctx;
 
-static void aes128_cskey(unsigned char *key) {
+static void aes128_cskey(unsigned char *key)
+{
     aes_setup(&csctx, 16, key, 16);
     logevent("Initialised AES-128 client->server encryption");
 }
 
-static void aes128_sckey(unsigned char *key) {
+static void aes128_sckey(unsigned char *key)
+{
     aes_setup(&scctx, 16, key, 16);
     logevent("Initialised AES-128 server->client encryption");
 }
 
-static void aes192_cskey(unsigned char *key) {
+static void aes192_cskey(unsigned char *key)
+{
     aes_setup(&csctx, 16, key, 24);
     logevent("Initialised AES-192 client->server encryption");
 }
 
-static void aes192_sckey(unsigned char *key) {
+static void aes192_sckey(unsigned char *key)
+{
     aes_setup(&scctx, 16, key, 24);
     logevent("Initialised AES-192 server->client encryption");
 }
 
-static void aes256_cskey(unsigned char *key) {
+static void aes256_cskey(unsigned char *key)
+{
     aes_setup(&csctx, 16, key, 32);
     logevent("Initialised AES-256 client->server encryption");
 }
 
-static void aes256_sckey(unsigned char *key) {
+static void aes256_sckey(unsigned char *key)
+{
     aes_setup(&scctx, 16, key, 32);
     logevent("Initialised AES-256 server->client encryption");
 }
 
-static void aes_csiv(unsigned char *iv) {
+static void aes_csiv(unsigned char *iv)
+{
     int i;
     for (i = 0; i < 4; i++)
-        csctx.iv[i] = GET_32BIT_MSB_FIRST(iv+4*i);
+       csctx.iv[i] = GET_32BIT_MSB_FIRST(iv + 4 * i);
 }
 
-static void aes_sciv(unsigned char *iv) {
+static void aes_sciv(unsigned char *iv)
+{
     int i;
     for (i = 0; i < 4; i++)
-        scctx.iv[i] = GET_32BIT_MSB_FIRST(iv+4*i);
+       scctx.iv[i] = GET_32BIT_MSB_FIRST(iv + 4 * i);
 }
 
-static void aes_ssh2_encrypt_blk(unsigned char *blk, int len) {
+static void aes_ssh2_encrypt_blk(unsigned char *blk, int len)
+{
     aes_encrypt_cbc(blk, len, &csctx);
 }
 
-static void aes_ssh2_decrypt_blk(unsigned char *blk, int len) {
+static void aes_ssh2_decrypt_blk(unsigned char *blk, int len)
+{
     aes_decrypt_cbc(blk, len, &scctx);
 }
 
-void aes256_encrypt_pubkey(unsigned char *key, unsigned char *blk, int len) {
+void aes256_encrypt_pubkey(unsigned char *key, unsigned char *blk, int len)
+{
     AESContext ctx;
     aes_setup(&ctx, 16, key, 32);
     memset(ctx.iv, 0, sizeof(ctx.iv));
     aes_encrypt_cbc(blk, len, &ctx);
 }
 
-void aes256_decrypt_pubkey(unsigned char *key, unsigned char *blk, int len) {
+void aes256_decrypt_pubkey(unsigned char *key, unsigned char *blk, int len)
+{
     AESContext ctx;
     aes_setup(&ctx, 16, key, 32);
     memset(ctx.iv, 0, sizeof(ctx.iv));
index f3c49b8..a4b43de 100644 (file)
@@ -235,8 +235,9 @@ static const word32 sbox3[] = {
 #define F(x) Fprime( ((x>>24)&0xFF), ((x>>16)&0xFF), ((x>>8)&0xFF), (x&0xFF) )
 #define ROUND(n) ( xL ^= P[n], t = xL, xL = F(xL) ^ xR, xR = t )
 
-static void blowfish_encrypt(word32 xL, word32 xR, word32 *output,
-                             BlowfishContext *ctx) {
+static void blowfish_encrypt(word32 xL, word32 xR, word32 * output,
+                            BlowfishContext * ctx)
+{
     word32 *S0 = ctx->S0;
     word32 *S1 = ctx->S1;
     word32 *S2 = ctx->S2;
@@ -267,8 +268,9 @@ static void blowfish_encrypt(word32 xL, word32 xR, word32 *output,
     output[1] = xL;
 }
 
-static void blowfish_decrypt(word32 xL, word32 xR, word32 *output,
-                             BlowfishContext *ctx) {
+static void blowfish_decrypt(word32 xL, word32 xR, word32 * output,
+                            BlowfishContext * ctx)
+{
     word32 *S0 = ctx->S0;
     word32 *S1 = ctx->S1;
     word32 *S2 = ctx->S2;
@@ -300,107 +302,120 @@ static void blowfish_decrypt(word32 xL, word32 xR, word32 *output,
 }
 
 static void blowfish_lsb_encrypt_cbc(unsigned char *blk, int len,
-                                     BlowfishContext *ctx) {
+                                    BlowfishContext * ctx)
+{
     word32 xL, xR, out[2], iv0, iv1;
 
     assert((len & 7) == 0);
 
-    iv0 = ctx->iv0; iv1 = ctx->iv1;
+    iv0 = ctx->iv0;
+    iv1 = ctx->iv1;
 
     while (len > 0) {
-        xL = GET_32BIT_LSB_FIRST(blk);
-        xR = GET_32BIT_LSB_FIRST(blk+4);
-        iv0 ^= xL;
-        iv1 ^= xR;
-        blowfish_encrypt(iv0, iv1, out, ctx);
-        iv0 = out[0];
-        iv1 = out[1];
-        PUT_32BIT_LSB_FIRST(blk, iv0);
-        PUT_32BIT_LSB_FIRST(blk+4, iv1);
-        blk += 8;
-        len -= 8;
+       xL = GET_32BIT_LSB_FIRST(blk);
+       xR = GET_32BIT_LSB_FIRST(blk + 4);
+       iv0 ^= xL;
+       iv1 ^= xR;
+       blowfish_encrypt(iv0, iv1, out, ctx);
+       iv0 = out[0];
+       iv1 = out[1];
+       PUT_32BIT_LSB_FIRST(blk, iv0);
+       PUT_32BIT_LSB_FIRST(blk + 4, iv1);
+       blk += 8;
+       len -= 8;
     }
 
-    ctx->iv0 = iv0; ctx->iv1 = iv1;
+    ctx->iv0 = iv0;
+    ctx->iv1 = iv1;
 }
 
 static void blowfish_lsb_decrypt_cbc(unsigned char *blk, int len,
-                                     BlowfishContext *ctx) {
+                                    BlowfishContext * ctx)
+{
     word32 xL, xR, out[2], iv0, iv1;
 
     assert((len & 7) == 0);
 
-    iv0 = ctx->iv0; iv1 = ctx->iv1;
+    iv0 = ctx->iv0;
+    iv1 = ctx->iv1;
 
     while (len > 0) {
-        xL = GET_32BIT_LSB_FIRST(blk);
-        xR = GET_32BIT_LSB_FIRST(blk+4);
-        blowfish_decrypt(xL, xR, out, ctx);
-        iv0 ^= out[0];
-        iv1 ^= out[1];
-        PUT_32BIT_LSB_FIRST(blk, iv0);
-        PUT_32BIT_LSB_FIRST(blk+4, iv1);
-        iv0 = xL;
-        iv1 = xR;
-        blk += 8;
-        len -= 8;
+       xL = GET_32BIT_LSB_FIRST(blk);
+       xR = GET_32BIT_LSB_FIRST(blk + 4);
+       blowfish_decrypt(xL, xR, out, ctx);
+       iv0 ^= out[0];
+       iv1 ^= out[1];
+       PUT_32BIT_LSB_FIRST(blk, iv0);
+       PUT_32BIT_LSB_FIRST(blk + 4, iv1);
+       iv0 = xL;
+       iv1 = xR;
+       blk += 8;
+       len -= 8;
     }
 
-    ctx->iv0 = iv0; ctx->iv1 = iv1;
+    ctx->iv0 = iv0;
+    ctx->iv1 = iv1;
 }
 
 static void blowfish_msb_encrypt_cbc(unsigned char *blk, int len,
-                                     BlowfishContext *ctx) {
+                                    BlowfishContext * ctx)
+{
     word32 xL, xR, out[2], iv0, iv1;
 
     assert((len & 7) == 0);
 
-    iv0 = ctx->iv0; iv1 = ctx->iv1;
+    iv0 = ctx->iv0;
+    iv1 = ctx->iv1;
 
     while (len > 0) {
-        xL = GET_32BIT_MSB_FIRST(blk);
-        xR = GET_32BIT_MSB_FIRST(blk+4);
-        iv0 ^= xL;
-        iv1 ^= xR;
-        blowfish_encrypt(iv0, iv1, out, ctx);
-        iv0 = out[0];
-        iv1 = out[1];
-        PUT_32BIT_MSB_FIRST(blk, iv0);
-        PUT_32BIT_MSB_FIRST(blk+4, iv1);
-        blk += 8;
-        len -= 8;
+       xL = GET_32BIT_MSB_FIRST(blk);
+       xR = GET_32BIT_MSB_FIRST(blk + 4);
+       iv0 ^= xL;
+       iv1 ^= xR;
+       blowfish_encrypt(iv0, iv1, out, ctx);
+       iv0 = out[0];
+       iv1 = out[1];
+       PUT_32BIT_MSB_FIRST(blk, iv0);
+       PUT_32BIT_MSB_FIRST(blk + 4, iv1);
+       blk += 8;
+       len -= 8;
     }
 
-    ctx->iv0 = iv0; ctx->iv1 = iv1;
+    ctx->iv0 = iv0;
+    ctx->iv1 = iv1;
 }
 
 static void blowfish_msb_decrypt_cbc(unsigned char *blk, int len,
-                                     BlowfishContext *ctx) {
+                                    BlowfishContext * ctx)
+{
     word32 xL, xR, out[2], iv0, iv1;
 
     assert((len & 7) == 0);
 
-    iv0 = ctx->iv0; iv1 = ctx->iv1;
+    iv0 = ctx->iv0;
+    iv1 = ctx->iv1;
 
     while (len > 0) {
-        xL = GET_32BIT_MSB_FIRST(blk);
-        xR = GET_32BIT_MSB_FIRST(blk+4);
-        blowfish_decrypt(xL, xR, out, ctx);
-        iv0 ^= out[0];
-        iv1 ^= out[1];
-        PUT_32BIT_MSB_FIRST(blk, iv0);
-        PUT_32BIT_MSB_FIRST(blk+4, iv1);
-        iv0 = xL;
-        iv1 = xR;
-        blk += 8;
-        len -= 8;
+       xL = GET_32BIT_MSB_FIRST(blk);
+       xR = GET_32BIT_MSB_FIRST(blk + 4);
+       blowfish_decrypt(xL, xR, out, ctx);
+       iv0 ^= out[0];
+       iv1 ^= out[1];
+       PUT_32BIT_MSB_FIRST(blk, iv0);
+       PUT_32BIT_MSB_FIRST(blk + 4, iv1);
+       iv0 = xL;
+       iv1 = xR;
+       blk += 8;
+       len -= 8;
     }
 
-    ctx->iv0 = iv0; ctx->iv1 = iv1;
+    ctx->iv0 = iv0;
+    ctx->iv1 = iv1;
 }
 
-static void blowfish_setkey(BlowfishContext *ctx,
-                            const unsigned char *key, short keybytes) {
+static void blowfish_setkey(BlowfishContext * ctx,
+                           const unsigned char *key, short keybytes)
+{
     word32 *S0 = ctx->S0;
     word32 *S1 = ctx->S1;
     word32 *S2 = ctx->S2;
@@ -410,42 +425,50 @@ static void blowfish_setkey(BlowfishContext *ctx,
     int i;
 
     for (i = 0; i < 18; i++) {
-        P[i] = parray[i];
-        P[i] ^= ((word32)(unsigned char)(key[ (i*4+0) % keybytes ])) << 24;
-        P[i] ^= ((word32)(unsigned char)(key[ (i*4+1) % keybytes ])) << 16;
-        P[i] ^= ((word32)(unsigned char)(key[ (i*4+2) % keybytes ])) << 8;
-        P[i] ^= ((word32)(unsigned char)(key[ (i*4+3) % keybytes ]));
+       P[i] = parray[i];
+       P[i] ^=
+           ((word32) (unsigned char) (key[(i * 4 + 0) % keybytes])) << 24;
+       P[i] ^=
+           ((word32) (unsigned char) (key[(i * 4 + 1) % keybytes])) << 16;
+       P[i] ^=
+           ((word32) (unsigned char) (key[(i * 4 + 2) % keybytes])) << 8;
+       P[i] ^= ((word32) (unsigned char) (key[(i * 4 + 3) % keybytes]));
     }
 
     for (i = 0; i < 256; i++) {
-        S0[i] = sbox0[i];
-        S1[i] = sbox1[i];
-        S2[i] = sbox2[i];
-        S3[i] = sbox3[i];
+       S0[i] = sbox0[i];
+       S1[i] = sbox1[i];
+       S2[i] = sbox2[i];
+       S3[i] = sbox3[i];
     }
 
     str[0] = str[1] = 0;
 
     for (i = 0; i < 18; i += 2) {
-        blowfish_encrypt(str[0], str[1], str, ctx);
-        P[i] = str[0]; P[i+1] = str[1];
+       blowfish_encrypt(str[0], str[1], str, ctx);
+       P[i] = str[0];
+       P[i + 1] = str[1];
     }
 
     for (i = 0; i < 256; i += 2) {
-        blowfish_encrypt(str[0], str[1], str, ctx);
-        S0[i] = str[0]; S0[i+1] = str[1];
+       blowfish_encrypt(str[0], str[1], str, ctx);
+       S0[i] = str[0];
+       S0[i + 1] = str[1];
     }
     for (i = 0; i < 256; i += 2) {
-        blowfish_encrypt(str[0], str[1], str, ctx);
-        S1[i] = str[0]; S1[i+1] = str[1];
+       blowfish_encrypt(str[0], str[1], str, ctx);
+       S1[i] = str[0];
+       S1[i + 1] = str[1];
     }
     for (i = 0; i < 256; i += 2) {
-        blowfish_encrypt(str[0], str[1], str, ctx);
-        S2[i] = str[0]; S2[i+1] = str[1];
+       blowfish_encrypt(str[0], str[1], str, ctx);
+       S2[i] = str[0];
+       S2[i + 1] = str[1];
     }
     for (i = 0; i < 256; i += 2) {
-        blowfish_encrypt(str[0], str[1], str, ctx);
-        S3[i] = str[0]; S3[i+1] = str[1];
+       blowfish_encrypt(str[0], str[1], str, ctx);
+       S3[i] = str[0];
+       S3[i + 1] = str[1];
     }
 }
 
@@ -454,31 +477,31 @@ static void blowfish_setkey(BlowfishContext *ctx,
 #define SSH_SESSION_KEY_LENGTH 32
 static BlowfishContext ectx, dctx;
 
-static void blowfish_cskey(unsigned char *key) 
+static void blowfish_cskey(unsigned char *key)
 {
     blowfish_setkey(&ectx, key, 16);
     logevent("Initialised Blowfish client->server encryption");
 }
 
-static void blowfish_sckey(unsigned char *key) 
+static void blowfish_sckey(unsigned char *key)
 {
     blowfish_setkey(&dctx, key, 16);
     logevent("Initialised Blowfish server->client encryption");
 }
 
-static void blowfish_csiv(unsigned char *key) 
+static void blowfish_csiv(unsigned char *key)
 {
     ectx.iv0 = GET_32BIT_MSB_FIRST(key);
-    ectx.iv1 = GET_32BIT_MSB_FIRST(key+4);
+    ectx.iv1 = GET_32BIT_MSB_FIRST(key + 4);
 }
 
-static void blowfish_sciv(unsigned char *key) 
+static void blowfish_sciv(unsigned char *key)
 {
     dctx.iv0 = GET_32BIT_MSB_FIRST(key);
-    dctx.iv1 = GET_32BIT_MSB_FIRST(key+4);
+    dctx.iv1 = GET_32BIT_MSB_FIRST(key + 4);
 }
 
-static void blowfish_sesskey(unsigned char *key) 
+static void blowfish_sesskey(unsigned char *key)
 {
     blowfish_setkey(&ectx, key, SSH_SESSION_KEY_LENGTH);
     ectx.iv0 = 0;
diff --git a/sshbn.c b/sshbn.c
index 2fd98f9..0d0fce3 100644 (file)
--- a/sshbn.c
+++ b/sshbn.c
@@ -6,7 +6,7 @@
 #include <stdlib.h>
 #include <string.h>
 
-#if 0 // use PuTTY main debugging for diagbn()
+#if 0                                 // use PuTTY main debugging for diagbn()
 #include <windows.h>
 #include "putty.h"
 #define debugprint debug
@@ -38,28 +38,33 @@ unsigned short bnOne[2] = { 1, 1 };
 
 Bignum Zero = bnZero, One = bnOne;
 
-static Bignum newbn(int length) {
-    Bignum b = smalloc((length+1)*sizeof(unsigned short));
+static Bignum newbn(int length)
+{
+    Bignum b = smalloc((length + 1) * sizeof(unsigned short));
     if (!b)
        abort();                       /* FIXME */
-    memset(b, 0, (length+1)*sizeof(*b));
+    memset(b, 0, (length + 1) * sizeof(*b));
     b[0] = length;
     return b;
 }
 
-void bn_restore_invariant(Bignum b) {
-    while (b[0] > 1 && b[b[0]] == 0) b[0]--;
+void bn_restore_invariant(Bignum b)
+{
+    while (b[0] > 1 && b[b[0]] == 0)
+       b[0]--;
 }
 
-Bignum copybn(Bignum orig) {
-    Bignum b = smalloc((orig[0]+1)*sizeof(unsigned short));
+Bignum copybn(Bignum orig)
+{
+    Bignum b = smalloc((orig[0] + 1) * sizeof(unsigned short));
     if (!b)
        abort();                       /* FIXME */
-    memcpy(b, orig, (orig[0]+1)*sizeof(*b));
+    memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
     return b;
 }
 
-void freebn(Bignum b) {
+void freebn(Bignum b)
+{
     /*
      * Burn the evidence, just in case.
      */
@@ -67,8 +72,9 @@ void freebn(Bignum b) {
     sfree(b);
 }
 
-Bignum bn_power_2(int n) {
-    Bignum ret = newbn(n/16+1);
+Bignum bn_power_2(int n)
+{
+    Bignum ret = newbn(n / 16 + 1);
     bignum_set_bit(ret, n, 1);
     return ret;
 }
@@ -79,12 +85,12 @@ Bignum bn_power_2(int n) {
  * Result is returned in the first 2*len words of c.
  */
 static void internal_mul(unsigned short *a, unsigned short *b,
-                         unsigned short *c, int len)
+                        unsigned short *c, int len)
 {
     int i, j;
     unsigned long ai, t;
 
-    for (j = 0; j < 2*len; j++)
+    for (j = 0; j < 2 * len; j++)
        c[j] = 0;
 
     for (i = len - 1; i >= 0; i--) {
@@ -92,16 +98,17 @@ static void internal_mul(unsigned short *a, unsigned short *b,
        t = 0;
        for (j = len - 1; j >= 0; j--) {
            t += ai * (unsigned long) b[j];
-           t += (unsigned long) c[i+j+1];
-           c[i+j+1] = (unsigned short)t;
+           t += (unsigned long) c[i + j + 1];
+           c[i + j + 1] = (unsigned short) t;
            t = t >> 16;
        }
-       c[i] = (unsigned short)t;
+       c[i] = (unsigned short) t;
     }
 }
 
 static void internal_add_shifted(unsigned short *number,
-                                unsigned n, int shift) {
+                                unsigned n, int shift)
+{
     int word = 1 + (shift / 16);
     int bshift = shift % 16;
     unsigned long addend;
@@ -109,10 +116,10 @@ static void internal_add_shifted(unsigned short *number,
     addend = n << bshift;
 
     while (addend) {
-        addend += number[word];
-        number[word] = (unsigned short) addend & 0xFFFF;
-        addend >>= 16;
-        word++;
+       addend += number[word];
+       number[word] = (unsigned short) addend & 0xFFFF;
+       addend >>= 16;
+       word++;
     }
 }
 
@@ -127,8 +134,8 @@ static void internal_add_shifted(unsigned short *number,
  * left by `qshift' before adding into quot.
  */
 static void internal_mod(unsigned short *a, int alen,
-                         unsigned short *m, int mlen,
-                         unsigned short *quot, int qshift)
+                        unsigned short *m, int mlen,
+                        unsigned short *quot, int qshift)
 {
     unsigned short m0, m1;
     unsigned int h;
@@ -136,25 +143,25 @@ static void internal_mod(unsigned short *a, int alen,
 
     m0 = m[0];
     if (mlen > 1)
-        m1 = m[1];
+       m1 = m[1];
     else
-        m1 = 0;
+       m1 = 0;
 
-    for (i = 0; i <= alen-mlen; i++) {
+    for (i = 0; i <= alen - mlen; i++) {
        unsigned long t;
        unsigned int q, r, c, ai1;
 
        if (i == 0) {
            h = 0;
        } else {
-           h = a[i-1];
-           a[i-1] = 0;
+           h = a[i - 1];
+           a[i - 1] = 0;
        }
 
-        if (i == alen-1)
-            ai1 = 0;
-        else
-            ai1 = a[i+1];
+       if (i == alen - 1)
+           ai1 = 0;
+       else
+           ai1 = a[i + 1];
 
        /* Find q = h:a[i] / m0 */
        t = ((unsigned long) h << 16) + a[i];
@@ -162,25 +169,25 @@ static void internal_mod(unsigned short *a, int alen,
        r = t % m0;
 
        /* Refine our estimate of q by looking at
-        h:a[i]:a[i+1] / m0:m1 */
-       t = (long) m1 * (long) q;
+          h:a[i]:a[i+1] / m0:m1 */
+       t = (long) m1 *(long) q;
        if (t > ((unsigned long) r << 16) + ai1) {
            q--;
            t -= m1;
-           r = (r + m0) & 0xffff; /* overflow? */
-           if (r >= (unsigned long)m0 &&
-                t > ((unsigned long) r << 16) + ai1)
-               q--;
+           r = (r + m0) & 0xffff;     /* overflow? */
+           if (r >= (unsigned long) m0 &&
+               t > ((unsigned long) r << 16) + ai1) q--;
        }
 
        /* Subtract q * m from a[i...] */
        c = 0;
        for (k = mlen - 1; k >= 0; k--) {
-           t = (long) q * (long) m[k];
+           t = (long) q *(long) m[k];
            t += c;
            c = t >> 16;
-           if ((unsigned short) t > a[i+k]) c++;
-           a[i+k] -= (unsigned short) t;
+           if ((unsigned short) t > a[i + k])
+               c++;
+           a[i + k] -= (unsigned short) t;
        }
 
        /* Add back m in case of borrow */
@@ -188,14 +195,14 @@ static void internal_mod(unsigned short *a, int alen,
            t = 0;
            for (k = mlen - 1; k >= 0; k--) {
                t += m[k];
-               t += a[i+k];
-               a[i+k] = (unsigned short)t;
+               t += a[i + k];
+               a[i + k] = (unsigned short) t;
                t = t >> 16;
            }
-            q--;
+           q--;
        }
-        if (quot)
-            internal_add_shifted(quot, q, qshift + 16 * (alen-mlen-i));
+       if (quot)
+           internal_add_shifted(quot, q, qshift + 16 * (alen - mlen - i));
     }
 }
 
@@ -216,74 +223,95 @@ Bignum modpow(Bignum base, Bignum exp, Bignum mod)
     /* We use big endian internally */
     mlen = mod[0];
     m = smalloc(mlen * sizeof(unsigned short));
-    for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
+    for (j = 0; j < mlen; j++)
+       m[j] = mod[mod[0] - j];
 
     /* Shift m left to make msb bit set */
     for (mshift = 0; mshift < 15; mshift++)
-       if ((m[0] << mshift) & 0x8000) break;
+       if ((m[0] << mshift) & 0x8000)
+           break;
     if (mshift) {
        for (i = 0; i < mlen - 1; i++)
-           m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
-       m[mlen-1] = m[mlen-1] << mshift;
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
+       m[mlen - 1] = m[mlen - 1] << mshift;
     }
 
     /* Allocate n of size mlen, copy base to n */
     n = smalloc(mlen * sizeof(unsigned short));
     i = mlen - base[0];
-    for (j = 0; j < i; j++) n[j] = 0;
-    for (j = 0; j < base[0]; j++) n[i+j] = base[base[0] - j];
+    for (j = 0; j < i; j++)
+       n[j] = 0;
+    for (j = 0; j < base[0]; j++)
+       n[i + j] = base[base[0] - j];
 
     /* Allocate a and b of size 2*mlen. Set a = 1 */
     a = smalloc(2 * mlen * sizeof(unsigned short));
     b = smalloc(2 * mlen * sizeof(unsigned short));
-    for (i = 0; i < 2*mlen; i++) a[i] = 0;
-    a[2*mlen-1] = 1;
+    for (i = 0; i < 2 * mlen; i++)
+       a[i] = 0;
+    a[2 * mlen - 1] = 1;
 
     /* Skip leading zero bits of exp. */
-    i = 0; j = 15;
+    i = 0;
+    j = 15;
     while (i < exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
        j--;
-       if (j < 0) { i++; j = 15; }
+       if (j < 0) {
+           i++;
+           j = 15;
+       }
     }
 
     /* Main computation */
     while (i < exp[0]) {
        while (j >= 0) {
            internal_mul(a + mlen, a + mlen, b, mlen);
-           internal_mod(b, mlen*2, m, mlen, NULL, 0);
+           internal_mod(b, mlen * 2, m, mlen, NULL, 0);
            if ((exp[exp[0] - i] & (1 << j)) != 0) {
                internal_mul(b + mlen, n, a, mlen);
-               internal_mod(a, mlen*2, m, mlen, NULL, 0);
+               internal_mod(a, mlen * 2, m, mlen, NULL, 0);
            } else {
                unsigned short *t;
-               t = a;  a = b;  b = t;
+               t = a;
+               a = b;
+               b = t;
            }
            j--;
        }
-       i++; j = 15;
+       i++;
+       j = 15;
     }
 
     /* Fixup result in case the modulus was shifted */
     if (mshift) {
-       for (i = mlen - 1; i < 2*mlen - 1; i++)
-           a[i] = (a[i] << mshift) | (a[i+1] >> (16-mshift));
-       a[2*mlen-1] = a[2*mlen-1] << mshift;
-       internal_mod(a, mlen*2, m, mlen, NULL, 0);
-       for (i = 2*mlen - 1; i >= mlen; i--)
-           a[i] = (a[i] >> mshift) | (a[i-1] << (16-mshift));
+       for (i = mlen - 1; i < 2 * mlen - 1; i++)
+           a[i] = (a[i] << mshift) | (a[i + 1] >> (16 - mshift));
+       a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
+       internal_mod(a, mlen * 2, m, mlen, NULL, 0);
+       for (i = 2 * mlen - 1; i >= mlen; i--)
+           a[i] = (a[i] >> mshift) | (a[i - 1] << (16 - mshift));
     }
 
     /* Copy result to buffer */
     result = newbn(mod[0]);
     for (i = 0; i < mlen; i++)
-       result[result[0] - i] = a[i+mlen];
-    while (result[0] > 1 && result[result[0]] == 0) result[0]--;
+       result[result[0] - i] = a[i + mlen];
+    while (result[0] > 1 && result[result[0]] == 0)
+       result[0]--;
 
     /* Free temporary arrays */
-    for (i = 0; i < 2*mlen; i++) a[i] = 0; sfree(a);
-    for (i = 0; i < 2*mlen; i++) b[i] = 0; sfree(b);
-    for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
-    for (i = 0; i < mlen; i++) n[i] = 0; sfree(n);
+    for (i = 0; i < 2 * mlen; i++)
+       a[i] = 0;
+    sfree(a);
+    for (i = 0; i < 2 * mlen; i++)
+       b[i] = 0;
+    sfree(b);
+    for (i = 0; i < mlen; i++)
+       m[i] = 0;
+    sfree(m);
+    for (i = 0; i < mlen; i++)
+       n[i] = 0;
+    sfree(n);
 
     return result;
 }
@@ -304,15 +332,17 @@ Bignum modmul(Bignum p, Bignum q, Bignum mod)
     /* We use big endian internally */
     mlen = mod[0];
     m = smalloc(mlen * sizeof(unsigned short));
-    for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
+    for (j = 0; j < mlen; j++)
+       m[j] = mod[mod[0] - j];
 
     /* Shift m left to make msb bit set */
     for (mshift = 0; mshift < 15; mshift++)
-       if ((m[0] << mshift) & 0x8000) break;
+       if ((m[0] << mshift) & 0x8000)
+           break;
     if (mshift) {
        for (i = 0; i < mlen - 1; i++)
-           m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
-       m[mlen-1] = m[mlen-1] << mshift;
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
+       m[mlen - 1] = m[mlen - 1] << mshift;
     }
 
     pqlen = (p[0] > q[0] ? p[0] : q[0]);
@@ -320,44 +350,57 @@ Bignum modmul(Bignum p, Bignum q, Bignum mod)
     /* Allocate n of size pqlen, copy p to n */
     n = smalloc(pqlen * sizeof(unsigned short));
     i = pqlen - p[0];
-    for (j = 0; j < i; j++) n[j] = 0;
-    for (j = 0; j < p[0]; j++) n[i+j] = p[p[0] - j];
+    for (j = 0; j < i; j++)
+       n[j] = 0;
+    for (j = 0; j < p[0]; j++)
+       n[i + j] = p[p[0] - j];
 
     /* Allocate o of size pqlen, copy q to o */
     o = smalloc(pqlen * sizeof(unsigned short));
     i = pqlen - q[0];
-    for (j = 0; j < i; j++) o[j] = 0;
-    for (j = 0; j < q[0]; j++) o[i+j] = q[q[0] - j];
+    for (j = 0; j < i; j++)
+       o[j] = 0;
+    for (j = 0; j < q[0]; j++)
+       o[i + j] = q[q[0] - j];
 
     /* Allocate a of size 2*pqlen for result */
     a = smalloc(2 * pqlen * sizeof(unsigned short));
 
     /* Main computation */
     internal_mul(n, o, a, pqlen);
-    internal_mod(a, pqlen*2, m, mlen, NULL, 0);
+    internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
 
     /* Fixup result in case the modulus was shifted */
     if (mshift) {
-       for (i = 2*pqlen - mlen - 1; i < 2*pqlen - 1; i++)
-           a[i] = (a[i] << mshift) | (a[i+1] >> (16-mshift));
-       a[2*pqlen-1] = a[2*pqlen-1] << mshift;
-       internal_mod(a, pqlen*2, m, mlen, NULL, 0);
-       for (i = 2*pqlen - 1; i >= 2*pqlen - mlen; i--)
-           a[i] = (a[i] >> mshift) | (a[i-1] << (16-mshift));
+       for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
+           a[i] = (a[i] << mshift) | (a[i + 1] >> (16 - mshift));
+       a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
+       internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
+       for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
+           a[i] = (a[i] >> mshift) | (a[i - 1] << (16 - mshift));
     }
 
     /* Copy result to buffer */
-    rlen = (mlen < pqlen*2 ? mlen : pqlen*2);
+    rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
     result = newbn(rlen);
     for (i = 0; i < rlen; i++)
-       result[result[0] - i] = a[i+2*pqlen-rlen];
-    while (result[0] > 1 && result[result[0]] == 0) result[0]--;
+       result[result[0] - i] = a[i + 2 * pqlen - rlen];
+    while (result[0] > 1 && result[result[0]] == 0)
+       result[0]--;
 
     /* Free temporary arrays */
-    for (i = 0; i < 2*pqlen; i++) a[i] = 0; sfree(a);
-    for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
-    for (i = 0; i < pqlen; i++) n[i] = 0; sfree(n);
-    for (i = 0; i < pqlen; i++) o[i] = 0; sfree(o);
+    for (i = 0; i < 2 * pqlen; i++)
+       a[i] = 0;
+    sfree(a);
+    for (i = 0; i < mlen; i++)
+       m[i] = 0;
+    sfree(m);
+    for (i = 0; i < pqlen; i++)
+       n[i] = 0;
+    sfree(n);
+    for (i = 0; i < pqlen; i++)
+       o[i] = 0;
+    sfree(o);
 
     return result;
 }
@@ -378,25 +421,30 @@ void bigmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
     /* We use big endian internally */
     mlen = mod[0];
     m = smalloc(mlen * sizeof(unsigned short));
-    for (j = 0; j < mlen; j++) m[j] = mod[mod[0] - j];
+    for (j = 0; j < mlen; j++)
+       m[j] = mod[mod[0] - j];
 
     /* Shift m left to make msb bit set */
     for (mshift = 0; mshift < 15; mshift++)
-       if ((m[0] << mshift) & 0x8000) break;
+       if ((m[0] << mshift) & 0x8000)
+           break;
     if (mshift) {
        for (i = 0; i < mlen - 1; i++)
-           m[i] = (m[i] << mshift) | (m[i+1] >> (16-mshift));
-       m[mlen-1] = m[mlen-1] << mshift;
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (16 - mshift));
+       m[mlen - 1] = m[mlen - 1] << mshift;
     }
 
     plen = p[0];
     /* Ensure plen > mlen */
-    if (plen <= mlen) plen = mlen+1;
+    if (plen <= mlen)
+       plen = mlen + 1;
 
     /* Allocate n of size plen, copy p to n */
     n = smalloc(plen * sizeof(unsigned short));
-    for (j = 0; j < plen; j++) n[j] = 0;
-    for (j = 1; j <= p[0]; j++) n[plen-j] = p[j];
+    for (j = 0; j < plen; j++)
+       n[j] = 0;
+    for (j = 1; j <= p[0]; j++)
+       n[plen - j] = p[j];
 
     /* Main computation */
     internal_mod(n, plen, m, mlen, quotient, mshift);
@@ -404,52 +452,59 @@ void bigmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
     /* Fixup result in case the modulus was shifted */
     if (mshift) {
        for (i = plen - mlen - 1; i < plen - 1; i++)
-           n[i] = (n[i] << mshift) | (n[i+1] >> (16-mshift));
-       n[plen-1] = n[plen-1] << mshift;
+           n[i] = (n[i] << mshift) | (n[i + 1] >> (16 - mshift));
+       n[plen - 1] = n[plen - 1] << mshift;
        internal_mod(n, plen, m, mlen, quotient, 0);
        for (i = plen - 1; i >= plen - mlen; i--)
-           n[i] = (n[i] >> mshift) | (n[i-1] << (16-mshift));
+           n[i] = (n[i] >> mshift) | (n[i - 1] << (16 - mshift));
     }
 
     /* Copy result to buffer */
     for (i = 1; i <= result[0]; i++) {
-        int j = plen-i;
-        result[i] = j>=0 ? n[j] : 0;
+       int j = plen - i;
+       result[i] = j >= 0 ? n[j] : 0;
     }
 
     /* Free temporary arrays */
-    for (i = 0; i < mlen; i++) m[i] = 0; sfree(m);
-    for (i = 0; i < plen; i++) n[i] = 0; sfree(n);
+    for (i = 0; i < mlen; i++)
+       m[i] = 0;
+    sfree(m);
+    for (i = 0; i < plen; i++)
+       n[i] = 0;
+    sfree(n);
 }
 
 /*
  * Decrement a number.
  */
-void decbn(Bignum bn) {
+void decbn(Bignum bn)
+{
     int i = 1;
     while (i < bn[0] && bn[i] == 0)
-        bn[i++] = 0xFFFF;
+       bn[i++] = 0xFFFF;
     bn[i]--;
 }
 
-Bignum bignum_from_bytes(unsigned char *data, int nbytes) {
+Bignum bignum_from_bytes(unsigned char *data, int nbytes)
+{
     Bignum result;
     int w, i;
 
-    w = (nbytes+1)/2;                 /* bytes -> words */
+    w = (nbytes + 1) / 2;             /* bytes -> words */
 
     result = newbn(w);
-    for (i=1; i<=w; i++)
-        result[i] = 0;
-    for (i=nbytes; i-- ;) {
-        unsigned char byte = *data++;
-        if (i & 1)
-            result[1+i/2] |= byte<<8;
-        else
-            result[1+i/2] |= byte;
+    for (i = 1; i <= w; i++)
+       result[i] = 0;
+    for (i = nbytes; i--;) {
+       unsigned char byte = *data++;
+       if (i & 1)
+           result[1 + i / 2] |= byte << 8;
+       else
+           result[1 + i / 2] |= byte;
     }
 
-    while (result[0] > 1 && result[result[0]] == 0) result[0]--;
+    while (result[0] > 1 && result[result[0]] == 0)
+       result[0]--;
     return result;
 }
 
@@ -457,18 +512,19 @@ Bignum bignum_from_bytes(unsigned char *data, int nbytes) {
  * Read an ssh1-format bignum from a data buffer. Return the number
  * of bytes consumed.
  */
-int ssh1_read_bignum(unsigned char *data, Bignum *result) {
+int ssh1_read_bignum(unsigned char *data, Bignum * result)
+{
     unsigned char *p = data;
     int i;
     int w, b;
 
     w = 0;
-    for (i=0; i<2; i++)
-        w = (w << 8) + *p++;
-    b = (w+7)/8;                       /* bits -> bytes */
+    for (i = 0; i < 2; i++)
+       w = (w << 8) + *p++;
+    b = (w + 7) / 8;                  /* bits -> bytes */
 
-    if (!result)                       /* just return length */
-        return b + 2;
+    if (!result)                      /* just return length */
+       return b + 2;
 
     *result = bignum_from_bytes(p, b);
 
@@ -478,62 +534,68 @@ int ssh1_read_bignum(unsigned char *data, Bignum *result) {
 /*
  * Return the bit count of a bignum, for ssh1 encoding.
  */
-int bignum_bitcount(Bignum bn) {
+int bignum_bitcount(Bignum bn)
+{
     int bitcount = bn[0] * 16 - 1;
-    while (bitcount >= 0 && (bn[bitcount/16+1] >> (bitcount % 16)) == 0)
-        bitcount--;
+    while (bitcount >= 0
+          && (bn[bitcount / 16 + 1] >> (bitcount % 16)) == 0) bitcount--;
     return bitcount + 1;
 }
 
 /*
  * Return the byte length of a bignum when ssh1 encoded.
  */
-int ssh1_bignum_length(Bignum bn) {
-    return 2 + (bignum_bitcount(bn)+7)/8;
+int ssh1_bignum_length(Bignum bn)
+{
+    return 2 + (bignum_bitcount(bn) + 7) / 8;
 }
 
 /*
  * Return the byte length of a bignum when ssh2 encoded.
  */
-int ssh2_bignum_length(Bignum bn) {
-    return 4 + (bignum_bitcount(bn)+8)/8;
+int ssh2_bignum_length(Bignum bn)
+{
+    return 4 + (bignum_bitcount(bn) + 8) / 8;
 }
 
 /*
  * Return a byte from a bignum; 0 is least significant, etc.
  */
-int bignum_byte(Bignum bn, int i) {
-    if (i >= 2*bn[0])
-        return 0;                      /* beyond the end */
+int bignum_byte(Bignum bn, int i)
+{
+    if (i >= 2 * bn[0])
+       return 0;                      /* beyond the end */
     else if (i & 1)
-        return (bn[i/2+1] >> 8) & 0xFF;
+       return (bn[i / 2 + 1] >> 8) & 0xFF;
     else
-        return (bn[i/2+1]     ) & 0xFF;
+       return (bn[i / 2 + 1]) & 0xFF;
 }
 
 /*
  * Return a bit from a bignum; 0 is least significant, etc.
  */
-int bignum_bit(Bignum bn, int i) {
-    if (i >= 16*bn[0])
-        return 0;                      /* beyond the end */
+int bignum_bit(Bignum bn, int i)
+{
+    if (i >= 16 * bn[0])
+       return 0;                      /* beyond the end */
     else
-        return (bn[i/16+1] >> (i%16)) & 1;
+       return (bn[i / 16 + 1] >> (i % 16)) & 1;
 }
 
 /*
  * Set a bit in a bignum; 0 is least significant, etc.
  */
-void bignum_set_bit(Bignum bn, int bitnum, int value) {
-    if (bitnum >= 16*bn[0])
-        abort();                       /* beyond the end */
+void bignum_set_bit(Bignum bn, int bitnum, int value)
+{
+    if (bitnum >= 16 * bn[0])
+       abort();                       /* beyond the end */
     else {
-        int v = bitnum/16+1;
-        int mask = 1 << (bitnum%16);
-        if (value)
-            bn[v] |= mask;
-        else
-            bn[v] &= ~mask;
+       int v = bitnum / 16 + 1;
+       int mask = 1 << (bitnum % 16);
+       if (value)
+           bn[v] |= mask;
+       else
+           bn[v] &= ~mask;
     }
 }
 
@@ -541,31 +603,35 @@ void bignum_set_bit(Bignum bn, int bitnum, int value) {
  * Write a ssh1-format bignum into a buffer. It is assumed the
  * buffer is big enough. Returns the number of bytes used.
  */
-int ssh1_write_bignum(void *data, Bignum bn) {
+int ssh1_write_bignum(void *data, Bignum bn)
+{
     unsigned char *p = data;
     int len = ssh1_bignum_length(bn);
     int i;
     int bitc = bignum_bitcount(bn);
 
     *p++ = (bitc >> 8) & 0xFF;
-    *p++ = (bitc     ) & 0xFF;
-    for (i = len-2; i-- ;)
-        *p++ = bignum_byte(bn, i);
+    *p++ = (bitc) & 0xFF;
+    for (i = len - 2; i--;)
+       *p++ = bignum_byte(bn, i);
     return len;
 }
 
 /*
  * Compare two bignums. Returns like strcmp.
  */
-int bignum_cmp(Bignum a, Bignum b) {
+int bignum_cmp(Bignum a, Bignum b)
+{
     int amax = a[0], bmax = b[0];
     int i = (amax > bmax ? amax : bmax);
     while (i) {
-        unsigned short aval = (i > amax ? 0 : a[i]);
-        unsigned short bval = (i > bmax ? 0 : b[i]);
-        if (aval < bval) return -1;
-        if (aval > bval) return +1;
-        i--;
+       unsigned short aval = (i > amax ? 0 : a[i]);
+       unsigned short bval = (i > bmax ? 0 : b[i]);
+       if (aval < bval)
+           return -1;
+       if (aval > bval)
+           return +1;
+       i--;
     }
     return 0;
 }
@@ -573,25 +639,26 @@ int bignum_cmp(Bignum a, Bignum b) {
 /*
  * Right-shift one bignum to form another.
  */
-Bignum bignum_rshift(Bignum a, int shift) {
+Bignum bignum_rshift(Bignum a, int shift)
+{
     Bignum ret;
     int i, shiftw, shiftb, shiftbb, bits;
     unsigned short ai, ai1;
 
     bits = bignum_bitcount(a) - shift;
-    ret = newbn((bits+15)/16);
+    ret = newbn((bits + 15) / 16);
 
     if (ret) {
-        shiftw = shift / 16;
-        shiftb = shift % 16;
-        shiftbb = 16 - shiftb;
-
-        ai1 = a[shiftw+1];
-        for (i = 1; i <= ret[0]; i++) {
-            ai = ai1;
-            ai1 = (i+shiftw+1 <= a[0] ? a[i+shiftw+1] : 0);
-            ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & 0xFFFF;
-        }
+       shiftw = shift / 16;
+       shiftb = shift % 16;
+       shiftbb = 16 - shiftb;
+
+       ai1 = a[shiftw + 1];
+       for (i = 1; i <= ret[0]; i++) {
+           ai = ai1;
+           ai1 = (i + shiftw + 1 <= a[0] ? a[i + shiftw + 1] : 0);
+           ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & 0xFFFF;
+       }
     }
 
     return ret;
@@ -600,7 +667,8 @@ Bignum bignum_rshift(Bignum a, int shift) {
 /*
  * Non-modular multiplication and addition.
  */
-Bignum bigmuladd(Bignum a, Bignum b, Bignum addend) {
+Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
+{
     int alen = a[0], blen = b[0];
     int mlen = (alen > blen ? alen : blen);
     int rlen, i, maxspot;
@@ -610,36 +678,37 @@ Bignum bigmuladd(Bignum a, Bignum b, Bignum addend) {
     /* mlen space for a, mlen space for b, 2*mlen for result */
     workspace = smalloc(mlen * 4 * sizeof(unsigned short));
     for (i = 0; i < mlen; i++) {
-        workspace[0*mlen + i] = (mlen-i <= a[0] ? a[mlen-i] : 0);
-        workspace[1*mlen + i] = (mlen-i <= b[0] ? b[mlen-i] : 0);
+       workspace[0 * mlen + i] = (mlen - i <= a[0] ? a[mlen - i] : 0);
+       workspace[1 * mlen + i] = (mlen - i <= b[0] ? b[mlen - i] : 0);
     }
 
-    internal_mul(workspace+0*mlen, workspace+1*mlen, workspace+2*mlen, mlen);
+    internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
+                workspace + 2 * mlen, mlen);
 
     /* now just copy the result back */
     rlen = alen + blen + 1;
     if (addend && rlen <= addend[0])
-        rlen = addend[0] + 1;
+       rlen = addend[0] + 1;
     ret = newbn(rlen);
     maxspot = 0;
     for (i = 1; i <= ret[0]; i++) {
-        ret[i] = (i <= 2*mlen ? workspace[4*mlen - i] : 0);
-        if (ret[i] != 0)
-            maxspot = i;
+       ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
+       if (ret[i] != 0)
+           maxspot = i;
     }
     ret[0] = maxspot;
 
     /* now add in the addend, if any */
     if (addend) {
-        unsigned long carry = 0;
-        for (i = 1; i <= rlen; i++) {
-            carry += (i <= ret[0] ? ret[i] : 0);
-            carry += (i <= addend[0] ? addend[i] : 0);
-            ret[i] = (unsigned short) carry & 0xFFFF;
-            carry >>= 16;
-            if (ret[i] != 0 && i > maxspot)
-                maxspot = i;
-        }
+       unsigned long carry = 0;
+       for (i = 1; i <= rlen; i++) {
+           carry += (i <= ret[0] ? ret[i] : 0);
+           carry += (i <= addend[0] ? addend[i] : 0);
+           ret[i] = (unsigned short) carry & 0xFFFF;
+           carry >>= 16;
+           if (ret[i] != 0 && i > maxspot)
+               maxspot = i;
+       }
     }
     ret[0] = maxspot;
 
@@ -649,7 +718,8 @@ Bignum bigmuladd(Bignum a, Bignum b, Bignum addend) {
 /*
  * Non-modular multiplication.
  */
-Bignum bigmul(Bignum a, Bignum b) {
+Bignum bigmul(Bignum a, Bignum b)
+{
     return bigmuladd(a, b, NULL);
 }
 
@@ -658,54 +728,57 @@ Bignum bigmul(Bignum a, Bignum b) {
  * is, the smallest integer which is >= N and is also one less than
  * a power of two.
  */
-Bignum bignum_bitmask(Bignum n) {
+Bignum bignum_bitmask(Bignum n)
+{
     Bignum ret = copybn(n);
     int i;
     unsigned short j;
 
     i = ret[0];
     while (n[i] == 0 && i > 0)
-        i--;
+       i--;
     if (i <= 0)
-        return ret;                    /* input was zero */
+       return ret;                    /* input was zero */
     j = 1;
     while (j < n[i])
-        j = 2*j+1;
+       j = 2 * j + 1;
     ret[i] = j;
     while (--i > 0)
-        ret[i] = 0xFFFF;
+       ret[i] = 0xFFFF;
     return ret;
 }
 
 /*
  * Convert a (max 16-bit) short into a bignum.
  */
-Bignum bignum_from_short(unsigned short n) {
+Bignum bignum_from_short(unsigned short n)
+{
     Bignum ret;
 
     ret = newbn(2);
     ret[1] = n & 0xFFFF;
     ret[2] = (n >> 16) & 0xFFFF;
     ret[0] = (ret[2] ? 2 : 1);
-    return ret;        
+    return ret;
 }
 
 /*
  * Add a long to a bignum.
  */
-Bignum bignum_add_long(Bignum number, unsigned long addend) {
-    Bignum ret = newbn(number[0]+1);
+Bignum bignum_add_long(Bignum number, unsigned long addend)
+{
+    Bignum ret = newbn(number[0] + 1);
     int i, maxspot = 0;
     unsigned long carry = 0;
 
     for (i = 1; i <= ret[0]; i++) {
-        carry += addend & 0xFFFF;
-        carry += (i <= number[0] ? number[i] : 0);
-        addend >>= 16;
-        ret[i] = (unsigned short) carry & 0xFFFF;
-        carry >>= 16;
-        if (ret[i] != 0)
-            maxspot = i;
+       carry += addend & 0xFFFF;
+       carry += (i <= number[0] ? number[i] : 0);
+       addend >>= 16;
+       ret[i] = (unsigned short) carry & 0xFFFF;
+       carry >>= 16;
+       if (ret[i] != 0)
+           maxspot = i;
     }
     ret[0] = maxspot;
     return ret;
@@ -714,49 +787,59 @@ Bignum bignum_add_long(Bignum number, unsigned long addend) {
 /*
  * Compute the residue of a bignum, modulo a (max 16-bit) short.
  */
-unsigned short bignum_mod_short(Bignum number, unsigned short modulus) {
+unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
+{
     unsigned long mod, r;
     int i;
 
     r = 0;
     mod = modulus;
     for (i = number[0]; i > 0; i--)
-        r = (r * 65536 + number[i]) % mod;
+       r = (r * 65536 + number[i]) % mod;
     return (unsigned short) r;
 }
 
-void diagbn(char *prefix, Bignum md) {
+void diagbn(char *prefix, Bignum md)
+{
     int i, nibbles, morenibbles;
     static const char hex[] = "0123456789ABCDEF";
 
     debugprint(("%s0x", prefix ? prefix : ""));
 
-    nibbles = (3 + bignum_bitcount(md))/4; if (nibbles<1) nibbles=1;
-    morenibbles = 4*md[0] - nibbles;
-    for (i=0; i<morenibbles; i++) debugprint(("-"));
-    for (i=nibbles; i-- ;)
-        debugprint(("%c",hex[(bignum_byte(md, i/2) >> (4*(i%2))) & 0xF]));
+    nibbles = (3 + bignum_bitcount(md)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    morenibbles = 4 * md[0] - nibbles;
+    for (i = 0; i < morenibbles; i++)
+       debugprint(("-"));
+    for (i = nibbles; i--;)
+       debugprint(
+                  ("%c",
+                   hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
 
-    if (prefix) debugprint(("\n"));
+    if (prefix)
+       debugprint(("\n"));
 }
 
 /*
  * Greatest common divisor.
  */
-Bignum biggcd(Bignum av, Bignum bv) {
+Bignum biggcd(Bignum av, Bignum bv)
+{
     Bignum a = copybn(av);
     Bignum b = copybn(bv);
 
     diagbn("a = ", a);
     diagbn("b = ", b);
     while (bignum_cmp(b, Zero) != 0) {
-        Bignum t = newbn(b[0]);
-        bigmod(a, b, t, NULL);
-        diagbn("t = ", t);
-        while (t[0] > 1 && t[t[0]] == 0) t[0]--;
-        freebn(a);
-        a = b;
-        b = t;
+       Bignum t = newbn(b[0]);
+       bigmod(a, b, t, NULL);
+       diagbn("t = ", t);
+       while (t[0] > 1 && t[t[0]] == 0)
+           t[0]--;
+       freebn(a);
+       a = b;
+       b = t;
     }
 
     freebn(b);
@@ -766,7 +849,8 @@ Bignum biggcd(Bignum av, Bignum bv) {
 /*
  * Modular inverse, using Euclid's extended algorithm.
  */
-Bignum modinv(Bignum number, Bignum modulus) {
+Bignum modinv(Bignum number, Bignum modulus)
+{
     Bignum a = copybn(modulus);
     Bignum b = copybn(number);
     Bignum xp = copybn(Zero);
@@ -774,18 +858,19 @@ Bignum modinv(Bignum number, Bignum modulus) {
     int sign = +1;
 
     while (bignum_cmp(b, One) != 0) {
-        Bignum t = newbn(b[0]);
-        Bignum q = newbn(a[0]);
-        bigmod(a, b, t, q);
-        while (t[0] > 1 && t[t[0]] == 0) t[0]--;
-        freebn(a);
-        a = b;
-        b = t;
-        t = xp;
-        xp = x;
-        x = bigmuladd(q, xp, t);
-        sign = -sign;
-        freebn(t);
+       Bignum t = newbn(b[0]);
+       Bignum q = newbn(a[0]);
+       bigmod(a, b, t, q);
+       while (t[0] > 1 && t[t[0]] == 0)
+           t[0]--;
+       freebn(a);
+       a = b;
+       b = t;
+       t = xp;
+       xp = x;
+       x = bigmuladd(q, xp, t);
+       sign = -sign;
+       freebn(t);
     }
 
     freebn(b);
@@ -794,24 +879,24 @@ Bignum modinv(Bignum number, Bignum modulus) {
 
     /* now we know that sign * x == 1, and that x < modulus */
     if (sign < 0) {
-        /* set a new x to be modulus - x */
-        Bignum newx = newbn(modulus[0]);
-        unsigned short carry = 0;
-        int maxspot = 1;
-        int i;
-
-        for (i = 1; i <= newx[0]; i++) {
-            unsigned short aword = (i <= modulus[0] ? modulus[i] : 0);
-            unsigned short bword = (i <= x[0] ? x[i] : 0);
-            newx[i] = aword - bword - carry;
-            bword = ~bword;
-            carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
-            if (newx[i] != 0)
-                maxspot = i;
-        }
-        newx[0] = maxspot;
-        freebn(x);
-        x = newx;
+       /* set a new x to be modulus - x */
+       Bignum newx = newbn(modulus[0]);
+       unsigned short carry = 0;
+       int maxspot = 1;
+       int i;
+
+       for (i = 1; i <= newx[0]; i++) {
+           unsigned short aword = (i <= modulus[0] ? modulus[i] : 0);
+           unsigned short bword = (i <= x[0] ? x[i] : 0);
+           newx[i] = aword - bword - carry;
+           bword = ~bword;
+           carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
+           if (newx[i] != 0)
+               maxspot = i;
+       }
+       newx[0] = maxspot;
+       freebn(x);
+       x = newx;
     }
 
     /* and return. */
@@ -822,7 +907,8 @@ Bignum modinv(Bignum number, Bignum modulus) {
  * Render a bignum into decimal. Return a malloced string holding
  * the decimal representation.
  */
-char *bignum_decimal(Bignum x) {
+char *bignum_decimal(Bignum x)
+{
     int ndigits, ndigit;
     int i, iszero;
     unsigned long carry;
@@ -843,8 +929,8 @@ char *bignum_decimal(Bignum x) {
      * up, we will have enough digits.
      */
     i = bignum_bitcount(x);
-    ndigits = (28*i + 92)/93;          /* multiply by 28/93 and round up */
-    ndigits++;                         /* allow for trailing \0 */
+    ndigits = (28 * i + 92) / 93;      /* multiply by 28/93 and round up */
+    ndigits++;                        /* allow for trailing \0 */
     ret = smalloc(ndigits);
 
     /*
@@ -854,26 +940,26 @@ char *bignum_decimal(Bignum x) {
      */
     workspace = smalloc(sizeof(unsigned short) * x[0]);
     for (i = 0; i < x[0]; i++)
-        workspace[i] = x[x[0] - i];
+       workspace[i] = x[x[0] - i];
 
     /*
      * Next, write the decimal number starting with the last digit.
      * We use ordinary short division, dividing 10 into the
      * workspace.
      */
-    ndigit = ndigits-1;
+    ndigit = ndigits - 1;
     ret[ndigit] = '\0';
     do {
-        iszero = 1;
-        carry = 0;
-        for (i = 0; i < x[0]; i++) {
-            carry = (carry << 16) + workspace[i];
-            workspace[i] = (unsigned short) (carry / 10);
-            if (workspace[i])
-                iszero = 0;
-            carry %= 10;
-        }
-        ret[--ndigit] = (char)(carry + '0');
+       iszero = 1;
+       carry = 0;
+       for (i = 0; i < x[0]; i++) {
+           carry = (carry << 16) + workspace[i];
+           workspace[i] = (unsigned short) (carry / 10);
+           if (workspace[i])
+               iszero = 0;
+           carry %= 10;
+       }
+       ret[--ndigit] = (char) (carry + '0');
     } while (!iszero);
 
     /*
@@ -881,7 +967,7 @@ char *bignum_decimal(Bignum x) {
      * string. Correct if so.
      */
     if (ndigit > 0)
-        memmove(ret, ret+ndigit, ndigits-ndigit);
+       memmove(ret, ret + ndigit, ndigits - ndigit);
 
     /*
      * Done.
index 63050b9..fb0db0c 100644 (file)
--- a/sshcrc.c
+++ b/sshcrc.c
@@ -89,7 +89,7 @@
 #define POLY (0xEDB88320L)
 
 #ifdef GENPROGRAM
-#define INITFUNC /* the gen program needs the init func :-) */
+#define INITFUNC                      /* the gen program needs the init func :-) */
 #endif
 
 #ifdef INITFUNC
  */
 static unsigned long crc32_table[256];
 
-void crc32_init(void) {
+void crc32_init(void)
+{
     unsigned long crcword;
     int i;
-    
+
     for (i = 0; i < 256; i++) {
-        unsigned long newbyte, x32term;
-        int j;
-        crcword = 0;
-        newbyte = i;
-        for (j = 0; j < 8; j++) {
-            x32term = (crcword ^ newbyte) & 1;
-            crcword = (crcword >> 1) ^ (x32term * POLY);
-            newbyte >>= 1;
-        }
-        crc32_table[i] = crcword;
+       unsigned long newbyte, x32term;
+       int j;
+       crcword = 0;
+       newbyte = i;
+       for (j = 0; j < 8; j++) {
+           x32term = (crcword ^ newbyte) & 1;
+           crcword = (crcword >> 1) ^ (x32term * POLY);
+           newbyte >>= 1;
+       }
+       crc32_table[i] = crcword;
     }
 }
 
@@ -193,29 +194,31 @@ static const unsigned long crc32_table[256] = {
 #endif
 
 #ifdef GENPROGRAM
-int main(void) {
+int main(void)
+{
     unsigned long crcword;
     int i;
 
     crc32_init();
     for (i = 0; i < 256; i++) {
-        printf("%s0x%08XL%s",
-               (i % 4 == 0 ? "    " : " "),
-               crc32_table[i],
-               (i % 4 == 3 ? (i == 255 ? "\n" : ",\n") : ","));
+       printf("%s0x%08XL%s",
+              (i % 4 == 0 ? "    " : " "),
+              crc32_table[i],
+              (i % 4 == 3 ? (i == 255 ? "\n" : ",\n") : ","));
     }
 
     return 0;
 }
 #endif
 
-unsigned long crc32(const void *buf, size_t len) {
+unsigned long crc32(const void *buf, size_t len)
+{
     unsigned long crcword = 0L;
     const unsigned char *p = (const unsigned char *) buf;
     while (len--) {
-        unsigned long newbyte = *p++;
-        newbyte ^= crcword & 0xFFL;
-        crcword = (crcword >> 8) ^ crc32_table[newbyte];
+       unsigned long newbyte = *p++;
+       newbyte ^= crcword & 0xFFL;
+       crcword = (crcword >> 8) ^ crc32_table[newbyte];
     }
     return crcword;
 }
index 1665b3d..44fbf00 100644 (file)
--- a/sshdes.c
+++ b/sshdes.c
@@ -285,26 +285,28 @@ typedef struct {
 #define rotl(x, c) ( (x << c) | (x >> (32-c)) )
 #define rotl28(x, c) ( ( (x << c) | (x >> (28-c)) ) & 0x0FFFFFFF)
 
-static word32 bitsel(word32 *input, const int *bitnums, int size) {
+static word32 bitsel(word32 * input, const int *bitnums, int size)
+{
     word32 ret = 0;
     while (size--) {
-        int bitpos = *bitnums++;
-        ret <<= 1;
-        if (bitpos >= 0)
-            ret |= 1 & (input[bitpos / 32] >> (bitpos % 32));
+       int bitpos = *bitnums++;
+       ret <<= 1;
+       if (bitpos >= 0)
+           ret |= 1 & (input[bitpos / 32] >> (bitpos % 32));
     }
     return ret;
 }
 
-void des_key_setup(word32 key_msw, word32 key_lsw, DESContext *sched) {
+void des_key_setup(word32 key_msw, word32 key_lsw, DESContext * sched)
+{
 
     static const int PC1_Cbits[] = {
-        7, 15, 23, 31, 39, 47, 55, 63, 6, 14, 22, 30, 38, 46,
-        54, 62, 5, 13, 21, 29, 37, 45, 53, 61, 4, 12, 20, 28
+       7, 15, 23, 31, 39, 47, 55, 63, 6, 14, 22, 30, 38, 46,
+       54, 62, 5, 13, 21, 29, 37, 45, 53, 61, 4, 12, 20, 28
     };
     static const int PC1_Dbits[] = {
-        1, 9, 17, 25, 33, 41, 49, 57, 2, 10, 18, 26, 34, 42,
-        50, 58, 3, 11, 19, 27, 35, 43, 51, 59, 36, 44, 52, 60
+       1, 9, 17, 25, 33, 41, 49, 57, 2, 10, 18, 26, 34, 42,
+       50, 58, 3, 11, 19, 27, 35, 43, 51, 59, 36, 44, 52, 60
     };
     /*
      * The bit numbers in the two lists below don't correspond to
@@ -315,14 +317,15 @@ void des_key_setup(word32 key_msw, word32 key_lsw, DESContext *sched) {
      * 0 of C is addressed by writing `32' here.
      */
     static const int PC2_0246[] = {
-        49, 36, 59, 55, -1, -1, 37, 41, 48, 56, 34, 52, -1, -1, 15, 4,
-        25, 19, 9, 1, -1, -1, 12, 7, 17, 0, 22, 3, -1, -1, 46, 43
+       49, 36, 59, 55, -1, -1, 37, 41, 48, 56, 34, 52, -1, -1, 15, 4,
+       25, 19, 9, 1, -1, -1, 12, 7, 17, 0, 22, 3, -1, -1, 46, 43
     };
     static const int PC2_1357[] = {
-        -1, -1, 57, 32, 45, 54, 39, 50, -1, -1, 44, 53, 33, 40, 47, 58,
-        -1, -1, 26, 16, 5, 11, 23, 8, -1, -1, 10, 14, 6, 20, 27, 24
+       -1, -1, 57, 32, 45, 54, 39, 50, -1, -1, 44, 53, 33, 40, 47, 58,
+       -1, -1, 26, 16, 5, 11, 23, 8, -1, -1, 10, 14, 6, 20, 27, 24
     };
-    static const int leftshifts[] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};
+    static const int leftshifts[] =
+       { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
 
     word32 C, D;
     word32 buf[2];
@@ -335,154 +338,154 @@ void des_key_setup(word32 key_msw, word32 key_lsw, DESContext *sched) {
     D = bitsel(buf, PC1_Dbits, 28);
 
     for (i = 0; i < 16; i++) {
-        C = rotl28(C, leftshifts[i]);
-        D = rotl28(D, leftshifts[i]);
-        buf[0] = D;
-        buf[1] = C;
-        sched->k0246[i] = bitsel(buf, PC2_0246, 32);
-        sched->k1357[i] = bitsel(buf, PC2_1357, 32);
+       C = rotl28(C, leftshifts[i]);
+       D = rotl28(D, leftshifts[i]);
+       buf[0] = D;
+       buf[1] = C;
+       sched->k0246[i] = bitsel(buf, PC2_0246, 32);
+       sched->k1357[i] = bitsel(buf, PC2_1357, 32);
     }
 
     sched->eiv0 = sched->eiv1 = 0;
-    sched->div0 = sched->div1 = 0;       /* for good measure */
+    sched->div0 = sched->div1 = 0;     /* for good measure */
 }
 
 static const word32 SPboxes[8][64] = {
     {0x01010400, 0x00000000, 0x00010000, 0x01010404,
-    0x01010004, 0x00010404, 0x00000004, 0x00010000,
-    0x00000400, 0x01010400, 0x01010404, 0x00000400,
-    0x01000404, 0x01010004, 0x01000000, 0x00000004,
-    0x00000404, 0x01000400, 0x01000400, 0x00010400,
-    0x00010400, 0x01010000, 0x01010000, 0x01000404,
-    0x00010004, 0x01000004, 0x01000004, 0x00010004,
-    0x00000000, 0x00000404, 0x00010404, 0x01000000,
-    0x00010000, 0x01010404, 0x00000004, 0x01010000,
-    0x01010400, 0x01000000, 0x01000000, 0x00000400,
-    0x01010004, 0x00010000, 0x00010400, 0x01000004,
-    0x00000400, 0x00000004, 0x01000404, 0x00010404,
-    0x01010404, 0x00010004, 0x01010000, 0x01000404,
-    0x01000004, 0x00000404, 0x00010404, 0x01010400,
-    0x00000404, 0x01000400, 0x01000400, 0x00000000,
-    0x00010004, 0x00010400, 0x00000000, 0x01010004L},
+     0x01010004, 0x00010404, 0x00000004, 0x00010000,
+     0x00000400, 0x01010400, 0x01010404, 0x00000400,
+     0x01000404, 0x01010004, 0x01000000, 0x00000004,
+     0x00000404, 0x01000400, 0x01000400, 0x00010400,
+     0x00010400, 0x01010000, 0x01010000, 0x01000404,
+     0x00010004, 0x01000004, 0x01000004, 0x00010004,
+     0x00000000, 0x00000404, 0x00010404, 0x01000000,
+     0x00010000, 0x01010404, 0x00000004, 0x01010000,
+     0x01010400, 0x01000000, 0x01000000, 0x00000400,
+     0x01010004, 0x00010000, 0x00010400, 0x01000004,
+     0x00000400, 0x00000004, 0x01000404, 0x00010404,
+     0x01010404, 0x00010004, 0x01010000, 0x01000404,
+     0x01000004, 0x00000404, 0x00010404, 0x01010400,
+     0x00000404, 0x01000400, 0x01000400, 0x00000000,
+     0x00010004, 0x00010400, 0x00000000, 0x01010004L},
 
     {0x80108020, 0x80008000, 0x00008000, 0x00108020,
-    0x00100000, 0x00000020, 0x80100020, 0x80008020,
-    0x80000020, 0x80108020, 0x80108000, 0x80000000,
-    0x80008000, 0x00100000, 0x00000020, 0x80100020,
-    0x00108000, 0x00100020, 0x80008020, 0x00000000,
-    0x80000000, 0x00008000, 0x00108020, 0x80100000,
-    0x00100020, 0x80000020, 0x00000000, 0x00108000,
-    0x00008020, 0x80108000, 0x80100000, 0x00008020,
-    0x00000000, 0x00108020, 0x80100020, 0x00100000,
-    0x80008020, 0x80100000, 0x80108000, 0x00008000,
-    0x80100000, 0x80008000, 0x00000020, 0x80108020,
-    0x00108020, 0x00000020, 0x00008000, 0x80000000,
-    0x00008020, 0x80108000, 0x00100000, 0x80000020,
-    0x00100020, 0x80008020, 0x80000020, 0x00100020,
-    0x00108000, 0x00000000, 0x80008000, 0x00008020,
-    0x80000000, 0x80100020, 0x80108020, 0x00108000L},
+     0x00100000, 0x00000020, 0x80100020, 0x80008020,
+     0x80000020, 0x80108020, 0x80108000, 0x80000000,
+     0x80008000, 0x00100000, 0x00000020, 0x80100020,
+     0x00108000, 0x00100020, 0x80008020, 0x00000000,
+     0x80000000, 0x00008000, 0x00108020, 0x80100000,
+     0x00100020, 0x80000020, 0x00000000, 0x00108000,
+     0x00008020, 0x80108000, 0x80100000, 0x00008020,
+     0x00000000, 0x00108020, 0x80100020, 0x00100000,
+     0x80008020, 0x80100000, 0x80108000, 0x00008000,
+     0x80100000, 0x80008000, 0x00000020, 0x80108020,
+     0x00108020, 0x00000020, 0x00008000, 0x80000000,
+     0x00008020, 0x80108000, 0x00100000, 0x80000020,
+     0x00100020, 0x80008020, 0x80000020, 0x00100020,
+     0x00108000, 0x00000000, 0x80008000, 0x00008020,
+     0x80000000, 0x80100020, 0x80108020, 0x00108000L},
 
     {0x00000208, 0x08020200, 0x00000000, 0x08020008,
-    0x08000200, 0x00000000, 0x00020208, 0x08000200,
-    0x00020008, 0x08000008, 0x08000008, 0x00020000,
-    0x08020208, 0x00020008, 0x08020000, 0x00000208,
-    0x08000000, 0x00000008, 0x08020200, 0x00000200,
-    0x00020200, 0x08020000, 0x08020008, 0x00020208,
-    0x08000208, 0x00020200, 0x00020000, 0x08000208,
-    0x00000008, 0x08020208, 0x00000200, 0x08000000,
-    0x08020200, 0x08000000, 0x00020008, 0x00000208,
-    0x00020000, 0x08020200, 0x08000200, 0x00000000,
-    0x00000200, 0x00020008, 0x08020208, 0x08000200,
-    0x08000008, 0x00000200, 0x00000000, 0x08020008,
-    0x08000208, 0x00020000, 0x08000000, 0x08020208,
-    0x00000008, 0x00020208, 0x00020200, 0x08000008,
-    0x08020000, 0x08000208, 0x00000208, 0x08020000,
-    0x00020208, 0x00000008, 0x08020008, 0x00020200L},
+     0x08000200, 0x00000000, 0x00020208, 0x08000200,
+     0x00020008, 0x08000008, 0x08000008, 0x00020000,
+     0x08020208, 0x00020008, 0x08020000, 0x00000208,
+     0x08000000, 0x00000008, 0x08020200, 0x00000200,
+     0x00020200, 0x08020000, 0x08020008, 0x00020208,
+     0x08000208, 0x00020200, 0x00020000, 0x08000208,
+     0x00000008, 0x08020208, 0x00000200, 0x08000000,
+     0x08020200, 0x08000000, 0x00020008, 0x00000208,
+     0x00020000, 0x08020200, 0x08000200, 0x00000000,
+     0x00000200, 0x00020008, 0x08020208, 0x08000200,
+     0x08000008, 0x00000200, 0x00000000, 0x08020008,
+     0x08000208, 0x00020000, 0x08000000, 0x08020208,
+     0x00000008, 0x00020208, 0x00020200, 0x08000008,
+     0x08020000, 0x08000208, 0x00000208, 0x08020000,
+     0x00020208, 0x00000008, 0x08020008, 0x00020200L},
 
     {0x00802001, 0x00002081, 0x00002081, 0x00000080,
-    0x00802080, 0x00800081, 0x00800001, 0x00002001,
-    0x00000000, 0x00802000, 0x00802000, 0x00802081,
-    0x00000081, 0x00000000, 0x00800080, 0x00800001,
-    0x00000001, 0x00002000, 0x00800000, 0x00802001,
-    0x00000080, 0x00800000, 0x00002001, 0x00002080,
-    0x00800081, 0x00000001, 0x00002080, 0x00800080,
-    0x00002000, 0x00802080, 0x00802081, 0x00000081,
-    0x00800080, 0x00800001, 0x00802000, 0x00802081,
-    0x00000081, 0x00000000, 0x00000000, 0x00802000,
-    0x00002080, 0x00800080, 0x00800081, 0x00000001,
-    0x00802001, 0x00002081, 0x00002081, 0x00000080,
-    0x00802081, 0x00000081, 0x00000001, 0x00002000,
-    0x00800001, 0x00002001, 0x00802080, 0x00800081,
-    0x00002001, 0x00002080, 0x00800000, 0x00802001,
-    0x00000080, 0x00800000, 0x00002000, 0x00802080L},
+     0x00802080, 0x00800081, 0x00800001, 0x00002001,
+     0x00000000, 0x00802000, 0x00802000, 0x00802081,
+     0x00000081, 0x00000000, 0x00800080, 0x00800001,
+     0x00000001, 0x00002000, 0x00800000, 0x00802001,
+     0x00000080, 0x00800000, 0x00002001, 0x00002080,
+     0x00800081, 0x00000001, 0x00002080, 0x00800080,
+     0x00002000, 0x00802080, 0x00802081, 0x00000081,
+     0x00800080, 0x00800001, 0x00802000, 0x00802081,
+     0x00000081, 0x00000000, 0x00000000, 0x00802000,
+     0x00002080, 0x00800080, 0x00800081, 0x00000001,
+     0x00802001, 0x00002081, 0x00002081, 0x00000080,
+     0x00802081, 0x00000081, 0x00000001, 0x00002000,
+     0x00800001, 0x00002001, 0x00802080, 0x00800081,
+     0x00002001, 0x00002080, 0x00800000, 0x00802001,
+     0x00000080, 0x00800000, 0x00002000, 0x00802080L},
 
     {0x00000100, 0x02080100, 0x02080000, 0x42000100,
-    0x00080000, 0x00000100, 0x40000000, 0x02080000,
-    0x40080100, 0x00080000, 0x02000100, 0x40080100,
-    0x42000100, 0x42080000, 0x00080100, 0x40000000,
-    0x02000000, 0x40080000, 0x40080000, 0x00000000,
-    0x40000100, 0x42080100, 0x42080100, 0x02000100,
-    0x42080000, 0x40000100, 0x00000000, 0x42000000,
-    0x02080100, 0x02000000, 0x42000000, 0x00080100,
-    0x00080000, 0x42000100, 0x00000100, 0x02000000,
-    0x40000000, 0x02080000, 0x42000100, 0x40080100,
-    0x02000100, 0x40000000, 0x42080000, 0x02080100,
-    0x40080100, 0x00000100, 0x02000000, 0x42080000,
-    0x42080100, 0x00080100, 0x42000000, 0x42080100,
-    0x02080000, 0x00000000, 0x40080000, 0x42000000,
-    0x00080100, 0x02000100, 0x40000100, 0x00080000,
-    0x00000000, 0x40080000, 0x02080100, 0x40000100L},
+     0x00080000, 0x00000100, 0x40000000, 0x02080000,
+     0x40080100, 0x00080000, 0x02000100, 0x40080100,
+     0x42000100, 0x42080000, 0x00080100, 0x40000000,
+     0x02000000, 0x40080000, 0x40080000, 0x00000000,
+     0x40000100, 0x42080100, 0x42080100, 0x02000100,
+     0x42080000, 0x40000100, 0x00000000, 0x42000000,
+     0x02080100, 0x02000000, 0x42000000, 0x00080100,
+     0x00080000, 0x42000100, 0x00000100, 0x02000000,
+     0x40000000, 0x02080000, 0x42000100, 0x40080100,
+     0x02000100, 0x40000000, 0x42080000, 0x02080100,
+     0x40080100, 0x00000100, 0x02000000, 0x42080000,
+     0x42080100, 0x00080100, 0x42000000, 0x42080100,
+     0x02080000, 0x00000000, 0x40080000, 0x42000000,
+     0x00080100, 0x02000100, 0x40000100, 0x00080000,
+     0x00000000, 0x40080000, 0x02080100, 0x40000100L},
 
     {0x20000010, 0x20400000, 0x00004000, 0x20404010,
-    0x20400000, 0x00000010, 0x20404010, 0x00400000,
-    0x20004000, 0x00404010, 0x00400000, 0x20000010,
-    0x00400010, 0x20004000, 0x20000000, 0x00004010,
-    0x00000000, 0x00400010, 0x20004010, 0x00004000,
-    0x00404000, 0x20004010, 0x00000010, 0x20400010,
-    0x20400010, 0x00000000, 0x00404010, 0x20404000,
-    0x00004010, 0x00404000, 0x20404000, 0x20000000,
-    0x20004000, 0x00000010, 0x20400010, 0x00404000,
-    0x20404010, 0x00400000, 0x00004010, 0x20000010,
-    0x00400000, 0x20004000, 0x20000000, 0x00004010,
-    0x20000010, 0x20404010, 0x00404000, 0x20400000,
-    0x00404010, 0x20404000, 0x00000000, 0x20400010,
-    0x00000010, 0x00004000, 0x20400000, 0x00404010,
-    0x00004000, 0x00400010, 0x20004010, 0x00000000,
-    0x20404000, 0x20000000, 0x00400010, 0x20004010L},
+     0x20400000, 0x00000010, 0x20404010, 0x00400000,
+     0x20004000, 0x00404010, 0x00400000, 0x20000010,
+     0x00400010, 0x20004000, 0x20000000, 0x00004010,
+     0x00000000, 0x00400010, 0x20004010, 0x00004000,
+     0x00404000, 0x20004010, 0x00000010, 0x20400010,
+     0x20400010, 0x00000000, 0x00404010, 0x20404000,
+     0x00004010, 0x00404000, 0x20404000, 0x20000000,
+     0x20004000, 0x00000010, 0x20400010, 0x00404000,
+     0x20404010, 0x00400000, 0x00004010, 0x20000010,
+     0x00400000, 0x20004000, 0x20000000, 0x00004010,
+     0x20000010, 0x20404010, 0x00404000, 0x20400000,
+     0x00404010, 0x20404000, 0x00000000, 0x20400010,
+     0x00000010, 0x00004000, 0x20400000, 0x00404010,
+     0x00004000, 0x00400010, 0x20004010, 0x00000000,
+     0x20404000, 0x20000000, 0x00400010, 0x20004010L},
 
     {0x00200000, 0x04200002, 0x04000802, 0x00000000,
-    0x00000800, 0x04000802, 0x00200802, 0x04200800,
-    0x04200802, 0x00200000, 0x00000000, 0x04000002,
-    0x00000002, 0x04000000, 0x04200002, 0x00000802,
-    0x04000800, 0x00200802, 0x00200002, 0x04000800,
-    0x04000002, 0x04200000, 0x04200800, 0x00200002,
-    0x04200000, 0x00000800, 0x00000802, 0x04200802,
-    0x00200800, 0x00000002, 0x04000000, 0x00200800,
-    0x04000000, 0x00200800, 0x00200000, 0x04000802,
-    0x04000802, 0x04200002, 0x04200002, 0x00000002,
-    0x00200002, 0x04000000, 0x04000800, 0x00200000,
-    0x04200800, 0x00000802, 0x00200802, 0x04200800,
-    0x00000802, 0x04000002, 0x04200802, 0x04200000,
-    0x00200800, 0x00000000, 0x00000002, 0x04200802,
-    0x00000000, 0x00200802, 0x04200000, 0x00000800,
-    0x04000002, 0x04000800, 0x00000800, 0x00200002L},
+     0x00000800, 0x04000802, 0x00200802, 0x04200800,
+     0x04200802, 0x00200000, 0x00000000, 0x04000002,
+     0x00000002, 0x04000000, 0x04200002, 0x00000802,
+     0x04000800, 0x00200802, 0x00200002, 0x04000800,
+     0x04000002, 0x04200000, 0x04200800, 0x00200002,
+     0x04200000, 0x00000800, 0x00000802, 0x04200802,
+     0x00200800, 0x00000002, 0x04000000, 0x00200800,
+     0x04000000, 0x00200800, 0x00200000, 0x04000802,
+     0x04000802, 0x04200002, 0x04200002, 0x00000002,
+     0x00200002, 0x04000000, 0x04000800, 0x00200000,
+     0x04200800, 0x00000802, 0x00200802, 0x04200800,
+     0x00000802, 0x04000002, 0x04200802, 0x04200000,
+     0x00200800, 0x00000000, 0x00000002, 0x04200802,
+     0x00000000, 0x00200802, 0x04200000, 0x00000800,
+     0x04000002, 0x04000800, 0x00000800, 0x00200002L},
 
     {0x10001040, 0x00001000, 0x00040000, 0x10041040,
-    0x10000000, 0x10001040, 0x00000040, 0x10000000,
-    0x00040040, 0x10040000, 0x10041040, 0x00041000,
-    0x10041000, 0x00041040, 0x00001000, 0x00000040,
-    0x10040000, 0x10000040, 0x10001000, 0x00001040,
-    0x00041000, 0x00040040, 0x10040040, 0x10041000,
-    0x00001040, 0x00000000, 0x00000000, 0x10040040,
-    0x10000040, 0x10001000, 0x00041040, 0x00040000,
-    0x00041040, 0x00040000, 0x10041000, 0x00001000,
-    0x00000040, 0x10040040, 0x00001000, 0x00041040,
-    0x10001000, 0x00000040, 0x10000040, 0x10040000,
-    0x10040040, 0x10000000, 0x00040000, 0x10001040,
-    0x00000000, 0x10041040, 0x00040040, 0x10000040,
-    0x10040000, 0x10001000, 0x10001040, 0x00000000,
-    0x10041040, 0x00041000, 0x00041000, 0x00001040,
-    0x00001040, 0x00040040, 0x10000000, 0x10041000L}
+     0x10000000, 0x10001040, 0x00000040, 0x10000000,
+     0x00040040, 0x10040000, 0x10041040, 0x00041000,
+     0x10041000, 0x00041040, 0x00001000, 0x00000040,
+     0x10040000, 0x10000040, 0x10001000, 0x00001040,
+     0x00041000, 0x00040040, 0x10040040, 0x10041000,
+     0x00001040, 0x00000000, 0x00000000, 0x10040040,
+     0x10000040, 0x10001000, 0x00041040, 0x00040000,
+     0x00041040, 0x00040000, 0x10041000, 0x00001000,
+     0x00000040, 0x10040040, 0x00001000, 0x00041040,
+     0x10001000, 0x00000040, 0x10000040, 0x10040000,
+     0x10040040, 0x10000000, 0x00040000, 0x10001040,
+     0x00000000, 0x10041040, 0x00040040, 0x10000040,
+     0x10040000, 0x10001000, 0x10001040, 0x00000000,
+     0x10041040, 0x00041000, 0x00041000, 0x00001040,
+     0x00001040, 0x00040040, 0x10000000, 0x10041000L}
 };
 
 #define f(R, K0246, K1357) (\
@@ -519,7 +522,8 @@ static const word32 SPboxes[8][64] = {
     bitswap(R, L, 16, 0x0000FFFF), \
     bitswap(R, L,  4, 0x0F0F0F0F))
 
-void des_encipher(word32 *output, word32 L, word32 R, DESContext *sched) {
+void des_encipher(word32 * output, word32 L, word32 R, DESContext * sched)
+{
     word32 swap, s0246, s1357;
 
     IP(L, R);
@@ -527,16 +531,16 @@ void des_encipher(word32 *output, word32 L, word32 R, DESContext *sched) {
     L = rotl(L, 1);
     R = rotl(R, 1);
 
-    L ^= f(R, sched->k0246[ 0], sched->k1357[ 0]);
-    R ^= f(L, sched->k0246[ 1], sched->k1357[ 1]);
-    L ^= f(R, sched->k0246[ 2], sched->k1357[ 2]);
-    R ^= f(L, sched->k0246[ 3], sched->k1357[ 3]);
-    L ^= f(R, sched->k0246[ 4], sched->k1357[ 4]);
-    R ^= f(L, sched->k0246[ 5], sched->k1357[ 5]);
-    L ^= f(R, sched->k0246[ 6], sched->k1357[ 6]);
-    R ^= f(L, sched->k0246[ 7], sched->k1357[ 7]);
-    L ^= f(R, sched->k0246[ 8], sched->k1357[ 8]);
-    R ^= f(L, sched->k0246[ 9], sched->k1357[ 9]);
+    L ^= f(R, sched->k0246[0], sched->k1357[0]);
+    R ^= f(L, sched->k0246[1], sched->k1357[1]);
+    L ^= f(R, sched->k0246[2], sched->k1357[2]);
+    R ^= f(L, sched->k0246[3], sched->k1357[3]);
+    L ^= f(R, sched->k0246[4], sched->k1357[4]);
+    R ^= f(L, sched->k0246[5], sched->k1357[5]);
+    L ^= f(R, sched->k0246[6], sched->k1357[6]);
+    R ^= f(L, sched->k0246[7], sched->k1357[7]);
+    L ^= f(R, sched->k0246[8], sched->k1357[8]);
+    R ^= f(L, sched->k0246[9], sched->k1357[9]);
     L ^= f(R, sched->k0246[10], sched->k1357[10]);
     R ^= f(L, sched->k0246[11], sched->k1357[11]);
     L ^= f(R, sched->k0246[12], sched->k1357[12]);
@@ -547,7 +551,9 @@ void des_encipher(word32 *output, word32 L, word32 R, DESContext *sched) {
     L = rotl(L, 31);
     R = rotl(R, 31);
 
-    swap = L; L = R; R = swap;
+    swap = L;
+    L = R;
+    R = swap;
 
     FP(L, R);
 
@@ -555,7 +561,8 @@ void des_encipher(word32 *output, word32 L, word32 R, DESContext *sched) {
     output[1] = R;
 }
 
-void des_decipher(word32 *output, word32 L, word32 R, DESContext *sched) {
+void des_decipher(word32 * output, word32 L, word32 R, DESContext * sched)
+{
     word32 swap, s0246, s1357;
 
     IP(L, R);
@@ -569,21 +576,23 @@ void des_decipher(word32 *output, word32 L, word32 R, DESContext *sched) {
     R ^= f(L, sched->k0246[12], sched->k1357[12]);
     L ^= f(R, sched->k0246[11], sched->k1357[11]);
     R ^= f(L, sched->k0246[10], sched->k1357[10]);
-    L ^= f(R, sched->k0246[ 9], sched->k1357[ 9]);
-    R ^= f(L, sched->k0246[ 8], sched->k1357[ 8]);
-    L ^= f(R, sched->k0246[ 7], sched->k1357[ 7]);
-    R ^= f(L, sched->k0246[ 6], sched->k1357[ 6]);
-    L ^= f(R, sched->k0246[ 5], sched->k1357[ 5]);
-    R ^= f(L, sched->k0246[ 4], sched->k1357[ 4]);
-    L ^= f(R, sched->k0246[ 3], sched->k1357[ 3]);
-    R ^= f(L, sched->k0246[ 2], sched->k1357[ 2]);
-    L ^= f(R, sched->k0246[ 1], sched->k1357[ 1]);
-    R ^= f(L, sched->k0246[ 0], sched->k1357[ 0]);
+    L ^= f(R, sched->k0246[9], sched->k1357[9]);
+    R ^= f(L, sched->k0246[8], sched->k1357[8]);
+    L ^= f(R, sched->k0246[7], sched->k1357[7]);
+    R ^= f(L, sched->k0246[6], sched->k1357[6]);
+    L ^= f(R, sched->k0246[5], sched->k1357[5]);
+    R ^= f(L, sched->k0246[4], sched->k1357[4]);
+    L ^= f(R, sched->k0246[3], sched->k1357[3]);
+    R ^= f(L, sched->k0246[2], sched->k1357[2]);
+    L ^= f(R, sched->k0246[1], sched->k1357[1]);
+    R ^= f(L, sched->k0246[0], sched->k1357[0]);
 
     L = rotl(L, 31);
     R = rotl(R, 31);
 
-    swap = L; L = R; R = swap;
+    swap = L;
+    L = R;
+    R = swap;
 
     FP(L, R);
 
@@ -604,7 +613,8 @@ void des_decipher(word32 *output, word32 L, word32 R, DESContext *sched) {
   (cp)[0] = (value) >> 24; } while (0)
 
 static void des_cbc_encrypt(unsigned char *dest, const unsigned char *src,
-                            unsigned int len, DESContext *sched) {
+                           unsigned int len, DESContext * sched)
+{
     word32 out[2], iv0, iv1;
     unsigned int i;
 
@@ -613,20 +623,25 @@ static void des_cbc_encrypt(unsigned char *dest, const unsigned char *src,
     iv0 = sched->eiv0;
     iv1 = sched->eiv1;
     for (i = 0; i < len; i += 8) {
-        iv0 ^= GET_32BIT_MSB_FIRST(src); src += 4;
-        iv1 ^= GET_32BIT_MSB_FIRST(src); src += 4;
-        des_encipher(out, iv0, iv1, sched);
-        iv0 = out[0];
-        iv1 = out[1];
-        PUT_32BIT_MSB_FIRST(dest, iv0); dest += 4;
-        PUT_32BIT_MSB_FIRST(dest, iv1); dest += 4;
+       iv0 ^= GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       iv1 ^= GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       des_encipher(out, iv0, iv1, sched);
+       iv0 = out[0];
+       iv1 = out[1];
+       PUT_32BIT_MSB_FIRST(dest, iv0);
+       dest += 4;
+       PUT_32BIT_MSB_FIRST(dest, iv1);
+       dest += 4;
     }
     sched->eiv0 = iv0;
     sched->eiv1 = iv1;
 }
 
 static void des_cbc_decrypt(unsigned char *dest, const unsigned char *src,
-                            unsigned int len, DESContext *sched) {
+                           unsigned int len, DESContext * sched)
+{
     word32 out[2], iv0, iv1, xL, xR;
     unsigned int i;
 
@@ -635,29 +650,35 @@ static void des_cbc_decrypt(unsigned char *dest, const unsigned char *src,
     iv0 = sched->div0;
     iv1 = sched->div1;
     for (i = 0; i < len; i += 8) {
-        xL = GET_32BIT_MSB_FIRST(src); src += 4;
-        xR = GET_32BIT_MSB_FIRST(src); src += 4;
-        des_decipher(out, xL, xR, sched);
-        iv0 ^= out[0];
-        iv1 ^= out[1];
-        PUT_32BIT_MSB_FIRST(dest, iv0); dest += 4;
-        PUT_32BIT_MSB_FIRST(dest, iv1); dest += 4;
-        iv0 = xL;
-        iv1 = xR;
+       xL = GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       xR = GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       des_decipher(out, xL, xR, sched);
+       iv0 ^= out[0];
+       iv1 ^= out[1];
+       PUT_32BIT_MSB_FIRST(dest, iv0);
+       dest += 4;
+       PUT_32BIT_MSB_FIRST(dest, iv1);
+       dest += 4;
+       iv0 = xL;
+       iv1 = xR;
     }
     sched->div0 = iv0;
     sched->div1 = iv1;
 }
 
 static void des_3cbc_encrypt(unsigned char *dest, const unsigned char *src,
-                             unsigned int len, DESContext *scheds) {
+                            unsigned int len, DESContext * scheds)
+{
     des_cbc_encrypt(dest, src, len, &scheds[0]);
     des_cbc_decrypt(dest, src, len, &scheds[1]);
     des_cbc_encrypt(dest, src, len, &scheds[2]);
 }
 
 static void des_cbc3_encrypt(unsigned char *dest, const unsigned char *src,
-                             unsigned int len, DESContext *scheds) {
+                            unsigned int len, DESContext * scheds)
+{
     word32 out[2], iv0, iv1;
     unsigned int i;
 
@@ -666,29 +687,35 @@ static void des_cbc3_encrypt(unsigned char *dest, const unsigned char *src,
     iv0 = scheds->eiv0;
     iv1 = scheds->eiv1;
     for (i = 0; i < len; i += 8) {
-        iv0 ^= GET_32BIT_MSB_FIRST(src); src += 4;
-        iv1 ^= GET_32BIT_MSB_FIRST(src); src += 4;
-        des_encipher(out, iv0, iv1, &scheds[0]);
-        des_decipher(out, out[0], out[1], &scheds[1]);
-        des_encipher(out, out[0], out[1], &scheds[2]);
-        iv0 = out[0];
-        iv1 = out[1];
-        PUT_32BIT_MSB_FIRST(dest, iv0); dest += 4;
-        PUT_32BIT_MSB_FIRST(dest, iv1); dest += 4;
+       iv0 ^= GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       iv1 ^= GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       des_encipher(out, iv0, iv1, &scheds[0]);
+       des_decipher(out, out[0], out[1], &scheds[1]);
+       des_encipher(out, out[0], out[1], &scheds[2]);
+       iv0 = out[0];
+       iv1 = out[1];
+       PUT_32BIT_MSB_FIRST(dest, iv0);
+       dest += 4;
+       PUT_32BIT_MSB_FIRST(dest, iv1);
+       dest += 4;
     }
     scheds->eiv0 = iv0;
     scheds->eiv1 = iv1;
 }
 
 static void des_3cbc_decrypt(unsigned char *dest, const unsigned char *src,
-                             unsigned int len, DESContext *scheds) {
+                            unsigned int len, DESContext * scheds)
+{
     des_cbc_decrypt(dest, src, len, &scheds[2]);
     des_cbc_encrypt(dest, src, len, &scheds[1]);
     des_cbc_decrypt(dest, src, len, &scheds[0]);
 }
 
 static void des_cbc3_decrypt(unsigned char *dest, const unsigned char *src,
-                             unsigned int len, DESContext *scheds) {
+                            unsigned int len, DESContext * scheds)
+{
     word32 out[2], iv0, iv1, xL, xR;
     unsigned int i;
 
@@ -697,17 +724,21 @@ static void des_cbc3_decrypt(unsigned char *dest, const unsigned char *src,
     iv0 = scheds->div0;
     iv1 = scheds->div1;
     for (i = 0; i < len; i += 8) {
-        xL = GET_32BIT_MSB_FIRST(src); src += 4;
-        xR = GET_32BIT_MSB_FIRST(src); src += 4;
-        des_decipher(out, xL, xR, &scheds[2]);
-        des_encipher(out, out[0], out[1], &scheds[1]);
-        des_decipher(out, out[0], out[1], &scheds[0]);
-        iv0 ^= out[0];
-        iv1 ^= out[1];
-        PUT_32BIT_MSB_FIRST(dest, iv0); dest += 4;
-        PUT_32BIT_MSB_FIRST(dest, iv1); dest += 4;
-        iv0 = xL;
-        iv1 = xR;
+       xL = GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       xR = GET_32BIT_MSB_FIRST(src);
+       src += 4;
+       des_decipher(out, xL, xR, &scheds[2]);
+       des_encipher(out, out[0], out[1], &scheds[1]);
+       des_decipher(out, out[0], out[1], &scheds[0]);
+       iv0 ^= out[0];
+       iv1 ^= out[1];
+       PUT_32BIT_MSB_FIRST(dest, iv0);
+       dest += 4;
+       PUT_32BIT_MSB_FIRST(dest, iv1);
+       dest += 4;
+       iv0 = xL;
+       iv1 = xR;
     }
     scheds->div0 = iv0;
     scheds->div1 = iv1;
@@ -715,78 +746,87 @@ static void des_cbc3_decrypt(unsigned char *dest, const unsigned char *src,
 
 static DESContext cskeys[3], sckeys[3];
 
-static void des3_cskey(unsigned char *key) {
+static void des3_cskey(unsigned char *key)
+{
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &cskeys[0]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+8),
-                  GET_32BIT_MSB_FIRST(key+12), &cskeys[1]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+16),
-                  GET_32BIT_MSB_FIRST(key+20), &cskeys[2]);
+                 GET_32BIT_MSB_FIRST(key + 4), &cskeys[0]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 8),
+                 GET_32BIT_MSB_FIRST(key + 12), &cskeys[1]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 16),
+                 GET_32BIT_MSB_FIRST(key + 20), &cskeys[2]);
     logevent("Initialised triple-DES client->server encryption");
 }
 
-static void des3_csiv(unsigned char *key) {
+static void des3_csiv(unsigned char *key)
+{
     cskeys[0].eiv0 = GET_32BIT_MSB_FIRST(key);
-    cskeys[0].eiv1 = GET_32BIT_MSB_FIRST(key+4);
+    cskeys[0].eiv1 = GET_32BIT_MSB_FIRST(key + 4);
 }
 
-static void des3_sciv(unsigned char *key) {
+static void des3_sciv(unsigned char *key)
+{
     sckeys[0].div0 = GET_32BIT_MSB_FIRST(key);
-    sckeys[0].div1 = GET_32BIT_MSB_FIRST(key+4);
+    sckeys[0].div1 = GET_32BIT_MSB_FIRST(key + 4);
 }
 
-static void des3_sckey(unsigned char *key) {
+static void des3_sckey(unsigned char *key)
+{
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &sckeys[0]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+8),
-                  GET_32BIT_MSB_FIRST(key+12), &sckeys[1]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+16),
-                  GET_32BIT_MSB_FIRST(key+20), &sckeys[2]);
+                 GET_32BIT_MSB_FIRST(key + 4), &sckeys[0]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 8),
+                 GET_32BIT_MSB_FIRST(key + 12), &sckeys[1]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 16),
+                 GET_32BIT_MSB_FIRST(key + 20), &sckeys[2]);
     logevent("Initialised triple-DES server->client encryption");
 }
 
-static void des3_sesskey(unsigned char *key) {
+static void des3_sesskey(unsigned char *key)
+{
     des3_cskey(key);
     des3_sckey(key);
 }
 
-static void des3_encrypt_blk(unsigned char *blk, int len) {
+static void des3_encrypt_blk(unsigned char *blk, int len)
+{
     des_3cbc_encrypt(blk, blk, len, cskeys);
 }
 
-static void des3_decrypt_blk(unsigned char *blk, int len) {
+static void des3_decrypt_blk(unsigned char *blk, int len)
+{
     des_3cbc_decrypt(blk, blk, len, sckeys);
 }
 
-static void des3_ssh2_encrypt_blk(unsigned char *blk, int len) {
+static void des3_ssh2_encrypt_blk(unsigned char *blk, int len)
+{
     des_cbc3_encrypt(blk, blk, len, cskeys);
 }
 
-static void des3_ssh2_decrypt_blk(unsigned char *blk, int len) {
+static void des3_ssh2_decrypt_blk(unsigned char *blk, int len)
+{
     des_cbc3_decrypt(blk, blk, len, sckeys);
 }
 
-void des3_decrypt_pubkey(unsigned char *key,
-                         unsigned char *blk, int len) {
+void des3_decrypt_pubkey(unsigned char *key, unsigned char *blk, int len)
+{
     DESContext ourkeys[3];
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &ourkeys[0]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+8),
-                  GET_32BIT_MSB_FIRST(key+12), &ourkeys[1]);
+                 GET_32BIT_MSB_FIRST(key + 4), &ourkeys[0]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 8),
+                 GET_32BIT_MSB_FIRST(key + 12), &ourkeys[1]);
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &ourkeys[2]);
+                 GET_32BIT_MSB_FIRST(key + 4), &ourkeys[2]);
     des_3cbc_decrypt(blk, blk, len, ourkeys);
 }
 
-void des3_encrypt_pubkey(unsigned char *key,
-                         unsigned char *blk, int len) {
+void des3_encrypt_pubkey(unsigned char *key, unsigned char *blk, int len)
+{
     DESContext ourkeys[3];
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &ourkeys[0]);
-    des_key_setup(GET_32BIT_MSB_FIRST(key+8),
-                  GET_32BIT_MSB_FIRST(key+12), &ourkeys[1]);
+                 GET_32BIT_MSB_FIRST(key + 4), &ourkeys[0]);
+    des_key_setup(GET_32BIT_MSB_FIRST(key + 8),
+                 GET_32BIT_MSB_FIRST(key + 12), &ourkeys[1]);
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &ourkeys[2]);
+                 GET_32BIT_MSB_FIRST(key + 4), &ourkeys[2]);
     des_3cbc_encrypt(blk, blk, len, ourkeys);
 }
 
@@ -815,17 +855,20 @@ const struct ssh_cipher ssh_3des = {
     8
 };
 
-static void des_sesskey(unsigned char *key) {
+static void des_sesskey(unsigned char *key)
+{
     des_key_setup(GET_32BIT_MSB_FIRST(key),
-                  GET_32BIT_MSB_FIRST(key+4), &cskeys[0]);
+                 GET_32BIT_MSB_FIRST(key + 4), &cskeys[0]);
     logevent("Initialised single-DES encryption");
 }
 
-static void des_encrypt_blk(unsigned char *blk, int len) {
+static void des_encrypt_blk(unsigned char *blk, int len)
+{
     des_cbc_encrypt(blk, blk, len, cskeys);
 }
 
-static void des_decrypt_blk(unsigned char *blk, int len) {
+static void des_decrypt_blk(unsigned char *blk, int len)
+{
     des_cbc_decrypt(blk, blk, len, cskeys);
 }
 
diff --git a/sshdh.c b/sshdh.c
index 845a72b..edd05b6 100644 (file)
--- a/sshdh.c
+++ b/sshdh.c
@@ -39,7 +39,8 @@ static int need_to_free_pg;
 /*
  * Common DH initialisation.
  */
-static void dh_init(void) {
+static void dh_init(void)
+{
     q = bignum_rshift(p, 1);
     qmask = bignum_bitmask(q);
 }
@@ -47,7 +48,8 @@ static void dh_init(void) {
 /*
  * Initialise DH for the standard group1.
  */
-void dh_setup_group1(void) {
+void dh_setup_group1(void)
+{
     p = bignum_from_bytes(P, sizeof(P));
     g = bignum_from_bytes(G, sizeof(G));
     dh_init();
@@ -56,7 +58,8 @@ void dh_setup_group1(void) {
 /*
  * Initialise DH for an alternative group.
  */
-void dh_setup_group(Bignum pval, Bignum gval) {
+void dh_setup_group(Bignum pval, Bignum gval)
+{
     p = copybn(pval);
     g = copybn(gval);
     dh_init();
@@ -65,7 +68,8 @@ void dh_setup_group(Bignum pval, Bignum gval) {
 /*
  * Clean up.
  */
-void dh_cleanup(void) {
+void dh_cleanup(void)
+{
     freebn(p);
     freebn(g);
     freebn(q);
@@ -87,7 +91,8 @@ void dh_cleanup(void) {
  * Advances in Cryptology: Proceedings of Eurocrypt '96
  * Springer-Verlag, May 1996.
  */
-Bignum dh_create_e(int nbits) {
+Bignum dh_create_e(int nbits)
+{
     int i;
 
     int nbytes;
@@ -101,7 +106,8 @@ Bignum dh_create_e(int nbits) {
         * Create a potential x, by ANDing a string of random bytes
         * with qmask.
         */
-        if (x) freebn(x);
+       if (x)
+           freebn(x);
        if (nbits == 0 || nbits > bignum_bitcount(qmask)) {
            ssh1_write_bignum(buf, qmask);
            for (i = 2; i < nbytes; i++)
@@ -134,7 +140,8 @@ Bignum dh_create_e(int nbits) {
 /*
  * DH stage 2: given a number f, compute K = f^x mod p.
  */
-Bignum dh_find_K(Bignum f) {
+Bignum dh_find_K(Bignum f)
+{
     Bignum ret;
     ret = modpow(f, x, p);
     return ret;
index 672a257..71ad59e 100644 (file)
--- a/sshdss.c
+++ b/sshdss.c
 #define diagbn(x,y)
 #endif
 
-static void getstring(char **data, int *datalen, char **p, int *length) {
+static void getstring(char **data, int *datalen, char **p, int *length)
+{
     *p = NULL;
     if (*datalen < 4)
-        return;
+       return;
     *length = GET_32BIT(*data);
-    *datalen -= 4; *data += 4;
+    *datalen -= 4;
+    *data += 4;
     if (*datalen < *length)
-        return;
+       return;
     *p = *data;
-    *data += *length; *datalen -= *length;
+    *data += *length;
+    *datalen -= *length;
 }
-static Bignum getmp(char **data, int *datalen) {
+static Bignum getmp(char **data, int *datalen)
+{
     char *p;
     int length;
     Bignum b;
 
     getstring(data, datalen, &p, &length);
     if (!p)
-        return NULL;
+       return NULL;
     if (p[0] & 0x80)
-        return NULL;                   /* negative mp */
+       return NULL;                   /* negative mp */
     b = bignum_from_bytes(p, length);
     return b;
 }
 
-static Bignum get160(char **data, int *datalen) {
+static Bignum get160(char **data, int *datalen)
+{
     Bignum b;
 
     b = bignum_from_bytes(*data, 20);
-    *data += 20; *datalen -= 20;
+    *data += 20;
+    *datalen -= 20;
 
     return b;
 }
@@ -60,22 +66,24 @@ struct dss_key {
     Bignum p, q, g, y;
 };
 
-static void *dss_newkey(char *data, int len) {
+static void *dss_newkey(char *data, int len)
+{
     char *p;
     int slen;
     struct dss_key *dss;
 
     dss = smalloc(sizeof(struct dss_key));
-    if (!dss) return NULL;
+    if (!dss)
+       return NULL;
     getstring(&data, &len, &p, &slen);
 
 #ifdef DEBUG_DSS
     {
-        int i;
-        printf("key:");
-        for (i=0;i<len;i++)
-            printf("  %02x", (unsigned char)(data[i]));
-        printf("\n");
+       int i;
+       printf("key:");
+       for (i = 0; i < len; i++)
+           printf("  %02x", (unsigned char) (data[i]));
+       printf("\n");
     }
 #endif
 
@@ -91,8 +99,9 @@ static void *dss_newkey(char *data, int len) {
     return dss;
 }
 
-static void dss_freekey(void *key) {
-    struct dss_key *dss = (struct dss_key *)key;
+static void dss_freekey(void *key)
+{
+    struct dss_key *dss = (struct dss_key *) key;
     freebn(dss->p);
     freebn(dss->q);
     freebn(dss->g);
@@ -100,47 +109,62 @@ static void dss_freekey(void *key) {
     sfree(dss);
 }
 
-static char *dss_fmtkey(void *key) {
-    struct dss_key *dss = (struct dss_key *)key;
+static char *dss_fmtkey(void *key)
+{
+    struct dss_key *dss = (struct dss_key *) key;
     char *p;
     int len, i, pos, nibbles;
     static const char hex[] = "0123456789abcdef";
     if (!dss->p)
-        return NULL;
-    len = 8 + 4 + 1;                   /* 4 x "0x", punctuation, \0 */
-    len += 4 * (bignum_bitcount(dss->p)+15)/16;
-    len += 4 * (bignum_bitcount(dss->q)+15)/16;
-    len += 4 * (bignum_bitcount(dss->g)+15)/16;
-    len += 4 * (bignum_bitcount(dss->y)+15)/16;
+       return NULL;
+    len = 8 + 4 + 1;                  /* 4 x "0x", punctuation, \0 */
+    len += 4 * (bignum_bitcount(dss->p) + 15) / 16;
+    len += 4 * (bignum_bitcount(dss->q) + 15) / 16;
+    len += 4 * (bignum_bitcount(dss->g) + 15) / 16;
+    len += 4 * (bignum_bitcount(dss->y) + 15) / 16;
     p = smalloc(len);
-    if (!p) return NULL;
+    if (!p)
+       return NULL;
 
     pos = 0;
-    pos += sprintf(p+pos, "0x");
-    nibbles = (3 + bignum_bitcount(dss->p))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        p[pos++] = hex[(bignum_byte(dss->p, i/2) >> (4*(i%2))) & 0xF];
-    pos += sprintf(p+pos, ",0x");
-    nibbles = (3 + bignum_bitcount(dss->q))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        p[pos++] = hex[(bignum_byte(dss->q, i/2) >> (4*(i%2))) & 0xF];
-    pos += sprintf(p+pos, ",0x");
-    nibbles = (3 + bignum_bitcount(dss->g))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        p[pos++] = hex[(bignum_byte(dss->g, i/2) >> (4*(i%2))) & 0xF];
-    pos += sprintf(p+pos, ",0x");
-    nibbles = (3 + bignum_bitcount(dss->y))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        p[pos++] = hex[(bignum_byte(dss->y, i/2) >> (4*(i%2))) & 0xF];
+    pos += sprintf(p + pos, "0x");
+    nibbles = (3 + bignum_bitcount(dss->p)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       p[pos++] =
+           hex[(bignum_byte(dss->p, i / 2) >> (4 * (i % 2))) & 0xF];
+    pos += sprintf(p + pos, ",0x");
+    nibbles = (3 + bignum_bitcount(dss->q)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       p[pos++] =
+           hex[(bignum_byte(dss->q, i / 2) >> (4 * (i % 2))) & 0xF];
+    pos += sprintf(p + pos, ",0x");
+    nibbles = (3 + bignum_bitcount(dss->g)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       p[pos++] =
+           hex[(bignum_byte(dss->g, i / 2) >> (4 * (i % 2))) & 0xF];
+    pos += sprintf(p + pos, ",0x");
+    nibbles = (3 + bignum_bitcount(dss->y)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       p[pos++] =
+           hex[(bignum_byte(dss->y, i / 2) >> (4 * (i % 2))) & 0xF];
     p[pos] = '\0';
     return p;
 }
 
-static char *dss_fingerprint(void *key) {
-    struct dss_key *dss = (struct dss_key *)key;
+static char *dss_fingerprint(void *key)
+{
+    struct dss_key *dss = (struct dss_key *) key;
     struct MD5Context md5c;
     unsigned char digest[16], lenbuf[4];
-    char buffer[16*3+40];
+    char buffer[16 * 3 + 40];
     char *ret;
     int numlen, i;
 
@@ -164,16 +188,18 @@ static char *dss_fingerprint(void *key) {
 
     sprintf(buffer, "ssh-dss %d ", bignum_bitcount(dss->p));
     for (i = 0; i < 16; i++)
-        sprintf(buffer+strlen(buffer), "%s%02x", i?":":"", digest[i]);
-    ret = smalloc(strlen(buffer)+1);
+       sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
+               digest[i]);
+    ret = smalloc(strlen(buffer) + 1);
     if (ret)
-        strcpy(ret, buffer);
+       strcpy(ret, buffer);
     return ret;
 }
 
 static int dss_verifysig(void *key, char *sig, int siglen,
-                        char *data, int datalen) {
-    struct dss_key *dss = (struct dss_key *)key;
+                        char *data, int datalen)
+{
+    struct dss_key *dss = (struct dss_key *) key;
     char *p;
     int slen;
     char hash[20];
@@ -181,15 +207,15 @@ static int dss_verifysig(void *key, char *sig, int siglen,
     int ret;
 
     if (!dss->p)
-        return 0;
+       return 0;
 
 #ifdef DEBUG_DSS
     {
-        int i;
-        printf("sig:");
-        for (i=0;i<siglen;i++)
-            printf("  %02x", (unsigned char)(sig[i]));
-        printf("\n");
+       int i;
+       printf("sig:");
+       for (i = 0; i < siglen; i++)
+           printf("  %02x", (unsigned char) (sig[i]));
+       printf("\n");
     }
 #endif
     /*
@@ -203,12 +229,12 @@ static int dss_verifysig(void *key, char *sig, int siglen,
      * the length: length 40 means the commercial-SSH bug, anything
      * else is assumed to be IETF-compliant.
      */
-    if (siglen != 40) {                /* bug not present; read admin fields */
-        getstring(&sig, &siglen, &p, &slen);
-        if (!p || slen != 7 || memcmp(p, "ssh-dss", 7)) {
-            return 0;
-        }
-        sig += 4, siglen -= 4;             /* skip yet another length field */
+    if (siglen != 40) {                       /* bug not present; read admin fields */
+       getstring(&sig, &siglen, &p, &slen);
+       if (!p || slen != 7 || memcmp(p, "ssh-dss", 7)) {
+           return 0;
+       }
+       sig += 4, siglen -= 4;         /* skip yet another length field */
     }
     diagbn("p=", dss->p);
     diagbn("q=", dss->q);
@@ -219,7 +245,7 @@ static int dss_verifysig(void *key, char *sig, int siglen,
     s = get160(&sig, &siglen);
     diagbn("s=", s);
     if (!r || !s)
-        return 0;
+       return 0;
 
     /*
      * Step 1. w <- s^-1 mod q.
@@ -231,7 +257,9 @@ static int dss_verifysig(void *key, char *sig, int siglen,
      * Step 2. u1 <- SHA(message) * w mod q.
      */
     SHA_Simple(data, datalen, hash);
-    p = hash; slen = 20; sha = get160(&p, &slen);
+    p = hash;
+    slen = 20;
+    sha = get160(&p, &slen);
     diagbn("sha=", sha);
     u1 = modmul(sha, w, dss->q);
     diagbn("u1=", u1);
@@ -273,57 +301,73 @@ static int dss_verifysig(void *key, char *sig, int siglen,
     return ret;
 }
 
-static unsigned char *dss_public_blob(void *key, int *len) {
-    struct dss_key *dss = (struct dss_key *)key;
+static unsigned char *dss_public_blob(void *key, int *len)
+{
+    struct dss_key *dss = (struct dss_key *) key;
     int plen, qlen, glen, ylen, bloblen;
     int i;
     unsigned char *blob, *p;
 
-    plen = (bignum_bitcount(dss->p)+8)/8;
-    qlen = (bignum_bitcount(dss->q)+8)/8;
-    glen = (bignum_bitcount(dss->g)+8)/8;
-    ylen = (bignum_bitcount(dss->y)+8)/8;
+    plen = (bignum_bitcount(dss->p) + 8) / 8;
+    qlen = (bignum_bitcount(dss->q) + 8) / 8;
+    glen = (bignum_bitcount(dss->g) + 8) / 8;
+    ylen = (bignum_bitcount(dss->y) + 8) / 8;
 
     /*
      * string "ssh-dss", mpint p, mpint q, mpint g, mpint y. Total
      * 27 + sum of lengths. (five length fields, 20+7=27).
      */
-    bloblen = 27+plen+qlen+glen+ylen;
+    bloblen = 27 + plen + qlen + glen + ylen;
     blob = smalloc(bloblen);
     p = blob;
-    PUT_32BIT(p, 7); p += 4;
-    memcpy(p, "ssh-dss", 7); p += 7;
-    PUT_32BIT(p, plen); p += 4;
-    for (i = plen; i-- ;) *p++ = bignum_byte(dss->p, i);
-    PUT_32BIT(p, qlen); p += 4;
-    for (i = qlen; i-- ;) *p++ = bignum_byte(dss->q, i);
-    PUT_32BIT(p, glen); p += 4;
-    for (i = glen; i-- ;) *p++ = bignum_byte(dss->g, i);
-    PUT_32BIT(p, ylen); p += 4;
-    for (i = ylen; i-- ;) *p++ = bignum_byte(dss->y, i);
+    PUT_32BIT(p, 7);
+    p += 4;
+    memcpy(p, "ssh-dss", 7);
+    p += 7;
+    PUT_32BIT(p, plen);
+    p += 4;
+    for (i = plen; i--;)
+       *p++ = bignum_byte(dss->p, i);
+    PUT_32BIT(p, qlen);
+    p += 4;
+    for (i = qlen; i--;)
+       *p++ = bignum_byte(dss->q, i);
+    PUT_32BIT(p, glen);
+    p += 4;
+    for (i = glen; i--;)
+       *p++ = bignum_byte(dss->g, i);
+    PUT_32BIT(p, ylen);
+    p += 4;
+    for (i = ylen; i--;)
+       *p++ = bignum_byte(dss->y, i);
     assert(p == blob + bloblen);
     *len = bloblen;
     return blob;
 }
 
-static unsigned char *dss_private_blob(void *key, int *len) {
+static unsigned char *dss_private_blob(void *key, int *len)
+{
     return NULL;                      /* can't handle DSS private keys */
 }
 
 static void *dss_createkey(unsigned char *pub_blob, int pub_len,
-                          unsigned char *priv_blob, int priv_len) {
+                          unsigned char *priv_blob, int priv_len)
+{
     return NULL;                      /* can't handle DSS private keys */
 }
 
-static void *dss_openssh_createkey(unsigned char **blob, int *len) {
+static void *dss_openssh_createkey(unsigned char **blob, int *len)
+{
     return NULL;                      /* can't handle DSS private keys */
 }
 
-static int dss_openssh_fmtkey(void *key, unsigned char *blob, int len) {
+static int dss_openssh_fmtkey(void *key, unsigned char *blob, int len)
+{
     return -1;                        /* can't handle DSS private keys */
 }
 
-unsigned char *dss_sign(void *key, char *data, int datalen, int *siglen) {
+unsigned char *dss_sign(void *key, char *data, int datalen, int *siglen)
+{
     return NULL;                      /* can't handle DSS private keys */
 }
 
index 2b0d5f5..0625f76 100644 (file)
--- a/sshmd5.c
+++ b/sshmd5.c
 #define subround(f,w,x,y,z,k,s,ti) \
        w = x + rol(w + f(x,y,z) + block[k] + ti, s)
 
-void MD5_Core_Init(MD5_Core_State *s) {
+void MD5_Core_Init(MD5_Core_State * s)
+{
     s->h[0] = 0x67452301;
     s->h[1] = 0xefcdab89;
     s->h[2] = 0x98badcfe;
     s->h[3] = 0x10325476;
 }
 
-void MD5_Block(MD5_Core_State *s, uint32 *block) {
-    uint32 a,b,c,d;
+void MD5_Block(MD5_Core_State * s, uint32 * block)
+{
+    uint32 a, b, c, d;
 
-    a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3];
+    a = s->h[0];
+    b = s->h[1];
+    c = s->h[2];
+    d = s->h[3];
 
     subround(F, a, b, c, d, 0, 7, 0xd76aa478);
     subround(F, d, a, b, c, 1, 12, 0xe8c7b756);
@@ -96,7 +101,10 @@ void MD5_Block(MD5_Core_State *s, uint32 *block) {
     subround(I, c, d, a, b, 2, 15, 0x2ad7d2bb);
     subround(I, b, c, d, a, 9, 21, 0xeb86d391);
 
-    s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d;
+    s->h[0] += a;
+    s->h[1] += b;
+    s->h[2] += c;
+    s->h[3] += d;
 }
 
 /* ----------------------------------------------------------------------
@@ -107,15 +115,16 @@ void MD5_Block(MD5_Core_State *s, uint32 *block) {
 
 #define BLKSIZE 64
 
-void MD5Init(struct MD5Context *s) {
+void MD5Init(struct MD5Context *s)
+{
     MD5_Core_Init(&s->core);
     s->blkused = 0;
     s->lenhi = s->lenlo = 0;
 }
 
-void MD5Update(struct MD5Context *s, unsigned char const *p,
-               unsigned len) {
-    unsigned char *q = (unsigned char *)p;
+void MD5Update(struct MD5Context *s, unsigned char const *p, unsigned len)
+{
+    unsigned char *q = (unsigned char *) p;
     uint32 wordblock[16];
     uint32 lenw = len;
     int i;
@@ -126,48 +135,49 @@ void MD5Update(struct MD5Context *s, unsigned char const *p,
     s->lenlo += lenw;
     s->lenhi += (s->lenlo < lenw);
 
-    if (s->blkused+len < BLKSIZE) {
-        /*
-         * Trivial case: just add to the block.
-         */
-        memcpy(s->block + s->blkused, q, len);
-        s->blkused += len;
+    if (s->blkused + len < BLKSIZE) {
+       /*
+        * Trivial case: just add to the block.
+        */
+       memcpy(s->block + s->blkused, q, len);
+       s->blkused += len;
     } else {
-        /*
-         * We must complete and process at least one block.
-         */
-        while (s->blkused + len >= BLKSIZE) {
-            memcpy(s->block + s->blkused, q, BLKSIZE - s->blkused);
-            q += BLKSIZE - s->blkused;
-            len -= BLKSIZE - s->blkused;
-            /* Now process the block. Gather bytes little-endian into words */
-            for (i = 0; i < 16; i++) {
-                wordblock[i] =
-                    ( ((uint32)s->block[i*4+3]) << 24 ) |
-                    ( ((uint32)s->block[i*4+2]) << 16 ) |
-                    ( ((uint32)s->block[i*4+1]) <<  8 ) |
-                    ( ((uint32)s->block[i*4+0]) <<  0 );
-            }
-            MD5_Block(&s->core, wordblock);
-            s->blkused = 0;
-        }
-        memcpy(s->block, q, len);
-        s->blkused = len;
+       /*
+        * We must complete and process at least one block.
+        */
+       while (s->blkused + len >= BLKSIZE) {
+           memcpy(s->block + s->blkused, q, BLKSIZE - s->blkused);
+           q += BLKSIZE - s->blkused;
+           len -= BLKSIZE - s->blkused;
+           /* Now process the block. Gather bytes little-endian into words */
+           for (i = 0; i < 16; i++) {
+               wordblock[i] =
+                   (((uint32) s->block[i * 4 + 3]) << 24) |
+                   (((uint32) s->block[i * 4 + 2]) << 16) |
+                   (((uint32) s->block[i * 4 + 1]) << 8) |
+                   (((uint32) s->block[i * 4 + 0]) << 0);
+           }
+           MD5_Block(&s->core, wordblock);
+           s->blkused = 0;
+       }
+       memcpy(s->block, q, len);
+       s->blkused = len;
     }
 }
 
-void MD5Final(unsigned char output[16], struct MD5Context *s) {
+void MD5Final(unsigned char output[16], struct MD5Context *s)
+{
     int i;
     unsigned pad;
     unsigned char c[64];
     uint32 lenhi, lenlo;
 
     if (s->blkused >= 56)
-        pad = 56 + 64 - s->blkused;
+       pad = 56 + 64 - s->blkused;
     else
-        pad = 56 - s->blkused;
+       pad = 56 - s->blkused;
 
-    lenhi = (s->lenhi << 3) | (s->lenlo >> (32-3));
+    lenhi = (s->lenhi << 3) | (s->lenlo >> (32 - 3));
     lenlo = (s->lenlo << 3);
 
     memset(c, 0, pad);
@@ -176,20 +186,20 @@ void MD5Final(unsigned char output[16], struct MD5Context *s) {
 
     c[7] = (lenhi >> 24) & 0xFF;
     c[6] = (lenhi >> 16) & 0xFF;
-    c[5] = (lenhi >>  8) & 0xFF;
-    c[4] = (lenhi >>  0) & 0xFF;
+    c[5] = (lenhi >> 8) & 0xFF;
+    c[4] = (lenhi >> 0) & 0xFF;
     c[3] = (lenlo >> 24) & 0xFF;
     c[2] = (lenlo >> 16) & 0xFF;
-    c[1] = (lenlo >>  8) & 0xFF;
-    c[0] = (lenlo >>  0) & 0xFF;
+    c[1] = (lenlo >> 8) & 0xFF;
+    c[0] = (lenlo >> 0) & 0xFF;
 
     MD5Update(s, c, 8);
 
     for (i = 0; i < 4; i++) {
-        output[4*i+3] = (s->core.h[i] >> 24) & 0xFF;
-        output[4*i+2] = (s->core.h[i] >> 16) & 0xFF;
-        output[4*i+1] = (s->core.h[i] >>  8) & 0xFF;
-        output[4*i+0] = (s->core.h[i] >>  0) & 0xFF;
+       output[4 * i + 3] = (s->core.h[i] >> 24) & 0xFF;
+       output[4 * i + 2] = (s->core.h[i] >> 16) & 0xFF;
+       output[4 * i + 1] = (s->core.h[i] >> 8) & 0xFF;
+       output[4 * i + 0] = (s->core.h[i] >> 0) & 0xFF;
     }
 }
 
@@ -202,61 +212,67 @@ static struct MD5Context md5_cs_mac_s1, md5_cs_mac_s2;
 static struct MD5Context md5_sc_mac_s1, md5_sc_mac_s2;
 
 static void md5_key(struct MD5Context *s1, struct MD5Context *s2,
-                    unsigned char *key, int len) {
+                   unsigned char *key, int len)
+{
     unsigned char foo[64];
     int i;
 
     memset(foo, 0x36, 64);
     for (i = 0; i < len && i < 64; i++)
-        foo[i] ^= key[i];
+       foo[i] ^= key[i];
     MD5Init(s1);
     MD5Update(s1, foo, 64);
 
     memset(foo, 0x5C, 64);
     for (i = 0; i < len && i < 64; i++)
-        foo[i] ^= key[i];
+       foo[i] ^= key[i];
     MD5Init(s2);
     MD5Update(s2, foo, 64);
 
-    memset(foo, 0, 64);                /* burn the evidence */
+    memset(foo, 0, 64);                       /* burn the evidence */
 }
 
-static void md5_cskey(unsigned char *key) {
+static void md5_cskey(unsigned char *key)
+{
     md5_key(&md5_cs_mac_s1, &md5_cs_mac_s2, key, 16);
 }
 
-static void md5_sckey(unsigned char *key) {
+static void md5_sckey(unsigned char *key)
+{
     md5_key(&md5_sc_mac_s1, &md5_sc_mac_s2, key, 16);
 }
 
 static void md5_do_hmac(struct MD5Context *s1, struct MD5Context *s2,
-                         unsigned char *blk, int len, unsigned long seq,
-                         unsigned char *hmac) {
+                       unsigned char *blk, int len, unsigned long seq,
+                       unsigned char *hmac)
+{
     struct MD5Context s;
     unsigned char intermediate[16];
 
-    intermediate[0] = (unsigned char)((seq >> 24) & 0xFF);
-    intermediate[1] = (unsigned char)((seq >> 16) & 0xFF);
-    intermediate[2] = (unsigned char)((seq >>  8) & 0xFF);
-    intermediate[3] = (unsigned char)((seq      ) & 0xFF);
+    intermediate[0] = (unsigned char) ((seq >> 24) & 0xFF);
+    intermediate[1] = (unsigned char) ((seq >> 16) & 0xFF);
+    intermediate[2] = (unsigned char) ((seq >> 8) & 0xFF);
+    intermediate[3] = (unsigned char) ((seq) & 0xFF);
 
-    s = *s1;                           /* structure copy */
+    s = *s1;                          /* structure copy */
     MD5Update(&s, intermediate, 4);
     MD5Update(&s, blk, len);
     MD5Final(intermediate, &s);
-    s = *s2;                           /* structure copy */
+    s = *s2;                          /* structure copy */
     MD5Update(&s, intermediate, 16);
     MD5Final(hmac, &s);
 }
 
-static void md5_generate(unsigned char *blk, int len, unsigned long seq) {
-    md5_do_hmac(&md5_cs_mac_s1, &md5_cs_mac_s2, blk, len, seq, blk+len);
+static void md5_generate(unsigned char *blk, int len, unsigned long seq)
+{
+    md5_do_hmac(&md5_cs_mac_s1, &md5_cs_mac_s2, blk, len, seq, blk + len);
 }
 
-static int md5_verify(unsigned char *blk, int len, unsigned long seq) {
+static int md5_verify(unsigned char *blk, int len, unsigned long seq)
+{
     unsigned char correct[16];
     md5_do_hmac(&md5_sc_mac_s1, &md5_sc_mac_s2, blk, len, seq, correct);
-    return !memcmp(correct, blk+len, 16);
+    return !memcmp(correct, blk + len, 16);
 }
 
 const struct ssh_mac ssh_md5 = {
index bd815e9..e6d3b3f 100644 (file)
  * for i in list[1:]: sys.stdout.write("%d," % i)
  */
 static const unsigned short primes[] = {
-    3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,
-    103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,
-    197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,
-    307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,
-    419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,
-    523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,
-    643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,
-    761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,
-    883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,
-    1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,
-    1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,
-    1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,
-    1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,
-    1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,
-    1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,
-    1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,
-    1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,
-    1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,
-    1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,
-    2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,
-    2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,
-    2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,
-    2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,
-    2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,
-    2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,
-    2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,
-    2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,
-    2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,
-    3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,
-    3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,
-    3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,
-    3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,
-    3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,
-    3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,
-    3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,
-    3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,
-    3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,
-    4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,
-    4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,
-    4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,
-    4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,
-    4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,
-    4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,
-    4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,
-    4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,
-    5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,
-    5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,
-    5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,
-    5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,
-    5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,
-    5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,
-    5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,
-    5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,
-    6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,
-    6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,
-    6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,
-    6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,
-    6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,
-    6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,
-    6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,
-    6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,
-    6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,
-    7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,
-    7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,
-    7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,
-    7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,
-    7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,
-    7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,
-    7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,
-    8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,
-    8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,
-    8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,
-    8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,
-    8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,
-    8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,
-    8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,
-    8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,
-    9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,
-    9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,
-    9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,
-    9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,
-    9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,
-    9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,
-    9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,
-    9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007,10009,10037,
-    10039,10061,10067,10069,10079,10091,10093,10099,10103,10111,10133,10139,
-    10141,10151,10159,10163,10169,10177,10181,10193,10211,10223,10243,10247,
-    10253,10259,10267,10271,10273,10289,10301,10303,10313,10321,10331,10333,
-    10337,10343,10357,10369,10391,10399,10427,10429,10433,10453,10457,10459,
-    10463,10477,10487,10499,10501,10513,10529,10531,10559,10567,10589,10597,
-    10601,10607,10613,10627,10631,10639,10651,10657,10663,10667,10687,10691,
-    10709,10711,10723,10729,10733,10739,10753,10771,10781,10789,10799,10831,
-    10837,10847,10853,10859,10861,10867,10883,10889,10891,10903,10909,10937,
-    10939,10949,10957,10973,10979,10987,10993,11003,11027,11047,11057,11059,
-    11069,11071,11083,11087,11093,11113,11117,11119,11131,11149,11159,11161,
-    11171,11173,11177,11197,11213,11239,11243,11251,11257,11261,11273,11279,
-    11287,11299,11311,11317,11321,11329,11351,11353,11369,11383,11393,11399,
-    11411,11423,11437,11443,11447,11467,11471,11483,11489,11491,11497,11503,
-    11519,11527,11549,11551,11579,11587,11593,11597,11617,11621,11633,11657,
-    11677,11681,11689,11699,11701,11717,11719,11731,11743,11777,11779,11783,
-    11789,11801,11807,11813,11821,11827,11831,11833,11839,11863,11867,11887,
-    11897,11903,11909,11923,11927,11933,11939,11941,11953,11959,11969,11971,
-    11981,11987,12007,12011,12037,12041,12043,12049,12071,12073,12097,12101,
-    12107,12109,12113,12119,12143,12149,12157,12161,12163,12197,12203,12211,
-    12227,12239,12241,12251,12253,12263,12269,12277,12281,12289,12301,12323,
-    12329,12343,12347,12373,12377,12379,12391,12401,12409,12413,12421,12433,
-    12437,12451,12457,12473,12479,12487,12491,12497,12503,12511,12517,12527,
-    12539,12541,12547,12553,12569,12577,12583,12589,12601,12611,12613,12619,
-    12637,12641,12647,12653,12659,12671,12689,12697,12703,12713,12721,12739,
-    12743,12757,12763,12781,12791,12799,12809,12821,12823,12829,12841,12853,
-    12889,12893,12899,12907,12911,12917,12919,12923,12941,12953,12959,12967,
-    12973,12979,12983,13001,13003,13007,13009,13033,13037,13043,13049,13063,
-    13093,13099,13103,13109,13121,13127,13147,13151,13159,13163,13171,13177,
-    13183,13187,13217,13219,13229,13241,13249,13259,13267,13291,13297,13309,
-    13313,13327,13331,13337,13339,13367,13381,13397,13399,13411,13417,13421,
-    13441,13451,13457,13463,13469,13477,13487,13499,13513,13523,13537,13553,
-    13567,13577,13591,13597,13613,13619,13627,13633,13649,13669,13679,13681,
-    13687,13691,13693,13697,13709,13711,13721,13723,13729,13751,13757,13759,
-    13763,13781,13789,13799,13807,13829,13831,13841,13859,13873,13877,13879,
-    13883,13901,13903,13907,13913,13921,13931,13933,13963,13967,13997,13999,
-    14009,14011,14029,14033,14051,14057,14071,14081,14083,14087,14107,14143,
-    14149,14153,14159,14173,14177,14197,14207,14221,14243,14249,14251,14281,
-    14293,14303,14321,14323,14327,14341,14347,14369,14387,14389,14401,14407,
-    14411,14419,14423,14431,14437,14447,14449,14461,14479,14489,14503,14519,
-    14533,14537,14543,14549,14551,14557,14561,14563,14591,14593,14621,14627,
-    14629,14633,14639,14653,14657,14669,14683,14699,14713,14717,14723,14731,
-    14737,14741,14747,14753,14759,14767,14771,14779,14783,14797,14813,14821,
-    14827,14831,14843,14851,14867,14869,14879,14887,14891,14897,14923,14929,
-    14939,14947,14951,14957,14969,14983,15013,15017,15031,15053,15061,15073,
-    15077,15083,15091,15101,15107,15121,15131,15137,15139,15149,15161,15173,
-    15187,15193,15199,15217,15227,15233,15241,15259,15263,15269,15271,15277,
-    15287,15289,15299,15307,15313,15319,15329,15331,15349,15359,15361,15373,
-    15377,15383,15391,15401,15413,15427,15439,15443,15451,15461,15467,15473,
-    15493,15497,15511,15527,15541,15551,15559,15569,15581,15583,15601,15607,
-    15619,15629,15641,15643,15647,15649,15661,15667,15671,15679,15683,15727,
-    15731,15733,15737,15739,15749,15761,15767,15773,15787,15791,15797,15803,
-    15809,15817,15823,15859,15877,15881,15887,15889,15901,15907,15913,15919,
-    15923,15937,15959,15971,15973,15991,16001,16007,16033,16057,16061,16063,
-    16067,16069,16073,16087,16091,16097,16103,16111,16127,16139,16141,16183,
-    16187,16189,16193,16217,16223,16229,16231,16249,16253,16267,16273,16301,
-    16319,16333,16339,16349,16361,16363,16369,16381,16411,16417,16421,16427,
-    16433,16447,16451,16453,16477,16481,16487,16493,16519,16529,16547,16553,
-    16561,16567,16573,16603,16607,16619,16631,16633,16649,16651,16657,16661,
-    16673,16691,16693,16699,16703,16729,16741,16747,16759,16763,16787,16811,
-    16823,16829,16831,16843,16871,16879,16883,16889,16901,16903,16921,16927,
-    16931,16937,16943,16963,16979,16981,16987,16993,17011,17021,17027,17029,
-    17033,17041,17047,17053,17077,17093,17099,17107,17117,17123,17137,17159,
-    17167,17183,17189,17191,17203,17207,17209,17231,17239,17257,17291,17293,
-    17299,17317,17321,17327,17333,17341,17351,17359,17377,17383,17387,17389,
-    17393,17401,17417,17419,17431,17443,17449,17467,17471,17477,17483,17489,
-    17491,17497,17509,17519,17539,17551,17569,17573,17579,17581,17597,17599,
-    17609,17623,17627,17657,17659,17669,17681,17683,17707,17713,17729,17737,
-    17747,17749,17761,17783,17789,17791,17807,17827,17837,17839,17851,17863,
-    17881,17891,17903,17909,17911,17921,17923,17929,17939,17957,17959,17971,
-    17977,17981,17987,17989,18013,18041,18043,18047,18049,18059,18061,18077,
-    18089,18097,18119,18121,18127,18131,18133,18143,18149,18169,18181,18191,
-    18199,18211,18217,18223,18229,18233,18251,18253,18257,18269,18287,18289,
-    18301,18307,18311,18313,18329,18341,18353,18367,18371,18379,18397,18401,
-    18413,18427,18433,18439,18443,18451,18457,18461,18481,18493,18503,18517,
-    18521,18523,18539,18541,18553,18583,18587,18593,18617,18637,18661,18671,
-    18679,18691,18701,18713,18719,18731,18743,18749,18757,18773,18787,18793,
-    18797,18803,18839,18859,18869,18899,18911,18913,18917,18919,18947,18959,
-    18973,18979,19001,19009,19013,19031,19037,19051,19069,19073,19079,19081,
-    19087,19121,19139,19141,19157,19163,19181,19183,19207,19211,19213,19219,
-    19231,19237,19249,19259,19267,19273,19289,19301,19309,19319,19333,19373,
-    19379,19381,19387,19391,19403,19417,19421,19423,19427,19429,19433,19441,
-    19447,19457,19463,19469,19471,19477,19483,19489,19501,19507,19531,19541,
-    19543,19553,19559,19571,19577,19583,19597,19603,19609,19661,19681,19687,
-    19697,19699,19709,19717,19727,19739,19751,19753,19759,19763,19777,19793,
-    19801,19813,19819,19841,19843,19853,19861,19867,19889,19891,19913,19919,
-    19927,19937,19949,19961,19963,19973,19979,19991,19993,19997,20011,20021,
-    20023,20029,20047,20051,20063,20071,20089,20101,20107,20113,20117,20123,
-    20129,20143,20147,20149,20161,20173,20177,20183,20201,20219,20231,20233,
-    20249,20261,20269,20287,20297,20323,20327,20333,20341,20347,20353,20357,
-    20359,20369,20389,20393,20399,20407,20411,20431,20441,20443,20477,20479,
-    20483,20507,20509,20521,20533,20543,20549,20551,20563,20593,20599,20611,
-    20627,20639,20641,20663,20681,20693,20707,20717,20719,20731,20743,20747,
-    20749,20753,20759,20771,20773,20789,20807,20809,20849,20857,20873,20879,
-    20887,20897,20899,20903,20921,20929,20939,20947,20959,20963,20981,20983,
-    21001,21011,21013,21017,21019,21023,21031,21059,21061,21067,21089,21101,
-    21107,21121,21139,21143,21149,21157,21163,21169,21179,21187,21191,21193,
-    21211,21221,21227,21247,21269,21277,21283,21313,21317,21319,21323,21341,
-    21347,21377,21379,21383,21391,21397,21401,21407,21419,21433,21467,21481,
-    21487,21491,21493,21499,21503,21517,21521,21523,21529,21557,21559,21563,
-    21569,21577,21587,21589,21599,21601,21611,21613,21617,21647,21649,21661,
-    21673,21683,21701,21713,21727,21737,21739,21751,21757,21767,21773,21787,
-    21799,21803,21817,21821,21839,21841,21851,21859,21863,21871,21881,21893,
-    21911,21929,21937,21943,21961,21977,21991,21997,22003,22013,22027,22031,
-    22037,22039,22051,22063,22067,22073,22079,22091,22093,22109,22111,22123,
-    22129,22133,22147,22153,22157,22159,22171,22189,22193,22229,22247,22259,
-    22271,22273,22277,22279,22283,22291,22303,22307,22343,22349,22367,22369,
-    22381,22391,22397,22409,22433,22441,22447,22453,22469,22481,22483,22501,
-    22511,22531,22541,22543,22549,22567,22571,22573,22613,22619,22621,22637,
-    22639,22643,22651,22669,22679,22691,22697,22699,22709,22717,22721,22727,
-    22739,22741,22751,22769,22777,22783,22787,22807,22811,22817,22853,22859,
-    22861,22871,22877,22901,22907,22921,22937,22943,22961,22963,22973,22993,
-    23003,23011,23017,23021,23027,23029,23039,23041,23053,23057,23059,23063,
-    23071,23081,23087,23099,23117,23131,23143,23159,23167,23173,23189,23197,
-    23201,23203,23209,23227,23251,23269,23279,23291,23293,23297,23311,23321,
-    23327,23333,23339,23357,23369,23371,23399,23417,23431,23447,23459,23473,
-    23497,23509,23531,23537,23539,23549,23557,23561,23563,23567,23581,23593,
-    23599,23603,23609,23623,23627,23629,23633,23663,23669,23671,23677,23687,
-    23689,23719,23741,23743,23747,23753,23761,23767,23773,23789,23801,23813,
-    23819,23827,23831,23833,23857,23869,23873,23879,23887,23893,23899,23909,
-    23911,23917,23929,23957,23971,23977,23981,23993,24001,24007,24019,24023,
-    24029,24043,24049,24061,24071,24077,24083,24091,24097,24103,24107,24109,
-    24113,24121,24133,24137,24151,24169,24179,24181,24197,24203,24223,24229,
-    24239,24247,24251,24281,24317,24329,24337,24359,24371,24373,24379,24391,
-    24407,24413,24419,24421,24439,24443,24469,24473,24481,24499,24509,24517,
-    24527,24533,24547,24551,24571,24593,24611,24623,24631,24659,24671,24677,
-    24683,24691,24697,24709,24733,24749,24763,24767,24781,24793,24799,24809,
-    24821,24841,24847,24851,24859,24877,24889,24907,24917,24919,24923,24943,
-    24953,24967,24971,24977,24979,24989,25013,25031,25033,25037,25057,25073,
-    25087,25097,25111,25117,25121,25127,25147,25153,25163,25169,25171,25183,
-    25189,25219,25229,25237,25243,25247,25253,25261,25301,25303,25307,25309,
-    25321,25339,25343,25349,25357,25367,25373,25391,25409,25411,25423,25439,
-    25447,25453,25457,25463,25469,25471,25523,25537,25541,25561,25577,25579,
-    25583,25589,25601,25603,25609,25621,25633,25639,25643,25657,25667,25673,
-    25679,25693,25703,25717,25733,25741,25747,25759,25763,25771,25793,25799,
-    25801,25819,25841,25847,25849,25867,25873,25889,25903,25913,25919,25931,
-    25933,25939,25943,25951,25969,25981,25997,25999,26003,26017,26021,26029,
-    26041,26053,26083,26099,26107,26111,26113,26119,26141,26153,26161,26171,
-    26177,26183,26189,26203,26209,26227,26237,26249,26251,26261,26263,26267,
-    26293,26297,26309,26317,26321,26339,26347,26357,26371,26387,26393,26399,
-    26407,26417,26423,26431,26437,26449,26459,26479,26489,26497,26501,26513,
-    26539,26557,26561,26573,26591,26597,26627,26633,26641,26647,26669,26681,
-    26683,26687,26693,26699,26701,26711,26713,26717,26723,26729,26731,26737,
-    26759,26777,26783,26801,26813,26821,26833,26839,26849,26861,26863,26879,
-    26881,26891,26893,26903,26921,26927,26947,26951,26953,26959,26981,26987,
-    26993,27011,27017,27031,27043,27059,27061,27067,27073,27077,27091,27103,
-    27107,27109,27127,27143,27179,27191,27197,27211,27239,27241,27253,27259,
-    27271,27277,27281,27283,27299,27329,27337,27361,27367,27397,27407,27409,
-    27427,27431,27437,27449,27457,27479,27481,27487,27509,27527,27529,27539,
-    27541,27551,27581,27583,27611,27617,27631,27647,27653,27673,27689,27691,
-    27697,27701,27733,27737,27739,27743,27749,27751,27763,27767,27773,27779,
-    27791,27793,27799,27803,27809,27817,27823,27827,27847,27851,27883,27893,
-    27901,27917,27919,27941,27943,27947,27953,27961,27967,27983,27997,28001,
-    28019,28027,28031,28051,28057,28069,28081,28087,28097,28099,28109,28111,
-    28123,28151,28163,28181,28183,28201,28211,28219,28229,28277,28279,28283,
-    28289,28297,28307,28309,28319,28349,28351,28387,28393,28403,28409,28411,
-    28429,28433,28439,28447,28463,28477,28493,28499,28513,28517,28537,28541,
-    28547,28549,28559,28571,28573,28579,28591,28597,28603,28607,28619,28621,
-    28627,28631,28643,28649,28657,28661,28663,28669,28687,28697,28703,28711,
-    28723,28729,28751,28753,28759,28771,28789,28793,28807,28813,28817,28837,
-    28843,28859,28867,28871,28879,28901,28909,28921,28927,28933,28949,28961,
-    28979,29009,29017,29021,29023,29027,29033,29059,29063,29077,29101,29123,
-    29129,29131,29137,29147,29153,29167,29173,29179,29191,29201,29207,29209,
-    29221,29231,29243,29251,29269,29287,29297,29303,29311,29327,29333,29339,
-    29347,29363,29383,29387,29389,29399,29401,29411,29423,29429,29437,29443,
-    29453,29473,29483,29501,29527,29531,29537,29567,29569,29573,29581,29587,
-    29599,29611,29629,29633,29641,29663,29669,29671,29683,29717,29723,29741,
-    29753,29759,29761,29789,29803,29819,29833,29837,29851,29863,29867,29873,
-    29879,29881,29917,29921,29927,29947,29959,29983,29989,30011,30013,30029,
-    30047,30059,30071,30089,30091,30097,30103,30109,30113,30119,30133,30137,
-    30139,30161,30169,30181,30187,30197,30203,30211,30223,30241,30253,30259,
-    30269,30271,30293,30307,30313,30319,30323,30341,30347,30367,30389,30391,
-    30403,30427,30431,30449,30467,30469,30491,30493,30497,30509,30517,30529,
-    30539,30553,30557,30559,30577,30593,30631,30637,30643,30649,30661,30671,
-    30677,30689,30697,30703,30707,30713,30727,30757,30763,30773,30781,30803,
-    30809,30817,30829,30839,30841,30851,30853,30859,30869,30871,30881,30893,
-    30911,30931,30937,30941,30949,30971,30977,30983,31013,31019,31033,31039,
-    31051,31063,31069,31079,31081,31091,31121,31123,31139,31147,31151,31153,
-    31159,31177,31181,31183,31189,31193,31219,31223,31231,31237,31247,31249,
-    31253,31259,31267,31271,31277,31307,31319,31321,31327,31333,31337,31357,
-    31379,31387,31391,31393,31397,31469,31477,31481,31489,31511,31513,31517,
-    31531,31541,31543,31547,31567,31573,31583,31601,31607,31627,31643,31649,
-    31657,31663,31667,31687,31699,31721,31723,31727,31729,31741,31751,31769,
-    31771,31793,31799,31817,31847,31849,31859,31873,31883,31891,31907,31957,
-    31963,31973,31981,31991,32003,32009,32027,32029,32051,32057,32059,32063,
-    32069,32077,32083,32089,32099,32117,32119,32141,32143,32159,32173,32183,
-    32189,32191,32203,32213,32233,32237,32251,32257,32261,32297,32299,32303,
-    32309,32321,32323,32327,32341,32353,32359,32363,32369,32371,32377,32381,
-    32401,32411,32413,32423,32429,32441,32443,32467,32479,32491,32497,32503,
-    32507,32531,32533,32537,32561,32563,32569,32573,32579,32587,32603,32609,
-    32611,32621,32633,32647,32653,32687,32693,32707,32713,32717,32719,32749,
-    32771,32779,32783,32789,32797,32801,32803,32831,32833,32839,32843,32869,
-    32887,32909,32911,32917,32933,32939,32941,32957,32969,32971,32983,32987,
-    32993,32999,33013,33023,33029,33037,33049,33053,33071,33073,33083,33091,
-    33107,33113,33119,33149,33151,33161,33179,33181,33191,33199,33203,33211,
-    33223,33247,33287,33289,33301,33311,33317,33329,33331,33343,33347,33349,
-    33353,33359,33377,33391,33403,33409,33413,33427,33457,33461,33469,33479,
-    33487,33493,33503,33521,33529,33533,33547,33563,33569,33577,33581,33587,
-    33589,33599,33601,33613,33617,33619,33623,33629,33637,33641,33647,33679,
-    33703,33713,33721,33739,33749,33751,33757,33767,33769,33773,33791,33797,
-    33809,33811,33827,33829,33851,33857,33863,33871,33889,33893,33911,33923,
-    33931,33937,33941,33961,33967,33997,34019,34031,34033,34039,34057,34061,
-    34123,34127,34129,34141,34147,34157,34159,34171,34183,34211,34213,34217,
-    34231,34253,34259,34261,34267,34273,34283,34297,34301,34303,34313,34319,
-    34327,34337,34351,34361,34367,34369,34381,34403,34421,34429,34439,34457,
-    34469,34471,34483,34487,34499,34501,34511,34513,34519,34537,34543,34549,
-    34583,34589,34591,34603,34607,34613,34631,34649,34651,34667,34673,34679,
-    34687,34693,34703,34721,34729,34739,34747,34757,34759,34763,34781,34807,
-    34819,34841,34843,34847,34849,34871,34877,34883,34897,34913,34919,34939,
-    34949,34961,34963,34981,35023,35027,35051,35053,35059,35069,35081,35083,
-    35089,35099,35107,35111,35117,35129,35141,35149,35153,35159,35171,35201,
-    35221,35227,35251,35257,35267,35279,35281,35291,35311,35317,35323,35327,
-    35339,35353,35363,35381,35393,35401,35407,35419,35423,35437,35447,35449,
-    35461,35491,35507,35509,35521,35527,35531,35533,35537,35543,35569,35573,
-    35591,35593,35597,35603,35617,35671,35677,35729,35731,35747,35753,35759,
-    35771,35797,35801,35803,35809,35831,35837,35839,35851,35863,35869,35879,
-    35897,35899,35911,35923,35933,35951,35963,35969,35977,35983,35993,35999,
-    36007,36011,36013,36017,36037,36061,36067,36073,36083,36097,36107,36109,
-    36131,36137,36151,36161,36187,36191,36209,36217,36229,36241,36251,36263,
-    36269,36277,36293,36299,36307,36313,36319,36341,36343,36353,36373,36383,
-    36389,36433,36451,36457,36467,36469,36473,36479,36493,36497,36523,36527,
-    36529,36541,36551,36559,36563,36571,36583,36587,36599,36607,36629,36637,
-    36643,36653,36671,36677,36683,36691,36697,36709,36713,36721,36739,36749,
-    36761,36767,36779,36781,36787,36791,36793,36809,36821,36833,36847,36857,
-    36871,36877,36887,36899,36901,36913,36919,36923,36929,36931,36943,36947,
-    36973,36979,36997,37003,37013,37019,37021,37039,37049,37057,37061,37087,
-    37097,37117,37123,37139,37159,37171,37181,37189,37199,37201,37217,37223,
-    37243,37253,37273,37277,37307,37309,37313,37321,37337,37339,37357,37361,
-    37363,37369,37379,37397,37409,37423,37441,37447,37463,37483,37489,37493,
-    37501,37507,37511,37517,37529,37537,37547,37549,37561,37567,37571,37573,
-    37579,37589,37591,37607,37619,37633,37643,37649,37657,37663,37691,37693,
-    37699,37717,37747,37781,37783,37799,37811,37813,37831,37847,37853,37861,
-    37871,37879,37889,37897,37907,37951,37957,37963,37967,37987,37991,37993,
-    37997,38011,38039,38047,38053,38069,38083,38113,38119,38149,38153,38167,
-    38177,38183,38189,38197,38201,38219,38231,38237,38239,38261,38273,38281,
-    38287,38299,38303,38317,38321,38327,38329,38333,38351,38371,38377,38393,
-    38431,38447,38449,38453,38459,38461,38501,38543,38557,38561,38567,38569,
-    38593,38603,38609,38611,38629,38639,38651,38653,38669,38671,38677,38693,
-    38699,38707,38711,38713,38723,38729,38737,38747,38749,38767,38783,38791,
-    38803,38821,38833,38839,38851,38861,38867,38873,38891,38903,38917,38921,
-    38923,38933,38953,38959,38971,38977,38993,39019,39023,39041,39043,39047,
-    39079,39089,39097,39103,39107,39113,39119,39133,39139,39157,39161,39163,
-    39181,39191,39199,39209,39217,39227,39229,39233,39239,39241,39251,39293,
-    39301,39313,39317,39323,39341,39343,39359,39367,39371,39373,39383,39397,
-    39409,39419,39439,39443,39451,39461,39499,39503,39509,39511,39521,39541,
-    39551,39563,39569,39581,39607,39619,39623,39631,39659,39667,39671,39679,
-    39703,39709,39719,39727,39733,39749,39761,39769,39779,39791,39799,39821,
-    39827,39829,39839,39841,39847,39857,39863,39869,39877,39883,39887,39901,
-    39929,39937,39953,39971,39979,39983,39989,40009,40013,40031,40037,40039,
-    40063,40087,40093,40099,40111,40123,40127,40129,40151,40153,40163,40169,
-    40177,40189,40193,40213,40231,40237,40241,40253,40277,40283,40289,40343,
-    40351,40357,40361,40387,40423,40427,40429,40433,40459,40471,40483,40487,
-    40493,40499,40507,40519,40529,40531,40543,40559,40577,40583,40591,40597,
-    40609,40627,40637,40639,40693,40697,40699,40709,40739,40751,40759,40763,
-    40771,40787,40801,40813,40819,40823,40829,40841,40847,40849,40853,40867,
-    40879,40883,40897,40903,40927,40933,40939,40949,40961,40973,40993,41011,
-    41017,41023,41039,41047,41051,41057,41077,41081,41113,41117,41131,41141,
-    41143,41149,41161,41177,41179,41183,41189,41201,41203,41213,41221,41227,
-    41231,41233,41243,41257,41263,41269,41281,41299,41333,41341,41351,41357,
-    41381,41387,41389,41399,41411,41413,41443,41453,41467,41479,41491,41507,
-    41513,41519,41521,41539,41543,41549,41579,41593,41597,41603,41609,41611,
-    41617,41621,41627,41641,41647,41651,41659,41669,41681,41687,41719,41729,
-    41737,41759,41761,41771,41777,41801,41809,41813,41843,41849,41851,41863,
-    41879,41887,41893,41897,41903,41911,41927,41941,41947,41953,41957,41959,
-    41969,41981,41983,41999,42013,42017,42019,42023,42043,42061,42071,42073,
-    42083,42089,42101,42131,42139,42157,42169,42179,42181,42187,42193,42197,
-    42209,42221,42223,42227,42239,42257,42281,42283,42293,42299,42307,42323,
-    42331,42337,42349,42359,42373,42379,42391,42397,42403,42407,42409,42433,
-    42437,42443,42451,42457,42461,42463,42467,42473,42487,42491,42499,42509,
-    42533,42557,42569,42571,42577,42589,42611,42641,42643,42649,42667,42677,
-    42683,42689,42697,42701,42703,42709,42719,42727,42737,42743,42751,42767,
-    42773,42787,42793,42797,42821,42829,42839,42841,42853,42859,42863,42899,
-    42901,42923,42929,42937,42943,42953,42961,42967,42979,42989,43003,43013,
-    43019,43037,43049,43051,43063,43067,43093,43103,43117,43133,43151,43159,
-    43177,43189,43201,43207,43223,43237,43261,43271,43283,43291,43313,43319,
-    43321,43331,43391,43397,43399,43403,43411,43427,43441,43451,43457,43481,
-    43487,43499,43517,43541,43543,43573,43577,43579,43591,43597,43607,43609,
-    43613,43627,43633,43649,43651,43661,43669,43691,43711,43717,43721,43753,
-    43759,43777,43781,43783,43787,43789,43793,43801,43853,43867,43889,43891,
-    43913,43933,43943,43951,43961,43963,43969,43973,43987,43991,43997,44017,
-    44021,44027,44029,44041,44053,44059,44071,44087,44089,44101,44111,44119,
-    44123,44129,44131,44159,44171,44179,44189,44201,44203,44207,44221,44249,
-    44257,44263,44267,44269,44273,44279,44281,44293,44351,44357,44371,44381,
-    44383,44389,44417,44449,44453,44483,44491,44497,44501,44507,44519,44531,
-    44533,44537,44543,44549,44563,44579,44587,44617,44621,44623,44633,44641,
-    44647,44651,44657,44683,44687,44699,44701,44711,44729,44741,44753,44771,
-    44773,44777,44789,44797,44809,44819,44839,44843,44851,44867,44879,44887,
-    44893,44909,44917,44927,44939,44953,44959,44963,44971,44983,44987,45007,
-    45013,45053,45061,45077,45083,45119,45121,45127,45131,45137,45139,45161,
-    45179,45181,45191,45197,45233,45247,45259,45263,45281,45289,45293,45307,
-    45317,45319,45329,45337,45341,45343,45361,45377,45389,45403,45413,45427,
-    45433,45439,45481,45491,45497,45503,45523,45533,45541,45553,45557,45569,
-    45587,45589,45599,45613,45631,45641,45659,45667,45673,45677,45691,45697,
-    45707,45737,45751,45757,45763,45767,45779,45817,45821,45823,45827,45833,
-    45841,45853,45863,45869,45887,45893,45943,45949,45953,45959,45971,45979,
-    45989,46021,46027,46049,46051,46061,46073,46091,46093,46099,46103,46133,
-    46141,46147,46153,46171,46181,46183,46187,46199,46219,46229,46237,46261,
-    46271,46273,46279,46301,46307,46309,46327,46337,46349,46351,46381,46399,
-    46411,46439,46441,46447,46451,46457,46471,46477,46489,46499,46507,46511,
-    46523,46549,46559,46567,46573,46589,46591,46601,46619,46633,46639,46643,
-    46649,46663,46679,46681,46687,46691,46703,46723,46727,46747,46751,46757,
-    46769,46771,46807,46811,46817,46819,46829,46831,46853,46861,46867,46877,
-    46889,46901,46919,46933,46957,46993,46997,47017,47041,47051,47057,47059,
-    47087,47093,47111,47119,47123,47129,47137,47143,47147,47149,47161,47189,
-    47207,47221,47237,47251,47269,47279,47287,47293,47297,47303,47309,47317,
-    47339,47351,47353,47363,47381,47387,47389,47407,47417,47419,47431,47441,
-    47459,47491,47497,47501,47507,47513,47521,47527,47533,47543,47563,47569,
-    47581,47591,47599,47609,47623,47629,47639,47653,47657,47659,47681,47699,
-    47701,47711,47713,47717,47737,47741,47743,47777,47779,47791,47797,47807,
-    47809,47819,47837,47843,47857,47869,47881,47903,47911,47917,47933,47939,
-    47947,47951,47963,47969,47977,47981,48017,48023,48029,48049,48073,48079,
-    48091,48109,48119,48121,48131,48157,48163,48179,48187,48193,48197,48221,
-    48239,48247,48259,48271,48281,48299,48311,48313,48337,48341,48353,48371,
-    48383,48397,48407,48409,48413,48437,48449,48463,48473,48479,48481,48487,
-    48491,48497,48523,48527,48533,48539,48541,48563,48571,48589,48593,48611,
-    48619,48623,48647,48649,48661,48673,48677,48679,48731,48733,48751,48757,
-    48761,48767,48779,48781,48787,48799,48809,48817,48821,48823,48847,48857,
-    48859,48869,48871,48883,48889,48907,48947,48953,48973,48989,48991,49003,
-    49009,49019,49031,49033,49037,49043,49057,49069,49081,49103,49109,49117,
-    49121,49123,49139,49157,49169,49171,49177,49193,49199,49201,49207,49211,
-    49223,49253,49261,49277,49279,49297,49307,49331,49333,49339,49363,49367,
-    49369,49391,49393,49409,49411,49417,49429,49433,49451,49459,49463,49477,
-    49481,49499,49523,49529,49531,49537,49547,49549,49559,49597,49603,49613,
-    49627,49633,49639,49663,49667,49669,49681,49697,49711,49727,49739,49741,
-    49747,49757,49783,49787,49789,49801,49807,49811,49823,49831,49843,49853,
-    49871,49877,49891,49919,49921,49927,49937,49939,49943,49957,49991,49993,
-    49999,50021,50023,50033,50047,50051,50053,50069,50077,50087,50093,50101,
-    50111,50119,50123,50129,50131,50147,50153,50159,50177,50207,50221,50227,
-    50231,50261,50263,50273,50287,50291,50311,50321,50329,50333,50341,50359,
-    50363,50377,50383,50387,50411,50417,50423,50441,50459,50461,50497,50503,
-    50513,50527,50539,50543,50549,50551,50581,50587,50591,50593,50599,50627,
-    50647,50651,50671,50683,50707,50723,50741,50753,50767,50773,50777,50789,
-    50821,50833,50839,50849,50857,50867,50873,50891,50893,50909,50923,50929,
-    50951,50957,50969,50971,50989,50993,51001,51031,51043,51047,51059,51061,
-    51071,51109,51131,51133,51137,51151,51157,51169,51193,51197,51199,51203,
-    51217,51229,51239,51241,51257,51263,51283,51287,51307,51329,51341,51343,
-    51347,51349,51361,51383,51407,51413,51419,51421,51427,51431,51437,51439,
-    51449,51461,51473,51479,51481,51487,51503,51511,51517,51521,51539,51551,
-    51563,51577,51581,51593,51599,51607,51613,51631,51637,51647,51659,51673,
-    51679,51683,51691,51713,51719,51721,51749,51767,51769,51787,51797,51803,
-    51817,51827,51829,51839,51853,51859,51869,51871,51893,51899,51907,51913,
-    51929,51941,51949,51971,51973,51977,51991,52009,52021,52027,52051,52057,
-    52067,52069,52081,52103,52121,52127,52147,52153,52163,52177,52181,52183,
-    52189,52201,52223,52237,52249,52253,52259,52267,52289,52291,52301,52313,
-    52321,52361,52363,52369,52379,52387,52391,52433,52453,52457,52489,52501,
-    52511,52517,52529,52541,52543,52553,52561,52567,52571,52579,52583,52609,
-    52627,52631,52639,52667,52673,52691,52697,52709,52711,52721,52727,52733,
-    52747,52757,52769,52783,52807,52813,52817,52837,52859,52861,52879,52883,
-    52889,52901,52903,52919,52937,52951,52957,52963,52967,52973,52981,52999,
-    53003,53017,53047,53051,53069,53077,53087,53089,53093,53101,53113,53117,
-    53129,53147,53149,53161,53171,53173,53189,53197,53201,53231,53233,53239,
-    53267,53269,53279,53281,53299,53309,53323,53327,53353,53359,53377,53381,
-    53401,53407,53411,53419,53437,53441,53453,53479,53503,53507,53527,53549,
-    53551,53569,53591,53593,53597,53609,53611,53617,53623,53629,53633,53639,
-    53653,53657,53681,53693,53699,53717,53719,53731,53759,53773,53777,53783,
-    53791,53813,53819,53831,53849,53857,53861,53881,53887,53891,53897,53899,
-    53917,53923,53927,53939,53951,53959,53987,53993,54001,54011,54013,54037,
-    54049,54059,54083,54091,54101,54121,54133,54139,54151,54163,54167,54181,
-    54193,54217,54251,54269,54277,54287,54293,54311,54319,54323,54331,54347,
-    54361,54367,54371,54377,54401,54403,54409,54413,54419,54421,54437,54443,
-    54449,54469,54493,54497,54499,54503,54517,54521,54539,54541,54547,54559,
-    54563,54577,54581,54583,54601,54617,54623,54629,54631,54647,54667,54673,
-    54679,54709,54713,54721,54727,54751,54767,54773,54779,54787,54799,54829,
-    54833,54851,54869,54877,54881,54907,54917,54919,54941,54949,54959,54973,
-    54979,54983,55001,55009,55021,55049,55051,55057,55061,55073,55079,55103,
-    55109,55117,55127,55147,55163,55171,55201,55207,55213,55217,55219,55229,
-    55243,55249,55259,55291,55313,55331,55333,55337,55339,55343,55351,55373,
-    55381,55399,55411,55439,55441,55457,55469,55487,55501,55511,55529,55541,
-    55547,55579,55589,55603,55609,55619,55621,55631,55633,55639,55661,55663,
-    55667,55673,55681,55691,55697,55711,55717,55721,55733,55763,55787,55793,
-    55799,55807,55813,55817,55819,55823,55829,55837,55843,55849,55871,55889,
-    55897,55901,55903,55921,55927,55931,55933,55949,55967,55987,55997,56003,
-    56009,56039,56041,56053,56081,56087,56093,56099,56101,56113,56123,56131,
-    56149,56167,56171,56179,56197,56207,56209,56237,56239,56249,56263,56267,
-    56269,56299,56311,56333,56359,56369,56377,56383,56393,56401,56417,56431,
-    56437,56443,56453,56467,56473,56477,56479,56489,56501,56503,56509,56519,
-    56527,56531,56533,56543,56569,56591,56597,56599,56611,56629,56633,56659,
-    56663,56671,56681,56687,56701,56711,56713,56731,56737,56747,56767,56773,
-    56779,56783,56807,56809,56813,56821,56827,56843,56857,56873,56891,56893,
-    56897,56909,56911,56921,56923,56929,56941,56951,56957,56963,56983,56989,
-    56993,56999,57037,57041,57047,57059,57073,57077,57089,57097,57107,57119,
-    57131,57139,57143,57149,57163,57173,57179,57191,57193,57203,57221,57223,
-    57241,57251,57259,57269,57271,57283,57287,57301,57329,57331,57347,57349,
-    57367,57373,57383,57389,57397,57413,57427,57457,57467,57487,57493,57503,
-    57527,57529,57557,57559,57571,57587,57593,57601,57637,57641,57649,57653,
-    57667,57679,57689,57697,57709,57713,57719,57727,57731,57737,57751,57773,
-    57781,57787,57791,57793,57803,57809,57829,57839,57847,57853,57859,57881,
-    57899,57901,57917,57923,57943,57947,57973,57977,57991,58013,58027,58031,
-    58043,58049,58057,58061,58067,58073,58099,58109,58111,58129,58147,58151,
-    58153,58169,58171,58189,58193,58199,58207,58211,58217,58229,58231,58237,
-    58243,58271,58309,58313,58321,58337,58363,58367,58369,58379,58391,58393,
-    58403,58411,58417,58427,58439,58441,58451,58453,58477,58481,58511,58537,
-    58543,58549,58567,58573,58579,58601,58603,58613,58631,58657,58661,58679,
-    58687,58693,58699,58711,58727,58733,58741,58757,58763,58771,58787,58789,
-    58831,58889,58897,58901,58907,58909,58913,58921,58937,58943,58963,58967,
-    58979,58991,58997,59009,59011,59021,59023,59029,59051,59053,59063,59069,
-    59077,59083,59093,59107,59113,59119,59123,59141,59149,59159,59167,59183,
-    59197,59207,59209,59219,59221,59233,59239,59243,59263,59273,59281,59333,
-    59341,59351,59357,59359,59369,59377,59387,59393,59399,59407,59417,59419,
-    59441,59443,59447,59453,59467,59471,59473,59497,59509,59513,59539,59557,
-    59561,59567,59581,59611,59617,59621,59627,59629,59651,59659,59663,59669,
-    59671,59693,59699,59707,59723,59729,59743,59747,59753,59771,59779,59791,
-    59797,59809,59833,59863,59879,59887,59921,59929,59951,59957,59971,59981,
-    59999,60013,60017,60029,60037,60041,60077,60083,60089,60091,60101,60103,
-    60107,60127,60133,60139,60149,60161,60167,60169,60209,60217,60223,60251,
-    60257,60259,60271,60289,60293,60317,60331,60337,60343,60353,60373,60383,
-    60397,60413,60427,60443,60449,60457,60493,60497,60509,60521,60527,60539,
-    60589,60601,60607,60611,60617,60623,60631,60637,60647,60649,60659,60661,
-    60679,60689,60703,60719,60727,60733,60737,60757,60761,60763,60773,60779,
-    60793,60811,60821,60859,60869,60887,60889,60899,60901,60913,60917,60919,
-    60923,60937,60943,60953,60961,61001,61007,61027,61031,61043,61051,61057,
-    61091,61099,61121,61129,61141,61151,61153,61169,61211,61223,61231,61253,
-    61261,61283,61291,61297,61331,61333,61339,61343,61357,61363,61379,61381,
-    61403,61409,61417,61441,61463,61469,61471,61483,61487,61493,61507,61511,
-    61519,61543,61547,61553,61559,61561,61583,61603,61609,61613,61627,61631,
-    61637,61643,61651,61657,61667,61673,61681,61687,61703,61717,61723,61729,
-    61751,61757,61781,61813,61819,61837,61843,61861,61871,61879,61909,61927,
-    61933,61949,61961,61967,61979,61981,61987,61991,62003,62011,62017,62039,
-    62047,62053,62057,62071,62081,62099,62119,62129,62131,62137,62141,62143,
-    62171,62189,62191,62201,62207,62213,62219,62233,62273,62297,62299,62303,
-    62311,62323,62327,62347,62351,62383,62401,62417,62423,62459,62467,62473,
-    62477,62483,62497,62501,62507,62533,62539,62549,62563,62581,62591,62597,
-    62603,62617,62627,62633,62639,62653,62659,62683,62687,62701,62723,62731,
-    62743,62753,62761,62773,62791,62801,62819,62827,62851,62861,62869,62873,
-    62897,62903,62921,62927,62929,62939,62969,62971,62981,62983,62987,62989,
-    63029,63031,63059,63067,63073,63079,63097,63103,63113,63127,63131,63149,
-    63179,63197,63199,63211,63241,63247,63277,63281,63299,63311,63313,63317,
-    63331,63337,63347,63353,63361,63367,63377,63389,63391,63397,63409,63419,
-    63421,63439,63443,63463,63467,63473,63487,63493,63499,63521,63527,63533,
-    63541,63559,63577,63587,63589,63599,63601,63607,63611,63617,63629,63647,
-    63649,63659,63667,63671,63689,63691,63697,63703,63709,63719,63727,63737,
-    63743,63761,63773,63781,63793,63799,63803,63809,63823,63839,63841,63853,
-    63857,63863,63901,63907,63913,63929,63949,63977,63997,64007,64013,64019,
-    64033,64037,64063,64067,64081,64091,64109,64123,64151,64153,64157,64171,
-    64187,64189,64217,64223,64231,64237,64271,64279,64283,64301,64303,64319,
-    64327,64333,64373,64381,64399,64403,64433,64439,64451,64453,64483,64489,
-    64499,64513,64553,64567,64577,64579,64591,64601,64609,64613,64621,64627,
-    64633,64661,64663,64667,64679,64693,64709,64717,64747,64763,64781,64783,
-    64793,64811,64817,64849,64853,64871,64877,64879,64891,64901,64919,64921,
-    64927,64937,64951,64969,64997,65003,65011,65027,65029,65033,65053,65063,
-    65071,65089,65099,65101,65111,65119,65123,65129,65141,65147,65167,65171,
-    65173,65179,65183,65203,65213,65239,65257,65267,65269,65287,65293,65309,
-    65323,65327,65353,65357,65371,65381,65393,65407,65413,65419,65423,65437,
-    65447,65449,65479,65497,65519,65521,
+    3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
+    71, 73, 79, 83, 89, 97, 101,
+    103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
+    179, 181, 191, 193,
+    197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271,
+    277, 281, 283, 293,
+    307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
+    389, 397, 401, 409,
+    419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
+    499, 503, 509, 521,
+    523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
+    617, 619, 631, 641,
+    643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
+    739, 743, 751, 757,
+    761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857,
+    859, 863, 877, 881,
+    883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
+    991, 997, 1009,
+    1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087,
+    1091, 1093,
+    1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187,
+    1193, 1201,
+    1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289,
+    1291, 1297,
+    1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409,
+    1423, 1427,
+    1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489,
+    1493, 1499,
+    1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597,
+    1601, 1607,
+    1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697,
+    1699, 1709,
+    1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801,
+    1811, 1823,
+    1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913,
+    1931, 1933,
+    1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027,
+    2029, 2039,
+    2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131,
+    2137, 2141,
+    2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251,
+    2267, 2269,
+    2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351,
+    2357, 2371,
+    2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447,
+    2459, 2467,
+    2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591,
+    2593, 2609,
+    2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689,
+    2693, 2699,
+    2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789,
+    2791, 2797,
+    2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897,
+    2903, 2909,
+    2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019,
+    3023, 3037,
+    3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163,
+    3167, 3169,
+    3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259,
+    3271, 3299,
+    3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371,
+    3373, 3389,
+    3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499,
+    3511, 3517,
+    3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593,
+    3607, 3613,
+    3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701,
+    3709, 3719,
+    3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823,
+    3833, 3847,
+    3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929,
+    3931, 3943,
+    3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051,
+    4057, 4073,
+    4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159,
+    4177, 4201,
+    4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273,
+    4283, 4289,
+    4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421,
+    4423, 4441,
+    4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523,
+    4547, 4549,
+    4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651,
+    4657, 4663,
+    4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787,
+    4789, 4793,
+    4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919,
+    4931, 4933,
+    4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009,
+    5011, 5021,
+    5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119,
+    5147, 5153,
+    5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273,
+    5279, 5281,
+    5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407,
+    5413, 5417,
+    5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503,
+    5507, 5519,
+    5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641,
+    5647, 5651,
+    5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741,
+    5743, 5749,
+    5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851,
+    5857, 5861,
+    5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987,
+    6007, 6011,
+    6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113,
+    6121, 6131,
+    6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229,
+    6247, 6257,
+    6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337,
+    6343, 6353,
+    6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469,
+    6473, 6481,
+    6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599,
+    6607, 6619,
+    6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719,
+    6733, 6737,
+    6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841,
+    6857, 6863,
+    6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967,
+    6971, 6977,
+    6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079,
+    7103, 7109,
+    7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219,
+    7229, 7237,
+    7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351,
+    7369, 7393,
+    7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507,
+    7517, 7523,
+    7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591,
+    7603, 7607,
+    7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717,
+    7723, 7727,
+    7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867,
+    7873, 7877,
+    7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993,
+    8009, 8011,
+    8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117,
+    8123, 8147,
+    8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243,
+    8263, 8269,
+    8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377,
+    8387, 8389,
+    8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527,
+    8537, 8539,
+    8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647,
+    8663, 8669,
+    8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747,
+    8753, 8761,
+    8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863,
+    8867, 8887,
+    8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007,
+    9011, 9013,
+    9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137,
+    9151, 9157,
+    9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257,
+    9277, 9281,
+    9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391,
+    9397, 9403,
+    9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479,
+    9491, 9497,
+    9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629,
+    9631, 9643,
+    9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749,
+    9767, 9769,
+    9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859,
+    9871, 9883,
+    9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007,
+    10009, 10037,
+    10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111,
+    10133, 10139,
+    10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223,
+    10243, 10247,
+    10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321,
+    10331, 10333,
+    10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453,
+    10457, 10459,
+    10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567,
+    10589, 10597,
+    10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667,
+    10687, 10691,
+    10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789,
+    10799, 10831,
+    10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903,
+    10909, 10937,
+    10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047,
+    11057, 11059,
+    11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149,
+    11159, 11161,
+    11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261,
+    11273, 11279,
+    11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383,
+    11393, 11399,
+    11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491,
+    11497, 11503,
+    11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621,
+    11633, 11657,
+    11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777,
+    11779, 11783,
+    11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863,
+    11867, 11887,
+    11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959,
+    11969, 11971,
+    11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073,
+    12097, 12101,
+    12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197,
+    12203, 12211,
+    12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289,
+    12301, 12323,
+    12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413,
+    12421, 12433,
+    12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511,
+    12517, 12527,
+    12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611,
+    12613, 12619,
+    12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713,
+    12721, 12739,
+    12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829,
+    12841, 12853,
+    12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953,
+    12959, 12967,
+    12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043,
+    13049, 13063,
+    13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163,
+    13171, 13177,
+    13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291,
+    13297, 13309,
+    13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411,
+    13417, 13421,
+    13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523,
+    13537, 13553,
+    13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669,
+    13679, 13681,
+    13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751,
+    13757, 13759,
+    13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873,
+    13877, 13879,
+    13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967,
+    13997, 13999,
+    14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087,
+    14107, 14143,
+    14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249,
+    14251, 14281,
+    14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389,
+    14401, 14407,
+    14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489,
+    14503, 14519,
+    14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593,
+    14621, 14627,
+    14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717,
+    14723, 14731,
+    14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797,
+    14813, 14821,
+    14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897,
+    14923, 14929,
+    14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053,
+    15061, 15073,
+    15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149,
+    15161, 15173,
+    15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269,
+    15271, 15277,
+    15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359,
+    15361, 15373,
+    15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461,
+    15467, 15473,
+    15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583,
+    15601, 15607,
+    15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679,
+    15683, 15727,
+    15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791,
+    15797, 15803,
+    15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907,
+    15913, 15919,
+    15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057,
+    16061, 16063,
+    16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139,
+    16141, 16183,
+    16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267,
+    16273, 16301,
+    16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417,
+    16421, 16427,
+    16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529,
+    16547, 16553,
+    16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651,
+    16657, 16661,
+    16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763,
+    16787, 16811,
+    16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903,
+    16921, 16927,
+    16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021,
+    17027, 17029,
+    17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123,
+    17137, 17159,
+    17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257,
+    17291, 17293,
+    17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383,
+    17387, 17389,
+    17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477,
+    17483, 17489,
+    17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581,
+    17597, 17599,
+    17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713,
+    17729, 17737,
+    17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839,
+    17851, 17863,
+    17881, 17891, 17903, 17909, 17911, 17921, 17923, 17929, 17939, 17957,
+    17959, 17971,
+    17977, 17981, 17987, 17989, 18013, 18041, 18043, 18047, 18049, 18059,
+    18061, 18077,
+    18089, 18097, 18119, 18121, 18127, 18131, 18133, 18143, 18149, 18169,
+    18181, 18191,
+    18199, 18211, 18217, 18223, 18229, 18233, 18251, 18253, 18257, 18269,
+    18287, 18289,
+    18301, 18307, 18311, 18313, 18329, 18341, 18353, 18367, 18371, 18379,
+    18397, 18401,
+    18413, 18427, 18433, 18439, 18443, 18451, 18457, 18461, 18481, 18493,
+    18503, 18517,
+    18521, 18523, 18539, 18541, 18553, 18583, 18587, 18593, 18617, 18637,
+    18661, 18671,
+    18679, 18691, 18701, 18713, 18719, 18731, 18743, 18749, 18757, 18773,
+    18787, 18793,
+    18797, 18803, 18839, 18859, 18869, 18899, 18911, 18913, 18917, 18919,
+    18947, 18959,
+    18973, 18979, 19001, 19009, 19013, 19031, 19037, 19051, 19069, 19073,
+    19079, 19081,
+    19087, 19121, 19139, 19141, 19157, 19163, 19181, 19183, 19207, 19211,
+    19213, 19219,
+    19231, 19237, 19249, 19259, 19267, 19273, 19289, 19301, 19309, 19319,
+    19333, 19373,
+    19379, 19381, 19387, 19391, 19403, 19417, 19421, 19423, 19427, 19429,
+    19433, 19441,
+    19447, 19457, 19463, 19469, 19471, 19477, 19483, 19489, 19501, 19507,
+    19531, 19541,
+    19543, 19553, 19559, 19571, 19577, 19583, 19597, 19603, 19609, 19661,
+    19681, 19687,
+    19697, 19699, 19709, 19717, 19727, 19739, 19751, 19753, 19759, 19763,
+    19777, 19793,
+    19801, 19813, 19819, 19841, 19843, 19853, 19861, 19867, 19889, 19891,
+    19913, 19919,
+    19927, 19937, 19949, 19961, 19963, 19973, 19979, 19991, 19993, 19997,
+    20011, 20021,
+    20023, 20029, 20047, 20051, 20063, 20071, 20089, 20101, 20107, 20113,
+    20117, 20123,
+    20129, 20143, 20147, 20149, 20161, 20173, 20177, 20183, 20201, 20219,
+    20231, 20233,
+    20249, 20261, 20269, 20287, 20297, 20323, 20327, 20333, 20341, 20347,
+    20353, 20357,
+    20359, 20369, 20389, 20393, 20399, 20407, 20411, 20431, 20441, 20443,
+    20477, 20479,
+    20483, 20507, 20509, 20521, 20533, 20543, 20549, 20551, 20563, 20593,
+    20599, 20611,
+    20627, 20639, 20641, 20663, 20681, 20693, 20707, 20717, 20719, 20731,
+    20743, 20747,
+    20749, 20753, 20759, 20771, 20773, 20789, 20807, 20809, 20849, 20857,
+    20873, 20879,
+    20887, 20897, 20899, 20903, 20921, 20929, 20939, 20947, 20959, 20963,
+    20981, 20983,
+    21001, 21011, 21013, 21017, 21019, 21023, 21031, 21059, 21061, 21067,
+    21089, 21101,
+    21107, 21121, 21139, 21143, 21149, 21157, 21163, 21169, 21179, 21187,
+    21191, 21193,
+    21211, 21221, 21227, 21247, 21269, 21277, 21283, 21313, 21317, 21319,
+    21323, 21341,
+    21347, 21377, 21379, 21383, 21391, 21397, 21401, 21407, 21419, 21433,
+    21467, 21481,
+    21487, 21491, 21493, 21499, 21503, 21517, 21521, 21523, 21529, 21557,
+    21559, 21563,
+    21569, 21577, 21587, 21589, 21599, 21601, 21611, 21613, 21617, 21647,
+    21649, 21661,
+    21673, 21683, 21701, 21713, 21727, 21737, 21739, 21751, 21757, 21767,
+    21773, 21787,
+    21799, 21803, 21817, 21821, 21839, 21841, 21851, 21859, 21863, 21871,
+    21881, 21893,
+    21911, 21929, 21937, 21943, 21961, 21977, 21991, 21997, 22003, 22013,
+    22027, 22031,
+    22037, 22039, 22051, 22063, 22067, 22073, 22079, 22091, 22093, 22109,
+    22111, 22123,
+    22129, 22133, 22147, 22153, 22157, 22159, 22171, 22189, 22193, 22229,
+    22247, 22259,
+    22271, 22273, 22277, 22279, 22283, 22291, 22303, 22307, 22343, 22349,
+    22367, 22369,
+    22381, 22391, 22397, 22409, 22433, 22441, 22447, 22453, 22469, 22481,
+    22483, 22501,
+    22511, 22531, 22541, 22543, 22549, 22567, 22571, 22573, 22613, 22619,
+    22621, 22637,
+    22639, 22643, 22651, 22669, 22679, 22691, 22697, 22699, 22709, 22717,
+    22721, 22727,
+    22739, 22741, 22751, 22769, 22777, 22783, 22787, 22807, 22811, 22817,
+    22853, 22859,
+    22861, 22871, 22877, 22901, 22907, 22921, 22937, 22943, 22961, 22963,
+    22973, 22993,
+    23003, 23011, 23017, 23021, 23027, 23029, 23039, 23041, 23053, 23057,
+    23059, 23063,
+    23071, 23081, 23087, 23099, 23117, 23131, 23143, 23159, 23167, 23173,
+    23189, 23197,
+    23201, 23203, 23209, 23227, 23251, 23269, 23279, 23291, 23293, 23297,
+    23311, 23321,
+    23327, 23333, 23339, 23357, 23369, 23371, 23399, 23417, 23431, 23447,
+    23459, 23473,
+    23497, 23509, 23531, 23537, 23539, 23549, 23557, 23561, 23563, 23567,
+    23581, 23593,
+    23599, 23603, 23609, 23623, 23627, 23629, 23633, 23663, 23669, 23671,
+    23677, 23687,
+    23689, 23719, 23741, 23743, 23747, 23753, 23761, 23767, 23773, 23789,
+    23801, 23813,
+    23819, 23827, 23831, 23833, 23857, 23869, 23873, 23879, 23887, 23893,
+    23899, 23909,
+    23911, 23917, 23929, 23957, 23971, 23977, 23981, 23993, 24001, 24007,
+    24019, 24023,
+    24029, 24043, 24049, 24061, 24071, 24077, 24083, 24091, 24097, 24103,
+    24107, 24109,
+    24113, 24121, 24133, 24137, 24151, 24169, 24179, 24181, 24197, 24203,
+    24223, 24229,
+    24239, 24247, 24251, 24281, 24317, 24329, 24337, 24359, 24371, 24373,
+    24379, 24391,
+    24407, 24413, 24419, 24421, 24439, 24443, 24469, 24473, 24481, 24499,
+    24509, 24517,
+    24527, 24533, 24547, 24551, 24571, 24593, 24611, 24623, 24631, 24659,
+    24671, 24677,
+    24683, 24691, 24697, 24709, 24733, 24749, 24763, 24767, 24781, 24793,
+    24799, 24809,
+    24821, 24841, 24847, 24851, 24859, 24877, 24889, 24907, 24917, 24919,
+    24923, 24943,
+    24953, 24967, 24971, 24977, 24979, 24989, 25013, 25031, 25033, 25037,
+    25057, 25073,
+    25087, 25097, 25111, 25117, 25121, 25127, 25147, 25153, 25163, 25169,
+    25171, 25183,
+    25189, 25219, 25229, 25237, 25243, 25247, 25253, 25261, 25301, 25303,
+    25307, 25309,
+    25321, 25339, 25343, 25349, 25357, 25367, 25373, 25391, 25409, 25411,
+    25423, 25439,
+    25447, 25453, 25457, 25463, 25469, 25471, 25523, 25537, 25541, 25561,
+    25577, 25579,
+    25583, 25589, 25601, 25603, 25609, 25621, 25633, 25639, 25643, 25657,
+    25667, 25673,
+    25679, 25693, 25703, 25717, 25733, 25741, 25747, 25759, 25763, 25771,
+    25793, 25799,
+    25801, 25819, 25841, 25847, 25849, 25867, 25873, 25889, 25903, 25913,
+    25919, 25931,
+    25933, 25939, 25943, 25951, 25969, 25981, 25997, 25999, 26003, 26017,
+    26021, 26029,
+    26041, 26053, 26083, 26099, 26107, 26111, 26113, 26119, 26141, 26153,
+    26161, 26171,
+    26177, 26183, 26189, 26203, 26209, 26227, 26237, 26249, 26251, 26261,
+    26263, 26267,
+    26293, 26297, 26309, 26317, 26321, 26339, 26347, 26357, 26371, 26387,
+    26393, 26399,
+    26407, 26417, 26423, 26431, 26437, 26449, 26459, 26479, 26489, 26497,
+    26501, 26513,
+    26539, 26557, 26561, 26573, 26591, 26597, 26627, 26633, 26641, 26647,
+    26669, 26681,
+    26683, 26687, 26693, 26699, 26701, 26711, 26713, 26717, 26723, 26729,
+    26731, 26737,
+    26759, 26777, 26783, 26801, 26813, 26821, 26833, 26839, 26849, 26861,
+    26863, 26879,
+    26881, 26891, 26893, 26903, 26921, 26927, 26947, 26951, 26953, 26959,
+    26981, 26987,
+    26993, 27011, 27017, 27031, 27043, 27059, 27061, 27067, 27073, 27077,
+    27091, 27103,
+    27107, 27109, 27127, 27143, 27179, 27191, 27197, 27211, 27239, 27241,
+    27253, 27259,
+    27271, 27277, 27281, 27283, 27299, 27329, 27337, 27361, 27367, 27397,
+    27407, 27409,
+    27427, 27431, 27437, 27449, 27457, 27479, 27481, 27487, 27509, 27527,
+    27529, 27539,
+    27541, 27551, 27581, 27583, 27611, 27617, 27631, 27647, 27653, 27673,
+    27689, 27691,
+    27697, 27701, 27733, 27737, 27739, 27743, 27749, 27751, 27763, 27767,
+    27773, 27779,
+    27791, 27793, 27799, 27803, 27809, 27817, 27823, 27827, 27847, 27851,
+    27883, 27893,
+    27901, 27917, 27919, 27941, 27943, 27947, 27953, 27961, 27967, 27983,
+    27997, 28001,
+    28019, 28027, 28031, 28051, 28057, 28069, 28081, 28087, 28097, 28099,
+    28109, 28111,
+    28123, 28151, 28163, 28181, 28183, 28201, 28211, 28219, 28229, 28277,
+    28279, 28283,
+    28289, 28297, 28307, 28309, 28319, 28349, 28351, 28387, 28393, 28403,
+    28409, 28411,
+    28429, 28433, 28439, 28447, 28463, 28477, 28493, 28499, 28513, 28517,
+    28537, 28541,
+    28547, 28549, 28559, 28571, 28573, 28579, 28591, 28597, 28603, 28607,
+    28619, 28621,
+    28627, 28631, 28643, 28649, 28657, 28661, 28663, 28669, 28687, 28697,
+    28703, 28711,
+    28723, 28729, 28751, 28753, 28759, 28771, 28789, 28793, 28807, 28813,
+    28817, 28837,
+    28843, 28859, 28867, 28871, 28879, 28901, 28909, 28921, 28927, 28933,
+    28949, 28961,
+    28979, 29009, 29017, 29021, 29023, 29027, 29033, 29059, 29063, 29077,
+    29101, 29123,
+    29129, 29131, 29137, 29147, 29153, 29167, 29173, 29179, 29191, 29201,
+    29207, 29209,
+    29221, 29231, 29243, 29251, 29269, 29287, 29297, 29303, 29311, 29327,
+    29333, 29339,
+    29347, 29363, 29383, 29387, 29389, 29399, 29401, 29411, 29423, 29429,
+    29437, 29443,
+    29453, 29473, 29483, 29501, 29527, 29531, 29537, 29567, 29569, 29573,
+    29581, 29587,
+    29599, 29611, 29629, 29633, 29641, 29663, 29669, 29671, 29683, 29717,
+    29723, 29741,
+    29753, 29759, 29761, 29789, 29803, 29819, 29833, 29837, 29851, 29863,
+    29867, 29873,
+    29879, 29881, 29917, 29921, 29927, 29947, 29959, 29983, 29989, 30011,
+    30013, 30029,
+    30047, 30059, 30071, 30089, 30091, 30097, 30103, 30109, 30113, 30119,
+    30133, 30137,
+    30139, 30161, 30169, 30181, 30187, 30197, 30203, 30211, 30223, 30241,
+    30253, 30259,
+    30269, 30271, 30293, 30307, 30313, 30319, 30323, 30341, 30347, 30367,
+    30389, 30391,
+    30403, 30427, 30431, 30449, 30467, 30469, 30491, 30493, 30497, 30509,
+    30517, 30529,
+    30539, 30553, 30557, 30559, 30577, 30593, 30631, 30637, 30643, 30649,
+    30661, 30671,
+    30677, 30689, 30697, 30703, 30707, 30713, 30727, 30757, 30763, 30773,
+    30781, 30803,
+    30809, 30817, 30829, 30839, 30841, 30851, 30853, 30859, 30869, 30871,
+    30881, 30893,
+    30911, 30931, 30937, 30941, 30949, 30971, 30977, 30983, 31013, 31019,
+    31033, 31039,
+    31051, 31063, 31069, 31079, 31081, 31091, 31121, 31123, 31139, 31147,
+    31151, 31153,
+    31159, 31177, 31181, 31183, 31189, 31193, 31219, 31223, 31231, 31237,
+    31247, 31249,
+    31253, 31259, 31267, 31271, 31277, 31307, 31319, 31321, 31327, 31333,
+    31337, 31357,
+    31379, 31387, 31391, 31393, 31397, 31469, 31477, 31481, 31489, 31511,
+    31513, 31517,
+    31531, 31541, 31543, 31547, 31567, 31573, 31583, 31601, 31607, 31627,
+    31643, 31649,
+    31657, 31663, 31667, 31687, 31699, 31721, 31723, 31727, 31729, 31741,
+    31751, 31769,
+    31771, 31793, 31799, 31817, 31847, 31849, 31859, 31873, 31883, 31891,
+    31907, 31957,
+    31963, 31973, 31981, 31991, 32003, 32009, 32027, 32029, 32051, 32057,
+    32059, 32063,
+    32069, 32077, 32083, 32089, 32099, 32117, 32119, 32141, 32143, 32159,
+    32173, 32183,
+    32189, 32191, 32203, 32213, 32233, 32237, 32251, 32257, 32261, 32297,
+    32299, 32303,
+    32309, 32321, 32323, 32327, 32341, 32353, 32359, 32363, 32369, 32371,
+    32377, 32381,
+    32401, 32411, 32413, 32423, 32429, 32441, 32443, 32467, 32479, 32491,
+    32497, 32503,
+    32507, 32531, 32533, 32537, 32561, 32563, 32569, 32573, 32579, 32587,
+    32603, 32609,
+    32611, 32621, 32633, 32647, 32653, 32687, 32693, 32707, 32713, 32717,
+    32719, 32749,
+    32771, 32779, 32783, 32789, 32797, 32801, 32803, 32831, 32833, 32839,
+    32843, 32869,
+    32887, 32909, 32911, 32917, 32933, 32939, 32941, 32957, 32969, 32971,
+    32983, 32987,
+    32993, 32999, 33013, 33023, 33029, 33037, 33049, 33053, 33071, 33073,
+    33083, 33091,
+    33107, 33113, 33119, 33149, 33151, 33161, 33179, 33181, 33191, 33199,
+    33203, 33211,
+    33223, 33247, 33287, 33289, 33301, 33311, 33317, 33329, 33331, 33343,
+    33347, 33349,
+    33353, 33359, 33377, 33391, 33403, 33409, 33413, 33427, 33457, 33461,
+    33469, 33479,
+    33487, 33493, 33503, 33521, 33529, 33533, 33547, 33563, 33569, 33577,
+    33581, 33587,
+    33589, 33599, 33601, 33613, 33617, 33619, 33623, 33629, 33637, 33641,
+    33647, 33679,
+    33703, 33713, 33721, 33739, 33749, 33751, 33757, 33767, 33769, 33773,
+    33791, 33797,
+    33809, 33811, 33827, 33829, 33851, 33857, 33863, 33871, 33889, 33893,
+    33911, 33923,
+    33931, 33937, 33941, 33961, 33967, 33997, 34019, 34031, 34033, 34039,
+    34057, 34061,
+    34123, 34127, 34129, 34141, 34147, 34157, 34159, 34171, 34183, 34211,
+    34213, 34217,
+    34231, 34253, 34259, 34261, 34267, 34273, 34283, 34297, 34301, 34303,
+    34313, 34319,
+    34327, 34337, 34351, 34361, 34367, 34369, 34381, 34403, 34421, 34429,
+    34439, 34457,
+    34469, 34471, 34483, 34487, 34499, 34501, 34511, 34513, 34519, 34537,
+    34543, 34549,
+    34583, 34589, 34591, 34603, 34607, 34613, 34631, 34649, 34651, 34667,
+    34673, 34679,
+    34687, 34693, 34703, 34721, 34729, 34739, 34747, 34757, 34759, 34763,
+    34781, 34807,
+    34819, 34841, 34843, 34847, 34849, 34871, 34877, 34883, 34897, 34913,
+    34919, 34939,
+    34949, 34961, 34963, 34981, 35023, 35027, 35051, 35053, 35059, 35069,
+    35081, 35083,
+    35089, 35099, 35107, 35111, 35117, 35129, 35141, 35149, 35153, 35159,
+    35171, 35201,
+    35221, 35227, 35251, 35257, 35267, 35279, 35281, 35291, 35311, 35317,
+    35323, 35327,
+    35339, 35353, 35363, 35381, 35393, 35401, 35407, 35419, 35423, 35437,
+    35447, 35449,
+    35461, 35491, 35507, 35509, 35521, 35527, 35531, 35533, 35537, 35543,
+    35569, 35573,
+    35591, 35593, 35597, 35603, 35617, 35671, 35677, 35729, 35731, 35747,
+    35753, 35759,
+    35771, 35797, 35801, 35803, 35809, 35831, 35837, 35839, 35851, 35863,
+    35869, 35879,
+    35897, 35899, 35911, 35923, 35933, 35951, 35963, 35969, 35977, 35983,
+    35993, 35999,
+    36007, 36011, 36013, 36017, 36037, 36061, 36067, 36073, 36083, 36097,
+    36107, 36109,
+    36131, 36137, 36151, 36161, 36187, 36191, 36209, 36217, 36229, 36241,
+    36251, 36263,
+    36269, 36277, 36293, 36299, 36307, 36313, 36319, 36341, 36343, 36353,
+    36373, 36383,
+    36389, 36433, 36451, 36457, 36467, 36469, 36473, 36479, 36493, 36497,
+    36523, 36527,
+    36529, 36541, 36551, 36559, 36563, 36571, 36583, 36587, 36599, 36607,
+    36629, 36637,
+    36643, 36653, 36671, 36677, 36683, 36691, 36697, 36709, 36713, 36721,
+    36739, 36749,
+    36761, 36767, 36779, 36781, 36787, 36791, 36793, 36809, 36821, 36833,
+    36847, 36857,
+    36871, 36877, 36887, 36899, 36901, 36913, 36919, 36923, 36929, 36931,
+    36943, 36947,
+    36973, 36979, 36997, 37003, 37013, 37019, 37021, 37039, 37049, 37057,
+    37061, 37087,
+    37097, 37117, 37123, 37139, 37159, 37171, 37181, 37189, 37199, 37201,
+    37217, 37223,
+    37243, 37253, 37273, 37277, 37307, 37309, 37313, 37321, 37337, 37339,
+    37357, 37361,
+    37363, 37369, 37379, 37397, 37409, 37423, 37441, 37447, 37463, 37483,
+    37489, 37493,
+    37501, 37507, 37511, 37517, 37529, 37537, 37547, 37549, 37561, 37567,
+    37571, 37573,
+    37579, 37589, 37591, 37607, 37619, 37633, 37643, 37649, 37657, 37663,
+    37691, 37693,
+    37699, 37717, 37747, 37781, 37783, 37799, 37811, 37813, 37831, 37847,
+    37853, 37861,
+    37871, 37879, 37889, 37897, 37907, 37951, 37957, 37963, 37967, 37987,
+    37991, 37993,
+    37997, 38011, 38039, 38047, 38053, 38069, 38083, 38113, 38119, 38149,
+    38153, 38167,
+    38177, 38183, 38189, 38197, 38201, 38219, 38231, 38237, 38239, 38261,
+    38273, 38281,
+    38287, 38299, 38303, 38317, 38321, 38327, 38329, 38333, 38351, 38371,
+    38377, 38393,
+    38431, 38447, 38449, 38453, 38459, 38461, 38501, 38543, 38557, 38561,
+    38567, 38569,
+    38593, 38603, 38609, 38611, 38629, 38639, 38651, 38653, 38669, 38671,
+    38677, 38693,
+    38699, 38707, 38711, 38713, 38723, 38729, 38737, 38747, 38749, 38767,
+    38783, 38791,
+    38803, 38821, 38833, 38839, 38851, 38861, 38867, 38873, 38891, 38903,
+    38917, 38921,
+    38923, 38933, 38953, 38959, 38971, 38977, 38993, 39019, 39023, 39041,
+    39043, 39047,
+    39079, 39089, 39097, 39103, 39107, 39113, 39119, 39133, 39139, 39157,
+    39161, 39163,
+    39181, 39191, 39199, 39209, 39217, 39227, 39229, 39233, 39239, 39241,
+    39251, 39293,
+    39301, 39313, 39317, 39323, 39341, 39343, 39359, 39367, 39371, 39373,
+    39383, 39397,
+    39409, 39419, 39439, 39443, 39451, 39461, 39499, 39503, 39509, 39511,
+    39521, 39541,
+    39551, 39563, 39569, 39581, 39607, 39619, 39623, 39631, 39659, 39667,
+    39671, 39679,
+    39703, 39709, 39719, 39727, 39733, 39749, 39761, 39769, 39779, 39791,
+    39799, 39821,
+    39827, 39829, 39839, 39841, 39847, 39857, 39863, 39869, 39877, 39883,
+    39887, 39901,
+    39929, 39937, 39953, 39971, 39979, 39983, 39989, 40009, 40013, 40031,
+    40037, 40039,
+    40063, 40087, 40093, 40099, 40111, 40123, 40127, 40129, 40151, 40153,
+    40163, 40169,
+    40177, 40189, 40193, 40213, 40231, 40237, 40241, 40253, 40277, 40283,
+    40289, 40343,
+    40351, 40357, 40361, 40387, 40423, 40427, 40429, 40433, 40459, 40471,
+    40483, 40487,
+    40493, 40499, 40507, 40519, 40529, 40531, 40543, 40559, 40577, 40583,
+    40591, 40597,
+    40609, 40627, 40637, 40639, 40693, 40697, 40699, 40709, 40739, 40751,
+    40759, 40763,
+    40771, 40787, 40801, 40813, 40819, 40823, 40829, 40841, 40847, 40849,
+    40853, 40867,
+    40879, 40883, 40897, 40903, 40927, 40933, 40939, 40949, 40961, 40973,
+    40993, 41011,
+    41017, 41023, 41039, 41047, 41051, 41057, 41077, 41081, 41113, 41117,
+    41131, 41141,
+    41143, 41149, 41161, 41177, 41179, 41183, 41189, 41201, 41203, 41213,
+    41221, 41227,
+    41231, 41233, 41243, 41257, 41263, 41269, 41281, 41299, 41333, 41341,
+    41351, 41357,
+    41381, 41387, 41389, 41399, 41411, 41413, 41443, 41453, 41467, 41479,
+    41491, 41507,
+    41513, 41519, 41521, 41539, 41543, 41549, 41579, 41593, 41597, 41603,
+    41609, 41611,
+    41617, 41621, 41627, 41641, 41647, 41651, 41659, 41669, 41681, 41687,
+    41719, 41729,
+    41737, 41759, 41761, 41771, 41777, 41801, 41809, 41813, 41843, 41849,
+    41851, 41863,
+    41879, 41887, 41893, 41897, 41903, 41911, 41927, 41941, 41947, 41953,
+    41957, 41959,
+    41969, 41981, 41983, 41999, 42013, 42017, 42019, 42023, 42043, 42061,
+    42071, 42073,
+    42083, 42089, 42101, 42131, 42139, 42157, 42169, 42179, 42181, 42187,
+    42193, 42197,
+    42209, 42221, 42223, 42227, 42239, 42257, 42281, 42283, 42293, 42299,
+    42307, 42323,
+    42331, 42337, 42349, 42359, 42373, 42379, 42391, 42397, 42403, 42407,
+    42409, 42433,
+    42437, 42443, 42451, 42457, 42461, 42463, 42467, 42473, 42487, 42491,
+    42499, 42509,
+    42533, 42557, 42569, 42571, 42577, 42589, 42611, 42641, 42643, 42649,
+    42667, 42677,
+    42683, 42689, 42697, 42701, 42703, 42709, 42719, 42727, 42737, 42743,
+    42751, 42767,
+    42773, 42787, 42793, 42797, 42821, 42829, 42839, 42841, 42853, 42859,
+    42863, 42899,
+    42901, 42923, 42929, 42937, 42943, 42953, 42961, 42967, 42979, 42989,
+    43003, 43013,
+    43019, 43037, 43049, 43051, 43063, 43067, 43093, 43103, 43117, 43133,
+    43151, 43159,
+    43177, 43189, 43201, 43207, 43223, 43237, 43261, 43271, 43283, 43291,
+    43313, 43319,
+    43321, 43331, 43391, 43397, 43399, 43403, 43411, 43427, 43441, 43451,
+    43457, 43481,
+    43487, 43499, 43517, 43541, 43543, 43573, 43577, 43579, 43591, 43597,
+    43607, 43609,
+    43613, 43627, 43633, 43649, 43651, 43661, 43669, 43691, 43711, 43717,
+    43721, 43753,
+    43759, 43777, 43781, 43783, 43787, 43789, 43793, 43801, 43853, 43867,
+    43889, 43891,
+    43913, 43933, 43943, 43951, 43961, 43963, 43969, 43973, 43987, 43991,
+    43997, 44017,
+    44021, 44027, 44029, 44041, 44053, 44059, 44071, 44087, 44089, 44101,
+    44111, 44119,
+    44123, 44129, 44131, 44159, 44171, 44179, 44189, 44201, 44203, 44207,
+    44221, 44249,
+    44257, 44263, 44267, 44269, 44273, 44279, 44281, 44293, 44351, 44357,
+    44371, 44381,
+    44383, 44389, 44417, 44449, 44453, 44483, 44491, 44497, 44501, 44507,
+    44519, 44531,
+    44533, 44537, 44543, 44549, 44563, 44579, 44587, 44617, 44621, 44623,
+    44633, 44641,
+    44647, 44651, 44657, 44683, 44687, 44699, 44701, 44711, 44729, 44741,
+    44753, 44771,
+    44773, 44777, 44789, 44797, 44809, 44819, 44839, 44843, 44851, 44867,
+    44879, 44887,
+    44893, 44909, 44917, 44927, 44939, 44953, 44959, 44963, 44971, 44983,
+    44987, 45007,
+    45013, 45053, 45061, 45077, 45083, 45119, 45121, 45127, 45131, 45137,
+    45139, 45161,
+    45179, 45181, 45191, 45197, 45233, 45247, 45259, 45263, 45281, 45289,
+    45293, 45307,
+    45317, 45319, 45329, 45337, 45341, 45343, 45361, 45377, 45389, 45403,
+    45413, 45427,
+    45433, 45439, 45481, 45491, 45497, 45503, 45523, 45533, 45541, 45553,
+    45557, 45569,
+    45587, 45589, 45599, 45613, 45631, 45641, 45659, 45667, 45673, 45677,
+    45691, 45697,
+    45707, 45737, 45751, 45757, 45763, 45767, 45779, 45817, 45821, 45823,
+    45827, 45833,
+    45841, 45853, 45863, 45869, 45887, 45893, 45943, 45949, 45953, 45959,
+    45971, 45979,
+    45989, 46021, 46027, 46049, 46051, 46061, 46073, 46091, 46093, 46099,
+    46103, 46133,
+    46141, 46147, 46153, 46171, 46181, 46183, 46187, 46199, 46219, 46229,
+    46237, 46261,
+    46271, 46273, 46279, 46301, 46307, 46309, 46327, 46337, 46349, 46351,
+    46381, 46399,
+    46411, 46439, 46441, 46447, 46451, 46457, 46471, 46477, 46489, 46499,
+    46507, 46511,
+    46523, 46549, 46559, 46567, 46573, 46589, 46591, 46601, 46619, 46633,
+    46639, 46643,
+    46649, 46663, 46679, 46681, 46687, 46691, 46703, 46723, 46727, 46747,
+    46751, 46757,
+    46769, 46771, 46807, 46811, 46817, 46819, 46829, 46831, 46853, 46861,
+    46867, 46877,
+    46889, 46901, 46919, 46933, 46957, 46993, 46997, 47017, 47041, 47051,
+    47057, 47059,
+    47087, 47093, 47111, 47119, 47123, 47129, 47137, 47143, 47147, 47149,
+    47161, 47189,
+    47207, 47221, 47237, 47251, 47269, 47279, 47287, 47293, 47297, 47303,
+    47309, 47317,
+    47339, 47351, 47353, 47363, 47381, 47387, 47389, 47407, 47417, 47419,
+    47431, 47441,
+    47459, 47491, 47497, 47501, 47507, 47513, 47521, 47527, 47533, 47543,
+    47563, 47569,
+    47581, 47591, 47599, 47609, 47623, 47629, 47639, 47653, 47657, 47659,
+    47681, 47699,
+    47701, 47711, 47713, 47717, 47737, 47741, 47743, 47777, 47779, 47791,
+    47797, 47807,
+    47809, 47819, 47837, 47843, 47857, 47869, 47881, 47903, 47911, 47917,
+    47933, 47939,
+    47947, 47951, 47963, 47969, 47977, 47981, 48017, 48023, 48029, 48049,
+    48073, 48079,
+    48091, 48109, 48119, 48121, 48131, 48157, 48163, 48179, 48187, 48193,
+    48197, 48221,
+    48239, 48247, 48259, 48271, 48281, 48299, 48311, 48313, 48337, 48341,
+    48353, 48371,
+    48383, 48397, 48407, 48409, 48413, 48437, 48449, 48463, 48473, 48479,
+    48481, 48487,
+    48491, 48497, 48523, 48527, 48533, 48539, 48541, 48563, 48571, 48589,
+    48593, 48611,
+    48619, 48623, 48647, 48649, 48661, 48673, 48677, 48679, 48731, 48733,
+    48751, 48757,
+    48761, 48767, 48779, 48781, 48787, 48799, 48809, 48817, 48821, 48823,
+    48847, 48857,
+    48859, 48869, 48871, 48883, 48889, 48907, 48947, 48953, 48973, 48989,
+    48991, 49003,
+    49009, 49019, 49031, 49033, 49037, 49043, 49057, 49069, 49081, 49103,
+    49109, 49117,
+    49121, 49123, 49139, 49157, 49169, 49171, 49177, 49193, 49199, 49201,
+    49207, 49211,
+    49223, 49253, 49261, 49277, 49279, 49297, 49307, 49331, 49333, 49339,
+    49363, 49367,
+    49369, 49391, 49393, 49409, 49411, 49417, 49429, 49433, 49451, 49459,
+    49463, 49477,
+    49481, 49499, 49523, 49529, 49531, 49537, 49547, 49549, 49559, 49597,
+    49603, 49613,
+    49627, 49633, 49639, 49663, 49667, 49669, 49681, 49697, 49711, 49727,
+    49739, 49741,
+    49747, 49757, 49783, 49787, 49789, 49801, 49807, 49811, 49823, 49831,
+    49843, 49853,
+    49871, 49877, 49891, 49919, 49921, 49927, 49937, 49939, 49943, 49957,
+    49991, 49993,
+    49999, 50021, 50023, 50033, 50047, 50051, 50053, 50069, 50077, 50087,
+    50093, 50101,
+    50111, 50119, 50123, 50129, 50131, 50147, 50153, 50159, 50177, 50207,
+    50221, 50227,
+    50231, 50261, 50263, 50273, 50287, 50291, 50311, 50321, 50329, 50333,
+    50341, 50359,
+    50363, 50377, 50383, 50387, 50411, 50417, 50423, 50441, 50459, 50461,
+    50497, 50503,
+    50513, 50527, 50539, 50543, 50549, 50551, 50581, 50587, 50591, 50593,
+    50599, 50627,
+    50647, 50651, 50671, 50683, 50707, 50723, 50741, 50753, 50767, 50773,
+    50777, 50789,
+    50821, 50833, 50839, 50849, 50857, 50867, 50873, 50891, 50893, 50909,
+    50923, 50929,
+    50951, 50957, 50969, 50971, 50989, 50993, 51001, 51031, 51043, 51047,
+    51059, 51061,
+    51071, 51109, 51131, 51133, 51137, 51151, 51157, 51169, 51193, 51197,
+    51199, 51203,
+    51217, 51229, 51239, 51241, 51257, 51263, 51283, 51287, 51307, 51329,
+    51341, 51343,
+    51347, 51349, 51361, 51383, 51407, 51413, 51419, 51421, 51427, 51431,
+    51437, 51439,
+    51449, 51461, 51473, 51479, 51481, 51487, 51503, 51511, 51517, 51521,
+    51539, 51551,
+    51563, 51577, 51581, 51593, 51599, 51607, 51613, 51631, 51637, 51647,
+    51659, 51673,
+    51679, 51683, 51691, 51713, 51719, 51721, 51749, 51767, 51769, 51787,
+    51797, 51803,
+    51817, 51827, 51829, 51839, 51853, 51859, 51869, 51871, 51893, 51899,
+    51907, 51913,
+    51929, 51941, 51949, 51971, 51973, 51977, 51991, 52009, 52021, 52027,
+    52051, 52057,
+    52067, 52069, 52081, 52103, 52121, 52127, 52147, 52153, 52163, 52177,
+    52181, 52183,
+    52189, 52201, 52223, 52237, 52249, 52253, 52259, 52267, 52289, 52291,
+    52301, 52313,
+    52321, 52361, 52363, 52369, 52379, 52387, 52391, 52433, 52453, 52457,
+    52489, 52501,
+    52511, 52517, 52529, 52541, 52543, 52553, 52561, 52567, 52571, 52579,
+    52583, 52609,
+    52627, 52631, 52639, 52667, 52673, 52691, 52697, 52709, 52711, 52721,
+    52727, 52733,
+    52747, 52757, 52769, 52783, 52807, 52813, 52817, 52837, 52859, 52861,
+    52879, 52883,
+    52889, 52901, 52903, 52919, 52937, 52951, 52957, 52963, 52967, 52973,
+    52981, 52999,
+    53003, 53017, 53047, 53051, 53069, 53077, 53087, 53089, 53093, 53101,
+    53113, 53117,
+    53129, 53147, 53149, 53161, 53171, 53173, 53189, 53197, 53201, 53231,
+    53233, 53239,
+    53267, 53269, 53279, 53281, 53299, 53309, 53323, 53327, 53353, 53359,
+    53377, 53381,
+    53401, 53407, 53411, 53419, 53437, 53441, 53453, 53479, 53503, 53507,
+    53527, 53549,
+    53551, 53569, 53591, 53593, 53597, 53609, 53611, 53617, 53623, 53629,
+    53633, 53639,
+    53653, 53657, 53681, 53693, 53699, 53717, 53719, 53731, 53759, 53773,
+    53777, 53783,
+    53791, 53813, 53819, 53831, 53849, 53857, 53861, 53881, 53887, 53891,
+    53897, 53899,
+    53917, 53923, 53927, 53939, 53951, 53959, 53987, 53993, 54001, 54011,
+    54013, 54037,
+    54049, 54059, 54083, 54091, 54101, 54121, 54133, 54139, 54151, 54163,
+    54167, 54181,
+    54193, 54217, 54251, 54269, 54277, 54287, 54293, 54311, 54319, 54323,
+    54331, 54347,
+    54361, 54367, 54371, 54377, 54401, 54403, 54409, 54413, 54419, 54421,
+    54437, 54443,
+    54449, 54469, 54493, 54497, 54499, 54503, 54517, 54521, 54539, 54541,
+    54547, 54559,
+    54563, 54577, 54581, 54583, 54601, 54617, 54623, 54629, 54631, 54647,
+    54667, 54673,
+    54679, 54709, 54713, 54721, 54727, 54751, 54767, 54773, 54779, 54787,
+    54799, 54829,
+    54833, 54851, 54869, 54877, 54881, 54907, 54917, 54919, 54941, 54949,
+    54959, 54973,
+    54979, 54983, 55001, 55009, 55021, 55049, 55051, 55057, 55061, 55073,
+    55079, 55103,
+    55109, 55117, 55127, 55147, 55163, 55171, 55201, 55207, 55213, 55217,
+    55219, 55229,
+    55243, 55249, 55259, 55291, 55313, 55331, 55333, 55337, 55339, 55343,
+    55351, 55373,
+    55381, 55399, 55411, 55439, 55441, 55457, 55469, 55487, 55501, 55511,
+    55529, 55541,
+    55547, 55579, 55589, 55603, 55609, 55619, 55621, 55631, 55633, 55639,
+    55661, 55663,
+    55667, 55673, 55681, 55691, 55697, 55711, 55717, 55721, 55733, 55763,
+    55787, 55793,
+    55799, 55807, 55813, 55817, 55819, 55823, 55829, 55837, 55843, 55849,
+    55871, 55889,
+    55897, 55901, 55903, 55921, 55927, 55931, 55933, 55949, 55967, 55987,
+    55997, 56003,
+    56009, 56039, 56041, 56053, 56081, 56087, 56093, 56099, 56101, 56113,
+    56123, 56131,
+    56149, 56167, 56171, 56179, 56197, 56207, 56209, 56237, 56239, 56249,
+    56263, 56267,
+    56269, 56299, 56311, 56333, 56359, 56369, 56377, 56383, 56393, 56401,
+    56417, 56431,
+    56437, 56443, 56453, 56467, 56473, 56477, 56479, 56489, 56501, 56503,
+    56509, 56519,
+    56527, 56531, 56533, 56543, 56569, 56591, 56597, 56599, 56611, 56629,
+    56633, 56659,
+    56663, 56671, 56681, 56687, 56701, 56711, 56713, 56731, 56737, 56747,
+    56767, 56773,
+    56779, 56783, 56807, 56809, 56813, 56821, 56827, 56843, 56857, 56873,
+    56891, 56893,
+    56897, 56909, 56911, 56921, 56923, 56929, 56941, 56951, 56957, 56963,
+    56983, 56989,
+    56993, 56999, 57037, 57041, 57047, 57059, 57073, 57077, 57089, 57097,
+    57107, 57119,
+    57131, 57139, 57143, 57149, 57163, 57173, 57179, 57191, 57193, 57203,
+    57221, 57223,
+    57241, 57251, 57259, 57269, 57271, 57283, 57287, 57301, 57329, 57331,
+    57347, 57349,
+    57367, 57373, 57383, 57389, 57397, 57413, 57427, 57457, 57467, 57487,
+    57493, 57503,
+    57527, 57529, 57557, 57559, 57571, 57587, 57593, 57601, 57637, 57641,
+    57649, 57653,
+    57667, 57679, 57689, 57697, 57709, 57713, 57719, 57727, 57731, 57737,
+    57751, 57773,
+    57781, 57787, 57791, 57793, 57803, 57809, 57829, 57839, 57847, 57853,
+    57859, 57881,
+    57899, 57901, 57917, 57923, 57943, 57947, 57973, 57977, 57991, 58013,
+    58027, 58031,
+    58043, 58049, 58057, 58061, 58067, 58073, 58099, 58109, 58111, 58129,
+    58147, 58151,
+    58153, 58169, 58171, 58189, 58193, 58199, 58207, 58211, 58217, 58229,
+    58231, 58237,
+    58243, 58271, 58309, 58313, 58321, 58337, 58363, 58367, 58369, 58379,
+    58391, 58393,
+    58403, 58411, 58417, 58427, 58439, 58441, 58451, 58453, 58477, 58481,
+    58511, 58537,
+    58543, 58549, 58567, 58573, 58579, 58601, 58603, 58613, 58631, 58657,
+    58661, 58679,
+    58687, 58693, 58699, 58711, 58727, 58733, 58741, 58757, 58763, 58771,
+    58787, 58789,
+    58831, 58889, 58897, 58901, 58907, 58909, 58913, 58921, 58937, 58943,
+    58963, 58967,
+    58979, 58991, 58997, 59009, 59011, 59021, 59023, 59029, 59051, 59053,
+    59063, 59069,
+    59077, 59083, 59093, 59107, 59113, 59119, 59123, 59141, 59149, 59159,
+    59167, 59183,
+    59197, 59207, 59209, 59219, 59221, 59233, 59239, 59243, 59263, 59273,
+    59281, 59333,
+    59341, 59351, 59357, 59359, 59369, 59377, 59387, 59393, 59399, 59407,
+    59417, 59419,
+    59441, 59443, 59447, 59453, 59467, 59471, 59473, 59497, 59509, 59513,
+    59539, 59557,
+    59561, 59567, 59581, 59611, 59617, 59621, 59627, 59629, 59651, 59659,
+    59663, 59669,
+    59671, 59693, 59699, 59707, 59723, 59729, 59743, 59747, 59753, 59771,
+    59779, 59791,
+    59797, 59809, 59833, 59863, 59879, 59887, 59921, 59929, 59951, 59957,
+    59971, 59981,
+    59999, 60013, 60017, 60029, 60037, 60041, 60077, 60083, 60089, 60091,
+    60101, 60103,
+    60107, 60127, 60133, 60139, 60149, 60161, 60167, 60169, 60209, 60217,
+    60223, 60251,
+    60257, 60259, 60271, 60289, 60293, 60317, 60331, 60337, 60343, 60353,
+    60373, 60383,
+    60397, 60413, 60427, 60443, 60449, 60457, 60493, 60497, 60509, 60521,
+    60527, 60539,
+    60589, 60601, 60607, 60611, 60617, 60623, 60631, 60637, 60647, 60649,
+    60659, 60661,
+    60679, 60689, 60703, 60719, 60727, 60733, 60737, 60757, 60761, 60763,
+    60773, 60779,
+    60793, 60811, 60821, 60859, 60869, 60887, 60889, 60899, 60901, 60913,
+    60917, 60919,
+    60923, 60937, 60943, 60953, 60961, 61001, 61007, 61027, 61031, 61043,
+    61051, 61057,
+    61091, 61099, 61121, 61129, 61141, 61151, 61153, 61169, 61211, 61223,
+    61231, 61253,
+    61261, 61283, 61291, 61297, 61331, 61333, 61339, 61343, 61357, 61363,
+    61379, 61381,
+    61403, 61409, 61417, 61441, 61463, 61469, 61471, 61483, 61487, 61493,
+    61507, 61511,
+    61519, 61543, 61547, 61553, 61559, 61561, 61583, 61603, 61609, 61613,
+    61627, 61631,
+    61637, 61643, 61651, 61657, 61667, 61673, 61681, 61687, 61703, 61717,
+    61723, 61729,
+    61751, 61757, 61781, 61813, 61819, 61837, 61843, 61861, 61871, 61879,
+    61909, 61927,
+    61933, 61949, 61961, 61967, 61979, 61981, 61987, 61991, 62003, 62011,
+    62017, 62039,
+    62047, 62053, 62057, 62071, 62081, 62099, 62119, 62129, 62131, 62137,
+    62141, 62143,
+    62171, 62189, 62191, 62201, 62207, 62213, 62219, 62233, 62273, 62297,
+    62299, 62303,
+    62311, 62323, 62327, 62347, 62351, 62383, 62401, 62417, 62423, 62459,
+    62467, 62473,
+    62477, 62483, 62497, 62501, 62507, 62533, 62539, 62549, 62563, 62581,
+    62591, 62597,
+    62603, 62617, 62627, 62633, 62639, 62653, 62659, 62683, 62687, 62701,
+    62723, 62731,
+    62743, 62753, 62761, 62773, 62791, 62801, 62819, 62827, 62851, 62861,
+    62869, 62873,
+    62897, 62903, 62921, 62927, 62929, 62939, 62969, 62971, 62981, 62983,
+    62987, 62989,
+    63029, 63031, 63059, 63067, 63073, 63079, 63097, 63103, 63113, 63127,
+    63131, 63149,
+    63179, 63197, 63199, 63211, 63241, 63247, 63277, 63281, 63299, 63311,
+    63313, 63317,
+    63331, 63337, 63347, 63353, 63361, 63367, 63377, 63389, 63391, 63397,
+    63409, 63419,
+    63421, 63439, 63443, 63463, 63467, 63473, 63487, 63493, 63499, 63521,
+    63527, 63533,
+    63541, 63559, 63577, 63587, 63589, 63599, 63601, 63607, 63611, 63617,
+    63629, 63647,
+    63649, 63659, 63667, 63671, 63689, 63691, 63697, 63703, 63709, 63719,
+    63727, 63737,
+    63743, 63761, 63773, 63781, 63793, 63799, 63803, 63809, 63823, 63839,
+    63841, 63853,
+    63857, 63863, 63901, 63907, 63913, 63929, 63949, 63977, 63997, 64007,
+    64013, 64019,
+    64033, 64037, 64063, 64067, 64081, 64091, 64109, 64123, 64151, 64153,
+    64157, 64171,
+    64187, 64189, 64217, 64223, 64231, 64237, 64271, 64279, 64283, 64301,
+    64303, 64319,
+    64327, 64333, 64373, 64381, 64399, 64403, 64433, 64439, 64451, 64453,
+    64483, 64489,
+    64499, 64513, 64553, 64567, 64577, 64579, 64591, 64601, 64609, 64613,
+    64621, 64627,
+    64633, 64661, 64663, 64667, 64679, 64693, 64709, 64717, 64747, 64763,
+    64781, 64783,
+    64793, 64811, 64817, 64849, 64853, 64871, 64877, 64879, 64891, 64901,
+    64919, 64921,
+    64927, 64937, 64951, 64969, 64997, 65003, 65011, 65027, 65029, 65033,
+    65053, 65063,
+    65071, 65089, 65099, 65101, 65111, 65119, 65123, 65129, 65141, 65147,
+    65167, 65171,
+    65173, 65179, 65183, 65203, 65213, 65239, 65257, 65267, 65269, 65287,
+    65293, 65309,
+    65323, 65327, 65353, 65357, 65371, 65381, 65393, 65407, 65413, 65419,
+    65423, 65437,
+    65447, 65449, 65479, 65497, 65519, 65521,
 };
 
 #define NPRIMES (sizeof(primes) / sizeof(*primes))
@@ -659,33 +1186,35 @@ static const unsigned short primes[] = {
  * (prime % modulus) != residue (to speed up use in RSA).
  */
 Bignum primegen(int bits, int modulus, int residue,
-                int phase, progfn_t pfn, void *pfnparam) {
+               int phase, progfn_t pfn, void *pfnparam)
+{
     int i, k, v, byte, bitsleft, check, checks;
-    unsigned long delta, moduli[NPRIMES+1], residues[NPRIMES+1];
+    unsigned long delta, moduli[NPRIMES + 1], residues[NPRIMES + 1];
     Bignum p, pm1, q, wqp, wqp2;
     int progress = 0;
 
-    byte = 0; bitsleft = 0;
+    byte = 0;
+    bitsleft = 0;
 
-    STARTOVER:
+  STARTOVER:
 
     pfn(pfnparam, phase, ++progress);
 
     /*
      * Generate a k-bit random number with top and bottom bits set.
      */
-    p = bn_power_2(bits-1);
+    p = bn_power_2(bits - 1);
     for (i = 0; i < bits; i++) {
-        if (i == 0 || i == bits-1)
-            v = 1;
-        else {
-            if (bitsleft <= 0)
-                bitsleft = 8, byte = random_byte();
-            v = byte & 1;
-            byte >>= 1;
-            bitsleft--;
-        }
-        bignum_set_bit(p, i, v);
+       if (i == 0 || i == bits - 1)
+           v = 1;
+       else {
+           if (bitsleft <= 0)
+               bitsleft = 8, byte = random_byte();
+           v = byte & 1;
+           byte >>= 1;
+           bitsleft--;
+       }
+       bignum_set_bit(p, i, v);
     }
 
     /*
@@ -693,26 +1222,26 @@ Bignum primegen(int bits, int modulus, int residue,
      * primes, by repeatedly adding 2 to it until it is.
      */
     for (i = 0; i < NPRIMES; i++) {
-        moduli[i] = primes[i];
-        residues[i] = bignum_mod_short(p, primes[i]);
+       moduli[i] = primes[i];
+       residues[i] = bignum_mod_short(p, primes[i]);
     }
     moduli[NPRIMES] = modulus;
-    residues[NPRIMES] = (bignum_mod_short(p, (unsigned short)modulus)
-                         + modulus - residue);
+    residues[NPRIMES] = (bignum_mod_short(p, (unsigned short) modulus)
+                        + modulus - residue);
     delta = 0;
     while (1) {
-        for (i = 0; i < (sizeof(moduli) / sizeof(*moduli)); i++)
-            if (!((residues[i] + delta) % moduli[i]))
-                break;
-        if (i < (sizeof(moduli) / sizeof(*moduli))) {/* we broke */
-            delta += 2;
-            if (delta < 2) {
-                freebn(p);
-                goto STARTOVER;
-            }
-            continue;
-        }
-        break;
+       for (i = 0; i < (sizeof(moduli) / sizeof(*moduli)); i++)
+           if (!((residues[i] + delta) % moduli[i]))
+               break;
+       if (i < (sizeof(moduli) / sizeof(*moduli))) {   /* we broke */
+           delta += 2;
+           if (delta < 2) {
+               freebn(p);
+               goto STARTOVER;
+           }
+           continue;
+       }
+       break;
     }
     q = p;
     p = bignum_add_long(q, delta);
@@ -723,22 +1252,33 @@ Bignum primegen(int bits, int modulus, int residue,
      * work out how many checks are needed.
      */
     checks = 27;
-    if (bits >= 150) checks = 18;
-    if (bits >= 200) checks = 15;
-    if (bits >= 250) checks = 12;
-    if (bits >= 300) checks = 9;
-    if (bits >= 350) checks = 8;
-    if (bits >= 400) checks = 7;
-    if (bits >= 450) checks = 6;
-    if (bits >= 550) checks = 5;
-    if (bits >= 650) checks = 4;
-    if (bits >= 850) checks = 3;
-    if (bits >= 1300) checks = 2;
+    if (bits >= 150)
+       checks = 18;
+    if (bits >= 200)
+       checks = 15;
+    if (bits >= 250)
+       checks = 12;
+    if (bits >= 300)
+       checks = 9;
+    if (bits >= 350)
+       checks = 8;
+    if (bits >= 400)
+       checks = 7;
+    if (bits >= 450)
+       checks = 6;
+    if (bits >= 550)
+       checks = 5;
+    if (bits >= 650)
+       checks = 4;
+    if (bits >= 850)
+       checks = 3;
+    if (bits >= 1300)
+       checks = 2;
 
     /*
      * Next, write p-1 as q*2^k.
      */
-    for (k = 0; bignum_bit(p, k) == !k; k++);   /* find first 1 bit in p-1 */
+    for (k = 0; bignum_bit(p, k) == !k; k++);  /* find first 1 bit in p-1 */
     q = bignum_rshift(p, k);
     /* And store p-1 itself, which we'll need. */
     pm1 = copybn(p);
@@ -748,65 +1288,65 @@ Bignum primegen(int bits, int modulus, int residue,
      * Now, for each check ...
      */
     for (check = 0; check < checks; check++) {
-        Bignum w;
+       Bignum w;
 
-        /*
-         * Invent a random number between 1 and p-1 inclusive.
-         */
-        while (1) {
-            w = bn_power_2(bits-1);
-            for (i = 0; i < bits; i++) {
-                if (bitsleft <= 0)
-                    bitsleft = 8, byte = random_byte();
-                v = byte & 1;
-                byte >>= 1;
-                bitsleft--;
-                bignum_set_bit(w, i, v);
-            }
-            bn_restore_invariant(w);
-            if (bignum_cmp(w, p) >= 0 || bignum_cmp(w, Zero) == 0) {
-                freebn(w);
-                continue;
-            }
-            break;
-        }
+       /*
+        * Invent a random number between 1 and p-1 inclusive.
+        */
+       while (1) {
+           w = bn_power_2(bits - 1);
+           for (i = 0; i < bits; i++) {
+               if (bitsleft <= 0)
+                   bitsleft = 8, byte = random_byte();
+               v = byte & 1;
+               byte >>= 1;
+               bitsleft--;
+               bignum_set_bit(w, i, v);
+           }
+           bn_restore_invariant(w);
+           if (bignum_cmp(w, p) >= 0 || bignum_cmp(w, Zero) == 0) {
+               freebn(w);
+               continue;
+           }
+           break;
+       }
 
-        pfn(pfnparam, phase, ++progress);
+       pfn(pfnparam, phase, ++progress);
 
-        /*
-         * Compute w^q mod p.
-         */
-        wqp = modpow(w, q, p);
-        freebn(w);
+       /*
+        * Compute w^q mod p.
+        */
+       wqp = modpow(w, q, p);
+       freebn(w);
 
-        /*
-         * See if this is 1, or if it is -1, or if it becomes -1
-         * when squared at most k-1 times.
-         */
-        if (bignum_cmp(wqp, One) == 0 || bignum_cmp(wqp, pm1) == 0) {
-            freebn(wqp);
-            continue;
-        }
-        for (i = 0; i < k-1; i++) {
-            wqp2 = modmul(wqp, wqp, p);
-            freebn(wqp);
-            wqp = wqp2;
-            if (bignum_cmp(wqp, pm1) == 0)
-                break;
-        }
-        if (i < k-1) {
-            freebn(wqp);
-            continue;
-        }
+       /*
+        * See if this is 1, or if it is -1, or if it becomes -1
+        * when squared at most k-1 times.
+        */
+       if (bignum_cmp(wqp, One) == 0 || bignum_cmp(wqp, pm1) == 0) {
+           freebn(wqp);
+           continue;
+       }
+       for (i = 0; i < k - 1; i++) {
+           wqp2 = modmul(wqp, wqp, p);
+           freebn(wqp);
+           wqp = wqp2;
+           if (bignum_cmp(wqp, pm1) == 0)
+               break;
+       }
+       if (i < k - 1) {
+           freebn(wqp);
+           continue;
+       }
 
-        /*
-         * It didn't. Therefore, w is a witness for the
-         * compositeness of p.
-         */
-        freebn(p);
-        freebn(pm1);
-        freebn(q);
-        goto STARTOVER;
+       /*
+        * It didn't. Therefore, w is a witness for the
+        * compositeness of p.
+        */
+       freebn(p);
+       freebn(pm1);
+       freebn(q);
+       goto STARTOVER;
     }
 
     /*
index ed16534..d5576e8 100644 (file)
--- a/sshpubk.c
+++ b/sshpubk.c
@@ -31,8 +31,9 @@
                           (x)=='+' ? 62 : \
                           (x)=='/' ? 63 : 0 )
 
-static int loadrsakey_main(FILE *fp, struct RSAKey *key,
-                           char **commentptr, char *passphrase) {
+static int loadrsakey_main(FILE * fp, struct RSAKey *key,
+                          char **commentptr, char *passphrase)
+{
     unsigned char buf[16384];
     unsigned char keybuf[16];
     int len;
@@ -45,70 +46,75 @@ static int loadrsakey_main(FILE *fp, struct RSAKey *key,
     len = fread(buf, 1, sizeof(buf), fp);
     fclose(fp);
     if (len < 0 || len == sizeof(buf))
-        goto end;                      /* file too big or not read */
+       goto end;                      /* file too big or not read */
 
     i = 0;
 
     /*
      * A zero byte. (The signature includes a terminating NUL.)
      */
-    if (len-i < 1 || buf[i] != 0)
-        goto end;
+    if (len - i < 1 || buf[i] != 0)
+       goto end;
     i++;
 
     /* One byte giving encryption type, and one reserved uint32. */
-    if (len-i < 1)
-        goto end;
+    if (len - i < 1)
+       goto end;
     ciphertype = buf[i];
     if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
-        goto end;
+       goto end;
     i++;
-    if (len-i < 4)
-        goto end;                      /* reserved field not present */
-    if (buf[i] != 0 || buf[i+1] != 0 || buf[i+2] != 0 || buf[i+3] != 0)
-        goto end;                      /* reserved field nonzero, panic! */
+    if (len - i < 4)
+       goto end;                      /* reserved field not present */
+    if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
+       || buf[i + 3] != 0) goto end;  /* reserved field nonzero, panic! */
     i += 4;
 
     /* Now the serious stuff. An ordinary SSH 1 public key. */
-    i += makekey(buf+i, key, NULL, 1);
-    if (len-i < 0)
-        goto end;                      /* overran */
+    i += makekey(buf + i, key, NULL, 1);
+    if (len - i < 0)
+       goto end;                      /* overran */
 
     /* Next, the comment field. */
-    j = GET_32BIT(buf+i);
+    j = GET_32BIT(buf + i);
     i += 4;
-    if (len-i < j) goto end;
-    comment = smalloc(j+1);
+    if (len - i < j)
+       goto end;
+    comment = smalloc(j + 1);
     if (comment) {
-        memcpy(comment, buf+i, j);
-        comment[j] = '\0';
+       memcpy(comment, buf + i, j);
+       comment[j] = '\0';
     }
     i += j;
     if (commentptr)
-        *commentptr = comment;
+       *commentptr = comment;
     if (key)
-        key->comment = comment;
+       key->comment = comment;
     if (!key) {
-        return ciphertype != 0;
+       return ciphertype != 0;
     }
 
     /*
      * Decrypt remainder of buffer.
      */
     if (ciphertype) {
-        MD5Init(&md5c);
-        MD5Update(&md5c, passphrase, strlen(passphrase));
-        MD5Final(keybuf, &md5c);
-        des3_decrypt_pubkey(keybuf, buf+i, (len-i+7)&~7);
-        memset(keybuf, 0, sizeof(keybuf));    /* burn the evidence */
+       MD5Init(&md5c);
+       MD5Update(&md5c, passphrase, strlen(passphrase));
+       MD5Final(keybuf, &md5c);
+       des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
+       memset(keybuf, 0, sizeof(keybuf));      /* burn the evidence */
     }
 
     /*
      * We are now in the secret part of the key. The first four
      * bytes should be of the form a, b, a, b.
      */
-    if (len-i < 4) goto end;
-    if (buf[i] != buf[i+2] || buf[i+1] != buf[i+3]) { ret = -1; goto end; }
+    if (len - i < 4)
+       goto end;
+    if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
+       ret = -1;
+       goto end;
+    }
     i += 4;
 
     /*
@@ -116,14 +122,18 @@ static int loadrsakey_main(FILE *fp, struct RSAKey *key,
      * decryption exponent, and then the three auxiliary values
      * (iqmp, q, p).
      */
-    i += makeprivate(buf+i, key);
-    if (len-i < 0) goto end;
-    i += ssh1_read_bignum(buf+i, &key->iqmp);
-    if (len-i < 0) goto end;
-    i += ssh1_read_bignum(buf+i, &key->q);
-    if (len-i < 0) goto end;
-    i += ssh1_read_bignum(buf+i, &key->p);
-    if (len-i < 0) goto end;
+    i += makeprivate(buf + i, key);
+    if (len - i < 0)
+       goto end;
+    i += ssh1_read_bignum(buf + i, &key->iqmp);
+    if (len - i < 0)
+       goto end;
+    i += ssh1_read_bignum(buf + i, &key->q);
+    if (len - i < 0)
+       goto end;
+    i += ssh1_read_bignum(buf + i, &key->p);
+    if (len - i < 0)
+       goto end;
 
     if (!rsa_verify(key)) {
        freersakey(key);
@@ -131,26 +141,26 @@ static int loadrsakey_main(FILE *fp, struct RSAKey *key,
     } else
        ret = 1;
 
-    end:
+  end:
     memset(buf, 0, sizeof(buf));       /* burn the evidence */
     return ret;
 }
 
-int loadrsakey(char *filename, struct RSAKey *key, char *passphrase) {
+int loadrsakey(char *filename, struct RSAKey *key, char *passphrase)
+{
     FILE *fp;
     unsigned char buf[64];
 
     fp = fopen(filename, "rb");
     if (!fp)
-        return 0;                      /* doesn't even exist */
+       return 0;                      /* doesn't even exist */
 
     /*
      * Read the first line of the file and see if it's a v1 private
      * key file.
      */
-    if (fgets(buf, sizeof(buf), fp) &&
-        !strcmp(buf, rsa_signature)) {
-        return loadrsakey_main(fp, key, NULL, passphrase);
+    if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
+       return loadrsakey_main(fp, key, NULL, passphrase);
     }
 
     /*
@@ -164,30 +174,31 @@ int loadrsakey(char *filename, struct RSAKey *key, char *passphrase) {
  * See whether an RSA key is encrypted. Return its comment field as
  * well.
  */
-int rsakey_encrypted(char *filename, char **comment) {
+int rsakey_encrypted(char *filename, char **comment)
+{
     FILE *fp;
     unsigned char buf[64];
 
     fp = fopen(filename, "rb");
     if (!fp)
-        return 0;                      /* doesn't even exist */
+       return 0;                      /* doesn't even exist */
 
     /*
      * Read the first line of the file and see if it's a v1 private
      * key file.
      */
-    if (fgets(buf, sizeof(buf), fp) &&
-        !strcmp(buf, rsa_signature)) {
-        return loadrsakey_main(fp, NULL, comment, NULL);
+    if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
+       return loadrsakey_main(fp, NULL, comment, NULL);
     }
     fclose(fp);
-    return 0;                          /* wasn't the right kind of file */
+    return 0;                         /* wasn't the right kind of file */
 }
 
 /*
  * Save an RSA key file. Return nonzero on success.
  */
-int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
+int saversakey(char *filename, struct RSAKey *key, char *passphrase)
+{
     unsigned char buf[16384];
     unsigned char keybuf[16];
     struct MD5Context md5c;
@@ -206,14 +217,16 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
      * uint32.
      */
     *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
-    PUT_32BIT(p, 0); p += 4;
+    PUT_32BIT(p, 0);
+    p += 4;
 
     /*
      * An ordinary SSH 1 public key consists of: a uint32
      * containing the bit count, then two bignums containing the
      * modulus and exponent respectively.
      */
-    PUT_32BIT(p, bignum_bitcount(key->modulus)); p += 4;
+    PUT_32BIT(p, bignum_bitcount(key->modulus));
+    p += 4;
     p += ssh1_write_bignum(p, key->modulus);
     p += ssh1_write_bignum(p, key->exponent);
 
@@ -221,11 +234,13 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
      * A string containing the comment field.
      */
     if (key->comment) {
-        PUT_32BIT(p, strlen(key->comment)); p += 4;
-        memcpy(p, key->comment, strlen(key->comment));
-        p += strlen(key->comment);
+       PUT_32BIT(p, strlen(key->comment));
+       p += 4;
+       memcpy(p, key->comment, strlen(key->comment));
+       p += strlen(key->comment);
     } else {
-        PUT_32BIT(p, 0); p += 4;
+       PUT_32BIT(p, 0);
+       p += 4;
     }
 
     /*
@@ -238,7 +253,9 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
      */
     *p++ = random_byte();
     *p++ = random_byte();
-    p[0] = p[-2]; p[1] = p[-1]; p += 2;
+    p[0] = p[-2];
+    p[1] = p[-1];
+    p += 2;
 
     /*
      * Four more bignums: the decryption exponent, then iqmp, then
@@ -253,18 +270,18 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
      * Now write zeros until the encrypted portion is a multiple of
      * 8 bytes.
      */
-    while ((p-estart) % 8)
-        *p++ = '\0';
+    while ((p - estart) % 8)
+       *p++ = '\0';
 
     /*
      * Now encrypt the encrypted portion.
      */
     if (passphrase) {
-        MD5Init(&md5c);
-        MD5Update(&md5c, passphrase, strlen(passphrase));
-        MD5Final(keybuf, &md5c);
-        des3_encrypt_pubkey(keybuf, estart, p-estart);
-        memset(keybuf, 0, sizeof(keybuf));    /* burn the evidence */
+       MD5Init(&md5c);
+       MD5Update(&md5c, passphrase, strlen(passphrase));
+       MD5Final(keybuf, &md5c);
+       des3_encrypt_pubkey(keybuf, estart, p - estart);
+       memset(keybuf, 0, sizeof(keybuf));      /* burn the evidence */
     }
 
     /*
@@ -272,11 +289,11 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
      */
     fp = fopen(filename, "wb");
     if (fp) {
-        int ret = (fwrite(buf, 1, p-buf, fp) == (size_t)(p-buf));
-        ret = ret && (fclose(fp) == 0);
-        return ret;
+       int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
+       ret = ret && (fclose(fp) == 0);
+       return ret;
     } else
-        return 0;
+       return 0;
 }
 
 /* ----------------------------------------------------------------------
@@ -345,7 +362,8 @@ int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
  * section other than just x.
  */
 
-static int read_header(FILE *fp, char *header) {
+static int read_header(FILE * fp, char *header)
+{
     int len = 39;
     int c;
 
@@ -368,7 +386,8 @@ static int read_header(FILE *fp, char *header) {
     return 0;                         /* failure */
 }
 
-static char *read_body(FILE *fp) {
+static char *read_body(FILE * fp)
+{
     char *text;
     int len;
     int size;
@@ -400,12 +419,13 @@ static char *read_body(FILE *fp) {
     }
 }
 
-int base64_decode_atom(char *atom, unsigned char *out) {
+int base64_decode_atom(char *atom, unsigned char *out)
+{
     int vals[4];
     int i, v, len;
     unsigned word;
     char c;
-    
+
     for (i = 0; i < 4; i++) {
        c = atom[i];
        if (c >= 'A' && c <= 'Z')
@@ -438,9 +458,7 @@ int base64_decode_atom(char *atom, unsigned char *out) {
        len = 1;
 
     word = ((vals[0] << 18) |
-           (vals[1] << 12) |
-           ((vals[2] & 0x3F) << 6) |
-           (vals[3] & 0x3F));
+           (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
     out[0] = (word >> 16) & 0xFF;
     if (len > 1)
        out[1] = (word >> 8) & 0xFF;
@@ -449,7 +467,8 @@ int base64_decode_atom(char *atom, unsigned char *out) {
     return len;
 }
 
-static char *read_blob(FILE *fp, int nlines, int *bloblen) {
+static char *read_blob(FILE * fp, int nlines, int *bloblen)
+{
     unsigned char *blob;
     char *line;
     int linelen, len;
@@ -471,7 +490,7 @@ static char *read_blob(FILE *fp, int nlines, int *bloblen) {
            return NULL;
        }
        for (j = 0; j < linelen; j += 4) {
-           k = base64_decode_atom(line+j, blob+len);
+           k = base64_decode_atom(line + j, blob + len);
            if (!k) {
                sfree(line);
                sfree(blob);
@@ -492,7 +511,8 @@ struct ssh2_userkey ssh2_wrong_passphrase = {
     NULL, NULL, NULL
 };
 
-struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
+struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase)
+{
     FILE *fp;
     char header[40], *b, *comment, *hash;
     const struct ssh_signkey *alg;
@@ -511,7 +531,8 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
        goto error;
 
     /* Read the first header line which contains the key type. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1"))
+    if (!read_header(fp, header)
+       || 0 != strcmp(header, "PuTTY-User-Key-File-1"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
@@ -523,16 +544,18 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
        goto error;
     }
     sfree(b);
-    
+
     /* Read the Encryption header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Encryption"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
     if (!strcmp(b, "aes256-cbc")) {
-       cipher = 1; cipherblk = 16;
+       cipher = 1;
+       cipherblk = 16;
     } else if (!strcmp(b, "none")) {
-       cipher = 0; cipherblk = 1;
+       cipher = 0;
+       cipherblk = 1;
     } else {
        sfree(b);
        goto error;
@@ -540,13 +563,13 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
     sfree(b);
 
     /* Read the Comment header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Comment"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
        goto error;
     if ((comment = read_body(fp)) == NULL)
        goto error;
 
     /* Read the Public-Lines header line and the public blob. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Public-Lines"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
@@ -556,7 +579,7 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
        goto error;
 
     /* Read the Private-Lines header line and the Private blob. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Private-Lines"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
@@ -566,7 +589,7 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
        goto error;
 
     /* Read the Private-Hash header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Private-Hash"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Private-Hash"))
        goto error;
     if ((hash = read_body(fp)) == NULL)
        goto error;
@@ -592,11 +615,11 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
        SHA_Init(&s);
        SHA_Bytes(&s, "\0\0\0\0", 4);
        SHA_Bytes(&s, passphrase, passlen);
-       SHA_Final(&s, key+0);
+       SHA_Final(&s, key + 0);
        SHA_Init(&s);
        SHA_Bytes(&s, "\0\0\0\1", 4);
        SHA_Bytes(&s, passphrase, passlen);
-       SHA_Final(&s, key+20);
+       SHA_Final(&s, key + 20);
        aes256_decrypt_pubkey(key, private_blob, private_blob_len);
     }
 
@@ -609,7 +632,7 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
 
        SHA_Simple(private_blob, private_blob_len, binary);
        for (i = 0; i < 20; i++)
-           sprintf(realhash+2*i, "%02x", binary[i]);
+           sprintf(realhash + 2 * i, "%02x", binary[i]);
 
        if (strcmp(hash, realhash)) {
            /* An incorrect hash is an unconditional Error if the key is
@@ -640,16 +663,23 @@ struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
     /*
      * Error processing.
      */
-    error:
-    if (fp) fclose(fp);
-    if (comment) sfree(comment);
-    if (hash) sfree(hash);
-    if (public_blob) sfree(public_blob);
-    if (private_blob) sfree(private_blob);
+  error:
+    if (fp)
+       fclose(fp);
+    if (comment)
+       sfree(comment);
+    if (hash)
+       sfree(hash);
+    if (public_blob)
+       sfree(public_blob);
+    if (private_blob)
+       sfree(private_blob);
     return ret;
 }
 
-char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len) {
+char *ssh2_userkey_loadpub(char *filename, char **algorithm,
+                          int *pub_blob_len)
+{
     FILE *fp;
     char header[40], *b;
     const struct ssh_signkey *alg;
@@ -664,7 +694,8 @@ char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len)
        goto error;
 
     /* Read the first header line which contains the key type. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1"))
+    if (!read_header(fp, header)
+       || 0 != strcmp(header, "PuTTY-User-Key-File-1"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
@@ -676,23 +707,23 @@ char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len)
        goto error;
     }
     sfree(b);
-    
+
     /* Read the Encryption header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Encryption"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
     sfree(b);                         /* we don't care */
 
     /* Read the Comment header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Comment"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
     sfree(b);                         /* we don't care */
 
     /* Read the Public-Lines header line and the public blob. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Public-Lines"))
+    if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
        goto error;
     if ((b = read_body(fp)) == NULL)
        goto error;
@@ -709,46 +740,60 @@ char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len)
     /*
      * Error processing.
      */
-    error:
-    if (fp) fclose(fp);
-    if (public_blob) sfree(public_blob);
+  error:
+    if (fp)
+       fclose(fp);
+    if (public_blob)
+       sfree(public_blob);
     return NULL;
 }
 
-int ssh2_userkey_encrypted(char *filename, char **commentptr) {
+int ssh2_userkey_encrypted(char *filename, char **commentptr)
+{
     FILE *fp;
     char header[40], *b, *comment;
     int ret;
 
-    if (commentptr) *commentptr = NULL;
+    if (commentptr)
+       *commentptr = NULL;
 
     fp = fopen(filename, "rb");
     if (!fp)
        return 0;
-    if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1")) {
-       fclose(fp); return 0;
+    if (!read_header(fp, header)
+       || 0 != strcmp(header, "PuTTY-User-Key-File-1")) {
+       fclose(fp);
+       return 0;
     }
     if ((b = read_body(fp)) == NULL) {
-       fclose(fp); return 0;
+       fclose(fp);
+       return 0;
     }
     sfree(b);                         /* we don't care about key type here */
     /* Read the Encryption header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Encryption")) {
-       fclose(fp); return 0;
+    if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
+       fclose(fp);
+       return 0;
     }
     if ((b = read_body(fp)) == NULL) {
-       fclose(fp); return 0;
+       fclose(fp);
+       return 0;
     }
 
     /* Read the Comment header line. */
-    if (!read_header(fp, header) || 0!=strcmp(header, "Comment")) {
-       fclose(fp); sfree(b); return 1;
+    if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
+       fclose(fp);
+       sfree(b);
+       return 1;
     }
     if ((comment = read_body(fp)) == NULL) {
-       fclose(fp); sfree(b); return 1;
+       fclose(fp);
+       sfree(b);
+       return 1;
     }
 
-    if (commentptr) *commentptr = comment;
+    if (commentptr)
+       *commentptr = comment;
 
     fclose(fp);
     if (!strcmp(b, "aes256-cbc"))
@@ -759,12 +804,14 @@ int ssh2_userkey_encrypted(char *filename, char **commentptr) {
     return ret;
 }
 
-int base64_lines(int datalen) {
+int base64_lines(int datalen)
+{
     /* When encoding, we use 64 chars/line, which equals 48 real chars. */
-    return (datalen+47) / 48;
+    return (datalen + 47) / 48;
 }
 
-void base64_encode_atom(unsigned char *data, int n, char *out) {
+void base64_encode_atom(unsigned char *data, int n, char *out)
+{
     static const char base64_chars[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
@@ -787,7 +834,8 @@ void base64_encode_atom(unsigned char *data, int n, char *out) {
        out[3] = '=';
 }
 
-void base64_encode(FILE *fp, unsigned char *data, int datalen) {
+void base64_encode(FILE * fp, unsigned char *data, int datalen)
+{
     int linelen = 0;
     char out[4];
     int n;
@@ -807,7 +855,9 @@ void base64_encode(FILE *fp, unsigned char *data, int datalen) {
     fputc('\n', fp);
 }
 
-int ssh2_save_userkey(char *filename, struct ssh2_userkey *key, char *passphrase) {
+int ssh2_save_userkey(char *filename, struct ssh2_userkey *key,
+                     char *passphrase)
+{
     FILE *fp;
     unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
     int pub_blob_len, priv_blob_len, priv_encrypted_len;
@@ -862,12 +912,13 @@ int ssh2_save_userkey(char *filename, struct ssh2_userkey *key, char *passphrase
        SHA_Init(&s);
        SHA_Bytes(&s, "\0\0\0\0", 4);
        SHA_Bytes(&s, passphrase, passlen);
-       SHA_Final(&s, key+0);
+       SHA_Final(&s, key + 0);
        SHA_Init(&s);
        SHA_Bytes(&s, "\0\0\0\1", 4);
        SHA_Bytes(&s, passphrase, passlen);
-       SHA_Final(&s, key+20);
-       aes256_encrypt_pubkey(key, priv_blob_encrypted, priv_encrypted_len);
+       SHA_Final(&s, key + 20);
+       aes256_encrypt_pubkey(key, priv_blob_encrypted,
+                             priv_encrypted_len);
     }
 
     fp = fopen(filename, "w");
@@ -892,7 +943,8 @@ int ssh2_save_userkey(char *filename, struct ssh2_userkey *key, char *passphrase
  * A function to determine which version of SSH to try on a private
  * key file. Returns 0 on failure, 1 or 2 on success.
  */
-int keyfile_version(char *filename) {
+int keyfile_version(char *filename)
+{
     FILE *fp;
     int i;
 
index 21a1b83..3014da4 100644 (file)
--- a/sshrand.c
+++ b/sshrand.c
@@ -41,14 +41,15 @@ struct RandPool {
 static struct RandPool pool;
 static int random_active = 0;
 
-void random_stir(void) {
-    word32 block[HASHINPUT/sizeof(word32)];
-    word32 digest[HASHSIZE/sizeof(word32)];
+void random_stir(void)
+{
+    word32 block[HASHINPUT / sizeof(word32)];
+    word32 digest[HASHSIZE / sizeof(word32)];
     int i, j, k;
 
     noise_get_light(random_add_noise);
 
-    SHATransform((word32 *)pool.incoming, (word32 *)pool.incomingb);
+    SHATransform((word32 *) pool.incoming, (word32 *) pool.incomingb);
     pool.incomingpos = 0;
 
     /*
@@ -77,14 +78,14 @@ void random_stir(void) {
         * things will be that much less predictable that way
         * round, when we subsequently return bytes ...
         */
-       for (j = POOLSIZE; (j -= HASHSIZE) >= 0 ;) {
+       for (j = POOLSIZE; (j -= HASHSIZE) >= 0;) {
            /*
             * XOR the bit of the pool we're processing into the
             * digest.
             */
 
-           for (k = 0; k < sizeof(digest)/sizeof(*digest); k++)
-               digest[k] ^= ((word32 *)(pool.pool+j))[k];
+           for (k = 0; k < sizeof(digest) / sizeof(*digest); k++)
+               digest[k] ^= ((word32 *) (pool.pool + j))[k];
 
            /*
             * Munge our unrevealed first block of the pool into
@@ -96,8 +97,8 @@ void random_stir(void) {
             * Stick the result back into the pool.
             */
 
-           for (k = 0; k < sizeof(digest)/sizeof(*digest); k++)
-               ((word32 *)(pool.pool+j))[k] = digest[k];
+           for (k = 0; k < sizeof(digest) / sizeof(*digest); k++)
+               ((word32 *) (pool.pool + j))[k] = digest[k];
        }
     }
 
@@ -111,12 +112,13 @@ void random_stir(void) {
     pool.poolpos = sizeof(pool.incoming);
 }
 
-void random_add_noise(void *noise, int length) {
+void random_add_noise(void *noise, int length)
+{
     unsigned char *p = noise;
     int i;
 
     if (!random_active)
-        return;
+       return;
 
     /*
      * This function processes HASHINPUT bytes into only HASHSIZE
@@ -128,14 +130,14 @@ void random_add_noise(void *noise, int length) {
               HASHINPUT - pool.incomingpos);
        p += HASHINPUT - pool.incomingpos;
        length -= HASHINPUT - pool.incomingpos;
-       SHATransform((word32 *)pool.incoming, (word32 *)pool.incomingb);
-        for (i = 0; i < HASHSIZE; i++) {
-            pool.pool[pool.poolpos++] ^= pool.incomingb[i];
-            if (pool.poolpos >= POOLSIZE)
-                pool.poolpos = 0;
-        }
-        if (pool.poolpos < HASHSIZE)
-            random_stir();
+       SHATransform((word32 *) pool.incoming, (word32 *) pool.incomingb);
+       for (i = 0; i < HASHSIZE; i++) {
+           pool.pool[pool.poolpos++] ^= pool.incomingb[i];
+           if (pool.poolpos >= POOLSIZE)
+               pool.poolpos = 0;
+       }
+       if (pool.poolpos < HASHSIZE)
+           random_stir();
 
        pool.incomingpos = 0;
     }
@@ -144,40 +146,43 @@ void random_add_noise(void *noise, int length) {
     pool.incomingpos += length;
 }
 
-void random_add_heavynoise(void *noise, int length) {
+void random_add_heavynoise(void *noise, int length)
+{
     unsigned char *p = noise;
     int i;
 
     while (length >= POOLSIZE) {
-        for (i = 0; i < POOLSIZE; i++)
-            pool.pool[i] ^= *p++;
+       for (i = 0; i < POOLSIZE; i++)
+           pool.pool[i] ^= *p++;
        random_stir();
        length -= POOLSIZE;
     }
 
     for (i = 0; i < length; i++)
-        pool.pool[i] ^= *p++;
+       pool.pool[i] ^= *p++;
     random_stir();
 }
 
-static void random_add_heavynoise_bitbybit(void *noise, int length) {
+static void random_add_heavynoise_bitbybit(void *noise, int length)
+{
     unsigned char *p = noise;
     int i;
 
     while (length >= POOLSIZE - pool.poolpos) {
-        for (i = 0; i < POOLSIZE - pool.poolpos; i++)
-            pool.pool[pool.poolpos + i] ^= *p++;
+       for (i = 0; i < POOLSIZE - pool.poolpos; i++)
+           pool.pool[pool.poolpos + i] ^= *p++;
        random_stir();
        length -= POOLSIZE - pool.poolpos;
-        pool.poolpos = 0;
+       pool.poolpos = 0;
     }
 
     for (i = 0; i < length; i++)
-        pool.pool[i] ^= *p++;
+       pool.pool[i] ^= *p++;
     pool.poolpos = i;
 }
 
-void random_init(void) {
+void random_init(void)
+{
     memset(&pool, 0, sizeof(pool));    /* just to start with */
 
     random_active = 1;
@@ -186,15 +191,17 @@ void random_init(void) {
     random_stir();
 }
 
-int random_byte(void) {
+int random_byte(void)
+{
     if (pool.poolpos >= POOLSIZE)
        random_stir();
 
     return pool.pool[pool.poolpos++];
 }
 
-void random_get_savedata(void **data, int *len) {
+void random_get_savedata(void **data, int *len)
+{
     random_stir();
-    *data = pool.pool+pool.poolpos;
-    *len = POOLSIZE/2;
+    *data = pool.pool + pool.poolpos;
+    *len = POOLSIZE / 2;
 }
index 930d151..74cfac5 100644 (file)
--- a/sshrsa.c
+++ b/sshrsa.c
 
 
 int makekey(unsigned char *data, struct RSAKey *result,
-           unsigned char **keystr, int order) {
+           unsigned char **keystr, int order)
+{
     unsigned char *p = data;
     int i;
 
     if (result) {
-        result->bits = 0;
-        for (i=0; i<4; i++)
-            result->bits = (result->bits << 8) + *p++;
+       result->bits = 0;
+       for (i = 0; i < 4; i++)
+           result->bits = (result->bits << 8) + *p++;
     } else
-        p += 4;
+       p += 4;
 
     /*
      * order=0 means exponent then modulus (the keys sent by the
@@ -32,68 +33,74 @@ int makekey(unsigned char *data, struct RSAKey *result,
      */
 
     if (order == 0)
-        p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
+       p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
     if (result)
-        result->bytes = (((p[0] << 8) + p[1]) + 7) / 8;
-    if (keystr) *keystr = p+2;
+       result->bytes = (((p[0] << 8) + p[1]) + 7) / 8;
+    if (keystr)
+       *keystr = p + 2;
     p += ssh1_read_bignum(p, result ? &result->modulus : NULL);
     if (order == 1)
-        p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
+       p += ssh1_read_bignum(p, result ? &result->exponent : NULL);
 
     return p - data;
 }
 
-int makeprivate(unsigned char *data, struct RSAKey *result) {
+int makeprivate(unsigned char *data, struct RSAKey *result)
+{
     return ssh1_read_bignum(data, &result->private_exponent);
 }
 
-void rsaencrypt(unsigned char *data, int length, struct RSAKey *key) {
+void rsaencrypt(unsigned char *data, int length, struct RSAKey *key)
+{
     Bignum b1, b2;
     int i;
     unsigned char *p;
 
-    memmove(data+key->bytes-length, data, length);
+    memmove(data + key->bytes - length, data, length);
     data[0] = 0;
     data[1] = 2;
 
-    for (i = 2; i < key->bytes-length-1; i++) {
+    for (i = 2; i < key->bytes - length - 1; i++) {
        do {
            data[i] = random_byte();
        } while (data[i] == 0);
     }
-    data[key->bytes-length-1] = 0;
+    data[key->bytes - length - 1] = 0;
 
     b1 = bignum_from_bytes(data, key->bytes);
 
     b2 = modpow(b1, key->exponent, key->modulus);
 
     p = data;
-    for (i=key->bytes; i-- ;) {
-        *p++ = bignum_byte(b2, i);
+    for (i = key->bytes; i--;) {
+       *p++ = bignum_byte(b2, i);
     }
 
     freebn(b1);
     freebn(b2);
 }
 
-Bignum rsadecrypt(Bignum input, struct RSAKey *key) {
+Bignum rsadecrypt(Bignum input, struct RSAKey *key)
+{
     Bignum ret;
     ret = modpow(input, key->private_exponent, key->modulus);
     return ret;
 }
 
-int rsastr_len(struct RSAKey *key) {
+int rsastr_len(struct RSAKey *key)
+{
     Bignum md, ex;
     int mdlen, exlen;
 
     md = key->modulus;
     ex = key->exponent;
-    mdlen = (bignum_bitcount(md)+15) / 16;
-    exlen = (bignum_bitcount(ex)+15) / 16;
-    return 4 * (mdlen+exlen) + 20;
+    mdlen = (bignum_bitcount(md) + 15) / 16;
+    exlen = (bignum_bitcount(ex) + 15) / 16;
+    return 4 * (mdlen + exlen) + 20;
 }
 
-void rsastr_fmt(char *str, struct RSAKey *key) {
+void rsastr_fmt(char *str, struct RSAKey *key)
+{
     Bignum md, ex;
     int len = 0, i, nibbles;
     static const char hex[] = "0123456789abcdef";
@@ -101,17 +108,21 @@ void rsastr_fmt(char *str, struct RSAKey *key) {
     md = key->modulus;
     ex = key->exponent;
 
-    len += sprintf(str+len, "0x");
+    len += sprintf(str + len, "0x");
 
-    nibbles = (3 + bignum_bitcount(ex))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        str[len++] = hex[(bignum_byte(ex, i/2) >> (4*(i%2))) & 0xF];
+    nibbles = (3 + bignum_bitcount(ex)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       str[len++] = hex[(bignum_byte(ex, i / 2) >> (4 * (i % 2))) & 0xF];
 
-    len += sprintf(str+len, ",0x");
+    len += sprintf(str + len, ",0x");
 
-    nibbles = (3 + bignum_bitcount(md))/4; if (nibbles<1) nibbles=1;
-    for (i=nibbles; i-- ;)
-        str[len++] = hex[(bignum_byte(md, i/2) >> (4*(i%2))) & 0xF];
+    nibbles = (3 + bignum_bitcount(md)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    for (i = nibbles; i--;)
+       str[len++] = hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF];
 
     str[len] = '\0';
 }
@@ -120,34 +131,37 @@ void rsastr_fmt(char *str, struct RSAKey *key) {
  * Generate a fingerprint string for the key. Compatible with the
  * OpenSSH fingerprint code.
  */
-void rsa_fingerprint(char *str, int len, struct RSAKey *key) {
+void rsa_fingerprint(char *str, int len, struct RSAKey *key)
+{
     struct MD5Context md5c;
     unsigned char digest[16];
-    char buffer[16*3+40];
+    char buffer[16 * 3 + 40];
     int numlen, slen, i;
 
     MD5Init(&md5c);
     numlen = ssh1_bignum_length(key->modulus) - 2;
-    for (i = numlen; i-- ;) {
-        unsigned char c = bignum_byte(key->modulus, i);
-        MD5Update(&md5c, &c, 1);
+    for (i = numlen; i--;) {
+       unsigned char c = bignum_byte(key->modulus, i);
+       MD5Update(&md5c, &c, 1);
     }
     numlen = ssh1_bignum_length(key->exponent) - 2;
-    for (i = numlen; i-- ;) {
-        unsigned char c = bignum_byte(key->exponent, i);
-        MD5Update(&md5c, &c, 1);
+    for (i = numlen; i--;) {
+       unsigned char c = bignum_byte(key->exponent, i);
+       MD5Update(&md5c, &c, 1);
     }
     MD5Final(digest, &md5c);
 
     sprintf(buffer, "%d ", bignum_bitcount(key->modulus));
     for (i = 0; i < 16; i++)
-        sprintf(buffer+strlen(buffer), "%s%02x", i?":":"", digest[i]);
-    strncpy(str, buffer, len); str[len-1] = '\0';
+       sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
+               digest[i]);
+    strncpy(str, buffer, len);
+    str[len - 1] = '\0';
     slen = strlen(str);
-    if (key->comment && slen < len-1) {
-        str[slen] = ' ';
-        strncpy(str+slen+1, key->comment, len-slen-1);
-        str[len-1] = '\0';
+    if (key->comment && slen < len - 1) {
+       str[slen] = ' ';
+       strncpy(str + slen + 1, key->comment, len - slen - 1);
+       str[len - 1] = '\0';
     }
 }
 
@@ -156,7 +170,8 @@ void rsa_fingerprint(char *str, int len, struct RSAKey *key) {
  * data. We also check the private data itself: we ensure that p >
  * q and that iqmp really is the inverse of q mod p.
  */
-int rsa_verify(struct RSAKey *key) {
+int rsa_verify(struct RSAKey *key)
+{
     Bignum n, ed, pm1, qm1;
     int cmp;
 
@@ -188,7 +203,7 @@ int rsa_verify(struct RSAKey *key) {
      * Ensure p > q.
      */
     if (bignum_cmp(key->p, key->q) <= 0)
-        return 0;
+       return 0;
 
     /*
      * Ensure iqmp * q is congruent to 1, modulo p.
@@ -197,16 +212,21 @@ int rsa_verify(struct RSAKey *key) {
     cmp = bignum_cmp(n, One);
     sfree(n);
     if (cmp != 0)
-        return 0;
+       return 0;
 
     return 1;
 }
 
-void freersakey(struct RSAKey *key) {
-    if (key->modulus) freebn(key->modulus);
-    if (key->exponent) freebn(key->exponent);
-    if (key->private_exponent) freebn(key->private_exponent);
-    if (key->comment) sfree(key->comment);
+void freersakey(struct RSAKey *key)
+{
+    if (key->modulus)
+       freebn(key->modulus);
+    if (key->exponent)
+       freebn(key->exponent);
+    if (key->private_exponent)
+       freebn(key->private_exponent);
+    if (key->comment)
+       sfree(key->comment);
 }
 
 /* ----------------------------------------------------------------------
@@ -225,36 +245,42 @@ void freersakey(struct RSAKey *key) {
     (cp)[2] = (unsigned char)((value) >> 8); \
     (cp)[3] = (unsigned char)(value); }
 
-static void getstring(char **data, int *datalen, char **p, int *length) {
+static void getstring(char **data, int *datalen, char **p, int *length)
+{
     *p = NULL;
     if (*datalen < 4)
-        return;
+       return;
     *length = GET_32BIT(*data);
-    *datalen -= 4; *data += 4;
+    *datalen -= 4;
+    *data += 4;
     if (*datalen < *length)
-        return;
+       return;
     *p = *data;
-    *data += *length; *datalen -= *length;
+    *data += *length;
+    *datalen -= *length;
 }
-static Bignum getmp(char **data, int *datalen) {
+static Bignum getmp(char **data, int *datalen)
+{
     char *p;
     int length;
     Bignum b;
 
     getstring(data, datalen, &p, &length);
     if (!p)
-        return NULL;
+       return NULL;
     b = bignum_from_bytes(p, length);
     return b;
 }
 
-static void *rsa2_newkey(char *data, int len) {
+static void *rsa2_newkey(char *data, int len)
+{
     char *p;
     int slen;
     struct RSAKey *rsa;
 
     rsa = smalloc(sizeof(struct RSAKey));
-    if (!rsa) return NULL;
+    if (!rsa)
+       return NULL;
     getstring(&data, &len, &p, &slen);
 
     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
@@ -269,87 +295,106 @@ static void *rsa2_newkey(char *data, int len) {
     return rsa;
 }
 
-static void rsa2_freekey(void *key) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static void rsa2_freekey(void *key)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     freersakey(rsa);
     sfree(rsa);
 }
 
-static char *rsa2_fmtkey(void *key) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static char *rsa2_fmtkey(void *key)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     char *p;
     int len;
-    
+
     len = rsastr_len(rsa);
     p = smalloc(len);
-     rsastr_fmt(p, rsa);
+    rsastr_fmt(p, rsa);
     return p;
 }
 
-static unsigned char *rsa2_public_blob(void *key, int *len) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static unsigned char *rsa2_public_blob(void *key, int *len)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     int elen, mlen, bloblen;
     int i;
     unsigned char *blob, *p;
 
-    elen = (bignum_bitcount(rsa->exponent)+8)/8;
-    mlen = (bignum_bitcount(rsa->modulus)+8)/8;
+    elen = (bignum_bitcount(rsa->exponent) + 8) / 8;
+    mlen = (bignum_bitcount(rsa->modulus) + 8) / 8;
 
     /*
      * string "ssh-rsa", mpint exp, mpint mod. Total 19+elen+mlen.
      * (three length fields, 12+7=19).
      */
-    bloblen = 19+elen+mlen;
+    bloblen = 19 + elen + mlen;
     blob = smalloc(bloblen);
     p = blob;
-    PUT_32BIT(p, 7); p += 4;
-    memcpy(p, "ssh-rsa", 7); p += 7;
-    PUT_32BIT(p, elen); p += 4;
-    for (i = elen; i-- ;) *p++ = bignum_byte(rsa->exponent, i);
-    PUT_32BIT(p, mlen); p += 4;
-    for (i = mlen; i-- ;) *p++ = bignum_byte(rsa->modulus, i);
+    PUT_32BIT(p, 7);
+    p += 4;
+    memcpy(p, "ssh-rsa", 7);
+    p += 7;
+    PUT_32BIT(p, elen);
+    p += 4;
+    for (i = elen; i--;)
+       *p++ = bignum_byte(rsa->exponent, i);
+    PUT_32BIT(p, mlen);
+    p += 4;
+    for (i = mlen; i--;)
+       *p++ = bignum_byte(rsa->modulus, i);
     assert(p == blob + bloblen);
     *len = bloblen;
     return blob;
 }
 
-static unsigned char *rsa2_private_blob(void *key, int *len) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static unsigned char *rsa2_private_blob(void *key, int *len)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     int dlen, plen, qlen, ulen, bloblen;
     int i;
     unsigned char *blob, *p;
 
-    dlen = (bignum_bitcount(rsa->private_exponent)+8)/8;
-    plen = (bignum_bitcount(rsa->p)+8)/8;
-    qlen = (bignum_bitcount(rsa->q)+8)/8;
-    ulen = (bignum_bitcount(rsa->iqmp)+8)/8;
+    dlen = (bignum_bitcount(rsa->private_exponent) + 8) / 8;
+    plen = (bignum_bitcount(rsa->p) + 8) / 8;
+    qlen = (bignum_bitcount(rsa->q) + 8) / 8;
+    ulen = (bignum_bitcount(rsa->iqmp) + 8) / 8;
 
     /*
      * mpint private_exp, mpint p, mpint q, mpint iqmp. Total 16 +
      * sum of lengths.
      */
-    bloblen = 16+dlen+plen+qlen+ulen;
+    bloblen = 16 + dlen + plen + qlen + ulen;
     blob = smalloc(bloblen);
     p = blob;
-    PUT_32BIT(p, dlen); p += 4;
-    for (i = dlen; i-- ;) *p++ = bignum_byte(rsa->private_exponent, i);
-    PUT_32BIT(p, plen); p += 4;
-    for (i = plen; i-- ;) *p++ = bignum_byte(rsa->p, i);
-    PUT_32BIT(p, qlen); p += 4;
-    for (i = qlen; i-- ;) *p++ = bignum_byte(rsa->q, i);
-    PUT_32BIT(p, ulen); p += 4;
-    for (i = ulen; i-- ;) *p++ = bignum_byte(rsa->iqmp, i);
+    PUT_32BIT(p, dlen);
+    p += 4;
+    for (i = dlen; i--;)
+       *p++ = bignum_byte(rsa->private_exponent, i);
+    PUT_32BIT(p, plen);
+    p += 4;
+    for (i = plen; i--;)
+       *p++ = bignum_byte(rsa->p, i);
+    PUT_32BIT(p, qlen);
+    p += 4;
+    for (i = qlen; i--;)
+       *p++ = bignum_byte(rsa->q, i);
+    PUT_32BIT(p, ulen);
+    p += 4;
+    for (i = ulen; i--;)
+       *p++ = bignum_byte(rsa->iqmp, i);
     assert(p == blob + bloblen);
     *len = bloblen;
     return blob;
 }
 
 static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
-                           unsigned char *priv_blob, int priv_len) {
+                           unsigned char *priv_blob, int priv_len)
+{
     struct RSAKey *rsa;
-    char *pb = (char *)priv_blob;
-    
-    rsa = rsa2_newkey((char *)pub_blob, pub_len);
+    char *pb = (char *) priv_blob;
+
+    rsa = rsa2_newkey((char *) pub_blob, pub_len);
     rsa->private_exponent = getmp(&pb, &priv_len);
     rsa->p = getmp(&pb, &priv_len);
     rsa->q = getmp(&pb, &priv_len);
@@ -363,12 +408,14 @@ static void *rsa2_createkey(unsigned char *pub_blob, int pub_len,
     return rsa;
 }
 
-static void *rsa2_openssh_createkey(unsigned char **blob, int *len) {
-    char **b = (char **)blob;
+static void *rsa2_openssh_createkey(unsigned char **blob, int *len)
+{
+    char **b = (char **) blob;
     struct RSAKey *rsa;
 
     rsa = smalloc(sizeof(struct RSAKey));
-    if (!rsa) return NULL;
+    if (!rsa)
+       return NULL;
     rsa->comment = NULL;
 
     rsa->modulus = getmp(b, len);
@@ -393,8 +440,9 @@ static void *rsa2_openssh_createkey(unsigned char **blob, int *len) {
     return rsa;
 }
 
-static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     int bloblen, i;
 
     bloblen =
@@ -402,8 +450,7 @@ static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len) {
        ssh2_bignum_length(rsa->exponent) +
        ssh2_bignum_length(rsa->private_exponent) +
        ssh2_bignum_length(rsa->iqmp) +
-       ssh2_bignum_length(rsa->p) +
-       ssh2_bignum_length(rsa->q);
+       ssh2_bignum_length(rsa->p) + ssh2_bignum_length(rsa->q);
 
     if (bloblen > len)
        return bloblen;
@@ -422,11 +469,12 @@ static int rsa2_openssh_fmtkey(void *key, unsigned char *blob, int len) {
     return bloblen;
 }
 
-static char *rsa2_fingerprint(void *key) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+static char *rsa2_fingerprint(void *key)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     struct MD5Context md5c;
     unsigned char digest[16], lenbuf[4];
-    char buffer[16*3+40];
+    char buffer[16 * 3 + 40];
     char *ret;
     int numlen, i;
 
@@ -448,10 +496,11 @@ static char *rsa2_fingerprint(void *key) {
 
     sprintf(buffer, "ssh-rsa %d ", bignum_bitcount(rsa->modulus));
     for (i = 0; i < 16; i++)
-        sprintf(buffer+strlen(buffer), "%s%02x", i?":":"", digest[i]);
-    ret = smalloc(strlen(buffer)+1);
+       sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
+               digest[i]);
+    ret = smalloc(strlen(buffer) + 1);
     if (ret)
-        strcpy(ret, buffer);
+       strcpy(ret, buffer);
     return ret;
 }
 
@@ -480,15 +529,16 @@ static char *rsa2_fingerprint(void *key) {
  *    algorithms(2) 26 }
  */
 static unsigned char asn1_weird_stuff[] = {
-    0x00,0x30,0x21,0x30,0x09,0x06,0x05,0x2B,
-    0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14,
+    0x00, 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
+    0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14,
 };
 
 #define ASN1_LEN ( (int) sizeof(asn1_weird_stuff) )
 
 static int rsa2_verifysig(void *key, char *sig, int siglen,
-                        char *data, int datalen) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+                         char *data, int datalen)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     Bignum in, out;
     char *p;
     int slen;
@@ -497,7 +547,7 @@ static int rsa2_verifysig(void *key, char *sig, int siglen,
 
     getstring(&sig, &siglen, &p, &slen);
     if (!p || slen != 7 || memcmp(p, "ssh-rsa", 7)) {
-        return 0;
+       return 0;
     }
     in = getmp(&sig, &siglen);
     out = modpow(in, rsa->exponent, rsa->modulus);
@@ -507,33 +557,34 @@ static int rsa2_verifysig(void *key, char *sig, int siglen,
 
     bytes = bignum_bitcount(rsa->modulus) / 8;
     /* Top (partial) byte should be zero. */
-    if (bignum_byte(out, bytes-1) != 0)
-        ret = 0;
+    if (bignum_byte(out, bytes - 1) != 0)
+       ret = 0;
     /* First whole byte should be 1. */
-    if (bignum_byte(out, bytes-2) != 1)
-        ret = 0;
+    if (bignum_byte(out, bytes - 2) != 1)
+       ret = 0;
     /* Most of the rest should be FF. */
-    for (i = bytes-3; i >= 20 + ASN1_LEN; i--) {
-        if (bignum_byte(out, i) != 0xFF)
-            ret = 0;
+    for (i = bytes - 3; i >= 20 + ASN1_LEN; i--) {
+       if (bignum_byte(out, i) != 0xFF)
+           ret = 0;
     }
     /* Then we expect to see the asn1_weird_stuff. */
-    for (i = 20 + ASN1_LEN - 1, j=0; i >= 20; i--,j++) {
-        if (bignum_byte(out, i) != asn1_weird_stuff[j])
-            ret = 0;
+    for (i = 20 + ASN1_LEN - 1, j = 0; i >= 20; i--, j++) {
+       if (bignum_byte(out, i) != asn1_weird_stuff[j])
+           ret = 0;
     }
     /* Finally, we expect to see the SHA-1 hash of the signed data. */
     SHA_Simple(data, datalen, hash);
-    for (i = 19, j=0; i >= 0; i--,j++) {
-        if (bignum_byte(out, i) != hash[j])
-            ret = 0;
+    for (i = 19, j = 0; i >= 0; i--, j++) {
+       if (bignum_byte(out, i) != hash[j])
+           ret = 0;
     }
 
     return ret;
 }
 
-unsigned char *rsa2_sign(void *key, char *data, int datalen, int *siglen) {
-    struct RSAKey *rsa = (struct RSAKey *)key;
+unsigned char *rsa2_sign(void *key, char *data, int datalen, int *siglen)
+{
+    struct RSAKey *rsa = (struct RSAKey *) key;
     unsigned char *bytes;
     int nbytes;
     unsigned char hash[20];
@@ -542,15 +593,15 @@ unsigned char *rsa2_sign(void *key, char *data, int datalen, int *siglen) {
 
     SHA_Simple(data, datalen, hash);
 
-    nbytes = (bignum_bitcount(rsa->modulus)-1) / 8;
+    nbytes = (bignum_bitcount(rsa->modulus) - 1) / 8;
     bytes = smalloc(nbytes);
 
     bytes[0] = 1;
-    for (i = 1; i < nbytes-20-ASN1_LEN; i++)
+    for (i = 1; i < nbytes - 20 - ASN1_LEN; i++)
        bytes[i] = 0xFF;
-    for (i = nbytes-20-ASN1_LEN, j=0; i < nbytes-20; i++,j++)
+    for (i = nbytes - 20 - ASN1_LEN, j = 0; i < nbytes - 20; i++, j++)
        bytes[i] = asn1_weird_stuff[j];
-    for (i = nbytes-20, j=0; i < nbytes; i++,j++)
+    for (i = nbytes - 20, j = 0; i < nbytes; i++, j++)
        bytes[i] = hash[j];
 
     in = bignum_from_bytes(bytes, nbytes);
@@ -559,16 +610,16 @@ unsigned char *rsa2_sign(void *key, char *data, int datalen, int *siglen) {
     out = modpow(in, rsa->private_exponent, rsa->modulus);
     freebn(in);
 
-    nbytes = (bignum_bitcount(out)+7)/8;
-    bytes = smalloc(4+7+4+nbytes);
+    nbytes = (bignum_bitcount(out) + 7) / 8;
+    bytes = smalloc(4 + 7 + 4 + nbytes);
     PUT_32BIT(bytes, 7);
-    memcpy(bytes+4, "ssh-rsa", 7);
-    PUT_32BIT(bytes+4+7, nbytes);
+    memcpy(bytes + 4, "ssh-rsa", 7);
+    PUT_32BIT(bytes + 4 + 7, nbytes);
     for (i = 0; i < nbytes; i++)
-       bytes[4+7+4+i] = bignum_byte(out, nbytes-1-i);
+       bytes[4 + 7 + 4 + i] = bignum_byte(out, nbytes - 1 - i);
     freebn(out);
 
-    *siglen = 4+7+4+nbytes;
+    *siglen = 4 + 7 + 4 + nbytes;
     return bytes;
 }
 
index 03f416a..9e543c9 100644 (file)
--- a/sshrsag.c
+++ b/sshrsag.c
@@ -4,26 +4,33 @@
 
 #include "ssh.h"
 
-#define RSA_EXPONENT 37                /* we like this prime */
+#define RSA_EXPONENT 37                       /* we like this prime */
 
-#if 0                                  /* bignum diagnostic function */
-static void diagbn(char *prefix, Bignum md) {
+#if 0                                 /* bignum diagnostic function */
+static void diagbn(char *prefix, Bignum md)
+{
     int i, nibbles, morenibbles;
     static const char hex[] = "0123456789ABCDEF";
 
     printf("%s0x", prefix ? prefix : "");
 
-    nibbles = (3 + bignum_bitcount(md))/4; if (nibbles<1) nibbles=1;
-    morenibbles = 4*md[0] - nibbles;
-    for (i=0; i<morenibbles; i++) putchar('-');
-    for (i=nibbles; i-- ;)
-        putchar(hex[(bignum_byte(md, i/2) >> (4*(i%2))) & 0xF]);
+    nibbles = (3 + bignum_bitcount(md)) / 4;
+    if (nibbles < 1)
+       nibbles = 1;
+    morenibbles = 4 * md[0] - nibbles;
+    for (i = 0; i < morenibbles; i++)
+       putchar('-');
+    for (i = nibbles; i--;)
+       putchar(hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]);
 
-    if (prefix) putchar('\n');
+    if (prefix)
+       putchar('\n');
 }
 #endif
 
-int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn, void *pfnparam) {
+int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn,
+                void *pfnparam)
+{
     Bignum pm1, qm1, phi_n;
 
     /*
@@ -54,8 +61,8 @@ int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn, void *pfnparam) {
      * time. We do this in 16-bit fixed point, so 29.34 becomes
      * 0x1D.57C4.
      */
-    pfn(pfnparam, -1, -0x1D57C4/(bits/2));
-    pfn(pfnparam, -2, -0x1D57C4/(bits-bits/2));
+    pfn(pfnparam, -1, -0x1D57C4 / (bits / 2));
+    pfn(pfnparam, -2, -0x1D57C4 / (bits - bits / 2));
     pfn(pfnparam, -3, 5);
 
     /*
@@ -70,16 +77,16 @@ int rsa_generate(struct RSAKey *key, int bits, progfn_t pfn, void *pfnparam) {
      * general that's slightly more fiddly to arrange. By choosing
      * a prime e, we can simplify the criterion.)
      */
-    key->p = primegen(bits/2, RSA_EXPONENT, 1, 1, pfn, pfnparam);
-    key->q = primegen(bits - bits/2, RSA_EXPONENT, 1, 2, pfn, pfnparam);
+    key->p = primegen(bits / 2, RSA_EXPONENT, 1, 1, pfn, pfnparam);
+    key->q = primegen(bits - bits / 2, RSA_EXPONENT, 1, 2, pfn, pfnparam);
 
     /*
      * Ensure p > q, by swapping them if not.
      */
     if (bignum_cmp(key->p, key->q) < 0) {
-        Bignum t = key->p;
-        key->p = key->q;
-        key->q = t;
+       Bignum t = key->p;
+       key->p = key->q;
+       key->q = t;
     }
 
     /*
index 2a07cc3..6031685 100644 (file)
--- a/sshsha.c
+++ b/sshsha.c
@@ -13,7 +13,8 @@
 
 #define rol(x,y) ( ((x) << (y)) | (((uint32)x) >> (32-y)) )
 
-void SHA_Core_Init(uint32 h[5]) {
+void SHA_Core_Init(uint32 h[5])
+{
     h[0] = 0x67452301;
     h[1] = 0xefcdab89;
     h[2] = 0x98badcfe;
@@ -21,17 +22,18 @@ void SHA_Core_Init(uint32 h[5]) {
     h[4] = 0xc3d2e1f0;
 }
 
-void SHATransform(word32 *digest, word32 *block) {
+void SHATransform(word32 * digest, word32 * block)
+{
     word32 w[80];
-    word32 a,b,c,d,e;
+    word32 a, b, c, d, e;
     int t;
 
     for (t = 0; t < 16; t++)
-        w[t] = block[t];
+       w[t] = block[t];
 
     for (t = 16; t < 80; t++) {
-        word32 tmp = w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16];
-        w[t] = rol(tmp, 1);
+       word32 tmp = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
+       w[t] = rol(tmp, 1);
     }
 
     a = digest[0];
@@ -41,20 +43,39 @@ void SHATransform(word32 *digest, word32 *block) {
     e = digest[4];
 
     for (t = 0; t < 20; t++) {
-        word32 tmp = rol(a, 5) + ( (b&c) | (d&~b) ) + e + w[t] + 0x5a827999;
-        e = d; d = c; c = rol(b, 30); b = a; a = tmp;
+       word32 tmp =
+           rol(a, 5) + ((b & c) | (d & ~b)) + e + w[t] + 0x5a827999;
+       e = d;
+       d = c;
+       c = rol(b, 30);
+       b = a;
+       a = tmp;
     }
     for (t = 20; t < 40; t++) {
-        word32 tmp = rol(a, 5) + (b^c^d) + e + w[t] + 0x6ed9eba1;
-        e = d; d = c; c = rol(b, 30); b = a; a = tmp;
+       word32 tmp = rol(a, 5) + (b ^ c ^ d) + e + w[t] + 0x6ed9eba1;
+       e = d;
+       d = c;
+       c = rol(b, 30);
+       b = a;
+       a = tmp;
     }
     for (t = 40; t < 60; t++) {
-        word32 tmp = rol(a, 5) + ( (b&c) | (b&d) | (c&d) ) + e + w[t] + 0x8f1bbcdc;
-        e = d; d = c; c = rol(b, 30); b = a; a = tmp;
+       word32 tmp = rol(a,
+                        5) + ((b & c) | (b & d) | (c & d)) + e + w[t] +
+           0x8f1bbcdc;
+       e = d;
+       d = c;
+       c = rol(b, 30);
+       b = a;
+       a = tmp;
     }
     for (t = 60; t < 80; t++) {
-        word32 tmp = rol(a, 5) + (b^c^d) + e + w[t] + 0xca62c1d6;
-        e = d; d = c; c = rol(b, 30); b = a; a = tmp;
+       word32 tmp = rol(a, 5) + (b ^ c ^ d) + e + w[t] + 0xca62c1d6;
+       e = d;
+       d = c;
+       c = rol(b, 30);
+       b = a;
+       a = tmp;
     }
 
     digest[0] += a;
@@ -70,14 +91,16 @@ void SHATransform(word32 *digest, word32 *block) {
  * the end, and pass those blocks to the core SHA algorithm.
  */
 
-void SHA_Init(SHA_State *s) {
+void SHA_Init(SHA_State * s)
+{
     SHA_Core_Init(s->h);
     s->blkused = 0;
     s->lenhi = s->lenlo = 0;
 }
 
-void SHA_Bytes(SHA_State *s, void *p, int len) {
-    unsigned char *q = (unsigned char *)p;
+void SHA_Bytes(SHA_State * s, void *p, int len)
+{
+    unsigned char *q = (unsigned char *) p;
     uint32 wordblock[16];
     uint32 lenw = len;
     int i;
@@ -88,48 +111,49 @@ void SHA_Bytes(SHA_State *s, void *p, int len) {
     s->lenlo += lenw;
     s->lenhi += (s->lenlo < lenw);
 
-    if (s->blkused && s->blkused+len < 64) {
-        /*
-         * Trivial case: just add to the block.
-         */
-        memcpy(s->block + s->blkused, q, len);
-        s->blkused += len;
+    if (s->blkused && s->blkused + len < 64) {
+       /*
+        * Trivial case: just add to the block.
+        */
+       memcpy(s->block + s->blkused, q, len);
+       s->blkused += len;
     } else {
-        /*
-         * We must complete and process at least one block.
-         */
-        while (s->blkused + len >= 64) {
-            memcpy(s->block + s->blkused, q, 64 - s->blkused);
-            q += 64 - s->blkused;
-            len -= 64 - s->blkused;
-            /* Now process the block. Gather bytes big-endian into words */
-            for (i = 0; i < 16; i++) {
-                wordblock[i] =
-                    ( ((uint32)s->block[i*4+0]) << 24 ) |
-                    ( ((uint32)s->block[i*4+1]) << 16 ) |
-                    ( ((uint32)s->block[i*4+2]) <<  8 ) |
-                    ( ((uint32)s->block[i*4+3]) <<  0 );
-            }
-            SHATransform(s->h, wordblock);
-            s->blkused = 0;
-        }
-        memcpy(s->block, q, len);
-        s->blkused = len;
+       /*
+        * We must complete and process at least one block.
+        */
+       while (s->blkused + len >= 64) {
+           memcpy(s->block + s->blkused, q, 64 - s->blkused);
+           q += 64 - s->blkused;
+           len -= 64 - s->blkused;
+           /* Now process the block. Gather bytes big-endian into words */
+           for (i = 0; i < 16; i++) {
+               wordblock[i] =
+                   (((uint32) s->block[i * 4 + 0]) << 24) |
+                   (((uint32) s->block[i * 4 + 1]) << 16) |
+                   (((uint32) s->block[i * 4 + 2]) << 8) |
+                   (((uint32) s->block[i * 4 + 3]) << 0);
+           }
+           SHATransform(s->h, wordblock);
+           s->blkused = 0;
+       }
+       memcpy(s->block, q, len);
+       s->blkused = len;
     }
 }
 
-void SHA_Final(SHA_State *s, unsigned char *output) {
+void SHA_Final(SHA_State * s, unsigned char *output)
+{
     int i;
     int pad;
     unsigned char c[64];
     uint32 lenhi, lenlo;
 
     if (s->blkused >= 56)
-        pad = 56 + 64 - s->blkused;
+       pad = 56 + 64 - s->blkused;
     else
-        pad = 56 - s->blkused;
+       pad = 56 - s->blkused;
 
-    lenhi = (s->lenhi << 3) | (s->lenlo >> (32-3));
+    lenhi = (s->lenhi << 3) | (s->lenlo >> (32 - 3));
     lenlo = (s->lenlo << 3);
 
     memset(c, 0, pad);
@@ -138,24 +162,25 @@ void SHA_Final(SHA_State *s, unsigned char *output) {
 
     c[0] = (lenhi >> 24) & 0xFF;
     c[1] = (lenhi >> 16) & 0xFF;
-    c[2] = (lenhi >>  8) & 0xFF;
-    c[3] = (lenhi >>  0) & 0xFF;
+    c[2] = (lenhi >> 8) & 0xFF;
+    c[3] = (lenhi >> 0) & 0xFF;
     c[4] = (lenlo >> 24) & 0xFF;
     c[5] = (lenlo >> 16) & 0xFF;
-    c[6] = (lenlo >>  8) & 0xFF;
-    c[7] = (lenlo >>  0) & 0xFF;
+    c[6] = (lenlo >> 8) & 0xFF;
+    c[7] = (lenlo >> 0) & 0xFF;
 
     SHA_Bytes(s, &c, 8);
 
     for (i = 0; i < 5; i++) {
-        output[i*4  ] = (s->h[i] >> 24) & 0xFF;
-        output[i*4+1] = (s->h[i] >> 16) & 0xFF;
-        output[i*4+2] = (s->h[i] >>  8) & 0xFF;
-        output[i*4+3] = (s->h[i]      ) & 0xFF;
+       output[i * 4] = (s->h[i] >> 24) & 0xFF;
+       output[i * 4 + 1] = (s->h[i] >> 16) & 0xFF;
+       output[i * 4 + 2] = (s->h[i] >> 8) & 0xFF;
+       output[i * 4 + 3] = (s->h[i]) & 0xFF;
     }
 }
 
-void SHA_Simple(void *p, int len, unsigned char *output) {
+void SHA_Simple(void *p, int len, unsigned char *output)
+{
     SHA_State s;
 
     SHA_Init(&s);
@@ -171,70 +196,79 @@ void SHA_Simple(void *p, int len, unsigned char *output) {
 static SHA_State sha1_cs_mac_s1, sha1_cs_mac_s2;
 static SHA_State sha1_sc_mac_s1, sha1_sc_mac_s2;
 
-static void sha1_key(SHA_State *s1, SHA_State *s2,
-                     unsigned char *key, int len) {
+static void sha1_key(SHA_State * s1, SHA_State * s2,
+                    unsigned char *key, int len)
+{
     unsigned char foo[64];
     int i;
 
     memset(foo, 0x36, 64);
     for (i = 0; i < len && i < 64; i++)
-        foo[i] ^= key[i];
+       foo[i] ^= key[i];
     SHA_Init(s1);
     SHA_Bytes(s1, foo, 64);
 
     memset(foo, 0x5C, 64);
     for (i = 0; i < len && i < 64; i++)
-        foo[i] ^= key[i];
+       foo[i] ^= key[i];
     SHA_Init(s2);
     SHA_Bytes(s2, foo, 64);
 
-    memset(foo, 0, 64);                /* burn the evidence */
+    memset(foo, 0, 64);                       /* burn the evidence */
 }
 
-static void sha1_cskey(unsigned char *key) {
+static void sha1_cskey(unsigned char *key)
+{
     sha1_key(&sha1_cs_mac_s1, &sha1_cs_mac_s2, key, 20);
 }
 
-static void sha1_sckey(unsigned char *key) {
+static void sha1_sckey(unsigned char *key)
+{
     sha1_key(&sha1_sc_mac_s1, &sha1_sc_mac_s2, key, 20);
 }
 
-static void sha1_cskey_buggy(unsigned char *key) {
+static void sha1_cskey_buggy(unsigned char *key)
+{
     sha1_key(&sha1_cs_mac_s1, &sha1_cs_mac_s2, key, 16);
 }
 
-static void sha1_sckey_buggy(unsigned char *key) {
+static void sha1_sckey_buggy(unsigned char *key)
+{
     sha1_key(&sha1_sc_mac_s1, &sha1_sc_mac_s2, key, 16);
 }
 
-static void sha1_do_hmac(SHA_State *s1, SHA_State *s2,
-                         unsigned char *blk, int len, unsigned long seq,
-                         unsigned char *hmac) {
+static void sha1_do_hmac(SHA_State * s1, SHA_State * s2,
+                        unsigned char *blk, int len, unsigned long seq,
+                        unsigned char *hmac)
+{
     SHA_State s;
     unsigned char intermediate[20];
 
-    intermediate[0] = (unsigned char)((seq >> 24) & 0xFF);
-    intermediate[1] = (unsigned char)((seq >> 16) & 0xFF);
-    intermediate[2] = (unsigned char)((seq >>  8) & 0xFF);
-    intermediate[3] = (unsigned char)((seq      ) & 0xFF);
+    intermediate[0] = (unsigned char) ((seq >> 24) & 0xFF);
+    intermediate[1] = (unsigned char) ((seq >> 16) & 0xFF);
+    intermediate[2] = (unsigned char) ((seq >> 8) & 0xFF);
+    intermediate[3] = (unsigned char) ((seq) & 0xFF);
 
-    s = *s1;                           /* structure copy */
+    s = *s1;                          /* structure copy */
     SHA_Bytes(&s, intermediate, 4);
     SHA_Bytes(&s, blk, len);
     SHA_Final(&s, intermediate);
-    s = *s2;                           /* structure copy */
+    s = *s2;                          /* structure copy */
     SHA_Bytes(&s, intermediate, 20);
     SHA_Final(&s, hmac);
 }
 
-static void sha1_generate(unsigned char *blk, int len, unsigned long seq) {
-    sha1_do_hmac(&sha1_cs_mac_s1, &sha1_cs_mac_s2, blk, len, seq, blk+len);
+static void sha1_generate(unsigned char *blk, int len, unsigned long seq)
+{
+    sha1_do_hmac(&sha1_cs_mac_s1, &sha1_cs_mac_s2, blk, len, seq,
+                blk + len);
 }
 
-static int sha1_verify(unsigned char *blk, int len, unsigned long seq) {
+static int sha1_verify(unsigned char *blk, int len, unsigned long seq)
+{
     unsigned char correct[20];
     sha1_do_hmac(&sha1_sc_mac_s1, &sha1_sc_mac_s2, blk, len, seq, correct);
-    return !memcmp(correct, blk+len, 20);
+    return !memcmp(correct, blk + len, 20);
 }
 
 const struct ssh_mac ssh_sha1 = {
index 66ab214..0124953 100644 (file)
--- a/sshzlib.c
+++ b/sshzlib.c
@@ -57,8 +57,8 @@ struct LZ77InternalContext;
 struct LZ77Context {
     struct LZ77InternalContext *ictx;
     void *userdata;
-    void (*literal)(struct LZ77Context *ctx, unsigned char c);
-    void (*match)(struct LZ77Context *ctx, int distance, int len);
+    void (*literal) (struct LZ77Context * ctx, unsigned char c);
+    void (*match) (struct LZ77Context * ctx, int distance, int len);
 };
 
 /*
@@ -74,7 +74,7 @@ static int lz77_init(struct LZ77Context *ctx);
  * instead call literal() for everything.
  */
 static void lz77_compress(struct LZ77Context *ctx,
-                          unsigned char *data, int len, int compress);
+                         unsigned char *data, int len, int compress);
 
 /*
  * Modifiable parameters.
@@ -116,15 +116,17 @@ struct LZ77InternalContext {
     int npending;
 };
 
-static int lz77_hash(unsigned char *data) {
-    return (257*data[0] + 263*data[1] + 269*data[2]) % HASHMAX;
+static int lz77_hash(unsigned char *data)
+{
+    return (257 * data[0] + 263 * data[1] + 269 * data[2]) % HASHMAX;
 }
 
-static int lz77_init(struct LZ77Context *ctx) {
+static int lz77_init(struct LZ77Context *ctx)
+{
     struct LZ77InternalContext *st;
     int i;
 
-    st = (struct LZ77InternalContext *)smalloc(sizeof(*st));
+    st = (struct LZ77InternalContext *) smalloc(sizeof(*st));
     if (!st)
        return 0;
 
@@ -142,7 +144,8 @@ static int lz77_init(struct LZ77Context *ctx) {
 }
 
 static void lz77_advance(struct LZ77InternalContext *st,
-                        unsigned char c, int hash) {
+                        unsigned char c, int hash)
+{
     int off;
 
     /*
@@ -170,13 +173,14 @@ static void lz77_advance(struct LZ77InternalContext *st,
     /*
      * Advance the window pointer.
      */
-    st->winpos = (st->winpos + 1) & (WINSIZE-1);
+    st->winpos = (st->winpos + 1) & (WINSIZE - 1);
 }
 
 #define CHARAT(k) ( (k)<0 ? st->data[(st->winpos+k)&(WINSIZE-1)] : data[k] )
 
 static void lz77_compress(struct LZ77Context *ctx,
-                          unsigned char *data, int len, int compress) {
+                         unsigned char *data, int len, int compress)
+{
     struct LZ77InternalContext *st = ctx->ictx;
     int i, hash, distance, off, nmatch, matchlen, advance;
     struct Match defermatch, matches[MAXMATCH];
@@ -192,11 +196,11 @@ static void lz77_compress(struct LZ77Context *ctx,
        if (len + st->npending - i < HASHCHARS) {
            /* Update the pending array. */
            for (j = i; j < st->npending; j++)
-               st->pending[j-i] = st->pending[j];
+               st->pending[j - i] = st->pending[j];
            break;
        }
        for (j = 0; j < HASHCHARS; j++)
-           foo[j] = (i + j < st->npending ? st->pending[i+j] :
+           foo[j] = (i + j < st->npending ? st->pending[i + j] :
                      data[i + j - st->npending]);
        lz77_advance(st, foo[0], lz77_hash(foo));
     }
@@ -205,35 +209,36 @@ static void lz77_compress(struct LZ77Context *ctx,
     defermatch.len = 0;
     while (len > 0) {
 
-        /* Don't even look for a match, if we're not compressing. */
-        if (compress && len >= HASHCHARS) {
-            /*
-             * Hash the next few characters.
-             */
-            hash = lz77_hash(data);
-
-            /*
-             * Look the hash up in the corresponding hash chain and see
-             * what we can find.
-             */
-            nmatch = 0;
-            for (off = st->hashtab[hash].first;
-                 off != INVALID; off = st->win[off].next) {
-                /* distance = 1       if off == st->winpos-1 */
-                /* distance = WINSIZE if off == st->winpos   */
-                distance = WINSIZE - (off + WINSIZE - st->winpos) % WINSIZE;
-                for (i = 0; i < HASHCHARS; i++)
-                    if (CHARAT(i) != CHARAT(i-distance))
-                        break;
-                if (i == HASHCHARS) {
-                    matches[nmatch].distance = distance;
-                    matches[nmatch].len = 3;
-                    if (++nmatch >= MAXMATCH)
-                        break;
-                }
-            }
-        } else {
-            nmatch = 0;
+       /* Don't even look for a match, if we're not compressing. */
+       if (compress && len >= HASHCHARS) {
+           /*
+            * Hash the next few characters.
+            */
+           hash = lz77_hash(data);
+
+           /*
+            * Look the hash up in the corresponding hash chain and see
+            * what we can find.
+            */
+           nmatch = 0;
+           for (off = st->hashtab[hash].first;
+                off != INVALID; off = st->win[off].next) {
+               /* distance = 1       if off == st->winpos-1 */
+               /* distance = WINSIZE if off == st->winpos   */
+               distance =
+                   WINSIZE - (off + WINSIZE - st->winpos) % WINSIZE;
+               for (i = 0; i < HASHCHARS; i++)
+                   if (CHARAT(i) != CHARAT(i - distance))
+                       break;
+               if (i == HASHCHARS) {
+                   matches[nmatch].distance = distance;
+                   matches[nmatch].len = 3;
+                   if (++nmatch >= MAXMATCH)
+                       break;
+               }
+           }
+       } else {
+           nmatch = 0;
            hash = INVALID;
        }
 
@@ -269,7 +274,7 @@ static void lz77_compress(struct LZ77Context *ctx,
                if (matches[0].len > defermatch.len + 1) {
                    /* We have a better match. Emit the deferred char,
                     * and defer this match. */
-                   ctx->literal(ctx, (unsigned char)deferchr);
+                   ctx->literal(ctx, (unsigned char) deferchr);
                    defermatch = matches[0];
                    deferchr = data[0];
                    advance = 1;
@@ -284,7 +289,7 @@ static void lz77_compress(struct LZ77Context *ctx,
                defermatch = matches[0];
                deferchr = data[0];
                advance = 1;
-           }       
+           }
        } else {
            /*
             * We found no matches. Emit the deferred match, if
@@ -342,18 +347,19 @@ struct Outbuf {
     int comp_disabled;
 };
 
-static void outbits(struct Outbuf *out, unsigned long bits, int nbits) {
+static void outbits(struct Outbuf *out, unsigned long bits, int nbits)
+{
     assert(out->noutbits + nbits <= 32);
     out->outbits |= bits << out->noutbits;
     out->noutbits += nbits;
     while (out->noutbits >= 8) {
-        if (out->outlen >= out->outsize) {
-            out->outsize = out->outlen + 64;
-            out->outbuf = srealloc(out->outbuf, out->outsize);
-        }
-        out->outbuf[out->outlen++] = (unsigned char)(out->outbits & 0xFF);
-        out->outbits >>= 8;
-        out->noutbits -= 8;
+       if (out->outlen >= out->outsize) {
+           out->outsize = out->outlen + 64;
+           out->outbuf = srealloc(out->outbuf, out->outsize);
+       }
+       out->outbuf[out->outlen++] = (unsigned char) (out->outbits & 0xFF);
+       out->outbits >>= 8;
+       out->noutbits -= 8;
     }
 }
 
@@ -398,100 +404,102 @@ typedef struct {
 } coderecord;
 
 static const coderecord lencodes[] = {
-    {257, 0, 3,3},
-    {258, 0, 4,4},
-    {259, 0, 5,5},
-    {260, 0, 6,6},
-    {261, 0, 7,7},
-    {262, 0, 8,8},
-    {263, 0, 9,9},
-    {264, 0, 10,10},
-    {265, 1, 11,12},
-    {266, 1, 13,14},
-    {267, 1, 15,16},
-    {268, 1, 17,18},
-    {269, 2, 19,22},
-    {270, 2, 23,26},
-    {271, 2, 27,30},
-    {272, 2, 31,34},
-    {273, 3, 35,42},
-    {274, 3, 43,50},
-    {275, 3, 51,58},
-    {276, 3, 59,66},
-    {277, 4, 67,82},
-    {278, 4, 83,98},
-    {279, 4, 99,114},
-    {280, 4, 115,130},
-    {281, 5, 131,162},
-    {282, 5, 163,194},
-    {283, 5, 195,226},
-    {284, 5, 227,257},
-    {285, 0, 258,258},
+    {257, 0, 3, 3},
+    {258, 0, 4, 4},
+    {259, 0, 5, 5},
+    {260, 0, 6, 6},
+    {261, 0, 7, 7},
+    {262, 0, 8, 8},
+    {263, 0, 9, 9},
+    {264, 0, 10, 10},
+    {265, 1, 11, 12},
+    {266, 1, 13, 14},
+    {267, 1, 15, 16},
+    {268, 1, 17, 18},
+    {269, 2, 19, 22},
+    {270, 2, 23, 26},
+    {271, 2, 27, 30},
+    {272, 2, 31, 34},
+    {273, 3, 35, 42},
+    {274, 3, 43, 50},
+    {275, 3, 51, 58},
+    {276, 3, 59, 66},
+    {277, 4, 67, 82},
+    {278, 4, 83, 98},
+    {279, 4, 99, 114},
+    {280, 4, 115, 130},
+    {281, 5, 131, 162},
+    {282, 5, 163, 194},
+    {283, 5, 195, 226},
+    {284, 5, 227, 257},
+    {285, 0, 258, 258},
 };
 
 static const coderecord distcodes[] = {
-    {0, 0, 1,1},
-    {1, 0, 2,2},
-    {2, 0, 3,3},
-    {3, 0, 4,4},
-    {4, 1, 5,6},
-    {5, 1, 7,8},
-    {6, 2, 9,12},
-    {7, 2, 13,16},
-    {8, 3, 17,24},
-    {9, 3, 25,32},
-    {10, 4, 33,48},
-    {11, 4, 49,64},
-    {12, 5, 65,96},
-    {13, 5, 97,128},
-    {14, 6, 129,192},
-    {15, 6, 193,256},
-    {16, 7, 257,384},
-    {17, 7, 385,512},
-    {18, 8, 513,768},
-    {19, 8, 769,1024},
-    {20, 9, 1025,1536},
-    {21, 9, 1537,2048},
-    {22, 10, 2049,3072},
-    {23, 10, 3073,4096},
-    {24, 11, 4097,6144},
-    {25, 11, 6145,8192},
-    {26, 12, 8193,12288},
-    {27, 12, 12289,16384},
-    {28, 13, 16385,24576},
-    {29, 13, 24577,32768},
+    {0, 0, 1, 1},
+    {1, 0, 2, 2},
+    {2, 0, 3, 3},
+    {3, 0, 4, 4},
+    {4, 1, 5, 6},
+    {5, 1, 7, 8},
+    {6, 2, 9, 12},
+    {7, 2, 13, 16},
+    {8, 3, 17, 24},
+    {9, 3, 25, 32},
+    {10, 4, 33, 48},
+    {11, 4, 49, 64},
+    {12, 5, 65, 96},
+    {13, 5, 97, 128},
+    {14, 6, 129, 192},
+    {15, 6, 193, 256},
+    {16, 7, 257, 384},
+    {17, 7, 385, 512},
+    {18, 8, 513, 768},
+    {19, 8, 769, 1024},
+    {20, 9, 1025, 1536},
+    {21, 9, 1537, 2048},
+    {22, 10, 2049, 3072},
+    {23, 10, 3073, 4096},
+    {24, 11, 4097, 6144},
+    {25, 11, 6145, 8192},
+    {26, 12, 8193, 12288},
+    {27, 12, 12289, 16384},
+    {28, 13, 16385, 24576},
+    {29, 13, 24577, 32768},
 };
 
-static void zlib_literal(struct LZ77Context *ectx, unsigned char c) {
-    struct Outbuf *out = (struct Outbuf *)ectx->userdata;
+static void zlib_literal(struct LZ77Context *ectx, unsigned char c)
+{
+    struct Outbuf *out = (struct Outbuf *) ectx->userdata;
 
     if (out->comp_disabled) {
-        /*
-         * We're in an uncompressed block, so just output the byte.
-         */
-        outbits(out, c, 8);
-        return;
+       /*
+        * We're in an uncompressed block, so just output the byte.
+        */
+       outbits(out, c, 8);
+       return;
     }
 
     if (c <= 143) {
-        /* 0 through 143 are 8 bits long starting at 00110000. */
-        outbits(out, mirrorbytes[0x30 + c], 8);
+       /* 0 through 143 are 8 bits long starting at 00110000. */
+       outbits(out, mirrorbytes[0x30 + c], 8);
     } else {
-        /* 144 through 255 are 9 bits long starting at 110010000. */
-        outbits(out, 1 + 2*mirrorbytes[0x90 - 144 + c], 9);
+       /* 144 through 255 are 9 bits long starting at 110010000. */
+       outbits(out, 1 + 2 * mirrorbytes[0x90 - 144 + c], 9);
     }
 }
 
-static void zlib_match(struct LZ77Context *ectx, int distance, int len) {
+static void zlib_match(struct LZ77Context *ectx, int distance, int len)
+{
     const coderecord *d, *l;
     int i, j, k;
-    struct Outbuf *out = (struct Outbuf *)ectx->userdata;
+    struct Outbuf *out = (struct Outbuf *) ectx->userdata;
 
     assert(!out->comp_disabled);
 
     while (len > 0) {
-        int thislen;
-       
+       int thislen;
+
        /*
         * We can transmit matches of lengths 3 through 258
         * inclusive. So if len exceeds 258, we must transmit in
@@ -502,74 +510,77 @@ static void zlib_match(struct LZ77Context *ectx, int distance, int len) {
         * len <= 258, we can just transmit len. But if len == 259
         * or 260, we must transmit len-3.
         */
-       thislen = (len > 260 ? 258 : len <= 258 ? len : len-3);
-        len -= thislen;
-
-        /*
-         * Binary-search to find which length code we're
-         * transmitting.
-         */
-        i = -1; j = sizeof(lencodes)/sizeof(*lencodes);
-        while (j - i >= 2) {
-            k = (j+i)/2;
-            if (thislen < lencodes[k].min)
-                j = k;
-            else if (thislen > lencodes[k].max)
-                i = k;
-            else {
-                l = &lencodes[k];
-                break;                 /* found it! */
-            }
-        }
-
-        /*
-         * Transmit the length code. 256-279 are seven bits
-         * starting at 0000000; 280-287 are eight bits starting at
-         * 11000000.
-         */
-        if (l->code <= 279) {
-            outbits(out, mirrorbytes[(l->code-256)*2], 7);
-        } else {
-            outbits(out, mirrorbytes[0xc0 - 280 + l->code], 8);
-        }
-
-        /*
-         * Transmit the extra bits.
-         */
-        if (l->extrabits)
-            outbits(out, thislen - l->min, l->extrabits);
-
-        /*
-         * Binary-search to find which distance code we're
-         * transmitting.
-         */
-        i = -1; j = sizeof(distcodes)/sizeof(*distcodes);
-        while (j - i >= 2) {
-            k = (j+i)/2;
-            if (distance < distcodes[k].min)
-                j = k;
-            else if (distance > distcodes[k].max)
-                i = k;
-            else {
-                d = &distcodes[k];
-                break;                 /* found it! */
-            }
-        }
-
-        /*
-         * Transmit the distance code. Five bits starting at 00000.
-         */
-        outbits(out, mirrorbytes[d->code*8], 5);
-
-        /*
-         * Transmit the extra bits.
-         */
-        if (d->extrabits)
-            outbits(out, distance - d->min, d->extrabits);
+       thislen = (len > 260 ? 258 : len <= 258 ? len : len - 3);
+       len -= thislen;
+
+       /*
+        * Binary-search to find which length code we're
+        * transmitting.
+        */
+       i = -1;
+       j = sizeof(lencodes) / sizeof(*lencodes);
+       while (j - i >= 2) {
+           k = (j + i) / 2;
+           if (thislen < lencodes[k].min)
+               j = k;
+           else if (thislen > lencodes[k].max)
+               i = k;
+           else {
+               l = &lencodes[k];
+               break;                 /* found it! */
+           }
+       }
+
+       /*
+        * Transmit the length code. 256-279 are seven bits
+        * starting at 0000000; 280-287 are eight bits starting at
+        * 11000000.
+        */
+       if (l->code <= 279) {
+           outbits(out, mirrorbytes[(l->code - 256) * 2], 7);
+       } else {
+           outbits(out, mirrorbytes[0xc0 - 280 + l->code], 8);
+       }
+
+       /*
+        * Transmit the extra bits.
+        */
+       if (l->extrabits)
+           outbits(out, thislen - l->min, l->extrabits);
+
+       /*
+        * Binary-search to find which distance code we're
+        * transmitting.
+        */
+       i = -1;
+       j = sizeof(distcodes) / sizeof(*distcodes);
+       while (j - i >= 2) {
+           k = (j + i) / 2;
+           if (distance < distcodes[k].min)
+               j = k;
+           else if (distance > distcodes[k].max)
+               i = k;
+           else {
+               d = &distcodes[k];
+               break;                 /* found it! */
+           }
+       }
+
+       /*
+        * Transmit the distance code. Five bits starting at 00000.
+        */
+       outbits(out, mirrorbytes[d->code * 8], 5);
+
+       /*
+        * Transmit the extra bits.
+        */
+       if (d->extrabits)
+           outbits(out, distance - d->min, d->extrabits);
     }
 }
 
-void zlib_compress_init(void) {
+void zlib_compress_init(void)
+{
     struct Outbuf *out;
 
     lz77_init(&ectx);
@@ -591,8 +602,9 @@ void zlib_compress_init(void) {
  * length adjustment (which is only valid for packets < 65536
  * bytes, but that seems reasonable enough).
  */
-int zlib_disable_compression(void) {
-    struct Outbuf *out = (struct Outbuf *)ectx.userdata;
+int zlib_disable_compression(void)
+{
+    struct Outbuf *out = (struct Outbuf *) ectx.userdata;
     int n;
 
     out->comp_disabled = TRUE;
@@ -605,15 +617,15 @@ int zlib_disable_compression(void) {
      * a byte boundary, this is certain).
      */
     if (out->firstblock) {
-        n = 3;
+       n = 3;
     } else {
-        /*
-         * Otherwise, we will output seven bits to close the
-         * previous static block, and _then_ three bits to begin an
-         * uncompressed block, and then flush the current byte.
-         * This may cost two bytes or three, depending on noutbits.
-         */
-        n += (out->noutbits + 10) / 8;
+       /*
+        * Otherwise, we will output seven bits to close the
+        * previous static block, and _then_ three bits to begin an
+        * uncompressed block, and then flush the current byte.
+        * This may cost two bytes or three, depending on noutbits.
+        */
+       n += (out->noutbits + 10) / 8;
     }
 
     /*
@@ -626,8 +638,9 @@ int zlib_disable_compression(void) {
 }
 
 int zlib_compress_block(unsigned char *block, int len,
-                       unsigned char **outblock, int *outlen) {
-    struct Outbuf *out = (struct Outbuf *)ectx.userdata;
+                       unsigned char **outblock, int *outlen)
+{
+    struct Outbuf *out = (struct Outbuf *) ectx.userdata;
     int in_block;
 
     out->outbuf = NULL;
@@ -639,100 +652,100 @@ int zlib_compress_block(unsigned char *block, int len,
      * algorithm.)
      */
     if (out->firstblock) {
-        outbits(out, 0x9C78, 16);
-        out->firstblock = 0;
+       outbits(out, 0x9C78, 16);
+       out->firstblock = 0;
 
-        in_block = FALSE;
+       in_block = FALSE;
     }
 
     if (out->comp_disabled) {
-        if (in_block)
-            outbits(out, 0, 7);                       /* close static block */
-
-        while (len > 0) {
-            int blen = (len < 65535 ? len : 65535);
-
-            /*
-             * Start a Deflate (RFC1951) uncompressed block. We
-             * transmit a zero bit (BFINAL=0), followed by a zero
-             * bit and a one bit (BTYPE=00). Of course these are in
-             * the wrong order (00 0).
-             */
-            outbits(out, 0, 3);
-
-            /*
-             * Output zero bits to align to a byte boundary.
-             */
-            if (out->noutbits)
-                outbits(out, 0, 8 - out->noutbits);
-
-            /*
-             * Output the block length, and then its one's
-             * complement. They're little-endian, so all we need to
-             * do is pass them straight to outbits() with bit count
-             * 16.
-             */
-            outbits(out, blen, 16);
-            outbits(out, blen ^ 0xFFFF, 16);
-
-            /*
-             * Do the `compression': we need to pass the data to
-             * lz77_compress so that it will be taken into account
-             * for subsequent (distance,length) pairs. But
-             * lz77_compress is passed FALSE, which means it won't
-             * actually find (or even look for) any matches; so
-             * every character will be passed straight to
-             * zlib_literal which will spot out->comp_disabled and
-             * emit in the uncompressed format.
-             */
-            lz77_compress(&ectx, block, blen, FALSE);
-
-            len -= blen;
-            block += blen;
-        }
-        outbits(out, 2, 3);                   /* open new block */
+       if (in_block)
+           outbits(out, 0, 7);        /* close static block */
+
+       while (len > 0) {
+           int blen = (len < 65535 ? len : 65535);
+
+           /*
+            * Start a Deflate (RFC1951) uncompressed block. We
+            * transmit a zero bit (BFINAL=0), followed by a zero
+            * bit and a one bit (BTYPE=00). Of course these are in
+            * the wrong order (00 0).
+            */
+           outbits(out, 0, 3);
+
+           /*
+            * Output zero bits to align to a byte boundary.
+            */
+           if (out->noutbits)
+               outbits(out, 0, 8 - out->noutbits);
+
+           /*
+            * Output the block length, and then its one's
+            * complement. They're little-endian, so all we need to
+            * do is pass them straight to outbits() with bit count
+            * 16.
+            */
+           outbits(out, blen, 16);
+           outbits(out, blen ^ 0xFFFF, 16);
+
+           /*
+            * Do the `compression': we need to pass the data to
+            * lz77_compress so that it will be taken into account
+            * for subsequent (distance,length) pairs. But
+            * lz77_compress is passed FALSE, which means it won't
+            * actually find (or even look for) any matches; so
+            * every character will be passed straight to
+            * zlib_literal which will spot out->comp_disabled and
+            * emit in the uncompressed format.
+            */
+           lz77_compress(&ectx, block, blen, FALSE);
+
+           len -= blen;
+           block += blen;
+       }
+       outbits(out, 2, 3);            /* open new block */
     } else {
-        if (!in_block) {
-            /*
-             * Start a Deflate (RFC1951) fixed-trees block. We
-             * transmit a zero bit (BFINAL=0), followed by a zero
-             * bit and a one bit (BTYPE=01). Of course these are in
-             * the wrong order (01 0).
-             */
-            outbits(out, 2, 3);
-        }
-
-        /*
-         * Do the compression.
-         */
-        lz77_compress(&ectx, block, len, TRUE);
-
-        /*
-         * End the block (by transmitting code 256, which is
-         * 0000000 in fixed-tree mode), and transmit some empty
-         * blocks to ensure we have emitted the byte containing the
-         * last piece of genuine data. There are three ways we can
-         * do this:
-         *
-         *  - Minimal flush. Output end-of-block and then open a
-         *    new static block. This takes 9 bits, which is
-         *    guaranteed to flush out the last genuine code in the
-         *    closed block; but allegedly zlib can't handle it.
-         *
-         *  - Zlib partial flush. Output EOB, open and close an
-         *    empty static block, and _then_ open the new block.
-         *    This is the best zlib can handle.
-         *
-         *  - Zlib sync flush. Output EOB, then an empty
-         *    _uncompressed_ block (000, then sync to byte
-         *    boundary, then send bytes 00 00 FF FF). Then open the
-         *    new block.
-         *
-         * For the moment, we will use Zlib partial flush.
-         */
-        outbits(out, 0, 7);                   /* close block */
-        outbits(out, 2, 3+7);         /* empty static block */
-        outbits(out, 2, 3);                   /* open new block */
+       if (!in_block) {
+           /*
+            * Start a Deflate (RFC1951) fixed-trees block. We
+            * transmit a zero bit (BFINAL=0), followed by a zero
+            * bit and a one bit (BTYPE=01). Of course these are in
+            * the wrong order (01 0).
+            */
+           outbits(out, 2, 3);
+       }
+
+       /*
+        * Do the compression.
+        */
+       lz77_compress(&ectx, block, len, TRUE);
+
+       /*
+        * End the block (by transmitting code 256, which is
+        * 0000000 in fixed-tree mode), and transmit some empty
+        * blocks to ensure we have emitted the byte containing the
+        * last piece of genuine data. There are three ways we can
+        * do this:
+        *
+        *  - Minimal flush. Output end-of-block and then open a
+        *    new static block. This takes 9 bits, which is
+        *    guaranteed to flush out the last genuine code in the
+        *    closed block; but allegedly zlib can't handle it.
+        *
+        *  - Zlib partial flush. Output EOB, open and close an
+        *    empty static block, and _then_ open the new block.
+        *    This is the best zlib can handle.
+        *
+        *  - Zlib sync flush. Output EOB, then an empty
+        *    _uncompressed_ block (000, then sync to byte
+        *    boundary, then send bytes 00 00 FF FF). Then open the
+        *    new block.
+        *
+        * For the moment, we will use Zlib partial flush.
+        */
+       outbits(out, 0, 7);            /* close block */
+       outbits(out, 2, 3 + 7);        /* empty static block */
+       outbits(out, 2, 3);            /* open new block */
     }
 
     out->comp_disabled = FALSE;
@@ -766,7 +779,7 @@ struct zlib_tableentry {
 };
 
 struct zlib_table {
-    int mask;                          /* mask applied to input bit stream */
+    int mask;                         /* mask applied to input bit stream */
     struct zlib_tableentry *table;
 };
 
@@ -779,8 +792,9 @@ struct zlib_table {
  * recurse to build subtables.
  */
 static struct zlib_table *zlib_mkonetab(int *codes, unsigned char *lengths,
-                                        int nsyms,
-                                        int pfx, int pfxbits, int bits) {
+                                       int nsyms,
+                                       int pfx, int pfxbits, int bits)
+{
     struct zlib_table *tab = smalloc(sizeof(struct zlib_table));
     int pfxmask = (1 << pfxbits) - 1;
     int nbits, i, j, code;
@@ -789,34 +803,34 @@ static struct zlib_table *zlib_mkonetab(int *codes, unsigned char *lengths,
     tab->mask = (1 << bits) - 1;
 
     for (code = 0; code <= tab->mask; code++) {
-        tab->table[code].code = -1;
-        tab->table[code].nbits = 0;
-        tab->table[code].nexttable = NULL;
+       tab->table[code].code = -1;
+       tab->table[code].nbits = 0;
+       tab->table[code].nexttable = NULL;
     }
 
     for (i = 0; i < nsyms; i++) {
-        if (lengths[i] <= pfxbits || (codes[i] & pfxmask) != pfx)
-            continue;
-        code = (codes[i] >> pfxbits) & tab->mask;
-        for (j = code; j <= tab->mask; j += 1 << (lengths[i]-pfxbits)) {
-            tab->table[j].code = i;
-            nbits = lengths[i] - pfxbits;
-            if (tab->table[j].nbits < nbits)
-                tab->table[j].nbits = nbits;
-        }
+       if (lengths[i] <= pfxbits || (codes[i] & pfxmask) != pfx)
+           continue;
+       code = (codes[i] >> pfxbits) & tab->mask;
+       for (j = code; j <= tab->mask; j += 1 << (lengths[i] - pfxbits)) {
+           tab->table[j].code = i;
+           nbits = lengths[i] - pfxbits;
+           if (tab->table[j].nbits < nbits)
+               tab->table[j].nbits = nbits;
+       }
     }
     for (code = 0; code <= tab->mask; code++) {
-        if (tab->table[code].nbits <= bits)
-            continue;
-        /* Generate a subtable. */
-        tab->table[code].code = -1;
-        nbits = tab->table[code].nbits - bits;
-        if (nbits > 7)
-            nbits = 7;
-        tab->table[code].nbits = bits;
-        tab->table[code].nexttable = zlib_mkonetab(codes, lengths, nsyms,
-                                                   pfx | (code << pfxbits),
-                                                   pfxbits + bits, nbits);
+       if (tab->table[code].nbits <= bits)
+           continue;
+       /* Generate a subtable. */
+       tab->table[code].code = -1;
+       nbits = tab->table[code].nbits - bits;
+       if (nbits > 7)
+           nbits = 7;
+       tab->table[code].nbits = bits;
+       tab->table[code].nexttable = zlib_mkonetab(codes, lengths, nsyms,
+                                                  pfx | (code << pfxbits),
+                                                  pfxbits + bits, nbits);
     }
 
     return tab;
@@ -825,34 +839,37 @@ static struct zlib_table *zlib_mkonetab(int *codes, unsigned char *lengths,
 /*
  * Build a decode table, given a set of Huffman tree lengths.
  */
-static struct zlib_table *zlib_mktable(unsigned char *lengths, int nlengths) {
+static struct zlib_table *zlib_mktable(unsigned char *lengths,
+                                      int nlengths)
+{
     int count[MAXCODELEN], startcode[MAXCODELEN], codes[MAXSYMS];
     int code, maxlen;
     int i, j;
 
     /* Count the codes of each length. */
     maxlen = 0;
-    for (i = 1; i < MAXCODELEN; i++) count[i] = 0;
+    for (i = 1; i < MAXCODELEN; i++)
+       count[i] = 0;
     for (i = 0; i < nlengths; i++) {
-        count[lengths[i]]++;
-        if (maxlen < lengths[i])
-            maxlen = lengths[i];
+       count[lengths[i]]++;
+       if (maxlen < lengths[i])
+           maxlen = lengths[i];
     }
     /* Determine the starting code for each length block. */
     code = 0;
     for (i = 1; i < MAXCODELEN; i++) {
-        startcode[i] = code;
-        code += count[i];
-        code <<= 1;
+       startcode[i] = code;
+       code += count[i];
+       code <<= 1;
     }
     /* Determine the code for each symbol. Mirrored, of course. */
     for (i = 0; i < nlengths; i++) {
-        code = startcode[lengths[i]]++;
-        codes[i] = 0;
-        for (j = 0; j < lengths[i]; j++) {
-            codes[i] = (codes[i] << 1) | (code & 1);
-            code >>= 1;
-        }
+       code = startcode[lengths[i]]++;
+       codes[i] = 0;
+       for (j = 0; j < lengths[i]; j++) {
+           codes[i] = (codes[i] << 1) | (code & 1);
+           code >>= 1;
+       }
     }
 
     /*
@@ -860,10 +877,11 @@ static struct zlib_table *zlib_mktable(unsigned char *lengths, int nlengths) {
      * table.
      */
     return zlib_mkonetab(codes, lengths, nlengths, 0, 0,
-                         maxlen < 9 ? maxlen : 9);
+                        maxlen < 9 ? maxlen : 9);
 }
 
-static int zlib_freetable(struct zlib_table ** ztab) {
+static int zlib_freetable(struct zlib_table **ztab)
+{
     struct zlib_table *tab;
     int code;
 
@@ -885,22 +903,23 @@ static int zlib_freetable(struct zlib_table ** ztab) {
     sfree(tab);
     *ztab = NULL;
 
-    return(0);
+    return (0);
 }
 
 static struct zlib_decompress_ctx {
     struct zlib_table *staticlentable, *staticdisttable;
     struct zlib_table *currlentable, *currdisttable, *lenlentable;
     enum {
-        START, OUTSIDEBLK,
-        TREES_HDR, TREES_LENLEN, TREES_LEN, TREES_LENREP,
-        INBLK, GOTLENSYM, GOTLEN, GOTDISTSYM,
-        UNCOMP_LEN, UNCOMP_NLEN, UNCOMP_DATA
+       START, OUTSIDEBLK,
+       TREES_HDR, TREES_LENLEN, TREES_LEN, TREES_LENREP,
+       INBLK, GOTLENSYM, GOTLEN, GOTDISTSYM,
+       UNCOMP_LEN, UNCOMP_NLEN, UNCOMP_DATA
     } state;
-    int sym, hlit, hdist, hclen, lenptr, lenextrabits, lenaddon, len, lenrep;
+    int sym, hlit, hdist, hclen, lenptr, lenextrabits, lenaddon, len,
+       lenrep;
     int uncomplen;
     unsigned char lenlen[19];
-    unsigned char lengths[286+32];
+    unsigned char lengths[286 + 32];
     unsigned long bits;
     int nbits;
     unsigned char window[WINSIZE];
@@ -909,45 +928,49 @@ static struct zlib_decompress_ctx {
     int outlen, outsize;
 } dctx;
 
-void zlib_decompress_init(void) {
+void zlib_decompress_init(void)
+{
     unsigned char lengths[288];
     memset(lengths, 8, 144);
-    memset(lengths+144, 9, 256-144);
-    memset(lengths+256, 7, 280-256);
-    memset(lengths+280, 8, 288-280);
+    memset(lengths + 144, 9, 256 - 144);
+    memset(lengths + 256, 7, 280 - 256);
+    memset(lengths + 280, 8, 288 - 280);
     dctx.staticlentable = zlib_mktable(lengths, 288);
     memset(lengths, 5, 32);
     dctx.staticdisttable = zlib_mktable(lengths, 32);
-    dctx.state = START;                /* even before header */
+    dctx.state = START;                       /* even before header */
     dctx.currlentable = dctx.currdisttable = dctx.lenlentable = NULL;
     dctx.bits = 0;
     dctx.nbits = 0;
     logevent("Initialised zlib (RFC1950) decompression");
 }
 
-int zlib_huflookup(unsigned long *bitsp, int *nbitsp, struct zlib_table *tab) {
+int zlib_huflookup(unsigned long *bitsp, int *nbitsp,
+                  struct zlib_table *tab)
+{
     unsigned long bits = *bitsp;
     int nbits = *nbitsp;
     while (1) {
-        struct zlib_tableentry *ent;
-        ent = &tab->table[bits & tab->mask];
-        if (ent->nbits > nbits)
-            return -1;                 /* not enough data */
-        bits >>= ent->nbits;
-        nbits -= ent->nbits;
-        if (ent->code == -1)
-            tab = ent->nexttable;
-        else {
-            *bitsp = bits;
-            *nbitsp = nbits;
-            return ent->code;
-        }
+       struct zlib_tableentry *ent;
+       ent = &tab->table[bits & tab->mask];
+       if (ent->nbits > nbits)
+           return -1;                 /* not enough data */
+       bits >>= ent->nbits;
+       nbits -= ent->nbits;
+       if (ent->code == -1)
+           tab = ent->nexttable;
+       else {
+           *bitsp = bits;
+           *nbitsp = nbits;
+           return ent->code;
+       }
     }
 }
 
-static void zlib_emit_char(int c) {
+static void zlib_emit_char(int c)
+{
     dctx.window[dctx.winpos] = c;
-    dctx.winpos = (dctx.winpos + 1) & (WINSIZE-1);
+    dctx.winpos = (dctx.winpos + 1) & (WINSIZE - 1);
     if (dctx.outlen >= dctx.outsize) {
        dctx.outsize = dctx.outlen + 512;
        dctx.outblk = srealloc(dctx.outblk, dctx.outsize);
@@ -958,152 +981,164 @@ static void zlib_emit_char(int c) {
 #define EATBITS(n) ( dctx.nbits -= (n), dctx.bits >>= (n) )
 
 int zlib_decompress_block(unsigned char *block, int len,
-                         unsigned char **outblock, int *outlen) {
+                         unsigned char **outblock, int *outlen)
+{
     const coderecord *rec;
     int code, blktype, rep, dist, nlen;
     static const unsigned char lenlenmap[] = {
-        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+       16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
     };
 
     dctx.outblk = NULL;
     dctx.outsize = dctx.outlen = 0;
 
     while (len > 0 || dctx.nbits > 0) {
-        while (dctx.nbits < 24 && len > 0) {
-            dctx.bits |= (*block++) << dctx.nbits;
-            dctx.nbits += 8;
-            len--;
-        }
-        switch (dctx.state) {
-          case START:
-            /* Expect 16-bit zlib header, which we'll dishonourably ignore. */
-            if (dctx.nbits < 16)
-                goto finished;        /* done all we can */
-            EATBITS(16);
-            dctx.state = OUTSIDEBLK;
-            break;
-          case OUTSIDEBLK:
-            /* Expect 3-bit block header. */
-            if (dctx.nbits < 3)
-                goto finished;        /* done all we can */
-            EATBITS(1);
-            blktype = dctx.bits & 3;
-            EATBITS(2);
-            if (blktype == 0) {
+       while (dctx.nbits < 24 && len > 0) {
+           dctx.bits |= (*block++) << dctx.nbits;
+           dctx.nbits += 8;
+           len--;
+       }
+       switch (dctx.state) {
+         case START:
+           /* Expect 16-bit zlib header, which we'll dishonourably ignore. */
+           if (dctx.nbits < 16)
+               goto finished;         /* done all we can */
+           EATBITS(16);
+           dctx.state = OUTSIDEBLK;
+           break;
+         case OUTSIDEBLK:
+           /* Expect 3-bit block header. */
+           if (dctx.nbits < 3)
+               goto finished;         /* done all we can */
+           EATBITS(1);
+           blktype = dctx.bits & 3;
+           EATBITS(2);
+           if (blktype == 0) {
                int to_eat = dctx.nbits & 7;
-                dctx.state = UNCOMP_LEN;
+               dctx.state = UNCOMP_LEN;
                EATBITS(to_eat);       /* align to byte boundary */
-            } else if (blktype == 1) {
-                dctx.currlentable = dctx.staticlentable;
-                dctx.currdisttable = dctx.staticdisttable;
-                dctx.state = INBLK;
-            } else if (blktype == 2) {
-                dctx.state = TREES_HDR;
-            }
-            break;
-          case TREES_HDR:
-            /*
-             * Dynamic block header. Five bits of HLIT, five of
-             * HDIST, four of HCLEN.
-             */
-            if (dctx.nbits < 5+5+4)
-                goto finished;        /* done all we can */
-            dctx.hlit = 257 + (dctx.bits & 31); EATBITS(5);
-            dctx.hdist = 1 + (dctx.bits & 31); EATBITS(5);
-            dctx.hclen = 4 + (dctx.bits & 15); EATBITS(4);
-            dctx.lenptr = 0;
-            dctx.state = TREES_LENLEN;
-            memset(dctx.lenlen, 0, sizeof(dctx.lenlen));
-            break;
-          case TREES_LENLEN:
-            if (dctx.nbits < 3)
-                goto finished;
-            while (dctx.lenptr < dctx.hclen && dctx.nbits >= 3) {
-                dctx.lenlen[lenlenmap[dctx.lenptr++]] =
-                   (unsigned char)(dctx.bits & 7);
-                EATBITS(3);
-            }
-            if (dctx.lenptr == dctx.hclen) {
-                dctx.lenlentable = zlib_mktable(dctx.lenlen, 19);
-                dctx.state = TREES_LEN;
-                dctx.lenptr = 0;
-            }
-            break;
-          case TREES_LEN:
-            if (dctx.lenptr >= dctx.hlit+dctx.hdist) {
-                dctx.currlentable = zlib_mktable(dctx.lengths, dctx.hlit);
-                dctx.currdisttable = zlib_mktable(dctx.lengths + dctx.hlit,
-                                                  dctx.hdist);
+           } else if (blktype == 1) {
+               dctx.currlentable = dctx.staticlentable;
+               dctx.currdisttable = dctx.staticdisttable;
+               dctx.state = INBLK;
+           } else if (blktype == 2) {
+               dctx.state = TREES_HDR;
+           }
+           break;
+         case TREES_HDR:
+           /*
+            * Dynamic block header. Five bits of HLIT, five of
+            * HDIST, four of HCLEN.
+            */
+           if (dctx.nbits < 5 + 5 + 4)
+               goto finished;         /* done all we can */
+           dctx.hlit = 257 + (dctx.bits & 31);
+           EATBITS(5);
+           dctx.hdist = 1 + (dctx.bits & 31);
+           EATBITS(5);
+           dctx.hclen = 4 + (dctx.bits & 15);
+           EATBITS(4);
+           dctx.lenptr = 0;
+           dctx.state = TREES_LENLEN;
+           memset(dctx.lenlen, 0, sizeof(dctx.lenlen));
+           break;
+         case TREES_LENLEN:
+           if (dctx.nbits < 3)
+               goto finished;
+           while (dctx.lenptr < dctx.hclen && dctx.nbits >= 3) {
+               dctx.lenlen[lenlenmap[dctx.lenptr++]] =
+                   (unsigned char) (dctx.bits & 7);
+               EATBITS(3);
+           }
+           if (dctx.lenptr == dctx.hclen) {
+               dctx.lenlentable = zlib_mktable(dctx.lenlen, 19);
+               dctx.state = TREES_LEN;
+               dctx.lenptr = 0;
+           }
+           break;
+         case TREES_LEN:
+           if (dctx.lenptr >= dctx.hlit + dctx.hdist) {
+               dctx.currlentable = zlib_mktable(dctx.lengths, dctx.hlit);
+               dctx.currdisttable = zlib_mktable(dctx.lengths + dctx.hlit,
+                                                 dctx.hdist);
                zlib_freetable(&dctx.lenlentable);
                dctx.state = INBLK;
-                break;
-            }
-            code = zlib_huflookup(&dctx.bits, &dctx.nbits, dctx.lenlentable);
-            if (code == -1)
-                goto finished;
-            if (code < 16)
-                dctx.lengths[dctx.lenptr++] = code;
-            else {
-                dctx.lenextrabits = (code == 16 ? 2 : code == 17 ? 3 : 7);
-                dctx.lenaddon = (code == 18 ? 11 : 3);
-                dctx.lenrep = (code == 16 && dctx.lenptr > 0 ?
-                               dctx.lengths[dctx.lenptr-1] : 0);
-                dctx.state = TREES_LENREP;
-            }
-            break;
-          case TREES_LENREP:
-            if (dctx.nbits < dctx.lenextrabits)
-                goto finished;
-            rep = dctx.lenaddon + (dctx.bits & ((1<<dctx.lenextrabits)-1));
-            EATBITS(dctx.lenextrabits);
-            while (rep > 0 && dctx.lenptr < dctx.hlit+dctx.hdist) {
-                dctx.lengths[dctx.lenptr] = dctx.lenrep;
-                dctx.lenptr++;
-                rep--;
-            }
-            dctx.state = TREES_LEN;
-            break;
-          case INBLK:
-            code = zlib_huflookup(&dctx.bits, &dctx.nbits, dctx.currlentable);
-            if (code == -1)
-                goto finished;
-            if (code < 256)
+               break;
+           }
+           code =
+               zlib_huflookup(&dctx.bits, &dctx.nbits, dctx.lenlentable);
+           if (code == -1)
+               goto finished;
+           if (code < 16)
+               dctx.lengths[dctx.lenptr++] = code;
+           else {
+               dctx.lenextrabits = (code == 16 ? 2 : code == 17 ? 3 : 7);
+               dctx.lenaddon = (code == 18 ? 11 : 3);
+               dctx.lenrep = (code == 16 && dctx.lenptr > 0 ?
+                              dctx.lengths[dctx.lenptr - 1] : 0);
+               dctx.state = TREES_LENREP;
+           }
+           break;
+         case TREES_LENREP:
+           if (dctx.nbits < dctx.lenextrabits)
+               goto finished;
+           rep =
+               dctx.lenaddon +
+               (dctx.bits & ((1 << dctx.lenextrabits) - 1));
+           EATBITS(dctx.lenextrabits);
+           while (rep > 0 && dctx.lenptr < dctx.hlit + dctx.hdist) {
+               dctx.lengths[dctx.lenptr] = dctx.lenrep;
+               dctx.lenptr++;
+               rep--;
+           }
+           dctx.state = TREES_LEN;
+           break;
+         case INBLK:
+           code =
+               zlib_huflookup(&dctx.bits, &dctx.nbits, dctx.currlentable);
+           if (code == -1)
+               goto finished;
+           if (code < 256)
                zlib_emit_char(code);
-            else if (code == 256) {
-                dctx.state = OUTSIDEBLK;
+           else if (code == 256) {
+               dctx.state = OUTSIDEBLK;
                if (dctx.currlentable != dctx.staticlentable)
                    zlib_freetable(&dctx.currlentable);
                if (dctx.currdisttable != dctx.staticdisttable)
                    zlib_freetable(&dctx.currdisttable);
-            } else if (code < 286) {   /* static tree can give >285; ignore */
-                dctx.state = GOTLENSYM;
-                dctx.sym = code;
-            }
-            break;
-          case GOTLENSYM:
-            rec = &lencodes[dctx.sym - 257];
-            if (dctx.nbits < rec->extrabits)
-                goto finished;
-            dctx.len = rec->min + (dctx.bits & ((1<<rec->extrabits)-1));
-            EATBITS(rec->extrabits);
-            dctx.state = GOTLEN;
-            break;
-          case GOTLEN:
-            code = zlib_huflookup(&dctx.bits, &dctx.nbits, dctx.currdisttable);
-            if (code == -1)
-                goto finished;
-            dctx.state = GOTDISTSYM;
-            dctx.sym = code;
-            break;
-          case GOTDISTSYM:
-            rec = &distcodes[dctx.sym];
-            if (dctx.nbits < rec->extrabits)
-                goto finished;
-            dist = rec->min + (dctx.bits & ((1<<rec->extrabits)-1));
-            EATBITS(rec->extrabits);
-            dctx.state = INBLK;
+           } else if (code < 286) {   /* static tree can give >285; ignore */
+               dctx.state = GOTLENSYM;
+               dctx.sym = code;
+           }
+           break;
+         case GOTLENSYM:
+           rec = &lencodes[dctx.sym - 257];
+           if (dctx.nbits < rec->extrabits)
+               goto finished;
+           dctx.len =
+               rec->min + (dctx.bits & ((1 << rec->extrabits) - 1));
+           EATBITS(rec->extrabits);
+           dctx.state = GOTLEN;
+           break;
+         case GOTLEN:
+           code =
+               zlib_huflookup(&dctx.bits, &dctx.nbits,
+                              dctx.currdisttable);
+           if (code == -1)
+               goto finished;
+           dctx.state = GOTDISTSYM;
+           dctx.sym = code;
+           break;
+         case GOTDISTSYM:
+           rec = &distcodes[dctx.sym];
+           if (dctx.nbits < rec->extrabits)
+               goto finished;
+           dist = rec->min + (dctx.bits & ((1 << rec->extrabits) - 1));
+           EATBITS(rec->extrabits);
+           dctx.state = INBLK;
            while (dctx.len--)
-               zlib_emit_char(dctx.window[(dctx.winpos-dist) & (WINSIZE-1)]);
+               zlib_emit_char(dctx.window[(dctx.winpos - dist) &
+                                          (WINSIZE - 1)]);
            break;
          case UNCOMP_LEN:
            /*
@@ -1133,12 +1168,12 @@ int zlib_decompress_block(unsigned char *block, int len,
            zlib_emit_char(dctx.bits & 0xFF);
            EATBITS(8);
            if (--dctx.uncomplen == 0)
-               dctx.state = OUTSIDEBLK;   /* end of uncompressed block */
+               dctx.state = OUTSIDEBLK;        /* end of uncompressed block */
            break;
-        }
+       }
     }
 
-    finished:
+  finished:
     *outblock = dctx.outblk;
     *outlen = dctx.outlen;
 
index 43f22d3..779712d 100644 (file)
--- a/storage.h
+++ b/storage.h
@@ -79,7 +79,7 @@ void store_host_key(char *hostname, int port, char *keytype, char *key);
  * Functions to access PuTTY's random number seed file.
  */
 
-typedef void (*noise_consumer_t)(void *data, int len);
+typedef void (*noise_consumer_t) (void *data, int len);
 
 /*
  * Read PuTTY's random seed file and pass its contents to a noise
index 29daf0f..b2e4999 100644 (file)
--- a/telnet.c
+++ b/telnet.c
 
 static Socket s = NULL;
 
-#define        IAC     255             /* interpret as command: */
-#define        DONT    254             /* you are not to use option */
-#define        DO      253             /* please, you use option */
-#define        WONT    252             /* I won't use option */
-#define        WILL    251             /* I will use option */
-#define        SB      250             /* interpret as subnegotiation */
-#define        SE      240             /* end sub negotiation */
-
-#define GA      249             /* you may reverse the line */
-#define EL      248             /* erase the current line */
-#define EC      247             /* erase the current character */
-#define        AYT     246             /* are you there */
-#define        AO      245             /* abort output--but let prog finish */
-#define        IP      244             /* interrupt process--permanently */
-#define        BREAK   243             /* break */
-#define DM      242             /* data mark--for connect. cleaning */
-#define NOP     241             /* nop */
-#define EOR     239             /* end of record (transparent mode) */
-#define ABORT   238             /* Abort process */
-#define SUSP    237             /* Suspend process */
-#define xEOF    236             /* End of file: EOF is already used... */
-
-#define TELOPT_BINARY  0       /* 8-bit data path */
-#define TELOPT_ECHO    1       /* echo */
-#define        TELOPT_RCP      2       /* prepare to reconnect */
-#define        TELOPT_SGA      3       /* suppress go ahead */
-#define        TELOPT_NAMS     4       /* approximate message size */
-#define        TELOPT_STATUS   5       /* give status */
-#define        TELOPT_TM       6       /* timing mark */
-#define        TELOPT_RCTE     7       /* remote controlled transmission and echo */
-#define TELOPT_NAOL    8       /* negotiate about output line width */
-#define TELOPT_NAOP    9       /* negotiate about output page size */
-#define TELOPT_NAOCRD  10      /* negotiate about CR disposition */
-#define TELOPT_NAOHTS  11      /* negotiate about horizontal tabstops */
-#define TELOPT_NAOHTD  12      /* negotiate about horizontal tab disposition */
-#define TELOPT_NAOFFD  13      /* negotiate about formfeed disposition */
-#define TELOPT_NAOVTS  14      /* negotiate about vertical tab stops */
-#define TELOPT_NAOVTD  15      /* negotiate about vertical tab disposition */
-#define TELOPT_NAOLFD  16      /* negotiate about output LF disposition */
-#define TELOPT_XASCII  17      /* extended ascic character set */
-#define        TELOPT_LOGOUT   18      /* force logout */
-#define        TELOPT_BM       19      /* byte macro */
-#define        TELOPT_DET      20      /* data entry terminal */
-#define        TELOPT_SUPDUP   21      /* supdup protocol */
-#define        TELOPT_SUPDUPOUTPUT 22  /* supdup output */
-#define        TELOPT_SNDLOC   23      /* send location */
-#define        TELOPT_TTYPE    24      /* terminal type */
-#define        TELOPT_EOR      25      /* end or record */
-#define        TELOPT_TUID     26      /* TACACS user identification */
-#define        TELOPT_OUTMRK   27      /* output marking */
-#define        TELOPT_TTYLOC   28      /* terminal location number */
-#define        TELOPT_3270REGIME 29    /* 3270 regime */
-#define        TELOPT_X3PAD    30      /* X.3 PAD */
-#define        TELOPT_NAWS     31      /* window size */
-#define        TELOPT_TSPEED   32      /* terminal speed */
-#define        TELOPT_LFLOW    33      /* remote flow control */
-#define TELOPT_LINEMODE        34      /* Linemode option */
-#define TELOPT_XDISPLOC        35      /* X Display Location */
-#define TELOPT_OLD_ENVIRON 36  /* Old - Environment variables */
-#define        TELOPT_AUTHENTICATION 37/* Authenticate */
-#define        TELOPT_ENCRYPT  38      /* Encryption option */
-#define TELOPT_NEW_ENVIRON 39  /* New - Environment variables */
-#define        TELOPT_EXOPL    255     /* extended-options-list */
-
-#define        TELQUAL_IS      0       /* option is... */
-#define        TELQUAL_SEND    1       /* send option */
-#define        TELQUAL_INFO    2       /* ENVIRON: informational version of IS */
+#define        IAC     255                    /* interpret as command: */
+#define        DONT    254                    /* you are not to use option */
+#define        DO      253                    /* please, you use option */
+#define        WONT    252                    /* I won't use option */
+#define        WILL    251                    /* I will use option */
+#define        SB      250                    /* interpret as subnegotiation */
+#define        SE      240                    /* end sub negotiation */
+
+#define GA      249                   /* you may reverse the line */
+#define EL      248                   /* erase the current line */
+#define EC      247                   /* erase the current character */
+#define        AYT     246                    /* are you there */
+#define        AO      245                    /* abort output--but let prog finish */
+#define        IP      244                    /* interrupt process--permanently */
+#define        BREAK   243                    /* break */
+#define DM      242                   /* data mark--for connect. cleaning */
+#define NOP     241                   /* nop */
+#define EOR     239                   /* end of record (transparent mode) */
+#define ABORT   238                   /* Abort process */
+#define SUSP    237                   /* Suspend process */
+#define xEOF    236                   /* End of file: EOF is already used... */
+
+#define TELOPT_BINARY  0              /* 8-bit data path */
+#define TELOPT_ECHO    1              /* echo */
+#define        TELOPT_RCP      2              /* prepare to reconnect */
+#define        TELOPT_SGA      3              /* suppress go ahead */
+#define        TELOPT_NAMS     4              /* approximate message size */
+#define        TELOPT_STATUS   5              /* give status */
+#define        TELOPT_TM       6              /* timing mark */
+#define        TELOPT_RCTE     7              /* remote controlled transmission and echo */
+#define TELOPT_NAOL    8              /* negotiate about output line width */
+#define TELOPT_NAOP    9              /* negotiate about output page size */
+#define TELOPT_NAOCRD  10             /* negotiate about CR disposition */
+#define TELOPT_NAOHTS  11             /* negotiate about horizontal tabstops */
+#define TELOPT_NAOHTD  12             /* negotiate about horizontal tab disposition */
+#define TELOPT_NAOFFD  13             /* negotiate about formfeed disposition */
+#define TELOPT_NAOVTS  14             /* negotiate about vertical tab stops */
+#define TELOPT_NAOVTD  15             /* negotiate about vertical tab disposition */
+#define TELOPT_NAOLFD  16             /* negotiate about output LF disposition */
+#define TELOPT_XASCII  17             /* extended ascic character set */
+#define        TELOPT_LOGOUT   18             /* force logout */
+#define        TELOPT_BM       19             /* byte macro */
+#define        TELOPT_DET      20             /* data entry terminal */
+#define        TELOPT_SUPDUP   21             /* supdup protocol */
+#define        TELOPT_SUPDUPOUTPUT 22         /* supdup output */
+#define        TELOPT_SNDLOC   23             /* send location */
+#define        TELOPT_TTYPE    24             /* terminal type */
+#define        TELOPT_EOR      25             /* end or record */
+#define        TELOPT_TUID     26             /* TACACS user identification */
+#define        TELOPT_OUTMRK   27             /* output marking */
+#define        TELOPT_TTYLOC   28             /* terminal location number */
+#define        TELOPT_3270REGIME 29           /* 3270 regime */
+#define        TELOPT_X3PAD    30             /* X.3 PAD */
+#define        TELOPT_NAWS     31             /* window size */
+#define        TELOPT_TSPEED   32             /* terminal speed */
+#define        TELOPT_LFLOW    33             /* remote flow control */
+#define TELOPT_LINEMODE        34             /* Linemode option */
+#define TELOPT_XDISPLOC        35             /* X Display Location */
+#define TELOPT_OLD_ENVIRON 36         /* Old - Environment variables */
+#define        TELOPT_AUTHENTICATION 37       /* Authenticate */
+#define        TELOPT_ENCRYPT  38             /* Encryption option */
+#define TELOPT_NEW_ENVIRON 39         /* New - Environment variables */
+#define        TELOPT_EXOPL    255            /* extended-options-list */
+
+#define        TELQUAL_IS      0              /* option is... */
+#define        TELQUAL_SEND    1              /* send option */
+#define        TELQUAL_INFO    2              /* ENVIRON: informational version of IS */
 #define BSD_VAR 1
 #define BSD_VALUE 0
 #define RFC_VAR 0
@@ -91,15 +91,49 @@ static Socket s = NULL;
 
 #define iswritable(x) ( (x) != IAC && (x) != CR )
 
-static char *telopt(int opt) {
+static char *telopt(int opt)
+{
 #define i(x) if (opt == TELOPT_ ## x) return #x;
-    i(BINARY); i(ECHO); i(RCP); i(SGA); i(NAMS); i(STATUS); i(TM); i(RCTE);
-    i(NAOL); i(NAOP); i(NAOCRD); i(NAOHTS); i(NAOHTD); i(NAOFFD); i(NAOVTS);
-    i(NAOVTD); i(NAOLFD); i(XASCII); i(LOGOUT); i(BM); i(DET); i(SUPDUP);
-    i(SUPDUPOUTPUT); i(SNDLOC); i(TTYPE); i(EOR); i(TUID); i(OUTMRK);
-    i(TTYLOC); i(X3PAD); i(NAWS); i(TSPEED); i(LFLOW); i(LINEMODE);
-    i(XDISPLOC); i(OLD_ENVIRON); i(AUTHENTICATION); i(ENCRYPT);
-    i(NEW_ENVIRON); i(EXOPL);
+    i(BINARY);
+    i(ECHO);
+    i(RCP);
+    i(SGA);
+    i(NAMS);
+    i(STATUS);
+    i(TM);
+    i(RCTE);
+    i(NAOL);
+    i(NAOP);
+    i(NAOCRD);
+    i(NAOHTS);
+    i(NAOHTD);
+    i(NAOFFD);
+    i(NAOVTS);
+    i(NAOVTD);
+    i(NAOLFD);
+    i(XASCII);
+    i(LOGOUT);
+    i(BM);
+    i(DET);
+    i(SUPDUP);
+    i(SUPDUPOUTPUT);
+    i(SNDLOC);
+    i(TTYPE);
+    i(EOR);
+    i(TUID);
+    i(OUTMRK);
+    i(TTYLOC);
+    i(X3PAD);
+    i(NAWS);
+    i(TSPEED);
+    i(LFLOW);
+    i(LINEMODE);
+    i(XDISPLOC);
+    i(OLD_ENVIRON);
+    i(AUTHENTICATION);
+    i(ENCRYPT);
+    i(NEW_ENVIRON);
+    i(EXOPL);
 #undef i
     return "<unknown>";
 }
@@ -116,16 +150,24 @@ struct Opt {
     } state;
 };
 
-static struct Opt o_naws = {WILL, WONT, DO, DONT, TELOPT_NAWS, REQUESTED};
-static struct Opt o_tspeed = {WILL, WONT, DO, DONT, TELOPT_TSPEED, REQUESTED};
-static struct Opt o_ttype = {WILL, WONT, DO, DONT, TELOPT_TTYPE, REQUESTED};
-static struct Opt o_oenv = {WILL, WONT, DO, DONT, TELOPT_OLD_ENVIRON,
-    INACTIVE};
-static struct Opt o_nenv = {WILL, WONT, DO, DONT, TELOPT_NEW_ENVIRON,
-    REQUESTED};
-static struct Opt o_echo = {DO, DONT, WILL, WONT, TELOPT_ECHO, REQUESTED};
-static struct Opt o_we_sga = {WILL, WONT, DO, DONT, TELOPT_SGA, REQUESTED};
-static struct Opt o_they_sga = {DO, DONT, WILL, WONT, TELOPT_SGA, REQUESTED};
+static struct Opt o_naws =
+    { WILL, WONT, DO, DONT, TELOPT_NAWS, REQUESTED };
+static struct Opt o_tspeed =
+    { WILL, WONT, DO, DONT, TELOPT_TSPEED, REQUESTED };
+static struct Opt o_ttype =
+    { WILL, WONT, DO, DONT, TELOPT_TTYPE, REQUESTED };
+static struct Opt o_oenv = { WILL, WONT, DO, DONT, TELOPT_OLD_ENVIRON,
+    INACTIVE
+};
+static struct Opt o_nenv = { WILL, WONT, DO, DONT, TELOPT_NEW_ENVIRON,
+    REQUESTED
+};
+static struct Opt o_echo =
+    { DO, DONT, WILL, WONT, TELOPT_ECHO, REQUESTED };
+static struct Opt o_we_sga =
+    { WILL, WONT, DO, DONT, TELOPT_SGA, REQUESTED };
+static struct Opt o_they_sga =
+    { DO, DONT, WILL, WONT, TELOPT_SGA, REQUESTED };
 
 static struct Opt *opts[] = {
     &o_naws, &o_tspeed, &o_ttype, &o_oenv, &o_nenv, &o_echo,
@@ -140,12 +182,14 @@ static char *sb_buf = NULL;
 static int sb_size = 0;
 #define SB_DELTA 1024
 
-static void c_write1(int c) {
-    char cc = (char)c;
+static void c_write1(int c)
+{
+    char cc = (char) c;
     from_backend(0, &cc, 1);
 }
 
-static void log_option (char *sender, int cmd, int option) {
+static void log_option(char *sender, int cmd, int option)
+{
     char buf[50];
     sprintf(buf, "%s:\t%s %s", sender,
            (cmd == WILL ? "WILL" : cmd == WONT ? "WONT" :
@@ -154,32 +198,38 @@ static void log_option (char *sender, int cmd, int option) {
     logevent(buf);
 }
 
-static void send_opt (int cmd, int option) {
+static void send_opt(int cmd, int option)
+{
     unsigned char b[3];
 
-    b[0] = IAC; b[1] = cmd; b[2] = option;
+    b[0] = IAC;
+    b[1] = cmd;
+    b[2] = option;
     sk_write(s, b, 3);
     log_option("client", cmd, option);
 }
 
-static void deactivate_option (struct Opt *o) {
+static void deactivate_option(struct Opt *o)
+{
     if (o->state == REQUESTED || o->state == ACTIVE)
-       send_opt (o->nsend, o->option);
+       send_opt(o->nsend, o->option);
     o->state = REALLY_INACTIVE;
 }
 
 /*
  * Generate side effects of enabling or disabling an option.
  */
-static void option_side_effects(struct Opt *o, int enabled) {
+static void option_side_effects(struct Opt *o, int enabled)
+{
     if (o->option == TELOPT_ECHO && o->send == DO)
-        echoing = !enabled;
+       echoing = !enabled;
     else if (o->option == TELOPT_SGA && o->send == DO)
-        editing = !enabled;
-    ldisc_send(NULL, 0);               /* cause ldisc to notice the change */
+       editing = !enabled;
+    ldisc_send(NULL, 0);              /* cause ldisc to notice the change */
 }
 
-static void activate_option (struct Opt *o) {
+static void activate_option(struct Opt *o)
+{
     if (o->send == WILL && o->option == TELOPT_NAWS)
        telnet_size();
     if (o->send == WILL &&
@@ -189,40 +239,43 @@ static void activate_option (struct Opt *o) {
         * We may only have one kind of ENVIRON going at a time.
         * This is a hack, but who cares.
         */
-       deactivate_option (o->option==TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv);
+       deactivate_option(o->option ==
+                         TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv);
     }
     option_side_effects(o, 1);
 }
 
-static void refused_option (struct Opt *o) {
+static void refused_option(struct Opt *o)
+{
     if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON &&
        o_oenv.state == INACTIVE) {
-       send_opt (WILL, TELOPT_OLD_ENVIRON);
+       send_opt(WILL, TELOPT_OLD_ENVIRON);
        o_oenv.state = REQUESTED;
     }
     option_side_effects(o, 0);
 }
 
-static void proc_rec_opt (int cmd, int option) {
+static void proc_rec_opt(int cmd, int option)
+{
     struct Opt **o;
 
-    log_option ("server", cmd, option);
+    log_option("server", cmd, option);
     for (o = opts; *o; o++) {
        if ((*o)->option == option && (*o)->ack == cmd) {
            switch ((*o)->state) {
              case REQUESTED:
                (*o)->state = ACTIVE;
-               activate_option (*o);
+               activate_option(*o);
                break;
              case ACTIVE:
                break;
              case INACTIVE:
                (*o)->state = ACTIVE;
-               send_opt ((*o)->send, option);
-               activate_option (*o);
+               send_opt((*o)->send, option);
+               activate_option(*o);
                break;
              case REALLY_INACTIVE:
-               send_opt ((*o)->nsend, option);
+               send_opt((*o)->nsend, option);
                break;
            }
            return;
@@ -230,12 +283,12 @@ static void proc_rec_opt (int cmd, int option) {
            switch ((*o)->state) {
              case REQUESTED:
                (*o)->state = INACTIVE;
-               refused_option (*o);
+               refused_option(*o);
                break;
              case ACTIVE:
                (*o)->state = INACTIVE;
-               send_opt ((*o)->nsend, option);
-                option_side_effects(*o, 0);
+               send_opt((*o)->nsend, option);
+               option_side_effects(*o, 0);
                break;
              case INACTIVE:
              case REALLY_INACTIVE:
@@ -248,10 +301,11 @@ static void proc_rec_opt (int cmd, int option) {
      * If we reach here, the option was one we weren't prepared to
      * cope with. So send a negative ack.
      */
-    send_opt ((cmd == WILL ? DONT : WONT), option);
+    send_opt((cmd == WILL ? DONT : WONT), option);
 }
 
-static void process_subneg (void) {
+static void process_subneg(void)
+{
     unsigned char b[2048], *p, *q;
     int var, value, n;
     char *e;
@@ -259,45 +313,53 @@ static void process_subneg (void) {
     switch (sb_opt) {
       case TELOPT_TSPEED:
        if (sb_len == 1 && sb_buf[0] == TELQUAL_SEND) {
-           char logbuf[sizeof(cfg.termspeed)+80];
-           b[0] = IAC; b[1] = SB; b[2] = TELOPT_TSPEED;
+           char logbuf[sizeof(cfg.termspeed) + 80];
+           b[0] = IAC;
+           b[1] = SB;
+           b[2] = TELOPT_TSPEED;
            b[3] = TELQUAL_IS;
-           strcpy(b+4, cfg.termspeed);
+           strcpy(b + 4, cfg.termspeed);
            n = 4 + strlen(cfg.termspeed);
-           b[n] = IAC; b[n+1] = SE;
-           sk_write(s, b, n+2);
+           b[n] = IAC;
+           b[n + 1] = SE;
+           sk_write(s, b, n + 2);
            logevent("server:\tSB TSPEED SEND");
            sprintf(logbuf, "client:\tSB TSPEED IS %s", cfg.termspeed);
-           logevent (logbuf);
+           logevent(logbuf);
        } else
-           logevent ("server:\tSB TSPEED <something weird>");
+           logevent("server:\tSB TSPEED <something weird>");
        break;
       case TELOPT_TTYPE:
        if (sb_len == 1 && sb_buf[0] == TELQUAL_SEND) {
-           char logbuf[sizeof(cfg.termtype)+80];
-           b[0] = IAC; b[1] = SB; b[2] = TELOPT_TTYPE;
+           char logbuf[sizeof(cfg.termtype) + 80];
+           b[0] = IAC;
+           b[1] = SB;
+           b[2] = TELOPT_TTYPE;
            b[3] = TELQUAL_IS;
            for (n = 0; cfg.termtype[n]; n++)
-               b[n+4] = (cfg.termtype[n] >= 'a' && cfg.termtype[n] <= 'z' ?
-                         cfg.termtype[n] + 'A'-'a' : cfg.termtype[n]);
-           b[n+4] = IAC; b[n+5] = SE;
-           sk_write(s, b, n+6);
-           b[n+4] = 0;
+               b[n + 4] = (cfg.termtype[n] >= 'a'
+                           && cfg.termtype[n] <=
+                           'z' ? cfg.termtype[n] + 'A' -
+                           'a' : cfg.termtype[n]);
+           b[n + 4] = IAC;
+           b[n + 5] = SE;
+           sk_write(s, b, n + 6);
+           b[n + 4] = 0;
            logevent("server:\tSB TTYPE SEND");
-           sprintf(logbuf, "client:\tSB TTYPE IS %s", b+4);
+           sprintf(logbuf, "client:\tSB TTYPE IS %s", b + 4);
            logevent(logbuf);
        } else
            logevent("server:\tSB TTYPE <something weird>\r\n");
        break;
       case TELOPT_OLD_ENVIRON:
-      case TELOPT_NEW_ENVIRON: 
+      case TELOPT_NEW_ENVIRON:
        p = sb_buf;
        q = p + sb_len;
        if (p < q && *p == TELQUAL_SEND) {
            char logbuf[50];
            p++;
-           sprintf (logbuf, "server:\tSB %s SEND", telopt(sb_opt));
-           logevent (logbuf);
+           sprintf(logbuf, "server:\tSB %s SEND", telopt(sb_opt));
+           logevent(logbuf);
            if (sb_opt == TELOPT_OLD_ENVIRON) {
                if (cfg.rfc_environ) {
                    value = RFC_VALUE;
@@ -327,29 +389,40 @@ static void process_subneg (void) {
                value = RFC_VALUE;
                var = RFC_VAR;
            }
-           b[0] = IAC; b[1] = SB; b[2] = sb_opt;
+           b[0] = IAC;
+           b[1] = SB;
+           b[2] = sb_opt;
            b[3] = TELQUAL_IS;
            n = 4;
-          e = cfg.environmt;
+           e = cfg.environmt;
            while (*e) {
                b[n++] = var;
-               while (*e && *e != '\t') b[n++] = *e++;
-               if (*e == '\t') e++;
+               while (*e && *e != '\t')
+                   b[n++] = *e++;
+               if (*e == '\t')
+                   e++;
                b[n++] = value;
-               while (*e) b[n++] = *e++;
+               while (*e)
+                   b[n++] = *e++;
                e++;
            }
            if (*cfg.username) {
-               b[n++] = var; b[n++] = 'U'; b[n++] = 'S';
-               b[n++] = 'E'; b[n++] = 'R'; b[n++] = value;
+               b[n++] = var;
+               b[n++] = 'U';
+               b[n++] = 'S';
+               b[n++] = 'E';
+               b[n++] = 'R';
+               b[n++] = value;
                e = cfg.username;
-               while (*e) b[n++] = *e++;
+               while (*e)
+                   b[n++] = *e++;
            }
-           b[n++] = IAC; b[n++] = SE;
+           b[n++] = IAC;
+           b[n++] = SE;
            sk_write(s, b, n);
            sprintf(logbuf, "client:\tSB %s IS %s", telopt(sb_opt),
-                   n==6 ? "<nothing>" : "<stuff>");
-           logevent (logbuf);
+                   n == 6 ? "<nothing>" : "<stuff>");
+           logevent(logbuf);
        }
        break;
     }
@@ -360,7 +433,8 @@ static enum {
     SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR
 } telnet_state = TOPLEVEL;
 
-static void do_telnet_read (char *buf, int len) {
+static void do_telnet_read(char *buf, int len)
+{
 
     while (len--) {
        int c = (unsigned char) *buf++;
@@ -385,7 +459,8 @@ static void do_telnet_read (char *buf, int len) {
                 * Oh well, we do get the DM in the right place so I'll
                 * just stop hiding on the next 0xf2 and hope for the best.
                 */
-               else if (c == DM) in_synch = 0;
+               else if (c == DM)
+                   in_synch = 0;
 #endif
                if (c == CR)
                    telnet_state = SEENCR;
@@ -394,16 +469,20 @@ static void do_telnet_read (char *buf, int len) {
            }
            break;
          case SEENIAC:
-           if (c == DO) telnet_state = SEENDO;
-           else if (c == DONT) telnet_state = SEENDONT;
-           else if (c == WILL) telnet_state = SEENWILL;
-           else if (c == WONT) telnet_state = SEENWONT;
-           else if (c == SB) telnet_state = SEENSB;
+           if (c == DO)
+               telnet_state = SEENDO;
+           else if (c == DONT)
+               telnet_state = SEENDONT;
+           else if (c == WILL)
+               telnet_state = SEENWILL;
+           else if (c == WONT)
+               telnet_state = SEENWONT;
+           else if (c == SB)
+               telnet_state = SEENSB;
            else if (c == DM) {
-               in_synch = 0;
+               in_synch = 0;
                telnet_state = TOPLEVEL;
-           } 
-           else {
+           } else {
                /* ignore everything else; print it if it's IAC */
                if (c == IAC) {
                    c_write1(c);
@@ -412,19 +491,19 @@ static void do_telnet_read (char *buf, int len) {
            }
            break;
          case SEENWILL:
-           proc_rec_opt (WILL, c);
+           proc_rec_opt(WILL, c);
            telnet_state = TOPLEVEL;
            break;
          case SEENWONT:
-           proc_rec_opt (WONT, c);
+           proc_rec_opt(WONT, c);
            telnet_state = TOPLEVEL;
            break;
          case SEENDO:
-           proc_rec_opt (DO, c);
+           proc_rec_opt(DO, c);
            telnet_state = TOPLEVEL;
            break;
          case SEENDONT:
-           proc_rec_opt (DONT, c);
+           proc_rec_opt(DONT, c);
            telnet_state = TOPLEVEL;
            break;
          case SEENSB:
@@ -436,7 +515,7 @@ static void do_telnet_read (char *buf, int len) {
            if (c == IAC)
                telnet_state = SUBNEG_IAC;
            else {
-               subneg_addchar:
+             subneg_addchar:
                if (sb_len >= sb_size) {
                    char *newbuf;
                    sb_size += SB_DELTA;
@@ -450,7 +529,7 @@ static void do_telnet_read (char *buf, int len) {
                }
                if (sb_len < sb_size)
                    sb_buf[sb_len++] = c;
-               telnet_state = SUBNEGOT;/* in case we came here by goto */
+               telnet_state = SUBNEGOT;        /* in case we came here by goto */
            }
            break;
          case SUBNEG_IAC:
@@ -465,19 +544,23 @@ static void do_telnet_read (char *buf, int len) {
     }
 }
 
-static int telnet_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
+static int telnet_closing(Plug plug, char *error_msg, int error_code,
+                         int calling_back)
+{
     sk_close(s);
     s = NULL;
     if (error_msg) {
-        /* A socket error has occurred. */
-        connection_fatal (error_msg);
-    } /* Otherwise, the remote side closed the connection normally. */
+       /* A socket error has occurred. */
+       connection_fatal(error_msg);
+    }                                 /* Otherwise, the remote side closed the connection normally. */
     return 0;
 }
 
-static int telnet_receive(Plug plug, int urgent, char *data, int len) {
-    if(urgent) in_synch = TRUE;
-    do_telnet_read (data, len);
+static int telnet_receive(Plug plug, int urgent, char *data, int len)
+{
+    if (urgent)
+       in_synch = TRUE;
+    do_telnet_read(data, len);
     return 1;
 }
 
@@ -488,7 +571,8 @@ static int telnet_receive(Plug plug, int urgent, char *data, int len) {
  *
  * Also places the canonical host name into `realhost'.
  */
-static char *telnet_init (char *host, int port, char **realhost) {
+static char *telnet_init(char *host, int port, char **realhost)
+{
     static struct plug_function_table fn_table = {
        telnet_closing,
        telnet_receive
@@ -501,7 +585,7 @@ static char *telnet_init (char *host, int port, char **realhost) {
      * Try to find host.
      */
     addr = sk_namelookup(host, realhost);
-    if ( (err = sk_addr_error(addr)) )
+    if ((err = sk_addr_error(addr)))
        return err;
 
     if (port < 0)
@@ -511,7 +595,7 @@ static char *telnet_init (char *host, int port, char **realhost) {
      * Open socket.
      */
     s = sk_new(addr, port, 0, 1, &fn_table_ptr);
-    if ( (err = sk_socket_error(s)) )
+    if ((err = sk_socket_error(s)))
        return err;
 
     sk_addr_free(addr);
@@ -524,7 +608,7 @@ static char *telnet_init (char *host, int port, char **realhost) {
 
        for (o = opts; *o; o++)
            if ((*o)->state == REQUESTED)
-               send_opt ((*o)->send, (*o)->option);
+               send_opt((*o)->send, (*o)->option);
     }
 
     /*
@@ -538,7 +622,8 @@ static char *telnet_init (char *host, int port, char **realhost) {
 /*
  * Called to send data down the Telnet connection.
  */
-static void telnet_send (char *buf, int len) {
+static void telnet_send(char *buf, int len)
+{
     char *p;
     static unsigned char iac[2] = { IAC, IAC };
     static unsigned char cr[2] = { CR, NUL };
@@ -548,14 +633,15 @@ static void telnet_send (char *buf, int len) {
        return;
 
     p = buf;
-    while (p < buf+len) {
+    while (p < buf + len) {
        char *q = p;
 
-       while (iswritable((unsigned char)*p) && p < buf+len) p++;
-       sk_write(s, q, p-q);
+       while (iswritable((unsigned char) *p) && p < buf + len)
+           p++;
+       sk_write(s, q, p - q);
 
-       while (p < buf+len && !iswritable((unsigned char)*p)) {
-           sk_write(s, (unsigned char)*p == IAC ? iac : nl, 2);
+       while (p < buf + len && !iswritable((unsigned char) *p)) {
+           sk_write(s, (unsigned char) *p == IAC ? iac : nl, 2);
            p++;
        }
     }
@@ -564,27 +650,34 @@ static void telnet_send (char *buf, int len) {
 /*
  * Called to set the size of the window from Telnet's POV.
  */
-static void telnet_size(void) {
+static void telnet_size(void)
+{
     unsigned char b[16];
     char logbuf[50];
 
     if (s == NULL || o_naws.state != ACTIVE)
        return;
-    b[0] = IAC; b[1] = SB; b[2] = TELOPT_NAWS;
-    b[3] = cols >> 8; b[4] = cols & 0xFF;
-    b[5] = rows >> 8; b[6] = rows & 0xFF;
-    b[7] = IAC; b[8] = SE;
+    b[0] = IAC;
+    b[1] = SB;
+    b[2] = TELOPT_NAWS;
+    b[3] = cols >> 8;
+    b[4] = cols & 0xFF;
+    b[5] = rows >> 8;
+    b[6] = rows & 0xFF;
+    b[7] = IAC;
+    b[8] = SE;
     sk_write(s, b, 9);
     sprintf(logbuf, "client:\tSB NAWS %d,%d",
-           ((unsigned char)b[3] << 8) + (unsigned char)b[4],
-           ((unsigned char)b[5] << 8) + (unsigned char)b[6]);
-    logevent (logbuf);
+           ((unsigned char) b[3] << 8) + (unsigned char) b[4],
+           ((unsigned char) b[5] << 8) + (unsigned char) b[6]);
+    logevent(logbuf);
 }
 
 /*
  * Send Telnet special codes.
  */
-static void telnet_special (Telnet_Special code) {
+static void telnet_special(Telnet_Special code)
+{
     unsigned char b[2];
 
     if (s == NULL)
@@ -592,51 +685,96 @@ static void telnet_special (Telnet_Special code) {
 
     b[0] = IAC;
     switch (code) {
-      case TS_AYT: b[1] = AYT; sk_write(s, b, 2); break;
-      case TS_BRK: b[1] = BREAK; sk_write(s, b, 2); break;
-      case TS_EC: b[1] = EC; sk_write(s, b, 2); break;
-      case TS_EL: b[1] = EL; sk_write(s, b, 2); break;
-      case TS_GA: b[1] = GA; sk_write(s, b, 2); break;
-      case TS_NOP: b[1] = NOP; sk_write(s, b, 2); break;
-      case TS_ABORT: b[1] = ABORT; sk_write(s, b, 2); break;
-      case TS_AO: b[1] = AO; sk_write(s, b, 2); break;
-      case TS_IP: b[1] = IP; sk_write(s, b, 2); break;
-      case TS_SUSP: b[1] = SUSP; sk_write(s, b, 2); break;
-      case TS_EOR: b[1] = EOR; sk_write(s, b, 2); break;
-      case TS_EOF: b[1] = xEOF; sk_write(s, b, 2); break;
+      case TS_AYT:
+       b[1] = AYT;
+       sk_write(s, b, 2);
+       break;
+      case TS_BRK:
+       b[1] = BREAK;
+       sk_write(s, b, 2);
+       break;
+      case TS_EC:
+       b[1] = EC;
+       sk_write(s, b, 2);
+       break;
+      case TS_EL:
+       b[1] = EL;
+       sk_write(s, b, 2);
+       break;
+      case TS_GA:
+       b[1] = GA;
+       sk_write(s, b, 2);
+       break;
+      case TS_NOP:
+       b[1] = NOP;
+       sk_write(s, b, 2);
+       break;
+      case TS_ABORT:
+       b[1] = ABORT;
+       sk_write(s, b, 2);
+       break;
+      case TS_AO:
+       b[1] = AO;
+       sk_write(s, b, 2);
+       break;
+      case TS_IP:
+       b[1] = IP;
+       sk_write(s, b, 2);
+       break;
+      case TS_SUSP:
+       b[1] = SUSP;
+       sk_write(s, b, 2);
+       break;
+      case TS_EOR:
+       b[1] = EOR;
+       sk_write(s, b, 2);
+       break;
+      case TS_EOF:
+       b[1] = xEOF;
+       sk_write(s, b, 2);
+       break;
       case TS_SYNCH:
-        b[1] = DM;
-        sk_write (s, b, 1);
-        sk_write_oob (s, b+1, 1);
-        break;
+       b[1] = DM;
+       sk_write(s, b, 1);
+       sk_write_oob(s, b + 1, 1);
+       break;
       case TS_RECHO:
        if (o_echo.state == INACTIVE || o_echo.state == REALLY_INACTIVE) {
            o_echo.state = REQUESTED;
-           send_opt (o_echo.send, o_echo.option);
+           send_opt(o_echo.send, o_echo.option);
        }
        break;
       case TS_LECHO:
        if (o_echo.state == ACTIVE) {
            o_echo.state = REQUESTED;
-           send_opt (o_echo.nsend, o_echo.option);
+           send_opt(o_echo.nsend, o_echo.option);
        }
        break;
-      case TS_PING: 
+      case TS_PING:
        if (o_they_sga.state == ACTIVE) {
-           b[1] = NOP; 
-           sk_write(s, b, 2); 
+           b[1] = NOP;
+           sk_write(s, b, 2);
        }
-        break;
+       break;
     }
 }
 
-static Socket telnet_socket(void) { return s; }
+static Socket telnet_socket(void)
+{
+    return s;
+}
 
-static int telnet_sendok(void) { return 1; }
+static int telnet_sendok(void)
+{
+    return 1;
+}
 
-static int telnet_ldisc(int option) {
-    if (option == LD_ECHO) return echoing;
-    if (option == LD_EDIT) return editing;
+static int telnet_ldisc(int option)
+{
+    if (option == LD_ECHO)
+       return echoing;
+    if (option == LD_EDIT)
+       return editing;
     return FALSE;
 }
 
index c3a4e2c..64b5685 100644 (file)
@@ -9,18 +9,18 @@
 #include "putty.h"
 #include "tree234.h"
 
-#define CL_ANSIMIN     0x0001  /* Codes in all ANSI like terminals. */
-#define CL_VT100       0x0002  /* VT100 */
-#define CL_VT100AVO    0x0004  /* VT100 +AVO; 132x24 (not 132x14) & attrs */
-#define CL_VT102       0x0008  /* VT102 */
-#define CL_VT220       0x0010  /* VT220 */
-#define CL_VT320       0x0020  /* VT320 */
-#define CL_VT420       0x0040  /* VT420 */
-#define CL_VT510       0x0080  /* VT510, NB VT510 includes ANSI */
-#define CL_VT340TEXT   0x0100  /* VT340 extensions that appear in the VT420 */
-#define CL_SCOANSI     0x1000  /* SCOANSI not in ANSIMIN. */
-#define CL_ANSI                0x2000  /* ANSI ECMA-48 not in the VT100..VT420 */
-#define CL_OTHER       0x4000  /* Others, Xterm, linux, putty, dunno, etc */
+#define CL_ANSIMIN     0x0001         /* Codes in all ANSI like terminals. */
+#define CL_VT100       0x0002         /* VT100 */
+#define CL_VT100AVO    0x0004         /* VT100 +AVO; 132x24 (not 132x14) & attrs */
+#define CL_VT102       0x0008         /* VT102 */
+#define CL_VT220       0x0010         /* VT220 */
+#define CL_VT320       0x0020         /* VT320 */
+#define CL_VT420       0x0040         /* VT420 */
+#define CL_VT510       0x0080         /* VT510, NB VT510 includes ANSI */
+#define CL_VT340TEXT   0x0100         /* VT340 extensions that appear in the VT420 */
+#define CL_SCOANSI     0x1000         /* SCOANSI not in ANSIMIN. */
+#define CL_ANSI                0x2000         /* ANSI ECMA-48 not in the VT100..VT420 */
+#define CL_OTHER       0x4000         /* Others, Xterm, linux, putty, dunno, etc */
 
 #define TM_VT100       (CL_ANSIMIN|CL_VT100)
 #define TM_VT100AVO    (TM_VT100|CL_VT100AVO)
@@ -101,10 +101,10 @@ static int use_bce;                      /* Use Background coloured erase */
 static int blinker;                   /* When blinking is the cursor on ? */
 static int tblinker;                  /* When the blinking text is on */
 static int blink_is_real;             /* Actually blink blinking text */
-static int term_echoing;               /* Does terminal want local echo? */
-static int term_editing;               /* Does terminal want local edit? */
+static int term_echoing;              /* Does terminal want local echo? */
+static int term_editing;              /* Does terminal want local edit? */
 
-static int xterm_mouse;                /* send mouse messages to app */
+static int xterm_mouse;                       /* send mouse messages to app */
 
 static unsigned long cset_attr[2];
 
@@ -126,7 +126,7 @@ static int esc_query;
 
 #define OSC_STR_MAX 2048
 static int osc_strlen;
-static char osc_string[OSC_STR_MAX+1];
+static char osc_string[OSC_STR_MAX + 1];
 static int osc_w;
 
 static char id_string[1024] = "\033[?6c";
@@ -161,28 +161,36 @@ static enum {
 static pos selstart, selend, selanchor;
 
 static short wordness[256] = {
-    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 01 */
-    0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2, 2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1, /* 23 */
-    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2, /* 45 */
-    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1, /* 67 */
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 89 */
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* AB */
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* CD */
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2, /* EF */
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0,           /* 01 */
+    0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+    2, 2, 1, 1, 1, 1, 1, 1,           /* 23 */
+    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+    2, 2, 2, 1, 1, 1, 1, 2,           /* 45 */
+    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+    2, 2, 2, 1, 1, 1, 1, 1,           /* 67 */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1,           /* 89 */
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1,           /* AB */
+    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
+    2, 2, 2, 2, 2, 2, 2, 2,           /* CD */
+    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
+    2, 2, 2, 2, 2, 2, 2, 2,           /* EF */
 };
 
 static unsigned char sel_nl[] = SEL_NL;
-static char * paste_buffer = 0;
+static char *paste_buffer = 0;
 static int paste_len, paste_pos, paste_hold;
 
 /*
  * Internal prototypes.
  */
-static void do_paint (Context, int);
-static void erase_lots (int, int, int);
-static void swap_screen (int);
-static void update_sbar (void);
-static void deselect (void);
+static void do_paint(Context, int);
+static void erase_lots(int, int, int);
+static void swap_screen(int);
+static void update_sbar(void);
+static void deselect(void);
 /* log session to file stuff ... */
 static FILE *lgfp = NULL;
 static void logtraffic(unsigned char c, int logmode);
@@ -192,7 +200,8 @@ static void logtraffic(unsigned char c, int logmode);
  * whether the y coordinate is non-negative or negative
  * (respectively).
  */
-unsigned long *lineptr(int y, int lineno) {
+unsigned long *lineptr(int y, int lineno)
+{
     unsigned long *line, lineattrs;
     tree234 *whichtree;
     int i, treeindex, oldlen;
@@ -215,23 +224,25 @@ unsigned long *lineptr(int y, int lineno) {
         * hasn't been accessed since a resize. Resize it now.
         */
        oldlen = line[0];
-       lineattrs = line[oldlen+1];
+       lineattrs = line[oldlen + 1];
        delpos234(whichtree, treeindex);
-       line = srealloc(line, TSIZE * (2+cols));
+       line = srealloc(line, TSIZE * (2 + cols));
        line[0] = cols;
        for (i = oldlen; i < cols; i++)
-           line[i+1] = ERASE_CHAR;
-       line[cols+1] = lineattrs & LATTR_MODE;
+           line[i + 1] = ERASE_CHAR;
+       line[cols + 1] = lineattrs & LATTR_MODE;
        addpos234(whichtree, line, treeindex);
     }
 
-    return line+1;
+    return line + 1;
 }
+
 #define lineptr(x) lineptr(x,__LINE__)
 /*
  * Set up power-on settings for the terminal.
  */
-static void power_on(void) {
+static void power_on(void)
+{
     curs.x = curs.y = alt_x = alt_y = savecurs.x = savecurs.y = 0;
     alt_t = marg_t = 0;
     if (rows != -1)
@@ -253,7 +264,7 @@ static void power_on(void) {
     cursor_on = 1;
     save_attr = curr_attr = ATTR_DEFAULT;
     term_editing = term_echoing = FALSE;
-    ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
+    ldisc_send(NULL, 0);              /* cause ldisc to notice changes */
     app_cursor_keys = cfg.app_cursor;
     app_keypad_keys = cfg.app_keypad;
     use_bce = cfg.bce;
@@ -266,36 +277,38 @@ static void power_on(void) {
            wordness[i] = cfg.wordness[i];
     }
     if (screen) {
-       swap_screen (1);
-       erase_lots (FALSE, TRUE, TRUE);
-       swap_screen (0);
-       erase_lots (FALSE, TRUE, TRUE);
+       swap_screen(1);
+       erase_lots(FALSE, TRUE, TRUE);
+       swap_screen(0);
+       erase_lots(FALSE, TRUE, TRUE);
     }
 }
 
 /*
  * Force a screen update.
  */
-void term_update(void) {
+void term_update(void)
+{
     Context ctx;
     ctx = get_ctx();
     if (ctx) {
-        if ( (seen_key_event && (cfg.scroll_on_key)) ||
-            (seen_disp_event && (cfg.scroll_on_disp)) ) {
+       if ((seen_key_event && (cfg.scroll_on_key)) ||
+           (seen_disp_event && (cfg.scroll_on_disp))) {
            disptop = 0;               /* return to main screen */
            seen_disp_event = seen_key_event = 0;
            update_sbar();
        }
-       do_paint (ctx, TRUE);
-        sys_cursor(curs.x, curs.y - disptop);
-       free_ctx (ctx);
+       do_paint(ctx, TRUE);
+       sys_cursor(curs.x, curs.y - disptop);
+       free_ctx(ctx);
     }
 }
 
 /*
  * Same as power_on(), but an external function.
  */
-void term_pwron(void) {
+void term_pwron(void)
+{
     power_on();
     fix_cpos;
     disptop = 0;
@@ -306,7 +319,8 @@ void term_pwron(void) {
 /*
  * Clear the scrollback.
  */
-void term_clrsb(void) {
+void term_clrsb(void)
+{
     unsigned long *line;
     disptop = 0;
     while ((line = delpos234(scrollback, 0)) != NULL) {
@@ -318,7 +332,8 @@ void term_clrsb(void) {
 /*
  * Initialise the terminal.
  */
-void term_init(void) {
+void term_init(void)
+{
     screen = alt_screen = scrollback = NULL;
     disptop = 0;
     disptext = wanttext = NULL;
@@ -336,7 +351,8 @@ void term_init(void) {
 /*
  * Set up the terminal for a given size.
  */
-void term_size(int newrows, int newcols, int newsavelines) {
+void term_size(int newrows, int newcols, int newsavelines)
+{
     tree234 *newsb, *newscreen, *newalt;
     unsigned long *newdisp, *newwant, *oldline, *line;
     int i, j, ccols;
@@ -381,20 +397,20 @@ void term_size(int newrows, int newcols, int newsavelines) {
     sblen = count234(scrollback);
     /* Do this loop to expand the screen if newrows > rows */
     for (i = rows; i < newrows; i++) {
-        if (sblen > 0) {
-            line = delpos234(scrollback, --sblen);
-        } else {
-            line = smalloc(TSIZE * (newcols+2));
-            line[0] = newcols;
-            for (j = 0; j <= newcols; j++)
-                line[j+1] = ERASE_CHAR;
-        }
-        addpos234(screen, line, 0);
+       if (sblen > 0) {
+           line = delpos234(scrollback, --sblen);
+       } else {
+           line = smalloc(TSIZE * (newcols + 2));
+           line[0] = newcols;
+           for (j = 0; j <= newcols; j++)
+               line[j + 1] = ERASE_CHAR;
+       }
+       addpos234(screen, line, 0);
     }
     /* Do this loop to shrink the screen if newrows < rows */
     for (i = newrows; i < rows; i++) {
-        line = delpos234(screen, 0);
-        addpos234(scrollback, line, sblen++);
+       line = delpos234(screen, 0);
+       addpos234(scrollback, line, sblen++);
     }
     assert(count234(screen) == newrows);
     while (sblen > newsavelines) {
@@ -405,24 +421,24 @@ void term_size(int newrows, int newcols, int newsavelines) {
     assert(count234(scrollback) <= newsavelines);
     disptop = 0;
 
-    newdisp = smalloc (newrows*(newcols+1)*TSIZE);
-    for (i=0; i<newrows*(newcols+1); i++)
+    newdisp = smalloc(newrows * (newcols + 1) * TSIZE);
+    for (i = 0; i < newrows * (newcols + 1); i++)
        newdisp[i] = ATTR_INVALID;
-    sfree (disptext);
+    sfree(disptext);
     disptext = newdisp;
 
-    newwant = smalloc (newrows*(newcols+1)*TSIZE);
-    for (i=0; i<newrows*(newcols+1); i++)
+    newwant = smalloc(newrows * (newcols + 1) * TSIZE);
+    for (i = 0; i < newrows * (newcols + 1); i++)
        newwant[i] = ATTR_INVALID;
-    sfree (wanttext);
+    sfree(wanttext);
     wanttext = newwant;
 
     newalt = newtree234(NULL);
-    for (i=0; i<newrows; i++) {
-       line = smalloc(TSIZE * (newcols+2));
+    for (i = 0; i < newrows; i++) {
+       line = smalloc(TSIZE * (newcols + 2));
        line[0] = newcols;
        for (j = 0; j <= newcols; j++)
-           line[j+1] = erase_char;
+           line[j + 1] = erase_char;
        addpos234(newalt, line, i);
     }
     if (alt_screen) {
@@ -432,10 +448,11 @@ void term_size(int newrows, int newcols, int newsavelines) {
     }
     alt_screen = newalt;
 
-    sfree (selspace);
-    selspace = smalloc ( (newrows+newsavelines) * (newcols+sizeof(sel_nl)) );
+    sfree(selspace);
+    selspace =
+       smalloc((newrows + newsavelines) * (newcols + sizeof(sel_nl)));
 
-    tabs = srealloc (tabs, newcols*sizeof(*tabs));
+    tabs = srealloc(tabs, newcols * sizeof(*tabs));
     {
        int i;
        for (i = (cols > 0 ? cols : 0); i < newcols; i++)
@@ -447,9 +464,9 @@ void term_size(int newrows, int newcols, int newsavelines) {
     if (curs.y < 0)
        curs.y = 0;
     if (curs.y >= newrows)
-       curs.y = newrows-1;
+       curs.y = newrows - 1;
     if (curs.x >= newcols)
-       curs.x = newcols-1;
+       curs.x = newcols - 1;
     alt_x = alt_y = 0;
     wrapnext = alt_wnext = FALSE;
 
@@ -467,7 +484,8 @@ void term_size(int newrows, int newcols, int newsavelines) {
 /*
  * Swap screens.
  */
-static void swap_screen (int which) {
+static void swap_screen(int which)
+{
     int t;
     tree234 *ttr;
 
@@ -476,16 +494,36 @@ static void swap_screen (int which) {
 
     alt_which = which;
 
-    ttr = alt_screen; alt_screen = screen; screen = ttr;
-    t = curs.x; curs.x = alt_x; alt_x = t;
-    t = curs.y; curs.y = alt_y; alt_y = t;
-    t = marg_t; marg_t = alt_t; alt_t = t;
-    t = marg_b; marg_b = alt_b; alt_b = t;
-    t = dec_om; dec_om = alt_om; alt_om = t;
-    t = wrap; wrap = alt_wrap; alt_wrap = t;
-    t = wrapnext; wrapnext = alt_wnext; alt_wnext = t;
-    t = insert; insert = alt_ins; alt_ins = t;
-    t = cset; cset = alt_cset; alt_cset = t;
+    ttr = alt_screen;
+    alt_screen = screen;
+    screen = ttr;
+    t = curs.x;
+    curs.x = alt_x;
+    alt_x = t;
+    t = curs.y;
+    curs.y = alt_y;
+    alt_y = t;
+    t = marg_t;
+    marg_t = alt_t;
+    alt_t = t;
+    t = marg_b;
+    marg_b = alt_b;
+    alt_b = t;
+    t = dec_om;
+    dec_om = alt_om;
+    alt_om = t;
+    t = wrap;
+    wrap = alt_wrap;
+    alt_wrap = t;
+    t = wrapnext;
+    wrapnext = alt_wnext;
+    alt_wnext = t;
+    t = insert;
+    insert = alt_ins;
+    alt_ins = t;
+    t = cset;
+    cset = alt_cset;
+    alt_cset = t;
 
     fix_cpos;
 }
@@ -493,19 +531,21 @@ static void swap_screen (int which) {
 /*
  * Update the scroll bar.
  */
-static void update_sbar(void) {
+static void update_sbar(void)
+{
     int nscroll;
 
     nscroll = count234(scrollback);
 
-    set_sbar (nscroll + rows, nscroll + disptop, rows);
+    set_sbar(nscroll + rows, nscroll + disptop, rows);
 }
 
 /*
  * Check whether the region bounded by the two pointers intersects
  * the scroll region, and de-select the on-screen selection if so.
  */
-static void check_selection (pos from, pos to) {
+static void check_selection(pos from, pos to)
+{
     if (poslt(from, selend) && poslt(selstart, to))
        deselect();
 }
@@ -520,7 +560,8 @@ static void check_selection (pos from, pos to) {
  * after calling scroll() and before doing anything else that
  * uses the cpos shortcut pointer.
  */
-static void scroll (int topline, int botline, int lines, int sb) {
+static void scroll(int topline, int botline, int lines, int sb)
+{
     unsigned long *line, *line2;
     int i;
 
@@ -531,8 +572,8 @@ static void scroll (int topline, int botline, int lines, int sb) {
        while (lines < 0) {
            line = delpos234(screen, botline);
            for (i = 0; i < cols; i++)
-               line[i+1] = erase_char;
-           line[cols+1] = 0;
+               line[i + 1] = erase_char;
+           line[cols + 1] = 0;
            addpos234(screen, line, topline);
 
            if (selstart.y >= topline && selstart.y <= botline) {
@@ -566,15 +607,15 @@ static void scroll (int topline, int botline, int lines, int sb) {
                if (sblen == savelines) {
                    sblen--, line2 = delpos234(scrollback, 0);
                } else {
-                   line2 = smalloc(TSIZE * (cols+2));
+                   line2 = smalloc(TSIZE * (cols + 2));
                    line2[0] = cols;
                }
                addpos234(scrollback, line, sblen);
                line = line2;
            }
            for (i = 0; i < cols; i++)
-               line[i+1] = erase_char;
-           line[cols+1] = 0;
+               line[i + 1] = erase_char;
+           line[cols + 1] = 0;
            addpos234(screen, line, botline);
 
            if (selstart.y >= topline && selstart.y <= botline) {
@@ -603,11 +644,12 @@ static void scroll (int topline, int botline, int lines, int sb) {
  * not to, 1 to disallow _passing_ the margins, and 2 to disallow
  * even _being_ outside the margins.
  */
-static void move (int x, int y, int marg_clip) {
+static void move(int x, int y, int marg_clip)
+{
     if (x < 0)
        x = 0;
     if (x >= cols)
-       x = cols-1;
+       x = cols - 1;
     if (marg_clip) {
        if ((curs.y >= marg_t || marg_clip == 2) && y < marg_t)
            y = marg_t;
@@ -617,7 +659,7 @@ static void move (int x, int y, int marg_clip) {
     if (y < 0)
        y = 0;
     if (y >= rows)
-       y = rows-1;
+       y = rows - 1;
     curs.x = x;
     curs.y = y;
     fix_cpos;
@@ -627,7 +669,8 @@ static void move (int x, int y, int marg_clip) {
 /*
  * Save or restore the cursor and SGR mode.
  */
-static void save_cursor(int save) {
+static void save_cursor(int save)
+{
     if (save) {
        savecurs = curs;
        save_attr = curr_attr;
@@ -636,14 +679,17 @@ static void save_cursor(int save) {
     } else {
        curs = savecurs;
        /* Make sure the window hasn't shrunk since the save */
-       if (curs.x >= cols) curs.x = cols-1;
-       if (curs.y >= rows) curs.y = rows-1;
+       if (curs.x >= cols)
+           curs.x = cols - 1;
+       if (curs.y >= rows)
+           curs.y = rows - 1;
 
        curr_attr = save_attr;
        cset = save_cset;
        cset_attr[cset] = save_csattr;
        fix_cpos;
-        if (use_bce) erase_char = (' ' |(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
+       if (use_bce)
+           erase_char = (' ' | (curr_attr & (ATTR_FGMASK | ATTR_BGMASK)));
     }
 }
 
@@ -651,7 +697,8 @@ static void save_cursor(int save) {
  * Erase a large portion of the screen: the whole screen, or the
  * whole line, or parts thereof.
  */
-static void erase_lots (int line_only, int from_begin, int to_end) {
+static void erase_lots(int line_only, int from_begin, int to_end)
+{
     pos start, end;
     int erase_lattr;
     unsigned long *ldata;
@@ -675,11 +722,11 @@ static void erase_lots (int line_only, int from_begin, int to_end) {
     if (!to_end) {
        end = curs;
     }
-    check_selection (start, end);
+    check_selection(start, end);
 
     /* Clear screen also forces a full window redraw, just in case. */
     if (start.y == 0 && start.x == 0 && end.y == rows)
-       term_invalidate();
+       term_invalidate();
 
     ldata = lineptr(start.y);
     while (poslt(start, end)) {
@@ -696,7 +743,8 @@ static void erase_lots (int line_only, int from_begin, int to_end) {
  * Insert or delete characters within the current line. n is +ve if
  * insertion is desired, and -ve for deletion.
  */
-static void insch (int n) {
+static void insch(int n)
+{
     int dir = (n < 0 ? -1 : +1);
     int m;
     pos cursplus;
@@ -708,14 +756,14 @@ static void insch (int n) {
     m = cols - curs.x - n;
     cursplus.y = curs.y;
     cursplus.x = curs.x + n;
-    check_selection (curs, cursplus);
+    check_selection(curs, cursplus);
     ldata = lineptr(curs.y);
     if (dir < 0) {
-       memmove (ldata + curs.x, ldata + curs.x + n, m*TSIZE);
+       memmove(ldata + curs.x, ldata + curs.x + n, m * TSIZE);
        while (n--)
            ldata[curs.x + m++] = erase_char;
     } else {
-       memmove (ldata + curs.x + n, ldata + curs.x, m*TSIZE);
+       memmove(ldata + curs.x + n, ldata + curs.x, m * TSIZE);
        while (n--)
            ldata[curs.x + n] = erase_char;
     }
@@ -725,108 +773,113 @@ static void insch (int n) {
  * Toggle terminal mode `mode' to state `state'. (`query' indicates
  * whether the mode is a DEC private one or a normal one.)
  */
-static void toggle_mode (int mode, int query, int state) {
+static void toggle_mode(int mode, int query, int state)
+{
     long ticks;
 
-    if (query) switch (mode) {
-      case 1:                         /* application cursor keys */
-       app_cursor_keys = state;
-       break;
-      case 2:                         /* VT52 mode */
-       vt52_mode = !state;
-       break;
-      case 3:                         /* 80/132 columns */
-       deselect();
-       request_resize (state ? 132 : 80, rows, 1);
-       reset_132 = state;
-       break;
-      case 5:                         /* reverse video */
-       /*
-        * Toggle reverse video. If we receive an OFF within the
-        * visual bell timeout period after an ON, we trigger an
-        * effective visual bell, so that ESC[?5hESC[?5l will
-        * always be an actually _visible_ visual bell.
-        */
-       ticks = GetTickCount();
-       if (rvideo && !state &&        /* we're turning it off */
-           ticks < rvbell_timeout) {  /* and it's not long since it was turned on */
-           in_vbell = TRUE;           /* we may clear rvideo but we set in_vbell */
-           if (vbell_timeout < rvbell_timeout)   /* don't move vbell end forward */
-               vbell_timeout = rvbell_timeout;   /* vbell end is at least then */
-       } else if (!rvideo && state) {
-           /* This is an ON, so we notice the time and save it. */
-           rvbell_timeout = ticks + VBELL_TIMEOUT;
+    if (query)
+       switch (mode) {
+         case 1:                      /* application cursor keys */
+           app_cursor_keys = state;
+           break;
+         case 2:                      /* VT52 mode */
+           vt52_mode = !state;
+           break;
+         case 3:                      /* 80/132 columns */
+           deselect();
+           request_resize(state ? 132 : 80, rows, 1);
+           reset_132 = state;
+           break;
+         case 5:                      /* reverse video */
+           /*
+            * Toggle reverse video. If we receive an OFF within the
+            * visual bell timeout period after an ON, we trigger an
+            * effective visual bell, so that ESC[?5hESC[?5l will
+            * always be an actually _visible_ visual bell.
+            */
+           ticks = GetTickCount();
+           if (rvideo && !state &&    /* we're turning it off */
+               ticks < rvbell_timeout) {       /* and it's not long since it was turned on */
+               in_vbell = TRUE;       /* we may clear rvideo but we set in_vbell */
+               if (vbell_timeout < rvbell_timeout)     /* don't move vbell end forward */
+                   vbell_timeout = rvbell_timeout;     /* vbell end is at least then */
+           } else if (!rvideo && state) {
+               /* This is an ON, so we notice the time and save it. */
+               rvbell_timeout = ticks + VBELL_TIMEOUT;
+           }
+           rvideo = state;
+           seen_disp_event = TRUE;
+           if (state)
+               term_update();
+           break;
+         case 6:                      /* DEC origin mode */
+           dec_om = state;
+           break;
+         case 7:                      /* auto wrap */
+           wrap = state;
+           break;
+         case 8:                      /* auto key repeat */
+           repeat_off = !state;
+           break;
+         case 10:                     /* set local edit mode */
+           term_editing = state;
+           ldisc_send(NULL, 0);       /* cause ldisc to notice changes */
+           break;
+         case 25:                     /* enable/disable cursor */
+           compatibility2(OTHER, VT220);
+           cursor_on = state;
+           seen_disp_event = TRUE;
+           break;
+         case 47:                     /* alternate screen */
+           compatibility(OTHER);
+           deselect();
+           swap_screen(state);
+           disptop = 0;
+           break;
+         case 1000:                   /* xterm mouse 1 */
+           xterm_mouse = state ? 1 : 0;
+           set_raw_mouse_mode(state);
+           break;
+         case 1002:                   /* xterm mouse 2 */
+           xterm_mouse = state ? 2 : 0;
+           set_raw_mouse_mode(state);
+           break;
+    } else
+       switch (mode) {
+         case 4:                      /* set insert mode */
+           compatibility(VT102);
+           insert = state;
+           break;
+         case 12:                     /* set echo mode */
+           term_echoing = !state;
+           ldisc_send(NULL, 0);       /* cause ldisc to notice changes */
+           break;
+         case 20:                     /* Return sends ... */
+           cr_lf_return = state;
+           break;
        }
-       rvideo = state;
-       seen_disp_event = TRUE;
-       if (state) term_update();
-       break;
-      case 6:                         /* DEC origin mode */
-       dec_om = state;
-       break;
-      case 7:                         /* auto wrap */
-       wrap = state;
-       break;
-      case 8:                         /* auto key repeat */
-       repeat_off = !state;
-       break;
-      case 10:                        /* set local edit mode */
-        term_editing = state;
-        ldisc_send(NULL, 0);           /* cause ldisc to notice changes */
-       break;
-      case 25:                        /* enable/disable cursor */
-       compatibility2(OTHER,VT220);
-       cursor_on = state;
-       seen_disp_event = TRUE;
-       break;
-      case 47:                        /* alternate screen */
-       compatibility(OTHER);
-       deselect();
-       swap_screen (state);
-       disptop = 0;
-       break;
-      case 1000:                      /* xterm mouse 1 */
-       xterm_mouse = state ? 1 : 0;
-       set_raw_mouse_mode(state);
-       break;
-      case 1002:                      /* xterm mouse 2 */
-       xterm_mouse = state ? 2: 0;
-       set_raw_mouse_mode(state);
-       break;
-    } else switch (mode) {
-      case 4:                         /* set insert mode */
-       compatibility(VT102);
-       insert = state;
-       break;
-      case 12:                        /* set echo mode */
-        term_echoing = !state;
-        ldisc_send(NULL, 0);           /* cause ldisc to notice changes */
-       break;
-      case 20:                        /* Return sends ... */
-       cr_lf_return = state;
-       break;
-    }
 }
 
 /*
  * Process an OSC sequence: set window title or icon name.
  */
-static void do_osc(void) {
+static void do_osc(void)
+{
     if (osc_w) {
        while (osc_strlen--)
-           wordness[(unsigned char)osc_string[osc_strlen]] = esc_args[0];
+           wordness[(unsigned char) osc_string[osc_strlen]] = esc_args[0];
     } else {
        osc_string[osc_strlen] = '\0';
        switch (esc_args[0]) {
          case 0:
          case 1:
-           set_icon (osc_string);
+           set_icon(osc_string);
            if (esc_args[0] == 1)
                break;
            /* fall through: parameter 0 means set both */
          case 2:
          case 21:
-           set_title (osc_string);
+           set_title(osc_string);
            break;
        }
     }
@@ -837,26 +890,25 @@ static void do_osc(void) {
  * in-memory display. There's a big state machine in here to
  * process escape sequences...
  */
-void term_out(void) {
+void term_out(void)
+{
     int c, inbuf_reap;
 
-    for(inbuf_reap = 0; inbuf_reap < inbuf_head; inbuf_reap++)
-    {
-        c = inbuf[inbuf_reap];
+    for (inbuf_reap = 0; inbuf_reap < inbuf_head; inbuf_reap++) {
+       c = inbuf[inbuf_reap];
 
        /*
-         * Optionally log the session traffic to a file. Useful for
-         * debugging and possibly also useful for actual logging.
-         */
-       logtraffic((unsigned char)c, LGTYP_DEBUG);
+        * Optionally log the session traffic to a file. Useful for
+        * debugging and possibly also useful for actual logging.
+        */
+       logtraffic((unsigned char) c, LGTYP_DEBUG);
 
        /* Note only VT220+ are 8-bit VT102 is seven bit, it shouldn't even
         * be able to display 8-bit characters, but I'll let that go 'cause
         * of i18n.
         */
-       if( ( (c&0x60) == 0 || c == '\177') && 
-            termstate < DO_CTRLS &&
-           ( (c&0x80) == 0 || has_compat(VT220))) {
+       if (((c & 0x60) == 0 || c == '\177') &&
+           termstate < DO_CTRLS && ((c & 0x80) == 0 || has_compat(VT220))) {
            switch (c) {
              case '\005':             /* terminal type query */
                /* Strictly speaking this is VT100 but a VT100 defaults to
@@ -867,29 +919,26 @@ void term_out(void) {
                 *
                 * An xterm returns "xterm" (5 characters)
                 */
-               compatibility(ANSIMIN);
+               compatibility(ANSIMIN);
                {
                    char abuf[256], *s, *d;
-                   int state=0;
-                   for(s=cfg.answerback, d=abuf; *s; s++) {
-                        if (state)
-                        {
-                            if (*s >= 'a' && *s <= 'z')
-                                *d++ = (*s - ('a'-1));
-                            else if ((*s >='@' && *s<='_') ||
-                                     *s == '?' || (*s&0x80))
-                                *d++ = ('@'^*s);
-                            else if (*s == '~')
-                                *d++ = '^';
-                            state = 0;
-                        }
-                        else if (*s == '^') {
-                            state = 1;
-                        }
-                        else
-                            *d++ = xlat_kbd2tty((unsigned char)*s);
+                   int state = 0;
+                   for (s = cfg.answerback, d = abuf; *s; s++) {
+                       if (state) {
+                           if (*s >= 'a' && *s <= 'z')
+                               *d++ = (*s - ('a' - 1));
+                           else if ((*s >= '@' && *s <= '_') ||
+                                    *s == '?' || (*s & 0x80))
+                               *d++ = ('@' ^ *s);
+                           else if (*s == '~')
+                               *d++ = '^';
+                           state = 0;
+                       } else if (*s == '^') {
+                           state = 1;
+                       } else
+                           *d++ = xlat_kbd2tty((unsigned char) *s);
                    }
-                   ldisc_send (abuf, d-abuf);
+                   ldisc_send(abuf, d - abuf);
                }
                break;
              case '\007':
@@ -926,7 +975,7 @@ void term_out(void) {
                    }
 
                    if (cfg.bellovl && beep_overloaded &&
-                       ticks-lastbeep >= cfg.bellovl_s) {
+                       ticks - lastbeep >= cfg.bellovl_s) {
                        /*
                         * If we're currently overloaded and the
                         * last beep was more than s seconds ago,
@@ -947,10 +996,11 @@ void term_out(void) {
                    /*
                     * Perform an actual beep if we're not overloaded.
                     */
-                   if ((!cfg.bellovl || !beep_overloaded) && cfg.beep != 0) {
+                   if ((!cfg.bellovl || !beep_overloaded)
+                       && cfg.beep != 0) {
                        if (cfg.beep != 2)
                            beep(cfg.beep);
-                       else if(cfg.beep == 2) {
+                       else if (cfg.beep == 2) {
                            in_vbell = TRUE;
                            vbell_timeout = ticks + VBELL_TIMEOUT;
                            term_update();
@@ -960,10 +1010,9 @@ void term_out(void) {
                }
                break;
              case '\b':
-               if (curs.x == 0 && curs.y == 0)
-                   ;
+               if (curs.x == 0 && curs.y == 0);
                else if (curs.x == 0 && curs.y > 0)
-                   curs.x = cols-1, curs.y--;
+                   curs.x = cols - 1, curs.y--;
                else if (wrapnext)
                    wrapnext = FALSE;
                else
@@ -972,30 +1021,30 @@ void term_out(void) {
                seen_disp_event = TRUE;
                break;
              case '\016':
-               compatibility(VT100);
+               compatibility(VT100);
                cset = 1;
                break;
              case '\017':
-               compatibility(VT100);
+               compatibility(VT100);
                cset = 0;
                break;
              case '\033':
-               if (vt52_mode) 
-                  termstate = VT52_ESC;
+               if (vt52_mode)
+                   termstate = VT52_ESC;
                else {
                    compatibility(ANSIMIN);
                    termstate = SEEN_ESC;
                }
                break;
              case 0233:
-               compatibility(VT220);
+               compatibility(VT220);
                termstate = SEEN_CSI;
                esc_nargs = 1;
                esc_args[0] = ARG_DEFAULT;
                esc_query = FALSE;
                break;
              case 0235:
-               compatibility(VT220);
+               compatibility(VT220);
                termstate = SEEN_OSC;
                esc_args[0] = 0;
                break;
@@ -1005,15 +1054,15 @@ void term_out(void) {
                fix_cpos;
                seen_disp_event = TRUE;
                paste_hold = 0;
-               logtraffic((unsigned char)c,LGTYP_ASCII);
+               logtraffic((unsigned char) c, LGTYP_ASCII);
                break;
              case '\013':
              case '\014':
-               compatibility(VT100);
+               compatibility(VT100);
              case '\n':
                if (curs.y == marg_b)
-                   scroll (marg_t, marg_b, 1, TRUE);
-               else if (curs.y < rows-1)
+                   scroll(marg_t, marg_b, 1, TRUE);
+               else if (curs.y < rows - 1)
                    curs.y++;
                if (cfg.lfhascr)
                    curs.x = 0;
@@ -1021,7 +1070,7 @@ void term_out(void) {
                wrapnext = FALSE;
                seen_disp_event = 1;
                paste_hold = 0;
-               logtraffic((unsigned char)c,LGTYP_ASCII);
+               logtraffic((unsigned char) c, LGTYP_ASCII);
                break;
              case '\t':
                {
@@ -1030,877 +1079,958 @@ void term_out(void) {
 
                    do {
                        curs.x++;
-                   } while (curs.x < cols-1 && !tabs[curs.x]);
+                   } while (curs.x < cols - 1 && !tabs[curs.x]);
 
-                   if ((ldata[cols] & LATTR_MODE) != LATTR_NORM)
-                   {
-                       if (curs.x >= cols/2)
-                           curs.x = cols/2-1;
-                   }
-                   else
-                   {
+                   if ((ldata[cols] & LATTR_MODE) != LATTR_NORM) {
+                       if (curs.x >= cols / 2)
+                           curs.x = cols / 2 - 1;
+                   } else {
                        if (curs.x >= cols)
-                           curs.x = cols-1;
+                           curs.x = cols - 1;
                    }
 
                    fix_cpos;
-                   check_selection (old_curs, curs);
+                   check_selection(old_curs, curs);
                }
                seen_disp_event = TRUE;
                break;
-             case '\177': /* Destructive backspace
-                             This does nothing on a real VT100 */
-               compatibility(OTHER);
-               if (curs.x && !wrapnext) curs.x--;
+             case '\177':             /* Destructive backspace
+                                         This does nothing on a real VT100 */
+               compatibility(OTHER);
+               if (curs.x && !wrapnext)
+                   curs.x--;
                wrapnext = FALSE;
                fix_cpos;
                *cpos = (' ' | curr_attr | ATTR_ASCII);
                break;
            }
-       }
-       else switch (termstate) {
-         case TOPLEVEL:
-           /* Only graphic characters get this far, ctrls are stripped above */
-           if (wrapnext && wrap) {
-               cpos[1] |= ATTR_WRAPPED;
-               if (curs.y == marg_b)
-                   scroll (marg_t, marg_b, 1, TRUE);
-               else if (curs.y < rows-1)
-                   curs.y++;
-               curs.x = 0;
-               fix_cpos;
-               wrapnext = FALSE;
-           }
-           if (insert)
-               insch (1);
-           if (selstate != NO_SELECTION) {
-               pos cursplus = curs;
-               incpos(cursplus);
-               check_selection (curs, cursplus);
-           }
-           switch (cset_attr[cset]) {
-               /*
-                * Linedraw characters are different from 'ESC ( B'
-                * only for a small range. For ones outside that
-                * range, make sure we use the same font as well as
-                * the same encoding.
-                */
-           case ATTR_LINEDRW:
-               if (c<0x5f || c>0x7F)
-                   *cpos++ = xlat_tty2scr((unsigned char)c) | curr_attr |
-                             ATTR_ASCII;
-               else if (c==0x5F)
-                   *cpos++ = ' ' | curr_attr | ATTR_ASCII;
-               else
-                   *cpos++ = ((unsigned char)c) | curr_attr | ATTR_LINEDRW;
-               break;
-           case ATTR_GBCHR:
-               /* If UK-ASCII, make the '#' a LineDraw Pound */
-               if (c == '#') {
-                   *cpos++ = '}' | curr_attr | ATTR_LINEDRW;
-                   break;
-               }
-               /*FALLTHROUGH*/
-           default:
-               *cpos = xlat_tty2scr((unsigned char)c) | curr_attr |
-                   (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
-               logtraffic((unsigned char)c, LGTYP_ASCII);
-               cpos++;
-               break;
-           }
-           curs.x++;
-           if (curs.x == cols) {
-               cpos--;
-               curs.x--;
-               wrapnext = TRUE;
-           }
-           seen_disp_event = 1;
-           break;
-
-         case IGNORE_NEXT:
-           termstate = TOPLEVEL;
-           break;
-         case OSC_MAYBE_ST:
-           /*
-            * This state is virtually identical to SEEN_ESC, with the
-            * exception that we have an OSC sequence in the pipeline,
-            * and _if_ we see a backslash, we process it.
-            */
-           if (c == '\\') {
-               do_osc();
-               termstate = TOPLEVEL;
-               break;
-           }
-           /* else fall through */
-         case SEEN_ESC:
-           termstate = TOPLEVEL;
-           switch (c) {
-             case ' ':                /* some weird sequence? */
-               compatibility(VT220);
-               termstate = IGNORE_NEXT;
-               break;
-             case '[':                /* enter CSI mode */
-               termstate = SEEN_CSI;
-               esc_nargs = 1;
-               esc_args[0] = ARG_DEFAULT;
-               esc_query = FALSE;
-               break;
-             case ']':                /* xterm escape sequences */
-               /* Compatibility is nasty here, xterm, linux, decterm yuk! */
-               compatibility(OTHER);
-               termstate = SEEN_OSC;
-               esc_args[0] = 0;
-               break;
-             case '(':                /* should set GL */
-               compatibility(VT100);
-               termstate = SET_GL;
-               break;
-             case ')':                /* should set GR */
-               compatibility(VT100);
-               termstate = SET_GR;
-               break;
-             case '7':                /* save cursor */
-               compatibility(VT100);
-               save_cursor (TRUE);
-               break;
-             case '8':                /* restore cursor */
-               compatibility(VT100);
-               save_cursor (FALSE);
-               seen_disp_event = TRUE;
-               break;
-             case '=':
-               compatibility(VT100);
-               app_keypad_keys = TRUE;
-               break;
-             case '>':
-               compatibility(VT100);
-               app_keypad_keys = FALSE;
-               break;
-             case 'D':                /* exactly equivalent to LF */
-               compatibility(VT100);
-               if (curs.y == marg_b)
-                   scroll (marg_t, marg_b, 1, TRUE);
-               else if (curs.y < rows-1)
-                   curs.y++;
-               fix_cpos;
-               wrapnext = FALSE;
-               seen_disp_event = TRUE;
-               break;
-             case 'E':                /* exactly equivalent to CR-LF */
-               compatibility(VT100);
-               curs.x = 0;
-               if (curs.y == marg_b)
-                   scroll (marg_t, marg_b, 1, TRUE);
-               else if (curs.y < rows-1)
-                   curs.y++;
-               fix_cpos;
-               wrapnext = FALSE;
-               seen_disp_event = TRUE;
-               break;
-             case 'M':                /* reverse index - backwards LF */
-               compatibility(VT100);
-               if (curs.y == marg_t)
-                   scroll (marg_t, marg_b, -1, TRUE);
-               else if (curs.y > 0)
-                   curs.y--;
-               fix_cpos;
-               wrapnext = FALSE;
-               seen_disp_event = TRUE;
-               break;
-             case 'Z':                /* terminal type query */
-               compatibility(VT100);
-               ldisc_send (id_string, strlen(id_string));
-               break;
-             case 'c':                /* restore power-on settings */
-               compatibility(VT100);
-               power_on();
-               if (reset_132) {
-                   request_resize (80, rows, 1);
-                   reset_132 = 0;
-               }
-               fix_cpos;
-               disptop = 0;
-               seen_disp_event = TRUE;
-               break;
-             case '#':                /* ESC # 8 fills screen with Es :-) */
-               compatibility(VT100);
-               termstate = SEEN_ESCHASH;
-               break;
-             case 'H':                /* set a tab */
-               compatibility(VT100);
-               tabs[curs.x] = TRUE;
-               break;
-           }
-           break;
-         case SEEN_CSI:
-           termstate = TOPLEVEL;      /* default */
-           if( isdigit(c) )
-           {
-               if (esc_nargs <= ARGS_MAX) {
-                   if (esc_args[esc_nargs-1] == ARG_DEFAULT)
-                       esc_args[esc_nargs-1] = 0;
-                   esc_args[esc_nargs-1] =
-                       10 * esc_args[esc_nargs-1] + c - '0';
-               }
-               termstate = SEEN_CSI;
-           }
-           else if( c == ';' )
-           {
-               if (++esc_nargs <= ARGS_MAX)
-                   esc_args[esc_nargs-1] = ARG_DEFAULT;
-               termstate = SEEN_CSI;
-           }
-           else if( c < '@' )
-           {
-               if( esc_query )     esc_query = -1;
-               else if( c == '?' ) esc_query = TRUE;
-               else                esc_query = c;
-               termstate = SEEN_CSI;
-           }
-           else switch (ANSI(c,esc_query)) {
-             case 'A':                /* move up N lines */
-               move (curs.x, curs.y - def(esc_args[0], 1), 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'e':      /* move down N lines */
-               compatibility(ANSI);
-             case 'B':
-               move (curs.x, curs.y + def(esc_args[0], 1), 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'a':      /* move right N cols */
-               compatibility(ANSI);
-             case ANSI('c', '>'):      /* report xterm version */
-               compatibility(OTHER);
-               /* this reports xterm version 136 so that VIM can
-                use the drag messages from the mouse reporting */
-               ldisc_send("\033[>0;136;0c", 11);
-               break;
-             case 'C':
-               move (curs.x + def(esc_args[0], 1), curs.y, 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'D':                /* move left N cols */
-               move (curs.x - def(esc_args[0], 1), curs.y, 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'E':                /* move down N lines and CR */
-               compatibility(ANSI);
-               move (0, curs.y + def(esc_args[0], 1), 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'F':                /* move up N lines and CR */
-               compatibility(ANSI);
-               move (0, curs.y - def(esc_args[0], 1), 1);
-               seen_disp_event = TRUE;
-               break;
-             case 'G': case '`':      /* set horizontal posn */
-               compatibility(ANSI);
-               move (def(esc_args[0], 1) - 1, curs.y, 0);
-               seen_disp_event = TRUE;
-               break;
-             case 'd':                /* set vertical posn */
-               compatibility(ANSI);
-               move (curs.x, (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
-                     (dec_om ? 2 : 0));
-               seen_disp_event = TRUE;
-               break;
-             case 'H': case 'f':      /* set horz and vert posns at once */
-               if (esc_nargs < 2)
-                   esc_args[1] = ARG_DEFAULT;
-               move (def(esc_args[1], 1) - 1,
-                     (dec_om ? marg_t : 0) + def(esc_args[0], 1) - 1,
-                     (dec_om ? 2 : 0));
-               seen_disp_event = TRUE;
-               break;
-             case 'J':                /* erase screen or parts of it */
-               {
-                   unsigned int i = def(esc_args[0], 0) + 1;
-                   if (i > 3)
-                       i = 0;
-                   erase_lots(FALSE, !!(i & 2), !!(i & 1));
+       } else
+           switch (termstate) {
+             case TOPLEVEL:
+               /* Only graphic characters get this far, ctrls are stripped above */
+               if (wrapnext && wrap) {
+                   cpos[1] |= ATTR_WRAPPED;
+                   if (curs.y == marg_b)
+                       scroll(marg_t, marg_b, 1, TRUE);
+                   else if (curs.y < rows - 1)
+                       curs.y++;
+                   curs.x = 0;
+                   fix_cpos;
+                   wrapnext = FALSE;
                }
-               disptop = 0;
-               seen_disp_event = TRUE;
-               break;
-             case 'K':                /* erase line or parts of it */
-               {
-                   unsigned int i = def(esc_args[0], 0) + 1;
-                   if (i > 3)
-                       i = 0;
-                   erase_lots(TRUE, !!(i & 2), !!(i & 1));
+               if (insert)
+                   insch(1);
+               if (selstate != NO_SELECTION) {
+                   pos cursplus = curs;
+                   incpos(cursplus);
+                   check_selection(curs, cursplus);
                }
-               seen_disp_event = TRUE;
-               break;
-             case 'L':                /* insert lines */
-               compatibility(VT102);
-               if (curs.y <= marg_b)
-                   scroll (curs.y, marg_b, -def(esc_args[0], 1), FALSE);
-                fix_cpos;
-               seen_disp_event = TRUE;
-               break;
-             case 'M':                /* delete lines */
-               compatibility(VT102);
-               if (curs.y <= marg_b)
-                   scroll (curs.y, marg_b, def(esc_args[0], 1), TRUE);
-                fix_cpos;
-               seen_disp_event = TRUE;
-               break;
-             case '@':                /* insert chars */
-               /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
-               compatibility(VT102);   
-               insch (def(esc_args[0], 1));
-               seen_disp_event = TRUE;
-               break;
-             case 'P':                /* delete chars */
-               compatibility(VT102);   
-               insch (-def(esc_args[0], 1));
-               seen_disp_event = TRUE;
-               break;
-             case 'c':                /* terminal type query */
-               compatibility(VT100);
-               /* This is the response for a VT102 */
-               ldisc_send (id_string, strlen(id_string));
-               break;
-             case 'n':                /* cursor position query */
-               if (esc_args[0] == 6) {
-                   char buf[32];
-                   sprintf (buf, "\033[%d;%dR", curs.y + 1, curs.x + 1);
-                   ldisc_send (buf, strlen(buf));
+               switch (cset_attr[cset]) {
+                   /*
+                    * Linedraw characters are different from 'ESC ( B'
+                    * only for a small range. For ones outside that
+                    * range, make sure we use the same font as well as
+                    * the same encoding.
+                    */
+                 case ATTR_LINEDRW:
+                   if (c < 0x5f || c > 0x7F)
+                       *cpos++ =
+                           xlat_tty2scr((unsigned char) c) | curr_attr |
+                           ATTR_ASCII;
+                   else if (c == 0x5F)
+                       *cpos++ = ' ' | curr_attr | ATTR_ASCII;
+                   else
+                       *cpos++ =
+                           ((unsigned char) c) | curr_attr | ATTR_LINEDRW;
+                   break;
+                 case ATTR_GBCHR:
+                   /* If UK-ASCII, make the '#' a LineDraw Pound */
+                   if (c == '#') {
+                       *cpos++ = '}' | curr_attr | ATTR_LINEDRW;
+                       break;
+                   }
+                 /*FALLTHROUGH*/ default:
+                   *cpos = xlat_tty2scr((unsigned char) c) | curr_attr |
+                       (c <= 0x7F ? cset_attr[cset] : ATTR_ASCII);
+                   logtraffic((unsigned char) c, LGTYP_ASCII);
+                   cpos++;
+                   break;
                }
-               else if (esc_args[0] == 5) {
-                   ldisc_send ("\033[0n", 4);
+               curs.x++;
+               if (curs.x == cols) {
+                   cpos--;
+                   curs.x--;
+                   wrapnext = TRUE;
                }
+               seen_disp_event = 1;
                break;
-             case 'h':                /* toggle modes to high */
-             case ANSI_QUE('h'):
-               compatibility(VT100);
-               {
-                   int i;
-                   for (i=0; i<esc_nargs; i++)
-                       toggle_mode (esc_args[i], esc_query, TRUE);
-               }
+
+             case IGNORE_NEXT:
+               termstate = TOPLEVEL;
                break;
-             case 'l':                /* toggle modes to low */
-             case ANSI_QUE('l'):
-               compatibility(VT100);
-               {
-                   int i;
-                   for (i=0; i<esc_nargs; i++)
-                       toggle_mode (esc_args[i], esc_query, FALSE);
+             case OSC_MAYBE_ST:
+               /*
+                * This state is virtually identical to SEEN_ESC, with the
+                * exception that we have an OSC sequence in the pipeline,
+                * and _if_ we see a backslash, we process it.
+                */
+               if (c == '\\') {
+                   do_osc();
+                   termstate = TOPLEVEL;
+                   break;
                }
-               break;
-             case 'g':                /* clear tabs */
-               compatibility(VT100);
-               if (esc_nargs == 1) {
-                   if (esc_args[0] == 0) {
-                       tabs[curs.x] = FALSE;
-                   } else if (esc_args[0] == 3) {
-                       int i;
-                       for (i = 0; i < cols; i++)
-                           tabs[i] = FALSE;
+               /* else fall through */
+             case SEEN_ESC:
+               termstate = TOPLEVEL;
+               switch (c) {
+                 case ' ':            /* some weird sequence? */
+                   compatibility(VT220);
+                   termstate = IGNORE_NEXT;
+                   break;
+                 case '[':            /* enter CSI mode */
+                   termstate = SEEN_CSI;
+                   esc_nargs = 1;
+                   esc_args[0] = ARG_DEFAULT;
+                   esc_query = FALSE;
+                   break;
+                 case ']':            /* xterm escape sequences */
+                   /* Compatibility is nasty here, xterm, linux, decterm yuk! */
+                   compatibility(OTHER);
+                   termstate = SEEN_OSC;
+                   esc_args[0] = 0;
+                   break;
+                 case '(':            /* should set GL */
+                   compatibility(VT100);
+                   termstate = SET_GL;
+                   break;
+                 case ')':            /* should set GR */
+                   compatibility(VT100);
+                   termstate = SET_GR;
+                   break;
+                 case '7':            /* save cursor */
+                   compatibility(VT100);
+                   save_cursor(TRUE);
+                   break;
+                 case '8':            /* restore cursor */
+                   compatibility(VT100);
+                   save_cursor(FALSE);
+                   seen_disp_event = TRUE;
+                   break;
+                 case '=':
+                   compatibility(VT100);
+                   app_keypad_keys = TRUE;
+                   break;
+                 case '>':
+                   compatibility(VT100);
+                   app_keypad_keys = FALSE;
+                   break;
+                 case 'D':            /* exactly equivalent to LF */
+                   compatibility(VT100);
+                   if (curs.y == marg_b)
+                       scroll(marg_t, marg_b, 1, TRUE);
+                   else if (curs.y < rows - 1)
+                       curs.y++;
+                   fix_cpos;
+                   wrapnext = FALSE;
+                   seen_disp_event = TRUE;
+                   break;
+                 case 'E':            /* exactly equivalent to CR-LF */
+                   compatibility(VT100);
+                   curs.x = 0;
+                   if (curs.y == marg_b)
+                       scroll(marg_t, marg_b, 1, TRUE);
+                   else if (curs.y < rows - 1)
+                       curs.y++;
+                   fix_cpos;
+                   wrapnext = FALSE;
+                   seen_disp_event = TRUE;
+                   break;
+                 case 'M':            /* reverse index - backwards LF */
+                   compatibility(VT100);
+                   if (curs.y == marg_t)
+                       scroll(marg_t, marg_b, -1, TRUE);
+                   else if (curs.y > 0)
+                       curs.y--;
+                   fix_cpos;
+                   wrapnext = FALSE;
+                   seen_disp_event = TRUE;
+                   break;
+                 case 'Z':            /* terminal type query */
+                   compatibility(VT100);
+                   ldisc_send(id_string, strlen(id_string));
+                   break;
+                 case 'c':            /* restore power-on settings */
+                   compatibility(VT100);
+                   power_on();
+                   if (reset_132) {
+                       request_resize(80, rows, 1);
+                       reset_132 = 0;
                    }
+                   fix_cpos;
+                   disptop = 0;
+                   seen_disp_event = TRUE;
+                   break;
+                 case '#':            /* ESC # 8 fills screen with Es :-) */
+                   compatibility(VT100);
+                   termstate = SEEN_ESCHASH;
+                   break;
+                 case 'H':            /* set a tab */
+                   compatibility(VT100);
+                   tabs[curs.x] = TRUE;
+                   break;
                }
                break;
-             case 'r':                /* set scroll margins */
-               compatibility(VT100);
-               if (esc_nargs <= 2) {
-                   int top, bot;
-                   top = def(esc_args[0], 1) - 1;
-                   bot = (esc_nargs <= 1 || esc_args[1] == 0 ? rows :
-                          def(esc_args[1], rows)) - 1;
-                   if (bot >= rows)
-                       bot = rows-1;
-                   /* VTTEST Bug 9 - if region is less than 2 lines
-                    * don't change region.
-                    */
-                   if (bot-top > 0) {
-                       marg_t = top;
-                       marg_b = bot;
-                       curs.x = 0;
+             case SEEN_CSI:
+               termstate = TOPLEVEL;  /* default */
+               if (isdigit(c)) {
+                   if (esc_nargs <= ARGS_MAX) {
+                       if (esc_args[esc_nargs - 1] == ARG_DEFAULT)
+                           esc_args[esc_nargs - 1] = 0;
+                       esc_args[esc_nargs - 1] =
+                           10 * esc_args[esc_nargs - 1] + c - '0';
+                   }
+                   termstate = SEEN_CSI;
+               } else if (c == ';') {
+                   if (++esc_nargs <= ARGS_MAX)
+                       esc_args[esc_nargs - 1] = ARG_DEFAULT;
+                   termstate = SEEN_CSI;
+               } else if (c < '@') {
+                   if (esc_query)
+                       esc_query = -1;
+                   else if (c == '?')
+                       esc_query = TRUE;
+                   else
+                       esc_query = c;
+                   termstate = SEEN_CSI;
+               } else
+                   switch (ANSI(c, esc_query)) {
+                     case 'A':       /* move up N lines */
+                       move(curs.x, curs.y - def(esc_args[0], 1), 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'e':       /* move down N lines */
+                       compatibility(ANSI);
+                     case 'B':
+                       move(curs.x, curs.y + def(esc_args[0], 1), 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'a':       /* move right N cols */
+                       compatibility(ANSI);
+                     case ANSI('c', '>'):      /* report xterm version */
+                       compatibility(OTHER);
+                       /* this reports xterm version 136 so that VIM can
+                          use the drag messages from the mouse reporting */
+                       ldisc_send("\033[>0;136;0c", 11);
+                       break;
+                     case 'C':
+                       move(curs.x + def(esc_args[0], 1), curs.y, 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'D':       /* move left N cols */
+                       move(curs.x - def(esc_args[0], 1), curs.y, 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'E':       /* move down N lines and CR */
+                       compatibility(ANSI);
+                       move(0, curs.y + def(esc_args[0], 1), 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'F':       /* move up N lines and CR */
+                       compatibility(ANSI);
+                       move(0, curs.y - def(esc_args[0], 1), 1);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'G':
+                     case '`':       /* set horizontal posn */
+                       compatibility(ANSI);
+                       move(def(esc_args[0], 1) - 1, curs.y, 0);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'd':       /* set vertical posn */
+                       compatibility(ANSI);
+                       move(curs.x,
+                            (dec_om ? marg_t : 0) + def(esc_args[0],
+                                                        1) - 1,
+                            (dec_om ? 2 : 0));
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'H':
+                     case 'f':       /* set horz and vert posns at once */
+                       if (esc_nargs < 2)
+                           esc_args[1] = ARG_DEFAULT;
+                       move(def(esc_args[1], 1) - 1,
+                            (dec_om ? marg_t : 0) + def(esc_args[0],
+                                                        1) - 1,
+                            (dec_om ? 2 : 0));
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'J':       /* erase screen or parts of it */
+                       {
+                           unsigned int i = def(esc_args[0], 0) + 1;
+                           if (i > 3)
+                               i = 0;
+                           erase_lots(FALSE, !!(i & 2), !!(i & 1));
+                       }
+                       disptop = 0;
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'K':       /* erase line or parts of it */
+                       {
+                           unsigned int i = def(esc_args[0], 0) + 1;
+                           if (i > 3)
+                               i = 0;
+                           erase_lots(TRUE, !!(i & 2), !!(i & 1));
+                       }
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'L':       /* insert lines */
+                       compatibility(VT102);
+                       if (curs.y <= marg_b)
+                           scroll(curs.y, marg_b, -def(esc_args[0], 1),
+                                  FALSE);
+                       fix_cpos;
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'M':       /* delete lines */
+                       compatibility(VT102);
+                       if (curs.y <= marg_b)
+                           scroll(curs.y, marg_b, def(esc_args[0], 1),
+                                  TRUE);
+                       fix_cpos;
+                       seen_disp_event = TRUE;
+                       break;
+                     case '@':       /* insert chars */
+                       /* XXX VTTEST says this is vt220, vt510 manual says vt102 */
+                       compatibility(VT102);
+                       insch(def(esc_args[0], 1));
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'P':       /* delete chars */
+                       compatibility(VT102);
+                       insch(-def(esc_args[0], 1));
+                       seen_disp_event = TRUE;
+                       break;
+                     case 'c':       /* terminal type query */
+                       compatibility(VT100);
+                       /* This is the response for a VT102 */
+                       ldisc_send(id_string, strlen(id_string));
+                       break;
+                     case 'n':       /* cursor position query */
+                       if (esc_args[0] == 6) {
+                           char buf[32];
+                           sprintf(buf, "\033[%d;%dR", curs.y + 1,
+                                   curs.x + 1);
+                           ldisc_send(buf, strlen(buf));
+                       } else if (esc_args[0] == 5) {
+                           ldisc_send("\033[0n", 4);
+                       }
+                       break;
+                     case 'h':       /* toggle modes to high */
+                     case ANSI_QUE('h'):
+                       compatibility(VT100);
+                       {
+                           int i;
+                           for (i = 0; i < esc_nargs; i++)
+                               toggle_mode(esc_args[i], esc_query, TRUE);
+                       }
+                       break;
+                     case 'l':       /* toggle modes to low */
+                     case ANSI_QUE('l'):
+                       compatibility(VT100);
+                       {
+                           int i;
+                           for (i = 0; i < esc_nargs; i++)
+                               toggle_mode(esc_args[i], esc_query, FALSE);
+                       }
+                       break;
+                     case 'g':       /* clear tabs */
+                       compatibility(VT100);
+                       if (esc_nargs == 1) {
+                           if (esc_args[0] == 0) {
+                               tabs[curs.x] = FALSE;
+                           } else if (esc_args[0] == 3) {
+                               int i;
+                               for (i = 0; i < cols; i++)
+                                   tabs[i] = FALSE;
+                           }
+                       }
+                       break;
+                     case 'r':       /* set scroll margins */
+                       compatibility(VT100);
+                       if (esc_nargs <= 2) {
+                           int top, bot;
+                           top = def(esc_args[0], 1) - 1;
+                           bot = (esc_nargs <= 1
+                                  || esc_args[1] ==
+                                  0 ? rows : def(esc_args[1], rows)) - 1;
+                           if (bot >= rows)
+                               bot = rows - 1;
+                           /* VTTEST Bug 9 - if region is less than 2 lines
+                            * don't change region.
+                            */
+                           if (bot - top > 0) {
+                               marg_t = top;
+                               marg_b = bot;
+                               curs.x = 0;
+                               /*
+                                * I used to think the cursor should be
+                                * placed at the top of the newly marginned
+                                * area. Apparently not: VMS TPU falls over
+                                * if so.
+                                *
+                                * Well actually it should for Origin mode - RDB
+                                */
+                               curs.y = (dec_om ? marg_t : 0);
+                               fix_cpos;
+                               seen_disp_event = TRUE;
+                           }
+                       }
+                       break;
+                     case 'm':       /* set graphics rendition */
+                       {
+                           /* 
+                            * A VT100 without the AVO only had one attribute, either
+                            * underline or reverse video depending on the cursor type,
+                            * this was selected by CSI 7m.
+                            *
+                            * case 2:
+                            *  This is DIM on the VT100-AVO and VT102
+                            * case 5:
+                            *  This is BLINK on the VT100-AVO and VT102+
+                            * case 8:
+                            *  This is INVIS on the VT100-AVO and VT102
+                            * case 21:
+                            *  This like 22 disables BOLD, DIM and INVIS
+                            *
+                            * The ANSI colours appear on any terminal that has colour
+                            * (obviously) but the interaction between sgr0 and the
+                            * colours varies but is usually related to the background
+                            * colour erase item.
+                            * The interaction between colour attributes and the mono
+                            * ones is also very implementation dependent.
+                            *
+                            * The 39 and 49 attributes are likely to be unimplemented.
+                            */
+                           int i;
+                           for (i = 0; i < esc_nargs; i++) {
+                               switch (def(esc_args[i], 0)) {
+                                 case 0:       /* restore defaults */
+                                   curr_attr = ATTR_DEFAULT;
+                                   break;
+                                 case 1:       /* enable bold */
+                                   compatibility(VT100AVO);
+                                   curr_attr |= ATTR_BOLD;
+                                   break;
+                                 case 21:      /* (enable double underline) */
+                                   compatibility(OTHER);
+                                 case 4:       /* enable underline */
+                                   compatibility(VT100AVO);
+                                   curr_attr |= ATTR_UNDER;
+                                   break;
+                                 case 5:       /* enable blink */
+                                   compatibility(VT100AVO);
+                                   curr_attr |= ATTR_BLINK;
+                                   break;
+                                 case 7:       /* enable reverse video */
+                                   curr_attr |= ATTR_REVERSE;
+                                   break;
+                                 case 22:      /* disable bold */
+                                   compatibility2(OTHER, VT220);
+                                   curr_attr &= ~ATTR_BOLD;
+                                   break;
+                                 case 24:      /* disable underline */
+                                   compatibility2(OTHER, VT220);
+                                   curr_attr &= ~ATTR_UNDER;
+                                   break;
+                                 case 25:      /* disable blink */
+                                   compatibility2(OTHER, VT220);
+                                   curr_attr &= ~ATTR_BLINK;
+                                   break;
+                                 case 27:      /* disable reverse video */
+                                   compatibility2(OTHER, VT220);
+                                   curr_attr &= ~ATTR_REVERSE;
+                                   break;
+                                 case 30:
+                                 case 31:
+                                 case 32:
+                                 case 33:
+                                 case 34:
+                                 case 35:
+                                 case 36:
+                                 case 37:
+                                   /* foreground */
+                                   curr_attr &= ~ATTR_FGMASK;
+                                   curr_attr |=
+                                       (esc_args[i] - 30) << ATTR_FGSHIFT;
+                                   break;
+                                 case 39:      /* default-foreground */
+                                   curr_attr &= ~ATTR_FGMASK;
+                                   curr_attr |= ATTR_DEFFG;
+                                   break;
+                                 case 40:
+                                 case 41:
+                                 case 42:
+                                 case 43:
+                                 case 44:
+                                 case 45:
+                                 case 46:
+                                 case 47:
+                                   /* background */
+                                   curr_attr &= ~ATTR_BGMASK;
+                                   curr_attr |=
+                                       (esc_args[i] - 40) << ATTR_BGSHIFT;
+                                   break;
+                                 case 49:      /* default-background */
+                                   curr_attr &= ~ATTR_BGMASK;
+                                   curr_attr |= ATTR_DEFBG;
+                                   break;
+                               }
+                           }
+                           if (use_bce)
+                               erase_char =
+                                   (' ' |
+                                    (curr_attr &
+                                     (ATTR_FGMASK | ATTR_BGMASK |
+                                      ATTR_BLINK)));
+                       }
+                       break;
+                     case 's':       /* save cursor */
+                       save_cursor(TRUE);
+                       break;
+                     case 'u':       /* restore cursor */
+                       save_cursor(FALSE);
+                       seen_disp_event = TRUE;
+                       break;
+                     case 't':       /* set page size - ie window height */
                        /*
-                        * I used to think the cursor should be
-                        * placed at the top of the newly marginned
-                        * area. Apparently not: VMS TPU falls over
-                        * if so.
+                        * VT340/VT420 sequence DECSLPP, DEC only allows values
+                        *  24/25/36/48/72/144 other emulators (eg dtterm) use
+                        * illegal values (eg first arg 1..9) for window changing 
+                        * and reports.
+                        */
+                       compatibility(VT340TEXT);
+                       if (esc_nargs <= 1
+                           && (esc_args[0] < 1 || esc_args[0] >= 24)) {
+                           request_resize(cols, def(esc_args[0], 24), 0);
+                           deselect();
+                       }
+                       break;
+                     case ANSI('|', '*'):
+                       /* VT420 sequence DECSNLS
+                        * Set number of lines on screen
+                        * VT420 uses VGA like hardware and can support any size in
+                        * reasonable range (24..49 AIUI) with no default specified.
+                        */
+                       compatibility(VT420);
+                       if (esc_nargs == 1 && esc_args[0] > 0) {
+                           request_resize(cols,
+                                          def(esc_args[0], cfg.height),
+                                          0);
+                           deselect();
+                       }
+                       break;
+                     case ANSI('|', '$'):
+                       /* VT340/VT420 sequence DECSCPP
+                        * Set number of columns per page
+                        * Docs imply range is only 80 or 132, but I'll allow any.
+                        */
+                       compatibility(VT340TEXT);
+                       if (esc_nargs <= 1) {
+                           request_resize(def(esc_args[0], cfg.width),
+                                          rows, 0);
+                           deselect();
+                       }
+                       break;
+                     case 'X':       /* write N spaces w/o moving cursor */
+                       /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
+                       compatibility(ANSIMIN);
+                       {
+                           int n = def(esc_args[0], 1);
+                           pos cursplus;
+                           unsigned long *p = cpos;
+                           if (n > cols - curs.x)
+                               n = cols - curs.x;
+                           cursplus = curs;
+                           cursplus.x += n;
+                           check_selection(curs, cursplus);
+                           while (n--)
+                               *p++ = erase_char;
+                           seen_disp_event = TRUE;
+                       }
+                       break;
+                     case 'x':       /* report terminal characteristics */
+                       compatibility(VT100);
+                       {
+                           char buf[32];
+                           int i = def(esc_args[0], 0);
+                           if (i == 0 || i == 1) {
+                               strcpy(buf, "\033[2;1;1;112;112;1;0x");
+                               buf[2] += i;
+                               ldisc_send(buf, 20);
+                           }
+                       }
+                       break;
+                     case ANSI('L', '='):
+                       compatibility(OTHER);
+                       use_bce = (esc_args[0] <= 0);
+                       erase_char = ERASE_CHAR;
+                       if (use_bce)
+                           erase_char =
+                               (' ' |
+                                (curr_attr &
+                                 (ATTR_FGMASK | ATTR_BGMASK)));
+                       break;
+                     case ANSI('E', '='):
+                       compatibility(OTHER);
+                       blink_is_real = (esc_args[0] >= 1);
+                       break;
+                     case ANSI('p', '"'):
+                       /* Allow the host to make this emulator a 'perfect' VT102.
+                        * This first appeared in the VT220, but we do need to get 
+                        * back to PuTTY mode so I won't check it.
                         *
-                        * Well actually it should for Origin mode - RDB
+                        * The arg in 40..42 are a PuTTY extension.
+                        * The 2nd arg, 8bit vs 7bit is not checked.
+                        *
+                        * Setting VT102 mode should also change the Fkeys to
+                        * generate PF* codes as a real VT102 has no Fkeys.
+                        * The VT220 does this, F11..F13 become ESC,BS,LF other Fkeys
+                        * send nothing.
+                        *
+                        * Note ESC c will NOT change this!
                         */
-                       curs.y = (dec_om ? marg_t : 0);
-                       fix_cpos;
-                       seen_disp_event = TRUE;
-                   }
-               }
-               break;
-             case 'm':                /* set graphics rendition */
-               {
-                   /* 
-                    * A VT100 without the AVO only had one attribute, either
-                    * underline or reverse video depending on the cursor type,
-                    * this was selected by CSI 7m.
-                    *
-                    * case 2:
-                    *  This is DIM on the VT100-AVO and VT102
-                    * case 5:
-                    *  This is BLINK on the VT100-AVO and VT102+
-                    * case 8:
-                    *  This is INVIS on the VT100-AVO and VT102
-                    * case 21:
-                    *  This like 22 disables BOLD, DIM and INVIS
-                    *
-                    * The ANSI colours appear on any terminal that has colour
-                    * (obviously) but the interaction between sgr0 and the
-                    * colours varies but is usually related to the background
-                    * colour erase item.
-                    * The interaction between colour attributes and the mono
-                    * ones is also very implementation dependent.
-                    *
-                    * The 39 and 49 attributes are likely to be unimplemented.
-                    */
-                   int i;
-                   for (i=0; i<esc_nargs; i++) {
-                       switch (def(esc_args[i], 0)) {
-                         case 0:      /* restore defaults */
-                           curr_attr = ATTR_DEFAULT; break;
-                         case 1:      /* enable bold */
-                           compatibility(VT100AVO);
-                           curr_attr |= ATTR_BOLD; break;
-                         case 21:     /* (enable double underline) */
-                           compatibility(OTHER);
-                         case 4:      /* enable underline */
-                           compatibility(VT100AVO);
-                           curr_attr |= ATTR_UNDER; break;
-                         case 5:      /* enable blink */
-                           compatibility(VT100AVO);
-                           curr_attr |= ATTR_BLINK; break;
-                         case 7:      /* enable reverse video */
-                           curr_attr |= ATTR_REVERSE; break;
-                         case 22:     /* disable bold */
-                           compatibility2(OTHER,VT220);
-                           curr_attr &= ~ATTR_BOLD; break;
-                         case 24:     /* disable underline */
-                           compatibility2(OTHER,VT220);
-                           curr_attr &= ~ATTR_UNDER; break;
-                         case 25:     /* disable blink */
-                           compatibility2(OTHER,VT220);
-                           curr_attr &= ~ATTR_BLINK; break;
-                         case 27:     /* disable reverse video */
-                           compatibility2(OTHER,VT220);
-                           curr_attr &= ~ATTR_REVERSE; break;
-                         case 30: case 31: case 32: case 33:
-                         case 34: case 35: case 36: case 37:
-                           /* foreground */
-                           curr_attr &= ~ATTR_FGMASK;
-                           curr_attr |= (esc_args[i] - 30) << ATTR_FGSHIFT;
+
+                       switch (esc_args[0]) {
+                         case 61:
+                           compatibility_level &= ~TM_VTXXX;
+                           compatibility_level |= TM_VT102;
                            break;
-                         case 39:     /* default-foreground */
-                           curr_attr &= ~ATTR_FGMASK;
-                           curr_attr |= ATTR_DEFFG;
+                         case 62:
+                           compatibility_level &= ~TM_VTXXX;
+                           compatibility_level |= TM_VT220;
+                           break;
+
+                         default:
+                           if (esc_args[0] > 60 && esc_args[0] < 70)
+                               compatibility_level |= TM_VTXXX;
+                           break;
+
+                         case 40:
+                           compatibility_level &= TM_VTXXX;
                            break;
-                         case 40: case 41: case 42: case 43:
-                         case 44: case 45: case 46: case 47:
-                           /* background */
-                           curr_attr &= ~ATTR_BGMASK;
-                           curr_attr |= (esc_args[i] - 40) << ATTR_BGSHIFT;
+                         case 41:
+                           compatibility_level = TM_PUTTY;
                            break;
-                         case 49:     /* default-background */
-                           curr_attr &= ~ATTR_BGMASK;
-                           curr_attr |= ATTR_DEFBG;
+                         case 42:
+                           compatibility_level = TM_SCOANSI;
                            break;
+
+                         case ARG_DEFAULT:
+                           compatibility_level = TM_PUTTY;
+                           break;
+                         case 50:
+                           break;
+                       }
+
+                       /* Change the response to CSI c */
+                       if (esc_args[0] == 50) {
+                           int i;
+                           char lbuf[64];
+                           strcpy(id_string, "\033[?");
+                           for (i = 1; i < esc_nargs; i++) {
+                               if (i != 1)
+                                   strcat(id_string, ";");
+                               sprintf(lbuf, "%d", esc_args[i]);
+                               strcat(id_string, lbuf);
+                           }
+                           strcat(id_string, "c");
+                       }
+#if 0
+                       /* Is this a good idea ? 
+                        * Well we should do a soft reset at this point ...
+                        */
+                       if (!has_compat(VT420) && has_compat(VT100)) {
+                           if (reset_132)
+                               request_resize(132, 24, 1);
+                           else
+                               request_resize(80, 24, 1);
                        }
+#endif
+                       break;
                    }
-                   if (use_bce) 
-                      erase_char = 
-                           (' '|
-                             (curr_attr&(ATTR_FGMASK|ATTR_BGMASK|ATTR_BLINK))
-                           );
-               }
-               break;
-             case 's':                /* save cursor */
-               save_cursor (TRUE);
                break;
-             case 'u':                /* restore cursor */
-               save_cursor (FALSE);
-               seen_disp_event = TRUE;
-               break;
-             case 't':                /* set page size - ie window height */
-               /*
-                * VT340/VT420 sequence DECSLPP, DEC only allows values
-                *  24/25/36/48/72/144 other emulators (eg dtterm) use
-                * illegal values (eg first arg 1..9) for window changing 
-                * and reports.
-                */
-               compatibility(VT340TEXT);
-               if (esc_nargs<=1 && (esc_args[0]<1 || esc_args[0]>=24)) {
-                   request_resize (cols, def(esc_args[0], 24), 0);
-                   deselect();
+             case SET_GL:
+             case SET_GR:
+               /* VT100 only here, checked above */
+               switch (c) {
+                 case 'A':
+                   cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
+                   break;
+                 case '0':
+                   cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
+                   break;
+                 case 'B':
+                 default:             /* specifically, 'B' */
+                   cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
+                   break;
                }
+               if (!has_compat(VT220) || c != '%')
+                   termstate = TOPLEVEL;
                break;
-             case ANSI('|', '*'):
-               /* VT420 sequence DECSNLS
-                * Set number of lines on screen
-                * VT420 uses VGA like hardware and can support any size in
-                * reasonable range (24..49 AIUI) with no default specified.
-                */
-               compatibility(VT420);
-               if (esc_nargs==1 && esc_args[0]>0) {
-                   request_resize (cols, def(esc_args[0], cfg.height), 0);
-                   deselect();
+             case SEEN_OSC:
+               osc_w = FALSE;
+               switch (c) {
+                 case 'P':            /* Linux palette sequence */
+                   termstate = SEEN_OSC_P;
+                   osc_strlen = 0;
+                   break;
+                 case 'R':            /* Linux palette reset */
+                   palette_reset();
+                   term_invalidate();
+                   termstate = TOPLEVEL;
+                   break;
+                 case 'W':            /* word-set */
+                   termstate = SEEN_OSC_W;
+                   osc_w = TRUE;
+                   break;
+                 case '0':
+                 case '1':
+                 case '2':
+                 case '3':
+                 case '4':
+                 case '5':
+                 case '6':
+                 case '7':
+                 case '8':
+                 case '9':
+                   esc_args[0] = 10 * esc_args[0] + c - '0';
+                   break;
+                 case 'L':
+                   /*
+                    * Grotty hack to support xterm and DECterm title
+                    * sequences concurrently.
+                    */
+                   if (esc_args[0] == 2) {
+                       esc_args[0] = 1;
+                       break;
+                   }
+                   /* else fall through */
+                 default:
+                   termstate = OSC_STRING;
+                   osc_strlen = 0;
                }
                break;
-             case ANSI('|', '$'):
-               /* VT340/VT420 sequence DECSCPP
-                * Set number of columns per page
-                * Docs imply range is only 80 or 132, but I'll allow any.
+             case OSC_STRING:
+               /*
+                * This OSC stuff is EVIL. It takes just one character to get into
+                * sysline mode and it's not initially obvious how to get out.
+                * So I've added CR and LF as string aborts.
+                * This shouldn't effect compatibility as I believe embedded 
+                * control characters are supposed to be interpreted (maybe?) 
+                * and they don't display anything useful anyway.
+                *
+                * -- RDB
                 */
-               compatibility(VT340TEXT);
-               if (esc_nargs<=1) {
-                   request_resize (def(esc_args[0], cfg.width), rows, 0);
-                   deselect();
-               }
-               break;
-             case 'X':                /* write N spaces w/o moving cursor */
-               /* XXX VTTEST says this is vt220, vt510 manual says vt100 */
-               compatibility(ANSIMIN);
-               {
-                   int n = def(esc_args[0], 1);
-                   pos cursplus;
-                   unsigned long *p = cpos;
-                   if (n > cols - curs.x)
-                       n = cols - curs.x;
-                   cursplus = curs;
-                   cursplus.x += n;
-                   check_selection (curs, cursplus);
-                   while (n--)
-                       *p++ = erase_char;
-                   seen_disp_event = TRUE;
-               }
+               if (c == '\n' || c == '\r') {
+                   termstate = TOPLEVEL;
+               } else if (c == 0234 || c == '\007') {
+                   /*
+                    * These characters terminate the string; ST and BEL
+                    * terminate the sequence and trigger instant
+                    * processing of it, whereas ESC goes back to SEEN_ESC
+                    * mode unless it is followed by \, in which case it is
+                    * synonymous with ST in the first place.
+                    */
+                   do_osc();
+                   termstate = TOPLEVEL;
+               } else if (c == '\033')
+                   termstate = OSC_MAYBE_ST;
+               else if (osc_strlen < OSC_STR_MAX)
+                   osc_string[osc_strlen++] = c;
                break;
-             case 'x':                /* report terminal characteristics */
-               compatibility(VT100);
+             case SEEN_OSC_P:
                {
-                   char buf[32];
-                   int i = def(esc_args[0], 0);
-                   if (i == 0 || i == 1) {
-                       strcpy (buf, "\033[2;1;1;112;112;1;0x");
-                       buf[2] += i;
-                       ldisc_send (buf, 20);
+                   int max = (osc_strlen == 0 ? 21 : 16);
+                   int val;
+                   if (c >= '0' && c <= '9')
+                       val = c - '0';
+                   else if (c >= 'A' && c <= 'A' + max - 10)
+                       val = c - 'A' + 10;
+                   else if (c >= 'a' && c <= 'a' + max - 10)
+                       val = c - 'a' + 10;
+                   else
+                       termstate = TOPLEVEL;
+                   osc_string[osc_strlen++] = val;
+                   if (osc_strlen >= 7) {
+                       palette_set(osc_string[0],
+                                   osc_string[1] * 16 + osc_string[2],
+                                   osc_string[3] * 16 + osc_string[4],
+                                   osc_string[5] * 16 + osc_string[6]);
+                       term_invalidate();
+                       termstate = TOPLEVEL;
                    }
                }
                break;
-             case ANSI('L','='):
-               compatibility(OTHER);
-               use_bce = (esc_args[0]<=0);
-               erase_char = ERASE_CHAR;
-               if (use_bce)
-                   erase_char = (' '|(curr_attr&(ATTR_FGMASK|ATTR_BGMASK)));
-               break;
-             case ANSI('E','='):
-               compatibility(OTHER);
-               blink_is_real = (esc_args[0]>=1);
-               break;
-             case ANSI('p','"'):
-               /* Allow the host to make this emulator a 'perfect' VT102.
-                * This first appeared in the VT220, but we do need to get 
-                * back to PuTTY mode so I won't check it.
-                *
-                * The arg in 40..42 are a PuTTY extension.
-                * The 2nd arg, 8bit vs 7bit is not checked.
-                *
-                * Setting VT102 mode should also change the Fkeys to
-                * generate PF* codes as a real VT102 has no Fkeys.
-                * The VT220 does this, F11..F13 become ESC,BS,LF other Fkeys
-                * send nothing.
-                *
-                * Note ESC c will NOT change this!
-                */
-
-               switch (esc_args[0]) {
-               case 61: compatibility_level &= ~TM_VTXXX;
-                        compatibility_level |=  TM_VT102;      break;
-               case 62: compatibility_level &= ~TM_VTXXX;
-                        compatibility_level |=  TM_VT220;      break;
-
-               default: if( esc_args[0] > 60 && esc_args[0] < 70 )
-                           compatibility_level |= TM_VTXXX;    
-                        break;
-
-               case 40: compatibility_level &=  TM_VTXXX;      break;
-               case 41: compatibility_level  =  TM_PUTTY;      break;
-               case 42: compatibility_level  =  TM_SCOANSI;    break;
-
-               case ARG_DEFAULT: 
-                        compatibility_level  =  TM_PUTTY;      break;
-               case 50: break;
-               }
-
-               /* Change the response to CSI c */
-               if (esc_args[0] == 50) {
-                  int i;
-                  char lbuf[64];
-                  strcpy(id_string, "\033[?");
-                  for (i=1; i<esc_nargs; i++) {
-                     if (i!=1) strcat(id_string, ";");
-                     sprintf(lbuf, "%d", esc_args[i]);
-                     strcat(id_string, lbuf);
-                  }
-                  strcat(id_string, "c");
+             case SEEN_OSC_W:
+               switch (c) {
+                 case '0':
+                 case '1':
+                 case '2':
+                 case '3':
+                 case '4':
+                 case '5':
+                 case '6':
+                 case '7':
+                 case '8':
+                 case '9':
+                   esc_args[0] = 10 * esc_args[0] + c - '0';
+                   break;
+                 default:
+                   termstate = OSC_STRING;
+                   osc_strlen = 0;
                }
+               break;
+             case SEEN_ESCHASH:
+               {
+                   unsigned long nlattr;
+                   unsigned long *ldata;
+                   int i, j;
+                   pos scrtop, scrbot;
+
+                   switch (c) {
+                     case '8':
+                       for (i = 0; i < rows; i++) {
+                           ldata = lineptr(i);
+                           for (j = 0; j < cols; j++)
+                               ldata[j] = ATTR_DEFAULT | 'E';
+                           ldata[cols] = 0;
+                       }
+                       disptop = 0;
+                       seen_disp_event = TRUE;
+                       scrtop.x = scrtop.y = 0;
+                       scrbot.x = 0;
+                       scrbot.y = rows;
+                       check_selection(scrtop, scrbot);
+                       break;
+
+                     case '3':
+                     case '4':
+                     case '5':
+                     case '6':
+                       switch (c) {
+                         case '3':
+                           nlattr = LATTR_TOP;
+                           break;
+                         case '4':
+                           nlattr = LATTR_BOT;
+                           break;
+                         case '5':
+                           nlattr = LATTR_NORM;
+                           break;
+                         case '6':
+                           nlattr = LATTR_WIDE;
+                           break;
+                       }
 
-#if 0
-               /* Is this a good idea ? 
-                * Well we should do a soft reset at this point ...
-                */
-               if (!has_compat(VT420) && has_compat(VT100)) {
-                   if (reset_132) request_resize (132, 24, 1);
-                   else           request_resize ( 80, 24, 1);
+                       ldata = lineptr(curs.y);
+                       ldata[cols] &= ~LATTR_MODE;
+                       ldata[cols] |= nlattr;
+                   }
                }
-#endif
-               break;
-           }
-           break;
-         case SET_GL:
-         case SET_GR:
-           /* VT100 only here, checked above */
-           switch (c) {
-             case 'A':
-               cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_GBCHR;
-               break;
-             case '0':
-               cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_LINEDRW;
-               break;
-             case 'B':
-             default:                 /* specifically, 'B' */
-               cset_attr[termstate == SET_GL ? 0 : 1] = ATTR_ASCII;
-               break;
-           }
-           if( !has_compat(VT220) || c != '%' )
-               termstate = TOPLEVEL;
-           break;
-         case SEEN_OSC:
-           osc_w = FALSE;
-           switch (c) {
-             case 'P':                /* Linux palette sequence */
-               termstate = SEEN_OSC_P;
-               osc_strlen = 0;
-               break;
-             case 'R':                /* Linux palette reset */
-               palette_reset();
-               term_invalidate();
                termstate = TOPLEVEL;
                break;
-             case 'W':                /* word-set */
-               termstate = SEEN_OSC_W;
-               osc_w = TRUE;
-               break;
-             case '0': case '1': case '2': case '3': case '4':
-             case '5': case '6': case '7': case '8': case '9':
-               esc_args[0] = 10 * esc_args[0] + c - '0';
-               break;
-             case 'L':
-               /*
-                * Grotty hack to support xterm and DECterm title
-                * sequences concurrently.
-                */
-               if (esc_args[0] == 2) {
-                   esc_args[0] = 1;
-                   break;
-               }
-               /* else fall through */
-             default:
-               termstate = OSC_STRING;
-               osc_strlen = 0;
-           }
-           break;
-         case OSC_STRING:
-           /*
-            * This OSC stuff is EVIL. It takes just one character to get into
-            * sysline mode and it's not initially obvious how to get out.
-            * So I've added CR and LF as string aborts.
-            * This shouldn't effect compatibility as I believe embedded 
-            * control characters are supposed to be interpreted (maybe?) 
-            * and they don't display anything useful anyway.
-            *
-            * -- RDB
-            */
-           if (c == '\n' || c == '\r') {
-               termstate = TOPLEVEL;
-           } else if (c == 0234 || c == '\007' ) {
-               /*
-                * These characters terminate the string; ST and BEL
-                * terminate the sequence and trigger instant
-                * processing of it, whereas ESC goes back to SEEN_ESC
-                * mode unless it is followed by \, in which case it is
-                * synonymous with ST in the first place.
-                */
-               do_osc();
+             case VT52_ESC:
                termstate = TOPLEVEL;
-           } else if (c == '\033')
-                   termstate = OSC_MAYBE_ST;
-           else if (osc_strlen < OSC_STR_MAX)
-               osc_string[osc_strlen++] = c;
-           break;
-         case SEEN_OSC_P:
-           {
-               int max = (osc_strlen == 0 ? 21 : 16);
-               int val;
-               if (c >= '0' && c <= '9')
-                   val = c - '0';
-               else if (c >= 'A' && c <= 'A'+max-10)
-                   val = c - 'A' + 10;
-               else if (c >= 'a' && c <= 'a'+max-10)
-                   val = c - 'a' + 10;
-               else
-                   termstate = TOPLEVEL;
-               osc_string[osc_strlen++] = val;
-               if (osc_strlen >= 7) {
-                   palette_set (osc_string[0],
-                                osc_string[1] * 16 + osc_string[2],
-                                osc_string[3] * 16 + osc_string[4],
-                                osc_string[5] * 16 + osc_string[6]);
-                   term_invalidate();
-                   termstate = TOPLEVEL;
-               }
-           }
-           break;
-         case SEEN_OSC_W:
-           switch (c) {
-             case '0': case '1': case '2': case '3': case '4':
-             case '5': case '6': case '7': case '8': case '9':
-               esc_args[0] = 10 * esc_args[0] + c - '0';
-               break;
-             default:
-               termstate = OSC_STRING;
-               osc_strlen = 0;
-           }
-           break;
-         case SEEN_ESCHASH:
-           {
-               unsigned long nlattr;
-               unsigned long *ldata;
-               int i, j;
-               pos scrtop, scrbot;
-
+               seen_disp_event = TRUE;
                switch (c) {
-               case '8':
-                   for (i = 0; i < rows; i++) {
-                       ldata = lineptr(i);
-                       for (j = 0; j < cols; j++)
-                           ldata[j] = ATTR_DEFAULT | 'E';
-                       ldata[cols] = 0;
-                   }
+                 case 'A':
+                   move(curs.x, curs.y - 1, 1);
+                   break;
+                 case 'B':
+                   move(curs.x, curs.y + 1, 1);
+                   break;
+                 case 'C':
+                   move(curs.x + 1, curs.y, 1);
+                   break;
+                 case 'D':
+                   move(curs.x - 1, curs.y, 1);
+                   break;
+                 case 'F':
+                   cset_attr[cset = 0] = ATTR_LINEDRW;
+                   break;
+                 case 'G':
+                   cset_attr[cset = 0] = ATTR_ASCII;
+                   break;
+                 case 'H':
+                   move(0, 0, 0);
+                   break;
+                 case 'I':
+                   if (curs.y == 0)
+                       scroll(0, rows - 1, -1, TRUE);
+                   else if (curs.y > 0)
+                       curs.y--;
+                   fix_cpos;
+                   wrapnext = FALSE;
+                   break;
+                 case 'J':
+                   erase_lots(FALSE, FALSE, TRUE);
                    disptop = 0;
-                   seen_disp_event = TRUE;
-                   scrtop.x = scrtop.y = 0;
-                   scrbot.x = 0; scrbot.y = rows;
-                   check_selection (scrtop, scrbot);
                    break;
-
-               case '3': nlattr = LATTR_TOP; goto lattr_common;
-               case '4': nlattr = LATTR_BOT; goto lattr_common;
-               case '5': nlattr = LATTR_NORM; goto lattr_common;
-               case '6': nlattr = LATTR_WIDE;
-                   lattr_common:
-
-                   ldata = lineptr(curs.y);
-                   ldata[cols] &= ~LATTR_MODE;
-                   ldata[cols] |=  nlattr;
+                 case 'K':
+                   erase_lots(TRUE, FALSE, TRUE);
+                   break;
+                 case 'V':
+                   /* XXX Print cursor line */
+                   break;
+                 case 'W':
+                   /* XXX Start controller mode */
+                   break;
+                 case 'X':
+                   /* XXX Stop controller mode */
+                   break;
+                 case 'Y':
+                   termstate = VT52_Y1;
+                   break;
+                 case 'Z':
+                   ldisc_send("\033/Z", 3);
+                   break;
+                 case '=':
+                   app_keypad_keys = TRUE;
+                   break;
+                 case '>':
+                   app_keypad_keys = FALSE;
+                   break;
+                 case '<':
+                   /* XXX This should switch to VT100 mode not current or default
+                    *     VT mode. But this will only have effect in a VT220+
+                    *     emulation.
+                    */
+                   vt52_mode = FALSE;
+                   break;
+                 case '^':
+                   /* XXX Enter auto print mode */
+                   break;
+                 case '_':
+                   /* XXX Exit auto print mode */
+                   break;
+                 case ']':
+                   /* XXX Print screen */
+                   break;
                }
-           }
-           termstate = TOPLEVEL;
-           break;
-         case VT52_ESC:
-           termstate = TOPLEVEL;
-           seen_disp_event = TRUE;
-           switch (c) {
-             case 'A':
-               move (curs.x, curs.y - 1, 1);
-               break;
-             case 'B':
-               move (curs.x, curs.y + 1, 1);
-               break;
-             case 'C':
-               move (curs.x + 1, curs.y, 1);
-               break;
-             case 'D':
-               move (curs.x - 1, curs.y, 1);
-               break;
-             case 'F':
-               cset_attr[cset=0] = ATTR_LINEDRW;
-               break;
-             case 'G':
-               cset_attr[cset=0] = ATTR_ASCII;
-               break;
-             case 'H':
-               move (0, 0, 0);
-               break;
-             case 'I':
-               if (curs.y == 0)
-                   scroll (0, rows-1, -1, TRUE);
-               else if (curs.y > 0)
-                   curs.y--;
-               fix_cpos;
-               wrapnext = FALSE;
-               break;
-             case 'J':
-               erase_lots(FALSE, FALSE, TRUE);
-               disptop = 0;
                break;
-             case 'K':
-               erase_lots(TRUE, FALSE, TRUE);
+             case VT52_Y1:
+               termstate = VT52_Y2;
+               move(curs.x, c - ' ', 0);
                break;
-             case 'V':
-               /* XXX Print cursor line */
-               break;
-             case 'W':
-               /* XXX Start controller mode */
-               break;
-             case 'X':
-               /* XXX Stop controller mode */
-               break;
-             case 'Y':
-               termstate = VT52_Y1;
-               break;
-             case 'Z':
-               ldisc_send ("\033/Z", 3);
-               break;
-             case '=':
-               app_keypad_keys = TRUE;
-               break;
-             case '>':
-               app_keypad_keys = FALSE;
-               break;
-             case '<':
-               /* XXX This should switch to VT100 mode not current or default
-                *     VT mode. But this will only have effect in a VT220+
-                *     emulation.
-                */
-               vt52_mode = FALSE;
-               break;
-             case '^':
-               /* XXX Enter auto print mode */
-               break;
-             case '_':
-               /* XXX Exit auto print mode */
-               break;
-             case ']':
-               /* XXX Print screen */
+             case VT52_Y2:
+               termstate = TOPLEVEL;
+               move(c - ' ', curs.y, 0);
                break;
            }
-           break;
-         case VT52_Y1:
-           termstate = VT52_Y2;
-           move(curs.x, c-' ', 0);
-           break;
-         case VT52_Y2:
-           termstate = TOPLEVEL;
-           move(c-' ', curs.y, 0);
-           break;
-       }
        if (selstate != NO_SELECTION) {
            pos cursplus = curs;
            incpos(cursplus);
-           check_selection (curs, cursplus);
+           check_selection(curs, cursplus);
        }
     }
     inbuf_head = 0;
@@ -1911,10 +2041,11 @@ void term_out(void) {
  * alike to scroll-optimise one to the other. Return the degree of
  * similarity.
  */
-static int linecmp (unsigned long *a, unsigned long *b) {
+static int linecmp(unsigned long *a, unsigned long *b)
+{
     int i, n;
 
-    for (i=n=0; i < cols; i++)
+    for (i = n = 0; i < cols; i++)
        n += (*a++ == *b++);
     return n;
 }
@@ -1923,7 +2054,8 @@ static int linecmp (unsigned long *a, unsigned long *b) {
  * Given a context, update the window. Out of paranoia, we don't
  * allow WM_PAINT responses to do scrolling optimisations.
  */
-static void do_paint (Context ctx, int may_optimise) {
+static void do_paint(Context ctx, int may_optimise)
+{
     int i, j, start, our_curs_y;
     unsigned long attr, rv, cursor;
     pos scrpos;
@@ -1946,41 +2078,39 @@ static void do_paint (Context ctx, int may_optimise) {
      * curs.y, curs.x, blinker, cfg.blink_cur, cursor_on, has_focus
      */
     if (cursor_on) {
-        if (has_focus) {
+       if (has_focus) {
            if (blinker || !cfg.blink_cur)
-                cursor = ATTR_ACTCURS;
-            else
-                cursor = 0;
-        }
-        else
-            cursor = ATTR_PASCURS;
+               cursor = ATTR_ACTCURS;
+           else
+               cursor = 0;
+       } else
+           cursor = ATTR_PASCURS;
        if (wrapnext)
            cursor |= ATTR_RIGHTCURS;
-    }
-    else
+    } else
        cursor = 0;
     rv = (!rvideo ^ !in_vbell ? ATTR_REVERSE : 0);
     our_curs_y = curs.y - disptop;
 
-    for (i=0; i<rows; i++) {
+    for (i = 0; i < rows; i++) {
        unsigned long *ldata;
        int lattr;
        scrpos.y = i + disptop;
        ldata = lineptr(scrpos.y);
        lattr = (ldata[cols] & LATTR_MODE);
-       for (j=0; j<=cols; j++) {
+       for (j = 0; j <= cols; j++) {
            unsigned long d = ldata[j];
-           int idx = i*(cols+1)+j;
+           int idx = i * (cols + 1) + j;
            scrpos.x = j;
-           
-           wanttext[idx] = lattr | (((d &ATTR_WRAPPED) ^ rv
+
+           wanttext[idx] = lattr | (((d & ~ATTR_WRAPPED) ^ rv
                                      ^ (posle(selstart, scrpos) &&
                                         poslt(scrpos, selend) ?
                                         ATTR_REVERSE : 0)) |
-                                    (i==our_curs_y && j==curs.x ? cursor : 0));
+                                    (i == our_curs_y
+                                     && j == curs.x ? cursor : 0));
            if (blink_is_real) {
-               if (has_focus && tblinker && (wanttext[idx]&ATTR_BLINK) )
-               {
+               if (has_focus && tblinker && (wanttext[idx] & ATTR_BLINK)) {
                    wanttext[idx] &= ATTR_MASK;
                    wanttext[idx] += ' ';
                }
@@ -1996,18 +2126,18 @@ static void do_paint (Context ctx, int may_optimise) {
      * We'll leave it well alone...
      */
 
-    for (i=0; i<rows; i++) {
-       int idx = i*(cols+1);
-       int lattr = (wanttext[idx+cols] & LATTR_MODE);
+    for (i = 0; i < rows; i++) {
+       int idx = i * (cols + 1);
+       int lattr = (wanttext[idx + cols] & LATTR_MODE);
        start = -1;
-       for (j=0; j<=cols; j++,idx++) {
+       for (j = 0; j <= cols; j++, idx++) {
            unsigned long t = wanttext[idx];
            int needs_update = (j < cols && t != disptext[idx]);
            int keep_going = (start != -1 && needs_update &&
                              (t & ATTR_MASK) == attr &&
-                             j-start < sizeof(ch));
+                             j - start < sizeof(ch));
            if (start != -1 && !keep_going) {
-               do_text (ctx, start, i, ch, j-start, attr, lattr);
+               do_text(ctx, start, i, ch, j - start, attr, lattr);
                start = -1;
            }
            if (needs_update) {
@@ -2015,7 +2145,7 @@ static void do_paint (Context ctx, int may_optimise) {
                    start = j;
                    attr = t & ATTR_MASK;
                }
-               ch[j-start] = (char) (t & CHAR_MASK);
+               ch[j - start] = (char) (t & CHAR_MASK);
            }
            disptext[idx] = t;
        }
@@ -2026,33 +2156,33 @@ static void do_paint (Context ctx, int may_optimise) {
  * Flick the switch that says if blinking things should be shown or hidden.
  */
 
-void term_blink(int flg) {
+void term_blink(int flg)
+{
     static long last_blink = 0;
     static long last_tblink = 0;
     long now, blink_diff;
 
     now = GetTickCount();
-    blink_diff = now-last_tblink;
+    blink_diff = now - last_tblink;
 
     /* Make sure the text blinks no more than 2Hz */
-    if (blink_diff<0 || blink_diff>450)
-    {
-        last_tblink = now;
+    if (blink_diff < 0 || blink_diff > 450) {
+       last_tblink = now;
        tblinker = !tblinker;
     }
 
     if (flg) {
-        blinker = 1;
-        last_blink = now;
+       blinker = 1;
+       last_blink = now;
        return;
-    } 
+    }
 
-    blink_diff = now-last_blink;
+    blink_diff = now - last_blink;
 
     /* Make sure the cursor blinks no faster than GetCaretBlinkTime() */
-    if (blink_diff>=0 && blink_diff<(long)GetCaretBlinkTime())
-       return;
+    if (blink_diff >= 0 && blink_diff < (long) GetCaretBlinkTime())
+       return;
+
     last_blink = now;
     blinker = !blinker;
 }
@@ -2060,38 +2190,39 @@ void term_blink(int flg) {
 /*
  * Invalidate the whole screen so it will be repainted in full.
  */
-void term_invalidate(void) {
+void term_invalidate(void)
+{
     int i;
 
-    for (i=0; i<rows*(cols+1); i++)
+    for (i = 0; i < rows * (cols + 1); i++)
        disptext[i] = ATTR_INVALID;
 }
 
 /*
  * Paint the window in response to a WM_PAINT message.
  */
-void term_paint (Context ctx, int l, int t, int r, int b) {
+void term_paint(Context ctx, int l, int t, int r, int b)
+{
     int i, j, left, top, right, bottom;
 
     left = l / font_width;
     right = (r - 1) / font_width;
     top = t / font_height;
     bottom = (b - 1) / font_height;
-    for (i = top; i <= bottom && i < rows ; i++)
-    {
-       if ( (disptext[i*(cols+1)+cols]&LATTR_MODE) == LATTR_NORM)
-           for (j = left; j <= right && j < cols ; j++)
-               disptext[i*(cols+1)+j] = ATTR_INVALID;
+    for (i = top; i <= bottom && i < rows; i++) {
+       if ((disptext[i * (cols + 1) + cols] & LATTR_MODE) == LATTR_NORM)
+           for (j = left; j <= right && j < cols; j++)
+               disptext[i * (cols + 1) + j] = ATTR_INVALID;
        else
-           for (j = left/2; j <= right/2+1 && j < cols ; j++)
-               disptext[i*(cols+1)+j] = ATTR_INVALID;
+           for (j = left / 2; j <= right / 2 + 1 && j < cols; j++)
+               disptext[i * (cols + 1) + j] = ATTR_INVALID;
     }
 
     /* This should happen soon enough, also for some reason it sometimes 
      * fails to actually do anything when re-sizing ... painting the wrong
      * window perhaps ?
-    do_paint (ctx, FALSE);
-    */
+     do_paint (ctx, FALSE);
+     */
 }
 
 /*
@@ -2101,11 +2232,11 @@ void term_paint (Context ctx, int l, int t, int r, int b) {
  * to denote it is relative to the end, and 0 to denote that it is
  * relative to the current position.
  */
-void term_scroll (int rel, int where) {
+void term_scroll(int rel, int where)
+{
     int sbtop = -count234(scrollback);
 
-    disptop = (rel < 0 ? 0 :
-              rel > 0 ? sbtop : disptop) + where;
+    disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : disptop) + where;
     if (disptop < sbtop)
        disptop = sbtop;
     if (disptop > 0)
@@ -2114,17 +2245,17 @@ void term_scroll (int rel, int where) {
     term_update();
 }
 
-static void clipme(pos top, pos bottom, char *workbuf) {
-    char *wbptr;               /* where next char goes within workbuf */
-    int wblen = 0;             /* workbuf len */
-    int buflen;                        /* amount of memory allocated to workbuf */
+static void clipme(pos top, pos bottom, char *workbuf)
+{
+    char *wbptr;                      /* where next char goes within workbuf */
+    int wblen = 0;                    /* workbuf len */
+    int buflen;                               /* amount of memory allocated to workbuf */
 
-    if ( workbuf != NULL ) {   /* user supplied buffer? */
-       buflen = -1;            /* assume buffer passed in is big enough */
-       wbptr = workbuf;        /* start filling here */
-    }
-    else
-       buflen = 0;             /* No data is available yet */
+    if (workbuf != NULL) {            /* user supplied buffer? */
+       buflen = -1;                   /* assume buffer passed in is big enough */
+       wbptr = workbuf;               /* start filling here */
+    } else
+       buflen = 0;                    /* No data is available yet */
 
     while (poslt(top, bottom)) {
        int nl = FALSE;
@@ -2135,8 +2266,8 @@ static void clipme(pos top, pos bottom, char *workbuf) {
        nlpos.x = cols;
 
        if (!(ldata[cols] & ATTR_WRAPPED)) {
-           while ((ldata[nlpos.x-1] & CHAR_MASK) == 0x20 && poslt(top, nlpos))
-               decpos(nlpos);
+           while ((ldata[nlpos.x - 1] & CHAR_MASK) == 0x20
+                  && poslt(top, nlpos)) decpos(nlpos);
            if (poslt(nlpos, bottom))
                nl = TRUE;
        }
@@ -2146,63 +2277,62 @@ static void clipme(pos top, pos bottom, char *workbuf) {
 
            /* VT Specials -> ISO8859-1 for Cut&Paste */
            static const unsigned char poorman2[] =
-"* # HTFFCRLF\xB0 \xB1 NLVT+ + + + + - - - - - + + + + | <=>=PI!=\xA3 \xB7 ";
+               "* # HTFFCRLF\xB0 \xB1 NLVT+ + + + + - - - - - + + + + | <=>=PI!=\xA3 \xB7 ";
 
            if (set && !cfg.rawcnp) {
-               if (set == ATTR_LINEDRW && ch >= 0x60 && ch < 0x7F) {
+               if (set == ATTR_LINEDRW && ch >= 0x60 && ch < 0x7F) {
                    int x;
-                   if ((x = poorman2[2*(ch-0x60)+1]) == ' ')
-                       x = 0;
-                   ch = (x<<8) + poorman2[2*(ch-0x60)];
-               }
+                   if ((x = poorman2[2 * (ch - 0x60) + 1]) == ' ')
+                       x = 0;
+                   ch = (x << 8) + poorman2[2 * (ch - 0x60)];
+               }
            }
 
-           while(ch != 0) {
-               if (cfg.rawcnp || !!(ch&0xE0)) {
-                   if ( wblen == buflen )
-                   {
-                       workbuf = srealloc(workbuf, buflen += 100);
-                       wbptr = workbuf + wblen;
+           while (ch != 0) {
+               if (cfg.rawcnp || !!(ch & 0xE0)) {
+                   if (wblen == buflen) {
+                       workbuf = srealloc(workbuf, buflen += 100);
+                       wbptr = workbuf + wblen;
                    }
                    wblen++;
                    *wbptr++ = (unsigned char) ch;
                }
-               ch>>=8;
+               ch >>= 8;
            }
            top.x++;
        }
        if (nl) {
            int i;
-           for (i=0; i<sizeof(sel_nl); i++)
-           {
-               if ( wblen == buflen )
-               {
+           for (i = 0; i < sizeof(sel_nl); i++) {
+               if (wblen == buflen) {
                    workbuf = srealloc(workbuf, buflen += 100);
                    wbptr = workbuf + wblen;
                }
-               wblen++;
+               wblen++;
                *wbptr++ = sel_nl[i];
            }
        }
        top.y++;
        top.x = 0;
     }
-    write_clip (workbuf, wblen, FALSE);        /* transfer to clipboard */
-    if ( buflen > 0 )  /* indicates we allocated this buffer */
+    write_clip(workbuf, wblen, FALSE); /* transfer to clipboard */
+    if (buflen > 0)                   /* indicates we allocated this buffer */
        sfree(workbuf);
 
 }
-void term_copyall (void) {
+void term_copyall(void)
+{
     pos top;
     top.y = -count234(scrollback);
     top.x = 0;
-    clipme(top, curs, NULL /* dynamic allocation */);
+    clipme(top, curs, NULL /* dynamic allocation */ );
 }
 
 /*
  * Spread the selection outwards according to the selection mode.
  */
-static pos sel_spread_half (pos p, int dir) {
+static pos sel_spread_half(pos p, int dir)
+{
     unsigned long *ldata;
     short wvalue;
 
@@ -2215,13 +2345,13 @@ static pos sel_spread_half (pos p, int dir) {
         * for runs of spaces at the end of a non-wrapping line.
         */
        if (!(ldata[cols] & ATTR_WRAPPED)) {
-           unsigned long *q = ldata+cols;
+           unsigned long *q = ldata + cols;
            while (q > ldata && (q[-1] & CHAR_MASK) == 0x20)
                q--;
-           if (q == ldata+cols)
+           if (q == ldata + cols)
                q--;
-           if (p.x >= q-ldata)
-               p.x = (dir == -1 ? q-ldata : cols - 1);
+           if (p.x >= q - ldata)
+               p.x = (dir == -1 ? q - ldata : cols - 1);
        }
        break;
       case SM_WORD:
@@ -2231,11 +2361,13 @@ static pos sel_spread_half (pos p, int dir) {
         */
        wvalue = wordness[ldata[p.x] & CHAR_MASK];
        if (dir == +1) {
-           while (p.x < cols && wordness[ldata[p.x+1] & CHAR_MASK] == wvalue)
-               p.x++;
+           while (p.x < cols
+                  && wordness[ldata[p.x + 1] & CHAR_MASK] ==
+                  wvalue) p.x++;
        } else {
-           while (p.x > 0 && wordness[ldata[p.x-1] & CHAR_MASK] == wvalue)
-               p.x--;
+           while (p.x > 0
+                  && wordness[ldata[p.x - 1] & CHAR_MASK] ==
+                  wvalue) p.x--;
        }
        break;
       case SM_LINE:
@@ -2248,33 +2380,38 @@ static pos sel_spread_half (pos p, int dir) {
     return p;
 }
 
-static void sel_spread (void) {
-    selstart = sel_spread_half (selstart, -1);
+static void sel_spread(void)
+{
+    selstart = sel_spread_half(selstart, -1);
     decpos(selend);
-    selend = sel_spread_half (selend, +1);
+    selend = sel_spread_half(selend, +1);
     incpos(selend);
 }
 
-void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
-                int shift, int ctrl) {
+void term_mouse(Mouse_Button b, Mouse_Action a, int x, int y,
+               int shift, int ctrl)
+{
     pos selpoint;
     unsigned long *ldata;
-    
-    if (y<0) y = 0;
-    if (y>=rows) y = rows-1;
-    if (x<0) {
-        if (y > 0) {
-            x = cols-1;
-            y--;
-        } else
-            x = 0;
+
+    if (y < 0)
+       y = 0;
+    if (y >= rows)
+       y = rows - 1;
+    if (x < 0) {
+       if (y > 0) {
+           x = cols - 1;
+           y--;
+       } else
+           x = 0;
     }
-    if (x>=cols) x = cols-1;
+    if (x >= cols)
+       x = cols - 1;
 
     selpoint.y = y + disptop;
     selpoint.x = x;
     ldata = lineptr(selpoint.y);
-    if ((ldata[cols]&LATTR_MODE) != LATTR_NORM)
+    if ((ldata[cols] & LATTR_MODE) != LATTR_NORM)
        selpoint.x /= 2;
 
     if (xterm_mouse) {
@@ -2282,9 +2419,9 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
        char abuf[16];
        static int is_down = 0;
 
-       switch(b) {
+       switch (b) {
          case MBT_LEFT:
-           encstate = 0x20;    /* left button down */
+           encstate = 0x20;           /* left button down */
            break;
          case MBT_MIDDLE:
            encstate = 0x21;
@@ -2299,7 +2436,7 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
            encstate = 0x61;
            break;
        }
-       switch(a) {
+       switch (a) {
          case MA_DRAG:
            if (xterm_mouse == 1)
                return;
@@ -2347,7 +2484,8 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
        if (selstate == ABOUT_TO && poseq(selanchor, selpoint))
            return;
        if (b == MBT_EXTEND && a != MA_DRAG && selstate == SELECTED) {
-           if (posdiff(selpoint,selstart) < posdiff(selend,selstart)/2) {
+           if (posdiff(selpoint, selstart) <
+               posdiff(selend, selstart) / 2) {
                selanchor = selend;
                decpos(selanchor);
            } else {
@@ -2378,7 +2516,8 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
            selstate = SELECTED;
        } else
            selstate = NO_SELECTION;
-    } else if (b == MBT_PASTE && (a==MA_CLICK || a==MA_2CLK || a==MA_3CLK)) {
+    } else if (b == MBT_PASTE
+              && (a == MA_CLICK || a == MA_2CLK || a == MA_3CLK)) {
        char *data;
        int len;
 
@@ -2386,28 +2525,28 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
        if (data) {
            char *p, *q;
 
-           if (paste_buffer) sfree(paste_buffer);
+           if (paste_buffer)
+               sfree(paste_buffer);
            paste_pos = paste_hold = paste_len = 0;
            paste_buffer = smalloc(len);
 
            p = q = data;
-           while (p < data+len) {
-               while (p < data+len &&
-                      !(p <= data+len-sizeof(sel_nl) &&
+           while (p < data + len) {
+               while (p < data + len &&
+                      !(p <= data + len - sizeof(sel_nl) &&
                         !memcmp(p, sel_nl, sizeof(sel_nl))))
                    p++;
 
                {
                    int i;
                    unsigned char c;
-                   for(i=0;i<p-q;i++)
-                   {
-                       c=xlat_kbd2tty(q[i]);
+                   for (i = 0; i < p - q; i++) {
+                       c = xlat_kbd2tty(q[i]);
                        paste_buffer[paste_len++] = c;
                    }
                }
 
-               if (p <= data+len-sizeof(sel_nl) &&
+               if (p <= data + len - sizeof(sel_nl) &&
                    !memcmp(p, sel_nl, sizeof(sel_nl))) {
                    paste_buffer[paste_len++] = '\r';
                    p += sizeof(sel_nl);
@@ -2416,11 +2555,12 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
            }
 
            /* Assume a small paste will be OK in one go. */
-           if (paste_len<256) {
-               ldisc_send (paste_buffer, paste_len);
-               if (paste_buffer) sfree(paste_buffer);
+           if (paste_len < 256) {
+               ldisc_send(paste_buffer, paste_len);
+               if (paste_buffer)
+                   sfree(paste_buffer);
                paste_buffer = 0;
-               paste_pos = paste_hold = paste_len = 0;
+               paste_pos = paste_hold = paste_len = 0;
            }
        }
        get_clip(NULL, NULL);
@@ -2429,36 +2569,39 @@ void term_mouse (Mouse_Button b, Mouse_Action a, int x, int y,
     term_update();
 }
 
-void term_nopaste() {
-    if(paste_len == 0) return;
+void term_nopaste()
+{
+    if (paste_len == 0)
+       return;
     sfree(paste_buffer);
     paste_buffer = 0;
     paste_len = 0;
 }
 
-void term_paste() {
+void term_paste()
+{
     static long last_paste = 0;
     long now, paste_diff;
 
-    if(paste_len == 0) return;
+    if (paste_len == 0)
+       return;
 
     /* Don't wait forever to paste */
-    if(paste_hold) {
-       now = GetTickCount();
-       paste_diff = now-last_paste;
-       if (paste_diff>=0 && paste_diff<450)
+    if (paste_hold) {
+       now = GetTickCount();
+       paste_diff = now - last_paste;
+       if (paste_diff >= 0 && paste_diff < 450)
            return;
     }
     paste_hold = 0;
 
-    while(paste_pos<paste_len)
-    {
+    while (paste_pos < paste_len) {
        int n = 0;
        while (n + paste_pos < paste_len) {
            if (paste_buffer[paste_pos + n++] == '\r')
                break;
        }
-       ldisc_send (paste_buffer+paste_pos, n);
+       ldisc_send(paste_buffer + paste_pos, n);
        paste_pos += n;
 
        if (paste_pos < paste_len) {
@@ -2471,26 +2614,32 @@ void term_paste() {
     paste_len = 0;
 }
 
-static void deselect (void) {
+static void deselect(void)
+{
     selstate = NO_SELECTION;
     selstart.x = selstart.y = selend.x = selend.y = 0;
 }
 
-void term_deselect (void) {
+void term_deselect(void)
+{
     deselect();
     term_update();
 }
 
-int term_ldisc(int option) {
-    if (option == LD_ECHO) return term_echoing;
-    if (option == LD_EDIT) return term_editing;
+int term_ldisc(int option)
+{
+    if (option == LD_ECHO)
+       return term_echoing;
+    if (option == LD_EDIT)
+       return term_editing;
     return FALSE;
 }
 
 /*
  * from_backend(), to get data from the backend for the terminal.
  */
-void from_backend(int is_stderr, char *data, int len) {
+void from_backend(int is_stderr, char *data, int len)
+{
     while (len--) {
        if (inbuf_head >= INBUF_SIZE)
            term_out();
@@ -2501,18 +2650,22 @@ void from_backend(int is_stderr, char *data, int len) {
 /*
  * Log session traffic.
  */
-void logtraffic(unsigned char c, int logmode) {
+void logtraffic(unsigned char c, int logmode)
+{
     if (cfg.logtype > 0) {
        if (cfg.logtype == logmode) {
            /* deferred open file from pgm start? */
-           if (!lgfp) logfopen();
-           if (lgfp) fputc (c, lgfp);
-       }
+           if (!lgfp)
+               logfopen();
+           if (lgfp)
+               fputc(c, lgfp);
+       }
     }
 }
 
 /* open log file append/overwrite mode */
-void logfopen(void) {
+void logfopen(void)
+{
     char buf[256];
     time_t t;
     struct tm *tm;
@@ -2520,8 +2673,8 @@ void logfopen(void) {
 
     if (!cfg.logtype)
        return;
-    sprintf (writemod, "wb");         /* default to rewrite */
-    lgfp = fopen(cfg.logfilename, "r");  /* file already present? */
+    sprintf(writemod, "wb");          /* default to rewrite */
+    lgfp = fopen(cfg.logfilename, "r");        /* file already present? */
     if (lgfp) {
        int i;
        fclose(lgfp);
@@ -2530,32 +2683,36 @@ void logfopen(void) {
            writemod[0] = 'a';         /* set append mode */
        else if (i == 0) {             /* cancelled */
            lgfp = NULL;
-            cfg.logtype = 0;           /* disable logging */
+           cfg.logtype = 0;           /* disable logging */
            return;
        }
     }
 
     lgfp = fopen(cfg.logfilename, writemod);
-    if (lgfp) { /* enter into event log */
+    if (lgfp) {                               /* enter into event log */
        sprintf(buf, "%s session log (%s mode) to file : ",
                (writemod[0] == 'a') ? "Appending" : "Writing new",
                (cfg.logtype == LGTYP_ASCII ? "ASCII" :
-                cfg.logtype == LGTYP_DEBUG ? "raw" : "<ukwn>")  );
+                cfg.logtype == LGTYP_DEBUG ? "raw" : "<ukwn>"));
        /* Make sure we do not exceed the output buffer size */
-       strncat (buf, cfg.logfilename, 128);
+       strncat(buf, cfg.logfilename, 128);
        buf[strlen(buf)] = '\0';
        logevent(buf);
 
-        /* --- write header line iinto log file */
-       fputs ("=~=~=~=~=~=~=~=~=~=~=~= PuTTY log ", lgfp);
+       /* --- write header line iinto log file */
+       fputs("=~=~=~=~=~=~=~=~=~=~=~= PuTTY log ", lgfp);
        time(&t);
        tm = localtime(&t);
        strftime(buf, 24, "%Y.%m.%d %H:%M:%S", tm);
-       fputs (buf, lgfp);
-       fputs (" =~=~=~=~=~=~=~=~=~=~=~=\r\n", lgfp);
+       fputs(buf, lgfp);
+       fputs(" =~=~=~=~=~=~=~=~=~=~=~=\r\n", lgfp);
     }
 }
 
-void logfclose (void) {
-    if (lgfp) { fclose(lgfp); lgfp = NULL; }
+void logfclose(void)
+{
+    if (lgfp) {
+       fclose(lgfp);
+       lgfp = NULL;
+    }
 }
index 9d1d7b0..0837dc6 100644 (file)
--- a/tree234.c
+++ b/tree234.c
@@ -59,7 +59,8 @@ struct node234_Tag {
 /*
  * Create a 2-3-4 tree.
  */
-tree234 *newtree234(cmpfn234 cmp) {
+tree234 *newtree234(cmpfn234 cmp)
+{
     tree234 *ret = mknew(tree234);
     LOG(("created tree %p\n", ret));
     ret->root = NULL;
@@ -70,7 +71,8 @@ tree234 *newtree234(cmpfn234 cmp) {
 /*
  * Free a 2-3-4 tree (not including freeing the elements).
  */
-static void freenode234(node234 *n) {
+static void freenode234(node234 * n)
+{
     if (!n)
        return;
     freenode234(n->kids[0]);
@@ -79,7 +81,9 @@ static void freenode234(node234 *n) {
     freenode234(n->kids[3]);
     sfree(n);
 }
-void freetree234(tree234 *t) {
+
+void freetree234(tree234 * t)
+{
     freenode234(t->root);
     sfree(t);
 }
@@ -87,7 +91,8 @@ void freetree234(tree234 *t) {
 /*
  * Internal function to count a node.
  */
-static int countnode234(node234 *n) {
+static int countnode234(node234 * n)
+{
     int count = 0;
     int i;
     if (!n)
@@ -103,7 +108,8 @@ static int countnode234(node234 *n) {
 /*
  * Count the elements in a tree.
  */
-int count234(tree234 *t) {
+int count234(tree234 * t)
+{
     if (t->root)
        return countnode234(t->root);
     else
@@ -114,7 +120,8 @@ int count234(tree234 *t) {
  * Add an element e to a 2-3-4 tree t. Returns e on success, or if
  * an existing element compares equal, returns that.
  */
-static void *add234_internal(tree234 *t, void *e, int index) {
+static void *add234_internal(tree234 * t, void *e, int index)
+{
     node234 *n, **np, *left, *right;
     void *orig_e = e;
     int c, lcount, rcount;
@@ -158,7 +165,7 @@ static void *add234_internal(tree234 *t, void *e, int index) {
                 * always starts at the bottom, never in the
                 * middle).
                 */
-               do { /* this is a do ... while (0) to allow `break' */
+               do {                   /* this is a do ... while (0) to allow `break' */
                    if (index <= n->counts[0]) {
                        childnum = 0;
                        break;
@@ -185,15 +192,15 @@ static void *add234_internal(tree234 *t, void *e, int index) {
            if ((c = t->cmp(e, n->elems[0])) < 0)
                childnum = 0;
            else if (c == 0)
-               return n->elems[0];            /* already exists */
-           else if (n->elems[1] == NULL || (c = t->cmp(e, n->elems[1])) < 0)
-               childnum = 1;
+               return n->elems[0];    /* already exists */
+           else if (n->elems[1] == NULL
+                    || (c = t->cmp(e, n->elems[1])) < 0) childnum = 1;
            else if (c == 0)
-               return n->elems[1];            /* already exists */
-           else if (n->elems[2] == NULL || (c = t->cmp(e, n->elems[2])) < 0)
-               childnum = 2;
+               return n->elems[1];    /* already exists */
+           else if (n->elems[2] == NULL
+                    || (c = t->cmp(e, n->elems[2])) < 0) childnum = 2;
            else if (c == 0)
-               return n->elems[2];            /* already exists */
+               return n->elems[2];    /* already exists */
            else
                childnum = 3;
        }
@@ -204,8 +211,10 @@ static void *add234_internal(tree234 *t, void *e, int index) {
     /*
      * We need to insert the new element in n at position np.
      */
-    left = NULL;  lcount = 0;
-    right = NULL; rcount = 0;
+    left = NULL;
+    lcount = 0;
+    right = NULL;
+    rcount = 0;
     while (n) {
        LOG(("  at %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d\n",
             n,
@@ -221,20 +230,28 @@ static void *add234_internal(tree234 *t, void *e, int index) {
             */
            if (np == &n->kids[0]) {
                LOG(("  inserting on left of 2-node\n"));
-               n->kids[2] = n->kids[1];     n->counts[2] = n->counts[1];
+               n->kids[2] = n->kids[1];
+               n->counts[2] = n->counts[1];
                n->elems[1] = n->elems[0];
-               n->kids[1] = right;          n->counts[1] = rcount;
+               n->kids[1] = right;
+               n->counts[1] = rcount;
                n->elems[0] = e;
-               n->kids[0] = left;           n->counts[0] = lcount;
-           } else { /* np == &n->kids[1] */
+               n->kids[0] = left;
+               n->counts[0] = lcount;
+           } else {                   /* np == &n->kids[1] */
                LOG(("  inserting on right of 2-node\n"));
-               n->kids[2] = right;          n->counts[2] = rcount;
+               n->kids[2] = right;
+               n->counts[2] = rcount;
                n->elems[1] = e;
-               n->kids[1] = left;           n->counts[1] = lcount;
+               n->kids[1] = left;
+               n->counts[1] = lcount;
            }
-           if (n->kids[0]) n->kids[0]->parent = n;
-           if (n->kids[1]) n->kids[1]->parent = n;
-           if (n->kids[2]) n->kids[2]->parent = n;
+           if (n->kids[0])
+               n->kids[0]->parent = n;
+           if (n->kids[1])
+               n->kids[1]->parent = n;
+           if (n->kids[2])
+               n->kids[2]->parent = n;
            LOG(("  done\n"));
            break;
        } else if (n->elems[2] == NULL) {
@@ -243,30 +260,43 @@ static void *add234_internal(tree234 *t, void *e, int index) {
             */
            if (np == &n->kids[0]) {
                LOG(("  inserting on left of 3-node\n"));
-               n->kids[3] = n->kids[2];    n->counts[3] = n->counts[2];
+               n->kids[3] = n->kids[2];
+               n->counts[3] = n->counts[2];
                n->elems[2] = n->elems[1];
-               n->kids[2] = n->kids[1];    n->counts[2] = n->counts[1];
+               n->kids[2] = n->kids[1];
+               n->counts[2] = n->counts[1];
                n->elems[1] = n->elems[0];
-               n->kids[1] = right;         n->counts[1] = rcount;
+               n->kids[1] = right;
+               n->counts[1] = rcount;
                n->elems[0] = e;
-               n->kids[0] = left;          n->counts[0] = lcount;
+               n->kids[0] = left;
+               n->counts[0] = lcount;
            } else if (np == &n->kids[1]) {
                LOG(("  inserting in middle of 3-node\n"));
-               n->kids[3] = n->kids[2];    n->counts[3] = n->counts[2];
+               n->kids[3] = n->kids[2];
+               n->counts[3] = n->counts[2];
                n->elems[2] = n->elems[1];
-               n->kids[2] = right;         n->counts[2] = rcount;
+               n->kids[2] = right;
+               n->counts[2] = rcount;
                n->elems[1] = e;
-               n->kids[1] = left;          n->counts[1] = lcount;
-           } else { /* np == &n->kids[2] */
+               n->kids[1] = left;
+               n->counts[1] = lcount;
+           } else {                   /* np == &n->kids[2] */
                LOG(("  inserting on right of 3-node\n"));
-               n->kids[3] = right;         n->counts[3] = rcount;
+               n->kids[3] = right;
+               n->counts[3] = rcount;
                n->elems[2] = e;
-               n->kids[2] = left;          n->counts[2] = lcount;
+               n->kids[2] = left;
+               n->counts[2] = lcount;
            }
-           if (n->kids[0]) n->kids[0]->parent = n;
-           if (n->kids[1]) n->kids[1]->parent = n;
-           if (n->kids[2]) n->kids[2]->parent = n;
-           if (n->kids[3]) n->kids[3]->parent = n;
+           if (n->kids[0])
+               n->kids[0]->parent = n;
+           if (n->kids[1])
+               n->kids[1]->parent = n;
+           if (n->kids[2])
+               n->kids[2]->parent = n;
+           if (n->kids[3])
+               n->kids[3]->parent = n;
            LOG(("  done\n"));
            break;
        } else {
@@ -282,54 +312,79 @@ static void *add234_internal(tree234 *t, void *e, int index) {
             * always.
             */
            if (np == &n->kids[0]) {
-               m->kids[0] = left;          m->counts[0] = lcount;
+               m->kids[0] = left;
+               m->counts[0] = lcount;
                m->elems[0] = e;
-               m->kids[1] = right;         m->counts[1] = rcount;
+               m->kids[1] = right;
+               m->counts[1] = rcount;
                m->elems[1] = n->elems[0];
-               m->kids[2] = n->kids[1];    m->counts[2] = n->counts[1];
+               m->kids[2] = n->kids[1];
+               m->counts[2] = n->counts[1];
                e = n->elems[1];
-               n->kids[0] = n->kids[2];    n->counts[0] = n->counts[2];
+               n->kids[0] = n->kids[2];
+               n->counts[0] = n->counts[2];
                n->elems[0] = n->elems[2];
-               n->kids[1] = n->kids[3];    n->counts[1] = n->counts[3];
+               n->kids[1] = n->kids[3];
+               n->counts[1] = n->counts[3];
            } else if (np == &n->kids[1]) {
-               m->kids[0] = n->kids[0];    m->counts[0] = n->counts[0];
+               m->kids[0] = n->kids[0];
+               m->counts[0] = n->counts[0];
                m->elems[0] = n->elems[0];
-               m->kids[1] = left;          m->counts[1] = lcount;
+               m->kids[1] = left;
+               m->counts[1] = lcount;
                m->elems[1] = e;
-               m->kids[2] = right;         m->counts[2] = rcount;
+               m->kids[2] = right;
+               m->counts[2] = rcount;
                e = n->elems[1];
-               n->kids[0] = n->kids[2];    n->counts[0] = n->counts[2];
+               n->kids[0] = n->kids[2];
+               n->counts[0] = n->counts[2];
                n->elems[0] = n->elems[2];
-               n->kids[1] = n->kids[3];    n->counts[1] = n->counts[3];
+               n->kids[1] = n->kids[3];
+               n->counts[1] = n->counts[3];
            } else if (np == &n->kids[2]) {
-               m->kids[0] = n->kids[0];    m->counts[0] = n->counts[0];
+               m->kids[0] = n->kids[0];
+               m->counts[0] = n->counts[0];
                m->elems[0] = n->elems[0];
-               m->kids[1] = n->kids[1];    m->counts[1] = n->counts[1];
+               m->kids[1] = n->kids[1];
+               m->counts[1] = n->counts[1];
                m->elems[1] = n->elems[1];
-               m->kids[2] = left;          m->counts[2] = lcount;
+               m->kids[2] = left;
+               m->counts[2] = lcount;
                /* e = e; */
-               n->kids[0] = right;         n->counts[0] = rcount;
+               n->kids[0] = right;
+               n->counts[0] = rcount;
                n->elems[0] = n->elems[2];
-               n->kids[1] = n->kids[3];    n->counts[1] = n->counts[3];
-           } else { /* np == &n->kids[3] */
-               m->kids[0] = n->kids[0];    m->counts[0] = n->counts[0];
+               n->kids[1] = n->kids[3];
+               n->counts[1] = n->counts[3];
+           } else {                   /* np == &n->kids[3] */
+               m->kids[0] = n->kids[0];
+               m->counts[0] = n->counts[0];
                m->elems[0] = n->elems[0];
-               m->kids[1] = n->kids[1];    m->counts[1] = n->counts[1];
+               m->kids[1] = n->kids[1];
+               m->counts[1] = n->counts[1];
                m->elems[1] = n->elems[1];
-               m->kids[2] = n->kids[2];    m->counts[2] = n->counts[2];
-               n->kids[0] = left;          n->counts[0] = lcount;
+               m->kids[2] = n->kids[2];
+               m->counts[2] = n->counts[2];
+               n->kids[0] = left;
+               n->counts[0] = lcount;
                n->elems[0] = e;
-               n->kids[1] = right;         n->counts[1] = rcount;
+               n->kids[1] = right;
+               n->counts[1] = rcount;
                e = n->elems[2];
            }
            m->kids[3] = n->kids[3] = n->kids[2] = NULL;
            m->counts[3] = n->counts[3] = n->counts[2] = 0;
            m->elems[2] = n->elems[2] = n->elems[1] = NULL;
-           if (m->kids[0]) m->kids[0]->parent = m;
-           if (m->kids[1]) m->kids[1]->parent = m;
-           if (m->kids[2]) m->kids[2]->parent = m;
-           if (n->kids[0]) n->kids[0]->parent = n;
-           if (n->kids[1]) n->kids[1]->parent = n;
+           if (m->kids[0])
+               m->kids[0]->parent = m;
+           if (m->kids[1])
+               m->kids[1]->parent = m;
+           if (m->kids[2])
+               m->kids[2]->parent = m;
+           if (n->kids[0])
+               n->kids[0]->parent = n;
+           if (n->kids[1])
+               n->kids[1]->parent = n;
            LOG(("  left (%p): %p/%d [%p] %p/%d [%p] %p/%d\n", m,
                 m->kids[0], m->counts[0], m->elems[0],
                 m->kids[1], m->counts[1], m->elems[1],
@@ -337,8 +392,10 @@ static void *add234_internal(tree234 *t, void *e, int index) {
            LOG(("  right (%p): %p/%d [%p] %p/%d\n", n,
                 n->kids[0], n->counts[0], n->elems[0],
                 n->kids[1], n->counts[1]));
-           left = m;  lcount = countnode234(left);
-           right = n; rcount = countnode234(right);
+           left = m;
+           lcount = countnode234(left);
+           right = n;
+           rcount = countnode234(right);
        }
        if (n->parent)
            np = (n->parent->kids[0] == n ? &n->parent->kids[0] :
@@ -367,44 +424,52 @@ static void *add234_internal(tree234 *t, void *e, int index) {
     } else {
        LOG(("  root is overloaded, split into two\n"));
        t->root = mknew(node234);
-       t->root->kids[0] = left;     t->root->counts[0] = lcount;
+       t->root->kids[0] = left;
+       t->root->counts[0] = lcount;
        t->root->elems[0] = e;
-       t->root->kids[1] = right;    t->root->counts[1] = rcount;
+       t->root->kids[1] = right;
+       t->root->counts[1] = rcount;
        t->root->elems[1] = NULL;
-       t->root->kids[2] = NULL;     t->root->counts[2] = 0;
+       t->root->kids[2] = NULL;
+       t->root->counts[2] = 0;
        t->root->elems[2] = NULL;
-       t->root->kids[3] = NULL;     t->root->counts[3] = 0;
+       t->root->kids[3] = NULL;
+       t->root->counts[3] = 0;
        t->root->parent = NULL;
-       if (t->root->kids[0]) t->root->kids[0]->parent = t->root;
-       if (t->root->kids[1]) t->root->kids[1]->parent = t->root;
+       if (t->root->kids[0])
+           t->root->kids[0]->parent = t->root;
+       if (t->root->kids[1])
+           t->root->kids[1]->parent = t->root;
        LOG(("  new root is %p/%d [%p] %p/%d\n",
             t->root->kids[0], t->root->counts[0],
-            t->root->elems[0],
-            t->root->kids[1], t->root->counts[1]));
+            t->root->elems[0], t->root->kids[1], t->root->counts[1]));
     }
 
     return orig_e;
 }
 
-void *add234(tree234 *t, void *e) {
+void *add234(tree234 * t, void *e)
+{
     if (!t->cmp)                      /* tree is unsorted */
        return NULL;
 
     return add234_internal(t, e, -1);
 }
-void *addpos234(tree234 *t, void *e, int index) {
+void *addpos234(tree234 * t, void *e, int index)
+{
     if (index < 0 ||                  /* index out of range */
        t->cmp)                        /* tree is sorted */
        return NULL;                   /* return failure */
 
-    return add234_internal(t, e, index);  /* this checks the upper bound */
+    return add234_internal(t, e, index);       /* this checks the upper bound */
 }
 
 /*
  * Look up the element at a given numeric index in a 2-3-4 tree.
  * Returns NULL if the index is out of range.
  */
-void *index234(tree234 *t, int index) {
+void *index234(tree234 * t, int index)
+{
     node234 *n;
 
     if (!t->root)
@@ -414,7 +479,7 @@ void *index234(tree234 *t, int index) {
        return NULL;                   /* out of range */
 
     n = t->root;
-    
+
     while (n) {
        if (index < n->counts[0])
            n = n->kids[0];
@@ -443,8 +508,9 @@ void *index234(tree234 *t, int index) {
  * as NULL, in which case the compare function from the tree proper
  * will be used.
  */
-void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp,
-                   int relation, int *index) {
+void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp,
+                   int relation, int *index)
+{
     node234 *n;
     void *ret;
     int c;
@@ -479,7 +545,8 @@ void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp,
                (c = cmpret ? cmpret : cmp(e, n->elems[kcount])) < 0) {
                break;
            }
-           if (n->kids[kcount]) idx += n->counts[kcount];
+           if (n->kids[kcount])
+               idx += n->counts[kcount];
            if (c == 0) {
                ecount = kcount;
                break;
@@ -501,7 +568,8 @@ void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp,
         * relation is EQ, LE or GE we can now go home.
         */
        if (relation != REL234_LT && relation != REL234_GT) {
-           if (index) *index = idx;
+           if (index)
+               *index = idx;
            return n->elems[ecount];
        }
 
@@ -544,16 +612,20 @@ void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp,
      * bounds, which is exactly what we want.
      */
     ret = index234(t, idx);
-    if (ret && index) *index = idx;
+    if (ret && index)
+       *index = idx;
     return ret;
 }
-void *find234(tree234 *t, void *e, cmpfn234 cmp) {
+void *find234(tree234 * t, void *e, cmpfn234 cmp)
+{
     return findrelpos234(t, e, cmp, REL234_EQ, NULL);
 }
-void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation) {
+void *findrel234(tree234 * t, void *e, cmpfn234 cmp, int relation)
+{
     return findrelpos234(t, e, cmp, relation, NULL);
 }
-void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index) {
+void *findpos234(tree234 * t, void *e, cmpfn234 cmp, int *index)
+{
     return findrelpos234(t, e, cmp, REL234_EQ, index);
 }
 
@@ -561,7 +633,8 @@ void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index) {
  * Delete an element e in a 2-3-4 tree. Does not free the element,
  * merely removes all links to it from the tree nodes.
  */
-static void *delpos234_internal(tree234 *t, int index) {
+static void *delpos234_internal(tree234 * t, int index)
+{
     node234 *n;
     void *retval;
     int ei = -1;
@@ -575,25 +648,26 @@ static void *delpos234_internal(tree234 *t, int index) {
            int ki;
            node234 *sub;
 
-           LOG(("  node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d index=%d\n",
-                n,
-                n->kids[0], n->counts[0], n->elems[0],
-                n->kids[1], n->counts[1], n->elems[1],
-                n->kids[2], n->counts[2], n->elems[2],
-                n->kids[3], n->counts[3],
-                index));
+           LOG(
+               ("  node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%d index=%d\n",
+                n, n->kids[0], n->counts[0], n->elems[0], n->kids[1],
+                n->counts[1], n->elems[1], n->kids[2], n->counts[2],
+                n->elems[2], n->kids[3], n->counts[3], index));
            if (index < n->counts[0]) {
                ki = 0;
-           } else if (index -= n->counts[0]+1, index < 0) {
-               ei = 0; break;
+           } else if (index -= n->counts[0] + 1, index < 0) {
+               ei = 0;
+               break;
            } else if (index < n->counts[1]) {
                ki = 1;
-           } else if (index -= n->counts[1]+1, index < 0) {
-               ei = 1; break;
+           } else if (index -= n->counts[1] + 1, index < 0) {
+               ei = 1;
+               break;
            } else if (index < n->counts[2]) {
                ki = 2;
-           } else if (index -= n->counts[2]+1, index < 0) {
-               ei = 2; break;
+           } else if (index -= n->counts[2] + 1, index < 0) {
+               ei = 2;
+               break;
            } else {
                ki = 3;
            }
@@ -605,7 +679,7 @@ static void *delpos234_internal(tree234 *t, int index) {
            sub = n->kids[ki];
            if (!sub->elems[1]) {
                LOG(("  subtree has only one element!\n", ki));
-               if (ki > 0 && n->kids[ki-1]->elems[1]) {
+               if (ki > 0 && n->kids[ki - 1]->elems[1]) {
                    /*
                     * Case 3a, left-handed variant. Child ki has
                     * only one element, but child ki-1 has two or
@@ -616,7 +690,7 @@ static void *delpos234_internal(tree234 *t, int index) {
                     *               /     \     ->            /     \
                     * [more] a A b B c   d D e      [more] a A b   c C d D e
                     */
-                   node234 *sib = n->kids[ki-1];
+                   node234 *sib = n->kids[ki - 1];
                    int lastelem = (sib->elems[2] ? 2 :
                                    sib->elems[1] ? 1 : 0);
                    sub->kids[2] = sub->kids[1];
@@ -624,25 +698,28 @@ static void *delpos234_internal(tree234 *t, int index) {
                    sub->elems[1] = sub->elems[0];
                    sub->kids[1] = sub->kids[0];
                    sub->counts[1] = sub->counts[0];
-                   sub->elems[0] = n->elems[ki-1];
-                   sub->kids[0] = sib->kids[lastelem+1];
-                   sub->counts[0] = sib->counts[lastelem+1];
-                   if (sub->kids[0]) sub->kids[0]->parent = sub;
-                   n->elems[ki-1] = sib->elems[lastelem];
-                   sib->kids[lastelem+1] = NULL;
-                   sib->counts[lastelem+1] = 0;
+                   sub->elems[0] = n->elems[ki - 1];
+                   sub->kids[0] = sib->kids[lastelem + 1];
+                   sub->counts[0] = sib->counts[lastelem + 1];
+                   if (sub->kids[0])
+                       sub->kids[0]->parent = sub;
+                   n->elems[ki - 1] = sib->elems[lastelem];
+                   sib->kids[lastelem + 1] = NULL;
+                   sib->counts[lastelem + 1] = 0;
                    sib->elems[lastelem] = NULL;
                    n->counts[ki] = countnode234(sub);
                    LOG(("  case 3a left\n"));
-                   LOG(("  index and left subtree count before adjustment: %d, %d\n",
-                        index, n->counts[ki-1]));
-                   index += n->counts[ki-1];
-                   n->counts[ki-1] = countnode234(sib);
-                   index -= n->counts[ki-1];
-                   LOG(("  index and left subtree count after adjustment: %d, %d\n",
-                        index, n->counts[ki-1]));
-               } else if (ki < 3 && n->kids[ki+1] &&
-                          n->kids[ki+1]->elems[1]) {
+                   LOG(
+                       ("  index and left subtree count before adjustment: %d, %d\n",
+                        index, n->counts[ki - 1]));
+                   index += n->counts[ki - 1];
+                   n->counts[ki - 1] = countnode234(sib);
+                   index -= n->counts[ki - 1];
+                   LOG(
+                       ("  index and left subtree count after adjustment: %d, %d\n",
+                        index, n->counts[ki - 1]));
+               } else if (ki < 3 && n->kids[ki + 1]
+                          && n->kids[ki + 1]->elems[1]) {
                    /*
                     * Case 3a, right-handed variant. ki has only
                     * one element but ki+1 has two or more. Move a
@@ -652,25 +729,26 @@ static void *delpos234_internal(tree234 *t, int index) {
                     *     /     \                ->         /     \
                     *  a A b   c C d D e [more]      a A b B c   d D e [more]
                     */
-                   node234 *sib = n->kids[ki+1];
+                   node234 *sib = n->kids[ki + 1];
                    int j;
                    sub->elems[1] = n->elems[ki];
                    sub->kids[2] = sib->kids[0];
                    sub->counts[2] = sib->counts[0];
-                   if (sub->kids[2]) sub->kids[2]->parent = sub;
+                   if (sub->kids[2])
+                       sub->kids[2]->parent = sub;
                    n->elems[ki] = sib->elems[0];
                    sib->kids[0] = sib->kids[1];
                    sib->counts[0] = sib->counts[1];
-                   for (j = 0; j < 2 && sib->elems[j+1]; j++) {
-                       sib->kids[j+1] = sib->kids[j+2];
-                       sib->counts[j+1] = sib->counts[j+2];
-                       sib->elems[j] = sib->elems[j+1];
+                   for (j = 0; j < 2 && sib->elems[j + 1]; j++) {
+                       sib->kids[j + 1] = sib->kids[j + 2];
+                       sib->counts[j + 1] = sib->counts[j + 2];
+                       sib->elems[j] = sib->elems[j + 1];
                    }
-                   sib->kids[j+1] = NULL;
-                   sib->counts[j+1] = 0;
+                   sib->kids[j + 1] = NULL;
+                   sib->counts[j + 1] = 0;
                    sib->elems[j] = NULL;
                    n->counts[ki] = countnode234(sub);
-                   n->counts[ki+1] = countnode234(sib);
+                   n->counts[ki + 1] = countnode234(sib);
                    LOG(("  case 3a right\n"));
                } else {
                    /*
@@ -700,7 +778,7 @@ static void *delpos234_internal(tree234 *t, int index) {
                        index += n->counts[ki] + 1;
                    }
                    sib = n->kids[ki];
-                   sub = n->kids[ki+1];
+                   sub = n->kids[ki + 1];
 
                    sub->kids[3] = sub->kids[1];
                    sub->counts[3] = sub->counts[1];
@@ -710,13 +788,15 @@ static void *delpos234_internal(tree234 *t, int index) {
                    sub->elems[1] = n->elems[ki];
                    sub->kids[1] = sib->kids[1];
                    sub->counts[1] = sib->counts[1];
-                   if (sub->kids[1]) sub->kids[1]->parent = sub;
+                   if (sub->kids[1])
+                       sub->kids[1]->parent = sub;
                    sub->elems[0] = sib->elems[0];
                    sub->kids[0] = sib->kids[0];
                    sub->counts[0] = sib->counts[0];
-                   if (sub->kids[0]) sub->kids[0]->parent = sub;
+                   if (sub->kids[0])
+                       sub->kids[0]->parent = sub;
 
-                   n->counts[ki+1] = countnode234(sub);
+                   n->counts[ki + 1] = countnode234(sub);
 
                    sfree(sib);
 
@@ -724,14 +804,15 @@ static void *delpos234_internal(tree234 *t, int index) {
                     * That's built the big node in sub. Now we
                     * need to remove the reference to sib in n.
                     */
-                   for (j = ki; j < 3 && n->kids[j+1]; j++) {
-                       n->kids[j] = n->kids[j+1];
-                       n->counts[j] = n->counts[j+1];
-                       n->elems[j] = j<2 ? n->elems[j+1] : NULL;
+                   for (j = ki; j < 3 && n->kids[j + 1]; j++) {
+                       n->kids[j] = n->kids[j + 1];
+                       n->counts[j] = n->counts[j + 1];
+                       n->elems[j] = j < 2 ? n->elems[j + 1] : NULL;
                    }
                    n->kids[j] = NULL;
                    n->counts[j] = 0;
-                   if (j < 3) n->elems[j] = NULL;
+                   if (j < 3)
+                       n->elems[j] = NULL;
                    LOG(("  case 3b ki=%d\n", ki));
 
                    if (!n->elems[0]) {
@@ -751,7 +832,7 @@ static void *delpos234_internal(tree234 *t, int index) {
        if (!retval)
            retval = n->elems[ei];
 
-       if (ei==-1)
+       if (ei == -1)
            return NULL;               /* although this shouldn't happen */
 
        /*
@@ -780,8 +861,8 @@ static void *delpos234_internal(tree234 *t, int index) {
             */
            int i;
            LOG(("  case 1\n"));
-           for (i = ei; i < 2 && n->elems[i+1]; i++)
-               n->elems[i] = n->elems[i+1];
+           for (i = ei; i < 2 && n->elems[i + 1]; i++)
+               n->elems[i] = n->elems[i + 1];
            n->elems[i] = NULL;
            /*
             * Having done that to the leaf node, we now go back up
@@ -811,19 +892,19 @@ static void *delpos234_internal(tree234 *t, int index) {
            while (m->kids[0]) {
                m = (m->kids[3] ? m->kids[3] :
                     m->kids[2] ? m->kids[2] :
-                    m->kids[1] ? m->kids[1] : m->kids[0]);                  
+                    m->kids[1] ? m->kids[1] : m->kids[0]);
            }
            target = (m->elems[2] ? m->elems[2] :
                      m->elems[1] ? m->elems[1] : m->elems[0]);
            n->elems[ei] = target;
-           index = n->counts[ei]-1;
+           index = n->counts[ei] - 1;
            n = n->kids[ei];
-       } else if (n->kids[ei+1]->elems[1]) {
+       } else if (n->kids[ei + 1]->elems[1]) {
            /*
             * Case 2b, symmetric to 2a but s/left/right/ and
             * s/predecessor/successor/. (And s/largest/smallest/).
             */
-           node234 *m = n->kids[ei+1];
+           node234 *m = n->kids[ei + 1];
            void *target;
            LOG(("  case 2b\n"));
            while (m->kids[0]) {
@@ -831,7 +912,7 @@ static void *delpos234_internal(tree234 *t, int index) {
            }
            target = m->elems[0];
            n->elems[ei] = target;
-           n = n->kids[ei+1];
+           n = n->kids[ei + 1];
            index = 0;
        } else {
            /*
@@ -842,43 +923,45 @@ static void *delpos234_internal(tree234 *t, int index) {
             * in the middle, then restart the deletion process on
             * that subtree, with e still as target.
             */
-           node234 *a = n->kids[ei], *b = n->kids[ei+1];
+           node234 *a = n->kids[ei], *b = n->kids[ei + 1];
            int j;
 
            LOG(("  case 2c\n"));
            a->elems[1] = n->elems[ei];
            a->kids[2] = b->kids[0];
            a->counts[2] = b->counts[0];
-           if (a->kids[2]) a->kids[2]->parent = a;
+           if (a->kids[2])
+               a->kids[2]->parent = a;
            a->elems[2] = b->elems[0];
            a->kids[3] = b->kids[1];
            a->counts[3] = b->counts[1];
-           if (a->kids[3]) a->kids[3]->parent = a;
+           if (a->kids[3])
+               a->kids[3]->parent = a;
            sfree(b);
            n->counts[ei] = countnode234(a);
            /*
             * That's built the big node in a, and destroyed b. Now
             * remove the reference to b (and e) in n.
             */
-           for (j = ei; j < 2 && n->elems[j+1]; j++) {
-               n->elems[j] = n->elems[j+1];
-               n->kids[j+1] = n->kids[j+2];
-               n->counts[j+1] = n->counts[j+2];
+           for (j = ei; j < 2 && n->elems[j + 1]; j++) {
+               n->elems[j] = n->elems[j + 1];
+               n->kids[j + 1] = n->kids[j + 2];
+               n->counts[j + 1] = n->counts[j + 2];
            }
            n->elems[j] = NULL;
-           n->kids[j+1] = NULL;
-           n->counts[j+1] = 0;
-            /*
-             * It's possible, in this case, that we've just removed
-             * the only element in the root of the tree. If so,
-             * shift the root.
-             */
-            if (n->elems[0] == NULL) {
-                LOG(("  shifting root!\n"));
-                t->root = a;
-                a->parent = NULL;
-                sfree(n);
-            }
+           n->kids[j + 1] = NULL;
+           n->counts[j + 1] = 0;
+           /*
+            * It's possible, in this case, that we've just removed
+            * the only element in the root of the tree. If so,
+            * shift the root.
+            */
+           if (n->elems[0] == NULL) {
+               LOG(("  shifting root!\n"));
+               t->root = a;
+               a->parent = NULL;
+               sfree(n);
+           }
            /*
             * Now go round the deletion process again, with n
             * pointing at the new big node and e still the same.
@@ -888,16 +971,18 @@ static void *delpos234_internal(tree234 *t, int index) {
        }
     }
 }
-void *delpos234(tree234 *t, int index) {
+void *delpos234(tree234 * t, int index)
+{
     if (index < 0 || index >= countnode234(t->root))
        return NULL;
     return delpos234_internal(t, index);
 }
-void *del234(tree234 *t, void *e) {
+void *del234(tree234 * t, void *e)
+{
     int index;
     if (!findrelpos234(t, e, NULL, REL234_EQ, &index))
        return NULL;                   /* it wasn't in there anyway */
-    return delpos234_internal(t, index); /* it's there; delete it. */
+    return delpos234_internal(t, index);       /* it's there; delete it. */
 }
 
 #ifdef TEST
@@ -932,7 +1017,8 @@ void *del234(tree234 *t, void *e) {
 /*
  * Error reporting function.
  */
-void error(char *fmt, ...) {
+void error(char *fmt, ...)
+{
     va_list ap;
     printf("ERROR: ");
     va_start(ap, fmt);
@@ -954,8 +1040,9 @@ typedef struct {
     int elemcount;
 } chkctx;
 
-int chknode(chkctx *ctx, int level, node234 *node,
-             void *lowbound, void *highbound) {
+int chknode(chkctx * ctx, int level, node234 * node,
+           void *lowbound, void *highbound)
+{
     int nkids, nelems;
     int i;
     int count;
@@ -964,51 +1051,51 @@ int chknode(chkctx *ctx, int level, node234 *node,
     for (nkids = 0; nkids < 4 && node->kids[nkids]; nkids++);
     /* Ensure no kids beyond the first NULL are non-NULL. */
     for (i = nkids; i < 4; i++)
-        if (node->kids[i]) {
-            error("node %p: nkids=%d but kids[%d] non-NULL",
-                   node, nkids, i);
-        } else if (node->counts[i]) {
-            error("node %p: kids[%d] NULL but count[%d]=%d nonzero",
-                   node, i, i, node->counts[i]);
+       if (node->kids[i]) {
+           error("node %p: nkids=%d but kids[%d] non-NULL",
+                 node, nkids, i);
+       } else if (node->counts[i]) {
+           error("node %p: kids[%d] NULL but count[%d]=%d nonzero",
+                 node, i, i, node->counts[i]);
        }
 
     /* Count the non-NULL elements. */
     for (nelems = 0; nelems < 3 && node->elems[nelems]; nelems++);
     /* Ensure no elements beyond the first NULL are non-NULL. */
     for (i = nelems; i < 3; i++)
-        if (node->elems[i]) {
-            error("node %p: nelems=%d but elems[%d] non-NULL",
-                   node, nelems, i);
-        }
+       if (node->elems[i]) {
+           error("node %p: nelems=%d but elems[%d] non-NULL",
+                 node, nelems, i);
+       }
 
     if (nkids == 0) {
-        /*
-         * If nkids==0, this is a leaf node; verify that the tree
-         * depth is the same everywhere.
-         */
-        if (ctx->treedepth < 0)
-            ctx->treedepth = level;    /* we didn't know the depth yet */
-        else if (ctx->treedepth != level)
-            error("node %p: leaf at depth %d, previously seen depth %d",
-                   node, level, ctx->treedepth);
+       /*
+        * If nkids==0, this is a leaf node; verify that the tree
+        * depth is the same everywhere.
+        */
+       if (ctx->treedepth < 0)
+           ctx->treedepth = level;    /* we didn't know the depth yet */
+       else if (ctx->treedepth != level)
+           error("node %p: leaf at depth %d, previously seen depth %d",
+                 node, level, ctx->treedepth);
     } else {
-        /*
-         * If nkids != 0, then it should be nelems+1, unless nelems
-         * is 0 in which case nkids should also be 0 (and so we
-         * shouldn't be in this condition at all).
-         */
-        int shouldkids = (nelems ? nelems+1 : 0);
-        if (nkids != shouldkids) {
-            error("node %p: %d elems should mean %d kids but has %d",
-                   node, nelems, shouldkids, nkids);
-        }
+       /*
+        * If nkids != 0, then it should be nelems+1, unless nelems
+        * is 0 in which case nkids should also be 0 (and so we
+        * shouldn't be in this condition at all).
+        */
+       int shouldkids = (nelems ? nelems + 1 : 0);
+       if (nkids != shouldkids) {
+           error("node %p: %d elems should mean %d kids but has %d",
+                 node, nelems, shouldkids, nkids);
+       }
     }
 
     /*
      * nelems should be at least 1.
      */
     if (nelems == 0) {
-        error("node %p: no elems", node, nkids);
+       error("node %p: no elems", node, nkids);
     }
 
     /*
@@ -1026,10 +1113,11 @@ int chknode(chkctx *ctx, int level, node234 *node,
     if (cmp) {
        for (i = -1; i < nelems; i++) {
            void *lower = (i == -1 ? lowbound : node->elems[i]);
-           void *higher = (i+1 == nelems ? highbound : node->elems[i+1]);
+           void *higher =
+               (i + 1 == nelems ? highbound : node->elems[i + 1]);
            if (lower && higher && cmp(lower, higher) >= 0) {
                error("node %p: kid comparison [%d=%s,%d=%s] failed",
-                     node, i, lower, i+1, higher);
+                     node, i, lower, i + 1, higher);
            }
        }
     }
@@ -1039,10 +1127,10 @@ int chknode(chkctx *ctx, int level, node234 *node,
      * parent pointer coming back to this node.
      */
     for (i = 0; i < nkids; i++)
-        if (node->kids[i]->parent != node) {
-            error("node %p kid %d: parent ptr is %p not %p",
-                   node, i, node->kids[i]->parent, node);
-        }
+       if (node->kids[i]->parent != node) {
+           error("node %p kid %d: parent ptr is %p not %p",
+                 node, i, node->kids[i]->parent, node);
+       }
 
 
     /*
@@ -1051,85 +1139,89 @@ int chknode(chkctx *ctx, int level, node234 *node,
     count = nelems;
 
     for (i = 0; i < nkids; i++) {
-        void *lower = (i == 0 ? lowbound : node->elems[i-1]);
-        void *higher = (i >= nelems ? highbound : node->elems[i]);
-       int subcount = chknode(ctx, level+1, node->kids[i], lower, higher);
+       void *lower = (i == 0 ? lowbound : node->elems[i - 1]);
+       void *higher = (i >= nelems ? highbound : node->elems[i]);
+       int subcount =
+           chknode(ctx, level + 1, node->kids[i], lower, higher);
        if (node->counts[i] != subcount) {
            error("node %p kid %d: count says %d, subtree really has %d",
                  node, i, node->counts[i], subcount);
        }
-        count += subcount;
+       count += subcount;
     }
 
     return count;
 }
 
-void verify(void) {
+void verify(void)
+{
     chkctx ctx;
     int i;
     void *p;
 
-    ctx.treedepth = -1;                /* depth unknown yet */
-    ctx.elemcount = 0;                 /* no elements seen yet */
+    ctx.treedepth = -1;                       /* depth unknown yet */
+    ctx.elemcount = 0;                /* no elements seen yet */
     /*
      * Verify validity of tree properties.
      */
     if (tree->root) {
        if (tree->root->parent != NULL)
            error("root->parent is %p should be null", tree->root->parent);
-        chknode(&ctx, 0, tree->root, NULL, NULL);
+       chknode(&ctx, 0, tree->root, NULL, NULL);
     }
     printf("tree depth: %d\n", ctx.treedepth);
     /*
      * Enumerate the tree and ensure it matches up to the array.
      */
     for (i = 0; NULL != (p = index234(tree, i)); i++) {
-        if (i >= arraylen)
-            error("tree contains more than %d elements", arraylen);
-        if (array[i] != p)
-            error("enum at position %d: array says %s, tree says %s",
-                   i, array[i], p);
+       if (i >= arraylen)
+           error("tree contains more than %d elements", arraylen);
+       if (array[i] != p)
+           error("enum at position %d: array says %s, tree says %s",
+                 i, array[i], p);
     }
     if (ctx.elemcount != i) {
-        error("tree really contains %d elements, enum gave %d",
-               ctx.elemcount, i);
+       error("tree really contains %d elements, enum gave %d",
+             ctx.elemcount, i);
     }
     if (i < arraylen) {
-        error("enum gave only %d elements, array has %d", i, arraylen);
+       error("enum gave only %d elements, array has %d", i, arraylen);
     }
     i = count234(tree);
     if (ctx.elemcount != i) {
-        error("tree really contains %d elements, count234 gave %d",
+       error("tree really contains %d elements, count234 gave %d",
              ctx.elemcount, i);
     }
 }
 
-void internal_addtest(void *elem, int index, void *realret) {
+void internal_addtest(void *elem, int index, void *realret)
+{
     int i, j;
     void *retval;
 
-    if (arraysize < arraylen+1) {
-        arraysize = arraylen+1+256;
-        array = (array == NULL ? smalloc(arraysize*sizeof(*array)) :
-                 srealloc(array, arraysize*sizeof(*array)));
+    if (arraysize < arraylen + 1) {
+       arraysize = arraylen + 1 + 256;
+       array = (array == NULL ? smalloc(arraysize * sizeof(*array)) :
+                srealloc(array, arraysize * sizeof(*array)));
     }
 
     i = index;
     /* now i points to the first element >= elem */
-    retval = elem;                  /* expect elem returned (success) */
+    retval = elem;                    /* expect elem returned (success) */
     for (j = arraylen; j > i; j--)
-       array[j] = array[j-1];
-    array[i] = elem;                /* add elem to array */
+       array[j] = array[j - 1];
+    array[i] = elem;                  /* add elem to array */
     arraylen++;
 
     if (realret != retval) {
-        error("add: retval was %p expected %p", realret, retval);
+       error("add: retval was %p expected %p", realret, retval);
     }
 
     verify();
 }
 
-void addtest(void *elem) {
+void addtest(void *elem)
+{
     int i;
     void *realret;
 
@@ -1137,9 +1229,9 @@ void addtest(void *elem) {
 
     i = 0;
     while (i < arraylen && cmp(elem, array[i]) > 0)
-        i++;
+       i++;
     if (i < arraylen && !cmp(elem, array[i])) {
-        void *retval = array[i];       /* expect that returned not elem */
+       void *retval = array[i];       /* expect that returned not elem */
        if (realret != retval) {
            error("add: retval was %p expected %p", realret, retval);
        }
@@ -1147,7 +1239,8 @@ void addtest(void *elem) {
        internal_addtest(elem, i, realret);
 }
 
-void addpostest(void *elem, int i) {
+void addpostest(void *elem, int i)
+{
     void *realret;
 
     realret = addpos234(tree, elem, i);
@@ -1155,13 +1248,14 @@ void addpostest(void *elem, int i) {
     internal_addtest(elem, i, realret);
 }
 
-void delpostest(int i) {
+void delpostest(int i)
+{
     int index = i;
     void *elem = array[i], *ret;
 
     /* i points to the right element */
-    while (i < arraylen-1) {
-       array[i] = array[i+1];
+    while (i < arraylen - 1) {
+       array[i] = array[i + 1];
        i++;
     }
     arraylen--;                               /* delete elem from array */
@@ -1178,14 +1272,15 @@ void delpostest(int i) {
     verify();
 }
 
-void deltest(void *elem) {
+void deltest(void *elem)
+{
     int i;
 
     i = 0;
     while (i < arraylen && cmp(elem, array[i]) > 0)
-        i++;
+       i++;
     if (i >= arraylen || cmp(elem, array[i]) != 0)
-        return;                        /* don't do it! */
+       return;                        /* don't do it! */
     delpostest(i);
 }
 
@@ -1197,15 +1292,17 @@ void deltest(void *elem) {
  * given in ANSI C99 draft N869. It assumes `unsigned' is 32 bits;
  * change it if not.
  */
-int randomnumber(unsigned *seed) {
+int randomnumber(unsigned *seed)
+{
     *seed *= 1103515245;
     *seed += 12345;
     return ((*seed) / 65536) % 32768;
 }
 
-int mycmp(void *av, void *bv) {
-    char const *a = (char const *)av;
-    char const *b = (char const *)bv;
+int mycmp(void *av, void *bv)
+{
+    char const *a = (char const *) av;
+    char const *b = (char const *) bv;
     return strcmp(a, b);
 }
 
@@ -1227,7 +1324,8 @@ char *strings[] = {
 
 #define NSTR lenof(strings)
 
-int findtest(void) {
+int findtest(void)
+{
     const static int rels[] = {
        REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT
     };
@@ -1240,17 +1338,18 @@ int findtest(void) {
 
     for (i = 0; i < NSTR; i++) {
        p = strings[i];
-       for (j = 0; j < sizeof(rels)/sizeof(*rels); j++) {
+       for (j = 0; j < sizeof(rels) / sizeof(*rels); j++) {
            rel = rels[j];
 
-           lo = 0; hi = arraylen-1;
+           lo = 0;
+           hi = arraylen - 1;
            while (lo <= hi) {
                mid = (lo + hi) / 2;
                c = strcmp(p, array[mid]);
                if (c < 0)
-                   hi = mid-1;
+                   hi = mid - 1;
                else if (c > 0)
-                   lo = mid+1;
+                   lo = mid + 1;
                else
                    break;
            }
@@ -1259,11 +1358,11 @@ int findtest(void) {
                if (rel == REL234_LT)
                    ret = (mid > 0 ? array[--mid] : NULL);
                else if (rel == REL234_GT)
-                   ret = (mid < arraylen-1 ? array[++mid] : NULL);
+                   ret = (mid < arraylen - 1 ? array[++mid] : NULL);
                else
                    ret = array[mid];
            } else {
-               assert(lo == hi+1);
+               assert(lo == hi + 1);
                if (rel == REL234_LT || rel == REL234_LE) {
                    mid = hi;
                    ret = (hi >= 0 ? array[hi] : NULL);
@@ -1302,26 +1401,27 @@ int findtest(void) {
        error("find(NULL,GT) gave %s(%d) should be %s(0)",
              realret, index, array[0]);
     } else if (!arraylen && (realret != NULL)) {
-       error("find(NULL,GT) gave %s(%d) should be NULL",
-             realret, index);
+       error("find(NULL,GT) gave %s(%d) should be NULL", realret, index);
     }
 
     realret = findrelpos234(tree, NULL, NULL, REL234_LT, &index);
-    if (arraylen && (realret != array[arraylen-1] || index != arraylen-1)) {
-       error("find(NULL,LT) gave %s(%d) should be %s(0)",
-             realret, index, array[arraylen-1]);
+    if (arraylen
+       && (realret != array[arraylen - 1] || index != arraylen - 1)) {
+       error("find(NULL,LT) gave %s(%d) should be %s(0)", realret, index,
+             array[arraylen - 1]);
     } else if (!arraylen && (realret != NULL)) {
-       error("find(NULL,LT) gave %s(%d) should be NULL",
-             realret, index);
+       error("find(NULL,LT) gave %s(%d) should be NULL", realret, index);
     }
 }
 
-int main(void) {
+int main(void)
+{
     int in[NSTR];
     int i, j, k;
     unsigned seed = 0;
 
-    for (i = 0; i < NSTR; i++) in[i] = 0;
+    for (i = 0; i < NSTR; i++)
+       in[i] = 0;
     array = NULL;
     arraylen = arraysize = 0;
     tree = newtree234(mycmp);
@@ -1329,25 +1429,25 @@ int main(void) {
 
     verify();
     for (i = 0; i < 10000; i++) {
-        j = randomnumber(&seed);
-        j %= NSTR;
-        printf("trial: %d\n", i);
-        if (in[j]) {
-            printf("deleting %s (%d)\n", strings[j], j);
-            deltest(strings[j]);
-            in[j] = 0;
-        } else {
-            printf("adding %s (%d)\n", strings[j], j);
-            addtest(strings[j]);
-            in[j] = 1;
-        }
+       j = randomnumber(&seed);
+       j %= NSTR;
+       printf("trial: %d\n", i);
+       if (in[j]) {
+           printf("deleting %s (%d)\n", strings[j], j);
+           deltest(strings[j]);
+           in[j] = 0;
+       } else {
+           printf("adding %s (%d)\n", strings[j], j);
+           addtest(strings[j]);
+           in[j] = 1;
+       }
        findtest();
     }
 
     while (arraylen > 0) {
-        j = randomnumber(&seed);
-        j %= arraylen;
-        deltest(array[j]);
+       j = randomnumber(&seed);
+       j %= arraylen;
+       deltest(array[j]);
     }
 
     freetree234(tree);
@@ -1367,7 +1467,7 @@ int main(void) {
        j = randomnumber(&seed);
        j %= NSTR;
        k = randomnumber(&seed);
-       k %= count234(tree)+1;
+       k %= count234(tree) + 1;
        printf("adding string %s at index %d\n", strings[j], k);
        addpostest(strings[j], k);
     }
index 02a973e..ba74308 100644 (file)
--- a/tree234.h
+++ b/tree234.h
@@ -33,7 +33,7 @@
  */
 typedef struct tree234_Tag tree234;
 
-typedef int (*cmpfn234)(void *, void *);
+typedef int (*cmpfn234) (void *, void *);
 
 /*
  * Create a 2-3-4 tree. If `cmp' is NULL, the tree is unsorted, and
@@ -45,13 +45,13 @@ tree234 *newtree234(cmpfn234 cmp);
 /*
  * Free a 2-3-4 tree (not including freeing the elements).
  */
-void freetree234(tree234 *t);
+void freetree234(tree234 * t);
 
 /*
  * Add an element e to a sorted 2-3-4 tree t. Returns e on success,
  * or if an existing element compares equal, returns that.
  */
-void *add234(tree234 *t, void *e);
+void *add234(tree234 * t, void *e);
 
 /*
  * Add an element e to an unsorted 2-3-4 tree t. Returns e on
@@ -61,7 +61,7 @@ void *add234(tree234 *t, void *e);
  * Index range can be from 0 to the tree's current element count,
  * inclusive.
  */
-void *addpos234(tree234 *t, void *e, int index);
+void *addpos234(tree234 * t, void *e, int index);
 
 /*
  * Look up the element at a given numeric index in a 2-3-4 tree.
@@ -81,7 +81,7 @@ void *addpos234(tree234 *t, void *e, int index);
  *       consume(p);
  *   }
  */
-void *index234(tree234 *t, int index);
+void *index234(tree234 * t, int index);
 
 /*
  * Find an element e in a sorted 2-3-4 tree t. Returns NULL if not
@@ -126,10 +126,10 @@ void *index234(tree234 *t, int index);
 enum {
     REL234_EQ, REL234_LT, REL234_LE, REL234_GT, REL234_GE
 };
-void *find234(tree234 *t, void *e, cmpfn234 cmp);
-void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation);
-void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index);
-void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
+void *find234(tree234 * t, void *e, cmpfn234 cmp);
+void *findrel234(tree234 * t, void *e, cmpfn234 cmp, int relation);
+void *findpos234(tree234 * t, void *e, cmpfn234 cmp, int *index);
+void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp, int relation,
                    int *index);
 
 /*
@@ -149,12 +149,12 @@ void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
  * is out of range (delpos234) or the element is already not in the
  * tree (del234) then they return NULL.
  */
-void *del234(tree234 *t, void *e);
-void *delpos234(tree234 *t, int index);
+void *del234(tree234 * t, void *e);
+void *delpos234(tree234 * t, int index);
 
 /*
  * Return the total element count of a tree234.
  */
-int count234(tree234 *t);
+int count234(tree234 * t);
 
-#endif /* TREE234_H */
+#endif                         /* TREE234_H */
index 0e85dbe..f87d265 100644 (file)
@@ -22,7 +22,8 @@
 #define PROGBARHEIGHT 14
 
 void ctlposinit(struct ctlpos *cp, HWND hwnd,
-                int leftborder, int rightborder, int topborder) {
+               int leftborder, int rightborder, int topborder)
+{
     RECT r, r2;
     cp->hwnd = hwnd;
     cp->font = SendMessage(hwnd, WM_GETFONT, 0, 0);
@@ -33,14 +34,14 @@ void ctlposinit(struct ctlpos *cp, HWND hwnd,
     r2.bottom = 8;
     MapDialogRect(hwnd, &r2);
     cp->dlu4inpix = r2.right;
-    cp->width = (r.right * 4) / (r2.right) - 2*GAPBETWEEN;
+    cp->width = (r.right * 4) / (r2.right) - 2 * GAPBETWEEN;
     cp->xoff = leftborder;
     cp->width -= leftborder + rightborder;
 }
 
 void doctl(struct ctlpos *cp, RECT r,
-           char *wclass, int wstyle, int exstyle,
-           char *wtext, int wid) {
+          char *wclass, int wstyle, int exstyle, char *wtext, int wid)
+{
     HWND ctl;
     /*
      * Note nonstandard use of RECT. This is deliberate: by
@@ -52,19 +53,22 @@ void doctl(struct ctlpos *cp, RECT r,
     MapDialogRect(cp->hwnd, &r);
 
     ctl = CreateWindowEx(exstyle, wclass, wtext, wstyle,
-                         r.left, r.top, r.right, r.bottom,
-                         cp->hwnd, (HMENU)wid, hinst, NULL);
+                        r.left, r.top, r.right, r.bottom,
+                        cp->hwnd, (HMENU) wid, hinst, NULL);
     SendMessage(ctl, WM_SETFONT, cp->font, MAKELPARAM(TRUE, 0));
 }
 
 /*
  * A title bar across the top of a sub-dialog.
  */
-void bartitle(struct ctlpos *cp, char *name, int id) {
+void bartitle(struct ctlpos *cp, char *name, int id)
+{
     RECT r;
 
-    r.left = GAPBETWEEN; r.right = cp->width;
-    r.top = cp->ypos; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.right = cp->width;
+    r.top = cp->ypos;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, name, id);
 }
@@ -72,14 +76,15 @@ void bartitle(struct ctlpos *cp, char *name, int id) {
 /*
  * Begin a grouping box, with or without a group title.
  */
-void beginbox(struct ctlpos *cp, char *name, int idbox) {
+void beginbox(struct ctlpos *cp, char *name, int idbox)
+{
     cp->boxystart = cp->ypos;
     if (!name)
-        cp->boxystart -= STATICHEIGHT/2;
+       cp->boxystart -= STATICHEIGHT / 2;
     if (name)
-        cp->ypos += STATICHEIGHT;
+       cp->ypos += STATICHEIGHT;
     cp->ypos += GAPYBOX;
-    cp->width -= 2*GAPXBOX;
+    cp->width -= 2 * GAPXBOX;
     cp->xoff += GAPXBOX;
     cp->boxid = idbox;
     cp->boxtext = name;
@@ -88,15 +93,18 @@ void beginbox(struct ctlpos *cp, char *name, int idbox) {
 /*
  * End a grouping box.
  */
-void endbox(struct ctlpos *cp) {
+void endbox(struct ctlpos *cp)
+{
     RECT r;
     cp->xoff -= GAPXBOX;
-    cp->width += 2*GAPXBOX;
+    cp->width += 2 * GAPXBOX;
     cp->ypos += GAPYBOX - GAPBETWEEN;
-    r.left = GAPBETWEEN; r.right = cp->width;
-    r.top = cp->boxystart; r.bottom = cp->ypos - cp->boxystart;
+    r.left = GAPBETWEEN;
+    r.right = cp->width;
+    r.top = cp->boxystart;
+    r.bottom = cp->ypos - cp->boxystart;
     doctl(cp, r, "BUTTON", BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 0,
-          cp->boxtext ? cp->boxtext : "", cp->boxid);
+         cp->boxtext ? cp->boxtext : "", cp->boxid);
     cp->ypos += GAPYBOX;
 }
 
@@ -104,7 +112,8 @@ void endbox(struct ctlpos *cp) {
  * Some edit boxes. Each one has a static above it. The percentages
  * of the horizontal space are provided.
  */
-void multiedit(struct ctlpos *cp, ...) {
+void multiedit(struct ctlpos *cp, ...)
+{
     RECT r;
     va_list ap;
     int percent, xpos;
@@ -112,31 +121,31 @@ void multiedit(struct ctlpos *cp, ...) {
     percent = xpos = 0;
     va_start(ap, cp);
     while (1) {
-        char *text;
-        int staticid, editid, pcwidth;
-        text = va_arg(ap, char *);
-        if (!text)
-            break;
-        staticid = va_arg(ap, int);
-        editid = va_arg(ap, int);
-        pcwidth = va_arg(ap, int);
-
-        r.left = xpos + GAPBETWEEN;
-        percent += pcwidth;
-        xpos = (cp->width + GAPBETWEEN) * percent / 100;
-        r.right = xpos - r.left;
-
-        r.top = cp->ypos; r.bottom = STATICHEIGHT;
-        doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0,
-              text, staticid);
-        r.top = cp->ypos + 8 + GAPWITHIN; r.bottom = EDITHEIGHT;
-        doctl(cp, r, "EDIT",
-              WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
-              WS_EX_CLIENTEDGE,
-              "", editid);
+       char *text;
+       int staticid, editid, pcwidth;
+       text = va_arg(ap, char *);
+       if (!text)
+           break;
+       staticid = va_arg(ap, int);
+       editid = va_arg(ap, int);
+       pcwidth = va_arg(ap, int);
+
+       r.left = xpos + GAPBETWEEN;
+       percent += pcwidth;
+       xpos = (cp->width + GAPBETWEEN) * percent / 100;
+       r.right = xpos - r.left;
+
+       r.top = cp->ypos;
+       r.bottom = STATICHEIGHT;
+       doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid);
+       r.top = cp->ypos + 8 + GAPWITHIN;
+       r.bottom = EDITHEIGHT;
+       doctl(cp, r, "EDIT",
+             WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
+             WS_EX_CLIENTEDGE, "", editid);
     }
     va_end(ap);
-    cp->ypos += 8+GAPWITHIN+12+GAPBETWEEN;
+    cp->ypos += 8 + GAPWITHIN + 12 + GAPBETWEEN;
 }
 
 /*
@@ -153,16 +162,18 @@ void multiedit(struct ctlpos *cp, ...) {
  * 
  * (*) Button1  (*) Button2  (*) ButtonWithReallyLongTitle
  */
-void radioline(struct ctlpos *cp,
-               char *text, int id, int nacross, ...) {
+void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...)
+{
     RECT r;
     va_list ap;
     int group;
     int i;
     char *btext;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, id);
     va_start(ap, nacross);
@@ -170,29 +181,30 @@ void radioline(struct ctlpos *cp,
     i = 0;
     btext = va_arg(ap, char *);
     while (1) {
-        char *nextbtext;
-        int bid;
-        if (!btext)
-            break;
-       if (i==nacross) {
+       char *nextbtext;
+       int bid;
+       if (!btext)
+           break;
+       if (i == nacross) {
            cp->ypos += r.bottom + GAPBETWEEN;
-           i=0;
+           i = 0;
        }
-        bid = va_arg(ap, int);
-        nextbtext = va_arg(ap, char *);
-        r.left = GAPBETWEEN + i * (cp->width+GAPBETWEEN)/nacross;
-        if (nextbtext)
-            r.right = (i+1) * (cp->width+GAPBETWEEN)/nacross - r.left;
-        else
-            r.right = cp->width - r.left;
-        r.top = cp->ypos; r.bottom = RADIOHEIGHT;
-        doctl(cp, r, "BUTTON",
-              BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP | group,
-              0,
-              btext, bid);
-        group = 0;
-        i++;
-        btext = nextbtext;
+       bid = va_arg(ap, int);
+       nextbtext = va_arg(ap, char *);
+       r.left = GAPBETWEEN + i * (cp->width + GAPBETWEEN) / nacross;
+       if (nextbtext)
+           r.right =
+               (i + 1) * (cp->width + GAPBETWEEN) / nacross - r.left;
+       else
+           r.right = cp->width - r.left;
+       r.top = cp->ypos;
+       r.bottom = RADIOHEIGHT;
+       doctl(cp, r, "BUTTON",
+             BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP |
+             group, 0, btext, bid);
+       group = 0;
+       i++;
+       btext = nextbtext;
     }
     va_end(ap);
     cp->ypos += r.bottom + GAPBETWEEN;
@@ -202,32 +214,36 @@ void radioline(struct ctlpos *cp,
  * A set of radio buttons on multiple lines, with a static above
  * them.
  */
-void radiobig(struct ctlpos *cp, char *text, int id, ...) {
+void radiobig(struct ctlpos *cp, char *text, int id, ...)
+{
     RECT r;
     va_list ap;
     int group;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, id);
     va_start(ap, id);
     group = WS_GROUP;
     while (1) {
-        char *btext;
-        int bid;
-        btext = va_arg(ap, char *);
-        if (!btext)
-            break;
-        bid = va_arg(ap, int);
-        r.left = GAPBETWEEN; r.top = cp->ypos;
-        r.right = cp->width; r.bottom = STATICHEIGHT;
-        cp->ypos += r.bottom + GAPWITHIN;
-        doctl(cp, r, "BUTTON",
-              BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP | group,
-              0,
-              btext, bid);
-        group = 0;
+       char *btext;
+       int bid;
+       btext = va_arg(ap, char *);
+       if (!btext)
+           break;
+       bid = va_arg(ap, int);
+       r.left = GAPBETWEEN;
+       r.top = cp->ypos;
+       r.right = cp->width;
+       r.bottom = STATICHEIGHT;
+       cp->ypos += r.bottom + GAPWITHIN;
+       doctl(cp, r, "BUTTON",
+             BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP |
+             group, 0, btext, bid);
+       group = 0;
     }
     va_end(ap);
     cp->ypos += GAPBETWEEN - GAPWITHIN;
@@ -236,25 +252,31 @@ void radiobig(struct ctlpos *cp, char *text, int id, ...) {
 /*
  * A single standalone checkbox.
  */
-void checkbox(struct ctlpos *cp, char *text, int id) {
+void checkbox(struct ctlpos *cp, char *text, int id)
+{
     RECT r;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = CHECKBOXHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = CHECKBOXHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
     doctl(cp, r, "BUTTON",
-          BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0,
-          text, id);
+         BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0,
+         text, id);
 }
 
 /*
  * A single standalone static text control.
  */
-void statictext(struct ctlpos *cp, char *text, int id) {
+void statictext(struct ctlpos *cp, char *text, int id)
+{
     RECT r;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, id);
 }
@@ -263,26 +285,30 @@ void statictext(struct ctlpos *cp, char *text, int id) {
  * A button on the right hand side, with a static to its left.
  */
 void staticbtn(struct ctlpos *cp, char *stext, int sid,
-               char *btext, int bid) {
+              char *btext, int bid)
+{
     const int height = (PUSHBTNHEIGHT > STATICHEIGHT ?
-                        PUSHBTNHEIGHT : STATICHEIGHT);
+                       PUSHBTNHEIGHT : STATICHEIGHT);
     RECT r;
     int lwid, rwid, rpos;
 
     rpos = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
-    lwid = rpos - 2*GAPBETWEEN;
+    lwid = rpos - 2 * GAPBETWEEN;
     rwid = cp->width + GAPBETWEEN - rpos;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos + (height-STATICHEIGHT)/2;
-    r.right = lwid; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos + (height - STATICHEIGHT) / 2;
+    r.right = lwid;
+    r.bottom = STATICHEIGHT;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
-    r.left = rpos; r.top = cp->ypos + (height-PUSHBTNHEIGHT)/2;
-    r.right = rwid; r.bottom = PUSHBTNHEIGHT;
+    r.left = rpos;
+    r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
+    r.right = rwid;
+    r.bottom = PUSHBTNHEIGHT;
     doctl(cp, r, "BUTTON",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-          0,
-          btext, bid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+         0, btext, bid);
 
     cp->ypos += height + GAPBETWEEN;
 }
@@ -291,38 +317,45 @@ void staticbtn(struct ctlpos *cp, char *stext, int sid,
  * An edit control on the right hand side, with a static to its left.
  */
 static void staticedit_internal(struct ctlpos *cp, char *stext,
-                                int sid, int eid, int percentedit,
-                                int style) {
+                               int sid, int eid, int percentedit,
+                               int style)
+{
     const int height = (EDITHEIGHT > STATICHEIGHT ?
-                        EDITHEIGHT : STATICHEIGHT);
+                       EDITHEIGHT : STATICHEIGHT);
     RECT r;
     int lwid, rwid, rpos;
 
-    rpos = GAPBETWEEN + (100-percentedit) * (cp->width + GAPBETWEEN) / 100;
-    lwid = rpos - 2*GAPBETWEEN;
+    rpos =
+       GAPBETWEEN + (100 - percentedit) * (cp->width + GAPBETWEEN) / 100;
+    lwid = rpos - 2 * GAPBETWEEN;
     rwid = cp->width + GAPBETWEEN - rpos;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos + (height-STATICHEIGHT)/2;
-    r.right = lwid; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos + (height - STATICHEIGHT) / 2;
+    r.right = lwid;
+    r.bottom = STATICHEIGHT;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
-    r.left = rpos; r.top = cp->ypos + (height-EDITHEIGHT)/2;
-    r.right = rwid; r.bottom = EDITHEIGHT;
+    r.left = rpos;
+    r.top = cp->ypos + (height - EDITHEIGHT) / 2;
+    r.right = rwid;
+    r.bottom = EDITHEIGHT;
     doctl(cp, r, "EDIT",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | style,
-          WS_EX_CLIENTEDGE,
-          "", eid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | style,
+         WS_EX_CLIENTEDGE, "", eid);
 
     cp->ypos += height + GAPBETWEEN;
 }
 
 void staticedit(struct ctlpos *cp, char *stext,
-                int sid, int eid, int percentedit) {
+               int sid, int eid, int percentedit)
+{
     staticedit_internal(cp, stext, sid, eid, percentedit, 0);
 }
 
 void staticpassedit(struct ctlpos *cp, char *stext,
-                    int sid, int eid, int percentedit) {
+                   int sid, int eid, int percentedit)
+{
     staticedit_internal(cp, stext, sid, eid, percentedit, ES_PASSWORD);
 }
 
@@ -330,59 +363,67 @@ void staticpassedit(struct ctlpos *cp, char *stext,
  * A big multiline edit control with a static labelling it.
  */
 void bigeditctrl(struct ctlpos *cp, char *stext,
-                 int sid, int eid, int lines) {
+                int sid, int eid, int lines)
+{
     RECT r;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = EDITHEIGHT + (lines-1) * STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = EDITHEIGHT + (lines - 1) * STATICHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
     doctl(cp, r, "EDIT",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | ES_MULTILINE,
-          WS_EX_CLIENTEDGE,
-          "", eid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | ES_MULTILINE,
+         WS_EX_CLIENTEDGE, "", eid);
 }
 
 /*
  * A tab-control substitute when a real tab control is unavailable.
  */
-void ersatztab(struct ctlpos *cp, char *stext, int sid,
-               int lid, int s2id) {
+void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id)
+{
     const int height = (COMBOHEIGHT > STATICHEIGHT ?
-                        COMBOHEIGHT : STATICHEIGHT);
+                       COMBOHEIGHT : STATICHEIGHT);
     RECT r;
     int bigwid, lwid, rwid, rpos;
     static const int BIGGAP = 15;
     static const int MEDGAP = 3;
 
-    bigwid = cp->width + 2*GAPBETWEEN - 2*BIGGAP;
+    bigwid = cp->width + 2 * GAPBETWEEN - 2 * BIGGAP;
     cp->ypos += MEDGAP;
     rpos = BIGGAP + (bigwid + BIGGAP) / 2;
-    lwid = rpos - 2*BIGGAP;
+    lwid = rpos - 2 * BIGGAP;
     rwid = bigwid + BIGGAP - rpos;
 
-    r.left = BIGGAP; r.top = cp->ypos + (height-STATICHEIGHT)/2;
-    r.right = lwid; r.bottom = STATICHEIGHT;
+    r.left = BIGGAP;
+    r.top = cp->ypos + (height - STATICHEIGHT) / 2;
+    r.right = lwid;
+    r.bottom = STATICHEIGHT;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
-    r.left = rpos; r.top = cp->ypos + (height-COMBOHEIGHT)/2;
-    r.right = rwid; r.bottom = COMBOHEIGHT*10;
+    r.left = rpos;
+    r.top = cp->ypos + (height - COMBOHEIGHT) / 2;
+    r.right = rwid;
+    r.bottom = COMBOHEIGHT * 10;
     doctl(cp, r, "COMBOBOX",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP |
-          CBS_DROPDOWNLIST | CBS_HASSTRINGS,
-          WS_EX_CLIENTEDGE,
-          "", lid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP |
+         CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid);
 
     cp->ypos += height + MEDGAP + GAPBETWEEN;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = 2;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = 2;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_ETCHEDHORZ,
-          0, "", s2id);
+         0, "", s2id);
 }
 
 /*
@@ -390,34 +431,39 @@ void ersatztab(struct ctlpos *cp, char *stext, int sid,
  * and a button on the right.
  */
 void editbutton(struct ctlpos *cp, char *stext, int sid,
-                int eid, char *btext, int bid) {
+               int eid, char *btext, int bid)
+{
     const int height = (EDITHEIGHT > PUSHBTNHEIGHT ?
-                        EDITHEIGHT : PUSHBTNHEIGHT);
+                       EDITHEIGHT : PUSHBTNHEIGHT);
     RECT r;
     int lwid, rwid, rpos;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
     rpos = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
-    lwid = rpos - 2*GAPBETWEEN;
+    lwid = rpos - 2 * GAPBETWEEN;
     rwid = cp->width + GAPBETWEEN - rpos;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos + (height-EDITHEIGHT)/2;
-    r.right = lwid; r.bottom = EDITHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos + (height - EDITHEIGHT) / 2;
+    r.right = lwid;
+    r.bottom = EDITHEIGHT;
     doctl(cp, r, "EDIT",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
-          WS_EX_CLIENTEDGE,
-          "", eid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
+         WS_EX_CLIENTEDGE, "", eid);
 
-    r.left = rpos; r.top = cp->ypos + (height-PUSHBTNHEIGHT)/2;
-    r.right = rwid; r.bottom = PUSHBTNHEIGHT;
+    r.left = rpos;
+    r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2;
+    r.right = rwid;
+    r.bottom = PUSHBTNHEIGHT;
     doctl(cp, r, "BUTTON",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-          0,
-          btext, bid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+         0, btext, bid);
 
     cp->ypos += height + GAPBETWEEN;
 }
@@ -429,7 +475,8 @@ void editbutton(struct ctlpos *cp, char *stext, int sid,
  * buttons.
  */
 void sesssaver(struct ctlpos *cp, char *text,
-               int staticid, int editid, int listid, ...) {
+              int staticid, int editid, int listid, ...)
+{
     RECT r;
     va_list ap;
     int lwid, rwid, rpos;
@@ -437,23 +484,26 @@ void sesssaver(struct ctlpos *cp, char *text,
     const int LISTDEFHEIGHT = 66;
 
     rpos = GAPBETWEEN + 3 * (cp->width + GAPBETWEEN) / 4;
-    lwid = rpos - 2*GAPBETWEEN;
+    lwid = rpos - 2 * GAPBETWEEN;
     rwid = cp->width + GAPBETWEEN - rpos;
 
     /* The static control. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = lwid; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = lwid;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid);
 
     /* The edit control. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = lwid; r.bottom = EDITHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = lwid;
+    r.bottom = EDITHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "EDIT",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
-          WS_EX_CLIENTEDGE,
-          "", editid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
+         WS_EX_CLIENTEDGE, "", editid);
 
     /*
      * The buttons (we should hold off on the list box until we
@@ -462,31 +512,34 @@ void sesssaver(struct ctlpos *cp, char *text,
     va_start(ap, listid);
     y = cp->ypos;
     while (1) {
-        char *btext = va_arg(ap, char *);
-        int bid;
-        if (!btext) break;
-        bid = va_arg(ap, int);
-        r.left = rpos; r.top = y;
-        r.right = rwid; r.bottom = PUSHBTNHEIGHT;
-        y += r.bottom + GAPWITHIN;
-        doctl(cp, r, "BUTTON",
-              WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-              0,
-              btext, bid);
+       char *btext = va_arg(ap, char *);
+       int bid;
+       if (!btext)
+           break;
+       bid = va_arg(ap, int);
+       r.left = rpos;
+       r.top = y;
+       r.right = rwid;
+       r.bottom = PUSHBTNHEIGHT;
+       y += r.bottom + GAPWITHIN;
+       doctl(cp, r, "BUTTON",
+             WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+             0, btext, bid);
     }
 
     /* Compute list box height. LISTDEFHEIGHT, or height of buttons. */
     y -= cp->ypos;
     y -= GAPWITHIN;
-    if (y < LISTDEFHEIGHT) y = LISTDEFHEIGHT;
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = lwid; r.bottom = y;
+    if (y < LISTDEFHEIGHT)
+       y = LISTDEFHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = lwid;
+    r.bottom = y;
     cp->ypos += y + GAPBETWEEN;
     doctl(cp, r, "LISTBOX",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | 
-          LBS_NOTIFY | LBS_HASSTRINGS,
-          WS_EX_CLIENTEDGE,
-          "", listid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL |
+         LBS_NOTIFY | LBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", listid);
 }
 
 /*
@@ -495,66 +548,65 @@ void sesssaver(struct ctlpos *cp, char *text,
  * statics, and two buttons; then a list box.
  */
 void envsetter(struct ctlpos *cp, char *stext, int sid,
-               char *e1stext, int e1sid, int e1id,
-               char *e2stext, int e2sid, int e2id,
-               int listid,
-               char *b1text, int b1id, char *b2text, int b2id) {
+              char *e1stext, int e1sid, int e1id,
+              char *e2stext, int e2sid, int e2id,
+              int listid, char *b1text, int b1id, char *b2text, int b2id)
+{
     RECT r;
-    const int height = (STATICHEIGHT > EDITHEIGHT && STATICHEIGHT > PUSHBTNHEIGHT ?
-                        STATICHEIGHT :
-                        EDITHEIGHT > PUSHBTNHEIGHT ?
-                        EDITHEIGHT : PUSHBTNHEIGHT);
+    const int height = (STATICHEIGHT > EDITHEIGHT
+                       && STATICHEIGHT >
+                       PUSHBTNHEIGHT ? STATICHEIGHT : EDITHEIGHT >
+                       PUSHBTNHEIGHT ? EDITHEIGHT : PUSHBTNHEIGHT);
     const static int percents[] = { 20, 35, 10, 25 };
     int i, j, xpos, percent;
     const int LISTHEIGHT = 42;
 
     /* The static control. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
     /* The statics+edits+buttons. */
     for (j = 0; j < 2; j++) {
-        percent = 10;
-        for (i = 0; i < 4; i++) {
-            xpos = (cp->width + GAPBETWEEN) * percent / 100;
-            r.left = xpos + GAPBETWEEN;
-            percent += percents[i];
-            xpos = (cp->width + GAPBETWEEN) * percent / 100;
-            r.right = xpos - r.left;
-            r.top = cp->ypos;
-            r.bottom = (i==0 ? STATICHEIGHT :
-                        i==1 ? EDITHEIGHT :
-                        PUSHBTNHEIGHT);
-            r.top += (height-r.bottom)/2;
-            if (i==0) {
-                doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0,
-                      j==0 ? e1stext : e2stext, j==0 ? e1sid : e2sid);
-            } else if (i==1) {
-                doctl(cp, r, "EDIT",
-                      WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
-                      WS_EX_CLIENTEDGE,
-                      "", j==0 ? e1id : e2id);
-            } else if (i==3) {
-                doctl(cp, r, "BUTTON",
-                      WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-                      0,
-                      j==0 ? b1text : b2text, j==0 ? b1id : b2id);
-            }
-        }
-        cp->ypos += height + GAPWITHIN;
+       percent = 10;
+       for (i = 0; i < 4; i++) {
+           xpos = (cp->width + GAPBETWEEN) * percent / 100;
+           r.left = xpos + GAPBETWEEN;
+           percent += percents[i];
+           xpos = (cp->width + GAPBETWEEN) * percent / 100;
+           r.right = xpos - r.left;
+           r.top = cp->ypos;
+           r.bottom = (i == 0 ? STATICHEIGHT :
+                       i == 1 ? EDITHEIGHT : PUSHBTNHEIGHT);
+           r.top += (height - r.bottom) / 2;
+           if (i == 0) {
+               doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0,
+                     j == 0 ? e1stext : e2stext, j == 0 ? e1sid : e2sid);
+           } else if (i == 1) {
+               doctl(cp, r, "EDIT",
+                     WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
+                     WS_EX_CLIENTEDGE, "", j == 0 ? e1id : e2id);
+           } else if (i == 3) {
+               doctl(cp, r, "BUTTON",
+                     WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+                     0, j == 0 ? b1text : b2text, j == 0 ? b1id : b2id);
+           }
+       }
+       cp->ypos += height + GAPWITHIN;
     }
 
     /* The list box. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = LISTHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = LISTHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
     doctl(cp, r, "LISTBOX",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS |
-          LBS_USETABSTOPS,
-          WS_EX_CLIENTEDGE,
-          "", listid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS
+         | LBS_USETABSTOPS, WS_EX_CLIENTEDGE, "", listid);
 }
 
 /*
@@ -563,56 +615,58 @@ void envsetter(struct ctlpos *cp, char *stext, int sid,
  * button-and-static-and-edit. 
  */
 void charclass(struct ctlpos *cp, char *stext, int sid, int listid,
-               char *btext, int bid, int eid, char *s2text, int s2id) {
+              char *btext, int bid, int eid, char *s2text, int s2id)
+{
     RECT r;
-    const int height = (STATICHEIGHT > EDITHEIGHT && STATICHEIGHT > PUSHBTNHEIGHT ?
-                        STATICHEIGHT :
-                        EDITHEIGHT > PUSHBTNHEIGHT ?
-                        EDITHEIGHT : PUSHBTNHEIGHT);
+    const int height = (STATICHEIGHT > EDITHEIGHT
+                       && STATICHEIGHT >
+                       PUSHBTNHEIGHT ? STATICHEIGHT : EDITHEIGHT >
+                       PUSHBTNHEIGHT ? EDITHEIGHT : PUSHBTNHEIGHT);
     const static int percents[] = { 30, 40, 30 };
     int i, xpos, percent;
     const int LISTHEIGHT = 66;
 
     /* The static control. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
 
     /* The list box. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = LISTHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = LISTHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "LISTBOX",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS |
-          LBS_USETABSTOPS,
-          WS_EX_CLIENTEDGE,
-          "", listid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS
+         | LBS_USETABSTOPS, WS_EX_CLIENTEDGE, "", listid);
 
     /* The button+static+edit. */
     percent = xpos = 0;
     for (i = 0; i < 3; i++) {
-        r.left = xpos + GAPBETWEEN;
-        percent += percents[i];
-        xpos = (cp->width + GAPBETWEEN) * percent / 100;
-        r.right = xpos - r.left;
-        r.top = cp->ypos;
-        r.bottom = (i==0 ? PUSHBTNHEIGHT :
-                    i==1 ? STATICHEIGHT :
-                    EDITHEIGHT);
-        r.top += (height-r.bottom)/2;
-        if (i==0) {
-            doctl(cp, r, "BUTTON",
-                  WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-                  0, btext, bid);
-        } else if (i==1) {
-            doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_CENTER,
-                  0, s2text, s2id);
-        } else if (i==2) {
-            doctl(cp, r, "EDIT",
-                  WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
-                  WS_EX_CLIENTEDGE, "", eid);
-        }
+       r.left = xpos + GAPBETWEEN;
+       percent += percents[i];
+       xpos = (cp->width + GAPBETWEEN) * percent / 100;
+       r.right = xpos - r.left;
+       r.top = cp->ypos;
+       r.bottom = (i == 0 ? PUSHBTNHEIGHT :
+                   i == 1 ? STATICHEIGHT : EDITHEIGHT);
+       r.top += (height - r.bottom) / 2;
+       if (i == 0) {
+           doctl(cp, r, "BUTTON",
+                 WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+                 0, btext, bid);
+       } else if (i == 1) {
+           doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_CENTER,
+                 0, s2text, s2id);
+       } else if (i == 2) {
+           doctl(cp, r, "EDIT",
+                 WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL,
+                 WS_EX_CLIENTEDGE, "", eid);
+       }
     }
     cp->ypos += height + GAPBETWEEN;
 }
@@ -623,7 +677,8 @@ void charclass(struct ctlpos *cp, char *stext, int sid, int listid,
  * two-part statics followed by a button.
  */
 void colouredit(struct ctlpos *cp, char *stext, int sid, int listid,
-                char *btext, int bid, ...) {
+               char *btext, int bid, ...)
+{
     RECT r;
     int y;
     va_list ap;
@@ -631,49 +686,58 @@ void colouredit(struct ctlpos *cp, char *stext, int sid, int listid,
     const int LISTHEIGHT = 66;
 
     /* The static control. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = STATICHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = STATICHEIGHT;
     cp->ypos += r.bottom + GAPWITHIN;
     doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid);
-    
+
     rpos = GAPBETWEEN + 2 * (cp->width + GAPBETWEEN) / 3;
-    lwid = rpos - 2*GAPBETWEEN;
+    lwid = rpos - 2 * GAPBETWEEN;
     rwid = cp->width + GAPBETWEEN - rpos;
 
     /* The list box. */
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = lwid; r.bottom = LISTHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = lwid;
+    r.bottom = LISTHEIGHT;
     doctl(cp, r, "LISTBOX",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS |
-          LBS_USETABSTOPS | LBS_NOTIFY,
-          WS_EX_CLIENTEDGE,
-          "", listid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | LBS_HASSTRINGS
+         | LBS_USETABSTOPS | LBS_NOTIFY, WS_EX_CLIENTEDGE, "", listid);
 
     /* The statics. */
     y = cp->ypos;
     va_start(ap, bid);
     while (1) {
-        char *ltext;
-        int lid, rid;
-        ltext = va_arg(ap, char *);
-        if (!ltext) break;
-        lid = va_arg(ap, int);
-        rid = va_arg(ap, int);
-        r.top = y; r.bottom = STATICHEIGHT;
-        y += r.bottom + GAPWITHIN;
-        r.left = rpos; r.right = rwid/2;
-        doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, ltext, lid);
-        r.left = rpos + r.right; r.right = rwid - r.right;
-        doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_RIGHT, 0, "", rid);
+       char *ltext;
+       int lid, rid;
+       ltext = va_arg(ap, char *);
+       if (!ltext)
+           break;
+       lid = va_arg(ap, int);
+       rid = va_arg(ap, int);
+       r.top = y;
+       r.bottom = STATICHEIGHT;
+       y += r.bottom + GAPWITHIN;
+       r.left = rpos;
+       r.right = rwid / 2;
+       doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, ltext, lid);
+       r.left = rpos + r.right;
+       r.right = rwid - r.right;
+       doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_RIGHT, 0, "",
+             rid);
     }
     va_end(ap);
 
     /* The button. */
-    r.top = y + 2*GAPWITHIN; r.bottom = PUSHBTNHEIGHT;
-    r.left = rpos; r.right = rwid;
+    r.top = y + 2 * GAPWITHIN;
+    r.bottom = PUSHBTNHEIGHT;
+    r.left = rpos;
+    r.right = rwid;
     doctl(cp, r, "BUTTON",
-          WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
-          0, btext, bid);
+         WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
+         0, btext, bid);
 
     cp->ypos += LISTHEIGHT + GAPBETWEEN;
 }
@@ -683,17 +747,19 @@ void colouredit(struct ctlpos *cp, char *stext, int sid, int listid,
  * to be smooth and unbroken, without those ugly divisions; some
  * older compilers may not support that, but that's life.
  */
-void progressbar(struct ctlpos *cp, int id) {
+void progressbar(struct ctlpos *cp, int id)
+{
     RECT r;
 
-    r.left = GAPBETWEEN; r.top = cp->ypos;
-    r.right = cp->width; r.bottom = PROGBARHEIGHT;
+    r.left = GAPBETWEEN;
+    r.top = cp->ypos;
+    r.right = cp->width;
+    r.bottom = PROGBARHEIGHT;
     cp->ypos += r.bottom + GAPBETWEEN;
 
-    doctl(cp, r, PROGRESS_CLASS,
-          WS_CHILD | WS_VISIBLE
+    doctl(cp, r, PROGRESS_CLASS, WS_CHILD | WS_VISIBLE
 #ifdef PBS_SMOOTH
-          | PBS_SMOOTH
+         | PBS_SMOOTH
 #endif
-          , WS_EX_CLIENTEDGE, "", id);
+         , WS_EX_CLIENTEDGE, "", id);
 }
index 6f3c35c..76f1eca 100644 (file)
--- a/windlg.c
+++ b/windlg.c
@@ -23,129 +23,136 @@ void force_normal(HWND hwnd)
 
     WINDOWPLACEMENT wp;
 
-    if(recurse) return;
+    if (recurse)
+       return;
     recurse = 1;
 
     wp.length = sizeof(wp);
-    if (GetWindowPlacement(hwnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED)
-    {
+    if (GetWindowPlacement(hwnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED) {
        wp.showCmd = SW_SHOWNORMAL;
        SetWindowPlacement(hwnd, &wp);
     }
     recurse = 0;
 }
 
-static void MyGetDlgItemInt (HWND hwnd, int id, int *result) {
+static void MyGetDlgItemInt(HWND hwnd, int id, int *result)
+{
     BOOL ok;
     int n;
-    n = GetDlgItemInt (hwnd, id, &ok, FALSE);
+    n = GetDlgItemInt(hwnd, id, &ok, FALSE);
     if (ok)
        *result = n;
 }
 
-static void MyGetDlgItemFlt (HWND hwnd, int id, int *result, int scale) {
+static void MyGetDlgItemFlt(HWND hwnd, int id, int *result, int scale)
+{
     char text[80];
     BOOL ok;
-    ok = GetDlgItemText (hwnd, id, text, sizeof(text)-1);
+    ok = GetDlgItemText(hwnd, id, text, sizeof(text) - 1);
     if (ok && text[0])
        *result = (int) (scale * atof(text));
 }
 
-static void MySetDlgItemFlt (HWND hwnd, int id, double value) {
+static void MySetDlgItemFlt(HWND hwnd, int id, double value)
+{
     char text[80];
     sprintf(text, "%g", value);
-    SetDlgItemText (hwnd, id, text);
+    SetDlgItemText(hwnd, id, text);
 }
 
-static int CALLBACK LogProc (HWND hwnd, UINT msg,
-                            WPARAM wParam, LPARAM lParam) {
+static int CALLBACK LogProc(HWND hwnd, UINT msg,
+                           WPARAM wParam, LPARAM lParam)
+{
     int i;
 
     switch (msg) {
       case WM_INITDIALOG:
-        {
-            static int tabs[4] = {78, 108};
-            SendDlgItemMessage (hwnd, IDN_LIST, LB_SETTABSTOPS, 2,
-                                (LPARAM) tabs);
-        }
-       for (i=0; i<nevents; i++)
-           SendDlgItemMessage (hwnd, IDN_LIST, LB_ADDSTRING,
-                               0, (LPARAM)events[i]);
+       {
+           static int tabs[4] = { 78, 108 };
+           SendDlgItemMessage(hwnd, IDN_LIST, LB_SETTABSTOPS, 2,
+                              (LPARAM) tabs);
+       }
+       for (i = 0; i < nevents; i++)
+           SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING,
+                              0, (LPARAM) events[i]);
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
          case IDCANCEL:
            logbox = NULL;
-            SetActiveWindow(GetParent(hwnd));
-           DestroyWindow (hwnd);
+           SetActiveWindow(GetParent(hwnd));
+           DestroyWindow(hwnd);
            return 0;
-          case IDN_COPY:
+         case IDN_COPY:
            if (HIWORD(wParam) == BN_CLICKED ||
                HIWORD(wParam) == BN_DOUBLECLICKED) {
-                int selcount;
-                int *selitems;
-                selcount = SendDlgItemMessage(hwnd, IDN_LIST,
-                                              LB_GETSELCOUNT, 0, 0);
-                if (selcount == 0) {   /* don't even try to copy zero items */
-                    MessageBeep(0);
-                    break;
-                }
-                    
-                selitems = smalloc(selcount * sizeof(int));
-                if (selitems) {
-                    int count = SendDlgItemMessage(hwnd, IDN_LIST,
-                                                   LB_GETSELITEMS,
-                                                   selcount, (LPARAM)selitems);
-                    int i;
-                    int size;
-                    char *clipdata;
-                    static unsigned char sel_nl[] = SEL_NL;
-
-                    if (count == 0) {  /* can't copy zero stuff */
-                        MessageBeep(0);
-                        break;
-                    }
-
-                    size = 0;
-                    for (i = 0; i < count; i++)
-                        size += strlen(events[selitems[i]]) + sizeof(sel_nl);
-
-                    clipdata = smalloc(size);
-                    if (clipdata) {
-                        char *p = clipdata;
-                        for (i = 0; i < count; i++) {
-                            char *q = events[selitems[i]];
-                            int qlen = strlen(q);
-                            memcpy(p, q, qlen);
-                            p += qlen;
-                            memcpy(p, sel_nl, sizeof(sel_nl));
-                            p += sizeof(sel_nl);
-                        }
-                        write_clip(clipdata, size, TRUE);
-                        sfree(clipdata);
-                    }
-                    sfree(selitems);
-
-                    for (i = 0; i < nevents; i++)
-                        SendDlgItemMessage(hwnd, IDN_LIST, LB_SETSEL,
-                                           FALSE, i);
-                }
-            }
-            return 0;
+               int selcount;
+               int *selitems;
+               selcount = SendDlgItemMessage(hwnd, IDN_LIST,
+                                             LB_GETSELCOUNT, 0, 0);
+               if (selcount == 0) {   /* don't even try to copy zero items */
+                   MessageBeep(0);
+                   break;
+               }
+
+               selitems = smalloc(selcount * sizeof(int));
+               if (selitems) {
+                   int count = SendDlgItemMessage(hwnd, IDN_LIST,
+                                                  LB_GETSELITEMS,
+                                                  selcount,
+                                                  (LPARAM) selitems);
+                   int i;
+                   int size;
+                   char *clipdata;
+                   static unsigned char sel_nl[] = SEL_NL;
+
+                   if (count == 0) {  /* can't copy zero stuff */
+                       MessageBeep(0);
+                       break;
+                   }
+
+                   size = 0;
+                   for (i = 0; i < count; i++)
+                       size +=
+                           strlen(events[selitems[i]]) + sizeof(sel_nl);
+
+                   clipdata = smalloc(size);
+                   if (clipdata) {
+                       char *p = clipdata;
+                       for (i = 0; i < count; i++) {
+                           char *q = events[selitems[i]];
+                           int qlen = strlen(q);
+                           memcpy(p, q, qlen);
+                           p += qlen;
+                           memcpy(p, sel_nl, sizeof(sel_nl));
+                           p += sizeof(sel_nl);
+                       }
+                       write_clip(clipdata, size, TRUE);
+                       sfree(clipdata);
+                   }
+                   sfree(selitems);
+
+                   for (i = 0; i < nevents; i++)
+                       SendDlgItemMessage(hwnd, IDN_LIST, LB_SETSEL,
+                                          FALSE, i);
+               }
+           }
+           return 0;
        }
        return 0;
       case WM_CLOSE:
        logbox = NULL;
-        SetActiveWindow(GetParent(hwnd));
-       DestroyWindow (hwnd);
+       SetActiveWindow(GetParent(hwnd));
+       DestroyWindow(hwnd);
        return 0;
     }
     return 0;
 }
 
-static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
-                                WPARAM wParam, LPARAM lParam) {
+static int CALLBACK LicenceProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
        return 1;
@@ -163,36 +170,37 @@ static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
     return 0;
 }
 
-static int CALLBACK AboutProc (HWND hwnd, UINT msg,
-                              WPARAM wParam, LPARAM lParam) {
+static int CALLBACK AboutProc(HWND hwnd, UINT msg,
+                             WPARAM wParam, LPARAM lParam)
+{
     switch (msg) {
       case WM_INITDIALOG:
-        SetDlgItemText (hwnd, IDA_VERSION, ver);
+       SetDlgItemText(hwnd, IDA_VERSION, ver);
        return 1;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDOK:
-          case IDCANCEL:
-            EndDialog(hwnd, TRUE);
+         case IDCANCEL:
+           EndDialog(hwnd, TRUE);
            return 0;
          case IDA_LICENCE:
            EnableWindow(hwnd, 0);
-           DialogBox (hinst, MAKEINTRESOURCE(IDD_LICENCEBOX),
-                      NULL, LicenceProc);
+           DialogBox(hinst, MAKEINTRESOURCE(IDD_LICENCEBOX),
+                     NULL, LicenceProc);
            EnableWindow(hwnd, 1);
-            SetActiveWindow(hwnd);
+           SetActiveWindow(hwnd);
            return 0;
 
-          case IDA_WEB:
-            /* Load web browser */
-            ShellExecute(hwnd, "open",
-                         "http://www.chiark.greenend.org.uk/~sgtatham/putty/",
-                         0, 0, SW_SHOWDEFAULT);
-            return 0;
+         case IDA_WEB:
+           /* Load web browser */
+           ShellExecute(hwnd, "open",
+                        "http://www.chiark.greenend.org.uk/~sgtatham/putty/",
+                        0, 0, SW_SHOWDEFAULT);
+           return 0;
        }
        return 0;
       case WM_CLOSE:
-        EndDialog(hwnd, TRUE);
+       EndDialog(hwnd, TRUE);
        return 0;
     }
     return 0;
@@ -201,14 +209,16 @@ static int CALLBACK AboutProc (HWND hwnd, UINT msg,
 /*
  * Null dialog procedure.
  */
-static int CALLBACK NullDlgProc (HWND hwnd, UINT msg,
-                                 WPARAM wParam, LPARAM lParam) {
+static int CALLBACK NullDlgProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     return 0;
 }
 
 static char savedsession[2048];
 
-enum { IDCX_ABOUT = IDC_ABOUT, IDCX_TVSTATIC, IDCX_TREEVIEW, controlstartvalue,
+enum { IDCX_ABOUT =
+       IDC_ABOUT, IDCX_TVSTATIC, IDCX_TREEVIEW, controlstartvalue,
 
     sessionpanelstart,
     IDC_TITLE_SESSION,
@@ -516,122 +526,124 @@ static const int permcolour[] = {
     TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE
 };
 
-static void fmtfont (char *buf) {
-    sprintf (buf, "Font: %s, ", cfg.font);
+static void fmtfont(char *buf)
+{
+    sprintf(buf, "Font: %s, ", cfg.font);
     if (cfg.fontisbold)
        strcat(buf, "bold, ");
     if (cfg.fontheight == 0)
-       strcat (buf, "default height");
+       strcat(buf, "default height");
     else
-       sprintf (buf+strlen(buf), "%d-point",
-                (cfg.fontheight < 0 ? -cfg.fontheight : cfg.fontheight));
+       sprintf(buf + strlen(buf), "%d-point",
+               (cfg.fontheight < 0 ? -cfg.fontheight : cfg.fontheight));
 }
 
-static void init_dlg_ctrls(HWND hwnd) {
+static void init_dlg_ctrls(HWND hwnd)
+{
     int i;
     char fontstatic[256];
 
-    SetDlgItemText (hwnd, IDC_HOST, cfg.host);
-    SetDlgItemText (hwnd, IDC_SESSEDIT, savedsession);
+    SetDlgItemText(hwnd, IDC_HOST, cfg.host);
+    SetDlgItemText(hwnd, IDC_SESSEDIT, savedsession);
     {
        int i, n;
-       n = SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_GETCOUNT, 0, 0);
-       for (i=n; i-- >0 ;)
-           SendDlgItemMessage (hwnd, IDC_SESSLIST,
-                                   LB_DELETESTRING, i, 0);
-        for (i = 0; i < nsessions; i++)
-            SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_ADDSTRING,
-                                0, (LPARAM) (sessions[i]));
+       n = SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_GETCOUNT, 0, 0);
+       for (i = n; i-- > 0;)
+           SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_DELETESTRING, i, 0);
+       for (i = 0; i < nsessions; i++)
+           SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_ADDSTRING,
+                              0, (LPARAM) (sessions[i]));
     }
-    SetDlgItemInt (hwnd, IDC_PORT, cfg.port, FALSE);
-    CheckRadioButton (hwnd, IDC_PROTRAW, IDC_PROTSSH,
-                     cfg.protocol==PROT_SSH ? IDC_PROTSSH :
-                     cfg.protocol==PROT_TELNET ? IDC_PROTTELNET :
-                      cfg.protocol==PROT_RLOGIN ? IDC_PROTRLOGIN : IDC_PROTRAW );
-    SetDlgItemInt (hwnd, IDC_PINGEDIT, cfg.ping_interval, FALSE);
-
-    CheckRadioButton (hwnd, IDC_DEL008, IDC_DEL127,
-                     cfg.bksp_is_delete ? IDC_DEL127 : IDC_DEL008);
-    CheckRadioButton (hwnd, IDC_HOMETILDE, IDC_HOMERXVT,
-                     cfg.rxvt_homeend ? IDC_HOMERXVT : IDC_HOMETILDE);
-    CheckRadioButton (hwnd, IDC_FUNCTILDE, IDC_FUNCSCO,
-                      cfg.funky_type == 0 ? IDC_FUNCTILDE :
-                      cfg.funky_type == 1 ? IDC_FUNCLINUX :
-                      cfg.funky_type == 2 ? IDC_FUNCXTERM :
-                      cfg.funky_type == 3 ? IDC_FUNCVT400 :
-                      cfg.funky_type == 4 ? IDC_FUNCVT100P :
-                      cfg.funky_type == 5 ? IDC_FUNCSCO :
-                      IDC_FUNCTILDE );
-    CheckDlgButton (hwnd, IDC_NOAPPLICC, cfg.no_applic_c);
-    CheckDlgButton (hwnd, IDC_NOAPPLICK, cfg.no_applic_k);
-    CheckRadioButton (hwnd, IDC_CURNORMAL, IDC_CURAPPLIC,
-                     cfg.app_cursor ? IDC_CURAPPLIC : IDC_CURNORMAL);
-    CheckRadioButton (hwnd, IDC_KPNORMAL, IDC_KPNH,
-                     cfg.nethack_keypad ? IDC_KPNH :
-                     cfg.app_keypad ? IDC_KPAPPLIC : IDC_KPNORMAL);
-    CheckDlgButton (hwnd, IDC_ALTF4, cfg.alt_f4);
-    CheckDlgButton (hwnd, IDC_ALTSPACE, cfg.alt_space);
-    CheckDlgButton (hwnd, IDC_ALTONLY, cfg.alt_only);
-    CheckDlgButton (hwnd, IDC_COMPOSEKEY, cfg.compose_key);
-    CheckDlgButton (hwnd, IDC_CTRLALTKEYS, cfg.ctrlaltkeys);
-    CheckRadioButton (hwnd, IDC_ECHOBACKEND, IDC_ECHONO,
-                     cfg.localecho == LD_BACKEND ? IDC_ECHOBACKEND:
-                      cfg.localecho == LD_YES ? IDC_ECHOYES : IDC_ECHONO);
-    CheckRadioButton (hwnd, IDC_EDITBACKEND, IDC_EDITNO,
-                     cfg.localedit == LD_BACKEND ? IDC_EDITBACKEND:
-                      cfg.localedit == LD_YES ? IDC_EDITYES : IDC_EDITNO);
-    SetDlgItemText (hwnd, IDC_ANSWEREDIT, cfg.answerback);
-    CheckDlgButton (hwnd, IDC_ALWAYSONTOP, cfg.alwaysontop);
-    CheckDlgButton (hwnd, IDC_SCROLLKEY, cfg.scroll_on_key);
-    CheckDlgButton (hwnd, IDC_SCROLLDISP, cfg.scroll_on_disp);
-
-    CheckDlgButton (hwnd, IDC_WRAPMODE, cfg.wrap_mode);
-    CheckDlgButton (hwnd, IDC_DECOM, cfg.dec_om);
-    CheckDlgButton (hwnd, IDC_LFHASCR, cfg.lfhascr);
-    SetDlgItemInt (hwnd, IDC_ROWSEDIT, cfg.height, FALSE);
-    SetDlgItemInt (hwnd, IDC_COLSEDIT, cfg.width, FALSE);
-    SetDlgItemInt (hwnd, IDC_SAVEEDIT, cfg.savelines, FALSE);
-    fmtfont (fontstatic);
-    SetDlgItemText (hwnd, IDC_FONTSTATIC, fontstatic);
-    CheckRadioButton (hwnd, IDC_BELL_DISABLED, IDC_BELL_VISUAL,
-                     cfg.beep==BELL_DISABLED ? IDC_BELL_DISABLED :
-                     cfg.beep==BELL_DEFAULT ? IDC_BELL_DEFAULT :
-                     cfg.beep==BELL_WAVEFILE ? IDC_BELL_WAVEFILE :
-                     cfg.beep==BELL_VISUAL ? IDC_BELL_VISUAL : IDC_BELL_DEFAULT);
-    SetDlgItemText (hwnd, IDC_BELL_WAVEEDIT, cfg.bell_wavefile);
-    CheckDlgButton (hwnd, IDC_BELLOVL, cfg.bellovl);
-    SetDlgItemInt (hwnd, IDC_BELLOVLN, cfg.bellovl_n, FALSE);
-    MySetDlgItemFlt (hwnd, IDC_BELLOVLT, cfg.bellovl_t / 1000.0);
-    MySetDlgItemFlt (hwnd, IDC_BELLOVLS, cfg.bellovl_s / 1000.0);
-
-    CheckDlgButton (hwnd, IDC_BCE, cfg.bce);
-    CheckDlgButton (hwnd, IDC_BLINKTEXT, cfg.blinktext);
-
-    SetDlgItemText (hwnd, IDC_WINEDIT, cfg.wintitle);
-    CheckDlgButton (hwnd, IDC_WINNAME, cfg.win_name_always);
-    CheckDlgButton (hwnd, IDC_HIDEMOUSE, cfg.hide_mouseptr);
-    CheckDlgButton (hwnd, IDC_SUNKENEDGE, cfg.sunken_edge);
-    CheckRadioButton (hwnd, IDC_CURBLOCK, IDC_CURVERT,
-                     cfg.cursor_type==0 ? IDC_CURBLOCK :
-                     cfg.cursor_type==1 ? IDC_CURUNDER : IDC_CURVERT);
-    CheckDlgButton (hwnd, IDC_BLINKCUR, cfg.blink_cur);
-    CheckDlgButton (hwnd, IDC_SCROLLBAR, cfg.scrollbar);
-    CheckDlgButton (hwnd, IDC_LOCKSIZE, cfg.locksize);
-    CheckRadioButton (hwnd, IDC_COEALWAYS, IDC_COENORMAL,
-                      cfg.close_on_exit==COE_NORMAL ? IDC_COENORMAL :
-                      cfg.close_on_exit==COE_NEVER ? IDC_COENEVER : IDC_COEALWAYS);
-    CheckDlgButton (hwnd, IDC_CLOSEWARN, cfg.warn_on_close);
-
-    SetDlgItemText (hwnd, IDC_TTEDIT, cfg.termtype);
-    SetDlgItemText (hwnd, IDC_TSEDIT, cfg.termspeed);
-    SetDlgItemText (hwnd, IDC_R_TSEDIT, cfg.termspeed);
-    SetDlgItemText (hwnd, IDC_RLLUSEREDIT, cfg.localusername);
-    SetDlgItemText (hwnd, IDC_LOGEDIT, cfg.username);
-    SetDlgItemText (hwnd, IDC_LGFEDIT, cfg.logfilename);
+    SetDlgItemInt(hwnd, IDC_PORT, cfg.port, FALSE);
+    CheckRadioButton(hwnd, IDC_PROTRAW, IDC_PROTSSH,
+                    cfg.protocol == PROT_SSH ? IDC_PROTSSH :
+                    cfg.protocol == PROT_TELNET ? IDC_PROTTELNET :
+                    cfg.protocol ==
+                    PROT_RLOGIN ? IDC_PROTRLOGIN : IDC_PROTRAW);
+    SetDlgItemInt(hwnd, IDC_PINGEDIT, cfg.ping_interval, FALSE);
+
+    CheckRadioButton(hwnd, IDC_DEL008, IDC_DEL127,
+                    cfg.bksp_is_delete ? IDC_DEL127 : IDC_DEL008);
+    CheckRadioButton(hwnd, IDC_HOMETILDE, IDC_HOMERXVT,
+                    cfg.rxvt_homeend ? IDC_HOMERXVT : IDC_HOMETILDE);
+    CheckRadioButton(hwnd, IDC_FUNCTILDE, IDC_FUNCSCO,
+                    cfg.funky_type == 0 ? IDC_FUNCTILDE :
+                    cfg.funky_type == 1 ? IDC_FUNCLINUX :
+                    cfg.funky_type == 2 ? IDC_FUNCXTERM :
+                    cfg.funky_type == 3 ? IDC_FUNCVT400 :
+                    cfg.funky_type == 4 ? IDC_FUNCVT100P :
+                    cfg.funky_type == 5 ? IDC_FUNCSCO : IDC_FUNCTILDE);
+    CheckDlgButton(hwnd, IDC_NOAPPLICC, cfg.no_applic_c);
+    CheckDlgButton(hwnd, IDC_NOAPPLICK, cfg.no_applic_k);
+    CheckRadioButton(hwnd, IDC_CURNORMAL, IDC_CURAPPLIC,
+                    cfg.app_cursor ? IDC_CURAPPLIC : IDC_CURNORMAL);
+    CheckRadioButton(hwnd, IDC_KPNORMAL, IDC_KPNH,
+                    cfg.nethack_keypad ? IDC_KPNH :
+                    cfg.app_keypad ? IDC_KPAPPLIC : IDC_KPNORMAL);
+    CheckDlgButton(hwnd, IDC_ALTF4, cfg.alt_f4);
+    CheckDlgButton(hwnd, IDC_ALTSPACE, cfg.alt_space);
+    CheckDlgButton(hwnd, IDC_ALTONLY, cfg.alt_only);
+    CheckDlgButton(hwnd, IDC_COMPOSEKEY, cfg.compose_key);
+    CheckDlgButton(hwnd, IDC_CTRLALTKEYS, cfg.ctrlaltkeys);
+    CheckRadioButton(hwnd, IDC_ECHOBACKEND, IDC_ECHONO,
+                    cfg.localecho == LD_BACKEND ? IDC_ECHOBACKEND :
+                    cfg.localecho == LD_YES ? IDC_ECHOYES : IDC_ECHONO);
+    CheckRadioButton(hwnd, IDC_EDITBACKEND, IDC_EDITNO,
+                    cfg.localedit == LD_BACKEND ? IDC_EDITBACKEND :
+                    cfg.localedit == LD_YES ? IDC_EDITYES : IDC_EDITNO);
+    SetDlgItemText(hwnd, IDC_ANSWEREDIT, cfg.answerback);
+    CheckDlgButton(hwnd, IDC_ALWAYSONTOP, cfg.alwaysontop);
+    CheckDlgButton(hwnd, IDC_SCROLLKEY, cfg.scroll_on_key);
+    CheckDlgButton(hwnd, IDC_SCROLLDISP, cfg.scroll_on_disp);
+
+    CheckDlgButton(hwnd, IDC_WRAPMODE, cfg.wrap_mode);
+    CheckDlgButton(hwnd, IDC_DECOM, cfg.dec_om);
+    CheckDlgButton(hwnd, IDC_LFHASCR, cfg.lfhascr);
+    SetDlgItemInt(hwnd, IDC_ROWSEDIT, cfg.height, FALSE);
+    SetDlgItemInt(hwnd, IDC_COLSEDIT, cfg.width, FALSE);
+    SetDlgItemInt(hwnd, IDC_SAVEEDIT, cfg.savelines, FALSE);
+    fmtfont(fontstatic);
+    SetDlgItemText(hwnd, IDC_FONTSTATIC, fontstatic);
+    CheckRadioButton(hwnd, IDC_BELL_DISABLED, IDC_BELL_VISUAL,
+                    cfg.beep == BELL_DISABLED ? IDC_BELL_DISABLED :
+                    cfg.beep == BELL_DEFAULT ? IDC_BELL_DEFAULT :
+                    cfg.beep == BELL_WAVEFILE ? IDC_BELL_WAVEFILE :
+                    cfg.beep ==
+                    BELL_VISUAL ? IDC_BELL_VISUAL : IDC_BELL_DEFAULT);
+    SetDlgItemText(hwnd, IDC_BELL_WAVEEDIT, cfg.bell_wavefile);
+    CheckDlgButton(hwnd, IDC_BELLOVL, cfg.bellovl);
+    SetDlgItemInt(hwnd, IDC_BELLOVLN, cfg.bellovl_n, FALSE);
+    MySetDlgItemFlt(hwnd, IDC_BELLOVLT, cfg.bellovl_t / 1000.0);
+    MySetDlgItemFlt(hwnd, IDC_BELLOVLS, cfg.bellovl_s / 1000.0);
+
+    CheckDlgButton(hwnd, IDC_BCE, cfg.bce);
+    CheckDlgButton(hwnd, IDC_BLINKTEXT, cfg.blinktext);
+
+    SetDlgItemText(hwnd, IDC_WINEDIT, cfg.wintitle);
+    CheckDlgButton(hwnd, IDC_WINNAME, cfg.win_name_always);
+    CheckDlgButton(hwnd, IDC_HIDEMOUSE, cfg.hide_mouseptr);
+    CheckDlgButton(hwnd, IDC_SUNKENEDGE, cfg.sunken_edge);
+    CheckRadioButton(hwnd, IDC_CURBLOCK, IDC_CURVERT,
+                    cfg.cursor_type == 0 ? IDC_CURBLOCK :
+                    cfg.cursor_type == 1 ? IDC_CURUNDER : IDC_CURVERT);
+    CheckDlgButton(hwnd, IDC_BLINKCUR, cfg.blink_cur);
+    CheckDlgButton(hwnd, IDC_SCROLLBAR, cfg.scrollbar);
+    CheckDlgButton(hwnd, IDC_LOCKSIZE, cfg.locksize);
+    CheckRadioButton(hwnd, IDC_COEALWAYS, IDC_COENORMAL,
+                    cfg.close_on_exit == COE_NORMAL ? IDC_COENORMAL :
+                    cfg.close_on_exit ==
+                    COE_NEVER ? IDC_COENEVER : IDC_COEALWAYS);
+    CheckDlgButton(hwnd, IDC_CLOSEWARN, cfg.warn_on_close);
+
+    SetDlgItemText(hwnd, IDC_TTEDIT, cfg.termtype);
+    SetDlgItemText(hwnd, IDC_TSEDIT, cfg.termspeed);
+    SetDlgItemText(hwnd, IDC_R_TSEDIT, cfg.termspeed);
+    SetDlgItemText(hwnd, IDC_RLLUSEREDIT, cfg.localusername);
+    SetDlgItemText(hwnd, IDC_LOGEDIT, cfg.username);
+    SetDlgItemText(hwnd, IDC_LGFEDIT, cfg.logfilename);
     CheckRadioButton(hwnd, IDC_LSTATOFF, IDC_LSTATRAW,
                     cfg.logtype == 0 ? IDC_LSTATOFF :
-                    cfg.logtype == 1 ? IDC_LSTATASCII :
-                    IDC_LSTATRAW);
+                    cfg.logtype == 1 ? IDC_LSTATASCII : IDC_LSTATRAW);
     CheckRadioButton(hwnd, IDC_LSTATXOVR, IDC_LSTATXASK,
                     cfg.logxfovr == LGXF_OVR ? IDC_LSTATXOVR :
                     cfg.logxfovr == LGXF_ASK ? IDC_LSTATXASK :
@@ -639,80 +651,78 @@ static void init_dlg_ctrls(HWND hwnd) {
     {
        char *p = cfg.environmt;
        while (*p) {
-           SendDlgItemMessage (hwnd, IDC_ENVLIST, LB_ADDSTRING, 0,
-                               (LPARAM) p);
-           p += strlen(p)+1;
+           SendDlgItemMessage(hwnd, IDC_ENVLIST, LB_ADDSTRING, 0,
+                              (LPARAM) p);
+           p += strlen(p) + 1;
        }
     }
-    CheckRadioButton (hwnd, IDC_EMBSD, IDC_EMRFC,
-                     cfg.rfc_environ ? IDC_EMRFC : IDC_EMBSD);
-
-    SetDlgItemText (hwnd, IDC_TTEDIT, cfg.termtype);
-    SetDlgItemText (hwnd, IDC_LOGEDIT, cfg.username);
-    CheckDlgButton (hwnd, IDC_NOPTY, cfg.nopty);
-    CheckDlgButton (hwnd, IDC_COMPRESS, cfg.compression);
-    CheckDlgButton (hwnd, IDC_BUGGYMAC, cfg.buggymac);
-    CheckDlgButton (hwnd, IDC_AGENTFWD, cfg.agentfwd);
-    CheckRadioButton (hwnd, IDC_CIPHER3DES, IDC_CIPHERAES,
-                     cfg.cipher == CIPHER_BLOWFISH ? IDC_CIPHERBLOWF :
-                     cfg.cipher == CIPHER_DES ? IDC_CIPHERDES :
-                     cfg.cipher == CIPHER_AES ? IDC_CIPHERAES :
-                     IDC_CIPHER3DES);
-    CheckRadioButton (hwnd, IDC_SSHPROT1, IDC_SSHPROT2,
-                     cfg.sshprot == 1 ? IDC_SSHPROT1 : IDC_SSHPROT2);
-    CheckDlgButton (hwnd, IDC_AUTHTIS, cfg.try_tis_auth);
-    SetDlgItemText (hwnd, IDC_PKEDIT, cfg.keyfile);
-    SetDlgItemText (hwnd, IDC_CMDEDIT, cfg.remote_cmd);
-
-    CheckRadioButton (hwnd, IDC_MBWINDOWS, IDC_MBXTERM,
-                     cfg.mouse_is_xterm ? IDC_MBXTERM : IDC_MBWINDOWS);
-    CheckDlgButton (hwnd, IDC_RAWCNP, cfg.rawcnp);
+    CheckRadioButton(hwnd, IDC_EMBSD, IDC_EMRFC,
+                    cfg.rfc_environ ? IDC_EMRFC : IDC_EMBSD);
+
+    SetDlgItemText(hwnd, IDC_TTEDIT, cfg.termtype);
+    SetDlgItemText(hwnd, IDC_LOGEDIT, cfg.username);
+    CheckDlgButton(hwnd, IDC_NOPTY, cfg.nopty);
+    CheckDlgButton(hwnd, IDC_COMPRESS, cfg.compression);
+    CheckDlgButton(hwnd, IDC_BUGGYMAC, cfg.buggymac);
+    CheckDlgButton(hwnd, IDC_AGENTFWD, cfg.agentfwd);
+    CheckRadioButton(hwnd, IDC_CIPHER3DES, IDC_CIPHERAES,
+                    cfg.cipher == CIPHER_BLOWFISH ? IDC_CIPHERBLOWF :
+                    cfg.cipher == CIPHER_DES ? IDC_CIPHERDES :
+                    cfg.cipher == CIPHER_AES ? IDC_CIPHERAES :
+                    IDC_CIPHER3DES);
+    CheckRadioButton(hwnd, IDC_SSHPROT1, IDC_SSHPROT2,
+                    cfg.sshprot == 1 ? IDC_SSHPROT1 : IDC_SSHPROT2);
+    CheckDlgButton(hwnd, IDC_AUTHTIS, cfg.try_tis_auth);
+    SetDlgItemText(hwnd, IDC_PKEDIT, cfg.keyfile);
+    SetDlgItemText(hwnd, IDC_CMDEDIT, cfg.remote_cmd);
+
+    CheckRadioButton(hwnd, IDC_MBWINDOWS, IDC_MBXTERM,
+                    cfg.mouse_is_xterm ? IDC_MBXTERM : IDC_MBWINDOWS);
+    CheckDlgButton(hwnd, IDC_RAWCNP, cfg.rawcnp);
     {
-       static int tabs[4] = {25, 61, 96, 128};
-       SendDlgItemMessage (hwnd, IDC_CCLIST, LB_SETTABSTOPS, 4,
-                           (LPARAM) tabs);
+       static int tabs[4] = { 25, 61, 96, 128 };
+       SendDlgItemMessage(hwnd, IDC_CCLIST, LB_SETTABSTOPS, 4,
+                          (LPARAM) tabs);
     }
-    for (i=0; i<256; i++) {
+    for (i = 0; i < 256; i++) {
        char str[100];
        sprintf(str, "%d\t(0x%02X)\t%c\t%d", i, i,
-               (i>=0x21 && i != 0x7F) ? i : ' ',
-               cfg.wordness[i]);
-       SendDlgItemMessage (hwnd, IDC_CCLIST, LB_ADDSTRING, 0,
-                           (LPARAM) str);
+               (i >= 0x21 && i != 0x7F) ? i : ' ', cfg.wordness[i]);
+       SendDlgItemMessage(hwnd, IDC_CCLIST, LB_ADDSTRING, 0,
+                          (LPARAM) str);
     }
 
-    CheckDlgButton (hwnd, IDC_BOLDCOLOUR, cfg.bold_colour);
-    CheckDlgButton (hwnd, IDC_PALETTE, cfg.try_palette);
+    CheckDlgButton(hwnd, IDC_BOLDCOLOUR, cfg.bold_colour);
+    CheckDlgButton(hwnd, IDC_PALETTE, cfg.try_palette);
     {
        int i, n;
-       n = SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_GETCOUNT, 0, 0);
-       for (i=n; i-- >0 ;)
-           SendDlgItemMessage (hwnd, IDC_COLOURLIST,
-                                   LB_DELETESTRING, i, 0);
-       for (i=0; i<22; i++)
+       n = SendDlgItemMessage(hwnd, IDC_COLOURLIST, LB_GETCOUNT, 0, 0);
+       for (i = n; i-- > 0;)
+           SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                              LB_DELETESTRING, i, 0);
+       for (i = 0; i < 22; i++)
            if (cfg.bold_colour || permcolour[i])
-               SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_ADDSTRING, 0,
-                                   (LPARAM) colours[i]);
+               SendDlgItemMessage(hwnd, IDC_COLOURLIST, LB_ADDSTRING, 0,
+                                  (LPARAM) colours[i]);
     }
-    SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_SETCURSEL, 0, 0);
-    SetDlgItemInt (hwnd, IDC_RVALUE, cfg.colours[0][0], FALSE);
-    SetDlgItemInt (hwnd, IDC_GVALUE, cfg.colours[0][1], FALSE);
-    SetDlgItemInt (hwnd, IDC_BVALUE, cfg.colours[0][2], FALSE);
-
-    CheckRadioButton (hwnd, IDC_NOXLAT, IDC_88592CP852,
-                     cfg.xlat_88592w1250 ? IDC_88592WIN1250 :
-                     cfg.xlat_88592cp852 ? IDC_88592CP852 :
-                     cfg.xlat_enablekoiwin ? IDC_KOI8WIN1251 :
-                     IDC_NOXLAT);
-    CheckDlgButton (hwnd, IDC_CAPSLOCKCYR, cfg.xlat_capslockcyr);
-    CheckRadioButton (hwnd, IDC_VTXWINDOWS, IDC_VTPOORMAN,
-                     cfg.vtmode == VT_XWINDOWS ? IDC_VTXWINDOWS :
-                     cfg.vtmode == VT_OEMANSI ? IDC_VTOEMANSI :
-                     cfg.vtmode == VT_OEMONLY ? IDC_VTOEMONLY :
-                     IDC_VTPOORMAN);
-
-    CheckDlgButton (hwnd, IDC_X11_FORWARD, cfg.x11_forward);
-    SetDlgItemText (hwnd, IDC_X11_DISPLAY, cfg.x11_display);
+    SendDlgItemMessage(hwnd, IDC_COLOURLIST, LB_SETCURSEL, 0, 0);
+    SetDlgItemInt(hwnd, IDC_RVALUE, cfg.colours[0][0], FALSE);
+    SetDlgItemInt(hwnd, IDC_GVALUE, cfg.colours[0][1], FALSE);
+    SetDlgItemInt(hwnd, IDC_BVALUE, cfg.colours[0][2], FALSE);
+
+    CheckRadioButton(hwnd, IDC_NOXLAT, IDC_88592CP852,
+                    cfg.xlat_88592w1250 ? IDC_88592WIN1250 :
+                    cfg.xlat_88592cp852 ? IDC_88592CP852 :
+                    cfg.xlat_enablekoiwin ? IDC_KOI8WIN1251 : IDC_NOXLAT);
+    CheckDlgButton(hwnd, IDC_CAPSLOCKCYR, cfg.xlat_capslockcyr);
+    CheckRadioButton(hwnd, IDC_VTXWINDOWS, IDC_VTPOORMAN,
+                    cfg.vtmode == VT_XWINDOWS ? IDC_VTXWINDOWS :
+                    cfg.vtmode == VT_OEMANSI ? IDC_VTOEMANSI :
+                    cfg.vtmode == VT_OEMONLY ? IDC_VTOEMONLY :
+                    IDC_VTPOORMAN);
+
+    CheckDlgButton(hwnd, IDC_X11_FORWARD, cfg.x11_forward);
+    SetDlgItemText(hwnd, IDC_X11_DISPLAY, cfg.x11_display);
 }
 
 struct treeview_faff {
@@ -721,11 +731,12 @@ struct treeview_faff {
 };
 
 static HTREEITEM treeview_insert(struct treeview_faff *faff,
-                                 int level, char *text) {
+                                int level, char *text)
+{
     TVINSERTSTRUCT ins;
     int i;
     HTREEITEM newitem;
-    ins.hParent = (level > 0 ? faff->lastat[level-1] : TVI_ROOT);
+    ins.hParent = (level > 0 ? faff->lastat[level - 1] : TVI_ROOT);
     ins.hInsertAfter = faff->lastat[level];
 #if _WIN32_IE >= 0x0400 && defined NONAMELESSUNION
 #define INSITEM DUMMYUNIONNAME.item
@@ -736,136 +747,133 @@ static HTREEITEM treeview_insert(struct treeview_faff *faff,
     ins.INSITEM.pszText = text;
     newitem = TreeView_InsertItem(faff->treeview, &ins);
     if (level > 0)
-        TreeView_Expand(faff->treeview, faff->lastat[level-1], TVE_EXPAND);
+       TreeView_Expand(faff->treeview, faff->lastat[level - 1],
+                       TVE_EXPAND);
     faff->lastat[level] = newitem;
-    for (i = level+1; i < 4; i++) faff->lastat[i] = NULL;
+    for (i = level + 1; i < 4; i++)
+       faff->lastat[i] = NULL;
     return newitem;
 }
 
 /*
  * Create the panelfuls of controls in the configuration box.
  */
-static void create_controls(HWND hwnd, int dlgtype, int panel) {
+static void create_controls(HWND hwnd, int dlgtype, int panel)
+{
     if (panel == sessionpanelstart) {
        /* The Session panel. Accelerators used: [acgo] nprtih elsd w */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Basic options for your PuTTY session",
-                 IDC_TITLE_SESSION);
-        if (dlgtype == 0) {
-            beginbox(&cp, "Specify your connection by host name",
-                     IDC_BOX_SESSION1);
-            multiedit(&cp,
-                      "Host &Name", IDC_HOSTSTATIC, IDC_HOST, 75,
-                      "&Port", IDC_PORTSTATIC, IDC_PORT, 25, NULL);
-            if (backends[3].backend == NULL) {
-                /* this is PuTTYtel, so only three protocols available */
-                radioline(&cp, "Protocol:", IDC_PROTSTATIC, 4,
-                          "&Raw", IDC_PROTRAW,
-                          "&Telnet", IDC_PROTTELNET,
-                          "Rlog&in", IDC_PROTRLOGIN, NULL);
-            } else {
-                radioline(&cp, "Protocol:", IDC_PROTSTATIC, 4,
-                          "&Raw", IDC_PROTRAW,
-                          "&Telnet", IDC_PROTTELNET,
-                          "Rlog&in", IDC_PROTRLOGIN,
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Basic options for your PuTTY session",
+                IDC_TITLE_SESSION);
+       if (dlgtype == 0) {
+           beginbox(&cp, "Specify your connection by host name",
+                    IDC_BOX_SESSION1);
+           multiedit(&cp,
+                     "Host &Name", IDC_HOSTSTATIC, IDC_HOST, 75,
+                     "&Port", IDC_PORTSTATIC, IDC_PORT, 25, NULL);
+           if (backends[3].backend == NULL) {
+               /* this is PuTTYtel, so only three protocols available */
+               radioline(&cp, "Protocol:", IDC_PROTSTATIC, 4,
+                         "&Raw", IDC_PROTRAW,
+                         "&Telnet", IDC_PROTTELNET,
+                         "Rlog&in", IDC_PROTRLOGIN, NULL);
+           } else {
+               radioline(&cp, "Protocol:", IDC_PROTSTATIC, 4,
+                         "&Raw", IDC_PROTRAW,
+                         "&Telnet", IDC_PROTTELNET,
+                         "Rlog&in", IDC_PROTRLOGIN,
 #ifdef FWHACK
-                          "SS&H/hack",
+                         "SS&H/hack",
 #else
-                          "SS&H",
+                         "SS&H",
 #endif
-                          IDC_PROTSSH, NULL);
-            }
-            endbox(&cp);
-            beginbox(&cp, "Load, save or delete a stored session",
-                     IDC_BOX_SESSION2);
-            sesssaver(&cp, "Sav&ed Sessions",
-                      IDC_SESSSTATIC, IDC_SESSEDIT, IDC_SESSLIST,
-                      "&Load", IDC_SESSLOAD,
-                      "&Save", IDC_SESSSAVE,
-                      "&Delete", IDC_SESSDEL, NULL);
-            endbox(&cp);
-        }
-        beginbox(&cp, NULL, IDC_BOX_SESSION3);
-        radioline(&cp, "Close &window on exit:", IDC_CLOSEEXIT, 4,
-                  "Always", IDC_COEALWAYS,
-                  "Never", IDC_COENEVER,
-                  "Only on clean exit", IDC_COENORMAL, NULL);
-        endbox(&cp);
+                         IDC_PROTSSH, NULL);
+           }
+           endbox(&cp);
+           beginbox(&cp, "Load, save or delete a stored session",
+                    IDC_BOX_SESSION2);
+           sesssaver(&cp, "Sav&ed Sessions",
+                     IDC_SESSSTATIC, IDC_SESSEDIT, IDC_SESSLIST,
+                     "&Load", IDC_SESSLOAD,
+                     "&Save", IDC_SESSSAVE, "&Delete", IDC_SESSDEL, NULL);
+           endbox(&cp);
+       }
+       beginbox(&cp, NULL, IDC_BOX_SESSION3);
+       radioline(&cp, "Close &window on exit:", IDC_CLOSEEXIT, 4,
+                 "Always", IDC_COEALWAYS,
+                 "Never", IDC_COENEVER,
+                 "Only on clean exit", IDC_COENORMAL, NULL);
+       endbox(&cp);
     }
 
     if (panel == loggingpanelstart) {
-        /* The Logging panel. Accelerators used: [acgo] tplfwe */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling session logging",
-                 IDC_TITLE_LOGGING);
-        beginbox(&cp, NULL, IDC_BOX_LOGGING1);
-        radiobig(&cp,
-                 "Session logging:", IDC_LSTATSTATIC,
-                 "Logging &turned off completely", IDC_LSTATOFF,
-                 "Log &printable output only", IDC_LSTATASCII,
-                 "&Log all session output", IDC_LSTATRAW, NULL);
-        editbutton(&cp, "Log &file name:",
-                   IDC_LGFSTATIC, IDC_LGFEDIT, "Bro&wse...",
-                   IDC_LGFBUTTON);
-        radiobig(&cp,
-                 "What to do if the log file already &exists:", IDC_LSTATXIST,
-                 "Always overwrite it", IDC_LSTATXOVR,
-                 "Always append to the end of it", IDC_LSTATXAPN,
-                 "Ask the user every time", IDC_LSTATXASK, NULL);
-        endbox(&cp);
+       /* The Logging panel. Accelerators used: [acgo] tplfwe */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling session logging",
+                IDC_TITLE_LOGGING);
+       beginbox(&cp, NULL, IDC_BOX_LOGGING1);
+       radiobig(&cp,
+                "Session logging:", IDC_LSTATSTATIC,
+                "Logging &turned off completely", IDC_LSTATOFF,
+                "Log &printable output only", IDC_LSTATASCII,
+                "&Log all session output", IDC_LSTATRAW, NULL);
+       editbutton(&cp, "Log &file name:",
+                  IDC_LGFSTATIC, IDC_LGFEDIT, "Bro&wse...",
+                  IDC_LGFBUTTON);
+       radiobig(&cp,
+                "What to do if the log file already &exists:",
+                IDC_LSTATXIST, "Always overwrite it", IDC_LSTATXOVR,
+                "Always append to the end of it", IDC_LSTATXAPN,
+                "Ask the user every time", IDC_LSTATXASK, NULL);
+       endbox(&cp);
     }
 
     if (panel == terminalpanelstart) {
-        /* The Terminal panel. Accelerators used: [acgo] wdlen hts */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling the terminal emulation",
-                 IDC_TITLE_TERMINAL);
-        beginbox(&cp, "Set various terminal options",
-                 IDC_BOX_TERMINAL1);
-        checkbox(&cp, "Auto &wrap mode initially on", IDC_WRAPMODE);
-        checkbox(&cp, "&DEC Origin Mode initially on", IDC_DECOM);
-        checkbox(&cp, "Implicit CR in every &LF", IDC_LFHASCR);
-        checkbox(&cp, "Use background colour to &erase screen", IDC_BCE);
-        checkbox(&cp, "Enable bli&nking text", IDC_BLINKTEXT);
-        multiedit(&cp,
-                  "An&swerback to ^E:", IDC_ANSWERBACK,
-                  IDC_ANSWEREDIT, 100, NULL);
-        endbox(&cp);
-
-        beginbox(&cp, "Line discipline options",
-                 IDC_BOX_TERMINAL2);
-        radioline(&cp, "Local ec&ho:", IDC_ECHOSTATIC, 3,
-                  "Auto", IDC_ECHOBACKEND,
-                  "Force on", IDC_ECHOYES,
-                  "Force off", IDC_ECHONO, NULL);
-        radioline(&cp, "Local line edi&ting:", IDC_EDITSTATIC, 3,
-                  "Auto", IDC_EDITBACKEND,
-                  "Force on", IDC_EDITYES,
-                  "Force off", IDC_EDITNO, NULL);
-        endbox(&cp);
+       /* The Terminal panel. Accelerators used: [acgo] wdlen hts */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling the terminal emulation",
+                IDC_TITLE_TERMINAL);
+       beginbox(&cp, "Set various terminal options", IDC_BOX_TERMINAL1);
+       checkbox(&cp, "Auto &wrap mode initially on", IDC_WRAPMODE);
+       checkbox(&cp, "&DEC Origin Mode initially on", IDC_DECOM);
+       checkbox(&cp, "Implicit CR in every &LF", IDC_LFHASCR);
+       checkbox(&cp, "Use background colour to &erase screen", IDC_BCE);
+       checkbox(&cp, "Enable bli&nking text", IDC_BLINKTEXT);
+       multiedit(&cp,
+                 "An&swerback to ^E:", IDC_ANSWERBACK,
+                 IDC_ANSWEREDIT, 100, NULL);
+       endbox(&cp);
+
+       beginbox(&cp, "Line discipline options", IDC_BOX_TERMINAL2);
+       radioline(&cp, "Local ec&ho:", IDC_ECHOSTATIC, 3,
+                 "Auto", IDC_ECHOBACKEND,
+                 "Force on", IDC_ECHOYES, "Force off", IDC_ECHONO, NULL);
+       radioline(&cp, "Local line edi&ting:", IDC_EDITSTATIC, 3,
+                 "Auto", IDC_EDITBACKEND,
+                 "Force on", IDC_EDITYES, "Force off", IDC_EDITNO, NULL);
+       endbox(&cp);
     }
 
     if (panel == bellpanelstart) {
-        /* The Bell panel. Accelerators used: [acgo] bdsm wt */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling the terminal bell",
-                 IDC_TITLE_BELL);
-        beginbox(&cp, "Set the style of bell",
-                 IDC_BOX_BELL1);
-        radiobig(&cp,
-                 "Action to happen when a &bell occurs:", IDC_BELLSTATIC,
-                 "None (bell disabled)", IDC_BELL_DISABLED,
-                 "Play Windows Default Sound", IDC_BELL_DEFAULT,
-                 "Play a custom sound file", IDC_BELL_WAVEFILE,
-                 "Visual bell (flash window)", IDC_BELL_VISUAL, NULL);
+       /* The Bell panel. Accelerators used: [acgo] bdsm wt */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling the terminal bell",
+                IDC_TITLE_BELL);
+       beginbox(&cp, "Set the style of bell", IDC_BOX_BELL1);
+       radiobig(&cp,
+                "Action to happen when a &bell occurs:", IDC_BELLSTATIC,
+                "None (bell disabled)", IDC_BELL_DISABLED,
+                "Play Windows Default Sound", IDC_BELL_DEFAULT,
+                "Play a custom sound file", IDC_BELL_WAVEFILE,
+                "Visual bell (flash window)", IDC_BELL_VISUAL, NULL);
        editbutton(&cp, "Custom sound file to play as a bell:",
                   IDC_BELL_WAVESTATIC, IDC_BELL_WAVEEDIT,
                   "Bro&wse...", IDC_BELL_WAVEBROWSE);
-        endbox(&cp);
+       endbox(&cp);
        beginbox(&cp, "Control the bell overload behaviour",
                 IDC_BOX_BELL2);
        checkbox(&cp, "Bell is temporarily &disabled when over-used",
@@ -874,332 +882,322 @@ static void create_controls(HWND hwnd, int dlgtype, int panel) {
                   IDC_BELLOVLNSTATIC, IDC_BELLOVLN, 20);
        staticedit(&cp, "... in &this many seconds",
                   IDC_BELLOVLTSTATIC, IDC_BELLOVLT, 20);
-       statictext(&cp, "The bell is re-enabled after a few seconds of silence.",
+       statictext(&cp,
+                  "The bell is re-enabled after a few seconds of silence.",
                   IDC_BELLOVLEXPLAIN);
-       staticedit(&cp, "Seconds of &silence required",
-                  IDC_BELLOVLSSTATIC, IDC_BELLOVLS, 20);
-        endbox(&cp);
+       staticedit(&cp, "Seconds of &silence required", IDC_BELLOVLSSTATIC,
+                  IDC_BELLOVLS, 20);
+       endbox(&cp);
     }
 
     if (panel == keyboardpanelstart) {
-        /* The Keyboard panel. Accelerators used: [acgo] bhf ruyntd */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
+       /* The Keyboard panel. Accelerators used: [acgo] bhf ruyntd */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
        /*
-        bartitle(&cp, "Options controlling the effects of keys",
-                 IDC_TITLE_KEYBOARD);
-                */
-        beginbox(&cp, "Change the sequences sent by:",
-                 IDC_BOX_KEYBOARD1);
-        radioline(&cp, "The &Backspace key", IDC_DELSTATIC, 2,
-                  "Control-H", IDC_DEL008,
-                  "Control-? (127)", IDC_DEL127, NULL);
-        radioline(&cp, "The &Home and End keys", IDC_HOMESTATIC, 2,
-                  "Standard", IDC_HOMETILDE,
-                  "rxvt", IDC_HOMERXVT, NULL);
-        radioline(&cp, "The &Function keys and keypad", IDC_FUNCSTATIC, 3,
-                  "ESC[n~", IDC_FUNCTILDE,
-                  "Linux", IDC_FUNCLINUX,
-                  "Xterm R6", IDC_FUNCXTERM,
+          bartitle(&cp, "Options controlling the effects of keys",
+          IDC_TITLE_KEYBOARD);
+        */
+       beginbox(&cp, "Change the sequences sent by:", IDC_BOX_KEYBOARD1);
+       radioline(&cp, "The &Backspace key", IDC_DELSTATIC, 2,
+                 "Control-H", IDC_DEL008,
+                 "Control-? (127)", IDC_DEL127, NULL);
+       radioline(&cp, "The &Home and End keys", IDC_HOMESTATIC, 2,
+                 "Standard", IDC_HOMETILDE, "rxvt", IDC_HOMERXVT, NULL);
+       radioline(&cp, "The &Function keys and keypad", IDC_FUNCSTATIC, 3,
+                 "ESC[n~", IDC_FUNCTILDE,
+                 "Linux", IDC_FUNCLINUX,
+                 "Xterm R6", IDC_FUNCXTERM,
                  "VT400", IDC_FUNCVT400,
-                  "VT100+", IDC_FUNCVT100P,
-                 "SCO", IDC_FUNCSCO, NULL);
-        endbox(&cp);
-        beginbox(&cp, "Application keypad settings:",
-                 IDC_BOX_KEYBOARD2);
-        checkbox(&cp,
-                 "Application c&ursor keys totally disabled",
-                 IDC_NOAPPLICC);
-        radioline(&cp, "Initial state of cu&rsor keys:", IDC_CURSTATIC, 2,
-                  "Normal", IDC_CURNORMAL,
-                  "Application", IDC_CURAPPLIC, NULL);
-        checkbox(&cp,
-                 "Application ke&ypad keys totally disabled",
-                 IDC_NOAPPLICK);
-        radioline(&cp, "Initial state of &numeric keypad:", IDC_KPSTATIC, 3,
-                  "Normal", IDC_KPNORMAL,
-                  "Application", IDC_KPAPPLIC,
-                  "NetHack", IDC_KPNH, NULL);
-        endbox(&cp);
-        beginbox(&cp, "Enable extra keyboard features:",
-                 IDC_BOX_KEYBOARD3);
-        checkbox(&cp, "AltGr ac&ts as Compose key",
-                 IDC_COMPOSEKEY);
-        checkbox(&cp, "Control-Alt is &different from AltGr",
-                 IDC_CTRLALTKEYS);
-        endbox(&cp);
+                 "VT100+", IDC_FUNCVT100P, "SCO", IDC_FUNCSCO, NULL);
+       endbox(&cp);
+       beginbox(&cp, "Application keypad settings:", IDC_BOX_KEYBOARD2);
+       checkbox(&cp,
+                "Application c&ursor keys totally disabled",
+                IDC_NOAPPLICC);
+       radioline(&cp, "Initial state of cu&rsor keys:", IDC_CURSTATIC, 2,
+                 "Normal", IDC_CURNORMAL,
+                 "Application", IDC_CURAPPLIC, NULL);
+       checkbox(&cp,
+                "Application ke&ypad keys totally disabled",
+                IDC_NOAPPLICK);
+       radioline(&cp, "Initial state of &numeric keypad:", IDC_KPSTATIC,
+                 3, "Normal", IDC_KPNORMAL, "Application", IDC_KPAPPLIC,
+                 "NetHack", IDC_KPNH, NULL);
+       endbox(&cp);
+       beginbox(&cp, "Enable extra keyboard features:",
+                IDC_BOX_KEYBOARD3);
+       checkbox(&cp, "AltGr ac&ts as Compose key", IDC_COMPOSEKEY);
+       checkbox(&cp, "Control-Alt is &different from AltGr",
+                IDC_CTRLALTKEYS);
+       endbox(&cp);
     }
 
     if (panel == windowpanelstart) {
-        /* The Window panel. Accelerators used: [acgo] rmz sdkp w4ylt */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling PuTTY's window",
-                 IDC_TITLE_WINDOW);
-        beginbox(&cp, "Set the size of the window",
-                 IDC_BOX_WINDOW1);
-        multiedit(&cp,
-                  "&Rows", IDC_ROWSSTATIC, IDC_ROWSEDIT, 50,
-                  "Colu&mns", IDC_COLSSTATIC, IDC_COLSEDIT, 50,
-                  NULL);
-        checkbox(&cp, "Lock window size against resi&zing", IDC_LOCKSIZE);
-        endbox(&cp);
-        beginbox(&cp, "Control the scrollback in the window",
-                 IDC_BOX_WINDOW2);
-        staticedit(&cp, "Lines of &scrollback",
-                   IDC_SAVESTATIC, IDC_SAVEEDIT, 50);
-        checkbox(&cp, "&Display scrollbar", IDC_SCROLLBAR);
-        checkbox(&cp, "Reset scrollback on &keypress", IDC_SCROLLKEY);
-        checkbox(&cp, "Reset scrollback on dis&play activity",
-                 IDC_SCROLLDISP);
-        endbox(&cp);
-        beginbox(&cp, NULL, IDC_BOX_WINDOW3);
-        checkbox(&cp, "&Warn before closing window", IDC_CLOSEWARN);
-        checkbox(&cp, "Window closes on ALT-F&4", IDC_ALTF4);
-        checkbox(&cp, "S&ystem menu appears on ALT-Space", IDC_ALTSPACE);
-        checkbox(&cp, "System menu appears on A&LT alone", IDC_ALTONLY);
-        checkbox(&cp, "Ensure window is always on &top", IDC_ALWAYSONTOP);
-        endbox(&cp);
+       /* The Window panel. Accelerators used: [acgo] rmz sdkp w4ylt */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling PuTTY's window",
+                IDC_TITLE_WINDOW);
+       beginbox(&cp, "Set the size of the window", IDC_BOX_WINDOW1);
+       multiedit(&cp,
+                 "&Rows", IDC_ROWSSTATIC, IDC_ROWSEDIT, 50,
+                 "Colu&mns", IDC_COLSSTATIC, IDC_COLSEDIT, 50, NULL);
+       checkbox(&cp, "Lock window size against resi&zing", IDC_LOCKSIZE);
+       endbox(&cp);
+       beginbox(&cp, "Control the scrollback in the window",
+                IDC_BOX_WINDOW2);
+       staticedit(&cp, "Lines of &scrollback",
+                  IDC_SAVESTATIC, IDC_SAVEEDIT, 50);
+       checkbox(&cp, "&Display scrollbar", IDC_SCROLLBAR);
+       checkbox(&cp, "Reset scrollback on &keypress", IDC_SCROLLKEY);
+       checkbox(&cp, "Reset scrollback on dis&play activity",
+                IDC_SCROLLDISP);
+       endbox(&cp);
+       beginbox(&cp, NULL, IDC_BOX_WINDOW3);
+       checkbox(&cp, "&Warn before closing window", IDC_CLOSEWARN);
+       checkbox(&cp, "Window closes on ALT-F&4", IDC_ALTF4);
+       checkbox(&cp, "S&ystem menu appears on ALT-Space", IDC_ALTSPACE);
+       checkbox(&cp, "System menu appears on A&LT alone", IDC_ALTONLY);
+       checkbox(&cp, "Ensure window is always on &top", IDC_ALWAYSONTOP);
+       endbox(&cp);
     }
 
     if (panel == appearancepanelstart) {
-        /* The Appearance panel. Accelerators used: [acgo] luvb h ti p s */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling PuTTY's appearance",
-                 IDC_TITLE_APPEARANCE);
-        beginbox(&cp, "Adjust the use of the cursor",
-                 IDC_BOX_APPEARANCE1);
-        radioline(&cp, "Cursor appearance:", IDC_CURSORSTATIC, 3,
-                  "B&lock", IDC_CURBLOCK,
-                  "&Underline", IDC_CURUNDER,
-                  "&Vertical line", IDC_CURVERT,
-                  NULL);
-        checkbox(&cp, "Cursor &blinks", IDC_BLINKCUR);
-        endbox(&cp);
-        beginbox(&cp, "Set the font used in the terminal window",
-                 IDC_BOX_APPEARANCE2);
-        staticbtn(&cp, "", IDC_FONTSTATIC, "C&hange...", IDC_CHOOSEFONT);
-        endbox(&cp);
-        beginbox(&cp, "Adjust the use of the window title",
-                 IDC_BOX_APPEARANCE3);
-        multiedit(&cp,
-                  "Window &title:", IDC_WINTITLE,
-                  IDC_WINEDIT, 100, NULL);
-        checkbox(&cp, "Avoid ever using &icon title", IDC_WINNAME);
-        endbox(&cp);
-        beginbox(&cp, "Adjust the use of the mouse pointer",
-                 IDC_BOX_APPEARANCE4);
-        checkbox(&cp, "Hide mouse &pointer when typing in window",
-                 IDC_HIDEMOUSE);
-        endbox(&cp);
-        beginbox(&cp, "Adjust the window border",
-                 IDC_BOX_APPEARANCE5);
-        checkbox(&cp, "&Sunken-edge border (slightly thicker)",
-                 IDC_SUNKENEDGE);
-        endbox(&cp);
+       /* The Appearance panel. Accelerators used: [acgo] luvb h ti p s */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling PuTTY's appearance",
+                IDC_TITLE_APPEARANCE);
+       beginbox(&cp, "Adjust the use of the cursor", IDC_BOX_APPEARANCE1);
+       radioline(&cp, "Cursor appearance:", IDC_CURSORSTATIC, 3,
+                 "B&lock", IDC_CURBLOCK,
+                 "&Underline", IDC_CURUNDER,
+                 "&Vertical line", IDC_CURVERT, NULL);
+       checkbox(&cp, "Cursor &blinks", IDC_BLINKCUR);
+       endbox(&cp);
+       beginbox(&cp, "Set the font used in the terminal window",
+                IDC_BOX_APPEARANCE2);
+       staticbtn(&cp, "", IDC_FONTSTATIC, "C&hange...", IDC_CHOOSEFONT);
+       endbox(&cp);
+       beginbox(&cp, "Adjust the use of the window title",
+                IDC_BOX_APPEARANCE3);
+       multiedit(&cp,
+                 "Window &title:", IDC_WINTITLE, IDC_WINEDIT, 100, NULL);
+       checkbox(&cp, "Avoid ever using &icon title", IDC_WINNAME);
+       endbox(&cp);
+       beginbox(&cp, "Adjust the use of the mouse pointer",
+                IDC_BOX_APPEARANCE4);
+       checkbox(&cp, "Hide mouse &pointer when typing in window",
+                IDC_HIDEMOUSE);
+       endbox(&cp);
+       beginbox(&cp, "Adjust the window border", IDC_BOX_APPEARANCE5);
+       checkbox(&cp, "&Sunken-edge border (slightly thicker)",
+                IDC_SUNKENEDGE);
+       endbox(&cp);
     }
 
     if (panel == translationpanelstart) {
-        /* The Translation panel. Accelerators used: [acgo] xbep t s */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling character set translation",
-                 IDC_TITLE_TRANSLATION);
-        beginbox(&cp, "Adjust how PuTTY displays line drawing characters",
-                 IDC_BOX_TRANSLATION1);
-        radiobig(&cp,
-                 "Handling of line drawing characters:", IDC_VTSTATIC,
-                 "Font has &XWindows encoding", IDC_VTXWINDOWS,
-                 "Use font in &both ANSI and OEM modes", IDC_VTOEMANSI,
-                 "Use font in O&EM mode only", IDC_VTOEMONLY,
-                 "&Poor man's line drawing (""+"", ""-"" and ""|"")",
-                 IDC_VTPOORMAN, NULL);
-        endbox(&cp);
-        beginbox(&cp, "Enable character set translation on received data",
-                 IDC_BOX_TRANSLATION2);
-        radiobig(&cp,
-                 "Character set &translation:", IDC_XLATSTATIC,
-                 "None", IDC_NOXLAT,
-                 "KOI8 / Win-1251", IDC_KOI8WIN1251,
-                 "ISO-8859-2 / Win-1250", IDC_88592WIN1250,
-                 "ISO-8859-2 / CP852", IDC_88592CP852, NULL);
-        endbox(&cp);
-        beginbox(&cp, "Enable character set translation on input data",
-                 IDC_BOX_TRANSLATION3);
-        checkbox(&cp, "CAP&S LOCK acts as cyrillic switch",
-                 IDC_CAPSLOCKCYR);
-        endbox(&cp);
+       /* The Translation panel. Accelerators used: [acgo] xbep t s */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling character set translation",
+                IDC_TITLE_TRANSLATION);
+       beginbox(&cp, "Adjust how PuTTY displays line drawing characters",
+                IDC_BOX_TRANSLATION1);
+       radiobig(&cp,
+                "Handling of line drawing characters:", IDC_VTSTATIC,
+                "Font has &XWindows encoding", IDC_VTXWINDOWS,
+                "Use font in &both ANSI and OEM modes", IDC_VTOEMANSI,
+                "Use font in O&EM mode only", IDC_VTOEMONLY,
+                "&Poor man's line drawing (" "+" ", " "-" " and " "|" ")",
+                IDC_VTPOORMAN, NULL);
+       endbox(&cp);
+       beginbox(&cp, "Enable character set translation on received data",
+                IDC_BOX_TRANSLATION2);
+       radiobig(&cp,
+                "Character set &translation:", IDC_XLATSTATIC,
+                "None", IDC_NOXLAT,
+                "KOI8 / Win-1251", IDC_KOI8WIN1251,
+                "ISO-8859-2 / Win-1250", IDC_88592WIN1250,
+                "ISO-8859-2 / CP852", IDC_88592CP852, NULL);
+       endbox(&cp);
+       beginbox(&cp, "Enable character set translation on input data",
+                IDC_BOX_TRANSLATION3);
+       checkbox(&cp, "CAP&S LOCK acts as cyrillic switch",
+                IDC_CAPSLOCKCYR);
+       endbox(&cp);
     }
 
     if (panel == selectionpanelstart) {
-        /* The Selection panel. Accelerators used: [acgo] d wx hst */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling copy and paste",
-                 IDC_TITLE_SELECTION);
-        beginbox(&cp, "Translation of pasted characters",
-                 IDC_BOX_SELECTION1);
-        checkbox(&cp, "&Don't translate line drawing chars into +, - and |",
-                 IDC_RAWCNP);
-        endbox(&cp);
-        beginbox(&cp, "Control which mouse button does which thing",
-                 IDC_BOX_SELECTION2);
-        radiobig(&cp, "Action of mouse buttons:", IDC_MBSTATIC,
-                 "&Windows (Right pastes, Middle extends)", IDC_MBWINDOWS,
-                 "&xterm (Right extends, Middle pastes)", IDC_MBXTERM,
-                 NULL);
-        endbox(&cp);
-        beginbox(&cp, "Control the select-one-word-at-a-time mode",
-                 IDC_BOX_SELECTION3);
-        charclass(&cp, "C&haracter classes:", IDC_CCSTATIC, IDC_CCLIST,
-                  "&Set", IDC_CCSET, IDC_CCEDIT,
-                  "&to class", IDC_CCSTATIC2);
-        endbox(&cp);
+       /* The Selection panel. Accelerators used: [acgo] d wx hst */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling copy and paste",
+                IDC_TITLE_SELECTION);
+       beginbox(&cp, "Translation of pasted characters",
+                IDC_BOX_SELECTION1);
+       checkbox(&cp,
+                "&Don't translate line drawing chars into +, - and |",
+                IDC_RAWCNP);
+       endbox(&cp);
+       beginbox(&cp, "Control which mouse button does which thing",
+                IDC_BOX_SELECTION2);
+       radiobig(&cp, "Action of mouse buttons:", IDC_MBSTATIC,
+                "&Windows (Right pastes, Middle extends)", IDC_MBWINDOWS,
+                "&xterm (Right extends, Middle pastes)", IDC_MBXTERM,
+                NULL);
+       endbox(&cp);
+       beginbox(&cp, "Control the select-one-word-at-a-time mode",
+                IDC_BOX_SELECTION3);
+       charclass(&cp, "C&haracter classes:", IDC_CCSTATIC, IDC_CCLIST,
+                 "&Set", IDC_CCSET, IDC_CCEDIT,
+                 "&to class", IDC_CCSTATIC2);
+       endbox(&cp);
     }
 
     if (panel == colourspanelstart) {
-        /* The Colours panel. Accelerators used: [acgo] blum */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling use of colours",
-                 IDC_TITLE_COLOURS);
-        beginbox(&cp, "General options for colour usage",
-                 IDC_BOX_COLOURS1);
-        checkbox(&cp, "&Bolded text is a different colour", IDC_BOLDCOLOUR);
-        checkbox(&cp, "Attempt to use &logical palettes", IDC_PALETTE);
-        endbox(&cp);
-        beginbox(&cp, "Adjust the precise colours PuTTY displays",
-                 IDC_BOX_COLOURS2);
-        colouredit(&cp, "Select a colo&ur and then click to modify it:",
-                   IDC_COLOURSTATIC, IDC_COLOURLIST,
-                   "&Modify...", IDC_CHANGE,
-                   "Red:", IDC_RSTATIC, IDC_RVALUE,
-                   "Green:", IDC_GSTATIC, IDC_GVALUE,
-                   "Blue:", IDC_BSTATIC, IDC_BVALUE, NULL);
-        endbox(&cp);
+       /* The Colours panel. Accelerators used: [acgo] blum */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling use of colours",
+                IDC_TITLE_COLOURS);
+       beginbox(&cp, "General options for colour usage",
+                IDC_BOX_COLOURS1);
+       checkbox(&cp, "&Bolded text is a different colour",
+                IDC_BOLDCOLOUR);
+       checkbox(&cp, "Attempt to use &logical palettes", IDC_PALETTE);
+       endbox(&cp);
+       beginbox(&cp, "Adjust the precise colours PuTTY displays",
+                IDC_BOX_COLOURS2);
+       colouredit(&cp, "Select a colo&ur and then click to modify it:",
+                  IDC_COLOURSTATIC, IDC_COLOURLIST,
+                  "&Modify...", IDC_CHANGE,
+                  "Red:", IDC_RSTATIC, IDC_RVALUE,
+                  "Green:", IDC_GSTATIC, IDC_GVALUE,
+                  "Blue:", IDC_BSTATIC, IDC_BVALUE, NULL);
+       endbox(&cp);
     }
 
     if (panel == connectionpanelstart) {
-        /* The Connection panel. Accelerators used: [acgo] tuk */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        bartitle(&cp, "Options controlling the connection", IDC_TITLE_CONNECTION);
-        if (dlgtype == 0) {
-            beginbox(&cp, "Data to send to the server",
-                     IDC_BOX_CONNECTION1);
-            staticedit(&cp, "Terminal-&type string", IDC_TTSTATIC, IDC_TTEDIT, 50);
-            staticedit(&cp, "Auto-login &username", IDC_LOGSTATIC, IDC_LOGEDIT, 50);
-            endbox(&cp);
-        }
-        beginbox(&cp, "Sending of null packets to keep session active",
-                 IDC_BOX_CONNECTION2);
-        staticedit(&cp, "Seconds between &keepalives (0 to turn off)",
-                   IDC_PINGSTATIC, IDC_PINGEDIT, 20);
-        endbox(&cp);
+       /* The Connection panel. Accelerators used: [acgo] tuk */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       bartitle(&cp, "Options controlling the connection",
+                IDC_TITLE_CONNECTION);
+       if (dlgtype == 0) {
+           beginbox(&cp, "Data to send to the server",
+                    IDC_BOX_CONNECTION1);
+           staticedit(&cp, "Terminal-&type string", IDC_TTSTATIC,
+                      IDC_TTEDIT, 50);
+           staticedit(&cp, "Auto-login &username", IDC_LOGSTATIC,
+                      IDC_LOGEDIT, 50);
+           endbox(&cp);
+       }
+       beginbox(&cp, "Sending of null packets to keep session active",
+                IDC_BOX_CONNECTION2);
+       staticedit(&cp, "Seconds between &keepalives (0 to turn off)",
+                  IDC_PINGSTATIC, IDC_PINGEDIT, 20);
+       endbox(&cp);
     }
 
     if (panel == telnetpanelstart) {
-        /* The Telnet panel. Accelerators used: [acgo] svldr bf */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        if (dlgtype == 0) {
-            bartitle(&cp, "Options controlling Telnet connections", IDC_TITLE_TELNET);
-            beginbox(&cp, "Data to send to the server",
-                     IDC_BOX_TELNET1);
-            staticedit(&cp, "Terminal-&speed string", IDC_TSSTATIC, IDC_TSEDIT, 50);
-            envsetter(&cp, "Environment variables:", IDC_ENVSTATIC,
-                      "&Variable", IDC_VARSTATIC, IDC_VAREDIT,
-                      "Va&lue", IDC_VALSTATIC, IDC_VALEDIT,
-                      IDC_ENVLIST,
-                      "A&dd", IDC_ENVADD, "&Remove", IDC_ENVREMOVE);
-            endbox(&cp);
-            beginbox(&cp, "Telnet protocol adjustments",
-                     IDC_BOX_TELNET2);
-            radioline(&cp, "Handling of OLD_ENVIRON ambiguity:", IDC_EMSTATIC, 2,
-                      "&BSD (commonplace)", IDC_EMBSD,
-                      "R&FC 1408 (unusual)", IDC_EMRFC, NULL);
-            endbox(&cp);
-        }
+       /* The Telnet panel. Accelerators used: [acgo] svldr bf */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       if (dlgtype == 0) {
+           bartitle(&cp, "Options controlling Telnet connections",
+                    IDC_TITLE_TELNET);
+           beginbox(&cp, "Data to send to the server", IDC_BOX_TELNET1);
+           staticedit(&cp, "Terminal-&speed string", IDC_TSSTATIC,
+                      IDC_TSEDIT, 50);
+           envsetter(&cp, "Environment variables:", IDC_ENVSTATIC,
+                     "&Variable", IDC_VARSTATIC, IDC_VAREDIT, "Va&lue",
+                     IDC_VALSTATIC, IDC_VALEDIT, IDC_ENVLIST, "A&dd",
+                     IDC_ENVADD, "&Remove", IDC_ENVREMOVE);
+           endbox(&cp);
+           beginbox(&cp, "Telnet protocol adjustments", IDC_BOX_TELNET2);
+           radioline(&cp, "Handling of OLD_ENVIRON ambiguity:",
+                     IDC_EMSTATIC, 2, "&BSD (commonplace)", IDC_EMBSD,
+                     "R&FC 1408 (unusual)", IDC_EMRFC, NULL);
+           endbox(&cp);
+       }
     }
 
     if (panel == rloginpanelstart) {
-        /* The Rlogin panel. Accelerators used: [acgo] sl */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        if (dlgtype == 0) {
-            bartitle(&cp, "Options controlling Rlogin connections", IDC_TITLE_RLOGIN);
-            beginbox(&cp, "Data to send to the server",
-                     IDC_BOX_RLOGIN1);
-            staticedit(&cp, "Terminal-&speed string", IDC_R_TSSTATIC, IDC_R_TSEDIT, 50);
-            staticedit(&cp, "&Local username:", IDC_RLLUSERSTATIC, IDC_RLLUSEREDIT, 50);
-            endbox(&cp);
-        }
+       /* The Rlogin panel. Accelerators used: [acgo] sl */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       if (dlgtype == 0) {
+           bartitle(&cp, "Options controlling Rlogin connections",
+                    IDC_TITLE_RLOGIN);
+           beginbox(&cp, "Data to send to the server", IDC_BOX_RLOGIN1);
+           staticedit(&cp, "Terminal-&speed string", IDC_R_TSSTATIC,
+                      IDC_R_TSEDIT, 50);
+           staticedit(&cp, "&Local username:", IDC_RLLUSERSTATIC,
+                      IDC_RLLUSEREDIT, 50);
+           endbox(&cp);
+       }
     }
 
     if (panel == sshpanelstart) {
-        /* The SSH panel. Accelerators used: [acgo] rmfkw pe123bds i */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        if (dlgtype == 0) {
-            bartitle(&cp, "Options controlling SSH connections", IDC_TITLE_SSH);
-            beginbox(&cp, "Data to send to the server",
-                     IDC_BOX_SSH1);
-            multiedit(&cp,
-                      "&Remote command:", IDC_CMDSTATIC, IDC_CMDEDIT, 100,
-                      NULL);
-            endbox(&cp);
-            beginbox(&cp, "Authentication options",
-                     IDC_BOX_SSH2);
-            checkbox(&cp, "Atte&mpt TIS or CryptoCard authentication",
-                     IDC_AUTHTIS);
-            checkbox(&cp, "Allow agent &forwarding", IDC_AGENTFWD);
-            editbutton(&cp, "Private &key file for authentication:",
-                       IDC_PKSTATIC, IDC_PKEDIT, "Bro&wse...", IDC_PKBUTTON);
-            endbox(&cp);
-            beginbox(&cp, "Protocol options",
-                     IDC_BOX_SSH3);
-            checkbox(&cp, "Don't allocate a &pseudo-terminal", IDC_NOPTY);
-            checkbox(&cp, "Enable compr&ession", IDC_COMPRESS);
-            radioline(&cp, "Preferred SSH protocol version:",
-                      IDC_SSHPROTSTATIC, 2,
-                      "&1", IDC_SSHPROT1, "&2", IDC_SSHPROT2, NULL);
-            radioline(&cp, "Preferred encryption algorithm:", IDC_CIPHERSTATIC, 4,
-                      "&3DES", IDC_CIPHER3DES,
-                      "&Blowfish", IDC_CIPHERBLOWF,
-                      "&DES", IDC_CIPHERDES,
-                      "AE&S", IDC_CIPHERAES,
-                      NULL);
-            checkbox(&cp, "&Imitate SSH 2 MAC bug in commercial <= v2.3.x",
-                     IDC_BUGGYMAC);
-            endbox(&cp);
-        }
+       /* The SSH panel. Accelerators used: [acgo] rmfkw pe123bds i */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       if (dlgtype == 0) {
+           bartitle(&cp, "Options controlling SSH connections",
+                    IDC_TITLE_SSH);
+           beginbox(&cp, "Data to send to the server", IDC_BOX_SSH1);
+           multiedit(&cp,
+                     "&Remote command:", IDC_CMDSTATIC, IDC_CMDEDIT, 100,
+                     NULL);
+           endbox(&cp);
+           beginbox(&cp, "Authentication options", IDC_BOX_SSH2);
+           checkbox(&cp, "Atte&mpt TIS or CryptoCard authentication",
+                    IDC_AUTHTIS);
+           checkbox(&cp, "Allow agent &forwarding", IDC_AGENTFWD);
+           editbutton(&cp, "Private &key file for authentication:",
+                      IDC_PKSTATIC, IDC_PKEDIT, "Bro&wse...",
+                      IDC_PKBUTTON);
+           endbox(&cp);
+           beginbox(&cp, "Protocol options", IDC_BOX_SSH3);
+           checkbox(&cp, "Don't allocate a &pseudo-terminal", IDC_NOPTY);
+           checkbox(&cp, "Enable compr&ession", IDC_COMPRESS);
+           radioline(&cp, "Preferred SSH protocol version:",
+                     IDC_SSHPROTSTATIC, 2,
+                     "&1", IDC_SSHPROT1, "&2", IDC_SSHPROT2, NULL);
+           radioline(&cp, "Preferred encryption algorithm:",
+                     IDC_CIPHERSTATIC, 4, "&3DES", IDC_CIPHER3DES,
+                     "&Blowfish", IDC_CIPHERBLOWF, "&DES", IDC_CIPHERDES,
+                     "AE&S", IDC_CIPHERAES, NULL);
+           checkbox(&cp, "&Imitate SSH 2 MAC bug in commercial <= v2.3.x",
+                    IDC_BUGGYMAC);
+           endbox(&cp);
+       }
     }
 
     if (panel == tunnelspanelstart) {
-        /* The Tunnels panel. Accelerators used: [acgo] ex */
-        struct ctlpos cp;
-        ctlposinit(&cp, hwnd, 80, 3, 13);
-        if (dlgtype == 0) {
-            bartitle(&cp, "Options controlling SSH tunnelling",
-                     IDC_TITLE_TUNNELS);
-            beginbox(&cp, "X11 forwarding options",
-                     IDC_BOX_TUNNELS);
-            checkbox(&cp, "&Enable X11 forwarding",
-                     IDC_X11_FORWARD);
-            multiedit(&cp, "&X display location", IDC_X11_DISPSTATIC,
-                      IDC_X11_DISPLAY, 50, NULL);
-            endbox(&cp);
-        }
+       /* The Tunnels panel. Accelerators used: [acgo] ex */
+       struct ctlpos cp;
+       ctlposinit(&cp, hwnd, 80, 3, 13);
+       if (dlgtype == 0) {
+           bartitle(&cp, "Options controlling SSH tunnelling",
+                    IDC_TITLE_TUNNELS);
+           beginbox(&cp, "X11 forwarding options", IDC_BOX_TUNNELS);
+           checkbox(&cp, "&Enable X11 forwarding", IDC_X11_FORWARD);
+           multiedit(&cp, "&X display location", IDC_X11_DISPSTATIC,
+                     IDC_X11_DISPLAY, 50, NULL);
+           endbox(&cp);
+       }
     }
 }
 
 /*
  * This function is the configuration box.
  */
-static int GenericMainDlgProc (HWND hwnd, UINT msg,
-                              WPARAM wParam, LPARAM lParam,
-                              int dlgtype) {
+static int GenericMainDlgProc(HWND hwnd, UINT msg,
+                             WPARAM wParam, LPARAM lParam, int dlgtype)
+{
     HWND hw, treeview;
     struct treeview_faff tvfaff;
     HTREEITEM hsession;
@@ -1209,7 +1207,7 @@ static int GenericMainDlgProc (HWND hwnd, UINT msg,
     LOGFONT lf;
     char fontstatic[256];
     char portname[32];
-    struct servent * service;
+    struct servent *service;
     int i;
 
     switch (msg) {
@@ -1223,115 +1221,124 @@ static int GenericMainDlgProc (HWND hwnd, UINT msg,
            RECT rs, rd;
 
            hw = GetDesktopWindow();
-           if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
-               MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
-                           (rs.bottom + rs.top + rd.top - rd.bottom)/2,
-                           rd.right-rd.left, rd.bottom-rd.top, TRUE);
+           if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
+               MoveWindow(hwnd,
+                          (rs.right + rs.left + rd.left - rd.right) / 2,
+                          (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
+                          rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
        /*
         * Create the tree view.
         */
-        {
-            RECT r;
+       {
+           RECT r;
            WPARAM font;
-            HWND tvstatic;
-
-            r.left = 3; r.right = r.left + 75;
-            r.top = 3; r.bottom = r.top + 10;
-            MapDialogRect(hwnd, &r);
-            tvstatic = CreateWindowEx(0, "STATIC", "Cate&gory:",
-                                      WS_CHILD | WS_VISIBLE,
-                                      r.left, r.top,
-                                      r.right-r.left, r.bottom-r.top,
-                                      hwnd, (HMENU)IDCX_TVSTATIC, hinst, NULL);
+           HWND tvstatic;
+
+           r.left = 3;
+           r.right = r.left + 75;
+           r.top = 3;
+           r.bottom = r.top + 10;
+           MapDialogRect(hwnd, &r);
+           tvstatic = CreateWindowEx(0, "STATIC", "Cate&gory:",
+                                     WS_CHILD | WS_VISIBLE,
+                                     r.left, r.top,
+                                     r.right - r.left, r.bottom - r.top,
+                                     hwnd, (HMENU) IDCX_TVSTATIC, hinst,
+                                     NULL);
            font = SendMessage(hwnd, WM_GETFONT, 0, 0);
            SendMessage(tvstatic, WM_SETFONT, font, MAKELPARAM(TRUE, 0));
 
-            r.left = 3; r.right = r.left + 75;
-            r.top = 13; r.bottom = r.top + 206;
-            MapDialogRect(hwnd, &r);
-            treeview = CreateWindowEx(WS_EX_CLIENTEDGE, WC_TREEVIEW, "",
-                                      WS_CHILD | WS_VISIBLE |
-                                      WS_TABSTOP | TVS_HASLINES |
-                                      TVS_DISABLEDRAGDROP | TVS_HASBUTTONS |
-                                      TVS_LINESATROOT | TVS_SHOWSELALWAYS,
-                                      r.left, r.top,
-                                      r.right-r.left, r.bottom-r.top,
-                                      hwnd, (HMENU)IDCX_TREEVIEW, hinst, NULL);
+           r.left = 3;
+           r.right = r.left + 75;
+           r.top = 13;
+           r.bottom = r.top + 206;
+           MapDialogRect(hwnd, &r);
+           treeview = CreateWindowEx(WS_EX_CLIENTEDGE, WC_TREEVIEW, "",
+                                     WS_CHILD | WS_VISIBLE |
+                                     WS_TABSTOP | TVS_HASLINES |
+                                     TVS_DISABLEDRAGDROP | TVS_HASBUTTONS
+                                     | TVS_LINESATROOT |
+                                     TVS_SHOWSELALWAYS, r.left, r.top,
+                                     r.right - r.left, r.bottom - r.top,
+                                     hwnd, (HMENU) IDCX_TREEVIEW, hinst,
+                                     NULL);
            font = SendMessage(hwnd, WM_GETFONT, 0, 0);
            SendMessage(treeview, WM_SETFONT, font, MAKELPARAM(TRUE, 0));
-            tvfaff.treeview = treeview;
-            memset(tvfaff.lastat, 0, sizeof(tvfaff.lastat));
-        }
+           tvfaff.treeview = treeview;
+           memset(tvfaff.lastat, 0, sizeof(tvfaff.lastat));
+       }
 
        /*
         * Set up the tree view contents.
         */
-        hsession = treeview_insert(&tvfaff, 0, "Session");
-        treeview_insert(&tvfaff, 1, "Logging");
-        treeview_insert(&tvfaff, 0, "Terminal");
-        treeview_insert(&tvfaff, 1, "Keyboard");
-        treeview_insert(&tvfaff, 1, "Bell");
-        treeview_insert(&tvfaff, 0, "Window");
-        treeview_insert(&tvfaff, 1, "Appearance");
-        treeview_insert(&tvfaff, 1, "Translation");
-        treeview_insert(&tvfaff, 1, "Selection");
-        treeview_insert(&tvfaff, 1, "Colours");
-        treeview_insert(&tvfaff, 0, "Connection");
-        if (dlgtype == 0) {
-            treeview_insert(&tvfaff, 1, "Telnet");
-            treeview_insert(&tvfaff, 1, "Rlogin");
-            if (backends[3].backend != NULL) {
-                treeview_insert(&tvfaff, 1, "SSH");
-                treeview_insert(&tvfaff, 2, "Tunnels");
-            }
-        }
-
-        /*
-         * Put the treeview selection on to the Session panel. This
-         * should also cause creation of the relevant controls.
-         */
-        TreeView_SelectItem(treeview, hsession);
-
-        /*
-         * Set focus into the first available control.
-         */
-        {
-            HWND ctl;
-            ctl = GetDlgItem(hwnd, IDC_HOST);
-            if (!ctl) ctl = GetDlgItem(hwnd, IDC_CLOSEEXIT);
-            SetFocus(ctl);
-        }
+       hsession = treeview_insert(&tvfaff, 0, "Session");
+       treeview_insert(&tvfaff, 1, "Logging");
+       treeview_insert(&tvfaff, 0, "Terminal");
+       treeview_insert(&tvfaff, 1, "Keyboard");
+       treeview_insert(&tvfaff, 1, "Bell");
+       treeview_insert(&tvfaff, 0, "Window");
+       treeview_insert(&tvfaff, 1, "Appearance");
+       treeview_insert(&tvfaff, 1, "Translation");
+       treeview_insert(&tvfaff, 1, "Selection");
+       treeview_insert(&tvfaff, 1, "Colours");
+       treeview_insert(&tvfaff, 0, "Connection");
+       if (dlgtype == 0) {
+           treeview_insert(&tvfaff, 1, "Telnet");
+           treeview_insert(&tvfaff, 1, "Rlogin");
+           if (backends[3].backend != NULL) {
+               treeview_insert(&tvfaff, 1, "SSH");
+               treeview_insert(&tvfaff, 2, "Tunnels");
+           }
+       }
+
+       /*
+        * Put the treeview selection on to the Session panel. This
+        * should also cause creation of the relevant controls.
+        */
+       TreeView_SelectItem(treeview, hsession);
+
+       /*
+        * Set focus into the first available control.
+        */
+       {
+           HWND ctl;
+           ctl = GetDlgItem(hwnd, IDC_HOST);
+           if (!ctl)
+               ctl = GetDlgItem(hwnd, IDC_CLOSEEXIT);
+           SetFocus(ctl);
+       }
 
        SetWindowLong(hwnd, GWL_USERDATA, 1);
        return 0;
       case WM_LBUTTONUP:
-        /*
-         * Button release should trigger WM_OK if there was a
-         * previous double click on the session list.
-         */
-        ReleaseCapture();
-        if (readytogo)
-            SendMessage (hwnd, WM_COMMAND, IDOK, 0);
-        break;
+       /*
+        * Button release should trigger WM_OK if there was a
+        * previous double click on the session list.
+        */
+       ReleaseCapture();
+       if (readytogo)
+           SendMessage(hwnd, WM_COMMAND, IDOK, 0);
+       break;
       case WM_NOTIFY:
        if (LOWORD(wParam) == IDCX_TREEVIEW &&
-           ((LPNMHDR)lParam)->code == TVN_SELCHANGED) {
-           HTREEITEM i = TreeView_GetSelection(((LPNMHDR)lParam)->hwndFrom);
+           ((LPNMHDR) lParam)->code == TVN_SELCHANGED) {
+           HTREEITEM i =
+               TreeView_GetSelection(((LPNMHDR) lParam)->hwndFrom);
            TVITEM item;
-            int j;
+           int j;
            char buffer[64];
-            item.hItem = i;
+           item.hItem = i;
            item.pszText = buffer;
            item.cchTextMax = sizeof(buffer);
            item.mask = TVIF_TEXT;
-           TreeView_GetItem(((LPNMHDR)lParam)->hwndFrom, &item);
+           TreeView_GetItem(((LPNMHDR) lParam)->hwndFrom, &item);
            for (j = controlstartvalue; j < controlendvalue; j++) {
-                HWND item = GetDlgItem(hwnd, j);
-                if (item)
-                    DestroyWindow(item);
-            }
+               HWND item = GetDlgItem(hwnd, j);
+               if (item)
+                   DestroyWindow(item);
+           }
            if (!strcmp(buffer, "Session"))
                create_controls(hwnd, dlgtype, sessionpanelstart);
            if (!strcmp(buffer, "Logging"))
@@ -1363,9 +1370,9 @@ static int GenericMainDlgProc (HWND hwnd, UINT msg,
            if (!strcmp(buffer, "Translation"))
                create_controls(hwnd, dlgtype, translationpanelstart);
 
-            init_dlg_ctrls(hwnd);
+           init_dlg_ctrls(hwnd);
 
-           SetFocus (((LPNMHDR)lParam)->hwndFrom);   /* ensure focus stays */
+           SetFocus(((LPNMHDR) lParam)->hwndFrom);     /* ensure focus stays */
            return 0;
        }
        break;
@@ -1373,841 +1380,939 @@ static int GenericMainDlgProc (HWND hwnd, UINT msg,
        /*
         * Only process WM_COMMAND once the dialog is fully formed.
         */
-       if (GetWindowLong(hwnd, GWL_USERDATA) == 1) switch (LOWORD(wParam)) {
-         case IDOK:
-           if (*cfg.host)
-               EndDialog (hwnd, 1);
-           else
-               MessageBeep (0);
-           return 0;
-         case IDCANCEL:
-           EndDialog (hwnd, 0);
-           return 0;
-         case IDC_PROTTELNET:
-         case IDC_PROTRLOGIN:
-         case IDC_PROTSSH:
-         case IDC_PROTRAW:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               int i = IsDlgButtonChecked (hwnd, IDC_PROTSSH);
-               int j = IsDlgButtonChecked (hwnd, IDC_PROTTELNET);
-               int k = IsDlgButtonChecked (hwnd, IDC_PROTRLOGIN);
-               cfg.protocol = i ? PROT_SSH : j ? PROT_TELNET : k ? PROT_RLOGIN : PROT_RAW ;
-               if ((cfg.protocol == PROT_SSH && cfg.port != 22) ||
-                   (cfg.protocol == PROT_TELNET && cfg.port != 23) ||
-                   (cfg.protocol == PROT_RLOGIN && cfg.port != 513)) {
-                   cfg.port = i ? 22 : j ? 23 : 513;
-                   SetDlgItemInt (hwnd, IDC_PORT, cfg.port, FALSE);
+       if (GetWindowLong(hwnd, GWL_USERDATA) == 1)
+           switch (LOWORD(wParam)) {
+             case IDOK:
+               if (*cfg.host)
+                   EndDialog(hwnd, 1);
+               else
+                   MessageBeep(0);
+               return 0;
+             case IDCANCEL:
+               EndDialog(hwnd, 0);
+               return 0;
+             case IDC_PROTTELNET:
+             case IDC_PROTRLOGIN:
+             case IDC_PROTSSH:
+             case IDC_PROTRAW:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   int i = IsDlgButtonChecked(hwnd, IDC_PROTSSH);
+                   int j = IsDlgButtonChecked(hwnd, IDC_PROTTELNET);
+                   int k = IsDlgButtonChecked(hwnd, IDC_PROTRLOGIN);
+                   cfg.protocol =
+                       i ? PROT_SSH : j ? PROT_TELNET : k ? PROT_RLOGIN :
+                       PROT_RAW;
+                   if ((cfg.protocol == PROT_SSH && cfg.port != 22)
+                       || (cfg.protocol == PROT_TELNET && cfg.port != 23)
+                       || (cfg.protocol == PROT_RLOGIN
+                           && cfg.port != 513)) {
+                       cfg.port = i ? 22 : j ? 23 : 513;
+                       SetDlgItemInt(hwnd, IDC_PORT, cfg.port, FALSE);
+                   }
                }
-           }
-           break;
-         case IDC_HOST:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_HOST, cfg.host,
-                               sizeof(cfg.host)-1);
-           break;
-         case IDC_PORT:
-           if (HIWORD(wParam) == EN_CHANGE) {
-               GetDlgItemText (hwnd, IDC_PORT, portname, 31);
-               if (isdigit(portname[0]))
-                   MyGetDlgItemInt (hwnd, IDC_PORT, &cfg.port);
-               else {
-                   service = getservbyname(portname, NULL);
-                   if (service) cfg.port = ntohs(service->s_port);
-                   else cfg.port = 0;
+               break;
+             case IDC_HOST:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_HOST, cfg.host,
+                                  sizeof(cfg.host) - 1);
+               break;
+             case IDC_PORT:
+               if (HIWORD(wParam) == EN_CHANGE) {
+                   GetDlgItemText(hwnd, IDC_PORT, portname, 31);
+                   if (isdigit(portname[0]))
+                       MyGetDlgItemInt(hwnd, IDC_PORT, &cfg.port);
+                   else {
+                       service = getservbyname(portname, NULL);
+                       if (service)
+                           cfg.port = ntohs(service->s_port);
+                       else
+                           cfg.port = 0;
+                   }
                }
-           }
-           break;
-         case IDC_SESSEDIT:
-           if (HIWORD(wParam) == EN_CHANGE) {
-               SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_SETCURSEL,
-                                   (WPARAM) -1, 0);
-                GetDlgItemText (hwnd, IDC_SESSEDIT,
-                                savedsession, sizeof(savedsession)-1);
-                savedsession[sizeof(savedsession)-1] = '\0';
-            }
-           break;
-         case IDC_SESSSAVE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               /*
-                * Save a session
-                */
-               char str[2048];
-               GetDlgItemText (hwnd, IDC_SESSEDIT, str, sizeof(str)-1);
-               if (!*str) {
-                   int n = SendDlgItemMessage (hwnd, IDC_SESSLIST,
-                                               LB_GETCURSEL, 0, 0);
+               break;
+             case IDC_SESSEDIT:
+               if (HIWORD(wParam) == EN_CHANGE) {
+                   SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_SETCURSEL,
+                                      (WPARAM) - 1, 0);
+                   GetDlgItemText(hwnd, IDC_SESSEDIT,
+                                  savedsession, sizeof(savedsession) - 1);
+                   savedsession[sizeof(savedsession) - 1] = '\0';
+               }
+               break;
+             case IDC_SESSSAVE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   /*
+                    * Save a session
+                    */
+                   char str[2048];
+                   GetDlgItemText(hwnd, IDC_SESSEDIT, str,
+                                  sizeof(str) - 1);
+                   if (!*str) {
+                       int n = SendDlgItemMessage(hwnd, IDC_SESSLIST,
+                                                  LB_GETCURSEL, 0, 0);
+                       if (n == LB_ERR) {
+                           MessageBeep(0);
+                           break;
+                       }
+                       strcpy(str, sessions[n]);
+                   }
+                   save_settings(str, !!strcmp(str, "Default Settings"),
+                                 &cfg);
+                   get_sesslist(FALSE);
+                   get_sesslist(TRUE);
+                   SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_RESETCONTENT,
+                                      0, 0);
+                   for (i = 0; i < nsessions; i++)
+                       SendDlgItemMessage(hwnd, IDC_SESSLIST,
+                                          LB_ADDSTRING, 0,
+                                          (LPARAM) (sessions[i]));
+                   SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_SETCURSEL,
+                                      (WPARAM) - 1, 0);
+               }
+               break;
+             case IDC_SESSLIST:
+             case IDC_SESSLOAD:
+               if (LOWORD(wParam) == IDC_SESSLOAD &&
+                   HIWORD(wParam) != BN_CLICKED &&
+                   HIWORD(wParam) != BN_DOUBLECLICKED) break;
+               if (LOWORD(wParam) == IDC_SESSLIST &&
+                   HIWORD(wParam) != LBN_DBLCLK) break;
+               {
+                   int n = SendDlgItemMessage(hwnd, IDC_SESSLIST,
+                                              LB_GETCURSEL, 0, 0);
+                   int isdef;
                    if (n == LB_ERR) {
                        MessageBeep(0);
                        break;
                    }
-                   strcpy (str, sessions[n]);
+                   isdef = !strcmp(sessions[n], "Default Settings");
+                   load_settings(sessions[n], !isdef, &cfg);
+                   init_dlg_ctrls(hwnd);
+                   if (!isdef)
+                       SetDlgItemText(hwnd, IDC_SESSEDIT, sessions[n]);
+                   else
+                       SetDlgItemText(hwnd, IDC_SESSEDIT, "");
                }
-               save_settings (str, !!strcmp(str, "Default Settings"), &cfg);
-               get_sesslist (FALSE);
-               get_sesslist (TRUE);
-               SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_RESETCONTENT,
-                                   0, 0);
-               for (i = 0; i < nsessions; i++)
-                   SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_ADDSTRING,
-                                       0, (LPARAM) (sessions[i]));
-               SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_SETCURSEL,
-                                   (WPARAM) -1, 0);
-           }
-           break;
-         case IDC_SESSLIST:
-         case IDC_SESSLOAD:
-           if (LOWORD(wParam) == IDC_SESSLOAD &&
-               HIWORD(wParam) != BN_CLICKED &&
-               HIWORD(wParam) != BN_DOUBLECLICKED)
-               break;
-           if (LOWORD(wParam) == IDC_SESSLIST &&
-               HIWORD(wParam) != LBN_DBLCLK)
-               break;
-           {
-               int n = SendDlgItemMessage (hwnd, IDC_SESSLIST,
-                                           LB_GETCURSEL, 0, 0);
-                int isdef;
-               if (n == LB_ERR) {
-                   MessageBeep(0);
-                   break;
+               if (LOWORD(wParam) == IDC_SESSLIST) {
+                   /*
+                    * A double-click on a saved session should
+                    * actually start the session, not just load it.
+                    * Unless it's Default Settings or some other
+                    * host-less set of saved settings.
+                    */
+                   if (*cfg.host) {
+                       readytogo = TRUE;
+                       SetCapture(hwnd);
+                   }
                }
-                isdef = !strcmp(sessions[n], "Default Settings");
-               load_settings (sessions[n], !isdef, &cfg);
-               init_dlg_ctrls(hwnd);
-                if (!isdef)
-                    SetDlgItemText(hwnd, IDC_SESSEDIT, sessions[n]);
-               else
-                    SetDlgItemText(hwnd, IDC_SESSEDIT, "");
-           }
-           if (LOWORD(wParam) == IDC_SESSLIST) {
-               /*
-                * A double-click on a saved session should
-                * actually start the session, not just load it.
-                * Unless it's Default Settings or some other
-                * host-less set of saved settings.
-                */
-               if (*cfg.host) {
-                    readytogo = TRUE;
-                    SetCapture(hwnd);
-                }
-           }
-           break;
-         case IDC_SESSDEL:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               int n = SendDlgItemMessage (hwnd, IDC_SESSLIST,
-                                           LB_GETCURSEL, 0, 0);
-               if (n == LB_ERR || n == 0) {
-                   MessageBeep(0);
-                   break;
+               break;
+             case IDC_SESSDEL:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   int n = SendDlgItemMessage(hwnd, IDC_SESSLIST,
+                                              LB_GETCURSEL, 0, 0);
+                   if (n == LB_ERR || n == 0) {
+                       MessageBeep(0);
+                       break;
+                   }
+                   del_settings(sessions[n]);
+                   get_sesslist(FALSE);
+                   get_sesslist(TRUE);
+                   SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_RESETCONTENT,
+                                      0, 0);
+                   for (i = 0; i < nsessions; i++)
+                       SendDlgItemMessage(hwnd, IDC_SESSLIST,
+                                          LB_ADDSTRING, 0,
+                                          (LPARAM) (sessions[i]));
+                   SendDlgItemMessage(hwnd, IDC_SESSLIST, LB_SETCURSEL,
+                                      (WPARAM) - 1, 0);
                }
-               del_settings(sessions[n]);
-               get_sesslist (FALSE);
-               get_sesslist (TRUE);
-               SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_RESETCONTENT,
-                                   0, 0);
-               for (i = 0; i < nsessions; i++)
-                   SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_ADDSTRING,
-                                       0, (LPARAM) (sessions[i]));
-               SendDlgItemMessage (hwnd, IDC_SESSLIST, LB_SETCURSEL,
-                                   (WPARAM) -1, 0);
-           }
-          case IDC_PINGEDIT:
-            if (HIWORD(wParam) == EN_CHANGE)
-                MyGetDlgItemInt (hwnd, IDC_PINGEDIT, &cfg.ping_interval);
-            break;
-         case IDC_DEL008:
-         case IDC_DEL127:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.bksp_is_delete = IsDlgButtonChecked (hwnd, IDC_DEL127);
-           break;
-         case IDC_HOMETILDE:
-         case IDC_HOMERXVT:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.rxvt_homeend = IsDlgButtonChecked (hwnd, IDC_HOMERXVT);
-           break;
-         case IDC_FUNCTILDE:
-         case IDC_FUNCLINUX:
-         case IDC_FUNCXTERM:
-         case IDC_FUNCVT400:
-         case IDC_FUNCVT100P:
-         case IDC_FUNCSCO:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               switch (LOWORD(wParam)) {
-                 case IDC_FUNCTILDE: cfg.funky_type = 0; break;
-                 case IDC_FUNCLINUX: cfg.funky_type = 1; break;
-                 case IDC_FUNCXTERM: cfg.funky_type = 2; break;
-                 case IDC_FUNCVT400: cfg.funky_type = 3; break;
-                 case IDC_FUNCVT100P: cfg.funky_type = 4; break;
-                 case IDC_FUNCSCO: cfg.funky_type = 5; break;
+             case IDC_PINGEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemInt(hwnd, IDC_PINGEDIT,
+                                   &cfg.ping_interval);
+               break;
+             case IDC_DEL008:
+             case IDC_DEL127:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.bksp_is_delete =
+                       IsDlgButtonChecked(hwnd, IDC_DEL127);
+               break;
+             case IDC_HOMETILDE:
+             case IDC_HOMERXVT:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.rxvt_homeend =
+                       IsDlgButtonChecked(hwnd, IDC_HOMERXVT);
+               break;
+             case IDC_FUNCTILDE:
+             case IDC_FUNCLINUX:
+             case IDC_FUNCXTERM:
+             case IDC_FUNCVT400:
+             case IDC_FUNCVT100P:
+             case IDC_FUNCSCO:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       switch (LOWORD(wParam)) {
+                     case IDC_FUNCTILDE:
+                       cfg.funky_type = 0;
+                       break;
+                     case IDC_FUNCLINUX:
+                       cfg.funky_type = 1;
+                       break;
+                     case IDC_FUNCXTERM:
+                       cfg.funky_type = 2;
+                       break;
+                     case IDC_FUNCVT400:
+                       cfg.funky_type = 3;
+                       break;
+                     case IDC_FUNCVT100P:
+                       cfg.funky_type = 4;
+                       break;
+                     case IDC_FUNCSCO:
+                       cfg.funky_type = 5;
+                       break;
+                   }
+               break;
+             case IDC_KPNORMAL:
+             case IDC_KPAPPLIC:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   cfg.app_keypad =
+                       IsDlgButtonChecked(hwnd, IDC_KPAPPLIC);
+                   cfg.nethack_keypad = FALSE;
                }
-           break;
-         case IDC_KPNORMAL:
-         case IDC_KPAPPLIC:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               cfg.app_keypad = IsDlgButtonChecked (hwnd, IDC_KPAPPLIC);
-               cfg.nethack_keypad = FALSE;
-           }
-           break;
-         case IDC_KPNH:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               cfg.app_keypad = FALSE;
-               cfg.nethack_keypad = TRUE;
-           }
-           break;
-         case IDC_CURNORMAL:
-         case IDC_CURAPPLIC:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.app_cursor = IsDlgButtonChecked (hwnd, IDC_CURAPPLIC);
-           break;
-         case IDC_NOAPPLICC:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.no_applic_c = IsDlgButtonChecked (hwnd, IDC_NOAPPLICC);
-           break;
-         case IDC_NOAPPLICK:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.no_applic_k = IsDlgButtonChecked (hwnd, IDC_NOAPPLICK);
-           break;
-         case IDC_ALTF4:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.alt_f4 = IsDlgButtonChecked (hwnd, IDC_ALTF4);
-           break;
-         case IDC_ALTSPACE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.alt_space = IsDlgButtonChecked (hwnd, IDC_ALTSPACE);
-           break;
-         case IDC_ALTONLY:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.alt_only = IsDlgButtonChecked (hwnd, IDC_ALTONLY);
-           break;
-         case IDC_ECHOBACKEND:
-         case IDC_ECHOYES:
-         case IDC_ECHONO:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (LOWORD(wParam)==IDC_ECHOBACKEND) cfg.localecho=LD_BACKEND;
-               if (LOWORD(wParam)==IDC_ECHOYES) cfg.localecho=LD_YES;
-               if (LOWORD(wParam)==IDC_ECHONO) cfg.localecho=LD_NO;
-            }
-           break;
-         case IDC_EDITBACKEND:
-         case IDC_EDITYES:
-         case IDC_EDITNO:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (LOWORD(wParam)==IDC_EDITBACKEND) cfg.localedit=LD_BACKEND;
-               if (LOWORD(wParam)==IDC_EDITYES) cfg.localedit=LD_YES;
-               if (LOWORD(wParam)==IDC_EDITNO) cfg.localedit=LD_NO;
-            }
-           break;
-         case IDC_ANSWEREDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_ANSWEREDIT, cfg.answerback,
-                               sizeof(cfg.answerback)-1);
-           break;
-          case IDC_ALWAYSONTOP:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-                cfg.alwaysontop = IsDlgButtonChecked (hwnd, IDC_ALWAYSONTOP);
-           break;
-         case IDC_SCROLLKEY:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.scroll_on_key = IsDlgButtonChecked (hwnd, IDC_SCROLLKEY);
-           break;
-         case IDC_SCROLLDISP:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.scroll_on_disp = IsDlgButtonChecked (hwnd, IDC_SCROLLDISP);
-           break;
-         case IDC_COMPOSEKEY:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.compose_key = IsDlgButtonChecked (hwnd, IDC_COMPOSEKEY);
-           break;
-         case IDC_CTRLALTKEYS:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.ctrlaltkeys = IsDlgButtonChecked (hwnd, IDC_CTRLALTKEYS);
-           break;
-         case IDC_WRAPMODE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.wrap_mode = IsDlgButtonChecked (hwnd, IDC_WRAPMODE);
-           break;
-         case IDC_DECOM:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.dec_om = IsDlgButtonChecked (hwnd, IDC_DECOM);
-           break;
-         case IDC_LFHASCR:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.lfhascr = IsDlgButtonChecked (hwnd, IDC_LFHASCR);
-           break;
-         case IDC_ROWSEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               MyGetDlgItemInt (hwnd, IDC_ROWSEDIT, &cfg.height);
-           break;
-         case IDC_COLSEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               MyGetDlgItemInt (hwnd, IDC_COLSEDIT, &cfg.width);
-           break;
-         case IDC_SAVEEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               MyGetDlgItemInt (hwnd, IDC_SAVEEDIT, &cfg.savelines);
-           break;
-         case IDC_CHOOSEFONT:
-           lf.lfHeight = cfg.fontheight;
-           lf.lfWidth = lf.lfEscapement = lf.lfOrientation = 0;
-           lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0;
-           lf.lfWeight = (cfg.fontisbold ? FW_BOLD : 0);
-           lf.lfCharSet = cfg.fontcharset;
-           lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
-           lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
-           lf.lfQuality = DEFAULT_QUALITY;
-           lf.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
-           strncpy (lf.lfFaceName, cfg.font, sizeof(lf.lfFaceName)-1);
-           lf.lfFaceName[sizeof(lf.lfFaceName)-1] = '\0';
-
-           cf.lStructSize = sizeof(cf);
-           cf.hwndOwner = hwnd;
-           cf.lpLogFont = &lf;
-           cf.Flags = CF_FIXEDPITCHONLY | CF_FORCEFONTEXIST |
-               CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
-
-           if (ChooseFont (&cf)) {
-               strncpy (cfg.font, lf.lfFaceName, sizeof(cfg.font)-1);
-               cfg.font[sizeof(cfg.font)-1] = '\0';
-               cfg.fontisbold = (lf.lfWeight == FW_BOLD);
-               cfg.fontcharset = lf.lfCharSet;
-               cfg.fontheight = cf.iPointSize / 10;
-               fmtfont (fontstatic);
-               SetDlgItemText (hwnd, IDC_FONTSTATIC, fontstatic);
-           }
-           break;
-         case IDC_BELL_DISABLED:
-         case IDC_BELL_DEFAULT:
-         case IDC_BELL_WAVEFILE:
-         case IDC_BELL_VISUAL:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (LOWORD(wParam)==IDC_BELL_DISABLED) cfg.beep = BELL_DISABLED;
-               if (LOWORD(wParam)==IDC_BELL_DEFAULT) cfg.beep = BELL_DEFAULT;
-               if (LOWORD(wParam)==IDC_BELL_WAVEFILE) cfg.beep = BELL_WAVEFILE;
-               if (LOWORD(wParam)==IDC_BELL_VISUAL) cfg.beep = BELL_VISUAL;
-            }
-           break;
-         case IDC_BELL_WAVEBROWSE:
-            memset(&of, 0, sizeof(of));
+               break;
+             case IDC_KPNH:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   cfg.app_keypad = FALSE;
+                   cfg.nethack_keypad = TRUE;
+               }
+               break;
+             case IDC_CURNORMAL:
+             case IDC_CURAPPLIC:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.app_cursor =
+                       IsDlgButtonChecked(hwnd, IDC_CURAPPLIC);
+               break;
+             case IDC_NOAPPLICC:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.no_applic_c =
+                       IsDlgButtonChecked(hwnd, IDC_NOAPPLICC);
+               break;
+             case IDC_NOAPPLICK:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.no_applic_k =
+                       IsDlgButtonChecked(hwnd, IDC_NOAPPLICK);
+               break;
+             case IDC_ALTF4:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.alt_f4 = IsDlgButtonChecked(hwnd, IDC_ALTF4);
+               break;
+             case IDC_ALTSPACE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.alt_space =
+                       IsDlgButtonChecked(hwnd, IDC_ALTSPACE);
+               break;
+             case IDC_ALTONLY:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.alt_only =
+                       IsDlgButtonChecked(hwnd, IDC_ALTONLY);
+               break;
+             case IDC_ECHOBACKEND:
+             case IDC_ECHOYES:
+             case IDC_ECHONO:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (LOWORD(wParam) == IDC_ECHOBACKEND)
+                       cfg.localecho = LD_BACKEND;
+                   if (LOWORD(wParam) == IDC_ECHOYES)
+                       cfg.localecho = LD_YES;
+                   if (LOWORD(wParam) == IDC_ECHONO)
+                       cfg.localecho = LD_NO;
+               }
+               break;
+             case IDC_EDITBACKEND:
+             case IDC_EDITYES:
+             case IDC_EDITNO:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (LOWORD(wParam) == IDC_EDITBACKEND)
+                       cfg.localedit = LD_BACKEND;
+                   if (LOWORD(wParam) == IDC_EDITYES)
+                       cfg.localedit = LD_YES;
+                   if (LOWORD(wParam) == IDC_EDITNO)
+                       cfg.localedit = LD_NO;
+               }
+               break;
+             case IDC_ANSWEREDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_ANSWEREDIT, cfg.answerback,
+                                  sizeof(cfg.answerback) - 1);
+               break;
+             case IDC_ALWAYSONTOP:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.alwaysontop =
+                       IsDlgButtonChecked(hwnd, IDC_ALWAYSONTOP);
+               break;
+             case IDC_SCROLLKEY:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.scroll_on_key =
+                       IsDlgButtonChecked(hwnd, IDC_SCROLLKEY);
+               break;
+             case IDC_SCROLLDISP:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.scroll_on_disp =
+                       IsDlgButtonChecked(hwnd, IDC_SCROLLDISP);
+               break;
+             case IDC_COMPOSEKEY:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.compose_key =
+                       IsDlgButtonChecked(hwnd, IDC_COMPOSEKEY);
+               break;
+             case IDC_CTRLALTKEYS:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.ctrlaltkeys =
+                       IsDlgButtonChecked(hwnd, IDC_CTRLALTKEYS);
+               break;
+             case IDC_WRAPMODE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.wrap_mode =
+                       IsDlgButtonChecked(hwnd, IDC_WRAPMODE);
+               break;
+             case IDC_DECOM:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.dec_om = IsDlgButtonChecked(hwnd, IDC_DECOM);
+               break;
+             case IDC_LFHASCR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.lfhascr =
+                       IsDlgButtonChecked(hwnd, IDC_LFHASCR);
+               break;
+             case IDC_ROWSEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemInt(hwnd, IDC_ROWSEDIT, &cfg.height);
+               break;
+             case IDC_COLSEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemInt(hwnd, IDC_COLSEDIT, &cfg.width);
+               break;
+             case IDC_SAVEEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemInt(hwnd, IDC_SAVEEDIT, &cfg.savelines);
+               break;
+             case IDC_CHOOSEFONT:
+               lf.lfHeight = cfg.fontheight;
+               lf.lfWidth = lf.lfEscapement = lf.lfOrientation = 0;
+               lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0;
+               lf.lfWeight = (cfg.fontisbold ? FW_BOLD : 0);
+               lf.lfCharSet = cfg.fontcharset;
+               lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
+               lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
+               lf.lfQuality = DEFAULT_QUALITY;
+               lf.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
+               strncpy(lf.lfFaceName, cfg.font,
+                       sizeof(lf.lfFaceName) - 1);
+               lf.lfFaceName[sizeof(lf.lfFaceName) - 1] = '\0';
+
+               cf.lStructSize = sizeof(cf);
+               cf.hwndOwner = hwnd;
+               cf.lpLogFont = &lf;
+               cf.Flags = CF_FIXEDPITCHONLY | CF_FORCEFONTEXIST |
+                   CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
+
+               if (ChooseFont(&cf)) {
+                   strncpy(cfg.font, lf.lfFaceName, sizeof(cfg.font) - 1);
+                   cfg.font[sizeof(cfg.font) - 1] = '\0';
+                   cfg.fontisbold = (lf.lfWeight == FW_BOLD);
+                   cfg.fontcharset = lf.lfCharSet;
+                   cfg.fontheight = cf.iPointSize / 10;
+                   fmtfont(fontstatic);
+                   SetDlgItemText(hwnd, IDC_FONTSTATIC, fontstatic);
+               }
+               break;
+             case IDC_BELL_DISABLED:
+             case IDC_BELL_DEFAULT:
+             case IDC_BELL_WAVEFILE:
+             case IDC_BELL_VISUAL:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (LOWORD(wParam) == IDC_BELL_DISABLED)
+                       cfg.beep = BELL_DISABLED;
+                   if (LOWORD(wParam) == IDC_BELL_DEFAULT)
+                       cfg.beep = BELL_DEFAULT;
+                   if (LOWORD(wParam) == IDC_BELL_WAVEFILE)
+                       cfg.beep = BELL_WAVEFILE;
+                   if (LOWORD(wParam) == IDC_BELL_VISUAL)
+                       cfg.beep = BELL_VISUAL;
+               }
+               break;
+             case IDC_BELL_WAVEBROWSE:
+               memset(&of, 0, sizeof(of));
 #ifdef OPENFILENAME_SIZE_VERSION_400
-            of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
+               of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
 #else
-            of.lStructSize = sizeof(of);
+               of.lStructSize = sizeof(of);
 #endif
-            of.hwndOwner = hwnd;
-            of.lpstrFilter = "Wave Files\0*.WAV\0AllFiles\0*\0\0\0";
-            of.lpstrCustomFilter = NULL;
-            of.nFilterIndex = 1;
-            of.lpstrFile = filename; strcpy(filename, cfg.bell_wavefile);
-            of.nMaxFile = sizeof(filename);
-            of.lpstrFileTitle = NULL;
-            of.lpstrInitialDir = NULL;
-            of.lpstrTitle = "Select Bell Sound File";
-            of.Flags = 0;
-            if (GetOpenFileName(&of)) {
-                strcpy(cfg.bell_wavefile, filename);
-                SetDlgItemText (hwnd, IDC_BELL_WAVEEDIT, cfg.bell_wavefile);
-            }
-           break;
-         case IDC_BELL_WAVEEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_BELL_WAVEEDIT, cfg.bell_wavefile,
-                               sizeof(cfg.bell_wavefile)-1);
-           break;
-         case IDC_BELLOVL:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.bellovl = IsDlgButtonChecked (hwnd, IDC_BELLOVL);
-           break;
-          case IDC_BELLOVLN:
-            if (HIWORD(wParam) == EN_CHANGE)
-                MyGetDlgItemInt (hwnd, IDC_BELLOVLN, &cfg.bellovl_n);
-            break;
-          case IDC_BELLOVLT:
-            if (HIWORD(wParam) == EN_CHANGE)
-                MyGetDlgItemFlt (hwnd, IDC_BELLOVLT, &cfg.bellovl_t, 1000);
-            break;
-          case IDC_BELLOVLS:
-            if (HIWORD(wParam) == EN_CHANGE)
-                MyGetDlgItemFlt (hwnd, IDC_BELLOVLS, &cfg.bellovl_s, 1000);
-            break;
-         case IDC_BLINKTEXT:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.blinktext = IsDlgButtonChecked (hwnd, IDC_BLINKTEXT);
-           break;
-         case IDC_BCE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.bce = IsDlgButtonChecked (hwnd, IDC_BCE);
-           break;
-         case IDC_WINNAME:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.win_name_always = IsDlgButtonChecked (hwnd, IDC_WINNAME);
-           break;
-         case IDC_HIDEMOUSE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.hide_mouseptr = IsDlgButtonChecked (hwnd, IDC_HIDEMOUSE);
-           break;
-         case IDC_SUNKENEDGE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.sunken_edge = IsDlgButtonChecked (hwnd, IDC_SUNKENEDGE);
-           break;
-         case IDC_CURBLOCK:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.cursor_type = 0;
-           break;
-         case IDC_CURUNDER:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.cursor_type = 1;
-           break;
-         case IDC_CURVERT:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.cursor_type = 2;
-           break;
-          case IDC_BLINKCUR:
-            if (HIWORD(wParam) == BN_CLICKED ||
-                HIWORD(wParam) == BN_DOUBLECLICKED)
-                cfg.blink_cur = IsDlgButtonChecked (hwnd, IDC_BLINKCUR);
-            break;
-          case IDC_SCROLLBAR:
-            if (HIWORD(wParam) == BN_CLICKED ||
-                HIWORD(wParam) == BN_DOUBLECLICKED)
-                cfg.scrollbar = IsDlgButtonChecked (hwnd, IDC_SCROLLBAR);
-            break;
-          case IDC_LOCKSIZE:
-            if (HIWORD(wParam) == BN_CLICKED ||
-                HIWORD(wParam) == BN_DOUBLECLICKED)
-                cfg.locksize = IsDlgButtonChecked (hwnd, IDC_LOCKSIZE);
-            break;
-         case IDC_WINEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_WINEDIT, cfg.wintitle,
-                               sizeof(cfg.wintitle)-1);
-           break;
-          case IDC_COEALWAYS:
-          case IDC_COENEVER:
-          case IDC_COENORMAL:
-            if (HIWORD(wParam) == BN_CLICKED ||
-                HIWORD(wParam) == BN_DOUBLECLICKED) {
-                cfg.close_on_exit = IsDlgButtonChecked (hwnd, IDC_COEALWAYS) ? COE_ALWAYS :
-                                    IsDlgButtonChecked (hwnd, IDC_COENEVER) ? COE_NEVER :
-                                    COE_NORMAL;
-            }
-            break;
-         case IDC_CLOSEWARN:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.warn_on_close = IsDlgButtonChecked (hwnd, IDC_CLOSEWARN);
-           break;
-         case IDC_TTEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-           GetDlgItemText (hwnd, IDC_TTEDIT, cfg.termtype,
-                           sizeof(cfg.termtype)-1);
-           break;
-         case IDC_LGFEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-           GetDlgItemText (hwnd, IDC_LGFEDIT, cfg.logfilename,
-                           sizeof(cfg.logfilename)-1);
-           break;
-         case IDC_LGFBUTTON:
-            memset(&of, 0, sizeof(of));
+               of.hwndOwner = hwnd;
+               of.lpstrFilter = "Wave Files\0*.WAV\0AllFiles\0*\0\0\0";
+               of.lpstrCustomFilter = NULL;
+               of.nFilterIndex = 1;
+               of.lpstrFile = filename;
+               strcpy(filename, cfg.bell_wavefile);
+               of.nMaxFile = sizeof(filename);
+               of.lpstrFileTitle = NULL;
+               of.lpstrInitialDir = NULL;
+               of.lpstrTitle = "Select Bell Sound File";
+               of.Flags = 0;
+               if (GetOpenFileName(&of)) {
+                   strcpy(cfg.bell_wavefile, filename);
+                   SetDlgItemText(hwnd, IDC_BELL_WAVEEDIT,
+                                  cfg.bell_wavefile);
+               }
+               break;
+             case IDC_BELL_WAVEEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_BELL_WAVEEDIT,
+                                  cfg.bell_wavefile,
+                                  sizeof(cfg.bell_wavefile) - 1);
+               break;
+             case IDC_BELLOVL:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.bellovl =
+                       IsDlgButtonChecked(hwnd, IDC_BELLOVL);
+               break;
+             case IDC_BELLOVLN:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemInt(hwnd, IDC_BELLOVLN, &cfg.bellovl_n);
+               break;
+             case IDC_BELLOVLT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemFlt(hwnd, IDC_BELLOVLT, &cfg.bellovl_t,
+                                   1000);
+               break;
+             case IDC_BELLOVLS:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   MyGetDlgItemFlt(hwnd, IDC_BELLOVLS, &cfg.bellovl_s,
+                                   1000);
+               break;
+             case IDC_BLINKTEXT:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.blinktext =
+                       IsDlgButtonChecked(hwnd, IDC_BLINKTEXT);
+               break;
+             case IDC_BCE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.bce = IsDlgButtonChecked(hwnd, IDC_BCE);
+               break;
+             case IDC_WINNAME:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.win_name_always =
+                       IsDlgButtonChecked(hwnd, IDC_WINNAME);
+               break;
+             case IDC_HIDEMOUSE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.hide_mouseptr =
+                       IsDlgButtonChecked(hwnd, IDC_HIDEMOUSE);
+               break;
+             case IDC_SUNKENEDGE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.sunken_edge =
+                       IsDlgButtonChecked(hwnd, IDC_SUNKENEDGE);
+               break;
+             case IDC_CURBLOCK:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.cursor_type = 0;
+               break;
+             case IDC_CURUNDER:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.cursor_type = 1;
+               break;
+             case IDC_CURVERT:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.cursor_type = 2;
+               break;
+             case IDC_BLINKCUR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.blink_cur =
+                       IsDlgButtonChecked(hwnd, IDC_BLINKCUR);
+               break;
+             case IDC_SCROLLBAR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.scrollbar =
+                       IsDlgButtonChecked(hwnd, IDC_SCROLLBAR);
+               break;
+             case IDC_LOCKSIZE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.locksize =
+                       IsDlgButtonChecked(hwnd, IDC_LOCKSIZE);
+               break;
+             case IDC_WINEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_WINEDIT, cfg.wintitle,
+                                  sizeof(cfg.wintitle) - 1);
+               break;
+             case IDC_COEALWAYS:
+             case IDC_COENEVER:
+             case IDC_COENORMAL:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   cfg.close_on_exit =
+                       IsDlgButtonChecked(hwnd,
+                                          IDC_COEALWAYS) ? COE_ALWAYS :
+                       IsDlgButtonChecked(hwnd,
+                                          IDC_COENEVER) ? COE_NEVER :
+                       COE_NORMAL;
+               }
+               break;
+             case IDC_CLOSEWARN:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.warn_on_close =
+                       IsDlgButtonChecked(hwnd, IDC_CLOSEWARN);
+               break;
+             case IDC_TTEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_TTEDIT, cfg.termtype,
+                                  sizeof(cfg.termtype) - 1);
+               break;
+             case IDC_LGFEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_LGFEDIT, cfg.logfilename,
+                                  sizeof(cfg.logfilename) - 1);
+               break;
+             case IDC_LGFBUTTON:
+               memset(&of, 0, sizeof(of));
 #ifdef OPENFILENAME_SIZE_VERSION_400
-            of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
+               of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
 #else
-            of.lStructSize = sizeof(of);
+               of.lStructSize = sizeof(of);
 #endif
-            of.hwndOwner = hwnd;
-            of.lpstrFilter = "All Files\0*\0\0\0";
-            of.lpstrCustomFilter = NULL;
-            of.nFilterIndex = 1;
-            of.lpstrFile = filename; strcpy(filename, cfg.logfilename);
-            of.nMaxFile = sizeof(filename);
-            of.lpstrFileTitle = NULL;
-            of.lpstrInitialDir = NULL;
-            of.lpstrTitle = "Select session log file";
-            of.Flags = 0;
-            if (GetSaveFileName(&of)) {
-                strcpy(cfg.logfilename, filename);
-                SetDlgItemText (hwnd, IDC_LGFEDIT, cfg.logfilename);
-            }
-           break;
-         case IDC_LSTATOFF:
-         case IDC_LSTATASCII:
-         case IDC_LSTATRAW:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATOFF)) cfg.logtype = 0;
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATASCII)) cfg.logtype = 1;
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATRAW)) cfg.logtype = 2;
-           }
-           break;
-         case IDC_LSTATXASK:
-         case IDC_LSTATXAPN:
-         case IDC_LSTATXOVR:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATXASK)) cfg.logxfovr = LGXF_ASK;
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATXAPN)) cfg.logxfovr = LGXF_APN;
-               if (IsDlgButtonChecked (hwnd, IDC_LSTATXOVR)) cfg.logxfovr = LGXF_OVR;
-           }
-           break;
-         case IDC_TSEDIT:
-         case IDC_R_TSEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, LOWORD(wParam), cfg.termspeed,
-                               sizeof(cfg.termspeed)-1);
-           break;
-         case IDC_LOGEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_LOGEDIT, cfg.username,
-                               sizeof(cfg.username)-1);
-           break;
-         case IDC_RLLUSEREDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_RLLUSEREDIT, cfg.localusername,
-                               sizeof(cfg.localusername)-1);
-           break;
-         case IDC_EMBSD:
-         case IDC_EMRFC:
-           cfg.rfc_environ = IsDlgButtonChecked (hwnd, IDC_EMRFC);
-           break;
-         case IDC_ENVADD:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-              char str[sizeof(cfg.environmt)];
-               char *p;
-               GetDlgItemText (hwnd, IDC_VAREDIT, str, sizeof(str)-1);
-               if (!*str) {
-                   MessageBeep(0);
-                   break;
+               of.hwndOwner = hwnd;
+               of.lpstrFilter = "All Files\0*\0\0\0";
+               of.lpstrCustomFilter = NULL;
+               of.nFilterIndex = 1;
+               of.lpstrFile = filename;
+               strcpy(filename, cfg.logfilename);
+               of.nMaxFile = sizeof(filename);
+               of.lpstrFileTitle = NULL;
+               of.lpstrInitialDir = NULL;
+               of.lpstrTitle = "Select session log file";
+               of.Flags = 0;
+               if (GetSaveFileName(&of)) {
+                   strcpy(cfg.logfilename, filename);
+                   SetDlgItemText(hwnd, IDC_LGFEDIT, cfg.logfilename);
                }
-               p = str + strlen(str);
-               *p++ = '\t';
-               GetDlgItemText (hwnd, IDC_VALEDIT, p, sizeof(str)-1-(p-str));
-               if (!*p) {
-                   MessageBeep(0);
-                   break;
+               break;
+             case IDC_LSTATOFF:
+             case IDC_LSTATASCII:
+             case IDC_LSTATRAW:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATOFF))
+                       cfg.logtype = 0;
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATASCII))
+                       cfg.logtype = 1;
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATRAW))
+                       cfg.logtype = 2;
                }
-              p = cfg.environmt;
-               while (*p) {
-                   while (*p) p++;
-                   p++;
+               break;
+             case IDC_LSTATXASK:
+             case IDC_LSTATXAPN:
+             case IDC_LSTATXOVR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATXASK))
+                       cfg.logxfovr = LGXF_ASK;
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATXAPN))
+                       cfg.logxfovr = LGXF_APN;
+                   if (IsDlgButtonChecked(hwnd, IDC_LSTATXOVR))
+                       cfg.logxfovr = LGXF_OVR;
                }
-              if ((p-cfg.environmt) + strlen(str) + 2 < sizeof(cfg.environmt)) {
-                   strcpy (p, str);
-                   p[strlen(str)+1] = '\0';
-                   SendDlgItemMessage (hwnd, IDC_ENVLIST, LB_ADDSTRING,
-                                       0, (LPARAM)str);
-                   SetDlgItemText (hwnd, IDC_VAREDIT, "");
-                   SetDlgItemText (hwnd, IDC_VALEDIT, "");
-               } else {
-                   MessageBox(hwnd, "Environment too big", "PuTTY Error",
-                              MB_OK | MB_ICONERROR);
+               break;
+             case IDC_TSEDIT:
+             case IDC_R_TSEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, LOWORD(wParam), cfg.termspeed,
+                                  sizeof(cfg.termspeed) - 1);
+               break;
+             case IDC_LOGEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_LOGEDIT, cfg.username,
+                                  sizeof(cfg.username) - 1);
+               break;
+             case IDC_RLLUSEREDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_RLLUSEREDIT,
+                                  cfg.localusername,
+                                  sizeof(cfg.localusername) - 1);
+               break;
+             case IDC_EMBSD:
+             case IDC_EMRFC:
+               cfg.rfc_environ = IsDlgButtonChecked(hwnd, IDC_EMRFC);
+               break;
+             case IDC_ENVADD:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   char str[sizeof(cfg.environmt)];
+                   char *p;
+                   GetDlgItemText(hwnd, IDC_VAREDIT, str,
+                                  sizeof(str) - 1);
+                   if (!*str) {
+                       MessageBeep(0);
+                       break;
+                   }
+                   p = str + strlen(str);
+                   *p++ = '\t';
+                   GetDlgItemText(hwnd, IDC_VALEDIT, p,
+                                  sizeof(str) - 1 - (p - str));
+                   if (!*p) {
+                       MessageBeep(0);
+                       break;
+                   }
+                   p = cfg.environmt;
+                   while (*p) {
+                       while (*p)
+                           p++;
+                       p++;
+                   }
+                   if ((p - cfg.environmt) + strlen(str) + 2 <
+                       sizeof(cfg.environmt)) {
+                       strcpy(p, str);
+                       p[strlen(str) + 1] = '\0';
+                       SendDlgItemMessage(hwnd, IDC_ENVLIST, LB_ADDSTRING,
+                                          0, (LPARAM) str);
+                       SetDlgItemText(hwnd, IDC_VAREDIT, "");
+                       SetDlgItemText(hwnd, IDC_VALEDIT, "");
+                   } else {
+                       MessageBox(hwnd, "Environment too big",
+                                  "PuTTY Error", MB_OK | MB_ICONERROR);
+                   }
                }
-           }
-           break;
-         case IDC_ENVREMOVE:
-           if (HIWORD(wParam) != BN_CLICKED &&
-               HIWORD(wParam) != BN_DOUBLECLICKED)
-               break;
-           i = SendDlgItemMessage (hwnd, IDC_ENVLIST, LB_GETCURSEL, 0, 0);
-           if (i == LB_ERR)
-               MessageBeep (0);
-           else {
-               char *p, *q;
-
-               SendDlgItemMessage (hwnd, IDC_ENVLIST, LB_DELETESTRING,
-                                   i, 0);
-              p = cfg.environmt;
-               while (i > 0) {
+               break;
+             case IDC_ENVREMOVE:
+               if (HIWORD(wParam) != BN_CLICKED &&
+                   HIWORD(wParam) != BN_DOUBLECLICKED) break;
+               i =
+                   SendDlgItemMessage(hwnd, IDC_ENVLIST, LB_GETCURSEL, 0,
+                                      0);
+               if (i == LB_ERR)
+                   MessageBeep(0);
+               else {
+                   char *p, *q;
+
+                   SendDlgItemMessage(hwnd, IDC_ENVLIST, LB_DELETESTRING,
+                                      i, 0);
+                   p = cfg.environmt;
+                   while (i > 0) {
+                       if (!*p)
+                           goto disaster;
+                       while (*p)
+                           p++;
+                       p++;
+                       i--;
+                   }
+                   q = p;
                    if (!*p)
                        goto disaster;
-                   while (*p) p++;
-                   p++;
-                   i--;
-               }
-               q = p;
-               if (!*p)
-                   goto disaster;
-               while (*p) p++;
-               p++;
-               while (*p) {
                    while (*p)
+                       p++;
+                   p++;
+                   while (*p) {
+                       while (*p)
+                           *q++ = *p++;
                        *q++ = *p++;
-                   *q++ = *p++;
+                   }
+                   *q = '\0';
+                 disaster:;
                }
-               *q = '\0';
-               disaster:;
-           }
-           break;
-         case IDC_NOPTY:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.nopty = IsDlgButtonChecked (hwnd, IDC_NOPTY);
-           break;
-         case IDC_COMPRESS:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.compression = IsDlgButtonChecked (hwnd, IDC_COMPRESS);
-           break;
-         case IDC_BUGGYMAC:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.buggymac = IsDlgButtonChecked (hwnd, IDC_BUGGYMAC);
-           break;
-         case IDC_AGENTFWD:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.agentfwd = IsDlgButtonChecked (hwnd, IDC_AGENTFWD);
-           break;
-         case IDC_CIPHER3DES:
-         case IDC_CIPHERBLOWF:
-         case IDC_CIPHERDES:
-         case IDC_CIPHERAES:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (IsDlgButtonChecked (hwnd, IDC_CIPHER3DES))
-                   cfg.cipher = CIPHER_3DES;
-               else if (IsDlgButtonChecked (hwnd, IDC_CIPHERBLOWF))
-                   cfg.cipher = CIPHER_BLOWFISH;
-               else if (IsDlgButtonChecked (hwnd, IDC_CIPHERDES))
-                   cfg.cipher = CIPHER_DES;
-               else if (IsDlgButtonChecked (hwnd, IDC_CIPHERAES))
-                   cfg.cipher = CIPHER_AES;
-           }
-           break;
-         case IDC_SSHPROT1:
-         case IDC_SSHPROT2:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               if (IsDlgButtonChecked (hwnd, IDC_SSHPROT1))
-                   cfg.sshprot = 1;
-               else if (IsDlgButtonChecked (hwnd, IDC_SSHPROT2))
-                   cfg.sshprot = 2;
-           }
-           break;
-         case IDC_AUTHTIS:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.try_tis_auth = IsDlgButtonChecked (hwnd, IDC_AUTHTIS);
-           break;
-         case IDC_PKEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_PKEDIT, cfg.keyfile,
-                               sizeof(cfg.keyfile)-1);
-           break;
-         case IDC_CMDEDIT:
-           if (HIWORD(wParam) == EN_CHANGE)
-               GetDlgItemText (hwnd, IDC_CMDEDIT, cfg.remote_cmd,
-                               sizeof(cfg.remote_cmd)-1);
-           break;
-         case IDC_PKBUTTON:
-            memset(&of, 0, sizeof(of));
+               break;
+             case IDC_NOPTY:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.nopty = IsDlgButtonChecked(hwnd, IDC_NOPTY);
+               break;
+             case IDC_COMPRESS:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.compression =
+                       IsDlgButtonChecked(hwnd, IDC_COMPRESS);
+               break;
+             case IDC_BUGGYMAC:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.buggymac =
+                       IsDlgButtonChecked(hwnd, IDC_BUGGYMAC);
+               break;
+             case IDC_AGENTFWD:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.agentfwd =
+                       IsDlgButtonChecked(hwnd, IDC_AGENTFWD);
+               break;
+             case IDC_CIPHER3DES:
+             case IDC_CIPHERBLOWF:
+             case IDC_CIPHERDES:
+             case IDC_CIPHERAES:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (IsDlgButtonChecked(hwnd, IDC_CIPHER3DES))
+                       cfg.cipher = CIPHER_3DES;
+                   else if (IsDlgButtonChecked(hwnd, IDC_CIPHERBLOWF))
+                       cfg.cipher = CIPHER_BLOWFISH;
+                   else if (IsDlgButtonChecked(hwnd, IDC_CIPHERDES))
+                       cfg.cipher = CIPHER_DES;
+                   else if (IsDlgButtonChecked(hwnd, IDC_CIPHERAES))
+                       cfg.cipher = CIPHER_AES;
+               }
+               break;
+             case IDC_SSHPROT1:
+             case IDC_SSHPROT2:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   if (IsDlgButtonChecked(hwnd, IDC_SSHPROT1))
+                       cfg.sshprot = 1;
+                   else if (IsDlgButtonChecked(hwnd, IDC_SSHPROT2))
+                       cfg.sshprot = 2;
+               }
+               break;
+             case IDC_AUTHTIS:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.try_tis_auth =
+                       IsDlgButtonChecked(hwnd, IDC_AUTHTIS);
+               break;
+             case IDC_PKEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_PKEDIT, cfg.keyfile,
+                                  sizeof(cfg.keyfile) - 1);
+               break;
+             case IDC_CMDEDIT:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_CMDEDIT, cfg.remote_cmd,
+                                  sizeof(cfg.remote_cmd) - 1);
+               break;
+             case IDC_PKBUTTON:
+               memset(&of, 0, sizeof(of));
 #ifdef OPENFILENAME_SIZE_VERSION_400
-            of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
+               of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
 #else
-            of.lStructSize = sizeof(of);
+               of.lStructSize = sizeof(of);
 #endif
-            of.hwndOwner = hwnd;
-            of.lpstrFilter = "All Files\0*\0\0\0";
-            of.lpstrCustomFilter = NULL;
-            of.nFilterIndex = 1;
-            of.lpstrFile = filename; strcpy(filename, cfg.keyfile);
-            of.nMaxFile = sizeof(filename);
-            of.lpstrFileTitle = NULL;
-            of.lpstrInitialDir = NULL;
-            of.lpstrTitle = "Select Public Key File";
-            of.Flags = 0;
-            if (GetOpenFileName(&of)) {
-                strcpy(cfg.keyfile, filename);
-                SetDlgItemText (hwnd, IDC_PKEDIT, cfg.keyfile);
-            }
-           break;
-         case IDC_RAWCNP:
-           cfg.rawcnp = IsDlgButtonChecked (hwnd, IDC_RAWCNP);
-         case IDC_MBWINDOWS:
-         case IDC_MBXTERM:
-           cfg.mouse_is_xterm = IsDlgButtonChecked (hwnd, IDC_MBXTERM);
-           break;
-         case IDC_CCSET:
-           {
-               BOOL ok;
-               int i;
-               int n = GetDlgItemInt (hwnd, IDC_CCEDIT, &ok, FALSE);
-
-               if (!ok)
-                   MessageBeep (0);
-               else {
-                   for (i=0; i<256; i++)
-                       if (SendDlgItemMessage (hwnd, IDC_CCLIST, LB_GETSEL,
-                                               i, 0)) {
-                           char str[100];
-                           cfg.wordness[i] = n;
-                           SendDlgItemMessage (hwnd, IDC_CCLIST,
-                                               LB_DELETESTRING, i, 0);
-                           sprintf(str, "%d\t(0x%02X)\t%c\t%d", i, i,
-                                   (i>=0x21 && i != 0x7F) ? i : ' ',
-                                   cfg.wordness[i]);
-                           SendDlgItemMessage (hwnd, IDC_CCLIST,
-                                               LB_INSERTSTRING, i,
-                                               (LPARAM)str);
-                       }
+               of.hwndOwner = hwnd;
+               of.lpstrFilter = "All Files\0*\0\0\0";
+               of.lpstrCustomFilter = NULL;
+               of.nFilterIndex = 1;
+               of.lpstrFile = filename;
+               strcpy(filename, cfg.keyfile);
+               of.nMaxFile = sizeof(filename);
+               of.lpstrFileTitle = NULL;
+               of.lpstrInitialDir = NULL;
+               of.lpstrTitle = "Select Public Key File";
+               of.Flags = 0;
+               if (GetOpenFileName(&of)) {
+                   strcpy(cfg.keyfile, filename);
+                   SetDlgItemText(hwnd, IDC_PKEDIT, cfg.keyfile);
                }
-           }
-           break;
-         case IDC_BOLDCOLOUR:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               int n, i;
-               cfg.bold_colour = IsDlgButtonChecked (hwnd, IDC_BOLDCOLOUR);
-               n = SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_GETCOUNT, 0, 0);
-               if (n != 12+10*cfg.bold_colour) {
-                   for (i=n; i-- >0 ;)
-                       SendDlgItemMessage (hwnd, IDC_COLOURLIST,
-                                               LB_DELETESTRING, i, 0);
-                   for (i=0; i<22; i++)
-                       if (cfg.bold_colour || permcolour[i])
-                           SendDlgItemMessage (hwnd, IDC_COLOURLIST, 
-                                               LB_ADDSTRING, 0,
-                                               (LPARAM) colours[i]);
+               break;
+             case IDC_RAWCNP:
+               cfg.rawcnp = IsDlgButtonChecked(hwnd, IDC_RAWCNP);
+             case IDC_MBWINDOWS:
+             case IDC_MBXTERM:
+               cfg.mouse_is_xterm = IsDlgButtonChecked(hwnd, IDC_MBXTERM);
+               break;
+             case IDC_CCSET:
+               {
+                   BOOL ok;
+                   int i;
+                   int n = GetDlgItemInt(hwnd, IDC_CCEDIT, &ok, FALSE);
+
+                   if (!ok)
+                       MessageBeep(0);
+                   else {
+                       for (i = 0; i < 256; i++)
+                           if (SendDlgItemMessage
+                               (hwnd, IDC_CCLIST, LB_GETSEL, i, 0)) {
+                               char str[100];
+                               cfg.wordness[i] = n;
+                               SendDlgItemMessage(hwnd, IDC_CCLIST,
+                                                  LB_DELETESTRING, i, 0);
+                               sprintf(str, "%d\t(0x%02X)\t%c\t%d", i, i,
+                                       (i >= 0x21 && i != 0x7F) ? i : ' ',
+                                       cfg.wordness[i]);
+                               SendDlgItemMessage(hwnd, IDC_CCLIST,
+                                                  LB_INSERTSTRING, i,
+                                                  (LPARAM) str);
+                           }
+                   }
                }
-           }
-           break;
-         case IDC_PALETTE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.try_palette = IsDlgButtonChecked (hwnd, IDC_PALETTE);
-           break;
-         case IDC_COLOURLIST:
-           if (HIWORD(wParam) == LBN_DBLCLK ||
-               HIWORD(wParam) == LBN_SELCHANGE) {
-               int i = SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_GETCURSEL,
-                                           0, 0);
-               if (!cfg.bold_colour)
-                   i = (i < 3 ? i*2 : i == 3 ? 5 : i*2-2);
-               SetDlgItemInt (hwnd, IDC_RVALUE, cfg.colours[i][0], FALSE);
-               SetDlgItemInt (hwnd, IDC_GVALUE, cfg.colours[i][1], FALSE);
-               SetDlgItemInt (hwnd, IDC_BVALUE, cfg.colours[i][2], FALSE);
-           }
-           break;
-         case IDC_CHANGE:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               static CHOOSECOLOR cc;
-               static DWORD custom[16] = {0};   /* zero initialisers */
-               int i = SendDlgItemMessage (hwnd, IDC_COLOURLIST, LB_GETCURSEL,
-                                           0, 0);
-               if (!cfg.bold_colour)
-                   i = (i < 3 ? i*2 : i == 3 ? 5 : i*2-2);
-               cc.lStructSize = sizeof(cc);
-               cc.hwndOwner = hwnd;
-               cc.hInstance = (HWND)hinst;
-               cc.lpCustColors = custom;
-               cc.rgbResult = RGB (cfg.colours[i][0], cfg.colours[i][1],
-                                   cfg.colours[i][2]);
-               cc.Flags = CC_FULLOPEN | CC_RGBINIT;
-               if (ChooseColor(&cc)) {
-                   cfg.colours[i][0] =
-                       (unsigned char) (cc.rgbResult & 0xFF);
-                   cfg.colours[i][1] =
-                       (unsigned char) (cc.rgbResult >> 8) & 0xFF;
-                   cfg.colours[i][2] =
-                       (unsigned char) (cc.rgbResult >> 16) & 0xFF;
-                   SetDlgItemInt (hwnd, IDC_RVALUE, cfg.colours[i][0],
-                                  FALSE);
-                   SetDlgItemInt (hwnd, IDC_GVALUE, cfg.colours[i][1],
-                                  FALSE);
-                   SetDlgItemInt (hwnd, IDC_BVALUE, cfg.colours[i][2],
-                                  FALSE);
+               break;
+             case IDC_BOLDCOLOUR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   int n, i;
+                   cfg.bold_colour =
+                       IsDlgButtonChecked(hwnd, IDC_BOLDCOLOUR);
+                   n =
+                       SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                                          LB_GETCOUNT, 0, 0);
+                   if (n != 12 + 10 * cfg.bold_colour) {
+                       for (i = n; i-- > 0;)
+                           SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                                              LB_DELETESTRING, i, 0);
+                       for (i = 0; i < 22; i++)
+                           if (cfg.bold_colour || permcolour[i])
+                               SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                                                  LB_ADDSTRING, 0,
+                                                  (LPARAM) colours[i]);
+                   }
                }
+               break;
+             case IDC_PALETTE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.try_palette =
+                       IsDlgButtonChecked(hwnd, IDC_PALETTE);
+               break;
+             case IDC_COLOURLIST:
+               if (HIWORD(wParam) == LBN_DBLCLK ||
+                   HIWORD(wParam) == LBN_SELCHANGE) {
+                   int i = SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                                              LB_GETCURSEL,
+                                              0, 0);
+                   if (!cfg.bold_colour)
+                       i = (i < 3 ? i * 2 : i == 3 ? 5 : i * 2 - 2);
+                   SetDlgItemInt(hwnd, IDC_RVALUE, cfg.colours[i][0],
+                                 FALSE);
+                   SetDlgItemInt(hwnd, IDC_GVALUE, cfg.colours[i][1],
+                                 FALSE);
+                   SetDlgItemInt(hwnd, IDC_BVALUE, cfg.colours[i][2],
+                                 FALSE);
+               }
+               break;
+             case IDC_CHANGE:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   static CHOOSECOLOR cc;
+                   static DWORD custom[16] = { 0 };    /* zero initialisers */
+                   int i = SendDlgItemMessage(hwnd, IDC_COLOURLIST,
+                                              LB_GETCURSEL,
+                                              0, 0);
+                   if (!cfg.bold_colour)
+                       i = (i < 3 ? i * 2 : i == 3 ? 5 : i * 2 - 2);
+                   cc.lStructSize = sizeof(cc);
+                   cc.hwndOwner = hwnd;
+                   cc.hInstance = (HWND) hinst;
+                   cc.lpCustColors = custom;
+                   cc.rgbResult =
+                       RGB(cfg.colours[i][0], cfg.colours[i][1],
+                           cfg.colours[i][2]);
+                   cc.Flags = CC_FULLOPEN | CC_RGBINIT;
+                   if (ChooseColor(&cc)) {
+                       cfg.colours[i][0] =
+                           (unsigned char) (cc.rgbResult & 0xFF);
+                       cfg.colours[i][1] =
+                           (unsigned char) (cc.rgbResult >> 8) & 0xFF;
+                       cfg.colours[i][2] =
+                           (unsigned char) (cc.rgbResult >> 16) & 0xFF;
+                       SetDlgItemInt(hwnd, IDC_RVALUE, cfg.colours[i][0],
+                                     FALSE);
+                       SetDlgItemInt(hwnd, IDC_GVALUE, cfg.colours[i][1],
+                                     FALSE);
+                       SetDlgItemInt(hwnd, IDC_BVALUE, cfg.colours[i][2],
+                                     FALSE);
+                   }
+               }
+               break;
+             case IDC_NOXLAT:
+             case IDC_KOI8WIN1251:
+             case IDC_88592WIN1250:
+             case IDC_88592CP852:
+               cfg.xlat_enablekoiwin =
+                   IsDlgButtonChecked(hwnd, IDC_KOI8WIN1251);
+               cfg.xlat_88592w1250 =
+                   IsDlgButtonChecked(hwnd, IDC_88592WIN1250);
+               cfg.xlat_88592cp852 =
+                   IsDlgButtonChecked(hwnd, IDC_88592CP852);
+               break;
+             case IDC_CAPSLOCKCYR:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED) {
+                   cfg.xlat_capslockcyr =
+                       IsDlgButtonChecked(hwnd, IDC_CAPSLOCKCYR);
+               }
+               break;
+             case IDC_VTXWINDOWS:
+             case IDC_VTOEMANSI:
+             case IDC_VTOEMONLY:
+             case IDC_VTPOORMAN:
+               cfg.vtmode =
+                   (IsDlgButtonChecked(hwnd, IDC_VTXWINDOWS) ? VT_XWINDOWS
+                    : IsDlgButtonChecked(hwnd,
+                                         IDC_VTOEMANSI) ? VT_OEMANSI :
+                    IsDlgButtonChecked(hwnd,
+                                       IDC_VTOEMONLY) ? VT_OEMONLY :
+                    VT_POORMAN);
+               break;
+             case IDC_X11_FORWARD:
+               if (HIWORD(wParam) == BN_CLICKED ||
+                   HIWORD(wParam) == BN_DOUBLECLICKED)
+                       cfg.x11_forward =
+                       IsDlgButtonChecked(hwnd, IDC_X11_FORWARD);
+               break;
+             case IDC_X11_DISPLAY:
+               if (HIWORD(wParam) == EN_CHANGE)
+                   GetDlgItemText(hwnd, IDC_X11_DISPLAY, cfg.x11_display,
+                                  sizeof(cfg.x11_display) - 1);
+               break;
            }
-           break;
-         case IDC_NOXLAT:
-         case IDC_KOI8WIN1251:
-         case IDC_88592WIN1250:
-         case IDC_88592CP852:
-           cfg.xlat_enablekoiwin =
-               IsDlgButtonChecked (hwnd, IDC_KOI8WIN1251);
-           cfg.xlat_88592w1250 =
-               IsDlgButtonChecked (hwnd, IDC_88592WIN1250);
-           cfg.xlat_88592cp852 =
-               IsDlgButtonChecked (hwnd, IDC_88592CP852);
-           break;
-         case IDC_CAPSLOCKCYR:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED) {
-               cfg.xlat_capslockcyr =
-                   IsDlgButtonChecked (hwnd, IDC_CAPSLOCKCYR);
-           }
-           break;
-         case IDC_VTXWINDOWS:
-         case IDC_VTOEMANSI:
-         case IDC_VTOEMONLY:
-         case IDC_VTPOORMAN:
-           cfg.vtmode =
-               (IsDlgButtonChecked (hwnd, IDC_VTXWINDOWS) ? VT_XWINDOWS :
-                IsDlgButtonChecked (hwnd, IDC_VTOEMANSI) ? VT_OEMANSI :
-                IsDlgButtonChecked (hwnd, IDC_VTOEMONLY) ? VT_OEMONLY :
-                VT_POORMAN);
-           break;
-         case IDC_X11_FORWARD:
-           if (HIWORD(wParam) == BN_CLICKED ||
-               HIWORD(wParam) == BN_DOUBLECLICKED)
-               cfg.x11_forward = IsDlgButtonChecked (hwnd, IDC_X11_FORWARD);
-           break;
-          case IDC_X11_DISPLAY:
-            if (HIWORD(wParam) == EN_CHANGE)
-                GetDlgItemText (hwnd, IDC_X11_DISPLAY, cfg.x11_display,
-                                sizeof(cfg.x11_display)-1);
-            break;
-       }
        return 0;
       case WM_CLOSE:
-       EndDialog (hwnd, 0);
+       EndDialog(hwnd, 0);
        return 0;
 
        /* Grrr Explorer will maximize Dialogs! */
       case WM_SIZE:
        if (wParam == SIZE_MAXIMIZED)
-          force_normal(hwnd);
+           force_normal(hwnd);
        return 0;
     }
     return 0;
 }
 
-static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
-                                WPARAM wParam, LPARAM lParam) {
+static int CALLBACK MainDlgProc(HWND hwnd, UINT msg,
+                               WPARAM wParam, LPARAM lParam)
+{
     if (msg == WM_COMMAND && LOWORD(wParam) == IDOK) {
     }
     if (msg == WM_COMMAND && LOWORD(wParam) == IDCX_ABOUT) {
@@ -2215,157 +2320,168 @@ static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
        DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX),
                  GetParent(hwnd), AboutProc);
        EnableWindow(hwnd, 1);
-        SetActiveWindow(hwnd);
+       SetActiveWindow(hwnd);
     }
-    return GenericMainDlgProc (hwnd, msg, wParam, lParam, 0);
+    return GenericMainDlgProc(hwnd, msg, wParam, lParam, 0);
 }
 
-static int CALLBACK ReconfDlgProc (HWND hwnd, UINT msg,
-                                  WPARAM wParam, LPARAM lParam) {
-    return GenericMainDlgProc (hwnd, msg, wParam, lParam, 1);
+static int CALLBACK ReconfDlgProc(HWND hwnd, UINT msg,
+                                 WPARAM wParam, LPARAM lParam)
+{
+    return GenericMainDlgProc(hwnd, msg, wParam, lParam, 1);
 }
 
-void defuse_showwindow(void) {
+void defuse_showwindow(void)
+{
     /*
      * Work around the fact that the app's first call to ShowWindow
      * will ignore the default in favour of the shell-provided
      * setting.
      */
     {
-        HWND hwnd;
-        hwnd = CreateDialog (hinst, MAKEINTRESOURCE(IDD_ABOUTBOX),
-                             NULL, NullDlgProc);
-        ShowWindow(hwnd, SW_HIDE);
-        DestroyWindow(hwnd);
+       HWND hwnd;
+       hwnd = CreateDialog(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX),
+                           NULL, NullDlgProc);
+       ShowWindow(hwnd, SW_HIDE);
+       DestroyWindow(hwnd);
     }
 }
 
-int do_config (void) {
+int do_config(void)
+{
     int ret;
 
     get_sesslist(TRUE);
     savedsession[0] = '\0';
-    ret = DialogBox (hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL, MainDlgProc);
+    ret =
+       DialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL, MainDlgProc);
     get_sesslist(FALSE);
 
     return ret;
 }
 
-int do_reconfig (HWND hwnd) {
+int do_reconfig(HWND hwnd)
+{
     Config backup_cfg;
     int ret;
 
     backup_cfg = cfg;                 /* structure copy */
-    ret = DialogBox (hinst, MAKEINTRESOURCE(IDD_RECONF), hwnd, ReconfDlgProc);
+    ret =
+       DialogBox(hinst, MAKEINTRESOURCE(IDD_RECONF), hwnd, ReconfDlgProc);
     if (!ret)
        cfg = backup_cfg;              /* structure copy */
 
     return ret;
 }
 
-void logevent (char *string) {
+void logevent(char *string)
+{
     char timebuf[40];
     time_t t;
 
     if (nevents >= negsize) {
        negsize += 64;
-       events = srealloc (events, negsize * sizeof(*events));
+       events = srealloc(events, negsize * sizeof(*events));
     }
 
     time(&t);
-    strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\t", localtime(&t));
+    strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\t",
+            localtime(&t));
 
-    events[nevents] = smalloc(strlen(timebuf)+strlen(string)+1);
+    events[nevents] = smalloc(strlen(timebuf) + strlen(string) + 1);
     strcpy(events[nevents], timebuf);
     strcat(events[nevents], string);
     if (logbox) {
-        int count;
-       SendDlgItemMessage (logbox, IDN_LIST, LB_ADDSTRING,
-                           0, (LPARAM)events[nevents]);
-       count = SendDlgItemMessage (logbox, IDN_LIST, LB_GETCOUNT, 0, 0);
-       SendDlgItemMessage (logbox, IDN_LIST, LB_SETTOPINDEX, count-1, 0);
+       int count;
+       SendDlgItemMessage(logbox, IDN_LIST, LB_ADDSTRING,
+                          0, (LPARAM) events[nevents]);
+       count = SendDlgItemMessage(logbox, IDN_LIST, LB_GETCOUNT, 0, 0);
+       SendDlgItemMessage(logbox, IDN_LIST, LB_SETTOPINDEX, count - 1, 0);
     }
     nevents++;
 }
 
-void showeventlog (HWND hwnd) {
+void showeventlog(HWND hwnd)
+{
     if (!logbox) {
-       logbox = CreateDialog (hinst, MAKEINTRESOURCE(IDD_LOGBOX),
-                              hwnd, LogProc);
-       ShowWindow (logbox, SW_SHOWNORMAL);
+       logbox = CreateDialog(hinst, MAKEINTRESOURCE(IDD_LOGBOX),
+                             hwnd, LogProc);
+       ShowWindow(logbox, SW_SHOWNORMAL);
     }
     SetActiveWindow(logbox);
 }
 
-void showabout (HWND hwnd) {
-    DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX),hwnd, AboutProc);
+void showabout(HWND hwnd)
+{
+    DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, AboutProc);
 }
 
 void verify_ssh_host_key(char *host, int port, char *keytype,
-                         char *keystr, char *fingerprint) {
+                        char *keystr, char *fingerprint)
+{
     int ret;
 
     static const char absentmsg[] =
-        "The server's host key is not cached in the registry. You\n"
-        "have no guarantee that the server is the computer you\n"
-        "think it is.\n"
-        "The server's key fingerprint is:\n"
-        "%s\n"
-        "If you trust this host, hit Yes to add the key to\n"
-        "PuTTY's cache and carry on connecting.\n"
-        "If you do not trust this host, hit No to abandon the\n"
-        "connection.\n";
+       "The server's host key is not cached in the registry. You\n"
+       "have no guarantee that the server is the computer you\n"
+       "think it is.\n"
+       "The server's key fingerprint is:\n"
+       "%s\n"
+       "If you trust this host, hit Yes to add the key to\n"
+       "PuTTY's cache and carry on connecting.\n"
+       "If you do not trust this host, hit No to abandon the\n"
+       "connection.\n";
 
     static const char wrongmsg[] =
-        "WARNING - POTENTIAL SECURITY BREACH!\n"
-        "\n"
-        "The server's host key does not match the one PuTTY has\n"
-        "cached in the registry. This means that either the\n"
-        "server administrator has changed the host key, or you\n"
-        "have actually connected to another computer pretending\n"
-        "to be the server.\n"
-        "The new key fingerprint is:\n"
-        "%s\n"
-        "If you were expecting this change and trust the new key,\n"
-        "hit Yes to update PuTTY's cache and continue connecting.\n"
-        "If you want to carry on connecting but without updating\n"
-        "the cache, hit No.\n"
-        "If you want to abandon the connection completely, hit\n"
-        "Cancel. Hitting Cancel is the ONLY guaranteed safe\n"
-        "choice.\n";
+       "WARNING - POTENTIAL SECURITY BREACH!\n"
+       "\n"
+       "The server's host key does not match the one PuTTY has\n"
+       "cached in the registry. This means that either the\n"
+       "server administrator has changed the host key, or you\n"
+       "have actually connected to another computer pretending\n"
+       "to be the server.\n"
+       "The new key fingerprint is:\n"
+       "%s\n"
+       "If you were expecting this change and trust the new key,\n"
+       "hit Yes to update PuTTY's cache and continue connecting.\n"
+       "If you want to carry on connecting but without updating\n"
+       "the cache, hit No.\n"
+       "If you want to abandon the connection completely, hit\n"
+       "Cancel. Hitting Cancel is the ONLY guaranteed safe\n" "choice.\n";
 
     static const char mbtitle[] = "PuTTY Security Alert";
 
-    
-    char message[160+                  /* sensible fingerprint max size */
-                 (sizeof(absentmsg) > sizeof(wrongmsg) ?
-                  sizeof(absentmsg) : sizeof(wrongmsg))];
+
+    char message[160 +
+                /* sensible fingerprint max size */
+       (sizeof(absentmsg) > sizeof(wrongmsg) ?
+        sizeof(absentmsg) : sizeof(wrongmsg))];
 
     /*
      * Verify the key against the registry.
      */
     ret = verify_host_key(host, port, keytype, keystr);
 
-    if (ret == 0)                      /* success - key matched OK */
-        return;
-    if (ret == 2) {                    /* key was different */
-        int mbret;
-        sprintf(message, wrongmsg, fingerprint);
-        mbret = MessageBox(NULL, message, mbtitle,
-                           MB_ICONWARNING | MB_YESNOCANCEL);
-        if (mbret == IDYES)
-            store_host_key(host, port, keytype, keystr);
-        if (mbret == IDCANCEL)
-            exit(0);
+    if (ret == 0)                     /* success - key matched OK */
+       return;
+    if (ret == 2) {                   /* key was different */
+       int mbret;
+       sprintf(message, wrongmsg, fingerprint);
+       mbret = MessageBox(NULL, message, mbtitle,
+                          MB_ICONWARNING | MB_YESNOCANCEL);
+       if (mbret == IDYES)
+           store_host_key(host, port, keytype, keystr);
+       if (mbret == IDCANCEL)
+           exit(0);
     }
-    if (ret == 1) {                    /* key was absent */
-        int mbret;
-        sprintf(message, absentmsg, fingerprint);
-        mbret = MessageBox(NULL, message, mbtitle,
-                           MB_ICONWARNING | MB_YESNO);
-        if (mbret == IDNO)
-            exit(0);
-        store_host_key(host, port, keytype, keystr);
+    if (ret == 1) {                   /* key was absent */
+       int mbret;
+       sprintf(message, absentmsg, fingerprint);
+       mbret = MessageBox(NULL, message, mbtitle,
+                          MB_ICONWARNING | MB_YESNO);
+       if (mbret == IDNO)
+           exit(0);
+       store_host_key(host, port, keytype, keystr);
     }
 }
 
@@ -2373,7 +2489,8 @@ void verify_ssh_host_key(char *host, int port, char *keytype,
  * Ask whether to wipe a session log file before writing to it.
  * Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
  */
-int askappend(char *filename) {
+int askappend(char *filename)
+{
     static const char mbtitle[] = "PuTTY Log to File";
     static const char msgtemplate[] =
        "The session log file \"%.*s\" already exists.\n"
@@ -2384,13 +2501,13 @@ int askappend(char *filename) {
        "or Cancel to disable logging.";
     char message[sizeof(msgtemplate) + FILENAME_MAX];
     int mbret;
-    if ( cfg.logxfovr != LGXF_ASK ) {
-       return ( (cfg.logxfovr==LGXF_OVR) ? 2 : 1);
+    if (cfg.logxfovr != LGXF_ASK) {
+       return ((cfg.logxfovr == LGXF_OVR) ? 2 : 1);
     }
     sprintf(message, msgtemplate, FILENAME_MAX, filename);
 
     mbret = MessageBox(NULL, message, mbtitle,
-                       MB_ICONQUESTION | MB_YESNOCANCEL);
+                      MB_ICONQUESTION | MB_YESNOCANCEL);
     if (mbret == IDYES)
        return 2;
     else if (mbret == IDNO)
index 6f3eb49..063f0db 100644 (file)
--- a/window.c
+++ b/window.c
@@ -14,7 +14,7 @@
 #include <ctype.h>
 #include <time.h>
 
-#define PUTTY_DO_GLOBALS                      /* actually _define_ globals */
+#define PUTTY_DO_GLOBALS              /* actually _define_ globals */
 #include "putty.h"
 #include "winstuff.h"
 #include "storage.h"
@@ -43,9 +43,9 @@
 #define IDM_SAVEDSESS 0x0150
 #define IDM_COPYALL   0x0160
 
-#define IDM_SESSLGP   0x0250  /* log type printable */
-#define IDM_SESSLGA   0x0260  /* log type all chars */
-#define IDM_SESSLGE   0x0270  /* log end */
+#define IDM_SESSLGP   0x0250          /* log type printable */
+#define IDM_SESSLGA   0x0260          /* log type all chars */
+#define IDM_SESSLGE   0x0270          /* log end */
 #define IDM_SAVED_MIN 0x1000
 #define IDM_SAVED_MAX 0x2000
 
@@ -57,8 +57,9 @@
 #define VK_PROCESSKEY 0xE5
 #endif
 
-static LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
-static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, unsigned char *output);
+static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
+static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
+                       unsigned char *output);
 static void cfgtopalette(void);
 static void init_palette(void);
 static void init_fonts(int);
@@ -112,9 +113,12 @@ static char *window_name, *icon_name;
 static int compose_state = 0;
 
 /* Dummy routine, only required in plink. */
-void ldisc_update(int echo, int edit) {}
+void ldisc_update(int echo, int edit)
+{
+}
 
-int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
+int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
+{
     static char appname[] = "PuTTY";
     WORD winsock_ver;
     WSADATA wsadata;
@@ -159,7 +163,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
        do_defaults(NULL, &cfg);
 
        p = cmdline;
-       while (*p && isspace(*p)) p++;
+       while (*p && isspace(*p))
+           p++;
 
        /*
         * Process command line options first. Yes, this can be
@@ -171,36 +176,34 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
            p++;
            if (q == p + 3 &&
                tolower(p[0]) == 's' &&
-               tolower(p[1]) == 's' &&
-               tolower(p[2]) == 'h') {
+               tolower(p[1]) == 's' && tolower(p[2]) == 'h') {
                default_protocol = cfg.protocol = PROT_SSH;
                default_port = cfg.port = 22;
            } else if (q == p + 7 &&
-               tolower(p[0]) == 'c' &&
-               tolower(p[1]) == 'l' &&
-               tolower(p[2]) == 'e' &&
-               tolower(p[3]) == 'a' &&
-               tolower(p[4]) == 'n' &&
-               tolower(p[5]) == 'u' &&
-               tolower(p[6]) == 'p') {
-                /*
-                 * `putty -cleanup'. Remove all registry entries
-                 * associated with PuTTY, and also find and delete
-                 * the random seed file.
-                 */
-                if (MessageBox(NULL,
-                               "This procedure will remove ALL Registry\n"
-                               "entries associated with PuTTY, and will\n"
-                               "also remove the PuTTY random seed file.\n"
-                               "\n"
-                               "THIS PROCESS WILL DESTROY YOUR SAVED\n"
-                               "SESSIONS. Are you really sure you want\n"
-                               "to continue?",
-                               "PuTTY Warning",
-                               MB_YESNO | MB_ICONWARNING) == IDYES) {
-                    cleanup_all();
-                }
-                exit(0);
+                      tolower(p[0]) == 'c' &&
+                      tolower(p[1]) == 'l' &&
+                      tolower(p[2]) == 'e' &&
+                      tolower(p[3]) == 'a' &&
+                      tolower(p[4]) == 'n' &&
+                      tolower(p[5]) == 'u' && tolower(p[6]) == 'p') {
+               /*
+                * `putty -cleanup'. Remove all registry entries
+                * associated with PuTTY, and also find and delete
+                * the random seed file.
+                */
+               if (MessageBox(NULL,
+                              "This procedure will remove ALL Registry\n"
+                              "entries associated with PuTTY, and will\n"
+                              "also remove the PuTTY random seed file.\n"
+                              "\n"
+                              "THIS PROCESS WILL DESTROY YOUR SAVED\n"
+                              "SESSIONS. Are you really sure you want\n"
+                              "to continue?",
+                              "PuTTY Warning",
+                              MB_YESNO | MB_ICONWARNING) == IDYES) {
+                   cleanup_all();
+               }
+               exit(0);
            }
            p = q + strspn(q, " \t");
        }
@@ -210,10 +213,10 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
         */
        if (*p == '@') {
            int i = strlen(p);
-           while (i > 1 && isspace(p[i-1]))
+           while (i > 1 && isspace(p[i - 1]))
                i--;
            p[i] = '\0';
-           do_defaults (p+1, &cfg);
+           do_defaults(p + 1, &cfg);
            if (!*cfg.host && !do_config()) {
                WSACleanup();
                return 0;
@@ -227,7 +230,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
             */
            HANDLE filemap;
            Config *cp;
-           if (sscanf(p+1, "%p", &filemap) == 1 &&
+           if (sscanf(p + 1, "%p", &filemap) == 1 &&
                (cp = MapViewOfFile(filemap, FILE_MAP_READ,
                                    0, 0, sizeof(Config))) != NULL) {
                cfg = *cp;
@@ -239,41 +242,44 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
            }
        } else if (*p) {
            char *q = p;
-            /*
-             * If the hostname starts with "telnet:", set the
-             * protocol to Telnet and process the string as a
-             * Telnet URL.
-             */
-            if (!strncmp(q, "telnet:", 7)) {
-                char c;
-
-                q += 7;
+           /*
+            * If the hostname starts with "telnet:", set the
+            * protocol to Telnet and process the string as a
+            * Telnet URL.
+            */
+           if (!strncmp(q, "telnet:", 7)) {
+               char c;
+
+               q += 7;
                if (q[0] == '/' && q[1] == '/')
                    q += 2;
-                cfg.protocol = PROT_TELNET;
-                p = q;
-                while (*p && *p != ':' && *p != '/') p++;
-                c = *p;
-                if (*p)
-                    *p++ = '\0';
-                if (c == ':')
-                    cfg.port = atoi(p);
-                else
-                    cfg.port = -1;
-                strncpy (cfg.host, q, sizeof(cfg.host)-1);
-                cfg.host[sizeof(cfg.host)-1] = '\0';
-            } else {
-                while (*p && !isspace(*p)) p++;
-                if (*p)
-                    *p++ = '\0';
-                strncpy (cfg.host, q, sizeof(cfg.host)-1);
-                cfg.host[sizeof(cfg.host)-1] = '\0';
-                while (*p && isspace(*p)) p++;
-                if (*p)
-                    cfg.port = atoi(p);
-                else
-                    cfg.port = -1;
-            }
+               cfg.protocol = PROT_TELNET;
+               p = q;
+               while (*p && *p != ':' && *p != '/')
+                   p++;
+               c = *p;
+               if (*p)
+                   *p++ = '\0';
+               if (c == ':')
+                   cfg.port = atoi(p);
+               else
+                   cfg.port = -1;
+               strncpy(cfg.host, q, sizeof(cfg.host) - 1);
+               cfg.host[sizeof(cfg.host) - 1] = '\0';
+           } else {
+               while (*p && !isspace(*p))
+                   p++;
+               if (*p)
+                   *p++ = '\0';
+               strncpy(cfg.host, q, sizeof(cfg.host) - 1);
+               cfg.host[sizeof(cfg.host) - 1] = '\0';
+               while (*p && isspace(*p))
+                   p++;
+               if (*p)
+                   cfg.port = atoi(p);
+               else
+                   cfg.port = -1;
+           }
        } else {
            if (!do_config()) {
                WSACleanup();
@@ -286,11 +292,11 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
            char *atsign = strchr(cfg.host, '@');
            /* Make sure we're not overflowing the user field */
            if (atsign) {
-               if (atsign-cfg.host < sizeof cfg.username) {
-                   strncpy (cfg.username, cfg.host, atsign-cfg.host);
-                   cfg.username[atsign-cfg.host] = '\0';
+               if (atsign - cfg.host < sizeof cfg.username) {
+                   strncpy(cfg.username, cfg.host, atsign - cfg.host);
+                   cfg.username[atsign - cfg.host] = '\0';
                }
-               memmove(cfg.host, atsign+1, 1+strlen(atsign+1));
+               memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
            }
        }
     }
@@ -300,43 +306,42 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      * separate file to enable an ssh-free variant.
      */
     {
-        int i;
-        back = NULL;
-        for (i = 0; backends[i].backend != NULL; i++)
-            if (backends[i].protocol == cfg.protocol) {
-                back = backends[i].backend;
-                break;
-            }
-        if (back == NULL) {
-            MessageBox(NULL, "Unsupported protocol number found",
-                       "PuTTY Internal Error", MB_OK | MB_ICONEXCLAMATION);
-            WSACleanup();
-            return 1;
-        }
+       int i;
+       back = NULL;
+       for (i = 0; backends[i].backend != NULL; i++)
+           if (backends[i].protocol == cfg.protocol) {
+               back = backends[i].backend;
+               break;
+           }
+       if (back == NULL) {
+           MessageBox(NULL, "Unsupported protocol number found",
+                      "PuTTY Internal Error", MB_OK | MB_ICONEXCLAMATION);
+           WSACleanup();
+           return 1;
+       }
     }
 
     /* Check for invalid Port number (i.e. zero) */
     if (cfg.port == 0) {
-        MessageBox(NULL, "Invalid Port Number",
-                  "PuTTY Internal Error", MB_OK |MB_ICONEXCLAMATION);
-        WSACleanup();
-        return 1;
+       MessageBox(NULL, "Invalid Port Number",
+                  "PuTTY Internal Error", MB_OK | MB_ICONEXCLAMATION);
+       WSACleanup();
+       return 1;
     }
 
     if (!prev) {
-       wndclass.style         = 0;
-       wndclass.lpfnWndProc   = WndProc;
-       wndclass.cbClsExtra    = 0;
-       wndclass.cbWndExtra    = 0;
-       wndclass.hInstance     = inst;
-       wndclass.hIcon         = LoadIcon (inst,
-                                          MAKEINTRESOURCE(IDI_MAINICON));
-       wndclass.hCursor       = LoadCursor (NULL, IDC_IBEAM);
-       wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
-       wndclass.lpszMenuName  = NULL;
+       wndclass.style = 0;
+       wndclass.lpfnWndProc = WndProc;
+       wndclass.cbClsExtra = 0;
+       wndclass.cbWndExtra = 0;
+       wndclass.hInstance = inst;
+       wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
+       wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
+       wndclass.hbrBackground = GetStockObject(BLACK_BRUSH);
+       wndclass.lpszMenuName = NULL;
        wndclass.lpszClassName = appname;
 
-       RegisterClass (&wndclass);
+       RegisterClass(&wndclass);
     }
 
     hwnd = NULL;
@@ -352,18 +357,18 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      * do want the font width/height guesses to correspond to a
      * large font rather than a small one...
      */
-    
+
     font_width = 10;
     font_height = 20;
     extra_width = 25;
     extra_height = 28;
-    term_size (cfg.height, cfg.width, cfg.savelines);
+    term_size(cfg.height, cfg.width, cfg.savelines);
     guess_width = extra_width + font_width * cols;
     guess_height = extra_height + font_height * rows;
     {
        RECT r;
        HWND w = GetDesktopWindow();
-       GetWindowRect (w, &r);
+       GetWindowRect(w, &r);
        if (guess_width > r.right - r.left)
            guess_width = r.right - r.left;
        if (guess_height > r.bottom - r.top)
@@ -371,17 +376,21 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
     }
 
     {
-       int winmode = WS_OVERLAPPEDWINDOW|WS_VSCROLL;
-        int exwinmode = 0;
-       if (!cfg.scrollbar)  winmode &= ~(WS_VSCROLL);
-       if (cfg.locksize)    winmode &= ~(WS_THICKFRAME|WS_MAXIMIZEBOX);
-        if (cfg.alwaysontop) exwinmode |= WS_EX_TOPMOST;
-       if (cfg.sunken_edge) exwinmode |= WS_EX_CLIENTEDGE;
-        hwnd = CreateWindowEx (exwinmode, appname, appname,
-                              winmode, CW_USEDEFAULT, CW_USEDEFAULT,
-                              guess_width, guess_height,
-                              NULL, NULL, inst, NULL);
-     }
+       int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
+       int exwinmode = 0;
+       if (!cfg.scrollbar)
+           winmode &= ~(WS_VSCROLL);
+       if (cfg.locksize)
+           winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
+       if (cfg.alwaysontop)
+           exwinmode |= WS_EX_TOPMOST;
+       if (cfg.sunken_edge)
+           exwinmode |= WS_EX_CLIENTEDGE;
+       hwnd = CreateWindowEx(exwinmode, appname, appname,
+                             winmode, CW_USEDEFAULT, CW_USEDEFAULT,
+                             guess_width, guess_height,
+                             NULL, NULL, inst, NULL);
+    }
 
     /*
      * Initialise the fonts, simultaneously correcting the guesses
@@ -396,8 +405,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      */
     {
        RECT cr, wr;
-       GetWindowRect (hwnd, &wr);
-       GetClientRect (hwnd, &cr);
+       GetWindowRect(hwnd, &wr);
+       GetClientRect(hwnd, &cr);
        extra_width = wr.right - wr.left - cr.right + cr.left;
        extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
     }
@@ -408,20 +417,20 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      */
     guess_width = extra_width + font_width * cols;
     guess_height = extra_height + font_height * rows;
-    SendMessage (hwnd, WM_IGNORE_SIZE, 0, 0);
-    SetWindowPos (hwnd, NULL, 0, 0, guess_width, guess_height,
-                 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
+    SendMessage(hwnd, WM_IGNORE_SIZE, 0, 0);
+    SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
+                SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
 
     /*
      * Set up a caret bitmap, with no content.
      */
     {
-        char *bits;
-        int size = (font_width+15)/16 * 2 * font_height; 
-        bits = smalloc(size);
-        memset(bits, 0, size);
-        caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
-        sfree(bits);
+       char *bits;
+       int size = (font_width + 15) / 16 * 2 * font_height;
+       bits = smalloc(size);
+       memset(bits, 0, size);
+       caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
+       sfree(bits);
     }
     CreateCaret(hwnd, caretbm, font_width, font_height);
 
@@ -434,10 +443,10 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
        si.cbSize = sizeof(si);
        si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
        si.nMin = 0;
-       si.nMax = rows-1;
+       si.nMax = rows - 1;
        si.nPage = rows;
        si.nPos = 0;
-       SetScrollInfo (hwnd, SB_VERT, &si, FALSE);
+       SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
     }
 
     /*
@@ -448,23 +457,22 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
        char msg[1024], *title;
        char *realhost;
 
-       error = back->init (cfg.host, cfg.port, &realhost);
+       error = back->init(cfg.host, cfg.port, &realhost);
        if (error) {
            sprintf(msg, "Unable to open connection to\n"
-                   "%.800s\n"
-                   "%s", cfg.host, error);
+                   "%.800s\n" "%s", cfg.host, error);
            MessageBox(NULL, msg, "PuTTY Error", MB_ICONERROR | MB_OK);
            return 0;
        }
        window_name = icon_name = NULL;
-        if (*cfg.wintitle) {
-            title = cfg.wintitle;
-        } else {
-            sprintf(msg, "%s - PuTTY", realhost);
-            title = msg;
-        }
-       set_title (title);
-       set_icon (title);
+       if (*cfg.wintitle) {
+           title = cfg.wintitle;
+       } else {
+           sprintf(msg, "%s - PuTTY", realhost);
+           title = msg;
+       }
+       set_title(title);
+       set_icon(title);
     }
 
     session_closed = FALSE;
@@ -486,54 +494,56 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      * Set up the session-control options on the system menu.
      */
     {
-       HMENU m = GetSystemMenu (hwnd, FALSE);
-       HMENU p,s;
+       HMENU m = GetSystemMenu(hwnd, FALSE);
+       HMENU p, s;
        int i;
 
-       AppendMenu (m, MF_SEPARATOR, 0, 0);
+       AppendMenu(m, MF_SEPARATOR, 0, 0);
        if (cfg.protocol == PROT_TELNET) {
            p = CreateMenu();
-           AppendMenu (p, MF_ENABLED, IDM_TEL_AYT, "Are You There");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_BRK, "Break");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_SYNCH, "Synch");
-           AppendMenu (p, MF_SEPARATOR, 0, 0);
-           AppendMenu (p, MF_ENABLED, IDM_TEL_EC, "Erase Character");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_EL, "Erase Line");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_GA, "Go Ahead");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_NOP, "No Operation");
-           AppendMenu (p, MF_SEPARATOR, 0, 0);
-           AppendMenu (p, MF_ENABLED, IDM_TEL_ABORT, "Abort Process");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_AO, "Abort Output");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_IP, "Interrupt Process");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_SUSP, "Suspend Process");
-           AppendMenu (p, MF_SEPARATOR, 0, 0);
-           AppendMenu (p, MF_ENABLED, IDM_TEL_EOR, "End Of Record");
-           AppendMenu (p, MF_ENABLED, IDM_TEL_EOF, "End Of File");
-           AppendMenu (m, MF_POPUP | MF_ENABLED, (UINT) p, "Telnet Command");
-           AppendMenu (m, MF_SEPARATOR, 0, 0);
-       }
-       AppendMenu (m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
-       AppendMenu (m, MF_SEPARATOR, 0, 0);
-       AppendMenu (m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
-       AppendMenu (m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_AYT, "Are You There");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_BRK, "Break");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_SYNCH, "Synch");
+           AppendMenu(p, MF_SEPARATOR, 0, 0);
+           AppendMenu(p, MF_ENABLED, IDM_TEL_EC, "Erase Character");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_EL, "Erase Line");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_GA, "Go Ahead");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_NOP, "No Operation");
+           AppendMenu(p, MF_SEPARATOR, 0, 0);
+           AppendMenu(p, MF_ENABLED, IDM_TEL_ABORT, "Abort Process");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_AO, "Abort Output");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_IP, "Interrupt Process");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_SUSP, "Suspend Process");
+           AppendMenu(p, MF_SEPARATOR, 0, 0);
+           AppendMenu(p, MF_ENABLED, IDM_TEL_EOR, "End Of Record");
+           AppendMenu(p, MF_ENABLED, IDM_TEL_EOF, "End Of File");
+           AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) p,
+                      "Telnet Command");
+           AppendMenu(m, MF_SEPARATOR, 0, 0);
+       }
+       AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
+       AppendMenu(m, MF_SEPARATOR, 0, 0);
+       AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
+       AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
        s = CreateMenu();
        get_sesslist(TRUE);
-       for (i = 1 ; i < ((nsessions < 256) ? nsessions : 256) ; i++)
-         AppendMenu (s, MF_ENABLED, IDM_SAVED_MIN + (16 * i) , sessions[i]);
-       AppendMenu (m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
-       AppendMenu (m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
-       AppendMenu (m, MF_SEPARATOR, 0, 0);
-       AppendMenu (m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
-       AppendMenu (m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
-       AppendMenu (m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
-       AppendMenu (m, MF_SEPARATOR, 0, 0);
-       AppendMenu (m, MF_ENABLED, IDM_ABOUT, "&About PuTTY");
+       for (i = 1; i < ((nsessions < 256) ? nsessions : 256); i++)
+           AppendMenu(s, MF_ENABLED, IDM_SAVED_MIN + (16 * i),
+                      sessions[i]);
+       AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
+       AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
+       AppendMenu(m, MF_SEPARATOR, 0, 0);
+       AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
+       AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
+       AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
+       AppendMenu(m, MF_SEPARATOR, 0, 0);
+       AppendMenu(m, MF_ENABLED, IDM_ABOUT, "&About PuTTY");
     }
 
     /*
      * Finally show the window!
      */
-    ShowWindow (hwnd, show);
+    ShowWindow(hwnd, show);
 
     /*
      * Open the initial log file if there is one.
@@ -548,10 +558,9 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
     init_palette();
 
     has_focus = (GetForegroundWindow() == hwnd);
-    UpdateWindow (hwnd);
+    UpdateWindow(hwnd);
 
-    if (GetMessage (&msg, NULL, 0, 0) == 1)
-    {
+    if (GetMessage(&msg, NULL, 0, 0) == 1) {
        int timer_id = 0, long_timer = 0;
 
        while (msg.message != WM_QUIT) {
@@ -561,14 +570,14 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
             * Also call term_update() from the timer so that if the host
             * is sending data flat out we still do redraws.
             */
-           if(timer_id && long_timer) {
+           if (timer_id && long_timer) {
                KillTimer(hwnd, timer_id);
                long_timer = timer_id = 0;
            }
-           if(!timer_id)
+           if (!timer_id)
                timer_id = SetTimer(hwnd, 1, 20, NULL);
-            if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
-                DispatchMessage (&msg);
+           if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
+               DispatchMessage(&msg);
 
            /* Make sure we blink everything that needs it. */
            term_blink(0);
@@ -580,7 +589,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
             * we've delayed, reading the socket, writing, and repainting
             * the window.
             */
-           if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+           if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
                continue;
 
            if (pending_netevent) {
@@ -589,7 +598,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
                /* Force the cursor blink on */
                term_blink(1);
 
-               if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+               if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
                    continue;
            }
 
@@ -601,25 +610,25 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
                KillTimer(hwnd, timer_id);
                timer_id = 0;
            }
-            HideCaret(hwnd);
+           HideCaret(hwnd);
            if (inbuf_head)
                term_out();
            term_update();
-            ShowCaret(hwnd);
+           ShowCaret(hwnd);
            if (in_vbell)
-              /* Hmm, term_update didn't want to do an update too soon ... */
-              timer_id = SetTimer(hwnd, 1, 50, NULL);
+               /* Hmm, term_update didn't want to do an update too soon ... */
+               timer_id = SetTimer(hwnd, 1, 50, NULL);
            else if (!has_focus)
-              timer_id = SetTimer(hwnd, 1, 2000, NULL);
+               timer_id = SetTimer(hwnd, 1, 2000, NULL);
            else
-              timer_id = SetTimer(hwnd, 1, 100, NULL);
+               timer_id = SetTimer(hwnd, 1, 100, NULL);
            long_timer = 1;
-       
+
            /* There's no point rescanning everything in the message queue
             * so we do an apparently unnecessary wait here
             */
            WaitMessage();
-           if (GetMessage (&msg, NULL, 0, 0) != 1)
+           if (GetMessage(&msg, NULL, 0, 0) != 1)
                break;
        }
     }
@@ -629,7 +638,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
      */
     {
        int i;
-       for (i=0; i<8; i++)
+       for (i = 0; i < 8; i++)
            if (fonts[i])
                DeleteObject(fonts[i]);
     }
@@ -651,7 +660,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
 /*
  * Set up, or shut down, an AsyncSelect. Called from winnet.c.
  */
-char *do_select(SOCKET skt, int startup) {
+char *do_select(SOCKET skt, int startup)
+{
     int msg, events;
     if (startup) {
        msg = WM_NETEVENT;
@@ -661,11 +671,13 @@ char *do_select(SOCKET skt, int startup) {
     }
     if (!hwnd)
        return "do_select(): internal error (hwnd==NULL)";
-    if (WSAAsyncSelect (skt, hwnd, msg, events) == SOCKET_ERROR) {
-        switch (WSAGetLastError()) {
-          case WSAENETDOWN: return "Network is down";
-          default: return "WSAAsyncSelect(): unknown error";
-        }
+    if (WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
+       switch (WSAGetLastError()) {
+         case WSAENETDOWN:
+           return "Network is down";
+         default:
+           return "WSAAsyncSelect(): unknown error";
+       }
     }
     return NULL;
 }
@@ -682,7 +694,8 @@ void set_raw_mouse_mode(int activate)
 /*
  * Print a message box and close the connection.
  */
-void connection_fatal(char *fmt, ...) {
+void connection_fatal(char *fmt, ...)
+{
     va_list ap;
     char stuff[200];
 
@@ -691,41 +704,41 @@ void connection_fatal(char *fmt, ...) {
     va_end(ap);
     MessageBox(hwnd, stuff, "PuTTY Fatal Error", MB_ICONERROR | MB_OK);
     if (cfg.close_on_exit == COE_ALWAYS)
-        PostQuitMessage(1);
+       PostQuitMessage(1);
     else {
-        session_closed = TRUE;
-        SetWindowText (hwnd, "PuTTY (inactive)");
+       session_closed = TRUE;
+       SetWindowText(hwnd, "PuTTY (inactive)");
     }
 }
 
 /*
  * Actually do the job requested by a WM_NETEVENT
  */
-static void enact_pending_netevent(void) {
+static void enact_pending_netevent(void)
+{
     static int reentering = 0;
     extern int select_result(WPARAM, LPARAM);
     int ret;
 
     if (reentering)
-        return;                        /* don't unpend the pending */
+       return;                        /* don't unpend the pending */
 
     pending_netevent = FALSE;
 
     reentering = 1;
-    ret = select_result (pend_netevent_wParam, pend_netevent_lParam);
+    ret = select_result(pend_netevent_wParam, pend_netevent_lParam);
     reentering = 0;
 
     if (ret == 0 && !session_closed) {
-        /* Abnormal exits will already have set session_closed and taken
-         * appropriate action. */
+       /* Abnormal exits will already have set session_closed and taken
+        * appropriate action. */
        if (cfg.close_on_exit == COE_ALWAYS ||
-            cfg.close_on_exit == COE_NORMAL)
-           PostQuitMessage(0);
+           cfg.close_on_exit == COE_NORMAL) PostQuitMessage(0);
        else {
-            session_closed = TRUE;
-            SetWindowText (hwnd, "PuTTY (inactive)");
-            MessageBox(hwnd, "Connection closed by remote host",
-                       "PuTTY", MB_OK | MB_ICONINFORMATION);
+           session_closed = TRUE;
+           SetWindowText(hwnd, "PuTTY (inactive)");
+           MessageBox(hwnd, "Connection closed by remote host",
+                      "PuTTY", MB_OK | MB_ICONINFORMATION);
        }
     }
 }
@@ -734,7 +747,8 @@ static void enact_pending_netevent(void) {
  * Copy the colour palette from the configuration data into defpal.
  * This is non-trivial because the colour indices are different.
  */
-static void cfgtopalette(void) {
+static void cfgtopalette(void)
+{
     int i;
     static const int ww[] = {
        6, 7, 8, 9, 10, 11, 12, 13,
@@ -742,7 +756,7 @@ static void cfgtopalette(void) {
        0, 1, 2, 3, 4, 4, 5, 5
     };
 
-    for (i=0; i<24; i++) {
+    for (i = 0; i < 24; i++) {
        int w = ww[i];
        defpal[i].rgbtRed = cfg.colours[w][0];
        defpal[i].rgbtGreen = cfg.colours[w][1];
@@ -753,12 +767,12 @@ static void cfgtopalette(void) {
 /*
  * Set up the colour palette.
  */
-static void init_palette(void) {
+static void init_palette(void)
+{
     int i;
-    HDC hdc = GetDC (hwnd);
+    HDC hdc = GetDC(hwnd);
     if (hdc) {
-       if (cfg.try_palette &&
-           GetDeviceCaps (hdc, RASTERCAPS) & RC_PALETTE) {
+       if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
            logpal = smalloc(sizeof(*logpal)
                             - sizeof(logpal->palPalEntry)
                             + NCOLOURS * sizeof(PALETTEENTRY));
@@ -770,26 +784,24 @@ static void init_palette(void) {
                logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
                logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
            }
-           pal = CreatePalette (logpal);
+           pal = CreatePalette(logpal);
            if (pal) {
-               SelectPalette (hdc, pal, FALSE);
-               RealizePalette (hdc);
-               SelectPalette (hdc, GetStockObject (DEFAULT_PALETTE),
-                              FALSE);
+               SelectPalette(hdc, pal, FALSE);
+               RealizePalette(hdc);
+               SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
            }
        }
-       ReleaseDC (hwnd, hdc);
+       ReleaseDC(hwnd, hdc);
     }
     if (pal)
-       for (i=0; i<NCOLOURS; i++)
+       for (i = 0; i < NCOLOURS; i++)
            colours[i] = PALETTERGB(defpal[i].rgbtRed,
                                    defpal[i].rgbtGreen,
                                    defpal[i].rgbtBlue);
     else
-       for(i=0; i<NCOLOURS; i++)
+       for (i = 0; i < NCOLOURS; i++)
            colours[i] = RGB(defpal[i].rgbtRed,
-                            defpal[i].rgbtGreen,
-                            defpal[i].rgbtBlue);
+                            defpal[i].rgbtGreen, defpal[i].rgbtBlue);
 }
 
 /*
@@ -806,7 +818,8 @@ static void init_palette(void) {
  *   ordinary one (manual underlining by means of line drawing can
  *   be done in a pinch).
  */
-static void init_fonts(int pick_width) {
+static void init_fonts(int pick_width)
+{
     TEXTMETRIC tm;
     int i;
     int fsize[8];
@@ -815,15 +828,15 @@ static void init_fonts(int pick_width) {
     int firstchar = ' ';
 
 #ifdef CHECKOEMFONT
-font_messup:
+  font_messup:
 #endif
-    for (i=0; i<8; i++)
+    for (i = 0; i < 8; i++)
        fonts[i] = NULL;
 
     if (cfg.fontisbold) {
        fw_dontcare = FW_BOLD;
        fw_bold = FW_HEAVY;
-   } else {
+    } else {
        fw_dontcare = FW_DONTCARE;
        fw_bold = FW_BOLD;
     }
@@ -832,7 +845,8 @@ font_messup:
 
     font_height = cfg.fontheight;
     if (font_height > 0) {
-        font_height = -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
+       font_height =
+           -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
     }
     font_width = pick_width;
 
@@ -845,63 +859,63 @@ font_messup:
     if (cfg.vtmode != VT_OEMONLY) {
        f(FONT_NORMAL, cfg.fontcharset, fw_dontcare, FALSE);
 
-       SelectObject (hdc, fonts[FONT_NORMAL]);
-       GetTextMetrics(hdc, &tm); 
+       SelectObject(hdc, fonts[FONT_NORMAL]);
+       GetTextMetrics(hdc, &tm);
        font_height = tm.tmHeight;
        font_width = tm.tmAveCharWidth;
 
        f(FONT_UNDERLINE, cfg.fontcharset, fw_dontcare, TRUE);
 
-        /*
-         * Some fonts, e.g. 9-pt Courier, draw their underlines
-         * outside their character cell. We successfully prevent
-         * screen corruption by clipping the text output, but then
-         * we lose the underline completely. Here we try to work
-         * out whether this is such a font, and if it is, we set a
-         * flag that causes underlines to be drawn by hand.
-         *
-         * Having tried other more sophisticated approaches (such
-         * as examining the TEXTMETRIC structure or requesting the
-         * height of a string), I think we'll do this the brute
-         * force way: we create a small bitmap, draw an underlined
-         * space on it, and test to see whether any pixels are
-         * foreground-coloured. (Since we expect the underline to
-         * go all the way across the character cell, we only search
-         * down a single column of the bitmap, half way across.)
-         */
-        {
-            HDC und_dc;
-            HBITMAP und_bm, und_oldbm;
-            int i, gotit;
-            COLORREF c;
-
-            und_dc = CreateCompatibleDC(hdc);
-            und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
-            und_oldbm = SelectObject(und_dc, und_bm);
-            SelectObject(und_dc, fonts[FONT_UNDERLINE]);
-            SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
-            SetTextColor (und_dc, RGB(255,255,255));
-            SetBkColor (und_dc, RGB(0,0,0));
-            SetBkMode (und_dc, OPAQUE);
-            ExtTextOut (und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
-            gotit = FALSE;
-            for (i = 0; i < font_height; i++) {
-                c = GetPixel(und_dc, font_width/2, i);
-                if (c != RGB(0,0,0))
-                    gotit = TRUE;
-            }
-            SelectObject(und_dc, und_oldbm);
-            DeleteObject(und_bm);
-            DeleteDC(und_dc);
-            font_needs_hand_underlining = !gotit;
-        }
-
-        if (bold_mode == BOLD_FONT) {
+       /*
+        * Some fonts, e.g. 9-pt Courier, draw their underlines
+        * outside their character cell. We successfully prevent
+        * screen corruption by clipping the text output, but then
+        * we lose the underline completely. Here we try to work
+        * out whether this is such a font, and if it is, we set a
+        * flag that causes underlines to be drawn by hand.
+        *
+        * Having tried other more sophisticated approaches (such
+        * as examining the TEXTMETRIC structure or requesting the
+        * height of a string), I think we'll do this the brute
+        * force way: we create a small bitmap, draw an underlined
+        * space on it, and test to see whether any pixels are
+        * foreground-coloured. (Since we expect the underline to
+        * go all the way across the character cell, we only search
+        * down a single column of the bitmap, half way across.)
+        */
+       {
+           HDC und_dc;
+           HBITMAP und_bm, und_oldbm;
+           int i, gotit;
+           COLORREF c;
+
+           und_dc = CreateCompatibleDC(hdc);
+           und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
+           und_oldbm = SelectObject(und_dc, und_bm);
+           SelectObject(und_dc, fonts[FONT_UNDERLINE]);
+           SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
+           SetTextColor(und_dc, RGB(255, 255, 255));
+           SetBkColor(und_dc, RGB(0, 0, 0));
+           SetBkMode(und_dc, OPAQUE);
+           ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
+           gotit = FALSE;
+           for (i = 0; i < font_height; i++) {
+               c = GetPixel(und_dc, font_width / 2, i);
+               if (c != RGB(0, 0, 0))
+                   gotit = TRUE;
+           }
+           SelectObject(und_dc, und_oldbm);
+           DeleteObject(und_bm);
+           DeleteDC(und_dc);
+           font_needs_hand_underlining = !gotit;
+       }
+
+       if (bold_mode == BOLD_FONT) {
            f(FONT_BOLD, cfg.fontcharset, fw_bold, FALSE);
            f(FONT_BOLDUND, cfg.fontcharset, fw_bold, TRUE);
        }
 
-        if (cfg.vtmode == VT_OEMANSI) {
+       if (cfg.vtmode == VT_OEMANSI) {
            f(FONT_OEM, OEM_CHARSET, fw_dontcare, FALSE);
            f(FONT_OEMUND, OEM_CHARSET, fw_dontcare, TRUE);
 
@@ -909,14 +923,12 @@ font_messup:
                f(FONT_OEMBOLD, OEM_CHARSET, fw_bold, FALSE);
                f(FONT_OEMBOLDUND, OEM_CHARSET, fw_bold, TRUE);
            }
-        }
-    }
-    else
-    {
+       }
+    } else {
        f(FONT_OEM, cfg.fontcharset, fw_dontcare, FALSE);
 
-       SelectObject (hdc, fonts[FONT_OEM]);
-       GetTextMetrics(hdc, &tm); 
+       SelectObject(hdc, fonts[FONT_OEM]);
+       GetTextMetrics(hdc, &tm);
        font_height = tm.tmHeight;
        font_width = tm.tmAveCharWidth;
 
@@ -934,133 +946,133 @@ font_messup:
        descent = font_height - 1;
     firstchar = tm.tmFirstChar;
 
-    for (i=0; i<8; i++) {
+    for (i = 0; i < 8; i++) {
        if (fonts[i]) {
-           if (SelectObject (hdc, fonts[i]) &&
-               GetTextMetrics(hdc, &tm) )
-                fsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
-           else fsize[i] = -i;
-       }
-       else fsize[i] = -i;
+           if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
+               fsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
+           else
+               fsize[i] = -i;
+       } else
+           fsize[i] = -i;
     }
 
-    ReleaseDC (hwnd, hdc);
+    ReleaseDC(hwnd, hdc);
 
     /* ... This is wrong in OEM only mode */
     if (fsize[FONT_UNDERLINE] != fsize[FONT_NORMAL] ||
        (bold_mode == BOLD_FONT &&
         fsize[FONT_BOLDUND] != fsize[FONT_BOLD])) {
        und_mode = UND_LINE;
-       DeleteObject (fonts[FONT_UNDERLINE]);
+       DeleteObject(fonts[FONT_UNDERLINE]);
        if (bold_mode == BOLD_FONT)
-           DeleteObject (fonts[FONT_BOLDUND]);
+           DeleteObject(fonts[FONT_BOLDUND]);
     }
 
-    if (bold_mode == BOLD_FONT &&
-       fsize[FONT_BOLD] != fsize[FONT_NORMAL]) {
+    if (bold_mode == BOLD_FONT && fsize[FONT_BOLD] != fsize[FONT_NORMAL]) {
        bold_mode = BOLD_SHADOW;
-       DeleteObject (fonts[FONT_BOLD]);
+       DeleteObject(fonts[FONT_BOLD]);
        if (und_mode == UND_FONT)
-           DeleteObject (fonts[FONT_BOLDUND]);
+           DeleteObject(fonts[FONT_BOLDUND]);
     }
-
 #ifdef CHECKOEMFONT
     /* With the fascist font painting it doesn't matter if the linedraw font
      * isn't exactly the right size anymore so we don't have to check this.
      */
-    if (cfg.vtmode == VT_OEMANSI && fsize[FONT_OEM] != fsize[FONT_NORMAL] ) {
-       if( cfg.fontcharset == OEM_CHARSET )
-       {
+    if (cfg.vtmode == VT_OEMANSI && fsize[FONT_OEM] != fsize[FONT_NORMAL]) {
+       if (cfg.fontcharset == OEM_CHARSET) {
            MessageBox(NULL, "The OEM and ANSI versions of this font are\n"
-                  "different sizes. Using OEM-only mode instead",
-                  "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
+                      "different sizes. Using OEM-only mode instead",
+                      "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
            cfg.vtmode = VT_OEMONLY;
-       }
-       else if( firstchar < ' ' )
-       {
+       } else if (firstchar < ' ') {
            MessageBox(NULL, "The OEM and ANSI versions of this font are\n"
-                  "different sizes. Using XTerm mode instead",
-                  "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
+                      "different sizes. Using XTerm mode instead",
+                      "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
            cfg.vtmode = VT_XWINDOWS;
-       }
-       else
-       {
+       } else {
            MessageBox(NULL, "The OEM and ANSI versions of this font are\n"
-                  "different sizes. Using ISO8859-1 mode instead",
-                  "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
+                      "different sizes. Using ISO8859-1 mode instead",
+                      "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
            cfg.vtmode = VT_POORMAN;
        }
 
-       for (i=0; i<8; i++)
+       for (i = 0; i < 8; i++)
            if (fonts[i])
-               DeleteObject (fonts[i]);
+               DeleteObject(fonts[i]);
        goto font_messup;
     }
 #endif
 }
 
-void request_resize (int w, int h, int refont) {
+void request_resize(int w, int h, int refont)
+{
     int width, height;
 
     /* If the window is maximized supress resizing attempts */
-    if(IsZoomed(hwnd)) return;
-    
+    if (IsZoomed(hwnd))
+       return;
+
 #ifdef CHECKOEMFONT
     /* Don't do this in OEMANSI, you may get disable messages */
-    if (refont && w != cols && (cols==80 || cols==132)
-         && cfg.vtmode != VT_OEMANSI)
+    if (refont && w != cols && (cols == 80 || cols == 132)
+       && cfg.vtmode != VT_OEMANSI)
 #else
-    if (refont && w != cols && (cols==80 || cols==132))
+    if (refont && w != cols && (cols == 80 || cols == 132))
 #endif
     {
-       /* If font width too big for screen should we shrink the font more ? */
-        if (w==132)
-            font_width = ((font_width*cols+w/2)/w);
-        else
+       /* If font width too big for screen should we shrink the font more ? */
+       if (w == 132)
+           font_width = ((font_width * cols + w / 2) / w);
+       else
            font_width = 0;
        {
            int i;
-           for (i=0; i<8; i++)
+           for (i = 0; i < 8; i++)
                if (fonts[i])
                    DeleteObject(fonts[i]);
        }
-        bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
-        und_mode = UND_FONT;
-        init_fonts(font_width);
-    }
-    else
-    {
-       static int first_time = 1;
-       static RECT ss;
-
-       switch(first_time)
-       {
-       case 1:
-            /* Get the size of the screen */
-            if (GetClientRect(GetDesktopWindow(),&ss))
-               /* first_time = 0 */;
-            else { first_time = 2; break; }
-       case 0:
-            /* Make sure the values are sane */
-            width  = (ss.right-ss.left-extra_width  ) / font_width;
-            height = (ss.bottom-ss.top-extra_height ) / font_height;
-
-            if (w>width)  w=width;
-            if (h>height) h=height;
-            if (w<15) w = 15;
-            if (h<1) w = 1;
-       }
+       bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
+       und_mode = UND_FONT;
+       init_fonts(font_width);
+    } else {
+       static int first_time = 1;
+       static RECT ss;
+
+       switch (first_time) {
+         case 1:
+           /* Get the size of the screen */
+           if (GetClientRect(GetDesktopWindow(), &ss))
+               /* first_time = 0 */ ;
+           else {
+               first_time = 2;
+               break;
+           }
+         case 0:
+           /* Make sure the values are sane */
+           width = (ss.right - ss.left - extra_width) / font_width;
+           height = (ss.bottom - ss.top - extra_height) / font_height;
+
+           if (w > width)
+               w = width;
+           if (h > height)
+               h = height;
+           if (w < 15)
+               w = 15;
+           if (h < 1)
+               w = 1;
+       }
     }
 
     width = extra_width + font_width * w;
     height = extra_height + font_height * h;
 
-    SetWindowPos (hwnd, NULL, 0, 0, width, height,
-                 SWP_NOACTIVATE | SWP_NOCOPYBITS |
-                 SWP_NOMOVE | SWP_NOZORDER);
+    SetWindowPos(hwnd, NULL, 0, 0, width, height,
+                SWP_NOACTIVATE | SWP_NOCOPYBITS |
+                SWP_NOMOVE | SWP_NOZORDER);
 }
 
-static void click (Mouse_Button b, int x, int y, int shift, int ctrl) {
+static void click(Mouse_Button b, int x, int y, int shift, int ctrl)
+{
     int thistime = GetMessageTime();
 
     if (send_raw_mouse) {
@@ -1077,7 +1089,7 @@ static void click (Mouse_Button b, int x, int y, int shift, int ctrl) {
        lastact = MA_CLICK;
     }
     if (lastact != MA_NOTHING)
-       term_mouse (b, lastact, x, y, shift, ctrl);
+       term_mouse(b, lastact, x, y, shift, ctrl);
     lasttime = thistime;
 }
 
@@ -1085,7 +1097,8 @@ static void click (Mouse_Button b, int x, int y, int shift, int ctrl) {
  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
  * into a cooked one (SELECT, EXTEND, PASTE).
  */
-Mouse_Button translate_button(Mouse_Button button) {
+Mouse_Button translate_button(Mouse_Button button)
+{
     if (button == MBT_LEFT)
        return MBT_SELECT;
     if (button == MBT_MIDDLE)
@@ -1094,19 +1107,21 @@ Mouse_Button translate_button(Mouse_Button button) {
        return cfg.mouse_is_xterm ? MBT_EXTEND : MBT_PASTE;
 }
 
-static void show_mouseptr(int show) {
+static void show_mouseptr(int show)
+{
     static int cursor_visible = 1;
-    if (!cfg.hide_mouseptr)            /* override if this feature disabled */
-        show = 1;
+    if (!cfg.hide_mouseptr)           /* override if this feature disabled */
+       show = 1;
     if (cursor_visible && !show)
-        ShowCursor(FALSE);
+       ShowCursor(FALSE);
     else if (!cursor_visible && show)
-        ShowCursor(TRUE);
+       ShowCursor(TRUE);
     cursor_visible = show;
 }
 
-static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
-                                 WPARAM wParam, LPARAM lParam) {
+static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
+                               WPARAM wParam, LPARAM lParam)
+{
     HDC hdc;
     static int ignore_size = FALSE;
     static int ignore_clip = FALSE;
@@ -1120,34 +1135,33 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
            enact_pending_netevent();
        if (inbuf_head)
            term_out();
-        noise_regular();
-        HideCaret(hwnd);
+       noise_regular();
+       HideCaret(hwnd);
        term_update();
-        ShowCaret(hwnd);
-       if (cfg.ping_interval > 0)
-        {
-           time_t now;
-           time(&now);
-           if (now-last_movement > cfg.ping_interval)
-           {
-              back->special(TS_PING);
-              last_movement = now;
-           }
-        }
+       ShowCaret(hwnd);
+       if (cfg.ping_interval > 0) {
+           time_t now;
+           time(&now);
+           if (now - last_movement > cfg.ping_interval) {
+               back->special(TS_PING);
+               last_movement = now;
+           }
+       }
        return 0;
       case WM_CREATE:
        break;
       case WM_CLOSE:
-        show_mouseptr(1);
+       show_mouseptr(1);
        if (!cfg.warn_on_close || session_closed ||
-           MessageBox(hwnd, "Are you sure you want to close this session?",
+           MessageBox(hwnd,
+                      "Are you sure you want to close this session?",
                       "PuTTY Exit Confirmation",
                       MB_ICONWARNING | MB_OKCANCEL) == IDOK)
            DestroyWindow(hwnd);
        return 0;
       case WM_DESTROY:
-        show_mouseptr(1);
-       PostQuitMessage (0);
+       show_mouseptr(1);
+       PostQuitMessage(0);
        return 0;
       case WM_SYSCOMMAND:
        switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
@@ -1176,16 +1190,14 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                    sa.nLength = sizeof(sa);
                    sa.lpSecurityDescriptor = NULL;
                    sa.bInheritHandle = TRUE;
-                   filemap = CreateFileMapping((HANDLE)0xFFFFFFFF,
+                   filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
                                                &sa,
                                                PAGE_READWRITE,
-                                               0,
-                                               sizeof(Config),
-                                               NULL);
+                                               0, sizeof(Config), NULL);
                    if (filemap) {
-                       p = (Config *)MapViewOfFile(filemap,
-                                                   FILE_MAP_WRITE,
-                                                   0, 0, sizeof(Config));
+                       p = (Config *) MapViewOfFile(filemap,
+                                                    FILE_MAP_WRITE,
+                                                    0, 0, sizeof(Config));
                        if (p) {
                            *p = cfg;  /* structure copy */
                            UnmapViewOfFile(p);
@@ -1194,8 +1206,9 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                    sprintf(c, "putty &%p", filemap);
                    cl = c;
                } else if (wParam == IDM_SAVEDSESS) {
-                   char *session = sessions[(lParam - IDM_SAVED_MIN) / 16];
-                   cl = smalloc(16 + strlen(session)); /* 8, but play safe */
+                   char *session =
+                       sessions[(lParam - IDM_SAVED_MIN) / 16];
+                   cl = smalloc(16 + strlen(session)); /* 8, but play safe */
                    if (!cl)
                        cl = NULL;     /* not a very important failure mode */
                    else {
@@ -1205,7 +1218,7 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                } else
                    cl = NULL;
 
-               GetModuleFileName (NULL, b, sizeof(b)-1);
+               GetModuleFileName(NULL, b, sizeof(b) - 1);
                si.cb = sizeof(si);
                si.lpReserved = NULL;
                si.lpDesktop = NULL;
@@ -1213,8 +1226,8 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                si.dwFlags = 0;
                si.cbReserved2 = 0;
                si.lpReserved2 = NULL;
-               CreateProcess (b, cl, NULL, NULL, TRUE,
-                              NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
+               CreateProcess(b, cl, NULL, NULL, TRUE,
+                             NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
 
                if (filemap)
                    CloseHandle(filemap);
@@ -1222,10 +1235,10 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                    sfree(cl);
            }
            break;
-          case IDM_RECONF:
-            {
-                int prev_alwaysontop = cfg.alwaysontop;
-                int prev_sunken_edge = cfg.sunken_edge;
+         case IDM_RECONF:
+           {
+               int prev_alwaysontop = cfg.alwaysontop;
+               int prev_sunken_edge = cfg.sunken_edge;
                char oldlogfile[FILENAME_MAX];
                int oldlogtype;
                int need_setwpos = FALSE;
@@ -1237,10 +1250,10 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                cfg.height = rows;
                old_fwidth = font_width;
                old_fheight = font_height;
-                GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
+               GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
 
-                if (!do_reconfig(hwnd))
-                    break;
+               if (!do_reconfig(hwnd))
+                   break;
 
                if (strcmp(oldlogfile, cfg.logfilename) ||
                    oldlogtype != cfg.logtype) {
@@ -1248,135 +1261,166 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                    logfopen();
                }
 
-                just_reconfigged = TRUE;
-                {
-                    int i;
-                    for (i=0; i<8; i++)
-                        if (fonts[i])
-                            DeleteObject(fonts[i]);
-                }
-                bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
-                und_mode = UND_FONT;
-                init_fonts(0);
-                sfree(logpal);
-                /*
-                 * Flush the line discipline's edit buffer in the
-                 * case where local editing has just been disabled.
-                 */
-                ldisc_send(NULL, 0);
-                if (pal)
-                    DeleteObject(pal);
-                logpal = NULL;
-                pal = NULL;
-                cfgtopalette();
-                init_palette();
-
-                /* Enable or disable the scroll bar, etc */
-                {
-                    LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
-                    LONG nexflag, exflag = GetWindowLong(hwnd, GWL_EXSTYLE);
-
-                    nexflag = exflag;
-                    if (cfg.alwaysontop != prev_alwaysontop) {
-                        if (cfg.alwaysontop) {
-                            nexflag |= WS_EX_TOPMOST;
-                            SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
-                                         SWP_NOMOVE | SWP_NOSIZE);
-                        } else {
-                            nexflag &= ~(WS_EX_TOPMOST);
-                            SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
-                                         SWP_NOMOVE | SWP_NOSIZE);
-                        }
-                    }
-                    if (cfg.sunken_edge)
-                        nexflag |= WS_EX_CLIENTEDGE;
-                    else
-                        nexflag &= ~(WS_EX_CLIENTEDGE);
-
-                    nflg = flag;
-                    if (cfg.scrollbar) nflg |=  WS_VSCROLL;
-                    else               nflg &= ~WS_VSCROLL;
-                    if (cfg.locksize)
-                        nflg &= ~(WS_THICKFRAME|WS_MAXIMIZEBOX);
-                    else
-                        nflg |= (WS_THICKFRAME|WS_MAXIMIZEBOX);
-
-                    if (nflg != flag || nexflag != exflag)
-                    {
-                        RECT cr, wr;
-
-                        if (nflg != flag)
-                            SetWindowLong(hwnd, GWL_STYLE, nflg);
-                        if (nexflag != exflag)
-                            SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
-
-                        SendMessage (hwnd, WM_IGNORE_SIZE, 0, 0);
-
-                        SetWindowPos(hwnd, NULL, 0,0,0,0,
-                                     SWP_NOACTIVATE|SWP_NOCOPYBITS|
-                                     SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|
-                                     SWP_FRAMECHANGED);
-
-                        GetWindowRect (hwnd, &wr);
-                        GetClientRect (hwnd, &cr);
-                        extra_width = wr.right - wr.left - cr.right + cr.left;
-                        extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
-                    }
-                }
+               just_reconfigged = TRUE;
+               {
+                   int i;
+                   for (i = 0; i < 8; i++)
+                       if (fonts[i])
+                           DeleteObject(fonts[i]);
+               }
+               bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
+               und_mode = UND_FONT;
+               init_fonts(0);
+               sfree(logpal);
+               /*
+                * Flush the line discipline's edit buffer in the
+                * case where local editing has just been disabled.
+                */
+               ldisc_send(NULL, 0);
+               if (pal)
+                   DeleteObject(pal);
+               logpal = NULL;
+               pal = NULL;
+               cfgtopalette();
+               init_palette();
+
+               /* Enable or disable the scroll bar, etc */
+               {
+                   LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
+                   LONG nexflag, exflag =
+                       GetWindowLong(hwnd, GWL_EXSTYLE);
+
+                   nexflag = exflag;
+                   if (cfg.alwaysontop != prev_alwaysontop) {
+                       if (cfg.alwaysontop) {
+                           nexflag |= WS_EX_TOPMOST;
+                           SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
+                                        SWP_NOMOVE | SWP_NOSIZE);
+                       } else {
+                           nexflag &= ~(WS_EX_TOPMOST);
+                           SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
+                                        SWP_NOMOVE | SWP_NOSIZE);
+                       }
+                   }
+                   if (cfg.sunken_edge)
+                       nexflag |= WS_EX_CLIENTEDGE;
+                   else
+                       nexflag &= ~(WS_EX_CLIENTEDGE);
+
+                   nflg = flag;
+                   if (cfg.scrollbar)
+                       nflg |= WS_VSCROLL;
+                   else
+                       nflg &= ~WS_VSCROLL;
+                   if (cfg.locksize)
+                       nflg &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
+                   else
+                       nflg |= (WS_THICKFRAME | WS_MAXIMIZEBOX);
+
+                   if (nflg != flag || nexflag != exflag) {
+                       RECT cr, wr;
+
+                       if (nflg != flag)
+                           SetWindowLong(hwnd, GWL_STYLE, nflg);
+                       if (nexflag != exflag)
+                           SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
+
+                       SendMessage(hwnd, WM_IGNORE_SIZE, 0, 0);
+
+                       SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
+                                    SWP_NOACTIVATE | SWP_NOCOPYBITS |
+                                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
+                                    | SWP_FRAMECHANGED);
+
+                       GetWindowRect(hwnd, &wr);
+                       GetClientRect(hwnd, &cr);
+                       extra_width =
+                           wr.right - wr.left - cr.right + cr.left;
+                       extra_height =
+                           wr.bottom - wr.top - cr.bottom + cr.top;
+                   }
+               }
 
                if (cfg.height != rows ||
                    cfg.width != cols ||
                    old_fwidth != font_width ||
                    old_fheight != font_height ||
                    cfg.savelines != savelines ||
-                    cfg.sunken_edge != prev_sunken_edge)
-                   need_setwpos = TRUE;
-                term_size(cfg.height, cfg.width, cfg.savelines);
-                InvalidateRect(hwnd, NULL, TRUE);
-                if (need_setwpos) {
+                   cfg.sunken_edge != prev_sunken_edge)
+                       need_setwpos = TRUE;
+               term_size(cfg.height, cfg.width, cfg.savelines);
+               InvalidateRect(hwnd, NULL, TRUE);
+               if (need_setwpos) {
                    force_normal(hwnd);
-                   SetWindowPos (hwnd, NULL, 0, 0,
-                                 extra_width + font_width * cfg.width,
-                                 extra_height + font_height * cfg.height,
-                                 SWP_NOACTIVATE | SWP_NOCOPYBITS |
-                                 SWP_NOMOVE | SWP_NOZORDER);
+                   SetWindowPos(hwnd, NULL, 0, 0,
+                                extra_width + font_width * cfg.width,
+                                extra_height + font_height * cfg.height,
+                                SWP_NOACTIVATE | SWP_NOCOPYBITS |
+                                SWP_NOMOVE | SWP_NOZORDER);
+               }
+               set_title(cfg.wintitle);
+               if (IsIconic(hwnd)) {
+                   SetWindowText(hwnd,
+                                 cfg.win_name_always ? window_name :
+                                 icon_name);
                }
-                set_title(cfg.wintitle);
-                if (IsIconic(hwnd)) {
-                    SetWindowText (hwnd,
-                                   cfg.win_name_always ? window_name : icon_name);
-                }
-            }
-            break;
+           }
+           break;
          case IDM_COPYALL:
            term_copyall();
            break;
-          case IDM_CLRSB:
-            term_clrsb();
-            break;
-          case IDM_RESET:
-            term_pwron();
-            break;
-          case IDM_TEL_AYT: back->special (TS_AYT); break;
-         case IDM_TEL_BRK: back->special (TS_BRK); break;
-         case IDM_TEL_SYNCH: back->special (TS_SYNCH); break;
-         case IDM_TEL_EC: back->special (TS_EC); break;
-         case IDM_TEL_EL: back->special (TS_EL); break;
-         case IDM_TEL_GA: back->special (TS_GA); break;
-         case IDM_TEL_NOP: back->special (TS_NOP); break;
-         case IDM_TEL_ABORT: back->special (TS_ABORT); break;
-         case IDM_TEL_AO: back->special (TS_AO); break;
-         case IDM_TEL_IP: back->special (TS_IP); break;
-         case IDM_TEL_SUSP: back->special (TS_SUSP); break;
-         case IDM_TEL_EOR: back->special (TS_EOR); break;
-         case IDM_TEL_EOF: back->special (TS_EOF); break;
+         case IDM_CLRSB:
+           term_clrsb();
+           break;
+         case IDM_RESET:
+           term_pwron();
+           break;
+         case IDM_TEL_AYT:
+           back->special(TS_AYT);
+           break;
+         case IDM_TEL_BRK:
+           back->special(TS_BRK);
+           break;
+         case IDM_TEL_SYNCH:
+           back->special(TS_SYNCH);
+           break;
+         case IDM_TEL_EC:
+           back->special(TS_EC);
+           break;
+         case IDM_TEL_EL:
+           back->special(TS_EL);
+           break;
+         case IDM_TEL_GA:
+           back->special(TS_GA);
+           break;
+         case IDM_TEL_NOP:
+           back->special(TS_NOP);
+           break;
+         case IDM_TEL_ABORT:
+           back->special(TS_ABORT);
+           break;
+         case IDM_TEL_AO:
+           back->special(TS_AO);
+           break;
+         case IDM_TEL_IP:
+           back->special(TS_IP);
+           break;
+         case IDM_TEL_SUSP:
+           back->special(TS_SUSP);
+           break;
+         case IDM_TEL_EOR:
+           back->special(TS_EOR);
+           break;
+         case IDM_TEL_EOF:
+           back->special(TS_EOF);
+           break;
          case IDM_ABOUT:
-           showabout (hwnd);
+           showabout(hwnd);
            break;
-       default:
-         if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
-           SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
-         }
+         default:
+           if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
+               SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
+           }
        }
        break;
 
@@ -1388,7 +1432,7 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
 #define WHEEL_DELTA 120
       case WM_MOUSEWHEEL:
        {
-           wheel_accumulator += (short)HIWORD(wParam);
+           wheel_accumulator += (short) HIWORD(wParam);
            wParam = LOWORD(wParam);
 
            /* process events when the threshold is reached */
@@ -1399,27 +1443,26 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                if (wheel_accumulator > 0) {
                    b = MBT_WHEEL_UP;
                    wheel_accumulator -= WHEEL_DELTA;
-               }
-               else if (wheel_accumulator < 0) {
+               } else if (wheel_accumulator < 0) {
                    b = MBT_WHEEL_DOWN;
                    wheel_accumulator += WHEEL_DELTA;
-               }
-               else
+               } else
                    break;
 
                if (send_raw_mouse) {
                    /* send a mouse-down followed by a mouse up */
                    term_mouse(b,
                               MA_CLICK,
-                              TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
-                              wParam & MK_SHIFT, wParam & MK_CONTROL);
-                   term_mouse(b,
-                              MA_RELEASE,
-                              TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
-                              wParam & MK_SHIFT, wParam & MK_CONTROL);
+                              TO_CHR_X(X_POS(lParam)),
+                              TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
+                              wParam & MK_CONTROL);
+                   term_mouse(b, MA_RELEASE, TO_CHR_X(X_POS(lParam)),
+                              TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
+                              wParam & MK_CONTROL);
                } else {
                    /* trigger a scroll */
-                   term_scroll(0, b == MBT_WHEEL_UP ? -rows/2 : rows/2);
+                   term_scroll(0,
+                               b == MBT_WHEEL_UP ? -rows / 2 : rows / 2);
                }
            }
            return 0;
@@ -1433,34 +1476,53 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
        {
            int button, press;
            switch (message) {
-             case WM_LBUTTONDOWN: button = MBT_LEFT;   press = 1; break;
-             case WM_MBUTTONDOWN: button = MBT_MIDDLE; press = 1; break;
-             case WM_RBUTTONDOWN: button = MBT_RIGHT;  press = 1; break;
-             case WM_LBUTTONUP:   button = MBT_LEFT;   press = 0; break;
-             case WM_MBUTTONUP:   button = MBT_MIDDLE; press = 0; break;
-             case WM_RBUTTONUP:   button = MBT_RIGHT;  press = 0; break;
+             case WM_LBUTTONDOWN:
+               button = MBT_LEFT;
+               press = 1;
+               break;
+             case WM_MBUTTONDOWN:
+               button = MBT_MIDDLE;
+               press = 1;
+               break;
+             case WM_RBUTTONDOWN:
+               button = MBT_RIGHT;
+               press = 1;
+               break;
+             case WM_LBUTTONUP:
+               button = MBT_LEFT;
+               press = 0;
+               break;
+             case WM_MBUTTONUP:
+               button = MBT_MIDDLE;
+               press = 0;
+               break;
+             case WM_RBUTTONUP:
+               button = MBT_RIGHT;
+               press = 0;
+               break;
            }
            show_mouseptr(1);
            if (press) {
-               click (button,
-                      TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
-                      wParam & MK_SHIFT, wParam & MK_CONTROL);
+               click(button,
+                     TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
+                     wParam & MK_SHIFT, wParam & MK_CONTROL);
                SetCapture(hwnd);
            } else {
-               term_mouse (button, MA_RELEASE,
-                           TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
-                           wParam & MK_SHIFT, wParam & MK_CONTROL);
+               term_mouse(button, MA_RELEASE,
+                          TO_CHR_X(X_POS(lParam)),
+                          TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
+                          wParam & MK_CONTROL);
                ReleaseCapture();
            }
        }
        return 0;
       case WM_MOUSEMOVE:
-        show_mouseptr(1);
+       show_mouseptr(1);
        /*
         * Add the mouse position and message time to the random
         * number noise.
         */
-        noise_ultralight(lParam);
+       noise_ultralight(lParam);
 
        if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) {
            Mouse_Button b;
@@ -1470,13 +1532,14 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
                b = cfg.mouse_is_xterm ? MBT_PASTE : MBT_EXTEND;
            else
                b = cfg.mouse_is_xterm ? MBT_EXTEND : MBT_PASTE;
-           term_mouse (b, MA_DRAG, TO_CHR_X(X_POS(lParam)),
-                       TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT, wParam & MK_CONTROL);
+           term_mouse(b, MA_DRAG, TO_CHR_X(X_POS(lParam)),
+                      TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
+                      wParam & MK_CONTROL);
        }
        return 0;
       case WM_NCMOUSEMOVE:
        show_mouseptr(1);
-        noise_ultralight(lParam);
+       noise_ultralight(lParam);
        return 0;
       case WM_IGNORE_CLIP:
        ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */
@@ -1489,18 +1552,18 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
       case WM_PAINT:
        {
            PAINTSTRUCT p;
-            HideCaret(hwnd);
-           hdc = BeginPaint (hwnd, &p);
+           HideCaret(hwnd);
+           hdc = BeginPaint(hwnd, &p);
            if (pal) {
-               SelectPalette (hdc, pal, TRUE);
-               RealizePalette (hdc);
+               SelectPalette(hdc, pal, TRUE);
+               RealizePalette(hdc);
            }
-           term_paint (hdc, p.rcPaint.left, p.rcPaint.top,
-                       p.rcPaint.right, p.rcPaint.bottom);
-           SelectObject (hdc, GetStockObject(SYSTEM_FONT));
-           SelectObject (hdc, GetStockObject(WHITE_PEN));
-           EndPaint (hwnd, &p);
-            ShowCaret(hwnd);
+           term_paint(hdc, p.rcPaint.left, p.rcPaint.top,
+                      p.rcPaint.right, p.rcPaint.bottom);
+           SelectObject(hdc, GetStockObject(SYSTEM_FONT));
+           SelectObject(hdc, GetStockObject(WHITE_PEN));
+           EndPaint(hwnd, &p);
+           ShowCaret(hwnd);
        }
        return 0;
       case WM_NETEVENT:
@@ -1512,22 +1575,22 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
            enact_pending_netevent();
 
        pending_netevent = TRUE;
-       pend_netevent_wParam=wParam;
-       pend_netevent_lParam=lParam;
+       pend_netevent_wParam = wParam;
+       pend_netevent_lParam = lParam;
        time(&last_movement);
        return 0;
       case WM_SETFOCUS:
        has_focus = TRUE;
-        CreateCaret(hwnd, caretbm, font_width, font_height);
-        ShowCaret(hwnd);
-        compose_state = 0;
+       CreateCaret(hwnd, caretbm, font_width, font_height);
+       ShowCaret(hwnd);
+       compose_state = 0;
        term_out();
        term_update();
        break;
       case WM_KILLFOCUS:
-        show_mouseptr(1);
+       show_mouseptr(1);
        has_focus = FALSE;
-        DestroyCaret();
+       DestroyCaret();
        term_out();
        term_update();
        break;
@@ -1535,40 +1598,42 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
        ignore_size = TRUE;            /* don't panic on next WM_SIZE msg */
        break;
       case WM_ENTERSIZEMOVE:
-        EnableSizeTip(1);
-        resizing = TRUE;
+       EnableSizeTip(1);
+       resizing = TRUE;
        need_backend_resize = FALSE;
-        break;
+       break;
       case WM_EXITSIZEMOVE:
-        EnableSizeTip(0);
-        resizing = FALSE;
+       EnableSizeTip(0);
+       resizing = FALSE;
        if (need_backend_resize)
            back->size();
-        break;
+       break;
       case WM_SIZING:
        {
            int width, height, w, h, ew, eh;
-           LPRECT r = (LPRECT)lParam;
+           LPRECT r = (LPRECT) lParam;
 
            width = r->right - r->left - extra_width;
            height = r->bottom - r->top - extra_height;
-           w = (width + font_width/2) / font_width; if (w < 1) w = 1;
-           h = (height + font_height/2) / font_height; if (h < 1) h = 1;
-            UpdateSizeTip(hwnd, w, h);
+           w = (width + font_width / 2) / font_width;
+           if (w < 1)
+               w = 1;
+           h = (height + font_height / 2) / font_height;
+           if (h < 1)
+               h = 1;
+           UpdateSizeTip(hwnd, w, h);
            ew = width - w * font_width;
            eh = height - h * font_height;
            if (ew != 0) {
                if (wParam == WMSZ_LEFT ||
-                   wParam == WMSZ_BOTTOMLEFT ||
-                   wParam == WMSZ_TOPLEFT)
+                   wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
                    r->left += ew;
                else
                    r->right -= ew;
            }
            if (eh != 0) {
                if (wParam == WMSZ_TOP ||
-                   wParam == WMSZ_TOPRIGHT ||
-                   wParam == WMSZ_TOPLEFT)
+                   wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
                    r->top += eh;
                else
                    r->bottom -= eh;
@@ -1578,47 +1643,51 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
            else
                return 0;
        }
-        /* break;  (never reached) */
+       /* break;  (never reached) */
       case WM_SIZE:
        if (wParam == SIZE_MINIMIZED) {
-           SetWindowText (hwnd,
-                          cfg.win_name_always ? window_name : icon_name);
+           SetWindowText(hwnd,
+                         cfg.win_name_always ? window_name : icon_name);
            break;
        }
        if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
-           SetWindowText (hwnd, window_name);
+           SetWindowText(hwnd, window_name);
        if (!ignore_size) {
            int width, height, w, h;
-#if 0 /* we have fixed this using WM_SIZING now */
-            int ew, eh;
+#if 0                                 /* we have fixed this using WM_SIZING now */
+           int ew, eh;
 #endif
 
            width = LOWORD(lParam);
            height = HIWORD(lParam);
-           w = width / font_width; if (w < 1) w = 1;
-           h = height / font_height; if (h < 1) h = 1;
-#if 0 /* we have fixed this using WM_SIZING now */
+           w = width / font_width;
+           if (w < 1)
+               w = 1;
+           h = height / font_height;
+           if (h < 1)
+               h = 1;
+#if 0                                 /* we have fixed this using WM_SIZING now */
            ew = width - w * font_width;
            eh = height - h * font_height;
            if (ew != 0 || eh != 0) {
                RECT r;
-               GetWindowRect (hwnd, &r);
-               SendMessage (hwnd, WM_IGNORE_SIZE, 0, 0);
-               SetWindowPos (hwnd, NULL, 0, 0,
-                             r.right - r.left - ew, r.bottom - r.top - eh,
-                             SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
+               GetWindowRect(hwnd, &r);
+               SendMessage(hwnd, WM_IGNORE_SIZE, 0, 0);
+               SetWindowPos(hwnd, NULL, 0, 0,
+                            r.right - r.left - ew, r.bottom - r.top - eh,
+                            SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
            }
 #endif
            if (w != cols || h != rows || just_reconfigged) {
                term_invalidate();
-               term_size (h, w, cfg.savelines);
-                /*
-                 * Don't call back->size in mid-resize. (To prevent
-                 * massive numbers of resize events getting sent
-                 * down the connection during an NT opaque drag.)
-                 */
-                if (!resizing)
-                    back->size();
+               term_size(h, w, cfg.savelines);
+               /*
+                * Don't call back->size in mid-resize. (To prevent
+                * massive numbers of resize events getting sent
+                * down the connection during an NT opaque drag.)
+                */
+               if (!resizing)
+                   back->size();
                else
                    need_backend_resize = TRUE;
                just_reconfigged = FALSE;
@@ -1628,23 +1697,37 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
        return 0;
       case WM_VSCROLL:
        switch (LOWORD(wParam)) {
-         case SB_BOTTOM: term_scroll(-1, 0); break;
-         case SB_TOP: term_scroll(+1, 0); break;
-         case SB_LINEDOWN: term_scroll (0, +1); break;
-         case SB_LINEUP: term_scroll (0, -1); break;
-         case SB_PAGEDOWN: term_scroll (0, +rows/2); break;
-         case SB_PAGEUP: term_scroll (0, -rows/2); break;
-         case SB_THUMBPOSITION: case SB_THUMBTRACK:
-           term_scroll (1, HIWORD(wParam)); break;
-       }
-       break; 
-     case WM_PALETTECHANGED:
+         case SB_BOTTOM:
+           term_scroll(-1, 0);
+           break;
+         case SB_TOP:
+           term_scroll(+1, 0);
+           break;
+         case SB_LINEDOWN:
+           term_scroll(0, +1);
+           break;
+         case SB_LINEUP:
+           term_scroll(0, -1);
+           break;
+         case SB_PAGEDOWN:
+           term_scroll(0, +rows / 2);
+           break;
+         case SB_PAGEUP:
+           term_scroll(0, -rows / 2);
+           break;
+         case SB_THUMBPOSITION:
+         case SB_THUMBTRACK:
+           term_scroll(1, HIWORD(wParam));
+           break;
+       }
+       break;
+      case WM_PALETTECHANGED:
        if ((HWND) wParam != hwnd && pal != NULL) {
            HDC hdc = get_ctx();
            if (hdc) {
-               if (RealizePalette (hdc) > 0)
-                   UpdateColors (hdc);
-               free_ctx (hdc);
+               if (RealizePalette(hdc) > 0)
+                   UpdateColors(hdc);
+               free_ctx(hdc);
            }
        }
        break;
@@ -1652,9 +1735,9 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
        if (pal != NULL) {
            HDC hdc = get_ctx();
            if (hdc) {
-               if (RealizePalette (hdc) > 0)
-                   UpdateColors (hdc);
-               free_ctx (hdc);
+               if (RealizePalette(hdc) > 0)
+                   UpdateColors(hdc);
+               free_ctx(hdc);
                return TRUE;
            }
        }
@@ -1667,7 +1750,7 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
         * Add the scan code and keypress timing to the random
         * number noise.
         */
-        noise_ultralight(lParam);
+       noise_ultralight(lParam);
 
        /*
         * We don't do TranslateMessage since it disassociates the
@@ -1680,21 +1763,21 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
            unsigned char buf[20];
            int len;
 
-            if (wParam==VK_PROCESSKEY) {
+           if (wParam == VK_PROCESSKEY) {
                MSG m;
-                m.hwnd = hwnd;
-                m.message = WM_KEYDOWN;
-                m.wParam = wParam;
-                m.lParam = lParam & 0xdfff;
-                TranslateMessage(&m);
-            } else {
-               len = TranslateKey (message, wParam, lParam, buf);
+               m.hwnd = hwnd;
+               m.message = WM_KEYDOWN;
+               m.wParam = wParam;
+               m.lParam = lParam & 0xdfff;
+               TranslateMessage(&m);
+           } else {
+               len = TranslateKey(message, wParam, lParam, buf);
                if (len == -1)
-                   return DefWindowProc (hwnd, message, wParam, lParam);
-               ldisc_send (buf, len);
+                   return DefWindowProc(hwnd, message, wParam, lParam);
+               ldisc_send(buf, len);
 
-                if (len > 0)
-                    show_mouseptr(0);
+               if (len > 0)
+                   show_mouseptr(0);
            }
        }
        return 0;
@@ -1704,7 +1787,7 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
 
            buf[1] = wParam;
            buf[0] = wParam >> 8;
-           ldisc_send (buf, 2);
+           ldisc_send(buf, 2);
        }
       case WM_CHAR:
       case WM_SYSCHAR:
@@ -1714,19 +1797,19 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
         * post the things to us as part of a macro manoeuvre,
         * we're ready to cope.
         */
-               {
-                   char c = xlat_kbd2tty((unsigned char)wParam);
-                   ldisc_send (&c, 1);
+       {
+           char c = xlat_kbd2tty((unsigned char) wParam);
+           ldisc_send(&c, 1);
        }
        return 0;
-               case WM_SETCURSOR:
-               if (send_raw_mouse) {
-                   SetCursor(LoadCursor(NULL, IDC_ARROW));
-                   return TRUE;
-               }
+      case WM_SETCURSOR:
+       if (send_raw_mouse) {
+           SetCursor(LoadCursor(NULL, IDC_ARROW));
+           return TRUE;
+       }
     }
 
-    return DefWindowProc (hwnd, message, wParam, lParam);
+    return DefWindowProc(hwnd, message, wParam, lParam);
 }
 
 /*
@@ -1735,7 +1818,8 @@ static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
  * helper software tracks the system caret, so we should arrange to
  * have one.)
  */
-void sys_cursor(int x, int y) {
+void sys_cursor(int x, int y)
+{
     if (has_focus)
        SetCaretPos(x * font_width, y * font_height);
 }
@@ -1746,24 +1830,25 @@ void sys_cursor(int x, int y) {
  *
  * We are allowed to fiddle with the contents of `text'.
  */
-void do_text (Context ctx, int x, int y, char *text, int len,
-             unsigned long attr, int lattr) {
+void do_text(Context ctx, int x, int y, char *text, int len,
+            unsigned long attr, int lattr)
+{
     COLORREF fg, bg, t;
     int nfg, nbg, nfont;
     HDC hdc = ctx;
     RECT line_box;
     int force_manual_underline = 0;
-    int fnt_width = font_width*(1+(lattr!=LATTR_NORM));
+    int fnt_width = font_width * (1 + (lattr != LATTR_NORM));
     static int *IpDx = 0, IpDxLEN = 0;;
 
-    if (len>IpDxLEN || IpDx[0] != fnt_width) {
+    if (len > IpDxLEN || IpDx[0] != fnt_width) {
        int i;
-       if (len>IpDxLEN) {
+       if (len > IpDxLEN) {
            sfree(IpDx);
-           IpDx = smalloc((len+16)*sizeof(int));
-           IpDxLEN = (len+16);
+           IpDx = smalloc((len + 16) * sizeof(int));
+           IpDxLEN = (len + 16);
        }
-       for(i=0; i<IpDxLEN; i++)
+       for (i = 0; i < IpDxLEN; i++)
            IpDx[i] = fnt_width;
     }
 
@@ -1786,24 +1871,23 @@ void do_text (Context ctx, int x, int y, char *text, int len,
      */
     if (nfont & FONT_OEM) {
        int i;
-       for (i=0; i<len; i++)
+       for (i = 0; i < len; i++)
            if (text[i] >= '\xA0' && text[i] <= '\xFF') {
 #if 0
                /* This is CP850 ... perfect translation */
-               static const char oemhighhalf[] =
-                   "\x20\xAD\xBD\x9C\xCF\xBE\xDD\xF5" /* A0-A7 */
-                   "\xF9\xB8\xA6\xAE\xAA\xF0\xA9\xEE" /* A8-AF */
-                   "\xF8\xF1\xFD\xFC\xEF\xE6\xF4\xFA" /* B0-B7 */
-                   "\xF7\xFB\xA7\xAF\xAC\xAB\xF3\xA8" /* B8-BF */
-                   "\xB7\xB5\xB6\xC7\x8E\x8F\x92\x80" /* C0-C7 */
-                   "\xD4\x90\xD2\xD3\xDE\xD6\xD7\xD8" /* C8-CF */
-                   "\xD1\xA5\xE3\xE0\xE2\xE5\x99\x9E" /* D0-D7 */
-                   "\x9D\xEB\xE9\xEA\x9A\xED\xE8\xE1" /* D8-DF */
-                   "\x85\xA0\x83\xC6\x84\x86\x91\x87" /* E0-E7 */
-                   "\x8A\x82\x88\x89\x8D\xA1\x8C\x8B" /* E8-EF */
-                   "\xD0\xA4\x95\xA2\x93\xE4\x94\xF6" /* F0-F7 */
-                   "\x9B\x97\xA3\x96\x81\xEC\xE7\x98" /* F8-FF */
-                   ;
+               static const char oemhighhalf[] = "\x20\xAD\xBD\x9C\xCF\xBE\xDD\xF5"    /* A0-A7 */
+                   "\xF9\xB8\xA6\xAE\xAA\xF0\xA9\xEE"  /* A8-AF */
+                   "\xF8\xF1\xFD\xFC\xEF\xE6\xF4\xFA"  /* B0-B7 */
+                   "\xF7\xFB\xA7\xAF\xAC\xAB\xF3\xA8"  /* B8-BF */
+                   "\xB7\xB5\xB6\xC7\x8E\x8F\x92\x80"  /* C0-C7 */
+                   "\xD4\x90\xD2\xD3\xDE\xD6\xD7\xD8"  /* C8-CF */
+                   "\xD1\xA5\xE3\xE0\xE2\xE5\x99\x9E"  /* D0-D7 */
+                   "\x9D\xEB\xE9\xEA\x9A\xED\xE8\xE1"  /* D8-DF */
+                   "\x85\xA0\x83\xC6\x84\x86\x91\x87"  /* E0-E7 */
+                   "\x8A\x82\x88\x89\x8D\xA1\x8C\x8B"  /* E8-EF */
+                   "\xD0\xA4\x95\xA2\x93\xE4\x94\xF6"  /* F0-F7 */
+                   "\x9B\x97\xA3\x96\x81\xEC\xE7\x98"  /* F8-FF */
+               ;
 #endif
                /* This is CP437 ... junk translation */
                static const unsigned char oemhighhalf[] = {
@@ -1821,7 +1905,7 @@ void do_text (Context ctx, int x, int y, char *text, int len,
                    0xed, 0x97, 0xa3, 0x96, 0x81, 0x79, 0x70, 0x98
                };
 
-               text[i] = oemhighhalf[(unsigned char)text[i] - 0xA0];
+               text[i] = oemhighhalf[(unsigned char) text[i] - 0xA0];
            }
     }
 
@@ -1854,24 +1938,24 @@ void do_text (Context ctx, int x, int y, char *text, int len,
         */
        switch (cfg.vtmode) {
          case VT_XWINDOWS:
-           for (i=0; i<len; i++)
+           for (i = 0; i < len; i++)
                if (text[i] >= '\x60' && text[i] <= '\x7E')
                    text[i] += '\x01' - '\x60';
            break;
          case VT_OEMANSI:
            /* Make sure we actually have an OEM font */
-           if (fonts[nfont|FONT_OEM]) { 
+           if (fonts[nfont | FONT_OEM]) {
          case VT_OEMONLY:
-               nfont |= FONT_OEM;
-               for (i=0; i<len; i++)
+               nfont |= FONT_OEM;
+               for (i = 0; i < len; i++)
                    if (text[i] >= '\x60' && text[i] <= '\x7E')
-                       text[i] = oemmap[(unsigned char)text[i] - 0x60];
-               break;
+                       text[i] = oemmap[(unsigned char) text[i] - 0x60];
+               break;
            }
          case VT_POORMAN:
-           for (i=0; i<len; i++)
+           for (i = 0; i < len; i++)
                if (text[i] >= '\x60' && text[i] <= '\x7E')
-                   text[i] = poorman[(unsigned char)text[i] - 0x60];
+                   text[i] = poorman[(unsigned char) text[i] - 0x60];
            break;
        }
     }
@@ -1882,18 +1966,19 @@ void do_text (Context ctx, int x, int y, char *text, int len,
        nfont |= FONT_BOLD;
     if (und_mode == UND_FONT && (attr & ATTR_UNDER))
        nfont |= FONT_UNDERLINE;
-    if (!fonts[nfont]) 
-    {
-       if (nfont&FONT_UNDERLINE)
+    if (!fonts[nfont]) {
+       if (nfont & FONT_UNDERLINE)
            force_manual_underline = 1;
        /* Don't do the same for manual bold, it could be bad news. */
 
-       nfont &= ~(FONT_BOLD|FONT_UNDERLINE);
+       nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
     }
     if (font_needs_hand_underlining && (attr & ATTR_UNDER))
-        force_manual_underline = 1;
+       force_manual_underline = 1;
     if (attr & ATTR_REVERSE) {
-       t = nfg; nfg = nbg; nbg = t;
+       t = nfg;
+       nfg = nbg;
+       nbg = t;
     }
     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
        nfg++;
@@ -1901,115 +1986,131 @@ void do_text (Context ctx, int x, int y, char *text, int len,
        nbg++;
     fg = colours[nfg];
     bg = colours[nbg];
-    SelectObject (hdc, fonts[nfont]);
-    SetTextColor (hdc, fg);
-    SetBkColor (hdc, bg);
-    SetBkMode (hdc, OPAQUE);
-    line_box.left   = x;
-    line_box.top    = y;
-    line_box.right  = x+fnt_width*len;
-    line_box.bottom = y+font_height;
-    ExtTextOut (hdc, x, y, ETO_CLIPPED|ETO_OPAQUE, &line_box, text, len, IpDx);
+    SelectObject(hdc, fonts[nfont]);
+    SetTextColor(hdc, fg);
+    SetBkColor(hdc, bg);
+    SetBkMode(hdc, OPAQUE);
+    line_box.left = x;
+    line_box.top = y;
+    line_box.right = x + fnt_width * len;
+    line_box.bottom = y + font_height;
+    ExtTextOut(hdc, x, y, ETO_CLIPPED | ETO_OPAQUE, &line_box, text, len,
+              IpDx);
     if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
-       SetBkMode (hdc, TRANSPARENT);
-
-       /* GRR: This draws the character outside it's box and can leave
-       * 'droppings' even with the clip box! I suppose I could loop it
-       * one character at a time ... yuk. 
-       * 
-       * Or ... I could do a test print with "W", and use +1 or -1 for this
-       * shift depending on if the leftmost column is blank...
-       */
-        ExtTextOut (hdc, x-1, y, ETO_CLIPPED, &line_box, text, len, IpDx);
+       SetBkMode(hdc, TRANSPARENT);
+
+       /* GRR: This draws the character outside it's box and can leave
+        * 'droppings' even with the clip box! I suppose I could loop it
+        * one character at a time ... yuk. 
+        
+        * Or ... I could do a test print with "W", and use +1 or -1 for this
+        * shift depending on if the leftmost column is blank...
+        */
+       ExtTextOut(hdc, x - 1, y, ETO_CLIPPED, &line_box, text, len, IpDx);
     }
-    if (force_manual_underline || 
-           (und_mode == UND_LINE && (attr & ATTR_UNDER))) {
-        HPEN oldpen;
-       oldpen = SelectObject (hdc, CreatePen(PS_SOLID, 0, fg));
-       MoveToEx (hdc, x, y+descent, NULL);
-       LineTo (hdc, x+len*fnt_width, y+descent);
-        oldpen = SelectObject (hdc, oldpen);
-        DeleteObject (oldpen);
+    if (force_manual_underline ||
+       (und_mode == UND_LINE && (attr & ATTR_UNDER))) {
+       HPEN oldpen;
+       oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
+       MoveToEx(hdc, x, y + descent, NULL);
+       LineTo(hdc, x + len * fnt_width, y + descent);
+       oldpen = SelectObject(hdc, oldpen);
+       DeleteObject(oldpen);
     }
     if ((attr & ATTR_PASCURS) && cfg.cursor_type == 0) {
        POINT pts[5];
-        HPEN oldpen;
+       HPEN oldpen;
        pts[0].x = pts[1].x = pts[4].x = x;
-       pts[2].x = pts[3].x = x+fnt_width-1;
+       pts[2].x = pts[3].x = x + fnt_width - 1;
        pts[0].y = pts[3].y = pts[4].y = y;
-       pts[1].y = pts[2].y = y+font_height-1;
-       oldpen = SelectObject (hdc, CreatePen(PS_SOLID, 0, colours[23]));
-       Polyline (hdc, pts, 5);
-        oldpen = SelectObject (hdc, oldpen);
-        DeleteObject (oldpen);
+       pts[1].y = pts[2].y = y + font_height - 1;
+       oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
+       Polyline(hdc, pts, 5);
+       oldpen = SelectObject(hdc, oldpen);
+       DeleteObject(oldpen);
     }
     if ((attr & (ATTR_ACTCURS | ATTR_PASCURS)) && cfg.cursor_type != 0) {
-        int startx, starty, dx, dy, length, i;
+       int startx, starty, dx, dy, length, i;
        if (cfg.cursor_type == 1) {
-            startx = x; starty = y+descent;
-            dx = 1; dy = 0; length = fnt_width;
-        } else {
+           startx = x;
+           starty = y + descent;
+           dx = 1;
+           dy = 0;
+           length = fnt_width;
+       } else {
            int xadjust = 0;
            if (attr & ATTR_RIGHTCURS)
-               xadjust = fnt_width-1;
-            startx = x+xadjust; starty = y;
-            dx = 0; dy = 1; length = font_height;
-       }
-        if (attr & ATTR_ACTCURS) {
-            HPEN oldpen;
-            oldpen = SelectObject (hdc, CreatePen(PS_SOLID, 0, colours[23]));
-            MoveToEx (hdc, startx, starty, NULL);
-            LineTo (hdc, startx+dx*length, starty+dy*length);
-            oldpen = SelectObject (hdc, oldpen);
-            DeleteObject (oldpen);
-        } else {
-            for (i = 0; i < length; i++) {
-                if (i % 2 == 0) {
-                    SetPixel(hdc, startx, starty, colours[23]);
-                }
-                startx += dx; starty += dy;
-            }
-        }
+               xadjust = fnt_width - 1;
+           startx = x + xadjust;
+           starty = y;
+           dx = 0;
+           dy = 1;
+           length = font_height;
+       }
+       if (attr & ATTR_ACTCURS) {
+           HPEN oldpen;
+           oldpen =
+               SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
+           MoveToEx(hdc, startx, starty, NULL);
+           LineTo(hdc, startx + dx * length, starty + dy * length);
+           oldpen = SelectObject(hdc, oldpen);
+           DeleteObject(oldpen);
+       } else {
+           for (i = 0; i < length; i++) {
+               if (i % 2 == 0) {
+                   SetPixel(hdc, startx, starty, colours[23]);
+               }
+               startx += dx;
+               starty += dy;
+           }
+       }
     }
 }
 
-static int check_compose(int first, int second) {
-
-    static char * composetbl[] = {
-       "++#", "AA@", "(([", "//\\", "))]", "(-{", "-)}", "/^|", "!!¡", "C/¢",
-       "C|¢", "L-£", "L=£", "XO¤", "X0¤", "Y-¥", "Y=¥", "||¦", "SO§", "S!§",
-       "S0§", "\"\"¨", "CO©", "C0©", "A_ª", "<<«", ",-¬", "--­", "RO®",
-       "-^¯", "0^°", "+-±", "2^²", "3^³", "''´", "/Uµ", "P!¶", ".^·", ",,¸",
-       "1^¹", "O_º", ">>»", "14¼", "12½", "34¾", "??¿", "`AÀ", "'AÁ", "^AÂ",
-       "~AÃ", "\"AÄ", "*AÅ", "AEÆ", ",CÇ", "`EÈ", "'EÉ", "^EÊ", "\"EË",
-       "`IÌ", "'IÍ", "^IÎ", "\"IÏ", "-DÐ", "~NÑ", "`OÒ", "'OÓ", "^OÔ",
-       "~OÕ", "\"OÖ", "XX×", "/OØ", "`UÙ", "'UÚ", "^UÛ", "\"UÜ", "'YÝ",
-       "HTÞ", "ssß", "`aà", "'aá", "^aâ", "~aã", "\"aä", "*aå", "aeæ", ",cç",
-       "`eè", "'eé", "^eê", "\"eë", "`iì", "'ií", "^iî", "\"iï", "-dð", "~nñ",
-       "`oò", "'oó", "^oô", "~oõ", "\"oö", ":-÷", "o/ø", "`uù", "'uú", "^uû",
-       "\"uü", "'yý", "htþ", "\"yÿ",
-    0};
-
-    char ** c;
+static int check_compose(int first, int second)
+{
+
+    static char *composetbl[] = {
+       "++#", "AA@", "(([", "//\\", "))]", "(-{", "-)}", "/^|", "!!¡",
+       "C/¢",
+       "C|¢", "L-£", "L=£", "XO¤", "X0¤", "Y-¥", "Y=¥", "||¦", "SO§",
+       "S!§",
+       "S0§", "\"\"¨", "CO©", "C0©", "A_ª", "<<«", ",-¬", "--­", "RO®",
+       "-^¯", "0^°", "+-±", "2^²", "3^³", "''´", "/Uµ", "P!¶", ".^·",
+       ",,¸",
+       "1^¹", "O_º", ">>»", "14¼", "12½", "34¾", "??¿", "`AÀ", "'AÁ",
+       "^AÂ",
+       "~AÃ", "\"AÄ", "*AÅ", "AEÆ", ",CÇ", "`EÈ", "'EÉ", "^EÊ", "\"EË",
+       "`IÌ", "'IÍ", "^IÎ", "\"IÏ", "-DÐ", "~NÑ", "`OÒ", "'OÓ", "^OÔ",
+       "~OÕ", "\"OÖ", "XX×", "/OØ", "`UÙ", "'UÚ", "^UÛ", "\"UÜ", "'YÝ",
+       "HTÞ", "ssß", "`aà", "'aá", "^aâ", "~aã", "\"aä", "*aå", "aeæ",
+       ",cç",
+       "`eè", "'eé", "^eê", "\"eë", "`iì", "'ií", "^iî", "\"iï", "-dð",
+       "~nñ",
+       "`oò", "'oó", "^oô", "~oõ", "\"oö", ":-÷", "o/ø", "`uù", "'uú",
+       "^uû",
+       "\"uü", "'yý", "htþ", "\"yÿ",
+       0
+    };
+
+    char **c;
     static int recurse = 0;
     int nc = -1;
 
-    for(c=composetbl; *c; c++) {
-       if( (*c)[0] == first && (*c)[1] == second)
-       {
+    for (c = composetbl; *c; c++) {
+       if ((*c)[0] == first && (*c)[1] == second) {
            return (*c)[2] & 0xFF;
        }
     }
 
-    if(recurse==0)
-    {
-       recurse=1;
+    if (recurse == 0) {
+       recurse = 1;
        nc = check_compose(second, first);
-       if(nc == -1)
+       if (nc == -1)
            nc = check_compose(toupper(first), toupper(second));
-       if(nc == -1)
+       if (nc == -1)
            nc = check_compose(toupper(second), toupper(first));
-       recurse=0;
+       recurse = 0;
     }
     return nc;
 }
@@ -2021,11 +2122,12 @@ static int check_compose(int first, int second) {
  * or -1 to forward the message to windows.
  */
 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
-                       unsigned char *output) {
+                       unsigned char *output)
+{
     BYTE keystate[256];
-    int  scan, left_alt = 0, key_down, shift_state;
-    int  r, i, code;
-    unsigned char * p = output;
+    int scan, left_alt = 0, key_down, shift_state;
+    int r, i, code;
+    unsigned char *p = output;
     static int alt_state = 0;
 
     HKL kbd_layout = GetKeyboardLayout(0);
@@ -2033,100 +2135,117 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
     static WORD keys[3];
     static int compose_char = 0;
     static WPARAM compose_key = 0;
-    
+
     r = GetKeyboardState(keystate);
-    if (!r) memset(keystate, 0, sizeof(keystate));
-    else
-    {
+    if (!r)
+       memset(keystate, 0, sizeof(keystate));
+    else {
 #if 0
-       {  /* Tell us all about key events */
-         static BYTE oldstate[256];
-         static int first = 1;
-         static int scan;
-         int ch;
-         if(first) memcpy(oldstate, keystate, sizeof(oldstate));
-         first=0;
-
-         if ((HIWORD(lParam)&(KF_UP|KF_REPEAT))==KF_REPEAT) {
-            debug(("+"));
-         } else if ((HIWORD(lParam)&KF_UP) && scan==(HIWORD(lParam) & 0xFF) ) {
-            debug((". U"));
-         } else {
-            debug((".\n"));
-            if (wParam >= VK_F1 && wParam <= VK_F20 )
-               debug(("K_F%d", wParam+1-VK_F1));
-            else switch(wParam)
-            {
-            case VK_SHIFT:   debug(("SHIFT")); break;
-            case VK_CONTROL: debug(("CTRL")); break;
-            case VK_MENU:    debug(("ALT")); break;
-            default:         debug(("VK_%02x", wParam));
-            }
-            if(message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
-               debug(("*"));
-            debug((", S%02x", scan=(HIWORD(lParam) & 0xFF) ));
-
-            ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
-            if (ch>=' ' && ch<='~') debug((", '%c'", ch));
-            else if (ch)            debug((", $%02x", ch));
-
-            if (keys[0]) debug((", KB0=%02x", keys[0]));
-            if (keys[1]) debug((", KB1=%02x", keys[1]));
-            if (keys[2]) debug((", KB2=%02x", keys[2]));
-
-            if ( (keystate[VK_SHIFT]&0x80)!=0)     debug((", S"));
-            if ( (keystate[VK_CONTROL]&0x80)!=0)   debug((", C"));
-            if ( (HIWORD(lParam)&KF_EXTENDED) )    debug((", E"));
-            if ( (HIWORD(lParam)&KF_UP) )          debug((", U"));
-         }
-
-         if ((HIWORD(lParam)&(KF_UP|KF_REPEAT))==KF_REPEAT)
-            ;
-         else if ( (HIWORD(lParam)&KF_UP) ) 
-            oldstate[wParam&0xFF] ^= 0x80;
-         else
-            oldstate[wParam&0xFF] ^= 0x81;
-
-         for(ch=0; ch<256; ch++)
-            if (oldstate[ch] != keystate[ch])
-               debug((", M%02x=%02x", ch, keystate[ch]));
-
-         memcpy(oldstate, keystate, sizeof(oldstate));
-       }
+       {                              /* Tell us all about key events */
+           static BYTE oldstate[256];
+           static int first = 1;
+           static int scan;
+           int ch;
+           if (first)
+               memcpy(oldstate, keystate, sizeof(oldstate));
+           first = 0;
+
+           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
+               debug(("+"));
+           } else if ((HIWORD(lParam) & KF_UP)
+                      && scan == (HIWORD(lParam) & 0xFF)) {
+               debug((". U"));
+           } else {
+               debug((".\n"));
+               if (wParam >= VK_F1 && wParam <= VK_F20)
+                   debug(("K_F%d", wParam + 1 - VK_F1));
+               else
+                   switch (wParam) {
+                     case VK_SHIFT:
+                       debug(("SHIFT"));
+                       break;
+                     case VK_CONTROL:
+                       debug(("CTRL"));
+                       break;
+                     case VK_MENU:
+                       debug(("ALT"));
+                       break;
+                     default:
+                       debug(("VK_%02x", wParam));
+                   }
+               if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
+                   debug(("*"));
+               debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
+
+               ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
+               if (ch >= ' ' && ch <= '~')
+                   debug((", '%c'", ch));
+               else if (ch)
+                   debug((", $%02x", ch));
+
+               if (keys[0])
+                   debug((", KB0=%02x", keys[0]));
+               if (keys[1])
+                   debug((", KB1=%02x", keys[1]));
+               if (keys[2])
+                   debug((", KB2=%02x", keys[2]));
+
+               if ((keystate[VK_SHIFT] & 0x80) != 0)
+                   debug((", S"));
+               if ((keystate[VK_CONTROL] & 0x80) != 0)
+                   debug((", C"));
+               if ((HIWORD(lParam) & KF_EXTENDED))
+                   debug((", E"));
+               if ((HIWORD(lParam) & KF_UP))
+                   debug((", U"));
+           }
+
+           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
+           else if ((HIWORD(lParam) & KF_UP))
+               oldstate[wParam & 0xFF] ^= 0x80;
+           else
+               oldstate[wParam & 0xFF] ^= 0x81;
+
+           for (ch = 0; ch < 256; ch++)
+               if (oldstate[ch] != keystate[ch])
+                   debug((", M%02x=%02x", ch, keystate[ch]));
+
+           memcpy(oldstate, keystate, sizeof(oldstate));
+       }
 #endif
 
-       if (wParam == VK_MENU && (HIWORD(lParam)&KF_EXTENDED)) {
+       if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
            keystate[VK_RMENU] = keystate[VK_MENU];
        }
 
 
        /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
-       if ( (cfg.funky_type == 3 ||
-              (cfg.funky_type <= 1 && app_keypad_keys && !cfg.no_applic_k))
-             && wParam==VK_NUMLOCK && !(keystate[VK_SHIFT]&0x80)) {
+       if ((cfg.funky_type == 3 ||
+            (cfg.funky_type <= 1 && app_keypad_keys && !cfg.no_applic_k))
+           && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
 
            wParam = VK_EXECUTE;
 
            /* UnToggle NUMLock */
-            if ((HIWORD(lParam)&(KF_UP|KF_REPEAT))==0)
-               keystate[VK_NUMLOCK] ^= 1;
+           if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
+               keystate[VK_NUMLOCK] ^= 1;
        }
 
        /* And write back the 'adjusted' state */
-       SetKeyboardState (keystate);
+       SetKeyboardState(keystate);
     }
 
     /* Disable Auto repeat if required */
-    if (repeat_off && (HIWORD(lParam)&(KF_UP|KF_REPEAT))==KF_REPEAT)
-       return 0;
+    if (repeat_off && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
+       return 0;
 
-    if ((HIWORD(lParam)&KF_ALTDOWN) && (keystate[VK_RMENU]&0x80) == 0)
+    if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
        left_alt = 1;
 
-    key_down = ((HIWORD(lParam)&KF_UP)==0);
+    key_down = ((HIWORD(lParam) & KF_UP) == 0);
 
     /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
-    if (left_alt && (keystate[VK_CONTROL]&0x80)) {
+    if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
        if (cfg.ctrlaltkeys)
            keystate[VK_MENU] = 0;
        else {
@@ -2136,103 +2255,123 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
     }
 
     scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
-    shift_state = ((keystate[VK_SHIFT]&0x80)!=0)
-                + ((keystate[VK_CONTROL]&0x80)!=0)*2;
+    shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
+       + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
 
     /* Note if AltGr was pressed and if it was used as a compose key */
     if (!compose_state) {
        compose_key = 0x100;
        if (cfg.compose_key) {
-           if (wParam == VK_MENU && (HIWORD(lParam)&KF_EXTENDED))
+           if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
                compose_key = wParam;
        }
        if (wParam == VK_APPS)
            compose_key = wParam;
     }
 
-    if (wParam == compose_key)
-    {
-       if (compose_state == 0 && (HIWORD(lParam)&(KF_UP|KF_REPEAT))==0)
-           compose_state = 1;
-       else if (compose_state == 1 && (HIWORD(lParam)&KF_UP))
+    if (wParam == compose_key) {
+       if (compose_state == 0
+           && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
+               1;
+       else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
            compose_state = 2;
        else
            compose_state = 0;
-    }
-    else if (compose_state==1 && wParam != VK_CONTROL)
+    } else if (compose_state == 1 && wParam != VK_CONTROL)
        compose_state = 0;
 
     /* 
      * Record that we pressed key so the scroll window can be reset, but
      * be careful to avoid Shift-UP/Down
      */
-    if( wParam != VK_SHIFT && wParam != VK_PRIOR && wParam != VK_NEXT ) {
-        seen_key_event = 1; 
+    if (wParam != VK_SHIFT && wParam != VK_PRIOR && wParam != VK_NEXT) {
+       seen_key_event = 1;
     }
 
     /* Make sure we're not pasting */
-    if (key_down) term_nopaste();
+    if (key_down)
+       term_nopaste();
 
-    if (compose_state>1 && left_alt) compose_state = 0;
+    if (compose_state > 1 && left_alt)
+       compose_state = 0;
 
     /* Sanitize the number pad if not using a PC NumPad */
-    if( left_alt || (app_keypad_keys && !cfg.no_applic_k
-                     && cfg.funky_type != 2)
-       || cfg.funky_type == 3 || cfg.nethack_keypad || compose_state )
-    {
-       if ((HIWORD(lParam)&KF_EXTENDED) == 0)
-       {
+    if (left_alt || (app_keypad_keys && !cfg.no_applic_k
+                    && cfg.funky_type != 2)
+       || cfg.funky_type == 3 || cfg.nethack_keypad || compose_state) {
+       if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
            int nParam = 0;
-           switch(wParam)
-           {
-           case VK_INSERT:     nParam = VK_NUMPAD0; break;
-           case VK_END:        nParam = VK_NUMPAD1; break;
-           case VK_DOWN:       nParam = VK_NUMPAD2; break;
-           case VK_NEXT:       nParam = VK_NUMPAD3; break;
-           case VK_LEFT:       nParam = VK_NUMPAD4; break;
-           case VK_CLEAR:      nParam = VK_NUMPAD5; break;
-           case VK_RIGHT:      nParam = VK_NUMPAD6; break;
-           case VK_HOME:       nParam = VK_NUMPAD7; break;
-           case VK_UP:         nParam = VK_NUMPAD8; break;
-           case VK_PRIOR:      nParam = VK_NUMPAD9; break;
-           case VK_DELETE:     nParam = VK_DECIMAL; break;
+           switch (wParam) {
+             case VK_INSERT:
+               nParam = VK_NUMPAD0;
+               break;
+             case VK_END:
+               nParam = VK_NUMPAD1;
+               break;
+             case VK_DOWN:
+               nParam = VK_NUMPAD2;
+               break;
+             case VK_NEXT:
+               nParam = VK_NUMPAD3;
+               break;
+             case VK_LEFT:
+               nParam = VK_NUMPAD4;
+               break;
+             case VK_CLEAR:
+               nParam = VK_NUMPAD5;
+               break;
+             case VK_RIGHT:
+               nParam = VK_NUMPAD6;
+               break;
+             case VK_HOME:
+               nParam = VK_NUMPAD7;
+               break;
+             case VK_UP:
+               nParam = VK_NUMPAD8;
+               break;
+             case VK_PRIOR:
+               nParam = VK_NUMPAD9;
+               break;
+             case VK_DELETE:
+               nParam = VK_DECIMAL;
+               break;
            }
-           if (nParam)
-           {
-               if (keystate[VK_NUMLOCK]&1) shift_state |= 1;
+           if (nParam) {
+               if (keystate[VK_NUMLOCK] & 1)
+                   shift_state |= 1;
                wParam = nParam;
            }
        }
     }
 
     /* If a key is pressed and AltGr is not active */
-    if (key_down && (keystate[VK_RMENU]&0x80) == 0 && !compose_state)
-    {
-       /* Okay, prepare for most alts then ...*/
-       if (left_alt) *p++ = '\033';
+    if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
+       /* Okay, prepare for most alts then ... */
+       if (left_alt)
+           *p++ = '\033';
 
        /* Lets see if it's a pattern we know all about ... */
        if (wParam == VK_PRIOR && shift_state == 1) {
-            SendMessage (hwnd, WM_VSCROLL, SB_PAGEUP, 0);
-            return 0;
+           SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
+           return 0;
        }
        if (wParam == VK_NEXT && shift_state == 1) {
-            SendMessage (hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
-            return 0;
-       }
-        if (wParam == VK_INSERT && shift_state == 1) {
-            term_mouse (MBT_PASTE, MA_CLICK, 0, 0, 0, 0);
-            term_mouse (MBT_PASTE, MA_RELEASE, 0, 0, 0, 0);
-            return 0;
-        }
+           SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
+           return 0;
+       }
+       if (wParam == VK_INSERT && shift_state == 1) {
+           term_mouse(MBT_PASTE, MA_CLICK, 0, 0, 0, 0);
+           term_mouse(MBT_PASTE, MA_RELEASE, 0, 0, 0, 0);
+           return 0;
+       }
        if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
-            return -1;
+           return -1;
        }
        if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
            alt_state = 0;
-            PostMessage(hwnd, WM_CHAR, ' ', 0);
-            SendMessage (hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
-            return -1;
+           PostMessage(hwnd, WM_CHAR, ' ', 0);
+           SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
+           return -1;
        }
        /* Control-Numlock for app-keypad mode switch */
        if (wParam == VK_PAUSE && shift_state == 2) {
@@ -2242,104 +2381,165 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
 
        /* Nethack keypad */
        if (cfg.nethack_keypad && !left_alt) {
-          switch(wParam) {
-              case VK_NUMPAD1: *p++ = shift_state ? 'B': 'b'; return p-output;
-              case VK_NUMPAD2: *p++ = shift_state ? 'J': 'j'; return p-output;
-              case VK_NUMPAD3: *p++ = shift_state ? 'N': 'n'; return p-output;
-              case VK_NUMPAD4: *p++ = shift_state ? 'H': 'h'; return p-output;
-              case VK_NUMPAD5: *p++ = shift_state ? '.': '.'; return p-output;
-              case VK_NUMPAD6: *p++ = shift_state ? 'L': 'l'; return p-output;
-              case VK_NUMPAD7: *p++ = shift_state ? 'Y': 'y'; return p-output;
-              case VK_NUMPAD8: *p++ = shift_state ? 'K': 'k'; return p-output;
-              case VK_NUMPAD9: *p++ = shift_state ? 'U': 'u'; return p-output;
-          }
+           switch (wParam) {
+             case VK_NUMPAD1:
+               *p++ = shift_state ? 'B' : 'b';
+               return p - output;
+             case VK_NUMPAD2:
+               *p++ = shift_state ? 'J' : 'j';
+               return p - output;
+             case VK_NUMPAD3:
+               *p++ = shift_state ? 'N' : 'n';
+               return p - output;
+             case VK_NUMPAD4:
+               *p++ = shift_state ? 'H' : 'h';
+               return p - output;
+             case VK_NUMPAD5:
+               *p++ = shift_state ? '.' : '.';
+               return p - output;
+             case VK_NUMPAD6:
+               *p++ = shift_state ? 'L' : 'l';
+               return p - output;
+             case VK_NUMPAD7:
+               *p++ = shift_state ? 'Y' : 'y';
+               return p - output;
+             case VK_NUMPAD8:
+               *p++ = shift_state ? 'K' : 'k';
+               return p - output;
+             case VK_NUMPAD9:
+               *p++ = shift_state ? 'U' : 'u';
+               return p - output;
+           }
        }
 
        /* Application Keypad */
        if (!left_alt) {
-          int xkey = 0;
-
-          if ( cfg.funky_type == 3 ||
-             ( cfg.funky_type <= 1 &&
-               app_keypad_keys && !cfg.no_applic_k)) switch(wParam) {
-              case VK_EXECUTE: xkey = 'P'; break;
-              case VK_DIVIDE:  xkey = 'Q'; break;
-              case VK_MULTIPLY:xkey = 'R'; break;
-              case VK_SUBTRACT:xkey = 'S'; break;
-          }
-          if(app_keypad_keys && !cfg.no_applic_k) switch(wParam) {
-              case VK_NUMPAD0: xkey = 'p'; break;
-              case VK_NUMPAD1: xkey = 'q'; break;
-              case VK_NUMPAD2: xkey = 'r'; break;
-              case VK_NUMPAD3: xkey = 's'; break;
-              case VK_NUMPAD4: xkey = 't'; break;
-              case VK_NUMPAD5: xkey = 'u'; break;
-              case VK_NUMPAD6: xkey = 'v'; break;
-              case VK_NUMPAD7: xkey = 'w'; break;
-              case VK_NUMPAD8: xkey = 'x'; break;
-              case VK_NUMPAD9: xkey = 'y'; break;
-
-              case VK_DECIMAL: xkey = 'n'; break;
-              case VK_ADD:     if(cfg.funky_type==2) { 
-                                   if(shift_state) xkey = 'l';
-                                   else            xkey = 'k';
-                               } else if(shift_state)  xkey = 'm'; 
-                                 else                  xkey = 'l';
-                               break;
-
-              case VK_DIVIDE:  if(cfg.funky_type==2) xkey = 'o'; break;
-              case VK_MULTIPLY:if(cfg.funky_type==2) xkey = 'j'; break;
-              case VK_SUBTRACT:if(cfg.funky_type==2) xkey = 'm'; break;
-
-              case VK_RETURN:
-                               if (HIWORD(lParam)&KF_EXTENDED)
-                                   xkey = 'M';
-                               break;
-           }
-           if(xkey)
-           {
-               if (vt52_mode)
-               {
-                   if (xkey>='P' && xkey<='S')
-                       p += sprintf((char *)p, "\x1B%c", xkey); 
+           int xkey = 0;
+
+           if (cfg.funky_type == 3 ||
+               (cfg.funky_type <= 1 &&
+                app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
+                 case VK_EXECUTE:
+                   xkey = 'P';
+                   break;
+                 case VK_DIVIDE:
+                   xkey = 'Q';
+                   break;
+                 case VK_MULTIPLY:
+                   xkey = 'R';
+                   break;
+                 case VK_SUBTRACT:
+                   xkey = 'S';
+                   break;
+               }
+           if (app_keypad_keys && !cfg.no_applic_k)
+               switch (wParam) {
+                 case VK_NUMPAD0:
+                   xkey = 'p';
+                   break;
+                 case VK_NUMPAD1:
+                   xkey = 'q';
+                   break;
+                 case VK_NUMPAD2:
+                   xkey = 'r';
+                   break;
+                 case VK_NUMPAD3:
+                   xkey = 's';
+                   break;
+                 case VK_NUMPAD4:
+                   xkey = 't';
+                   break;
+                 case VK_NUMPAD5:
+                   xkey = 'u';
+                   break;
+                 case VK_NUMPAD6:
+                   xkey = 'v';
+                   break;
+                 case VK_NUMPAD7:
+                   xkey = 'w';
+                   break;
+                 case VK_NUMPAD8:
+                   xkey = 'x';
+                   break;
+                 case VK_NUMPAD9:
+                   xkey = 'y';
+                   break;
+
+                 case VK_DECIMAL:
+                   xkey = 'n';
+                   break;
+                 case VK_ADD:
+                   if (cfg.funky_type == 2) {
+                       if (shift_state)
+                           xkey = 'l';
+                       else
+                           xkey = 'k';
+                   } else if (shift_state)
+                       xkey = 'm';
                    else
-                       p += sprintf((char *)p, "\x1B?%c", xkey); 
+                       xkey = 'l';
+                   break;
+
+                 case VK_DIVIDE:
+                   if (cfg.funky_type == 2)
+                       xkey = 'o';
+                   break;
+                 case VK_MULTIPLY:
+                   if (cfg.funky_type == 2)
+                       xkey = 'j';
+                   break;
+                 case VK_SUBTRACT:
+                   if (cfg.funky_type == 2)
+                       xkey = 'm';
+                   break;
+
+                 case VK_RETURN:
+                   if (HIWORD(lParam) & KF_EXTENDED)
+                       xkey = 'M';
+                   break;
                }
-               else 
-                   p += sprintf((char *)p, "\x1BO%c", xkey); 
-               return p - output;
+           if (xkey) {
+               if (vt52_mode) {
+                   if (xkey >= 'P' && xkey <= 'S')
+                       p += sprintf((char *) p, "\x1B%c", xkey);
+                   else
+                       p += sprintf((char *) p, "\x1B?%c", xkey);
+               } else
+                   p += sprintf((char *) p, "\x1BO%c", xkey);
+               return p - output;
            }
        }
 
-       if (wParam == VK_BACK && shift_state == 0 )     /* Backspace */
-       {
+       if (wParam == VK_BACK && shift_state == 0) {    /* Backspace */
            *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
-           return p-output;
+           return p - output;
        }
-       if (wParam == VK_TAB && shift_state == 1 )      /* Shift tab */
-       {
-           *p++ = 0x1B; *p++ = '['; *p++ = 'Z'; return p - output;
+       if (wParam == VK_TAB && shift_state == 1) {     /* Shift tab */
+           *p++ = 0x1B;
+           *p++ = '[';
+           *p++ = 'Z';
+           return p - output;
        }
-       if (wParam == VK_SPACE && shift_state == 2 )    /* Ctrl-Space */
-       {
-           *p++ = 0; return p - output;
+       if (wParam == VK_SPACE && shift_state == 2) {   /* Ctrl-Space */
+           *p++ = 0;
+           return p - output;
        }
-       if (wParam == VK_SPACE && shift_state == 3 )    /* Ctrl-Shift-Space */
-       {
-           *p++ = 160; return p - output;
+       if (wParam == VK_SPACE && shift_state == 3) {   /* Ctrl-Shift-Space */
+           *p++ = 160;
+           return p - output;
        }
-       if (wParam == VK_CANCEL && shift_state == 2 )   /* Ctrl-Break */
-       {
-           *p++ = 3; return p - output;
+       if (wParam == VK_CANCEL && shift_state == 2) {  /* Ctrl-Break */
+           *p++ = 3;
+           return p - output;
        }
-       if (wParam == VK_PAUSE)                         /* Break/Pause */
-       {
-           *p++ = 26; *p++ = 0; return -2;
+       if (wParam == VK_PAUSE) {      /* Break/Pause */
+           *p++ = 26;
+           *p++ = 0;
+           return -2;
        }
        /* Control-2 to Control-8 are special */
-       if (shift_state == 2 && wParam >= '2' && wParam <= '8')
-       {
-           *p++ = "\000\033\034\035\036\037\177"[wParam-'2'];
+       if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
+           *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
            return p - output;
        }
        if (shift_state == 2 && wParam == 0xBD) {
@@ -2351,7 +2551,8 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
            return p - output;
        }
        if (shift_state == 0 && wParam == VK_RETURN && cr_lf_return) {
-           *p++ = '\r'; *p++ = '\n';
+           *p++ = '\r';
+           *p++ = '\n';
            return p - output;
        }
 
@@ -2366,71 +2567,128 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
         */
        code = 0;
        switch (wParam) {
-         case VK_F1: code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11); break;
-         case VK_F2: code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12); break;
-         case VK_F3: code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13); break;
-         case VK_F4: code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14); break;
-         case VK_F5: code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15); break;
-         case VK_F6: code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17); break;
-         case VK_F7: code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18); break;
-         case VK_F8: code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19); break;
-         case VK_F9: code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20); break;
-         case VK_F10: code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21); break;
-         case VK_F11: code = 23; break;
-         case VK_F12: code = 24; break;
-         case VK_F13: code = 25; break;
-         case VK_F14: code = 26; break;
-         case VK_F15: code = 28; break;
-         case VK_F16: code = 29; break;
-         case VK_F17: code = 31; break;
-         case VK_F18: code = 32; break;
-         case VK_F19: code = 33; break;
-         case VK_F20: code = 34; break;
-         case VK_HOME: code = 1; break;
-         case VK_INSERT: code = 2; break;
-         case VK_DELETE: code = 3; break;
-         case VK_END: code = 4; break;
-         case VK_PRIOR: code = 5; break;
-         case VK_NEXT: code = 6; break;
+         case VK_F1:
+           code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
+           break;
+         case VK_F2:
+           code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
+           break;
+         case VK_F3:
+           code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
+           break;
+         case VK_F4:
+           code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
+           break;
+         case VK_F5:
+           code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
+           break;
+         case VK_F6:
+           code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
+           break;
+         case VK_F7:
+           code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
+           break;
+         case VK_F8:
+           code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
+           break;
+         case VK_F9:
+           code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
+           break;
+         case VK_F10:
+           code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
+           break;
+         case VK_F11:
+           code = 23;
+           break;
+         case VK_F12:
+           code = 24;
+           break;
+         case VK_F13:
+           code = 25;
+           break;
+         case VK_F14:
+           code = 26;
+           break;
+         case VK_F15:
+           code = 28;
+           break;
+         case VK_F16:
+           code = 29;
+           break;
+         case VK_F17:
+           code = 31;
+           break;
+         case VK_F18:
+           code = 32;
+           break;
+         case VK_F19:
+           code = 33;
+           break;
+         case VK_F20:
+           code = 34;
+           break;
+         case VK_HOME:
+           code = 1;
+           break;
+         case VK_INSERT:
+           code = 2;
+           break;
+         case VK_DELETE:
+           code = 3;
+           break;
+         case VK_END:
+           code = 4;
+           break;
+         case VK_PRIOR:
+           code = 5;
+           break;
+         case VK_NEXT:
+           code = 6;
+           break;
        }
        /* Reorder edit keys to physical order */
-       if (cfg.funky_type == 3 && code <= 6 ) code = "\0\2\1\4\5\3\6"[code];
+       if (cfg.funky_type == 3 && code <= 6)
+           code = "\0\2\1\4\5\3\6"[code];
 
        if (vt52_mode && code > 0 && code <= 6) {
-           p += sprintf((char *)p, "\x1B%c", " HLMEIG"[code]);
+           p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
            return p - output;
        }
 
        if (cfg.funky_type == 5 && code >= 11 && code <= 24) {
-           p += sprintf((char *)p, "\x1B[%c", code + 'M' - 11);
+           p += sprintf((char *) p, "\x1B[%c", code + 'M' - 11);
            return p - output;
        }
        if ((vt52_mode || cfg.funky_type == 4) && code >= 11 && code <= 24) {
            int offt = 0;
-           if (code>15) offt++; if (code>21) offt++;
+           if (code > 15)
+               offt++;
+           if (code > 21)
+               offt++;
            if (vt52_mode)
-               p += sprintf((char *)p, "\x1B%c", code + 'P' - 11 - offt);
+               p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
            else
-               p += sprintf((char *)p, "\x1BO%c", code + 'P' - 11 - offt);
+               p +=
+                   sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
            return p - output;
        }
        if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
-           p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
+           p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
            return p - output;
        }
        if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
            if (vt52_mode)
-               p += sprintf((char *)p, "\x1B%c", code + 'P' - 11);
+               p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
            else
-               p += sprintf((char *)p, "\x1BO%c", code + 'P' - 11);
+               p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
            return p - output;
        }
        if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
-           p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
+           p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
            return p - output;
        }
        if (code) {
-           p += sprintf((char *)p, "\x1B[%d~", code);
+           p += sprintf((char *) p, "\x1B[%d~", code);
            return p - output;
        }
 
@@ -2441,20 +2699,29 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
        {
            char xkey = 0;
            switch (wParam) {
-               case VK_UP:     xkey = 'A'; break;
-               case VK_DOWN:   xkey = 'B'; break;
-               case VK_RIGHT:  xkey = 'C'; break;
-               case VK_LEFT:   xkey = 'D'; break;
-               case VK_CLEAR:  xkey = 'G'; break;
+             case VK_UP:
+               xkey = 'A';
+               break;
+             case VK_DOWN:
+               xkey = 'B';
+               break;
+             case VK_RIGHT:
+               xkey = 'C';
+               break;
+             case VK_LEFT:
+               xkey = 'D';
+               break;
+             case VK_CLEAR:
+               xkey = 'G';
+               break;
            }
-           if (xkey)
-           {
+           if (xkey) {
                if (vt52_mode)
-                   p += sprintf((char *)p, "\x1B%c", xkey);
+                   p += sprintf((char *) p, "\x1B%c", xkey);
                else if (app_cursor_keys && !cfg.no_applic_c)
-                   p += sprintf((char *)p, "\x1BO%c", xkey);
+                   p += sprintf((char *) p, "\x1BO%c", xkey);
                else
-                   p += sprintf((char *)p, "\x1B[%c", xkey);
+                   p += sprintf((char *) p, "\x1B[%c", xkey);
                return p - output;
            }
        }
@@ -2463,107 +2730,108 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
         * Finally, deal with Return ourselves. (Win95 seems to
         * foul it up when Alt is pressed, for some reason.)
         */
-       if (wParam == VK_RETURN)       /* Return */
-       {
+       if (wParam == VK_RETURN) {     /* Return */
            *p++ = 0x0D;
-           return p-output;
+           return p - output;
        }
     }
 
     /* Okay we've done everything interesting; let windows deal with 
      * the boring stuff */
     {
-       BOOL capsOn=keystate[VK_CAPITAL] !=0;
+       BOOL capsOn = keystate[VK_CAPITAL] != 0;
 
        /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
-       if(cfg.xlat_capslockcyr)
+       if (cfg.xlat_capslockcyr)
            keystate[VK_CAPITAL] = 0;
 
        r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
-       if(r>0)
-       {
+       if (r > 0) {
            p = output;
-           for(i=0; i<r; i++)
-           {
-               unsigned char ch = (unsigned char)keys[i];
+           for (i = 0; i < r; i++) {
+               unsigned char ch = (unsigned char) keys[i];
 
-               if (compose_state==2 && (ch&0x80) == 0 && ch>' ') {
+               if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
                    compose_char = ch;
-                   compose_state ++;
+                   compose_state++;
                    continue;
                }
-               if (compose_state==3 && (ch&0x80) == 0 && ch>' ') {
+               if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
                    int nc;
                    compose_state = 0;
 
-                   if ((nc=check_compose(compose_char,ch)) == -1)
-                   {
+                   if ((nc = check_compose(compose_char, ch)) == -1) {
                        MessageBeep(MB_ICONHAND);
                        return 0;
                    }
-                   *p++ = xlat_kbd2tty((unsigned char)nc);
-                   return p-output;
+                   *p++ = xlat_kbd2tty((unsigned char) nc);
+                   return p - output;
                }
 
                compose_state = 0;
 
-               if( left_alt && key_down ) *p++ = '\033';
+               if (left_alt && key_down)
+                   *p++ = '\033';
                if (!key_down)
                    *p++ = ch;
-               else
-               {
-                   if(capsOn)
+               else {
+                   if (capsOn)
                        ch = xlat_latkbd2win(ch);
-                   *p++ = xlat_kbd2tty(ch);
+                   *p++ = xlat_kbd2tty(ch);
                }
            }
 
            /* This is so the ALT-Numpad and dead keys work correctly. */
            keys[0] = 0;
 
-           return p-output;
+           return p - output;
        }
        /* If we're definitly not building up an ALT-54321 then clear it */
-       if (!left_alt) keys[0] = 0;
+       if (!left_alt)
+           keys[0] = 0;
     }
 
     /* ALT alone may or may not want to bring up the System menu */
     if (wParam == VK_MENU) {
-        if (cfg.alt_only) {
-            if (message == WM_SYSKEYDOWN)
-                alt_state = 1;
-            else if (message == WM_SYSKEYUP && alt_state)
-                PostMessage(hwnd, WM_CHAR, ' ', 0);
-            if (message == WM_SYSKEYUP)
-                alt_state = 0;
-        } else
+       if (cfg.alt_only) {
+           if (message == WM_SYSKEYDOWN)
+               alt_state = 1;
+           else if (message == WM_SYSKEYUP && alt_state)
+               PostMessage(hwnd, WM_CHAR, ' ', 0);
+           if (message == WM_SYSKEYUP)
+               alt_state = 0;
+       } else
            return 0;
-    }
-    else alt_state = 0;
+    } else
+       alt_state = 0;
 
     return -1;
 }
 
-void set_title (char *title) {
-    sfree (window_name);
-    window_name = smalloc(1+strlen(title));
-    strcpy (window_name, title);
+void set_title(char *title)
+{
+    sfree(window_name);
+    window_name = smalloc(1 + strlen(title));
+    strcpy(window_name, title);
     if (cfg.win_name_always || !IsIconic(hwnd))
-       SetWindowText (hwnd, title);
+       SetWindowText(hwnd, title);
 }
 
-void set_icon (char *title) {
-    sfree (icon_name);
-    icon_name = smalloc(1+strlen(title));
-    strcpy (icon_name, title);
+void set_icon(char *title)
+{
+    sfree(icon_name);
+    icon_name = smalloc(1 + strlen(title));
+    strcpy(icon_name, title);
     if (!cfg.win_name_always && IsIconic(hwnd))
-       SetWindowText (hwnd, title);
+       SetWindowText(hwnd, title);
 }
 
-void set_sbar (int total, int start, int page) {
+void set_sbar(int total, int start, int page)
+{
     SCROLLINFO si;
 
-    if (!cfg.scrollbar) return;
+    if (!cfg.scrollbar)
+       return;
 
     si.cbSize = sizeof(si);
     si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
@@ -2572,55 +2840,60 @@ void set_sbar (int total, int start, int page) {
     si.nPage = page;
     si.nPos = start;
     if (hwnd)
-        SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
+       SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
 }
 
-Context get_ctx(void) {
+Context get_ctx(void)
+{
     HDC hdc;
     if (hwnd) {
-       hdc = GetDC (hwnd);
+       hdc = GetDC(hwnd);
        if (hdc && pal)
-           SelectPalette (hdc, pal, FALSE);
+           SelectPalette(hdc, pal, FALSE);
        return hdc;
     } else
        return NULL;
 }
 
-void free_ctx (Context ctx) {
-    SelectPalette (ctx, GetStockObject (DEFAULT_PALETTE), FALSE);
-    ReleaseDC (hwnd, ctx);
+void free_ctx(Context ctx)
+{
+    SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
+    ReleaseDC(hwnd, ctx);
 }
 
-static void real_palette_set (int n, int r, int g, int b) {
+static void real_palette_set(int n, int r, int g, int b)
+{
     if (pal) {
        logpal->palPalEntry[n].peRed = r;
        logpal->palPalEntry[n].peGreen = g;
        logpal->palPalEntry[n].peBlue = b;
        logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
        colours[n] = PALETTERGB(r, g, b);
-       SetPaletteEntries (pal, 0, NCOLOURS, logpal->palPalEntry);
+       SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
     } else
        colours[n] = RGB(r, g, b);
 }
 
-void palette_set (int n, int r, int g, int b) {
+void palette_set(int n, int r, int g, int b)
+{
     static const int first[21] = {
        0, 2, 4, 6, 8, 10, 12, 14,
        1, 3, 5, 7, 9, 11, 13, 15,
        16, 17, 18, 20, 22
     };
-    real_palette_set (first[n], r, g, b);
+    real_palette_set(first[n], r, g, b);
     if (first[n] >= 18)
-       real_palette_set (first[n]+1, r, g, b);
+       real_palette_set(first[n] + 1, r, g, b);
     if (pal) {
        HDC hdc = get_ctx();
-       UnrealizeObject (pal);
-       RealizePalette (hdc);
-       free_ctx (hdc);
+       UnrealizeObject(pal);
+       RealizePalette(hdc);
+       free_ctx(hdc);
     }
 }
 
-void palette_reset (void) {
+void palette_reset(void)
+{
     int i;
 
     for (i = 0; i < NCOLOURS; i++) {
@@ -2634,61 +2907,62 @@ void palette_reset (void) {
                                    defpal[i].rgbtBlue);
        } else
            colours[i] = RGB(defpal[i].rgbtRed,
-                            defpal[i].rgbtGreen,
-                            defpal[i].rgbtBlue);
+                            defpal[i].rgbtGreen, defpal[i].rgbtBlue);
     }
 
     if (pal) {
        HDC hdc;
-       SetPaletteEntries (pal, 0, NCOLOURS, logpal->palPalEntry);
+       SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
        hdc = get_ctx();
-       RealizePalette (hdc);
-       free_ctx (hdc);
+       RealizePalette(hdc);
+       free_ctx(hdc);
     }
 }
 
-void write_clip (void *data, int len, int must_deselect) {
+void write_clip(void *data, int len, int must_deselect)
+{
     HGLOBAL clipdata;
     void *lock;
 
-    clipdata = GlobalAlloc (GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
+    clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
     if (!clipdata)
        return;
-    lock = GlobalLock (clipdata);
+    lock = GlobalLock(clipdata);
     if (!lock)
        return;
-    memcpy (lock, data, len);
-    ((unsigned char *) lock) [len] = 0;
-    GlobalUnlock (clipdata);
+    memcpy(lock, data, len);
+    ((unsigned char *) lock)[len] = 0;
+    GlobalUnlock(clipdata);
 
     if (!must_deselect)
-        SendMessage (hwnd, WM_IGNORE_CLIP, TRUE, 0);
+       SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
 
-    if (OpenClipboard (hwnd)) {
+    if (OpenClipboard(hwnd)) {
        EmptyClipboard();
-       SetClipboardData (CF_TEXT, clipdata);
+       SetClipboardData(CF_TEXT, clipdata);
        CloseClipboard();
     } else
-       GlobalFree (clipdata);
+       GlobalFree(clipdata);
 
     if (!must_deselect)
-        SendMessage (hwnd, WM_IGNORE_CLIP, FALSE, 0);
+       SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
 }
 
-void get_clip (void **p, int *len) {
+void get_clip(void **p, int *len)
+{
     static HGLOBAL clipdata = NULL;
 
     if (!p) {
        if (clipdata)
-           GlobalUnlock (clipdata);
+           GlobalUnlock(clipdata);
        clipdata = NULL;
        return;
     } else {
-       if (OpenClipboard (NULL)) {
-           clipdata = GetClipboardData (CF_TEXT);
+       if (OpenClipboard(NULL)) {
+           clipdata = GetClipboardData(CF_TEXT);
            CloseClipboard();
            if (clipdata) {
-               *p = GlobalLock (clipdata);
+               *p = GlobalLock(clipdata);
                if (*p) {
                    *len = strlen(*p);
                    return;
@@ -2705,22 +2979,26 @@ void get_clip (void **p, int *len) {
  * Move `lines' lines from position `from' to position `to' in the
  * window.
  */
-void optimised_move (int to, int from, int lines) {
+void optimised_move(int to, int from, int lines)
+{
     RECT r;
     int min, max;
 
     min = (to < from ? to : from);
     max = to + from - min;
 
-    r.left = 0; r.right = cols * font_width;
-    r.top = min * font_height; r.bottom = (max+lines) * font_height;
-    ScrollWindow (hwnd, 0, (to - from) * font_height, &r, &r);
+    r.left = 0;
+    r.right = cols * font_width;
+    r.top = min * font_height;
+    r.bottom = (max + lines) * font_height;
+    ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
 }
 
 /*
  * Print a message box and perform a fatal exit.
  */
-void fatalbox(char *fmt, ...) {
+void fatalbox(char *fmt, ...)
+{
     va_list ap;
     char stuff[200];
 
@@ -2734,7 +3012,8 @@ void fatalbox(char *fmt, ...) {
 /*
  * Beep.
  */
-void beep(int mode) {
+void beep(int mode)
+{
     if (mode == BELL_DEFAULT) {
        /*
         * For MessageBeep style bells, we want to be careful of
@@ -2753,10 +3032,11 @@ void beep(int mode) {
        lastbeep = now;
     } else if (mode == BELL_WAVEFILE) {
        if (!PlaySound(cfg.bell_wavefile, NULL, SND_ASYNC | SND_FILENAME)) {
-           char buf[sizeof(cfg.bell_wavefile)+80];
+           char buf[sizeof(cfg.bell_wavefile) + 80];
            sprintf(buf, "Unable to play sound file\n%s\n"
                    "Using default sound instead", cfg.bell_wavefile);
-           MessageBox(hwnd, buf, "PuTTY Sound Error", MB_OK | MB_ICONEXCLAMATION);
+           MessageBox(hwnd, buf, "PuTTY Sound Error",
+                      MB_OK | MB_ICONEXCLAMATION);
            cfg.beep = BELL_DEFAULT;
        }
     }
index 7d92791..238730c 100644 (file)
--- a/winnet.c
+++ b/winnet.c
@@ -82,7 +82,7 @@ typedef struct Socket_tag *Actual_Socket;
 struct SockAddr_tag {
     char *error;
     /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
-    int family;                             
+    int family;
     unsigned long address;            /* Address IPv4 style. */
 #ifdef IPV6
     struct addrinfo *ai;              /* Address IPv6 style. */
@@ -102,64 +102,109 @@ struct buffer {
 
 static tree234 *sktree;
 
-static int cmpfortree(void *av, void *bv) {
-    Actual_Socket a = (Actual_Socket)av, b = (Actual_Socket)bv;
-    unsigned long as = (unsigned long)a->s, bs = (unsigned long)b->s;
-    if (as < bs) return -1;
-    if (as > bs) return +1;
+static int cmpfortree(void *av, void *bv)
+{
+    Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
+    unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
+    if (as < bs)
+       return -1;
+    if (as > bs)
+       return +1;
     return 0;
 }
 
-static int cmpforsearch(void *av, void *bv) {
-    Actual_Socket b = (Actual_Socket)bv;
-    unsigned long as = (unsigned long)av, bs = (unsigned long)b->s;
-    if (as < bs) return -1;
-    if (as > bs) return +1;
+static int cmpforsearch(void *av, void *bv)
+{
+    Actual_Socket b = (Actual_Socket) bv;
+    unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
+    if (as < bs)
+       return -1;
+    if (as > bs)
+       return +1;
     return 0;
 }
 
-void sk_init(void) {
+void sk_init(void)
+{
     sktree = newtree234(cmpfortree);
 }
 
-char *winsock_error_string(int error) {
+char *winsock_error_string(int error)
+{
     switch (error) {
-      case WSAEACCES: return "Network error: Permission denied";
-      case WSAEADDRINUSE: return "Network error: Address already in use";
-      case WSAEADDRNOTAVAIL: return "Network error: Cannot assign requested address";
-      case WSAEAFNOSUPPORT: return "Network error: Address family not supported by protocol family";
-      case WSAEALREADY: return "Network error: Operation already in progress";
-      case WSAECONNABORTED: return "Network error: Software caused connection abort";
-      case WSAECONNREFUSED: return "Network error: Connection refused";
-      case WSAECONNRESET: return "Network error: Connection reset by peer";
-      case WSAEDESTADDRREQ: return "Network error: Destination address required";
-      case WSAEFAULT: return "Network error: Bad address";
-      case WSAEHOSTDOWN: return "Network error: Host is down";
-      case WSAEHOSTUNREACH: return "Network error: No route to host";
-      case WSAEINPROGRESS: return "Network error: Operation now in progress";
-      case WSAEINTR: return "Network error: Interrupted function call";
-      case WSAEINVAL: return "Network error: Invalid argument";
-      case WSAEISCONN: return "Network error: Socket is already connected";
-      case WSAEMFILE: return "Network error: Too many open files";
-      case WSAEMSGSIZE: return "Network error: Message too long";
-      case WSAENETDOWN: return "Network error: Network is down";
-      case WSAENETRESET: return "Network error: Network dropped connection on reset";
-      case WSAENETUNREACH: return "Network error: Network is unreachable";
-      case WSAENOBUFS: return "Network error: No buffer space available";
-      case WSAENOPROTOOPT: return "Network error: Bad protocol option";
-      case WSAENOTCONN: return "Network error: Socket is not connected";
-      case WSAENOTSOCK: return "Network error: Socket operation on non-socket";
-      case WSAEOPNOTSUPP: return "Network error: Operation not supported";
-      case WSAEPFNOSUPPORT: return "Network error: Protocol family not supported";
-      case WSAEPROCLIM: return "Network error: Too many processes";
-      case WSAEPROTONOSUPPORT: return "Network error: Protocol not supported";
-      case WSAEPROTOTYPE: return "Network error: Protocol wrong type for socket";
-      case WSAESHUTDOWN: return "Network error: Cannot send after socket shutdown";
-      case WSAESOCKTNOSUPPORT: return "Network error: Socket type not supported";
-      case WSAETIMEDOUT: return "Network error: Connection timed out";
-      case WSAEWOULDBLOCK: return "Network error: Resource temporarily unavailable";
-      case WSAEDISCON: return "Network error: Graceful shutdown in progress";
-      default: return "Unknown network error";
+      case WSAEACCES:
+       return "Network error: Permission denied";
+      case WSAEADDRINUSE:
+       return "Network error: Address already in use";
+      case WSAEADDRNOTAVAIL:
+       return "Network error: Cannot assign requested address";
+      case WSAEAFNOSUPPORT:
+       return
+           "Network error: Address family not supported by protocol family";
+      case WSAEALREADY:
+       return "Network error: Operation already in progress";
+      case WSAECONNABORTED:
+       return "Network error: Software caused connection abort";
+      case WSAECONNREFUSED:
+       return "Network error: Connection refused";
+      case WSAECONNRESET:
+       return "Network error: Connection reset by peer";
+      case WSAEDESTADDRREQ:
+       return "Network error: Destination address required";
+      case WSAEFAULT:
+       return "Network error: Bad address";
+      case WSAEHOSTDOWN:
+       return "Network error: Host is down";
+      case WSAEHOSTUNREACH:
+       return "Network error: No route to host";
+      case WSAEINPROGRESS:
+       return "Network error: Operation now in progress";
+      case WSAEINTR:
+       return "Network error: Interrupted function call";
+      case WSAEINVAL:
+       return "Network error: Invalid argument";
+      case WSAEISCONN:
+       return "Network error: Socket is already connected";
+      case WSAEMFILE:
+       return "Network error: Too many open files";
+      case WSAEMSGSIZE:
+       return "Network error: Message too long";
+      case WSAENETDOWN:
+       return "Network error: Network is down";
+      case WSAENETRESET:
+       return "Network error: Network dropped connection on reset";
+      case WSAENETUNREACH:
+       return "Network error: Network is unreachable";
+      case WSAENOBUFS:
+       return "Network error: No buffer space available";
+      case WSAENOPROTOOPT:
+       return "Network error: Bad protocol option";
+      case WSAENOTCONN:
+       return "Network error: Socket is not connected";
+      case WSAENOTSOCK:
+       return "Network error: Socket operation on non-socket";
+      case WSAEOPNOTSUPP:
+       return "Network error: Operation not supported";
+      case WSAEPFNOSUPPORT:
+       return "Network error: Protocol family not supported";
+      case WSAEPROCLIM:
+       return "Network error: Too many processes";
+      case WSAEPROTONOSUPPORT:
+       return "Network error: Protocol not supported";
+      case WSAEPROTOTYPE:
+       return "Network error: Protocol wrong type for socket";
+      case WSAESHUTDOWN:
+       return "Network error: Cannot send after socket shutdown";
+      case WSAESOCKTNOSUPPORT:
+       return "Network error: Socket type not supported";
+      case WSAETIMEDOUT:
+       return "Network error: Connection timed out";
+      case WSAEWOULDBLOCK:
+       return "Network error: Resource temporarily unavailable";
+      case WSAEDISCON:
+       return "Network error: Graceful shutdown in progress";
+      default:
+       return "Unknown network error";
     }
 }
 
@@ -174,54 +219,54 @@ SockAddr sk_namelookup(char *host, char **canonicalname)
     ret->family = 0;                  /* We set this one when we have resolved the host. */
     *canonicalname = ret->realhost;    /* This makes sure we always have a hostname to return. */
 
-    if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE)
-    {
+    if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
 #ifdef IPV6
 
        /* Try to get the getaddrinfo() function from wship6.dll */
        /* This way one doesn't need to have IPv6 dll's to use PuTTY and
         * it will fallback to IPv4. */
-       typedef int (CALLBACK* FGETADDRINFO)(const char *nodename,
-                                            const char *servname,
-                                            const struct addrinfo *hints,
-                                            struct addrinfo **res);
+       typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
+                                              const char *servname,
+                                              const struct addrinfo *
+                                              hints,
+                                              struct addrinfo ** res);
        FGETADDRINFO fGetAddrInfo = NULL;
 
        HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
        if (dllWSHIP6)
-           fGetAddrInfo = (FGETADDRINFO)GetProcAddress(dllWSHIP6,
-                                                       "getaddrinfo");
+           fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
+                                                        "getaddrinfo");
 
        /*
         * Use fGetAddrInfo when it's available (which usually also
         * means IPv6 is installed...)
         */
-       if (fGetAddrInfo)
-       {
+       if (fGetAddrInfo) {
            /*debug(("Resolving \"%s\" with getaddrinfo()  (IPv4+IPv6 capable)...\n", host)); */
            if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
                ret->family = ret->ai->ai_family;
-       }
-       else
+       } else
 #endif
+       {
            /*
             * Otherwise use the IPv4-only gethostbyname...
             * (NOTE: we don't use gethostbyname as a
             * fallback!)
             */
-           if (ret->family == 0)
-       {
-           /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
-           if (h = gethostbyname(host)) ret->family = AF_INET;
+           if (ret->family == 0) {
+               /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
+               if (h = gethostbyname(host))
+                   ret->family = AF_INET;
+           }
        }
        /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
 
-       if (ret->family == 0)
-       {
+       if (ret->family == 0) {
            DWORD err = WSAGetLastError();
            ret->error = (err == WSAENETDOWN ? "Network is down" :
-                         err == WSAHOST_NOT_FOUND ? "Host does not exist" :
-                         err == WSATRY_AGAIN ? "Host not found" :
+                         err ==
+                         WSAHOST_NOT_FOUND ? "Host does not exist" : err
+                         == WSATRY_AGAIN ? "Host not found" :
 #ifdef IPV6
                          fGetAddrInfo ? "getaddrinfo: unknown error" :
 #endif
@@ -229,42 +274,46 @@ SockAddr sk_namelookup(char *host, char **canonicalname)
 #ifdef DEBUG
            {
                LPVOID lpMsgBuf;
-               FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf,     0,      NULL);
-               /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h));*/
+               FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                             FORMAT_MESSAGE_FROM_SYSTEM |
+                             FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
+                             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                             (LPTSTR) & lpMsgBuf, 0, NULL);
+               /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
                /* Free the buffer. */
                LocalFree(lpMsgBuf);
            }
 #endif
-       }
-       else
-       {
+       } else {
            ret->error = NULL;
 
 #ifdef IPV6
            /* If we got an address info use that... */
-           if (ret->ai)
-           {
-               typedef int (CALLBACK* FGETNAMEINFO)
-                   (const struct sockaddr FAR *sa, socklen_t salen,
-                    char FAR * host, size_t hostlen, char FAR * serv,
-                    size_t servlen, int flags);
+           if (ret->ai) {
+               typedef int (CALLBACK * FGETNAMEINFO)
+                (const struct sockaddr FAR * sa, socklen_t salen,
+                 char FAR * host, size_t hostlen, char FAR * serv,
+                 size_t servlen, int flags);
                FGETNAMEINFO fGetNameInfo = NULL;
 
                /* Are we in IPv4 fallback mode? */
                /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
                if (ret->family == AF_INET)
-                   memcpy(&a, (char *)&((SOCKADDR_IN *)ret->ai->ai_addr)->sin_addr, sizeof(a));
+                   memcpy(&a,
+                          (char *) &((SOCKADDR_IN *) ret->ai->
+                                     ai_addr)->sin_addr, sizeof(a));
 
                /* Now let's find that canonicalname... */
-               if ((dllWSHIP6) && (fGetNameInfo = (FGETNAMEINFO)GetProcAddress(dllWSHIP6, "getnameinfo")))
-               {
-                   if (fGetNameInfo((struct sockaddr *)ret->ai->ai_addr,
-                                    ret->family == AF_INET ?
-                                    sizeof(SOCKADDR_IN) :
-                                    sizeof(SOCKADDR_IN6), ret->realhost,
-                                    sizeof(ret->realhost), NULL,
-                                    0, 0) != 0)
-                   {
+               if ((dllWSHIP6)
+                   && (fGetNameInfo =
+                       (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
+                                                     "getnameinfo"))) {
+                   if (fGetNameInfo
+                       ((struct sockaddr *) ret->ai->ai_addr,
+                        ret->family ==
+                        AF_INET ? sizeof(SOCKADDR_IN) :
+                        sizeof(SOCKADDR_IN6), ret->realhost,
+                        sizeof(ret->realhost), NULL, 0, 0) != 0) {
                        strncpy(ret->realhost, host,
                                sizeof(ret->realhost));
                    }
@@ -272,57 +321,57 @@ SockAddr sk_namelookup(char *host, char **canonicalname)
            }
            /* We used the IPv4-only gethostbyname()... */
            else
-           {
 #endif
+           {
                memcpy(&a, h->h_addr, sizeof(a));
                /* This way we are always sure the h->h_name is valid :) */
                strncpy(ret->realhost, h->h_name, sizeof(ret->realhost));
-#ifdef IPV6
            }
-#endif
        }
 #ifdef IPV6
        FreeLibrary(dllWSHIP6);
 #endif
-    }
-    else
-    {
+    } else {
        /*
         * This must be a numeric IPv4 address because it caused a
         * success return from inet_addr.
         */
-        ret->family = AF_INET;
+       ret->family = AF_INET;
        *canonicalname = host;
     }
     ret->address = ntohl(a);
     return ret;
 }
 
-void sk_addr_free(SockAddr addr) {
+void sk_addr_free(SockAddr addr)
+{
     sfree(addr);
 }
 
-static Plug sk_tcp_plug (Socket sock, Plug p) {
+static Plug sk_tcp_plug(Socket sock, Plug p)
+{
     Actual_Socket s = (Actual_Socket) sock;
     Plug ret = s->plug;
-    if (p) s->plug = p;
+    if (p)
+       s->plug = p;
     return ret;
 }
 
-static void sk_tcp_flush (Socket s) {
+static void sk_tcp_flush(Socket s)
+{
     /*
      * We send data to the socket as soon as we can anyway,
      * so we don't need to do anything here.  :-)
      */
 }
 
-void sk_tcp_close (Socket s);
-void sk_tcp_write (Socket s, char *data, int len);
-void sk_tcp_write_oob (Socket s, char *data, int len);
+void sk_tcp_close(Socket s);
+void sk_tcp_write(Socket s, char *data, int len);
+void sk_tcp_write_oob(Socket s, char *data, int len);
 char *sk_tcp_socket_error(Socket s);
 
 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
-              Plug plug)
+             Plug plug)
 {
     static struct socket_function_table fn_table = {
        sk_tcp_plug,
@@ -363,69 +412,67 @@ Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
 
     if (s == INVALID_SOCKET) {
        err = WSAGetLastError();
-        ret->error = winsock_error_string(err);
+       ret->error = winsock_error_string(err);
        return (Socket) ret;
     }
 
     ret->oobinline = oobinline;
     if (oobinline) {
        BOOL b = TRUE;
-       setsockopt (s, SOL_SOCKET, SO_OOBINLINE, (void *)&b, sizeof(b));
+       setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
     }
 
     /*
      * Bind to local address.
      */
     if (privport)
-        localport = 1023;              /* count from 1023 downwards */
+       localport = 1023;              /* count from 1023 downwards */
     else
-        localport = 0;                 /* just use port 0 (ie winsock picks) */
+       localport = 0;                 /* just use port 0 (ie winsock picks) */
 
     /* Loop round trying to bind */
     while (1) {
-        int retcode;
+       int retcode;
 
 #ifdef IPV6
-        if (addr->family == AF_INET6)
-        {
-            memset(&a6,0,sizeof(a6));
-            a6.sin6_family     = AF_INET6;
-            /*a6.sin6_addr     = in6addr_any;*/  /* == 0 */
-            a6.sin6_port       = htons(localport);
-        }
-        else
-        {
+       if (addr->family == AF_INET6) {
+           memset(&a6, 0, sizeof(a6));
+           a6.sin6_family = AF_INET6;
+/*a6.sin6_addr      = in6addr_any; *//* == 0 */
+           a6.sin6_port = htons(localport);
+       } else
 #endif
-            a.sin_family = AF_INET;
-            a.sin_addr.s_addr = htonl(INADDR_ANY);
-            a.sin_port = htons(localport);
+       {
+           a.sin_family = AF_INET;
+           a.sin_addr.s_addr = htonl(INADDR_ANY);
+           a.sin_port = htons(localport);
+       }
 #ifdef IPV6
-        }
-        retcode = bind (s, (addr->family == AF_INET6 ?
-                            (struct sockaddr *)&a6 :
-                            (struct sockaddr *)&a),
-                        (addr->family == AF_INET6 ? sizeof(a6) : sizeof(a)));
+       retcode = bind(s, (addr->family == AF_INET6 ?
+                          (struct sockaddr *) &a6 :
+                          (struct sockaddr *) &a),
+                      (addr->family ==
+                       AF_INET6 ? sizeof(a6) : sizeof(a)));
 #else
-        retcode = bind (s, (struct sockaddr *)&a, sizeof(a));
+       retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
 #endif
-        if (retcode != SOCKET_ERROR) {
-            err = 0;
-            break;                     /* done */
-        } else {
-            err = WSAGetLastError();
-            if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
-                break;
-        }
-
-        if (localport == 0)
-            break;                     /* we're only looping once */
-        localport--;
-        if (localport == 0)
-            break;                     /* we might have got to the end */
+       if (retcode != SOCKET_ERROR) {
+           err = 0;
+           break;                     /* done */
+       } else {
+           err = WSAGetLastError();
+           if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
+               break;
+       }
+
+       if (localport == 0)
+           break;                     /* we're only looping once */
+       localport--;
+       if (localport == 0)
+           break;                     /* we might have got to the end */
     }
 
-    if (err)
-    {
+    if (err) {
        ret->error = winsock_error_string(err);
        return (Socket) ret;
     }
@@ -434,26 +481,28 @@ Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
      * Connect to remote address.
      */
 #ifdef IPV6
-    if (addr->family == AF_INET6)
-    {
-       memset(&a,0,sizeof(a));
+    if (addr->family == AF_INET6) {
+       memset(&a, 0, sizeof(a));
        a6.sin6_family = AF_INET6;
-       a6.sin6_port = htons((short)port);
-       a6.sin6_addr = ((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr;
-    }
-    else
-    {
+       a6.sin6_port = htons((short) port);
+       a6.sin6_addr =
+           ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
+    } else
 #endif
+    {
        a.sin_family = AF_INET;
        a.sin_addr.s_addr = htonl(addr->address);
-       a.sin_port = htons((short)port);
-#ifdef IPV6
+       a.sin_port = htons((short) port);
     }
-    if (connect (s, (addr->family == AF_INET6) ? (struct sockaddr *)&a6 : (struct sockaddr *)&a, (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a)) == SOCKET_ERROR)
+    if ((
+#ifdef IPV6
+           connect(s, ((addr->family == AF_INET6) ?
+                       (struct sockaddr *) &a6 : (struct sockaddr *) &a),
+                   (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
 #else
-       if (connect (s, (struct sockaddr *)&a, sizeof(a)) == SOCKET_ERROR)
+           connect(s, (struct sockaddr *) &a, sizeof(a))
 #endif
-    {
+       ) == SOCKET_ERROR) {
        err = WSAGetLastError();
        ret->error = winsock_error_string(err);
        return (Socket) ret;
@@ -472,7 +521,8 @@ Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
     return (Socket) ret;
 }
 
-static void sk_tcp_close(Socket sock) {
+static void sk_tcp_close(Socket sock)
+{
     extern char *do_select(SOCKET skt, int startup);
     Actual_Socket s = (Actual_Socket) sock;
 
@@ -486,25 +536,27 @@ static void sk_tcp_close(Socket sock) {
  * The function which tries to send on a socket once it's deemed
  * writable.
  */
-void try_send(Actual_Socket s) {
+void try_send(Actual_Socket s)
+{
     while (s->head) {
        int nsent;
        DWORD err;
-        int len, urgentflag;
-
-        if (s->sending_oob) {
-            urgentflag = MSG_OOB;
-            len = s->sending_oob;
-        } else {
-            urgentflag = 0;
-            len = s->head->buflen - s->head->bufpos;
-        }
-
-       nsent = send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
-        noise_ultralight(nsent);
+       int len, urgentflag;
+
+       if (s->sending_oob) {
+           urgentflag = MSG_OOB;
+           len = s->sending_oob;
+       } else {
+           urgentflag = 0;
+           len = s->head->buflen - s->head->bufpos;
+       }
+
+       nsent =
+           send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
+       noise_ultralight(nsent);
        if (nsent <= 0) {
            err = (nsent < 0 ? WSAGetLastError() : 0);
-           if ((err==0 && nsent < 0) || err == WSAEWOULDBLOCK) {
+           if ((err == 0 && nsent < 0) || err == WSAEWOULDBLOCK) {
                /*
                 * Perfectly normal: we've sent all we can for the moment.
                 * 
@@ -514,29 +566,28 @@ void try_send(Actual_Socket s) {
                 * and treat it just like WSAEWOULDBLOCK.)
                 */
                s->writable = FALSE;
-                return;
+               return;
            } else if (nsent == 0 ||
-                      err == WSAECONNABORTED ||
-                      err == WSAECONNRESET) {
-                /*
-                 * FIXME. This will have to be done better when we
-                 * start managing multiple sockets (e.g. SSH port
-                 * forwarding), because if we get CONNRESET while
-                 * trying to write a particular forwarded socket
-                 * then it isn't necessarily the end of the world.
-                 * Ideally I'd like to pass the error code back to
-                 * somewhere the next select_result() will see it,
-                 * but that might be hard. Perhaps I should pass it
-                 * back to be queued in the Windows front end bit.
-                 */
-                fatalbox(winsock_error_string(err));
+                      err == WSAECONNABORTED || err == WSAECONNRESET) {
+               /*
+                * FIXME. This will have to be done better when we
+                * start managing multiple sockets (e.g. SSH port
+                * forwarding), because if we get CONNRESET while
+                * trying to write a particular forwarded socket
+                * then it isn't necessarily the end of the world.
+                * Ideally I'd like to pass the error code back to
+                * somewhere the next select_result() will see it,
+                * but that might be hard. Perhaps I should pass it
+                * back to be queued in the Windows front end bit.
+                */
+               fatalbox(winsock_error_string(err));
            } else {
                fatalbox(winsock_error_string(err));
            }
        } else {
            s->head->bufpos += nsent;
-            if (s->sending_oob)
-                s->sending_oob -= nsent;
+           if (s->sending_oob)
+               s->sending_oob -= nsent;
            if (s->head->bufpos >= s->head->buflen) {
                struct buffer *tmp = s->head;
                s->head = tmp->next;
@@ -548,7 +599,8 @@ void try_send(Actual_Socket s) {
     }
 }
 
-static void sk_tcp_write(Socket sock, char *buf, int len) {
+static void sk_tcp_write(Socket sock, char *buf, int len)
+{
     Actual_Socket s = (Actual_Socket) sock;
 
     /*
@@ -585,7 +637,8 @@ static void sk_tcp_write(Socket sock, char *buf, int len) {
        try_send(s);
 }
 
-static void sk_tcp_write_oob(Socket sock, char *buf, int len) {
+static void sk_tcp_write_oob(Socket sock, char *buf, int len)
+{
     Actual_Socket s = (Actual_Socket) sock;
 
     /*
@@ -594,12 +647,12 @@ static void sk_tcp_write_oob(Socket sock, char *buf, int len) {
     if (!s->head) {
        s->head = smalloc(sizeof(struct buffer));
     } else {
-        struct buffer *walk = s->head->next;
-        while (walk) {
-            struct buffer *tmp = walk;
-            walk = tmp->next;
-            sfree(tmp);
-        }
+       struct buffer *walk = s->head->next;
+       while (walk) {
+           struct buffer *tmp = walk;
+           walk = tmp->next;
+           sfree(tmp);
+       }
     }
     s->head->next = NULL;
     s->tail = s->head;
@@ -618,7 +671,8 @@ static void sk_tcp_write_oob(Socket sock, char *buf, int len) {
        try_send(s);
 }
 
-int select_result(WPARAM wParam, LPARAM lParam) {
+int select_result(WPARAM wParam, LPARAM lParam)
+{
     int ret, open;
     DWORD err;
     char buf[20480];                  /* nice big buffer for plenty of speed */
@@ -626,43 +680,43 @@ int select_result(WPARAM wParam, LPARAM lParam) {
     u_long atmark;
 
     /* wParam is the socket itself */
-    s = find234(sktree, (void *)wParam, cmpforsearch);
+    s = find234(sktree, (void *) wParam, cmpforsearch);
     if (!s)
        return 1;                      /* boggle */
 
     if ((err = WSAGETSELECTERROR(lParam)) != 0) {
-        /*
-         * An error has occurred on this socket. Pass it to the
-         * plug.
-         */
-        return plug_closing (s->plug, winsock_error_string(err), err, 0);
+       /*
+        * An error has occurred on this socket. Pass it to the
+        * plug.
+        */
+       return plug_closing(s->plug, winsock_error_string(err), err, 0);
     }
 
     noise_ultralight(lParam);
 
     switch (WSAGETSELECTEVENT(lParam)) {
       case FD_READ:
-        /*
-         * We have received data on the socket. For an oobinline
-         * socket, this might be data _before_ an urgent pointer,
-         * in which case we send it to the back end with type==1
-         * (data prior to urgent).
-         */
-        if (s->oobinline) {
-            atmark = 1;
-            ioctlsocket(s->s, SIOCATMARK, &atmark);
-            /*
-             * Avoid checking the return value from ioctlsocket(),
-             * on the grounds that some WinSock wrappers don't
-             * support it. If it does nothing, we get atmark==1,
-             * which is equivalent to `no OOB pending', so the
-             * effect will be to non-OOB-ify any OOB data.
-             */
-        } else
-            atmark = 1;
+       /*
+        * We have received data on the socket. For an oobinline
+        * socket, this might be data _before_ an urgent pointer,
+        * in which case we send it to the back end with type==1
+        * (data prior to urgent).
+        */
+       if (s->oobinline) {
+           atmark = 1;
+           ioctlsocket(s->s, SIOCATMARK, &atmark);
+           /*
+            * Avoid checking the return value from ioctlsocket(),
+            * on the grounds that some WinSock wrappers don't
+            * support it. If it does nothing, we get atmark==1,
+            * which is equivalent to `no OOB pending', so the
+            * effect will be to non-OOB-ify any OOB data.
+            */
+       } else
+           atmark = 1;
 
        ret = recv(s->s, buf, sizeof(buf), 0);
-        noise_ultralight(ret);
+       noise_ultralight(ret);
        if (ret < 0) {
            err = WSAGetLastError();
            if (err == WSAEWOULDBLOCK) {
@@ -670,49 +724,53 @@ int select_result(WPARAM wParam, LPARAM lParam) {
            }
        }
        if (ret < 0) {
-           return plug_closing (s->plug, winsock_error_string(err), err, 0);
+           return plug_closing(s->plug, winsock_error_string(err), err,
+                               0);
        } else if (0 == ret) {
-           return plug_closing (s->plug, NULL, 0, 0);
+           return plug_closing(s->plug, NULL, 0, 0);
        } else {
-           return plug_receive (s->plug, atmark ? 0 : 1, buf, ret);
+           return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
        }
        break;
       case FD_OOB:
-        /*
-         * This will only happen on a non-oobinline socket. It
-         * indicates that we can immediately perform an OOB read
-         * and get back OOB data, which we will send to the back
-         * end with type==2 (urgent data).
-         */
-        ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
-        noise_ultralight(ret);
-        if (ret <= 0) {
-            fatalbox(ret == 0 ? "Internal networking trouble" :
-                     winsock_error_string(WSAGetLastError()));
-        } else {
-           return plug_receive (s->plug, 2, buf, ret);
-        }
-        break;
+       /*
+        * This will only happen on a non-oobinline socket. It
+        * indicates that we can immediately perform an OOB read
+        * and get back OOB data, which we will send to the back
+        * end with type==2 (urgent data).
+        */
+       ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
+       noise_ultralight(ret);
+       if (ret <= 0) {
+           fatalbox(ret == 0 ? "Internal networking trouble" :
+                    winsock_error_string(WSAGetLastError()));
+       } else {
+           return plug_receive(s->plug, 2, buf, ret);
+       }
+       break;
       case FD_WRITE:
        s->writable = 1;
        try_send(s);
        break;
       case FD_CLOSE:
        /* Signal a close on the socket. First read any outstanding data. */
-        open = 1;
-        do {
-            ret = recv(s->s, buf, sizeof(buf), 0);
-            if (ret < 0) {
-                err = WSAGetLastError();
-                if (err == WSAEWOULDBLOCK)
-                    break;
-                return plug_closing (s->plug, winsock_error_string(err), err, 0);
-            } else {
-               if (ret) open &= plug_receive (s->plug, 0, buf, ret);
-               else open &= plug_closing (s->plug, NULL, 0, 0);
+       open = 1;
+       do {
+           ret = recv(s->s, buf, sizeof(buf), 0);
+           if (ret < 0) {
+               err = WSAGetLastError();
+               if (err == WSAEWOULDBLOCK)
+                   break;
+               return plug_closing(s->plug, winsock_error_string(err),
+                                   err, 0);
+           } else {
+               if (ret)
+                   open &= plug_receive(s->plug, 0, buf, ret);
+               else
+                   open &= plug_closing(s->plug, NULL, 0, 0);
            }
        } while (ret > 0);
-        return open;
+       return open;
     }
 
     return 1;
@@ -722,11 +780,14 @@ int select_result(WPARAM wParam, LPARAM lParam) {
  * Each socket abstraction contains a `void *' private field in
  * which the client can keep state.
  */
-void sk_set_private_ptr(Socket sock, void *ptr) {
+void sk_set_private_ptr(Socket sock, void *ptr)
+{
     Actual_Socket s = (Actual_Socket) sock;
     s->private_ptr = ptr;
 }
-void *sk_get_private_ptr(Socket sock) {
+
+void *sk_get_private_ptr(Socket sock)
+{
     Actual_Socket s = (Actual_Socket) sock;
     return s->private_ptr;
 }
@@ -736,10 +797,12 @@ void *sk_get_private_ptr(Socket sock) {
  * if there's a problem. These functions extract an error message,
  * or return NULL if there's no problem.
  */
-char *sk_addr_error(SockAddr addr) {
+char *sk_addr_error(SockAddr addr)
+{
     return addr->error;
 }
-static char *sk_tcp_socket_error(Socket sock) {
+static char *sk_tcp_socket_error(Socket sock)
+{
     Actual_Socket s = (Actual_Socket) sock;
     return s->error;
 }
@@ -747,13 +810,16 @@ static char *sk_tcp_socket_error(Socket sock) {
 /*
  * For Plink: enumerate all sockets currently active.
  */
-SOCKET first_socket(int *state) {
+SOCKET first_socket(int *state)
+{
     Actual_Socket s;
     *state = 0;
     s = index234(sktree, (*state)++);
     return s ? s->s : INVALID_SOCKET;
 }
-SOCKET next_socket(int *state) {
+
+SOCKET next_socket(int *state)
+{
     Actual_Socket s = index234(sktree, (*state)++);
     return s ? s->s : INVALID_SOCKET;
 }
index fd53ecf..651fbad 100644 (file)
 
 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
 
-static char seedpath[2*MAX_PATH+10] = "\0";
+static char seedpath[2 * MAX_PATH + 10] = "\0";
 
 static char hex[16] = "0123456789ABCDEF";
 
-static void mungestr(char *in, char *out) {
+static void mungestr(char *in, char *out)
+{
     int candot = 0;
 
     while (*in) {
        if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
-           *in == '%' || *in < ' ' || *in > '~' || (*in == '.' && !candot)) {
+           *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
+                                                    && !candot)) {
            *out++ = '%';
-           *out++ = hex[((unsigned char)*in) >> 4];
-           *out++ = hex[((unsigned char)*in) & 15];
+           *out++ = hex[((unsigned char) *in) >> 4];
+           *out++ = hex[((unsigned char) *in) & 15];
        } else
            *out++ = *in;
        in++;
@@ -33,67 +35,78 @@ static void mungestr(char *in, char *out) {
     return;
 }
 
-static void unmungestr(char *in, char *out, int outlen) {
+static void unmungestr(char *in, char *out, int outlen)
+{
     while (*in) {
        if (*in == '%' && in[1] && in[2]) {
            int i, j;
 
-           i = in[1] - '0'; i -= (i > 9 ? 7 : 0);
-           j = in[2] - '0'; j -= (j > 9 ? 7 : 0);
+           i = in[1] - '0';
+           i -= (i > 9 ? 7 : 0);
+           j = in[2] - '0';
+           j -= (j > 9 ? 7 : 0);
 
-           *out++ = (i<<4) + j;
-            if (!--outlen) return;
+           *out++ = (i << 4) + j;
+           if (!--outlen)
+               return;
            in += 3;
        } else {
            *out++ = *in++;
-            if (!--outlen) return;
-        }
+           if (!--outlen)
+               return;
+       }
     }
     *out = '\0';
     return;
 }
 
-void *open_settings_w(char *sessionname) {
+void *open_settings_w(char *sessionname)
+{
     HKEY subkey1, sesskey;
     int ret;
     char *p;
 
-    p = smalloc(3*strlen(sessionname)+1);
+    p = smalloc(3 * strlen(sessionname) + 1);
     mungestr(sessionname, p);
-    
+
     ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
     if (ret != ERROR_SUCCESS) {
-        sfree(p);
-        return NULL;
+       sfree(p);
+       return NULL;
     }
     ret = RegCreateKey(subkey1, p, &sesskey);
     sfree(p);
     RegCloseKey(subkey1);
     if (ret != ERROR_SUCCESS)
-        return NULL;
-    return (void *)sesskey;
+       return NULL;
+    return (void *) sesskey;
 }
 
-void write_setting_s(void *handle, char *key, char *value) {
+void write_setting_s(void *handle, char *key, char *value)
+{
     if (handle)
-        RegSetValueEx((HKEY)handle, key, 0, REG_SZ, value, 1+strlen(value));
+       RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
+                     1 + strlen(value));
 }
 
-void write_setting_i(void *handle, char *key, int value) {
+void write_setting_i(void *handle, char *key, int value)
+{
     if (handle)
-        RegSetValueEx((HKEY)handle, key, 0, REG_DWORD,
-                      (CONST BYTE *)&value, sizeof(value));
+       RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
+                     (CONST BYTE *) & value, sizeof(value));
 }
 
-void close_settings_w(void *handle) {
-    RegCloseKey((HKEY)handle);
+void close_settings_w(void *handle)
+{
+    RegCloseKey((HKEY) handle);
 }
 
-void *open_settings_r(char *sessionname) {
+void *open_settings_r(char *sessionname)
+{
     HKEY subkey1, sesskey;
     char *p;
 
-    p = smalloc(3*strlen(sessionname)+1);
+    p = smalloc(3 * strlen(sessionname) + 1);
     mungestr(sessionname, p);
 
     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
@@ -107,47 +120,50 @@ void *open_settings_r(char *sessionname) {
 
     sfree(p);
 
-    return (void *)sesskey;
+    return (void *) sesskey;
 }
 
-char *read_setting_s(void *handle, char *key, char *buffer, int buflen) {
+char *read_setting_s(void *handle, char *key, char *buffer, int buflen)
+{
     DWORD type, size;
     size = buflen;
 
     if (!handle ||
-        RegQueryValueEx((HKEY)handle, key, 0,
-                        &type, buffer, &size) != ERROR_SUCCESS ||
-       type != REG_SZ)
-        return NULL;
+       RegQueryValueEx((HKEY) handle, key, 0,
+                       &type, buffer, &size) != ERROR_SUCCESS ||
+       type != REG_SZ) return NULL;
     else
-        return buffer;
+       return buffer;
 }
 
-int read_setting_i(void *handle, char *key, int defvalue) {
+int read_setting_i(void *handle, char *key, int defvalue)
+{
     DWORD type, val, size;
     size = sizeof(val);
 
     if (!handle ||
-       RegQueryValueEx((HKEY)handle, key, 0, &type,
-                       (BYTE *)&val, &size) != ERROR_SUCCESS ||
+       RegQueryValueEx((HKEY) handle, key, 0, &type,
+                       (BYTE *) & val, &size) != ERROR_SUCCESS ||
        size != sizeof(val) || type != REG_DWORD)
        return defvalue;
     else
        return val;
 }
 
-void close_settings_r(void *handle) {
-    RegCloseKey((HKEY)handle);
+void close_settings_r(void *handle)
+{
+    RegCloseKey((HKEY) handle);
 }
 
-void del_settings (char *sessionname) {
+void del_settings(char *sessionname)
+{
     HKEY subkey1;
     char *p;
 
     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
        return;
 
-    p = smalloc(3*strlen(sessionname)+1);
+    p = smalloc(3 * strlen(sessionname) + 1);
     mungestr(sessionname, p);
     RegDeleteKey(subkey1, p);
     sfree(p);
@@ -160,53 +176,58 @@ struct enumsettings {
     int i;
 };
 
-void *enum_settings_start(void) {
+void *enum_settings_start(void)
+{
     struct enumsettings *ret;
     HKEY key;
 
     if (RegCreateKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
-        return NULL;
+       return NULL;
 
     ret = smalloc(sizeof(*ret));
     if (ret) {
-        ret->key = key;
-        ret->i = 0;
+       ret->key = key;
+       ret->i = 0;
     }
 
     return ret;
 }
 
-char *enum_settings_next(void *handle, char *buffer, int buflen) {
-    struct enumsettings *e = (struct enumsettings *)handle;
+char *enum_settings_next(void *handle, char *buffer, int buflen)
+{
+    struct enumsettings *e = (struct enumsettings *) handle;
     char *otherbuf;
-    otherbuf = smalloc(3*buflen);
+    otherbuf = smalloc(3 * buflen);
     if (otherbuf && RegEnumKey(e->key, e->i++, otherbuf,
-                               3*buflen) == ERROR_SUCCESS) {
-        unmungestr(otherbuf, buffer, buflen);
-        sfree(otherbuf);
-        return buffer;
+                              3 * buflen) == ERROR_SUCCESS) {
+       unmungestr(otherbuf, buffer, buflen);
+       sfree(otherbuf);
+       return buffer;
     } else
-        return NULL;
+       return NULL;
 
 }
 
-void enum_settings_finish(void *handle) {
-    struct enumsettings *e = (struct enumsettings *)handle;
+void enum_settings_finish(void *handle)
+{
+    struct enumsettings *e = (struct enumsettings *) handle;
     RegCloseKey(e->key);
     sfree(e);
 }
 
 static void hostkey_regname(char *buffer, char *hostname,
-                            int port, char *keytype) {
+                           int port, char *keytype)
+{
     int len;
     strcpy(buffer, keytype);
     strcat(buffer, "@");
     len = strlen(buffer);
-    len += sprintf(buffer+len, "%d:", port);
+    len += sprintf(buffer + len, "%d:", port);
     mungestr(hostname, buffer + strlen(buffer));
 }
 
-int verify_host_key(char *hostname, int port, char *keytype, char *key) {
+int verify_host_key(char *hostname, int port, char *keytype, char *key)
+{
     char *otherstr, *regname;
     int len;
     HKEY rkey;
@@ -221,76 +242,77 @@ int verify_host_key(char *hostname, int port, char *keytype, char *key) {
      * says.
      */
     otherstr = smalloc(len);
-    regname = smalloc(3*(strlen(hostname)+strlen(keytype))+15);
+    regname = smalloc(3 * (strlen(hostname) + strlen(keytype)) + 15);
 
     hostkey_regname(regname, hostname, port, keytype);
 
     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
                     &rkey) != ERROR_SUCCESS)
-        return 1;                      /* key does not exist in registry */
+       return 1;                      /* key does not exist in registry */
 
     readlen = len;
     ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
 
     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
-        !strcmp(keytype, "rsa")) {
-        /*
-         * Key didn't exist. If the key type is RSA, we'll try
-         * another trick, which is to look up the _old_ key format
-         * under just the hostname and translate that.
-         */
-        char *justhost = regname + 1 + strcspn(regname, ":");
-        char *oldstyle = smalloc(len + 10);   /* safety margin */
-        readlen = len;
-        ret = RegQueryValueEx(rkey, justhost, NULL, &type,
-                              oldstyle, &readlen);
-        
-        if (ret == ERROR_SUCCESS && type == REG_SZ) {
-            /*
-             * The old format is two old-style bignums separated by
-             * a slash. An old-style bignum is made of groups of
-             * four hex digits: digits are ordered in sensible
-             * (most to least significant) order within each group,
-             * but groups are ordered in silly (least to most)
-             * order within the bignum. The new format is two
-             * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
-             * A nonzero except in the special case 0x0, which
-             * doesn't appear anyway in RSA keys) separated by a
-             * comma. All hex digits are lowercase in both formats.
-             */
-            char *p = otherstr;
-            char *q = oldstyle;
-            int i, j;
-
-            for (i = 0; i < 2; i++) {
-                int ndigits, nwords;
-                *p++ = '0'; *p++ = 'x';
-                ndigits = strcspn(q, "/");   /* find / or end of string */
-                nwords = ndigits / 4;
-                /* now trim ndigits to remove leading zeros */
-                while (q[ (ndigits-1) ^ 3 ] == '0' && ndigits > 1)
-                    ndigits--;
-                /* now move digits over to new string */
-                for (j = 0; j < ndigits; j++)
-                    p[ndigits-1-j] = q[j^3];
-                p += ndigits;
-                q += nwords*4;
-                if (*q) {
-                    q++;               /* eat the slash */
-                    *p++ = ',';        /* add a comma */
-                }
-                *p = '\0';             /* terminate the string */
-            }
-
-            /*
-             * Now _if_ this key matches, we'll enter it in the new
-             * format. If not, we'll assume something odd went
-             * wrong, and hyper-cautiously do nothing.
-             */
-            if (!strcmp(otherstr, key))
-                RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
-                              strlen(otherstr)+1);
-        }
+       !strcmp(keytype, "rsa")) {
+       /*
+        * Key didn't exist. If the key type is RSA, we'll try
+        * another trick, which is to look up the _old_ key format
+        * under just the hostname and translate that.
+        */
+       char *justhost = regname + 1 + strcspn(regname, ":");
+       char *oldstyle = smalloc(len + 10);     /* safety margin */
+       readlen = len;
+       ret = RegQueryValueEx(rkey, justhost, NULL, &type,
+                             oldstyle, &readlen);
+
+       if (ret == ERROR_SUCCESS && type == REG_SZ) {
+           /*
+            * The old format is two old-style bignums separated by
+            * a slash. An old-style bignum is made of groups of
+            * four hex digits: digits are ordered in sensible
+            * (most to least significant) order within each group,
+            * but groups are ordered in silly (least to most)
+            * order within the bignum. The new format is two
+            * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
+            * A nonzero except in the special case 0x0, which
+            * doesn't appear anyway in RSA keys) separated by a
+            * comma. All hex digits are lowercase in both formats.
+            */
+           char *p = otherstr;
+           char *q = oldstyle;
+           int i, j;
+
+           for (i = 0; i < 2; i++) {
+               int ndigits, nwords;
+               *p++ = '0';
+               *p++ = 'x';
+               ndigits = strcspn(q, "/");      /* find / or end of string */
+               nwords = ndigits / 4;
+               /* now trim ndigits to remove leading zeros */
+               while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
+                   ndigits--;
+               /* now move digits over to new string */
+               for (j = 0; j < ndigits; j++)
+                   p[ndigits - 1 - j] = q[j ^ 3];
+               p += ndigits;
+               q += nwords * 4;
+               if (*q) {
+                   q++;               /* eat the slash */
+                   *p++ = ',';        /* add a comma */
+               }
+               *p = '\0';             /* terminate the string */
+           }
+
+           /*
+            * Now _if_ this key matches, we'll enter it in the new
+            * format. If not, we'll assume something odd went
+            * wrong, and hyper-cautiously do nothing.
+            */
+           if (!strcmp(otherstr, key))
+               RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
+                             strlen(otherstr) + 1);
+       }
     }
 
     RegCloseKey(rkey);
@@ -301,40 +323,42 @@ int verify_host_key(char *hostname, int port, char *keytype, char *key) {
     sfree(regname);
 
     if (ret == ERROR_MORE_DATA ||
-        (ret == ERROR_SUCCESS && type == REG_SZ && compare))
-        return 2;                      /* key is different in registry */
+       (ret == ERROR_SUCCESS && type == REG_SZ && compare))
+       return 2;                      /* key is different in registry */
     else if (ret != ERROR_SUCCESS || type != REG_SZ)
-        return 1;                      /* key does not exist in registry */
+       return 1;                      /* key does not exist in registry */
     else
-        return 0;                      /* key matched OK in registry */
+       return 0;                      /* key matched OK in registry */
 }
 
-void store_host_key(char *hostname, int port, char *keytype, char *key) {
+void store_host_key(char *hostname, int port, char *keytype, char *key)
+{
     char *regname;
     HKEY rkey;
 
-    regname = smalloc(3*(strlen(hostname)+strlen(keytype))+15);
+    regname = smalloc(3 * (strlen(hostname) + strlen(keytype)) + 15);
 
     hostkey_regname(regname, hostname, port, keytype);
 
     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
                     &rkey) != ERROR_SUCCESS)
-        return;                        /* key does not exist in registry */
-    RegSetValueEx(rkey, regname, 0, REG_SZ, key,
-                  strlen(key)+1);
+       return;                        /* key does not exist in registry */
+    RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
     RegCloseKey(rkey);
 }
 
 /*
  * Find the random seed file path and store it in `seedpath'.
  */
-static void get_seedpath(void) {
+static void get_seedpath(void)
+{
     HKEY rkey;
     DWORD type, size;
 
     size = sizeof(seedpath);
 
-    if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey)==ERROR_SUCCESS) {
+    if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
+       ERROR_SUCCESS) {
        int ret = RegQueryValueEx(rkey, "RandSeedFile",
                                  0, &type, seedpath, &size);
        if (ret != ERROR_SUCCESS || type != REG_SZ)
@@ -346,19 +370,23 @@ static void get_seedpath(void) {
     if (!seedpath[0]) {
        int len, ret;
 
-       len = GetEnvironmentVariable("HOMEDRIVE", seedpath, sizeof(seedpath));
-       ret = GetEnvironmentVariable("HOMEPATH", seedpath+len,
-                                     sizeof(seedpath)-len);
+       len =
+           GetEnvironmentVariable("HOMEDRIVE", seedpath,
+                                  sizeof(seedpath));
+       ret =
+           GetEnvironmentVariable("HOMEPATH", seedpath + len,
+                                  sizeof(seedpath) - len);
        if (ret == 0) {                /* probably win95; store in \WINDOWS */
            GetWindowsDirectory(seedpath, sizeof(seedpath));
            len = strlen(seedpath);
        } else
            len += ret;
-       strcpy(seedpath+len, "\\PUTTY.RND");
+       strcpy(seedpath + len, "\\PUTTY.RND");
     }
 }
 
-void read_random_seed(noise_consumer_t consumer) {
+void read_random_seed(noise_consumer_t consumer)
+{
     HANDLE seedf;
 
     if (!seedpath[0])
@@ -374,7 +402,7 @@ void read_random_seed(noise_consumer_t consumer) {
            DWORD len;
 
            if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
-                consumer(buf, len);
+               consumer(buf, len);
            else
                break;
        }
@@ -382,7 +410,8 @@ void read_random_seed(noise_consumer_t consumer) {
     }
 }
 
-void write_random_seed(void *data, int len) {
+void write_random_seed(void *data, int len)
+{
     HANDLE seedf;
 
     if (!seedpath[0])
@@ -402,25 +431,27 @@ void write_random_seed(void *data, int len) {
 /*
  * Recursively delete a registry key and everything under it.
  */
-static void registry_recursive_remove(HKEY key) {
+static void registry_recursive_remove(HKEY key)
+{
     DWORD i;
-    char name[MAX_PATH+1];
+    char name[MAX_PATH + 1];
     HKEY subkey;
 
     i = 0;
     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
-        if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
-            registry_recursive_remove(subkey);
-            RegCloseKey(subkey);
-        }
-        RegDeleteKey(key, name);
+       if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
+           registry_recursive_remove(subkey);
+           RegCloseKey(subkey);
+       }
+       RegDeleteKey(key, name);
     }
 }
 
-void cleanup_all(void) {
+void cleanup_all(void)
+{
     HKEY key;
     int ret;
-    char name[MAX_PATH+1];
+    char name[MAX_PATH + 1];
 
     /* ------------------------------------------------------------
      * Wipe out the random seed file.
@@ -436,9 +467,10 @@ void cleanup_all(void) {
     /*
      * Open the main PuTTY registry key and remove everything in it.
      */
-    if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) == ERROR_SUCCESS) {
-        registry_recursive_remove(key);
-        RegCloseKey(key);
+    if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
+       ERROR_SUCCESS) {
+       registry_recursive_remove(key);
+       RegCloseKey(key);
     }
     /*
      * Now open the parent key and remove the PuTTY main key. Once
@@ -446,22 +478,22 @@ void cleanup_all(void) {
      * children.
      */
     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
-                   &key) == ERROR_SUCCESS) {
-        RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
-        ret = RegEnumKey(key, 0, name, sizeof(name));
-        RegCloseKey(key);
-        /*
-         * If the parent key had no other children, we must delete
-         * it in its turn. That means opening the _grandparent_
-         * key.
-         */
-        if (ret != ERROR_SUCCESS) {
-            if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
-                           &key) == ERROR_SUCCESS) {
-                RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
-                RegCloseKey(key);
-            }
-        }
+                  &key) == ERROR_SUCCESS) {
+       RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
+       ret = RegEnumKey(key, 0, name, sizeof(name));
+       RegCloseKey(key);
+       /*
+        * If the parent key had no other children, we must delete
+        * it in its turn. That means opening the _grandparent_
+        * key.
+        */
+       if (ret != ERROR_SUCCESS) {
+           if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
+                          &key) == ERROR_SUCCESS) {
+               RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
+               RegCloseKey(key);
+           }
+       }
     }
     /*
      * Now we're done.
index 2b2fa2c..17eaca3 100644 (file)
@@ -30,40 +30,36 @@ struct ctlpos {
 };
 
 void ctlposinit(struct ctlpos *cp, HWND hwnd,
-                int leftborder, int rightborder, int topborder);
+               int leftborder, int rightborder, int topborder);
 void doctl(struct ctlpos *cp, RECT r,
-           char *wclass, int wstyle, int exstyle,
-           char *wtext, int wid);
+          char *wclass, int wstyle, int exstyle, char *wtext, int wid);
 void bartitle(struct ctlpos *cp, char *name, int id);
 void beginbox(struct ctlpos *cp, char *name, int idbox);
 void endbox(struct ctlpos *cp);
 void multiedit(struct ctlpos *cp, ...);
-void radioline(struct ctlpos *cp,
-               char *text, int id, int nacross, ...);
+void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...);
 void radiobig(struct ctlpos *cp, char *text, int id, ...);
 void checkbox(struct ctlpos *cp, char *text, int id);
 void statictext(struct ctlpos *cp, char *text, int id);
 void staticbtn(struct ctlpos *cp, char *stext, int sid,
-               char *btext, int bid);
+              char *btext, int bid);
 void staticedit(struct ctlpos *cp, char *stext,
-                int sid, int eid, int percentedit);
+               int sid, int eid, int percentedit);
 void staticpassedit(struct ctlpos *cp, char *stext,
-                    int sid, int eid, int percentedit);
+                   int sid, int eid, int percentedit);
 void bigeditctrl(struct ctlpos *cp, char *stext,
-                 int sid, int eid, int lines);
-void ersatztab(struct ctlpos *cp, char *stext, int sid,
-               int lid, int s2id);
+                int sid, int eid, int lines);
+void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id);
 void editbutton(struct ctlpos *cp, char *stext, int sid,
-                int eid, char *btext, int bid);
+               int eid, char *btext, int bid);
 void sesssaver(struct ctlpos *cp, char *text,
-               int staticid, int editid, int listid, ...);
+              int staticid, int editid, int listid, ...);
 void envsetter(struct ctlpos *cp, char *stext, int sid,
-               char *e1stext, int e1sid, int e1id,
-               char *e2stext, int e2sid, int e2id,
-               int listid,
-               char *b1text, int b1id, char *b2text, int b2id);
+              char *e1stext, int e1sid, int e1id,
+              char *e2stext, int e2sid, int e2id,
+              int listid, char *b1text, int b1id, char *b2text, int b2id);
 void charclass(struct ctlpos *cp, char *stext, int sid, int listid,
-               char *btext, int bid, int eid, char *s2text, int s2id);
+              char *btext, int bid, int eid, char *s2text, int s2id);
 void colouredit(struct ctlpos *cp, char *stext, int sid, int listid,
-                char *btext, int bid, ...);
+               char *btext, int bid, ...);
 void progressbar(struct ctlpos *cp, int id);
index 2b4a6bc..5be69b8 100644 (file)
--- a/x11fwd.c
+++ b/x11fwd.c
@@ -64,49 +64,53 @@ extern void sshfwd_write(void *, char *, int);
 struct X11Private {
     struct plug_function_table *fn;
     /* the above variable absolutely *must* be the first in this structure */
-    unsigned char firstpkt[12];        /* first X data packet */
+    unsigned char firstpkt[12];               /* first X data packet */
     char *auth_protocol;
     unsigned char *auth_data;
     int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;
     int verified;
-    void *c;                           /* data used by ssh.c */
+    void *c;                          /* data used by ssh.c */
     Socket s;
 };
 
-void x11_close (Socket s);
+void x11_close(Socket s);
 
 static unsigned char x11_authdata[64];
 static int x11_authdatalen;
 
 void x11_invent_auth(char *proto, int protomaxlen,
-                     char *data, int datamaxlen) {
+                    char *data, int datamaxlen)
+{
     char ourdata[64];
     int i;
 
     /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
     x11_authdatalen = 16;
     for (i = 0; i < 16; i++)
-        x11_authdata[i] = random_byte();
+       x11_authdata[i] = random_byte();
 
     /* Now format for the recipient. */
     strncpy(proto, "MIT-MAGIC-COOKIE-1", protomaxlen);
     ourdata[0] = '\0';
     for (i = 0; i < x11_authdatalen; i++)
-        sprintf(ourdata+strlen(ourdata), "%02x", x11_authdata[i]);
+       sprintf(ourdata + strlen(ourdata), "%02x", x11_authdata[i]);
     strncpy(data, ourdata, datamaxlen);
 }
 
-static int x11_verify(char *proto, unsigned char *data, int dlen) {
+static int x11_verify(char *proto, unsigned char *data, int dlen)
+{
     if (strcmp(proto, "MIT-MAGIC-COOKIE-1") != 0)
-        return 0;                      /* wrong protocol attempted */
+       return 0;                      /* wrong protocol attempted */
     if (dlen != x11_authdatalen)
-        return 0;                      /* cookie was wrong length */
+       return 0;                      /* cookie was wrong length */
     if (memcmp(x11_authdata, data, dlen) != 0)
-        return 0;                      /* cookie was wrong cookie! */
+       return 0;                      /* cookie was wrong cookie! */
     return 1;
 }
 
-static int x11_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
+static int x11_closing(Plug plug, char *error_msg, int error_code,
+                      int calling_back)
+{
     struct X11Private *pr = (struct X11Private *) plug;
 
     /*
@@ -119,7 +123,8 @@ static int x11_closing (Plug plug, char *error_msg, int error_code, int calling_
     return 1;
 }
 
-static int x11_receive (Plug plug, int urgent, char *data, int len) {
+static int x11_receive(Plug plug, int urgent, char *data, int len)
+{
     struct X11Private *pr = (struct X11Private *) plug;
 
     sshfwd_write(pr->c, data, len);
@@ -132,7 +137,8 @@ static int x11_receive (Plug plug, int urgent, char *data, int len) {
  * Returns an error message, or NULL on success.
  * also, fills the SocketsStructure
  */
-char *x11_init (Socket *s, char *display, void *c) {
+char *x11_init(Socket * s, char *display, void *c)
+{
     static struct plug_function_table fn_table = {
        x11_closing,
        x11_receive
@@ -150,11 +156,11 @@ char *x11_init (Socket *s, char *display, void *c) {
      */
     n = strcspn(display, ":");
     if (display[n])
-        displaynum = atoi(display+n+1);
+       displaynum = atoi(display + n + 1);
     else
-        displaynum = 0;                /* sensible default */
-    if (n > sizeof(host)-1)
-        n = sizeof(host)-1;
+       displaynum = 0;                /* sensible default */
+    if (n > sizeof(host) - 1)
+       n = sizeof(host) - 1;
     strncpy(host, display, n);
     host[n] = '\0';
 
@@ -162,7 +168,7 @@ char *x11_init (Socket *s, char *display, void *c) {
      * Try to find host.
      */
     addr = sk_namelookup(host, &dummy_realhost);
-    if ( (err = sk_addr_error(addr)) )
+    if ((err = sk_addr_error(addr)))
        return err;
 
     port = 6000 + displaynum;
@@ -170,7 +176,7 @@ char *x11_init (Socket *s, char *display, void *c) {
     /*
      * Open socket.
      */
-    pr = (struct X11Private *)smalloc(sizeof(struct X11Private));
+    pr = (struct X11Private *) smalloc(sizeof(struct X11Private));
     pr->fn = &fn_table;
     pr->auth_protocol = NULL;
     pr->verified = 0;
@@ -178,8 +184,8 @@ char *x11_init (Socket *s, char *display, void *c) {
     pr->c = c;
 
     pr->s = *s = sk_new(addr, port, 0, 1, (Plug) pr);
-    if ( (err = sk_socket_error(*s)) ) {
-       sfree (pr);
+    if ((err = sk_socket_error(*s))) {
+       sfree(pr);
        return err;
     }
 
@@ -188,15 +194,16 @@ char *x11_init (Socket *s, char *display, void *c) {
     return NULL;
 }
 
-void x11_close (Socket s) {
-    struct X11Private *pr;\r
-       if (!s)\r
-               return;\r
-       pr = (struct X11Private *)sk_get_private_ptr(s);
+void x11_close(Socket s)
+{
+    struct X11Private *pr;
+    \rif (!s)
+       \rreturn;
+    \rpr = (struct X11Private *) sk_get_private_ptr(s);
 
     if (pr->auth_protocol) {
-        sfree(pr->auth_protocol);
-        sfree(pr->auth_data);
+       sfree(pr->auth_protocol);
+       sfree(pr->auth_data);
     }
 
     sfree(pr);
@@ -207,8 +214,9 @@ void x11_close (Socket s) {
 /*
  * Called to send data down the raw connection.
  */
-void x11_send (Socket s, char *data, int len) {
-    struct X11Private *pr = (struct X11Private *)sk_get_private_ptr(s);
+void x11_send(Socket s, char *data, int len)
+{
+    struct X11Private *pr = (struct X11Private *) sk_get_private_ptr(s);
 
     if (s == NULL)
        return;
@@ -217,74 +225,74 @@ void x11_send (Socket s, char *data, int len) {
      * Read the first packet.
      */
     while (len > 0 && pr->data_read < 12)
-        pr->firstpkt[pr->data_read++] = (unsigned char)(len--, *data++);
+       pr->firstpkt[pr->data_read++] = (unsigned char) (len--, *data++);
     if (pr->data_read < 12)
-        return;
+       return;
 
     /*
      * If we have not allocated the auth_protocol and auth_data
      * strings, do so now.
      */
     if (!pr->auth_protocol) {
-        pr->auth_plen = GET_16BIT(pr->firstpkt[0], pr->firstpkt+6);
-        pr->auth_dlen = GET_16BIT(pr->firstpkt[0], pr->firstpkt+8);
-        pr->auth_psize = (pr->auth_plen + 3) &~ 3;
-        pr->auth_dsize = (pr->auth_dlen + 3) &~ 3;
-        /* Leave room for a terminating zero, to make our lives easier. */
-        pr->auth_protocol = (char *)smalloc(pr->auth_psize+1);
-        pr->auth_data = (char *)smalloc(pr->auth_dsize);
+       pr->auth_plen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 6);
+       pr->auth_dlen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 8);
+       pr->auth_psize = (pr->auth_plen + 3) & ~3;
+       pr->auth_dsize = (pr->auth_dlen + 3) & ~3;
+       /* Leave room for a terminating zero, to make our lives easier. */
+       pr->auth_protocol = (char *) smalloc(pr->auth_psize + 1);
+       pr->auth_data = (char *) smalloc(pr->auth_dsize);
     }
 
     /*
      * Read the auth_protocol and auth_data strings.
      */
     while (len > 0 && pr->data_read < 12 + pr->auth_psize)
-        pr->auth_protocol[pr->data_read++ - 12] = (len--, *data++);
+       pr->auth_protocol[pr->data_read++ - 12] = (len--, *data++);
     while (len > 0 && pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)
-        pr->auth_data[pr->data_read++ - 12 -
-                      pr->auth_psize] = (unsigned char)(len--, *data++);
+       pr->auth_data[pr->data_read++ - 12 -
+                     pr->auth_psize] = (unsigned char) (len--, *data++);
     if (pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)
-        return;
+       return;
 
     /*
      * If we haven't verified the authentication, do so now.
      */
     if (!pr->verified) {
-        int ret;
-
-        pr->auth_protocol[pr->auth_plen] = '\0';   /* ASCIZ */
-        ret = x11_verify(pr->auth_protocol, pr->auth_data, pr->auth_dlen);
-
-        /*
-         * If authentication failed, construct and send an error
-         * packet, then terminate the connection.
-         */
-        if (!ret) {
-            char message[] = "Authentication failed at PuTTY X11 proxy";
-            unsigned char reply[8 + sizeof(message) + 4];
-            int msglen = sizeof(message)-1;   /* skip zero byte */
-            int msgsize = (msglen+3) &~ 3;
-            reply[0] = 0;              /* failure */
-            reply[1] = msglen;         /* length of reason string */
-            memcpy(reply+2, pr->firstpkt+2, 4);   /* major/minor proto vsn */
-            PUT_16BIT(pr->firstpkt[0], reply+6, msglen >> 2);   /* data len */
-            memset(reply+8, 0, msgsize);
-            memcpy(reply+8, message, msglen);
-            sshfwd_write(pr->c, reply, 8+msgsize);
-            sshfwd_close(pr->c);
-            x11_close(s);
-            return;
-        }
-
-        /*
-         * Now we know we're going to accept the connection. Strip
-         * the auth data. (TODO: if we ever work out how, we should
-         * replace some real auth data in here.)
-         */
-        PUT_16BIT(pr->firstpkt[0], pr->firstpkt+6, 0);   /* auth proto */ 
-        PUT_16BIT(pr->firstpkt[0], pr->firstpkt+8, 0);   /* auth data */
-        sk_write(s, pr->firstpkt, 12);
-        pr->verified = 1;
+       int ret;
+
+       pr->auth_protocol[pr->auth_plen] = '\0';        /* ASCIZ */
+       ret = x11_verify(pr->auth_protocol, pr->auth_data, pr->auth_dlen);
+
+       /*
+        * If authentication failed, construct and send an error
+        * packet, then terminate the connection.
+        */
+       if (!ret) {
+           char message[] = "Authentication failed at PuTTY X11 proxy";
+           unsigned char reply[8 + sizeof(message) + 4];
+           int msglen = sizeof(message) - 1;   /* skip zero byte */
+           int msgsize = (msglen + 3) & ~3;
+           reply[0] = 0;              /* failure */
+           reply[1] = msglen;         /* length of reason string */
+           memcpy(reply + 2, pr->firstpkt + 2, 4);     /* major/minor proto vsn */
+           PUT_16BIT(pr->firstpkt[0], reply + 6, msglen >> 2); /* data len */
+           memset(reply + 8, 0, msgsize);
+           memcpy(reply + 8, message, msglen);
+           sshfwd_write(pr->c, reply, 8 + msgsize);
+           sshfwd_close(pr->c);
+           x11_close(s);
+           return;
+       }
+
+       /*
+        * Now we know we're going to accept the connection. Strip
+        * the auth data. (TODO: if we ever work out how, we should
+        * replace some real auth data in here.)
+        */
+       PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 6, 0);        /* auth proto */
+       PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 8, 0);        /* auth data */
+       sk_write(s, pr->firstpkt, 12);
+       pr->verified = 1;
     }
 
     /*
diff --git a/xlat.c b/xlat.c
index 092f5ca..c1d9efc 100644 (file)
--- a/xlat.c
+++ b/xlat.c
 #include <stdio.h>
 #include "putty.h"
 
-static unsigned char win2koi[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
-    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
-    160,161,162,163,164,189,166,167,179,169,180,171,172,173,174,183,
-    176,177,182,166,173,181,182,183,163,185,164,187,188,189,190,167,
-    225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
-    242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
-    193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
-    210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209
+static unsigned char win2koi[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
+    142, 143,
+    144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+    158, 159,
+    160, 161, 162, 163, 164, 189, 166, 167, 179, 169, 180, 171, 172, 173,
+    174, 183,
+    176, 177, 182, 166, 173, 181, 182, 183, 163, 185, 164, 187, 188, 189,
+    190, 167,
+    225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, 236, 237, 238,
+    239, 240,
+    242, 243, 244, 245, 230, 232, 227, 254, 251, 253, 255, 249, 248, 252,
+    224, 241,
+    193, 194, 215, 199, 196, 197, 214, 218, 201, 202, 203, 204, 205, 206,
+    207, 208,
+    210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220,
+    192, 209
 };
 
-static unsigned char koi2win[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
-    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
-    160,161,162,184,186,165,179,191,168,169,170,171,172,180,174,175,
-    176,177,178,168,170,181,178,175,184,185,186,187,188,165,190,191,
-    254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
-    239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
-    222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206,
-    207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218
+static unsigned char koi2win[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
+    142, 143,
+    144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+    158, 159,
+    160, 161, 162, 184, 186, 165, 179, 191, 168, 169, 170, 171, 172, 180,
+    174, 175,
+    176, 177, 178, 168, 170, 181, 178, 175, 184, 185, 186, 187, 188, 165,
+    190, 191,
+    254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, 234, 235, 236,
+    237, 238,
+    239, 255, 240, 241, 242, 243, 230, 226, 252, 251, 231, 248, 253, 249,
+    247, 250,
+    222, 192, 193, 214, 196, 197, 212, 195, 213, 200, 201, 202, 203, 204,
+    205, 206,
+    207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217,
+    215, 218
 };
 
-static unsigned char xlatWIN1250toISO88592[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    128,129, 39,131, 34, 46,124,124,136, 47,169, 60,166,171,174,172,
-    144, 96, 39, 34, 34, 42, 45, 45,152, 84,185, 62,182,187,190,188,
-    160,183,162,163,164,161,124,167,168, 99,170, 34, 39,173, 82,175,
-    176, 63,178,179,180,117,182,255,184,177,186, 34,165,189,181,191,
-    192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
-    208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
-    224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
-    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
+static unsigned char xlatWIN1250toISO88592[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    128, 129, 39, 131, 34, 46, 124, 124, 136, 47, 169, 60, 166, 171, 174,
+    172,
+    144, 96, 39, 34, 34, 42, 45, 45, 152, 84, 185, 62, 182, 187, 190, 188,
+    160, 183, 162, 163, 164, 161, 124, 167, 168, 99, 170, 34, 39, 173, 82,
+    175,
+    176, 63, 178, 179, 180, 117, 182, 255, 184, 177, 186, 34, 165, 189,
+    181, 191,
+    192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
+    206, 207,
+    208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
+    222, 223,
+    224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237,
+    238, 239,
+    240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
+    254, 255
 };
 
-static unsigned char xlatISO88592toWIN1250[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
-    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
-    160,165,162,163,164,188,140,167,168,138,170,141,143,173,142,175,
-    176,185,178,179,180,190,156,161,184,154,186,157,159,189,158,191,
-    192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
-    208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
-    224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
-    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
+static unsigned char xlatISO88592toWIN1250[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
+    142, 143,
+    144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+    158, 159,
+    160, 165, 162, 163, 164, 188, 140, 167, 168, 138, 170, 141, 143, 173,
+    142, 175,
+    176, 185, 178, 179, 180, 190, 156, 161, 184, 154, 186, 157, 159, 189,
+    158, 191,
+    192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
+    206, 207,
+    208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
+    222, 223,
+    224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237,
+    238, 239,
+    240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
+    254, 255
 };
 
-static unsigned char xlatISO88592toCP852[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    242, 32, 34, 32, 34, 46, 43, 35, 32, 47,138, 60,151,141,166,141,
-    032, 34, 34, 34, 34,254, 45, 45, 32,126,154, 62,152,157,167,171,
-    255,164,244,157,207,149,151,245,249,230,184,155,141,240,166,189,
-    248,165,247,136,239,150,152,243,242,231,173,156,171,241,167,190,
-    232,181,182,198,142,145,143,128,172,144,168,211,183,214,215,210,
-    209,227,213,224,226,138,153,158,252,222,233,235,154,237,221,225,
-    234,160,131,199,132,146,134,135,159,130,169,137,216,161,140,212,
-    208,228,229,162,147,139,148,246,253,133,163,251,129,236,238,250,
+static unsigned char xlatISO88592toCP852[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    242, 32, 34, 32, 34, 46, 43, 35, 32, 47, 138, 60, 151, 141, 166, 141,
+    032, 34, 34, 34, 34, 254, 45, 45, 32, 126, 154, 62, 152, 157, 167, 171,
+    255, 164, 244, 157, 207, 149, 151, 245, 249, 230, 184, 155, 141, 240,
+    166, 189,
+    248, 165, 247, 136, 239, 150, 152, 243, 242, 231, 173, 156, 171, 241,
+    167, 190,
+    232, 181, 182, 198, 142, 145, 143, 128, 172, 144, 168, 211, 183, 214,
+    215, 210,
+    209, 227, 213, 224, 226, 138, 153, 158, 252, 222, 233, 235, 154, 237,
+    221, 225,
+    234, 160, 131, 199, 132, 146, 134, 135, 159, 130, 169, 137, 216, 161,
+    140, 212,
+    208, 228, 229, 162, 147, 139, 148, 246, 253, 133, 163, 251, 129, 236,
+    238, 250,
 };
 
-static unsigned char xlatCP852toISO88592[] =
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 
-     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 
-     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 
-     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 
-     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111,
-    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
-    199,252,233,226,228,249,230,231,179,235,138,245,238,141,196,198,
-    201,197,229,244,246,165,181,140,156,214,154,171,187,157,215,232,
-    225,237,243,250,161,177,142,158,202,234,170,159,200,186,174,175,
-    176,177,178,179,180,193,194,204,170,185,186,187,188,175,191,191,
-    192,193,194,195,196,197,195,227,200,201,202,203,204,205,206,164,
-    240,208,207,203,239,210,205,206,236,217,218,219,220,222,217,223,
-    211,223,212,209,241,242,169,185,192,218,224,219,253,221,254,180,
-    173,189,128,183,162,167,247,178,176,168,255,251,216,248,149,160,
+static unsigned char xlatCP852toISO88592[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+    64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+    80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+    96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
+    111,
+    112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
+    126, 127,
+    199, 252, 233, 226, 228, 249, 230, 231, 179, 235, 138, 245, 238, 141,
+    196, 198,
+    201, 197, 229, 244, 246, 165, 181, 140, 156, 214, 154, 171, 187, 157,
+    215, 232,
+    225, 237, 243, 250, 161, 177, 142, 158, 202, 234, 170, 159, 200, 186,
+    174, 175,
+    176, 177, 178, 179, 180, 193, 194, 204, 170, 185, 186, 187, 188, 175,
+    191, 191,
+    192, 193, 194, 195, 196, 197, 195, 227, 200, 201, 202, 203, 204, 205,
+    206, 164,
+    240, 208, 207, 203, 239, 210, 205, 206, 236, 217, 218, 219, 220, 222,
+    217, 223,
+    211, 223, 212, 209, 241, 242, 169, 185, 192, 218, 224, 219, 253, 221,
+    254, 180,
+    173, 189, 128, 183, 162, 167, 247, 178, 176, 168, 255, 251, 216, 248,
+    149, 160,
 };
 
 unsigned char xlat_kbd2tty(unsigned char c)
 {
-    if(cfg.xlat_enablekoiwin)
+    if (cfg.xlat_enablekoiwin)
        return win2koi[c];
     else if (cfg.xlat_88592w1250 || cfg.xlat_88592cp852)
-        return xlatWIN1250toISO88592[c];
+       return xlatWIN1250toISO88592[c];
     return c;
 }
 
 unsigned char xlat_tty2scr(unsigned char c)
 {
-    if(cfg.xlat_enablekoiwin)
+    if (cfg.xlat_enablekoiwin)
        return koi2win[c];
     else if (cfg.xlat_88592w1250)
-        return xlatISO88592toWIN1250[c];
+       return xlatISO88592toWIN1250[c];
     else if (cfg.xlat_88592cp852)
-        return xlatISO88592toCP852[c];
+       return xlatISO88592toCP852[c];
     return c;
 }
 
 
-static unsigned char latkbd2_win[]=
-{
-      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
-     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
-     32, 33,221, 35, 36, 37, 38,253, 40, 41, 42,178,225,186,254, 46,
-     48, 49, 50, 51, 52, 53, 54, 55, 56, 57,198,230,193,179,222, 44,
-     64,212,200,209,194,211,192,207,208,216,206,203,196,220,210,217,
-    199,201,202,219,197,195,204,214,215,205,223,245,191,250, 94,170,
-     96,244,232,241,226,243,224,239,240,248,238,235,228,252,242,249,
-    231,233,234,251,229,227,236,246,247,237,255,213,175,218,126,127,
-    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
-    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
-    160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
-    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
-    192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
-    208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
-    224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
-    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
+static unsigned char latkbd2_win[] = {
+    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+    32, 33, 221, 35, 36, 37, 38, 253, 40, 41, 42, 178, 225, 186, 254, 46,
+    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 198, 230, 193, 179, 222, 44,
+    64, 212, 200, 209, 194, 211, 192, 207, 208, 216, 206, 203, 196, 220,
+    210, 217,
+    199, 201, 202, 219, 197, 195, 204, 214, 215, 205, 223, 245, 191, 250,
+    94, 170,
+    96, 244, 232, 241, 226, 243, 224, 239, 240, 248, 238, 235, 228, 252,
+    242, 249,
+    231, 233, 234, 251, 229, 227, 236, 246, 247, 237, 255, 213, 175, 218,
+    126, 127,
+    128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
+    142, 143,
+    144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+    158, 159,
+    160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173,
+    174, 175,
+    176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
+    190, 191,
+    192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
+    206, 207,
+    208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
+    222, 223,
+    224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237,
+    238, 239,
+    240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
+    254, 255
 };
 
-unsigned char xlat_latkbd2win(unsigned char  c)
+unsigned char xlat_latkbd2win(unsigned char c)
 {
-    if(cfg.xlat_capslockcyr)
+    if (cfg.xlat_capslockcyr)
        return latkbd2_win[c];
     return c;
 }