diff --git a/Recipe b/Recipe index bd2962f8..4bad3f33 100644 --- a/Recipe +++ b/Recipe @@ -1,5 +1,5 @@ # -*- makefile -*- -# +# # This file describes which PuTTY programs are made up from which # object and resource files. It is processed into the various # Makefiles by means of a Perl script. Makefile changes should diff --git a/charset/charset.h b/charset/charset.h index bc5ae3ac..a967aab9 100644 --- a/charset/charset.h +++ b/charset/charset.h @@ -13,9 +13,9 @@ * character sets known to this library. */ typedef enum { - CS_NONE, /* used for reporting errors, etc */ + CS_NONE, /* used for reporting errors, etc */ CS_ISO8859_1, - CS_ISO8859_1_X11, /* X font encoding with VT100 glyphs */ + CS_ISO8859_1_X11, /* X font encoding with VT100 glyphs */ CS_ISO8859_2, CS_ISO8859_3, CS_ISO8859_4, @@ -77,7 +77,7 @@ typedef struct { /* * Routine to convert a MB/SB character set to Unicode. - * + * * This routine accepts some number of bytes, updates a state * variable, and outputs some number of Unicode characters. There * are no guarantees. You can't even guarantee that at most one @@ -86,12 +86,12 @@ typedef struct { * then you suddenly see FE. Now you need to output _two_ error * characters - one for the incomplete sequence E1 80, and one for * the completely invalid UTF-8 byte FE. - * + * * Returns the number of wide characters output; will never output * more than the size of the buffer (as specified on input). * Advances the `input' pointer and decrements `inlen', to indicate * how far along the input string it got. - * + * * The sequence of `errlen' wide characters pointed to by `errstr' * will be used to indicate a conversion error. If `errstr' is * NULL, `errlen' will be ignored, and the library will choose @@ -101,21 +101,21 @@ typedef struct { int charset_to_unicode(const char **input, int *inlen, wchar_t *output, int outlen, - int charset, charset_state *state, - const wchar_t *errstr, int errlen); + int charset, charset_state *state, + const wchar_t *errstr, int errlen); /* * Routine to convert Unicode to an MB/SB character set. - * + * * This routine accepts some number of Unicode characters, updates * a state variable, and outputs some number of bytes. - * + * * Returns the number of bytes characters output; will never output * more than the size of the buffer (as specified on input), and * will never output a partial MB character. Advances the `input' * pointer and decrements `inlen', to indicate how far along the * input string it got. - * + * * The sequence of `errlen' characters pointed to by `errstr' will * be used to indicate a conversion error. If `errstr' is NULL, * `errlen' will be ignored, and the library will choose something @@ -125,8 +125,8 @@ int charset_to_unicode(const char **input, int *inlen, int charset_from_unicode(const wchar_t **input, int *inlen, char *output, int outlen, - int charset, charset_state *state, - const char *errstr, int errlen); + int charset, charset_state *state, + const char *errstr, int errlen); /* * Convert X11 encoding names to and from our charset identifiers. @@ -152,6 +152,6 @@ int charset_localenc_nth(int n); * Convert Mac OS script/region/font to our charset identifiers. */ int charset_from_macenc(int script, int region, int sysvers, - const char *fontname); + const char *fontname); #endif /* charset_charset_h */ diff --git a/charset/enum.c b/charset/enum.c index 347647d1..f659e846 100644 --- a/charset/enum.c +++ b/charset/enum.c @@ -1,12 +1,12 @@ /* * enum.c - enumerate all charsets defined by the library. - * + * * This file maintains a list of every other source file which * contains ENUM_CHARSET definitions. It #includes each one with * ENUM_CHARSETS defined, which causes those source files to do * nothing at all except call the ENUM_CHARSET macro on each * charset they define. - * + * * This file in turn is included from various other places, with * the ENUM_CHARSET macro defined to various different things. This * allows us to have multiple implementations of the master charset diff --git a/charset/fromucs.c b/charset/fromucs.c index 6ccdb864..a4100e3f 100644 --- a/charset/fromucs.c +++ b/charset/fromucs.c @@ -21,29 +21,29 @@ static void charset_emit(void *ctx, long int output) int outlen; if (output == ERROR) { - p = param->errstr; - outlen = param->errlen; + p = param->errstr; + outlen = param->errlen; } else { - outval = output; - p = &outval; - outlen = 1; + outval = output; + p = &outval; + outlen = 1; } if (param->outlen >= outlen) { - while (outlen > 0) { - *param->output++ = *p++; - param->outlen--; - outlen--; - } + while (outlen > 0) { + *param->output++ = *p++; + param->outlen--; + outlen--; + } } else { - param->stopped = 1; + param->stopped = 1; } } int charset_from_unicode(const wchar_t **input, int *inlen, char *output, int outlen, - int charset, charset_state *state, - const char *errstr, int errlen) + int charset, charset_state *state, + const char *errstr, int errlen) { charset_spec const *spec = charset_find_spec(charset); charset_state localstate; @@ -57,36 +57,36 @@ int charset_from_unicode(const wchar_t **input, int *inlen, * charset_emit will expect a valid errstr. */ if (!errstr) { - /* *shrug* this is good enough, and consistent across all SBCS... */ - param.errstr = "."; - param.errlen = 1; + /* *shrug* this is good enough, and consistent across all SBCS... */ + param.errstr = "."; + param.errlen = 1; } param.errstr = errstr; param.errlen = errlen; if (!state) { - localstate.s0 = 0; + localstate.s0 = 0; } else { - localstate = *state; /* structure copy */ + localstate = *state; /* structure copy */ } state = &localstate; while (*inlen > 0) { - int lenbefore = param.output - output; - spec->write(spec, **input, &localstate, charset_emit, ¶m); - if (param.stopped) { - /* - * The emit function has _tried_ to output some - * characters, but ran up against the end of the - * buffer. Leave immediately, and return what happened - * _before_ attempting to process this character. - */ - return lenbefore; - } - if (state) - *state = localstate; /* structure copy */ - (*input)++; - (*inlen)--; + int lenbefore = param.output - output; + spec->write(spec, **input, &localstate, charset_emit, ¶m); + if (param.stopped) { + /* + * The emit function has _tried_ to output some + * characters, but ran up against the end of the + * buffer. Leave immediately, and return what happened + * _before_ attempting to process this character. + */ + return lenbefore; + } + if (state) + *state = localstate; /* structure copy */ + (*input)++; + (*inlen)--; } return param.output - output; } diff --git a/charset/internal.h b/charset/internal.h index 38df2eaa..32d0f6d5 100644 --- a/charset/internal.h +++ b/charset/internal.h @@ -9,13 +9,13 @@ #define lenof(x) ( sizeof((x)) / sizeof(*(x)) ) /* This is an invalid Unicode value used to indicate an error. */ -#define ERROR 0xFFFFL /* Unicode value representing error */ +#define ERROR 0xFFFFL /* Unicode value representing error */ typedef struct charset_spec charset_spec; typedef struct sbcs_data sbcs_data; struct charset_spec { - int charset; /* numeric identifier */ + int charset; /* numeric identifier */ /* * A function to read the character set and output Unicode @@ -24,8 +24,8 @@ struct charset_spec { * on the input. */ void (*read)(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx); + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx); /* * A function to read Unicode characters and output in this * character set. The `emit' function expects to get byte @@ -33,8 +33,8 @@ struct charset_spec { * non-representable characters on the input. */ void (*write)(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx); + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx); void const *data; }; @@ -60,7 +60,7 @@ struct sbcs_data { * position in this table, you branch according to whether * sbcs2ucs[ucs2sbcs[X]] is less than, greater than, or equal * to U. - * + * * Note that since there may be fewer than 256 valid byte * values in a particular SBCS, we must supply the length of * this table as well as the contents. @@ -74,11 +74,11 @@ struct sbcs_data { */ charset_spec const *charset_find_spec(int charset); void read_sbcs(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx); + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx); void write_sbcs(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx); + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx); /* * Placate compiler warning about unused parameters, of which we diff --git a/charset/localenc.c b/charset/localenc.c index a24126d3..4aa4ae66 100644 --- a/charset/localenc.c +++ b/charset/localenc.c @@ -5,7 +5,7 @@ * announcing what character set it will be using), and a set of * enumeration functions which return a list of supported * encodings one by one. - * + * * charset_from_localenc will attempt all other text translations * as well as this table, to maximise the number of different ways * you can select a supported charset. @@ -83,10 +83,10 @@ const char *charset_to_localenc(int charset) int i; for (i = 0; i < (int)lenof(localencs); i++) - if (charset == localencs[i].charset) - return localencs[i].name; + if (charset == localencs[i].charset) + return localencs[i].name; - return NULL; /* not found */ + return NULL; /* not found */ } int charset_from_localenc(const char *name) @@ -94,24 +94,24 @@ int charset_from_localenc(const char *name) int i; if ( (i = charset_from_mimeenc(name)) != CS_NONE) - return i; + return i; if ( (i = charset_from_xenc(name)) != CS_NONE) - return i; + return i; for (i = 0; i < (int)lenof(localencs); i++) { - const char *p, *q; - p = name; - q = localencs[i].name; - while (*p || *q) { - if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) - break; - p++; q++; - } - if (!*p && !*q) - return localencs[i].charset; + const char *p, *q; + p = name; + q = localencs[i].name; + while (*p || *q) { + if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) + break; + p++; q++; + } + if (!*p && !*q) + return localencs[i].charset; } - return CS_NONE; /* not found */ + return CS_NONE; /* not found */ } int charset_localenc_nth(int n) @@ -119,8 +119,8 @@ int charset_localenc_nth(int n) int i; for (i = 0; i < (int)lenof(localencs); i++) - if (localencs[i].return_in_enum && !n--) - return localencs[i].charset; + if (localencs[i].return_in_enum && !n--) + return localencs[i].charset; - return CS_NONE; /* end of list */ + return CS_NONE; /* end of list */ } diff --git a/charset/macenc.c b/charset/macenc.c index bf70e9c2..cde5fb89 100644 --- a/charset/macenc.c +++ b/charset/macenc.c @@ -10,10 +10,10 @@ * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -38,39 +38,39 @@ * independent of that. */ -#define smRoman 0 -#define smJapanese 1 -#define smTradChinese 2 -#define smKorean 3 -#define smArabic 4 -#define smHebrew 5 -#define smCyrillic 7 -#define smDevenagari 9 -#define smGurmukhi 10 -#define smGujurati 11 -#define smThai 21 -#define smSimpChinese 25 -#define smTibetan 26 -#define smEthiopic 28 -#define smCentralEuroRoman 29 +#define smRoman 0 +#define smJapanese 1 +#define smTradChinese 2 +#define smKorean 3 +#define smArabic 4 +#define smHebrew 5 +#define smCyrillic 7 +#define smDevenagari 9 +#define smGurmukhi 10 +#define smGujurati 11 +#define smThai 21 +#define smSimpChinese 25 +#define smTibetan 26 +#define smEthiopic 28 +#define smCentralEuroRoman 29 -#define verGreece 20 -#define verIceland 21 -#define verTurkey 24 -#define verYugoCroatian 25 -#define verRomania 39 -#define verFaroeIsl 47 -#define verIran 48 -#define verRussia 49 -#define verSlovenian 66 -#define verCroatia 68 -#define verBulgaria 72 -#define verScottishGaelic 75 -#define verManxGaelic 76 -#define verBreton 77 -#define verNunavut 78 -#define verWelsh 79 -#define verIrishGaelicScript 81 +#define verGreece 20 +#define verIceland 21 +#define verTurkey 24 +#define verYugoCroatian 25 +#define verRomania 39 +#define verFaroeIsl 47 +#define verIran 48 +#define verRussia 49 +#define verSlovenian 66 +#define verCroatia 68 +#define verBulgaria 72 +#define verScottishGaelic 75 +#define verManxGaelic 76 +#define verBreton 77 +#define verNunavut 78 +#define verWelsh 79 +#define verIrishGaelicScript 81 static const struct { int script; @@ -152,17 +152,17 @@ static const struct { }; int charset_from_macenc(int script, int region, int sysvers, - char const *fontname) + char const *fontname) { int i; for (i = 0; i < (int)lenof(macencs); i++) - if ((macencs[i].script == script) && - (macencs[i].region < 0 || macencs[i].region == region) && - (macencs[i].sysvermin <= sysvers) && - (macencs[i].fontname == NULL || - (fontname != NULL && strcmp(macencs[i].fontname, fontname) == 0))) - return macencs[i].charset; + if ((macencs[i].script == script) && + (macencs[i].region < 0 || macencs[i].region == region) && + (macencs[i].sysvermin <= sysvers) && + (macencs[i].fontname == NULL || + (fontname != NULL && strcmp(macencs[i].fontname, fontname) == 0))) + return macencs[i].charset; return CS_NONE; } diff --git a/charset/mimeenc.c b/charset/mimeenc.c index fb9243c6..2fec6d26 100644 --- a/charset/mimeenc.c +++ b/charset/mimeenc.c @@ -1,7 +1,7 @@ /* * mimeenc.c - translate our internal character set codes to and * from MIME standard character-set names. - * + * */ #include @@ -14,9 +14,9 @@ static const struct { } mimeencs[] = { /* * These names are taken from - * + * * http://www.iana.org/assignments/character-sets - * + * * Where multiple encoding names map to the same encoding id * (such as the variety of aliases for ISO-8859-1), the first * is considered canonical and will be returned when @@ -192,10 +192,10 @@ const char *charset_to_mimeenc(int charset) int i; for (i = 0; i < (int)lenof(mimeencs); i++) - if (charset == mimeencs[i].charset) - return mimeencs[i].name; + if (charset == mimeencs[i].charset) + return mimeencs[i].name; - return NULL; /* not found */ + return NULL; /* not found */ } int charset_from_mimeenc(const char *name) @@ -203,17 +203,17 @@ int charset_from_mimeenc(const char *name) int i; for (i = 0; i < (int)lenof(mimeencs); i++) { - const char *p, *q; - p = name; - q = mimeencs[i].name; - while (*p || *q) { - if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) - break; - p++; q++; - } - if (!*p && !*q) - return mimeencs[i].charset; + const char *p, *q; + p = name; + q = mimeencs[i].name; + while (*p || *q) { + if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) + break; + p++; q++; + } + if (!*p && !*q) + return mimeencs[i].charset; } - return CS_NONE; /* not found */ + return CS_NONE; /* not found */ } diff --git a/charset/sbcs.c b/charset/sbcs.c index 8e2a2274..9d9a3c94 100644 --- a/charset/sbcs.c +++ b/charset/sbcs.c @@ -13,8 +13,8 @@ */ void read_sbcs(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx) + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx) { const struct sbcs_data *sd = charset->data; @@ -24,8 +24,8 @@ void read_sbcs(charset_spec const *charset, long int input_chr, } void write_sbcs(charset_spec const *charset, long int input_chr, - charset_state *state, - void (*emit)(void *ctx, long int output), void *emitctx) + charset_state *state, + void (*emit)(void *ctx, long int output), void *emitctx) { const struct sbcs_data *sd = charset->data; int i, j, k, c; @@ -38,16 +38,16 @@ void write_sbcs(charset_spec const *charset, long int input_chr, i = -1; j = sd->nvalid; while (i+1 < j) { - k = (i+j)/2; - c = sd->ucs2sbcs[k]; - if (input_chr < sd->sbcs2ucs[c]) - j = k; - else if (input_chr > sd->sbcs2ucs[c]) - i = k; - else { - emit(emitctx, c); - return; - } + k = (i+j)/2; + c = sd->ucs2sbcs[k]; + if (input_chr < sd->sbcs2ucs[c]) + j = k; + else if (input_chr > sd->sbcs2ucs[c]) + i = k; + else { + emit(emitctx, c); + return; + } } emit(emitctx, ERROR); } diff --git a/charset/sbcs.dat b/charset/sbcs.dat index 3440dd20..4fe4a4ad 100644 --- a/charset/sbcs.dat +++ b/charset/sbcs.dat @@ -1,5 +1,5 @@ Data file defining single-byte character sets. - + All lines which begin with whitespace are considered comments. To generate an SBCS table from a unicode.org mapping table: @@ -588,7 +588,7 @@ XXXX 2018 2019 201c 201d 2022 2013 2014 02dc 2122 XXXX 203a 0153 XXXX XXXX 0178 0111 00f1 0323 00f3 00f4 01a1 00f6 00f7 00f8 00f9 00fa 00fb 00fc 01b0 20ab 00ff KOI8-R, generated by this code: - + { echo charset CS_KOI8_R; gensbcs http://www.unicode.org/Public/MAPPINGS/VENDORS/MISC/KOI8-R.TXT; } diff --git a/charset/sbcsgen.pl b/charset/sbcsgen.pl index 56eb61e3..078aebf7 100644 --- a/charset/sbcsgen.pl +++ b/charset/sbcsgen.pl @@ -32,24 +32,24 @@ my @sortpriority = (); while () { chomp; if (/^charset (.*)$/) { - $charsetname = $1; - @vals = (); - @sortpriority = map { 0 } 0..255; + $charsetname = $1; + @vals = (); + @sortpriority = map { 0 } 0..255; } elsif (/^sortpriority ([^-]*)-([^-]*) (.*)$/) { - for ($i = hex $1; $i <= hex $2; $i++) { - $sortpriority[$i] += $3; - } + for ($i = hex $1; $i <= hex $2; $i++) { + $sortpriority[$i] += $3; + } } elsif (/^[0-9a-fA-FX]/) { - push @vals, map { $_ eq "XXXX" ? -1 : hex $_ } split / +/, $_; - if (scalar @vals > 256) { - die "$infile:$.: charset $charsetname has more than 256 values\n"; - } elsif (scalar @vals == 256) { - &outcharset($charsetname, \@vals, \@sortpriority); - push @charsetnames, $charsetname; - $charsetname = undef; - @vals = (); - @sortpriority = map { 0 } 0..255; - } + push @vals, map { $_ eq "XXXX" ? -1 : hex $_ } split / +/, $_; + if (scalar @vals > 256) { + die "$infile:$.: charset $charsetname has more than 256 values\n"; + } elsif (scalar @vals == 256) { + &outcharset($charsetname, \@vals, \@sortpriority); + push @charsetnames, $charsetname; + $charsetname = undef; + @vals = (); + @sortpriority = map { 0 } 0..255; + } } } @@ -72,36 +72,36 @@ sub outcharset($$$) { $prefix = " "; @sorted = (); for ($i = 0; $i < 256; $i++) { - if ($vals->[$i] < 0) { - printf "%sERROR ", $prefix; - } else { - printf "%s0x%04x", $prefix, $vals->[$i]; - die "ooh? $i\n" unless defined $sortpriority->[$i]; - push @sorted, [$i, $vals->[$i], 0+$sortpriority->[$i]]; - } - if ($i % 8 == 7) { - $prefix = ",\n "; - } else { - $prefix = ", "; - } + if ($vals->[$i] < 0) { + printf "%sERROR ", $prefix; + } else { + printf "%s0x%04x", $prefix, $vals->[$i]; + die "ooh? $i\n" unless defined $sortpriority->[$i]; + push @sorted, [$i, $vals->[$i], 0+$sortpriority->[$i]]; + } + if ($i % 8 == 7) { + $prefix = ",\n "; + } else { + $prefix = ", "; + } } print "\n },\n {\n"; @sorted = sort { ($a->[1] == $b->[1] ? - $b->[2] <=> $a->[2] : - $a->[1] <=> $b->[1]) || + $b->[2] <=> $a->[2] : + $a->[1] <=> $b->[1]) || $a->[0] <=> $b->[0] } @sorted; $prefix = " "; $uval = -1; for ($i = $j = 0; $i < scalar @sorted; $i++) { - next if ($uval == $sorted[$i]->[1]); # low-priority alternative - $uval = $sorted[$i]->[1]; - printf "%s0x%02x", $prefix, $sorted[$i]->[0]; - if ($j % 8 == 7) { - $prefix = ",\n "; - } else { - $prefix = ", "; - } - $j++; + next if ($uval == $sorted[$i]->[1]); # low-priority alternative + $uval = $sorted[$i]->[1]; + printf "%s0x%02x", $prefix, $sorted[$i]->[0]; + if ($j % 8 == 7) { + $prefix = ",\n "; + } else { + $prefix = ", "; + } + $j++; } printf "\n },\n %d\n", $j; print "};\n"; diff --git a/charset/slookup.c b/charset/slookup.c index 7a4d7c28..80d7aeff 100644 --- a/charset/slookup.c +++ b/charset/slookup.c @@ -22,8 +22,8 @@ charset_spec const *charset_find_spec(int charset) int i; for (i = 0; i < (int)lenof(cs_table); i++) - if (cs_table[i]->charset == charset) - return cs_table[i]; + if (cs_table[i]->charset == charset) + return cs_table[i]; return NULL; } diff --git a/charset/toucs.c b/charset/toucs.c index 1df788a6..34d1bf81 100644 --- a/charset/toucs.c +++ b/charset/toucs.c @@ -21,35 +21,35 @@ static void unicode_emit(void *ctx, long int output) int outlen; if (output == ERROR) { - if (param->errstr) { - p = param->errstr; - outlen = param->errlen; - } else { - outval = 0xFFFD; /* U+FFFD REPLACEMENT CHARACTER */ - p = &outval; - outlen = 1; - } + if (param->errstr) { + p = param->errstr; + outlen = param->errlen; + } else { + outval = 0xFFFD; /* U+FFFD REPLACEMENT CHARACTER */ + p = &outval; + outlen = 1; + } } else { - outval = output; - p = &outval; - outlen = 1; + outval = output; + p = &outval; + outlen = 1; } if (param->outlen >= outlen) { - while (outlen > 0) { - *param->output++ = *p++; - param->outlen--; - outlen--; - } + while (outlen > 0) { + *param->output++ = *p++; + param->outlen--; + outlen--; + } } else { - param->stopped = 1; + param->stopped = 1; } } int charset_to_unicode(const char **input, int *inlen, wchar_t *output, int outlen, - int charset, charset_state *state, - const wchar_t *errstr, int errlen) + int charset, charset_state *state, + const wchar_t *errstr, int errlen) { charset_spec const *spec = charset_find_spec(charset); charset_state localstate; @@ -62,28 +62,28 @@ int charset_to_unicode(const char **input, int *inlen, param.stopped = 0; if (!state) { - localstate.s0 = 0; + localstate.s0 = 0; } else { - localstate = *state; /* structure copy */ + localstate = *state; /* structure copy */ } while (*inlen > 0) { - int lenbefore = param.output - output; - spec->read(spec, (unsigned char)**input, &localstate, - unicode_emit, ¶m); - if (param.stopped) { - /* - * The emit function has _tried_ to output some - * characters, but ran up against the end of the - * buffer. Leave immediately, and return what happened - * _before_ attempting to process this character. - */ - return lenbefore; - } - if (state) - *state = localstate; /* structure copy */ - (*input)++; - (*inlen)--; + int lenbefore = param.output - output; + spec->read(spec, (unsigned char)**input, &localstate, + unicode_emit, ¶m); + if (param.stopped) { + /* + * The emit function has _tried_ to output some + * characters, but ran up against the end of the + * buffer. Leave immediately, and return what happened + * _before_ attempting to process this character. + */ + return lenbefore; + } + if (state) + *state = localstate; /* structure copy */ + (*input)++; + (*inlen)--; } return param.output - output; diff --git a/charset/utf8.c b/charset/utf8.c index 13c5baa8..2594fec3 100644 --- a/charset/utf8.c +++ b/charset/utf8.c @@ -19,23 +19,23 @@ static void read_utf8(charset_spec const *charset, long int input_chr, /* * For reading UTF-8, the `state' word contains: - * + * * - in bits 29-31, the number of bytes expected to be in the * current multibyte character (which we can tell instantly * from the first byte, of course). - * + * * - in bits 26-28, the number of bytes _seen so far_ in the * current multibyte character. - * + * * - in the remainder of the word, the current value of the * character, which is shifted upwards by 6 bits to * accommodate each new byte. - * + * * As required, the state is zero when we are not in the middle * of a multibyte character at all. - * + * * For example, when reading E9 8D 8B, starting at state=0: - * + * * - after E9, the state is 0x64000009 * - after 8D, the state is 0x6800024d * - after 8B, the state conceptually becomes 0x6c00934b, at @@ -53,124 +53,124 @@ static void read_utf8(charset_spec const *charset, long int input_chr, */ if (input_chr < 0x80) { - /* - * Single-byte character. If the state is nonzero before - * coming here, output an error for an incomplete sequence. - * Then output the character. - */ - if (state->s0 != 0) { - emit(emitctx, ERROR); - state->s0 = 0; - } - emit(emitctx, input_chr); + /* + * Single-byte character. If the state is nonzero before + * coming here, output an error for an incomplete sequence. + * Then output the character. + */ + if (state->s0 != 0) { + emit(emitctx, ERROR); + state->s0 = 0; + } + emit(emitctx, input_chr); } else if (input_chr == 0xFE || input_chr == 0xFF) { - /* - * FE and FF bytes should _never_ occur in UTF-8. They are - * automatic errors; if the state was nonzero to start - * with, output a further error for an incomplete sequence. - */ - if (state->s0 != 0) { - emit(emitctx, ERROR); - state->s0 = 0; - } - emit(emitctx, ERROR); + /* + * FE and FF bytes should _never_ occur in UTF-8. They are + * automatic errors; if the state was nonzero to start + * with, output a further error for an incomplete sequence. + */ + if (state->s0 != 0) { + emit(emitctx, ERROR); + state->s0 = 0; + } + emit(emitctx, ERROR); } else if (input_chr >= 0x80 && input_chr < 0xC0) { - /* - * Continuation byte. Output an error for an unexpected - * continuation byte, if the state is zero. - */ - if (state->s0 == 0) { - emit(emitctx, ERROR); - } else { - unsigned long charval; - unsigned long topstuff; - int bytes; + /* + * Continuation byte. Output an error for an unexpected + * continuation byte, if the state is zero. + */ + if (state->s0 == 0) { + emit(emitctx, ERROR); + } else { + unsigned long charval; + unsigned long topstuff; + int bytes; - /* - * Otherwise, accumulate more of the character value. - */ - charval = state->s0 & 0x03ffffffL; - charval = (charval << 6) | (input_chr & 0x3F); + /* + * Otherwise, accumulate more of the character value. + */ + charval = state->s0 & 0x03ffffffL; + charval = (charval << 6) | (input_chr & 0x3F); - /* - * Check the byte counts; if we have not reached the - * end of the character, update the state and return. - */ - topstuff = state->s0 & 0xfc000000L; - topstuff += 0x04000000L; /* add one to the byte count */ - if (((topstuff << 3) ^ topstuff) & 0xe0000000L) { - state->s0 = topstuff | charval; - return; - } + /* + * Check the byte counts; if we have not reached the + * end of the character, update the state and return. + */ + topstuff = state->s0 & 0xfc000000L; + topstuff += 0x04000000L; /* add one to the byte count */ + if (((topstuff << 3) ^ topstuff) & 0xe0000000L) { + state->s0 = topstuff | charval; + return; + } - /* - * Now we know we've reached the end of the character. - * `charval' is the Unicode value. We should check for - * various invalid things, and then either output - * charval or an error. In all cases we reset the state - * to zero. - */ - bytes = topstuff >> 29; - state->s0 = 0; + /* + * Now we know we've reached the end of the character. + * `charval' is the Unicode value. We should check for + * various invalid things, and then either output + * charval or an error. In all cases we reset the state + * to zero. + */ + bytes = topstuff >> 29; + state->s0 = 0; - if (charval >= 0xD800 && charval < 0xE000) { - /* - * Surrogates (0xD800-0xDFFF) may never be encoded - * in UTF-8. A surrogate pair in Unicode should - * have been encoded as a single UTF-8 character - * occupying more than three bytes. - */ - emit(emitctx, ERROR); - } else if (charval == 0xFFFE || charval == 0xFFFF) { - /* - * U+FFFE and U+FFFF are invalid Unicode characters - * and may never be encoded in UTF-8. (This is one - * reason why U+FFFF is our way of signalling an - * error to our `emit' function :-) - */ - emit(emitctx, ERROR); - } else if ((charval <= 0x7FL /* && bytes > 1 */) || - (charval <= 0x7FFL && bytes > 2) || - (charval <= 0xFFFFL && bytes > 3) || - (charval <= 0x1FFFFFL && bytes > 4) || - (charval <= 0x3FFFFFFL && bytes > 5)) { - /* - * Overlong sequences are not to be tolerated, - * under any circumstances. - */ - emit(emitctx, ERROR); - } else { - /* - * Oh, all right. We'll let this one off. - */ - emit(emitctx, charval); - } - } + if (charval >= 0xD800 && charval < 0xE000) { + /* + * Surrogates (0xD800-0xDFFF) may never be encoded + * in UTF-8. A surrogate pair in Unicode should + * have been encoded as a single UTF-8 character + * occupying more than three bytes. + */ + emit(emitctx, ERROR); + } else if (charval == 0xFFFE || charval == 0xFFFF) { + /* + * U+FFFE and U+FFFF are invalid Unicode characters + * and may never be encoded in UTF-8. (This is one + * reason why U+FFFF is our way of signalling an + * error to our `emit' function :-) + */ + emit(emitctx, ERROR); + } else if ((charval <= 0x7FL /* && bytes > 1 */) || + (charval <= 0x7FFL && bytes > 2) || + (charval <= 0xFFFFL && bytes > 3) || + (charval <= 0x1FFFFFL && bytes > 4) || + (charval <= 0x3FFFFFFL && bytes > 5)) { + /* + * Overlong sequences are not to be tolerated, + * under any circumstances. + */ + emit(emitctx, ERROR); + } else { + /* + * Oh, all right. We'll let this one off. + */ + emit(emitctx, charval); + } + } } else { - /* - * Lead byte. First output an error for an incomplete - * sequence, if the state is nonzero. - */ - if (state->s0 != 0) - emit(emitctx, ERROR); + /* + * Lead byte. First output an error for an incomplete + * sequence, if the state is nonzero. + */ + if (state->s0 != 0) + emit(emitctx, ERROR); - /* - * Now deal with the lead byte: work out the number of - * bytes we expect to see in this character, and extract - * the initial bits of it too. - */ - if (input_chr >= 0xC0 && input_chr < 0xE0) { - state->s0 = 0x44000000L | (input_chr & 0x1F); - } else if (input_chr >= 0xE0 && input_chr < 0xF0) { - state->s0 = 0x64000000L | (input_chr & 0x0F); - } else if (input_chr >= 0xF0 && input_chr < 0xF8) { - state->s0 = 0x84000000L | (input_chr & 0x07); - } else if (input_chr >= 0xF8 && input_chr < 0xFC) { - state->s0 = 0xa4000000L | (input_chr & 0x03); - } else if (input_chr >= 0xFC && input_chr < 0xFE) { - state->s0 = 0xc4000000L | (input_chr & 0x01); - } + /* + * Now deal with the lead byte: work out the number of + * bytes we expect to see in this character, and extract + * the initial bits of it too. + */ + if (input_chr >= 0xC0 && input_chr < 0xE0) { + state->s0 = 0x44000000L | (input_chr & 0x1F); + } else if (input_chr >= 0xE0 && input_chr < 0xF0) { + state->s0 = 0x64000000L | (input_chr & 0x0F); + } else if (input_chr >= 0xF0 && input_chr < 0xF8) { + state->s0 = 0x84000000L | (input_chr & 0x07); + } else if (input_chr >= 0xF8 && input_chr < 0xFC) { + state->s0 = 0xa4000000L | (input_chr & 0x03); + } else if (input_chr >= 0xFC && input_chr < 0xFE) { + state->s0 = 0xc4000000L | (input_chr & 0x01); + } } } @@ -192,35 +192,35 @@ static void write_utf8(charset_spec const *charset, long int input_chr, * Refuse to output any illegal code points. */ if (input_chr == 0xFFFE || input_chr == 0xFFFF || - (input_chr >= 0xD800 && input_chr < 0xE000)) { - emit(emitctx, ERROR); + (input_chr >= 0xD800 && input_chr < 0xE000)) { + emit(emitctx, ERROR); } else if (input_chr < 0x80) { /* one-byte character */ - emit(emitctx, input_chr); + emit(emitctx, input_chr); } else if (input_chr < 0x800) { /* two-byte character */ - emit(emitctx, 0xC0 | (0x1F & (input_chr >> 6))); - emit(emitctx, 0x80 | (0x3F & (input_chr ))); + emit(emitctx, 0xC0 | (0x1F & (input_chr >> 6))); + emit(emitctx, 0x80 | (0x3F & (input_chr ))); } else if (input_chr < 0x10000) { /* three-byte character */ - emit(emitctx, 0xE0 | (0x0F & (input_chr >> 12))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); - emit(emitctx, 0x80 | (0x3F & (input_chr ))); + emit(emitctx, 0xE0 | (0x0F & (input_chr >> 12))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); + emit(emitctx, 0x80 | (0x3F & (input_chr ))); } else if (input_chr < 0x200000) { /* four-byte character */ - emit(emitctx, 0xF0 | (0x07 & (input_chr >> 18))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); - emit(emitctx, 0x80 | (0x3F & (input_chr ))); + emit(emitctx, 0xF0 | (0x07 & (input_chr >> 18))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); + emit(emitctx, 0x80 | (0x3F & (input_chr ))); } else if (input_chr < 0x4000000) {/* five-byte character */ - emit(emitctx, 0xF8 | (0x03 & (input_chr >> 24))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 18))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); - emit(emitctx, 0x80 | (0x3F & (input_chr ))); - } else { /* six-byte character */ - emit(emitctx, 0xFC | (0x01 & (input_chr >> 30))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 24))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 18))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); - emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); - emit(emitctx, 0x80 | (0x3F & (input_chr ))); + emit(emitctx, 0xF8 | (0x03 & (input_chr >> 24))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 18))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); + emit(emitctx, 0x80 | (0x3F & (input_chr ))); + } else { /* six-byte character */ + emit(emitctx, 0xFC | (0x01 & (input_chr >> 30))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 24))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 18))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 12))); + emit(emitctx, 0x80 | (0x3F & (input_chr >> 6))); + emit(emitctx, 0x80 | (0x3F & (input_chr ))); } } @@ -249,29 +249,29 @@ void utf8_read_test(int line, char *input, int inlen, ...) p = str; for (i = 0; i < inlen; i++) - read_utf8(NULL, input[i] & 0xFF, &state, utf8_emit, &p); + read_utf8(NULL, input[i] & 0xFF, &state, utf8_emit, &p); va_start(ap, inlen); l = 0; for (i = 0; i < p - str; i++) { - l = va_arg(ap, long int); - if (l == -1) { - printf("%d: correct string shorter than output\n", line); - total_errs++; - break; - } - if (l != str[i]) { - printf("%d: char %d came out as %08x, should be %08x\n", + l = va_arg(ap, long int); + if (l == -1) { + printf("%d: correct string shorter than output\n", line); + total_errs++; + break; + } + if (l != str[i]) { + printf("%d: char %d came out as %08x, should be %08x\n", line, i, str[i], (unsigned)l); - total_errs++; - } + total_errs++; + } } if (l != -1) { - l = va_arg(ap, long int); - if (l != -1) { - printf("%d: correct string longer than output\n", line); - total_errs++; - } + l = va_arg(ap, long int); + if (l != -1) { + printf("%d: correct string longer than output\n", line); + total_errs++; + } } va_end(ap); } @@ -288,29 +288,29 @@ void utf8_write_test(int line, const long *input, int inlen, ...) p = str; for (i = 0; i < inlen; i++) - write_utf8(NULL, input[i], &state, utf8_emit, &p); + write_utf8(NULL, input[i], &state, utf8_emit, &p); va_start(ap, inlen); l = 0; for (i = 0; i < p - str; i++) { - l = va_arg(ap, long int); - if (l == -1) { - printf("%d: correct string shorter than output\n", line); - total_errs++; - break; - } - if (l != str[i]) { - printf("%d: char %d came out as %08x, should be %08x\n", + l = va_arg(ap, long int); + if (l == -1) { + printf("%d: correct string shorter than output\n", line); + total_errs++; + break; + } + if (l != str[i]) { + printf("%d: char %d came out as %08x, should be %08x\n", line, i, str[i], (unsigned)l); - total_errs++; - } + total_errs++; + } } if (l != -1) { - l = va_arg(ap, long int); - if (l != -1) { - printf("%d: correct string longer than output\n", line); - total_errs++; - } + l = va_arg(ap, long int); + if (l != -1) { + printf("%d: correct string longer than output\n", line); + total_errs++; + } } va_end(ap); } @@ -322,542 +322,542 @@ int main(void) { printf("read tests beginning\n"); utf8_read_test(TESTSTR("\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5"), - 0x000003BA, /* GREEK SMALL LETTER KAPPA */ - 0x00001F79, /* GREEK SMALL LETTER OMICRON WITH OXIA */ - 0x000003C3, /* GREEK SMALL LETTER SIGMA */ - 0x000003BC, /* GREEK SMALL LETTER MU */ - 0x000003B5, /* GREEK SMALL LETTER EPSILON */ - 0, -1); + 0x000003BA, /* GREEK SMALL LETTER KAPPA */ + 0x00001F79, /* GREEK SMALL LETTER OMICRON WITH OXIA */ + 0x000003C3, /* GREEK SMALL LETTER SIGMA */ + 0x000003BC, /* GREEK SMALL LETTER MU */ + 0x000003B5, /* GREEK SMALL LETTER EPSILON */ + 0, -1); utf8_read_test(TESTSTR("\x00"), - 0x00000000, /* */ - 0, -1); + 0x00000000, /* */ + 0, -1); utf8_read_test(TESTSTR("\xC2\x80"), - 0x00000080, /* */ - 0, -1); + 0x00000080, /* */ + 0, -1); utf8_read_test(TESTSTR("\xE0\xA0\x80"), - 0x00000800, /* */ - 0, -1); + 0x00000800, /* */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x90\x80\x80"), - 0x00010000, /* */ - 0, -1); + 0x00010000, /* */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x88\x80\x80\x80"), - 0x00200000, /* */ - 0, -1); + 0x00200000, /* */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x84\x80\x80\x80\x80"), - 0x04000000, /* */ - 0, -1); + 0x04000000, /* */ + 0, -1); utf8_read_test(TESTSTR("\x7F"), - 0x0000007F, /* */ - 0, -1); + 0x0000007F, /* */ + 0, -1); utf8_read_test(TESTSTR("\xDF\xBF"), - 0x000007FF, /* */ - 0, -1); + 0x000007FF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF\xBD"), - 0x0000FFFD, /* REPLACEMENT CHARACTER */ - 0, -1); + 0x0000FFFD, /* REPLACEMENT CHARACTER */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF\xBF"), - ERROR, /* (invalid char) */ - 0, -1); + ERROR, /* (invalid char) */ + 0, -1); utf8_read_test(TESTSTR("\xF7\xBF\xBF\xBF"), - 0x001FFFFF, /* */ - 0, -1); + 0x001FFFFF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xFB\xBF\xBF\xBF\xBF"), - 0x03FFFFFF, /* */ - 0, -1); + 0x03FFFFFF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xFD\xBF\xBF\xBF\xBF\xBF"), - 0x7FFFFFFF, /* */ - 0, -1); + 0x7FFFFFFF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xED\x9F\xBF"), - 0x0000D7FF, /* */ - 0, -1); + 0x0000D7FF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xEE\x80\x80"), - 0x0000E000, /* */ - 0, -1); + 0x0000E000, /* */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF\xBD"), - 0x0000FFFD, /* REPLACEMENT CHARACTER */ - 0, -1); + 0x0000FFFD, /* REPLACEMENT CHARACTER */ + 0, -1); utf8_read_test(TESTSTR("\xF4\x8F\xBF\xBF"), - 0x0010FFFF, /* */ - 0, -1); + 0x0010FFFF, /* */ + 0, -1); utf8_read_test(TESTSTR("\xF4\x90\x80\x80"), - 0x00110000, /* */ - 0, -1); + 0x00110000, /* */ + 0, -1); utf8_read_test(TESTSTR("\x80"), - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\xBF"), - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF\x80"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF\x80\xBF"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF\x80\xBF\x80"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF\x80\xBF\x80\xBF"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\xBF\x80\xBF\x80\xBF\x80"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF"), - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - ERROR, /* (unexpected continuation byte) */ - 0, -1); + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + ERROR, /* (unexpected continuation byte) */ + 0, -1); utf8_read_test(TESTSTR("\xC0\x20\xC1\x20\xC2\x20\xC3\x20\xC4\x20\xC5\x20\xC6\x20\xC7\x20"), - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + 0, -1); utf8_read_test(TESTSTR("\xE0\x20\xE1\x20\xE2\x20\xE3\x20\xE4\x20\xE5\x20\xE6\x20\xE7\x20\xE8\x20\xE9\x20\xEA\x20\xEB\x20\xEC\x20\xED\x20\xEE\x20\xEF\x20"), - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x20\xF1\x20\xF2\x20\xF3\x20\xF4\x20\xF5\x20\xF6\x20\xF7\x20"), - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x20\xF9\x20\xFA\x20\xFB\x20"), - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x20\xFD\x20"), - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - ERROR, /* (incomplete sequence) */ - 0x00000020, /* SPACE */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + ERROR, /* (incomplete sequence) */ + 0x00000020, /* SPACE */ + 0, -1); utf8_read_test(TESTSTR("\xC0"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xE0\x80"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x80\x80"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x80\x80\x80"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x80\x80\x80\x80"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xDF"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xF7\xBF\xBF"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xFB\xBF\xBF\xBF"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xFD\xBF\xBF\xBF\xBF"), - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF"), - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - ERROR, /* (incomplete sequence) */ - 0, -1); + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + ERROR, /* (incomplete sequence) */ + 0, -1); utf8_read_test(TESTSTR("\xFE"), - ERROR, /* (invalid UTF-8 byte) */ - 0, -1); + ERROR, /* (invalid UTF-8 byte) */ + 0, -1); utf8_read_test(TESTSTR("\xFF"), - ERROR, /* (invalid UTF-8 byte) */ - 0, -1); + ERROR, /* (invalid UTF-8 byte) */ + 0, -1); utf8_read_test(TESTSTR("\xFE\xFE\xFF\xFF"), - ERROR, /* (invalid UTF-8 byte) */ - ERROR, /* (invalid UTF-8 byte) */ - ERROR, /* (invalid UTF-8 byte) */ - ERROR, /* (invalid UTF-8 byte) */ - 0, -1); + ERROR, /* (invalid UTF-8 byte) */ + ERROR, /* (invalid UTF-8 byte) */ + ERROR, /* (invalid UTF-8 byte) */ + ERROR, /* (invalid UTF-8 byte) */ + 0, -1); utf8_read_test(TESTSTR("\xC0\xAF"), - ERROR, /* SOLIDUS (overlong form of 2F) */ - 0, -1); + ERROR, /* SOLIDUS (overlong form of 2F) */ + 0, -1); utf8_read_test(TESTSTR("\xE0\x80\xAF"), - ERROR, /* SOLIDUS (overlong form of 2F) */ - 0, -1); + ERROR, /* SOLIDUS (overlong form of 2F) */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x80\x80\xAF"), - ERROR, /* SOLIDUS (overlong form of 2F) */ - 0, -1); + ERROR, /* SOLIDUS (overlong form of 2F) */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x80\x80\x80\xAF"), - ERROR, /* SOLIDUS (overlong form of 2F) */ - 0, -1); + ERROR, /* SOLIDUS (overlong form of 2F) */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x80\x80\x80\x80\xAF"), - ERROR, /* SOLIDUS (overlong form of 2F) */ - 0, -1); + ERROR, /* SOLIDUS (overlong form of 2F) */ + 0, -1); utf8_read_test(TESTSTR("\xC1\xBF"), - ERROR, /* (overlong form of 7F) */ - 0, -1); + ERROR, /* (overlong form of 7F) */ + 0, -1); utf8_read_test(TESTSTR("\xE0\x9F\xBF"), - ERROR, /* (overlong form of DF BF) */ - 0, -1); + ERROR, /* (overlong form of DF BF) */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x8F\xBF\xBF"), - ERROR, /* (overlong form of EF BF BF) (invalid char) */ - 0, -1); + ERROR, /* (overlong form of EF BF BF) (invalid char) */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x87\xBF\xBF\xBF"), - ERROR, /* (overlong form of F7 BF BF BF) */ - 0, -1); + ERROR, /* (overlong form of F7 BF BF BF) */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x83\xBF\xBF\xBF\xBF"), - ERROR, /* (overlong form of FB BF BF BF BF) */ - 0, -1); + ERROR, /* (overlong form of FB BF BF BF BF) */ + 0, -1); utf8_read_test(TESTSTR("\xC0\x80"), - ERROR, /* (overlong form of 00) */ - 0, -1); + ERROR, /* (overlong form of 00) */ + 0, -1); utf8_read_test(TESTSTR("\xE0\x80\x80"), - ERROR, /* (overlong form of 00) */ - 0, -1); + ERROR, /* (overlong form of 00) */ + 0, -1); utf8_read_test(TESTSTR("\xF0\x80\x80\x80"), - ERROR, /* (overlong form of 00) */ - 0, -1); + ERROR, /* (overlong form of 00) */ + 0, -1); utf8_read_test(TESTSTR("\xF8\x80\x80\x80\x80"), - ERROR, /* (overlong form of 00) */ - 0, -1); + ERROR, /* (overlong form of 00) */ + 0, -1); utf8_read_test(TESTSTR("\xFC\x80\x80\x80\x80\x80"), - ERROR, /* (overlong form of 00) */ - 0, -1); + ERROR, /* (overlong form of 00) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xA0\x80"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAD\xBF"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAE\x80"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAF\xBF"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xB0\x80"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xBE\x80"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xBF\xBF"), - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xA0\x80\xED\xB0\x80"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xA0\x80\xED\xBF\xBF"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAD\xBF\xED\xB0\x80"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAD\xBF\xED\xBF\xBF"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAE\x80\xED\xB0\x80"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAE\x80\xED\xBF\xBF"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAF\xBF\xED\xB0\x80"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xED\xAF\xBF\xED\xBF\xBF"), - ERROR, /* (surrogate) */ - ERROR, /* (surrogate) */ - 0, -1); + ERROR, /* (surrogate) */ + ERROR, /* (surrogate) */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF\xBE"), - ERROR, /* (invalid char) */ - 0, -1); + ERROR, /* (invalid char) */ + 0, -1); utf8_read_test(TESTSTR("\xEF\xBF\xBF"), - ERROR, /* (invalid char) */ - 0, -1); + ERROR, /* (invalid char) */ + 0, -1); printf("read tests completed\n"); printf("write tests beginning\n"); { - const static long str[] = - {0x03BAL, 0x1F79L, 0x03C3L, 0x03BCL, 0x03B5L, 0}; - utf8_write_test(TESTSTR(str), - 0xCE, 0xBA, - 0xE1, 0xBD, 0xB9, - 0xCF, 0x83, - 0xCE, 0xBC, - 0xCE, 0xB5, - 0, -1); + const static long str[] = + {0x03BAL, 0x1F79L, 0x03C3L, 0x03BCL, 0x03B5L, 0}; + utf8_write_test(TESTSTR(str), + 0xCE, 0xBA, + 0xE1, 0xBD, 0xB9, + 0xCF, 0x83, + 0xCE, 0xBC, + 0xCE, 0xB5, + 0, -1); } { - const static long str[] = {0x0000L, 0}; - utf8_write_test(TESTSTR(str), - 0x00, - 0, -1); + const static long str[] = {0x0000L, 0}; + utf8_write_test(TESTSTR(str), + 0x00, + 0, -1); } { - const static long str[] = {0x0080L, 0}; - utf8_write_test(TESTSTR(str), - 0xC2, 0x80, - 0, -1); + const static long str[] = {0x0080L, 0}; + utf8_write_test(TESTSTR(str), + 0xC2, 0x80, + 0, -1); } { - const static long str[] = {0x0800L, 0}; - utf8_write_test(TESTSTR(str), - 0xE0, 0xA0, 0x80, - 0, -1); + const static long str[] = {0x0800L, 0}; + utf8_write_test(TESTSTR(str), + 0xE0, 0xA0, 0x80, + 0, -1); } { - const static long str[] = {0x00010000L, 0}; - utf8_write_test(TESTSTR(str), - 0xF0, 0x90, 0x80, 0x80, - 0, -1); + const static long str[] = {0x00010000L, 0}; + utf8_write_test(TESTSTR(str), + 0xF0, 0x90, 0x80, 0x80, + 0, -1); } { - const static long str[] = {0x00200000L, 0}; - utf8_write_test(TESTSTR(str), - 0xF8, 0x88, 0x80, 0x80, 0x80, - 0, -1); + const static long str[] = {0x00200000L, 0}; + utf8_write_test(TESTSTR(str), + 0xF8, 0x88, 0x80, 0x80, 0x80, + 0, -1); } { - const static long str[] = {0x04000000L, 0}; - utf8_write_test(TESTSTR(str), - 0xFC, 0x84, 0x80, 0x80, 0x80, 0x80, - 0, -1); + const static long str[] = {0x04000000L, 0}; + utf8_write_test(TESTSTR(str), + 0xFC, 0x84, 0x80, 0x80, 0x80, 0x80, + 0, -1); } { - const static long str[] = {0x007FL, 0}; - utf8_write_test(TESTSTR(str), - 0x7F, - 0, -1); + const static long str[] = {0x007FL, 0}; + utf8_write_test(TESTSTR(str), + 0x7F, + 0, -1); } { - const static long str[] = {0x07FFL, 0}; - utf8_write_test(TESTSTR(str), - 0xDF, 0xBF, - 0, -1); + const static long str[] = {0x07FFL, 0}; + utf8_write_test(TESTSTR(str), + 0xDF, 0xBF, + 0, -1); } { - const static long str[] = {0xFFFDL, 0}; - utf8_write_test(TESTSTR(str), - 0xEF, 0xBF, 0xBD, - 0, -1); + const static long str[] = {0xFFFDL, 0}; + utf8_write_test(TESTSTR(str), + 0xEF, 0xBF, 0xBD, + 0, -1); } { - const static long str[] = {0xFFFFL, 0}; - utf8_write_test(TESTSTR(str), - ERROR, - 0, -1); + const static long str[] = {0xFFFFL, 0}; + utf8_write_test(TESTSTR(str), + ERROR, + 0, -1); } { - const static long str[] = {0x001FFFFFL, 0}; - utf8_write_test(TESTSTR(str), - 0xF7, 0xBF, 0xBF, 0xBF, - 0, -1); + const static long str[] = {0x001FFFFFL, 0}; + utf8_write_test(TESTSTR(str), + 0xF7, 0xBF, 0xBF, 0xBF, + 0, -1); } { - const static long str[] = {0x03FFFFFFL, 0}; - utf8_write_test(TESTSTR(str), - 0xFB, 0xBF, 0xBF, 0xBF, 0xBF, - 0, -1); + const static long str[] = {0x03FFFFFFL, 0}; + utf8_write_test(TESTSTR(str), + 0xFB, 0xBF, 0xBF, 0xBF, 0xBF, + 0, -1); } { - const static long str[] = {0x7FFFFFFFL, 0}; - utf8_write_test(TESTSTR(str), - 0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, - 0, -1); + const static long str[] = {0x7FFFFFFFL, 0}; + utf8_write_test(TESTSTR(str), + 0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, + 0, -1); } { - const static long str[] = {0xD7FFL, 0}; - utf8_write_test(TESTSTR(str), - 0xED, 0x9F, 0xBF, - 0, -1); + const static long str[] = {0xD7FFL, 0}; + utf8_write_test(TESTSTR(str), + 0xED, 0x9F, 0xBF, + 0, -1); } { - const static long str[] = {0xD800L, 0}; - utf8_write_test(TESTSTR(str), - ERROR, - 0, -1); + const static long str[] = {0xD800L, 0}; + utf8_write_test(TESTSTR(str), + ERROR, + 0, -1); } { - const static long str[] = {0xD800L, 0xDC00L, 0}; - utf8_write_test(TESTSTR(str), - ERROR, - ERROR, - 0, -1); + const static long str[] = {0xD800L, 0xDC00L, 0}; + utf8_write_test(TESTSTR(str), + ERROR, + ERROR, + 0, -1); } { - const static long str[] = {0xDFFFL, 0}; - utf8_write_test(TESTSTR(str), - ERROR, - 0, -1); + const static long str[] = {0xDFFFL, 0}; + utf8_write_test(TESTSTR(str), + ERROR, + 0, -1); } { - const static long str[] = {0xE000L, 0}; - utf8_write_test(TESTSTR(str), - 0xEE, 0x80, 0x80, - 0, -1); + const static long str[] = {0xE000L, 0}; + utf8_write_test(TESTSTR(str), + 0xEE, 0x80, 0x80, + 0, -1); } printf("write tests completed\n"); diff --git a/charset/xenc.c b/charset/xenc.c index 444af704..964ca6ff 100644 --- a/charset/xenc.c +++ b/charset/xenc.c @@ -1,7 +1,7 @@ /* * xenc.c - translate our internal character set codes to and from * X11 character encoding names. - * + * */ #include @@ -15,9 +15,9 @@ static const struct { /* * Officially registered encoding names. This list is derived * from the font encodings section of - * + * * http://ftp.x.org/pub/DOCS/registry - * + * * Where multiple encoding names map to the same encoding id * (such as iso8859-15 and fcd8859-15), the first is considered * canonical and will be returned when translating the id to a @@ -67,10 +67,10 @@ const char *charset_to_xenc(int charset) int i; for (i = 0; i < (int)lenof(xencs); i++) - if (charset == xencs[i].charset) - return xencs[i].name; + if (charset == xencs[i].charset) + return xencs[i].name; - return NULL; /* not found */ + return NULL; /* not found */ } int charset_from_xenc(const char *name) @@ -78,17 +78,17 @@ int charset_from_xenc(const char *name) int i; for (i = 0; i < (int)lenof(xencs); i++) { - const char *p, *q; - p = name; - q = xencs[i].name; - while (*p || *q) { - if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) - break; - p++; q++; - } - if (!*p && !*q) - return xencs[i].charset; + const char *p, *q; + p = name; + q = xencs[i].name; + while (*p || *q) { + if (tolower((unsigned char)*p) != tolower((unsigned char)*q)) + break; + p++; q++; + } + if (!*p && !*q) + return xencs[i].charset; } - return CS_NONE; /* not found */ + return CS_NONE; /* not found */ } diff --git a/cmdgen.c b/cmdgen.c index b675d94d..eaaf2e48 100644 --- a/cmdgen.c +++ b/cmdgen.c @@ -20,18 +20,18 @@ /* * This section overrides some definitions below for test purposes. * When compiled with -DTEST_CMDGEN (as cgtest.c will do): - * + * * - Calls to get_random_data() are replaced with the diagnostic * function below (I #define the name so that I can still link * with the original set of modules without symbol clash), in * order to avoid depleting the test system's /dev/random * unnecessarily. - * + * * - Calls to console_get_userpass_input() are replaced with the * diagnostic function below, so that I can run tests in an * automated manner and provide their interactive passphrase * inputs. - * + * * - main() is renamed to cmdgen_main(); at the bottom of the file * I define another main() which calls the former repeatedly to * run tests. @@ -52,18 +52,18 @@ int console_get_userpass_input(prompts_t *p) size_t i; int ret = 1; for (i = 0; i < p->n_prompts; i++) { - if (promptsgot < nprompts) { - p->prompts[i]->result = dupstr(prompts[promptsgot++]); + if (promptsgot < nprompts) { + p->prompts[i]->result = dupstr(prompts[promptsgot++]); if (cgtest_verbose) printf(" prompt \"%s\": response \"%s\"\n", p->prompts[i]->prompt, p->prompts[i]->result); - } else { - promptsgot++; /* track number of requests anyway */ - ret = 0; + } else { + promptsgot++; /* track number of requests anyway */ + ret = 0; if (cgtest_verbose) printf(" prompt \"%s\": no response preloaded\n", p->prompts[i]->prompt); - } + } } return ret; } @@ -78,19 +78,19 @@ static void progress_update(void *param, int action, int phase, int iprogress) { struct progress *p = (struct progress *)param; if (action != PROGFN_PROGRESS) - return; + return; if (phase > p->phase) { - if (p->phase >= 0) - fputc('\n', stderr); - p->phase = phase; - if (iprogress >= 0) - p->current = iprogress - 1; - else - p->current = iprogress; + if (p->phase >= 0) + fputc('\n', stderr); + p->phase = phase; + if (iprogress >= 0) + p->current = iprogress - 1; + else + p->current = iprogress; } while (p->current < iprogress) { - fputc('+', stdout); - p->current++; + fputc('+', stdout); + p->current++; } fflush(stdout); } @@ -120,13 +120,13 @@ void showversion(void) void usage(bool standalone) { fprintf(standalone ? stderr : stdout, - "Usage: puttygen ( keyfile | -t type [ -b bits ] )\n" - " [ -C comment ] [ -P ] [ -q ]\n" - " [ -o output-keyfile ] [ -O type | -l | -L" - " | -p ]\n"); + "Usage: puttygen ( keyfile | -t type [ -b bits ] )\n" + " [ -C comment ] [ -P ] [ -q ]\n" + " [ -o output-keyfile ] [ -O type | -l | -L" + " | -p ]\n"); if (standalone) - fprintf(stderr, - "Use \"puttygen --help\" for more detail.\n"); + fprintf(stderr, + "Use \"puttygen --help\" for more detail.\n"); } void help(void) @@ -136,34 +136,34 @@ void help(void) * start with that, plus a version heading. */ printf("PuTTYgen: key generator and converter for the PuTTY tools\n" - "%s\n", ver); + "%s\n", ver); usage(false); printf(" -t specify key type when generating (ed25519, ecdsa, rsa, " - "dsa, rsa1)\n" - " -b specify number of bits when generating key\n" - " -C change or specify key comment\n" - " -P change key passphrase\n" - " -q quiet: do not display progress bar\n" - " -O specify output type:\n" - " private output PuTTY private key format\n" - " private-openssh export OpenSSH private key\n" - " private-openssh-new export OpenSSH private key " + "dsa, rsa1)\n" + " -b specify number of bits when generating key\n" + " -C change or specify key comment\n" + " -P change key passphrase\n" + " -q quiet: do not display progress bar\n" + " -O specify output type:\n" + " private output PuTTY private key format\n" + " private-openssh export OpenSSH private key\n" + " private-openssh-new export OpenSSH private key " "(force new format)\n" - " private-sshcom export ssh.com private key\n" - " public RFC 4716 / ssh.com public key\n" - " public-openssh OpenSSH public key\n" - " fingerprint output the key fingerprint\n" - " -o specify output file\n" - " -l equivalent to `-O fingerprint'\n" - " -L equivalent to `-O public-openssh'\n" - " -p equivalent to `-O public'\n" - " --old-passphrase file\n" - " specify file containing old key passphrase\n" - " --new-passphrase file\n" - " specify file containing new key passphrase\n" - " --random-device device\n" - " specify device to read entropy from (e.g. /dev/urandom)\n" - ); + " private-sshcom export ssh.com private key\n" + " public RFC 4716 / ssh.com public key\n" + " public-openssh OpenSSH public key\n" + " fingerprint output the key fingerprint\n" + " -o specify output file\n" + " -l equivalent to `-O fingerprint'\n" + " -L equivalent to `-O public-openssh'\n" + " -p equivalent to `-O public'\n" + " --old-passphrase file\n" + " specify file containing old key passphrase\n" + " --new-passphrase file\n" + " specify file containing new key passphrase\n" + " --random-device device\n" + " specify device to read entropy from (e.g. /dev/urandom)\n" + ); } static bool move(char *from, char *to) @@ -172,15 +172,15 @@ static bool move(char *from, char *to) ret = rename(from, to); if (ret) { - /* - * This OS may require us to remove the original file first. - */ - remove(to); - ret = rename(from, to); + /* + * This OS may require us to remove the original file first. + */ + remove(to); + ret = rename(from, to); } if (ret) { - perror("puttygen: cannot move new file on to old one"); - return false; + perror("puttygen: cannot move new file on to old one"); + return false; } return true; } @@ -192,18 +192,18 @@ static char *readpassphrase(const char *filename) fp = fopen(filename, "r"); if (!fp) { - fprintf(stderr, "puttygen: cannot open %s: %s\n", - filename, strerror(errno)); - return NULL; + fprintf(stderr, "puttygen: cannot open %s: %s\n", + filename, strerror(errno)); + return NULL; } line = fgetline(fp); if (line) - line[strcspn(line, "\r\n")] = '\0'; + line[strcspn(line, "\r\n")] = '\0'; else if (ferror(fp)) - fprintf(stderr, "puttygen: error reading from %s: %s\n", - filename, strerror(errno)); - else /* empty file */ - line = dupstr(""); + fprintf(stderr, "puttygen: error reading from %s: %s\n", + filename, strerror(errno)); + else /* empty file */ + line = dupstr(""); fclose(fp); return line; } @@ -246,38 +246,38 @@ int main(int argc, char **argv) * return success. */ if (argc <= 1) { - usage(true); - return 0; + usage(true); + return 0; } /* * Parse command line arguments. */ while (--argc) { - char *p = *++argv; - if (*p == '-') { - /* - * An option. - */ - while (p && *++p) { - char c = *p; - switch (c) { - case '-': - /* - * Long option. - */ - { - char *opt, *val; - opt = p++; /* opt will have _one_ leading - */ - while (*p && *p != '=') - p++; /* find end of option */ - if (*p == '=') { - *p++ = '\0'; - val = p; - } else + char *p = *++argv; + if (*p == '-') { + /* + * An option. + */ + while (p && *++p) { + char c = *p; + switch (c) { + case '-': + /* + * Long option. + */ + { + char *opt, *val; + opt = p++; /* opt will have _one_ leading - */ + while (*p && *p != '=') + p++; /* find end of option */ + if (*p == '=') { + *p++ = '\0'; + val = p; + } else val = NULL; - if (!strcmp(opt, "-help")) { + if (!strcmp(opt, "-help")) { if (val) { errs = true; fprintf(stderr, "puttygen: option `-%s'" @@ -286,7 +286,7 @@ int main(int argc, char **argv) help(); nogo = true; } - } else if (!strcmp(opt, "-version")) { + } else if (!strcmp(opt, "-version")) { if (val) { errs = true; fprintf(stderr, "puttygen: option `-%s'" @@ -295,7 +295,7 @@ int main(int argc, char **argv) showversion(); nogo = true; } - } else if (!strcmp(opt, "-pgpfp")) { + } else if (!strcmp(opt, "-pgpfp")) { if (val) { errs = true; fprintf(stderr, "puttygen: option `-%s'" @@ -305,175 +305,175 @@ int main(int argc, char **argv) pgp_fingerprints(); nogo = true; } - } else if (!strcmp(opt, "-old-passphrase")) { - if (!val && argc > 1) - --argc, val = *++argv; - if (!val) { - errs = true; - fprintf(stderr, "puttygen: option `-%s'" - " expects an argument\n", opt); - } else { - old_passphrase = readpassphrase(val); - if (!old_passphrase) - errs = true; - } - } else if (!strcmp(opt, "-new-passphrase")) { - if (!val && argc > 1) - --argc, val = *++argv; - if (!val) { - errs = true; - fprintf(stderr, "puttygen: option `-%s'" - " expects an argument\n", opt); - } else { - new_passphrase = readpassphrase(val); - if (!new_passphrase) - errs = true; - } - } else if (!strcmp(opt, "-random-device")) { - if (!val && argc > 1) - --argc, val = *++argv; - if (!val) { - errs = true; - fprintf(stderr, "puttygen: option `-%s'" - " expects an argument\n", opt); - } else { + } else if (!strcmp(opt, "-old-passphrase")) { + if (!val && argc > 1) + --argc, val = *++argv; + if (!val) { + errs = true; + fprintf(stderr, "puttygen: option `-%s'" + " expects an argument\n", opt); + } else { + old_passphrase = readpassphrase(val); + if (!old_passphrase) + errs = true; + } + } else if (!strcmp(opt, "-new-passphrase")) { + if (!val && argc > 1) + --argc, val = *++argv; + if (!val) { + errs = true; + fprintf(stderr, "puttygen: option `-%s'" + " expects an argument\n", opt); + } else { + new_passphrase = readpassphrase(val); + if (!new_passphrase) + errs = true; + } + } else if (!strcmp(opt, "-random-device")) { + if (!val && argc > 1) + --argc, val = *++argv; + if (!val) { + errs = true; + fprintf(stderr, "puttygen: option `-%s'" + " expects an argument\n", opt); + } else { random_device = val; - } - } else { - errs = true; - fprintf(stderr, - "puttygen: no such option `-%s'\n", opt); - } - } - p = NULL; - break; - case 'h': - case 'V': - case 'P': - case 'l': - case 'L': - case 'p': - case 'q': - /* - * Option requiring no parameter. - */ - switch (c) { - case 'h': - help(); - nogo = true; - break; - case 'V': - showversion(); - nogo = true; - break; - case 'P': - change_passphrase = true; - break; - case 'l': - outtype = FP; - break; - case 'L': - outtype = PUBLICO; - break; - case 'p': - outtype = PUBLIC; - break; - case 'q': - progressfn = no_progress; - break; - } - break; - case 't': - case 'b': - case 'C': - case 'O': - case 'o': - /* - * Option requiring parameter. - */ - p++; - if (!*p && argc > 1) - --argc, p = *++argv; - else if (!*p) { - fprintf(stderr, "puttygen: option `-%c' expects a" - " parameter\n", c); - errs = true; - } - /* - * Now c is the option and p is the parameter. - */ - switch (c) { - case 't': - if (!strcmp(p, "rsa") || !strcmp(p, "rsa2")) - keytype = RSA2, sshver = 2; - else if (!strcmp(p, "rsa1")) - keytype = RSA1, sshver = 1; - else if (!strcmp(p, "dsa") || !strcmp(p, "dss")) - keytype = DSA, sshver = 2; + } + } else { + errs = true; + fprintf(stderr, + "puttygen: no such option `-%s'\n", opt); + } + } + p = NULL; + break; + case 'h': + case 'V': + case 'P': + case 'l': + case 'L': + case 'p': + case 'q': + /* + * Option requiring no parameter. + */ + switch (c) { + case 'h': + help(); + nogo = true; + break; + case 'V': + showversion(); + nogo = true; + break; + case 'P': + change_passphrase = true; + break; + case 'l': + outtype = FP; + break; + case 'L': + outtype = PUBLICO; + break; + case 'p': + outtype = PUBLIC; + break; + case 'q': + progressfn = no_progress; + break; + } + break; + case 't': + case 'b': + case 'C': + case 'O': + case 'o': + /* + * Option requiring parameter. + */ + p++; + if (!*p && argc > 1) + --argc, p = *++argv; + else if (!*p) { + fprintf(stderr, "puttygen: option `-%c' expects a" + " parameter\n", c); + errs = true; + } + /* + * Now c is the option and p is the parameter. + */ + switch (c) { + case 't': + if (!strcmp(p, "rsa") || !strcmp(p, "rsa2")) + keytype = RSA2, sshver = 2; + else if (!strcmp(p, "rsa1")) + keytype = RSA1, sshver = 1; + else if (!strcmp(p, "dsa") || !strcmp(p, "dss")) + keytype = DSA, sshver = 2; else if (!strcmp(p, "ecdsa")) keytype = ECDSA, sshver = 2; else if (!strcmp(p, "ed25519")) keytype = ED25519, sshver = 2; - else { - fprintf(stderr, - "puttygen: unknown key type `%s'\n", p); - errs = true; - } + else { + fprintf(stderr, + "puttygen: unknown key type `%s'\n", p); + errs = true; + } break; - case 'b': - bits = atoi(p); + case 'b': + bits = atoi(p); break; - case 'C': - comment = p; + case 'C': + comment = p; break; - case 'O': - if (!strcmp(p, "public")) - outtype = PUBLIC; - else if (!strcmp(p, "public-openssh")) - outtype = PUBLICO; - else if (!strcmp(p, "private")) - outtype = PRIVATE; - else if (!strcmp(p, "fingerprint")) - outtype = FP; - else if (!strcmp(p, "private-openssh")) - outtype = OPENSSH_AUTO, sshver = 2; - else if (!strcmp(p, "private-openssh-new")) - outtype = OPENSSH_NEW, sshver = 2; - else if (!strcmp(p, "private-sshcom")) - outtype = SSHCOM, sshver = 2; - else { - fprintf(stderr, - "puttygen: unknown output type `%s'\n", p); - errs = true; - } + case 'O': + if (!strcmp(p, "public")) + outtype = PUBLIC; + else if (!strcmp(p, "public-openssh")) + outtype = PUBLICO; + else if (!strcmp(p, "private")) + outtype = PRIVATE; + else if (!strcmp(p, "fingerprint")) + outtype = FP; + else if (!strcmp(p, "private-openssh")) + outtype = OPENSSH_AUTO, sshver = 2; + else if (!strcmp(p, "private-openssh-new")) + outtype = OPENSSH_NEW, sshver = 2; + else if (!strcmp(p, "private-sshcom")) + outtype = SSHCOM, sshver = 2; + else { + fprintf(stderr, + "puttygen: unknown output type `%s'\n", p); + errs = true; + } break; - case 'o': - outfile = p; + case 'o': + outfile = p; break; - } - p = NULL; /* prevent continued processing */ - break; - default: - /* - * Unrecognised option. - */ - errs = true; - fprintf(stderr, "puttygen: no such option `-%c'\n", c); - break; - } - } - } else { - /* - * A non-option argument. - */ - if (!infile) - infile = p; - else { - errs = true; - fprintf(stderr, "puttygen: cannot handle more than one" - " input file\n"); - } - } + } + p = NULL; /* prevent continued processing */ + break; + default: + /* + * Unrecognised option. + */ + errs = true; + fprintf(stderr, "puttygen: no such option `-%c'\n", c); + break; + } + } + } else { + /* + * A non-option argument. + */ + if (!infile) + infile = p; + else { + errs = true; + fprintf(stderr, "puttygen: cannot handle more than one" + " input file\n"); + } + } } if (bits == -1) { @@ -518,18 +518,18 @@ int main(int argc, char **argv) } if (errs) - return 1; + return 1; if (nogo) - return 0; + return 0; /* * If run with at least one argument _but_ not the required * ones, print the usage message and return failure. */ if (!infile && keytype == NOKEYGEN) { - usage(true); - return 1; + usage(true); + return 1; } /* ------------------------------------------------------------------ @@ -541,19 +541,19 @@ int main(int argc, char **argv) * key. */ if (keytype != NOKEYGEN && infile) { - fprintf(stderr, "puttygen: cannot both load and generate a key\n"); - return 1; + fprintf(stderr, "puttygen: cannot both load and generate a key\n"); + return 1; } - /* + /* * We must save the private part when generating a new key. */ if (keytype != NOKEYGEN && - (outtype != PRIVATE && outtype != OPENSSH_AUTO && + (outtype != PRIVATE && outtype != OPENSSH_AUTO && outtype != OPENSSH_NEW && outtype != SSHCOM)) { - fprintf(stderr, "puttygen: this would generate a new key but " - "discard the private part\n"); - return 1; + fprintf(stderr, "puttygen: this would generate a new key but " + "discard the private part\n"); + return 1; } /* @@ -561,84 +561,84 @@ int main(int argc, char **argv) * course of action. */ if (infile) { - infilename = filename_from_str(infile); + infilename = filename_from_str(infile); - intype = key_type(infilename); + intype = key_type(infilename); - switch (intype) { - case SSH_KEYTYPE_UNOPENABLE: - case SSH_KEYTYPE_UNKNOWN: - fprintf(stderr, "puttygen: unable to load file `%s': %s\n", - infile, key_type_to_str(intype)); - return 1; + switch (intype) { + case SSH_KEYTYPE_UNOPENABLE: + case SSH_KEYTYPE_UNKNOWN: + fprintf(stderr, "puttygen: unable to load file `%s': %s\n", + infile, key_type_to_str(intype)); + return 1; - case SSH_KEYTYPE_SSH1: + case SSH_KEYTYPE_SSH1: case SSH_KEYTYPE_SSH1_PUBLIC: - if (sshver == 2) { - fprintf(stderr, "puttygen: conversion from SSH-1 to SSH-2 keys" - " not supported\n"); - return 1; - } - sshver = 1; - break; + if (sshver == 2) { + fprintf(stderr, "puttygen: conversion from SSH-1 to SSH-2 keys" + " not supported\n"); + return 1; + } + sshver = 1; + break; - case SSH_KEYTYPE_SSH2: + case SSH_KEYTYPE_SSH2: case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: - case SSH_KEYTYPE_OPENSSH_PEM: - case SSH_KEYTYPE_OPENSSH_NEW: - case SSH_KEYTYPE_SSHCOM: - if (sshver == 1) { - fprintf(stderr, "puttygen: conversion from SSH-2 to SSH-1 keys" - " not supported\n"); - return 1; - } - sshver = 2; - break; + case SSH_KEYTYPE_OPENSSH_PEM: + case SSH_KEYTYPE_OPENSSH_NEW: + case SSH_KEYTYPE_SSHCOM: + if (sshver == 1) { + fprintf(stderr, "puttygen: conversion from SSH-2 to SSH-1 keys" + " not supported\n"); + return 1; + } + sshver = 2; + break; - case SSH_KEYTYPE_OPENSSH_AUTO: + case SSH_KEYTYPE_OPENSSH_AUTO: default: unreachable("Should never see these types on an input file"); - } + } } /* * Determine the default output file, if none is provided. - * + * * This will usually be equal to stdout, except that if the * input and output file formats are the same then the default * output is to overwrite the input. - * + * * Also in this code, we bomb out if the input and output file * formats are the same and no other action is performed. */ if ((intype == SSH_KEYTYPE_SSH1 && outtype == PRIVATE) || - (intype == SSH_KEYTYPE_SSH2 && outtype == PRIVATE) || - (intype == SSH_KEYTYPE_OPENSSH_PEM && outtype == OPENSSH_AUTO) || - (intype == SSH_KEYTYPE_OPENSSH_NEW && outtype == OPENSSH_NEW) || - (intype == SSH_KEYTYPE_SSHCOM && outtype == SSHCOM)) { - if (!outfile) { - outfile = infile; - outfiletmp = dupcat(outfile, ".tmp", NULL); - } + (intype == SSH_KEYTYPE_SSH2 && outtype == PRIVATE) || + (intype == SSH_KEYTYPE_OPENSSH_PEM && outtype == OPENSSH_AUTO) || + (intype == SSH_KEYTYPE_OPENSSH_NEW && outtype == OPENSSH_NEW) || + (intype == SSH_KEYTYPE_SSHCOM && outtype == SSHCOM)) { + if (!outfile) { + outfile = infile; + outfiletmp = dupcat(outfile, ".tmp", NULL); + } - if (!change_passphrase && !comment) { - fprintf(stderr, "puttygen: this command would perform no useful" - " action\n"); - return 1; - } + if (!change_passphrase && !comment) { + fprintf(stderr, "puttygen: this command would perform no useful" + " action\n"); + return 1; + } } else { - if (!outfile) { - /* - * Bomb out rather than automatically choosing to write - * a private key file to stdout. - */ - if (outtype == PRIVATE || outtype == OPENSSH_AUTO || + if (!outfile) { + /* + * Bomb out rather than automatically choosing to write + * a private key file to stdout. + */ + if (outtype == PRIVATE || outtype == OPENSSH_AUTO || outtype == OPENSSH_NEW || outtype == SSHCOM) { - fprintf(stderr, "puttygen: need to specify an output file\n"); - return 1; - } - } + fprintf(stderr, "puttygen: need to specify an output file\n"); + return 1; + } + } } /* @@ -649,12 +649,12 @@ int main(int argc, char **argv) */ if (outtype == PRIVATE || outtype == OPENSSH_AUTO || outtype == OPENSSH_NEW || outtype == SSHCOM || - intype == SSH_KEYTYPE_OPENSSH_PEM || - intype == SSH_KEYTYPE_OPENSSH_NEW || + intype == SSH_KEYTYPE_OPENSSH_PEM || + intype == SSH_KEYTYPE_OPENSSH_NEW || intype == SSH_KEYTYPE_SSHCOM) - load_encrypted = true; + load_encrypted = true; else - load_encrypted = false; + load_encrypted = false; if (load_encrypted && (intype == SSH_KEYTYPE_SSH1_PUBLIC || intype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 || @@ -672,41 +672,41 @@ int main(int argc, char **argv) * Either load or generate a key. */ if (keytype != NOKEYGEN) { - char *entropy; - char default_comment[80]; - struct tm tm; - struct progress prog; + char *entropy; + char default_comment[80]; + struct tm tm; + struct progress prog; - prog.phase = -1; - prog.current = -1; + prog.phase = -1; + prog.current = -1; - tm = ltime(); - if (keytype == DSA) - strftime(default_comment, 30, "dsa-key-%Y%m%d", &tm); + tm = ltime(); + if (keytype == DSA) + strftime(default_comment, 30, "dsa-key-%Y%m%d", &tm); else if (keytype == ECDSA) strftime(default_comment, 30, "ecdsa-key-%Y%m%d", &tm); else if (keytype == ED25519) strftime(default_comment, 30, "ed25519-key-%Y%m%d", &tm); - else - strftime(default_comment, 30, "rsa-key-%Y%m%d", &tm); + else + strftime(default_comment, 30, "rsa-key-%Y%m%d", &tm); - entropy = get_random_data(bits / 8, random_device); - if (!entropy) { - fprintf(stderr, "puttygen: failed to collect entropy, " - "could not generate key\n"); - return 1; - } - random_setup_special(); + entropy = get_random_data(bits / 8, random_device); + if (!entropy) { + fprintf(stderr, "puttygen: failed to collect entropy, " + "could not generate key\n"); + return 1; + } + random_setup_special(); random_reseed(make_ptrlen(entropy, bits / 8)); - smemclr(entropy, bits/8); - sfree(entropy); + smemclr(entropy, bits/8); + sfree(entropy); - if (keytype == DSA) { - struct dss_key *dsskey = snew(struct dss_key); - dsa_generate(dsskey, bits, progressfn, &prog); - ssh2key = snew(ssh2_userkey); - ssh2key->key = &dsskey->sshk; - ssh1key = NULL; + if (keytype == DSA) { + struct dss_key *dsskey = snew(struct dss_key); + dsa_generate(dsskey, bits, progressfn, &prog); + ssh2key = snew(ssh2_userkey); + ssh2key->key = &dsskey->sshk; + ssh1key = NULL; } else if (keytype == ECDSA) { struct ecdsa_key *ek = snew(struct ecdsa_key); ecdsa_generate(ek, bits, progressfn, &prog); @@ -719,77 +719,77 @@ int main(int argc, char **argv) ssh2key = snew(ssh2_userkey); ssh2key->key = &ek->sshk; ssh1key = NULL; - } else { - RSAKey *rsakey = snew(RSAKey); - rsa_generate(rsakey, bits, progressfn, &prog); - rsakey->comment = NULL; - if (keytype == RSA1) { - ssh1key = rsakey; - } else { - ssh2key = snew(ssh2_userkey); - ssh2key->key = &rsakey->sshk; - } - } - progressfn(&prog, PROGFN_PROGRESS, INT_MAX, -1); + } else { + RSAKey *rsakey = snew(RSAKey); + rsa_generate(rsakey, bits, progressfn, &prog); + rsakey->comment = NULL; + if (keytype == RSA1) { + ssh1key = rsakey; + } else { + ssh2key = snew(ssh2_userkey); + ssh2key->key = &rsakey->sshk; + } + } + progressfn(&prog, PROGFN_PROGRESS, INT_MAX, -1); - if (ssh2key) - ssh2key->comment = dupstr(default_comment); - if (ssh1key) - ssh1key->comment = dupstr(default_comment); + if (ssh2key) + ssh2key->comment = dupstr(default_comment); + if (ssh1key) + ssh1key->comment = dupstr(default_comment); } else { - const char *error = NULL; - bool encrypted; + const char *error = NULL; + bool encrypted; - assert(infile != NULL); + assert(infile != NULL); - sfree(origcomment); - origcomment = NULL; + sfree(origcomment); + origcomment = NULL; - /* - * Find out whether the input key is encrypted. - */ - if (intype == SSH_KEYTYPE_SSH1) - encrypted = rsa_ssh1_encrypted(infilename, &origcomment); - else if (intype == SSH_KEYTYPE_SSH2) - encrypted = ssh2_userkey_encrypted(infilename, &origcomment); - else - encrypted = import_encrypted(infilename, intype, &origcomment); + /* + * Find out whether the input key is encrypted. + */ + if (intype == SSH_KEYTYPE_SSH1) + encrypted = rsa_ssh1_encrypted(infilename, &origcomment); + else if (intype == SSH_KEYTYPE_SSH2) + encrypted = ssh2_userkey_encrypted(infilename, &origcomment); + else + encrypted = import_encrypted(infilename, intype, &origcomment); - /* - * If so, ask for a passphrase. - */ - if (encrypted && load_encrypted) { - if (!old_passphrase) { - prompts_t *p = new_prompts(); - int ret; - p->to_server = false; - p->from_server = false; - p->name = dupstr("SSH key passphrase"); - add_prompt(p, dupstr("Enter passphrase to load key: "), false); - ret = console_get_userpass_input(p); - assert(ret >= 0); - if (!ret) { - free_prompts(p); - perror("puttygen: unable to read passphrase"); - return 1; - } else { - old_passphrase = dupstr(p->prompts[0]->result); - free_prompts(p); - } - } - } else { - old_passphrase = NULL; - } + /* + * If so, ask for a passphrase. + */ + if (encrypted && load_encrypted) { + if (!old_passphrase) { + prompts_t *p = new_prompts(); + int ret; + p->to_server = false; + p->from_server = false; + p->name = dupstr("SSH key passphrase"); + add_prompt(p, dupstr("Enter passphrase to load key: "), false); + ret = console_get_userpass_input(p); + assert(ret >= 0); + if (!ret) { + free_prompts(p); + perror("puttygen: unable to read passphrase"); + return 1; + } else { + old_passphrase = dupstr(p->prompts[0]->result); + free_prompts(p); + } + } + } else { + old_passphrase = NULL; + } - switch (intype) { - int ret; + switch (intype) { + int ret; - case SSH_KEYTYPE_SSH1: + case SSH_KEYTYPE_SSH1: case SSH_KEYTYPE_SSH1_PUBLIC: - ssh1key = snew(RSAKey); - if (!load_encrypted) { - strbuf *blob; + ssh1key = snew(RSAKey); + if (!load_encrypted) { + strbuf *blob; BinarySource src[1]; sfree(origcomment); @@ -797,35 +797,35 @@ int main(int argc, char **argv) blob = strbuf_new(); - ret = rsa_ssh1_loadpub(infilename, BinarySink_UPCAST(blob), + ret = rsa_ssh1_loadpub(infilename, BinarySink_UPCAST(blob), &origcomment, &error); BinarySource_BARE_INIT(src, blob->u, blob->len); get_rsa_ssh1_pub(src, ssh1key, RSA_SSH1_EXPONENT_FIRST); strbuf_free(blob); - ssh1key->comment = dupstr(origcomment); - ssh1key->private_exponent = NULL; - ssh1key->p = NULL; - ssh1key->q = NULL; - ssh1key->iqmp = NULL; - } else { - ret = rsa_ssh1_loadkey( + ssh1key->comment = dupstr(origcomment); + ssh1key->private_exponent = NULL; + ssh1key->p = NULL; + ssh1key->q = NULL; + ssh1key->iqmp = NULL; + } else { + ret = rsa_ssh1_loadkey( infilename, ssh1key, old_passphrase, &error); - } - if (ret > 0) - error = NULL; - else if (!error) - error = "unknown error"; - break; + } + if (ret > 0) + error = NULL; + else if (!error) + error = "unknown error"; + break; - case SSH_KEYTYPE_SSH2: + case SSH_KEYTYPE_SSH2: case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: - if (!load_encrypted) { + if (!load_encrypted) { sfree(origcomment); origcomment = NULL; ssh2blob = strbuf_new(); - if (ssh2_userkey_loadpub(infilename, &ssh2alg, BinarySink_UPCAST(ssh2blob), + if (ssh2_userkey_loadpub(infilename, &ssh2alg, BinarySink_UPCAST(ssh2blob), &origcomment, &error)) { const ssh_keyalg *alg = find_pubkey_alg(ssh2alg); if (alg) @@ -838,57 +838,57 @@ int main(int argc, char **argv) ssh2blob = NULL; } sfree(ssh2alg); - } else { - ssh2key = ssh2_load_userkey(infilename, old_passphrase, - &error); - } - if ((ssh2key && ssh2key != SSH2_WRONG_PASSPHRASE) || ssh2blob) - error = NULL; - else if (!error) { - if (ssh2key == SSH2_WRONG_PASSPHRASE) - error = "wrong passphrase"; - else - error = "unknown error"; - } - break; + } else { + ssh2key = ssh2_load_userkey(infilename, old_passphrase, + &error); + } + if ((ssh2key && ssh2key != SSH2_WRONG_PASSPHRASE) || ssh2blob) + error = NULL; + else if (!error) { + if (ssh2key == SSH2_WRONG_PASSPHRASE) + error = "wrong passphrase"; + else + error = "unknown error"; + } + break; - case SSH_KEYTYPE_OPENSSH_PEM: - case SSH_KEYTYPE_OPENSSH_NEW: - case SSH_KEYTYPE_SSHCOM: - ssh2key = import_ssh2(infilename, intype, old_passphrase, &error); - if (ssh2key) { - if (ssh2key != SSH2_WRONG_PASSPHRASE) - error = NULL; - else - error = "wrong passphrase"; - } else if (!error) - error = "unknown error"; - break; + case SSH_KEYTYPE_OPENSSH_PEM: + case SSH_KEYTYPE_OPENSSH_NEW: + case SSH_KEYTYPE_SSHCOM: + ssh2key = import_ssh2(infilename, intype, old_passphrase, &error); + if (ssh2key) { + if (ssh2key != SSH2_WRONG_PASSPHRASE) + error = NULL; + else + error = "wrong passphrase"; + } else if (!error) + error = "unknown error"; + break; - default: - unreachable("bad input key type"); - } + default: + unreachable("bad input key type"); + } - if (error) { - fprintf(stderr, "puttygen: error loading `%s': %s\n", - infile, error); - return 1; - } + if (error) { + fprintf(stderr, "puttygen: error loading `%s': %s\n", + infile, error); + return 1; + } } /* * Change the comment if asked to. */ if (comment) { - if (sshver == 1) { - assert(ssh1key); - sfree(ssh1key->comment); - ssh1key->comment = dupstr(comment); - } else { - assert(ssh2key); - sfree(ssh2key->comment); - ssh2key->comment = dupstr(comment); - } + if (sshver == 1) { + assert(ssh1key); + sfree(ssh1key->comment); + ssh1key->comment = dupstr(comment); + } else { + assert(ssh2key); + sfree(ssh2key->comment); + ssh2key->comment = dupstr(comment); + } } /* @@ -896,54 +896,54 @@ int main(int argc, char **argv) * reasonable default. */ if (!change_passphrase && old_passphrase && !new_passphrase) - new_passphrase = dupstr(old_passphrase); + new_passphrase = dupstr(old_passphrase); /* * Prompt for a new passphrase if we have been asked to, or if * we have just generated a key. */ if (!new_passphrase && (change_passphrase || keytype != NOKEYGEN)) { - prompts_t *p = new_prompts(NULL); - int ret; + prompts_t *p = new_prompts(NULL); + int ret; - p->to_server = false; - p->from_server = false; - p->name = dupstr("New SSH key passphrase"); - add_prompt(p, dupstr("Enter passphrase to save key: "), false); - add_prompt(p, dupstr("Re-enter passphrase to verify: "), false); - ret = console_get_userpass_input(p); - assert(ret >= 0); - if (!ret) { - free_prompts(p); - perror("puttygen: unable to read new passphrase"); - return 1; - } else { - if (strcmp(p->prompts[0]->result, p->prompts[1]->result)) { - free_prompts(p); - fprintf(stderr, "puttygen: passphrases do not match\n"); - return 1; - } - new_passphrase = dupstr(p->prompts[0]->result); - free_prompts(p); - } + p->to_server = false; + p->from_server = false; + p->name = dupstr("New SSH key passphrase"); + add_prompt(p, dupstr("Enter passphrase to save key: "), false); + add_prompt(p, dupstr("Re-enter passphrase to verify: "), false); + ret = console_get_userpass_input(p); + assert(ret >= 0); + if (!ret) { + free_prompts(p); + perror("puttygen: unable to read new passphrase"); + return 1; + } else { + if (strcmp(p->prompts[0]->result, p->prompts[1]->result)) { + free_prompts(p); + fprintf(stderr, "puttygen: passphrases do not match\n"); + return 1; + } + new_passphrase = dupstr(p->prompts[0]->result); + free_prompts(p); + } } if (new_passphrase && !*new_passphrase) { - sfree(new_passphrase); - new_passphrase = NULL; + sfree(new_passphrase); + new_passphrase = NULL; } /* * Write output. - * + * * (In the case where outfile and outfiletmp are both NULL, * there is no semantic reason to initialise outfilename at * all; but we have to write _something_ to it or some compiler * will probably complain that it might be used uninitialised.) */ if (outfiletmp) - outfilename = filename_from_str(outfiletmp); + outfilename = filename_from_str(outfiletmp); else - outfilename = filename_from_str(outfile ? outfile : ""); + outfilename = filename_from_str(outfile ? outfile : ""); switch (outtype) { bool ret; @@ -951,26 +951,26 @@ int main(int argc, char **argv) case PRIVATE: random_ref(); /* we'll need a few random bytes in the save file */ - if (sshver == 1) { - assert(ssh1key); - ret = rsa_ssh1_savekey(outfilename, ssh1key, new_passphrase); - if (!ret) { - fprintf(stderr, "puttygen: unable to save SSH-1 private key\n"); - return 1; - } - } else { - assert(ssh2key); - ret = ssh2_save_userkey(outfilename, ssh2key, new_passphrase); - if (!ret) { - fprintf(stderr, "puttygen: unable to save SSH-2 private key\n"); - return 1; - } - } - if (outfiletmp) { - if (!move(outfiletmp, outfile)) - return 1; /* rename failed */ - } - break; + if (sshver == 1) { + assert(ssh1key); + ret = rsa_ssh1_savekey(outfilename, ssh1key, new_passphrase); + if (!ret) { + fprintf(stderr, "puttygen: unable to save SSH-1 private key\n"); + return 1; + } + } else { + assert(ssh2key); + ret = ssh2_save_userkey(outfilename, ssh2key, new_passphrase); + if (!ret) { + fprintf(stderr, "puttygen: unable to save SSH-2 private key\n"); + return 1; + } + } + if (outfiletmp) { + if (!move(outfiletmp, outfile)) + return 1; /* rename failed */ + } + break; case PUBLIC: case PUBLICO: @@ -1003,52 +1003,52 @@ int main(int argc, char **argv) SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH)); } - if (outfile) - fclose(fp); + if (outfile) + fclose(fp); } - break; + break; case FP: - { - FILE *fp; - char *fingerprint; + { + FILE *fp; + char *fingerprint; - if (sshver == 1) { - assert(ssh1key); - fingerprint = rsa_ssh1_fingerprint(ssh1key); - } else { - if (ssh2key) { - fingerprint = ssh2_fingerprint(ssh2key->key); - } else { - assert(ssh2blob); - fingerprint = ssh2_fingerprint_blob( + if (sshver == 1) { + assert(ssh1key); + fingerprint = rsa_ssh1_fingerprint(ssh1key); + } else { + if (ssh2key) { + fingerprint = ssh2_fingerprint(ssh2key->key); + } else { + assert(ssh2blob); + fingerprint = ssh2_fingerprint_blob( ptrlen_from_strbuf(ssh2blob)); - } - } + } + } - if (outfile) { - fp = f_open(outfilename, "w", false); + if (outfile) { + fp = f_open(outfilename, "w", false); if (!fp) { fprintf(stderr, "unable to open output file\n"); exit(1); } } else { - fp = stdout; + fp = stdout; } - fprintf(fp, "%s\n", fingerprint); - if (outfile) - fclose(fp); + fprintf(fp, "%s\n", fingerprint); + if (outfile) + fclose(fp); + + sfree(fingerprint); + } + break; - sfree(fingerprint); - } - break; - case OPENSSH_AUTO: case OPENSSH_NEW: case SSHCOM: - assert(sshver == 2); - assert(ssh2key); - random_ref(); /* both foreign key types require randomness, + assert(sshver == 2); + assert(ssh2key); + random_ref(); /* both foreign key types require randomness, * for IV or padding */ switch (outtype) { case OPENSSH_AUTO: @@ -1063,35 +1063,35 @@ int main(int argc, char **argv) default: unreachable("control flow goof"); } - ret = export_ssh2(outfilename, real_outtype, ssh2key, new_passphrase); - if (!ret) { - fprintf(stderr, "puttygen: unable to export key\n"); - return 1; - } - if (outfiletmp) { - if (!move(outfiletmp, outfile)) - return 1; /* rename failed */ - } - break; + ret = export_ssh2(outfilename, real_outtype, ssh2key, new_passphrase); + if (!ret) { + fprintf(stderr, "puttygen: unable to export key\n"); + return 1; + } + if (outfiletmp) { + if (!move(outfiletmp, outfile)) + return 1; /* rename failed */ + } + break; } if (old_passphrase) { - smemclr(old_passphrase, strlen(old_passphrase)); - sfree(old_passphrase); + smemclr(old_passphrase, strlen(old_passphrase)); + sfree(old_passphrase); } if (new_passphrase) { - smemclr(new_passphrase, strlen(new_passphrase)); - sfree(new_passphrase); + smemclr(new_passphrase, strlen(new_passphrase)); + sfree(new_passphrase); } if (ssh1key) { - freersakey(ssh1key); + freersakey(ssh1key); sfree(ssh1key); } if (ssh2key) { - sfree(ssh2key->comment); - ssh_key_free(ssh2key->key); - sfree(ssh2key); + sfree(ssh2key->comment); + ssh_key_free(ssh2key->key); + sfree(ssh2key); } if (ssh2blob) strbuf_free(ssh2blob); @@ -1118,13 +1118,13 @@ void setup_passphrases(char *first, ...) nprompts = 0; if (first) { - prompts[nprompts++] = first; - va_start(ap, first); - while ((next = va_arg(ap, char *)) != NULL) { - assert(nprompts < lenof(prompts)); - prompts[nprompts++] = next; - } - va_end(ap); + prompts[nprompts++] = first; + va_start(ap, first); + while ((next = va_arg(ap, char *)) != NULL) { + assert(nprompts < lenof(prompts)); + prompts[nprompts++] = next; + } + va_end(ap); } } @@ -1137,13 +1137,13 @@ void test(int retval, ...) argc = 0; va_start(ap, retval); while (va_arg(ap, char *) != NULL) - argc++; + argc++; va_end(ap); argv = snewn(argc+1, char *); va_start(ap, retval); for (i = 0; i <= argc; i++) - argv[i] = va_arg(ap, char *); + argv[i] = va_arg(ap, char *); va_end(ap); promptsgot = 0; @@ -1176,19 +1176,19 @@ void test(int retval, ...) random_clear(); if (ret != retval) { - printf("FAILED retval (exp %d got %d):", retval, ret); - for (i = 0; i < argc; i++) - printf(" %s", argv[i]); - printf("\n"); - fails++; + printf("FAILED retval (exp %d got %d):", retval, ret); + for (i = 0; i < argc; i++) + printf(" %s", argv[i]); + printf("\n"); + fails++; } else if (promptsgot != nprompts) { - printf("FAILED nprompts (exp %d got %d):", nprompts, promptsgot); - for (i = 0; i < argc; i++) - printf(" %s", argv[i]); - printf("\n"); - fails++; + printf("FAILED nprompts (exp %d got %d):", nprompts, promptsgot); + for (i = 0; i < argc; i++) + printf(" %s", argv[i]); + printf("\n"); + fails++; } else { - passes++; + passes++; } sfree(argv); @@ -1210,19 +1210,19 @@ void filecmp(char *file1, char *file2, char *fmt, ...) sfree(buf); if (ret) { - va_list ap; + va_list ap; - printf("FAILED diff (ret=%d): ", ret); + printf("FAILED diff (ret=%d): ", ret); - va_start(ap, fmt); - vprintf(fmt, ap); - va_end(ap); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); - printf("\n"); + printf("\n"); - fails++; + fails++; } else - passes++; + passes++; } char *cleanup_fp(char *s) @@ -1251,11 +1251,11 @@ char *get_fp(char *filename) fp = fopen(filename, "r"); if (!fp) - return NULL; + return NULL; ret = fgets(buf, sizeof(buf), fp); fclose(fp); if (!ret) - return NULL; + return NULL; return cleanup_fp(buf); } @@ -1264,24 +1264,24 @@ void check_fp(char *filename, char *fp, char *fmt, ...) char *newfp; if (!fp) - return; + return; newfp = get_fp(filename); if (!strcmp(fp, newfp)) { - passes++; + passes++; } else { - va_list ap; + va_list ap; - printf("FAILED check_fp ['%s' != '%s']: ", newfp, fp); + printf("FAILED check_fp ['%s' != '%s']: ", newfp, fp); - va_start(ap, fmt); - vprintf(fmt, ap); - va_end(ap); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); - printf("\n"); + printf("\n"); - fails++; + fails++; } sfree(newfp); @@ -1301,382 +1301,382 @@ int main(int argc, char **argv) * options for _manual_ tests. */ if (argc > 1) - return cmdgen_main(argc, argv); + return cmdgen_main(argc, argv); passes = fails = 0; for (i = 0; i < lenof(keytypes); i++) { - char filename[128], osfilename[128], scfilename[128]; - char pubfilename[128], tmpfilename1[128], tmpfilename2[128]; - char *fp; + char filename[128], osfilename[128], scfilename[128]; + char pubfilename[128], tmpfilename1[128], tmpfilename2[128]; + char *fp; - sprintf(filename, "test-%s.ppk", keytypes[i]); - sprintf(pubfilename, "test-%s.pub", keytypes[i]); - sprintf(osfilename, "test-%s.os", keytypes[i]); - sprintf(scfilename, "test-%s.sc", keytypes[i]); - sprintf(tmpfilename1, "test-%s.tmp1", keytypes[i]); - sprintf(tmpfilename2, "test-%s.tmp2", keytypes[i]); + sprintf(filename, "test-%s.ppk", keytypes[i]); + sprintf(pubfilename, "test-%s.pub", keytypes[i]); + sprintf(osfilename, "test-%s.os", keytypes[i]); + sprintf(scfilename, "test-%s.sc", keytypes[i]); + sprintf(tmpfilename1, "test-%s.tmp1", keytypes[i]); + sprintf(tmpfilename2, "test-%s.tmp2", keytypes[i]); - /* - * Create an encrypted key. - */ - setup_passphrases("sponge", "sponge", NULL); - test(0, "puttygen", "-t", keytypes[i], "-o", filename, NULL); + /* + * Create an encrypted key. + */ + setup_passphrases("sponge", "sponge", NULL); + test(0, "puttygen", "-t", keytypes[i], "-o", filename, NULL); - /* - * List the public key in OpenSSH format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-L", filename, "-o", pubfilename, NULL); - { - char *cmdbuf; - fp = NULL; - cmdbuf = dupprintf("ssh-keygen -E md5 -l -f '%s' > '%s'", - pubfilename, tmpfilename1); - if (system(cmdbuf) || - (fp = get_fp(tmpfilename1)) == NULL) { - printf("UNABLE to test fingerprint matching against OpenSSH"); - } - sfree(cmdbuf); - } + /* + * List the public key in OpenSSH format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-L", filename, "-o", pubfilename, NULL); + { + char *cmdbuf; + fp = NULL; + cmdbuf = dupprintf("ssh-keygen -E md5 -l -f '%s' > '%s'", + pubfilename, tmpfilename1); + if (system(cmdbuf) || + (fp = get_fp(tmpfilename1)) == NULL) { + printf("UNABLE to test fingerprint matching against OpenSSH"); + } + sfree(cmdbuf); + } - /* - * List the public key in IETF/ssh.com format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-p", filename, NULL); + /* + * List the public key in IETF/ssh.com format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-p", filename, NULL); - /* - * List the fingerprint of the key. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-l", filename, "-o", tmpfilename1, NULL); - if (!fp) { - /* - * If we can't test fingerprints against OpenSSH, we - * can at the very least test equality of all the - * fingerprints we generate of this key throughout - * testing. - */ - fp = get_fp(tmpfilename1); - } else { - check_fp(tmpfilename1, fp, "%s initial fp", keytypes[i]); - } + /* + * List the fingerprint of the key. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-l", filename, "-o", tmpfilename1, NULL); + if (!fp) { + /* + * If we can't test fingerprints against OpenSSH, we + * can at the very least test equality of all the + * fingerprints we generate of this key throughout + * testing. + */ + fp = get_fp(tmpfilename1); + } else { + check_fp(tmpfilename1, fp, "%s initial fp", keytypes[i]); + } - /* - * Change the comment of the key; this _does_ require a - * passphrase owing to the tamperproofing. - * - * NOTE: In SSH-1, this only requires a passphrase because - * of inadequacies of the loading and saving mechanisms. In - * _principle_, it should be perfectly possible to modify - * the comment on an SSH-1 key without requiring a - * passphrase; the only reason I can't do it is because my - * loading and saving mechanisms don't include a method of - * loading all the key data without also trying to decrypt - * the private section. - * - * I don't consider this to be a problem worth solving, - * because (a) to fix it would probably end up bloating - * PuTTY proper, and (b) SSH-1 is on the way out anyway so - * it shouldn't be highly significant. If it seriously - * bothers anyone then perhaps I _might_ be persuadable. - */ - setup_passphrases("sponge", NULL); - test(0, "puttygen", "-C", "new-comment", filename, NULL); + /* + * Change the comment of the key; this _does_ require a + * passphrase owing to the tamperproofing. + * + * NOTE: In SSH-1, this only requires a passphrase because + * of inadequacies of the loading and saving mechanisms. In + * _principle_, it should be perfectly possible to modify + * the comment on an SSH-1 key without requiring a + * passphrase; the only reason I can't do it is because my + * loading and saving mechanisms don't include a method of + * loading all the key data without also trying to decrypt + * the private section. + * + * I don't consider this to be a problem worth solving, + * because (a) to fix it would probably end up bloating + * PuTTY proper, and (b) SSH-1 is on the way out anyway so + * it shouldn't be highly significant. If it seriously + * bothers anyone then perhaps I _might_ be persuadable. + */ + setup_passphrases("sponge", NULL); + test(0, "puttygen", "-C", "new-comment", filename, NULL); - /* - * Change the passphrase to nothing. - */ - setup_passphrases("sponge", "", "", NULL); - test(0, "puttygen", "-P", filename, NULL); + /* + * Change the passphrase to nothing. + */ + setup_passphrases("sponge", "", "", NULL); + test(0, "puttygen", "-P", filename, NULL); - /* - * Change the comment of the key again; this time we expect no - * passphrase to be required. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-C", "new-comment-2", filename, NULL); + /* + * Change the comment of the key again; this time we expect no + * passphrase to be required. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-C", "new-comment-2", filename, NULL); - /* - * Export the private key into OpenSSH format; no passphrase - * should be required since the key is currently unencrypted. - * For RSA1 keys, this should give an error. - */ - setup_passphrases(NULL); - test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename, - filename, NULL); + /* + * Export the private key into OpenSSH format; no passphrase + * should be required since the key is currently unencrypted. + * For RSA1 keys, this should give an error. + */ + setup_passphrases(NULL); + test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename, + filename, NULL); - if (i) { - /* - * List the fingerprint of the OpenSSH-formatted key. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL); - check_fp(tmpfilename1, fp, "%s openssh clear fp", keytypes[i]); + if (i) { + /* + * List the fingerprint of the OpenSSH-formatted key. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL); + check_fp(tmpfilename1, fp, "%s openssh clear fp", keytypes[i]); - /* - * List the public half of the OpenSSH-formatted key in - * OpenSSH format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-L", osfilename, NULL); + /* + * List the public half of the OpenSSH-formatted key in + * OpenSSH format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-L", osfilename, NULL); - /* - * List the public half of the OpenSSH-formatted key in - * IETF/ssh.com format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-p", osfilename, NULL); - } + /* + * List the public half of the OpenSSH-formatted key in + * IETF/ssh.com format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-p", osfilename, NULL); + } - /* - * Export the private key into ssh.com format; no passphrase - * should be required since the key is currently unencrypted. - * For RSA1 keys, this should give an error. - */ - setup_passphrases(NULL); - test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename, - filename, NULL); + /* + * Export the private key into ssh.com format; no passphrase + * should be required since the key is currently unencrypted. + * For RSA1 keys, this should give an error. + */ + setup_passphrases(NULL); + test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename, + filename, NULL); - if (i) { - /* - * List the fingerprint of the ssh.com-formatted key. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL); - check_fp(tmpfilename1, fp, "%s ssh.com clear fp", keytypes[i]); + if (i) { + /* + * List the fingerprint of the ssh.com-formatted key. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL); + check_fp(tmpfilename1, fp, "%s ssh.com clear fp", keytypes[i]); - /* - * List the public half of the ssh.com-formatted key in - * OpenSSH format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-L", scfilename, NULL); + /* + * List the public half of the ssh.com-formatted key in + * OpenSSH format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-L", scfilename, NULL); - /* - * List the public half of the ssh.com-formatted key in - * IETF/ssh.com format. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-p", scfilename, NULL); - } + /* + * List the public half of the ssh.com-formatted key in + * IETF/ssh.com format. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-p", scfilename, NULL); + } - if (i) { - /* - * Convert from OpenSSH into ssh.com. - */ - setup_passphrases(NULL); - test(0, "puttygen", osfilename, "-o", tmpfilename1, - "-O", "private-sshcom", NULL); + if (i) { + /* + * Convert from OpenSSH into ssh.com. + */ + setup_passphrases(NULL); + test(0, "puttygen", osfilename, "-o", tmpfilename1, + "-O", "private-sshcom", NULL); - /* - * Convert from ssh.com back into a PuTTY key, - * supplying the same comment as we had before we - * started to ensure the comparison works. - */ - setup_passphrases(NULL); - test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", - "-o", tmpfilename2, NULL); + /* + * Convert from ssh.com back into a PuTTY key, + * supplying the same comment as we had before we + * started to ensure the comparison works. + */ + setup_passphrases(NULL); + test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", + "-o", tmpfilename2, NULL); - /* - * See if the PuTTY key thus generated is the same as - * the original. - */ - filecmp(filename, tmpfilename2, - "p->o->s->p clear %s", keytypes[i]); + /* + * See if the PuTTY key thus generated is the same as + * the original. + */ + filecmp(filename, tmpfilename2, + "p->o->s->p clear %s", keytypes[i]); - /* - * Convert from ssh.com to OpenSSH. - */ - setup_passphrases(NULL); - test(0, "puttygen", scfilename, "-o", tmpfilename1, - "-O", "private-openssh", NULL); + /* + * Convert from ssh.com to OpenSSH. + */ + setup_passphrases(NULL); + test(0, "puttygen", scfilename, "-o", tmpfilename1, + "-O", "private-openssh", NULL); - /* - * Convert from OpenSSH back into a PuTTY key, - * supplying the same comment as we had before we - * started to ensure the comparison works. - */ - setup_passphrases(NULL); - test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", - "-o", tmpfilename2, NULL); + /* + * Convert from OpenSSH back into a PuTTY key, + * supplying the same comment as we had before we + * started to ensure the comparison works. + */ + setup_passphrases(NULL); + test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", + "-o", tmpfilename2, NULL); - /* - * See if the PuTTY key thus generated is the same as - * the original. - */ - filecmp(filename, tmpfilename2, - "p->s->o->p clear %s", keytypes[i]); + /* + * See if the PuTTY key thus generated is the same as + * the original. + */ + filecmp(filename, tmpfilename2, + "p->s->o->p clear %s", keytypes[i]); - /* - * Finally, do a round-trip conversion between PuTTY - * and ssh.com without involving OpenSSH, to test that - * the key comment is preserved in that case. - */ - setup_passphrases(NULL); - test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1, - filename, NULL); - setup_passphrases(NULL); - test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL); - filecmp(filename, tmpfilename2, - "p->s->p clear %s", keytypes[i]); - } + /* + * Finally, do a round-trip conversion between PuTTY + * and ssh.com without involving OpenSSH, to test that + * the key comment is preserved in that case. + */ + setup_passphrases(NULL); + test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1, + filename, NULL); + setup_passphrases(NULL); + test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL); + filecmp(filename, tmpfilename2, + "p->s->p clear %s", keytypes[i]); + } - /* - * Check that mismatched passphrases cause an error. - */ - setup_passphrases("sponge2", "sponge3", NULL); - test(1, "puttygen", "-P", filename, NULL); + /* + * Check that mismatched passphrases cause an error. + */ + setup_passphrases("sponge2", "sponge3", NULL); + test(1, "puttygen", "-P", filename, NULL); - /* - * Put a passphrase back on. - */ - setup_passphrases("sponge2", "sponge2", NULL); - test(0, "puttygen", "-P", filename, NULL); + /* + * Put a passphrase back on. + */ + setup_passphrases("sponge2", "sponge2", NULL); + test(0, "puttygen", "-P", filename, NULL); - /* - * Export the private key into OpenSSH format, this time - * while encrypted. For RSA1 keys, this should give an - * error. - */ - if (i == 0) - setup_passphrases(NULL); /* error, hence no passphrase read */ - else - setup_passphrases("sponge2", NULL); - test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename, - filename, NULL); + /* + * Export the private key into OpenSSH format, this time + * while encrypted. For RSA1 keys, this should give an + * error. + */ + if (i == 0) + setup_passphrases(NULL); /* error, hence no passphrase read */ + else + setup_passphrases("sponge2", NULL); + test((i==0), "puttygen", "-O", "private-openssh", "-o", osfilename, + filename, NULL); - if (i) { - /* - * List the fingerprint of the OpenSSH-formatted key. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL); - check_fp(tmpfilename1, fp, "%s openssh encrypted fp", keytypes[i]); + if (i) { + /* + * List the fingerprint of the OpenSSH-formatted key. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-l", osfilename, "-o", tmpfilename1, NULL); + check_fp(tmpfilename1, fp, "%s openssh encrypted fp", keytypes[i]); - /* - * List the public half of the OpenSSH-formatted key in - * OpenSSH format. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-L", osfilename, NULL); + /* + * List the public half of the OpenSSH-formatted key in + * OpenSSH format. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-L", osfilename, NULL); - /* - * List the public half of the OpenSSH-formatted key in - * IETF/ssh.com format. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-p", osfilename, NULL); - } + /* + * List the public half of the OpenSSH-formatted key in + * IETF/ssh.com format. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-p", osfilename, NULL); + } - /* - * Export the private key into ssh.com format, this time - * while encrypted. For RSA1 keys, this should give an - * error. - */ - if (i == 0) - setup_passphrases(NULL); /* error, hence no passphrase read */ - else - setup_passphrases("sponge2", NULL); - test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename, - filename, NULL); + /* + * Export the private key into ssh.com format, this time + * while encrypted. For RSA1 keys, this should give an + * error. + */ + if (i == 0) + setup_passphrases(NULL); /* error, hence no passphrase read */ + else + setup_passphrases("sponge2", NULL); + test((i==0), "puttygen", "-O", "private-sshcom", "-o", scfilename, + filename, NULL); - if (i) { - /* - * List the fingerprint of the ssh.com-formatted key. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL); - check_fp(tmpfilename1, fp, "%s ssh.com encrypted fp", keytypes[i]); + if (i) { + /* + * List the fingerprint of the ssh.com-formatted key. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-l", scfilename, "-o", tmpfilename1, NULL); + check_fp(tmpfilename1, fp, "%s ssh.com encrypted fp", keytypes[i]); - /* - * List the public half of the ssh.com-formatted key in - * OpenSSH format. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-L", scfilename, NULL); + /* + * List the public half of the ssh.com-formatted key in + * OpenSSH format. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-L", scfilename, NULL); - /* - * List the public half of the ssh.com-formatted key in - * IETF/ssh.com format. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-p", scfilename, NULL); - } + /* + * List the public half of the ssh.com-formatted key in + * IETF/ssh.com format. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-p", scfilename, NULL); + } - if (i) { - /* - * Convert from OpenSSH into ssh.com. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", osfilename, "-o", tmpfilename1, - "-O", "private-sshcom", NULL); + if (i) { + /* + * Convert from OpenSSH into ssh.com. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", osfilename, "-o", tmpfilename1, + "-O", "private-sshcom", NULL); - /* - * Convert from ssh.com back into a PuTTY key, - * supplying the same comment as we had before we - * started to ensure the comparison works. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", - "-o", tmpfilename2, NULL); + /* + * Convert from ssh.com back into a PuTTY key, + * supplying the same comment as we had before we + * started to ensure the comparison works. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", + "-o", tmpfilename2, NULL); - /* - * See if the PuTTY key thus generated is the same as - * the original. - */ - filecmp(filename, tmpfilename2, - "p->o->s->p encrypted %s", keytypes[i]); + /* + * See if the PuTTY key thus generated is the same as + * the original. + */ + filecmp(filename, tmpfilename2, + "p->o->s->p encrypted %s", keytypes[i]); - /* - * Convert from ssh.com to OpenSSH. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", scfilename, "-o", tmpfilename1, - "-O", "private-openssh", NULL); + /* + * Convert from ssh.com to OpenSSH. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", scfilename, "-o", tmpfilename1, + "-O", "private-openssh", NULL); - /* - * Convert from OpenSSH back into a PuTTY key, - * supplying the same comment as we had before we - * started to ensure the comparison works. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", - "-o", tmpfilename2, NULL); + /* + * Convert from OpenSSH back into a PuTTY key, + * supplying the same comment as we had before we + * started to ensure the comparison works. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", tmpfilename1, "-C", "new-comment-2", + "-o", tmpfilename2, NULL); - /* - * See if the PuTTY key thus generated is the same as - * the original. - */ - filecmp(filename, tmpfilename2, - "p->s->o->p encrypted %s", keytypes[i]); + /* + * See if the PuTTY key thus generated is the same as + * the original. + */ + filecmp(filename, tmpfilename2, + "p->s->o->p encrypted %s", keytypes[i]); - /* - * Finally, do a round-trip conversion between PuTTY - * and ssh.com without involving OpenSSH, to test that - * the key comment is preserved in that case. - */ - setup_passphrases("sponge2", NULL); - test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1, - filename, NULL); - setup_passphrases("sponge2", NULL); - test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL); - filecmp(filename, tmpfilename2, - "p->s->p encrypted %s", keytypes[i]); - } + /* + * Finally, do a round-trip conversion between PuTTY + * and ssh.com without involving OpenSSH, to test that + * the key comment is preserved in that case. + */ + setup_passphrases("sponge2", NULL); + test(0, "puttygen", "-O", "private-sshcom", "-o", tmpfilename1, + filename, NULL); + setup_passphrases("sponge2", NULL); + test(0, "puttygen", tmpfilename1, "-o", tmpfilename2, NULL); + filecmp(filename, tmpfilename2, + "p->s->p encrypted %s", keytypes[i]); + } - /* - * Load with the wrong passphrase. - */ - setup_passphrases("sponge8", NULL); - test(1, "puttygen", "-C", "spurious-new-comment", filename, NULL); + /* + * Load with the wrong passphrase. + */ + setup_passphrases("sponge8", NULL); + test(1, "puttygen", "-C", "spurious-new-comment", filename, NULL); - /* - * Load a totally bogus file. - */ - setup_passphrases(NULL); - test(1, "puttygen", "-C", "spurious-new-comment", pubfilename, NULL); + /* + * Load a totally bogus file. + */ + setup_passphrases(NULL); + test(1, "puttygen", "-C", "spurious-new-comment", pubfilename, NULL); } printf("%d passes, %d fails\n", passes, fails); return 0; diff --git a/cmdline.c b/cmdline.c index b3826a05..b9d068f6 100644 --- a/cmdline.c +++ b/cmdline.c @@ -14,14 +14,14 @@ * eventual running configuration. For this we use the macro * SAVEABLE, which notices if the `need_save' parameter is set and * saves the parameter and value on a list. - * + * * We also assign priorities to saved parameters, just to slightly * ameliorate silly ordering problems. For example, if you specify * a saved session to load, it will be loaded _before_ all your * local modifications such as -L are evaluated; and if you specify * a protocol and a port, the protocol is set up first so that the * port can override its choice of port number. - * + * * (In fact -load is not saved at all, since in at least Plink the * processing of further command-line options depends on whether or * not the loaded session contained a hostname. So it must be @@ -59,16 +59,16 @@ void cmdline_cleanup(void) int pri; if (cmdline_password) { - smemclr(cmdline_password, strlen(cmdline_password)); - sfree(cmdline_password); - cmdline_password = NULL; + smemclr(cmdline_password, strlen(cmdline_password)); + sfree(cmdline_password); + cmdline_password = NULL; } - + for (pri = 0; pri < NPRIORITIES; pri++) { - sfree(saves[pri].params); - saves[pri].params = NULL; - saves[pri].savesize = 0; - saves[pri].nsaved = 0; + sfree(saves[pri].params); + saves[pri].params = NULL; + saves[pri].savesize = 0; + saves[pri].nsaved = 0; } } @@ -91,7 +91,7 @@ int cmdline_get_passwd_input(prompts_t *p) * that comes in a prompt-set on its own. */ if (!cmdline_password || p->n_prompts != 1 || p->prompts[0]->echo) { - return -1; + return -1; } /* @@ -99,7 +99,7 @@ int cmdline_get_passwd_input(prompts_t *p) * to try). */ if (tried_once) - return 0; + return 0; prompt_set_result(p->prompts[0], cmdline_password); smemclr(cmdline_password, strlen(cmdline_password)); @@ -124,8 +124,8 @@ int cmdline_tooltype = 0; static bool cmdline_check_unavailable(int flag, const char *p) { if (cmdline_tooltype & flag) { - cmdline_error("option \"%s\" not available in this tool", p); - return true; + cmdline_error("option \"%s\" not available in this tool", p); + return true; } return false; } @@ -325,11 +325,11 @@ int cmdline_process_param(const char *p, char *value, !loaded_session) { /* * For some tools, we equivocate between a - * hostname argument and an argument naming a - * saved session. Here we attempt to load a - * session with the specified name, and if that - * session exists and is launchable, we overwrite - * the entire Conf with it. + * hostname argument and an argument naming a + * saved session. Here we attempt to load a + * session with the specified name, and if that + * session exists and is launchable, we overwrite + * the entire Conf with it. * * We skip this check if a -load option has * already happened, so that @@ -345,7 +345,7 @@ int cmdline_process_param(const char *p, char *value, * So if that was the behaviour someone wanted, * then they could get it by leaving off the * -load completely.) - */ + */ Conf *conf2 = conf_new(); if (do_defaults(hostname_after_user, conf2) && conf_launchable(conf2)) { @@ -394,83 +394,83 @@ int cmdline_process_param(const char *p, char *value, } if (!strcmp(p, "-load")) { - RETURN(2); - /* This parameter must be processed immediately rather than being - * saved. */ - do_defaults(value, conf); - loaded_session = true; - cmdline_session_name = dupstr(value); - return 2; + RETURN(2); + /* This parameter must be processed immediately rather than being + * saved. */ + do_defaults(value, conf); + loaded_session = true; + cmdline_session_name = dupstr(value); + return 2; } if (!strcmp(p, "-ssh")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - default_protocol = PROT_SSH; - default_port = 22; - conf_set_int(conf, CONF_protocol, default_protocol); - conf_set_int(conf, CONF_port, default_port); - return 1; + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + default_protocol = PROT_SSH; + default_port = 22; + conf_set_int(conf, CONF_protocol, default_protocol); + conf_set_int(conf, CONF_port, default_port); + return 1; } if (!strcmp(p, "-telnet")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - default_protocol = PROT_TELNET; - default_port = 23; - conf_set_int(conf, CONF_protocol, default_protocol); - conf_set_int(conf, CONF_port, default_port); - return 1; + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + default_protocol = PROT_TELNET; + default_port = 23; + conf_set_int(conf, CONF_protocol, default_protocol); + conf_set_int(conf, CONF_port, default_port); + return 1; } if (!strcmp(p, "-rlogin")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - default_protocol = PROT_RLOGIN; - default_port = 513; - conf_set_int(conf, CONF_protocol, default_protocol); - conf_set_int(conf, CONF_port, default_port); - return 1; + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + default_protocol = PROT_RLOGIN; + default_port = 513; + conf_set_int(conf, CONF_protocol, default_protocol); + conf_set_int(conf, CONF_port, default_port); + return 1; } if (!strcmp(p, "-raw")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - default_protocol = PROT_RAW; - conf_set_int(conf, CONF_protocol, default_protocol); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + default_protocol = PROT_RAW; + conf_set_int(conf, CONF_protocol, default_protocol); } if (!strcmp(p, "-serial")) { - RETURN(1); - /* Serial is not NONNETWORK in an odd sense of the word */ - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - default_protocol = PROT_SERIAL; - conf_set_int(conf, CONF_protocol, default_protocol); - /* The host parameter will already be loaded into CONF_host, - * so copy it across */ - conf_set_str(conf, CONF_serline, conf_get_str(conf, CONF_host)); + RETURN(1); + /* Serial is not NONNETWORK in an odd sense of the word */ + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + default_protocol = PROT_SERIAL; + conf_set_int(conf, CONF_protocol, default_protocol); + /* The host parameter will already be loaded into CONF_host, + * so copy it across */ + conf_set_str(conf, CONF_serline, conf_get_str(conf, CONF_host)); } if (!strcmp(p, "-v")) { - RETURN(1); - flags |= FLAG_VERBOSE; + RETURN(1); + flags |= FLAG_VERBOSE; } if (!strcmp(p, "-l")) { - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_str(conf, CONF_username, value); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_str(conf, CONF_username, value); } if (!strcmp(p, "-loghost")) { - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_str(conf, CONF_loghost, value); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_str(conf, CONF_loghost, value); } if (!strcmp(p, "-hostkey")) { char *dup; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); dup = dupstr(value); if (!validate_manual_hostkey(dup)) { cmdline_error("'%s' is not a valid format for a manual host " @@ -478,51 +478,51 @@ int cmdline_process_param(const char *p, char *value, sfree(dup); return ret; } - conf_set_str_str(conf, CONF_ssh_manual_hostkeys, dup, ""); + conf_set_str_str(conf, CONF_ssh_manual_hostkeys, dup, ""); sfree(dup); } if ((!strcmp(p, "-L") || !strcmp(p, "-R") || !strcmp(p, "-D"))) { - char type, *q, *qq, *key, *val; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - if (strcmp(p, "-D")) { - /* + char type, *q, *qq, *key, *val; + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + if (strcmp(p, "-D")) { + /* * For -L or -R forwarding types: * - * We expect _at least_ two colons in this string. The - * possible formats are `sourceport:desthost:destport', - * or `sourceip:sourceport:desthost:destport' if you're - * specifying a particular loopback address. We need to - * replace the one between source and dest with a \t; - * this means we must find the second-to-last colon in - * the string. - * - * (This looks like a foolish way of doing it given the - * existence of strrchr, but it's more efficient than - * two strrchrs - not to mention that the second strrchr - * would require us to modify the input string!) - */ + * We expect _at least_ two colons in this string. The + * possible formats are `sourceport:desthost:destport', + * or `sourceip:sourceport:desthost:destport' if you're + * specifying a particular loopback address. We need to + * replace the one between source and dest with a \t; + * this means we must find the second-to-last colon in + * the string. + * + * (This looks like a foolish way of doing it given the + * existence of strrchr, but it's more efficient than + * two strrchrs - not to mention that the second strrchr + * would require us to modify the input string!) + */ type = p[1]; /* 'L' or 'R' */ - q = qq = host_strchr(value, ':'); - while (qq) { - char *qqq = host_strchr(qq+1, ':'); - if (qqq) - q = qq; - qq = qqq; - } + q = qq = host_strchr(value, ':'); + while (qq) { + char *qqq = host_strchr(qq+1, ':'); + if (qqq) + q = qq; + qq = qqq; + } - if (!q) { - cmdline_error("-%c expects at least two colons in its" - " argument", type); - return ret; - } + if (!q) { + cmdline_error("-%c expects at least two colons in its" + " argument", type); + return ret; + } - key = dupprintf("%c%.*s", type, (int)(q - value), value); - val = dupstr(q+1); - } else { + key = dupprintf("%c%.*s", type, (int)(q - value), value); + val = dupstr(q+1); + } else { /* * Dynamic port forwardings are entered under the same key * as if they were local (because they occupy the same @@ -532,313 +532,313 @@ int cmdline_process_param(const char *p, char *value, * anything in the ordinary -L case by containing no * colon). */ - key = dupprintf("L%s", value); - val = dupstr("D"); - } - conf_set_str_str(conf, CONF_portfwd, key, val); - sfree(key); - sfree(val); + key = dupprintf("L%s", value); + val = dupstr("D"); + } + conf_set_str_str(conf, CONF_portfwd, key, val); + sfree(key); + sfree(val); } if ((!strcmp(p, "-nc"))) { - char *host, *portp; + char *host, *portp; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); - portp = host_strchr(value, ':'); - if (!portp) { - cmdline_error("-nc expects argument of form 'host:port'"); - return ret; - } + portp = host_strchr(value, ':'); + if (!portp) { + cmdline_error("-nc expects argument of form 'host:port'"); + return ret; + } - host = dupprintf("%.*s", (int)(portp - value), value); - conf_set_str(conf, CONF_ssh_nc_host, host); - conf_set_int(conf, CONF_ssh_nc_port, atoi(portp + 1)); + host = dupprintf("%.*s", (int)(portp - value), value); + conf_set_str(conf, CONF_ssh_nc_host, host); + conf_set_int(conf, CONF_ssh_nc_port, atoi(portp + 1)); sfree(host); } if (!strcmp(p, "-m")) { - const char *filename; - FILE *fp; + const char *filename; + FILE *fp; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); - filename = value; + filename = value; - fp = fopen(filename, "r"); - if (!fp) { - cmdline_error("unable to open command file \"%s\"", filename); - return ret; - } + fp = fopen(filename, "r"); + if (!fp) { + cmdline_error("unable to open command file \"%s\"", filename); + return ret; + } strbuf *command = strbuf_new(); char readbuf[4096]; - while (1) { + while (1) { size_t nread = fread(readbuf, 1, sizeof(readbuf), fp); if (nread == 0) break; put_data(command, readbuf, nread); - } - fclose(fp); - conf_set_str(conf, CONF_remote_cmd, command->s); - conf_set_str(conf, CONF_remote_cmd2, ""); - conf_set_bool(conf, CONF_nopty, true); /* command => no terminal */ - strbuf_free(command); + } + fclose(fp); + conf_set_str(conf, CONF_remote_cmd, command->s); + conf_set_str(conf, CONF_remote_cmd2, ""); + conf_set_bool(conf, CONF_nopty, true); /* command => no terminal */ + strbuf_free(command); } if (!strcmp(p, "-P")) { - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(1); /* lower priority than -ssh,-telnet */ - conf_set_int(conf, CONF_port, atoi(value)); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(1); /* lower priority than -ssh,-telnet */ + conf_set_int(conf, CONF_port, atoi(value)); } if (!strcmp(p, "-pw")) { - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(1); - /* We delay evaluating this until after the protocol is decided, - * so that we can warn if it's of no use with the selected protocol */ - if (conf_get_int(conf, CONF_protocol) != PROT_SSH) - cmdline_error("the -pw option can only be used with the " - "SSH protocol"); - else { - cmdline_password = dupstr(value); - /* Assuming that `value' is directly from argv, make a good faith - * attempt to trample it, to stop it showing up in `ps' output - * on Unix-like systems. Not guaranteed, of course. */ - smemclr(value, strlen(value)); - } + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(1); + /* We delay evaluating this until after the protocol is decided, + * so that we can warn if it's of no use with the selected protocol */ + if (conf_get_int(conf, CONF_protocol) != PROT_SSH) + cmdline_error("the -pw option can only be used with the " + "SSH protocol"); + else { + cmdline_password = dupstr(value); + /* Assuming that `value' is directly from argv, make a good faith + * attempt to trample it, to stop it showing up in `ps' output + * on Unix-like systems. Not guaranteed, of course. */ + smemclr(value, strlen(value)); + } } if (!strcmp(p, "-agent") || !strcmp(p, "-pagent") || - !strcmp(p, "-pageant")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_tryagent, true); + !strcmp(p, "-pageant")) { + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_tryagent, true); } if (!strcmp(p, "-noagent") || !strcmp(p, "-nopagent") || - !strcmp(p, "-nopageant")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_tryagent, false); + !strcmp(p, "-nopageant")) { + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_tryagent, false); } if (!strcmp(p, "-share")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_ssh_connection_sharing, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_ssh_connection_sharing, true); } if (!strcmp(p, "-noshare")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_ssh_connection_sharing, false); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_ssh_connection_sharing, false); } if (!strcmp(p, "-A")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_agentfwd, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_agentfwd, true); } if (!strcmp(p, "-a")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_agentfwd, false); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_agentfwd, false); } if (!strcmp(p, "-X")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_x11_forward, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_x11_forward, true); } if (!strcmp(p, "-x")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_x11_forward, false); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_x11_forward, false); } if (!strcmp(p, "-t")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(1); /* lower priority than -m */ - conf_set_bool(conf, CONF_nopty, false); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(1); /* lower priority than -m */ + conf_set_bool(conf, CONF_nopty, false); } if (!strcmp(p, "-T")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(1); - conf_set_bool(conf, CONF_nopty, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(1); + conf_set_bool(conf, CONF_nopty, true); } if (!strcmp(p, "-N")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_ssh_no_shell, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_ssh_no_shell, true); } if (!strcmp(p, "-C")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_bool(conf, CONF_compression, true); + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_bool(conf, CONF_compression, true); } if (!strcmp(p, "-1")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_int(conf, CONF_sshprot, 0); /* ssh protocol 1 only */ + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_int(conf, CONF_sshprot, 0); /* ssh protocol 1 only */ } if (!strcmp(p, "-2")) { - RETURN(1); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - conf_set_int(conf, CONF_sshprot, 3); /* ssh protocol 2 only */ + RETURN(1); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + conf_set_int(conf, CONF_sshprot, 3); /* ssh protocol 2 only */ } if (!strcmp(p, "-i")) { - Filename *fn; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - fn = filename_from_str(value); - conf_set_filename(conf, CONF_keyfile, fn); + Filename *fn; + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + fn = filename_from_str(value); + conf_set_filename(conf, CONF_keyfile, fn); filename_free(fn); } if (!strcmp(p, "-4") || !strcmp(p, "-ipv4")) { - RETURN(1); - SAVEABLE(1); - conf_set_int(conf, CONF_addressfamily, ADDRTYPE_IPV4); + RETURN(1); + SAVEABLE(1); + conf_set_int(conf, CONF_addressfamily, ADDRTYPE_IPV4); } if (!strcmp(p, "-6") || !strcmp(p, "-ipv6")) { - RETURN(1); - SAVEABLE(1); - conf_set_int(conf, CONF_addressfamily, ADDRTYPE_IPV6); + RETURN(1); + SAVEABLE(1); + conf_set_int(conf, CONF_addressfamily, ADDRTYPE_IPV6); } if (!strcmp(p, "-sercfg")) { - char* nextitem; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); - SAVEABLE(1); - if (conf_get_int(conf, CONF_protocol) != PROT_SERIAL) - cmdline_error("the -sercfg option can only be used with the " - "serial protocol"); - /* Value[0] contains one or more , separated values, like 19200,8,n,1,X */ - nextitem = value; - while (nextitem[0] != '\0') { - int length, skip; - char *end = strchr(nextitem, ','); - if (!end) { - length = strlen(nextitem); - skip = 0; - } else { - length = end - nextitem; - nextitem[length] = '\0'; - skip = 1; - } - if (length == 1) { - switch (*nextitem) { - case '1': - case '2': - conf_set_int(conf, CONF_serstopbits, 2 * (*nextitem-'0')); - break; + char* nextitem; + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK); + SAVEABLE(1); + if (conf_get_int(conf, CONF_protocol) != PROT_SERIAL) + cmdline_error("the -sercfg option can only be used with the " + "serial protocol"); + /* Value[0] contains one or more , separated values, like 19200,8,n,1,X */ + nextitem = value; + while (nextitem[0] != '\0') { + int length, skip; + char *end = strchr(nextitem, ','); + if (!end) { + length = strlen(nextitem); + skip = 0; + } else { + length = end - nextitem; + nextitem[length] = '\0'; + skip = 1; + } + if (length == 1) { + switch (*nextitem) { + case '1': + case '2': + conf_set_int(conf, CONF_serstopbits, 2 * (*nextitem-'0')); + break; - case '5': - case '6': - case '7': - case '8': - case '9': - conf_set_int(conf, CONF_serdatabits, *nextitem-'0'); - break; + case '5': + case '6': + case '7': + case '8': + case '9': + conf_set_int(conf, CONF_serdatabits, *nextitem-'0'); + break; - case 'n': - conf_set_int(conf, CONF_serparity, SER_PAR_NONE); - break; - case 'o': - conf_set_int(conf, CONF_serparity, SER_PAR_ODD); - break; - case 'e': - conf_set_int(conf, CONF_serparity, SER_PAR_EVEN); - break; - case 'm': - conf_set_int(conf, CONF_serparity, SER_PAR_MARK); - break; - case 's': - conf_set_int(conf, CONF_serparity, SER_PAR_SPACE); - break; + case 'n': + conf_set_int(conf, CONF_serparity, SER_PAR_NONE); + break; + case 'o': + conf_set_int(conf, CONF_serparity, SER_PAR_ODD); + break; + case 'e': + conf_set_int(conf, CONF_serparity, SER_PAR_EVEN); + break; + case 'm': + conf_set_int(conf, CONF_serparity, SER_PAR_MARK); + break; + case 's': + conf_set_int(conf, CONF_serparity, SER_PAR_SPACE); + break; - case 'N': - conf_set_int(conf, CONF_serflow, SER_FLOW_NONE); - break; - case 'X': - conf_set_int(conf, CONF_serflow, SER_FLOW_XONXOFF); - break; - case 'R': - conf_set_int(conf, CONF_serflow, SER_FLOW_RTSCTS); - break; - case 'D': - conf_set_int(conf, CONF_serflow, SER_FLOW_DSRDTR); - break; + case 'N': + conf_set_int(conf, CONF_serflow, SER_FLOW_NONE); + break; + case 'X': + conf_set_int(conf, CONF_serflow, SER_FLOW_XONXOFF); + break; + case 'R': + conf_set_int(conf, CONF_serflow, SER_FLOW_RTSCTS); + break; + case 'D': + conf_set_int(conf, CONF_serflow, SER_FLOW_DSRDTR); + break; - default: - cmdline_error("Unrecognised suboption \"-sercfg %c\"", - *nextitem); - } - } else if (length == 3 && !strncmp(nextitem,"1.5",3)) { - /* Messy special case */ - conf_set_int(conf, CONF_serstopbits, 3); - } else { - int serspeed = atoi(nextitem); - if (serspeed != 0) { - conf_set_int(conf, CONF_serspeed, serspeed); - } else { - cmdline_error("Unrecognised suboption \"-sercfg %s\"", - nextitem); - } - } - nextitem += length + skip; - } + default: + cmdline_error("Unrecognised suboption \"-sercfg %c\"", + *nextitem); + } + } else if (length == 3 && !strncmp(nextitem,"1.5",3)) { + /* Messy special case */ + conf_set_int(conf, CONF_serstopbits, 3); + } else { + int serspeed = atoi(nextitem); + if (serspeed != 0) { + conf_set_int(conf, CONF_serspeed, serspeed); + } else { + cmdline_error("Unrecognised suboption \"-sercfg %s\"", + nextitem); + } + } + nextitem += length + skip; + } } if (!strcmp(p, "-sessionlog")) { - Filename *fn; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER); - /* but available even in TOOLTYPE_NONNETWORK, cf pterm "-log" */ - SAVEABLE(0); - fn = filename_from_str(value); - conf_set_filename(conf, CONF_logfilename, fn); - conf_set_int(conf, CONF_logtype, LGTYP_DEBUG); + Filename *fn; + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER); + /* but available even in TOOLTYPE_NONNETWORK, cf pterm "-log" */ + SAVEABLE(0); + fn = filename_from_str(value); + conf_set_filename(conf, CONF_logfilename, fn); + conf_set_int(conf, CONF_logtype, LGTYP_DEBUG); filename_free(fn); } if (!strcmp(p, "-sshlog") || !strcmp(p, "-sshrawlog")) { - Filename *fn; - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); - fn = filename_from_str(value); - conf_set_filename(conf, CONF_logfilename, fn); - conf_set_int(conf, CONF_logtype, + Filename *fn; + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); + fn = filename_from_str(value); + conf_set_filename(conf, CONF_logfilename, fn); + conf_set_int(conf, CONF_logtype, !strcmp(p, "-sshlog") ? LGTYP_PACKETS : /* !strcmp(p, "-sshrawlog") ? */ LGTYP_SSHRAW); filename_free(fn); } if (!strcmp(p, "-proxycmd")) { - RETURN(2); - UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); - SAVEABLE(0); + RETURN(2); + UNAVAILABLE_IN(TOOLTYPE_NONNETWORK); + SAVEABLE(0); conf_set_int(conf, CONF_proxy_type, PROXY_CMD); - conf_set_str(conf, CONF_proxy_telnet_command, value); + conf_set_str(conf, CONF_proxy_telnet_command, value); } #ifdef _WINDOWS @@ -847,22 +847,22 @@ int cmdline_process_param(const char *p, char *value, */ if (!strcmp(p, "-restrict-acl") || !strcmp(p, "-restrict_acl") || !strcmp(p, "-restrictacl")) { - RETURN(1); + RETURN(1); restrict_process_acl(); restricted_acl = true; } #endif - return ret; /* unrecognised */ + return ret; /* unrecognised */ } void cmdline_run_saved(Conf *conf) { int pri, i; for (pri = 0; pri < NPRIORITIES; pri++) { - for (i = 0; i < saves[pri].nsaved; i++) { - cmdline_process_param(saves[pri].params[i].p, - saves[pri].params[i].value, 0, conf); + for (i = 0; i < saves[pri].nsaved; i++) { + cmdline_process_param(saves[pri].params[i].p, + saves[pri].params[i].value, 0, conf); sfree(saves[pri].params[i].p); sfree(saves[pri].params[i].value); } diff --git a/conf.c b/conf.c index f97b47df..ecd26cd0 100644 --- a/conf.c +++ b/conf.c @@ -36,8 +36,8 @@ static int valuetypes[] = { CONFIG_OPTIONS(CONF_VALUETYPE_DEF) }; struct key { int primary; union { - int i; - char *s; + int i; + char *s; } secondary; }; @@ -46,18 +46,18 @@ struct key { struct constkey { int primary; union { - int i; - const char *s; + int i; + const char *s; } secondary; }; struct value { union { - bool boolval; - int intval; - char *stringval; - Filename *fileval; - FontSpec *fontval; + bool boolval; + int intval; + char *stringval; + Filename *fileval; + FontSpec *fontval; } u; }; @@ -84,20 +84,20 @@ static int conf_cmp(void *av, void *bv) struct key *b = (struct key *)bv; if (a->primary < b->primary) - return -1; + return -1; else if (a->primary > b->primary) - return +1; + return +1; switch (subkeytypes[a->primary]) { case TYPE_INT: - if (a->secondary.i < b->secondary.i) - return -1; - else if (a->secondary.i > b->secondary.i) - return +1; - return 0; + if (a->secondary.i < b->secondary.i) + return -1; + else if (a->secondary.i > b->secondary.i) + return +1; + return 0; case TYPE_STR: - return strcmp(a->secondary.s, b->secondary.s); + return strcmp(a->secondary.s, b->secondary.s); default: - return 0; + return 0; } } @@ -107,20 +107,20 @@ static int conf_cmp_constkey(void *av, void *bv) struct constkey *b = (struct constkey *)bv; if (a->primary < b->primary) - return -1; + return -1; else if (a->primary > b->primary) - return +1; + return +1; switch (subkeytypes[a->primary]) { case TYPE_INT: - if (a->secondary.i < b->secondary.i) - return -1; - else if (a->secondary.i > b->secondary.i) - return +1; - return 0; + if (a->secondary.i < b->secondary.i) + return -1; + else if (a->secondary.i > b->secondary.i) + return +1; + return 0; case TYPE_STR: - return strcmp(a->secondary.s, b->secondary.s); + return strcmp(a->secondary.s, b->secondary.s); default: - return 0; + return 0; } } @@ -132,7 +132,7 @@ static int conf_cmp_constkey(void *av, void *bv) static void free_key(struct key *key) { if (subkeytypes[key->primary] == TYPE_STR) - sfree(key->secondary.s); + sfree(key->secondary.s); } /* @@ -144,11 +144,11 @@ static void copy_key(struct key *to, struct key *from) to->primary = from->primary; switch (subkeytypes[to->primary]) { case TYPE_INT: - to->secondary.i = from->secondary.i; - break; + to->secondary.i = from->secondary.i; + break; case TYPE_STR: - to->secondary.s = dupstr(from->secondary.s); - break; + to->secondary.s = dupstr(from->secondary.s); + break; } } @@ -160,11 +160,11 @@ static void copy_key(struct key *to, struct key *from) static void free_value(struct value *val, int type) { if (type == TYPE_STR) - sfree(val->u.stringval); + sfree(val->u.stringval); else if (type == TYPE_FILENAME) - filename_free(val->u.fileval); + filename_free(val->u.fileval); else if (type == TYPE_FONT) - fontspec_free(val->u.fontval); + fontspec_free(val->u.fontval); } /* @@ -175,20 +175,20 @@ static void copy_value(struct value *to, struct value *from, int type) { switch (type) { case TYPE_BOOL: - to->u.boolval = from->u.boolval; - break; + to->u.boolval = from->u.boolval; + break; case TYPE_INT: - to->u.intval = from->u.intval; - break; + to->u.intval = from->u.intval; + break; case TYPE_STR: - to->u.stringval = dupstr(from->u.stringval); - break; + to->u.stringval = dupstr(from->u.stringval); + break; case TYPE_FILENAME: - to->u.fileval = filename_copy(from->u.fileval); - break; + to->u.fileval = filename_copy(from->u.fileval); + break; case TYPE_FONT: - to->u.fontval = fontspec_copy(from->u.fontval); - break; + to->u.fontval = fontspec_copy(from->u.fontval); + break; } } @@ -216,7 +216,7 @@ static void conf_clear(Conf *conf) struct conf_entry *entry; while ((entry = delpos234(conf->tree, 0)) != NULL) - free_entry(entry); + free_entry(entry); } void conf_free(Conf *conf) @@ -230,10 +230,10 @@ static void conf_insert(Conf *conf, struct conf_entry *entry) { struct conf_entry *oldentry = add234(conf->tree, entry); if (oldentry && oldentry != entry) { - del234(conf->tree, oldentry); - free_entry(oldentry); - oldentry = add234(conf->tree, entry); - assert(oldentry == entry); + del234(conf->tree, oldentry); + free_entry(oldentry); + oldentry = add234(conf->tree, entry); + assert(oldentry == entry); } } @@ -245,11 +245,11 @@ void conf_copy_into(Conf *newconf, Conf *oldconf) conf_clear(newconf); for (i = 0; (entry = index234(oldconf->tree, i)) != NULL; i++) { - entry2 = snew(struct conf_entry); - copy_key(&entry2->key, &entry->key); - copy_value(&entry2->value, &entry->value, - valuetypes[entry->key.primary]); - add234(newconf->tree, entry2); + entry2 = snew(struct conf_entry); + copy_key(&entry2->key, &entry->key); + copy_value(&entry2->value, &entry->value, + valuetypes[entry->key.primary]); + add234(newconf->tree, entry2); } } @@ -336,7 +336,7 @@ char *conf_get_str_str(Conf *conf, int primary, const char *secondary) } char *conf_get_str_strs(Conf *conf, int primary, - char *subkeyin, char **subkeyout) + char *subkeyin, char **subkeyout) { struct constkey key; struct conf_entry *entry; @@ -345,14 +345,14 @@ char *conf_get_str_strs(Conf *conf, int primary, assert(valuetypes[primary] == TYPE_STR); key.primary = primary; if (subkeyin) { - key.secondary.s = subkeyin; - entry = findrel234(conf->tree, &key, NULL, REL234_GT); + key.secondary.s = subkeyin; + entry = findrel234(conf->tree, &key, NULL, REL234_GT); } else { - key.secondary.s = ""; - entry = findrel234(conf->tree, &key, conf_cmp_constkey, REL234_GE); + key.secondary.s = ""; + entry = findrel234(conf->tree, &key, conf_cmp_constkey, REL234_GE); } if (!entry || entry->key.primary != primary) - return NULL; + return NULL; *subkeyout = entry->key.secondary.s; return entry->value.u.stringval; } @@ -370,10 +370,10 @@ char *conf_get_str_nthstrkey(Conf *conf, int primary, int n) entry = findrelpos234(conf->tree, &key, conf_cmp_constkey, REL234_GE, &index); if (!entry || entry->key.primary != primary) - return NULL; + return NULL; entry = index234(conf->tree, index + n); if (!entry || entry->key.primary != primary) - return NULL; + return NULL; return entry->key.secondary.s; } @@ -450,7 +450,7 @@ void conf_set_str(Conf *conf, int primary, const char *value) } void conf_set_str_str(Conf *conf, int primary, const char *secondary, - const char *value) + const char *value) { struct conf_entry *entry = snew(struct conf_entry); @@ -473,8 +473,8 @@ void conf_del_str_str(Conf *conf, int primary, const char *secondary) key.secondary.s = (char *)secondary; entry = find234(conf->tree, &key, NULL); if (entry) { - del234(conf->tree, entry); - free_entry(entry); + del234(conf->tree, entry); + free_entry(entry); } } @@ -506,33 +506,33 @@ void conf_serialise(BinarySink *bs, Conf *conf) struct conf_entry *entry; for (i = 0; (entry = index234(conf->tree, i)) != NULL; i++) { - put_uint32(bs, entry->key.primary); + put_uint32(bs, entry->key.primary); - switch (subkeytypes[entry->key.primary]) { - case TYPE_INT: - put_uint32(bs, entry->key.secondary.i); - break; - case TYPE_STR: + switch (subkeytypes[entry->key.primary]) { + case TYPE_INT: + put_uint32(bs, entry->key.secondary.i); + break; + case TYPE_STR: put_asciz(bs, entry->key.secondary.s); - break; - } - switch (valuetypes[entry->key.primary]) { - case TYPE_BOOL: - put_bool(bs, entry->value.u.boolval); - break; - case TYPE_INT: - put_uint32(bs, entry->value.u.intval); - break; - case TYPE_STR: - put_asciz(bs, entry->value.u.stringval); - break; - case TYPE_FILENAME: + break; + } + switch (valuetypes[entry->key.primary]) { + case TYPE_BOOL: + put_bool(bs, entry->value.u.boolval); + break; + case TYPE_INT: + put_uint32(bs, entry->value.u.intval); + break; + case TYPE_STR: + put_asciz(bs, entry->value.u.stringval); + break; + case TYPE_FILENAME: filename_serialise(bs, entry->value.u.fileval); - break; - case TYPE_FONT: + break; + case TYPE_FONT: fontspec_serialise(bs, entry->value.u.fontval); - break; - } + break; + } } put_uint32(bs, 0xFFFFFFFFU); @@ -550,44 +550,44 @@ bool conf_deserialise(Conf *conf, BinarySource *src) return false; if (primary == 0xFFFFFFFFU) return true; - if (primary >= N_CONFIG_OPTIONS) - return false; + if (primary >= N_CONFIG_OPTIONS) + return false; - entry = snew(struct conf_entry); - entry->key.primary = primary; + entry = snew(struct conf_entry); + entry->key.primary = primary; - switch (subkeytypes[entry->key.primary]) { - case TYPE_INT: - entry->key.secondary.i = toint(get_uint32(src)); - break; - case TYPE_STR: - entry->key.secondary.s = dupstr(get_asciz(src)); - break; - } + switch (subkeytypes[entry->key.primary]) { + case TYPE_INT: + entry->key.secondary.i = toint(get_uint32(src)); + break; + case TYPE_STR: + entry->key.secondary.s = dupstr(get_asciz(src)); + break; + } - switch (valuetypes[entry->key.primary]) { - case TYPE_BOOL: - entry->value.u.boolval = get_bool(src); - break; - case TYPE_INT: - entry->value.u.intval = toint(get_uint32(src)); - break; - case TYPE_STR: - entry->value.u.stringval = dupstr(get_asciz(src)); - break; - case TYPE_FILENAME: + switch (valuetypes[entry->key.primary]) { + case TYPE_BOOL: + entry->value.u.boolval = get_bool(src); + break; + case TYPE_INT: + entry->value.u.intval = toint(get_uint32(src)); + break; + case TYPE_STR: + entry->value.u.stringval = dupstr(get_asciz(src)); + break; + case TYPE_FILENAME: entry->value.u.fileval = filename_deserialise(src); - break; - case TYPE_FONT: + break; + case TYPE_FONT: entry->value.u.fontval = fontspec_deserialise(src); - break; - } + break; + } if (get_err(src)) { free_entry(entry); return false; } - conf_insert(conf, entry); + conf_insert(conf, entry); } } diff --git a/config.c b/config.c index d9970c0c..a265dda5 100644 --- a/config.c +++ b/config.c @@ -16,7 +16,7 @@ #define PORT_BOX_TITLE "Port" void conf_radiobutton_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int button; Conf *conf = (Conf *)data; @@ -28,18 +28,18 @@ void conf_radiobutton_handler(union control *ctrl, dlgparam *dlg, * is the one selected. */ if (event == EVENT_REFRESH) { - int val = conf_get_int(conf, ctrl->radio.context.i); - for (button = 0; button < ctrl->radio.nbuttons; button++) - if (val == ctrl->radio.buttondata[button].i) - break; - /* We expected that `break' to happen, in all circumstances. */ - assert(button < ctrl->radio.nbuttons); - dlg_radiobutton_set(ctrl, dlg, button); + int val = conf_get_int(conf, ctrl->radio.context.i); + for (button = 0; button < ctrl->radio.nbuttons; button++) + if (val == ctrl->radio.buttondata[button].i) + break; + /* We expected that `break' to happen, in all circumstances. */ + assert(button < ctrl->radio.nbuttons); + dlg_radiobutton_set(ctrl, dlg, button); } else if (event == EVENT_VALCHANGE) { - button = dlg_radiobutton_get(ctrl, dlg); - assert(button >= 0 && button < ctrl->radio.nbuttons); - conf_set_int(conf, ctrl->radio.context.i, - ctrl->radio.buttondata[button].i); + button = dlg_radiobutton_get(ctrl, dlg); + assert(button >= 0 && button < ctrl->radio.nbuttons); + conf_set_int(conf, ctrl->radio.context.i, + ctrl->radio.buttondata[button].i); } } @@ -55,24 +55,24 @@ void conf_radiobutton_bool_handler(union control *ctrl, dlgparam *dlg, * config option. */ if (event == EVENT_REFRESH) { - int val = conf_get_bool(conf, ctrl->radio.context.i); - for (button = 0; button < ctrl->radio.nbuttons; button++) - if (val == ctrl->radio.buttondata[button].i) - break; - /* We expected that `break' to happen, in all circumstances. */ - assert(button < ctrl->radio.nbuttons); - dlg_radiobutton_set(ctrl, dlg, button); + int val = conf_get_bool(conf, ctrl->radio.context.i); + for (button = 0; button < ctrl->radio.nbuttons; button++) + if (val == ctrl->radio.buttondata[button].i) + break; + /* We expected that `break' to happen, in all circumstances. */ + assert(button < ctrl->radio.nbuttons); + dlg_radiobutton_set(ctrl, dlg, button); } else if (event == EVENT_VALCHANGE) { - button = dlg_radiobutton_get(ctrl, dlg); - assert(button >= 0 && button < ctrl->radio.nbuttons); - conf_set_bool(conf, ctrl->radio.context.i, + button = dlg_radiobutton_get(ctrl, dlg); + assert(button >= 0 && button < ctrl->radio.nbuttons); + conf_set_bool(conf, ctrl->radio.context.i, ctrl->radio.buttondata[button].i); } } #define CHECKBOX_INVERT (1<<30) void conf_checkbox_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int key; bool invert; @@ -84,10 +84,10 @@ void conf_checkbox_handler(union control *ctrl, dlgparam *dlg, */ key = ctrl->checkbox.context.i; if (key & CHECKBOX_INVERT) { - key &= ~CHECKBOX_INVERT; - invert = true; + key &= ~CHECKBOX_INVERT; + invert = true; } else - invert = false; + invert = false; /* * C lacks a logical XOR, so the following code uses the idiom @@ -96,15 +96,15 @@ void conf_checkbox_handler(union control *ctrl, dlgparam *dlg, */ if (event == EVENT_REFRESH) { - bool val = conf_get_bool(conf, key); - dlg_checkbox_set(ctrl, dlg, (!val ^ !invert)); + bool val = conf_get_bool(conf, key); + dlg_checkbox_set(ctrl, dlg, (!val ^ !invert)); } else if (event == EVENT_VALCHANGE) { - conf_set_bool(conf, key, !dlg_checkbox_get(ctrl,dlg) ^ !invert); + conf_set_bool(conf, key, !dlg_checkbox_get(ctrl,dlg) ^ !invert); } } void conf_editbox_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { /* * The standard edit-box handler expects the main `context' @@ -124,68 +124,68 @@ void conf_editbox_handler(union control *ctrl, dlgparam *dlg, Conf *conf = (Conf *)data; if (length > 0) { - if (event == EVENT_REFRESH) { - char *field = conf_get_str(conf, key); - dlg_editbox_set(ctrl, dlg, field); - } else if (event == EVENT_VALCHANGE) { - char *field = dlg_editbox_get(ctrl, dlg); - conf_set_str(conf, key, field); - sfree(field); - } + if (event == EVENT_REFRESH) { + char *field = conf_get_str(conf, key); + dlg_editbox_set(ctrl, dlg, field); + } else if (event == EVENT_VALCHANGE) { + char *field = dlg_editbox_get(ctrl, dlg); + conf_set_str(conf, key, field); + sfree(field); + } } else if (length < 0) { - if (event == EVENT_REFRESH) { - char str[80]; - int value = conf_get_int(conf, key); - if (length == -1) - sprintf(str, "%d", value); - else - sprintf(str, "%g", (double)value / (double)(-length)); - dlg_editbox_set(ctrl, dlg, str); - } else if (event == EVENT_VALCHANGE) { - char *str = dlg_editbox_get(ctrl, dlg); - if (length == -1) - conf_set_int(conf, key, atoi(str)); - else - conf_set_int(conf, key, (int)((-length) * atof(str))); - sfree(str); - } + if (event == EVENT_REFRESH) { + char str[80]; + int value = conf_get_int(conf, key); + if (length == -1) + sprintf(str, "%d", value); + else + sprintf(str, "%g", (double)value / (double)(-length)); + dlg_editbox_set(ctrl, dlg, str); + } else if (event == EVENT_VALCHANGE) { + char *str = dlg_editbox_get(ctrl, dlg); + if (length == -1) + conf_set_int(conf, key, atoi(str)); + else + conf_set_int(conf, key, (int)((-length) * atof(str))); + sfree(str); + } } } void conf_filesel_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int key = ctrl->fileselect.context.i; Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - dlg_filesel_set( + dlg_filesel_set( ctrl, dlg, conf_get_filename(conf, key)); } else if (event == EVENT_VALCHANGE) { - Filename *filename = dlg_filesel_get(ctrl, dlg); - conf_set_filename(conf, key, filename); + Filename *filename = dlg_filesel_get(ctrl, dlg); + conf_set_filename(conf, key, filename); filename_free(filename); } } void conf_fontsel_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int key = ctrl->fontselect.context.i; Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - dlg_fontsel_set( + dlg_fontsel_set( ctrl, dlg, conf_get_fontspec(conf, key)); } else if (event == EVENT_VALCHANGE) { - FontSpec *fontspec = dlg_fontsel_get(ctrl, dlg); - conf_set_fontspec(conf, key, fontspec); + FontSpec *fontspec = dlg_fontsel_get(ctrl, dlg); + conf_set_fontspec(conf, key, fontspec); fontspec_free(fontspec); } } static void config_host_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; @@ -195,29 +195,29 @@ static void config_host_handler(union control *ctrl, dlgparam *dlg, * different places depending on the protocol. */ if (event == EVENT_REFRESH) { - if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) { - /* - * This label text is carefully chosen to contain an n, - * since that's the shortcut for the host name control. - */ - dlg_label_change(ctrl, dlg, "Serial line"); - dlg_editbox_set(ctrl, dlg, conf_get_str(conf, CONF_serline)); - } else { - dlg_label_change(ctrl, dlg, HOST_BOX_TITLE); - dlg_editbox_set(ctrl, dlg, conf_get_str(conf, CONF_host)); - } + if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) { + /* + * This label text is carefully chosen to contain an n, + * since that's the shortcut for the host name control. + */ + dlg_label_change(ctrl, dlg, "Serial line"); + dlg_editbox_set(ctrl, dlg, conf_get_str(conf, CONF_serline)); + } else { + dlg_label_change(ctrl, dlg, HOST_BOX_TITLE); + dlg_editbox_set(ctrl, dlg, conf_get_str(conf, CONF_host)); + } } else if (event == EVENT_VALCHANGE) { - char *s = dlg_editbox_get(ctrl, dlg); - if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) - conf_set_str(conf, CONF_serline, s); - else - conf_set_str(conf, CONF_host, s); - sfree(s); + char *s = dlg_editbox_get(ctrl, dlg); + if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) + conf_set_str(conf, CONF_serline, s); + else + conf_set_str(conf, CONF_host, s); + sfree(s); } } static void config_port_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; char buf[80]; @@ -228,31 +228,31 @@ static void config_port_handler(union control *ctrl, dlgparam *dlg, * different places depending on the protocol. */ if (event == EVENT_REFRESH) { - if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) { - /* - * This label text is carefully chosen to contain a p, - * since that's the shortcut for the port control. - */ - dlg_label_change(ctrl, dlg, "Speed"); - sprintf(buf, "%d", conf_get_int(conf, CONF_serspeed)); - } else { - dlg_label_change(ctrl, dlg, PORT_BOX_TITLE); - if (conf_get_int(conf, CONF_port) != 0) - sprintf(buf, "%d", conf_get_int(conf, CONF_port)); - else - /* Display an (invalid) port of 0 as blank */ - buf[0] = '\0'; - } - dlg_editbox_set(ctrl, dlg, buf); + if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) { + /* + * This label text is carefully chosen to contain a p, + * since that's the shortcut for the port control. + */ + dlg_label_change(ctrl, dlg, "Speed"); + sprintf(buf, "%d", conf_get_int(conf, CONF_serspeed)); + } else { + dlg_label_change(ctrl, dlg, PORT_BOX_TITLE); + if (conf_get_int(conf, CONF_port) != 0) + sprintf(buf, "%d", conf_get_int(conf, CONF_port)); + else + /* Display an (invalid) port of 0 as blank */ + buf[0] = '\0'; + } + dlg_editbox_set(ctrl, dlg, buf); } else if (event == EVENT_VALCHANGE) { - char *s = dlg_editbox_get(ctrl, dlg); - int i = atoi(s); - sfree(s); + char *s = dlg_editbox_get(ctrl, dlg); + int i = atoi(s); + sfree(s); - if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) - conf_set_int(conf, CONF_serspeed, i); - else - conf_set_int(conf, CONF_port, i); + if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) + conf_set_int(conf, CONF_serspeed, i); + else + conf_set_int(conf, CONF_port, i); } } @@ -266,7 +266,7 @@ struct hostport { * buttons in order to add to them. */ void config_protocolbuttons_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int button; Conf *conf = (Conf *)data; @@ -280,47 +280,47 @@ void config_protocolbuttons_handler(union control *ctrl, dlgparam *dlg, * structure giving the `union control's for both. */ if (event == EVENT_REFRESH) { - int protocol = conf_get_int(conf, CONF_protocol); - for (button = 0; button < ctrl->radio.nbuttons; button++) - if (protocol == ctrl->radio.buttondata[button].i) - break; - /* We expected that `break' to happen, in all circumstances. */ - assert(button < ctrl->radio.nbuttons); - dlg_radiobutton_set(ctrl, dlg, button); + int protocol = conf_get_int(conf, CONF_protocol); + for (button = 0; button < ctrl->radio.nbuttons; button++) + if (protocol == ctrl->radio.buttondata[button].i) + break; + /* We expected that `break' to happen, in all circumstances. */ + assert(button < ctrl->radio.nbuttons); + dlg_radiobutton_set(ctrl, dlg, button); } else if (event == EVENT_VALCHANGE) { - int oldproto = conf_get_int(conf, CONF_protocol); - int newproto, port; + int oldproto = conf_get_int(conf, CONF_protocol); + int newproto, port; - button = dlg_radiobutton_get(ctrl, dlg); - assert(button >= 0 && button < ctrl->radio.nbuttons); - newproto = ctrl->radio.buttondata[button].i; - conf_set_int(conf, CONF_protocol, newproto); + button = dlg_radiobutton_get(ctrl, dlg); + assert(button >= 0 && button < ctrl->radio.nbuttons); + newproto = ctrl->radio.buttondata[button].i; + conf_set_int(conf, CONF_protocol, newproto); - if (oldproto != newproto) { + if (oldproto != newproto) { const struct BackendVtable *ovt = backend_vt_from_proto(oldproto); const struct BackendVtable *nvt = backend_vt_from_proto(newproto); assert(ovt); assert(nvt); - /* Iff the user hasn't changed the port from the old protocol's - * default, update it with the new protocol's default. - * (This includes a "default" of 0, implying that there is no - * sensible default for that protocol; in this case it's - * displayed as a blank.) - * This helps with the common case of tabbing through the - * controls in order and setting a non-default port before - * getting to the protocol; we want that non-default port - * to be preserved. */ - port = conf_get_int(conf, CONF_port); + /* Iff the user hasn't changed the port from the old protocol's + * default, update it with the new protocol's default. + * (This includes a "default" of 0, implying that there is no + * sensible default for that protocol; in this case it's + * displayed as a blank.) + * This helps with the common case of tabbing through the + * controls in order and setting a non-default port before + * getting to the protocol; we want that non-default port + * to be preserved. */ + port = conf_get_int(conf, CONF_port); if (port == ovt->default_port) conf_set_int(conf, CONF_port, nvt->default_port); - } - dlg_refresh(hp->host, dlg); - dlg_refresh(hp->port, dlg); + } + dlg_refresh(hp->host, dlg); + dlg_refresh(hp->port, dlg); } } static void loggingbuttons_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int button; Conf *conf = (Conf *)data; @@ -329,18 +329,18 @@ static void loggingbuttons_handler(union control *ctrl, dlgparam *dlg, * configured logging type isn't applicable. */ if (event == EVENT_REFRESH) { - int logtype = conf_get_int(conf, CONF_logtype); + int logtype = conf_get_int(conf, CONF_logtype); for (button = 0; button < ctrl->radio.nbuttons; button++) if (logtype == ctrl->radio.buttondata[button].i) - break; + break; - /* We fell off the end, so we lack the configured logging type */ - if (button == ctrl->radio.nbuttons) { - button = 0; - conf_set_int(conf, CONF_logtype, LGTYP_NONE); - } - dlg_radiobutton_set(ctrl, dlg, button); + /* We fell off the end, so we lack the configured logging type */ + if (button == ctrl->radio.nbuttons) { + button = 0; + conf_set_int(conf, CONF_logtype, LGTYP_NONE); + } + dlg_radiobutton_set(ctrl, dlg, button); } else if (event == EVENT_VALCHANGE) { button = dlg_radiobutton_get(ctrl, dlg); assert(button >= 0 && button < ctrl->radio.nbuttons); @@ -349,7 +349,7 @@ static void loggingbuttons_handler(union control *ctrl, dlgparam *dlg, } static void numeric_keypad_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { int button; Conf *conf = (Conf *)data; @@ -358,141 +358,141 @@ static void numeric_keypad_handler(union control *ctrl, dlgparam *dlg, * handler, but it has to handle two fields in Conf. */ if (event == EVENT_REFRESH) { - if (conf_get_bool(conf, CONF_nethack_keypad)) - button = 2; - else if (conf_get_bool(conf, CONF_app_keypad)) - button = 1; - else - button = 0; - assert(button < ctrl->radio.nbuttons); - dlg_radiobutton_set(ctrl, dlg, button); + if (conf_get_bool(conf, CONF_nethack_keypad)) + button = 2; + else if (conf_get_bool(conf, CONF_app_keypad)) + button = 1; + else + button = 0; + assert(button < ctrl->radio.nbuttons); + dlg_radiobutton_set(ctrl, dlg, button); } else if (event == EVENT_VALCHANGE) { - button = dlg_radiobutton_get(ctrl, dlg); - assert(button >= 0 && button < ctrl->radio.nbuttons); - if (button == 2) { - conf_set_bool(conf, CONF_app_keypad, false); - conf_set_bool(conf, CONF_nethack_keypad, true); - } else { - conf_set_bool(conf, CONF_app_keypad, (button != 0)); - conf_set_bool(conf, CONF_nethack_keypad, false); - } + button = dlg_radiobutton_get(ctrl, dlg); + assert(button >= 0 && button < ctrl->radio.nbuttons); + if (button == 2) { + conf_set_bool(conf, CONF_app_keypad, false); + conf_set_bool(conf, CONF_nethack_keypad, true); + } else { + conf_set_bool(conf, CONF_app_keypad, (button != 0)); + conf_set_bool(conf, CONF_nethack_keypad, false); + } } } static void cipherlist_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - int i; + int i; - static const struct { const char *s; int c; } ciphers[] = { + static const struct { const char *s; int c; } ciphers[] = { { "ChaCha20 (SSH-2 only)", CIPHER_CHACHA20 }, - { "3DES", CIPHER_3DES }, - { "Blowfish", CIPHER_BLOWFISH }, - { "DES", CIPHER_DES }, - { "AES (SSH-2 only)", CIPHER_AES }, - { "Arcfour (SSH-2 only)", CIPHER_ARCFOUR }, - { "-- warn below here --", CIPHER_WARN } - }; + { "3DES", CIPHER_3DES }, + { "Blowfish", CIPHER_BLOWFISH }, + { "DES", CIPHER_DES }, + { "AES (SSH-2 only)", CIPHER_AES }, + { "Arcfour (SSH-2 only)", CIPHER_ARCFOUR }, + { "-- warn below here --", CIPHER_WARN } + }; - /* Set up the "selected ciphers" box. */ - /* (cipherlist assumed to contain all ciphers) */ - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < CIPHER_MAX; i++) { - int c = conf_get_int_int(conf, CONF_ssh_cipherlist, i); - int j; - const char *cstr = NULL; - for (j = 0; j < (sizeof ciphers) / (sizeof ciphers[0]); j++) { - if (ciphers[j].c == c) { - cstr = ciphers[j].s; - break; - } - } - dlg_listbox_addwithid(ctrl, dlg, cstr, c); - } - dlg_update_done(ctrl, dlg); + /* Set up the "selected ciphers" box. */ + /* (cipherlist assumed to contain all ciphers) */ + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < CIPHER_MAX; i++) { + int c = conf_get_int_int(conf, CONF_ssh_cipherlist, i); + int j; + const char *cstr = NULL; + for (j = 0; j < (sizeof ciphers) / (sizeof ciphers[0]); j++) { + if (ciphers[j].c == c) { + cstr = ciphers[j].s; + break; + } + } + dlg_listbox_addwithid(ctrl, dlg, cstr, c); + } + dlg_update_done(ctrl, dlg); } else if (event == EVENT_VALCHANGE) { - int i; + int i; - /* Update array to match the list box. */ - for (i=0; i < CIPHER_MAX; i++) - conf_set_int_int(conf, CONF_ssh_cipherlist, i, - dlg_listbox_getid(ctrl, dlg, i)); + /* Update array to match the list box. */ + for (i=0; i < CIPHER_MAX; i++) + conf_set_int_int(conf, CONF_ssh_cipherlist, i, + dlg_listbox_getid(ctrl, dlg, i)); } } #ifndef NO_GSSAPI static void gsslist_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - int i; + int i; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < ngsslibs; i++) { - int id = conf_get_int_int(conf, CONF_ssh_gsslist, i); - assert(id >= 0 && id < ngsslibs); - dlg_listbox_addwithid(ctrl, dlg, gsslibnames[id], id); - } - dlg_update_done(ctrl, dlg); + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < ngsslibs; i++) { + int id = conf_get_int_int(conf, CONF_ssh_gsslist, i); + assert(id >= 0 && id < ngsslibs); + dlg_listbox_addwithid(ctrl, dlg, gsslibnames[id], id); + } + dlg_update_done(ctrl, dlg); } else if (event == EVENT_VALCHANGE) { - int i; + int i; - /* Update array to match the list box. */ - for (i=0; i < ngsslibs; i++) - conf_set_int_int(conf, CONF_ssh_gsslist, i, - dlg_listbox_getid(ctrl, dlg, i)); + /* Update array to match the list box. */ + for (i=0; i < ngsslibs; i++) + conf_set_int_int(conf, CONF_ssh_gsslist, i, + dlg_listbox_getid(ctrl, dlg, i)); } } #endif static void kexlist_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - int i; + int i; - static const struct { const char *s; int k; } kexes[] = { - { "Diffie-Hellman group 1", KEX_DHGROUP1 }, - { "Diffie-Hellman group 14", KEX_DHGROUP14 }, - { "Diffie-Hellman group exchange", KEX_DHGEX }, - { "RSA-based key exchange", KEX_RSA }, + static const struct { const char *s; int k; } kexes[] = { + { "Diffie-Hellman group 1", KEX_DHGROUP1 }, + { "Diffie-Hellman group 14", KEX_DHGROUP14 }, + { "Diffie-Hellman group exchange", KEX_DHGEX }, + { "RSA-based key exchange", KEX_RSA }, { "ECDH key exchange", KEX_ECDH }, - { "-- warn below here --", KEX_WARN } - }; + { "-- warn below here --", KEX_WARN } + }; - /* Set up the "kex preference" box. */ - /* (kexlist assumed to contain all algorithms) */ - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); + /* Set up the "kex preference" box. */ + /* (kexlist assumed to contain all algorithms) */ + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); for (i = 0; i < KEX_MAX; i++) { - int k = conf_get_int_int(conf, CONF_ssh_kexlist, i); - int j; - const char *kstr = NULL; - for (j = 0; j < (sizeof kexes) / (sizeof kexes[0]); j++) { - if (kexes[j].k == k) { - kstr = kexes[j].s; - break; - } - } - dlg_listbox_addwithid(ctrl, dlg, kstr, k); - } - dlg_update_done(ctrl, dlg); + int k = conf_get_int_int(conf, CONF_ssh_kexlist, i); + int j; + const char *kstr = NULL; + for (j = 0; j < (sizeof kexes) / (sizeof kexes[0]); j++) { + if (kexes[j].k == k) { + kstr = kexes[j].s; + break; + } + } + dlg_listbox_addwithid(ctrl, dlg, kstr, k); + } + dlg_update_done(ctrl, dlg); } else if (event == EVENT_VALCHANGE) { - int i; + int i; - /* Update array to match the list box. */ + /* Update array to match the list box. */ for (i=0; i < KEX_MAX; i++) - conf_set_int_int(conf, CONF_ssh_kexlist, i, - dlg_listbox_getid(ctrl, dlg, i)); + conf_set_int_int(conf, CONF_ssh_kexlist, i, + dlg_listbox_getid(ctrl, dlg, i)); } } @@ -540,67 +540,67 @@ static void hklist_handler(union control *ctrl, dlgparam *dlg, } static void printerbox_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - int nprinters, i; - printer_enum *pe; - const char *printer; + int nprinters, i; + printer_enum *pe; + const char *printer; - dlg_update_start(ctrl, dlg); - /* - * Some backends may wish to disable the drop-down list on - * this edit box. Be prepared for this. - */ - if (ctrl->editbox.has_list) { - dlg_listbox_clear(ctrl, dlg); - dlg_listbox_add(ctrl, dlg, PRINTER_DISABLED_STRING); - pe = printer_start_enum(&nprinters); - for (i = 0; i < nprinters; i++) - dlg_listbox_add(ctrl, dlg, printer_get_name(pe, i)); - printer_finish_enum(pe); - } - printer = conf_get_str(conf, CONF_printer); - if (!printer) - printer = PRINTER_DISABLED_STRING; - dlg_editbox_set(ctrl, dlg, printer); - dlg_update_done(ctrl, dlg); + dlg_update_start(ctrl, dlg); + /* + * Some backends may wish to disable the drop-down list on + * this edit box. Be prepared for this. + */ + if (ctrl->editbox.has_list) { + dlg_listbox_clear(ctrl, dlg); + dlg_listbox_add(ctrl, dlg, PRINTER_DISABLED_STRING); + pe = printer_start_enum(&nprinters); + for (i = 0; i < nprinters; i++) + dlg_listbox_add(ctrl, dlg, printer_get_name(pe, i)); + printer_finish_enum(pe); + } + printer = conf_get_str(conf, CONF_printer); + if (!printer) + printer = PRINTER_DISABLED_STRING; + dlg_editbox_set(ctrl, dlg, printer); + dlg_update_done(ctrl, dlg); } else if (event == EVENT_VALCHANGE) { - char *printer = dlg_editbox_get(ctrl, dlg); - if (!strcmp(printer, PRINTER_DISABLED_STRING)) - printer[0] = '\0'; - conf_set_str(conf, CONF_printer, printer); - sfree(printer); + char *printer = dlg_editbox_get(ctrl, dlg); + if (!strcmp(printer, PRINTER_DISABLED_STRING)) + printer[0] = '\0'; + conf_set_str(conf, CONF_printer, printer); + sfree(printer); } } static void codepage_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - int i; - const char *cp, *thiscp; - dlg_update_start(ctrl, dlg); - thiscp = cp_name(decode_codepage(conf_get_str(conf, - CONF_line_codepage))); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; (cp = cp_enumerate(i)) != NULL; i++) - dlg_listbox_add(ctrl, dlg, cp); - dlg_editbox_set(ctrl, dlg, thiscp); - conf_set_str(conf, CONF_line_codepage, thiscp); - dlg_update_done(ctrl, dlg); + int i; + const char *cp, *thiscp; + dlg_update_start(ctrl, dlg); + thiscp = cp_name(decode_codepage(conf_get_str(conf, + CONF_line_codepage))); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; (cp = cp_enumerate(i)) != NULL; i++) + dlg_listbox_add(ctrl, dlg, cp); + dlg_editbox_set(ctrl, dlg, thiscp); + conf_set_str(conf, CONF_line_codepage, thiscp); + dlg_update_done(ctrl, dlg); } else if (event == EVENT_VALCHANGE) { - char *codepage = dlg_editbox_get(ctrl, dlg); - conf_set_str(conf, CONF_line_codepage, - cp_name(decode_codepage(codepage))); - sfree(codepage); + char *codepage = dlg_editbox_get(ctrl, dlg); + conf_set_str(conf, CONF_line_codepage, + cp_name(decode_codepage(codepage))); + sfree(codepage); } } static void sshbug_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { @@ -611,24 +611,24 @@ static void sshbug_handler(union control *ctrl, dlgparam *dlg, * the value we wanted to keep. */ int oldconf = conf_get_int(conf, ctrl->listbox.context.i); - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - dlg_listbox_addwithid(ctrl, dlg, "Auto", AUTO); - dlg_listbox_addwithid(ctrl, dlg, "Off", FORCE_OFF); - dlg_listbox_addwithid(ctrl, dlg, "On", FORCE_ON); - switch (oldconf) { - case AUTO: dlg_listbox_select(ctrl, dlg, 0); break; - case FORCE_OFF: dlg_listbox_select(ctrl, dlg, 1); break; - case FORCE_ON: dlg_listbox_select(ctrl, dlg, 2); break; - } - dlg_update_done(ctrl, dlg); + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + dlg_listbox_addwithid(ctrl, dlg, "Auto", AUTO); + dlg_listbox_addwithid(ctrl, dlg, "Off", FORCE_OFF); + dlg_listbox_addwithid(ctrl, dlg, "On", FORCE_ON); + switch (oldconf) { + case AUTO: dlg_listbox_select(ctrl, dlg, 0); break; + case FORCE_OFF: dlg_listbox_select(ctrl, dlg, 1); break; + case FORCE_ON: dlg_listbox_select(ctrl, dlg, 2); break; + } + dlg_update_done(ctrl, dlg); } else if (event == EVENT_SELCHANGE) { - int i = dlg_listbox_index(ctrl, dlg); - if (i < 0) - i = AUTO; - else - i = dlg_listbox_getid(ctrl, dlg, i); - conf_set_int(conf, ctrl->listbox.context.i, i); + int i = dlg_listbox_index(ctrl, dlg); + if (i < 0) + i = AUTO; + else + i = dlg_listbox_getid(ctrl, dlg, i); + conf_set_int(conf, ctrl->listbox.context.i, i); } } @@ -648,7 +648,7 @@ static void sessionsaver_data_free(void *ssdv) sfree(ssd); } -/* +/* * Helper function to load the session selected in the list box, if * any, as this is done in more than one place below. Returns 0 for * failure. @@ -660,8 +660,8 @@ static bool load_selected_session( int i = dlg_listbox_index(ssd->listbox, dlg); bool isdef; if (i < 0) { - dlg_beep(dlg); - return false; + dlg_beep(dlg); + return false; } isdef = !strcmp(ssd->sesslist.sessions[i], "Default Settings"); load_settings(ssd->sesslist.sessions[i], conf); @@ -677,73 +677,73 @@ static bool load_selected_session( } static void sessionsaver_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct sessionsaver_data *ssd = - (struct sessionsaver_data *)ctrl->generic.context.p; + (struct sessionsaver_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == ssd->editbox) { - dlg_editbox_set(ctrl, dlg, ssd->savedsession); - } else if (ctrl == ssd->listbox) { - int i; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < ssd->sesslist.nsessions; i++) - dlg_listbox_add(ctrl, dlg, ssd->sesslist.sessions[i]); - dlg_update_done(ctrl, dlg); - } + if (ctrl == ssd->editbox) { + dlg_editbox_set(ctrl, dlg, ssd->savedsession); + } else if (ctrl == ssd->listbox) { + int i; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < ssd->sesslist.nsessions; i++) + dlg_listbox_add(ctrl, dlg, ssd->sesslist.sessions[i]); + dlg_update_done(ctrl, dlg); + } } else if (event == EVENT_VALCHANGE) { int top, bottom, halfway, i; - if (ctrl == ssd->editbox) { + if (ctrl == ssd->editbox) { sfree(ssd->savedsession); ssd->savedsession = dlg_editbox_get(ctrl, dlg); - top = ssd->sesslist.nsessions; - bottom = -1; - while (top-bottom > 1) { - halfway = (top+bottom)/2; - i = strcmp(ssd->savedsession, ssd->sesslist.sessions[halfway]); - if (i <= 0 ) { - top = halfway; - } else { - bottom = halfway; - } - } - if (top == ssd->sesslist.nsessions) { - top -= 1; - } - dlg_listbox_select(ssd->listbox, dlg, top); - } + top = ssd->sesslist.nsessions; + bottom = -1; + while (top-bottom > 1) { + halfway = (top+bottom)/2; + i = strcmp(ssd->savedsession, ssd->sesslist.sessions[halfway]); + if (i <= 0 ) { + top = halfway; + } else { + bottom = halfway; + } + } + if (top == ssd->sesslist.nsessions) { + top -= 1; + } + dlg_listbox_select(ssd->listbox, dlg, top); + } } else if (event == EVENT_ACTION) { - bool mbl = false; - if (!ssd->midsession && - (ctrl == ssd->listbox || - (ssd->loadbutton && ctrl == ssd->loadbutton))) { - /* - * The user has double-clicked a session, or hit Load. - * We must load the selected session, and then - * terminate the configuration dialog _if_ there was a - * double-click on the list box _and_ that session - * contains a hostname. - */ - if (load_selected_session(ssd, dlg, conf, &mbl) && - (mbl && ctrl == ssd->listbox && conf_launchable(conf))) { - dlg_end(dlg, 1); /* it's all over, and succeeded */ - } - } else if (ctrl == ssd->savebutton) { - bool isdef = !strcmp(ssd->savedsession, "Default Settings"); - if (!ssd->savedsession[0]) { - int i = dlg_listbox_index(ssd->listbox, dlg); - if (i < 0) { - dlg_beep(dlg); - return; - } - isdef = !strcmp(ssd->sesslist.sessions[i], "Default Settings"); + bool mbl = false; + if (!ssd->midsession && + (ctrl == ssd->listbox || + (ssd->loadbutton && ctrl == ssd->loadbutton))) { + /* + * The user has double-clicked a session, or hit Load. + * We must load the selected session, and then + * terminate the configuration dialog _if_ there was a + * double-click on the list box _and_ that session + * contains a hostname. + */ + if (load_selected_session(ssd, dlg, conf, &mbl) && + (mbl && ctrl == ssd->listbox && conf_launchable(conf))) { + dlg_end(dlg, 1); /* it's all over, and succeeded */ + } + } else if (ctrl == ssd->savebutton) { + bool isdef = !strcmp(ssd->savedsession, "Default Settings"); + if (!ssd->savedsession[0]) { + int i = dlg_listbox_index(ssd->listbox, dlg); + if (i < 0) { + dlg_beep(dlg); + return; + } + isdef = !strcmp(ssd->sesslist.sessions[i], "Default Settings"); sfree(ssd->savedsession); ssd->savedsession = dupstr(isdef ? "" : ssd->sesslist.sessions[i]); - } + } { char *errmsg = save_settings(ssd->savedsession, conf); if (errmsg) { @@ -751,65 +751,65 @@ static void sessionsaver_handler(union control *ctrl, dlgparam *dlg, sfree(errmsg); } } - get_sesslist(&ssd->sesslist, false); - get_sesslist(&ssd->sesslist, true); - dlg_refresh(ssd->editbox, dlg); - dlg_refresh(ssd->listbox, dlg); - } else if (!ssd->midsession && - ssd->delbutton && ctrl == ssd->delbutton) { - int i = dlg_listbox_index(ssd->listbox, dlg); - if (i <= 0) { - dlg_beep(dlg); - } else { - del_settings(ssd->sesslist.sessions[i]); - get_sesslist(&ssd->sesslist, false); - get_sesslist(&ssd->sesslist, true); - dlg_refresh(ssd->listbox, dlg); - } - } else if (ctrl == ssd->okbutton) { + get_sesslist(&ssd->sesslist, false); + get_sesslist(&ssd->sesslist, true); + dlg_refresh(ssd->editbox, dlg); + dlg_refresh(ssd->listbox, dlg); + } else if (!ssd->midsession && + ssd->delbutton && ctrl == ssd->delbutton) { + int i = dlg_listbox_index(ssd->listbox, dlg); + if (i <= 0) { + dlg_beep(dlg); + } else { + del_settings(ssd->sesslist.sessions[i]); + get_sesslist(&ssd->sesslist, false); + get_sesslist(&ssd->sesslist, true); + dlg_refresh(ssd->listbox, dlg); + } + } else if (ctrl == ssd->okbutton) { if (ssd->midsession) { /* In a mid-session Change Settings, Apply is always OK. */ - dlg_end(dlg, 1); + dlg_end(dlg, 1); return; } - /* - * Annoying special case. If the `Open' button is - * pressed while no host name is currently set, _and_ - * the session list previously had the focus, _and_ - * there was a session selected in that which had a - * valid host name in it, then load it and go. - */ - if (dlg_last_focused(ctrl, dlg) == ssd->listbox && - !conf_launchable(conf) && dlg_is_visible(ssd->listbox, dlg)) { - Conf *conf2 = conf_new(); - bool mbl = false; - if (!load_selected_session(ssd, dlg, conf2, &mbl)) { - dlg_beep(dlg); - conf_free(conf2); - return; - } - /* If at this point we have a valid session, go! */ - if (mbl && conf_launchable(conf2)) { - conf_copy_into(conf, conf2); - dlg_end(dlg, 1); - } else - dlg_beep(dlg); + /* + * Annoying special case. If the `Open' button is + * pressed while no host name is currently set, _and_ + * the session list previously had the focus, _and_ + * there was a session selected in that which had a + * valid host name in it, then load it and go. + */ + if (dlg_last_focused(ctrl, dlg) == ssd->listbox && + !conf_launchable(conf) && dlg_is_visible(ssd->listbox, dlg)) { + Conf *conf2 = conf_new(); + bool mbl = false; + if (!load_selected_session(ssd, dlg, conf2, &mbl)) { + dlg_beep(dlg); + conf_free(conf2); + return; + } + /* If at this point we have a valid session, go! */ + if (mbl && conf_launchable(conf2)) { + conf_copy_into(conf, conf2); + dlg_end(dlg, 1); + } else + dlg_beep(dlg); - conf_free(conf2); + conf_free(conf2); return; - } + } - /* - * Otherwise, do the normal thing: if we have a valid - * session, get going. - */ - if (conf_launchable(conf)) { - dlg_end(dlg, 1); - } else - dlg_beep(dlg); - } else if (ctrl == ssd->cancelbutton) { - dlg_end(dlg, 0); - } + /* + * Otherwise, do the normal thing: if we have a valid + * session, get going. + */ + if (conf_launchable(conf)) { + dlg_end(dlg, 1); + } else + dlg_beep(dlg); + } else if (ctrl == ssd->cancelbutton) { + dlg_end(dlg, 0); + } } } @@ -818,39 +818,39 @@ struct charclass_data { }; static void charclass_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct charclass_data *ccd = - (struct charclass_data *)ctrl->generic.context.p; + (struct charclass_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == ccd->listbox) { - int i; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < 128; i++) { - char str[100]; - sprintf(str, "%d\t(0x%02X)\t%c\t%d", i, i, - (i >= 0x21 && i != 0x7F) ? i : ' ', - conf_get_int_int(conf, CONF_wordness, i)); - dlg_listbox_add(ctrl, dlg, str); - } - dlg_update_done(ctrl, dlg); - } + if (ctrl == ccd->listbox) { + int i; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < 128; i++) { + char str[100]; + sprintf(str, "%d\t(0x%02X)\t%c\t%d", i, i, + (i >= 0x21 && i != 0x7F) ? i : ' ', + conf_get_int_int(conf, CONF_wordness, i)); + dlg_listbox_add(ctrl, dlg, str); + } + dlg_update_done(ctrl, dlg); + } } else if (event == EVENT_ACTION) { - if (ctrl == ccd->button) { - char *str; - int i, n; - str = dlg_editbox_get(ccd->editbox, dlg); - n = atoi(str); - sfree(str); - for (i = 0; i < 128; i++) { - if (dlg_listbox_issel(ccd->listbox, dlg, i)) - conf_set_int_int(conf, CONF_wordness, i, n); - } - dlg_refresh(ccd->listbox, dlg); - } + if (ctrl == ccd->button) { + char *str; + int i, n; + str = dlg_editbox_get(ccd->editbox, dlg); + n = atoi(str); + sfree(str); + for (i = 0; i < 128; i++) { + if (dlg_listbox_issel(ccd->listbox, dlg, i)) + conf_set_int_int(conf, CONF_wordness, i, n); + } + dlg_refresh(ccd->listbox, dlg); + } } } @@ -873,107 +873,107 @@ static const char *const colours[] = { }; static void colour_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct colour_data *cd = - (struct colour_data *)ctrl->generic.context.p; + (struct colour_data *)ctrl->generic.context.p; bool update = false, clear = false; int r, g, b; if (event == EVENT_REFRESH) { - if (ctrl == cd->listbox) { - int i; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < lenof(colours); i++) - dlg_listbox_add(ctrl, dlg, colours[i]); - dlg_update_done(ctrl, dlg); - clear = true; - update = true; - } + if (ctrl == cd->listbox) { + int i; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < lenof(colours); i++) + dlg_listbox_add(ctrl, dlg, colours[i]); + dlg_update_done(ctrl, dlg); + clear = true; + update = true; + } } else if (event == EVENT_SELCHANGE) { - if (ctrl == cd->listbox) { - /* The user has selected a colour. Update the RGB text. */ - int i = dlg_listbox_index(ctrl, dlg); - if (i < 0) { - clear = true; - } else { - clear = false; - r = conf_get_int_int(conf, CONF_colours, i*3+0); - g = conf_get_int_int(conf, CONF_colours, i*3+1); - b = conf_get_int_int(conf, CONF_colours, i*3+2); - } - update = true; - } + if (ctrl == cd->listbox) { + /* The user has selected a colour. Update the RGB text. */ + int i = dlg_listbox_index(ctrl, dlg); + if (i < 0) { + clear = true; + } else { + clear = false; + r = conf_get_int_int(conf, CONF_colours, i*3+0); + g = conf_get_int_int(conf, CONF_colours, i*3+1); + b = conf_get_int_int(conf, CONF_colours, i*3+2); + } + update = true; + } } else if (event == EVENT_VALCHANGE) { - if (ctrl == cd->redit || ctrl == cd->gedit || ctrl == cd->bedit) { - /* The user has changed the colour using the edit boxes. */ - char *str; - int i, cval; + if (ctrl == cd->redit || ctrl == cd->gedit || ctrl == cd->bedit) { + /* The user has changed the colour using the edit boxes. */ + char *str; + int i, cval; - str = dlg_editbox_get(ctrl, dlg); - cval = atoi(str); - sfree(str); - if (cval > 255) cval = 255; - if (cval < 0) cval = 0; + str = dlg_editbox_get(ctrl, dlg); + cval = atoi(str); + sfree(str); + if (cval > 255) cval = 255; + if (cval < 0) cval = 0; - i = dlg_listbox_index(cd->listbox, dlg); - if (i >= 0) { - if (ctrl == cd->redit) - conf_set_int_int(conf, CONF_colours, i*3+0, cval); - else if (ctrl == cd->gedit) - conf_set_int_int(conf, CONF_colours, i*3+1, cval); - else if (ctrl == cd->bedit) - conf_set_int_int(conf, CONF_colours, i*3+2, cval); - } - } + i = dlg_listbox_index(cd->listbox, dlg); + if (i >= 0) { + if (ctrl == cd->redit) + conf_set_int_int(conf, CONF_colours, i*3+0, cval); + else if (ctrl == cd->gedit) + conf_set_int_int(conf, CONF_colours, i*3+1, cval); + else if (ctrl == cd->bedit) + conf_set_int_int(conf, CONF_colours, i*3+2, cval); + } + } } else if (event == EVENT_ACTION) { - if (ctrl == cd->button) { - int i = dlg_listbox_index(cd->listbox, dlg); - if (i < 0) { - dlg_beep(dlg); - return; - } - /* - * Start a colour selector, which will send us an - * EVENT_CALLBACK when it's finished and allow us to - * pick up the results. - */ - dlg_coloursel_start(ctrl, dlg, - conf_get_int_int(conf, CONF_colours, i*3+0), - conf_get_int_int(conf, CONF_colours, i*3+1), - conf_get_int_int(conf, CONF_colours, i*3+2)); - } + if (ctrl == cd->button) { + int i = dlg_listbox_index(cd->listbox, dlg); + if (i < 0) { + dlg_beep(dlg); + return; + } + /* + * Start a colour selector, which will send us an + * EVENT_CALLBACK when it's finished and allow us to + * pick up the results. + */ + dlg_coloursel_start(ctrl, dlg, + conf_get_int_int(conf, CONF_colours, i*3+0), + conf_get_int_int(conf, CONF_colours, i*3+1), + conf_get_int_int(conf, CONF_colours, i*3+2)); + } } else if (event == EVENT_CALLBACK) { - if (ctrl == cd->button) { - int i = dlg_listbox_index(cd->listbox, dlg); - /* - * Collect the results of the colour selector. Will - * return nonzero on success, or zero if the colour - * selector did nothing (user hit Cancel, for example). - */ - if (dlg_coloursel_results(ctrl, dlg, &r, &g, &b)) { - conf_set_int_int(conf, CONF_colours, i*3+0, r); - conf_set_int_int(conf, CONF_colours, i*3+1, g); - conf_set_int_int(conf, CONF_colours, i*3+2, b); - clear = false; - update = true; - } - } + if (ctrl == cd->button) { + int i = dlg_listbox_index(cd->listbox, dlg); + /* + * Collect the results of the colour selector. Will + * return nonzero on success, or zero if the colour + * selector did nothing (user hit Cancel, for example). + */ + if (dlg_coloursel_results(ctrl, dlg, &r, &g, &b)) { + conf_set_int_int(conf, CONF_colours, i*3+0, r); + conf_set_int_int(conf, CONF_colours, i*3+1, g); + conf_set_int_int(conf, CONF_colours, i*3+2, b); + clear = false; + update = true; + } + } } if (update) { - if (clear) { - dlg_editbox_set(cd->redit, dlg, ""); - dlg_editbox_set(cd->gedit, dlg, ""); - dlg_editbox_set(cd->bedit, dlg, ""); - } else { - char buf[40]; - sprintf(buf, "%d", r); dlg_editbox_set(cd->redit, dlg, buf); - sprintf(buf, "%d", g); dlg_editbox_set(cd->gedit, dlg, buf); - sprintf(buf, "%d", b); dlg_editbox_set(cd->bedit, dlg, buf); - } + if (clear) { + dlg_editbox_set(cd->redit, dlg, ""); + dlg_editbox_set(cd->gedit, dlg, ""); + dlg_editbox_set(cd->bedit, dlg, ""); + } else { + char buf[40]; + sprintf(buf, "%d", r); dlg_editbox_set(cd->redit, dlg, buf); + sprintf(buf, "%d", g); dlg_editbox_set(cd->gedit, dlg, buf); + sprintf(buf, "%d", b); dlg_editbox_set(cd->bedit, dlg, buf); + } } } @@ -982,83 +982,83 @@ struct ttymodes_data { }; static void ttymodes_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct ttymodes_data *td = - (struct ttymodes_data *)ctrl->generic.context.p; + (struct ttymodes_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == td->listbox) { - char *key, *val; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (val = conf_get_str_strs(conf, CONF_ttymodes, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, CONF_ttymodes, key, &key)) { - char *disp = dupprintf("%s\t%s", key, - (val[0] == 'A') ? "(auto)" : - ((val[0] == 'N') ? "(don't send)" - : val+1)); - dlg_listbox_add(ctrl, dlg, disp); - sfree(disp); - } - dlg_update_done(ctrl, dlg); - } else if (ctrl == td->valradio) { - dlg_radiobutton_set(ctrl, dlg, 0); - } + if (ctrl == td->listbox) { + char *key, *val; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (val = conf_get_str_strs(conf, CONF_ttymodes, NULL, &key); + val != NULL; + val = conf_get_str_strs(conf, CONF_ttymodes, key, &key)) { + char *disp = dupprintf("%s\t%s", key, + (val[0] == 'A') ? "(auto)" : + ((val[0] == 'N') ? "(don't send)" + : val+1)); + dlg_listbox_add(ctrl, dlg, disp); + sfree(disp); + } + dlg_update_done(ctrl, dlg); + } else if (ctrl == td->valradio) { + dlg_radiobutton_set(ctrl, dlg, 0); + } } else if (event == EVENT_SELCHANGE) { - if (ctrl == td->listbox) { - int ind = dlg_listbox_index(td->listbox, dlg); - char *val; - if (ind < 0) { - return; /* no item selected */ - } - val = conf_get_str_str(conf, CONF_ttymodes, - conf_get_str_nthstrkey(conf, CONF_ttymodes, - ind)); - assert(val != NULL); - /* Do this first to defuse side-effects on radio buttons: */ - dlg_editbox_set(td->valbox, dlg, val+1); - dlg_radiobutton_set(td->valradio, dlg, - val[0] == 'A' ? 0 : (val[0] == 'N' ? 1 : 2)); - } + if (ctrl == td->listbox) { + int ind = dlg_listbox_index(td->listbox, dlg); + char *val; + if (ind < 0) { + return; /* no item selected */ + } + val = conf_get_str_str(conf, CONF_ttymodes, + conf_get_str_nthstrkey(conf, CONF_ttymodes, + ind)); + assert(val != NULL); + /* Do this first to defuse side-effects on radio buttons: */ + dlg_editbox_set(td->valbox, dlg, val+1); + dlg_radiobutton_set(td->valradio, dlg, + val[0] == 'A' ? 0 : (val[0] == 'N' ? 1 : 2)); + } } else if (event == EVENT_VALCHANGE) { - if (ctrl == td->valbox) { - /* If they're editing the text box, we assume they want its - * value to be used. */ - dlg_radiobutton_set(td->valradio, dlg, 2); - } + if (ctrl == td->valbox) { + /* If they're editing the text box, we assume they want its + * value to be used. */ + dlg_radiobutton_set(td->valradio, dlg, 2); + } } else if (event == EVENT_ACTION) { - if (ctrl == td->setbutton) { - int ind = dlg_listbox_index(td->listbox, dlg); - const char *key; - char *str, *val; - char type; + if (ctrl == td->setbutton) { + int ind = dlg_listbox_index(td->listbox, dlg); + const char *key; + char *str, *val; + char type; - { + { const char types[] = {'A', 'N', 'V'}; - int button = dlg_radiobutton_get(td->valradio, dlg); - assert(button >= 0 && button < lenof(types)); - type = types[button]; - } + int button = dlg_radiobutton_get(td->valradio, dlg); + assert(button >= 0 && button < lenof(types)); + type = types[button]; + } - /* Construct new entry */ - if (ind >= 0) { - key = conf_get_str_nthstrkey(conf, CONF_ttymodes, ind); - str = (type == 'V' ? dlg_editbox_get(td->valbox, dlg) - : dupstr("")); - val = dupprintf("%c%s", type, str); - sfree(str); - conf_set_str_str(conf, CONF_ttymodes, key, val); - sfree(val); - dlg_refresh(td->listbox, dlg); - dlg_listbox_select(td->listbox, dlg, ind); - } else { - /* Not a multisel listbox, so this means nothing selected */ - dlg_beep(dlg); - } - } + /* Construct new entry */ + if (ind >= 0) { + key = conf_get_str_nthstrkey(conf, CONF_ttymodes, ind); + str = (type == 'V' ? dlg_editbox_get(td->valbox, dlg) + : dupstr("")); + val = dupprintf("%c%s", type, str); + sfree(str); + conf_set_str_str(conf, CONF_ttymodes, key, val); + sfree(val); + dlg_refresh(td->listbox, dlg); + dlg_listbox_select(td->listbox, dlg, ind); + } else { + /* Not a multisel listbox, so this means nothing selected */ + dlg_beep(dlg); + } + } } } @@ -1067,70 +1067,70 @@ struct environ_data { }; static void environ_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct environ_data *ed = - (struct environ_data *)ctrl->generic.context.p; + (struct environ_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == ed->listbox) { - char *key, *val; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, CONF_environmt, key, &key)) { - char *p = dupprintf("%s\t%s", key, val); - dlg_listbox_add(ctrl, dlg, p); - sfree(p); - } - dlg_update_done(ctrl, dlg); - } + if (ctrl == ed->listbox) { + char *key, *val; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key); + val != NULL; + val = conf_get_str_strs(conf, CONF_environmt, key, &key)) { + char *p = dupprintf("%s\t%s", key, val); + dlg_listbox_add(ctrl, dlg, p); + sfree(p); + } + dlg_update_done(ctrl, dlg); + } } else if (event == EVENT_ACTION) { - if (ctrl == ed->addbutton) { - char *key, *val, *str; - key = dlg_editbox_get(ed->varbox, dlg); - if (!*key) { - sfree(key); - dlg_beep(dlg); - return; - } - val = dlg_editbox_get(ed->valbox, dlg); - if (!*val) { - sfree(key); - sfree(val); - dlg_beep(dlg); - return; - } - conf_set_str_str(conf, CONF_environmt, key, val); - str = dupcat(key, "\t", val, NULL); - dlg_editbox_set(ed->varbox, dlg, ""); - dlg_editbox_set(ed->valbox, dlg, ""); - sfree(str); - sfree(key); - sfree(val); - dlg_refresh(ed->listbox, dlg); - } else if (ctrl == ed->rembutton) { - int i = dlg_listbox_index(ed->listbox, dlg); - if (i < 0) { - dlg_beep(dlg); - } else { - char *key, *val; + if (ctrl == ed->addbutton) { + char *key, *val, *str; + key = dlg_editbox_get(ed->varbox, dlg); + if (!*key) { + sfree(key); + dlg_beep(dlg); + return; + } + val = dlg_editbox_get(ed->valbox, dlg); + if (!*val) { + sfree(key); + sfree(val); + dlg_beep(dlg); + return; + } + conf_set_str_str(conf, CONF_environmt, key, val); + str = dupcat(key, "\t", val, NULL); + dlg_editbox_set(ed->varbox, dlg, ""); + dlg_editbox_set(ed->valbox, dlg, ""); + sfree(str); + sfree(key); + sfree(val); + dlg_refresh(ed->listbox, dlg); + } else if (ctrl == ed->rembutton) { + int i = dlg_listbox_index(ed->listbox, dlg); + if (i < 0) { + dlg_beep(dlg); + } else { + char *key, *val; - key = conf_get_str_nthstrkey(conf, CONF_environmt, i); - if (key) { - /* Populate controls with the entry we're about to delete - * for ease of editing */ - val = conf_get_str_str(conf, CONF_environmt, key); - dlg_editbox_set(ed->varbox, dlg, key); - dlg_editbox_set(ed->valbox, dlg, val); - /* And delete it */ - conf_del_str_str(conf, CONF_environmt, key); - } - } - dlg_refresh(ed->listbox, dlg); - } + key = conf_get_str_nthstrkey(conf, CONF_environmt, i); + if (key) { + /* Populate controls with the entry we're about to delete + * for ease of editing */ + val = conf_get_str_str(conf, CONF_environmt, key); + dlg_editbox_set(ed->varbox, dlg, key); + dlg_editbox_set(ed->valbox, dlg, val); + /* And delete it */ + conf_del_str_str(conf, CONF_environmt, key); + } + } + dlg_refresh(ed->listbox, dlg); + } } } @@ -1143,21 +1143,21 @@ struct portfwd_data { }; static void portfwd_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { Conf *conf = (Conf *)data; struct portfwd_data *pfd = - (struct portfwd_data *)ctrl->generic.context.p; + (struct portfwd_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == pfd->listbox) { - char *key, *val; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) { - char *p; + if (ctrl == pfd->listbox) { + char *key, *val; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key); + val != NULL; + val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) { + char *p; if (!strcmp(val, "D")) { char *L; /* @@ -1176,129 +1176,129 @@ static void portfwd_handler(union control *ctrl, dlgparam *dlg, if (L) *L = 'D'; } else p = dupprintf("%s\t%s", key, val); - dlg_listbox_add(ctrl, dlg, p); - sfree(p); - } - dlg_update_done(ctrl, dlg); - } else if (ctrl == pfd->direction) { - /* - * Default is Local. - */ - dlg_radiobutton_set(ctrl, dlg, 0); + dlg_listbox_add(ctrl, dlg, p); + sfree(p); + } + dlg_update_done(ctrl, dlg); + } else if (ctrl == pfd->direction) { + /* + * Default is Local. + */ + dlg_radiobutton_set(ctrl, dlg, 0); #ifndef NO_IPV6 - } else if (ctrl == pfd->addressfamily) { - dlg_radiobutton_set(ctrl, dlg, 0); + } else if (ctrl == pfd->addressfamily) { + dlg_radiobutton_set(ctrl, dlg, 0); #endif - } + } } else if (event == EVENT_ACTION) { - if (ctrl == pfd->addbutton) { - const char *family, *type; + if (ctrl == pfd->addbutton) { + const char *family, *type; char *src, *key, *val; - int whichbutton; + int whichbutton; #ifndef NO_IPV6 - whichbutton = dlg_radiobutton_get(pfd->addressfamily, dlg); - if (whichbutton == 1) - family = "4"; - else if (whichbutton == 2) - family = "6"; - else + whichbutton = dlg_radiobutton_get(pfd->addressfamily, dlg); + if (whichbutton == 1) + family = "4"; + else if (whichbutton == 2) + family = "6"; + else #endif - family = ""; + family = ""; - whichbutton = dlg_radiobutton_get(pfd->direction, dlg); - if (whichbutton == 0) - type = "L"; - else if (whichbutton == 1) - type = "R"; - else - type = "D"; - - src = dlg_editbox_get(pfd->sourcebox, dlg); - if (!*src) { - dlg_error_msg(dlg, "You need to specify a source port number"); - sfree(src); - return; - } - if (*type != 'D') { - val = dlg_editbox_get(pfd->destbox, dlg); - if (!*val || !host_strchr(val, ':')) { - dlg_error_msg(dlg, - "You need to specify a destination address\n" - "in the form \"host.name:port\""); - sfree(src); - sfree(val); - return; - } - } else { + whichbutton = dlg_radiobutton_get(pfd->direction, dlg); + if (whichbutton == 0) type = "L"; - val = dupstr("D"); /* special case */ + else if (whichbutton == 1) + type = "R"; + else + type = "D"; + + src = dlg_editbox_get(pfd->sourcebox, dlg); + if (!*src) { + dlg_error_msg(dlg, "You need to specify a source port number"); + sfree(src); + return; + } + if (*type != 'D') { + val = dlg_editbox_get(pfd->destbox, dlg); + if (!*val || !host_strchr(val, ':')) { + dlg_error_msg(dlg, + "You need to specify a destination address\n" + "in the form \"host.name:port\""); + sfree(src); + sfree(val); + return; + } + } else { + type = "L"; + val = dupstr("D"); /* special case */ } - key = dupcat(family, type, src, NULL); - sfree(src); + key = dupcat(family, type, src, NULL); + sfree(src); - if (conf_get_str_str_opt(conf, CONF_portfwd, key)) { - dlg_error_msg(dlg, "Specified forwarding already exists"); - } else { - conf_set_str_str(conf, CONF_portfwd, key, val); - } + if (conf_get_str_str_opt(conf, CONF_portfwd, key)) { + dlg_error_msg(dlg, "Specified forwarding already exists"); + } else { + conf_set_str_str(conf, CONF_portfwd, key, val); + } - sfree(key); - sfree(val); - dlg_refresh(pfd->listbox, dlg); - } else if (ctrl == pfd->rembutton) { - int i = dlg_listbox_index(pfd->listbox, dlg); - if (i < 0) { - dlg_beep(dlg); - } else { - char *key, *p; + sfree(key); + sfree(val); + dlg_refresh(pfd->listbox, dlg); + } else if (ctrl == pfd->rembutton) { + int i = dlg_listbox_index(pfd->listbox, dlg); + if (i < 0) { + dlg_beep(dlg); + } else { + char *key, *p; const char *val; - key = conf_get_str_nthstrkey(conf, CONF_portfwd, i); - if (key) { - static const char *const afs = "A46"; - static const char *const dirs = "LRD"; - const char *afp; - int dir; + key = conf_get_str_nthstrkey(conf, CONF_portfwd, i); + if (key) { + static const char *const afs = "A46"; + static const char *const dirs = "LRD"; + const char *afp; + int dir; #ifndef NO_IPV6 - int idx; + int idx; #endif - /* Populate controls with the entry we're about to delete - * for ease of editing */ - p = key; + /* Populate controls with the entry we're about to delete + * for ease of editing */ + p = key; - afp = strchr(afs, *p); + afp = strchr(afs, *p); #ifndef NO_IPV6 - idx = afp ? afp-afs : 0; + idx = afp ? afp-afs : 0; #endif - if (afp) - p++; + if (afp) + p++; #ifndef NO_IPV6 - dlg_radiobutton_set(pfd->addressfamily, dlg, idx); + dlg_radiobutton_set(pfd->addressfamily, dlg, idx); #endif - dir = *p; + dir = *p; val = conf_get_str_str(conf, CONF_portfwd, key); - if (!strcmp(val, "D")) { + if (!strcmp(val, "D")) { dir = 'D'; - val = ""; - } + val = ""; + } - dlg_radiobutton_set(pfd->direction, dlg, - strchr(dirs, dir) - dirs); - p++; + dlg_radiobutton_set(pfd->direction, dlg, + strchr(dirs, dir) - dirs); + p++; - dlg_editbox_set(pfd->sourcebox, dlg, p); - dlg_editbox_set(pfd->destbox, dlg, val); - /* And delete it */ - conf_del_str_str(conf, CONF_portfwd, key); - } - } - dlg_refresh(pfd->listbox, dlg); - } + dlg_editbox_set(pfd->sourcebox, dlg, p); + dlg_editbox_set(pfd->destbox, dlg, val); + /* And delete it */ + conf_del_str_str(conf, CONF_portfwd, key); + } + } + dlg_refresh(pfd->listbox, dlg); + } } } @@ -1311,61 +1311,61 @@ static void manual_hostkey_handler(union control *ctrl, dlgparam *dlg, { Conf *conf = (Conf *)data; struct manual_hostkey_data *mh = - (struct manual_hostkey_data *)ctrl->generic.context.p; + (struct manual_hostkey_data *)ctrl->generic.context.p; if (event == EVENT_REFRESH) { - if (ctrl == mh->listbox) { - char *key, *val; - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (val = conf_get_str_strs(conf, CONF_ssh_manual_hostkeys, + if (ctrl == mh->listbox) { + char *key, *val; + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (val = conf_get_str_strs(conf, CONF_ssh_manual_hostkeys, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, CONF_ssh_manual_hostkeys, + val != NULL; + val = conf_get_str_strs(conf, CONF_ssh_manual_hostkeys, key, &key)) { - dlg_listbox_add(ctrl, dlg, key); - } - dlg_update_done(ctrl, dlg); - } + dlg_listbox_add(ctrl, dlg, key); + } + dlg_update_done(ctrl, dlg); + } } else if (event == EVENT_ACTION) { - if (ctrl == mh->addbutton) { - char *key; + if (ctrl == mh->addbutton) { + char *key; - key = dlg_editbox_get(mh->keybox, dlg); - if (!*key) { - dlg_error_msg(dlg, "You need to specify a host key or " + key = dlg_editbox_get(mh->keybox, dlg); + if (!*key) { + dlg_error_msg(dlg, "You need to specify a host key or " "fingerprint"); - sfree(key); - return; - } + sfree(key); + return; + } if (!validate_manual_hostkey(key)) { - dlg_error_msg(dlg, "Host key is not in a valid format"); + dlg_error_msg(dlg, "Host key is not in a valid format"); } else if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys, key)) { - dlg_error_msg(dlg, "Specified host key is already listed"); - } else { - conf_set_str_str(conf, CONF_ssh_manual_hostkeys, key, ""); - } + dlg_error_msg(dlg, "Specified host key is already listed"); + } else { + conf_set_str_str(conf, CONF_ssh_manual_hostkeys, key, ""); + } - sfree(key); - dlg_refresh(mh->listbox, dlg); - } else if (ctrl == mh->rembutton) { - int i = dlg_listbox_index(mh->listbox, dlg); - if (i < 0) { - dlg_beep(dlg); - } else { - char *key; + sfree(key); + dlg_refresh(mh->listbox, dlg); + } else if (ctrl == mh->rembutton) { + int i = dlg_listbox_index(mh->listbox, dlg); + if (i < 0) { + dlg_beep(dlg); + } else { + char *key; - key = conf_get_str_nthstrkey(conf, CONF_ssh_manual_hostkeys, i); - if (key) { - dlg_editbox_set(mh->keybox, dlg, key); - /* And delete it */ - conf_del_str_str(conf, CONF_ssh_manual_hostkeys, key); - } - } - dlg_refresh(mh->listbox, dlg); - } + key = conf_get_str_nthstrkey(conf, CONF_ssh_manual_hostkeys, i); + if (key) { + dlg_editbox_set(mh->keybox, dlg, key); + /* And delete it */ + conf_del_str_str(conf, CONF_ssh_manual_hostkeys, key); + } + } + dlg_refresh(mh->listbox, dlg); + } } } @@ -1422,7 +1422,7 @@ static void clipboard_selector_handler(union control *ctrl, dlgparam *dlg, if (val == options[i].id) dlg_listbox_select(ctrl, dlg, i); #endif - dlg_update_done(ctrl, dlg); + dlg_update_done(ctrl, dlg); } else if (event == EVENT_SELCHANGE #ifdef NAMED_CLIPBOARDS || event == EVENT_VALCHANGE @@ -1469,7 +1469,7 @@ static void clipboard_control(struct controlset *s, const char *label, } void setup_config_box(struct controlbox *b, bool midsession, - int protocol, int protcfginfo) + int protocol, int protcfginfo) { struct controlset *s; struct sessionsaver_data *ssd; @@ -1483,7 +1483,7 @@ void setup_config_box(struct controlbox *b, bool midsession, char *str; ssd = (struct sessionsaver_data *) - ctrl_alloc_with_free(b, sizeof(struct sessionsaver_data), + ctrl_alloc_with_free(b, sizeof(struct sessionsaver_data), sessionsaver_data_free); memset(ssd, 0, sizeof(*ssd)); ssd->savedsession = dupstr(""); @@ -1496,14 +1496,14 @@ void setup_config_box(struct controlbox *b, bool midsession, s = ctrl_getset(b, "", "", ""); ctrl_columns(s, 5, 20, 20, 20, 20, 20); ssd->okbutton = ctrl_pushbutton(s, - (midsession ? "Apply" : "Open"), - (char)(midsession ? 'a' : 'o'), - HELPCTX(no_help), - sessionsaver_handler, P(ssd)); + (midsession ? "Apply" : "Open"), + (char)(midsession ? 'a' : 'o'), + HELPCTX(no_help), + sessionsaver_handler, P(ssd)); ssd->okbutton->button.isdefault = true; ssd->okbutton->generic.column = 3; ssd->cancelbutton = ctrl_pushbutton(s, "Cancel", 'c', HELPCTX(no_help), - sessionsaver_handler, P(ssd)); + sessionsaver_handler, P(ssd)); ssd->cancelbutton->button.iscancel = true; ssd->cancelbutton->generic.column = 4; /* We carefully don't close the 5-column part, so that platform- @@ -1517,90 +1517,90 @@ void setup_config_box(struct controlbox *b, bool midsession, sfree(str); if (!midsession) { - struct hostport *hp = (struct hostport *) - ctrl_alloc(b, sizeof(struct hostport)); + struct hostport *hp = (struct hostport *) + ctrl_alloc(b, sizeof(struct hostport)); - s = ctrl_getset(b, "Session", "hostport", - "Specify the destination you want to connect to"); - ctrl_columns(s, 2, 75, 25); - c = ctrl_editbox(s, HOST_BOX_TITLE, 'n', 100, - HELPCTX(session_hostname), - config_host_handler, I(0), I(0)); - c->generic.column = 0; - hp->host = c; - c = ctrl_editbox(s, PORT_BOX_TITLE, 'p', 100, - HELPCTX(session_hostname), - config_port_handler, I(0), I(0)); - c->generic.column = 1; - hp->port = c; - ctrl_columns(s, 1, 100); + s = ctrl_getset(b, "Session", "hostport", + "Specify the destination you want to connect to"); + ctrl_columns(s, 2, 75, 25); + c = ctrl_editbox(s, HOST_BOX_TITLE, 'n', 100, + HELPCTX(session_hostname), + config_host_handler, I(0), I(0)); + c->generic.column = 0; + hp->host = c; + c = ctrl_editbox(s, PORT_BOX_TITLE, 'p', 100, + HELPCTX(session_hostname), + config_port_handler, I(0), I(0)); + c->generic.column = 1; + hp->port = c; + ctrl_columns(s, 1, 100); if (!backend_vt_from_proto(PROT_SSH)) { - ctrl_radiobuttons(s, "Connection type:", NO_SHORTCUT, 3, - HELPCTX(session_hostname), - config_protocolbuttons_handler, P(hp), - "Raw", 'w', I(PROT_RAW), - "Telnet", 't', I(PROT_TELNET), - "Rlogin", 'i', I(PROT_RLOGIN), - NULL); - } else { - ctrl_radiobuttons(s, "Connection type:", NO_SHORTCUT, 4, - HELPCTX(session_hostname), - config_protocolbuttons_handler, P(hp), - "Raw", 'w', I(PROT_RAW), - "Telnet", 't', I(PROT_TELNET), - "Rlogin", 'i', I(PROT_RLOGIN), - "SSH", 's', I(PROT_SSH), - NULL); - } + ctrl_radiobuttons(s, "Connection type:", NO_SHORTCUT, 3, + HELPCTX(session_hostname), + config_protocolbuttons_handler, P(hp), + "Raw", 'w', I(PROT_RAW), + "Telnet", 't', I(PROT_TELNET), + "Rlogin", 'i', I(PROT_RLOGIN), + NULL); + } else { + ctrl_radiobuttons(s, "Connection type:", NO_SHORTCUT, 4, + HELPCTX(session_hostname), + config_protocolbuttons_handler, P(hp), + "Raw", 'w', I(PROT_RAW), + "Telnet", 't', I(PROT_TELNET), + "Rlogin", 'i', I(PROT_RLOGIN), + "SSH", 's', I(PROT_SSH), + NULL); + } } /* * The Load/Save panel is available even in mid-session. */ s = ctrl_getset(b, "Session", "savedsessions", - midsession ? "Save the current session settings" : - "Load, save or delete a stored session"); + midsession ? "Save the current session settings" : + "Load, save or delete a stored session"); ctrl_columns(s, 2, 75, 25); get_sesslist(&ssd->sesslist, true); ssd->editbox = ctrl_editbox(s, "Saved Sessions", 'e', 100, - HELPCTX(session_saved), - sessionsaver_handler, P(ssd), P(NULL)); + HELPCTX(session_saved), + sessionsaver_handler, P(ssd), P(NULL)); ssd->editbox->generic.column = 0; /* Reset columns so that the buttons are alongside the list, rather * than alongside that edit box. */ ctrl_columns(s, 1, 100); ctrl_columns(s, 2, 75, 25); ssd->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, - HELPCTX(session_saved), - sessionsaver_handler, P(ssd)); + HELPCTX(session_saved), + sessionsaver_handler, P(ssd)); ssd->listbox->generic.column = 0; ssd->listbox->listbox.height = 7; if (!midsession) { - ssd->loadbutton = ctrl_pushbutton(s, "Load", 'l', - HELPCTX(session_saved), - sessionsaver_handler, P(ssd)); - ssd->loadbutton->generic.column = 1; + ssd->loadbutton = ctrl_pushbutton(s, "Load", 'l', + HELPCTX(session_saved), + sessionsaver_handler, P(ssd)); + ssd->loadbutton->generic.column = 1; } else { - /* We can't offer the Load button mid-session, as it would allow the - * user to load and subsequently save settings they can't see. (And - * also change otherwise immutable settings underfoot; that probably - * shouldn't be a problem, but.) */ - ssd->loadbutton = NULL; + /* We can't offer the Load button mid-session, as it would allow the + * user to load and subsequently save settings they can't see. (And + * also change otherwise immutable settings underfoot; that probably + * shouldn't be a problem, but.) */ + ssd->loadbutton = NULL; } /* "Save" button is permitted mid-session. */ ssd->savebutton = ctrl_pushbutton(s, "Save", 'v', - HELPCTX(session_saved), - sessionsaver_handler, P(ssd)); + HELPCTX(session_saved), + sessionsaver_handler, P(ssd)); ssd->savebutton->generic.column = 1; if (!midsession) { - ssd->delbutton = ctrl_pushbutton(s, "Delete", 'd', - HELPCTX(session_saved), - sessionsaver_handler, P(ssd)); - ssd->delbutton->generic.column = 1; + ssd->delbutton = ctrl_pushbutton(s, "Delete", 'd', + HELPCTX(session_saved), + sessionsaver_handler, P(ssd)); + ssd->delbutton->generic.column = 1; } else { - /* Disable the Delete button mid-session too, for UI consistency. */ - ssd->delbutton = NULL; + /* Disable the Delete button mid-session too, for UI consistency. */ + ssd->delbutton = NULL; } ctrl_columns(s, 1, 100); @@ -1624,56 +1624,56 @@ void setup_config_box(struct controlbox *b, bool midsession, * logging can sensibly be available. */ { - const char *sshlogname, *sshrawlogname; - if ((midsession && protocol == PROT_SSH) || + const char *sshlogname, *sshrawlogname; + if ((midsession && protocol == PROT_SSH) || (!midsession && backend_vt_from_proto(PROT_SSH))) { - sshlogname = "SSH packets"; - sshrawlogname = "SSH packets and raw data"; + sshlogname = "SSH packets"; + sshrawlogname = "SSH packets and raw data"; } else { - sshlogname = NULL; /* this will disable both buttons */ - sshrawlogname = NULL; /* this will just placate optimisers */ + sshlogname = NULL; /* this will disable both buttons */ + sshrawlogname = NULL; /* this will just placate optimisers */ } - ctrl_radiobuttons(s, "Session logging:", NO_SHORTCUT, 2, - HELPCTX(logging_main), - loggingbuttons_handler, - I(CONF_logtype), - "None", 't', I(LGTYP_NONE), - "Printable output", 'p', I(LGTYP_ASCII), - "All session output", 'l', I(LGTYP_DEBUG), - sshlogname, 's', I(LGTYP_PACKETS), - sshrawlogname, 'r', I(LGTYP_SSHRAW), - NULL); + ctrl_radiobuttons(s, "Session logging:", NO_SHORTCUT, 2, + HELPCTX(logging_main), + loggingbuttons_handler, + I(CONF_logtype), + "None", 't', I(LGTYP_NONE), + "Printable output", 'p', I(LGTYP_ASCII), + "All session output", 'l', I(LGTYP_DEBUG), + sshlogname, 's', I(LGTYP_PACKETS), + sshrawlogname, 'r', I(LGTYP_SSHRAW), + NULL); } ctrl_filesel(s, "Log file name:", 'f', - NULL, true, "Select session log file name", - HELPCTX(logging_filename), - conf_filesel_handler, I(CONF_logfilename)); + NULL, true, "Select session log file name", + HELPCTX(logging_filename), + conf_filesel_handler, I(CONF_logfilename)); ctrl_text(s, "(Log file name can contain &Y, &M, &D for date," - " &T for time, &H for host name, and &P for port number)", - HELPCTX(logging_filename)); + " &T for time, &H for host name, and &P for port number)", + HELPCTX(logging_filename)); ctrl_radiobuttons(s, "What to do if the log file already exists:", 'e', 1, - HELPCTX(logging_exists), - conf_radiobutton_handler, I(CONF_logxfovr), - "Always overwrite it", I(LGXF_OVR), - "Always append to the end of it", I(LGXF_APN), - "Ask the user every time", I(LGXF_ASK), NULL); + HELPCTX(logging_exists), + conf_radiobutton_handler, I(CONF_logxfovr), + "Always overwrite it", I(LGXF_OVR), + "Always append to the end of it", I(LGXF_APN), + "Ask the user every time", I(LGXF_ASK), NULL); ctrl_checkbox(s, "Flush log file frequently", 'u', - HELPCTX(logging_flush), - conf_checkbox_handler, I(CONF_logflush)); + HELPCTX(logging_flush), + conf_checkbox_handler, I(CONF_logflush)); ctrl_checkbox(s, "Include header", 'i', - HELPCTX(logging_header), - conf_checkbox_handler, I(CONF_logheader)); + HELPCTX(logging_header), + conf_checkbox_handler, I(CONF_logheader)); if ((midsession && protocol == PROT_SSH) || (!midsession && backend_vt_from_proto(PROT_SSH))) { - s = ctrl_getset(b, "Session/Logging", "ssh", - "Options specific to SSH packet logging"); - ctrl_checkbox(s, "Omit known password fields", 'k', - HELPCTX(logging_ssh_omit_password), - conf_checkbox_handler, I(CONF_logomitpass)); - ctrl_checkbox(s, "Omit session data", 'd', - HELPCTX(logging_ssh_omit_data), - conf_checkbox_handler, I(CONF_logomitdata)); + s = ctrl_getset(b, "Session/Logging", "ssh", + "Options specific to SSH packet logging"); + ctrl_checkbox(s, "Omit known password fields", 'k', + HELPCTX(logging_ssh_omit_password), + conf_checkbox_handler, I(CONF_logomitpass)); + ctrl_checkbox(s, "Omit session data", 'd', + HELPCTX(logging_ssh_omit_data), + conf_checkbox_handler, I(CONF_logomitdata)); } /* @@ -1683,167 +1683,167 @@ void setup_config_box(struct controlbox *b, bool midsession, s = ctrl_getset(b, "Terminal", "general", "Set various terminal options"); ctrl_checkbox(s, "Auto wrap mode initially on", 'w', - HELPCTX(terminal_autowrap), - conf_checkbox_handler, I(CONF_wrap_mode)); + HELPCTX(terminal_autowrap), + conf_checkbox_handler, I(CONF_wrap_mode)); ctrl_checkbox(s, "DEC Origin Mode initially on", 'd', - HELPCTX(terminal_decom), - conf_checkbox_handler, I(CONF_dec_om)); + HELPCTX(terminal_decom), + conf_checkbox_handler, I(CONF_dec_om)); ctrl_checkbox(s, "Implicit CR in every LF", 'r', - HELPCTX(terminal_lfhascr), - conf_checkbox_handler, I(CONF_lfhascr)); + HELPCTX(terminal_lfhascr), + conf_checkbox_handler, I(CONF_lfhascr)); ctrl_checkbox(s, "Implicit LF in every CR", 'f', - HELPCTX(terminal_crhaslf), - conf_checkbox_handler, I(CONF_crhaslf)); + HELPCTX(terminal_crhaslf), + conf_checkbox_handler, I(CONF_crhaslf)); ctrl_checkbox(s, "Use background colour to erase screen", 'e', - HELPCTX(terminal_bce), - conf_checkbox_handler, I(CONF_bce)); + HELPCTX(terminal_bce), + conf_checkbox_handler, I(CONF_bce)); ctrl_checkbox(s, "Enable blinking text", 'n', - HELPCTX(terminal_blink), - conf_checkbox_handler, I(CONF_blinktext)); + HELPCTX(terminal_blink), + conf_checkbox_handler, I(CONF_blinktext)); ctrl_editbox(s, "Answerback to ^E:", 's', 100, - HELPCTX(terminal_answerback), - conf_editbox_handler, I(CONF_answerback), I(1)); + HELPCTX(terminal_answerback), + conf_editbox_handler, I(CONF_answerback), I(1)); s = ctrl_getset(b, "Terminal", "ldisc", "Line discipline options"); ctrl_radiobuttons(s, "Local echo:", 'l', 3, - HELPCTX(terminal_localecho), - conf_radiobutton_handler,I(CONF_localecho), - "Auto", I(AUTO), - "Force on", I(FORCE_ON), - "Force off", I(FORCE_OFF), NULL); + HELPCTX(terminal_localecho), + conf_radiobutton_handler,I(CONF_localecho), + "Auto", I(AUTO), + "Force on", I(FORCE_ON), + "Force off", I(FORCE_OFF), NULL); ctrl_radiobuttons(s, "Local line editing:", 't', 3, - HELPCTX(terminal_localedit), - conf_radiobutton_handler,I(CONF_localedit), - "Auto", I(AUTO), - "Force on", I(FORCE_ON), - "Force off", I(FORCE_OFF), NULL); + HELPCTX(terminal_localedit), + conf_radiobutton_handler,I(CONF_localedit), + "Auto", I(AUTO), + "Force on", I(FORCE_ON), + "Force off", I(FORCE_OFF), NULL); s = ctrl_getset(b, "Terminal", "printing", "Remote-controlled printing"); ctrl_combobox(s, "Printer to send ANSI printer output to:", 'p', 100, - HELPCTX(terminal_printing), - printerbox_handler, P(NULL), P(NULL)); + HELPCTX(terminal_printing), + printerbox_handler, P(NULL), P(NULL)); /* * The Terminal/Keyboard panel. */ ctrl_settitle(b, "Terminal/Keyboard", - "Options controlling the effects of keys"); + "Options controlling the effects of keys"); s = ctrl_getset(b, "Terminal/Keyboard", "mappings", - "Change the sequences sent by:"); + "Change the sequences sent by:"); ctrl_radiobuttons(s, "The Backspace key", 'b', 2, - HELPCTX(keyboard_backspace), - conf_radiobutton_bool_handler, - I(CONF_bksp_is_delete), - "Control-H", I(0), "Control-? (127)", I(1), NULL); + HELPCTX(keyboard_backspace), + conf_radiobutton_bool_handler, + I(CONF_bksp_is_delete), + "Control-H", I(0), "Control-? (127)", I(1), NULL); ctrl_radiobuttons(s, "The Home and End keys", 'e', 2, - HELPCTX(keyboard_homeend), - conf_radiobutton_bool_handler, - I(CONF_rxvt_homeend), - "Standard", I(false), "rxvt", I(true), NULL); + HELPCTX(keyboard_homeend), + conf_radiobutton_bool_handler, + I(CONF_rxvt_homeend), + "Standard", I(false), "rxvt", I(true), NULL); ctrl_radiobuttons(s, "The Function keys and keypad", 'f', 3, - HELPCTX(keyboard_funkeys), - conf_radiobutton_handler, - I(CONF_funky_type), - "ESC[n~", I(0), "Linux", I(1), "Xterm R6", I(2), - "VT400", I(3), "VT100+", I(4), "SCO", I(5), NULL); + HELPCTX(keyboard_funkeys), + conf_radiobutton_handler, + I(CONF_funky_type), + "ESC[n~", I(0), "Linux", I(1), "Xterm R6", I(2), + "VT400", I(3), "VT100+", I(4), "SCO", I(5), NULL); s = ctrl_getset(b, "Terminal/Keyboard", "appkeypad", - "Application keypad settings:"); + "Application keypad settings:"); ctrl_radiobuttons(s, "Initial state of cursor keys:", 'r', 3, - HELPCTX(keyboard_appcursor), - conf_radiobutton_bool_handler, - I(CONF_app_cursor), - "Normal", I(0), "Application", I(1), NULL); + HELPCTX(keyboard_appcursor), + conf_radiobutton_bool_handler, + I(CONF_app_cursor), + "Normal", I(0), "Application", I(1), NULL); ctrl_radiobuttons(s, "Initial state of numeric keypad:", 'n', 3, - HELPCTX(keyboard_appkeypad), - numeric_keypad_handler, P(NULL), - "Normal", I(0), "Application", I(1), "NetHack", I(2), - NULL); + HELPCTX(keyboard_appkeypad), + numeric_keypad_handler, P(NULL), + "Normal", I(0), "Application", I(1), "NetHack", I(2), + NULL); /* * The Terminal/Bell panel. */ ctrl_settitle(b, "Terminal/Bell", - "Options controlling the terminal bell"); + "Options controlling the terminal bell"); s = ctrl_getset(b, "Terminal/Bell", "style", "Set the style of bell"); ctrl_radiobuttons(s, "Action to happen when a bell occurs:", 'b', 1, - HELPCTX(bell_style), - conf_radiobutton_handler, I(CONF_beep), - "None (bell disabled)", I(BELL_DISABLED), - "Make default system alert sound", I(BELL_DEFAULT), - "Visual bell (flash window)", I(BELL_VISUAL), NULL); + HELPCTX(bell_style), + conf_radiobutton_handler, I(CONF_beep), + "None (bell disabled)", I(BELL_DISABLED), + "Make default system alert sound", I(BELL_DEFAULT), + "Visual bell (flash window)", I(BELL_VISUAL), NULL); s = ctrl_getset(b, "Terminal/Bell", "overload", - "Control the bell overload behaviour"); + "Control the bell overload behaviour"); ctrl_checkbox(s, "Bell is temporarily disabled when over-used", 'd', - HELPCTX(bell_overload), - conf_checkbox_handler, I(CONF_bellovl)); + HELPCTX(bell_overload), + conf_checkbox_handler, I(CONF_bellovl)); ctrl_editbox(s, "Over-use means this many bells...", 'm', 20, - HELPCTX(bell_overload), - conf_editbox_handler, I(CONF_bellovl_n), I(-1)); + HELPCTX(bell_overload), + conf_editbox_handler, I(CONF_bellovl_n), I(-1)); ctrl_editbox(s, "... in this many seconds", 't', 20, - HELPCTX(bell_overload), - conf_editbox_handler, I(CONF_bellovl_t), - I(-TICKSPERSEC)); + HELPCTX(bell_overload), + conf_editbox_handler, I(CONF_bellovl_t), + I(-TICKSPERSEC)); ctrl_text(s, "The bell is re-enabled after a few seconds of silence.", - HELPCTX(bell_overload)); + HELPCTX(bell_overload)); ctrl_editbox(s, "Seconds of silence required", 's', 20, - HELPCTX(bell_overload), - conf_editbox_handler, I(CONF_bellovl_s), - I(-TICKSPERSEC)); + HELPCTX(bell_overload), + conf_editbox_handler, I(CONF_bellovl_s), + I(-TICKSPERSEC)); /* * The Terminal/Features panel. */ ctrl_settitle(b, "Terminal/Features", - "Enabling and disabling advanced terminal features"); + "Enabling and disabling advanced terminal features"); s = ctrl_getset(b, "Terminal/Features", "main", NULL); ctrl_checkbox(s, "Disable application cursor keys mode", 'u', - HELPCTX(features_application), - conf_checkbox_handler, I(CONF_no_applic_c)); + HELPCTX(features_application), + conf_checkbox_handler, I(CONF_no_applic_c)); ctrl_checkbox(s, "Disable application keypad mode", 'k', - HELPCTX(features_application), - conf_checkbox_handler, I(CONF_no_applic_k)); + HELPCTX(features_application), + conf_checkbox_handler, I(CONF_no_applic_k)); ctrl_checkbox(s, "Disable xterm-style mouse reporting", 'x', - HELPCTX(features_mouse), - conf_checkbox_handler, I(CONF_no_mouse_rep)); + HELPCTX(features_mouse), + conf_checkbox_handler, I(CONF_no_mouse_rep)); ctrl_checkbox(s, "Disable remote-controlled terminal resizing", 's', - HELPCTX(features_resize), - conf_checkbox_handler, - I(CONF_no_remote_resize)); + HELPCTX(features_resize), + conf_checkbox_handler, + I(CONF_no_remote_resize)); ctrl_checkbox(s, "Disable switching to alternate terminal screen", 'w', - HELPCTX(features_altscreen), - conf_checkbox_handler, I(CONF_no_alt_screen)); + HELPCTX(features_altscreen), + conf_checkbox_handler, I(CONF_no_alt_screen)); ctrl_checkbox(s, "Disable remote-controlled window title changing", 't', - HELPCTX(features_retitle), - conf_checkbox_handler, - I(CONF_no_remote_wintitle)); + HELPCTX(features_retitle), + conf_checkbox_handler, + I(CONF_no_remote_wintitle)); ctrl_radiobuttons(s, "Response to remote title query (SECURITY):", 'q', 3, - HELPCTX(features_qtitle), - conf_radiobutton_handler, - I(CONF_remote_qtitle_action), - "None", I(TITLE_NONE), - "Empty string", I(TITLE_EMPTY), - "Window title", I(TITLE_REAL), NULL); + HELPCTX(features_qtitle), + conf_radiobutton_handler, + I(CONF_remote_qtitle_action), + "None", I(TITLE_NONE), + "Empty string", I(TITLE_EMPTY), + "Window title", I(TITLE_REAL), NULL); ctrl_checkbox(s, "Disable remote-controlled clearing of scrollback", 'e', - HELPCTX(features_clearscroll), - conf_checkbox_handler, - I(CONF_no_remote_clearscroll)); + HELPCTX(features_clearscroll), + conf_checkbox_handler, + I(CONF_no_remote_clearscroll)); ctrl_checkbox(s, "Disable destructive backspace on server sending ^?",'b', - HELPCTX(features_dbackspace), - conf_checkbox_handler, I(CONF_no_dbackspace)); + HELPCTX(features_dbackspace), + conf_checkbox_handler, I(CONF_no_dbackspace)); ctrl_checkbox(s, "Disable remote-controlled character set configuration", - 'r', HELPCTX(features_charset), conf_checkbox_handler, - I(CONF_no_remote_charset)); + 'r', HELPCTX(features_charset), conf_checkbox_handler, + I(CONF_no_remote_charset)); ctrl_checkbox(s, "Disable Arabic text shaping", - 'l', HELPCTX(features_arabicshaping), conf_checkbox_handler, - I(CONF_no_arabicshaping)); + 'l', HELPCTX(features_arabicshaping), conf_checkbox_handler, + I(CONF_no_arabicshaping)); ctrl_checkbox(s, "Disable bidirectional text display", - 'd', HELPCTX(features_bidi), conf_checkbox_handler, - I(CONF_no_bidi)); + 'd', HELPCTX(features_bidi), conf_checkbox_handler, + I(CONF_no_bidi)); /* * The Window panel. @@ -1855,33 +1855,33 @@ void setup_config_box(struct controlbox *b, bool midsession, s = ctrl_getset(b, "Window", "size", "Set the size of the window"); ctrl_columns(s, 2, 50, 50); c = ctrl_editbox(s, "Columns", 'm', 100, - HELPCTX(window_size), - conf_editbox_handler, I(CONF_width), I(-1)); + HELPCTX(window_size), + conf_editbox_handler, I(CONF_width), I(-1)); c->generic.column = 0; c = ctrl_editbox(s, "Rows", 'r', 100, - HELPCTX(window_size), - conf_editbox_handler, I(CONF_height),I(-1)); + HELPCTX(window_size), + conf_editbox_handler, I(CONF_height),I(-1)); c->generic.column = 1; ctrl_columns(s, 1, 100); s = ctrl_getset(b, "Window", "scrollback", - "Control the scrollback in the window"); + "Control the scrollback in the window"); ctrl_editbox(s, "Lines of scrollback", 's', 50, - HELPCTX(window_scrollback), - conf_editbox_handler, I(CONF_savelines), I(-1)); + HELPCTX(window_scrollback), + conf_editbox_handler, I(CONF_savelines), I(-1)); ctrl_checkbox(s, "Display scrollbar", 'd', - HELPCTX(window_scrollback), - conf_checkbox_handler, I(CONF_scrollbar)); + HELPCTX(window_scrollback), + conf_checkbox_handler, I(CONF_scrollbar)); ctrl_checkbox(s, "Reset scrollback on keypress", 'k', - HELPCTX(window_scrollback), - conf_checkbox_handler, I(CONF_scroll_on_key)); + HELPCTX(window_scrollback), + conf_checkbox_handler, I(CONF_scroll_on_key)); ctrl_checkbox(s, "Reset scrollback on display activity", 'p', - HELPCTX(window_scrollback), - conf_checkbox_handler, I(CONF_scroll_on_disp)); + HELPCTX(window_scrollback), + conf_checkbox_handler, I(CONF_scroll_on_disp)); ctrl_checkbox(s, "Push erased text into scrollback", 'e', - HELPCTX(window_erased), - conf_checkbox_handler, - I(CONF_erase_to_scrollback)); + HELPCTX(window_erased), + conf_checkbox_handler, + I(CONF_erase_to_scrollback)); /* * The Window/Appearance panel. @@ -1891,36 +1891,36 @@ void setup_config_box(struct controlbox *b, bool midsession, sfree(str); s = ctrl_getset(b, "Window/Appearance", "cursor", - "Adjust the use of the cursor"); + "Adjust the use of the cursor"); ctrl_radiobuttons(s, "Cursor appearance:", NO_SHORTCUT, 3, - HELPCTX(appearance_cursor), - conf_radiobutton_handler, - I(CONF_cursor_type), - "Block", 'l', I(0), - "Underline", 'u', I(1), - "Vertical line", 'v', I(2), NULL); + HELPCTX(appearance_cursor), + conf_radiobutton_handler, + I(CONF_cursor_type), + "Block", 'l', I(0), + "Underline", 'u', I(1), + "Vertical line", 'v', I(2), NULL); ctrl_checkbox(s, "Cursor blinks", 'b', - HELPCTX(appearance_cursor), - conf_checkbox_handler, I(CONF_blink_cur)); + HELPCTX(appearance_cursor), + conf_checkbox_handler, I(CONF_blink_cur)); s = ctrl_getset(b, "Window/Appearance", "font", - "Font settings"); + "Font settings"); ctrl_fontsel(s, "Font used in the terminal window", 'n', - HELPCTX(appearance_font), - conf_fontsel_handler, I(CONF_font)); + HELPCTX(appearance_font), + conf_fontsel_handler, I(CONF_font)); s = ctrl_getset(b, "Window/Appearance", "mouse", - "Adjust the use of the mouse pointer"); + "Adjust the use of the mouse pointer"); ctrl_checkbox(s, "Hide mouse pointer when typing in window", 'p', - HELPCTX(appearance_hidemouse), - conf_checkbox_handler, I(CONF_hide_mouseptr)); + HELPCTX(appearance_hidemouse), + conf_checkbox_handler, I(CONF_hide_mouseptr)); s = ctrl_getset(b, "Window/Appearance", "border", - "Adjust the window border"); + "Adjust the window border"); ctrl_editbox(s, "Gap between text and window edge:", 'e', 20, - HELPCTX(appearance_border), - conf_editbox_handler, - I(CONF_window_border), I(-1)); + HELPCTX(appearance_border), + conf_editbox_handler, + I(CONF_window_border), I(-1)); /* * The Window/Behaviour panel. @@ -1930,50 +1930,50 @@ void setup_config_box(struct controlbox *b, bool midsession, sfree(str); s = ctrl_getset(b, "Window/Behaviour", "title", - "Adjust the behaviour of the window title"); + "Adjust the behaviour of the window title"); ctrl_editbox(s, "Window title:", 't', 100, - HELPCTX(appearance_title), - conf_editbox_handler, I(CONF_wintitle), I(1)); + HELPCTX(appearance_title), + conf_editbox_handler, I(CONF_wintitle), I(1)); ctrl_checkbox(s, "Separate window and icon titles", 'i', - HELPCTX(appearance_title), - conf_checkbox_handler, - I(CHECKBOX_INVERT | CONF_win_name_always)); + HELPCTX(appearance_title), + conf_checkbox_handler, + I(CHECKBOX_INVERT | CONF_win_name_always)); s = ctrl_getset(b, "Window/Behaviour", "main", NULL); ctrl_checkbox(s, "Warn before closing window", 'w', - HELPCTX(behaviour_closewarn), - conf_checkbox_handler, I(CONF_warn_on_close)); + HELPCTX(behaviour_closewarn), + conf_checkbox_handler, I(CONF_warn_on_close)); /* * The Window/Translation panel. */ ctrl_settitle(b, "Window/Translation", - "Options controlling character set translation"); + "Options controlling character set translation"); s = ctrl_getset(b, "Window/Translation", "trans", - "Character set translation"); + "Character set translation"); ctrl_combobox(s, "Remote character set:", - 'r', 100, HELPCTX(translation_codepage), - codepage_handler, P(NULL), P(NULL)); + 'r', 100, HELPCTX(translation_codepage), + codepage_handler, P(NULL), P(NULL)); s = ctrl_getset(b, "Window/Translation", "tweaks", NULL); ctrl_checkbox(s, "Treat CJK ambiguous characters as wide", 'w', - HELPCTX(translation_cjk_ambig_wide), - conf_checkbox_handler, I(CONF_cjk_ambig_wide)); + HELPCTX(translation_cjk_ambig_wide), + conf_checkbox_handler, I(CONF_cjk_ambig_wide)); str = dupprintf("Adjust how %s handles line drawing characters", appname); s = ctrl_getset(b, "Window/Translation", "linedraw", str); sfree(str); ctrl_radiobuttons(s, "Handling of line drawing characters:", NO_SHORTCUT,1, - HELPCTX(translation_linedraw), - conf_radiobutton_handler, - I(CONF_vtmode), - "Use Unicode line drawing code points",'u',I(VT_UNICODE), - "Poor man's line drawing (+, - and |)",'p',I(VT_POORMAN), - NULL); + HELPCTX(translation_linedraw), + conf_radiobutton_handler, + I(CONF_vtmode), + "Use Unicode line drawing code points",'u',I(VT_UNICODE), + "Poor man's line drawing (+, - and |)",'p',I(VT_POORMAN), + NULL); ctrl_checkbox(s, "Copy and paste line drawing characters as lqqqk",'d', - HELPCTX(selection_linedraw), - conf_checkbox_handler, I(CONF_rawcnp)); + HELPCTX(selection_linedraw), + conf_checkbox_handler, I(CONF_rawcnp)); ctrl_checkbox(s, "Enable VT100 line drawing even in UTF-8 mode",'8', HELPCTX(translation_utf8linedraw), conf_checkbox_handler, I(CONF_utf8linedraw)); @@ -1982,20 +1982,20 @@ void setup_config_box(struct controlbox *b, bool midsession, * The Window/Selection panel. */ ctrl_settitle(b, "Window/Selection", "Options controlling copy and paste"); - + s = ctrl_getset(b, "Window/Selection", "mouse", - "Control use of mouse"); + "Control use of mouse"); ctrl_checkbox(s, "Shift overrides application's use of mouse", 'p', - HELPCTX(selection_shiftdrag), - conf_checkbox_handler, I(CONF_mouse_override)); + HELPCTX(selection_shiftdrag), + conf_checkbox_handler, I(CONF_mouse_override)); ctrl_radiobuttons(s, - "Default selection mode (Alt+drag does the other one):", - NO_SHORTCUT, 2, - HELPCTX(selection_rect), - conf_radiobutton_bool_handler, - I(CONF_rect_select), - "Normal", 'n', I(false), - "Rectangular block", 'r', I(true), NULL); + "Default selection mode (Alt+drag does the other one):", + NO_SHORTCUT, 2, + HELPCTX(selection_rect), + conf_radiobutton_bool_handler, + I(CONF_rect_select), + "Normal", 'n', I(false), + "Rectangular block", 'r', I(true), NULL); s = ctrl_getset(b, "Window/Selection", "clipboards", "Assign copy/paste actions to clipboards"); @@ -2026,12 +2026,12 @@ void setup_config_box(struct controlbox *b, bool midsession, "Options controlling copying from terminal to clipboard"); s = ctrl_getset(b, "Window/Selection/Copy", "charclass", - "Classes of character that group together"); + "Classes of character that group together"); ccd = (struct charclass_data *) - ctrl_alloc(b, sizeof(struct charclass_data)); + ctrl_alloc(b, sizeof(struct charclass_data)); ccd->listbox = ctrl_listbox(s, "Character classes:", 'e', - HELPCTX(copy_charclasses), - charclass_handler, P(ccd)); + HELPCTX(copy_charclasses), + charclass_handler, P(ccd)); ccd->listbox->listbox.multisel = 1; ccd->listbox->listbox.ncols = 4; ccd->listbox->listbox.percentages = snewn(4, int); @@ -2041,12 +2041,12 @@ void setup_config_box(struct controlbox *b, bool midsession, ccd->listbox->listbox.percentages[3] = 40; ctrl_columns(s, 2, 67, 33); ccd->editbox = ctrl_editbox(s, "Set to class", 't', 50, - HELPCTX(copy_charclasses), - charclass_handler, P(ccd), P(NULL)); + HELPCTX(copy_charclasses), + charclass_handler, P(ccd), P(NULL)); ccd->editbox->generic.column = 0; ccd->button = ctrl_pushbutton(s, "Set", 's', - HELPCTX(copy_charclasses), - charclass_handler, P(ccd)); + HELPCTX(copy_charclasses), + charclass_handler, P(ccd)); ccd->button->generic.column = 1; ctrl_columns(s, 1, 100); @@ -2056,16 +2056,16 @@ void setup_config_box(struct controlbox *b, bool midsession, ctrl_settitle(b, "Window/Colours", "Options controlling use of colours"); s = ctrl_getset(b, "Window/Colours", "general", - "General options for colour usage"); + "General options for colour usage"); ctrl_checkbox(s, "Allow terminal to specify ANSI colours", 'i', - HELPCTX(colours_ansi), - conf_checkbox_handler, I(CONF_ansi_colour)); + HELPCTX(colours_ansi), + conf_checkbox_handler, I(CONF_ansi_colour)); ctrl_checkbox(s, "Allow terminal to use xterm 256-colour mode", '2', - HELPCTX(colours_xterm256), conf_checkbox_handler, - I(CONF_xterm_256_colour)); + HELPCTX(colours_xterm256), conf_checkbox_handler, + I(CONF_xterm_256_colour)); ctrl_checkbox(s, "Allow terminal to use 24-bit colours", '4', - HELPCTX(colours_truecolour), conf_checkbox_handler, - I(CONF_true_colour)); + HELPCTX(colours_truecolour), conf_checkbox_handler, + I(CONF_true_colour)); ctrl_radiobuttons(s, "Indicate bolded text by changing:", 'b', 3, HELPCTX(colours_bold), conf_radiobutton_handler, I(CONF_bold_style), @@ -2078,27 +2078,27 @@ void setup_config_box(struct controlbox *b, bool midsession, s = ctrl_getset(b, "Window/Colours", "adjust", str); sfree(str); ctrl_text(s, "Select a colour from the list, and then click the" - " Modify button to change its appearance.", - HELPCTX(colours_config)); + " Modify button to change its appearance.", + HELPCTX(colours_config)); ctrl_columns(s, 2, 67, 33); cd = (struct colour_data *)ctrl_alloc(b, sizeof(struct colour_data)); cd->listbox = ctrl_listbox(s, "Select a colour to adjust:", 'u', - HELPCTX(colours_config), colour_handler, P(cd)); + HELPCTX(colours_config), colour_handler, P(cd)); cd->listbox->generic.column = 0; cd->listbox->listbox.height = 7; c = ctrl_text(s, "RGB value:", HELPCTX(colours_config)); c->generic.column = 1; cd->redit = ctrl_editbox(s, "Red", 'r', 50, HELPCTX(colours_config), - colour_handler, P(cd), P(NULL)); + colour_handler, P(cd), P(NULL)); cd->redit->generic.column = 1; cd->gedit = ctrl_editbox(s, "Green", 'n', 50, HELPCTX(colours_config), - colour_handler, P(cd), P(NULL)); + colour_handler, P(cd), P(NULL)); cd->gedit->generic.column = 1; cd->bedit = ctrl_editbox(s, "Blue", 'e', 50, HELPCTX(colours_config), - colour_handler, P(cd), P(NULL)); + colour_handler, P(cd), P(NULL)); cd->bedit->generic.column = 1; cd->button = ctrl_pushbutton(s, "Modify", 'm', HELPCTX(colours_config), - colour_handler, P(cd)); + colour_handler, P(cd)); cd->button->generic.column = 1; ctrl_columns(s, 1, 100); @@ -2108,191 +2108,191 @@ void setup_config_box(struct controlbox *b, bool midsession, * passed a protocol < 0. */ if (protocol >= 0) { - ctrl_settitle(b, "Connection", "Options controlling the connection"); + ctrl_settitle(b, "Connection", "Options controlling the connection"); - s = ctrl_getset(b, "Connection", "keepalive", - "Sending of null packets to keep session active"); - ctrl_editbox(s, "Seconds between keepalives (0 to turn off)", 'k', 20, - HELPCTX(connection_keepalive), - conf_editbox_handler, I(CONF_ping_interval), - I(-1)); + s = ctrl_getset(b, "Connection", "keepalive", + "Sending of null packets to keep session active"); + ctrl_editbox(s, "Seconds between keepalives (0 to turn off)", 'k', 20, + HELPCTX(connection_keepalive), + conf_editbox_handler, I(CONF_ping_interval), + I(-1)); - if (!midsession) { - s = ctrl_getset(b, "Connection", "tcp", - "Low-level TCP connection options"); - ctrl_checkbox(s, "Disable Nagle's algorithm (TCP_NODELAY option)", - 'n', HELPCTX(connection_nodelay), - conf_checkbox_handler, - I(CONF_tcp_nodelay)); - ctrl_checkbox(s, "Enable TCP keepalives (SO_KEEPALIVE option)", - 'p', HELPCTX(connection_tcpkeepalive), - conf_checkbox_handler, - I(CONF_tcp_keepalives)); + if (!midsession) { + s = ctrl_getset(b, "Connection", "tcp", + "Low-level TCP connection options"); + ctrl_checkbox(s, "Disable Nagle's algorithm (TCP_NODELAY option)", + 'n', HELPCTX(connection_nodelay), + conf_checkbox_handler, + I(CONF_tcp_nodelay)); + ctrl_checkbox(s, "Enable TCP keepalives (SO_KEEPALIVE option)", + 'p', HELPCTX(connection_tcpkeepalive), + conf_checkbox_handler, + I(CONF_tcp_keepalives)); #ifndef NO_IPV6 - s = ctrl_getset(b, "Connection", "ipversion", - "Internet protocol version"); - ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, - HELPCTX(connection_ipversion), - conf_radiobutton_handler, - I(CONF_addressfamily), - "Auto", 'u', I(ADDRTYPE_UNSPEC), - "IPv4", '4', I(ADDRTYPE_IPV4), - "IPv6", '6', I(ADDRTYPE_IPV6), - NULL); + s = ctrl_getset(b, "Connection", "ipversion", + "Internet protocol version"); + ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, + HELPCTX(connection_ipversion), + conf_radiobutton_handler, + I(CONF_addressfamily), + "Auto", 'u', I(ADDRTYPE_UNSPEC), + "IPv4", '4', I(ADDRTYPE_IPV4), + "IPv6", '6', I(ADDRTYPE_IPV6), + NULL); #endif - { + { const char *label = backend_vt_from_proto(PROT_SSH) ? - "Logical name of remote host (e.g. for SSH key lookup):" : - "Logical name of remote host:"; - s = ctrl_getset(b, "Connection", "identity", - "Logical name of remote host"); - ctrl_editbox(s, label, 'm', 100, - HELPCTX(connection_loghost), - conf_editbox_handler, I(CONF_loghost), I(1)); - } - } + "Logical name of remote host (e.g. for SSH key lookup):" : + "Logical name of remote host:"; + s = ctrl_getset(b, "Connection", "identity", + "Logical name of remote host"); + ctrl_editbox(s, label, 'm', 100, + HELPCTX(connection_loghost), + conf_editbox_handler, I(CONF_loghost), I(1)); + } + } - /* - * A sub-panel Connection/Data, containing options that - * decide on data to send to the server. - */ - if (!midsession) { - ctrl_settitle(b, "Connection/Data", "Data to send to the server"); + /* + * A sub-panel Connection/Data, containing options that + * decide on data to send to the server. + */ + if (!midsession) { + ctrl_settitle(b, "Connection/Data", "Data to send to the server"); - s = ctrl_getset(b, "Connection/Data", "login", - "Login details"); - ctrl_editbox(s, "Auto-login username", 'u', 50, - HELPCTX(connection_username), - conf_editbox_handler, I(CONF_username), I(1)); - { - /* We assume the local username is sufficiently stable - * to include on the dialog box. */ - char *user = get_username(); - char *userlabel = dupprintf("Use system username (%s)", - user ? user : ""); - sfree(user); - ctrl_radiobuttons(s, "When username is not specified:", 'n', 4, - HELPCTX(connection_username_from_env), - conf_radiobutton_bool_handler, - I(CONF_username_from_env), - "Prompt", I(false), - userlabel, I(true), - NULL); - sfree(userlabel); - } + s = ctrl_getset(b, "Connection/Data", "login", + "Login details"); + ctrl_editbox(s, "Auto-login username", 'u', 50, + HELPCTX(connection_username), + conf_editbox_handler, I(CONF_username), I(1)); + { + /* We assume the local username is sufficiently stable + * to include on the dialog box. */ + char *user = get_username(); + char *userlabel = dupprintf("Use system username (%s)", + user ? user : ""); + sfree(user); + ctrl_radiobuttons(s, "When username is not specified:", 'n', 4, + HELPCTX(connection_username_from_env), + conf_radiobutton_bool_handler, + I(CONF_username_from_env), + "Prompt", I(false), + userlabel, I(true), + NULL); + sfree(userlabel); + } - s = ctrl_getset(b, "Connection/Data", "term", - "Terminal details"); - ctrl_editbox(s, "Terminal-type string", 't', 50, - HELPCTX(connection_termtype), - conf_editbox_handler, I(CONF_termtype), I(1)); - ctrl_editbox(s, "Terminal speeds", 's', 50, - HELPCTX(connection_termspeed), - conf_editbox_handler, I(CONF_termspeed), I(1)); + s = ctrl_getset(b, "Connection/Data", "term", + "Terminal details"); + ctrl_editbox(s, "Terminal-type string", 't', 50, + HELPCTX(connection_termtype), + conf_editbox_handler, I(CONF_termtype), I(1)); + ctrl_editbox(s, "Terminal speeds", 's', 50, + HELPCTX(connection_termspeed), + conf_editbox_handler, I(CONF_termspeed), I(1)); - s = ctrl_getset(b, "Connection/Data", "env", - "Environment variables"); - ctrl_columns(s, 2, 80, 20); - ed = (struct environ_data *) - ctrl_alloc(b, sizeof(struct environ_data)); - ed->varbox = ctrl_editbox(s, "Variable", 'v', 60, - HELPCTX(telnet_environ), - environ_handler, P(ed), P(NULL)); - ed->varbox->generic.column = 0; - ed->valbox = ctrl_editbox(s, "Value", 'l', 60, - HELPCTX(telnet_environ), - environ_handler, P(ed), P(NULL)); - ed->valbox->generic.column = 0; - ed->addbutton = ctrl_pushbutton(s, "Add", 'd', - HELPCTX(telnet_environ), - environ_handler, P(ed)); - ed->addbutton->generic.column = 1; - ed->rembutton = ctrl_pushbutton(s, "Remove", 'r', - HELPCTX(telnet_environ), - environ_handler, P(ed)); - ed->rembutton->generic.column = 1; - ctrl_columns(s, 1, 100); - ed->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, - HELPCTX(telnet_environ), - environ_handler, P(ed)); - ed->listbox->listbox.height = 3; - ed->listbox->listbox.ncols = 2; - ed->listbox->listbox.percentages = snewn(2, int); - ed->listbox->listbox.percentages[0] = 30; - ed->listbox->listbox.percentages[1] = 70; - } + s = ctrl_getset(b, "Connection/Data", "env", + "Environment variables"); + ctrl_columns(s, 2, 80, 20); + ed = (struct environ_data *) + ctrl_alloc(b, sizeof(struct environ_data)); + ed->varbox = ctrl_editbox(s, "Variable", 'v', 60, + HELPCTX(telnet_environ), + environ_handler, P(ed), P(NULL)); + ed->varbox->generic.column = 0; + ed->valbox = ctrl_editbox(s, "Value", 'l', 60, + HELPCTX(telnet_environ), + environ_handler, P(ed), P(NULL)); + ed->valbox->generic.column = 0; + ed->addbutton = ctrl_pushbutton(s, "Add", 'd', + HELPCTX(telnet_environ), + environ_handler, P(ed)); + ed->addbutton->generic.column = 1; + ed->rembutton = ctrl_pushbutton(s, "Remove", 'r', + HELPCTX(telnet_environ), + environ_handler, P(ed)); + ed->rembutton->generic.column = 1; + ctrl_columns(s, 1, 100); + ed->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, + HELPCTX(telnet_environ), + environ_handler, P(ed)); + ed->listbox->listbox.height = 3; + ed->listbox->listbox.ncols = 2; + ed->listbox->listbox.percentages = snewn(2, int); + ed->listbox->listbox.percentages[0] = 30; + ed->listbox->listbox.percentages[1] = 70; + } } if (!midsession) { - /* - * The Connection/Proxy panel. - */ - ctrl_settitle(b, "Connection/Proxy", - "Options controlling proxy usage"); + /* + * The Connection/Proxy panel. + */ + ctrl_settitle(b, "Connection/Proxy", + "Options controlling proxy usage"); - s = ctrl_getset(b, "Connection/Proxy", "basics", NULL); - ctrl_radiobuttons(s, "Proxy type:", 't', 3, - HELPCTX(proxy_type), - conf_radiobutton_handler, - I(CONF_proxy_type), - "None", I(PROXY_NONE), - "SOCKS 4", I(PROXY_SOCKS4), - "SOCKS 5", I(PROXY_SOCKS5), - "HTTP", I(PROXY_HTTP), - "Telnet", I(PROXY_TELNET), - NULL); - ctrl_columns(s, 2, 80, 20); - c = ctrl_editbox(s, "Proxy hostname", 'y', 100, - HELPCTX(proxy_main), - conf_editbox_handler, - I(CONF_proxy_host), I(1)); - c->generic.column = 0; - c = ctrl_editbox(s, "Port", 'p', 100, - HELPCTX(proxy_main), - conf_editbox_handler, - I(CONF_proxy_port), - I(-1)); - c->generic.column = 1; - ctrl_columns(s, 1, 100); - ctrl_editbox(s, "Exclude Hosts/IPs", 'e', 100, - HELPCTX(proxy_exclude), - conf_editbox_handler, - I(CONF_proxy_exclude_list), I(1)); - ctrl_checkbox(s, "Consider proxying local host connections", 'x', - HELPCTX(proxy_exclude), - conf_checkbox_handler, - I(CONF_even_proxy_localhost)); - ctrl_radiobuttons(s, "Do DNS name lookup at proxy end:", 'd', 3, - HELPCTX(proxy_dns), - conf_radiobutton_handler, - I(CONF_proxy_dns), - "No", I(FORCE_OFF), - "Auto", I(AUTO), - "Yes", I(FORCE_ON), NULL); - ctrl_editbox(s, "Username", 'u', 60, - HELPCTX(proxy_auth), - conf_editbox_handler, - I(CONF_proxy_username), I(1)); - c = ctrl_editbox(s, "Password", 'w', 60, - HELPCTX(proxy_auth), - conf_editbox_handler, - I(CONF_proxy_password), I(1)); - c->editbox.password = true; - ctrl_editbox(s, "Telnet command", 'm', 100, - HELPCTX(proxy_command), - conf_editbox_handler, - I(CONF_proxy_telnet_command), I(1)); + s = ctrl_getset(b, "Connection/Proxy", "basics", NULL); + ctrl_radiobuttons(s, "Proxy type:", 't', 3, + HELPCTX(proxy_type), + conf_radiobutton_handler, + I(CONF_proxy_type), + "None", I(PROXY_NONE), + "SOCKS 4", I(PROXY_SOCKS4), + "SOCKS 5", I(PROXY_SOCKS5), + "HTTP", I(PROXY_HTTP), + "Telnet", I(PROXY_TELNET), + NULL); + ctrl_columns(s, 2, 80, 20); + c = ctrl_editbox(s, "Proxy hostname", 'y', 100, + HELPCTX(proxy_main), + conf_editbox_handler, + I(CONF_proxy_host), I(1)); + c->generic.column = 0; + c = ctrl_editbox(s, "Port", 'p', 100, + HELPCTX(proxy_main), + conf_editbox_handler, + I(CONF_proxy_port), + I(-1)); + c->generic.column = 1; + ctrl_columns(s, 1, 100); + ctrl_editbox(s, "Exclude Hosts/IPs", 'e', 100, + HELPCTX(proxy_exclude), + conf_editbox_handler, + I(CONF_proxy_exclude_list), I(1)); + ctrl_checkbox(s, "Consider proxying local host connections", 'x', + HELPCTX(proxy_exclude), + conf_checkbox_handler, + I(CONF_even_proxy_localhost)); + ctrl_radiobuttons(s, "Do DNS name lookup at proxy end:", 'd', 3, + HELPCTX(proxy_dns), + conf_radiobutton_handler, + I(CONF_proxy_dns), + "No", I(FORCE_OFF), + "Auto", I(AUTO), + "Yes", I(FORCE_ON), NULL); + ctrl_editbox(s, "Username", 'u', 60, + HELPCTX(proxy_auth), + conf_editbox_handler, + I(CONF_proxy_username), I(1)); + c = ctrl_editbox(s, "Password", 'w', 60, + HELPCTX(proxy_auth), + conf_editbox_handler, + I(CONF_proxy_password), I(1)); + c->editbox.password = true; + ctrl_editbox(s, "Telnet command", 'm', 100, + HELPCTX(proxy_command), + conf_editbox_handler, + I(CONF_proxy_telnet_command), I(1)); - ctrl_radiobuttons(s, "Print proxy diagnostics " + ctrl_radiobuttons(s, "Print proxy diagnostics " "in the terminal window", 'r', 5, - HELPCTX(proxy_logging), - conf_radiobutton_handler, - I(CONF_proxy_log_to_term), - "No", I(FORCE_OFF), - "Yes", I(FORCE_ON), - "Only until session starts", I(AUTO), NULL); + HELPCTX(proxy_logging), + conf_radiobutton_handler, + I(CONF_proxy_log_to_term), + "No", I(FORCE_OFF), + "Yes", I(FORCE_ON), + "Only until session starts", I(AUTO), NULL); } /* @@ -2300,52 +2300,52 @@ void setup_config_box(struct controlbox *b, bool midsession, * mid-session reconfig box _if_ we're using Telnet. */ if (!midsession || protocol == PROT_TELNET) { - /* - * The Connection/Telnet panel. - */ - ctrl_settitle(b, "Connection/Telnet", - "Options controlling Telnet connections"); + /* + * The Connection/Telnet panel. + */ + ctrl_settitle(b, "Connection/Telnet", + "Options controlling Telnet connections"); - s = ctrl_getset(b, "Connection/Telnet", "protocol", - "Telnet protocol adjustments"); + s = ctrl_getset(b, "Connection/Telnet", "protocol", + "Telnet protocol adjustments"); - if (!midsession) { - ctrl_radiobuttons(s, "Handling of OLD_ENVIRON ambiguity:", - NO_SHORTCUT, 2, - HELPCTX(telnet_oldenviron), - conf_radiobutton_bool_handler, - I(CONF_rfc_environ), - "BSD (commonplace)", 'b', I(false), - "RFC 1408 (unusual)", 'f', I(true), NULL); - ctrl_radiobuttons(s, "Telnet negotiation mode:", 't', 2, - HELPCTX(telnet_passive), - conf_radiobutton_bool_handler, - I(CONF_passive_telnet), - "Passive", I(true), "Active", I(false), NULL); - } - ctrl_checkbox(s, "Keyboard sends Telnet special commands", 'k', - HELPCTX(telnet_specialkeys), - conf_checkbox_handler, - I(CONF_telnet_keyboard)); - ctrl_checkbox(s, "Return key sends Telnet New Line instead of ^M", - 'm', HELPCTX(telnet_newline), - conf_checkbox_handler, - I(CONF_telnet_newline)); + if (!midsession) { + ctrl_radiobuttons(s, "Handling of OLD_ENVIRON ambiguity:", + NO_SHORTCUT, 2, + HELPCTX(telnet_oldenviron), + conf_radiobutton_bool_handler, + I(CONF_rfc_environ), + "BSD (commonplace)", 'b', I(false), + "RFC 1408 (unusual)", 'f', I(true), NULL); + ctrl_radiobuttons(s, "Telnet negotiation mode:", 't', 2, + HELPCTX(telnet_passive), + conf_radiobutton_bool_handler, + I(CONF_passive_telnet), + "Passive", I(true), "Active", I(false), NULL); + } + ctrl_checkbox(s, "Keyboard sends Telnet special commands", 'k', + HELPCTX(telnet_specialkeys), + conf_checkbox_handler, + I(CONF_telnet_keyboard)); + ctrl_checkbox(s, "Return key sends Telnet New Line instead of ^M", + 'm', HELPCTX(telnet_newline), + conf_checkbox_handler, + I(CONF_telnet_newline)); } if (!midsession) { - /* - * The Connection/Rlogin panel. - */ - ctrl_settitle(b, "Connection/Rlogin", - "Options controlling Rlogin connections"); + /* + * The Connection/Rlogin panel. + */ + ctrl_settitle(b, "Connection/Rlogin", + "Options controlling Rlogin connections"); - s = ctrl_getset(b, "Connection/Rlogin", "data", - "Data to send to the server"); - ctrl_editbox(s, "Local username:", 'l', 50, - HELPCTX(rlogin_localuser), - conf_editbox_handler, I(CONF_localusername), I(1)); + s = ctrl_getset(b, "Connection/Rlogin", "data", + "Data to send to the server"); + ctrl_editbox(s, "Local username:", 'l', 50, + HELPCTX(rlogin_localuser), + conf_editbox_handler, I(CONF_localusername), I(1)); } @@ -2357,106 +2357,106 @@ void setup_config_box(struct controlbox *b, bool midsession, if (backend_vt_from_proto(PROT_SSH) && (!midsession || protocol == PROT_SSH)) { - /* - * The Connection/SSH panel. - */ - ctrl_settitle(b, "Connection/SSH", - "Options controlling SSH connections"); + /* + * The Connection/SSH panel. + */ + ctrl_settitle(b, "Connection/SSH", + "Options controlling SSH connections"); - /* SSH-1 or connection-sharing downstream */ - if (midsession && (protcfginfo == 1 || protcfginfo == -1)) { - s = ctrl_getset(b, "Connection/SSH", "disclaimer", NULL); - ctrl_text(s, "Nothing on this panel may be reconfigured in mid-" - "session; it is only here so that sub-panels of it can " - "exist without looking strange.", HELPCTX(no_help)); - } + /* SSH-1 or connection-sharing downstream */ + if (midsession && (protcfginfo == 1 || protcfginfo == -1)) { + s = ctrl_getset(b, "Connection/SSH", "disclaimer", NULL); + ctrl_text(s, "Nothing on this panel may be reconfigured in mid-" + "session; it is only here so that sub-panels of it can " + "exist without looking strange.", HELPCTX(no_help)); + } - if (!midsession) { + if (!midsession) { - s = ctrl_getset(b, "Connection/SSH", "data", - "Data to send to the server"); - ctrl_editbox(s, "Remote command:", 'r', 100, - HELPCTX(ssh_command), - conf_editbox_handler, I(CONF_remote_cmd), I(1)); + s = ctrl_getset(b, "Connection/SSH", "data", + "Data to send to the server"); + ctrl_editbox(s, "Remote command:", 'r', 100, + HELPCTX(ssh_command), + conf_editbox_handler, I(CONF_remote_cmd), I(1)); - s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); - ctrl_checkbox(s, "Don't start a shell or command at all", 'n', - HELPCTX(ssh_noshell), - conf_checkbox_handler, - I(CONF_ssh_no_shell)); - } + s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); + ctrl_checkbox(s, "Don't start a shell or command at all", 'n', + HELPCTX(ssh_noshell), + conf_checkbox_handler, + I(CONF_ssh_no_shell)); + } - if (!midsession || !(protcfginfo == 1 || protcfginfo == -1)) { - s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); + if (!midsession || !(protcfginfo == 1 || protcfginfo == -1)) { + s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); - ctrl_checkbox(s, "Enable compression", 'e', - HELPCTX(ssh_compress), - conf_checkbox_handler, - I(CONF_compression)); - } + ctrl_checkbox(s, "Enable compression", 'e', + HELPCTX(ssh_compress), + conf_checkbox_handler, + I(CONF_compression)); + } - if (!midsession) { - s = ctrl_getset(b, "Connection/SSH", "sharing", "Sharing an SSH connection between PuTTY tools"); + if (!midsession) { + s = ctrl_getset(b, "Connection/SSH", "sharing", "Sharing an SSH connection between PuTTY tools"); - ctrl_checkbox(s, "Share SSH connections if possible", 's', - HELPCTX(ssh_share), - conf_checkbox_handler, - I(CONF_ssh_connection_sharing)); + ctrl_checkbox(s, "Share SSH connections if possible", 's', + HELPCTX(ssh_share), + conf_checkbox_handler, + I(CONF_ssh_connection_sharing)); ctrl_text(s, "Permitted roles in a shared connection:", HELPCTX(ssh_share)); - ctrl_checkbox(s, "Upstream (connecting to the real server)", 'u', - HELPCTX(ssh_share), - conf_checkbox_handler, - I(CONF_ssh_connection_sharing_upstream)); - ctrl_checkbox(s, "Downstream (connecting to the upstream PuTTY)", 'd', - HELPCTX(ssh_share), - conf_checkbox_handler, - I(CONF_ssh_connection_sharing_downstream)); - } + ctrl_checkbox(s, "Upstream (connecting to the real server)", 'u', + HELPCTX(ssh_share), + conf_checkbox_handler, + I(CONF_ssh_connection_sharing_upstream)); + ctrl_checkbox(s, "Downstream (connecting to the upstream PuTTY)", 'd', + HELPCTX(ssh_share), + conf_checkbox_handler, + I(CONF_ssh_connection_sharing_downstream)); + } - if (!midsession) { - s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); + if (!midsession) { + s = ctrl_getset(b, "Connection/SSH", "protocol", "Protocol options"); - ctrl_radiobuttons(s, "SSH protocol version:", NO_SHORTCUT, 2, - HELPCTX(ssh_protocol), - conf_radiobutton_handler, - I(CONF_sshprot), - "2", '2', I(3), - "1 (INSECURE)", '1', I(0), NULL); - } + ctrl_radiobuttons(s, "SSH protocol version:", NO_SHORTCUT, 2, + HELPCTX(ssh_protocol), + conf_radiobutton_handler, + I(CONF_sshprot), + "2", '2', I(3), + "1 (INSECURE)", '1', I(0), NULL); + } - /* - * The Connection/SSH/Kex panel. (Owing to repeat key - * exchange, much of this is meaningful in mid-session _if_ - * we're using SSH-2 and are not a connection-sharing - * downstream, or haven't decided yet.) - */ - if (protcfginfo != 1 && protcfginfo != -1) { - ctrl_settitle(b, "Connection/SSH/Kex", - "Options controlling SSH key exchange"); + /* + * The Connection/SSH/Kex panel. (Owing to repeat key + * exchange, much of this is meaningful in mid-session _if_ + * we're using SSH-2 and are not a connection-sharing + * downstream, or haven't decided yet.) + */ + if (protcfginfo != 1 && protcfginfo != -1) { + ctrl_settitle(b, "Connection/SSH/Kex", + "Options controlling SSH key exchange"); - s = ctrl_getset(b, "Connection/SSH/Kex", "main", - "Key exchange algorithm options"); - c = ctrl_draglist(s, "Algorithm selection policy:", 's', - HELPCTX(ssh_kexlist), - kexlist_handler, P(NULL)); + s = ctrl_getset(b, "Connection/SSH/Kex", "main", + "Key exchange algorithm options"); + c = ctrl_draglist(s, "Algorithm selection policy:", 's', + HELPCTX(ssh_kexlist), + kexlist_handler, P(NULL)); c->listbox.height = KEX_MAX; #ifndef NO_GSSAPI - ctrl_checkbox(s, "Attempt GSSAPI key exchange", - 'k', HELPCTX(ssh_gssapi), - conf_checkbox_handler, - I(CONF_try_gssapi_kex)); + ctrl_checkbox(s, "Attempt GSSAPI key exchange", + 'k', HELPCTX(ssh_gssapi), + conf_checkbox_handler, + I(CONF_try_gssapi_kex)); #endif - s = ctrl_getset(b, "Connection/SSH/Kex", "repeat", - "Options controlling key re-exchange"); + s = ctrl_getset(b, "Connection/SSH/Kex", "repeat", + "Options controlling key re-exchange"); - ctrl_editbox(s, "Max minutes before rekey (0 for no limit)", 't', 20, - HELPCTX(ssh_kex_repeat), - conf_editbox_handler, - I(CONF_ssh_rekey_time), - I(-1)); + ctrl_editbox(s, "Max minutes before rekey (0 for no limit)", 't', 20, + HELPCTX(ssh_kex_repeat), + conf_editbox_handler, + I(CONF_ssh_rekey_time), + I(-1)); #ifndef NO_GSSAPI ctrl_editbox(s, "Minutes between GSS checks (0 for never)", NO_SHORTCUT, 20, HELPCTX(ssh_kex_repeat), @@ -2464,38 +2464,38 @@ void setup_config_box(struct controlbox *b, bool midsession, I(CONF_gssapirekey), I(-1)); #endif - ctrl_editbox(s, "Max data before rekey (0 for no limit)", 'x', 20, - HELPCTX(ssh_kex_repeat), - conf_editbox_handler, - I(CONF_ssh_rekey_data), - I(16)); - ctrl_text(s, "(Use 1M for 1 megabyte, 1G for 1 gigabyte etc)", - HELPCTX(ssh_kex_repeat)); - } + ctrl_editbox(s, "Max data before rekey (0 for no limit)", 'x', 20, + HELPCTX(ssh_kex_repeat), + conf_editbox_handler, + I(CONF_ssh_rekey_data), + I(16)); + ctrl_text(s, "(Use 1M for 1 megabyte, 1G for 1 gigabyte etc)", + HELPCTX(ssh_kex_repeat)); + } - /* - * The 'Connection/SSH/Host keys' panel. - */ - if (protcfginfo != 1 && protcfginfo != -1) { - ctrl_settitle(b, "Connection/SSH/Host keys", - "Options controlling SSH host keys"); + /* + * The 'Connection/SSH/Host keys' panel. + */ + if (protcfginfo != 1 && protcfginfo != -1) { + ctrl_settitle(b, "Connection/SSH/Host keys", + "Options controlling SSH host keys"); - s = ctrl_getset(b, "Connection/SSH/Host keys", "main", - "Host key algorithm preference"); - c = ctrl_draglist(s, "Algorithm selection policy:", 's', - HELPCTX(ssh_hklist), - hklist_handler, P(NULL)); - c->listbox.height = 5; - } + s = ctrl_getset(b, "Connection/SSH/Host keys", "main", + "Host key algorithm preference"); + c = ctrl_draglist(s, "Algorithm selection policy:", 's', + HELPCTX(ssh_hklist), + hklist_handler, P(NULL)); + c->listbox.height = 5; + } - /* - * Manual host key configuration is irrelevant mid-session, - * as we enforce that the host key for rekeys is the - * same as that used at the start of the session. - */ - if (!midsession) { - s = ctrl_getset(b, "Connection/SSH/Host keys", "hostkeys", - "Manually configure host keys for this connection"); + /* + * Manual host key configuration is irrelevant mid-session, + * as we enforce that the host key for rekeys is the + * same as that used at the start of the session. + */ + if (!midsession) { + s = ctrl_getset(b, "Connection/SSH/Host keys", "hostkeys", + "Manually configure host keys for this connection"); ctrl_columns(s, 2, 75, 25); c = ctrl_text(s, "Host keys or fingerprints to accept:", @@ -2520,7 +2520,7 @@ void setup_config_box(struct controlbox *b, bool midsession, mh->listbox->listbox.height = 2; mh->listbox->listbox.hscroll = false; ctrl_tabdelay(s, mh->rembutton); - mh->keybox = ctrl_editbox(s, "Key", 'k', 80, + mh->keybox = ctrl_editbox(s, "Key", 'k', 80, HELPCTX(ssh_kex_manual_hostkeys), manual_hostkey_handler, P(mh), P(NULL)); mh->keybox->generic.column = 0; @@ -2529,336 +2529,336 @@ void setup_config_box(struct controlbox *b, bool midsession, manual_hostkey_handler, P(mh)); mh->addbutton->generic.column = 1; ctrl_columns(s, 1, 100); - } + } - if (!midsession || !(protcfginfo == 1 || protcfginfo == -1)) { - /* - * The Connection/SSH/Cipher panel. - */ - ctrl_settitle(b, "Connection/SSH/Cipher", - "Options controlling SSH encryption"); + if (!midsession || !(protcfginfo == 1 || protcfginfo == -1)) { + /* + * The Connection/SSH/Cipher panel. + */ + ctrl_settitle(b, "Connection/SSH/Cipher", + "Options controlling SSH encryption"); - s = ctrl_getset(b, "Connection/SSH/Cipher", + s = ctrl_getset(b, "Connection/SSH/Cipher", "encryption", "Encryption options"); - c = ctrl_draglist(s, "Encryption cipher selection policy:", 's', - HELPCTX(ssh_ciphers), - cipherlist_handler, P(NULL)); - c->listbox.height = 6; + c = ctrl_draglist(s, "Encryption cipher selection policy:", 's', + HELPCTX(ssh_ciphers), + cipherlist_handler, P(NULL)); + c->listbox.height = 6; - ctrl_checkbox(s, "Enable legacy use of single-DES in SSH-2", 'i', - HELPCTX(ssh_ciphers), - conf_checkbox_handler, - I(CONF_ssh2_des_cbc)); - } + ctrl_checkbox(s, "Enable legacy use of single-DES in SSH-2", 'i', + HELPCTX(ssh_ciphers), + conf_checkbox_handler, + I(CONF_ssh2_des_cbc)); + } - if (!midsession) { + if (!midsession) { - /* - * The Connection/SSH/Auth panel. - */ - ctrl_settitle(b, "Connection/SSH/Auth", - "Options controlling SSH authentication"); + /* + * The Connection/SSH/Auth panel. + */ + ctrl_settitle(b, "Connection/SSH/Auth", + "Options controlling SSH authentication"); - s = ctrl_getset(b, "Connection/SSH/Auth", "main", NULL); - ctrl_checkbox(s, "Display pre-authentication banner (SSH-2 only)", - 'd', HELPCTX(ssh_auth_banner), - conf_checkbox_handler, - I(CONF_ssh_show_banner)); - ctrl_checkbox(s, "Bypass authentication entirely (SSH-2 only)", 'b', - HELPCTX(ssh_auth_bypass), - conf_checkbox_handler, - I(CONF_ssh_no_userauth)); + s = ctrl_getset(b, "Connection/SSH/Auth", "main", NULL); + ctrl_checkbox(s, "Display pre-authentication banner (SSH-2 only)", + 'd', HELPCTX(ssh_auth_banner), + conf_checkbox_handler, + I(CONF_ssh_show_banner)); + ctrl_checkbox(s, "Bypass authentication entirely (SSH-2 only)", 'b', + HELPCTX(ssh_auth_bypass), + conf_checkbox_handler, + I(CONF_ssh_no_userauth)); - s = ctrl_getset(b, "Connection/SSH/Auth", "methods", - "Authentication methods"); - ctrl_checkbox(s, "Attempt authentication using Pageant", 'p', - HELPCTX(ssh_auth_pageant), - conf_checkbox_handler, - I(CONF_tryagent)); - ctrl_checkbox(s, "Attempt TIS or CryptoCard auth (SSH-1)", 'm', - HELPCTX(ssh_auth_tis), - conf_checkbox_handler, - I(CONF_try_tis_auth)); - ctrl_checkbox(s, "Attempt \"keyboard-interactive\" auth (SSH-2)", - 'i', HELPCTX(ssh_auth_ki), - conf_checkbox_handler, - I(CONF_try_ki_auth)); + s = ctrl_getset(b, "Connection/SSH/Auth", "methods", + "Authentication methods"); + ctrl_checkbox(s, "Attempt authentication using Pageant", 'p', + HELPCTX(ssh_auth_pageant), + conf_checkbox_handler, + I(CONF_tryagent)); + ctrl_checkbox(s, "Attempt TIS or CryptoCard auth (SSH-1)", 'm', + HELPCTX(ssh_auth_tis), + conf_checkbox_handler, + I(CONF_try_tis_auth)); + ctrl_checkbox(s, "Attempt \"keyboard-interactive\" auth (SSH-2)", + 'i', HELPCTX(ssh_auth_ki), + conf_checkbox_handler, + I(CONF_try_ki_auth)); - s = ctrl_getset(b, "Connection/SSH/Auth", "params", - "Authentication parameters"); - ctrl_checkbox(s, "Allow agent forwarding", 'f', - HELPCTX(ssh_auth_agentfwd), - conf_checkbox_handler, I(CONF_agentfwd)); - ctrl_checkbox(s, "Allow attempted changes of username in SSH-2", NO_SHORTCUT, - HELPCTX(ssh_auth_changeuser), - conf_checkbox_handler, - I(CONF_change_username)); - ctrl_filesel(s, "Private key file for authentication:", 'k', - FILTER_KEY_FILES, false, "Select private key file", - HELPCTX(ssh_auth_privkey), - conf_filesel_handler, I(CONF_keyfile)); + s = ctrl_getset(b, "Connection/SSH/Auth", "params", + "Authentication parameters"); + ctrl_checkbox(s, "Allow agent forwarding", 'f', + HELPCTX(ssh_auth_agentfwd), + conf_checkbox_handler, I(CONF_agentfwd)); + ctrl_checkbox(s, "Allow attempted changes of username in SSH-2", NO_SHORTCUT, + HELPCTX(ssh_auth_changeuser), + conf_checkbox_handler, + I(CONF_change_username)); + ctrl_filesel(s, "Private key file for authentication:", 'k', + FILTER_KEY_FILES, false, "Select private key file", + HELPCTX(ssh_auth_privkey), + conf_filesel_handler, I(CONF_keyfile)); #ifndef NO_GSSAPI - /* - * Connection/SSH/Auth/GSSAPI, which sadly won't fit on - * the main Auth panel. - */ - ctrl_settitle(b, "Connection/SSH/Auth/GSSAPI", - "Options controlling GSSAPI authentication"); - s = ctrl_getset(b, "Connection/SSH/Auth/GSSAPI", "gssapi", NULL); + /* + * Connection/SSH/Auth/GSSAPI, which sadly won't fit on + * the main Auth panel. + */ + ctrl_settitle(b, "Connection/SSH/Auth/GSSAPI", + "Options controlling GSSAPI authentication"); + s = ctrl_getset(b, "Connection/SSH/Auth/GSSAPI", "gssapi", NULL); - ctrl_checkbox(s, "Attempt GSSAPI authentication (SSH-2 only)", - 't', HELPCTX(ssh_gssapi), - conf_checkbox_handler, - I(CONF_try_gssapi_auth)); + ctrl_checkbox(s, "Attempt GSSAPI authentication (SSH-2 only)", + 't', HELPCTX(ssh_gssapi), + conf_checkbox_handler, + I(CONF_try_gssapi_auth)); - ctrl_checkbox(s, "Attempt GSSAPI key exchange (SSH-2 only)", - 'k', HELPCTX(ssh_gssapi), - conf_checkbox_handler, - I(CONF_try_gssapi_kex)); + ctrl_checkbox(s, "Attempt GSSAPI key exchange (SSH-2 only)", + 'k', HELPCTX(ssh_gssapi), + conf_checkbox_handler, + I(CONF_try_gssapi_kex)); - ctrl_checkbox(s, "Allow GSSAPI credential delegation", 'l', - HELPCTX(ssh_gssapi_delegation), - conf_checkbox_handler, - I(CONF_gssapifwd)); + ctrl_checkbox(s, "Allow GSSAPI credential delegation", 'l', + HELPCTX(ssh_gssapi_delegation), + conf_checkbox_handler, + I(CONF_gssapifwd)); - /* - * GSSAPI library selection. - */ - if (ngsslibs > 1) { - c = ctrl_draglist(s, "Preference order for GSSAPI libraries:", - 'p', HELPCTX(ssh_gssapi_libraries), - gsslist_handler, P(NULL)); - c->listbox.height = ngsslibs; + /* + * GSSAPI library selection. + */ + if (ngsslibs > 1) { + c = ctrl_draglist(s, "Preference order for GSSAPI libraries:", + 'p', HELPCTX(ssh_gssapi_libraries), + gsslist_handler, P(NULL)); + c->listbox.height = ngsslibs; - /* - * I currently assume that if more than one GSS - * library option is available, then one of them is - * 'user-supplied' and so we should present the - * following file selector. This is at least half- - * reasonable, because if we're using statically - * linked GSSAPI then there will only be one option - * and no way to load from a user-supplied library, - * whereas if we're using dynamic libraries then - * there will almost certainly be some default - * option in addition to a user-supplied path. If - * anyone ever ports PuTTY to a system on which - * dynamic-library GSSAPI is available but there is - * absolutely no consensus on where to keep the - * libraries, there'll need to be a flag alongside - * ngsslibs to control whether the file selector is - * displayed. - */ + /* + * I currently assume that if more than one GSS + * library option is available, then one of them is + * 'user-supplied' and so we should present the + * following file selector. This is at least half- + * reasonable, because if we're using statically + * linked GSSAPI then there will only be one option + * and no way to load from a user-supplied library, + * whereas if we're using dynamic libraries then + * there will almost certainly be some default + * option in addition to a user-supplied path. If + * anyone ever ports PuTTY to a system on which + * dynamic-library GSSAPI is available but there is + * absolutely no consensus on where to keep the + * libraries, there'll need to be a flag alongside + * ngsslibs to control whether the file selector is + * displayed. + */ - ctrl_filesel(s, "User-supplied GSSAPI library path:", 's', - FILTER_DYNLIB_FILES, false, "Select library file", - HELPCTX(ssh_gssapi_libraries), - conf_filesel_handler, - I(CONF_ssh_gss_custom)); - } + ctrl_filesel(s, "User-supplied GSSAPI library path:", 's', + FILTER_DYNLIB_FILES, false, "Select library file", + HELPCTX(ssh_gssapi_libraries), + conf_filesel_handler, + I(CONF_ssh_gss_custom)); + } #endif - } + } - if (!midsession) { - /* - * The Connection/SSH/TTY panel. - */ - ctrl_settitle(b, "Connection/SSH/TTY", "Remote terminal settings"); + if (!midsession) { + /* + * The Connection/SSH/TTY panel. + */ + ctrl_settitle(b, "Connection/SSH/TTY", "Remote terminal settings"); - s = ctrl_getset(b, "Connection/SSH/TTY", "sshtty", NULL); - ctrl_checkbox(s, "Don't allocate a pseudo-terminal", 'p', - HELPCTX(ssh_nopty), - conf_checkbox_handler, - I(CONF_nopty)); + s = ctrl_getset(b, "Connection/SSH/TTY", "sshtty", NULL); + ctrl_checkbox(s, "Don't allocate a pseudo-terminal", 'p', + HELPCTX(ssh_nopty), + conf_checkbox_handler, + I(CONF_nopty)); - s = ctrl_getset(b, "Connection/SSH/TTY", "ttymodes", - "Terminal modes"); - td = (struct ttymodes_data *) - ctrl_alloc(b, sizeof(struct ttymodes_data)); - ctrl_text(s, "Terminal modes to send:", HELPCTX(ssh_ttymodes)); - td->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, - HELPCTX(ssh_ttymodes), - ttymodes_handler, P(td)); - td->listbox->listbox.height = 8; - td->listbox->listbox.ncols = 2; - td->listbox->listbox.percentages = snewn(2, int); - td->listbox->listbox.percentages[0] = 40; - td->listbox->listbox.percentages[1] = 60; - ctrl_columns(s, 2, 75, 25); - c = ctrl_text(s, "For selected mode, send:", HELPCTX(ssh_ttymodes)); - c->generic.column = 0; - td->setbutton = ctrl_pushbutton(s, "Set", 's', - HELPCTX(ssh_ttymodes), - ttymodes_handler, P(td)); - td->setbutton->generic.column = 1; - td->setbutton->generic.tabdelay = true; - ctrl_columns(s, 1, 100); /* column break */ - /* Bit of a hack to get the value radio buttons and - * edit-box on the same row. */ - ctrl_columns(s, 2, 75, 25); - td->valradio = ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, - HELPCTX(ssh_ttymodes), - ttymodes_handler, P(td), - "Auto", NO_SHORTCUT, P(NULL), - "Nothing", NO_SHORTCUT, P(NULL), - "This:", NO_SHORTCUT, P(NULL), - NULL); - td->valradio->generic.column = 0; - td->valbox = ctrl_editbox(s, NULL, NO_SHORTCUT, 100, - HELPCTX(ssh_ttymodes), - ttymodes_handler, P(td), P(NULL)); - td->valbox->generic.column = 1; - ctrl_tabdelay(s, td->setbutton); - } + s = ctrl_getset(b, "Connection/SSH/TTY", "ttymodes", + "Terminal modes"); + td = (struct ttymodes_data *) + ctrl_alloc(b, sizeof(struct ttymodes_data)); + ctrl_text(s, "Terminal modes to send:", HELPCTX(ssh_ttymodes)); + td->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, + HELPCTX(ssh_ttymodes), + ttymodes_handler, P(td)); + td->listbox->listbox.height = 8; + td->listbox->listbox.ncols = 2; + td->listbox->listbox.percentages = snewn(2, int); + td->listbox->listbox.percentages[0] = 40; + td->listbox->listbox.percentages[1] = 60; + ctrl_columns(s, 2, 75, 25); + c = ctrl_text(s, "For selected mode, send:", HELPCTX(ssh_ttymodes)); + c->generic.column = 0; + td->setbutton = ctrl_pushbutton(s, "Set", 's', + HELPCTX(ssh_ttymodes), + ttymodes_handler, P(td)); + td->setbutton->generic.column = 1; + td->setbutton->generic.tabdelay = true; + ctrl_columns(s, 1, 100); /* column break */ + /* Bit of a hack to get the value radio buttons and + * edit-box on the same row. */ + ctrl_columns(s, 2, 75, 25); + td->valradio = ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, + HELPCTX(ssh_ttymodes), + ttymodes_handler, P(td), + "Auto", NO_SHORTCUT, P(NULL), + "Nothing", NO_SHORTCUT, P(NULL), + "This:", NO_SHORTCUT, P(NULL), + NULL); + td->valradio->generic.column = 0; + td->valbox = ctrl_editbox(s, NULL, NO_SHORTCUT, 100, + HELPCTX(ssh_ttymodes), + ttymodes_handler, P(td), P(NULL)); + td->valbox->generic.column = 1; + ctrl_tabdelay(s, td->setbutton); + } - if (!midsession) { - /* - * The Connection/SSH/X11 panel. - */ - ctrl_settitle(b, "Connection/SSH/X11", - "Options controlling SSH X11 forwarding"); + if (!midsession) { + /* + * The Connection/SSH/X11 panel. + */ + ctrl_settitle(b, "Connection/SSH/X11", + "Options controlling SSH X11 forwarding"); - s = ctrl_getset(b, "Connection/SSH/X11", "x11", "X11 forwarding"); - ctrl_checkbox(s, "Enable X11 forwarding", 'e', - HELPCTX(ssh_tunnels_x11), - conf_checkbox_handler,I(CONF_x11_forward)); - ctrl_editbox(s, "X display location", 'x', 50, - HELPCTX(ssh_tunnels_x11), - conf_editbox_handler, I(CONF_x11_display), I(1)); - ctrl_radiobuttons(s, "Remote X11 authentication protocol", 'u', 2, - HELPCTX(ssh_tunnels_x11auth), - conf_radiobutton_handler, - I(CONF_x11_auth), - "MIT-Magic-Cookie-1", I(X11_MIT), - "XDM-Authorization-1", I(X11_XDM), NULL); - } + s = ctrl_getset(b, "Connection/SSH/X11", "x11", "X11 forwarding"); + ctrl_checkbox(s, "Enable X11 forwarding", 'e', + HELPCTX(ssh_tunnels_x11), + conf_checkbox_handler,I(CONF_x11_forward)); + ctrl_editbox(s, "X display location", 'x', 50, + HELPCTX(ssh_tunnels_x11), + conf_editbox_handler, I(CONF_x11_display), I(1)); + ctrl_radiobuttons(s, "Remote X11 authentication protocol", 'u', 2, + HELPCTX(ssh_tunnels_x11auth), + conf_radiobutton_handler, + I(CONF_x11_auth), + "MIT-Magic-Cookie-1", I(X11_MIT), + "XDM-Authorization-1", I(X11_XDM), NULL); + } - /* - * The Tunnels panel _is_ still available in mid-session. - */ - ctrl_settitle(b, "Connection/SSH/Tunnels", - "Options controlling SSH port forwarding"); + /* + * The Tunnels panel _is_ still available in mid-session. + */ + ctrl_settitle(b, "Connection/SSH/Tunnels", + "Options controlling SSH port forwarding"); - s = ctrl_getset(b, "Connection/SSH/Tunnels", "portfwd", - "Port forwarding"); - ctrl_checkbox(s, "Local ports accept connections from other hosts",'t', - HELPCTX(ssh_tunnels_portfwd_localhost), - conf_checkbox_handler, - I(CONF_lport_acceptall)); - ctrl_checkbox(s, "Remote ports do the same (SSH-2 only)", 'p', - HELPCTX(ssh_tunnels_portfwd_localhost), - conf_checkbox_handler, - I(CONF_rport_acceptall)); + s = ctrl_getset(b, "Connection/SSH/Tunnels", "portfwd", + "Port forwarding"); + ctrl_checkbox(s, "Local ports accept connections from other hosts",'t', + HELPCTX(ssh_tunnels_portfwd_localhost), + conf_checkbox_handler, + I(CONF_lport_acceptall)); + ctrl_checkbox(s, "Remote ports do the same (SSH-2 only)", 'p', + HELPCTX(ssh_tunnels_portfwd_localhost), + conf_checkbox_handler, + I(CONF_rport_acceptall)); - ctrl_columns(s, 3, 55, 20, 25); - c = ctrl_text(s, "Forwarded ports:", HELPCTX(ssh_tunnels_portfwd)); - c->generic.column = COLUMN_FIELD(0,2); - /* You want to select from the list, _then_ hit Remove. So tab order - * should be that way round. */ - pfd = (struct portfwd_data *)ctrl_alloc(b,sizeof(struct portfwd_data)); - pfd->rembutton = ctrl_pushbutton(s, "Remove", 'r', - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd)); - pfd->rembutton->generic.column = 2; - pfd->rembutton->generic.tabdelay = true; - pfd->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd)); - pfd->listbox->listbox.height = 3; - pfd->listbox->listbox.ncols = 2; - pfd->listbox->listbox.percentages = snewn(2, int); - pfd->listbox->listbox.percentages[0] = 20; - pfd->listbox->listbox.percentages[1] = 80; - ctrl_tabdelay(s, pfd->rembutton); - ctrl_text(s, "Add new forwarded port:", HELPCTX(ssh_tunnels_portfwd)); - /* You want to enter source, destination and type, _then_ hit Add. - * Again, we adjust the tab order to reflect this. */ - pfd->addbutton = ctrl_pushbutton(s, "Add", 'd', - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd)); - pfd->addbutton->generic.column = 2; - pfd->addbutton->generic.tabdelay = true; - pfd->sourcebox = ctrl_editbox(s, "Source port", 's', 40, - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd), P(NULL)); - pfd->sourcebox->generic.column = 0; - pfd->destbox = ctrl_editbox(s, "Destination", 'i', 67, - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd), P(NULL)); - pfd->direction = ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, - HELPCTX(ssh_tunnels_portfwd), - portfwd_handler, P(pfd), - "Local", 'l', P(NULL), - "Remote", 'm', P(NULL), - "Dynamic", 'y', P(NULL), - NULL); + ctrl_columns(s, 3, 55, 20, 25); + c = ctrl_text(s, "Forwarded ports:", HELPCTX(ssh_tunnels_portfwd)); + c->generic.column = COLUMN_FIELD(0,2); + /* You want to select from the list, _then_ hit Remove. So tab order + * should be that way round. */ + pfd = (struct portfwd_data *)ctrl_alloc(b,sizeof(struct portfwd_data)); + pfd->rembutton = ctrl_pushbutton(s, "Remove", 'r', + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd)); + pfd->rembutton->generic.column = 2; + pfd->rembutton->generic.tabdelay = true; + pfd->listbox = ctrl_listbox(s, NULL, NO_SHORTCUT, + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd)); + pfd->listbox->listbox.height = 3; + pfd->listbox->listbox.ncols = 2; + pfd->listbox->listbox.percentages = snewn(2, int); + pfd->listbox->listbox.percentages[0] = 20; + pfd->listbox->listbox.percentages[1] = 80; + ctrl_tabdelay(s, pfd->rembutton); + ctrl_text(s, "Add new forwarded port:", HELPCTX(ssh_tunnels_portfwd)); + /* You want to enter source, destination and type, _then_ hit Add. + * Again, we adjust the tab order to reflect this. */ + pfd->addbutton = ctrl_pushbutton(s, "Add", 'd', + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd)); + pfd->addbutton->generic.column = 2; + pfd->addbutton->generic.tabdelay = true; + pfd->sourcebox = ctrl_editbox(s, "Source port", 's', 40, + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd), P(NULL)); + pfd->sourcebox->generic.column = 0; + pfd->destbox = ctrl_editbox(s, "Destination", 'i', 67, + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd), P(NULL)); + pfd->direction = ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, + HELPCTX(ssh_tunnels_portfwd), + portfwd_handler, P(pfd), + "Local", 'l', P(NULL), + "Remote", 'm', P(NULL), + "Dynamic", 'y', P(NULL), + NULL); #ifndef NO_IPV6 - pfd->addressfamily = - ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, - HELPCTX(ssh_tunnels_portfwd_ipversion), - portfwd_handler, P(pfd), - "Auto", 'u', I(ADDRTYPE_UNSPEC), - "IPv4", '4', I(ADDRTYPE_IPV4), - "IPv6", '6', I(ADDRTYPE_IPV6), - NULL); + pfd->addressfamily = + ctrl_radiobuttons(s, NULL, NO_SHORTCUT, 3, + HELPCTX(ssh_tunnels_portfwd_ipversion), + portfwd_handler, P(pfd), + "Auto", 'u', I(ADDRTYPE_UNSPEC), + "IPv4", '4', I(ADDRTYPE_IPV4), + "IPv6", '6', I(ADDRTYPE_IPV6), + NULL); #endif - ctrl_tabdelay(s, pfd->addbutton); - ctrl_columns(s, 1, 100); + ctrl_tabdelay(s, pfd->addbutton); + ctrl_columns(s, 1, 100); - if (!midsession) { - /* - * The Connection/SSH/Bugs panels. - */ - ctrl_settitle(b, "Connection/SSH/Bugs", - "Workarounds for SSH server bugs"); + if (!midsession) { + /* + * The Connection/SSH/Bugs panels. + */ + ctrl_settitle(b, "Connection/SSH/Bugs", + "Workarounds for SSH server bugs"); - s = ctrl_getset(b, "Connection/SSH/Bugs", "main", - "Detection of known bugs in SSH servers"); - ctrl_droplist(s, "Chokes on SSH-2 ignore messages", '2', 20, - HELPCTX(ssh_bugs_ignore2), - sshbug_handler, I(CONF_sshbug_ignore2)); - ctrl_droplist(s, "Handles SSH-2 key re-exchange badly", 'k', 20, - HELPCTX(ssh_bugs_rekey2), - sshbug_handler, I(CONF_sshbug_rekey2)); - ctrl_droplist(s, "Chokes on PuTTY's SSH-2 'winadj' requests", 'j', + s = ctrl_getset(b, "Connection/SSH/Bugs", "main", + "Detection of known bugs in SSH servers"); + ctrl_droplist(s, "Chokes on SSH-2 ignore messages", '2', 20, + HELPCTX(ssh_bugs_ignore2), + sshbug_handler, I(CONF_sshbug_ignore2)); + ctrl_droplist(s, "Handles SSH-2 key re-exchange badly", 'k', 20, + HELPCTX(ssh_bugs_rekey2), + sshbug_handler, I(CONF_sshbug_rekey2)); + ctrl_droplist(s, "Chokes on PuTTY's SSH-2 'winadj' requests", 'j', 20, HELPCTX(ssh_bugs_winadj), - sshbug_handler, I(CONF_sshbug_winadj)); - ctrl_droplist(s, "Replies to requests on closed channels", 'q', 20, - HELPCTX(ssh_bugs_chanreq), - sshbug_handler, I(CONF_sshbug_chanreq)); - ctrl_droplist(s, "Ignores SSH-2 maximum packet size", 'x', 20, - HELPCTX(ssh_bugs_maxpkt2), - sshbug_handler, I(CONF_sshbug_maxpkt2)); + sshbug_handler, I(CONF_sshbug_winadj)); + ctrl_droplist(s, "Replies to requests on closed channels", 'q', 20, + HELPCTX(ssh_bugs_chanreq), + sshbug_handler, I(CONF_sshbug_chanreq)); + ctrl_droplist(s, "Ignores SSH-2 maximum packet size", 'x', 20, + HELPCTX(ssh_bugs_maxpkt2), + sshbug_handler, I(CONF_sshbug_maxpkt2)); - ctrl_settitle(b, "Connection/SSH/More bugs", - "Further workarounds for SSH server bugs"); + ctrl_settitle(b, "Connection/SSH/More bugs", + "Further workarounds for SSH server bugs"); - s = ctrl_getset(b, "Connection/SSH/More bugs", "main", - "Detection of known bugs in SSH servers"); - ctrl_droplist(s, "Requires padding on SSH-2 RSA signatures", 'p', 20, - HELPCTX(ssh_bugs_rsapad2), - sshbug_handler, I(CONF_sshbug_rsapad2)); - ctrl_droplist(s, "Only supports pre-RFC4419 SSH-2 DH GEX", 'd', 20, - HELPCTX(ssh_bugs_oldgex2), - sshbug_handler, I(CONF_sshbug_oldgex2)); - ctrl_droplist(s, "Miscomputes SSH-2 HMAC keys", 'm', 20, - HELPCTX(ssh_bugs_hmac2), - sshbug_handler, I(CONF_sshbug_hmac2)); - ctrl_droplist(s, "Misuses the session ID in SSH-2 PK auth", 'n', 20, - HELPCTX(ssh_bugs_pksessid2), - sshbug_handler, I(CONF_sshbug_pksessid2)); - ctrl_droplist(s, "Miscomputes SSH-2 encryption keys", 'e', 20, - HELPCTX(ssh_bugs_derivekey2), - sshbug_handler, I(CONF_sshbug_derivekey2)); - ctrl_droplist(s, "Chokes on SSH-1 ignore messages", 'i', 20, - HELPCTX(ssh_bugs_ignore1), - sshbug_handler, I(CONF_sshbug_ignore1)); - ctrl_droplist(s, "Refuses all SSH-1 password camouflage", 's', 20, - HELPCTX(ssh_bugs_plainpw1), - sshbug_handler, I(CONF_sshbug_plainpw1)); - ctrl_droplist(s, "Chokes on SSH-1 RSA authentication", 'r', 20, - HELPCTX(ssh_bugs_rsa1), - sshbug_handler, I(CONF_sshbug_rsa1)); - } + s = ctrl_getset(b, "Connection/SSH/More bugs", "main", + "Detection of known bugs in SSH servers"); + ctrl_droplist(s, "Requires padding on SSH-2 RSA signatures", 'p', 20, + HELPCTX(ssh_bugs_rsapad2), + sshbug_handler, I(CONF_sshbug_rsapad2)); + ctrl_droplist(s, "Only supports pre-RFC4419 SSH-2 DH GEX", 'd', 20, + HELPCTX(ssh_bugs_oldgex2), + sshbug_handler, I(CONF_sshbug_oldgex2)); + ctrl_droplist(s, "Miscomputes SSH-2 HMAC keys", 'm', 20, + HELPCTX(ssh_bugs_hmac2), + sshbug_handler, I(CONF_sshbug_hmac2)); + ctrl_droplist(s, "Misuses the session ID in SSH-2 PK auth", 'n', 20, + HELPCTX(ssh_bugs_pksessid2), + sshbug_handler, I(CONF_sshbug_pksessid2)); + ctrl_droplist(s, "Miscomputes SSH-2 encryption keys", 'e', 20, + HELPCTX(ssh_bugs_derivekey2), + sshbug_handler, I(CONF_sshbug_derivekey2)); + ctrl_droplist(s, "Chokes on SSH-1 ignore messages", 'i', 20, + HELPCTX(ssh_bugs_ignore1), + sshbug_handler, I(CONF_sshbug_ignore1)); + ctrl_droplist(s, "Refuses all SSH-1 password camouflage", 's', 20, + HELPCTX(ssh_bugs_plainpw1), + sshbug_handler, I(CONF_sshbug_plainpw1)); + ctrl_droplist(s, "Chokes on SSH-1 RSA authentication", 'r', 20, + HELPCTX(ssh_bugs_rsa1), + sshbug_handler, I(CONF_sshbug_rsa1)); + } } } diff --git a/contrib/cygtermd/main.c b/contrib/cygtermd/main.c index 154c4315..7bfd49f0 100644 --- a/contrib/cygtermd/main.c +++ b/contrib/cygtermd/main.c @@ -47,12 +47,12 @@ void fatal(const char *fmt, ...) void net_readdata(sel_rfd *rfd, void *data, size_t len) { if (len == 0) - exit(0); /* EOF on network - client went away */ + exit(0); /* EOF on network - client went away */ telnet_from_net(telnet, data, len); if (sel_write(netw, NULL, 0) > BUF) - sel_rfd_freeze(ptyr); + sel_rfd_freeze(ptyr); if (sel_write(ptyw, NULL, 0) > BUF) - sel_rfd_freeze(netr); + sel_rfd_freeze(netr); } void net_readerr(sel_rfd *rfd, int error) @@ -64,7 +64,7 @@ void net_readerr(sel_rfd *rfd, int error) void net_written(sel_wfd *wfd, size_t bufsize) { if (bufsize < BUF) - sel_rfd_unfreeze(ptyr); + sel_rfd_unfreeze(ptyr); } void net_writeerr(sel_wfd *wfd, int error) @@ -76,18 +76,18 @@ void net_writeerr(sel_wfd *wfd, int error) void pty_readdata(sel_rfd *rfd, void *data, size_t len) { if (len == 0) - exit(0); /* EOF on pty */ + exit(0); /* EOF on pty */ telnet_from_pty(telnet, data, len); if (sel_write(netw, NULL, 0) > BUF) - sel_rfd_freeze(ptyr); + sel_rfd_freeze(ptyr); if (sel_write(ptyw, NULL, 0) > BUF) - sel_rfd_freeze(netr); + sel_rfd_freeze(netr); } void pty_readerr(sel_rfd *rfd, int error) { - if (error == EIO) /* means EOF, on a pty */ - exit(0); + if (error == EIO) /* means EOF, on a pty */ + exit(0); fprintf(stderr, "pty: read: %s\n", strerror(errno)); exit(1); } @@ -95,7 +95,7 @@ void pty_readerr(sel_rfd *rfd, int error) void pty_written(sel_wfd *wfd, size_t bufsize) { if (bufsize < BUF) - sel_rfd_unfreeze(netr); + sel_rfd_unfreeze(netr); } void pty_writeerr(sel_wfd *wfd, int error) @@ -109,12 +109,12 @@ void sig_readdata(sel_rfd *rfd, void *data, size_t len) char *p = data; while (len > 0) { - if (*p == 'C') { - int status; - waitpid(-1, &status, WNOHANG); - if (WIFEXITED(status) || WIFSIGNALED(status)) - exit(0); /* child process vanished */ - } + if (*p == 'C') { + int status; + waitpid(-1, &status, WNOHANG); + if (WIFEXITED(status) || WIFSIGNALED(status)) + exit(0); /* child process vanished */ + } } } @@ -150,24 +150,24 @@ int main(int argc, char **argv) telnet = telnet_new(netw, ptyw); if (pipe(signalpipe) < 0) { - perror("pipe"); - return 1; + perror("pipe"); + return 1; } sigr = sel_rfd_add(asel, signalpipe[0], sig_readdata, - sig_readerr, NULL); + sig_readerr, NULL); signal(SIGCHLD, sigchld); do { - struct shell_data shdata; + struct shell_data shdata; - ret = sel_iterate(asel, -1); - if (!shell_started && telnet_shell_ok(telnet, &shdata)) { - ptyfd = run_program_in_pty(&shdata, directory, program_args); - sel_rfd_setfd(ptyr, ptyfd); - sel_wfd_setfd(ptyw, ptyfd); - shell_started = 1; - } + ret = sel_iterate(asel, -1); + if (!shell_started && telnet_shell_ok(telnet, &shdata)) { + ptyfd = run_program_in_pty(&shdata, directory, program_args); + sel_rfd_setfd(ptyr, ptyfd); + sel_wfd_setfd(ptyw, ptyfd); + shell_started = 1; + } } while (ret == 0); return 0; diff --git a/contrib/cygtermd/malloc.c b/contrib/cygtermd/malloc.c index 5c5b94eb..6bad344e 100644 --- a/contrib/cygtermd/malloc.c +++ b/contrib/cygtermd/malloc.c @@ -13,26 +13,26 @@ void *smalloc(size_t size) { void *p; p = malloc(size); if (!p) { - fatal("out of memory"); + fatal("out of memory"); } return p; } void sfree(void *p) { if (p) { - free(p); + free(p); } } void *srealloc(void *p, size_t size) { void *q; if (p) { - q = realloc(p, size); + q = realloc(p, size); } else { - q = malloc(size); + q = malloc(size); } if (!q) - fatal("out of memory"); + fatal("out of memory"); return q; } diff --git a/contrib/cygtermd/pty.c b/contrib/cygtermd/pty.c index 6080ecfb..9ae1e48f 100644 --- a/contrib/cygtermd/pty.c +++ b/contrib/cygtermd/pty.c @@ -30,18 +30,18 @@ void pty_preinit(void) */ master = open("/dev/ptmx", O_RDWR); if (master < 0) { - perror("/dev/ptmx: open"); - exit(1); + perror("/dev/ptmx: open"); + exit(1); } if (grantpt(master) < 0) { - perror("grantpt"); - exit(1); + perror("grantpt"); + exit(1); } - + if (unlockpt(master) < 0) { - perror("unlockpt"); - exit(1); + perror("unlockpt"); + exit(1); } } @@ -70,24 +70,24 @@ int run_program_in_pty(const struct shell_data *shdata, #if 0 { - struct winsize ws; - struct termios ts; + struct winsize ws; + struct termios ts; - /* - * FIXME: think up some good defaults here - */ + /* + * FIXME: think up some good defaults here + */ - if (!ioctl(0, TIOCGWINSZ, &ws)) - ioctl(master, TIOCSWINSZ, &ws); - if (!tcgetattr(0, &ts)) - tcsetattr(master, TCSANOW, &ts); + if (!ioctl(0, TIOCGWINSZ, &ws)) + ioctl(master, TIOCSWINSZ, &ws); + if (!tcgetattr(0, &ts)) + tcsetattr(master, TCSANOW, &ts); } #endif slave = open(ptyname, O_RDWR | O_NOCTTY); if (slave < 0) { - perror("slave pty: open"); - return 1; + perror("slave pty: open"); + return 1; } /* @@ -95,26 +95,26 @@ int run_program_in_pty(const struct shell_data *shdata, */ pid = fork(); if (pid < 0) { - perror("fork"); - return 1; + perror("fork"); + return 1; } if (pid == 0) { - int i, fd; + int i, fd; - /* - * We are the child. - */ - close(master); + /* + * We are the child. + */ + close(master); - fcntl(slave, F_SETFD, 0); /* don't close on exec */ - dup2(slave, 0); - dup2(slave, 1); - if (slave != 0 && slave != 1) - close(slave); - dup2(1, 2); - setsid(); - setpgrp(); + fcntl(slave, F_SETFD, 0); /* don't close on exec */ + dup2(slave, 0); + dup2(slave, 1); + if (slave != 0 && slave != 1) + close(slave); + dup2(1, 2); + setsid(); + setpgrp(); i = 0; #ifdef TIOCNOTTY if ((fd = open("/dev/tty", O_RDWR)) >= 0) { @@ -139,26 +139,26 @@ int run_program_in_pty(const struct shell_data *shdata, perror("slave pty: open"); exit(127); } - tcsetpgrp(0, getpgrp()); + tcsetpgrp(0, getpgrp()); - for (i = 0; i < shdata->nenvvars; i++) + for (i = 0; i < shdata->nenvvars; i++) putenv(shdata->envvars[i]); - if (shdata->termtype) + if (shdata->termtype) putenv(shdata->termtype); if (directory) chdir(directory); - /* - * Use the provided shell program name, if the user gave - * one. Failing that, use $SHELL; failing that, look up - * the user's default shell in the password file; failing - * _that_, revert to the bog-standard /bin/sh. - */ - if (!program_args) { + /* + * Use the provided shell program name, if the user gave + * one. Failing that, use $SHELL; failing that, look up + * the user's default shell in the password file; failing + * _that_, revert to the bog-standard /bin/sh. + */ + if (!program_args) { char *shell; - - shell = getenv("SHELL"); + + shell = getenv("SHELL"); if (!shell) { const char *login; uid_t uid; @@ -189,11 +189,11 @@ int run_program_in_pty(const struct shell_data *shdata, execv(program_args[0], program_args); - /* - * If we're here, exec has gone badly foom. - */ - perror("exec"); - exit(127); + /* + * If we're here, exec has gone badly foom. + */ + perror("exec"); + exit(127); } close(slave); diff --git a/contrib/cygtermd/pty.h b/contrib/cygtermd/pty.h index 261fc41d..936963bf 100644 --- a/contrib/cygtermd/pty.h +++ b/contrib/cygtermd/pty.h @@ -5,7 +5,7 @@ #ifndef CYGTERMD_PTY_H #define CYGTERMD_PTY_H -#include "telnet.h" /* for struct shdata */ +#include "telnet.h" /* for struct shdata */ /* * Called at program startup to actually allocate a pty, so that diff --git a/contrib/cygtermd/sel.c b/contrib/cygtermd/sel.c index 43ec4760..788de08e 100644 --- a/contrib/cygtermd/sel.c +++ b/contrib/cygtermd/sel.c @@ -25,7 +25,7 @@ typedef struct bufchain_tag { struct bufchain_granule *head, *tail; - size_t buffersize; /* current amount of buffered data */ + size_t buffersize; /* current amount of buffered data */ } bufchain; struct bufchain_granule { struct bufchain_granule *next; @@ -43,9 +43,9 @@ static void bufchain_clear(bufchain *ch) { struct bufchain_granule *b; while (ch->head) { - b = ch->head; - ch->head = ch->head->next; - sfree(b); + b = ch->head; + ch->head = ch->head->next; + sfree(b); } ch->tail = NULL; ch->buffersize = 0; @@ -65,31 +65,31 @@ static void bufchain_add(bufchain *ch, const void *data, size_t len) ch->buffersize += len; if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) { - size_t copylen = BUFFER_GRANULE - ch->tail->buflen; - if (copylen > len) - copylen = len; - memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen); - buf += copylen; - len -= copylen; - ch->tail->buflen += copylen; + size_t copylen = BUFFER_GRANULE - ch->tail->buflen; + if (copylen > len) + copylen = len; + memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen); + buf += copylen; + len -= copylen; + ch->tail->buflen += copylen; } while (len > 0) { - struct bufchain_granule *newbuf; - size_t grainlen = BUFFER_GRANULE; - if (grainlen > len) - grainlen = len; - newbuf = snew(struct bufchain_granule); - newbuf->bufpos = 0; - newbuf->buflen = grainlen; - memcpy(newbuf->buf, buf, grainlen); - buf += grainlen; - len -= grainlen; - if (ch->tail) - ch->tail->next = newbuf; - else - ch->head = ch->tail = newbuf; - newbuf->next = NULL; - ch->tail = newbuf; + struct bufchain_granule *newbuf; + size_t grainlen = BUFFER_GRANULE; + if (grainlen > len) + grainlen = len; + newbuf = snew(struct bufchain_granule); + newbuf->bufpos = 0; + newbuf->buflen = grainlen; + memcpy(newbuf->buf, buf, grainlen); + buf += grainlen; + len -= grainlen; + if (ch->tail) + ch->tail->next = newbuf; + else + ch->head = ch->tail = newbuf; + newbuf->next = NULL; + ch->tail = newbuf; } } @@ -99,19 +99,19 @@ static void bufchain_consume(bufchain *ch, size_t len) assert(ch->buffersize >= len); while (len > 0) { - size_t remlen = len; - assert(ch->head != NULL); - if (remlen >= ch->head->buflen - ch->head->bufpos) { - remlen = ch->head->buflen - ch->head->bufpos; - tmp = ch->head; - ch->head = tmp->next; - sfree(tmp); - if (!ch->head) - ch->tail = NULL; - } else - ch->head->bufpos += remlen; - ch->buffersize -= remlen; - len -= remlen; + size_t remlen = len; + assert(ch->head != NULL); + if (remlen >= ch->head->buflen - ch->head->bufpos) { + remlen = ch->head->buflen - ch->head->bufpos; + tmp = ch->head; + ch->head = tmp->next; + sfree(tmp); + if (!ch->head) + ch->tail = NULL; + } else + ch->head->bufpos += remlen; + ch->buffersize -= remlen; + len -= remlen; } } @@ -163,8 +163,8 @@ sel *sel_new(void *ctx) } sel_wfd *sel_wfd_add(sel *sel, int fd, - sel_written_fn_t written, sel_writeerr_fn_t writeerr, - void *ctx) + sel_written_fn_t written, sel_writeerr_fn_t writeerr, + void *ctx) { sel_wfd *wfd = snew(sel_wfd); @@ -177,9 +177,9 @@ sel_wfd *sel_wfd_add(sel *sel, int fd, wfd->next = NULL; wfd->prev = sel->wtail; if (sel->wtail) - sel->wtail->next = wfd; + sel->wtail->next = wfd; else - sel->whead = wfd; + sel->whead = wfd; sel->wtail = wfd; wfd->parent = sel; @@ -187,8 +187,8 @@ sel_wfd *sel_wfd_add(sel *sel, int fd, } sel_rfd *sel_rfd_add(sel *sel, int fd, - sel_readdata_fn_t readdata, sel_readerr_fn_t readerr, - void *ctx) + sel_readdata_fn_t readdata, sel_readerr_fn_t readerr, + void *ctx) { sel_rfd *rfd = snew(sel_rfd); @@ -201,9 +201,9 @@ sel_rfd *sel_rfd_add(sel *sel, int fd, rfd->next = NULL; rfd->prev = sel->rtail; if (sel->rtail) - sel->rtail->next = rfd; + sel->rtail->next = rfd; else - sel->rhead = rfd; + sel->rhead = rfd; sel->rtail = rfd; rfd->parent = sel; @@ -242,13 +242,13 @@ int sel_wfd_delete(sel_wfd *wfd) int ret; if (wfd->prev) - wfd->prev->next = wfd->next; + wfd->prev->next = wfd->next; else - sel->whead = wfd->next; + sel->whead = wfd->next; if (wfd->next) - wfd->next->prev = wfd->prev; + wfd->next->prev = wfd->prev; else - sel->wtail = wfd->prev; + sel->wtail = wfd->prev; bufchain_clear(&wfd->buf); @@ -263,13 +263,13 @@ int sel_rfd_delete(sel_rfd *rfd) int ret; if (rfd->prev) - rfd->prev->next = rfd->next; + rfd->prev->next = rfd->next; else - sel->rhead = rfd->next; + sel->rhead = rfd->next; if (rfd->next) - rfd->next->prev = rfd->prev; + rfd->next->prev = rfd->prev; else - sel->rtail = rfd->prev; + sel->rtail = rfd->prev; ret = rfd->fd; sfree(rfd); @@ -279,9 +279,9 @@ int sel_rfd_delete(sel_rfd *rfd) void sel_free(sel *sel) { while (sel->whead) - sel_wfd_delete(sel->whead); + sel_wfd_delete(sel->whead); while (sel->rhead) - sel_rfd_delete(sel->rhead); + sel_rfd_delete(sel->rhead); sfree(sel); } @@ -306,35 +306,35 @@ int sel_iterate(sel *sel, long timeout) FD_ZERO(&wset); for (rfd = sel->rhead; rfd; rfd = rfd->next) { - if (rfd->fd >= 0 && !rfd->frozen) { - FD_SET(rfd->fd, &rset); - if (maxfd < rfd->fd + 1) - maxfd = rfd->fd + 1; - } + if (rfd->fd >= 0 && !rfd->frozen) { + FD_SET(rfd->fd, &rset); + if (maxfd < rfd->fd + 1) + maxfd = rfd->fd + 1; + } } for (wfd = sel->whead; wfd; wfd = wfd->next) { - if (wfd->fd >= 0 && bufchain_size(&wfd->buf)) { - FD_SET(wfd->fd, &wset); - if (maxfd < wfd->fd + 1) - maxfd = wfd->fd + 1; - } + if (wfd->fd >= 0 && bufchain_size(&wfd->buf)) { + FD_SET(wfd->fd, &wset); + if (maxfd < wfd->fd + 1) + maxfd = wfd->fd + 1; + } } if (timeout < 0) { - ptv = NULL; + ptv = NULL; } else { - ptv = &tv; - tv.tv_sec = timeout / 1000; - tv.tv_usec = 1000 * (timeout % 1000); + ptv = &tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = 1000 * (timeout % 1000); } do { - ret = select(maxfd, &rset, &wset, NULL, ptv); + ret = select(maxfd, &rset, &wset, NULL, ptv); } while (ret < 0 && (errno == EINTR || errno == EAGAIN)); if (ret < 0) - return errno; + return errno; /* * Just in case one of the callbacks destroys an rfd or wfd we @@ -346,40 +346,40 @@ int sel_iterate(sel *sel, long timeout) * using select in the first place. */ do { - for (wfd = sel->whead; wfd; wfd = wfd->next) - if (wfd->fd >= 0 && FD_ISSET(wfd->fd, &wset)) { - void *data; - size_t len; + for (wfd = sel->whead; wfd; wfd = wfd->next) + if (wfd->fd >= 0 && FD_ISSET(wfd->fd, &wset)) { + void *data; + size_t len; - FD_CLR(wfd->fd, &wset); - bufchain_prefix(&wfd->buf, &data, &len); - ret = write(wfd->fd, data, len); - assert(ret != 0); - if (ret < 0) { - if (wfd->writeerr) - wfd->writeerr(wfd, errno); - } else { - bufchain_consume(&wfd->buf, len); - if (wfd->written) - wfd->written(wfd, bufchain_size(&wfd->buf)); - } - break; - } + FD_CLR(wfd->fd, &wset); + bufchain_prefix(&wfd->buf, &data, &len); + ret = write(wfd->fd, data, len); + assert(ret != 0); + if (ret < 0) { + if (wfd->writeerr) + wfd->writeerr(wfd, errno); + } else { + bufchain_consume(&wfd->buf, len); + if (wfd->written) + wfd->written(wfd, bufchain_size(&wfd->buf)); + } + break; + } } while (wfd); do { - for (rfd = sel->rhead; rfd; rfd = rfd->next) - if (rfd->fd >= 0 && !rfd->frozen && FD_ISSET(rfd->fd, &rset)) { - FD_CLR(rfd->fd, &rset); - ret = read(rfd->fd, buf, sizeof(buf)); - if (ret < 0) { - if (rfd->readerr) - rfd->readerr(rfd, errno); - } else { - if (rfd->readdata) - rfd->readdata(rfd, buf, ret); - } - break; - } + for (rfd = sel->rhead; rfd; rfd = rfd->next) + if (rfd->fd >= 0 && !rfd->frozen && FD_ISSET(rfd->fd, &rset)) { + FD_CLR(rfd->fd, &rset); + ret = read(rfd->fd, buf, sizeof(buf)); + if (ret < 0) { + if (rfd->readerr) + rfd->readerr(rfd, errno); + } else { + if (rfd->readdata) + rfd->readdata(rfd, buf, ret); + } + break; + } } while (rfd); return 0; diff --git a/contrib/cygtermd/sel.h b/contrib/cygtermd/sel.h index 42c615ff..224fc617 100644 --- a/contrib/cygtermd/sel.h +++ b/contrib/cygtermd/sel.h @@ -37,7 +37,7 @@ typedef void (*sel_readerr_fn_t)(sel_rfd *rfd, int error); /* * Create a sel structure, which will oversee a select loop. - * + * * "ctx" is user-supplied data stored in the sel structure; it can * be read and written with sel_get_ctx() and sel_set_ctx(). */ @@ -47,10 +47,10 @@ sel *sel_new(void *ctx); * Add a new fd for writing. Returns a sel_wfd which identifies * that fd in the sel structure, e.g. for putting data into its * output buffer. - * + * * "ctx" is user-supplied data stored in the sel structure; it can * be read and written with sel_wfd_get_ctx() and sel_wfd_set_ctx(). - * + * * "written" and "writeerr" are called from the event loop when * things happen. * @@ -59,22 +59,22 @@ sel *sel_new(void *ctx); * using sel_wfd_setfd. */ sel_wfd *sel_wfd_add(sel *sel, int fd, - sel_written_fn_t written, sel_writeerr_fn_t writeerr, - void *ctx); + sel_written_fn_t written, sel_writeerr_fn_t writeerr, + void *ctx); /* * Add a new fd for reading. Returns a sel_rfd which identifies * that fd in the sel structure. - * + * * "ctx" is user-supplied data stored in the sel structure; it can * be read and written with sel_rfd_get_ctx() and sel_rfd_set_ctx(). - * + * * "readdata" and "readerr" are called from the event loop when * things happen. "ctx" is passed to both of them. */ sel_rfd *sel_rfd_add(sel *sel, int fd, - sel_readdata_fn_t readdata, sel_readerr_fn_t readerr, - void *ctx); + sel_readdata_fn_t readdata, sel_readerr_fn_t readerr, + void *ctx); /* * Write data into the output buffer of a wfd. Returns the new @@ -137,7 +137,7 @@ void sel_rfd_set_ctx(sel_rfd *rfd, void *ctx); * Run one iteration of the sel event loop, calling callbacks as * necessary. Returns zero on success; in the event of a fatal * error, returns the errno value. - * + * * "timeout" is a value in microseconds to limit the length of the * select call. Less than zero means to wait indefinitely. */ diff --git a/contrib/cygtermd/telnet.c b/contrib/cygtermd/telnet.c index 6c96eed5..f51823bc 100644 --- a/contrib/cygtermd/telnet.c +++ b/contrib/cygtermd/telnet.c @@ -13,27 +13,27 @@ #include "malloc.h" #include "pty.h" -#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 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 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 TELOPTS(X) \ X(BINARY, 0) /* 8-bit data path */ \ @@ -95,9 +95,9 @@ enum { TELOPTS(telnet_enum) dummy=0 }; #undef telnet_enum -#define TELQUAL_IS 0 /* option is... */ -#define TELQUAL_SEND 1 /* send option */ -#define TELQUAL_INFO 2 /* ENVIRON: informational version of IS */ +#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 @@ -113,9 +113,9 @@ static char *telopt(int opt) { #define telnet_str(x,y) case TELOPT_##x: return #x; switch (opt) { - TELOPTS(telnet_str) + TELOPTS(telnet_str) default: - return ""; + return ""; } #undef telnet_str } @@ -123,13 +123,13 @@ static char *telopt(int opt) static void telnet_size(void *handle, int width, int height); struct Opt { - int send; /* what we initially send */ - int nsend; /* -ve send if requested to stop it */ - int ack, nak; /* +ve and -ve acknowledgements */ - int option; /* the option code */ - int index; /* index into telnet->opt_states[] */ + int send; /* what we initially send */ + int nsend; /* -ve send if requested to stop it */ + int ack, nak; /* +ve and -ve acknowledgements */ + int option; /* the option code */ + int index; /* index into telnet->opt_states[] */ enum { - REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE + REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE } initial_state; }; @@ -174,8 +174,8 @@ struct Telnet { int sb_size; enum { - TOP_LEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT, - SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR + TOP_LEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT, + SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR } state; sel_wfd *net, *pty; @@ -210,8 +210,8 @@ static void send_opt(Telnet *telnet, int cmd, int option) static void deactivate_option(Telnet *telnet, const struct Opt *o) { if (telnet->opt_states[o->index] == REQUESTED || - telnet->opt_states[o->index] == ACTIVE) - send_opt(telnet, o->nsend, o->option); + telnet->opt_states[o->index] == ACTIVE) + send_opt(telnet, o->nsend, o->option); telnet->opt_states[o->index] = REALLY_INACTIVE; } @@ -225,16 +225,16 @@ static void option_side_effects(Telnet *telnet, const struct Opt *o, int enabled static void activate_option(Telnet *telnet, const struct Opt *o) { if (o->option == TELOPT_NEW_ENVIRON || - o->option == TELOPT_OLD_ENVIRON || - o->option == TELOPT_TTYPE) { - char buf[6]; - buf[0] = IAC; - buf[1] = SB; - buf[2] = o->option; - buf[3] = TELQUAL_SEND; - buf[4] = IAC; - buf[5] = SE; - sel_write(telnet->net, buf, 6); + o->option == TELOPT_OLD_ENVIRON || + o->option == TELOPT_TTYPE) { + char buf[6]; + buf[0] = IAC; + buf[1] = SB; + buf[2] = o->option; + buf[3] = TELQUAL_SEND; + buf[4] = IAC; + buf[5] = SE; + sel_write(telnet->net, buf, 6); } option_side_effects(telnet, o, 1); } @@ -242,15 +242,15 @@ static void activate_option(Telnet *telnet, const struct Opt *o) static void done_option(Telnet *telnet, int option) { if (option == TELOPT_OLD_ENVIRON) - telnet->old_environ_done = 1; + telnet->old_environ_done = 1; else if (option == TELOPT_NEW_ENVIRON) - telnet->new_environ_done = 1; + telnet->new_environ_done = 1; else if (option == TELOPT_TTYPE) - telnet->ttype_done = 1; + telnet->ttype_done = 1; if (telnet->old_environ_done && telnet->new_environ_done && - telnet->ttype_done) { - telnet->shell_ok = 1; + telnet->ttype_done) { + telnet->shell_ok = 1; } } @@ -258,10 +258,10 @@ static void refused_option(Telnet *telnet, const struct Opt *o) { done_option(telnet, o->option); if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON && - telnet->opt_states[o_oenv.index] == INACTIVE) { - send_opt(telnet, WILL, TELOPT_OLD_ENVIRON); - telnet->opt_states[o_oenv.index] = REQUESTED; - telnet->old_environ_done = 0; + telnet->opt_states[o_oenv.index] == INACTIVE) { + send_opt(telnet, WILL, TELOPT_OLD_ENVIRON); + telnet->opt_states[o_oenv.index] = REQUESTED; + telnet->old_environ_done = 0; } option_side_effects(telnet, o, 0); } @@ -271,41 +271,41 @@ static void proc_rec_opt(Telnet *telnet, int cmd, int option) const struct Opt *const *o; for (o = opts; *o; o++) { - if ((*o)->option == option && (*o)->ack == cmd) { - switch (telnet->opt_states[(*o)->index]) { - case REQUESTED: - telnet->opt_states[(*o)->index] = ACTIVE; - activate_option(telnet, *o); - break; - case ACTIVE: - break; - case INACTIVE: - telnet->opt_states[(*o)->index] = ACTIVE; - send_opt(telnet, (*o)->send, option); - activate_option(telnet, *o); - break; - case REALLY_INACTIVE: - send_opt(telnet, (*o)->nsend, option); - break; - } - return; - } else if ((*o)->option == option && (*o)->nak == cmd) { - switch (telnet->opt_states[(*o)->index]) { - case REQUESTED: - telnet->opt_states[(*o)->index] = INACTIVE; - refused_option(telnet, *o); - break; - case ACTIVE: - telnet->opt_states[(*o)->index] = INACTIVE; - send_opt(telnet, (*o)->nsend, option); - option_side_effects(telnet, *o, 0); - break; - case INACTIVE: - case REALLY_INACTIVE: - break; - } - return; - } + if ((*o)->option == option && (*o)->ack == cmd) { + switch (telnet->opt_states[(*o)->index]) { + case REQUESTED: + telnet->opt_states[(*o)->index] = ACTIVE; + activate_option(telnet, *o); + break; + case ACTIVE: + break; + case INACTIVE: + telnet->opt_states[(*o)->index] = ACTIVE; + send_opt(telnet, (*o)->send, option); + activate_option(telnet, *o); + break; + case REALLY_INACTIVE: + send_opt(telnet, (*o)->nsend, option); + break; + } + return; + } else if ((*o)->option == option && (*o)->nak == cmd) { + switch (telnet->opt_states[(*o)->index]) { + case REQUESTED: + telnet->opt_states[(*o)->index] = INACTIVE; + refused_option(telnet, *o); + break; + case ACTIVE: + telnet->opt_states[(*o)->index] = INACTIVE; + send_opt(telnet, (*o)->nsend, option); + option_side_effects(telnet, *o, 0); + break; + case INACTIVE: + case REALLY_INACTIVE: + break; + } + return; + } } /* * If we reach here, the option was one we weren't prepared to @@ -324,52 +324,52 @@ static void process_subneg(Telnet *telnet) switch (telnet->sb_opt) { case TELOPT_OLD_ENVIRON: case TELOPT_NEW_ENVIRON: - if (telnet->sb_buf[0] == TELQUAL_IS) { - if (telnet->sb_opt == TELOPT_NEW_ENVIRON) { - var = RFC_VAR; - value = RFC_VALUE; - } else { - if (telnet->sb_len > 1 && !(telnet->sb_buf[0] &~ 1)) { - var = telnet->sb_buf[0]; - value = BSD_VAR ^ BSD_VALUE ^ var; - } else { - var = BSD_VAR; - value = BSD_VALUE; - } - } - } - n = 1; - while (n < telnet->sb_len && telnet->sb_buf[n] == var) { - int varpos, varlen, valpos, vallen; - char *result; + if (telnet->sb_buf[0] == TELQUAL_IS) { + if (telnet->sb_opt == TELOPT_NEW_ENVIRON) { + var = RFC_VAR; + value = RFC_VALUE; + } else { + if (telnet->sb_len > 1 && !(telnet->sb_buf[0] &~ 1)) { + var = telnet->sb_buf[0]; + value = BSD_VAR ^ BSD_VALUE ^ var; + } else { + var = BSD_VAR; + value = BSD_VALUE; + } + } + } + n = 1; + while (n < telnet->sb_len && telnet->sb_buf[n] == var) { + int varpos, varlen, valpos, vallen; + char *result; - varpos = ++n; - while (n < telnet->sb_len && telnet->sb_buf[n] != value) - n++; - if (n == telnet->sb_len) - break; - varlen = n - varpos; - valpos = ++n; - while (n < telnet->sb_len && telnet->sb_buf[n] != var) - n++; - vallen = n - valpos; + varpos = ++n; + while (n < telnet->sb_len && telnet->sb_buf[n] != value) + n++; + if (n == telnet->sb_len) + break; + varlen = n - varpos; + valpos = ++n; + while (n < telnet->sb_len && telnet->sb_buf[n] != var) + n++; + vallen = n - valpos; - result = snewn(varlen + vallen + 2, char); - sprintf(result, "%.*s=%.*s", - varlen, telnet->sb_buf+varpos, - vallen, telnet->sb_buf+valpos); - if (telnet->shdata.nenvvars >= telnet->envvarsize) { - telnet->envvarsize = telnet->shdata.nenvvars * 3 / 2 + 16; - telnet->shdata.envvars = sresize(telnet->shdata.envvars, - telnet->envvarsize, char *); - } - telnet->shdata.envvars[telnet->shdata.nenvvars++] = result; - } - done_option(telnet, telnet->sb_opt); - break; + result = snewn(varlen + vallen + 2, char); + sprintf(result, "%.*s=%.*s", + varlen, telnet->sb_buf+varpos, + vallen, telnet->sb_buf+valpos); + if (telnet->shdata.nenvvars >= telnet->envvarsize) { + telnet->envvarsize = telnet->shdata.nenvvars * 3 / 2 + 16; + telnet->shdata.envvars = sresize(telnet->shdata.envvars, + telnet->envvarsize, char *); + } + telnet->shdata.envvars[telnet->shdata.nenvvars++] = result; + } + done_option(telnet, telnet->sb_opt); + break; case TELOPT_TTYPE: - if (telnet->sb_len >= 1 && telnet->sb_buf[0] == TELQUAL_IS) { - telnet->shdata.termtype = snewn(5 + telnet->sb_len, char); + if (telnet->sb_len >= 1 && telnet->sb_buf[0] == TELQUAL_IS) { + telnet->shdata.termtype = snewn(5 + telnet->sb_len, char); strcpy(telnet->shdata.termtype, "TERM="); for (n = 0; n < telnet->sb_len-1; n++) { char c = telnet->sb_buf[n+1]; @@ -377,117 +377,117 @@ static void process_subneg(Telnet *telnet) c = c + 'a' - 'A'; telnet->shdata.termtype[n+5] = c; } - telnet->shdata.termtype[telnet->sb_len+5-1] = '\0'; - } - done_option(telnet, telnet->sb_opt); - break; + telnet->shdata.termtype[telnet->sb_len+5-1] = '\0'; + } + done_option(telnet, telnet->sb_opt); + break; case TELOPT_NAWS: - if (telnet->sb_len == 4) { - int w, h; - w = (unsigned char)telnet->sb_buf[0]; - w = (w << 8) | (unsigned char)telnet->sb_buf[1]; - h = (unsigned char)telnet->sb_buf[2]; - h = (h << 8) | (unsigned char)telnet->sb_buf[3]; - pty_resize(w, h); - } - break; + if (telnet->sb_len == 4) { + int w, h; + w = (unsigned char)telnet->sb_buf[0]; + w = (w << 8) | (unsigned char)telnet->sb_buf[1]; + h = (unsigned char)telnet->sb_buf[2]; + h = (h << 8) | (unsigned char)telnet->sb_buf[3]; + pty_resize(w, h); + } + break; } } void telnet_from_net(Telnet *telnet, char *buf, int len) { while (len--) { - int c = (unsigned char) *buf++; + int c = (unsigned char) *buf++; - switch (telnet->state) { - case TOP_LEVEL: - case SEENCR: - /* - * PuTTY sends Telnet's new line sequence (CR LF on - * the wire) in response to the return key. We must - * therefore treat that as equivalent to CR NUL, and - * send CR to the pty. - */ - if ((c == NUL || c == '\n') && telnet->state == SEENCR) - telnet->state = TOP_LEVEL; - else if (c == IAC) - telnet->state = SEENIAC; - else { - char cc = c; - sel_write(telnet->pty, &cc, 1); + switch (telnet->state) { + case TOP_LEVEL: + case SEENCR: + /* + * PuTTY sends Telnet's new line sequence (CR LF on + * the wire) in response to the return key. We must + * therefore treat that as equivalent to CR NUL, and + * send CR to the pty. + */ + if ((c == NUL || c == '\n') && telnet->state == SEENCR) + telnet->state = TOP_LEVEL; + else if (c == IAC) + telnet->state = SEENIAC; + else { + char cc = c; + sel_write(telnet->pty, &cc, 1); - if (c == CR) - telnet->state = SEENCR; - else - telnet->state = TOP_LEVEL; - } - 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; - else if (c == DM) - telnet->state = TOP_LEVEL; - else { - /* ignore everything else; print it if it's IAC */ - if (c == IAC) { - char cc = c; - sel_write(telnet->pty, &cc, 1); - } - telnet->state = TOP_LEVEL; - } - break; - case SEENWILL: - proc_rec_opt(telnet, WILL, c); - telnet->state = TOP_LEVEL; - break; - case SEENWONT: - proc_rec_opt(telnet, WONT, c); - telnet->state = TOP_LEVEL; - break; - case SEENDO: - proc_rec_opt(telnet, DO, c); - telnet->state = TOP_LEVEL; - break; - case SEENDONT: - proc_rec_opt(telnet, DONT, c); - telnet->state = TOP_LEVEL; - break; - case SEENSB: - telnet->sb_opt = c; - telnet->sb_len = 0; - telnet->state = SUBNEGOT; - break; - case SUBNEGOT: - if (c == IAC) - telnet->state = SUBNEG_IAC; - else { - subneg_addchar: - if (telnet->sb_len >= telnet->sb_size) { - telnet->sb_size += SB_DELTA; - telnet->sb_buf = sresize(telnet->sb_buf, telnet->sb_size, - unsigned char); - } - telnet->sb_buf[telnet->sb_len++] = c; - telnet->state = SUBNEGOT; /* in case we came here by goto */ - } - break; - case SUBNEG_IAC: - if (c != SE) - goto subneg_addchar; /* yes, it's a hack, I know, but... */ - else { - process_subneg(telnet); - telnet->state = TOP_LEVEL; - } - break; - } + if (c == CR) + telnet->state = SEENCR; + else + telnet->state = TOP_LEVEL; + } + 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; + else if (c == DM) + telnet->state = TOP_LEVEL; + else { + /* ignore everything else; print it if it's IAC */ + if (c == IAC) { + char cc = c; + sel_write(telnet->pty, &cc, 1); + } + telnet->state = TOP_LEVEL; + } + break; + case SEENWILL: + proc_rec_opt(telnet, WILL, c); + telnet->state = TOP_LEVEL; + break; + case SEENWONT: + proc_rec_opt(telnet, WONT, c); + telnet->state = TOP_LEVEL; + break; + case SEENDO: + proc_rec_opt(telnet, DO, c); + telnet->state = TOP_LEVEL; + break; + case SEENDONT: + proc_rec_opt(telnet, DONT, c); + telnet->state = TOP_LEVEL; + break; + case SEENSB: + telnet->sb_opt = c; + telnet->sb_len = 0; + telnet->state = SUBNEGOT; + break; + case SUBNEGOT: + if (c == IAC) + telnet->state = SUBNEG_IAC; + else { + subneg_addchar: + if (telnet->sb_len >= telnet->sb_size) { + telnet->sb_size += SB_DELTA; + telnet->sb_buf = sresize(telnet->sb_buf, telnet->sb_size, + unsigned char); + } + telnet->sb_buf[telnet->sb_len++] = c; + telnet->state = SUBNEGOT; /* in case we came here by goto */ + } + break; + case SUBNEG_IAC: + if (c != SE) + goto subneg_addchar; /* yes, it's a hack, I know, but... */ + else { + process_subneg(telnet); + telnet->state = TOP_LEVEL; + } + break; + } } } @@ -509,13 +509,13 @@ Telnet *telnet_new(sel_wfd *net, sel_wfd *pty) * Initialise option states. */ { - const struct Opt *const *o; + const struct Opt *const *o; - for (o = opts; *o; o++) { - telnet->opt_states[(*o)->index] = (*o)->initial_state; - if (telnet->opt_states[(*o)->index] == REQUESTED) - send_opt(telnet, (*o)->send, (*o)->option); - } + for (o = opts; *o; o++) { + telnet->opt_states[(*o)->index] = (*o)->initial_state; + if (telnet->opt_states[(*o)->index] == REQUESTED) + send_opt(telnet, (*o)->send, (*o)->option); + } } telnet->old_environ_done = 1; /* initially don't want to bother */ @@ -544,22 +544,22 @@ void telnet_from_pty(Telnet *telnet, char *buf, int len) p = (unsigned char *)buf; end = (unsigned char *)(buf + len); while (p < end) { - unsigned char *q = p; + unsigned char *q = p; - while (p < end && iswritable(*p)) - p++; - sel_write(telnet->net, q, p - q); + while (p < end && iswritable(*p)) + p++; + sel_write(telnet->net, q, p - q); - while (p < end && !iswritable(*p)) { - sel_write(telnet->net, *p == IAC ? iac : cr, 2); - p++; - } + while (p < end && !iswritable(*p)) { + sel_write(telnet->net, *p == IAC ? iac : cr, 2); + p++; + } } } int telnet_shell_ok(Telnet *telnet, struct shell_data *shdata) { if (telnet->shell_ok) - *shdata = telnet->shdata; /* structure copy */ + *shdata = telnet->shdata; /* structure copy */ return telnet->shell_ok; } diff --git a/contrib/cygtermd/telnet.h b/contrib/cygtermd/telnet.h index 2dc1582b..8eefa4ff 100644 --- a/contrib/cygtermd/telnet.h +++ b/contrib/cygtermd/telnet.h @@ -10,7 +10,7 @@ typedef struct Telnet Telnet; struct shell_data { - char **envvars; /* array of "VAR=value" terms */ + char **envvars; /* array of "VAR=value" terms */ int nenvvars; char *termtype; }; diff --git a/contrib/logparse.pl b/contrib/logparse.pl index c1bd60d2..eb429302 100755 --- a/contrib/logparse.pl +++ b/contrib/logparse.pl @@ -36,78 +36,78 @@ my %chan_by_id = (); # indexed by 'c%d' or 's%d' for client and server ids my %globalreq = (); # indexed by 'i' or 'o' my %packets = ( -#define SSH2_MSG_DISCONNECT 1 /* 0x1 */ +#define SSH2_MSG_DISCONNECT 1 /* 0x1 */ 'SSH2_MSG_DISCONNECT' => sub { my ($direction, $seq, $data) = @_; my ($reason, $description, $lang) = &parse("uss", $data); printf "%s\n", &str($description); }, -#define SSH2_MSG_IGNORE 2 /* 0x2 */ +#define SSH2_MSG_IGNORE 2 /* 0x2 */ 'SSH2_MSG_IGNORE' => sub { my ($direction, $seq, $data) = @_; my ($str) = &parse("s", $data); printf "(%d bytes)\n", length $str; }, -#define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */ +#define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */ 'SSH2_MSG_UNIMPLEMENTED' => sub { my ($direction, $seq, $data) = @_; my ($rseq) = &parse("u", $data); printf "i%d\n", $rseq; }, -#define SSH2_MSG_DEBUG 4 /* 0x4 */ +#define SSH2_MSG_DEBUG 4 /* 0x4 */ 'SSH2_MSG_DEBUG' => sub { my ($direction, $seq, $data) = @_; my ($disp, $message, $lang) = &parse("bss", $data); printf "%s\n", &str($message); }, -#define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */ +#define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */ 'SSH2_MSG_SERVICE_REQUEST' => sub { my ($direction, $seq, $data) = @_; my ($service) = &parse("s", $data); printf "%s\n", &str($service); }, -#define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */ +#define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */ 'SSH2_MSG_SERVICE_ACCEPT' => sub { my ($direction, $seq, $data) = @_; my ($service) = &parse("s", $data); printf "%s\n", &str($service); }, -#define SSH2_MSG_KEXINIT 20 /* 0x14 */ +#define SSH2_MSG_KEXINIT 20 /* 0x14 */ 'SSH2_MSG_KEXINIT' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_NEWKEYS 21 /* 0x15 */ +#define SSH2_MSG_NEWKEYS 21 /* 0x15 */ 'SSH2_MSG_NEWKEYS' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */ +#define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */ 'SSH2_MSG_KEXDH_INIT' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */ +#define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */ 'SSH2_MSG_KEXDH_REPLY' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */ +#define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */ 'SSH2_MSG_KEX_DH_GEX_REQUEST' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */ +#define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */ 'SSH2_MSG_KEX_DH_GEX_GROUP' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */ +#define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */ 'SSH2_MSG_KEX_DH_GEX_INIT' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */ +#define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */ 'SSH2_MSG_KEX_DH_GEX_REPLY' => sub { my ($direction, $seq, $data) = @_; print "\n"; @@ -172,7 +172,7 @@ my %packets = ( my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */ +#define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */ 'SSH2_MSG_USERAUTH_REQUEST' => sub { my ($direction, $seq, $data) = @_; my ($user, $service, $method) = &parse("sss", $data); @@ -187,43 +187,43 @@ my %packets = ( } print "$out\n"; }, -#define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */ +#define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */ 'SSH2_MSG_USERAUTH_FAILURE' => sub { my ($direction, $seq, $data) = @_; my ($options) = &parse("s", $data); printf "%s\n", &str($options); }, -#define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */ +#define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */ 'SSH2_MSG_USERAUTH_SUCCESS' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */ +#define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */ 'SSH2_MSG_USERAUTH_BANNER' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */ +#define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */ 'SSH2_MSG_USERAUTH_PK_OK' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */ +#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */ 'SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */ +#define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */ 'SSH2_MSG_USERAUTH_INFO_REQUEST' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */ +#define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */ 'SSH2_MSG_USERAUTH_INFO_RESPONSE' => sub { my ($direction, $seq, $data) = @_; print "\n"; }, -#define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */ +#define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */ 'SSH2_MSG_GLOBAL_REQUEST' => sub { my ($direction, $seq, $data) = @_; my ($type, $wantreply) = &parse("sb", $data); @@ -237,7 +237,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */ +#define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */ 'SSH2_MSG_REQUEST_SUCCESS' => sub { my ($direction, $seq, $data) = @_; my $otherdir = ($direction eq "i" ? "o" : "i"); @@ -253,7 +253,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */ +#define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */ 'SSH2_MSG_REQUEST_FAILURE' => sub { my ($direction, $seq, $data) = @_; my $otherdir = ($direction eq "i" ? "o" : "i"); @@ -265,7 +265,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */ +#define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */ 'SSH2_MSG_CHANNEL_OPEN' => sub { my ($direction, $seq, $data) = @_; my ($type, $sid, $winsize, $packet) = &parse("suuu", $data); @@ -275,14 +275,14 @@ my %packets = ( # quote the _recipient's_ id of the channel. $sid = ($direction eq "i" ? "s" : "c") . $sid; my $chan = {'id'=>$sid, 'state'=>'halfopen', - 'i'=>{'win'=>0, 'seq'=>0}, - 'o'=>{'win'=>0, 'seq'=>0}}; - $chan->{$direction}{'win'} = $winsize; + 'i'=>{'win'=>0, 'seq'=>0}, + 'o'=>{'win'=>0, 'seq'=>0}}; + $chan->{$direction}{'win'} = $winsize; push @channels, $chan; my $index = $#channels; $chan_by_id{$sid} = $index; printf "ch%d (%s) %s (--%d)", $index, $chan->{'id'}, $type, - $chan->{$direction}{'win'}; + $chan->{$direction}{'win'}; if ($type eq "x11") { my ($addr, $port) = &parse("su", $data); printf " from %s:%s", $addr, $port; @@ -295,7 +295,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */ +#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */ 'SSH2_MSG_CHANNEL_OPEN_CONFIRMATION' => sub { my ($direction, $seq, $data) = @_; my ($rid, $sid, $winsize, $packet) = &parse("uuuu", $data); @@ -310,11 +310,11 @@ my %packets = ( my $chan = $channels[$index]; $chan->{'id'} = ($direction eq "i" ? "$rid/$sid" : "$sid/$rid"); $chan->{'state'} = 'open'; - $chan->{$direction}{'win'} = $winsize; + $chan->{$direction}{'win'} = $winsize; printf "ch%d (%s) (--%d)\n", $index, $chan->{'id'}, - $chan->{$direction}{'win'}; + $chan->{$direction}{'win'}; }, -#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */ +#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */ 'SSH2_MSG_CHANNEL_OPEN_FAILURE' => sub { my ($direction, $seq, $data) = @_; my ($rid, $reason, $desc, $lang) = &parse("uuss", $data); @@ -328,7 +328,7 @@ my %packets = ( $chan->{'state'} = 'rejected'; printf "ch%d (%s) %s\n", $index, $chan->{'id'}, &str($reason); }, -#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */ +#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */ 'SSH2_MSG_CHANNEL_WINDOW_ADJUST' => sub { my ($direction, $seq, $data) = @_; my ($rid, $bytes) = &parse("uu", $data); @@ -339,11 +339,11 @@ my %packets = ( return; } my $chan = $channels[$index]; - $chan->{$direction}{'win'} += $bytes; + $chan->{$direction}{'win'} += $bytes; printf "ch%d (%s) +%d (--%d)\n", $index, $chan->{'id'}, $bytes, - $chan->{$direction}{'win'}; + $chan->{$direction}{'win'}; }, -#define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */ +#define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */ 'SSH2_MSG_CHANNEL_DATA' => sub { my ($direction, $seq, $data) = @_; my ($rid, $bytes) = &parse("uu", $data); @@ -354,9 +354,9 @@ my %packets = ( return; } my $chan = $channels[$index]; - $chan->{$direction}{'seq'} += $bytes; + $chan->{$direction}{'seq'} += $bytes; printf "ch%d (%s), %s bytes (%d--%d)\n", $index, $chan->{'id'}, $bytes, - $chan->{$direction}{'seq'}-$bytes, $chan->{$direction}{'seq'}; + $chan->{$direction}{'seq'}-$bytes, $chan->{$direction}{'seq'}; my @realdata = splice @$data, 0, $bytes; if ($dumpdata) { my $filekey = $direction . "file"; @@ -377,7 +377,7 @@ my %packets = ( $chan->{$direction."data"}->($chan, $index, $direction, $rawdata); } }, -#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */ +#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */ 'SSH2_MSG_CHANNEL_EXTENDED_DATA' => sub { my ($direction, $seq, $data) = @_; my ($rid, $type, $bytes) = &parse("uuu", $data); @@ -392,7 +392,7 @@ my %packets = ( return; } my $chan = $channels[$index]; - $chan->{$direction}{'seq'} += $bytes; + $chan->{$direction}{'seq'} += $bytes; printf "ch%d (%s), type %s, %s bytes (%d--%d)\n", $index,$chan->{'id'}, $type, $bytes, $chan->{$direction}{'seq'}-$bytes, $chan->{$direction}{'seq'}; @@ -421,7 +421,7 @@ my %packets = ( $chan->{$direction."data"}->($chan, $index, $direction, $rawdata); } }, -#define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */ +#define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */ 'SSH2_MSG_CHANNEL_EOF' => sub { my ($direction, $seq, $data) = @_; my ($rid) = &parse("uu", $data); @@ -434,7 +434,7 @@ my %packets = ( my $chan = $channels[$index]; printf "ch%d (%s)\n", $index, $chan->{'id'}; }, -#define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */ +#define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */ 'SSH2_MSG_CHANNEL_CLOSE' => sub { my ($direction, $seq, $data) = @_; my ($rid) = &parse("uu", $data); @@ -454,7 +454,7 @@ my %packets = ( } printf "ch%d (%s)\n", $index, $chan->{'id'}; }, -#define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */ +#define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */ 'SSH2_MSG_CHANNEL_REQUEST' => sub { my ($direction, $seq, $data) = @_; my ($rid, $type, $wantreply) = &parse("usb", $data); @@ -469,7 +469,7 @@ my %packets = ( printf "ch%d (%s) %s (%s)", $index, $chan->{'id'}, $type, $wantreply eq "yes" ? "reply" : "noreply"; push @{$chan->{'requests_'.$direction}}, [$seq, $type] - if $wantreply eq "yes"; + if $wantreply eq "yes"; } if ($type eq "pty-req") { my ($term, $w, $h, $pw, $ph, $modes) = &parse("suuuus", $data); @@ -506,7 +506,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */ +#define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */ 'SSH2_MSG_CHANNEL_SUCCESS' => sub { my ($direction, $seq, $data) = @_; my ($rid) = &parse("uu", $data); @@ -527,7 +527,7 @@ my %packets = ( } print "\n"; }, -#define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */ +#define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */ 'SSH2_MSG_CHANNEL_FAILURE' => sub { my ($direction, $seq, $data) = @_; my ($rid) = &parse("uu", $data); @@ -796,19 +796,19 @@ my %verbose_packet_dump_functions = ( ); my %sftp_packets = ( -#define SSH_FXP_INIT 1 /* 0x1 */ +#define SSH_FXP_INIT 1 /* 0x1 */ 0x1 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($ver) = &parse("u", $data); printf "SSH_FXP_INIT %d\n", $ver; }, -#define SSH_FXP_VERSION 2 /* 0x2 */ +#define SSH_FXP_VERSION 2 /* 0x2 */ 0x2 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($ver) = &parse("u", $data); printf "SSH_FXP_VERSION %d\n", $ver; }, -#define SSH_FXP_OPEN 3 /* 0x3 */ +#define SSH_FXP_OPEN 3 /* 0x3 */ 0x3 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path, $pflags) = &parse("usu", $data); @@ -828,7 +828,7 @@ my %sftp_packets = ( } print "\n"; }, -#define SSH_FXP_CLOSE 4 /* 0x4 */ +#define SSH_FXP_CLOSE 4 /* 0x4 */ 0x4 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle) = &parse("us", $data); @@ -836,7 +836,7 @@ my %sftp_packets = ( printf " \"%s\"", &stringescape($handle); print "\n"; }, -#define SSH_FXP_READ 5 /* 0x5 */ +#define SSH_FXP_READ 5 /* 0x5 */ 0x5 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle, $offset, $len) = &parse("usUu", $data); @@ -844,7 +844,7 @@ my %sftp_packets = ( printf " \"%s\" %d %d", &stringescape($handle), $offset, $len; print "\n"; }, -#define SSH_FXP_WRITE 6 /* 0x6 */ +#define SSH_FXP_WRITE 6 /* 0x6 */ 0x6 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle, $offset, $wdata) = &parse("usUs", $data); @@ -852,7 +852,7 @@ my %sftp_packets = ( printf " \"%s\" %d [%d bytes]", &stringescape($handle), $offset, length $wdata; print "\n"; }, -#define SSH_FXP_LSTAT 7 /* 0x7 */ +#define SSH_FXP_LSTAT 7 /* 0x7 */ 0x7 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -860,7 +860,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_FSTAT 8 /* 0x8 */ +#define SSH_FXP_FSTAT 8 /* 0x8 */ 0x8 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle) = &parse("us", $data); @@ -868,7 +868,7 @@ my %sftp_packets = ( printf " \"%s\"", &stringescape($handle); print "\n"; }, -#define SSH_FXP_SETSTAT 9 /* 0x9 */ +#define SSH_FXP_SETSTAT 9 /* 0x9 */ 0x9 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -877,7 +877,7 @@ my %sftp_packets = ( printf " \"%s\" %s", $path, $attrs; print "\n"; }, -#define SSH_FXP_FSETSTAT 10 /* 0xa */ +#define SSH_FXP_FSETSTAT 10 /* 0xa */ 0xa => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle) = &parse("us", $data); @@ -886,7 +886,7 @@ my %sftp_packets = ( printf " \"%s\" %s", &stringescape($handle), $attrs; print "\n"; }, -#define SSH_FXP_OPENDIR 11 /* 0xb */ +#define SSH_FXP_OPENDIR 11 /* 0xb */ 0xb => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -894,7 +894,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_READDIR 12 /* 0xc */ +#define SSH_FXP_READDIR 12 /* 0xc */ 0xc => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle) = &parse("us", $data); @@ -902,7 +902,7 @@ my %sftp_packets = ( printf " \"%s\"", &stringescape($handle); print "\n"; }, -#define SSH_FXP_REMOVE 13 /* 0xd */ +#define SSH_FXP_REMOVE 13 /* 0xd */ 0xd => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -910,7 +910,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_MKDIR 14 /* 0xe */ +#define SSH_FXP_MKDIR 14 /* 0xe */ 0xe => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -918,7 +918,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_RMDIR 15 /* 0xf */ +#define SSH_FXP_RMDIR 15 /* 0xf */ 0xf => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -926,7 +926,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_REALPATH 16 /* 0x10 */ +#define SSH_FXP_REALPATH 16 /* 0x10 */ 0x10 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -934,7 +934,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_STAT 17 /* 0x11 */ +#define SSH_FXP_STAT 17 /* 0x11 */ 0x11 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $path) = &parse("us", $data); @@ -942,7 +942,7 @@ my %sftp_packets = ( printf " \"%s\"", $path; print "\n"; }, -#define SSH_FXP_RENAME 18 /* 0x12 */ +#define SSH_FXP_RENAME 18 /* 0x12 */ 0x12 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $srcpath, $dstpath) = &parse("uss", $data); @@ -950,7 +950,7 @@ my %sftp_packets = ( printf " \"%s\" \"%s\"", $srcpath, $dstpath; print "\n"; }, -#define SSH_FXP_STATUS 101 /* 0x65 */ +#define SSH_FXP_STATUS 101 /* 0x65 */ 0x65 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $status) = &parse("uu", $data); @@ -968,7 +968,7 @@ my %sftp_packets = ( else { printf "[unknown status %d]", $status; } print "\n"; }, -#define SSH_FXP_HANDLE 102 /* 0x66 */ +#define SSH_FXP_HANDLE 102 /* 0x66 */ 0x66 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $handle) = &parse("us", $data); @@ -976,7 +976,7 @@ my %sftp_packets = ( printf " \"%s\"", &stringescape($handle); print "\n"; }, -#define SSH_FXP_DATA 103 /* 0x67 */ +#define SSH_FXP_DATA 103 /* 0x67 */ 0x67 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $retdata) = &parse("us", $data); @@ -984,7 +984,7 @@ my %sftp_packets = ( printf " [%d bytes]", length $retdata; print "\n"; }, -#define SSH_FXP_NAME 104 /* 0x68 */ +#define SSH_FXP_NAME 104 /* 0x68 */ 0x68 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $count) = &parse("uu", $data); @@ -996,7 +996,7 @@ my %sftp_packets = ( } print "\n"; }, -#define SSH_FXP_ATTRS 105 /* 0x69 */ +#define SSH_FXP_ATTRS 105 /* 0x69 */ 0x69 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid) = &parse("u", $data); @@ -1005,7 +1005,7 @@ my %sftp_packets = ( printf " %s", $attrs; print "\n"; }, -#define SSH_FXP_EXTENDED 200 /* 0xc8 */ +#define SSH_FXP_EXTENDED 200 /* 0xc8 */ 0xc8 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid, $type) = &parse("us", $data); @@ -1013,7 +1013,7 @@ my %sftp_packets = ( printf " \"%s\"", $type; print "\n"; }, -#define SSH_FXP_EXTENDED_REPLY 201 /* 0xc9 */ +#define SSH_FXP_EXTENDED_REPLY 201 /* 0xc9 */ 0xc9 => sub { my ($chan, $index, $direction, $id, $data) = @_; my ($reqid) = &parse("u", $data); diff --git a/cproxy.c b/cproxy.c index 0c2e62fe..e1d788b6 100644 --- a/cproxy.c +++ b/cproxy.c @@ -16,7 +16,7 @@ #include "marshal.h" static void hmacmd5_chap(const unsigned char *challenge, int challen, - const char *passwd, unsigned char *response) + const char *passwd, unsigned char *response) { mac_simple(&ssh_hmac_md5, ptrlen_from_asciz(passwd), make_ptrlen(challenge, challen), response); @@ -42,103 +42,103 @@ int proxy_socks5_handlechap (ProxySocket *p) unsigned char outbuf[20]; while(p->chap_num_attributes == 0 || - p->chap_num_attributes_processed < p->chap_num_attributes) { - if (p->chap_num_attributes == 0 || - p->chap_current_attribute == -1) { - /* CHAP normally reads in two bytes, either at the - * beginning or for each attribute/value pair. But if - * we're waiting for the value's data, we might not want - * to read 2 bytes. - */ - - if (bufchain_size(&p->pending_input_data) < 2) - return 1; /* not got anything yet */ + p->chap_num_attributes_processed < p->chap_num_attributes) { + if (p->chap_num_attributes == 0 || + p->chap_current_attribute == -1) { + /* CHAP normally reads in two bytes, either at the + * beginning or for each attribute/value pair. But if + * we're waiting for the value's data, we might not want + * to read 2 bytes. + */ - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, 2); - bufchain_consume(&p->pending_input_data, 2); - } + if (bufchain_size(&p->pending_input_data) < 2) + return 1; /* not got anything yet */ - if (p->chap_num_attributes == 0) { - /* If there are no attributes, this is our first msg - * with the server, where we negotiate version and - * number of attributes - */ - if (data[0] != 0x01) { - plug_closing(p->plug, "Proxy error: SOCKS proxy wants" - " a different CHAP version", - PROXY_ERROR_GENERAL, 0); - return 1; - } - if (data[1] == 0x00) { - plug_closing(p->plug, "Proxy error: SOCKS proxy won't" - " negotiate CHAP with us", - PROXY_ERROR_GENERAL, 0); - return 1; - } - p->chap_num_attributes = data[1]; - } else { - if (p->chap_current_attribute == -1) { - /* We have to read in each attribute/value pair - - * those we don't understand can be ignored, but - * there are a few we'll need to handle. - */ - p->chap_current_attribute = data[0]; - p->chap_current_datalen = data[1]; - } - if (bufchain_size(&p->pending_input_data) < - p->chap_current_datalen) - return 1; /* not got everything yet */ + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, 2); + bufchain_consume(&p->pending_input_data, 2); + } - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, - p->chap_current_datalen); + if (p->chap_num_attributes == 0) { + /* If there are no attributes, this is our first msg + * with the server, where we negotiate version and + * number of attributes + */ + if (data[0] != 0x01) { + plug_closing(p->plug, "Proxy error: SOCKS proxy wants" + " a different CHAP version", + PROXY_ERROR_GENERAL, 0); + return 1; + } + if (data[1] == 0x00) { + plug_closing(p->plug, "Proxy error: SOCKS proxy won't" + " negotiate CHAP with us", + PROXY_ERROR_GENERAL, 0); + return 1; + } + p->chap_num_attributes = data[1]; + } else { + if (p->chap_current_attribute == -1) { + /* We have to read in each attribute/value pair - + * those we don't understand can be ignored, but + * there are a few we'll need to handle. + */ + p->chap_current_attribute = data[0]; + p->chap_current_datalen = data[1]; + } + if (bufchain_size(&p->pending_input_data) < + p->chap_current_datalen) + return 1; /* not got everything yet */ - bufchain_consume(&p->pending_input_data, - p->chap_current_datalen); + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, + p->chap_current_datalen); - switch (p->chap_current_attribute) { - case 0x00: - /* Successful authentication */ - if (data[0] == 0x00) - p->state = 2; - else { - plug_closing(p->plug, "Proxy error: SOCKS proxy" - " refused CHAP authentication", - PROXY_ERROR_GENERAL, 0); - return 1; - } - break; - case 0x03: - outbuf[0] = 0x01; /* Version */ - outbuf[1] = 0x01; /* One attribute */ - outbuf[2] = 0x04; /* Response */ - outbuf[3] = 0x10; /* Length */ - hmacmd5_chap(data, p->chap_current_datalen, - conf_get_str(p->conf, CONF_proxy_password), - &outbuf[4]); - sk_write(p->sub_socket, outbuf, 20); - break; - case 0x11: - /* Chose a protocol */ - if (data[0] != 0x85) { - plug_closing(p->plug, "Proxy error: Server chose " - "CHAP of other than HMAC-MD5 but we " - "didn't offer it!", - PROXY_ERROR_GENERAL, 0); - return 1; - } - break; - } - p->chap_current_attribute = -1; - p->chap_num_attributes_processed++; - } - if (p->state == 8 && - p->chap_num_attributes_processed >= p->chap_num_attributes) { - p->chap_num_attributes = 0; - p->chap_num_attributes_processed = 0; - p->chap_current_datalen = 0; - } + bufchain_consume(&p->pending_input_data, + p->chap_current_datalen); + + switch (p->chap_current_attribute) { + case 0x00: + /* Successful authentication */ + if (data[0] == 0x00) + p->state = 2; + else { + plug_closing(p->plug, "Proxy error: SOCKS proxy" + " refused CHAP authentication", + PROXY_ERROR_GENERAL, 0); + return 1; + } + break; + case 0x03: + outbuf[0] = 0x01; /* Version */ + outbuf[1] = 0x01; /* One attribute */ + outbuf[2] = 0x04; /* Response */ + outbuf[3] = 0x10; /* Length */ + hmacmd5_chap(data, p->chap_current_datalen, + conf_get_str(p->conf, CONF_proxy_password), + &outbuf[4]); + sk_write(p->sub_socket, outbuf, 20); + break; + case 0x11: + /* Chose a protocol */ + if (data[0] != 0x85) { + plug_closing(p->plug, "Proxy error: Server chose " + "CHAP of other than HMAC-MD5 but we " + "didn't offer it!", + PROXY_ERROR_GENERAL, 0); + return 1; + } + break; + } + p->chap_current_attribute = -1; + p->chap_num_attributes_processed++; + } + if (p->state == 8 && + p->chap_num_attributes_processed >= p->chap_num_attributes) { + p->chap_num_attributes = 0; + p->chap_num_attributes_processed = 0; + p->chap_current_datalen = 0; + } } return 0; } @@ -148,32 +148,32 @@ int proxy_socks5_selectchap(ProxySocket *p) char *username = conf_get_str(p->conf, CONF_proxy_username); char *password = conf_get_str(p->conf, CONF_proxy_password); if (username[0] || password[0]) { - char chapbuf[514]; - int ulen; - chapbuf[0] = '\x01'; /* Version */ - chapbuf[1] = '\x02'; /* Number of attributes sent */ - chapbuf[2] = '\x11'; /* First attribute - algorithms list */ - chapbuf[3] = '\x01'; /* Only one CHAP algorithm */ - chapbuf[4] = '\x85'; /* ...and it's HMAC-MD5, the core one */ - chapbuf[5] = '\x02'; /* Second attribute - username */ + char chapbuf[514]; + int ulen; + chapbuf[0] = '\x01'; /* Version */ + chapbuf[1] = '\x02'; /* Number of attributes sent */ + chapbuf[2] = '\x11'; /* First attribute - algorithms list */ + chapbuf[3] = '\x01'; /* Only one CHAP algorithm */ + chapbuf[4] = '\x85'; /* ...and it's HMAC-MD5, the core one */ + chapbuf[5] = '\x02'; /* Second attribute - username */ - ulen = strlen(username); - if (ulen > 255) ulen = 255; - if (ulen < 1) ulen = 1; + ulen = strlen(username); + if (ulen > 255) ulen = 255; + if (ulen < 1) ulen = 1; - chapbuf[6] = ulen; - memcpy(chapbuf+7, username, ulen); + chapbuf[6] = ulen; + memcpy(chapbuf+7, username, ulen); - sk_write(p->sub_socket, chapbuf, ulen + 7); - p->chap_num_attributes = 0; - p->chap_num_attributes_processed = 0; - p->chap_current_attribute = -1; - p->chap_current_datalen = 0; + sk_write(p->sub_socket, chapbuf, ulen + 7); + p->chap_num_attributes = 0; + p->chap_num_attributes_processed = 0; + p->chap_current_attribute = -1; + p->chap_current_datalen = 0; - p->state = 8; - } else - plug_closing(p->plug, "Proxy error: Server chose " - "CHAP authentication but we didn't offer it!", - PROXY_ERROR_GENERAL, 0); + p->state = 8; + } else + plug_closing(p->plug, "Proxy error: Server chose " + "CHAP authentication but we didn't offer it!", + PROXY_ERROR_GENERAL, 0); return 1; } diff --git a/dialog.c b/dialog.c index c1e0a2b6..f8004eee 100644 --- a/dialog.c +++ b/dialog.c @@ -17,8 +17,8 @@ int ctrl_path_elements(const char *path) { int i = 1; while (*path) { - if (*path == '/') i++; - path++; + if (*path == '/') i++; + path++; } return i; } @@ -29,14 +29,14 @@ int ctrl_path_compare(const char *p1, const char *p2) { int i = 0; while (*p1 || *p2) { - if ((*p1 == '/' || *p1 == '\0') && - (*p2 == '/' || *p2 == '\0')) - i++; /* a whole element matches, ooh */ - if (*p1 != *p2) - return i; /* mismatch */ - p1++, p2++; + if ((*p1 == '/' || *p1 == '\0') && + (*p2 == '/' || *p2 == '\0')) + i++; /* a whole element matches, ooh */ + if (*p1 != *p2) + return i; /* mismatch */ + p1++, p2++; } - return INT_MAX; /* exact match */ + return INT_MAX; /* exact match */ } struct controlbox *ctrl_new_box(void) @@ -57,10 +57,10 @@ void ctrl_free_box(struct controlbox *b) int i; for (i = 0; i < b->nctrlsets; i++) { - ctrl_free_set(b->ctrlsets[i]); + ctrl_free_set(b->ctrlsets[i]); } for (i = 0; i < b->nfrees; i++) - b->freefuncs[i](b->frees[i]); + b->freefuncs[i](b->frees[i]); sfree(b->ctrlsets); sfree(b->frees); sfree(b->freefuncs); @@ -75,7 +75,7 @@ void ctrl_free_set(struct controlset *s) sfree(s->boxname); sfree(s->boxtitle); for (i = 0; i < s->ncontrols; i++) { - ctrl_free(s->ctrls[i]); + ctrl_free(s->ctrls[i]); } sfree(s->ctrls); sfree(s); @@ -92,19 +92,19 @@ static int ctrl_find_set(struct controlbox *b, const char *path, bool start) last = 0; for (i = 0; i < b->nctrlsets; i++) { - thisone = ctrl_path_compare(path, b->ctrlsets[i]->pathname); - /* - * If `start' is true and there exists a controlset with - * exactly the path we've been given, we should return the - * index of the first such controlset we find. Otherwise, - * we should return the index of the first entry in which - * _fewer_ path elements match than they did last time. - */ - if ((start && thisone == INT_MAX) || thisone < last) - return i; - last = thisone; + thisone = ctrl_path_compare(path, b->ctrlsets[i]->pathname); + /* + * If `start' is true and there exists a controlset with + * exactly the path we've been given, we should return the + * index of the first such controlset we find. Otherwise, + * we should return the index of the first entry in which + * _fewer_ path elements match than they did last time. + */ + if ((start && thisone == INT_MAX) || thisone < last) + return i; + last = thisone; } - return b->nctrlsets; /* insert at end */ + return b->nctrlsets; /* insert at end */ } /* @@ -115,33 +115,33 @@ static int ctrl_find_set(struct controlbox *b, const char *path, bool start) int ctrl_find_path(struct controlbox *b, const char *path, int index) { if (index < 0) - index = ctrl_find_set(b, path, true); + index = ctrl_find_set(b, path, true); else - index++; + index++; if (index < b->nctrlsets && !strcmp(path, b->ctrlsets[index]->pathname)) - return index; + return index; else - return -1; + return -1; } /* Set up a panel title. */ struct controlset *ctrl_settitle(struct controlbox *b, - const char *path, const char *title) + const char *path, const char *title) { - + struct controlset *s = snew(struct controlset); int index = ctrl_find_set(b, path, true); s->pathname = dupstr(path); s->boxname = NULL; s->boxtitle = dupstr(title); s->ncontrols = s->ctrlsize = 0; - s->ncolumns = 0; /* this is a title! */ + s->ncolumns = 0; /* this is a title! */ s->ctrls = NULL; sgrowarray(b->ctrlsets, b->ctrlsetsize, b->nctrlsets); if (index < b->nctrlsets) - memmove(&b->ctrlsets[index+1], &b->ctrlsets[index], - (b->nctrlsets-index) * sizeof(*b->ctrlsets)); + memmove(&b->ctrlsets[index+1], &b->ctrlsets[index], + (b->nctrlsets-index) * sizeof(*b->ctrlsets)); b->ctrlsets[index] = s; b->nctrlsets++; return s; @@ -154,11 +154,11 @@ struct controlset *ctrl_getset(struct controlbox *b, const char *path, struct controlset *s; int index = ctrl_find_set(b, path, true); while (index < b->nctrlsets && - !strcmp(b->ctrlsets[index]->pathname, path)) { - if (b->ctrlsets[index]->boxname && - !strcmp(b->ctrlsets[index]->boxname, name)) - return b->ctrlsets[index]; - index++; + !strcmp(b->ctrlsets[index]->pathname, path)) { + if (b->ctrlsets[index]->boxname && + !strcmp(b->ctrlsets[index]->boxname, name)) + return b->ctrlsets[index]; + index++; } s = snew(struct controlset); s->pathname = dupstr(path); @@ -169,8 +169,8 @@ struct controlset *ctrl_getset(struct controlbox *b, const char *path, s->ctrls = NULL; sgrowarray(b->ctrlsets, b->ctrlsetsize, b->nctrlsets); if (index < b->nctrlsets) - memmove(&b->ctrlsets[index+1], &b->ctrlsets[index], - (b->nctrlsets-index) * sizeof(*b->ctrlsets)); + memmove(&b->ctrlsets[index+1], &b->ctrlsets[index], + (b->nctrlsets-index) * sizeof(*b->ctrlsets)); b->ctrlsets[index] = s; b->nctrlsets++; return s; @@ -205,8 +205,8 @@ void *ctrl_alloc(struct controlbox *b, size_t size) } static union control *ctrl_new(struct controlset *s, int type, - intorptr helpctx, handler_fn handler, - intorptr context) + intorptr helpctx, handler_fn handler, + intorptr context) { union control *c = snew(union control); sgrowarray(s->ctrls, s->ctrlsize, s->ncontrols); @@ -232,23 +232,23 @@ union control *ctrl_columns(struct controlset *s, int ncolumns, ...) c->columns.ncols = ncolumns; s->ncolumns = ncolumns; if (ncolumns == 1) { - c->columns.percentages = NULL; + c->columns.percentages = NULL; } else { - va_list ap; - int i; - c->columns.percentages = snewn(ncolumns, int); - va_start(ap, ncolumns); - for (i = 0; i < ncolumns; i++) - c->columns.percentages[i] = va_arg(ap, int); - va_end(ap); + va_list ap; + int i; + c->columns.percentages = snewn(ncolumns, int); + va_start(ap, ncolumns); + for (i = 0; i < ncolumns; i++) + c->columns.percentages[i] = va_arg(ap, int); + va_end(ap); } return c; } union control *ctrl_editbox(struct controlset *s, const char *label, char shortcut, int percentage, - intorptr helpctx, handler_fn handler, - intorptr context, intorptr context2) + intorptr helpctx, handler_fn handler, + intorptr context, intorptr context2) { union control *c = ctrl_new(s, CTRL_EDITBOX, helpctx, handler, context); c->editbox.label = label ? dupstr(label) : NULL; @@ -262,8 +262,8 @@ union control *ctrl_editbox(struct controlset *s, const char *label, union control *ctrl_combobox(struct controlset *s, const char *label, char shortcut, int percentage, - intorptr helpctx, handler_fn handler, - intorptr context, intorptr context2) + intorptr helpctx, handler_fn handler, + intorptr context, intorptr context2) { union control *c = ctrl_new(s, CTRL_EDITBOX, helpctx, handler, context); c->editbox.label = label ? dupstr(label) : NULL; @@ -282,8 +282,8 @@ union control *ctrl_combobox(struct controlset *s, const char *label, * is NO_SHORTCUT. */ union control *ctrl_radiobuttons(struct controlset *s, const char *label, - char shortcut, int ncolumns, intorptr helpctx, - handler_fn handler, intorptr context, ...) + char shortcut, int ncolumns, intorptr helpctx, + handler_fn handler, intorptr context, ...) { va_list ap; int i; @@ -298,17 +298,17 @@ union control *ctrl_radiobuttons(struct controlset *s, const char *label, va_start(ap, context); i = 0; while (va_arg(ap, char *) != NULL) { - i++; - if (c->radio.shortcut == NO_SHORTCUT) - (void)va_arg(ap, int); /* char promotes to int in arg lists */ - (void)va_arg(ap, intorptr); + i++; + if (c->radio.shortcut == NO_SHORTCUT) + (void)va_arg(ap, int); /* char promotes to int in arg lists */ + (void)va_arg(ap, intorptr); } va_end(ap); c->radio.nbuttons = i; if (c->radio.shortcut == NO_SHORTCUT) - c->radio.shortcuts = snewn(c->radio.nbuttons, char); + c->radio.shortcuts = snewn(c->radio.nbuttons, char); else - c->radio.shortcuts = NULL; + c->radio.shortcuts = NULL; c->radio.buttons = snewn(c->radio.nbuttons, char *); c->radio.buttondata = snewn(c->radio.nbuttons, intorptr); /* @@ -317,11 +317,11 @@ union control *ctrl_radiobuttons(struct controlset *s, const char *label, */ va_start(ap, context); for (i = 0; i < c->radio.nbuttons; i++) { - c->radio.buttons[i] = dupstr(va_arg(ap, char *)); - if (c->radio.shortcut == NO_SHORTCUT) - c->radio.shortcuts[i] = va_arg(ap, int); - /* char promotes to int in arg lists */ - c->radio.buttondata[i] = va_arg(ap, intorptr); + c->radio.buttons[i] = dupstr(va_arg(ap, char *)); + if (c->radio.shortcut == NO_SHORTCUT) + c->radio.shortcuts[i] = va_arg(ap, int); + /* char promotes to int in arg lists */ + c->radio.buttondata[i] = va_arg(ap, intorptr); } va_end(ap); return c; @@ -346,7 +346,7 @@ union control *ctrl_listbox(struct controlset *s, const char *label, union control *c = ctrl_new(s, CTRL_LISTBOX, helpctx, handler, context); c->listbox.label = label ? dupstr(label) : NULL; c->listbox.shortcut = shortcut; - c->listbox.height = 5; /* *shrug* a plausible default */ + c->listbox.height = 5; /* *shrug* a plausible default */ c->listbox.draglist = false; c->listbox.multisel = 0; c->listbox.percentwidth = 100; @@ -358,12 +358,12 @@ union control *ctrl_listbox(struct controlset *s, const char *label, union control *ctrl_droplist(struct controlset *s, const char *label, char shortcut, int percentage, intorptr helpctx, - handler_fn handler, intorptr context) + handler_fn handler, intorptr context) { union control *c = ctrl_new(s, CTRL_LISTBOX, helpctx, handler, context); c->listbox.label = label ? dupstr(label) : NULL; c->listbox.shortcut = shortcut; - c->listbox.height = 0; /* means it's a drop-down list */ + c->listbox.height = 0; /* means it's a drop-down list */ c->listbox.draglist = false; c->listbox.multisel = 0; c->listbox.percentwidth = percentage; @@ -380,7 +380,7 @@ union control *ctrl_draglist(struct controlset *s, const char *label, union control *c = ctrl_new(s, CTRL_LISTBOX, helpctx, handler, context); c->listbox.label = label ? dupstr(label) : NULL; c->listbox.shortcut = shortcut; - c->listbox.height = 5; /* *shrug* a plausible default */ + c->listbox.height = 5; /* *shrug* a plausible default */ c->listbox.draglist = true; c->listbox.multisel = 0; c->listbox.percentwidth = 100; @@ -446,21 +446,21 @@ void ctrl_free(union control *ctrl) sfree(ctrl->generic.label); switch (ctrl->generic.type) { case CTRL_RADIO: - for (i = 0; i < ctrl->radio.nbuttons; i++) - sfree(ctrl->radio.buttons[i]); - sfree(ctrl->radio.buttons); - sfree(ctrl->radio.shortcuts); - sfree(ctrl->radio.buttondata); - break; + for (i = 0; i < ctrl->radio.nbuttons; i++) + sfree(ctrl->radio.buttons[i]); + sfree(ctrl->radio.buttons); + sfree(ctrl->radio.shortcuts); + sfree(ctrl->radio.buttondata); + break; case CTRL_COLUMNS: - sfree(ctrl->columns.percentages); - break; + sfree(ctrl->columns.percentages); + break; case CTRL_LISTBOX: - sfree(ctrl->listbox.percentages); - break; + sfree(ctrl->listbox.percentages); + break; case CTRL_FILESELECT: - sfree(ctrl->fileselect.title); - break; + sfree(ctrl->fileselect.title); + break; } sfree(ctrl); } diff --git a/dialog.h b/dialog.h index ac1601c7..e1887efd 100644 --- a/dialog.h +++ b/dialog.h @@ -5,7 +5,7 @@ /* * This is the big union which defines a single control, of any * type. - * + * * General principles: * - _All_ pointers in this structure are expected to point to * dynamically allocated things, unless otherwise indicated. @@ -20,16 +20,16 @@ #define NO_SHORTCUT '\0' enum { - CTRL_TEXT, /* just a static line of text */ - CTRL_EDITBOX, /* label plus edit box */ - CTRL_RADIO, /* label plus radio buttons */ - CTRL_CHECKBOX, /* checkbox (contains own label) */ - CTRL_BUTTON, /* simple push button (no label) */ - CTRL_LISTBOX, /* label plus list box */ - CTRL_COLUMNS, /* divide window into columns */ - CTRL_FILESELECT, /* label plus filename selector */ - CTRL_FONTSELECT, /* label plus font selector */ - CTRL_TABDELAY /* see `tabdelay' below */ + CTRL_TEXT, /* just a static line of text */ + CTRL_EDITBOX, /* label plus edit box */ + CTRL_RADIO, /* label plus radio buttons */ + CTRL_CHECKBOX, /* checkbox (contains own label) */ + CTRL_BUTTON, /* simple push button (no label) */ + CTRL_LISTBOX, /* label plus list box */ + CTRL_COLUMNS, /* divide window into columns */ + CTRL_FILESELECT, /* label plus filename selector */ + CTRL_FONTSELECT, /* label plus font selector */ + CTRL_TABDELAY /* see `tabdelay' below */ }; /* @@ -37,7 +37,7 @@ enum { * since the user might reasonably want to store either an integer * or a void * pointer. Here I define a union, and two convenience * functions to create that union from actual integers or pointers. - * + * * The convenience functions are declared as inline if possible. * Otherwise, they're declared here and defined when this header is * included with DEFINE_INTORPTR_FNS defined. This is a total pain, @@ -65,7 +65,7 @@ PREFIX intorptr P(void *p) { intorptr ret; ret.p = p; return ret; } * Each control has an `int' field specifying which columns it * occupies in a multi-column part of the dialog box. These macros * pack and unpack that field. - * + * * If a control belongs in exactly one column, just specifying the * column number is perfectly adequate. */ @@ -104,15 +104,15 @@ enum { EVENT_CALLBACK }; typedef void (*handler_fn)(union control *ctrl, dlgparam *dp, - void *data, int event); + void *data, int event); #define STANDARD_PREFIX \ - int type; \ - char *label; \ - bool tabdelay; \ - int column; \ + int type; \ + char *label; \ + bool tabdelay; \ + int column; \ handler_fn handler; \ - intorptr context; \ + intorptr context; \ intorptr helpctx union control { @@ -122,223 +122,223 @@ union control { * to access through any one of them. */ struct { - int type; - /* - * Every control except CTRL_COLUMNS has _some_ sort of - * label. By putting it in the `generic' union as well as - * everywhere else, we avoid having to have an irritating - * switch statement when we go through and deallocate all - * the memory in a config-box structure. - * - * Yes, this does mean that any non-NULL value in this - * field is expected to be dynamically allocated and - * freeable. - * - * For CTRL_COLUMNS, this field MUST be NULL. - */ - char *label; - /* - * If `tabdelay' is non-zero, it indicates that this - * particular control should not yet appear in the tab - * order. A subsequent CTRL_TABDELAY entry will place it. - */ - bool tabdelay; - /* - * Indicate which column(s) this control occupies. This can - * be unpacked into starting column and column span by the - * COLUMN macros above. - */ - int column; - /* - * Most controls need to provide a function which gets - * called when that control's setting is changed, or when - * the control's setting needs initialising. - * - * The `data' parameter points to the writable data being - * modified as a result of the configuration activity; for - * example, the PuTTY `Conf' structure, although not - * necessarily. - * - * The `dlg' parameter is passed back to the platform- - * specific routines to read and write the actual control - * state. - */ - handler_fn handler; - /* - * Almost all of the above functions will find it useful to - * be able to store a piece of `void *' or `int' data. - */ - intorptr context; - /* - * For any control, we also allow the storage of a piece of - * data for use by context-sensitive help. For example, on - * Windows you can click the magic question mark and then - * click a control, and help for that control should spring - * up. Hence, here is a slot in which to store per-control - * data that a particular platform-specific driver can use - * to ensure it brings up the right piece of help text. - */ - intorptr helpctx; + int type; + /* + * Every control except CTRL_COLUMNS has _some_ sort of + * label. By putting it in the `generic' union as well as + * everywhere else, we avoid having to have an irritating + * switch statement when we go through and deallocate all + * the memory in a config-box structure. + * + * Yes, this does mean that any non-NULL value in this + * field is expected to be dynamically allocated and + * freeable. + * + * For CTRL_COLUMNS, this field MUST be NULL. + */ + char *label; + /* + * If `tabdelay' is non-zero, it indicates that this + * particular control should not yet appear in the tab + * order. A subsequent CTRL_TABDELAY entry will place it. + */ + bool tabdelay; + /* + * Indicate which column(s) this control occupies. This can + * be unpacked into starting column and column span by the + * COLUMN macros above. + */ + int column; + /* + * Most controls need to provide a function which gets + * called when that control's setting is changed, or when + * the control's setting needs initialising. + * + * The `data' parameter points to the writable data being + * modified as a result of the configuration activity; for + * example, the PuTTY `Conf' structure, although not + * necessarily. + * + * The `dlg' parameter is passed back to the platform- + * specific routines to read and write the actual control + * state. + */ + handler_fn handler; + /* + * Almost all of the above functions will find it useful to + * be able to store a piece of `void *' or `int' data. + */ + intorptr context; + /* + * For any control, we also allow the storage of a piece of + * data for use by context-sensitive help. For example, on + * Windows you can click the magic question mark and then + * click a control, and help for that control should spring + * up. Hence, here is a slot in which to store per-control + * data that a particular platform-specific driver can use + * to ensure it brings up the right piece of help text. + */ + intorptr helpctx; } generic; struct { - STANDARD_PREFIX; - union control *ctrl; + STANDARD_PREFIX; + union control *ctrl; } tabdelay; struct { - STANDARD_PREFIX; + STANDARD_PREFIX; } text; struct { - STANDARD_PREFIX; - char shortcut; /* keyboard shortcut */ - /* - * Percentage of the dialog-box width used by the edit box. - * If this is set to 100, the label is on its own line; - * otherwise the label is on the same line as the box - * itself. - */ - int percentwidth; - bool password; /* details of input are hidden */ - /* - * A special case of the edit box is the combo box, which - * has a drop-down list built in. (Note that a _non_- - * editable drop-down list is done as a special case of a - * list box.) - * - * Don't try setting has_list and password on the same - * control; front ends are not required to support that - * combination. - */ - bool has_list; - /* - * Edit boxes tend to need two items of context, so here's - * a spare. - */ - intorptr context2; + STANDARD_PREFIX; + char shortcut; /* keyboard shortcut */ + /* + * Percentage of the dialog-box width used by the edit box. + * If this is set to 100, the label is on its own line; + * otherwise the label is on the same line as the box + * itself. + */ + int percentwidth; + bool password; /* details of input are hidden */ + /* + * A special case of the edit box is the combo box, which + * has a drop-down list built in. (Note that a _non_- + * editable drop-down list is done as a special case of a + * list box.) + * + * Don't try setting has_list and password on the same + * control; front ends are not required to support that + * combination. + */ + bool has_list; + /* + * Edit boxes tend to need two items of context, so here's + * a spare. + */ + intorptr context2; } editbox; struct { - STANDARD_PREFIX; - /* - * `shortcut' here is a single keyboard shortcut which is - * expected to select the whole group of radio buttons. It - * can be NO_SHORTCUT if required, and there is also a way - * to place individual shortcuts on each button; see below. - */ - char shortcut; - /* - * There are separate fields for `ncolumns' and `nbuttons' - * for several reasons. - * - * Firstly, we sometimes want the last of a set of buttons - * to have a longer label than the rest; we achieve this by - * setting `ncolumns' higher than `nbuttons', and the - * layout code is expected to understand that the final - * button should be given all the remaining space on the - * line. This sounds like a ludicrously specific special - * case (if we're doing this sort of thing, why not have - * the general ability to have a particular button span - * more than one column whether it's the last one or not?) - * but actually it's reasonably common for the sort of - * three-way control you get a lot of in PuTTY: `yes' - * versus `no' versus `some more complex way to decide'. - * - * Secondly, setting `nbuttons' higher than `ncolumns' lets - * us have more than one line of radio buttons for a single - * setting. A very important special case of this is - * setting `ncolumns' to 1, so that each button is on its - * own line. - */ - int ncolumns; - int nbuttons; - /* - * This points to a dynamically allocated array of `char *' - * pointers, each of which points to a dynamically - * allocated string. - */ - char **buttons; /* `nbuttons' button labels */ - /* - * This points to a dynamically allocated array of `char' - * giving the individual keyboard shortcuts for each radio - * button. The array may be NULL if none are required. - */ - char *shortcuts; /* `nbuttons' shortcuts; may be NULL */ - /* - * This points to a dynamically allocated array of - * intorptr, giving helpful data for each button. - */ - intorptr *buttondata; /* `nbuttons' entries; may be NULL */ + STANDARD_PREFIX; + /* + * `shortcut' here is a single keyboard shortcut which is + * expected to select the whole group of radio buttons. It + * can be NO_SHORTCUT if required, and there is also a way + * to place individual shortcuts on each button; see below. + */ + char shortcut; + /* + * There are separate fields for `ncolumns' and `nbuttons' + * for several reasons. + * + * Firstly, we sometimes want the last of a set of buttons + * to have a longer label than the rest; we achieve this by + * setting `ncolumns' higher than `nbuttons', and the + * layout code is expected to understand that the final + * button should be given all the remaining space on the + * line. This sounds like a ludicrously specific special + * case (if we're doing this sort of thing, why not have + * the general ability to have a particular button span + * more than one column whether it's the last one or not?) + * but actually it's reasonably common for the sort of + * three-way control you get a lot of in PuTTY: `yes' + * versus `no' versus `some more complex way to decide'. + * + * Secondly, setting `nbuttons' higher than `ncolumns' lets + * us have more than one line of radio buttons for a single + * setting. A very important special case of this is + * setting `ncolumns' to 1, so that each button is on its + * own line. + */ + int ncolumns; + int nbuttons; + /* + * This points to a dynamically allocated array of `char *' + * pointers, each of which points to a dynamically + * allocated string. + */ + char **buttons; /* `nbuttons' button labels */ + /* + * This points to a dynamically allocated array of `char' + * giving the individual keyboard shortcuts for each radio + * button. The array may be NULL if none are required. + */ + char *shortcuts; /* `nbuttons' shortcuts; may be NULL */ + /* + * This points to a dynamically allocated array of + * intorptr, giving helpful data for each button. + */ + intorptr *buttondata; /* `nbuttons' entries; may be NULL */ } radio; struct { - STANDARD_PREFIX; - char shortcut; + STANDARD_PREFIX; + char shortcut; } checkbox; struct { - STANDARD_PREFIX; - char shortcut; - /* - * At least Windows has the concept of a `default push - * button', which gets implicitly pressed when you hit - * Return even if it doesn't have the input focus. - */ - bool isdefault; - /* - * Also, the reverse of this: a default cancel-type button, - * which is implicitly pressed when you hit Escape. - */ - bool iscancel; + STANDARD_PREFIX; + char shortcut; + /* + * At least Windows has the concept of a `default push + * button', which gets implicitly pressed when you hit + * Return even if it doesn't have the input focus. + */ + bool isdefault; + /* + * Also, the reverse of this: a default cancel-type button, + * which is implicitly pressed when you hit Escape. + */ + bool iscancel; } button; struct { - STANDARD_PREFIX; - char shortcut; /* keyboard shortcut */ - /* - * Height of the list box, in approximate number of lines. - * If this is zero, the list is a drop-down list. - */ - int height; /* height in lines */ - /* - * If this is set, the list elements can be reordered by - * the user (by drag-and-drop or by Up and Down buttons, - * whatever the per-platform implementation feels - * comfortable with). This is not guaranteed to work on a - * drop-down list, so don't try it! - */ - bool draglist; - /* - * If this is non-zero, the list can have more than one - * element selected at a time. This is not guaranteed to - * work on a drop-down list, so don't try it! - * - * Different non-zero values request slightly different - * types of multi-selection (this may well be meaningful - * only in GTK, so everyone else can ignore it if they - * want). 1 means the list box expects to have individual - * items selected, whereas 2 means it expects the user to - * want to select a large contiguous range at a time. - */ - int multisel; - /* - * Percentage of the dialog-box width used by the list box. - * If this is set to 100, the label is on its own line; - * otherwise the label is on the same line as the box - * itself. Setting this to anything other than 100 is not - * guaranteed to work on a _non_-drop-down list, so don't - * try it! - */ - int percentwidth; - /* - * Some list boxes contain strings that contain tab - * characters. If `ncols' is greater than 0, then - * `percentages' is expected to be non-zero and to contain - * the respective widths of `ncols' columns, which together - * will exactly fit the width of the list box. Otherwise - * `percentages' must be NULL. - * - * There should never be more than one column in a - * drop-down list (one with height==0), because front ends - * may have to implement it as a special case of an - * editable combo box. - */ - int ncols; /* number of columns */ - int *percentages; /* % width of each column */ + STANDARD_PREFIX; + char shortcut; /* keyboard shortcut */ + /* + * Height of the list box, in approximate number of lines. + * If this is zero, the list is a drop-down list. + */ + int height; /* height in lines */ + /* + * If this is set, the list elements can be reordered by + * the user (by drag-and-drop or by Up and Down buttons, + * whatever the per-platform implementation feels + * comfortable with). This is not guaranteed to work on a + * drop-down list, so don't try it! + */ + bool draglist; + /* + * If this is non-zero, the list can have more than one + * element selected at a time. This is not guaranteed to + * work on a drop-down list, so don't try it! + * + * Different non-zero values request slightly different + * types of multi-selection (this may well be meaningful + * only in GTK, so everyone else can ignore it if they + * want). 1 means the list box expects to have individual + * items selected, whereas 2 means it expects the user to + * want to select a large contiguous range at a time. + */ + int multisel; + /* + * Percentage of the dialog-box width used by the list box. + * If this is set to 100, the label is on its own line; + * otherwise the label is on the same line as the box + * itself. Setting this to anything other than 100 is not + * guaranteed to work on a _non_-drop-down list, so don't + * try it! + */ + int percentwidth; + /* + * Some list boxes contain strings that contain tab + * characters. If `ncols' is greater than 0, then + * `percentages' is expected to be non-zero and to contain + * the respective widths of `ncols' columns, which together + * will exactly fit the width of the list box. Otherwise + * `percentages' must be NULL. + * + * There should never be more than one column in a + * drop-down list (one with height==0), because front ends + * may have to implement it as a special case of an + * editable combo box. + */ + int ncols; /* number of columns */ + int *percentages; /* % width of each column */ /* * Flag which can be set to false to suppress the horizontal * scroll bar if a list box entry goes off the right-hand @@ -347,62 +347,62 @@ union control { bool hscroll; } listbox; struct { - STANDARD_PREFIX; - char shortcut; - /* - * `filter' dictates what type of files will be selected by - * default; for example, when selecting private key files - * the file selector would do well to only show .PPK files - * (on those systems where this is the chosen extension). - * - * The precise contents of `filter' are platform-defined, - * unfortunately. The special value NULL means `all files' - * and is always a valid fallback. - * - * Unlike almost all strings in this structure, this value - * is NOT expected to require freeing (although of course - * you can always use ctrl_alloc if you do need to create - * one on the fly). This is because the likely mode of use - * is to define string constants in a platform-specific - * header file, and directly reference those. Or worse, a - * particular platform might choose to cast integers into - * this pointer type... - */ - char const *filter; - /* - * Some systems like to know whether a file selector is - * choosing a file to read or one to write (and possibly - * create). - */ - bool for_writing; - /* - * On at least some platforms, the file selector is a - * separate dialog box, and contains a user-settable title. - * - * This value _is_ expected to require freeing. - */ - char *title; + STANDARD_PREFIX; + char shortcut; + /* + * `filter' dictates what type of files will be selected by + * default; for example, when selecting private key files + * the file selector would do well to only show .PPK files + * (on those systems where this is the chosen extension). + * + * The precise contents of `filter' are platform-defined, + * unfortunately. The special value NULL means `all files' + * and is always a valid fallback. + * + * Unlike almost all strings in this structure, this value + * is NOT expected to require freeing (although of course + * you can always use ctrl_alloc if you do need to create + * one on the fly). This is because the likely mode of use + * is to define string constants in a platform-specific + * header file, and directly reference those. Or worse, a + * particular platform might choose to cast integers into + * this pointer type... + */ + char const *filter; + /* + * Some systems like to know whether a file selector is + * choosing a file to read or one to write (and possibly + * create). + */ + bool for_writing; + /* + * On at least some platforms, the file selector is a + * separate dialog box, and contains a user-settable title. + * + * This value _is_ expected to require freeing. + */ + char *title; } fileselect; struct { - /* In this variant, `label' MUST be NULL. */ - STANDARD_PREFIX; - int ncols; /* number of columns */ - int *percentages; /* % width of each column */ - /* - * Every time this control type appears, exactly one of - * `ncols' and the previous number of columns MUST be one. - * Attempting to allow a seamless transition from a four- - * to a five-column layout, for example, would be way more - * trouble than it was worth. If you must lay things out - * like that, define eight unevenly sized columns and use - * column-spanning a lot. But better still, just don't. - * - * `percentages' may be NULL if ncols==1, to save space. - */ + /* In this variant, `label' MUST be NULL. */ + STANDARD_PREFIX; + int ncols; /* number of columns */ + int *percentages; /* % width of each column */ + /* + * Every time this control type appears, exactly one of + * `ncols' and the previous number of columns MUST be one. + * Attempting to allow a seamless transition from a four- + * to a five-column layout, for example, would be way more + * trouble than it was worth. If you must lay things out + * like that, define eight unevenly sized columns and use + * column-spanning a lot. But better still, just don't. + * + * `percentages' may be NULL if ncols==1, to save space. + */ } columns; struct { - STANDARD_PREFIX; - char shortcut; + STANDARD_PREFIX; + char shortcut; } fontselect; }; @@ -413,18 +413,18 @@ union control { * structures, together with a panel name and a title for the whole * set. In Windows and any similar-looking GUI, each `controlset' * in the config will be a container box within a panel. - * + * * Special case: if `boxname' is NULL, the control set gives an * overall title for an entire panel of controls. */ struct controlset { - char *pathname; /* panel path, e.g. "SSH/Tunnels" */ - char *boxname; /* internal short name of controlset */ - char *boxtitle; /* title of container box */ - int ncolumns; /* current no. of columns at bottom */ + char *pathname; /* panel path, e.g. "SSH/Tunnels" */ + char *boxname; /* internal short name of controlset */ + char *boxtitle; /* title of container box */ + int ncolumns; /* current no. of columns at bottom */ size_t ncontrols; /* number of `union control' in array */ size_t ctrlsize; /* allocated size of array */ - union control **ctrls; /* actual array */ + union control **ctrls; /* actual array */ }; typedef void (*ctrl_freefn_t)(void *); /* used by ctrl_alloc_with_free */ @@ -434,12 +434,12 @@ typedef void (*ctrl_freefn_t)(void *); /* used by ctrl_alloc_with_free */ * controls. */ struct controlbox { - size_t nctrlsets; /* number of ctrlsets */ - size_t ctrlsetsize; /* ctrlset size */ + size_t nctrlsets; /* number of ctrlsets */ + size_t ctrlsetsize; /* ctrlset size */ struct controlset **ctrlsets; /* actual array of ctrlsets */ size_t nfrees; size_t freesize; - void **frees; /* array of aux data areas to free */ + void **frees; /* array of aux data areas to free */ ctrl_freefn_t *freefuncs; /* parallel array of free functions */ }; @@ -452,7 +452,7 @@ void ctrl_free_box(struct controlbox *); /* Set up a panel title. */ struct controlset *ctrl_settitle(struct controlbox *, - const char *path, const char *title); + const char *path, const char *title); /* Retrieve a pointer to a controlset, creating it if absent. */ struct controlset *ctrl_getset(struct controlbox *, const char *path, const char *name, const char *boxtitle); @@ -478,7 +478,7 @@ void *ctrl_alloc_with_free(struct controlbox *b, size_t size, /* * Individual routines to create `union control' structures in a controlset. - * + * * Most of these routines allow the most common fields to be set * directly, and put default values in the rest. Each one returns a * pointer to the `union control' it created, so that final tweaks @@ -489,12 +489,12 @@ void *ctrl_alloc_with_free(struct controlbox *b, size_t size, union control *ctrl_columns(struct controlset *, int ncolumns, ...); union control *ctrl_editbox(struct controlset *, const char *label, char shortcut, int percentage, intorptr helpctx, - handler_fn handler, - intorptr context, intorptr context2); + handler_fn handler, + intorptr context, intorptr context2); union control *ctrl_combobox(struct controlset *, const char *label, char shortcut, int percentage, intorptr helpctx, - handler_fn handler, - intorptr context, intorptr context2); + handler_fn handler, + intorptr context, intorptr context2); /* * `ncolumns' is followed by (alternately) radio button titles and * intorptrs, until a NULL in place of a title string is seen. Each @@ -502,32 +502,32 @@ union control *ctrl_combobox(struct controlset *, const char *label, * is NO_SHORTCUT. */ union control *ctrl_radiobuttons(struct controlset *, const char *label, - char shortcut, int ncolumns, intorptr helpctx, - handler_fn handler, intorptr context, ...); + char shortcut, int ncolumns, intorptr helpctx, + handler_fn handler, intorptr context, ...); union control *ctrl_pushbutton(struct controlset *, const char *label, char shortcut, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_listbox(struct controlset *, const char *label, char shortcut, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_droplist(struct controlset *, const char *label, char shortcut, int percentage, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_draglist(struct controlset *, const char *label, char shortcut, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_filesel(struct controlset *, const char *label, char shortcut, const char *filter, bool write, const char *title, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_fontsel(struct controlset *, const char *label, char shortcut, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_text(struct controlset *, const char *text, intorptr helpctx); union control *ctrl_checkbox(struct controlset *, const char *label, char shortcut, intorptr helpctx, - handler_fn handler, intorptr context); + handler_fn handler, intorptr context); union control *ctrl_tabdelay(struct controlset *, union control *); /* @@ -552,7 +552,7 @@ void dlg_listbox_add(union control *ctrl, dlgparam *dp, char const *text); * IDs and expect to get meaningful results back. */ void dlg_listbox_addwithid(union control *ctrl, dlgparam *dp, - char const *text, int id); + char const *text, int id); int dlg_listbox_getid(union control *ctrl, dlgparam *dp, int index); /* dlg_listbox_index returns <0 if no single element is selected. */ int dlg_listbox_index(union control *ctrl, dlgparam *dp); @@ -612,12 +612,12 @@ void dlg_end(dlgparam *dp, int value); * dlg_coloursel_results() fetches the results, as integers from 0 * to 255; it returns nonzero on success, or zero if the colour * selector was dismissed by hitting Cancel or similar. - * + * * dlg_coloursel_start() accepts an RGB triple which is used to * initialise the colour selector to its starting value. */ void dlg_coloursel_start(union control *ctrl, dlgparam *dp, - int r, int g, int b); + int r, int g, int b); bool dlg_coloursel_results(union control *ctrl, dlgparam *dp, int *r, int *g, int *b); @@ -626,7 +626,7 @@ bool dlg_coloursel_results(union control *ctrl, dlgparam *dp, * indicate that the value of a particular control is likely to * have changed. It triggers a call of the handler for that control * with `event' set to EVENT_REFRESH. - * + * * If `ctrl' is NULL, _all_ controls in the dialog get refreshed * (for loading or saving entire sets of settings). */ @@ -640,8 +640,8 @@ void dlg_refresh(union control *ctrl, dlgparam *dp); * Find the index of next controlset in a controlbox for a given * path, or -1 if no such controlset exists. If -1 is passed as * input, finds the first. Intended usage is something like - * - * for (index=-1; (index=ctrl_find_path(ctrlbox, index, path)) >= 0 ;) { + * + * for (index=-1; (index=ctrl_find_path(ctrlbox, index, path)) >= 0 ;) { * ... process this controlset ... * } */ diff --git a/doc/config.but b/doc/config.but index 58ed670f..ee179668 100644 --- a/doc/config.but +++ b/doc/config.but @@ -359,8 +359,8 @@ Most servers send two control characters, \i{CR} and \i{LF}, to start a left-hand side of the screen. The LF character makes the cursor move one line down (and might make the screen scroll). -Some servers only send CR, and so the newly -written line is overwritten by the following line. This option causes +Some servers only send CR, and so the newly +written line is overwritten by the following line. This option causes a line feed so that all lines are displayed. \S{config-erase} \q{Use \i{background colour} to erase screen} @@ -1194,7 +1194,7 @@ characters should be treated as single-width for the purposes of \I{wrapping, terminal}wrapping and so on; however, in some CJK contexts, they are better treated as double-width for historical reasons, and some server-side applications may expect them to be displayed as such. Setting this option -will cause PuTTY to take the double-width interpretation. +will cause PuTTY to take the double-width interpretation. If you use legacy CJK applications, and you find your lines are wrapping in the wrong places, or you are having other display @@ -1508,7 +1508,7 @@ If you enable \q{Copy to clipboard in RTF as well as plain text}, PuTTY will write formatting information to the clipboard as well as the actual text you copy. The effect of this is that if you paste into (say) a word processor, the text will appear -in the word processor in the same \i{font}, \i{colour}, and style +in the word processor in the same \i{font}, \i{colour}, and style (e.g. bold, underline) PuTTY was using to display it. This option can easily be inconvenient, so by default it is @@ -2053,7 +2053,7 @@ itself. Also, the special strings \c{%host} and \c{%port} will be replaced by the host name and port number you want to connect to. The strings -\c{%user} and \c{%pass} will be replaced by the proxy username and +\c{%user} and \c{%pass} will be replaced by the proxy username and password you specify. The strings \c{%proxyhost} and \c{%proxyport} will be replaced by the host details specified on the \e{Proxy} panel, if any (this is most likely to be useful for the Local proxy type). @@ -2064,8 +2064,8 @@ before commands can be sent, you can use a command such as: \c %user\n%pass\nconnect %host %port\n -This will send your username and password as the first two lines to -the proxy, followed by a command to connect to the desired host and +This will send your username and password as the first two lines to +the proxy, followed by a command to connect to the desired host and port. Note that if you do not include the \c{%user} or \c{%pass} tokens in the Telnet command, then the \q{Username} and \q{Password} configuration fields will be ignored. @@ -3565,13 +3565,13 @@ once it's been successfully saved back to the file. Here is \c{PUTTYDEL.REG}: \c REGEDIT4 -\c +\c \c [-HKEY_CURRENT_USER\Software\SimonTatham\PuTTY] Here is an example \c{PUTTYRND.REG} file: \c REGEDIT4 -\c +\c \c [HKEY_CURRENT_USER\Software\SimonTatham\PuTTY] \c "RandSeedFile"="a:\\putty.rnd" diff --git a/doc/errors.but b/doc/errors.but index a9c15c1a..ee88c002 100644 --- a/doc/errors.but +++ b/doc/errors.but @@ -193,7 +193,7 @@ Various forms of this error are printed in the PuTTY window, or written to the PuTTY Event Log (see \k{using-eventlog}) during authentication. -If you see one of these messages, it means that the server has refused +If you see one of these messages, it means that the server has refused all the forms of authentication PuTTY has tried and it has no further ideas. @@ -231,7 +231,7 @@ noticed. Occasionally this has been caused by server bugs. An example is the bug described at \k{config-ssh-bug-hmac2}, although you're very -unlikely to encounter that one these days. +unlikely to encounter that one these days. In this context MAC stands for \ii{Message Authentication Code}. It's a cryptographic term, and it has nothing at all to do with Ethernet diff --git a/doc/faq.but b/doc/faq.but index a790c18d..8977703d 100644 --- a/doc/faq.but +++ b/doc/faq.but @@ -166,7 +166,7 @@ will not. Adding an option to turn host key checking off completely is the wrong solution and we will not do it. If you have host keys available in the common \i\c{known_hosts} format, -we have a script called +we have a script called \W{https://git.tartarus.org/?p=simon/putty.git;a=blob;f=contrib/kh2reg.py;hb=HEAD}\c{kh2reg.py} to convert them to a Windows .REG file, which can be installed ahead of time by double-clicking or using \c{REGEDIT}. @@ -241,7 +241,7 @@ present time. If anyone told you we had an Android port, or an iOS port, or any other port of PuTTY, they were mistaken. We don't. There are some third-party ports to various platforms, mentioned -on the +on the \W{https://www.chiark.greenend.org.uk/~sgtatham/putty/links.html}{Links page of our website}. \S{faq-unix}{Question} \I{Unix version}Is there a port to Unix? @@ -991,7 +991,7 @@ means you need to use non-\cw{127.0.0.1} addresses to forward Terminal Services in the first place.) \S{faq-missing-slash}{Question} PSFTP commands seem to be missing a -directory separator (slash). +directory separator (slash). Some people have reported the following incorrect behaviour with PSFTP: diff --git a/doc/feedback.but b/doc/feedback.but index 2d8867e4..eb2fb5d5 100644 --- a/doc/feedback.but +++ b/doc/feedback.but @@ -148,7 +148,7 @@ information: use the \q{About PuTTY} option from the System menu. Please \e{do not} just tell us \q{I'm running the latest version}; e-mail can be delayed and it may not be obvious which version was the latest at -the time you sent the message. +the time you sent the message. \b PuTTY is a multi-platform application; tell us what version of what OS you are running PuTTY on. (If you're running on Unix, or Windows @@ -218,7 +218,7 @@ Secure Contact Key. See \k{pgpkeys-pubkey} for details of this. much information as possible about them, the same way you would with any other bug report.) -\H{feedback-features} Requesting extra features +\H{feedback-features} Requesting extra features If you want to request a new feature in PuTTY, the very first things you should do are: diff --git a/doc/plink.but b/doc/plink.but index d83495fd..ef5fb3a1 100644 --- a/doc/plink.but +++ b/doc/plink.but @@ -290,7 +290,7 @@ zero exit status if a usable \q{upstream} exists, nonzero otherwise. In some situations, Plink applies a sanitisation pass to the output received from the server, to strip out control characters such as backspace and the escape character. - + The idea of this is to prevent remote processes from sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like \cw{git} or CVS. If the @@ -418,7 +418,7 @@ labelled \q{Check for an alternate \cw{rsh} name} and in the text entry field to the right enter the full path to \c{plink.exe}. Select \q{OK} on the \q{Preferences} dialogue box. -Next, select \q{Command Line} from the WinCVS \q{Admin} menu, and type +Next, select \q{Command Line} from the WinCVS \q{Admin} menu, and type a CVS command as in \k{plink-cvs}, for example: \c cvs -d :ext:user@hostname:/path/to/repository co module diff --git a/doc/pscp.but b/doc/pscp.but index dbd2a993..da197713 100644 --- a/doc/pscp.but +++ b/doc/pscp.but @@ -78,7 +78,7 @@ familiar with that.) \S{pscp-usage-basics} The basics -To \I{receiving files}receive (a) file(s) from a remote server: +To \I{receiving files}receive (a) file(s) from a remote server: \c pscp [options] [user@]host:source target @@ -87,7 +87,7 @@ user \c{fred} to the file \c{c:\\temp\\example-hosts.txt}, you would type: \c pscp fred@example.com:/etc/hosts c:\temp\example-hosts.txt -To \I{sending files}send (a) file(s) to a remote server: +To \I{sending files}send (a) file(s) to a remote server: \c pscp [options] source [source...] [user@]host:target @@ -146,7 +146,7 @@ trying to get out of that directory using pathnames including \S2{pscp-usage-basics-user} \c{user} The \i{login name} on the remote server. If this is omitted, and \c{host} -is a PuTTY saved session, PSCP will use any username specified by that +is a PuTTY saved session, PSCP will use any username specified by that saved session. Otherwise, PSCP will attempt to use the local Windows username. @@ -160,8 +160,8 @@ number, cipher type and username will be used. One or more source files. \ii{Wildcards} are allowed. The syntax of wildcards depends on the system to which they apply, so if you are -copying \e{from} a Windows system \e{to} a UNIX system, you should use -Windows wildcard syntax (e.g. \c{*.*}), but if you are copying \e{from} +copying \e{from} a Windows system \e{to} a UNIX system, you should use +Windows wildcard syntax (e.g. \c{*.*}), but if you are copying \e{from} a UNIX system \e{to} a Windows system, you would use the wildcard syntax allowed by your UNIX shell (e.g. \c{*}). @@ -179,7 +179,7 @@ target of \c{.}. For example: \c pscp fred@example.com:/home/tom/.emacs . -...would copy \c{/home/tom/.emacs} on the remote server to the current +...would copy \c{/home/tom/.emacs} on the remote server to the current directory. As with the \c{source} parameter, if the target is on a remote server @@ -235,7 +235,7 @@ these statistics. By default, PSCP will only copy files. Any directories you specify to copy will be skipped, as will their contents. The \c{-r} option tells -PSCP to descend into any directories you specify, and to copy them and +PSCP to descend into any directories you specify, and to copy them and their contents. This allows you to use PSCP to transfer whole directory structures between machines. diff --git a/ecc.c b/ecc.c index acdc7d3f..82fd14d9 100644 --- a/ecc.c +++ b/ecc.c @@ -524,7 +524,7 @@ unsigned ecc_weierstrass_point_valid(WeierstrassPoint *P) mp_int *z6 = monty_mul(wc->mc, z2, z4); mp_int *bz6 = monty_mul(wc->mc, wc->b, z6); mp_int *rhs = monty_add(wc->mc, x3_plus_axz4, bz6); - + unsigned valid = mp_cmp_eq(lhs, rhs); mp_free(lhs); diff --git a/errsock.c b/errsock.c index e691dec2..a01e7cad 100644 --- a/errsock.c +++ b/errsock.c @@ -21,7 +21,7 @@ static Plug *sk_error_plug(Socket *s, Plug *p) ErrorSocket *es = container_of(s, ErrorSocket, sock); Plug *ret = es->plug; if (p) - es->plug = p; + es->plug = p; return ret; } diff --git a/fuzzterm.c b/fuzzterm.c index a54f6fc6..f1085589 100644 --- a/fuzzterm.c +++ b/fuzzterm.c @@ -13,34 +13,34 @@ static const TermWinVtable fuzz_termwin_vt; int main(int argc, char **argv) { - char blk[512]; - size_t len; - Terminal *term; - Conf *conf; - struct unicode_data ucsdata; + char blk[512]; + size_t len; + Terminal *term; + Conf *conf; + struct unicode_data ucsdata; TermWin termwin; termwin.vt = &fuzz_termwin_vt; - conf = conf_new(); - do_defaults(NULL, conf); - init_ucs(&ucsdata, conf_get_str(conf, CONF_line_codepage), - conf_get_bool(conf, CONF_utf8_override), - CS_NONE, conf_get_int(conf, CONF_vtmode)); + conf = conf_new(); + do_defaults(NULL, conf); + init_ucs(&ucsdata, conf_get_str(conf, CONF_line_codepage), + conf_get_bool(conf, CONF_utf8_override), + CS_NONE, conf_get_int(conf, CONF_vtmode)); - term = term_init(conf, &ucsdata, &termwin); - term_size(term, 24, 80, 10000); - term->ldisc = NULL; - /* Tell american fuzzy lop that this is a good place to fork. */ + term = term_init(conf, &ucsdata, &termwin); + term_size(term, 24, 80, 10000); + term->ldisc = NULL; + /* Tell american fuzzy lop that this is a good place to fork. */ #ifdef __AFL_HAVE_MANUAL_CONTROL - __AFL_INIT(); + __AFL_INIT(); #endif - while (!feof(stdin)) { - len = fread(blk, 1, sizeof(blk), stdin); - term_data(term, false, blk, len); - } - term_update(term); - return 0; + while (!feof(stdin)) { + len = fread(blk, 1, sizeof(blk), stdin); + term_data(term, false, blk, len); + } + term_update(term); + return 0; } /* functions required by terminal.c */ @@ -53,7 +53,7 @@ static void fuzz_draw_text( printf("TEXT[attr=%08lx,lattr=%02x]@(%d,%d):", attr, lattr, x, y); for (i = 0; i < len; i++) { - printf(" %x", (unsigned)text[i]); + printf(" %x", (unsigned)text[i]); } printf("\n"); } @@ -65,7 +65,7 @@ static void fuzz_draw_cursor( printf("CURS[attr=%08lx,lattr=%02x]@(%d,%d):", attr, lattr, x, y); for (i = 0; i < len; i++) { - printf(" %x", (unsigned)text[i]); + printf(" %x", (unsigned)text[i]); } printf("\n"); } @@ -152,7 +152,7 @@ void dlg_listbox_clear(union control *ctrl, void *dlg) { } void dlg_listbox_del(union control *ctrl, void *dlg, int index) { } void dlg_listbox_add(union control *ctrl, void *dlg, char const *text) { } void dlg_listbox_addwithid(union control *ctrl, void *dlg, - char const *text, int id) { } + char const *text, int id) { } int dlg_listbox_getid(union control *ctrl, void *dlg, int index) { return 0; } int dlg_listbox_index(union control *ctrl, void *dlg) { return -1; } int dlg_listbox_issel(union control *ctrl, void *dlg, int index) { return 0; } @@ -171,7 +171,7 @@ void dlg_beep(void *dlg) { } void dlg_error_msg(void *dlg, const char *msg) { } void dlg_end(void *dlg, int value) { } void dlg_coloursel_start(union control *ctrl, void *dlg, - int r, int g, int b) { } + int r, int g, int b) { } bool dlg_coloursel_results(union control *ctrl, void *dlg, int *r, int *g, int *b) { return false; } void dlg_refresh(union control *ctrl, void *dlg) { } @@ -188,9 +188,9 @@ const struct keyvalwhere gsslibkeywords[0] = { }; char *platform_default_s(const char *name) { if (!strcmp(name, "TermType")) - return dupstr(getenv("TERM")); + return dupstr(getenv("TERM")); if (!strcmp(name, "SerialLine")) - return dupstr("/dev/ttyS0"); + return dupstr("/dev/ttyS0"); return NULL; } @@ -212,12 +212,12 @@ FontSpec *platform_default_fontspec(const char *name) Filename *platform_default_filename(const char *name) { if (!strcmp(name, "LogFileName")) - return filename_from_str("putty.log"); + return filename_from_str("putty.log"); else - return filename_from_str(""); + return filename_from_str(""); } char *x_get_default(const char *key) { - return NULL; /* this is a stub */ + return NULL; /* this is a stub */ } diff --git a/icons/cicon.pl b/icons/cicon.pl index 08e9bcb9..dd635ce1 100755 --- a/icons/cicon.pl +++ b/icons/cicon.pl @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/perl # Given a list of input PNGs, create a C source file containing a # const array of XPMs, named by a given C identifier. diff --git a/icons/icon.pl b/icons/icon.pl index f746d69c..4275660f 100755 --- a/icons/icon.pl +++ b/icons/icon.pl @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/perl # Take a collection of input image files and convert them into a # multi-resolution Windows .ICO icon file. @@ -87,11 +87,11 @@ $depth = undef; foreach $_ (@ARGV) { if (/^-(24|8|4|1)$/) { - $depth = $1; + $depth = $1; } elsif (defined $depth) { - &readicon($_, $depth); + &readicon($_, $depth); } else { - $usage = 1; + $usage = 1; } } if ($usage || length @hdr == 0) { @@ -149,86 +149,86 @@ sub readicon { my $alpha = ""; for ($y = 0; $y < $h; $y++) { - my $currbyte = 0, $currbits = 0; - for ($x = 0; $x < (($w+31)|31)-31; $x++) { - $pix = ($x < $w ? $data->[$y*$w+$x] : "\x00\x00\x00\xFF"); - my @rgba = unpack "CCCC", $pix; - $currbyte <<= 1; - $currbits++; - if ($rgba[3] < 0x80) { - if ($x < $w) { - $data->[$y*$w+$x] = undef; - } - $currbyte |= 1; # MS has the alpha channel inverted :-) - } else { - # Might as well flip RGBA into BGR0 while we're here. - if ($x < $w) { - $data->[$y*$w+$x] = pack "CCCC", - $rgba[2], $rgba[1], $rgba[0], 0; - } - } - if ($currbits >= 8) { - $alpha .= pack "C", $currbyte; - $currbits -= 8; - } - } + my $currbyte = 0, $currbits = 0; + for ($x = 0; $x < (($w+31)|31)-31; $x++) { + $pix = ($x < $w ? $data->[$y*$w+$x] : "\x00\x00\x00\xFF"); + my @rgba = unpack "CCCC", $pix; + $currbyte <<= 1; + $currbits++; + if ($rgba[3] < 0x80) { + if ($x < $w) { + $data->[$y*$w+$x] = undef; + } + $currbyte |= 1; # MS has the alpha channel inverted :-) + } else { + # Might as well flip RGBA into BGR0 while we're here. + if ($x < $w) { + $data->[$y*$w+$x] = pack "CCCC", + $rgba[2], $rgba[1], $rgba[0], 0; + } + } + if ($currbits >= 8) { + $alpha .= pack "C", $currbyte; + $currbits -= 8; + } + } } # For an 8-bit image, check we have at most 256 distinct # colours, and build the palette. %pal = (); if ($depth == 8) { - my $palindex = 0; - foreach $pix (@$data) { - next unless defined $pix; - $pal{$pix} = $palindex++ unless defined $pal{$pix}; - } - die "too many colours in 8-bit image $filename\n" unless $palindex <= 256; + my $palindex = 0; + foreach $pix (@$data) { + next unless defined $pix; + $pal{$pix} = $palindex++ unless defined $pal{$pix}; + } + die "too many colours in 8-bit image $filename\n" unless $palindex <= 256; } elsif ($depth == 4) { - %pal = %win16pal; + %pal = %win16pal; } elsif ($depth == 1) { - %pal = %win2pal; + %pal = %win2pal; } my $raster = ""; if ($depth < 24) { - # For a non-24-bit image, flatten the image into one palette - # index per pixel. - $pad = 32 / $depth; # number of pixels to pad scanline to 4-byte align - $pmask = $pad-1; - for ($y = 0; $y < $h; $y++) { - my $currbyte = 0, $currbits = 0; - for ($x = 0; $x < (($w+$pmask)|$pmask)-$pmask; $x++) { - $currbyte <<= $depth; - $currbits += $depth; - if ($x < $w && defined ($pix = $data->[$y*$w+$x])) { - if (!defined $pal{$pix}) { + # For a non-24-bit image, flatten the image into one palette + # index per pixel. + $pad = 32 / $depth; # number of pixels to pad scanline to 4-byte align + $pmask = $pad-1; + for ($y = 0; $y < $h; $y++) { + my $currbyte = 0, $currbits = 0; + for ($x = 0; $x < (($w+$pmask)|$pmask)-$pmask; $x++) { + $currbyte <<= $depth; + $currbits += $depth; + if ($x < $w && defined ($pix = $data->[$y*$w+$x])) { + if (!defined $pal{$pix}) { $pixhex = sprintf "%02x%02x%02x", unpack "CCC", $pix; - die "illegal colour value $pixhex at pixel ($x,$y) in $filename\n"; - } - $currbyte |= $pal{$pix}; - } - if ($currbits >= 8) { - $raster .= pack "C", $currbyte; - $currbits -= 8; - } - } - } + die "illegal colour value $pixhex at pixel ($x,$y) in $filename\n"; + } + $currbyte |= $pal{$pix}; + } + if ($currbits >= 8) { + $raster .= pack "C", $currbyte; + $currbits -= 8; + } + } + } } else { - # For a 24-bit image, reverse the order of the R,G,B values - # and stick a padding zero on the end. - # - # (In this loop we don't need to bother padding the - # scanline out to a multiple of four bytes, because every - # pixel takes four whole bytes anyway.) - for ($i = 0; $i < scalar @$data; $i++) { - if (defined $data->[$i]) { - $raster .= $data->[$i]; - } else { - $raster .= "\x00\x00\x00\x00"; - } - } - $depth = 32; # and adjust this + # For a 24-bit image, reverse the order of the R,G,B values + # and stick a padding zero on the end. + # + # (In this loop we don't need to bother padding the + # scanline out to a multiple of four bytes, because every + # pixel takes four whole bytes anyway.) + for ($i = 0; $i < scalar @$data; $i++) { + if (defined $data->[$i]) { + $raster .= $data->[$i]; + } else { + $raster .= "\x00\x00\x00\x00"; + } + } + $depth = 32; # and adjust this } # Prepare the icon data. First the header... @@ -243,12 +243,12 @@ sub readicon { 0, 0, 0, 0; # resolution, colours used, colours important (ignored) # ... then the palette ... if ($depth <= 8) { - my $ncols = (1 << $depth); - my $palette = "\x00\x00\x00\x00" x $ncols; - foreach $i (keys %pal) { - substr($palette, $pal{$i}*4, 4) = $i; - } - $data .= $palette; + my $ncols = (1 << $depth); + my $palette = "\x00\x00\x00\x00" x $ncols; + foreach $i (keys %pal) { + substr($palette, $pal{$i}*4, 4) = $i; + } + $data .= $palette; } # ... the raster data we already had ready ... $data .= $raster; diff --git a/icons/mkicon.py b/icons/mkicon.py index 96b9cc84..d7d474ae 100755 --- a/icons/mkicon.py +++ b/icons/mkicon.py @@ -223,7 +223,7 @@ def sysbox(size, out={}): for y in range(depth): grey = 3 if x >= width-1 - highlight: - grey = grey + 1 + grey = grey + 1 pixel(x+(y+1), -(y+1), greypix(grey/4.0), canvas) # And draw a border. diff --git a/import.c b/import.c index 61f14371..effc65be 100644 --- a/import.c +++ b/import.c @@ -38,11 +38,11 @@ static bool sshcom_write( bool import_possible(int type) { if (type == SSH_KEYTYPE_OPENSSH_PEM) - return true; + return true; if (type == SSH_KEYTYPE_OPENSSH_NEW) - return true; + return true; if (type == SSH_KEYTYPE_SSHCOM) - return true; + return true; return false; } @@ -65,16 +65,16 @@ int import_target_type(int type) bool import_encrypted(const Filename *filename, int type, char **comment) { if (type == SSH_KEYTYPE_OPENSSH_PEM) { - /* OpenSSH PEM format doesn't contain a key comment at all */ - *comment = dupstr(filename_to_str(filename)); - return openssh_pem_encrypted(filename); + /* OpenSSH PEM format doesn't contain a key comment at all */ + *comment = dupstr(filename_to_str(filename)); + return openssh_pem_encrypted(filename); } else if (type == SSH_KEYTYPE_OPENSSH_NEW) { - /* OpenSSH new format does, but it's inside the encrypted + /* OpenSSH new format does, but it's inside the encrypted * section for some reason */ - *comment = dupstr(filename_to_str(filename)); - return openssh_new_encrypted(filename); + *comment = dupstr(filename_to_str(filename)); + return openssh_new_encrypted(filename); } else if (type == SSH_KEYTYPE_SSHCOM) { - return sshcom_encrypted(filename, comment); + return sshcom_encrypted(filename, comment); } return false; } @@ -83,7 +83,7 @@ bool import_encrypted(const Filename *filename, int type, char **comment) * Import an SSH-1 key. */ int import_ssh1(const Filename *filename, int type, - RSAKey *key, char *passphrase, const char **errmsg_p) + RSAKey *key, char *passphrase, const char **errmsg_p) { return 0; } @@ -92,14 +92,14 @@ int import_ssh1(const Filename *filename, int type, * Import an SSH-2 key. */ ssh2_userkey *import_ssh2(const Filename *filename, int type, - char *passphrase, const char **errmsg_p) + char *passphrase, const char **errmsg_p) { if (type == SSH_KEYTYPE_OPENSSH_PEM) - return openssh_pem_read(filename, passphrase, errmsg_p); + return openssh_pem_read(filename, passphrase, errmsg_p); else if (type == SSH_KEYTYPE_OPENSSH_NEW) - return openssh_new_read(filename, passphrase, errmsg_p); + return openssh_new_read(filename, passphrase, errmsg_p); if (type == SSH_KEYTYPE_SSHCOM) - return sshcom_read(filename, passphrase, errmsg_p); + return sshcom_read(filename, passphrase, errmsg_p); return NULL; } @@ -119,11 +119,11 @@ bool export_ssh2(const Filename *filename, int type, ssh2_userkey *key, char *passphrase) { if (type == SSH_KEYTYPE_OPENSSH_AUTO) - return openssh_auto_write(filename, key, passphrase); + return openssh_auto_write(filename, key, passphrase); if (type == SSH_KEYTYPE_OPENSSH_NEW) - return openssh_new_write(filename, key, passphrase); + return openssh_new_write(filename, key, passphrase); if (type == SSH_KEYTYPE_SSHCOM) - return sshcom_write(filename, key, passphrase); + return sshcom_write(filename, key, passphrase); return false; } @@ -135,7 +135,7 @@ void strip_crlf(char *str) char *p = str + strlen(str); while (p > str && (p[-1] == '\r' || p[-1] == '\n')) - *--p = '\0'; + *--p = '\0'; } /* ---------------------------------------------------------------------- @@ -150,9 +150,9 @@ void strip_crlf(char *str) /* * Read an ASN.1/BER identifier and length pair. - * + * * Flags are a combination of the #defines listed below. - * + * * Returns -1 if unsuccessful; otherwise returns the number of * bytes used out of the source data. */ @@ -177,42 +177,42 @@ static void BinarySink_put_ber_id_len(BinarySink *bs, int id, int length, int flags) { if (id <= 30) { - /* - * Identifier is one byte. - */ - put_byte(bs, id | flags); + /* + * Identifier is one byte. + */ + put_byte(bs, id | flags); } else { - int n; - /* - * Identifier is multiple bytes: the first byte is 11111 - * plus the flags, and subsequent bytes encode the value of - * the identifier, 7 bits at a time, with the top bit of - * each byte 1 except the last one which is 0. - */ - put_byte(bs, 0x1F | flags); - for (n = 1; (id >> (7*n)) > 0; n++) - continue; /* count the bytes */ - while (n--) - put_byte(bs, (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F)); + int n; + /* + * Identifier is multiple bytes: the first byte is 11111 + * plus the flags, and subsequent bytes encode the value of + * the identifier, 7 bits at a time, with the top bit of + * each byte 1 except the last one which is 0. + */ + put_byte(bs, 0x1F | flags); + for (n = 1; (id >> (7*n)) > 0; n++) + continue; /* count the bytes */ + while (n--) + put_byte(bs, (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F)); } if (length < 128) { - /* - * Length is one byte. - */ + /* + * Length is one byte. + */ put_byte(bs, length); } else { - int n; - /* - * Length is multiple bytes. The first is 0x80 plus the - * number of subsequent bytes, and the subsequent bytes - * encode the actual length. - */ - for (n = 1; (length >> (8*n)) > 0; n++) - continue; /* count the bytes */ - put_byte(bs, 0x80 | n); - while (n--) - put_byte(bs, (length >> (8*n)) & 0xFF); + int n; + /* + * Length is multiple bytes. The first is 0x80 plus the + * number of subsequent bytes, and the subsequent bytes + * encode the actual length. + */ + for (n = 1; (length >> (8*n)) > 0; n++) + continue; /* count the bytes */ + put_byte(bs, 0x80 | n); + while (n--) + put_byte(bs, (length >> (8*n)) & 0xFF); } } @@ -236,23 +236,23 @@ static ber_item BinarySource_get_ber(BinarySource *src) if ((leadbyte & 0x1F) == 0x1F) { unsigned char idbyte; - toret.id = 0; + toret.id = 0; do { idbyte = get_byte(src); - toret.id = (toret.id << 7) | (idbyte & 0x7F); + toret.id = (toret.id << 7) | (idbyte & 0x7F); } while (idbyte & 0x80); } else { - toret.id = leadbyte & 0x1F; + toret.id = leadbyte & 0x1F; } lenbyte = get_byte(src); if (lenbyte & 0x80) { int nbytes = lenbyte & 0x7F; length = 0; - while (nbytes-- > 0) - length = (length << 8) | get_byte(src); + while (nbytes-- > 0) + length = (length << 8) | get_byte(src); } else { - length = lenbyte; + length = lenbyte; } toret.data = get_data(src, length); @@ -317,19 +317,19 @@ static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename, fp = f_open(filename, "r", false); if (!fp) { - errmsg = "unable to open key file"; - goto error; + errmsg = "unable to open key file"; + goto error; } if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; + errmsg = "unexpected end of file"; + goto error; } strip_crlf(line); if (!strstartswith(line, "-----BEGIN ") || !strendswith(line, "PRIVATE KEY-----")) { - errmsg = "file does not begin with OpenSSH key header"; - goto error; + errmsg = "file does not begin with OpenSSH key header"; + goto error; } /* * Parse the BEGIN line. For old-format keys, this tells us the @@ -338,17 +338,17 @@ static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename, * base64. */ if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) { - ret->keytype = OP_RSA; + ret->keytype = OP_RSA; } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) { - ret->keytype = OP_DSA; + ret->keytype = OP_DSA; } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) { ret->keytype = OP_ECDSA; } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) { - errmsg = "this is a new-style OpenSSH key"; - goto error; + errmsg = "this is a new-style OpenSSH key"; + goto error; } else { - errmsg = "unrecognised key type"; - goto error; + errmsg = "unrecognised key type"; + goto error; } smemclr(line, strlen(line)); sfree(line); @@ -359,65 +359,65 @@ static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename, headers_done = false; while (1) { - if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; - } - strip_crlf(line); - if (strstartswith(line, "-----END ") && - strendswith(line, "PRIVATE KEY-----")) { + if (!(line = fgetline(fp))) { + errmsg = "unexpected end of file"; + goto error; + } + strip_crlf(line); + if (strstartswith(line, "-----END ") && + strendswith(line, "PRIVATE KEY-----")) { sfree(line); line = NULL; - break; /* done */ + break; /* done */ } - if ((p = strchr(line, ':')) != NULL) { - if (headers_done) { - errmsg = "header found in body of key data"; - goto error; - } - *p++ = '\0'; - while (*p && isspace((unsigned char)*p)) p++; - if (!strcmp(line, "Proc-Type")) { - if (p[0] != '4' || p[1] != ',') { - errmsg = "Proc-Type is not 4 (only 4 is supported)"; - goto error; - } - p += 2; - if (!strcmp(p, "ENCRYPTED")) - ret->encrypted = true; - } else if (!strcmp(line, "DEK-Info")) { - int i, ivlen; + if ((p = strchr(line, ':')) != NULL) { + if (headers_done) { + errmsg = "header found in body of key data"; + goto error; + } + *p++ = '\0'; + while (*p && isspace((unsigned char)*p)) p++; + if (!strcmp(line, "Proc-Type")) { + if (p[0] != '4' || p[1] != ',') { + errmsg = "Proc-Type is not 4 (only 4 is supported)"; + goto error; + } + p += 2; + if (!strcmp(p, "ENCRYPTED")) + ret->encrypted = true; + } else if (!strcmp(line, "DEK-Info")) { + int i, ivlen; - if (!strncmp(p, "DES-EDE3-CBC,", 13)) { - ret->encryption = OP_E_3DES; - ivlen = 8; - } else if (!strncmp(p, "AES-128-CBC,", 12)) { - ret->encryption = OP_E_AES; - ivlen = 16; - } else { - errmsg = "unsupported cipher"; - goto error; - } - p = strchr(p, ',') + 1;/* always non-NULL, by above checks */ - for (i = 0; i < ivlen; i++) { + if (!strncmp(p, "DES-EDE3-CBC,", 13)) { + ret->encryption = OP_E_3DES; + ivlen = 8; + } else if (!strncmp(p, "AES-128-CBC,", 12)) { + ret->encryption = OP_E_AES; + ivlen = 16; + } else { + errmsg = "unsupported cipher"; + goto error; + } + p = strchr(p, ',') + 1;/* always non-NULL, by above checks */ + for (i = 0; i < ivlen; i++) { unsigned j; - if (1 != sscanf(p, "%2x", &j)) { - errmsg = "expected more iv data in DEK-Info"; - goto error; - } - ret->iv[i] = j; - p += 2; - } - if (*p) { - errmsg = "more iv data than expected in DEK-Info"; - goto error; - } - } - } else { - headers_done = true; + if (1 != sscanf(p, "%2x", &j)) { + errmsg = "expected more iv data in DEK-Info"; + goto error; + } + ret->iv[i] = j; + p += 2; + } + if (*p) { + errmsg = "more iv data than expected in DEK-Info"; + goto error; + } + } + } else { + headers_done = true; - p = line; - while (isbase64(*p)) { + p = line; + while (isbase64(*p)) { base64_bit[base64_chars++] = *p; if (base64_chars == 4) { unsigned char out[3]; @@ -437,20 +437,20 @@ static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename, smemclr(out, sizeof(out)); } - p++; - } - } - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + p++; + } + } + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } fclose(fp); fp = NULL; if (!ret->keyblob || ret->keyblob->len == 0) { - errmsg = "key body not present"; - goto error; + errmsg = "key body not present"; + goto error; } if (ret->encrypted && ret->keyblob->len % 8 != 0) { @@ -465,16 +465,16 @@ static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename, error: if (line) { - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } smemclr(base64_bit, sizeof(base64_bit)); if (ret) { - if (ret->keyblob) + if (ret->keyblob) strbuf_free(ret->keyblob); smemclr(ret, sizeof(*ret)); - sfree(ret); + sfree(ret); } if (errmsg_p) *errmsg_p = errmsg; if (fp) fclose(fp); @@ -487,7 +487,7 @@ static bool openssh_pem_encrypted(const Filename *filename) bool ret; if (!key) - return false; + return false; ret = key->encrypted; strbuf_free(key->keyblob); smemclr(key, sizeof(*key)); @@ -539,7 +539,7 @@ static ssh2_userkey *openssh_pem_read( int privptr = 0, publen; if (!key) - return NULL; + return NULL; if (key->encrypted) { unsigned char keybuf[32]; @@ -583,7 +583,7 @@ static ssh2_userkey *openssh_pem_read( * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint */ - + BinarySource_BARE_INIT(src, key->keyblob->u, key->keyblob->len); { @@ -607,7 +607,7 @@ static ssh2_userkey *openssh_pem_read( else if (key->keytype == OP_DSA) num_integers = 6; else - num_integers = 0; /* placate compiler warnings */ + num_integers = 0; /* placate compiler warnings */ if (key->keytype == OP_ECDSA) { @@ -752,8 +752,8 @@ static ssh2_userkey *openssh_pem_read( } else { unreachable("Bad key type from load_openssh_pem_key"); - errmsg = "Bad key type from load_openssh_pem_key"; - goto error; + errmsg = "Bad key type from load_openssh_pem_key"; + goto error; } /* @@ -984,7 +984,7 @@ static bool openssh_pem_write( * old-style 3DES. */ if (passphrase) { - unsigned char keybuf[32]; + unsigned char keybuf[32]; int origlen, outlen, pad; /* @@ -1009,17 +1009,17 @@ static bool openssh_pem_write( pad = outlen - origlen; put_padding(outblob, pad, pad); - /* - * Invent an iv, and derive the encryption key. - */ + /* + * Invent an iv, and derive the encryption key. + */ random_read(iv, 8); openssh_pem_derivekey(ptrlen_from_asciz(passphrase), iv, keybuf); - /* - * Now encrypt the key blob. - */ - des3_encrypt_pubkey_ossh(keybuf, iv, + /* + * Now encrypt the key blob. + */ + des3_encrypt_pubkey_ossh(keybuf, iv, outblob->u, outlen); smemclr(keybuf, sizeof(keybuf)); @@ -1031,13 +1031,13 @@ static bool openssh_pem_write( */ fp = f_open(filename, "wb", true); /* ensure Unix line endings */ if (!fp) - goto error; + goto error; fputs(header, fp); if (passphrase) { - fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,"); - for (i = 0; i < 8; i++) - fprintf(fp, "%02X", iv[i]); - fprintf(fp, "\n\n"); + fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,"); + for (i = 0; i < 8; i++) + fprintf(fp, "%02X", iv[i]); + fprintf(fp, "\n\n"); } base64_encode(fp, outblob->u, outblob->len, 64); fputs(footer, fp); @@ -1106,33 +1106,33 @@ static struct openssh_new_key *load_openssh_new_key(const Filename *filename, fp = f_open(filename, "r", false); if (!fp) { - errmsg = "unable to open key file"; - goto error; + errmsg = "unable to open key file"; + goto error; } if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; + errmsg = "unexpected end of file"; + goto error; } strip_crlf(line); if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) { - errmsg = "file does not begin with OpenSSH new-style key header"; - goto error; + errmsg = "file does not begin with OpenSSH new-style key header"; + goto error; } smemclr(line, strlen(line)); sfree(line); line = NULL; while (1) { - if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; - } - strip_crlf(line); - if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) { + if (!(line = fgetline(fp))) { + errmsg = "unexpected end of file"; + goto error; + } + strip_crlf(line); + if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) { sfree(line); line = NULL; - break; /* done */ + break; /* done */ } p = line; @@ -1158,17 +1158,17 @@ static struct openssh_new_key *load_openssh_new_key(const Filename *filename, p++; } - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } fclose(fp); fp = NULL; if (ret->keyblob->len == 0) { - errmsg = "key body not present"; - goto error; + errmsg = "key body not present"; + goto error; } BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(ret->keyblob)); @@ -1273,15 +1273,15 @@ static struct openssh_new_key *load_openssh_new_key(const Filename *filename, error: if (line) { - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } smemclr(base64_bit, sizeof(base64_bit)); if (ret) { strbuf_free(ret->keyblob); smemclr(ret, sizeof(*ret)); - sfree(ret); + sfree(ret); } if (errmsg_p) *errmsg_p = errmsg; if (fp) fclose(fp); @@ -1294,7 +1294,7 @@ static bool openssh_new_encrypted(const Filename *filename) bool ret; if (!key) - return false; + return false; ret = (key->cipher != ON_E_NONE); strbuf_free(key->keyblob); smemclr(key, sizeof(*key)); @@ -1315,7 +1315,7 @@ static ssh2_userkey *openssh_new_read( const ssh_keyalg *alg = NULL; if (!key) - return NULL; + return NULL; if (key->cipher != ON_E_NONE) { unsigned char keybuf[48]; @@ -1583,7 +1583,7 @@ static bool openssh_new_write( */ fp = f_open(filename, "wb", true); /* ensure Unix line endings */ if (!fp) - goto error; + goto error; fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp); base64_encode(fp, cblob->u, cblob->len, 64); fputs("-----END OPENSSH PRIVATE KEY-----\n", fp); @@ -1631,26 +1631,26 @@ static bool openssh_auto_write( * except that mpints are a bit different: they're more like the * old SSH-1 mpint. You have a 32-bit bit count N, followed by * (N+7)/8 bytes of data. - * + * * So. The blob contains: - * + * * - uint32 0x3f6ff9eb (magic number) * - uint32 size (total blob size) * - string key-type (see below) * - string cipher-type (tells you if key is encrypted) * - string encrypted-blob - * + * * (The first size field includes the size field itself and the * magic number before it. All other size fields are ordinary SSH-2 * strings, so the size field indicates how much data is to * _follow_.) - * + * * The encrypted blob, once decrypted, contains a single string * which in turn contains the payload. (This allows padding to be * added after that string while still making it clear where the * real payload ends. Also it probably makes for a reasonable * decryption check.) - * + * * The payload blob, for an RSA key, contains: * - mpint e * - mpint d @@ -1658,7 +1658,7 @@ static bool openssh_auto_write( * - mpint u (presumably inverse of p mod q) * - mpint p (p is the smaller prime) * - mpint q (q is the larger) - * + * * For a DSA key, the payload blob contains: * - uint32 0 * - mpint p @@ -1666,30 +1666,30 @@ static bool openssh_auto_write( * - mpint q * - mpint y * - mpint x - * + * * Alternatively, if the parameters are `predefined', that * (0,p,g,q) sequence can be replaced by a uint32 1 and a string * containing some predefined parameter specification. *shudder*, * but I doubt we'll encounter this in real life. - * + * * The key type strings are ghastly. The RSA key I looked at had a * type string of - * + * * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}' - * + * * and the DSA key wasn't much better: - * + * * `dl-modp{sign{dsa-nist-sha1},dh{plain}}' - * + * * It isn't clear that these will always be the same. I think it * might be wise just to look at the `if-modn{sign{rsa' and * `dl-modp{sign{dsa' prefixes. - * + * * Finally, the encryption. The cipher-type string appears to be * either `none' or `3des-cbc'. Looks as if this is SSH-2-style * 3des-cbc (i.e. outer cbc rather than inner). The key is created * from the passphrase by means of yet another hashing faff: - * + * * - first 16 bytes are MD5(passphrase) * - next 16 bytes are MD5(passphrase || first 16 bytes) * - if there were more, they'd be MD5(passphrase || first 32), @@ -1704,7 +1704,7 @@ struct sshcom_key { }; static struct sshcom_key *load_sshcom_key(const Filename *filename, - const char **errmsg_p) + const char **errmsg_p) { struct sshcom_key *ret; FILE *fp; @@ -1722,17 +1722,17 @@ static struct sshcom_key *load_sshcom_key(const Filename *filename, fp = f_open(filename, "r", false); if (!fp) { - errmsg = "unable to open key file"; - goto error; + errmsg = "unable to open key file"; + goto error; } if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; + errmsg = "unexpected end of file"; + goto error; } strip_crlf(line); if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) { - errmsg = "file does not begin with ssh.com key header"; - goto error; + errmsg = "file does not begin with ssh.com key header"; + goto error; } smemclr(line, strlen(line)); sfree(line); @@ -1740,54 +1740,54 @@ static struct sshcom_key *load_sshcom_key(const Filename *filename, headers_done = false; while (1) { - if (!(line = fgetline(fp))) { - errmsg = "unexpected end of file"; - goto error; - } - strip_crlf(line); + if (!(line = fgetline(fp))) { + errmsg = "unexpected end of file"; + goto error; + } + strip_crlf(line); if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) { sfree(line); line = NULL; break; /* done */ } - if ((p = strchr(line, ':')) != NULL) { - if (headers_done) { - errmsg = "header found in body of key data"; - goto error; - } - *p++ = '\0'; - while (*p && isspace((unsigned char)*p)) p++; - hdrstart = p - line; + if ((p = strchr(line, ':')) != NULL) { + if (headers_done) { + errmsg = "header found in body of key data"; + goto error; + } + *p++ = '\0'; + while (*p && isspace((unsigned char)*p)) p++; + hdrstart = p - line; /* * Header lines can end in a trailing backslash for * continuation. */ - len = hdrstart + strlen(line+hdrstart); - assert(!line[len]); + len = hdrstart + strlen(line+hdrstart); + assert(!line[len]); while (line[len-1] == '\\') { - char *line2; - int line2len; + char *line2; + int line2len; - line2 = fgetline(fp); - if (!line2) { + line2 = fgetline(fp); + if (!line2) { errmsg = "unexpected end of file"; goto error; } - strip_crlf(line2); + strip_crlf(line2); - line2len = strlen(line2); - line = sresize(line, len + line2len + 1, char); - strcpy(line + len - 1, line2); - len += line2len - 1; - assert(!line[len]); + line2len = strlen(line2); + line = sresize(line, len + line2len + 1, char); + strcpy(line + len - 1, line2); + len += line2len - 1; + assert(!line[len]); - smemclr(line2, strlen(line2)); - sfree(line2); - line2 = NULL; + smemclr(line2, strlen(line2)); + sfree(line2); + line2 = NULL; } - p = line + hdrstart; - strip_crlf(p); + p = line + hdrstart; + strip_crlf(p); if (!strcmp(line, "Comment")) { /* Strip quotes in comment if present. */ if (p[0] == '"' && p[strlen(p)-1] == '"') { @@ -1797,11 +1797,11 @@ static struct sshcom_key *load_sshcom_key(const Filename *filename, strncpy(ret->comment, p, sizeof(ret->comment)); ret->comment[sizeof(ret->comment)-1] = '\0'; } - } else { - headers_done = true; + } else { + headers_done = true; - p = line; - while (isbase64(*p)) { + p = line; + while (isbase64(*p)) { base64_bit[base64_chars++] = *p; if (base64_chars == 4) { unsigned char out[3]; @@ -1818,17 +1818,17 @@ static struct sshcom_key *load_sshcom_key(const Filename *filename, put_data(ret->keyblob, out, len); } - p++; - } - } - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + p++; + } + } + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } if (ret->keyblob->len == 0) { - errmsg = "key body not present"; - goto error; + errmsg = "key body not present"; + goto error; } fclose(fp); @@ -1840,14 +1840,14 @@ static struct sshcom_key *load_sshcom_key(const Filename *filename, fclose(fp); if (line) { - smemclr(line, strlen(line)); - sfree(line); - line = NULL; + smemclr(line, strlen(line)); + sfree(line); + line = NULL; } if (ret) { strbuf_free(ret->keyblob); smemclr(ret, sizeof(*ret)); - sfree(ret); + sfree(ret); } if (errmsg_p) *errmsg_p = errmsg; return NULL; @@ -1895,10 +1895,10 @@ void BinarySink_put_mp_sshcom_from_string(BinarySink *bs, ptrlen str) int bits = nbytes * 8 - 1; while (bits > 0) { - if (*bytes & (1 << (bits & 7))) - break; - if (!(bits-- & 7)) - bytes++, nbytes--; + if (*bytes & (1 << (bits & 7))) + break; + if (!(bits-- & 7)) + bytes++, nbytes--; } put_uint32(bs, bits+1); @@ -1922,7 +1922,7 @@ static void sshcom_derivekey(ptrlen passphrase, uint8_t *keybuf) /* * Derive the encryption key for an ssh.com key file from the * passphrase and iv/salt: - * + * * - let block A equal MD5(passphrase) * - let block B equal MD5(passphrase || A) * - block C would be MD5(passphrase || A || B) and so on @@ -2005,15 +2005,15 @@ static ssh2_userkey *sshcom_read( * Decrypt it if necessary. */ if (encrypted) { - /* - * Derive encryption key from passphrase and iv/salt: - * - * - let block A equal MD5(passphrase) - * - let block B equal MD5(passphrase || A) - * - block C would be MD5(passphrase || A || B) and so on - * - encryption key is the first N bytes of A || B - */ - unsigned char keybuf[32], iv[8]; + /* + * Derive encryption key from passphrase and iv/salt: + * + * - let block A equal MD5(passphrase) + * - let block B equal MD5(passphrase || A) + * - block C would be MD5(passphrase || A || B) and so on + * - encryption key is the first N bytes of A || B + */ + unsigned char keybuf[32], iv[8]; if (ciphertext.len % 8 != 0) { errmsg = "encrypted part of key is not a multiple of cipher block" @@ -2023,12 +2023,12 @@ static ssh2_userkey *sshcom_read( sshcom_derivekey(ptrlen_from_asciz(passphrase), keybuf); - /* - * Now decrypt the key blob in place (casting away const from - * ciphertext being a ptrlen). - */ + /* + * Now decrypt the key blob in place (casting away const from + * ciphertext being a ptrlen). + */ memset(iv, 0, sizeof(iv)); - des3_decrypt_pubkey_ossh(keybuf, iv, + des3_decrypt_pubkey_ossh(keybuf, iv, (char *)ciphertext.ptr, ciphertext.len); smemclr(keybuf, sizeof(keybuf)); @@ -2118,9 +2118,9 @@ static ssh2_userkey *sshcom_read( alg, make_ptrlen(blob->u, publen), make_ptrlen(blob->u + publen, blob->len - publen)); if (!retkey->key) { - sfree(retkey); - errmsg = "unable to create key data structure"; - goto error; + sfree(retkey); + errmsg = "unable to create key data structure"; + goto error; } retkey->comment = dupstr(key->comment); @@ -2192,8 +2192,8 @@ static bool sshcom_write( numbers[5] = p; nnumbers = 6; - initial_zero = false; - type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}"; + initial_zero = false; + type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}"; } else if (ssh_key_alg(key->key) == &ssh_dss) { ptrlen p, q, g, y, x; @@ -2219,8 +2219,8 @@ static bool sshcom_write( numbers[4] = x; nnumbers = 5; - initial_zero = true; - type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}"; + initial_zero = true; + type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}"; } else { goto error; /* unsupported key type */ } @@ -2240,13 +2240,13 @@ static bool sshcom_write( if (initial_zero) put_uint32(outblob, 0); for (i = 0; i < nnumbers; i++) - put_mp_sshcom_from_string(outblob, numbers[i]); + put_mp_sshcom_from_string(outblob, numbers[i]); /* Now wrap up the encrypted payload. */ PUT_32BIT_MSB_FIRST(outblob->s + lenpos + 4, outblob->len - (lenpos + 8)); /* Pad encrypted blob to a multiple of cipher block size. */ if (passphrase) { - int padding = -(outblob->len - (lenpos+4)) & 7; + int padding = -(outblob->len - (lenpos+4)) & 7; uint8_t padding_buf[8]; random_read(padding_buf, padding); put_data(outblob, padding_buf, padding); @@ -2263,15 +2263,15 @@ static bool sshcom_write( * Encrypt the key. */ if (passphrase) { - unsigned char keybuf[32], iv[8]; + unsigned char keybuf[32], iv[8]; sshcom_derivekey(ptrlen_from_asciz(passphrase), keybuf); - /* - * Now decrypt the key blob. - */ + /* + * Now decrypt the key blob. + */ memset(iv, 0, sizeof(iv)); - des3_encrypt_pubkey_ossh(keybuf, iv, ciphertext, cipherlen); + des3_encrypt_pubkey_ossh(keybuf, iv, ciphertext, cipherlen); smemclr(keybuf, sizeof(keybuf)); } @@ -2282,7 +2282,7 @@ static bool sshcom_write( */ fp = f_open(filename, "wb", true); /* ensure Unix line endings */ if (!fp) - goto error; + goto error; fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp); fprintf(fp, "Comment: \""); /* @@ -2292,14 +2292,14 @@ static bool sshcom_write( * Don't ask me, I didn't design it. */ { - int slen = 60; /* starts at 60 due to "Comment: " */ - char *c = key->comment; - while ((int)strlen(c) > slen) { - fprintf(fp, "%.*s\\\n", slen, c); - c += slen; - slen = 70; /* allow 70 chars on subsequent lines */ - } - fprintf(fp, "%s\"\n", c); + int slen = 60; /* starts at 60 due to "Comment: " */ + char *c = key->comment; + while ((int)strlen(c) > slen) { + fprintf(fp, "%.*s\\\n", slen, c); + c += slen; + slen = 70; /* allow 70 chars on subsequent lines */ + } + fprintf(fp, "%s\"\n", c); } base64_encode(fp, outblob->u, outblob->len, 70); fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp); diff --git a/ldisc.c b/ldisc.c index bd7ffb05..8eb80175 100644 --- a/ldisc.c +++ b/ldisc.c @@ -28,48 +28,48 @@ static void c_write(Ldisc *ldisc, const void *buf, int len) static int plen(Ldisc *ldisc, unsigned char c) { if ((c >= 32 && c <= 126) || (c >= 160 && !in_utf(ldisc->term))) - return 1; + return 1; else if (c < 128) - return 2; /* ^x for some x */ + return 2; /* ^x for some x */ else if (in_utf(ldisc->term) && c >= 0xC0) - return 1; /* UTF-8 introducer character - * (FIXME: combining / wide chars) */ + return 1; /* UTF-8 introducer character + * (FIXME: combining / wide chars) */ else if (in_utf(ldisc->term) && c >= 0x80 && c < 0xC0) - return 0; /* UTF-8 followup character */ + return 0; /* UTF-8 followup character */ else - return 4; /* hex representation */ + return 4; /* hex representation */ } static void pwrite(Ldisc *ldisc, unsigned char c) { if ((c >= 32 && c <= 126) || - (!in_utf(ldisc->term) && c >= 0xA0) || - (in_utf(ldisc->term) && c >= 0x80)) { - c_write(ldisc, &c, 1); + (!in_utf(ldisc->term) && c >= 0xA0) || + (in_utf(ldisc->term) && c >= 0x80)) { + c_write(ldisc, &c, 1); } else if (c < 128) { - char cc[2]; - cc[1] = (c == 127 ? '?' : c + 0x40); - cc[0] = '^'; - c_write(ldisc, cc, 2); + char cc[2]; + cc[1] = (c == 127 ? '?' : c + 0x40); + cc[0] = '^'; + c_write(ldisc, cc, 2); } else { - char cc[5]; - sprintf(cc, "<%02X>", c); - c_write(ldisc, cc, 4); + char cc[5]; + sprintf(cc, "<%02X>", c); + c_write(ldisc, cc, 4); } } static bool char_start(Ldisc *ldisc, unsigned char c) { if (in_utf(ldisc->term)) - return (c < 0x80 || c >= 0xC0); + return (c < 0x80 || c >= 0xC0); else - return true; + return true; } static void bsb(Ldisc *ldisc, int n) { while (n--) - c_write(ldisc, "\010 \010", 3); + c_write(ldisc, "\010 \010", 3); } #define CTRL(x) (x^'@') @@ -92,7 +92,7 @@ Ldisc *ldisc_create(Conf *conf, Terminal *term, Backend *backend, Seat *seat) /* Link ourselves into the backend and the terminal */ if (term) - term->ldisc = ldisc; + term->ldisc = ldisc; if (backend) backend_provide_ldisc(backend, ldisc); @@ -111,11 +111,11 @@ void ldisc_configure(Ldisc *ldisc, Conf *conf) void ldisc_free(Ldisc *ldisc) { if (ldisc->term) - ldisc->term->ldisc = NULL; + ldisc->term->ldisc = NULL; if (ldisc->backend) backend_provide_ldisc(ldisc->backend, NULL); if (ldisc->buf) - sfree(ldisc->buf); + sfree(ldisc->buf); sfree(ldisc); } @@ -148,65 +148,65 @@ void ldisc_send(Ldisc *ldisc, const void *vbuf, int len, bool interactive) * Less than zero means null terminated special string. */ if (len < 0) { - len = strlen(buf); - keyflag = KCTRL('@'); + len = strlen(buf); + keyflag = KCTRL('@'); } /* * Either perform local editing, or just send characters. */ if (EDITING) { - while (len--) { - int c; - c = (unsigned char)(*buf++) + keyflag; - if (!interactive && c == '\r') - c += KCTRL('@'); - switch (ldisc->quotenext ? ' ' : c) { - /* - * ^h/^?: delete, and output BSBs, to return to - * last character boundary (in UTF-8 mode this may - * be more than one byte) - * ^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 KCTRL('H'): - case KCTRL('?'): /* backspace/delete */ - if (ldisc->buflen > 0) { - do { - if (ECHOING) - bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); - ldisc->buflen--; - } while (!char_start(ldisc, ldisc->buf[ldisc->buflen])); - } - break; - case CTRL('W'): /* delete word */ - while (ldisc->buflen > 0) { - if (ECHOING) - bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); - ldisc->buflen--; - if (ldisc->buflen > 0 && - isspace((unsigned char)ldisc->buf[ldisc->buflen-1]) && - !isspace((unsigned char)ldisc->buf[ldisc->buflen])) - break; - } - break; - case CTRL('U'): /* delete line */ - case CTRL('C'): /* Send IP */ - case CTRL('\\'): /* Quit */ - case CTRL('Z'): /* Suspend */ - while (ldisc->buflen > 0) { - if (ECHOING) - bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); - ldisc->buflen--; - } + while (len--) { + int c; + c = (unsigned char)(*buf++) + keyflag; + if (!interactive && c == '\r') + c += KCTRL('@'); + switch (ldisc->quotenext ? ' ' : c) { + /* + * ^h/^?: delete, and output BSBs, to return to + * last character boundary (in UTF-8 mode this may + * be more than one byte) + * ^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 KCTRL('H'): + case KCTRL('?'): /* backspace/delete */ + if (ldisc->buflen > 0) { + do { + if (ECHOING) + bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); + ldisc->buflen--; + } while (!char_start(ldisc, ldisc->buf[ldisc->buflen])); + } + break; + case CTRL('W'): /* delete word */ + while (ldisc->buflen > 0) { + if (ECHOING) + bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); + ldisc->buflen--; + if (ldisc->buflen > 0 && + isspace((unsigned char)ldisc->buf[ldisc->buflen-1]) && + !isspace((unsigned char)ldisc->buf[ldisc->buflen])) + break; + } + break; + case CTRL('U'): /* delete line */ + case CTRL('C'): /* Send IP */ + case CTRL('\\'): /* Quit */ + case CTRL('Z'): /* Suspend */ + while (ldisc->buflen > 0) { + if (ECHOING) + bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); + ldisc->buflen--; + } backend_special(ldisc->backend, SS_EL, 0); /* * We don't send IP, SUSP or ABORT if the user has @@ -215,130 +215,130 @@ void ldisc_send(Ldisc *ldisc, const void *vbuf, int len, bool interactive) */ if (!ldisc->telnet_keyboard) goto default_case; - if (c == CTRL('C')) + if (c == CTRL('C')) backend_special(ldisc->backend, SS_IP, 0); - if (c == CTRL('Z')) + if (c == CTRL('Z')) backend_special(ldisc->backend, SS_SUSP, 0); - if (c == CTRL('\\')) + if (c == CTRL('\\')) backend_special(ldisc->backend, SS_ABORT, 0); - break; - case CTRL('R'): /* redraw line */ - if (ECHOING) { - int i; - c_write(ldisc, "^R\r\n", 4); - for (i = 0; i < ldisc->buflen; i++) - pwrite(ldisc, ldisc->buf[i]); - } - break; - case CTRL('V'): /* quote next char */ - ldisc->quotenext = true; - break; - case CTRL('D'): /* logout or send */ - if (ldisc->buflen == 0) { + break; + case CTRL('R'): /* redraw line */ + if (ECHOING) { + int i; + c_write(ldisc, "^R\r\n", 4); + for (i = 0; i < ldisc->buflen; i++) + pwrite(ldisc, ldisc->buf[i]); + } + break; + case CTRL('V'): /* quote next char */ + ldisc->quotenext = true; + break; + case CTRL('D'): /* logout or send */ + if (ldisc->buflen == 0) { backend_special(ldisc->backend, SS_EOF, 0); - } else { + } else { backend_send(ldisc->backend, ldisc->buf, ldisc->buflen); - ldisc->buflen = 0; - } - break; - /* - * This particularly hideous bit of code from RDB - * allows ordinary ^M^J to do the same thing as - * magic-^M when in Raw protocol. The line `case - * KCTRL('M'):' is _inside_ the if block. Thus: - * - * - receiving regular ^M goes straight to the - * default clause and inserts as a literal ^M. - * - receiving regular ^J _not_ directly after a - * literal ^M (or not in Raw protocol) fails the - * if condition, leaps to the bottom of the if, - * and falls through into the default clause - * again. - * - receiving regular ^J just after a literal ^M - * in Raw protocol passes the if condition, - * deletes the literal ^M, and falls through - * into the magic-^M code - * - receiving a magic-^M empties the line buffer, - * signals end-of-line in one of the various - * entertaining ways, and _doesn't_ fall out of - * the bottom of the if and through to the - * default clause because of the break. - */ - case CTRL('J'): - if (ldisc->protocol == PROT_RAW && - ldisc->buflen > 0 && ldisc->buf[ldisc->buflen - 1] == '\r') { - if (ECHOING) - bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); - ldisc->buflen--; - /* FALLTHROUGH */ - case KCTRL('M'): /* send with newline */ - if (ldisc->buflen > 0) + ldisc->buflen = 0; + } + break; + /* + * This particularly hideous bit of code from RDB + * allows ordinary ^M^J to do the same thing as + * magic-^M when in Raw protocol. The line `case + * KCTRL('M'):' is _inside_ the if block. Thus: + * + * - receiving regular ^M goes straight to the + * default clause and inserts as a literal ^M. + * - receiving regular ^J _not_ directly after a + * literal ^M (or not in Raw protocol) fails the + * if condition, leaps to the bottom of the if, + * and falls through into the default clause + * again. + * - receiving regular ^J just after a literal ^M + * in Raw protocol passes the if condition, + * deletes the literal ^M, and falls through + * into the magic-^M code + * - receiving a magic-^M empties the line buffer, + * signals end-of-line in one of the various + * entertaining ways, and _doesn't_ fall out of + * the bottom of the if and through to the + * default clause because of the break. + */ + case CTRL('J'): + if (ldisc->protocol == PROT_RAW && + ldisc->buflen > 0 && ldisc->buf[ldisc->buflen - 1] == '\r') { + if (ECHOING) + bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); + ldisc->buflen--; + /* FALLTHROUGH */ + case KCTRL('M'): /* send with newline */ + if (ldisc->buflen > 0) backend_send(ldisc->backend, ldisc->buf, ldisc->buflen); - if (ldisc->protocol == PROT_RAW) + if (ldisc->protocol == PROT_RAW) backend_send(ldisc->backend, "\r\n", 2); - else if (ldisc->protocol == PROT_TELNET && ldisc->telnet_newline) + else if (ldisc->protocol == PROT_TELNET && ldisc->telnet_newline) backend_special(ldisc->backend, SS_EOL, 0); - else + else backend_send(ldisc->backend, "\r", 1); - if (ECHOING) - c_write(ldisc, "\r\n", 2); - ldisc->buflen = 0; - break; - } - /* FALLTHROUGH */ - default: /* get to this label from ^V handler */ + if (ECHOING) + c_write(ldisc, "\r\n", 2); + ldisc->buflen = 0; + break; + } + /* FALLTHROUGH */ + default: /* get to this label from ^V handler */ default_case: sgrowarray(ldisc->buf, ldisc->bufsiz, ldisc->buflen); - ldisc->buf[ldisc->buflen++] = c; - if (ECHOING) - pwrite(ldisc, (unsigned char) c); - ldisc->quotenext = false; - break; - } - } + ldisc->buf[ldisc->buflen++] = c; + if (ECHOING) + pwrite(ldisc, (unsigned char) c); + ldisc->quotenext = false; + break; + } + } } else { - if (ldisc->buflen != 0) { + if (ldisc->buflen != 0) { backend_send(ldisc->backend, ldisc->buf, ldisc->buflen); - while (ldisc->buflen > 0) { - bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); - ldisc->buflen--; - } - } - if (len > 0) { - if (ECHOING) - c_write(ldisc, buf, len); - if (keyflag && ldisc->protocol == PROT_TELNET && len == 1) { - switch (buf[0]) { - case CTRL('M'): - if (ldisc->protocol == PROT_TELNET && ldisc->telnet_newline) + while (ldisc->buflen > 0) { + bsb(ldisc, plen(ldisc, ldisc->buf[ldisc->buflen - 1])); + ldisc->buflen--; + } + } + if (len > 0) { + if (ECHOING) + c_write(ldisc, buf, len); + if (keyflag && ldisc->protocol == PROT_TELNET && len == 1) { + switch (buf[0]) { + case CTRL('M'): + if (ldisc->protocol == PROT_TELNET && ldisc->telnet_newline) backend_special(ldisc->backend, SS_EOL, 0); - else + else backend_send(ldisc->backend, "\r", 1); - break; - case CTRL('?'): - case CTRL('H'): - if (ldisc->telnet_keyboard) { + break; + case CTRL('?'): + case CTRL('H'): + if (ldisc->telnet_keyboard) { backend_special(ldisc->backend, SS_EC, 0); - break; - } - case CTRL('C'): - if (ldisc->telnet_keyboard) { + break; + } + case CTRL('C'): + if (ldisc->telnet_keyboard) { backend_special(ldisc->backend, SS_IP, 0); - break; - } - case CTRL('Z'): - if (ldisc->telnet_keyboard) { + break; + } + case CTRL('Z'): + if (ldisc->telnet_keyboard) { backend_special(ldisc->backend, SS_SUSP, 0); - break; - } + break; + } - default: + default: backend_send(ldisc->backend, buf, len); - break; - } - } else + break; + } + } else backend_send(ldisc->backend, buf, len); - } + } } } diff --git a/logging.c b/logging.c index bfe90b52..173ed080 100644 --- a/logging.c +++ b/logging.c @@ -19,7 +19,7 @@ struct LogContext { Filename *currlogfilename; LogPolicy *lp; Conf *conf; - int logtype; /* cached out of conf */ + int logtype; /* cached out of conf */ }; static Filename *xlatlognam(Filename *s, char *hostname, int port, @@ -39,19 +39,19 @@ static void logwrite(LogContext *ctx, ptrlen data) * those three _after_ processing L_CLOSED. */ if (ctx->state == L_CLOSED) - logfopen(ctx); + logfopen(ctx); if (ctx->state == L_OPENING) { - bufchain_add(&ctx->queue, data.ptr, data.len); + bufchain_add(&ctx->queue, data.ptr, data.len); } else if (ctx->state == L_OPEN) { - assert(ctx->lgfp); - if (fwrite(data.ptr, 1, data.len, ctx->lgfp) < data.len) { - logfclose(ctx); - ctx->state = L_ERROR; + assert(ctx->lgfp); + if (fwrite(data.ptr, 1, data.len, ctx->lgfp) < data.len) { + logfclose(ctx); + ctx->state = L_ERROR; lp_eventlog(ctx->lp, "Disabled writing session log " "due to error while writing"); - } - } /* else L_ERROR, so ignore the write */ + } + } /* else L_ERROR, so ignore the write */ } /* @@ -77,8 +77,8 @@ static void logprintf(LogContext *ctx, const char *fmt, ...) void logflush(LogContext *ctx) { if (ctx->logtype > 0) - if (ctx->state == L_OPEN) - fflush(ctx->lgfp); + if (ctx->state == L_OPEN) + fflush(ctx->lgfp); } static void logfopen_callback(void *vctx, int mode) @@ -90,36 +90,36 @@ static void logfopen_callback(void *vctx, int mode) bool shout = false; if (mode == 0) { - ctx->state = L_ERROR; /* disable logging */ + ctx->state = L_ERROR; /* disable logging */ } else { - fmode = (mode == 1 ? "ab" : "wb"); - ctx->lgfp = f_open(ctx->currlogfilename, fmode, false); - if (ctx->lgfp) { - ctx->state = L_OPEN; + fmode = (mode == 1 ? "ab" : "wb"); + ctx->lgfp = f_open(ctx->currlogfilename, fmode, false); + if (ctx->lgfp) { + ctx->state = L_OPEN; } else { - ctx->state = L_ERROR; + ctx->state = L_ERROR; shout = true; } } if (ctx->state == L_OPEN && conf_get_bool(ctx->conf, CONF_logheader)) { - /* Write header line into log file. */ - tm = ltime(); - strftime(buf, 24, "%Y.%m.%d %H:%M:%S", &tm); - logprintf(ctx, "=~=~=~=~=~=~=~=~=~=~=~= PuTTY log %s" - " =~=~=~=~=~=~=~=~=~=~=~=\r\n", buf); + /* Write header line into log file. */ + tm = ltime(); + strftime(buf, 24, "%Y.%m.%d %H:%M:%S", &tm); + logprintf(ctx, "=~=~=~=~=~=~=~=~=~=~=~= PuTTY log %s" + " =~=~=~=~=~=~=~=~=~=~=~=\r\n", buf); } event = dupprintf("%s session log (%s mode) to file: %s", - ctx->state == L_ERROR ? - (mode == 0 ? "Disabled writing" : "Error writing") : - (mode == 1 ? "Appending" : "Writing new"), - (ctx->logtype == LGTYP_ASCII ? "ASCII" : - ctx->logtype == LGTYP_DEBUG ? "raw" : - ctx->logtype == LGTYP_PACKETS ? "SSH packets" : - ctx->logtype == LGTYP_SSHRAW ? "SSH raw data" : - "unknown"), - filename_to_str(ctx->currlogfilename)); + ctx->state == L_ERROR ? + (mode == 0 ? "Disabled writing" : "Error writing") : + (mode == 1 ? "Appending" : "Writing new"), + (ctx->logtype == LGTYP_ASCII ? "ASCII" : + ctx->logtype == LGTYP_DEBUG ? "raw" : + ctx->logtype == LGTYP_PACKETS ? "SSH packets" : + ctx->logtype == LGTYP_SSHRAW ? "SSH raw data" : + "unknown"), + filename_to_str(ctx->currlogfilename)); lp_eventlog(ctx->lp, event); if (shout) { /* @@ -138,8 +138,8 @@ static void logfopen_callback(void *vctx, int mode) assert(ctx->state != L_OPENING); /* make _sure_ it won't be requeued */ while (bufchain_size(&ctx->queue)) { ptrlen data = bufchain_prefix(&ctx->queue); - logwrite(ctx, data); - bufchain_consume(&ctx->queue, data.len); + logwrite(ctx, data); + bufchain_consume(&ctx->queue, data.len); } logflush(ctx); } @@ -156,42 +156,42 @@ void logfopen(LogContext *ctx) /* Prevent repeat calls */ if (ctx->state != L_CLOSED) - return; + return; if (!ctx->logtype) - return; + return; tm = ltime(); /* substitute special codes in file name */ if (ctx->currlogfilename) filename_free(ctx->currlogfilename); - ctx->currlogfilename = + ctx->currlogfilename = xlatlognam(conf_get_filename(ctx->conf, CONF_logfilename), conf_get_str(ctx->conf, CONF_host), conf_get_int(ctx->conf, CONF_port), &tm); if (open_for_write_would_lose_data(ctx->currlogfilename)) { - int logxfovr = conf_get_int(ctx->conf, CONF_logxfovr); - if (logxfovr != LGXF_ASK) { - mode = ((logxfovr == LGXF_OVR) ? 2 : 1); - } else + int logxfovr = conf_get_int(ctx->conf, CONF_logxfovr); + if (logxfovr != LGXF_ASK) { + mode = ((logxfovr == LGXF_OVR) ? 2 : 1); + } else mode = lp_askappend(ctx->lp, ctx->currlogfilename, logfopen_callback, ctx); } else - mode = 2; /* create == overwrite */ + mode = 2; /* create == overwrite */ if (mode < 0) - ctx->state = L_OPENING; + ctx->state = L_OPENING; else - logfopen_callback(ctx, mode); /* open the file */ + logfopen_callback(ctx, mode); /* open the file */ } void logfclose(LogContext *ctx) { if (ctx->lgfp) { - fclose(ctx->lgfp); - ctx->lgfp = NULL; + fclose(ctx->lgfp); + ctx->lgfp = NULL; } ctx->state = L_CLOSED; } @@ -202,8 +202,8 @@ void logfclose(LogContext *ctx) void logtraffic(LogContext *ctx, unsigned char c, int logmode) { if (ctx->logtype > 0) { - if (ctx->logtype == logmode) - logwrite(ctx, make_ptrlen(&c, 1)); + if (ctx->logtype == logmode) + logwrite(ctx, make_ptrlen(&c, 1)); } } @@ -274,9 +274,9 @@ void logeventf(LogContext *ctx, const char *fmt, ...) * Set of blanking areas must be in increasing order. */ void log_packet(LogContext *ctx, int direction, int type, - const char *texttype, const void *data, size_t len, - int n_blanks, const struct logblank_t *blanks, - const unsigned long *seq, + const char *texttype, const void *data, size_t len, + int n_blanks, const struct logblank_t *blanks, + const unsigned long *seq, unsigned downstream_id, const char *additional_log_text) { char dumpdata[128], smalldata[5]; @@ -285,20 +285,20 @@ void log_packet(LogContext *ctx, int direction, int type, if (!(ctx->logtype == LGTYP_SSHRAW || (ctx->logtype == LGTYP_PACKETS && texttype))) - return; + return; /* Packet header. */ if (texttype) { logprintf(ctx, "%s packet ", direction == PKT_INCOMING ? "Incoming" : "Outgoing"); - if (seq) - logprintf(ctx, "#0x%lx, ", *seq); + if (seq) + logprintf(ctx, "#0x%lx, ", *seq); logprintf(ctx, "type %d / 0x%02x (%s)", type, type, texttype); if (downstream_id) { - logprintf(ctx, " on behalf of downstream #%u", downstream_id); + logprintf(ctx, " on behalf of downstream #%u", downstream_id); if (additional_log_text) logprintf(ctx, " (%s)", additional_log_text); } @@ -315,8 +315,8 @@ void log_packet(LogContext *ctx, int direction, int type, */ char buf[256]; struct tm tm; - tm = ltime(); - strftime(buf, 24, "%Y-%m-%d %H:%M:%S", &tm); + tm = ltime(); + strftime(buf, 24, "%Y-%m-%d %H:%M:%S", &tm); logprintf(ctx, "%s raw data at %s\r\n", direction == PKT_INCOMING ? "Incoming" : "Outgoing", buf); @@ -327,68 +327,68 @@ void log_packet(LogContext *ctx, int direction, int type, * parts as specified. */ while (p < len) { - int blktype; + int blktype; - /* Move to a current entry in the blanking array. */ - while ((b < n_blanks) && - (p >= blanks[b].offset + blanks[b].len)) - b++; - /* Work out what type of blanking to apply to - * this byte. */ - blktype = PKTLOG_EMIT; /* default */ - if ((b < n_blanks) && - (p >= blanks[b].offset) && - (p < blanks[b].offset + blanks[b].len)) - blktype = blanks[b].type; + /* Move to a current entry in the blanking array. */ + while ((b < n_blanks) && + (p >= blanks[b].offset + blanks[b].len)) + b++; + /* Work out what type of blanking to apply to + * this byte. */ + blktype = PKTLOG_EMIT; /* default */ + if ((b < n_blanks) && + (p >= blanks[b].offset) && + (p < blanks[b].offset + blanks[b].len)) + blktype = blanks[b].type; - /* If we're about to stop omitting, it's time to say how - * much we omitted. */ - if ((blktype != PKTLOG_OMIT) && omitted) { - logprintf(ctx, " (%d byte%s omitted)\r\n", - omitted, (omitted==1?"":"s")); - omitted = 0; - } + /* If we're about to stop omitting, it's time to say how + * much we omitted. */ + if ((blktype != PKTLOG_OMIT) && omitted) { + logprintf(ctx, " (%d byte%s omitted)\r\n", + omitted, (omitted==1?"":"s")); + omitted = 0; + } - /* (Re-)initialise dumpdata as necessary - * (start of row, or if we've just stopped omitting) */ - if (!output_pos && !omitted) - sprintf(dumpdata, " %08zx%*s\r\n", p-(p%16), 1+3*16+2+16, ""); + /* (Re-)initialise dumpdata as necessary + * (start of row, or if we've just stopped omitting) */ + if (!output_pos && !omitted) + sprintf(dumpdata, " %08zx%*s\r\n", p-(p%16), 1+3*16+2+16, ""); - /* Deal with the current byte. */ - if (blktype == PKTLOG_OMIT) { - omitted++; - } else { - int c; - if (blktype == PKTLOG_BLANK) { - c = 'X'; - sprintf(smalldata, "XX"); - } else { /* PKTLOG_EMIT */ - c = ((unsigned char *)data)[p]; - sprintf(smalldata, "%02x", c); - } - dumpdata[10+2+3*(p%16)] = smalldata[0]; - dumpdata[10+2+3*(p%16)+1] = smalldata[1]; - dumpdata[10+1+3*16+2+(p%16)] = (c >= 0x20 && c < 0x7F ? c : '.'); - output_pos = (p%16) + 1; - } + /* Deal with the current byte. */ + if (blktype == PKTLOG_OMIT) { + omitted++; + } else { + int c; + if (blktype == PKTLOG_BLANK) { + c = 'X'; + sprintf(smalldata, "XX"); + } else { /* PKTLOG_EMIT */ + c = ((unsigned char *)data)[p]; + sprintf(smalldata, "%02x", c); + } + dumpdata[10+2+3*(p%16)] = smalldata[0]; + dumpdata[10+2+3*(p%16)+1] = smalldata[1]; + dumpdata[10+1+3*16+2+(p%16)] = (c >= 0x20 && c < 0x7F ? c : '.'); + output_pos = (p%16) + 1; + } - p++; + p++; - /* Flush row if necessary */ - if (((p % 16) == 0) || (p == len) || omitted) { - if (output_pos) { - strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n"); - logwrite(ctx, ptrlen_from_asciz(dumpdata)); - output_pos = 0; - } - } + /* Flush row if necessary */ + if (((p % 16) == 0) || (p == len) || omitted) { + if (output_pos) { + strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n"); + logwrite(ctx, ptrlen_from_asciz(dumpdata)); + output_pos = 0; + } + } } /* Tidy up */ if (omitted) - logprintf(ctx, " (%d byte%s omitted)\r\n", - omitted, (omitted==1?"":"s")); + logprintf(ctx, " (%d byte%s omitted)\r\n", + omitted, (omitted==1?"":"s")); logflush(ctx); } @@ -420,15 +420,15 @@ void log_reconfig(LogContext *ctx, Conf *conf) bool reset_logging; if (!filename_equal(conf_get_filename(ctx->conf, CONF_logfilename), - conf_get_filename(conf, CONF_logfilename)) || - conf_get_int(ctx->conf, CONF_logtype) != - conf_get_int(conf, CONF_logtype)) - reset_logging = true; + conf_get_filename(conf, CONF_logfilename)) || + conf_get_int(ctx->conf, CONF_logtype) != + conf_get_int(conf, CONF_logtype)) + reset_logging = true; else - reset_logging = false; + reset_logging = false; if (reset_logging) - logfclose(ctx); + logfclose(ctx); conf_free(ctx->conf); ctx->conf = conf_copy(conf); @@ -436,7 +436,7 @@ void log_reconfig(LogContext *ctx, Conf *conf) ctx->logtype = conf_get_int(ctx->conf, CONF_logtype); if (reset_logging) - logfopen(ctx); + logfopen(ctx); } /* @@ -459,48 +459,48 @@ static Filename *xlatlognam(Filename *src, char *hostname, int port, while (*s) { bool sanitise = false; - /* Let (bufp, len) be the string to append. */ - bufp = buf; /* don't usually override this */ - if (*s == '&') { - char c; - s++; - size = 0; - if (*s) switch (c = *s++, tolower((unsigned char)c)) { - case 'y': - size = strftime(buf, sizeof(buf), "%Y", tm); - break; - case 'm': - size = strftime(buf, sizeof(buf), "%m", tm); - break; - case 'd': - size = strftime(buf, sizeof(buf), "%d", tm); - break; - case 't': - size = strftime(buf, sizeof(buf), "%H%M%S", tm); - break; - case 'h': - bufp = hostname; - size = strlen(bufp); - break; - case 'p': + /* Let (bufp, len) be the string to append. */ + bufp = buf; /* don't usually override this */ + if (*s == '&') { + char c; + s++; + size = 0; + if (*s) switch (c = *s++, tolower((unsigned char)c)) { + case 'y': + size = strftime(buf, sizeof(buf), "%Y", tm); + break; + case 'm': + size = strftime(buf, sizeof(buf), "%m", tm); + break; + case 'd': + size = strftime(buf, sizeof(buf), "%d", tm); + break; + case 't': + size = strftime(buf, sizeof(buf), "%H%M%S", tm); + break; + case 'h': + bufp = hostname; + size = strlen(bufp); + break; + case 'p': size = sprintf(buf, "%d", port); - break; - default: - buf[0] = '&'; - size = 1; - if (c != '&') - buf[size++] = c; - } + break; + default: + buf[0] = '&'; + size = 1; + if (c != '&') + buf[size++] = c; + } /* Never allow path separators - or any other illegal * filename character - to come out of any of these * auto-format directives. E.g. 'hostname' can contain * colons, if it's an IPv6 address, and colons aren't * legal in filenames on Windows. */ sanitise = true; - } else { - buf[0] = *s++; - size = 1; - } + } else { + buf[0] = *s++; + size = 1; + } while (size-- > 0) { char c = *bufp++; if (sanitise) diff --git a/mainchan.c b/mainchan.c index 320db2b9..7722d4e8 100644 --- a/mainchan.c +++ b/mainchan.c @@ -134,15 +134,15 @@ static void mainchan_open_confirmation(Channel *chan) sshfwd_hint_channel_is_simple(mc->sc); if (mc->type == MAINCHAN_SESSION) { - /* - * Send the CHANNEL_REQUESTS for the main session channel. + /* + * Send the CHANNEL_REQUESTS for the main session channel. */ char *key, *val, *cmd; struct X11Display *x11disp; struct X11FakeAuth *x11auth; bool retry_cmd_now = false; - if (conf_get_bool(mc->conf, CONF_x11_forward)) {; + if (conf_get_bool(mc->conf, CONF_x11_forward)) {; char *x11_setup_err; if ((x11disp = x11_setup_display( conf_get_str(mc->conf, CONF_x11_display), @@ -161,12 +161,12 @@ static void mainchan_open_confirmation(Channel *chan) } } - if (ssh_agent_forwarding_permitted(mc->cl)) { + if (ssh_agent_forwarding_permitted(mc->cl)) { sshfwd_request_agent_forwarding(mc->sc, true); mc->req_agent = true; } - if (!conf_get_bool(mc->conf, CONF_nopty)) { + if (!conf_get_bool(mc->conf, CONF_nopty)) { sshfwd_request_pty( mc->sc, true, mc->conf, mc->term_width, mc->term_height); mc->req_pty = true; @@ -327,7 +327,7 @@ static void mainchan_ready(mainchan *mc) /* If an EOF arrived before we were ready, handle it now. */ if (mc->eof_pending) { mc->eof_pending = false; - mainchan_special_cmd(mc, SS_EOF, 0); + mainchan_special_cmd(mc, SS_EOF, 0); } ssh_ldisc_update(mc->ppl->ssh); diff --git a/memory.c b/memory.c index 5d340253..43dd8666 100644 --- a/memory.c +++ b/memory.c @@ -46,22 +46,22 @@ void *saferealloc(void *ptr, size_t n, size_t size) void *p; if (n > INT_MAX / size) { - p = NULL; + p = NULL; } else { - size *= n; - if (!ptr) { + size *= n; + if (!ptr) { #ifdef MINEFIELD - p = minefield_c_malloc(size); + p = minefield_c_malloc(size); #else - p = malloc(size); + p = malloc(size); #endif - } else { + } 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) @@ -74,9 +74,9 @@ void safefree(void *ptr) { if (ptr) { #ifdef MINEFIELD - minefield_c_free(ptr); + minefield_c_free(ptr); #else - free(ptr); + free(ptr); #endif } } diff --git a/minibidi.c b/minibidi.c index 0ee087a5..39b66618 100644 --- a/minibidi.c +++ b/minibidi.c @@ -21,15 +21,15 @@ * - Ligatures */ -#include /* definition of wchar_t*/ +#include /* definition of wchar_t*/ #include "putty.h" #include "misc.h" -#define LMASK 0x3F /* Embedding Level mask */ -#define OMASK 0xC0 /* Override mask */ -#define OISL 0x80 /* Override is L */ -#define OISR 0x40 /* Override is R */ +#define LMASK 0x3F /* Embedding Level mask */ +#define OMASK 0xC0 /* Override mask */ +#define OISL 0x80 /* Override is L */ +#define OISR 0x40 /* Override is R */ /* For standalone compilation in a testing mode. * Still depends on the PuTTY headers for snewn and sfree, but can avoid @@ -303,18 +303,18 @@ static void flipThisRun( j = i = 0; while (i j; k--, j++) { - temp = from[k]; - from[k] = from[j]; - from[j] = temp; - } + /* find the start of the run of level=max */ + tlevel = max; + i = j = findIndexOfRun(level, i, count, max); + /* find the end of the run */ + while (i j; k--, j++) { + temp = from[k]; + from[k] = from[j]; + from[j] = temp; + } } } @@ -326,9 +326,9 @@ static int findIndexOfRun( { int i; for (i=start; i 1) { - k = (i + j) / 2; - if (ch < lookup[k].first) - j = k; - else if (ch > lookup[k].last) - i = k; - else - return lookup[k].type; + k = (i + j) / 2; + if (ch < lookup[k].first) + j = k; + else if (ch > lookup[k].last) + i = k; + else + return lookup[k].type; } /* @@ -1011,14 +1011,14 @@ static unsigned char getType(int ch) * text display function can't conveniently be prevented from doing * its own bidi and so special treatment is required for characters * that would cause the bidi algorithm to activate). - * + * * This function is passed a single Unicode code point, and returns * nonzero if the presence of this code point can possibly cause * the bidi algorithm to do any reordering. Thus, any string * composed entirely of characters for which is_rtl() returns zero * should be safe to pass to a bidi-active platform display * function without fear. - * + * * (is_rtl() must therefore also return true for any character * which would be affected by Arabic shaping, but this isn't * important because all such characters are right-to-left so it @@ -1049,11 +1049,11 @@ static unsigned char setOverrideBits( unsigned char level, unsigned char override) { if (override == ON) - return level; + return level; else if (override == R) - return level | OISR; + return level | OISR; else if (override == L) - return level | OISL; + return level | OISL; return level; } @@ -1091,83 +1091,83 @@ int do_shape(bidi_char *line, bidi_char *to, int count) bool ligFlag = false; for (i=0; i 0) switch (line[i-1].wc) { - case 0x622: - ligFlag = true; - if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = 0xFEF6; - else - to[i].wc = 0xFEF5; - break; - case 0x623: - ligFlag = true; - if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = 0xFEF8; - else - to[i].wc = 0xFEF7; - break; - case 0x625: - ligFlag = true; - if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = 0xFEFA; - else - to[i].wc = 0xFEF9; - break; - case 0x627: - ligFlag = true; - if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = 0xFEFC; - else - to[i].wc = 0xFEFB; - break; - } - if (ligFlag) { - to[i-1].wc = 0x20; - ligFlag = false; - break; - } - } + case SD: + /* Make Ligatures */ + tempShape = (i+1 < count ? STYPE(line[i+1].wc) : SU); + if (line[i].wc == 0x644) { + if (i > 0) switch (line[i-1].wc) { + case 0x622: + ligFlag = true; + if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = 0xFEF6; + else + to[i].wc = 0xFEF5; + break; + case 0x623: + ligFlag = true; + if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = 0xFEF8; + else + to[i].wc = 0xFEF7; + break; + case 0x625: + ligFlag = true; + if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = 0xFEFA; + else + to[i].wc = 0xFEF9; + break; + case 0x627: + ligFlag = true; + if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = 0xFEFC; + else + to[i].wc = 0xFEFB; + break; + } + if (ligFlag) { + to[i-1].wc = 0x20; + ligFlag = false; + break; + } + } - if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) { + if ((tempShape == SL) || (tempShape == SD) || (tempShape == SC)) { tempShape = (i > 0 ? STYPE(line[i-1].wc) : SU); - if ((tempShape == SR) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = SMEDIAL((SISOLATED(line[i].wc))); - else - to[i].wc = SFINAL((SISOLATED(line[i].wc))); - break; - } + if ((tempShape == SR) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = SMEDIAL((SISOLATED(line[i].wc))); + else + to[i].wc = SFINAL((SISOLATED(line[i].wc))); + break; + } tempShape = (i > 0 ? STYPE(line[i-1].wc) : SU); - if ((tempShape == SR) || (tempShape == SD) || (tempShape == SC)) - to[i].wc = SINITIAL((SISOLATED(line[i].wc))); - else - to[i].wc = SISOLATED(line[i].wc); - break; + if ((tempShape == SR) || (tempShape == SD) || (tempShape == SC)) + to[i].wc = SINITIAL((SISOLATED(line[i].wc))); + else + to[i].wc = SISOLATED(line[i].wc); + break; - } + } } return 1; } @@ -1194,14 +1194,14 @@ int do_bidi(bidi_char *line, int count) /* Check the presence of R or AL types as optimization */ yes = false; for (i=0; i= 0) { - if (types[j] == AL) { - types[i] = AN; - break; - } else if (types[j] == R || types[j] == L) { + if (types[i] == EN) { + j=i; + while (j >= 0) { + if (types[j] == AL) { + types[i] = AN; + break; + } else if (types[j] == R || types[j] == L) { break; } - j--; - } - } + j--; + } + } } /* Rule (W3) @@ -1379,8 +1379,8 @@ int do_bidi(bidi_char *line, int count) * to prevent this loop in L R lines only... */ for (i=0; i 0 && types[i-1] == EN) { - types[i] = EN; - continue; - } else if (i < count-1 && types[i+1] == EN) { + if (types[i] == ET) { + if (i > 0 && types[i-1] == EN) { + types[i] = EN; + continue; + } else if (i < count-1 && types[i+1] == EN) { types[i] = EN; continue; } else if (i < count-1 && types[i+1] == ET) { @@ -1422,20 +1422,20 @@ int do_bidi(bidi_char *line, int count) if (types[j] == EN) types[i] = EN; } - } + } } /* Rule (W6) * W6. Otherwise, separators and terminators change to Other Neutral: */ for (i=0; i= 0) { - if (types[j] == L) { - types[i] = L; - break; - } else if (types[j] == R || types[j] == AL) { - break; - } - j--; - } - } + if (types[i] == EN) { + j=i; + while (j >= 0) { + if (types[j] == L) { + types[i] = L; + break; + } else if (types[j] == R || types[j] == AL) { + break; + } + j--; + } + } } /* Rule (N1) @@ -1464,26 +1464,26 @@ int do_bidi(bidi_char *line, int count) * and Arabic numbers are treated as though they were R. */ if (count >= 2 && types[0] == ON) { - if ((types[1] == R) || (types[1] == EN) || (types[1] == AN)) - types[0] = R; - else if (types[1] == L) - types[0] = L; + if ((types[1] == R) || (types[1] == EN) || (types[1] == AN)) + types[0] = R; + else if (types[1] == L) + types[0] = L; } for (i=1; i<(count-1); i++) { - if (types[i] == ON) { - if (types[i-1] == L) { - j=i; - while (j<(count-1) && types[j] == ON) { - j++; - } - if (types[j] == L) { - while (i= 2 && types[count-1] == ON) { - if (types[count-2] == R || types[count-2] == EN || types[count-2] == AN) - types[count-1] = R; - else if (types[count-2] == L) - types[count-1] = L; + if (types[count-2] == R || types[count-2] == EN || types[count-2] == AN) + types[count-1] = R; + else if (types[count-2] == L) + types[count-1] = L; } /* Rule (N2) * N2. Any remaining neutrals take the embedding direction. */ for (i=0; i0 && (getType(line[j].wc) == WS)) { - j--; + j--; } if (j < (count-1)) { - for (j++; j=i ; j--) { - levels[j] = paragraphLevel; - } - } - } else if (tempType == B || tempType == S) { + for (j--; j>=i ; j--) { + levels[j] = paragraphLevel; + } + } + } else if (tempType == B || tempType == S) { levels[i] = paragraphLevel; } } @@ -1589,8 +1589,8 @@ int do_bidi(bidi_char *line, int count) */ /* Note: this is implemented before L2 for efficiency */ for (i=0; i tempType) - tempType = levels[i]; - i++; + if (levels[i] > tempType) + tempType = levels[i]; + i++; } /* maximum level in tempType. */ while (tempType > 0) { /* loop from highest level to the least odd, */ /* which i assume is 1 */ - flipThisRun(line, levels, tempType, count); - tempType--; + flipThisRun(line, levels, tempType, count); + tempType--; } /* Rule (L3) NOT IMPLEMENTED @@ -1634,146 +1634,146 @@ int do_bidi(bidi_char *line, int count) static void doMirror(unsigned int *ch) { if ((*ch & 0xFF00) == 0) { - switch (*ch) { - case 0x0028: *ch = 0x0029; break; - case 0x0029: *ch = 0x0028; break; - case 0x003C: *ch = 0x003E; break; - case 0x003E: *ch = 0x003C; break; - case 0x005B: *ch = 0x005D; break; - case 0x005D: *ch = 0x005B; break; - case 0x007B: *ch = 0x007D; break; - case 0x007D: *ch = 0x007B; break; - case 0x00AB: *ch = 0x00BB; break; - case 0x00BB: *ch = 0x00AB; break; - } + switch (*ch) { + case 0x0028: *ch = 0x0029; break; + case 0x0029: *ch = 0x0028; break; + case 0x003C: *ch = 0x003E; break; + case 0x003E: *ch = 0x003C; break; + case 0x005B: *ch = 0x005D; break; + case 0x005D: *ch = 0x005B; break; + case 0x007B: *ch = 0x007D; break; + case 0x007D: *ch = 0x007B; break; + case 0x00AB: *ch = 0x00BB; break; + case 0x00BB: *ch = 0x00AB; break; + } } else if ((*ch & 0xFF00) == 0x2000) { - switch (*ch) { - case 0x2039: *ch = 0x203A; break; - case 0x203A: *ch = 0x2039; break; - case 0x2045: *ch = 0x2046; break; - case 0x2046: *ch = 0x2045; break; - case 0x207D: *ch = 0x207E; break; - case 0x207E: *ch = 0x207D; break; - case 0x208D: *ch = 0x208E; break; - case 0x208E: *ch = 0x208D; break; - } + switch (*ch) { + case 0x2039: *ch = 0x203A; break; + case 0x203A: *ch = 0x2039; break; + case 0x2045: *ch = 0x2046; break; + case 0x2046: *ch = 0x2045; break; + case 0x207D: *ch = 0x207E; break; + case 0x207E: *ch = 0x207D; break; + case 0x208D: *ch = 0x208E; break; + case 0x208E: *ch = 0x208D; break; + } } else if ((*ch & 0xFF00) == 0x2200) { - switch (*ch) { - case 0x2208: *ch = 0x220B; break; - case 0x2209: *ch = 0x220C; break; - case 0x220A: *ch = 0x220D; break; - case 0x220B: *ch = 0x2208; break; - case 0x220C: *ch = 0x2209; break; - case 0x220D: *ch = 0x220A; break; - case 0x2215: *ch = 0x29F5; break; - case 0x223C: *ch = 0x223D; break; - case 0x223D: *ch = 0x223C; break; - case 0x2243: *ch = 0x22CD; break; - case 0x2252: *ch = 0x2253; break; - case 0x2253: *ch = 0x2252; break; - case 0x2254: *ch = 0x2255; break; - case 0x2255: *ch = 0x2254; break; - case 0x2264: *ch = 0x2265; break; - case 0x2265: *ch = 0x2264; break; - case 0x2266: *ch = 0x2267; break; - case 0x2267: *ch = 0x2266; break; - case 0x2268: *ch = 0x2269; break; - case 0x2269: *ch = 0x2268; break; - case 0x226A: *ch = 0x226B; break; - case 0x226B: *ch = 0x226A; break; - case 0x226E: *ch = 0x226F; break; - case 0x226F: *ch = 0x226E; break; - case 0x2270: *ch = 0x2271; break; - case 0x2271: *ch = 0x2270; break; - case 0x2272: *ch = 0x2273; break; - case 0x2273: *ch = 0x2272; break; - case 0x2274: *ch = 0x2275; break; - case 0x2275: *ch = 0x2274; break; - case 0x2276: *ch = 0x2277; break; - case 0x2277: *ch = 0x2276; break; - case 0x2278: *ch = 0x2279; break; - case 0x2279: *ch = 0x2278; break; - case 0x227A: *ch = 0x227B; break; - case 0x227B: *ch = 0x227A; break; - case 0x227C: *ch = 0x227D; break; - case 0x227D: *ch = 0x227C; break; - case 0x227E: *ch = 0x227F; break; - case 0x227F: *ch = 0x227E; break; - case 0x2280: *ch = 0x2281; break; - case 0x2281: *ch = 0x2280; break; - case 0x2282: *ch = 0x2283; break; - case 0x2283: *ch = 0x2282; break; - case 0x2284: *ch = 0x2285; break; - case 0x2285: *ch = 0x2284; break; - case 0x2286: *ch = 0x2287; break; - case 0x2287: *ch = 0x2286; break; - case 0x2288: *ch = 0x2289; break; - case 0x2289: *ch = 0x2288; break; - case 0x228A: *ch = 0x228B; break; - case 0x228B: *ch = 0x228A; break; - case 0x228F: *ch = 0x2290; break; - case 0x2290: *ch = 0x228F; break; - case 0x2291: *ch = 0x2292; break; - case 0x2292: *ch = 0x2291; break; - case 0x2298: *ch = 0x29B8; break; - case 0x22A2: *ch = 0x22A3; break; - case 0x22A3: *ch = 0x22A2; break; - case 0x22A6: *ch = 0x2ADE; break; - case 0x22A8: *ch = 0x2AE4; break; - case 0x22A9: *ch = 0x2AE3; break; - case 0x22AB: *ch = 0x2AE5; break; - case 0x22B0: *ch = 0x22B1; break; - case 0x22B1: *ch = 0x22B0; break; - case 0x22B2: *ch = 0x22B3; break; - case 0x22B3: *ch = 0x22B2; break; - case 0x22B4: *ch = 0x22B5; break; - case 0x22B5: *ch = 0x22B4; break; - case 0x22B6: *ch = 0x22B7; break; - case 0x22B7: *ch = 0x22B6; break; - case 0x22C9: *ch = 0x22CA; break; - case 0x22CA: *ch = 0x22C9; break; - case 0x22CB: *ch = 0x22CC; break; - case 0x22CC: *ch = 0x22CB; break; - case 0x22CD: *ch = 0x2243; break; - case 0x22D0: *ch = 0x22D1; break; - case 0x22D1: *ch = 0x22D0; break; - case 0x22D6: *ch = 0x22D7; break; - case 0x22D7: *ch = 0x22D6; break; - case 0x22D8: *ch = 0x22D9; break; - case 0x22D9: *ch = 0x22D8; break; - case 0x22DA: *ch = 0x22DB; break; - case 0x22DB: *ch = 0x22DA; break; - case 0x22DC: *ch = 0x22DD; break; - case 0x22DD: *ch = 0x22DC; break; - case 0x22DE: *ch = 0x22DF; break; - case 0x22DF: *ch = 0x22DE; break; - case 0x22E0: *ch = 0x22E1; break; - case 0x22E1: *ch = 0x22E0; break; - case 0x22E2: *ch = 0x22E3; break; - case 0x22E3: *ch = 0x22E2; break; - case 0x22E4: *ch = 0x22E5; break; - case 0x22E5: *ch = 0x22E4; break; - case 0x22E6: *ch = 0x22E7; break; - case 0x22E7: *ch = 0x22E6; break; - case 0x22E8: *ch = 0x22E9; break; - case 0x22E9: *ch = 0x22E8; break; - case 0x22EA: *ch = 0x22EB; break; - case 0x22EB: *ch = 0x22EA; break; - case 0x22EC: *ch = 0x22ED; break; - case 0x22ED: *ch = 0x22EC; break; - case 0x22F0: *ch = 0x22F1; break; - case 0x22F1: *ch = 0x22F0; break; - case 0x22F2: *ch = 0x22FA; break; - case 0x22F3: *ch = 0x22FB; break; - case 0x22F4: *ch = 0x22FC; break; - case 0x22F6: *ch = 0x22FD; break; - case 0x22F7: *ch = 0x22FE; break; - case 0x22FA: *ch = 0x22F2; break; - case 0x22FB: *ch = 0x22F3; break; - case 0x22FC: *ch = 0x22F4; break; - case 0x22FD: *ch = 0x22F6; break; - case 0x22FE: *ch = 0x22F7; break; - } + switch (*ch) { + case 0x2208: *ch = 0x220B; break; + case 0x2209: *ch = 0x220C; break; + case 0x220A: *ch = 0x220D; break; + case 0x220B: *ch = 0x2208; break; + case 0x220C: *ch = 0x2209; break; + case 0x220D: *ch = 0x220A; break; + case 0x2215: *ch = 0x29F5; break; + case 0x223C: *ch = 0x223D; break; + case 0x223D: *ch = 0x223C; break; + case 0x2243: *ch = 0x22CD; break; + case 0x2252: *ch = 0x2253; break; + case 0x2253: *ch = 0x2252; break; + case 0x2254: *ch = 0x2255; break; + case 0x2255: *ch = 0x2254; break; + case 0x2264: *ch = 0x2265; break; + case 0x2265: *ch = 0x2264; break; + case 0x2266: *ch = 0x2267; break; + case 0x2267: *ch = 0x2266; break; + case 0x2268: *ch = 0x2269; break; + case 0x2269: *ch = 0x2268; break; + case 0x226A: *ch = 0x226B; break; + case 0x226B: *ch = 0x226A; break; + case 0x226E: *ch = 0x226F; break; + case 0x226F: *ch = 0x226E; break; + case 0x2270: *ch = 0x2271; break; + case 0x2271: *ch = 0x2270; break; + case 0x2272: *ch = 0x2273; break; + case 0x2273: *ch = 0x2272; break; + case 0x2274: *ch = 0x2275; break; + case 0x2275: *ch = 0x2274; break; + case 0x2276: *ch = 0x2277; break; + case 0x2277: *ch = 0x2276; break; + case 0x2278: *ch = 0x2279; break; + case 0x2279: *ch = 0x2278; break; + case 0x227A: *ch = 0x227B; break; + case 0x227B: *ch = 0x227A; break; + case 0x227C: *ch = 0x227D; break; + case 0x227D: *ch = 0x227C; break; + case 0x227E: *ch = 0x227F; break; + case 0x227F: *ch = 0x227E; break; + case 0x2280: *ch = 0x2281; break; + case 0x2281: *ch = 0x2280; break; + case 0x2282: *ch = 0x2283; break; + case 0x2283: *ch = 0x2282; break; + case 0x2284: *ch = 0x2285; break; + case 0x2285: *ch = 0x2284; break; + case 0x2286: *ch = 0x2287; break; + case 0x2287: *ch = 0x2286; break; + case 0x2288: *ch = 0x2289; break; + case 0x2289: *ch = 0x2288; break; + case 0x228A: *ch = 0x228B; break; + case 0x228B: *ch = 0x228A; break; + case 0x228F: *ch = 0x2290; break; + case 0x2290: *ch = 0x228F; break; + case 0x2291: *ch = 0x2292; break; + case 0x2292: *ch = 0x2291; break; + case 0x2298: *ch = 0x29B8; break; + case 0x22A2: *ch = 0x22A3; break; + case 0x22A3: *ch = 0x22A2; break; + case 0x22A6: *ch = 0x2ADE; break; + case 0x22A8: *ch = 0x2AE4; break; + case 0x22A9: *ch = 0x2AE3; break; + case 0x22AB: *ch = 0x2AE5; break; + case 0x22B0: *ch = 0x22B1; break; + case 0x22B1: *ch = 0x22B0; break; + case 0x22B2: *ch = 0x22B3; break; + case 0x22B3: *ch = 0x22B2; break; + case 0x22B4: *ch = 0x22B5; break; + case 0x22B5: *ch = 0x22B4; break; + case 0x22B6: *ch = 0x22B7; break; + case 0x22B7: *ch = 0x22B6; break; + case 0x22C9: *ch = 0x22CA; break; + case 0x22CA: *ch = 0x22C9; break; + case 0x22CB: *ch = 0x22CC; break; + case 0x22CC: *ch = 0x22CB; break; + case 0x22CD: *ch = 0x2243; break; + case 0x22D0: *ch = 0x22D1; break; + case 0x22D1: *ch = 0x22D0; break; + case 0x22D6: *ch = 0x22D7; break; + case 0x22D7: *ch = 0x22D6; break; + case 0x22D8: *ch = 0x22D9; break; + case 0x22D9: *ch = 0x22D8; break; + case 0x22DA: *ch = 0x22DB; break; + case 0x22DB: *ch = 0x22DA; break; + case 0x22DC: *ch = 0x22DD; break; + case 0x22DD: *ch = 0x22DC; break; + case 0x22DE: *ch = 0x22DF; break; + case 0x22DF: *ch = 0x22DE; break; + case 0x22E0: *ch = 0x22E1; break; + case 0x22E1: *ch = 0x22E0; break; + case 0x22E2: *ch = 0x22E3; break; + case 0x22E3: *ch = 0x22E2; break; + case 0x22E4: *ch = 0x22E5; break; + case 0x22E5: *ch = 0x22E4; break; + case 0x22E6: *ch = 0x22E7; break; + case 0x22E7: *ch = 0x22E6; break; + case 0x22E8: *ch = 0x22E9; break; + case 0x22E9: *ch = 0x22E8; break; + case 0x22EA: *ch = 0x22EB; break; + case 0x22EB: *ch = 0x22EA; break; + case 0x22EC: *ch = 0x22ED; break; + case 0x22ED: *ch = 0x22EC; break; + case 0x22F0: *ch = 0x22F1; break; + case 0x22F1: *ch = 0x22F0; break; + case 0x22F2: *ch = 0x22FA; break; + case 0x22F3: *ch = 0x22FB; break; + case 0x22F4: *ch = 0x22FC; break; + case 0x22F6: *ch = 0x22FD; break; + case 0x22F7: *ch = 0x22FE; break; + case 0x22FA: *ch = 0x22F2; break; + case 0x22FB: *ch = 0x22F3; break; + case 0x22FC: *ch = 0x22F4; break; + case 0x22FD: *ch = 0x22F6; break; + case 0x22FE: *ch = 0x22F7; break; + } } else if ((*ch & 0xFF00) == 0x2300) { switch (*ch) { case 0x2308: *ch = 0x2309; break; @@ -1784,200 +1784,200 @@ static void doMirror(unsigned int *ch) case 0x232A: *ch = 0x2329; break; } } else if ((*ch & 0xFF00) == 0x2700) { - switch (*ch) { - case 0x2768: *ch = 0x2769; break; - case 0x2769: *ch = 0x2768; break; - case 0x276A: *ch = 0x276B; break; - case 0x276B: *ch = 0x276A; break; - case 0x276C: *ch = 0x276D; break; - case 0x276D: *ch = 0x276C; break; - case 0x276E: *ch = 0x276F; break; - case 0x276F: *ch = 0x276E; break; - case 0x2770: *ch = 0x2771; break; - case 0x2771: *ch = 0x2770; break; - case 0x2772: *ch = 0x2773; break; - case 0x2773: *ch = 0x2772; break; - case 0x2774: *ch = 0x2775; break; - case 0x2775: *ch = 0x2774; break; - case 0x27D5: *ch = 0x27D6; break; - case 0x27D6: *ch = 0x27D5; break; - case 0x27DD: *ch = 0x27DE; break; - case 0x27DE: *ch = 0x27DD; break; - case 0x27E2: *ch = 0x27E3; break; - case 0x27E3: *ch = 0x27E2; break; - case 0x27E4: *ch = 0x27E5; break; - case 0x27E5: *ch = 0x27E4; break; - case 0x27E6: *ch = 0x27E7; break; - case 0x27E7: *ch = 0x27E6; break; - case 0x27E8: *ch = 0x27E9; break; - case 0x27E9: *ch = 0x27E8; break; - case 0x27EA: *ch = 0x27EB; break; - case 0x27EB: *ch = 0x27EA; break; - } + switch (*ch) { + case 0x2768: *ch = 0x2769; break; + case 0x2769: *ch = 0x2768; break; + case 0x276A: *ch = 0x276B; break; + case 0x276B: *ch = 0x276A; break; + case 0x276C: *ch = 0x276D; break; + case 0x276D: *ch = 0x276C; break; + case 0x276E: *ch = 0x276F; break; + case 0x276F: *ch = 0x276E; break; + case 0x2770: *ch = 0x2771; break; + case 0x2771: *ch = 0x2770; break; + case 0x2772: *ch = 0x2773; break; + case 0x2773: *ch = 0x2772; break; + case 0x2774: *ch = 0x2775; break; + case 0x2775: *ch = 0x2774; break; + case 0x27D5: *ch = 0x27D6; break; + case 0x27D6: *ch = 0x27D5; break; + case 0x27DD: *ch = 0x27DE; break; + case 0x27DE: *ch = 0x27DD; break; + case 0x27E2: *ch = 0x27E3; break; + case 0x27E3: *ch = 0x27E2; break; + case 0x27E4: *ch = 0x27E5; break; + case 0x27E5: *ch = 0x27E4; break; + case 0x27E6: *ch = 0x27E7; break; + case 0x27E7: *ch = 0x27E6; break; + case 0x27E8: *ch = 0x27E9; break; + case 0x27E9: *ch = 0x27E8; break; + case 0x27EA: *ch = 0x27EB; break; + case 0x27EB: *ch = 0x27EA; break; + } } else if ((*ch & 0xFF00) == 0x2900) { - switch (*ch) { - case 0x2983: *ch = 0x2984; break; - case 0x2984: *ch = 0x2983; break; - case 0x2985: *ch = 0x2986; break; - case 0x2986: *ch = 0x2985; break; - case 0x2987: *ch = 0x2988; break; - case 0x2988: *ch = 0x2987; break; - case 0x2989: *ch = 0x298A; break; - case 0x298A: *ch = 0x2989; break; - case 0x298B: *ch = 0x298C; break; - case 0x298C: *ch = 0x298B; break; - case 0x298D: *ch = 0x2990; break; - case 0x298E: *ch = 0x298F; break; - case 0x298F: *ch = 0x298E; break; - case 0x2990: *ch = 0x298D; break; - case 0x2991: *ch = 0x2992; break; - case 0x2992: *ch = 0x2991; break; - case 0x2993: *ch = 0x2994; break; - case 0x2994: *ch = 0x2993; break; - case 0x2995: *ch = 0x2996; break; - case 0x2996: *ch = 0x2995; break; - case 0x2997: *ch = 0x2998; break; - case 0x2998: *ch = 0x2997; break; - case 0x29B8: *ch = 0x2298; break; - case 0x29C0: *ch = 0x29C1; break; - case 0x29C1: *ch = 0x29C0; break; - case 0x29C4: *ch = 0x29C5; break; - case 0x29C5: *ch = 0x29C4; break; - case 0x29CF: *ch = 0x29D0; break; - case 0x29D0: *ch = 0x29CF; break; - case 0x29D1: *ch = 0x29D2; break; - case 0x29D2: *ch = 0x29D1; break; - case 0x29D4: *ch = 0x29D5; break; - case 0x29D5: *ch = 0x29D4; break; - case 0x29D8: *ch = 0x29D9; break; - case 0x29D9: *ch = 0x29D8; break; - case 0x29DA: *ch = 0x29DB; break; - case 0x29DB: *ch = 0x29DA; break; - case 0x29F5: *ch = 0x2215; break; - case 0x29F8: *ch = 0x29F9; break; - case 0x29F9: *ch = 0x29F8; break; - case 0x29FC: *ch = 0x29FD; break; - case 0x29FD: *ch = 0x29FC; break; - } + switch (*ch) { + case 0x2983: *ch = 0x2984; break; + case 0x2984: *ch = 0x2983; break; + case 0x2985: *ch = 0x2986; break; + case 0x2986: *ch = 0x2985; break; + case 0x2987: *ch = 0x2988; break; + case 0x2988: *ch = 0x2987; break; + case 0x2989: *ch = 0x298A; break; + case 0x298A: *ch = 0x2989; break; + case 0x298B: *ch = 0x298C; break; + case 0x298C: *ch = 0x298B; break; + case 0x298D: *ch = 0x2990; break; + case 0x298E: *ch = 0x298F; break; + case 0x298F: *ch = 0x298E; break; + case 0x2990: *ch = 0x298D; break; + case 0x2991: *ch = 0x2992; break; + case 0x2992: *ch = 0x2991; break; + case 0x2993: *ch = 0x2994; break; + case 0x2994: *ch = 0x2993; break; + case 0x2995: *ch = 0x2996; break; + case 0x2996: *ch = 0x2995; break; + case 0x2997: *ch = 0x2998; break; + case 0x2998: *ch = 0x2997; break; + case 0x29B8: *ch = 0x2298; break; + case 0x29C0: *ch = 0x29C1; break; + case 0x29C1: *ch = 0x29C0; break; + case 0x29C4: *ch = 0x29C5; break; + case 0x29C5: *ch = 0x29C4; break; + case 0x29CF: *ch = 0x29D0; break; + case 0x29D0: *ch = 0x29CF; break; + case 0x29D1: *ch = 0x29D2; break; + case 0x29D2: *ch = 0x29D1; break; + case 0x29D4: *ch = 0x29D5; break; + case 0x29D5: *ch = 0x29D4; break; + case 0x29D8: *ch = 0x29D9; break; + case 0x29D9: *ch = 0x29D8; break; + case 0x29DA: *ch = 0x29DB; break; + case 0x29DB: *ch = 0x29DA; break; + case 0x29F5: *ch = 0x2215; break; + case 0x29F8: *ch = 0x29F9; break; + case 0x29F9: *ch = 0x29F8; break; + case 0x29FC: *ch = 0x29FD; break; + case 0x29FD: *ch = 0x29FC; break; + } } else if ((*ch & 0xFF00) == 0x2A00) { - switch (*ch) { - case 0x2A2B: *ch = 0x2A2C; break; - case 0x2A2C: *ch = 0x2A2B; break; - case 0x2A2D: *ch = 0x2A2C; break; - case 0x2A2E: *ch = 0x2A2D; break; - case 0x2A34: *ch = 0x2A35; break; - case 0x2A35: *ch = 0x2A34; break; - case 0x2A3C: *ch = 0x2A3D; break; - case 0x2A3D: *ch = 0x2A3C; break; - case 0x2A64: *ch = 0x2A65; break; - case 0x2A65: *ch = 0x2A64; break; - case 0x2A79: *ch = 0x2A7A; break; - case 0x2A7A: *ch = 0x2A79; break; - case 0x2A7D: *ch = 0x2A7E; break; - case 0x2A7E: *ch = 0x2A7D; break; - case 0x2A7F: *ch = 0x2A80; break; - case 0x2A80: *ch = 0x2A7F; break; - case 0x2A81: *ch = 0x2A82; break; - case 0x2A82: *ch = 0x2A81; break; - case 0x2A83: *ch = 0x2A84; break; - case 0x2A84: *ch = 0x2A83; break; - case 0x2A8B: *ch = 0x2A8C; break; - case 0x2A8C: *ch = 0x2A8B; break; - case 0x2A91: *ch = 0x2A92; break; - case 0x2A92: *ch = 0x2A91; break; - case 0x2A93: *ch = 0x2A94; break; - case 0x2A94: *ch = 0x2A93; break; - case 0x2A95: *ch = 0x2A96; break; - case 0x2A96: *ch = 0x2A95; break; - case 0x2A97: *ch = 0x2A98; break; - case 0x2A98: *ch = 0x2A97; break; - case 0x2A99: *ch = 0x2A9A; break; - case 0x2A9A: *ch = 0x2A99; break; - case 0x2A9B: *ch = 0x2A9C; break; - case 0x2A9C: *ch = 0x2A9B; break; - case 0x2AA1: *ch = 0x2AA2; break; - case 0x2AA2: *ch = 0x2AA1; break; - case 0x2AA6: *ch = 0x2AA7; break; - case 0x2AA7: *ch = 0x2AA6; break; - case 0x2AA8: *ch = 0x2AA9; break; - case 0x2AA9: *ch = 0x2AA8; break; - case 0x2AAA: *ch = 0x2AAB; break; - case 0x2AAB: *ch = 0x2AAA; break; - case 0x2AAC: *ch = 0x2AAD; break; - case 0x2AAD: *ch = 0x2AAC; break; - case 0x2AAF: *ch = 0x2AB0; break; - case 0x2AB0: *ch = 0x2AAF; break; - case 0x2AB3: *ch = 0x2AB4; break; - case 0x2AB4: *ch = 0x2AB3; break; - case 0x2ABB: *ch = 0x2ABC; break; - case 0x2ABC: *ch = 0x2ABB; break; - case 0x2ABD: *ch = 0x2ABE; break; - case 0x2ABE: *ch = 0x2ABD; break; - case 0x2ABF: *ch = 0x2AC0; break; - case 0x2AC0: *ch = 0x2ABF; break; - case 0x2AC1: *ch = 0x2AC2; break; - case 0x2AC2: *ch = 0x2AC1; break; - case 0x2AC3: *ch = 0x2AC4; break; - case 0x2AC4: *ch = 0x2AC3; break; - case 0x2AC5: *ch = 0x2AC6; break; - case 0x2AC6: *ch = 0x2AC5; break; - case 0x2ACD: *ch = 0x2ACE; break; - case 0x2ACE: *ch = 0x2ACD; break; - case 0x2ACF: *ch = 0x2AD0; break; - case 0x2AD0: *ch = 0x2ACF; break; - case 0x2AD1: *ch = 0x2AD2; break; - case 0x2AD2: *ch = 0x2AD1; break; - case 0x2AD3: *ch = 0x2AD4; break; - case 0x2AD4: *ch = 0x2AD3; break; - case 0x2AD5: *ch = 0x2AD6; break; - case 0x2AD6: *ch = 0x2AD5; break; - case 0x2ADE: *ch = 0x22A6; break; - case 0x2AE3: *ch = 0x22A9; break; - case 0x2AE4: *ch = 0x22A8; break; - case 0x2AE5: *ch = 0x22AB; break; - case 0x2AEC: *ch = 0x2AED; break; - case 0x2AED: *ch = 0x2AEC; break; - case 0x2AF7: *ch = 0x2AF8; break; - case 0x2AF8: *ch = 0x2AF7; break; - case 0x2AF9: *ch = 0x2AFA; break; - case 0x2AFA: *ch = 0x2AF9; break; - } + switch (*ch) { + case 0x2A2B: *ch = 0x2A2C; break; + case 0x2A2C: *ch = 0x2A2B; break; + case 0x2A2D: *ch = 0x2A2C; break; + case 0x2A2E: *ch = 0x2A2D; break; + case 0x2A34: *ch = 0x2A35; break; + case 0x2A35: *ch = 0x2A34; break; + case 0x2A3C: *ch = 0x2A3D; break; + case 0x2A3D: *ch = 0x2A3C; break; + case 0x2A64: *ch = 0x2A65; break; + case 0x2A65: *ch = 0x2A64; break; + case 0x2A79: *ch = 0x2A7A; break; + case 0x2A7A: *ch = 0x2A79; break; + case 0x2A7D: *ch = 0x2A7E; break; + case 0x2A7E: *ch = 0x2A7D; break; + case 0x2A7F: *ch = 0x2A80; break; + case 0x2A80: *ch = 0x2A7F; break; + case 0x2A81: *ch = 0x2A82; break; + case 0x2A82: *ch = 0x2A81; break; + case 0x2A83: *ch = 0x2A84; break; + case 0x2A84: *ch = 0x2A83; break; + case 0x2A8B: *ch = 0x2A8C; break; + case 0x2A8C: *ch = 0x2A8B; break; + case 0x2A91: *ch = 0x2A92; break; + case 0x2A92: *ch = 0x2A91; break; + case 0x2A93: *ch = 0x2A94; break; + case 0x2A94: *ch = 0x2A93; break; + case 0x2A95: *ch = 0x2A96; break; + case 0x2A96: *ch = 0x2A95; break; + case 0x2A97: *ch = 0x2A98; break; + case 0x2A98: *ch = 0x2A97; break; + case 0x2A99: *ch = 0x2A9A; break; + case 0x2A9A: *ch = 0x2A99; break; + case 0x2A9B: *ch = 0x2A9C; break; + case 0x2A9C: *ch = 0x2A9B; break; + case 0x2AA1: *ch = 0x2AA2; break; + case 0x2AA2: *ch = 0x2AA1; break; + case 0x2AA6: *ch = 0x2AA7; break; + case 0x2AA7: *ch = 0x2AA6; break; + case 0x2AA8: *ch = 0x2AA9; break; + case 0x2AA9: *ch = 0x2AA8; break; + case 0x2AAA: *ch = 0x2AAB; break; + case 0x2AAB: *ch = 0x2AAA; break; + case 0x2AAC: *ch = 0x2AAD; break; + case 0x2AAD: *ch = 0x2AAC; break; + case 0x2AAF: *ch = 0x2AB0; break; + case 0x2AB0: *ch = 0x2AAF; break; + case 0x2AB3: *ch = 0x2AB4; break; + case 0x2AB4: *ch = 0x2AB3; break; + case 0x2ABB: *ch = 0x2ABC; break; + case 0x2ABC: *ch = 0x2ABB; break; + case 0x2ABD: *ch = 0x2ABE; break; + case 0x2ABE: *ch = 0x2ABD; break; + case 0x2ABF: *ch = 0x2AC0; break; + case 0x2AC0: *ch = 0x2ABF; break; + case 0x2AC1: *ch = 0x2AC2; break; + case 0x2AC2: *ch = 0x2AC1; break; + case 0x2AC3: *ch = 0x2AC4; break; + case 0x2AC4: *ch = 0x2AC3; break; + case 0x2AC5: *ch = 0x2AC6; break; + case 0x2AC6: *ch = 0x2AC5; break; + case 0x2ACD: *ch = 0x2ACE; break; + case 0x2ACE: *ch = 0x2ACD; break; + case 0x2ACF: *ch = 0x2AD0; break; + case 0x2AD0: *ch = 0x2ACF; break; + case 0x2AD1: *ch = 0x2AD2; break; + case 0x2AD2: *ch = 0x2AD1; break; + case 0x2AD3: *ch = 0x2AD4; break; + case 0x2AD4: *ch = 0x2AD3; break; + case 0x2AD5: *ch = 0x2AD6; break; + case 0x2AD6: *ch = 0x2AD5; break; + case 0x2ADE: *ch = 0x22A6; break; + case 0x2AE3: *ch = 0x22A9; break; + case 0x2AE4: *ch = 0x22A8; break; + case 0x2AE5: *ch = 0x22AB; break; + case 0x2AEC: *ch = 0x2AED; break; + case 0x2AED: *ch = 0x2AEC; break; + case 0x2AF7: *ch = 0x2AF8; break; + case 0x2AF8: *ch = 0x2AF7; break; + case 0x2AF9: *ch = 0x2AFA; break; + case 0x2AFA: *ch = 0x2AF9; break; + } } else if ((*ch & 0xFF00) == 0x3000) { - switch (*ch) { - case 0x3008: *ch = 0x3009; break; - case 0x3009: *ch = 0x3008; break; - case 0x300A: *ch = 0x300B; break; - case 0x300B: *ch = 0x300A; break; - case 0x300C: *ch = 0x300D; break; - case 0x300D: *ch = 0x300C; break; - case 0x300E: *ch = 0x300F; break; - case 0x300F: *ch = 0x300E; break; - case 0x3010: *ch = 0x3011; break; - case 0x3011: *ch = 0x3010; break; - case 0x3014: *ch = 0x3015; break; - case 0x3015: *ch = 0x3014; break; - case 0x3016: *ch = 0x3017; break; - case 0x3017: *ch = 0x3016; break; - case 0x3018: *ch = 0x3019; break; - case 0x3019: *ch = 0x3018; break; - case 0x301A: *ch = 0x301B; break; - case 0x301B: *ch = 0x301A; break; - } + switch (*ch) { + case 0x3008: *ch = 0x3009; break; + case 0x3009: *ch = 0x3008; break; + case 0x300A: *ch = 0x300B; break; + case 0x300B: *ch = 0x300A; break; + case 0x300C: *ch = 0x300D; break; + case 0x300D: *ch = 0x300C; break; + case 0x300E: *ch = 0x300F; break; + case 0x300F: *ch = 0x300E; break; + case 0x3010: *ch = 0x3011; break; + case 0x3011: *ch = 0x3010; break; + case 0x3014: *ch = 0x3015; break; + case 0x3015: *ch = 0x3014; break; + case 0x3016: *ch = 0x3017; break; + case 0x3017: *ch = 0x3016; break; + case 0x3018: *ch = 0x3019; break; + case 0x3019: *ch = 0x3018; break; + case 0x301A: *ch = 0x301B; break; + case 0x301B: *ch = 0x301A; break; + } } else if ((*ch & 0xFF00) == 0xFF00) { - switch (*ch) { - case 0xFF08: *ch = 0xFF09; break; - case 0xFF09: *ch = 0xFF08; break; - case 0xFF1C: *ch = 0xFF1E; break; - case 0xFF1E: *ch = 0xFF1C; break; - case 0xFF3B: *ch = 0xFF3D; break; - case 0xFF3D: *ch = 0xFF3B; break; - case 0xFF5B: *ch = 0xFF5D; break; - case 0xFF5D: *ch = 0xFF5B; break; - case 0xFF5F: *ch = 0xFF60; break; - case 0xFF60: *ch = 0xFF5F; break; - case 0xFF62: *ch = 0xFF63; break; - case 0xFF63: *ch = 0xFF62; break; - } + switch (*ch) { + case 0xFF08: *ch = 0xFF09; break; + case 0xFF09: *ch = 0xFF08; break; + case 0xFF1C: *ch = 0xFF1E; break; + case 0xFF1E: *ch = 0xFF1C; break; + case 0xFF3B: *ch = 0xFF3D; break; + case 0xFF3D: *ch = 0xFF3B; break; + case 0xFF5B: *ch = 0xFF5D; break; + case 0xFF5D: *ch = 0xFF5B; break; + case 0xFF5F: *ch = 0xFF60; break; + case 0xFF60: *ch = 0xFF5F; break; + case 0xFF62: *ch = 0xFF63; break; + case 0xFF63: *ch = 0xFF62; break; + } } } @@ -1990,34 +1990,34 @@ int main(int argc, char **argv) { static const struct { int type; char *name; } typetoname[] = { #define TYPETONAME(X) { X , #X } - TYPETONAME(L), - TYPETONAME(LRE), - TYPETONAME(LRO), - TYPETONAME(R), - TYPETONAME(AL), - TYPETONAME(RLE), - TYPETONAME(RLO), - TYPETONAME(PDF), - TYPETONAME(EN), - TYPETONAME(ES), - TYPETONAME(ET), - TYPETONAME(AN), - TYPETONAME(CS), - TYPETONAME(NSM), - TYPETONAME(BN), - TYPETONAME(B), - TYPETONAME(S), - TYPETONAME(WS), - TYPETONAME(ON), + TYPETONAME(L), + TYPETONAME(LRE), + TYPETONAME(LRO), + TYPETONAME(R), + TYPETONAME(AL), + TYPETONAME(RLE), + TYPETONAME(RLO), + TYPETONAME(PDF), + TYPETONAME(EN), + TYPETONAME(ES), + TYPETONAME(ET), + TYPETONAME(AN), + TYPETONAME(CS), + TYPETONAME(NSM), + TYPETONAME(BN), + TYPETONAME(B), + TYPETONAME(S), + TYPETONAME(WS), + TYPETONAME(ON), #undef TYPETONAME }; int i; for (i = 1; i < argc; i++) { - unsigned long chr = strtoul(argv[i], NULL, 0); - int type = getType(chr); - assert(typetoname[type].type == type); - printf("U+%04x: %s\n", (unsigned)chr, typetoname[type].name); + unsigned long chr = strtoul(argv[i], NULL, 0); + int type = getType(chr); + assert(typetoname[type].type == type); + printf("U+%04x: %s\n", (unsigned)chr, typetoname[type].name); } return 0; diff --git a/misc.c b/misc.c index b2fc7719..0e52f7ae 100644 --- a/misc.c +++ b/misc.c @@ -85,11 +85,11 @@ void free_prompts(prompts_t *p) { size_t i; for (i=0; i < p->n_prompts; i++) { - prompt_t *pr = p->prompts[i]; - smemclr(pr->result, pr->resultsize); /* burn the evidence */ - sfree(pr->result); - sfree(pr->prompt); - sfree(pr); + prompt_t *pr = p->prompts[i]; + smemclr(pr->result, pr->resultsize); /* burn the evidence */ + sfree(pr->result); + sfree(pr->prompt); + sfree(pr); } sfree(p->prompts); sfree(p->name); @@ -104,17 +104,17 @@ void free_prompts(prompts_t *p) bool conf_launchable(Conf *conf) { if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) - return conf_get_str(conf, CONF_serline)[0] != 0; + return conf_get_str(conf, CONF_serline)[0] != 0; else - return conf_get_str(conf, CONF_host)[0] != 0; + return conf_get_str(conf, CONF_host)[0] != 0; } char const *conf_dest(Conf *conf) { if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL) - return conf_get_str(conf, CONF_serline); + return conf_get_str(conf, CONF_serline); else - return conf_get_str(conf, CONF_host); + return conf_get_str(conf, CONF_host); } /* diff --git a/misc.h b/misc.h index 465110a0..6991d8e8 100644 --- a/misc.h +++ b/misc.h @@ -9,8 +9,8 @@ #include "puttymem.h" #include "marshal.h" -#include /* for FILE * */ -#include /* for va_list */ +#include /* for FILE * */ +#include /* for va_list */ #include /* for abort */ #include /* for struct tm */ #include /* for INT_MAX/MIN */ diff --git a/mkfiles.pl b/mkfiles.pl index 0b378f66..00112a4d 100755 --- a/mkfiles.pl +++ b/mkfiles.pl @@ -67,9 +67,9 @@ while () { # If we're gathering help text, keep doing so. if (defined $divert) { if ((defined $_[0]) && $_[0] eq "!end") { - $divert = undef; + $divert = undef; } else { - ${$divert} .= "$_\n"; + ${$divert} .= "$_\n"; } next; } @@ -99,13 +99,13 @@ while () { if ($_[0] eq "!forceobj") { $forceobj{$_[1]} = 1; next; } if ($_[0] eq "!begin") { if ($_[1] =~ /^>(.*)/) { - $divert = \$auxfiles{$1}; + $divert = \$auxfiles{$1}; } elsif (&mfval($_[1])) { $sect = $_[2] ? $_[2] : "end"; - $divert = \($makefile_extra{$_[1]}->{$sect}); + $divert = \($makefile_extra{$_[1]}->{$sect}); } else { - $dummy = ''; - $divert = \$dummy; + $dummy = ''; + $divert = \$dummy; } next; } @@ -268,7 +268,7 @@ sub mfval($) { # Returns true if the argument is a known makefile type. Otherwise, # prints a warning and returns false; if (grep { $type eq $_ } - ("vc","vcproj","cygwin","lcc","devcppproj","gtk","unix", + ("vc","vcproj","cygwin","lcc","devcppproj","gtk","unix", "am","osx","vstudio10","vstudio12","clangcl")) { return 1; } @@ -290,13 +290,13 @@ sub dirpfx { my $i; while (($i = index $path, $sep) >= 0 || - ($j = index $path, "/") >= 0) { + ($j = index $path, "/") >= 0) { if ($i >= 0 and ($j < 0 or $i < $j)) { - $path = substr $path, ($i + length $sep); - } else { - $path = substr $path, ($j + 1); - } - $ret .= "..$sep"; + $path = substr $path, ($i + length $sep); + } else { + $path = substr $path, ($j + 1); + } + $ret .= "..$sep"; } return $ret; } @@ -560,13 +560,13 @@ if (defined $makefiles{'clangcl'}) { print &splitline("all:" . join "", map { " \$(BUILDDIR)$_.exe" } &progrealnames("G:C")); print "\n\n"; foreach $p (&prognames("G:C")) { - ($prog, $type) = split ",", $p; - $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", undef); - print &splitline("\$(BUILDDIR)$prog.exe: " . $objstr), "\n"; + ($prog, $type) = split ",", $p; + $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", undef); + print &splitline("\$(BUILDDIR)$prog.exe: " . $objstr), "\n"; - $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", "X.lib"); - $subsys = ($type eq "G") ? "windows" : "console"; - print &splitline("\t\$(LD) \$(LFLAGS) \$(XLFLAGS) ". + $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", "X.lib"); + $subsys = ($type eq "G") ? "windows" : "console"; + print &splitline("\t\$(LD) \$(LFLAGS) \$(XLFLAGS) ". "/out:\$(BUILDDIR)$prog.exe ". "/lldmap:\$(BUILDDIR)$prog.map ". "/subsystem:$subsys\$(SUBSYSVER) ". @@ -590,7 +590,7 @@ if (defined $makefiles{'clangcl'}) { sprintf("%s: %s", $rcpp, join " ", @incdeps)) ."\n" . "\t\$(RCPREPROC) \$(RCPPFLAGS) /Fi\$\@ \$<\n\n"; $rcdeps[0] = $rcpp; - } else { + } else { $rule = "\$(CC) /Fo\$(BUILDDIR) \$(COMPAT) \$(CFLAGS) \$(XFLAGS) /c \$<"; } print &splitline(sprintf("%s: %s", $d->{obj}, @@ -634,8 +634,8 @@ if (defined $makefiles{'cygwin'}) { "\n". &splitline("CFLAGS = -Wall -O2 -std=gnu99 -Wvla -D_WINDOWS". " -DWIN32S_COMPAT -D_NO_OLDNAMES -D__USE_MINGW_ANSI_STDIO=1 " . - (join " ", map {"-I$dirpfx$_"} @srcdirs)) . - "\n". + (join " ", map {"-I$dirpfx$_"} @srcdirs)) . + "\n". "LDFLAGS = -s\n". &splitline("RCFLAGS = \$(RCINC) --define WIN32=1 --define _WIN32=1 ". "--define WINVER=0x0400 ".(join " ", map {"-I$dirpfx$_"} @srcdirs))."\n". @@ -664,9 +664,9 @@ if (defined $makefiles{'cygwin'}) { join " ", @{$d->{deps}})), "\n"; } if ($d->{obj} =~ /\.res\.o$/) { - print "\t\$(RC) \$(RCFL) \$(RCFLAGS) ".$d->{deps}->[0]." -o ".$d->{obj}."\n\n"; + print "\t\$(RC) \$(RCFL) \$(RCFLAGS) ".$d->{deps}->[0]." -o ".$d->{obj}."\n\n"; } else { - print "\t\$(CC) \$(COMPAT) \$(CFLAGS) \$(XFLAGS) -c ".$d->{deps}->[0]."\n\n"; + print "\t\$(CC) \$(COMPAT) \$(CFLAGS) \$(XFLAGS) -c ".$d->{deps}->[0]."\n\n"; } } print "\n"; @@ -709,35 +709,35 @@ if (defined $makefiles{'vc'}) { print &splitline("all:" . join "", map { " \$(BUILDDIR)$_.exe" } &progrealnames("G:C")); print "\n\n"; foreach $p (&prognames("G:C")) { - ($prog, $type) = split ",", $p; - $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", undef); - print &splitline("\$(BUILDDIR)$prog.exe: " . $objstr), "\n"; + ($prog, $type) = split ",", $p; + $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", undef); + print &splitline("\$(BUILDDIR)$prog.exe: " . $objstr), "\n"; - $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", "X.lib"); - $subsys = ($type eq "G") ? "windows" : "console"; + $objstr = &objects($p, "\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", "X.lib"); + $subsys = ($type eq "G") ? "windows" : "console"; $inlinefilename = "link_$prog"; print "\ttype <<$inlinefilename\n"; - @objlist = split " ", $objstr; - @objlines = (""); - foreach $i (@objlist) { - if (length($objlines[$#objlines] . " $i") > 72) { - push @objlines, ""; - } - $objlines[$#objlines] .= " $i"; - } - for ($i=0; $i<=$#objlines; $i++) { - print "$objlines[$i]\n"; - } - print "<<\n"; - print "\tlink \$(LFLAGS) \$(XLFLAGS) -out:\$(BUILDDIR)$prog.exe -map:\$(BUILDDIR)$prog.map -nologo -subsystem:$subsys\$(SUBSYSVER) \@$inlinefilename\n\n"; + @objlist = split " ", $objstr; + @objlines = (""); + foreach $i (@objlist) { + if (length($objlines[$#objlines] . " $i") > 72) { + push @objlines, ""; + } + $objlines[$#objlines] .= " $i"; + } + for ($i=0; $i<=$#objlines; $i++) { + print "$objlines[$i]\n"; + } + print "<<\n"; + print "\tlink \$(LFLAGS) \$(XLFLAGS) -out:\$(BUILDDIR)$prog.exe -map:\$(BUILDDIR)$prog.map -nologo -subsystem:$subsys\$(SUBSYSVER) \@$inlinefilename\n\n"; } foreach $d (&deps("\$(BUILDDIR)X.obj", "\$(BUILDDIR)X.res", $dirpfx, "\\", "vc")) { $extradeps = $forceobj{$d->{obj_orig}} ? ["*.c","*.h","*.rc"] : []; print &splitline(sprintf("%s: %s", $d->{obj}, join " ", @$extradeps, @{$d->{deps}})), "\n"; if ($d->{obj} =~ /.res$/) { - print "\trc /Fo@{[$d->{obj}]} \$(RCFL) -r \$(RCFLAGS) ".$d->{deps}->[0],"\n\n"; - } + print "\trc /Fo@{[$d->{obj}]} \$(RCFL) -r \$(RCFLAGS) ".$d->{deps}->[0],"\n\n"; + } } print "\n"; foreach $real_srcdir ("", @srcdirs) { @@ -814,7 +814,7 @@ if (defined $makefiles{'vcproj'}) { # List projects foreach $progname (@prognames) { ($windows_project, $type) = split ",", $progname; - print "Project: \"$windows_project\"=\".\\$windows_project\\$windows_project.dsp\" - Package Owner=<4>\r\n"; + print "Project: \"$windows_project\"=\".\\$windows_project\\$windows_project.dsp\" - Package Owner=<4>\r\n"; } print "\r\n". @@ -844,200 +844,200 @@ if (defined $makefiles{'vcproj'}) { chdir $orig_dir; sub create_vc_project { - my ($all_object_deps, $progname) = @_; - # Construct program's dependency info - %seen_objects = (); - %lib_files = (); - %source_files = (); - %header_files = (); - %resource_files = (); - @object_files = split " ", &objects($progname, "X.obj", "X.res", "X.lib"); - foreach $object_file (@object_files) { - next if defined $seen_objects{$object_file}; - $seen_objects{$object_file} = 1; - if($object_file =~ /\.lib$/io) { - $lib_files{$object_file} = 1; - next; - } - $object_deps = $all_object_deps{$object_file}; - foreach $object_dep (@$object_deps) { - if($object_dep =~ /\.c$/io) { - $source_files{$object_dep} = 1; - next; - } - if($object_dep =~ /\.h$/io) { - $header_files{$object_dep} = 1; - next; - } - if($object_dep =~ /\.(rc|ico)$/io) { - $resource_files{$object_dep} = 1; - next; - } - } - } - $libs = join " ", sort keys %lib_files; - @source_files = sort keys %source_files; - @header_files = sort keys %header_files; - @resources = sort keys %resource_files; - ($windows_project, $type) = split ",", $progname; - mkdir $windows_project - if(! -d $windows_project); - chdir $windows_project; - $subsys = ($type eq "G") ? "windows" : "console"; - open OUT, ">$windows_project.dsp"; binmode OUT; select OUT; - print - "# Microsoft Developer Studio Project File - Name=\"$windows_project\" - Package Owner=<4>\r\n". - "# Microsoft Developer Studio Generated Build File, Format Version 6.00\r\n". - "# ** DO NOT EDIT **\r\n". - "\r\n". - "# TARGTYPE \"Win32 (x86) Application\" 0x0101\r\n". - "\r\n". - "CFG=$windows_project - Win32 Debug\r\n". - "!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r\n". - "!MESSAGE use the Export Makefile command and run\r\n". - "!MESSAGE \r\n". - "!MESSAGE NMAKE /f \"$windows_project.mak\".\r\n". - "!MESSAGE \r\n". - "!MESSAGE You can specify a configuration when running NMAKE\r\n". - "!MESSAGE by defining the macro CFG on the command line. For example:\r\n". - "!MESSAGE \r\n". - "!MESSAGE NMAKE /f \"$windows_project.mak\" CFG=\"$windows_project - Win32 Debug\"\r\n". - "!MESSAGE \r\n". - "!MESSAGE Possible choices for configuration are:\r\n". - "!MESSAGE \r\n". - "!MESSAGE \"$windows_project - Win32 Release\" (based on \"Win32 (x86) Application\")\r\n". - "!MESSAGE \"$windows_project - Win32 Debug\" (based on \"Win32 (x86) Application\")\r\n". - "!MESSAGE \r\n". - "\r\n". - "# Begin Project\r\n". - "# PROP AllowPerConfigDependencies 0\r\n". - "# PROP Scc_ProjName \"\"\r\n". - "# PROP Scc_LocalPath \"\"\r\n". - "CPP=cl.exe\r\n". - "MTL=midl.exe\r\n". - "RSC=rc.exe\r\n". - "\r\n". - "!IF \"\$(CFG)\" == \"$windows_project - Win32 Release\"\r\n". - "\r\n". - "# PROP BASE Use_MFC 0\r\n". - "# PROP BASE Use_Debug_Libraries 0\r\n". - "# PROP BASE Output_Dir \"Release\"\r\n". - "# PROP BASE Intermediate_Dir \"Release\"\r\n". - "# PROP BASE Target_Dir \"\"\r\n". - "# PROP Use_MFC 0\r\n". - "# PROP Use_Debug_Libraries 0\r\n". - "# PROP Output_Dir \"Release\"\r\n". - "# PROP Intermediate_Dir \"Release\"\r\n". - "# PROP Ignore_Export_Lib 0\r\n". - "# PROP Target_Dir \"\"\r\n". - "# ADD BASE CPP /nologo /W3 /GX /O2 ". - (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . - " /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\r\n". - "# ADD CPP /nologo /W3 /GX /O2 ". - (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . - " /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\r\n". - "# ADD BASE MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n". - "# ADD MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n". - "# ADD BASE RSC /l 0x809 /d \"NDEBUG\"\r\n". - "# ADD RSC /l 0x809 /d \"NDEBUG\"\r\n". - "BSC32=bscmake.exe\r\n". - "# ADD BASE BSC32 /nologo\r\n". - "# ADD BSC32 /nologo\r\n". - "LINK32=link.exe\r\n". - "# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:$subsys /machine:I386\r\n". - "# ADD LINK32 $libs /nologo /subsystem:$subsys /machine:I386\r\n". - "# SUBTRACT LINK32 /pdb:none\r\n". - "\r\n". - "!ELSEIF \"\$(CFG)\" == \"$windows_project - Win32 Debug\"\r\n". - "\r\n". - "# PROP BASE Use_MFC 0\r\n". - "# PROP BASE Use_Debug_Libraries 1\r\n". - "# PROP BASE Output_Dir \"Debug\"\r\n". - "# PROP BASE Intermediate_Dir \"Debug\"\r\n". - "# PROP BASE Target_Dir \"\"\r\n". - "# PROP Use_MFC 0\r\n". - "# PROP Use_Debug_Libraries 1\r\n". - "# PROP Output_Dir \"Debug\"\r\n". - "# PROP Intermediate_Dir \"Debug\"\r\n". - "# PROP Ignore_Export_Lib 0\r\n". - "# PROP Target_Dir \"\"\r\n". - "# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od ". - (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . - " /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\r\n". - "# ADD CPP /nologo /W3 /Gm /GX /ZI /Od ". - (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . - " /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\r\n". - "# ADD BASE MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n". - "# ADD MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n". - "# ADD BASE RSC /l 0x809 /d \"_DEBUG\"\r\n". - "# ADD RSC /l 0x809 /d \"_DEBUG\"\r\n". - "BSC32=bscmake.exe\r\n". - "# ADD BASE BSC32 /nologo\r\n". - "# ADD BSC32 /nologo\r\n". - "LINK32=link.exe\r\n". - "# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:$subsys /debug /machine:I386 /pdbtype:sept\r\n". - "# ADD LINK32 $libs /nologo /subsystem:$subsys /debug /machine:I386 /pdbtype:sept\r\n". - "# SUBTRACT LINK32 /pdb:none\r\n". - "\r\n". - "!ENDIF \r\n". - "\r\n". - "# Begin Target\r\n". - "\r\n". - "# Name \"$windows_project - Win32 Release\"\r\n". - "# Name \"$windows_project - Win32 Debug\"\r\n". - "# Begin Group \"Source Files\"\r\n". - "\r\n". - "# PROP Default_Filter \"cpp;c;cxx;rc;def;r;odl;idl;hpj;bat\"\r\n"; - foreach $source_file (@source_files) { - print - "# Begin Source File\r\n". - "\r\n". - "SOURCE=..\\..\\$source_file\r\n"; - if($source_file =~ /ssh\.c/io) { - # Disable 'Edit and continue' as Visual Studio can't handle the macros - print - "\r\n". - "!IF \"\$(CFG)\" == \"$windows_project - Win32 Release\"\r\n". - "\r\n". - "!ELSEIF \"\$(CFG)\" == \"$windows_project - Win32 Debug\"\r\n". - "\r\n". - "# ADD CPP /Zi\r\n". - "\r\n". - "!ENDIF \r\n". - "\r\n"; - } - print "# End Source File\r\n"; - } - print - "# End Group\r\n". - "# Begin Group \"Header Files\"\r\n". - "\r\n". - "# PROP Default_Filter \"h;hpp;hxx;hm;inl\"\r\n"; - foreach $header_file (@header_files) { - print - "# Begin Source File\r\n". - "\r\n". - "SOURCE=..\\..\\$header_file\r\n". - "# End Source File\r\n"; - } - print - "# End Group\r\n". - "# Begin Group \"Resource Files\"\r\n". - "\r\n". - "# PROP Default_Filter \"ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe\"\r\n"; - foreach $resource_file (@resources) { - print - "# Begin Source File\r\n". - "\r\n". - "SOURCE=..\\..\\$resource_file\r\n". - "# End Source File\r\n"; - } - print - "# End Group\r\n". - "# End Target\r\n". - "# End Project\r\n"; - select STDOUT; close OUT; - chdir ".."; + my ($all_object_deps, $progname) = @_; + # Construct program's dependency info + %seen_objects = (); + %lib_files = (); + %source_files = (); + %header_files = (); + %resource_files = (); + @object_files = split " ", &objects($progname, "X.obj", "X.res", "X.lib"); + foreach $object_file (@object_files) { + next if defined $seen_objects{$object_file}; + $seen_objects{$object_file} = 1; + if($object_file =~ /\.lib$/io) { + $lib_files{$object_file} = 1; + next; + } + $object_deps = $all_object_deps{$object_file}; + foreach $object_dep (@$object_deps) { + if($object_dep =~ /\.c$/io) { + $source_files{$object_dep} = 1; + next; + } + if($object_dep =~ /\.h$/io) { + $header_files{$object_dep} = 1; + next; + } + if($object_dep =~ /\.(rc|ico)$/io) { + $resource_files{$object_dep} = 1; + next; + } + } + } + $libs = join " ", sort keys %lib_files; + @source_files = sort keys %source_files; + @header_files = sort keys %header_files; + @resources = sort keys %resource_files; + ($windows_project, $type) = split ",", $progname; + mkdir $windows_project + if(! -d $windows_project); + chdir $windows_project; + $subsys = ($type eq "G") ? "windows" : "console"; + open OUT, ">$windows_project.dsp"; binmode OUT; select OUT; + print + "# Microsoft Developer Studio Project File - Name=\"$windows_project\" - Package Owner=<4>\r\n". + "# Microsoft Developer Studio Generated Build File, Format Version 6.00\r\n". + "# ** DO NOT EDIT **\r\n". + "\r\n". + "# TARGTYPE \"Win32 (x86) Application\" 0x0101\r\n". + "\r\n". + "CFG=$windows_project - Win32 Debug\r\n". + "!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r\n". + "!MESSAGE use the Export Makefile command and run\r\n". + "!MESSAGE \r\n". + "!MESSAGE NMAKE /f \"$windows_project.mak\".\r\n". + "!MESSAGE \r\n". + "!MESSAGE You can specify a configuration when running NMAKE\r\n". + "!MESSAGE by defining the macro CFG on the command line. For example:\r\n". + "!MESSAGE \r\n". + "!MESSAGE NMAKE /f \"$windows_project.mak\" CFG=\"$windows_project - Win32 Debug\"\r\n". + "!MESSAGE \r\n". + "!MESSAGE Possible choices for configuration are:\r\n". + "!MESSAGE \r\n". + "!MESSAGE \"$windows_project - Win32 Release\" (based on \"Win32 (x86) Application\")\r\n". + "!MESSAGE \"$windows_project - Win32 Debug\" (based on \"Win32 (x86) Application\")\r\n". + "!MESSAGE \r\n". + "\r\n". + "# Begin Project\r\n". + "# PROP AllowPerConfigDependencies 0\r\n". + "# PROP Scc_ProjName \"\"\r\n". + "# PROP Scc_LocalPath \"\"\r\n". + "CPP=cl.exe\r\n". + "MTL=midl.exe\r\n". + "RSC=rc.exe\r\n". + "\r\n". + "!IF \"\$(CFG)\" == \"$windows_project - Win32 Release\"\r\n". + "\r\n". + "# PROP BASE Use_MFC 0\r\n". + "# PROP BASE Use_Debug_Libraries 0\r\n". + "# PROP BASE Output_Dir \"Release\"\r\n". + "# PROP BASE Intermediate_Dir \"Release\"\r\n". + "# PROP BASE Target_Dir \"\"\r\n". + "# PROP Use_MFC 0\r\n". + "# PROP Use_Debug_Libraries 0\r\n". + "# PROP Output_Dir \"Release\"\r\n". + "# PROP Intermediate_Dir \"Release\"\r\n". + "# PROP Ignore_Export_Lib 0\r\n". + "# PROP Target_Dir \"\"\r\n". + "# ADD BASE CPP /nologo /W3 /GX /O2 ". + (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . + " /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\r\n". + "# ADD CPP /nologo /W3 /GX /O2 ". + (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . + " /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /c\r\n". + "# ADD BASE MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n". + "# ADD MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n". + "# ADD BASE RSC /l 0x809 /d \"NDEBUG\"\r\n". + "# ADD RSC /l 0x809 /d \"NDEBUG\"\r\n". + "BSC32=bscmake.exe\r\n". + "# ADD BASE BSC32 /nologo\r\n". + "# ADD BSC32 /nologo\r\n". + "LINK32=link.exe\r\n". + "# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:$subsys /machine:I386\r\n". + "# ADD LINK32 $libs /nologo /subsystem:$subsys /machine:I386\r\n". + "# SUBTRACT LINK32 /pdb:none\r\n". + "\r\n". + "!ELSEIF \"\$(CFG)\" == \"$windows_project - Win32 Debug\"\r\n". + "\r\n". + "# PROP BASE Use_MFC 0\r\n". + "# PROP BASE Use_Debug_Libraries 1\r\n". + "# PROP BASE Output_Dir \"Debug\"\r\n". + "# PROP BASE Intermediate_Dir \"Debug\"\r\n". + "# PROP BASE Target_Dir \"\"\r\n". + "# PROP Use_MFC 0\r\n". + "# PROP Use_Debug_Libraries 1\r\n". + "# PROP Output_Dir \"Debug\"\r\n". + "# PROP Intermediate_Dir \"Debug\"\r\n". + "# PROP Ignore_Export_Lib 0\r\n". + "# PROP Target_Dir \"\"\r\n". + "# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od ". + (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . + " /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\r\n". + "# ADD CPP /nologo /W3 /Gm /GX /ZI /Od ". + (join " ", map {"/I \"..\\..\\$dirpfx$_\""} @srcdirs) . + " /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /YX /FD /GZ /c\r\n". + "# ADD BASE MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n". + "# ADD MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n". + "# ADD BASE RSC /l 0x809 /d \"_DEBUG\"\r\n". + "# ADD RSC /l 0x809 /d \"_DEBUG\"\r\n". + "BSC32=bscmake.exe\r\n". + "# ADD BASE BSC32 /nologo\r\n". + "# ADD BSC32 /nologo\r\n". + "LINK32=link.exe\r\n". + "# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:$subsys /debug /machine:I386 /pdbtype:sept\r\n". + "# ADD LINK32 $libs /nologo /subsystem:$subsys /debug /machine:I386 /pdbtype:sept\r\n". + "# SUBTRACT LINK32 /pdb:none\r\n". + "\r\n". + "!ENDIF \r\n". + "\r\n". + "# Begin Target\r\n". + "\r\n". + "# Name \"$windows_project - Win32 Release\"\r\n". + "# Name \"$windows_project - Win32 Debug\"\r\n". + "# Begin Group \"Source Files\"\r\n". + "\r\n". + "# PROP Default_Filter \"cpp;c;cxx;rc;def;r;odl;idl;hpj;bat\"\r\n"; + foreach $source_file (@source_files) { + print + "# Begin Source File\r\n". + "\r\n". + "SOURCE=..\\..\\$source_file\r\n"; + if($source_file =~ /ssh\.c/io) { + # Disable 'Edit and continue' as Visual Studio can't handle the macros + print + "\r\n". + "!IF \"\$(CFG)\" == \"$windows_project - Win32 Release\"\r\n". + "\r\n". + "!ELSEIF \"\$(CFG)\" == \"$windows_project - Win32 Debug\"\r\n". + "\r\n". + "# ADD CPP /Zi\r\n". + "\r\n". + "!ENDIF \r\n". + "\r\n"; + } + print "# End Source File\r\n"; + } + print + "# End Group\r\n". + "# Begin Group \"Header Files\"\r\n". + "\r\n". + "# PROP Default_Filter \"h;hpp;hxx;hm;inl\"\r\n"; + foreach $header_file (@header_files) { + print + "# Begin Source File\r\n". + "\r\n". + "SOURCE=..\\..\\$header_file\r\n". + "# End Source File\r\n"; + } + print + "# End Group\r\n". + "# Begin Group \"Resource Files\"\r\n". + "\r\n". + "# PROP Default_Filter \"ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe\"\r\n"; + foreach $resource_file (@resources) { + print + "# Begin Source File\r\n". + "\r\n". + "SOURCE=..\\..\\$resource_file\r\n". + "# End Source File\r\n"; + } + print + "# End Group\r\n". + "# End Target\r\n". + "# End Project\r\n"; + select STDOUT; close OUT; + chdir ".."; } } @@ -1080,7 +1080,7 @@ if (defined $makefiles{'vstudio10'} || defined $makefiles{'vstudio12'}) { $projguids{$windows_project} = $guid = &invent_guid("project:$progname"); - + print "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"$windows_project\", \"$windows_project\\$windows_project.vcxproj\", \"{$guid}\"\n" . "EndProject\n"; @@ -1115,7 +1115,7 @@ if (defined $makefiles{'vstudio10'} || defined $makefiles{'vstudio12'}) { ($windows_project, $type) = split ",", $progname; create_vs_project(\%all_object_deps, $windows_project, $type, $projguids{$windows_project}, $toolsver); } - + chdir $orig_dir; } @@ -1426,9 +1426,9 @@ if (defined $makefiles{'gtk'}) { "unexport CFLAGS # work around a weird issue with krb5-config\n". "\n". &splitline("CFLAGS = -O2 -Wall -Werror -std=gnu99 -Wvla -g " . - (join " ", map {"-I$dirpfx$_"} @srcdirs) . - " \$(shell \$(GTK_CONFIG) --cflags)"). - " -D _FILE_OFFSET_BITS=64\n". + (join " ", map {"-I$dirpfx$_"} @srcdirs) . + " \$(shell \$(GTK_CONFIG) --cflags)"). + " -D _FILE_OFFSET_BITS=64\n". "XLDFLAGS = \$(LDFLAGS) \$(shell \$(GTK_CONFIG) --libs)\n". "ULDFLAGS = \$(LDFLAGS)\n". "ifeq (,\$(findstring NO_GSSAPI,\$(COMPAT)))\n". @@ -1507,8 +1507,8 @@ if (defined $makefiles{'unix'}) { "unexport CFLAGS # work around a weird issue with krb5-config\n". "\n". &splitline("CFLAGS = -O2 -Wall -Werror -std=gnu99 -Wvla -g " . - (join " ", map {"-I$dirpfx$_"} @srcdirs)). - " -D _FILE_OFFSET_BITS=64\n". + (join " ", map {"-I$dirpfx$_"} @srcdirs)). + " -D _FILE_OFFSET_BITS=64\n". "ULDFLAGS = \$(LDFLAGS)\n". "INSTALL=install\n". "INSTALL_PROGRAM=\$(INSTALL)\n". @@ -1714,8 +1714,8 @@ if (defined $makefiles{'lcc'}) { join " ", @{$d->{deps}})), "\n"; } if ($d->{obj} =~ /\.obj$/) { - print &splitline("\tlcc -O -p6 \$(COMPAT)". - " \$(CFLAGS) \$(XFLAGS) ".$d->{deps}->[0],69)."\n"; + print &splitline("\tlcc -O -p6 \$(COMPAT)". + " \$(CFLAGS) \$(XFLAGS) ".$d->{deps}->[0],69)."\n"; } else { print &splitline("\tlrc \$(RCFL) -r \$(RCFLAGS) ". $d->{deps}->[0],69)."\n"; @@ -1749,7 +1749,7 @@ if (defined $makefiles{'osx'}) { "CC = \$(TOOLPATH)gcc\n". "\n". &splitline("CFLAGS = -O2 -Wall -Werror -std=gnu99 -Wvla -g " . - (join " ", map {"-I$dirpfx$_"} @srcdirs))."\n". + (join " ", map {"-I$dirpfx$_"} @srcdirs))."\n". "MLDFLAGS = -framework Cocoa\n". "ULDFLAGS =\n". "\n" . @@ -1767,18 +1767,18 @@ if (defined $makefiles{'osx'}) { print "${prog}.app/Contents/MacOS: ${prog}.app/Contents\n\tmkdir -p \$\@\n"; $targets = "${prog}.app/Contents/MacOS/$prog"; if (defined $icon) { - print "${prog}.app/Contents/Resources: ${prog}.app/Contents\n\tmkdir -p \$\@\n"; - print "${prog}.app/Contents/Resources/${prog}.icns: ${prog}.app/Contents/Resources $icon\n\tcp $icon \$\@\n"; - $targets .= " ${prog}.app/Contents/Resources/${prog}.icns"; + print "${prog}.app/Contents/Resources: ${prog}.app/Contents\n\tmkdir -p \$\@\n"; + print "${prog}.app/Contents/Resources/${prog}.icns: ${prog}.app/Contents/Resources $icon\n\tcp $icon \$\@\n"; + $targets .= " ${prog}.app/Contents/Resources/${prog}.icns"; } if (defined $infoplist) { - print "${prog}.app/Contents/Info.plist: ${prog}.app/Contents/Resources $infoplist\n\tcp $infoplist \$\@\n"; - $targets .= " ${prog}.app/Contents/Info.plist"; + print "${prog}.app/Contents/Info.plist: ${prog}.app/Contents/Resources $infoplist\n\tcp $infoplist \$\@\n"; + $targets .= " ${prog}.app/Contents/Info.plist"; } $targets .= " \$(${prog}_extra)"; print &splitline("${prog}: $targets", 69) . "\n\n"; print &splitline("${prog}.app/Contents/MacOS/$prog: ". - "${prog}.app/Contents/MacOS " . $objstr), "\n"; + "${prog}.app/Contents/MacOS " . $objstr), "\n"; $libstr = &objects($p, undef, undef, "-lX"); print &splitline("\t\$(CC) \$(MLDFLAGS) -o \$@ " . $objstr . " $libstr", 69), "\n\n"; @@ -1800,9 +1800,9 @@ if (defined $makefiles{'osx'}) { } $firstdep = $d->{deps}->[0]; if ($firstdep =~ /\.c$/) { - print "\t\$(CC) \$(COMPAT) \$(FWHACK) \$(CFLAGS) \$(XFLAGS) -c \$<\n"; + print "\t\$(CC) \$(COMPAT) \$(FWHACK) \$(CFLAGS) \$(XFLAGS) -c \$<\n"; } elsif ($firstdep =~ /\.m$/) { - print "\t\$(CC) -x objective-c \$(COMPAT) \$(FWHACK) \$(CFLAGS) \$(XFLAGS) -c \$<\n"; + print "\t\$(CC) -x objective-c \$(COMPAT) \$(FWHACK) \$(CFLAGS) \$(XFLAGS) -c \$<\n"; } } print "\n".&def($makefile_extra{'osx'}->{'end'}); diff --git a/mpint.c b/mpint.c index 72ae0ea1..8140fafe 100644 --- a/mpint.c +++ b/mpint.c @@ -1846,7 +1846,7 @@ void mp_divmod_into(mp_int *n, mp_int *d, mp_int *q_out, mp_int *r_out) * * So when we multiply n (the input numerator) by our final * reciprocal approximation r, but actually r differs from R/d by - * up to 2, then it follows that + * up to 2, then it follows that * * n/d - nr/R = n/d - [ n (R/d + e) ] / R * = n/d - [ (n/d) R + n e ] / R diff --git a/mpint_i.h b/mpint_i.h index 7c1140ca..70fdc6e1 100644 --- a/mpint_i.h +++ b/mpint_i.h @@ -228,7 +228,7 @@ (ret) = (BignumInt)ADC_temp; \ (retc) = (BignumCarry)(ADC_temp >> BIGNUM_INT_BITS); \ } while (0) - + #define BignumMUL(rh, rl, a, b) do \ { \ DEFINE_BIGNUMDBLINT; \ @@ -237,7 +237,7 @@ (rh) = (BignumInt)(MUL_temp >> BIGNUM_INT_BITS); \ (rl) = (BignumInt)(MUL_temp); \ } while (0) - + #define BignumMULADD(rh, rl, a, b, addend) do \ { \ DEFINE_BIGNUMDBLINT; \ @@ -247,7 +247,7 @@ (rh) = (BignumInt)(MUL_temp >> BIGNUM_INT_BITS); \ (rl) = (BignumInt)(MUL_temp); \ } while (0) - + #define BignumMULADD2(rh, rl, a, b, addend1, addend2) do \ { \ DEFINE_BIGNUMDBLINT; \ diff --git a/network.h b/network.h index 6bffcec4..355da2b3 100644 --- a/network.h +++ b/network.h @@ -3,7 +3,7 @@ * * The way this works is: a back end can choose to open any number * of sockets - including zero, which might be necessary in some. - * It can register a bunch of callbacks (most notably for when + * It can register a bunch of callbacks (most notably for when * data is received) for each socket, and it can call the networking * abstraction to send data without having to worry about blocking. * The stuff behind the abstraction takes care of selects and @@ -46,18 +46,18 @@ struct Plug { struct PlugVtable { void (*log)(Plug *p, int type, SockAddr *addr, int port, - const char *error_msg, int error_code); + const char *error_msg, int error_code); /* * Passes the client progress reports on the process of setting * up the connection. - * - * - type==0 means we are about to try to connect to address - * `addr' (error_msg and error_code are ignored) - * - type==1 means we have failed to connect to address `addr' - * (error_msg and error_code are supplied). This is not a - * fatal error - we may well have other candidate addresses - * to fall back to. When it _is_ fatal, the closing() - * function will be called. + * + * - type==0 means we are about to try to connect to address + * `addr' (error_msg and error_code are ignored) + * - type==1 means we have failed to connect to address `addr' + * (error_msg and error_code are supplied). This is not a + * fatal error - we may well have other candidate addresses + * to fall back to. When it _is_ fatal, the closing() + * function will be called. * - type==2 means that error_msg contains a line of generic * logging information about setting up the connection. This * will typically be a wodge of standard-error output from a @@ -73,10 +73,10 @@ struct PlugVtable { /* * - 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. */ @@ -117,8 +117,8 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, /* socket functions */ -void sk_init(void); /* called once at program startup */ -void sk_cleanup(void); /* called just before program exit */ +void sk_init(void); /* called once at program startup */ +void sk_cleanup(void); /* called just before program exit */ SockAddr *sk_namelookup(const char *host, char **canonicalname, int address_family); SockAddr *sk_nonamelookup(const char *host); @@ -183,13 +183,13 @@ static inline const char *sk_socket_error(Socket *s) * which all READABLE notifications are ignored, so that data is * not accepted from the peer until the socket is unfrozen. This * exists for two purposes: - * + * * - Port forwarding: when a local listening port receives a * connection, we do not want to receive data from the new * socket until we have somewhere to send it. Hence, we freeze * the socket until its associated SSH channel is ready; then we * unfreeze it and pending data is delivered. - * + * * - Socket buffering: if an SSH channel (or the whole connection) * backs up or presents a zero window, we must freeze the * associated local socket in order to avoid unbounded buffer diff --git a/nocproxy.c b/nocproxy.c index 45e36a35..f93214fa 100644 --- a/nocproxy.c +++ b/nocproxy.c @@ -21,15 +21,15 @@ int proxy_socks5_handlechap (ProxySocket *p) { plug_closing(p->plug, "Proxy error: Trying to handle a SOCKS5 CHAP request" - " in telnet-only build", - PROXY_ERROR_GENERAL, 0); + " in telnet-only build", + PROXY_ERROR_GENERAL, 0); return 1; } int proxy_socks5_selectchap(ProxySocket *p) { plug_closing(p->plug, "Proxy error: Trying to handle a SOCKS5 CHAP request" - " in telnet-only build", - PROXY_ERROR_GENERAL, 0); + " in telnet-only build", + PROXY_ERROR_GENERAL, 0); return 1; } diff --git a/notiming.c b/notiming.c index 5fe44038..3feb5cdf 100644 --- a/notiming.c +++ b/notiming.c @@ -1,6 +1,6 @@ /* * notiming.c: stub version of timing API. - * + * * Used in any tool which needs a subsystem linked against the * timing API but doesn't want to actually provide timing. For * example, key generation tools need the random number generator, diff --git a/nullplug.c b/nullplug.c index cbcd6a63..81376d3e 100644 --- a/nullplug.c +++ b/nullplug.c @@ -13,7 +13,7 @@ static void nullplug_socket_log(Plug *plug, int type, SockAddr *addr, int port, } static void nullplug_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { } diff --git a/pageant.c b/pageant.c index 69a8920c..c5cef934 100644 --- a/pageant.c +++ b/pageant.c @@ -66,18 +66,18 @@ static int cmpkeys_ssh2_asymm(void *av, void *bv) c = 0; for (i = 0; i < ablob->len && i < bblob->len; i++) { unsigned char abyte = ((unsigned char *)ablob->ptr)[i]; - if (abyte < bblob->u[i]) { - c = -1; - break; - } else if (abyte > bblob->u[i]) { - c = +1; - break; - } + if (abyte < bblob->u[i]) { + c = -1; + break; + } else if (abyte > bblob->u[i]) { + c = +1; + break; + } } if (c == 0 && i < ablob->len) - c = +1; /* a is longer */ + c = +1; /* a is longer */ if (c == 0 && i < bblob->len) - c = -1; /* a is longer */ + c = -1; /* a is longer */ strbuf_free(bblob); @@ -111,7 +111,7 @@ void pageant_make_keylist1(BinarySink *bs) put_uint32(bs, count234(rsakeys)); for (i = 0; NULL != (key = index234(rsakeys, i)); i++) { rsa_ssh1_public_blob(bs, key, RSA_SSH1_EXPONENT_FIRST); - put_stringz(bs, key->comment); + put_stringz(bs, key->comment); } } @@ -125,7 +125,7 @@ void pageant_make_keylist2(BinarySink *bs) strbuf *blob = strbuf_new(); ssh_key_public_blob(key->key, BinarySink_UPCAST(blob)); put_stringsb(bs, blob); - put_stringz(bs, key->comment); + put_stringz(bs, key->comment); } } @@ -171,13 +171,13 @@ void pageant_handle_msg(BinarySink *bs, switch (type) { case SSH1_AGENTC_REQUEST_RSA_IDENTITIES: - /* - * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER. - */ - { + /* + * Reply with SSH1_AGENT_RSA_IDENTITIES_ANSWER. + */ + { plog(logctx, logfn, "request: SSH1_AGENTC_REQUEST_RSA_IDENTITIES"); - put_byte(bs, SSH1_AGENT_RSA_IDENTITIES_ANSWER); + put_byte(bs, SSH1_AGENT_RSA_IDENTITIES_ANSWER); pageant_make_keylist1(bs); plog(logctx, logfn, "reply: SSH1_AGENT_RSA_IDENTITIES_ANSWER"); @@ -190,16 +190,16 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } } - } - break; + } + break; case SSH2_AGENTC_REQUEST_IDENTITIES: - /* - * Reply with SSH2_AGENT_IDENTITIES_ANSWER. - */ - { + /* + * Reply with SSH2_AGENT_IDENTITIES_ANSWER. + */ + { plog(logctx, logfn, "request: SSH2_AGENTC_REQUEST_IDENTITIES"); - put_byte(bs, SSH2_AGENT_IDENTITIES_ANSWER); + put_byte(bs, SSH2_AGENT_IDENTITIES_ANSWER); pageant_make_keylist2(bs); plog(logctx, logfn, "reply: SSH2_AGENT_IDENTITIES_ANSWER"); @@ -213,21 +213,21 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } } - } - break; + } + 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. - */ - { - RSAKey reqkey, *key; - mp_int *challenge, *response; + /* + * Reply with either SSH1_AGENT_RSA_RESPONSE or + * SSH_AGENT_FAILURE, depending on whether we have that key + * or not. + */ + { + RSAKey reqkey, *key; + mp_int *challenge, *response; ptrlen session_id; unsigned response_type; - unsigned char response_md5[16]; - int i; + unsigned char response_md5[16]; + int i; plog(logctx, logfn, "request: SSH1_AGENTC_RSA_CHALLENGE"); @@ -237,7 +237,7 @@ void pageant_handle_msg(BinarySink *bs, get_rsa_ssh1_pub(msg, &reqkey, RSA_SSH1_EXPONENT_FIRST); challenge = get_mp_ssh1(msg); session_id = get_data(msg, 16); - response_type = get_uint32(msg); + response_type = get_uint32(msg); if (get_err(msg)) { pageant_failure_msg(bs, "unable to decode request", @@ -261,8 +261,8 @@ void pageant_handle_msg(BinarySink *bs, if ((key = find234(rsakeys, &reqkey, NULL)) == NULL) { pageant_failure_msg(bs, "key not found", logctx, logfn); goto challenge1_cleanup; - } - response = rsa_ssh1_decrypt(challenge, key); + } + response = rsa_ssh1_decrypt(challenge, key); { ssh_hash *h = ssh_hash_new(&ssh_md5); @@ -272,8 +272,8 @@ void pageant_handle_msg(BinarySink *bs, ssh_hash_final(h, response_md5); } - put_byte(bs, SSH1_AGENT_RSA_RESPONSE); - put_data(bs, response_md5, 16); + put_byte(bs, SSH1_AGENT_RSA_RESPONSE); + put_data(bs, response_md5, 16); plog(logctx, logfn, "reply: SSH1_AGENT_RSA_RESPONSE"); @@ -282,16 +282,16 @@ void pageant_handle_msg(BinarySink *bs, mp_free(response); mp_free(challenge); freersakey(&reqkey); - } - break; + } + break; case SSH2_AGENTC_SIGN_REQUEST: - /* - * Reply with either SSH2_AGENT_SIGN_RESPONSE or - * SSH_AGENT_FAILURE, depending on whether we have that key - * or not. - */ - { - ssh2_userkey *key; + /* + * Reply with either SSH2_AGENT_SIGN_RESPONSE or + * SSH_AGENT_FAILURE, depending on whether we have that key + * or not. + */ + { + ssh2_userkey *key; ptrlen keyblob, sigdata; strbuf *signature; uint32_t flags, supported_flags; @@ -326,7 +326,7 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } key = find234(ssh2keys, &keyblob, cmpkeys_ssh2_asymm); - if (!key) { + if (!key) { pageant_failure_msg(bs, "key not found", logctx, logfn); return; } @@ -367,20 +367,20 @@ void pageant_handle_msg(BinarySink *bs, put_stringsb(bs, signature); plog(logctx, logfn, "reply: SSH2_AGENT_SIGN_RESPONSE"); - } - break; + } + 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. - */ - { - RSAKey *key; + /* + * Add to the list and return SSH_AGENT_SUCCESS, or + * SSH_AGENT_FAILURE if the key was malformed. + */ + { + RSAKey *key; plog(logctx, logfn, "request: SSH1_AGENTC_ADD_RSA_IDENTITY"); - key = snew(RSAKey); - memset(key, 0, sizeof(RSAKey)); + key = snew(RSAKey); + memset(key, 0, sizeof(RSAKey)); get_rsa_ssh1_pub(msg, key, RSA_SSH1_MODULUS_FIRST); get_rsa_ssh1_priv(msg, key); @@ -388,11 +388,11 @@ void pageant_handle_msg(BinarySink *bs, /* SSH-1 names p and q the other way round, i.e. we have * the inverse of p mod q and not of q mod p. We swap the * names, because our internal RSA wants iqmp. */ - key->iqmp = get_mp_ssh1(msg); - key->q = get_mp_ssh1(msg); - key->p = get_mp_ssh1(msg); + key->iqmp = get_mp_ssh1(msg); + key->q = get_mp_ssh1(msg); + key->p = get_mp_ssh1(msg); - key->comment = mkstr(get_string(msg)); + key->comment = mkstr(get_string(msg)); if (get_err(msg)) { pageant_failure_msg(bs, "unable to decode request", @@ -402,7 +402,7 @@ void pageant_handle_msg(BinarySink *bs, if (!rsa_verify(key)) { pageant_failure_msg(bs, "key is invalid", logctx, logfn); - goto add1_cleanup; + goto add1_cleanup; } if (logfn) { @@ -411,30 +411,30 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } - if (add234(rsakeys, key) == key) { - keylist_update(); - put_byte(bs, SSH_AGENT_SUCCESS); + if (add234(rsakeys, key) == key) { + keylist_update(); + put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); key = NULL; /* don't free it in cleanup */ - } else { + } else { pageant_failure_msg(bs, "key already present", logctx, logfn); - } + } add1_cleanup: if (key) { - freersakey(key); - sfree(key); + freersakey(key); + sfree(key); } - } - break; + } + break; case SSH2_AGENTC_ADD_IDENTITY: - /* - * Add to the list and return SSH_AGENT_SUCCESS, or - * SSH_AGENT_FAILURE if the key was malformed. - */ - { - ssh2_userkey *key = NULL; + /* + * Add to the list and return SSH_AGENT_SUCCESS, or + * SSH_AGENT_FAILURE if the key was malformed. + */ + { + ssh2_userkey *key = NULL; ptrlen algpl; const ssh_keyalg *alg; @@ -442,23 +442,23 @@ void pageant_handle_msg(BinarySink *bs, algpl = get_string(msg); - key = snew(ssh2_userkey); + key = snew(ssh2_userkey); key->key = NULL; key->comment = NULL; alg = find_pubkey_alg_len(algpl); - if (!alg) { + if (!alg) { pageant_failure_msg(bs, "algorithm unknown", logctx, logfn); - goto add2_cleanup; - } + goto add2_cleanup; + } key->key = ssh_key_new_priv_openssh(alg, msg); - if (!key->key) { + if (!key->key) { pageant_failure_msg(bs, "key setup failed", logctx, logfn); - goto add2_cleanup; - } + goto add2_cleanup; + } - key->comment = mkstr(get_string(msg)); + key->comment = mkstr(get_string(msg)); if (get_err(msg)) { pageant_failure_msg(bs, "unable to decode request", @@ -473,17 +473,17 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } - if (add234(ssh2keys, key) == key) { - keylist_update(); - put_byte(bs, SSH_AGENT_SUCCESS); + if (add234(ssh2keys, key) == key) { + keylist_update(); + put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); key = NULL; /* don't clean it up */ - } else { + } else { pageant_failure_msg(bs, "key already present", logctx, logfn); - } + } add2_cleanup: if (key) { @@ -491,18 +491,18 @@ void pageant_handle_msg(BinarySink *bs, ssh_key_free(key->key); if (key->comment) sfree(key->comment); - sfree(key); + sfree(key); } - } - break; + } + 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. - */ - { - RSAKey reqkey, *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. + */ + { + RSAKey reqkey, *key; plog(logctx, logfn, "request: SSH1_AGENTC_REMOVE_RSA_IDENTITY"); @@ -524,31 +524,31 @@ void pageant_handle_msg(BinarySink *bs, sfree(fingerprint); } - key = find234(rsakeys, &reqkey, NULL); + key = find234(rsakeys, &reqkey, NULL); freersakey(&reqkey); - if (key) { + if (key) { plog(logctx, logfn, "found with comment: %s", key->comment); - del234(rsakeys, key); - keylist_update(); - freersakey(key); - sfree(key); - put_byte(bs, SSH_AGENT_SUCCESS); + del234(rsakeys, key); + keylist_update(); + freersakey(key); + sfree(key); + put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); - } else { + } else { pageant_failure_msg(bs, "key not found", logctx, logfn); } - } - break; + } + 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. - */ - { - 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. + */ + { + ssh2_userkey *key; ptrlen blob; plog(logctx, logfn, "request: SSH2_AGENTC_REMOVE_IDENTITY"); @@ -568,7 +568,7 @@ void pageant_handle_msg(BinarySink *bs, } key = find234(ssh2keys, &blob, cmpkeys_ssh2_asymm); - if (!key) { + if (!key) { pageant_failure_msg(bs, "key not found", logctx, logfn); return; } @@ -583,56 +583,56 @@ void pageant_handle_msg(BinarySink *bs, put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); - } - break; + } + break; case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES: - /* - * Remove all SSH-1 keys. Always returns success. - */ - { - RSAKey *rkey; + /* + * Remove all SSH-1 keys. Always returns success. + */ + { + RSAKey *rkey; plog(logctx, logfn, "request:" " SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES"); - while ((rkey = index234(rsakeys, 0)) != NULL) { - del234(rsakeys, rkey); - freersakey(rkey); - sfree(rkey); - } - keylist_update(); + while ((rkey = index234(rsakeys, 0)) != NULL) { + del234(rsakeys, rkey); + freersakey(rkey); + sfree(rkey); + } + keylist_update(); put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); - } - break; + } + break; case SSH2_AGENTC_REMOVE_ALL_IDENTITIES: - /* - * Remove all SSH-2 keys. Always returns success. - */ - { - ssh2_userkey *skey; + /* + * Remove all SSH-2 keys. Always returns success. + */ + { + ssh2_userkey *skey; plog(logctx, logfn, "request: SSH2_AGENTC_REMOVE_ALL_IDENTITIES"); - while ((skey = index234(ssh2keys, 0)) != NULL) { - del234(ssh2keys, skey); + while ((skey = index234(ssh2keys, 0)) != NULL) { + del234(ssh2keys, skey); ssh_key_free(skey->key); sfree(skey->comment); - sfree(skey); - } - keylist_update(); + sfree(skey); + } + keylist_update(); put_byte(bs, SSH_AGENT_SUCCESS); plog(logctx, logfn, "reply: SSH_AGENT_SUCCESS"); - } - break; + } + break; default: plog(logctx, logfn, "request: unknown message type %d", type); pageant_failure_msg(bs, "unrecognised message", logctx, logfn); - break; + break; } } @@ -729,7 +729,7 @@ struct pageant_conn_state { }; static void pageant_conn_closing(Plug *plug, const char *error_msg, - int error_code, bool calling_back) + int error_code, bool calling_back) { struct pageant_conn_state *pc = container_of( plug, struct pageant_conn_state, plug); @@ -824,7 +824,7 @@ struct pageant_listen_state { }; static void pageant_listen_closing(Plug *plug, const char *error_msg, - int error_code, bool calling_back) + int error_code, bool calling_back) { struct pageant_listen_state *pl = container_of( plug, struct pageant_listen_state, plug); @@ -861,7 +861,7 @@ static int pageant_listen_accepting(Plug *plug, if ((err = sk_socket_error(pc->connsock)) != NULL) { sk_close(pc->connsock); sfree(pc); - return 1; + return 1; } sk_set_frozen(pc->connsock, 0); @@ -933,10 +933,10 @@ void pageant_forget_passphrases(void) return; while (count234(passphrases) > 0) { - char *pp = index234(passphrases, 0); - smemclr(pp, strlen(pp)); - delpos234(passphrases, 0); - sfree(pp); + char *pp = index234(passphrases, 0); + smemclr(pp, strlen(pp)); + delpos234(passphrases, 0); + sfree(pp); } } @@ -946,30 +946,30 @@ void *pageant_get_keylist1(int *length) if (!pageant_local) { strbuf *request; - unsigned char *response; - void *vresponse; - int resplen; + unsigned char *response; + void *vresponse; + int resplen; request = strbuf_new_for_agent_query(); - put_byte(request, SSH1_AGENTC_REQUEST_RSA_IDENTITIES); + put_byte(request, SSH1_AGENTC_REQUEST_RSA_IDENTITIES); agent_query_synchronous(request, &vresponse, &resplen); strbuf_free(request); - response = vresponse; - if (resplen < 5 || response[4] != SSH1_AGENT_RSA_IDENTITIES_ANSWER) { + response = vresponse; + if (resplen < 5 || response[4] != SSH1_AGENT_RSA_IDENTITIES_ANSWER) { sfree(response); - return NULL; + return NULL; } - ret = snewn(resplen-5, unsigned char); - memcpy(ret, response+5, resplen-5); - sfree(response); + ret = snewn(resplen-5, unsigned char); + memcpy(ret, response+5, resplen-5); + sfree(response); - if (length) - *length = resplen-5; + if (length) + *length = resplen-5; } else { strbuf *buf = strbuf_new(); - pageant_make_keylist1(BinarySink_UPCAST(buf)); + pageant_make_keylist1(BinarySink_UPCAST(buf)); *length = buf->len; ret = strbuf_to_str(buf); } @@ -982,30 +982,30 @@ void *pageant_get_keylist2(int *length) if (!pageant_local) { strbuf *request; - unsigned char *response; - void *vresponse; - int resplen; + unsigned char *response; + void *vresponse; + int resplen; request = strbuf_new_for_agent_query(); - put_byte(request, SSH2_AGENTC_REQUEST_IDENTITIES); + put_byte(request, SSH2_AGENTC_REQUEST_IDENTITIES); agent_query_synchronous(request, &vresponse, &resplen); strbuf_free(request); - response = vresponse; - if (resplen < 5 || response[4] != SSH2_AGENT_IDENTITIES_ANSWER) { + response = vresponse; + if (resplen < 5 || response[4] != SSH2_AGENT_IDENTITIES_ANSWER) { sfree(response); - return NULL; + return NULL; } - ret = snewn(resplen-5, unsigned char); - memcpy(ret, response+5, resplen-5); - sfree(response); + ret = snewn(resplen-5, unsigned char); + memcpy(ret, response+5, resplen-5); + sfree(response); - if (length) - *length = resplen-5; + if (length) + *length = resplen-5; } else { strbuf *buf = strbuf_new(); - pageant_make_keylist2(BinarySink_UPCAST(buf)); + pageant_make_keylist2(BinarySink_UPCAST(buf)); *length = buf->len; ret = strbuf_to_str(buf); } @@ -1033,9 +1033,9 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, type = key_type(filename); if (type != SSH_KEYTYPE_SSH1 && type != SSH_KEYTYPE_SSH2) { - *retstr = dupprintf("Couldn't load this key (%s)", + *retstr = dupprintf("Couldn't load this key (%s)", key_type_to_str(type)); - return PAGEANT_ACTION_FAILURE; + return PAGEANT_ACTION_FAILURE; } /* @@ -1043,126 +1043,126 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, * which may or may not be us). */ { - strbuf *blob = strbuf_new(); - unsigned char *keylist, *p; - int i, nkeys, keylistlen; + strbuf *blob = strbuf_new(); + unsigned char *keylist, *p; + int i, nkeys, keylistlen; - if (type == SSH_KEYTYPE_SSH1) { - if (!rsa_ssh1_loadpub(filename, BinarySink_UPCAST(blob), NULL, &error)) { + if (type == SSH_KEYTYPE_SSH1) { + if (!rsa_ssh1_loadpub(filename, BinarySink_UPCAST(blob), NULL, &error)) { *retstr = dupprintf("Couldn't load private key (%s)", error); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - keylist = pageant_get_keylist1(&keylistlen); - } else { - /* For our purposes we want the blob prefixed with its + } + keylist = pageant_get_keylist1(&keylistlen); + } else { + /* For our purposes we want the blob prefixed with its * length, so add a placeholder here to fill in * afterwards */ put_uint32(blob, 0); - if (!ssh2_userkey_loadpub(filename, NULL, BinarySink_UPCAST(blob), + if (!ssh2_userkey_loadpub(filename, NULL, BinarySink_UPCAST(blob), NULL, &error)) { *retstr = dupprintf("Couldn't load private key (%s)", error); strbuf_free(blob); - return PAGEANT_ACTION_FAILURE; - } - PUT_32BIT_MSB_FIRST(blob->s, blob->len - 4); - keylist = pageant_get_keylist2(&keylistlen); - } - if (keylist) { - if (keylistlen < 4) { - *retstr = dupstr("Received broken key list from agent"); + return PAGEANT_ACTION_FAILURE; + } + PUT_32BIT_MSB_FIRST(blob->s, blob->len - 4); + keylist = pageant_get_keylist2(&keylistlen); + } + if (keylist) { + if (keylistlen < 4) { + *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); - return PAGEANT_ACTION_FAILURE; - } - nkeys = toint(GET_32BIT_MSB_FIRST(keylist)); - if (nkeys < 0) { - *retstr = dupstr("Received broken key list from agent"); + return PAGEANT_ACTION_FAILURE; + } + nkeys = toint(GET_32BIT_MSB_FIRST(keylist)); + if (nkeys < 0) { + *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); - return PAGEANT_ACTION_FAILURE; - } - p = keylist + 4; - keylistlen -= 4; + return PAGEANT_ACTION_FAILURE; + } + p = keylist + 4; + keylistlen -= 4; - for (i = 0; i < nkeys; i++) { - if (!memcmp(blob->s, p, blob->len)) { - /* Key is already present; we can now leave. */ - sfree(keylist); - strbuf_free(blob); + for (i = 0; i < nkeys; i++) { + if (!memcmp(blob->s, p, blob->len)) { + /* Key is already present; we can now leave. */ + sfree(keylist); + strbuf_free(blob); return PAGEANT_ACTION_OK; - } - /* Now skip over public blob */ - if (type == SSH_KEYTYPE_SSH1) { - int n = rsa_ssh1_public_blob_len( + } + /* Now skip over public blob */ + if (type == SSH_KEYTYPE_SSH1) { + int n = rsa_ssh1_public_blob_len( make_ptrlen(p, keylistlen)); - if (n < 0) { + if (n < 0) { *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - p += n; - keylistlen -= n; - } else { - int n; - if (keylistlen < 4) { + } + p += n; + keylistlen -= n; + } else { + int n; + if (keylistlen < 4) { *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - n = GET_32BIT_MSB_FIRST(p); + } + n = GET_32BIT_MSB_FIRST(p); p += 4; keylistlen -= 4; - if (n < 0 || n > keylistlen) { + if (n < 0 || n > keylistlen) { *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - p += n; - keylistlen -= n; - } - /* Now skip over comment field */ - { - int n; - if (keylistlen < 4) { + } + p += n; + keylistlen -= n; + } + /* Now skip over comment field */ + { + int n; + if (keylistlen < 4) { *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - n = GET_32BIT_MSB_FIRST(p); + } + n = GET_32BIT_MSB_FIRST(p); p += 4; keylistlen -= 4; - if (n < 0 || n > keylistlen) { + if (n < 0 || n > keylistlen) { *retstr = dupstr("Received broken key list from agent"); sfree(keylist); strbuf_free(blob); return PAGEANT_ACTION_FAILURE; - } - p += n; - keylistlen -= n; - } - } + } + p += n; + keylistlen -= n; + } + } - sfree(keylist); - } + sfree(keylist); + } - strbuf_free(blob); + strbuf_free(blob); } error = NULL; if (type == SSH_KEYTYPE_SSH1) - needs_pass = rsa_ssh1_encrypted(filename, &comment); + needs_pass = rsa_ssh1_encrypted(filename, &comment); else - needs_pass = ssh2_userkey_encrypted(filename, &comment); + needs_pass = ssh2_userkey_encrypted(filename, &comment); attempts = 0; if (type == SSH_KEYTYPE_SSH1) - rkey = snew(RSAKey); + rkey = snew(RSAKey); /* * Loop round repeatedly trying to load the key, until we either @@ -1170,7 +1170,7 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, * passphrases to try. */ while (1) { - if (needs_pass) { + if (needs_pass) { /* * If we've been given a passphrase on input, try using @@ -1191,20 +1191,20 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, sfree(rkey); return PAGEANT_ACTION_NEED_PP; } - } else - this_passphrase = ""; + } else + this_passphrase = ""; - if (type == SSH_KEYTYPE_SSH1) - ret = rsa_ssh1_loadkey(filename, rkey, this_passphrase, &error); - else { - skey = ssh2_load_userkey(filename, this_passphrase, &error); - if (skey == SSH2_WRONG_PASSPHRASE) - ret = -1; - else if (!skey) - ret = 0; - else - ret = 1; - } + if (type == SSH_KEYTYPE_SSH1) + ret = rsa_ssh1_loadkey(filename, rkey, this_passphrase, &error); + else { + skey = ssh2_load_userkey(filename, this_passphrase, &error); + if (skey == SSH2_WRONG_PASSPHRASE) + ret = -1; + else if (!skey) + ret = 0; + else + ret = 1; + } if (ret == 0) { /* @@ -1240,7 +1240,7 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, */ { char *pp_copy = dupstr(this_passphrase); - if (addpos234(passphrases, pp_copy, 0) != pp_copy) { + if (addpos234(passphrases, pp_copy, 0) != pp_copy) { /* No need; it was already there. */ smemclr(pp_copy, strlen(pp_copy)); sfree(pp_copy); @@ -1248,31 +1248,31 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, } if (comment) - sfree(comment); + sfree(comment); if (type == SSH_KEYTYPE_SSH1) { - if (!pageant_local) { + if (!pageant_local) { strbuf *request; - unsigned char *response; - void *vresponse; - int resplen; + unsigned char *response; + void *vresponse; + int resplen; - request = strbuf_new_for_agent_query(); - put_byte(request, SSH1_AGENTC_ADD_RSA_IDENTITY); - put_uint32(request, mp_get_nbits(rkey->modulus)); - put_mp_ssh1(request, rkey->modulus); - put_mp_ssh1(request, rkey->exponent); - put_mp_ssh1(request, rkey->private_exponent); - put_mp_ssh1(request, rkey->iqmp); - put_mp_ssh1(request, rkey->q); - put_mp_ssh1(request, rkey->p); - put_stringz(request, rkey->comment); - agent_query_synchronous(request, &vresponse, &resplen); + request = strbuf_new_for_agent_query(); + put_byte(request, SSH1_AGENTC_ADD_RSA_IDENTITY); + put_uint32(request, mp_get_nbits(rkey->modulus)); + put_mp_ssh1(request, rkey->modulus); + put_mp_ssh1(request, rkey->exponent); + put_mp_ssh1(request, rkey->private_exponent); + put_mp_ssh1(request, rkey->iqmp); + put_mp_ssh1(request, rkey->q); + put_mp_ssh1(request, rkey->p); + put_stringz(request, rkey->comment); + agent_query_synchronous(request, &vresponse, &resplen); strbuf_free(request); - response = vresponse; - if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS) { - *retstr = dupstr("The already running Pageant " + response = vresponse; + if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS) { + *retstr = dupstr("The already running Pageant " "refused to add the key."); freersakey(rkey); sfree(rkey); @@ -1281,31 +1281,31 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, } freersakey(rkey); sfree(rkey); - sfree(response); - } else { - if (!pageant_add_ssh1_key(rkey)) { + sfree(response); + } else { + if (!pageant_add_ssh1_key(rkey)) { freersakey(rkey); - sfree(rkey); /* already present, don't waste RAM */ + sfree(rkey); /* already present, don't waste RAM */ } - } + } } else { - if (!pageant_local) { - strbuf *request; + if (!pageant_local) { + strbuf *request; unsigned char *response; - void *vresponse; - int resplen; + void *vresponse; + int resplen; - request = strbuf_new_for_agent_query(); - put_byte(request, SSH2_AGENTC_ADD_IDENTITY); - put_stringz(request, ssh_key_ssh_id(skey->key)); + request = strbuf_new_for_agent_query(); + put_byte(request, SSH2_AGENTC_ADD_IDENTITY); + put_stringz(request, ssh_key_ssh_id(skey->key)); ssh_key_openssh_blob(skey->key, BinarySink_UPCAST(request)); - put_stringz(request, skey->comment); - agent_query_synchronous(request, &vresponse, &resplen); + put_stringz(request, skey->comment); + agent_query_synchronous(request, &vresponse, &resplen); strbuf_free(request); - response = vresponse; - if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS) { - *retstr = dupstr("The already running Pageant " + response = vresponse; + if (resplen < 5 || response[4] != SSH_AGENT_SUCCESS) { + *retstr = dupstr("The already running Pageant " "refused to add the key."); sfree(response); return PAGEANT_ACTION_FAILURE; @@ -1313,13 +1313,13 @@ int pageant_add_keyfile(Filename *filename, const char *passphrase, ssh_key_free(skey->key); sfree(skey); - sfree(response); - } else { - if (!pageant_add_ssh2_key(skey)) { + sfree(response); + } else { + if (!pageant_add_ssh2_key(skey)) { ssh_key_free(skey->key); - sfree(skey); /* already present, don't waste RAM */ - } - } + sfree(skey); /* already present, don't waste RAM */ + } + } } return PAGEANT_ACTION_OK; } diff --git a/pgssapi.h b/pgssapi.h index 74d9c774..53d8cb61 100644 --- a/pgssapi.h +++ b/pgssapi.h @@ -16,7 +16,7 @@ */ #ifdef STATIC_GSSAPI #include -typedef gss_OID const_gss_OID; /* for our prototypes below */ +typedef gss_OID const_gss_OID; /* for our prototypes below */ #else /* STATIC_GSSAPI */ /******************************************************************************* diff --git a/pinger.c b/pinger.c index ddebc727..7bf9b41b 100644 --- a/pinger.c +++ b/pinger.c @@ -20,8 +20,8 @@ static void pinger_timer(void *ctx, unsigned long now) if (pinger->pending && now == pinger->next) { backend_special(pinger->backend, SS_PING, 0); - pinger->pending = false; - pinger_schedule(pinger); + pinger->pending = false; + pinger_schedule(pinger); } } @@ -30,17 +30,17 @@ static void pinger_schedule(Pinger *pinger) unsigned long next; if (!pinger->interval) { - pinger->pending = false; /* cancel any pending ping */ - return; + pinger->pending = false; /* cancel any pending ping */ + return; } next = schedule_timer(pinger->interval * TICKSPERSEC, - pinger_timer, pinger); + pinger_timer, pinger); if (!pinger->pending || (next - pinger->when_set) < (pinger->next - pinger->when_set)) { - pinger->next = next; + pinger->next = next; pinger->when_set = timing_last_clock(); - pinger->pending = true; + pinger->pending = true; } } @@ -60,8 +60,8 @@ void pinger_reconfig(Pinger *pinger, Conf *oldconf, Conf *newconf) { int newinterval = conf_get_int(newconf, CONF_ping_interval); if (conf_get_int(oldconf, CONF_ping_interval) != newinterval) { - pinger->interval = newinterval; - pinger_schedule(pinger); + pinger->interval = newinterval; + pinger_schedule(pinger); } } diff --git a/portfwd.c b/portfwd.c index 49a8d50a..2fbaa299 100644 --- a/portfwd.c +++ b/portfwd.c @@ -96,13 +96,13 @@ static void free_portlistener_state(struct PortListener *pl) } static void pfd_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { /* we have to dump these since we have no interface to logging.c */ } static void pfl_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { /* we have to dump these since we have no interface to logging.c */ } @@ -110,7 +110,7 @@ static void pfl_log(Plug *plug, int type, SockAddr *addr, int port, static void pfd_close(struct PortForwarding *pf); static void pfd_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { struct PortForwarding *pf = container_of(plug, struct PortForwarding, plug); @@ -143,7 +143,7 @@ static void pfd_closing(Plug *plug, const char *error_msg, int error_code, static void pfl_terminate(struct PortListener *pl); static void pfl_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { struct PortListener *pl = (struct PortListener *) plug; pfl_terminate(pl); @@ -399,16 +399,16 @@ static void pfd_receive(Plug *plug, int urgent, const char *data, size_t len) } } - /* - * We come here when we're ready to make an actual - * connection. - */ + /* + * We come here when we're ready to make an actual + * connection. + */ - /* - * Freeze the socket until the SSH server confirms the - * connection. - */ - sk_set_frozen(pf->s, 1); + /* + * Freeze the socket until the SSH server confirms the + * connection. + */ + sk_set_frozen(pf->s, 1); pf->c = wrap_lportfwd_open(pf->cl, pf->hostname, pf->port, pf->s, &pf->chan); @@ -423,7 +423,7 @@ static void pfd_sent(Plug *plug, size_t bufsize) container_of(plug, struct PortForwarding, plug); if (pf->c) - sshfwd_unthrottle(pf->c, bufsize); + sshfwd_unthrottle(pf->c, bufsize); } static const PlugVtable PortForwarding_plugvt = { @@ -526,22 +526,22 @@ static int pfl_accepting(Plug *p, accept_fn_t constructor, accept_ctx_t ctx) chan = portfwd_raw_new(pl->cl, &plug); s = constructor(ctx, plug); if ((err = sk_socket_error(s)) != NULL) { - portfwd_raw_free(chan); - return 1; + portfwd_raw_free(chan); + return 1; } pf = container_of(chan, struct PortForwarding, chan); if (pl->is_dynamic) { pf->s = s; - pf->socks_state = SOCKS_INITIAL; + pf->socks_state = SOCKS_INITIAL; pf->socksbuf = strbuf_new(); pf->socksbuf_consumed = 0; - pf->port = 0; /* "hostname" buffer is so far empty */ - sk_set_frozen(s, 0); /* we want to receive SOCKS _now_! */ + pf->port = 0; /* "hostname" buffer is so far empty */ + sk_set_frozen(s, 0); /* we want to receive SOCKS _now_! */ } else { - pf->hostname = dupstr(pl->hostname); - pf->port = pl->port; + pf->hostname = dupstr(pl->hostname); + pf->port = pl->port; portfwd_raw_setup( chan, s, wrap_lportfwd_open(pl->cl, pf->hostname, pf->port, s, &pf->chan)); @@ -580,11 +580,11 @@ static char *pfl_listen(const char *desthost, int destport, pl = *pl_ret = new_portlistener_state(); pl->plug.vt = &PortListener_plugvt; if (desthost) { - pl->hostname = dupstr(desthost); - pl->port = destport; - pl->is_dynamic = false; + pl->hostname = dupstr(desthost); + pl->port = destport; + pl->is_dynamic = false; } else - pl->is_dynamic = true; + pl->is_dynamic = true; pl->cl = cl; pl->s = new_listener(srcaddr, port, &pl->plug, @@ -593,9 +593,9 @@ static char *pfl_listen(const char *desthost, int destport, if ((err = sk_socket_error(pl->s)) != NULL) { char *err_ret = dupstr(err); sk_close(pl->s); - free_portlistener_state(pl); + free_portlistener_state(pl); *pl_ret = NULL; - return err_ret; + return err_ret; } return NULL; @@ -609,7 +609,7 @@ static char *pfd_log_close_msg(Channel *chan) static void pfd_close(struct PortForwarding *pf) { if (!pf) - return; + return; sk_close(pf->s); free_portfwd_state(pf); @@ -621,7 +621,7 @@ static void pfd_close(struct PortForwarding *pf) static void pfl_terminate(struct PortListener *pl) { if (!pl) - return; + return; sk_close(pl->s); free_portlistener_state(pl); @@ -669,7 +669,7 @@ static void pfd_open_confirmation(Channel *chan) sk_set_frozen(pf->s, 0); sk_write(pf->s, NULL, 0); if (pf->socksbuf) { - sshfwd_write(pf->c, pf->socksbuf->u + pf->socksbuf_consumed, + sshfwd_write(pf->c, pf->socksbuf->u + pf->socksbuf_consumed, pf->socksbuf->len - pf->socksbuf_consumed); strbuf_free(pf->socksbuf); pf->socksbuf = NULL; diff --git a/proxy.c b/proxy.c index d99a1d12..ebe7be8b 100644 --- a/proxy.c +++ b/proxy.c @@ -15,8 +15,8 @@ #define do_proxy_dns(conf) \ (conf_get_int(conf, CONF_proxy_dns) == FORCE_ON || \ - (conf_get_int(conf, CONF_proxy_dns) == AUTO && \ - conf_get_int(conf, CONF_proxy_type) != PROXY_SOCKS4)) + (conf_get_int(conf, CONF_proxy_dns) == AUTO && \ + conf_get_int(conf, CONF_proxy_type) != PROXY_SOCKS4)) /* * Call this when proxy negotiation is complete, so that this @@ -25,7 +25,7 @@ void proxy_activate (ProxySocket *p) { size_t output_before, output_after; - + p->state = PROXY_STATE_ACTIVE; /* we want to ignore new receive events until we have sent @@ -35,22 +35,22 @@ void proxy_activate (ProxySocket *p) /* how many bytes of output have we buffered? */ output_before = bufchain_size(&p->pending_oob_output_data) + - bufchain_size(&p->pending_output_data); + bufchain_size(&p->pending_output_data); /* and keep track of how many bytes do not get sent. */ output_after = 0; - + /* send buffered OOB writes */ while (bufchain_size(&p->pending_oob_output_data) > 0) { ptrlen data = bufchain_prefix(&p->pending_oob_output_data); - output_after += sk_write_oob(p->sub_socket, data.ptr, data.len); - bufchain_consume(&p->pending_oob_output_data, data.len); + output_after += sk_write_oob(p->sub_socket, data.ptr, data.len); + bufchain_consume(&p->pending_oob_output_data, data.len); } /* send buffered normal writes */ while (bufchain_size(&p->pending_output_data) > 0) { - ptrlen data = bufchain_prefix(&p->pending_output_data); - output_after += sk_write(p->sub_socket, data.ptr, data.len); - bufchain_consume(&p->pending_output_data, data.len); + ptrlen data = bufchain_prefix(&p->pending_output_data); + output_after += sk_write(p->sub_socket, data.ptr, data.len); + bufchain_consume(&p->pending_output_data, data.len); } /* if we managed to send any data, let the higher levels know. */ @@ -65,7 +65,7 @@ void proxy_activate (ProxySocket *p) * unfreezing the actual underlying socket. */ if (!p->freeze) - sk_set_frozen(&p->sock, 0); + sk_set_frozen(&p->sock, 0); } /* basic proxy socket functions */ @@ -75,7 +75,7 @@ static Plug *sk_proxy_plug (Socket *s, Plug *p) ProxySocket *ps = container_of(s, ProxySocket, sock); Plug *ret = ps->plug; if (p) - ps->plug = p; + ps->plug = p; return ret; } @@ -93,8 +93,8 @@ static size_t sk_proxy_write (Socket *s, const void *data, size_t len) ProxySocket *ps = container_of(s, ProxySocket, sock); if (ps->state != PROXY_STATE_ACTIVE) { - bufchain_add(&ps->pending_output_data, data, len); - return bufchain_size(&ps->pending_output_data); + bufchain_add(&ps->pending_output_data, data, len); + return bufchain_size(&ps->pending_output_data); } return sk_write(ps->sub_socket, data, len); } @@ -104,10 +104,10 @@ static size_t sk_proxy_write_oob (Socket *s, const void *data, size_t len) ProxySocket *ps = container_of(s, ProxySocket, sock); if (ps->state != PROXY_STATE_ACTIVE) { - bufchain_clear(&ps->pending_output_data); - bufchain_clear(&ps->pending_oob_output_data); - bufchain_add(&ps->pending_oob_output_data, data, len); - return len; + bufchain_clear(&ps->pending_output_data); + bufchain_clear(&ps->pending_oob_output_data); + bufchain_add(&ps->pending_oob_output_data, data, len); + return len; } return sk_write_oob(ps->sub_socket, data, len); } @@ -118,7 +118,7 @@ static void sk_proxy_write_eof (Socket *s) if (ps->state != PROXY_STATE_ACTIVE) { ps->pending_eof = true; - return; + return; } sk_write_eof(ps->sub_socket); } @@ -128,35 +128,35 @@ static void sk_proxy_set_frozen (Socket *s, bool is_frozen) ProxySocket *ps = container_of(s, ProxySocket, sock); if (ps->state != PROXY_STATE_ACTIVE) { - ps->freeze = is_frozen; - return; + ps->freeze = is_frozen; + return; } - + /* handle any remaining buffered recv data first */ if (bufchain_size(&ps->pending_input_data) > 0) { - ps->freeze = is_frozen; + ps->freeze = is_frozen; - /* loop while we still have buffered data, and while we are - * unfrozen. the plug_receive call in the loop could result - * in a call back into this function refreezing the socket, - * so we have to check each time. - */ + /* loop while we still have buffered data, and while we are + * unfrozen. the plug_receive call in the loop could result + * in a call back into this function refreezing the socket, + * so we have to check each time. + */ while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) { - char databuf[512]; - ptrlen data = bufchain_prefix(&ps->pending_input_data); - if (data.len > lenof(databuf)) - data.len = lenof(databuf); - memcpy(databuf, data.ptr, data.len); - bufchain_consume(&ps->pending_input_data, data.len); - plug_receive(ps->plug, 0, databuf, data.len); - } + char databuf[512]; + ptrlen data = bufchain_prefix(&ps->pending_input_data); + if (data.len > lenof(databuf)) + data.len = lenof(databuf); + memcpy(databuf, data.ptr, data.len); + bufchain_consume(&ps->pending_input_data, data.len); + plug_receive(ps->plug, 0, databuf, data.len); + } - /* if we're still frozen, we'll have to wait for another - * call from the backend to finish unbuffering the data. - */ - if (ps->freeze) return; + /* if we're still frozen, we'll have to wait for another + * call from the backend to finish unbuffering the data. + */ + if (ps->freeze) return; } - + sk_set_frozen(ps->sub_socket, is_frozen); } @@ -164,7 +164,7 @@ static const char * sk_proxy_socket_error (Socket *s) { ProxySocket *ps = container_of(s, ProxySocket, sock); if (ps->error != NULL || ps->sub_socket == NULL) { - return ps->error; + return ps->error; } return sk_socket_error(ps->sub_socket); } @@ -172,7 +172,7 @@ static const char * sk_proxy_socket_error (Socket *s) /* basic proxy plug functions */ static void plug_proxy_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { ProxySocket *ps = container_of(plug, ProxySocket, plugimpl); @@ -180,15 +180,15 @@ static void plug_proxy_log(Plug *plug, int type, SockAddr *addr, int port, } static void plug_proxy_closing (Plug *p, const char *error_msg, - int error_code, bool calling_back) + int error_code, bool calling_back) { ProxySocket *ps = container_of(p, ProxySocket, plugimpl); if (ps->state != PROXY_STATE_ACTIVE) { - ps->closing_error_msg = error_msg; - ps->closing_error_code = error_code; - ps->closing_calling_back = calling_back; - ps->negotiate(ps, PROXY_CHANGE_CLOSING); + ps->closing_error_msg = error_msg; + ps->closing_error_code = error_code; + ps->closing_calling_back = calling_back; + ps->negotiate(ps, PROXY_CHANGE_CLOSING); } else { plug_closing(ps->plug, error_msg, error_code, calling_back); } @@ -200,15 +200,15 @@ static void plug_proxy_receive( ProxySocket *ps = container_of(p, ProxySocket, plugimpl); if (ps->state != PROXY_STATE_ACTIVE) { - /* we will lose the urgentness of this data, but since most, - * if not all, of this data will be consumed by the negotiation - * process, hopefully it won't affect the protocol above us - */ - bufchain_add(&ps->pending_input_data, data, len); - ps->receive_urgent = (urgent != 0); - ps->receive_data = data; - ps->receive_len = len; - ps->negotiate(ps, PROXY_CHANGE_RECEIVE); + /* we will lose the urgentness of this data, but since most, + * if not all, of this data will be consumed by the negotiation + * process, hopefully it won't affect the protocol above us + */ + bufchain_add(&ps->pending_input_data, data, len); + ps->receive_urgent = (urgent != 0); + ps->receive_data = data; + ps->receive_len = len; + ps->negotiate(ps, PROXY_CHANGE_RECEIVE); } else { plug_receive(ps->plug, urgent, data, len); } @@ -219,8 +219,8 @@ static void plug_proxy_sent (Plug *p, size_t bufsize) ProxySocket *ps = container_of(p, ProxySocket, plugimpl); if (ps->state != PROXY_STATE_ACTIVE) { - ps->negotiate(ps, PROXY_CHANGE_SENT); - return; + ps->negotiate(ps, PROXY_CHANGE_SENT); + return; } plug_sent(ps->plug, bufsize); } @@ -231,9 +231,9 @@ static int plug_proxy_accepting(Plug *p, ProxySocket *ps = container_of(p, ProxySocket, plugimpl); if (ps->state != PROXY_STATE_ACTIVE) { - ps->accepting_constructor = constructor; - ps->accepting_ctx = ctx; - return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING); + ps->accepting_constructor = constructor; + ps->accepting_ctx = ctx; + return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING); } return plug_accepting(ps->plug, constructor, ctx); } @@ -264,16 +264,16 @@ static bool proxy_for_destination(SockAddr *addr, const char *hostname, * representations of `localhost'. */ if (!conf_get_bool(conf, CONF_even_proxy_localhost) && - (sk_hostname_is_local(hostname) || - (addr && sk_address_is_local(addr)))) - return false; /* do not proxy */ + (sk_hostname_is_local(hostname) || + (addr && sk_address_is_local(addr)))) + return false; /* do not proxy */ /* we want a string representation of the IP address for comparisons */ if (addr) { - sk_getaddr(addr, hostip, 64); - hostip_len = strlen(hostip); + sk_getaddr(addr, hostip, 64); + hostip_len = strlen(hostip); } else - hostip_len = 0; /* placate gcc; shouldn't be required */ + hostip_len = 0; /* placate gcc; shouldn't be required */ hostname_len = strlen(hostname); @@ -284,55 +284,55 @@ static bool proxy_for_destination(SockAddr *addr, const char *hostname, */ while (exclude_list[s]) { - while (exclude_list[s] && - (isspace((unsigned char)exclude_list[s]) || - exclude_list[s] == ',')) s++; + while (exclude_list[s] && + (isspace((unsigned char)exclude_list[s]) || + exclude_list[s] == ',')) s++; - if (!exclude_list[s]) break; + if (!exclude_list[s]) break; - e = s; + e = s; - while (exclude_list[e] && - (isalnum((unsigned char)exclude_list[e]) || - exclude_list[e] == '-' || - exclude_list[e] == '.' || - exclude_list[e] == '*')) e++; + while (exclude_list[e] && + (isalnum((unsigned char)exclude_list[e]) || + exclude_list[e] == '-' || + exclude_list[e] == '.' || + exclude_list[e] == '*')) e++; - if (exclude_list[s] == '*') { - /* wildcard at beginning of entry */ + if (exclude_list[s] == '*') { + /* wildcard at beginning of entry */ - if ((addr && strnicmp(hostip + hostip_len - (e - s - 1), - exclude_list + s + 1, e - s - 1) == 0) || - strnicmp(hostname + hostname_len - (e - s - 1), + if ((addr && strnicmp(hostip + hostip_len - (e - s - 1), + exclude_list + s + 1, e - s - 1) == 0) || + strnicmp(hostname + hostname_len - (e - s - 1), exclude_list + s + 1, e - s - 1) == 0) { /* IP/hostname range excluded. do not use proxy. */ return false; } - } else if (exclude_list[e-1] == '*') { - /* wildcard at end of entry */ + } else if (exclude_list[e-1] == '*') { + /* wildcard at end of entry */ - if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) || + if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) || strnicmp(hostname, exclude_list + s, e - s - 1) == 0) { /* IP/hostname range excluded. do not use proxy. */ return false; } - } else { - /* no wildcard at either end, so let's try an absolute - * match (ie. a specific IP) - */ + } else { + /* no wildcard at either end, so let's try an absolute + * match (ie. a specific IP) + */ - if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0) - return false; /* IP/hostname excluded. do not use proxy. */ - if (strnicmp(hostname, exclude_list + s, e - s) == 0) - return false; /* IP/hostname excluded. do not use proxy. */ - } + if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0) + return false; /* IP/hostname excluded. do not use proxy. */ + if (strnicmp(hostname, exclude_list + s, e - s) == 0) + return false; /* IP/hostname excluded. do not use proxy. */ + } - s = e; + s = e; - /* Make sure we really have reached the next comma or end-of-string */ - while (exclude_list[s] && - !isspace((unsigned char)exclude_list[s]) && - exclude_list[s] != ',') s++; + /* Make sure we really have reached the next comma or end-of-string */ + while (exclude_list[s] && + !isspace((unsigned char)exclude_list[s]) && + exclude_list[s] != ',') s++; } /* no matches in the exclude list, so use the proxy */ @@ -353,15 +353,15 @@ SockAddr *name_lookup(const char *host, int port, char **canonicalname, const char *reason) { if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE && - do_proxy_dns(conf) && - proxy_for_destination(NULL, host, port, conf)) { + do_proxy_dns(conf) && + proxy_for_destination(NULL, host, port, conf)) { if (logctx) logeventf(logctx, "Leaving host lookup to proxy of \"%s\"" " (for %s)", host, reason); - *canonicalname = dupstr(host); - return sk_nonamelookup(host); + *canonicalname = dupstr(host); + return sk_nonamelookup(host); } else { if (logctx) logevent_and_free( @@ -396,58 +396,58 @@ Socket *new_connection(SockAddr *addr, const char *hostname, Plug *plug, Conf *conf) { if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE && - proxy_for_destination(addr, hostname, port, conf)) + proxy_for_destination(addr, hostname, port, conf)) { - ProxySocket *ret; - SockAddr *proxy_addr; - char *proxy_canonical_name; + ProxySocket *ret; + SockAddr *proxy_addr; + char *proxy_canonical_name; const char *proxy_type; - Socket *sret; - int type; + Socket *sret; + int type; - if ((sret = platform_new_connection(addr, hostname, port, privport, - oobinline, nodelay, keepalive, - plug, conf)) != - NULL) - return sret; + if ((sret = platform_new_connection(addr, hostname, port, privport, + oobinline, nodelay, keepalive, + plug, conf)) != + NULL) + return sret; - ret = snew(ProxySocket); - ret->sock.vt = &ProxySocket_sockvt; - ret->plugimpl.vt = &ProxySocket_plugvt; - ret->conf = conf_copy(conf); - ret->plug = plug; - ret->remote_addr = addr; /* will need to be freed on close */ - ret->remote_port = port; + ret = snew(ProxySocket); + ret->sock.vt = &ProxySocket_sockvt; + ret->plugimpl.vt = &ProxySocket_plugvt; + ret->conf = conf_copy(conf); + ret->plug = plug; + ret->remote_addr = addr; /* will need to be freed on close */ + ret->remote_port = port; - ret->error = NULL; - ret->pending_eof = false; - ret->freeze = false; + ret->error = NULL; + ret->pending_eof = false; + ret->freeze = false; - bufchain_init(&ret->pending_input_data); - bufchain_init(&ret->pending_output_data); - bufchain_init(&ret->pending_oob_output_data); + bufchain_init(&ret->pending_input_data); + bufchain_init(&ret->pending_output_data); + bufchain_init(&ret->pending_oob_output_data); - ret->sub_socket = NULL; - ret->state = PROXY_STATE_NEW; - ret->negotiate = NULL; + ret->sub_socket = NULL; + ret->state = PROXY_STATE_NEW; + ret->negotiate = NULL; - type = conf_get_int(conf, CONF_proxy_type); - if (type == PROXY_HTTP) { - ret->negotiate = proxy_http_negotiate; + type = conf_get_int(conf, CONF_proxy_type); + if (type == PROXY_HTTP) { + ret->negotiate = proxy_http_negotiate; proxy_type = "HTTP"; - } else if (type == PROXY_SOCKS4) { + } else if (type == PROXY_SOCKS4) { ret->negotiate = proxy_socks4_negotiate; proxy_type = "SOCKS 4"; - } else if (type == PROXY_SOCKS5) { + } else if (type == PROXY_SOCKS5) { ret->negotiate = proxy_socks5_negotiate; proxy_type = "SOCKS 5"; - } else if (type == PROXY_TELNET) { - ret->negotiate = proxy_telnet_negotiate; + } else if (type == PROXY_TELNET) { + ret->negotiate = proxy_telnet_negotiate; proxy_type = "Telnet"; - } else { - ret->error = "Proxy error: Unknown proxy method"; - return &ret->sock; - } + } else { + ret->error = "Proxy error: Unknown proxy method"; + return &ret->sock; + } { char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect" @@ -467,16 +467,16 @@ Socket *new_connection(SockAddr *addr, const char *hostname, sfree(logmsg); } - /* look-up proxy */ - proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host), - &proxy_canonical_name, - conf_get_int(conf, CONF_addressfamily)); - if (sk_addr_error(proxy_addr) != NULL) { - ret->error = "Proxy error: Unable to resolve proxy host name"; + /* look-up proxy */ + proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host), + &proxy_canonical_name, + conf_get_int(conf, CONF_addressfamily)); + if (sk_addr_error(proxy_addr) != NULL) { + ret->error = "Proxy error: Unable to resolve proxy host name"; sk_addr_free(proxy_addr); - return &ret->sock; - } - sfree(proxy_canonical_name); + return &ret->sock; + } + sfree(proxy_canonical_name); { char addrbuf[256], *logmsg; @@ -488,21 +488,21 @@ Socket *new_connection(SockAddr *addr, const char *hostname, sfree(logmsg); } - /* create the actual socket we will be using, - * connected to our proxy server and port. - */ - ret->sub_socket = sk_new(proxy_addr, - conf_get_int(conf, CONF_proxy_port), - privport, oobinline, - nodelay, keepalive, &ret->plugimpl); - if (sk_socket_error(ret->sub_socket) != NULL) - return &ret->sock; + /* create the actual socket we will be using, + * connected to our proxy server and port. + */ + ret->sub_socket = sk_new(proxy_addr, + conf_get_int(conf, CONF_proxy_port), + privport, oobinline, + nodelay, keepalive, &ret->plugimpl); + if (sk_socket_error(ret->sub_socket) != NULL) + return &ret->sock; - /* start the proxy negotiation process... */ - sk_set_frozen(ret->sub_socket, 0); - ret->negotiate(ret, PROXY_CHANGE_NEW); + /* start the proxy negotiation process... */ + sk_set_frozen(ret->sub_socket, 0); + ret->negotiate(ret, PROXY_CHANGE_NEW); - return &ret->sock; + return &ret->sock; } /* no proxy, so just return the direct socket */ @@ -529,33 +529,33 @@ static bool get_line_end(char *data, size_t len, size_t *out) while (off < len) { - if (data[off] == '\n') { - /* we have a newline */ - off++; + if (data[off] == '\n') { + /* we have a newline */ + off++; - /* is that the only thing on this line? */ + /* is that the only thing on this line? */ if (off <= 2) { *out = off; return true; } - /* if not, then there is the possibility that this header - * continues onto the next line, if it starts with a space - * or a tab. - */ + /* if not, then there is the possibility that this header + * continues onto the next line, if it starts with a space + * or a tab. + */ if (off + 1 < len && data[off+1] != ' ' && data[off+1] != '\t') { *out = off; return true; } - /* the line does continue, so we have to keep going - * until we see an the header's "real" end of line. - */ - off++; - } + /* the line does continue, so we have to keep going + * until we see an the header's "real" end of line. + */ + off++; + } - off++; + off++; } return false; @@ -564,177 +564,177 @@ static bool get_line_end(char *data, size_t len, size_t *out) int proxy_http_negotiate (ProxySocket *p, int change) { if (p->state == PROXY_STATE_NEW) { - /* we are just beginning the proxy negotiate process, - * so we'll send off the initial bits of the request. - * for this proxy method, it's just a simple HTTP - * request - */ - char *buf, dest[512]; - char *username, *password; + /* we are just beginning the proxy negotiate process, + * so we'll send off the initial bits of the request. + * for this proxy method, it's just a simple HTTP + * request + */ + char *buf, dest[512]; + char *username, *password; - sk_getaddr(p->remote_addr, dest, lenof(dest)); + sk_getaddr(p->remote_addr, dest, lenof(dest)); - buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n", - dest, p->remote_port, dest, p->remote_port); - sk_write(p->sub_socket, buf, strlen(buf)); - sfree(buf); + buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n", + dest, p->remote_port, dest, p->remote_port); + sk_write(p->sub_socket, buf, strlen(buf)); + sfree(buf); - username = conf_get_str(p->conf, CONF_proxy_username); - password = conf_get_str(p->conf, CONF_proxy_password); - if (username[0] || password[0]) { - char *buf, *buf2; - int i, j, len; - buf = dupprintf("%s:%s", username, password); - len = strlen(buf); - buf2 = snewn(len * 4 / 3 + 100, char); - sprintf(buf2, "Proxy-Authorization: Basic "); - for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4) - base64_encode_atom((unsigned char *)(buf+i), - (len-i > 3 ? 3 : len-i), buf2+j); - strcpy(buf2+j, "\r\n"); - sk_write(p->sub_socket, buf2, strlen(buf2)); - sfree(buf); - sfree(buf2); - } + username = conf_get_str(p->conf, CONF_proxy_username); + password = conf_get_str(p->conf, CONF_proxy_password); + if (username[0] || password[0]) { + char *buf, *buf2; + int i, j, len; + buf = dupprintf("%s:%s", username, password); + len = strlen(buf); + buf2 = snewn(len * 4 / 3 + 100, char); + sprintf(buf2, "Proxy-Authorization: Basic "); + for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4) + base64_encode_atom((unsigned char *)(buf+i), + (len-i > 3 ? 3 : len-i), buf2+j); + strcpy(buf2+j, "\r\n"); + sk_write(p->sub_socket, buf2, strlen(buf2)); + sfree(buf); + sfree(buf2); + } - sk_write(p->sub_socket, "\r\n", 2); + sk_write(p->sub_socket, "\r\n", 2); - p->state = 1; - return 0; + p->state = 1; + return 0; } if (change == PROXY_CHANGE_CLOSING) { - /* if our proxy negotiation process involves closing and opening - * new sockets, then we would want to intercept this closing - * callback when we were expecting it. if we aren't anticipating - * a socket close, then some error must have occurred. we'll - * just pass those errors up to the backend. - */ - plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, - p->closing_calling_back); - return 0; /* ignored */ + /* if our proxy negotiation process involves closing and opening + * new sockets, then we would want to intercept this closing + * callback when we were expecting it. if we aren't anticipating + * a socket close, then some error must have occurred. we'll + * just pass those errors up to the backend. + */ + plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, + p->closing_calling_back); + return 0; /* ignored */ } if (change == PROXY_CHANGE_SENT) { - /* some (or all) of what we wrote to the proxy was sent. - * we don't do anything new, however, until we receive the - * proxy's response. we might want to set a timer so we can - * timeout the proxy negotiation after a while... - */ - return 0; + /* some (or all) of what we wrote to the proxy was sent. + * we don't do anything new, however, until we receive the + * proxy's response. we might want to set a timer so we can + * timeout the proxy negotiation after a while... + */ + return 0; } if (change == PROXY_CHANGE_ACCEPTING) { - /* we should _never_ see this, as we are using our socket to - * connect to a proxy, not accepting inbound connections. - * what should we do? close the socket with an appropriate - * error message? - */ - return plug_accepting(p->plug, + /* we should _never_ see this, as we are using our socket to + * connect to a proxy, not accepting inbound connections. + * what should we do? close the socket with an appropriate + * error message? + */ + return plug_accepting(p->plug, p->accepting_constructor, p->accepting_ctx); } if (change == PROXY_CHANGE_RECEIVE) { - /* we have received data from the underlying socket, which - * we'll need to parse, process, and respond to appropriately. - */ + /* we have received data from the underlying socket, which + * we'll need to parse, process, and respond to appropriately. + */ - char *data, *datap; - size_t len, eol; + char *data, *datap; + size_t len, eol; - if (p->state == 1) { + if (p->state == 1) { - int min_ver, maj_ver, status; + int min_ver, maj_ver, status; - /* get the status line */ - len = bufchain_size(&p->pending_input_data); - assert(len > 0); /* or we wouldn't be here */ - data = snewn(len+1, char); - bufchain_fetch(&p->pending_input_data, data, len); - /* - * We must NUL-terminate this data, because Windows - * sscanf appears to require a NUL at the end of the - * string because it strlens it _first_. Sigh. - */ - data[len] = '\0'; + /* get the status line */ + len = bufchain_size(&p->pending_input_data); + assert(len > 0); /* or we wouldn't be here */ + data = snewn(len+1, char); + bufchain_fetch(&p->pending_input_data, data, len); + /* + * We must NUL-terminate this data, because Windows + * sscanf appears to require a NUL at the end of the + * string because it strlens it _first_. Sigh. + */ + data[len] = '\0'; if (!get_line_end(data, len, &eol)) { - sfree(data); - return 1; - } + sfree(data); + return 1; + } - status = -1; - /* We can't rely on whether the %n incremented the sscanf return */ - if (sscanf((char *)data, "HTTP/%i.%i %n", - &maj_ver, &min_ver, &status) < 2 || status == -1) { - plug_closing(p->plug, "Proxy error: HTTP response was absent", - PROXY_ERROR_GENERAL, 0); - sfree(data); - return 1; - } + status = -1; + /* We can't rely on whether the %n incremented the sscanf return */ + if (sscanf((char *)data, "HTTP/%i.%i %n", + &maj_ver, &min_ver, &status) < 2 || status == -1) { + plug_closing(p->plug, "Proxy error: HTTP response was absent", + PROXY_ERROR_GENERAL, 0); + sfree(data); + return 1; + } - /* remove the status line from the input buffer. */ - bufchain_consume(&p->pending_input_data, eol); - if (data[status] != '2') { - /* error */ - char *buf; - data[eol] = '\0'; - while (eol > status && - (data[eol-1] == '\r' || data[eol-1] == '\n')) - data[--eol] = '\0'; - buf = dupprintf("Proxy error: %s", data+status); - plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0); - sfree(buf); - sfree(data); - return 1; - } + /* remove the status line from the input buffer. */ + bufchain_consume(&p->pending_input_data, eol); + if (data[status] != '2') { + /* error */ + char *buf; + data[eol] = '\0'; + while (eol > status && + (data[eol-1] == '\r' || data[eol-1] == '\n')) + data[--eol] = '\0'; + buf = dupprintf("Proxy error: %s", data+status); + plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0); + sfree(buf); + sfree(data); + return 1; + } - sfree(data); + sfree(data); - p->state = 2; - } + p->state = 2; + } - if (p->state == 2) { + if (p->state == 2) { - /* get headers. we're done when we get a - * header of length 2, (ie. just "\r\n") - */ + /* get headers. we're done when we get a + * header of length 2, (ie. just "\r\n") + */ - len = bufchain_size(&p->pending_input_data); - assert(len > 0); /* or we wouldn't be here */ - data = snewn(len, char); - datap = data; - bufchain_fetch(&p->pending_input_data, data, len); + len = bufchain_size(&p->pending_input_data); + assert(len > 0); /* or we wouldn't be here */ + data = snewn(len, char); + datap = data; + bufchain_fetch(&p->pending_input_data, data, len); if (!get_line_end(datap, len, &eol)) { - sfree(data); - return 1; - } - while (eol > 2) { - bufchain_consume(&p->pending_input_data, eol); - datap += eol; - len -= eol; + sfree(data); + return 1; + } + while (eol > 2) { + bufchain_consume(&p->pending_input_data, eol); + datap += eol; + len -= eol; if (!get_line_end(datap, len, &eol)) eol = 0; /* terminate the loop */ - } + } - if (eol == 2) { - /* we're done */ - bufchain_consume(&p->pending_input_data, 2); - proxy_activate(p); - /* proxy activate will have dealt with - * whatever is left of the buffer */ - sfree(data); - return 1; - } + if (eol == 2) { + /* we're done */ + bufchain_consume(&p->pending_input_data, 2); + proxy_activate(p); + /* proxy activate will have dealt with + * whatever is left of the buffer */ + sfree(data); + return 1; + } - sfree(data); - return 1; - } + sfree(data); + return 1; + } } plug_closing(p->plug, "Proxy error: unexpected proxy error", - PROXY_ERROR_UNEXPECTED, 0); + PROXY_ERROR_UNEXPECTED, 0); return 1; } @@ -747,15 +747,15 @@ int proxy_socks4_negotiate (ProxySocket *p, int change) { if (p->state == PROXY_CHANGE_NEW) { - /* request format: - * version number (1 byte) = 4 - * command code (1 byte) - * 1 = CONNECT - * 2 = BIND - * dest. port (2 bytes) [network order] - * dest. address (4 bytes) - * user ID (variable length, null terminated string) - */ + /* request format: + * version number (1 byte) = 4 + * command code (1 byte) + * 1 = CONNECT + * 2 = BIND + * dest. port (2 bytes) [network order] + * dest. address (4 bytes) + * user ID (variable length, null terminated string) + */ strbuf *command = strbuf_new(); char hostname[512]; @@ -765,7 +765,7 @@ int proxy_socks4_negotiate (ProxySocket *p, int change) put_byte(command, 1); /* CONNECT command */ put_uint16(command, p->remote_port); - switch (sk_addrtype(p->remote_addr)) { + switch (sk_addrtype(p->remote_addr)) { case ADDRTYPE_IPV4: { char addr[4]; @@ -782,114 +782,114 @@ int proxy_socks4_negotiate (ProxySocket *p, int change) p->error = "Proxy error: SOCKS version 4 does not support IPv6"; strbuf_free(command); return 1; - } + } put_asciz(command, conf_get_str(p->conf, CONF_proxy_username)); if (write_hostname) put_asciz(command, hostname); - sk_write(p->sub_socket, command->s, command->len); - strbuf_free(command); + sk_write(p->sub_socket, command->s, command->len); + strbuf_free(command); - p->state = 1; - return 0; + p->state = 1; + return 0; } if (change == PROXY_CHANGE_CLOSING) { - /* if our proxy negotiation process involves closing and opening - * new sockets, then we would want to intercept this closing - * callback when we were expecting it. if we aren't anticipating - * a socket close, then some error must have occurred. we'll - * just pass those errors up to the backend. - */ - plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, - p->closing_calling_back); - return 0; /* ignored */ + /* if our proxy negotiation process involves closing and opening + * new sockets, then we would want to intercept this closing + * callback when we were expecting it. if we aren't anticipating + * a socket close, then some error must have occurred. we'll + * just pass those errors up to the backend. + */ + plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, + p->closing_calling_back); + return 0; /* ignored */ } if (change == PROXY_CHANGE_SENT) { - /* some (or all) of what we wrote to the proxy was sent. - * we don't do anything new, however, until we receive the - * proxy's response. we might want to set a timer so we can - * timeout the proxy negotiation after a while... - */ - return 0; + /* some (or all) of what we wrote to the proxy was sent. + * we don't do anything new, however, until we receive the + * proxy's response. we might want to set a timer so we can + * timeout the proxy negotiation after a while... + */ + return 0; } if (change == PROXY_CHANGE_ACCEPTING) { - /* we should _never_ see this, as we are using our socket to - * connect to a proxy, not accepting inbound connections. - * what should we do? close the socket with an appropriate - * error message? - */ - return plug_accepting(p->plug, + /* we should _never_ see this, as we are using our socket to + * connect to a proxy, not accepting inbound connections. + * what should we do? close the socket with an appropriate + * error message? + */ + return plug_accepting(p->plug, p->accepting_constructor, p->accepting_ctx); } if (change == PROXY_CHANGE_RECEIVE) { - /* we have received data from the underlying socket, which - * we'll need to parse, process, and respond to appropriately. - */ + /* we have received data from the underlying socket, which + * we'll need to parse, process, and respond to appropriately. + */ - if (p->state == 1) { - /* response format: - * version number (1 byte) = 4 - * reply code (1 byte) - * 90 = request granted - * 91 = request rejected or failed - * 92 = request rejected due to lack of IDENTD on client - * 93 = request rejected due to difference in user ID - * (what we sent vs. what IDENTD said) - * dest. port (2 bytes) - * dest. address (4 bytes) - */ + if (p->state == 1) { + /* response format: + * version number (1 byte) = 4 + * reply code (1 byte) + * 90 = request granted + * 91 = request rejected or failed + * 92 = request rejected due to lack of IDENTD on client + * 93 = request rejected due to difference in user ID + * (what we sent vs. what IDENTD said) + * dest. port (2 bytes) + * dest. address (4 bytes) + */ - char data[8]; + char data[8]; - if (bufchain_size(&p->pending_input_data) < 8) - return 1; /* not got anything yet */ - - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, 8); + if (bufchain_size(&p->pending_input_data) < 8) + return 1; /* not got anything yet */ - if (data[0] != 0) { - plug_closing(p->plug, "Proxy error: SOCKS proxy responded with " - "unexpected reply code version", - PROXY_ERROR_GENERAL, 0); - return 1; - } + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, 8); - if (data[1] != 90) { + if (data[0] != 0) { + plug_closing(p->plug, "Proxy error: SOCKS proxy responded with " + "unexpected reply code version", + PROXY_ERROR_GENERAL, 0); + return 1; + } - switch (data[1]) { - case 92: - plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client", - PROXY_ERROR_GENERAL, 0); - break; - case 93: - plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree", - PROXY_ERROR_GENERAL, 0); - break; - case 91: - default: - plug_closing(p->plug, "Proxy error: Error while communicating with proxy", - PROXY_ERROR_GENERAL, 0); - break; - } + if (data[1] != 90) { - return 1; - } - bufchain_consume(&p->pending_input_data, 8); + switch (data[1]) { + case 92: + plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client", + PROXY_ERROR_GENERAL, 0); + break; + case 93: + plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree", + PROXY_ERROR_GENERAL, 0); + break; + case 91: + default: + plug_closing(p->plug, "Proxy error: Error while communicating with proxy", + PROXY_ERROR_GENERAL, 0); + break; + } - /* we're done */ - proxy_activate(p); - /* proxy activate will have dealt with - * whatever is left of the buffer */ - return 1; - } + return 1; + } + bufchain_consume(&p->pending_input_data, 8); + + /* we're done */ + proxy_activate(p); + /* proxy activate will have dealt with + * whatever is left of the buffer */ + return 1; + } } plug_closing(p->plug, "Proxy error: unexpected proxy error", - PROXY_ERROR_UNEXPECTED, 0); + PROXY_ERROR_UNEXPECTED, 0); return 1; } @@ -898,25 +898,25 @@ int proxy_socks5_negotiate (ProxySocket *p, int change) { if (p->state == PROXY_CHANGE_NEW) { - /* initial command: - * version number (1 byte) = 5 - * number of available authentication methods (1 byte) - * available authentication methods (1 byte * previous value) - * authentication methods: - * 0x00 = no authentication - * 0x01 = GSSAPI - * 0x02 = username/password - * 0x03 = CHAP - */ + /* initial command: + * version number (1 byte) = 5 + * number of available authentication methods (1 byte) + * available authentication methods (1 byte * previous value) + * authentication methods: + * 0x00 = no authentication + * 0x01 = GSSAPI + * 0x02 = username/password + * 0x03 = CHAP + */ - strbuf *command; - char *username, *password; + strbuf *command; + char *username, *password; int method_count_offset, methods_start; command = strbuf_new(); - put_byte(command, 5); /* SOCKS version 5 */ - username = conf_get_str(p->conf, CONF_proxy_username); - password = conf_get_str(p->conf, CONF_proxy_password); + put_byte(command, 5); /* SOCKS version 5 */ + username = conf_get_str(p->conf, CONF_proxy_username); + password = conf_get_str(p->conf, CONF_proxy_password); method_count_offset = command->len; put_byte(command, 0); @@ -924,165 +924,165 @@ int proxy_socks5_negotiate (ProxySocket *p, int change) put_byte(command, 0x00); /* no authentication */ - if (username[0] || password[0]) { - proxy_socks5_offerencryptedauth(BinarySink_UPCAST(command)); + if (username[0] || password[0]) { + proxy_socks5_offerencryptedauth(BinarySink_UPCAST(command)); put_byte(command, 0x02); /* username/password */ - } + } command->u[method_count_offset] = command->len - methods_start; - sk_write(p->sub_socket, command->s, command->len); + sk_write(p->sub_socket, command->s, command->len); strbuf_free(command); - p->state = 1; - return 0; + p->state = 1; + return 0; } if (change == PROXY_CHANGE_CLOSING) { - /* if our proxy negotiation process involves closing and opening - * new sockets, then we would want to intercept this closing - * callback when we were expecting it. if we aren't anticipating - * a socket close, then some error must have occurred. we'll - * just pass those errors up to the backend. - */ + /* if our proxy negotiation process involves closing and opening + * new sockets, then we would want to intercept this closing + * callback when we were expecting it. if we aren't anticipating + * a socket close, then some error must have occurred. we'll + * just pass those errors up to the backend. + */ plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, - p->closing_calling_back); - return 0; /* ignored */ + p->closing_calling_back); + return 0; /* ignored */ } if (change == PROXY_CHANGE_SENT) { - /* some (or all) of what we wrote to the proxy was sent. - * we don't do anything new, however, until we receive the - * proxy's response. we might want to set a timer so we can - * timeout the proxy negotiation after a while... - */ - return 0; + /* some (or all) of what we wrote to the proxy was sent. + * we don't do anything new, however, until we receive the + * proxy's response. we might want to set a timer so we can + * timeout the proxy negotiation after a while... + */ + return 0; } if (change == PROXY_CHANGE_ACCEPTING) { - /* we should _never_ see this, as we are using our socket to - * connect to a proxy, not accepting inbound connections. - * what should we do? close the socket with an appropriate - * error message? - */ - return plug_accepting(p->plug, + /* we should _never_ see this, as we are using our socket to + * connect to a proxy, not accepting inbound connections. + * what should we do? close the socket with an appropriate + * error message? + */ + return plug_accepting(p->plug, p->accepting_constructor, p->accepting_ctx); } if (change == PROXY_CHANGE_RECEIVE) { - /* we have received data from the underlying socket, which - * we'll need to parse, process, and respond to appropriately. - */ + /* we have received data from the underlying socket, which + * we'll need to parse, process, and respond to appropriately. + */ - if (p->state == 1) { + if (p->state == 1) { - /* initial response: - * version number (1 byte) = 5 - * authentication method (1 byte) - * authentication methods: - * 0x00 = no authentication - * 0x01 = GSSAPI - * 0x02 = username/password - * 0x03 = CHAP - * 0xff = no acceptable methods - */ - char data[2]; + /* initial response: + * version number (1 byte) = 5 + * authentication method (1 byte) + * authentication methods: + * 0x00 = no authentication + * 0x01 = GSSAPI + * 0x02 = username/password + * 0x03 = CHAP + * 0xff = no acceptable methods + */ + char data[2]; - if (bufchain_size(&p->pending_input_data) < 2) - return 1; /* not got anything yet */ + if (bufchain_size(&p->pending_input_data) < 2) + return 1; /* not got anything yet */ - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, 2); + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, 2); - if (data[0] != 5) { - plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version", - PROXY_ERROR_GENERAL, 0); - return 1; - } + if (data[0] != 5) { + plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version", + PROXY_ERROR_GENERAL, 0); + return 1; + } - if (data[1] == 0x00) p->state = 2; /* no authentication needed */ - else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */ - else if (data[1] == 0x02) p->state = 5; /* username/password authentication */ - else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */ - else { - plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication", - PROXY_ERROR_GENERAL, 0); - return 1; - } - bufchain_consume(&p->pending_input_data, 2); - } + if (data[1] == 0x00) p->state = 2; /* no authentication needed */ + else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */ + else if (data[1] == 0x02) p->state = 5; /* username/password authentication */ + else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */ + else { + plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication", + PROXY_ERROR_GENERAL, 0); + return 1; + } + bufchain_consume(&p->pending_input_data, 2); + } - if (p->state == 7) { + if (p->state == 7) { - /* password authentication reply format: - * version number (1 bytes) = 1 - * reply code (1 byte) - * 0 = succeeded - * >0 = failed - */ - char data[2]; + /* password authentication reply format: + * version number (1 bytes) = 1 + * reply code (1 byte) + * 0 = succeeded + * >0 = failed + */ + char data[2]; - if (bufchain_size(&p->pending_input_data) < 2) - return 1; /* not got anything yet */ + if (bufchain_size(&p->pending_input_data) < 2) + return 1; /* not got anything yet */ - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, 2); + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, 2); - if (data[0] != 1) { - plug_closing(p->plug, "Proxy error: SOCKS password " - "subnegotiation contained wrong version number", - PROXY_ERROR_GENERAL, 0); - return 1; - } + if (data[0] != 1) { + plug_closing(p->plug, "Proxy error: SOCKS password " + "subnegotiation contained wrong version number", + PROXY_ERROR_GENERAL, 0); + return 1; + } - if (data[1] != 0) { + if (data[1] != 0) { - plug_closing(p->plug, "Proxy error: SOCKS proxy refused" - " password authentication", - PROXY_ERROR_GENERAL, 0); - return 1; - } + plug_closing(p->plug, "Proxy error: SOCKS proxy refused" + " password authentication", + PROXY_ERROR_GENERAL, 0); + return 1; + } - bufchain_consume(&p->pending_input_data, 2); - p->state = 2; /* now proceed as authenticated */ - } + bufchain_consume(&p->pending_input_data, 2); + p->state = 2; /* now proceed as authenticated */ + } - if (p->state == 8) { - int ret; - ret = proxy_socks5_handlechap(p); - if (ret) return ret; - } + if (p->state == 8) { + int ret; + ret = proxy_socks5_handlechap(p); + if (ret) return ret; + } - if (p->state == 2) { + if (p->state == 2) { - /* request format: - * version number (1 byte) = 5 - * command code (1 byte) - * 1 = CONNECT - * 2 = BIND - * 3 = UDP ASSOCIATE - * reserved (1 byte) = 0x00 - * address type (1 byte) - * 1 = IPv4 - * 3 = domainname (first byte has length, no terminating null) - * 4 = IPv6 - * dest. address (variable) - * dest. port (2 bytes) [network order] - */ + /* request format: + * version number (1 byte) = 5 + * command code (1 byte) + * 1 = CONNECT + * 2 = BIND + * 3 = UDP ASSOCIATE + * reserved (1 byte) = 0x00 + * address type (1 byte) + * 1 = IPv4 + * 3 = domainname (first byte has length, no terminating null) + * 4 = IPv6 + * dest. address (variable) + * dest. port (2 bytes) [network order] + */ - strbuf *command = strbuf_new(); - put_byte(command, 5); /* SOCKS version 5 */ - put_byte(command, 1); /* CONNECT command */ - put_byte(command, 0x00); /* reserved byte */ + strbuf *command = strbuf_new(); + put_byte(command, 5); /* SOCKS version 5 */ + put_byte(command, 1); /* CONNECT command */ + put_byte(command, 0x00); /* reserved byte */ - switch (sk_addrtype(p->remote_addr)) { + switch (sk_addrtype(p->remote_addr)) { case ADDRTYPE_IPV4: - put_byte(command, 1); /* IPv4 */ - sk_addrcopy(p->remote_addr, strbuf_append(command, 4)); + put_byte(command, 1); /* IPv4 */ + sk_addrcopy(p->remote_addr, strbuf_append(command, 4)); break; case ADDRTYPE_IPV6: - put_byte(command, 4); /* IPv6 */ - sk_addrcopy(p->remote_addr, strbuf_append(command, 16)); + put_byte(command, 4); /* IPv6 */ + sk_addrcopy(p->remote_addr, strbuf_append(command, 16)); break; case ADDRTYPE_NAME: { @@ -1097,116 +1097,116 @@ int proxy_socks5_negotiate (ProxySocket *p, int change) } } break; - } + } put_uint16(command, p->remote_port); - sk_write(p->sub_socket, command->s, command->len); + sk_write(p->sub_socket, command->s, command->len); strbuf_free(command); - p->state = 3; - return 1; - } + p->state = 3; + return 1; + } - if (p->state == 3) { + if (p->state == 3) { - /* reply format: - * version number (1 bytes) = 5 - * reply code (1 byte) - * 0 = succeeded - * 1 = general SOCKS server failure - * 2 = connection not allowed by ruleset - * 3 = network unreachable - * 4 = host unreachable - * 5 = connection refused - * 6 = TTL expired - * 7 = command not supported - * 8 = address type not supported - * reserved (1 byte) = x00 - * address type (1 byte) - * 1 = IPv4 - * 3 = domainname (first byte has length, no terminating null) - * 4 = IPv6 - * server bound address (variable) - * server bound port (2 bytes) [network order] - */ - char data[5]; - int len; + /* reply format: + * version number (1 bytes) = 5 + * reply code (1 byte) + * 0 = succeeded + * 1 = general SOCKS server failure + * 2 = connection not allowed by ruleset + * 3 = network unreachable + * 4 = host unreachable + * 5 = connection refused + * 6 = TTL expired + * 7 = command not supported + * 8 = address type not supported + * reserved (1 byte) = x00 + * address type (1 byte) + * 1 = IPv4 + * 3 = domainname (first byte has length, no terminating null) + * 4 = IPv6 + * server bound address (variable) + * server bound port (2 bytes) [network order] + */ + char data[5]; + int len; - /* First 5 bytes of packet are enough to tell its length. */ - if (bufchain_size(&p->pending_input_data) < 5) - return 1; /* not got anything yet */ + /* First 5 bytes of packet are enough to tell its length. */ + if (bufchain_size(&p->pending_input_data) < 5) + return 1; /* not got anything yet */ - /* get the response */ - bufchain_fetch(&p->pending_input_data, data, 5); + /* get the response */ + bufchain_fetch(&p->pending_input_data, data, 5); - if (data[0] != 5) { - plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number", - PROXY_ERROR_GENERAL, 0); - return 1; - } + if (data[0] != 5) { + plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number", + PROXY_ERROR_GENERAL, 0); + return 1; + } - if (data[1] != 0) { - char buf[256]; + if (data[1] != 0) { + char buf[256]; - strcpy(buf, "Proxy error: "); + strcpy(buf, "Proxy error: "); - switch (data[1]) { - case 1: strcat(buf, "General SOCKS server failure"); break; - case 2: strcat(buf, "Connection not allowed by ruleset"); break; - case 3: strcat(buf, "Network unreachable"); break; - case 4: strcat(buf, "Host unreachable"); break; - case 5: strcat(buf, "Connection refused"); break; - case 6: strcat(buf, "TTL expired"); break; - case 7: strcat(buf, "Command not supported"); break; - case 8: strcat(buf, "Address type not supported"); break; - default: sprintf(buf+strlen(buf), - "Unrecognised SOCKS error code %d", - data[1]); - break; - } - plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0); + switch (data[1]) { + case 1: strcat(buf, "General SOCKS server failure"); break; + case 2: strcat(buf, "Connection not allowed by ruleset"); break; + case 3: strcat(buf, "Network unreachable"); break; + case 4: strcat(buf, "Host unreachable"); break; + case 5: strcat(buf, "Connection refused"); break; + case 6: strcat(buf, "TTL expired"); break; + case 7: strcat(buf, "Command not supported"); break; + case 8: strcat(buf, "Address type not supported"); break; + default: sprintf(buf+strlen(buf), + "Unrecognised SOCKS error code %d", + data[1]); + break; + } + plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0); - return 1; - } + return 1; + } - /* - * Eat the rest of the reply packet. - */ - len = 6; /* first 4 bytes, last 2 */ - switch (data[3]) { - case 1: len += 4; break; /* IPv4 address */ - case 4: len += 16; break;/* IPv6 address */ - case 3: len += (unsigned char)data[4]; break; /* domain name */ - default: - plug_closing(p->plug, "Proxy error: SOCKS proxy returned " - "unrecognised address format", - PROXY_ERROR_GENERAL, 0); - return 1; - } - if (bufchain_size(&p->pending_input_data) < len) - return 1; /* not got whole reply yet */ - bufchain_consume(&p->pending_input_data, len); + /* + * Eat the rest of the reply packet. + */ + len = 6; /* first 4 bytes, last 2 */ + switch (data[3]) { + case 1: len += 4; break; /* IPv4 address */ + case 4: len += 16; break;/* IPv6 address */ + case 3: len += (unsigned char)data[4]; break; /* domain name */ + default: + plug_closing(p->plug, "Proxy error: SOCKS proxy returned " + "unrecognised address format", + PROXY_ERROR_GENERAL, 0); + return 1; + } + if (bufchain_size(&p->pending_input_data) < len) + return 1; /* not got whole reply yet */ + bufchain_consume(&p->pending_input_data, len); - /* we're done */ - proxy_activate(p); - return 1; - } + /* we're done */ + proxy_activate(p); + return 1; + } - if (p->state == 4) { - /* TODO: Handle GSSAPI authentication */ - plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication", - PROXY_ERROR_GENERAL, 0); - return 1; - } + if (p->state == 4) { + /* TODO: Handle GSSAPI authentication */ + plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication", + PROXY_ERROR_GENERAL, 0); + return 1; + } - if (p->state == 5) { + if (p->state == 5) { const char *username = conf_get_str(p->conf, CONF_proxy_username); const char *password = conf_get_str(p->conf, CONF_proxy_password); - if (username[0] || password[0]) { + if (username[0] || password[0]) { strbuf *auth = strbuf_new_nm(); - put_byte(auth, 1); /* version number of subnegotiation */ + put_byte(auth, 1); /* version number of subnegotiation */ if (!put_pstring(auth, username)) { p->error = "Proxy error: SOCKS 5 authentication cannot " "support usernames longer than 255 chars"; @@ -1219,27 +1219,27 @@ int proxy_socks5_negotiate (ProxySocket *p, int change) strbuf_free(auth); return 1; } - sk_write(p->sub_socket, auth->s, auth->len); + sk_write(p->sub_socket, auth->s, auth->len); strbuf_free(auth); - p->state = 7; - } else - plug_closing(p->plug, "Proxy error: Server chose " - "username/password authentication but we " - "didn't offer it!", - PROXY_ERROR_GENERAL, 0); - return 1; - } + p->state = 7; + } else + plug_closing(p->plug, "Proxy error: Server chose " + "username/password authentication but we " + "didn't offer it!", + PROXY_ERROR_GENERAL, 0); + return 1; + } - if (p->state == 6) { - int ret; - ret = proxy_socks5_selectchap(p); - if (ret) return ret; - } + if (p->state == 6) { + int ret; + ret = proxy_socks5_selectchap(p); + if (ret) return ret; + } } plug_closing(p->plug, "Proxy error: Unexpected proxy error", - PROXY_ERROR_UNEXPECTED, 0); + PROXY_ERROR_UNEXPECTED, 0); return 1; } @@ -1258,163 +1258,163 @@ char *format_telnet_command(SockAddr *addr, int port, Conf *conf) int so = 0, eo = 0; strbuf *buf = strbuf_new(); - /* we need to escape \\, \%, \r, \n, \t, \x??, \0???, + /* we need to escape \\, \%, \r, \n, \t, \x??, \0???, * %%, %host, %port, %user, and %pass */ while (fmt[eo] != 0) { - /* scan forward until we hit end-of-line, - * or an escape character (\ or %) */ - while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\') - eo++; + /* scan forward until we hit end-of-line, + * or an escape character (\ or %) */ + while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\') + eo++; - /* if we hit eol, break out of our escaping loop */ - if (fmt[eo] == 0) break; + /* if we hit eol, break out of our escaping loop */ + if (fmt[eo] == 0) break; - /* if there was any unescaped text before the escape - * character, send that now */ - if (eo != so) + /* if there was any unescaped text before the escape + * character, send that now */ + if (eo != so) put_data(buf, fmt + so, eo - so); - so = eo++; + so = eo++; - /* if the escape character was the last character of - * the line, we'll just stop and send it. */ - if (fmt[eo] == 0) break; + /* if the escape character was the last character of + * the line, we'll just stop and send it. */ + if (fmt[eo] == 0) break; - if (fmt[so] == '\\') { + if (fmt[so] == '\\') { - /* we recognize \\, \%, \r, \n, \t, \x??. - * anything else, we just send unescaped (including the \). - */ + /* we recognize \\, \%, \r, \n, \t, \x??. + * anything else, we just send unescaped (including the \). + */ - switch (fmt[eo]) { + switch (fmt[eo]) { - case '\\': - put_byte(buf, '\\'); - eo++; - break; + case '\\': + put_byte(buf, '\\'); + eo++; + break; - case '%': + case '%': put_byte(buf, '%'); - eo++; - break; + eo++; + break; - case 'r': + case 'r': put_byte(buf, '\r'); - eo++; - break; + eo++; + break; - case 'n': + case 'n': put_byte(buf, '\n'); - eo++; - break; + eo++; + break; - case 't': + case 't': put_byte(buf, '\t'); - eo++; - break; + eo++; + break; - case 'x': - case 'X': - { - /* escaped hexadecimal value (ie. \xff) */ - unsigned char v = 0; - int i = 0; + case 'x': + case 'X': + { + /* escaped hexadecimal value (ie. \xff) */ + unsigned char v = 0; + int i = 0; - for (;;) { - eo++; - if (fmt[eo] >= '0' && fmt[eo] <= '9') - v += fmt[eo] - '0'; - else if (fmt[eo] >= 'a' && fmt[eo] <= 'f') - v += fmt[eo] - 'a' + 10; - else if (fmt[eo] >= 'A' && fmt[eo] <= 'F') - v += fmt[eo] - 'A' + 10; - else { - /* non hex character, so we abort and just - * send the whole thing unescaped (including \x) - */ + for (;;) { + eo++; + if (fmt[eo] >= '0' && fmt[eo] <= '9') + v += fmt[eo] - '0'; + else if (fmt[eo] >= 'a' && fmt[eo] <= 'f') + v += fmt[eo] - 'a' + 10; + else if (fmt[eo] >= 'A' && fmt[eo] <= 'F') + v += fmt[eo] - 'A' + 10; + else { + /* non hex character, so we abort and just + * send the whole thing unescaped (including \x) + */ put_byte(buf, '\\'); - eo = so + 1; - break; - } + eo = so + 1; + break; + } - /* we only extract two hex characters */ - if (i == 1) { + /* we only extract two hex characters */ + if (i == 1) { put_byte(buf, v); - eo++; - break; - } + eo++; + break; + } - i++; - v <<= 4; - } - } - break; + i++; + v <<= 4; + } + } + break; - default: + default: put_data(buf, fmt + so, 2); - eo++; - break; - } - } else { + eo++; + break; + } + } else { - /* % escape. we recognize %%, %host, %port, %user, %pass. - * %proxyhost, %proxyport. Anything else we just send - * unescaped (including the %). - */ + /* % escape. we recognize %%, %host, %port, %user, %pass. + * %proxyhost, %proxyport. Anything else we just send + * unescaped (including the %). + */ - if (fmt[eo] == '%') { + if (fmt[eo] == '%') { put_byte(buf, '%'); - eo++; - } - else if (strnicmp(fmt + eo, "host", 4) == 0) { - char dest[512]; - sk_getaddr(addr, dest, lenof(dest)); - put_data(buf, dest, strlen(dest)); - eo += 4; - } - else if (strnicmp(fmt + eo, "port", 4) == 0) { + eo++; + } + else if (strnicmp(fmt + eo, "host", 4) == 0) { + char dest[512]; + sk_getaddr(addr, dest, lenof(dest)); + put_data(buf, dest, strlen(dest)); + eo += 4; + } + else if (strnicmp(fmt + eo, "port", 4) == 0) { strbuf_catf(buf, "%d", port); - eo += 4; - } - else if (strnicmp(fmt + eo, "user", 4) == 0) { - const char *username = conf_get_str(conf, CONF_proxy_username); - put_data(buf, username, strlen(username)); - eo += 4; - } - else if (strnicmp(fmt + eo, "pass", 4) == 0) { - const char *password = conf_get_str(conf, CONF_proxy_password); - put_data(buf, password, strlen(password)); - eo += 4; - } - else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) { - const char *host = conf_get_str(conf, CONF_proxy_host); - put_data(buf, host, strlen(host)); - eo += 9; - } - else if (strnicmp(fmt + eo, "proxyport", 9) == 0) { - int port = conf_get_int(conf, CONF_proxy_port); + eo += 4; + } + else if (strnicmp(fmt + eo, "user", 4) == 0) { + const char *username = conf_get_str(conf, CONF_proxy_username); + put_data(buf, username, strlen(username)); + eo += 4; + } + else if (strnicmp(fmt + eo, "pass", 4) == 0) { + const char *password = conf_get_str(conf, CONF_proxy_password); + put_data(buf, password, strlen(password)); + eo += 4; + } + else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) { + const char *host = conf_get_str(conf, CONF_proxy_host); + put_data(buf, host, strlen(host)); + eo += 9; + } + else if (strnicmp(fmt + eo, "proxyport", 9) == 0) { + int port = conf_get_int(conf, CONF_proxy_port); strbuf_catf(buf, "%d", port); - eo += 9; - } - else { - /* we don't escape this, so send the % now, and - * don't advance eo, so that we'll consider the - * text immediately following the % as unescaped. - */ + eo += 9; + } + else { + /* we don't escape this, so send the % now, and + * don't advance eo, so that we'll consider the + * text immediately following the % as unescaped. + */ put_byte(buf, '%'); - } - } + } + } - /* resume scanning for additional escapes after this one. */ - so = eo; + /* resume scanning for additional escapes after this one. */ + so = eo; } /* if there is any unescaped text at the end of the line, send it */ if (eo != so) { - put_data(buf, fmt + so, eo - so); + put_data(buf, fmt + so, eo - so); } return strbuf_to_str(buf); @@ -1423,10 +1423,10 @@ char *format_telnet_command(SockAddr *addr, int port, Conf *conf) int proxy_telnet_negotiate (ProxySocket *p, int change) { if (p->state == PROXY_CHANGE_NEW) { - char *formatted_cmd; + char *formatted_cmd; - formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port, - p->conf); + formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port, + p->conf); { /* @@ -1461,57 +1461,57 @@ int proxy_telnet_negotiate (ProxySocket *p, int change) sfree(reescaped); } - sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd)); - sfree(formatted_cmd); + sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd)); + sfree(formatted_cmd); - p->state = 1; - return 0; + p->state = 1; + return 0; } if (change == PROXY_CHANGE_CLOSING) { - /* if our proxy negotiation process involves closing and opening - * new sockets, then we would want to intercept this closing - * callback when we were expecting it. if we aren't anticipating - * a socket close, then some error must have occurred. we'll - * just pass those errors up to the backend. - */ - plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, - p->closing_calling_back); - return 0; /* ignored */ + /* if our proxy negotiation process involves closing and opening + * new sockets, then we would want to intercept this closing + * callback when we were expecting it. if we aren't anticipating + * a socket close, then some error must have occurred. we'll + * just pass those errors up to the backend. + */ + plug_closing(p->plug, p->closing_error_msg, p->closing_error_code, + p->closing_calling_back); + return 0; /* ignored */ } if (change == PROXY_CHANGE_SENT) { - /* some (or all) of what we wrote to the proxy was sent. - * we don't do anything new, however, until we receive the - * proxy's response. we might want to set a timer so we can - * timeout the proxy negotiation after a while... - */ - return 0; + /* some (or all) of what we wrote to the proxy was sent. + * we don't do anything new, however, until we receive the + * proxy's response. we might want to set a timer so we can + * timeout the proxy negotiation after a while... + */ + return 0; } if (change == PROXY_CHANGE_ACCEPTING) { - /* we should _never_ see this, as we are using our socket to - * connect to a proxy, not accepting inbound connections. - * what should we do? close the socket with an appropriate - * error message? - */ - return plug_accepting(p->plug, + /* we should _never_ see this, as we are using our socket to + * connect to a proxy, not accepting inbound connections. + * what should we do? close the socket with an appropriate + * error message? + */ + return plug_accepting(p->plug, p->accepting_constructor, p->accepting_ctx); } if (change == PROXY_CHANGE_RECEIVE) { - /* we have received data from the underlying socket, which - * we'll need to parse, process, and respond to appropriately. - */ + /* we have received data from the underlying socket, which + * we'll need to parse, process, and respond to appropriately. + */ - /* we're done */ - proxy_activate(p); - /* proxy activate will have dealt with - * whatever is left of the buffer */ - return 1; + /* we're done */ + proxy_activate(p); + /* proxy activate will have dealt with + * whatever is left of the buffer */ + return 1; } plug_closing(p->plug, "Proxy error: Unexpected proxy error", - PROXY_ERROR_UNEXPECTED, 0); + PROXY_ERROR_UNEXPECTED, 0); return 1; } diff --git a/proxy.h b/proxy.h index 26a76c4d..f11e1e3d 100644 --- a/proxy.h +++ b/proxy.h @@ -32,10 +32,10 @@ struct ProxySocket { #define PROXY_STATE_ACTIVE 0 int state; /* proxy states greater than 0 are implementation - * dependent, but represent various stages/states - * of the initialization/setup/negotiation with the - * proxy server. - */ + * dependent, but represent various stages/states + * of the initialization/setup/negotiation with the + * proxy server. + */ bool freeze; /* should we freeze the underlying socket when * we are done with the proxy negotiation? this * simply caches the value of sk_set_frozen calls. diff --git a/pscp.c b/pscp.c index f39d2d05..e53f1dee 100644 --- a/pscp.c +++ b/pscp.c @@ -4,7 +4,7 @@ * * This is mainly based on ssh-1.2.26/scp.c by Timo Rinne & Tatu Ylonen. * They, in turn, used stuff from BSD rcp. - * + * * (SGT, 2001-09-10: Joris van Rantwijk assures me that although * this file as originally submitted was inspired by, and * _structurally_ based on, ssh-1.2.26's scp.c, there wasn't any @@ -95,7 +95,7 @@ static void tell_str(FILE *stream, const char *str) unsigned int i; for (i = 0; i < strlen(str); ++i) - tell_char(stream, str[i]); + tell_char(stream, str[i]); } static void abandon_stats(void) @@ -132,7 +132,7 @@ static void tell_user(FILE *stream, const char *fmt, ...) * never-called stub. */ void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len) + void *callback_ctx, void *data, int len) { assert(!"We shouldn't be here"); } @@ -157,7 +157,7 @@ static size_t pscp_output( */ if (is_stderr) { put_data(stderr_bs, data, len); - return 0; + return 0; } bufchain_add(&received_data, data, len); @@ -205,23 +205,23 @@ static void ssh_scp_init(void) errs++; return; } - if (ssh_sftp_loop_iteration() < 0) { + if (ssh_sftp_loop_iteration() < 0) { errs++; - return; /* doom */ + return; /* doom */ } } /* Work out which backend we ended up using. */ if (!ssh_fallback_cmd(backend)) - using_sftp = main_cmd_is_sftp; + using_sftp = main_cmd_is_sftp; else - using_sftp = fallback_cmd_is_sftp; + using_sftp = fallback_cmd_is_sftp; if (verbose) { - if (using_sftp) - tell_user(stderr, "Using SFTP"); - else - tell_user(stderr, "Using SCP1"); + if (using_sftp) + tell_user(stderr, "Using SFTP"); + else + tell_user(stderr, "Using SCP1"); } } @@ -243,10 +243,10 @@ static NORETURN void bump(const char *fmt, ...) errs++; if (backend && backend_connected(backend)) { - char ch; + char ch; backend_special(backend, SS_EOF, 0); sent_eof = true; - ssh_scp_recv(&ch, 1); + ssh_scp_recv(&ch, 1); } cleanup_exit(1); @@ -299,7 +299,7 @@ static void do_cmd(char *host, char *user, char *cmd) LogContext *logctx; if (host == NULL || host[0] == '\0') - bump("Empty host name"); + bump("Empty host name"); /* * Remove a colon suffix. @@ -311,23 +311,23 @@ static void do_cmd(char *host, char *user, char *cmd) * try looking for a session called "host". */ if (!loaded_session) { - /* Try to load settings for `host' into a temporary config */ - Conf *conf2 = conf_new(); - conf_set_str(conf2, CONF_host, ""); - do_defaults(host, conf2); - if (conf_get_str(conf2, CONF_host)[0] != '\0') { - /* Settings present and include hostname */ - /* Re-load data into the real config. */ - do_defaults(host, conf); - } else { - /* Session doesn't exist or mention a hostname. */ - /* Use `host' as a bare hostname. */ - conf_set_str(conf, CONF_host, host); - } + /* Try to load settings for `host' into a temporary config */ + Conf *conf2 = conf_new(); + conf_set_str(conf2, CONF_host, ""); + do_defaults(host, conf2); + if (conf_get_str(conf2, CONF_host)[0] != '\0') { + /* Settings present and include hostname */ + /* Re-load data into the real config. */ + do_defaults(host, conf); + } else { + /* Session doesn't exist or mention a hostname. */ + /* Use `host' as a bare hostname. */ + conf_set_str(conf, CONF_host, host); + } conf_free(conf2); } else { - /* Patch in hostname `host' to session details. */ - conf_set_str(conf, CONF_host, host); + /* Patch in hostname `host' to session details. */ + conf_set_str(conf, CONF_host, host); } /* @@ -348,57 +348,57 @@ static void do_cmd(char *host, char *user, char *cmd) * Muck about with the hostname in various ways. */ { - char *hostbuf = dupstr(conf_get_str(conf, CONF_host)); - char *host = hostbuf; - char *p, *q; + char *hostbuf = dupstr(conf_get_str(conf, CONF_host)); + char *host = hostbuf; + char *p, *q; - /* - * Trim leading whitespace. - */ - host += strspn(host, " \t"); + /* + * Trim leading whitespace. + */ + host += strspn(host, " \t"); - /* - * See if host is of the form user@host, and separate out - * the username if so. - */ - if (host[0] != '\0') { - char *atsign = strrchr(host, '@'); - if (atsign) { - *atsign = '\0'; - conf_set_str(conf, CONF_username, host); - host = atsign + 1; - } - } + /* + * See if host is of the form user@host, and separate out + * the username if so. + */ + if (host[0] != '\0') { + char *atsign = strrchr(host, '@'); + if (atsign) { + *atsign = '\0'; + conf_set_str(conf, CONF_username, host); + host = atsign + 1; + } + } - /* - * Remove any remaining whitespace. - */ - p = hostbuf; - q = host; - while (*q) { - if (*q != ' ' && *q != '\t') - *p++ = *q; - q++; - } - *p = '\0'; + /* + * Remove any remaining whitespace. + */ + p = hostbuf; + q = host; + while (*q) { + if (*q != ' ' && *q != '\t') + *p++ = *q; + q++; + } + *p = '\0'; - conf_set_str(conf, CONF_host, hostbuf); - sfree(hostbuf); + conf_set_str(conf, CONF_host, hostbuf); + sfree(hostbuf); } /* Set username */ if (user != NULL && user[0] != '\0') { - conf_set_str(conf, CONF_username, user); + conf_set_str(conf, CONF_username, user); } else if (conf_get_str(conf, CONF_username)[0] == '\0') { - user = get_username(); - if (!user) - bump("Empty user name"); - else { - if (verbose) - tell_user(stderr, "Guessing user name: %s", user); - conf_set_str(conf, CONF_username, user); - sfree(user); - } + user = get_username(); + if (!user) + bump("Empty user name"); + else { + if (verbose) + tell_user(stderr, "Guessing user name: %s", user); + conf_set_str(conf, CONF_username, user); + sfree(user); + } } /* @@ -410,9 +410,9 @@ static void do_cmd(char *host, char *user, char *cmd) conf_set_bool(conf, CONF_agentfwd, false); conf_set_bool(conf, CONF_ssh_simple, true); { - char *key; - while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL) - conf_del_str_str(conf, CONF_portfwd, key); + char *key; + while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL) + conf_del_str_str(conf, CONF_portfwd, key); } /* @@ -423,34 +423,34 @@ static void do_cmd(char *host, char *user, char *cmd) */ conf_set_str(conf, CONF_remote_cmd2, ""); if (try_sftp) { - /* First choice is SFTP subsystem. */ - main_cmd_is_sftp = true; - conf_set_str(conf, CONF_remote_cmd, "sftp"); - conf_set_bool(conf, CONF_ssh_subsys, true); - if (try_scp) { - /* Fallback is to use the provided scp command. */ - fallback_cmd_is_sftp = false; - conf_set_str(conf, CONF_remote_cmd2, cmd); - conf_set_bool(conf, CONF_ssh_subsys2, false); - } else { - /* Since we're not going to try SCP, we may as well try - * harder to find an SFTP server, since in the current - * implementation we have a spare slot. */ - fallback_cmd_is_sftp = true; - /* see psftp.c for full explanation of this kludge */ - conf_set_str(conf, CONF_remote_cmd2, - "test -x /usr/lib/sftp-server &&" - " exec /usr/lib/sftp-server\n" - "test -x /usr/local/lib/sftp-server &&" - " exec /usr/local/lib/sftp-server\n" - "exec sftp-server"); - conf_set_bool(conf, CONF_ssh_subsys2, false); - } + /* First choice is SFTP subsystem. */ + main_cmd_is_sftp = true; + conf_set_str(conf, CONF_remote_cmd, "sftp"); + conf_set_bool(conf, CONF_ssh_subsys, true); + if (try_scp) { + /* Fallback is to use the provided scp command. */ + fallback_cmd_is_sftp = false; + conf_set_str(conf, CONF_remote_cmd2, cmd); + conf_set_bool(conf, CONF_ssh_subsys2, false); + } else { + /* Since we're not going to try SCP, we may as well try + * harder to find an SFTP server, since in the current + * implementation we have a spare slot. */ + fallback_cmd_is_sftp = true; + /* see psftp.c for full explanation of this kludge */ + conf_set_str(conf, CONF_remote_cmd2, + "test -x /usr/lib/sftp-server &&" + " exec /usr/lib/sftp-server\n" + "test -x /usr/local/lib/sftp-server &&" + " exec /usr/local/lib/sftp-server\n" + "exec sftp-server"); + conf_set_bool(conf, CONF_ssh_subsys2, false); + } } else { - /* Don't try SFTP at all; just try the scp command. */ - main_cmd_is_sftp = false; - conf_set_str(conf, CONF_remote_cmd, cmd); - conf_set_bool(conf, CONF_ssh_subsys, false); + /* Don't try SFTP at all; just try the scp command. */ + main_cmd_is_sftp = false; + conf_set_str(conf, CONF_remote_cmd, cmd); + conf_set_bool(conf, CONF_ssh_subsys, false); } conf_set_bool(conf, CONF_nopty, true); @@ -464,10 +464,10 @@ static void do_cmd(char *host, char *user, char *cmd) &realhost, 0, conf_get_bool(conf, CONF_tcp_keepalives)); if (err != NULL) - bump("ssh_init: %s", err); + bump("ssh_init: %s", err); ssh_scp_init(); if (verbose && realhost != NULL && errs == 0) - tell_user(stderr, "Connected to %s", realhost); + tell_user(stderr, "Connected to %s", realhost); sfree(realhost); } @@ -475,7 +475,7 @@ static void do_cmd(char *host, char *user, char *cmd) * Update statistic information about current file. */ static void print_stats(const char *name, uint64_t size, uint64_t done, - time_t start, time_t now) + time_t start, time_t now) { float ratebs; unsigned long eta; @@ -487,33 +487,33 @@ static void print_stats(const char *name, uint64_t size, uint64_t done, elap = (unsigned long) difftime(now, start); if (now > start) - ratebs = (float)done / elap; + ratebs = (float)done / elap; else - ratebs = (float)done; + ratebs = (float)done; if (ratebs < 1.0) - eta = size - done; + eta = size - done; else eta = (unsigned long)((size - done) / ratebs); etastr = dupprintf("%02ld:%02ld:%02ld", - eta / 3600, (eta % 3600) / 60, eta % 60); + eta / 3600, (eta % 3600) / 60, eta % 60); pct = (int) (100.0 * done / size); { - /* divide by 1024 to provide kB */ - len = printf("\r%-25.25s | %"PRIu64" kB | %5.1f kB/s | " + /* divide by 1024 to provide kB */ + len = printf("\r%-25.25s | %"PRIu64" kB | %5.1f kB/s | " "ETA: %8s | %3d%%", name, done >> 10, ratebs / 1024.0, etastr, pct); - if (len < prev_stats_len) - printf("%*s", prev_stats_len - len, ""); - prev_stats_len = len; + if (len < prev_stats_len) + printf("%*s", prev_stats_len - len, ""); + prev_stats_len = len; - if (done == size) + if (done == size) abandon_stats(); - fflush(stdout); + fflush(stdout); } free(etastr); @@ -530,12 +530,12 @@ static char *colon(char *str) of filenames like f:myfile.txt. */ if (str[0] == '\0' || str[0] == ':' || (str[0] != '[' && str[1] == ':')) - return (NULL); + return (NULL); str += host_strcspn(str, ":/\\"); if (*str == ':') - return (str); + return (str); else - return (NULL); + return (NULL); } /* @@ -556,29 +556,29 @@ static int response(void) int p; if (!ssh_scp_recv(&resp, 1)) - bump("Lost connection"); + bump("Lost connection"); p = 0; switch (resp) { - case 0: /* ok */ - return (0); + case 0: /* ok */ + return (0); default: - rbuf[p++] = resp; - /* fallthrough */ - case 1: /* error */ - case 2: /* fatal error */ - do { - if (!ssh_scp_recv(&ch, 1)) - bump("Protocol error: Lost connection"); - rbuf[p++] = ch; - } while (p < sizeof(rbuf) && ch != '\n'); - rbuf[p - 1] = '\0'; - if (resp == 1) - tell_user(stderr, "%s", rbuf); - else - bump("%s", rbuf); - errs++; - return (-1); + rbuf[p++] = resp; + /* fallthrough */ + case 1: /* error */ + case 2: /* fatal error */ + do { + if (!ssh_scp_recv(&ch, 1)) + bump("Protocol error: Lost connection"); + rbuf[p++] = ch; + } while (p < sizeof(rbuf) && ch != '\n'); + rbuf[p - 1] = '\0'; + if (resp == 1) + tell_user(stderr, "%s", rbuf); + else + bump("%s", rbuf); + errs++; + return (-1); } } @@ -619,9 +619,9 @@ void scp_sftp_listdir(const char *dirname) struct sftp_request *req; if (!fxp_init()) { - tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); - errs++; - return; + tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); + errs++; + return; } printf("Listing directory %s\n", dirname); @@ -631,37 +631,37 @@ void scp_sftp_listdir(const char *dirname) dirh = fxp_opendir_recv(pktin, req); if (dirh == NULL) { - tell_user(stderr, "Unable to open %s: %s\n", dirname, fxp_error()); - errs++; + tell_user(stderr, "Unable to open %s: %s\n", dirname, fxp_error()); + errs++; } else { struct list_directory_from_sftp_ctx *ctx = list_directory_from_sftp_new(); - while (1) { + while (1) { - req = fxp_readdir_send(dirh); + req = fxp_readdir_send(dirh); pktin = sftp_wait_for_reply(req); - names = fxp_readdir_recv(pktin, req); + names = fxp_readdir_recv(pktin, req); - if (names == NULL) { - if (fxp_error_type() == SSH_FX_EOF) - break; - printf("Reading directory %s: %s\n", dirname, fxp_error()); - break; - } - if (names->nnames == 0) { - fxp_free_names(names); - break; - } + if (names == NULL) { + if (fxp_error_type() == SSH_FX_EOF) + break; + printf("Reading directory %s: %s\n", dirname, fxp_error()); + break; + } + if (names->nnames == 0) { + fxp_free_names(names); + break; + } - for (size_t i = 0; i < names->nnames; i++) + for (size_t i = 0; i < names->nnames; i++) list_directory_from_sftp_feed(ctx, &names->names[i]); - fxp_free_names(names); - } - req = fxp_close_send(dirh); + fxp_free_names(names); + } + req = fxp_close_send(dirh); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); + fxp_close_recv(pktin, req); list_directory_from_sftp_finish(ctx); list_directory_from_sftp_free(ctx); @@ -694,39 +694,39 @@ static uint64_t scp_sftp_fileoffset; int scp_source_setup(const char *target, bool shouldbedir) { if (using_sftp) { - /* - * Find out whether the target filespec is in fact a - * directory. - */ - struct sftp_packet *pktin; - struct sftp_request *req; - struct fxp_attrs attrs; - bool ret; + /* + * Find out whether the target filespec is in fact a + * directory. + */ + struct sftp_packet *pktin; + struct sftp_request *req; + struct fxp_attrs attrs; + bool ret; - if (!fxp_init()) { - tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); - errs++; - return 1; - } + if (!fxp_init()) { + tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); + errs++; + return 1; + } - req = fxp_stat_send(target); + req = fxp_stat_send(target); pktin = sftp_wait_for_reply(req); - ret = fxp_stat_recv(pktin, req, &attrs); + ret = fxp_stat_recv(pktin, req, &attrs); - if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) - scp_sftp_targetisdir = false; - else - scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0; + if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) + scp_sftp_targetisdir = false; + else + scp_sftp_targetisdir = (attrs.permissions & 0040000) != 0; - if (shouldbedir && !scp_sftp_targetisdir) { - bump("pscp: remote filespec %s: not a directory\n", target); - } + if (shouldbedir && !scp_sftp_targetisdir) { + bump("pscp: remote filespec %s: not a directory\n", target); + } - scp_sftp_remotepath = dupstr(target); + scp_sftp_remotepath = dupstr(target); - scp_has_times = false; + scp_has_times = false; } else { - (void) response(); + (void) response(); } return 0; } @@ -734,248 +734,248 @@ int scp_source_setup(const char *target, bool shouldbedir) int scp_send_errmsg(char *str) { if (using_sftp) { - /* do nothing; we never need to send our errors to the server */ + /* do nothing; we never need to send our errors to the server */ } else { backend_send(backend, "\001", 1);/* scp protocol error prefix */ backend_send(backend, str, strlen(str)); } - return 0; /* can't fail */ + return 0; /* can't fail */ } int scp_send_filetimes(unsigned long mtime, unsigned long atime) { if (using_sftp) { - scp_sftp_mtime = mtime; - scp_sftp_atime = atime; - scp_has_times = true; - return 0; + scp_sftp_mtime = mtime; + scp_sftp_atime = atime; + scp_has_times = true; + return 0; } else { - char buf[80]; - sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime); + char buf[80]; + sprintf(buf, "T%lu 0 %lu 0\n", mtime, atime); backend_send(backend, buf, strlen(buf)); - return response(); + return response(); } } int scp_send_filename(const char *name, uint64_t size, int permissions) { if (using_sftp) { - char *fullname; - struct sftp_packet *pktin; - struct sftp_request *req; + char *fullname; + struct sftp_packet *pktin; + struct sftp_request *req; struct fxp_attrs attrs; - if (scp_sftp_targetisdir) { - fullname = dupcat(scp_sftp_remotepath, "/", name, NULL); - } else { - fullname = dupstr(scp_sftp_remotepath); - } + if (scp_sftp_targetisdir) { + fullname = dupcat(scp_sftp_remotepath, "/", name, NULL); + } else { + fullname = dupstr(scp_sftp_remotepath); + } attrs.flags = 0; PUT_PERMISSIONS(attrs, permissions); - req = fxp_open_send(fullname, + req = fxp_open_send(fullname, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC, &attrs); pktin = sftp_wait_for_reply(req); - scp_sftp_filehandle = fxp_open_recv(pktin, req); + scp_sftp_filehandle = fxp_open_recv(pktin, req); - if (!scp_sftp_filehandle) { - tell_user(stderr, "pscp: unable to open %s: %s", - fullname, fxp_error()); + if (!scp_sftp_filehandle) { + tell_user(stderr, "pscp: unable to open %s: %s", + fullname, fxp_error()); sfree(fullname); - errs++; - return 1; - } - scp_sftp_fileoffset = 0; - scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle, - scp_sftp_fileoffset); - sfree(fullname); - return 0; + errs++; + return 1; + } + scp_sftp_fileoffset = 0; + scp_sftp_xfer = xfer_upload_init(scp_sftp_filehandle, + scp_sftp_fileoffset); + sfree(fullname); + return 0; } else { - char *buf; + char *buf; if (permissions < 0) permissions = 0644; - buf = dupprintf("C%04o %"PRIu64" ", (int)(permissions & 07777), size); + buf = dupprintf("C%04o %"PRIu64" ", (int)(permissions & 07777), size); backend_send(backend, buf, strlen(buf)); sfree(buf); backend_send(backend, name, strlen(name)); backend_send(backend, "\n", 1); - return response(); + return response(); } } int scp_send_filedata(char *data, int len) { if (using_sftp) { - int ret; - struct sftp_packet *pktin; + int ret; + struct sftp_packet *pktin; - if (!scp_sftp_filehandle) { - return 1; - } + if (!scp_sftp_filehandle) { + return 1; + } - while (!xfer_upload_ready(scp_sftp_xfer)) { - pktin = sftp_recv(); - ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin); - if (ret <= 0) { - tell_user(stderr, "error while writing: %s", fxp_error()); + while (!xfer_upload_ready(scp_sftp_xfer)) { + pktin = sftp_recv(); + ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin); + if (ret <= 0) { + tell_user(stderr, "error while writing: %s", fxp_error()); if (ret == INT_MIN) /* pktin not even freed */ sfree(pktin); - errs++; - return 1; - } - } + errs++; + return 1; + } + } - xfer_upload_data(scp_sftp_xfer, data, len); + xfer_upload_data(scp_sftp_xfer, data, len); - scp_sftp_fileoffset += len; - return 0; + scp_sftp_fileoffset += len; + return 0; } else { int bufsize = backend_send(backend, data, len); - /* - * If the network transfer is backing up - that is, the - * remote site is not accepting data as fast as we can - * produce it - then we must loop on network events until - * we have space in the buffer again. - */ - while (bufsize > MAX_SCP_BUFSIZE) { - if (ssh_sftp_loop_iteration() < 0) - return 1; + /* + * If the network transfer is backing up - that is, the + * remote site is not accepting data as fast as we can + * produce it - then we must loop on network events until + * we have space in the buffer again. + */ + while (bufsize > MAX_SCP_BUFSIZE) { + if (ssh_sftp_loop_iteration() < 0) + return 1; bufsize = backend_sendbuffer(backend); - } + } - return 0; + return 0; } } int scp_send_finish(void) { if (using_sftp) { - struct fxp_attrs attrs; - struct sftp_packet *pktin; - struct sftp_request *req; + struct fxp_attrs attrs; + struct sftp_packet *pktin; + struct sftp_request *req; - while (!xfer_done(scp_sftp_xfer)) { - pktin = sftp_recv(); - int ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin); - if (ret <= 0) { - tell_user(stderr, "error while writing: %s", fxp_error()); + while (!xfer_done(scp_sftp_xfer)) { + pktin = sftp_recv(); + int ret = xfer_upload_gotpkt(scp_sftp_xfer, pktin); + if (ret <= 0) { + tell_user(stderr, "error while writing: %s", fxp_error()); if (ret == INT_MIN) /* pktin not even freed */ sfree(pktin); - errs++; - return 1; - } - } - xfer_cleanup(scp_sftp_xfer); + errs++; + return 1; + } + } + xfer_cleanup(scp_sftp_xfer); - if (!scp_sftp_filehandle) { - return 1; - } - if (scp_has_times) { - attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME; - attrs.atime = scp_sftp_atime; - attrs.mtime = scp_sftp_mtime; - req = fxp_fsetstat_send(scp_sftp_filehandle, attrs); + if (!scp_sftp_filehandle) { + return 1; + } + if (scp_has_times) { + attrs.flags = SSH_FILEXFER_ATTR_ACMODTIME; + attrs.atime = scp_sftp_atime; + attrs.mtime = scp_sftp_mtime; + req = fxp_fsetstat_send(scp_sftp_filehandle, attrs); pktin = sftp_wait_for_reply(req); - bool ret = fxp_fsetstat_recv(pktin, req); - if (!ret) { - tell_user(stderr, "unable to set file times: %s", fxp_error()); - errs++; - } - } - req = fxp_close_send(scp_sftp_filehandle); + bool ret = fxp_fsetstat_recv(pktin, req); + if (!ret) { + tell_user(stderr, "unable to set file times: %s", fxp_error()); + errs++; + } + } + req = fxp_close_send(scp_sftp_filehandle); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); - scp_has_times = false; - return 0; + fxp_close_recv(pktin, req); + scp_has_times = false; + return 0; } else { backend_send(backend, "", 1); - return response(); + return response(); } } char *scp_save_remotepath(void) { if (using_sftp) - return scp_sftp_remotepath; + return scp_sftp_remotepath; else - return NULL; + return NULL; } void scp_restore_remotepath(char *data) { if (using_sftp) - scp_sftp_remotepath = data; + scp_sftp_remotepath = data; } int scp_send_dirname(const char *name, int modes) { if (using_sftp) { - char *fullname; - char const *err; - struct fxp_attrs attrs; - struct sftp_packet *pktin; - struct sftp_request *req; + char *fullname; + char const *err; + struct fxp_attrs attrs; + struct sftp_packet *pktin; + struct sftp_request *req; bool ret; - if (scp_sftp_targetisdir) { - fullname = dupcat(scp_sftp_remotepath, "/", name, NULL); - } else { - fullname = dupstr(scp_sftp_remotepath); - } + if (scp_sftp_targetisdir) { + fullname = dupcat(scp_sftp_remotepath, "/", name, NULL); + } else { + fullname = dupstr(scp_sftp_remotepath); + } - /* - * We don't worry about whether we managed to create the - * directory, because if it exists already it's OK just to - * use it. Instead, we will stat it afterwards, and if it - * exists and is a directory we will assume we were either - * successful or it didn't matter. - */ - req = fxp_mkdir_send(fullname, NULL); + /* + * We don't worry about whether we managed to create the + * directory, because if it exists already it's OK just to + * use it. Instead, we will stat it afterwards, and if it + * exists and is a directory we will assume we were either + * successful or it didn't matter. + */ + req = fxp_mkdir_send(fullname, NULL); pktin = sftp_wait_for_reply(req); - ret = fxp_mkdir_recv(pktin, req); + ret = fxp_mkdir_recv(pktin, req); - if (!ret) - err = fxp_error(); - else - err = "server reported no error"; + if (!ret) + err = fxp_error(); + else + err = "server reported no error"; - req = fxp_stat_send(fullname); + req = fxp_stat_send(fullname); pktin = sftp_wait_for_reply(req); - ret = fxp_stat_recv(pktin, req, &attrs); + ret = fxp_stat_recv(pktin, req, &attrs); - if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) || - !(attrs.permissions & 0040000)) { - tell_user(stderr, "unable to create directory %s: %s", - fullname, err); + if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) || + !(attrs.permissions & 0040000)) { + tell_user(stderr, "unable to create directory %s: %s", + fullname, err); sfree(fullname); - errs++; - return 1; - } + errs++; + return 1; + } - scp_sftp_remotepath = fullname; + scp_sftp_remotepath = fullname; - return 0; + return 0; } else { - char buf[40]; - sprintf(buf, "D%04o 0 ", modes); + char buf[40]; + sprintf(buf, "D%04o 0 ", modes); backend_send(backend, buf, strlen(buf)); backend_send(backend, name, strlen(name)); backend_send(backend, "\n", 1); - return response(); + return response(); } } int scp_send_enddir(void) { if (using_sftp) { - sfree(scp_sftp_remotepath); - return 0; + sfree(scp_sftp_remotepath); + return 0; } else { backend_send(backend, "E\n", 2); - return response(); + return response(); } } @@ -988,83 +988,83 @@ int scp_send_enddir(void) int scp_sink_setup(const char *source, bool preserve, bool recursive) { if (using_sftp) { - char *newsource; + char *newsource; - if (!fxp_init()) { - tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); - errs++; - return 1; - } - /* - * It's possible that the source string we've been given - * contains a wildcard. If so, we must split the directory - * away from the wildcard itself (throwing an error if any - * wildcardness comes before the final slash) and arrange - * things so that a dirstack entry will be set up. - */ - newsource = snewn(1+strlen(source), char); - if (!wc_unescape(newsource, source)) { - /* Yes, here we go; it's a wildcard. Bah. */ - char *dupsource, *lastpart, *dirpart, *wildcard; + if (!fxp_init()) { + tell_user(stderr, "unable to initialise SFTP: %s", fxp_error()); + errs++; + return 1; + } + /* + * It's possible that the source string we've been given + * contains a wildcard. If so, we must split the directory + * away from the wildcard itself (throwing an error if any + * wildcardness comes before the final slash) and arrange + * things so that a dirstack entry will be set up. + */ + newsource = snewn(1+strlen(source), char); + if (!wc_unescape(newsource, source)) { + /* Yes, here we go; it's a wildcard. Bah. */ + char *dupsource, *lastpart, *dirpart, *wildcard; - sfree(newsource); + sfree(newsource); - dupsource = dupstr(source); - lastpart = stripslashes(dupsource, false); - wildcard = dupstr(lastpart); - *lastpart = '\0'; - if (*dupsource && dupsource[1]) { - /* - * The remains of dupsource are at least two - * characters long, meaning the pathname wasn't - * empty or just `/'. Hence, we remove the trailing - * slash. - */ - lastpart[-1] = '\0'; - } else if (!*dupsource) { - /* - * The remains of dupsource are _empty_ - the whole - * pathname was a wildcard. Hence we need to - * replace it with ".". - */ - sfree(dupsource); - dupsource = dupstr("."); - } + dupsource = dupstr(source); + lastpart = stripslashes(dupsource, false); + wildcard = dupstr(lastpart); + *lastpart = '\0'; + if (*dupsource && dupsource[1]) { + /* + * The remains of dupsource are at least two + * characters long, meaning the pathname wasn't + * empty or just `/'. Hence, we remove the trailing + * slash. + */ + lastpart[-1] = '\0'; + } else if (!*dupsource) { + /* + * The remains of dupsource are _empty_ - the whole + * pathname was a wildcard. Hence we need to + * replace it with ".". + */ + sfree(dupsource); + dupsource = dupstr("."); + } - /* - * Now we have separated our string into dupsource (the - * directory part) and wildcard. Both of these will - * need freeing at some point. Next step is to remove - * wildcard escapes from the directory part, throwing - * an error if it contains a real wildcard. - */ - dirpart = snewn(1+strlen(dupsource), char); - if (!wc_unescape(dirpart, dupsource)) { - tell_user(stderr, "%s: multiple-level wildcards unsupported", - source); - errs++; - sfree(dirpart); - sfree(wildcard); - sfree(dupsource); - return 1; - } + /* + * Now we have separated our string into dupsource (the + * directory part) and wildcard. Both of these will + * need freeing at some point. Next step is to remove + * wildcard escapes from the directory part, throwing + * an error if it contains a real wildcard. + */ + dirpart = snewn(1+strlen(dupsource), char); + if (!wc_unescape(dirpart, dupsource)) { + tell_user(stderr, "%s: multiple-level wildcards unsupported", + source); + errs++; + sfree(dirpart); + sfree(wildcard); + sfree(dupsource); + return 1; + } - /* - * Now we have dirpart (unescaped, ie a valid remote - * path), and wildcard (a wildcard). This will be - * sufficient to arrange a dirstack entry. - */ - scp_sftp_remotepath = dirpart; - scp_sftp_wildcard = wildcard; - sfree(dupsource); - } else { - scp_sftp_remotepath = newsource; - scp_sftp_wildcard = NULL; - } - scp_sftp_preserve = preserve; - scp_sftp_recursive = recursive; - scp_sftp_donethistarget = false; - scp_sftp_dirstack_head = NULL; + /* + * Now we have dirpart (unescaped, ie a valid remote + * path), and wildcard (a wildcard). This will be + * sufficient to arrange a dirstack entry. + */ + scp_sftp_remotepath = dirpart; + scp_sftp_wildcard = wildcard; + sfree(dupsource); + } else { + scp_sftp_remotepath = newsource; + scp_sftp_wildcard = NULL; + } + scp_sftp_preserve = preserve; + scp_sftp_recursive = recursive; + scp_sftp_donethistarget = false; + scp_sftp_dirstack_head = NULL; } return 0; } @@ -1080,175 +1080,175 @@ int scp_sink_init(void) #define SCP_SINK_FILE 1 #define SCP_SINK_DIR 2 #define SCP_SINK_ENDDIR 3 -#define SCP_SINK_RETRY 4 /* not an action; just try again */ +#define SCP_SINK_RETRY 4 /* not an action; just try again */ struct scp_sink_action { - int action; /* FILE, DIR, ENDDIR */ + int action; /* FILE, DIR, ENDDIR */ strbuf *buf; /* will need freeing after use */ - char *name; /* filename or dirname (not ENDDIR) */ - long permissions; /* access permissions (not ENDDIR) */ + char *name; /* filename or dirname (not ENDDIR) */ + long permissions; /* access permissions (not ENDDIR) */ uint64_t size; /* file size (not ENDDIR) */ bool settime; /* true if atime and mtime are filled */ - unsigned long atime, mtime; /* access times for the file */ + unsigned long atime, mtime; /* access times for the file */ }; int scp_get_sink_action(struct scp_sink_action *act) { if (using_sftp) { - char *fname; - bool must_free_fname; - struct fxp_attrs attrs; - struct sftp_packet *pktin; - struct sftp_request *req; - bool ret; + char *fname; + bool must_free_fname; + struct fxp_attrs attrs; + struct sftp_packet *pktin; + struct sftp_request *req; + bool ret; - if (!scp_sftp_dirstack_head) { - if (!scp_sftp_donethistarget) { - /* - * Simple case: we are only dealing with one file. - */ - fname = scp_sftp_remotepath; - must_free_fname = false; - scp_sftp_donethistarget = true; - } else { - /* - * Even simpler case: one file _which we've done_. - * Return 1 (finished). - */ - return 1; - } - } else { - /* - * We're now in the middle of stepping through a list - * of names returned from fxp_readdir(); so let's carry - * on. - */ - struct scp_sftp_dirstack *head = scp_sftp_dirstack_head; - while (head->namepos < head->namelen && - (is_dots(head->names[head->namepos].filename) || - (head->wildcard && - !wc_match(head->wildcard, - head->names[head->namepos].filename)))) - head->namepos++; /* skip . and .. */ - if (head->namepos < head->namelen) { - head->matched_something = true; - fname = dupcat(head->dirpath, "/", - head->names[head->namepos++].filename, - NULL); - must_free_fname = true; - } else { - /* - * We've come to the end of the list; pop it off - * the stack and return an ENDDIR action (or RETRY - * if this was a wildcard match). - */ - if (head->wildcard) { - act->action = SCP_SINK_RETRY; - if (!head->matched_something) { - tell_user(stderr, "pscp: wildcard '%s' matched " - "no files", head->wildcard); - errs++; - } - sfree(head->wildcard); + if (!scp_sftp_dirstack_head) { + if (!scp_sftp_donethistarget) { + /* + * Simple case: we are only dealing with one file. + */ + fname = scp_sftp_remotepath; + must_free_fname = false; + scp_sftp_donethistarget = true; + } else { + /* + * Even simpler case: one file _which we've done_. + * Return 1 (finished). + */ + return 1; + } + } else { + /* + * We're now in the middle of stepping through a list + * of names returned from fxp_readdir(); so let's carry + * on. + */ + struct scp_sftp_dirstack *head = scp_sftp_dirstack_head; + while (head->namepos < head->namelen && + (is_dots(head->names[head->namepos].filename) || + (head->wildcard && + !wc_match(head->wildcard, + head->names[head->namepos].filename)))) + head->namepos++; /* skip . and .. */ + if (head->namepos < head->namelen) { + head->matched_something = true; + fname = dupcat(head->dirpath, "/", + head->names[head->namepos++].filename, + NULL); + must_free_fname = true; + } else { + /* + * We've come to the end of the list; pop it off + * the stack and return an ENDDIR action (or RETRY + * if this was a wildcard match). + */ + if (head->wildcard) { + act->action = SCP_SINK_RETRY; + if (!head->matched_something) { + tell_user(stderr, "pscp: wildcard '%s' matched " + "no files", head->wildcard); + errs++; + } + sfree(head->wildcard); - } else { - act->action = SCP_SINK_ENDDIR; - } + } else { + act->action = SCP_SINK_ENDDIR; + } - sfree(head->dirpath); - sfree(head->names); - scp_sftp_dirstack_head = head->next; - sfree(head); + sfree(head->dirpath); + sfree(head->names); + scp_sftp_dirstack_head = head->next; + sfree(head); - return 0; - } - } + return 0; + } + } - /* - * Now we have a filename. Stat it, and see if it's a file - * or a directory. - */ - req = fxp_stat_send(fname); + /* + * Now we have a filename. Stat it, and see if it's a file + * or a directory. + */ + req = fxp_stat_send(fname); pktin = sftp_wait_for_reply(req); - ret = fxp_stat_recv(pktin, req, &attrs); + ret = fxp_stat_recv(pktin, req, &attrs); - if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) { + if (!ret || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) { with_stripctrl(san, fname) tell_user(stderr, "unable to identify %s: %s", san, ret ? "file type not supplied" : fxp_error()); if (must_free_fname) sfree(fname); - errs++; - return 1; - } + errs++; + return 1; + } - if (attrs.permissions & 0040000) { - struct scp_sftp_dirstack *newitem; - struct fxp_handle *dirhandle; - size_t nnames, namesize; - struct fxp_name *ournames; - struct fxp_names *names; + if (attrs.permissions & 0040000) { + struct scp_sftp_dirstack *newitem; + struct fxp_handle *dirhandle; + size_t nnames, namesize; + struct fxp_name *ournames; + struct fxp_names *names; - /* - * It's a directory. If we're not in recursive mode, - * this merits a complaint (which is fatal if the name - * was specified directly, but not if it was matched by - * a wildcard). - * - * We skip this complaint completely if - * scp_sftp_wildcard is set, because that's an - * indication that we're not actually supposed to - * _recursively_ transfer the dir, just scan it for - * things matching the wildcard. - */ - if (!scp_sftp_recursive && !scp_sftp_wildcard) { + /* + * It's a directory. If we're not in recursive mode, + * this merits a complaint (which is fatal if the name + * was specified directly, but not if it was matched by + * a wildcard). + * + * We skip this complaint completely if + * scp_sftp_wildcard is set, because that's an + * indication that we're not actually supposed to + * _recursively_ transfer the dir, just scan it for + * things matching the wildcard. + */ + if (!scp_sftp_recursive && !scp_sftp_wildcard) { with_stripctrl(san, fname) tell_user(stderr, "pscp: %s: is a directory", san); - errs++; - if (must_free_fname) sfree(fname); - if (scp_sftp_dirstack_head) { - act->action = SCP_SINK_RETRY; - return 0; - } else { - return 1; - } - } + errs++; + if (must_free_fname) sfree(fname); + if (scp_sftp_dirstack_head) { + act->action = SCP_SINK_RETRY; + return 0; + } else { + return 1; + } + } - /* - * Otherwise, the fun begins. We must fxp_opendir() the - * directory, slurp the filenames into memory, return - * SCP_SINK_DIR (unless this is a wildcard match), and - * set targetisdir. The next time we're called, we will - * run through the list of filenames one by one, - * matching them against a wildcard if present. - * - * If targetisdir is _already_ set (meaning we're - * already in the middle of going through another such - * list), we must push the other (target,namelist) pair - * on a stack. - */ - req = fxp_opendir_send(fname); + /* + * Otherwise, the fun begins. We must fxp_opendir() the + * directory, slurp the filenames into memory, return + * SCP_SINK_DIR (unless this is a wildcard match), and + * set targetisdir. The next time we're called, we will + * run through the list of filenames one by one, + * matching them against a wildcard if present. + * + * If targetisdir is _already_ set (meaning we're + * already in the middle of going through another such + * list), we must push the other (target,namelist) pair + * on a stack. + */ + req = fxp_opendir_send(fname); pktin = sftp_wait_for_reply(req); - dirhandle = fxp_opendir_recv(pktin, req); + dirhandle = fxp_opendir_recv(pktin, req); - if (!dirhandle) { + if (!dirhandle) { with_stripctrl(san, fname) tell_user(stderr, "pscp: unable to open directory %s: %s", san, fxp_error()); - if (must_free_fname) sfree(fname); - errs++; - return 1; - } - nnames = namesize = 0; - ournames = NULL; - while (1) { - int i; + if (must_free_fname) sfree(fname); + errs++; + return 1; + } + nnames = namesize = 0; + ournames = NULL; + while (1) { + int i; - req = fxp_readdir_send(dirhandle); + req = fxp_readdir_send(dirhandle); pktin = sftp_wait_for_reply(req); - names = fxp_readdir_recv(pktin, req); + names = fxp_readdir_recv(pktin, req); - if (names == NULL) { - if (fxp_error_type() == SSH_FX_EOF) - break; + if (names == NULL) { + if (fxp_error_type() == SSH_FX_EOF) + break; with_stripctrl(san, fname) tell_user(stderr, "pscp: reading directory %s: %s", san, fxp_error()); @@ -1257,269 +1257,269 @@ int scp_get_sink_action(struct scp_sink_action *act) pktin = sftp_wait_for_reply(req); fxp_close_recv(pktin, req); - if (must_free_fname) sfree(fname); - sfree(ournames); - errs++; - return 1; - } - if (names->nnames == 0) { - fxp_free_names(names); - break; - } + if (must_free_fname) sfree(fname); + sfree(ournames); + errs++; + return 1; + } + if (names->nnames == 0) { + fxp_free_names(names); + break; + } sgrowarrayn(ournames, namesize, nnames, names->nnames); - for (i = 0; i < names->nnames; i++) { - if (!strcmp(names->names[i].filename, ".") || - !strcmp(names->names[i].filename, "..")) { - /* - * . and .. are normal consequences of - * reading a directory, and aren't worth - * complaining about. - */ - } else if (!vet_filename(names->names[i].filename)) { + for (i = 0; i < names->nnames; i++) { + if (!strcmp(names->names[i].filename, ".") || + !strcmp(names->names[i].filename, "..")) { + /* + * . and .. are normal consequences of + * reading a directory, and aren't worth + * complaining about. + */ + } else if (!vet_filename(names->names[i].filename)) { with_stripctrl(san, names->names[i].filename) tell_user(stderr, "ignoring potentially dangerous " "server-supplied filename '%s'", san); - } else - ournames[nnames++] = names->names[i]; - } - names->nnames = 0; /* prevent free_names */ - fxp_free_names(names); - } - req = fxp_close_send(dirhandle); + } else + ournames[nnames++] = names->names[i]; + } + names->nnames = 0; /* prevent free_names */ + fxp_free_names(names); + } + req = fxp_close_send(dirhandle); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); + fxp_close_recv(pktin, req); - newitem = snew(struct scp_sftp_dirstack); - newitem->next = scp_sftp_dirstack_head; - newitem->names = ournames; - newitem->namepos = 0; - newitem->namelen = nnames; - if (must_free_fname) - newitem->dirpath = fname; - else - newitem->dirpath = dupstr(fname); - if (scp_sftp_wildcard) { - newitem->wildcard = scp_sftp_wildcard; - newitem->matched_something = false; - scp_sftp_wildcard = NULL; - } else { - newitem->wildcard = NULL; - } - scp_sftp_dirstack_head = newitem; + newitem = snew(struct scp_sftp_dirstack); + newitem->next = scp_sftp_dirstack_head; + newitem->names = ournames; + newitem->namepos = 0; + newitem->namelen = nnames; + if (must_free_fname) + newitem->dirpath = fname; + else + newitem->dirpath = dupstr(fname); + if (scp_sftp_wildcard) { + newitem->wildcard = scp_sftp_wildcard; + newitem->matched_something = false; + scp_sftp_wildcard = NULL; + } else { + newitem->wildcard = NULL; + } + scp_sftp_dirstack_head = newitem; - if (newitem->wildcard) { - act->action = SCP_SINK_RETRY; - } else { - act->action = SCP_SINK_DIR; - act->buf->len = 0; + if (newitem->wildcard) { + act->action = SCP_SINK_RETRY; + } else { + act->action = SCP_SINK_DIR; + act->buf->len = 0; put_asciz(act->buf, stripslashes(fname, false)); - act->name = act->buf->s; - act->size = 0; /* duhh, it's a directory */ - act->permissions = 07777 & attrs.permissions; - if (scp_sftp_preserve && - (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) { - act->atime = attrs.atime; - act->mtime = attrs.mtime; - act->settime = true; - } else - act->settime = false; - } - return 0; + act->name = act->buf->s; + act->size = 0; /* duhh, it's a directory */ + act->permissions = 07777 & attrs.permissions; + if (scp_sftp_preserve && + (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) { + act->atime = attrs.atime; + act->mtime = attrs.mtime; + act->settime = true; + } else + act->settime = false; + } + return 0; - } else { - /* - * It's a file. Return SCP_SINK_FILE. - */ - act->action = SCP_SINK_FILE; + } else { + /* + * It's a file. Return SCP_SINK_FILE. + */ + act->action = SCP_SINK_FILE; act->buf->len = 0; put_asciz(act->buf, stripslashes(fname, false)); - act->name = act->buf->s; - if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) { - act->size = attrs.size; - } else - act->size = UINT64_MAX; /* no idea */ - act->permissions = 07777 & attrs.permissions; - if (scp_sftp_preserve && - (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) { - act->atime = attrs.atime; - act->mtime = attrs.mtime; - act->settime = true; - } else - act->settime = false; - if (must_free_fname) - scp_sftp_currentname = fname; - else - scp_sftp_currentname = dupstr(fname); - return 0; - } + act->name = act->buf->s; + if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) { + act->size = attrs.size; + } else + act->size = UINT64_MAX; /* no idea */ + act->permissions = 07777 & attrs.permissions; + if (scp_sftp_preserve && + (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME)) { + act->atime = attrs.atime; + act->mtime = attrs.mtime; + act->settime = true; + } else + act->settime = false; + if (must_free_fname) + scp_sftp_currentname = fname; + else + scp_sftp_currentname = dupstr(fname); + return 0; + } } else { - bool done = false; - int action; - char ch; + bool done = false; + int action; + char ch; - act->settime = false; + act->settime = false; act->buf->len = 0; - while (!done) { - if (!ssh_scp_recv(&ch, 1)) - return 1; - if (ch == '\n') - bump("Protocol error: Unexpected newline"); - action = ch; + while (!done) { + if (!ssh_scp_recv(&ch, 1)) + return 1; + if (ch == '\n') + bump("Protocol error: Unexpected newline"); + action = ch; while (1) { - if (!ssh_scp_recv(&ch, 1)) - bump("Lost connection"); + if (!ssh_scp_recv(&ch, 1)) + bump("Lost connection"); if (ch == '\n') break; put_byte(act->buf, ch); } - switch (action) { - case '\01': /* error */ + switch (action) { + case '\01': /* error */ with_stripctrl(san, act->buf->s) tell_user(stderr, "%s", san); - errs++; - continue; /* go round again */ - case '\02': /* fatal error */ + errs++; + continue; /* go round again */ + case '\02': /* fatal error */ with_stripctrl(san, act->buf->s) bump("%s", san); - case 'E': + case 'E': backend_send(backend, "", 1); - act->action = SCP_SINK_ENDDIR; - return 0; - case 'T': - if (sscanf(act->buf->s, "%lu %*d %lu %*d", - &act->mtime, &act->atime) == 2) { - act->settime = true; + act->action = SCP_SINK_ENDDIR; + return 0; + case 'T': + if (sscanf(act->buf->s, "%lu %*d %lu %*d", + &act->mtime, &act->atime) == 2) { + act->settime = true; backend_send(backend, "", 1); act->buf->len = 0; - continue; /* go round again */ - } - bump("Protocol error: Illegal time format"); - case 'C': - case 'D': - act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR); + continue; /* go round again */ + } + bump("Protocol error: Illegal time format"); + case 'C': + case 'D': + act->action = (action == 'C' ? SCP_SINK_FILE : SCP_SINK_DIR); if (act->action == SCP_SINK_DIR && !recursive) { bump("security violation: remote host attempted to create " "a subdirectory in a non-recursive copy!"); } - break; - default: - bump("Protocol error: Expected control record"); - } - /* - * We will go round this loop only once, unless we hit - * `continue' above. - */ - done = true; - } + break; + default: + bump("Protocol error: Expected control record"); + } + /* + * We will go round this loop only once, unless we hit + * `continue' above. + */ + done = true; + } - /* - * If we get here, we must have seen SCP_SINK_FILE or - * SCP_SINK_DIR. - */ - { + /* + * If we get here, we must have seen SCP_SINK_FILE or + * SCP_SINK_DIR. + */ + { int i; if (sscanf(act->buf->s, "%lo %"SCNu64" %n", &act->permissions, &act->size, &i) != 2) - bump("Protocol error: Illegal file descriptor format"); - act->name = act->buf->s + i; - return 0; - } + bump("Protocol error: Illegal file descriptor format"); + act->name = act->buf->s + i; + return 0; + } } } int scp_accept_filexfer(void) { if (using_sftp) { - struct sftp_packet *pktin; - struct sftp_request *req; + struct sftp_packet *pktin; + struct sftp_request *req; - req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL); + req = fxp_open_send(scp_sftp_currentname, SSH_FXF_READ, NULL); pktin = sftp_wait_for_reply(req); - scp_sftp_filehandle = fxp_open_recv(pktin, req); + scp_sftp_filehandle = fxp_open_recv(pktin, req); - if (!scp_sftp_filehandle) { + if (!scp_sftp_filehandle) { with_stripctrl(san, scp_sftp_currentname) tell_user(stderr, "pscp: unable to open %s: %s", san, fxp_error()); - errs++; - return 1; - } - scp_sftp_fileoffset = 0; - scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle, - scp_sftp_fileoffset); - sfree(scp_sftp_currentname); - return 0; + errs++; + return 1; + } + scp_sftp_fileoffset = 0; + scp_sftp_xfer = xfer_download_init(scp_sftp_filehandle, + scp_sftp_fileoffset); + sfree(scp_sftp_currentname); + return 0; } else { backend_send(backend, "", 1); - return 0; /* can't fail */ + return 0; /* can't fail */ } } int scp_recv_filedata(char *data, int len) { if (using_sftp) { - struct sftp_packet *pktin; - int ret, actuallen; - void *vbuf; + struct sftp_packet *pktin; + int ret, actuallen; + void *vbuf; - xfer_download_queue(scp_sftp_xfer); - pktin = sftp_recv(); - ret = xfer_download_gotpkt(scp_sftp_xfer, pktin); - if (ret <= 0) { - tell_user(stderr, "pscp: error while reading: %s", fxp_error()); + xfer_download_queue(scp_sftp_xfer); + pktin = sftp_recv(); + ret = xfer_download_gotpkt(scp_sftp_xfer, pktin); + if (ret <= 0) { + tell_user(stderr, "pscp: error while reading: %s", fxp_error()); if (ret == INT_MIN) /* pktin not even freed */ sfree(pktin); - errs++; - return -1; - } + errs++; + return -1; + } - if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) { + if (xfer_download_data(scp_sftp_xfer, &vbuf, &actuallen)) { if (actuallen <= 0) { tell_user(stderr, "pscp: end of file while reading"); errs++; sfree(vbuf); return -1; } - /* - * This assertion relies on the fact that the natural - * block size used in the xfer manager is at most that - * used in this module. I don't like crossing layers in - * this way, but it'll do for now. - */ - assert(actuallen <= len); - memcpy(data, vbuf, actuallen); - sfree(vbuf); - } else - actuallen = 0; + /* + * This assertion relies on the fact that the natural + * block size used in the xfer manager is at most that + * used in this module. I don't like crossing layers in + * this way, but it'll do for now. + */ + assert(actuallen <= len); + memcpy(data, vbuf, actuallen); + sfree(vbuf); + } else + actuallen = 0; - scp_sftp_fileoffset += actuallen; + scp_sftp_fileoffset += actuallen; - return actuallen; + return actuallen; } else { - return ssh_scp_recv(data, len) ? len : 0; + return ssh_scp_recv(data, len) ? len : 0; } } int scp_finish_filerecv(void) { if (using_sftp) { - struct sftp_packet *pktin; - struct sftp_request *req; + struct sftp_packet *pktin; + struct sftp_request *req; - /* - * Ensure that xfer_done() will work correctly, so we can - * clean up any outstanding requests from the file - * transfer. - */ - xfer_set_error(scp_sftp_xfer); - while (!xfer_done(scp_sftp_xfer)) { - void *vbuf; - int ret, len; + /* + * Ensure that xfer_done() will work correctly, so we can + * clean up any outstanding requests from the file + * transfer. + */ + xfer_set_error(scp_sftp_xfer); + while (!xfer_done(scp_sftp_xfer)) { + void *vbuf; + int ret, len; - pktin = sftp_recv(); - ret = xfer_download_gotpkt(scp_sftp_xfer, pktin); + pktin = sftp_recv(); + ret = xfer_download_gotpkt(scp_sftp_xfer, pktin); if (ret <= 0) { tell_user(stderr, "pscp: error while reading: %s", fxp_error()); if (ret == INT_MIN) /* pktin not even freed */ @@ -1527,18 +1527,18 @@ int scp_finish_filerecv(void) errs++; return -1; } - if (xfer_download_data(scp_sftp_xfer, &vbuf, &len)) - sfree(vbuf); - } - xfer_cleanup(scp_sftp_xfer); + if (xfer_download_data(scp_sftp_xfer, &vbuf, &len)) + sfree(vbuf); + } + xfer_cleanup(scp_sftp_xfer); - req = fxp_close_send(scp_sftp_filehandle); + req = fxp_close_send(scp_sftp_filehandle); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); - return 0; + fxp_close_recv(pktin, req); + return 0; } else { backend_send(backend, "", 1); - return response(); + return response(); } } @@ -1579,62 +1579,62 @@ static void source(const char *src) attr = file_type(src); if (attr == FILE_TYPE_NONEXISTENT || - attr == FILE_TYPE_WEIRD) { - run_err("%s: %s file or directory", src, - (attr == FILE_TYPE_WEIRD ? "Not a" : "No such")); - return; + attr == FILE_TYPE_WEIRD) { + run_err("%s: %s file or directory", src, + (attr == FILE_TYPE_WEIRD ? "Not a" : "No such")); + return; } if (attr == FILE_TYPE_DIRECTORY) { - if (recursive) { - /* - * Avoid . and .. directories. - */ - const 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; + if (recursive) { + /* + * Avoid . and .. directories. + */ + const 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; } if ((last = strrchr(src, '/')) == NULL) - last = src; + last = src; else - last++; + last++; if (strrchr(last, '\\') != NULL) - last = strrchr(last, '\\') + 1; + last = strrchr(last, '\\') + 1; if (last == src && strchr(src, ':') != NULL) - last = strchr(src, ':') + 1; + last = strchr(src, ':') + 1; f = open_existing_file(src, &size, &mtime, &atime, &permissions); if (f == NULL) { - run_err("%s: Cannot open file", src); - return; + run_err("%s: Cannot open file", src); + return; } if (preserve) { - if (scp_send_filetimes(mtime, atime)) { + if (scp_send_filetimes(mtime, atime)) { close_rfile(f); - return; + return; } } if (verbose) { - tell_user(stderr, "Sending file %s, size=%"PRIu64, last, size); + tell_user(stderr, "Sending file %s, size=%"PRIu64, last, size); } if (scp_send_filename(last, size, permissions)) { close_rfile(f); - return; + return; } stat_bytes = 0; @@ -1643,25 +1643,25 @@ static void source(const char *src) #define PSCP_SEND_BLOCK 4096 for (i = 0; i < size; i += PSCP_SEND_BLOCK) { - char transbuf[PSCP_SEND_BLOCK]; - int j, k = PSCP_SEND_BLOCK; + char transbuf[PSCP_SEND_BLOCK]; + int j, k = PSCP_SEND_BLOCK; - if (i + k > size) - k = size - i; - if ((j = read_from_file(f, transbuf, k)) != k) { - bump("%s: Read error", src); - } - if (scp_send_filedata(transbuf, k)) - bump("%s: Network error occurred", src); + if (i + k > size) + k = size - i; + if ((j = read_from_file(f, transbuf, k)) != k) { + bump("%s: Read error", src); + } + if (scp_send_filedata(transbuf, k)) + bump("%s: Network error occurred", src); - if (statistics) { - stat_bytes += k; - if (time(NULL) != stat_lasttime || i + k == size) { - stat_lasttime = time(NULL); - print_stats(last, size, stat_bytes, - stat_starttime, stat_lasttime); - } - } + if (statistics) { + stat_bytes += k; + if (time(NULL) != stat_lasttime || i + k == size) { + stat_lasttime = time(NULL); + print_stats(last, size, stat_bytes, + stat_starttime, stat_lasttime); + } + } } close_rfile(f); @@ -1679,33 +1679,33 @@ static void rsource(const char *src) DirHandle *dir; if ((last = strrchr(src, '/')) == NULL) - last = src; + last = src; else - last++; + last++; if (strrchr(last, '\\') != NULL) - last = strrchr(last, '\\') + 1; + last = strrchr(last, '\\') + 1; if (last == src && strchr(src, ':') != NULL) - last = strchr(src, ':') + 1; + last = strchr(src, ':') + 1; /* maybe send filetime */ save_target = scp_save_remotepath(); if (verbose) - tell_user(stderr, "Entering directory: %s", last); + tell_user(stderr, "Entering directory: %s", last); if (scp_send_dirname(last, 0755)) - return; + return; const char *opendir_err; dir = open_directory(src, &opendir_err); if (dir != NULL) { - char *filename; - while ((filename = read_filename(dir)) != NULL) { - char *foundfile = dupcat(src, "/", filename, NULL); - source(foundfile); - sfree(foundfile); - sfree(filename); - } + char *filename; + while ((filename = read_filename(dir)) != NULL) { + char *foundfile = dupcat(src, "/", filename, NULL); + source(foundfile); + sfree(foundfile); + sfree(filename); + } close_directory(dir); } else { tell_user(stderr, "Error opening directory %s: %s", src, opendir_err); @@ -1734,10 +1734,10 @@ static void sink(const char *targ, const char *src) attr = file_type(targ); if (attr == FILE_TYPE_DIRECTORY) - targisdir = true; + targisdir = true; if (targetshouldbedirectory && !targisdir) - bump("%s: Not a directory", targ); + bump("%s: Not a directory", targ); scp_sink_init(); @@ -1746,50 +1746,50 @@ static void sink(const char *targ, const char *src) while (1) { - if (scp_get_sink_action(&act)) + if (scp_get_sink_action(&act)) goto out; - if (act.action == SCP_SINK_ENDDIR) + if (act.action == SCP_SINK_ENDDIR) goto out; - if (act.action == SCP_SINK_RETRY) - continue; + if (act.action == SCP_SINK_RETRY) + continue; - if (targisdir) { - /* - * Prevent the remote side from maliciously writing to - * files outside the target area by sending a filename - * containing `../'. In fact, it shouldn't be sending - * filenames with any slashes or colons in at all; so - * we'll find the last slash, backslash or colon in the - * filename and use only the part after that. (And - * warn!) - * - * In addition, we also ensure here that if we're - * copying a single file and the target is a directory - * (common usage: `pscp host:filename .') the remote - * can't send us a _different_ file name. We can - * distinguish this case because `src' will be non-NULL - * and the last component of that will fail to match - * (the last component of) the name sent. - * - * Well, not always; if `src' is a wildcard, we do - * expect to get back filenames that don't correspond - * exactly to it. Ideally in this case, we would like - * to ensure that the returned filename actually - * matches the wildcard pattern - but one of SCP's - * protocol infelicities is that wildcard matching is - * done at the server end _by the server's rules_ and - * so in general this is infeasible. Hence, we only - * accept filenames that don't correspond to `src' if - * unsafe mode is enabled or we are using SFTP (which - * resolves remote wildcards on the client side and can - * be trusted). - */ - char *striptarget, *stripsrc; + if (targisdir) { + /* + * Prevent the remote side from maliciously writing to + * files outside the target area by sending a filename + * containing `../'. In fact, it shouldn't be sending + * filenames with any slashes or colons in at all; so + * we'll find the last slash, backslash or colon in the + * filename and use only the part after that. (And + * warn!) + * + * In addition, we also ensure here that if we're + * copying a single file and the target is a directory + * (common usage: `pscp host:filename .') the remote + * can't send us a _different_ file name. We can + * distinguish this case because `src' will be non-NULL + * and the last component of that will fail to match + * (the last component of) the name sent. + * + * Well, not always; if `src' is a wildcard, we do + * expect to get back filenames that don't correspond + * exactly to it. Ideally in this case, we would like + * to ensure that the returned filename actually + * matches the wildcard pattern - but one of SCP's + * protocol infelicities is that wildcard matching is + * done at the server end _by the server's rules_ and + * so in general this is infeasible. Hence, we only + * accept filenames that don't correspond to `src' if + * unsafe mode is enabled or we are using SFTP (which + * resolves remote wildcards on the client side and can + * be trusted). + */ + char *striptarget, *stripsrc; - striptarget = stripslashes(act.name, true); - if (striptarget != act.name) { + striptarget = stripslashes(act.name, true); + if (striptarget != act.name) { with_stripctrl(sanname, act.name) { with_stripctrl(santarg, act.name) { tell_user(stderr, "warning: remote host sent a" @@ -1798,142 +1798,142 @@ static void sink(const char *targ, const char *src) " file to '%s'", santarg); } } - } + } - /* - * Also check to see if the target filename is '.' or - * '..', or indeed '...' and so on because Windows - * appears to interpret those like '..'. - */ - if (is_dots(striptarget)) { - bump("security violation: remote host attempted to write to" - " a '.' or '..' path!"); - } + /* + * Also check to see if the target filename is '.' or + * '..', or indeed '...' and so on because Windows + * appears to interpret those like '..'. + */ + if (is_dots(striptarget)) { + bump("security violation: remote host attempted to write to" + " a '.' or '..' path!"); + } - if (src) { - stripsrc = stripslashes(src, true); - if (strcmp(striptarget, stripsrc) && - !using_sftp && !scp_unsafe_mode) { + if (src) { + stripsrc = stripslashes(src, true); + if (strcmp(striptarget, stripsrc) && + !using_sftp && !scp_unsafe_mode) { with_stripctrl(san, striptarget) tell_user(stderr, "warning: remote host tried to " "write to a file called '%s'", san); - tell_user(stderr, " when we requested a file " - "called '%s'.", stripsrc); - tell_user(stderr, " If this is a wildcard, " - "consider upgrading to SSH-2 or using"); - tell_user(stderr, " the '-unsafe' option. Renaming" - " of this file has been disallowed."); - /* Override the name the server provided with our own. */ - striptarget = stripsrc; - } - } + tell_user(stderr, " when we requested a file " + "called '%s'.", stripsrc); + tell_user(stderr, " If this is a wildcard, " + "consider upgrading to SSH-2 or using"); + tell_user(stderr, " the '-unsafe' option. Renaming" + " of this file has been disallowed."); + /* Override the name the server provided with our own. */ + striptarget = stripsrc; + } + } - if (targ[0] != '\0') - destfname = dir_file_cat(targ, striptarget); - else - destfname = dupstr(striptarget); - } else { - /* - * In this branch of the if, the target area is a - * single file with an explicitly specified name in any - * case, so there's no danger. - */ - destfname = dupstr(targ); - } - attr = file_type(destfname); - exists = (attr != FILE_TYPE_NONEXISTENT); + if (targ[0] != '\0') + destfname = dir_file_cat(targ, striptarget); + else + destfname = dupstr(striptarget); + } else { + /* + * In this branch of the if, the target area is a + * single file with an explicitly specified name in any + * case, so there's no danger. + */ + destfname = dupstr(targ); + } + attr = file_type(destfname); + exists = (attr != FILE_TYPE_NONEXISTENT); - if (act.action == SCP_SINK_DIR) { - if (exists && attr != FILE_TYPE_DIRECTORY) { + if (act.action == SCP_SINK_DIR) { + if (exists && attr != FILE_TYPE_DIRECTORY) { with_stripctrl(san, destfname) run_err("%s: Not a directory", san); sfree(destfname); - continue; - } - if (!exists) { - if (!create_directory(destfname)) { + continue; + } + if (!exists) { + if (!create_directory(destfname)) { with_stripctrl(san, destfname) run_err("%s: Cannot create directory", san); sfree(destfname); - continue; - } - } - sink(destfname, NULL); - /* can we set the timestamp for directories ? */ + continue; + } + } + sink(destfname, NULL); + /* can we set the timestamp for directories ? */ sfree(destfname); - continue; - } + continue; + } - f = open_new_file(destfname, act.permissions); - if (f == NULL) { + f = open_new_file(destfname, act.permissions); + if (f == NULL) { with_stripctrl(san, destfname) run_err("%s: Cannot create file", san); sfree(destfname); - continue; - } - - if (scp_accept_filexfer()) { - sfree(destfname); - close_wfile(f); - goto out; + continue; } - stat_bytes = 0; - stat_starttime = time(NULL); - stat_lasttime = 0; + if (scp_accept_filexfer()) { + sfree(destfname); + close_wfile(f); + goto out; + } + + stat_bytes = 0; + stat_starttime = time(NULL); + stat_lasttime = 0; stat_name = stripctrl_string( string_scc, stripslashes(destfname, true)); - received = 0; - while (received < act.size) { - char transbuf[32768]; - uint64_t blksize; - int read; - blksize = 32768; - if (blksize > act.size - received) + received = 0; + while (received < act.size) { + char transbuf[32768]; + uint64_t blksize; + int read; + blksize = 32768; + if (blksize > act.size - received) blksize = act.size - received; - read = scp_recv_filedata(transbuf, (int)blksize); - if (read <= 0) - bump("Lost connection"); - if (wrerror) { + read = scp_recv_filedata(transbuf, (int)blksize); + if (read <= 0) + bump("Lost connection"); + if (wrerror) { received += read; - continue; + continue; } - if (write_to_file(f, transbuf, read) != (int)read) { - wrerror = true; - /* FIXME: in sftp we can actually abort the transfer */ - if (statistics) - printf("\r%-25.25s | %50s\n", - stat_name, - "Write error.. waiting for end of file"); + if (write_to_file(f, transbuf, read) != (int)read) { + wrerror = true; + /* FIXME: in sftp we can actually abort the transfer */ + if (statistics) + printf("\r%-25.25s | %50s\n", + stat_name, + "Write error.. waiting for end of file"); received += read; - continue; - } - if (statistics) { - stat_bytes += read; - if (time(NULL) > stat_lasttime || + continue; + } + if (statistics) { + stat_bytes += read; + if (time(NULL) > stat_lasttime || received + read == act.size) { - stat_lasttime = time(NULL); - print_stats(stat_name, act.size, stat_bytes, - stat_starttime, stat_lasttime); - } - } - received += read; - } - if (act.settime) { - set_file_times(f, act.mtime, act.atime); - } + stat_lasttime = time(NULL); + print_stats(stat_name, act.size, stat_bytes, + stat_starttime, stat_lasttime); + } + } + received += read; + } + if (act.settime) { + set_file_times(f, act.mtime, act.atime); + } - close_wfile(f); - if (wrerror) { + close_wfile(f); + if (wrerror) { with_stripctrl(san, destfname) run_err("%s: Write error", san); sfree(destfname); - continue; - } - (void) scp_finish_filerecv(); - sfree(stat_name); - sfree(destfname); + continue; + } + (void) scp_finish_filerecv(); + sfree(stat_name); + sfree(destfname); } out: strbuf_free(act.buf); @@ -1957,11 +1957,11 @@ static void toremote(int argc, char *argv[]) host = wtarg; wtarg = colon(wtarg); if (wtarg == NULL) - bump("wtarg == NULL in toremote()"); + bump("wtarg == NULL in toremote()"); *wtarg++ = '\0'; /* Substitute "." for empty target */ if (*wtarg == '\0') - targ = "."; + targ = "."; else targ = wtarg; @@ -1969,68 +1969,68 @@ static void toremote(int argc, char *argv[]) user = host; host = strrchr(host, '@'); if (host == NULL) { - host = user; - user = NULL; + host = user; + user = NULL; } else { - *host++ = '\0'; - if (*user == '\0') - user = NULL; + *host++ = '\0'; + if (*user == '\0') + user = NULL; } if (argc == 2) { - if (colon(argv[0]) != NULL) - bump("%s: Remote to remote not supported", argv[0]); + if (colon(argv[0]) != NULL) + bump("%s: Remote to remote not supported", argv[0]); - wc_type = test_wildcard(argv[0], true); - if (wc_type == WCTYPE_NONEXISTENT) - bump("%s: No such file or directory\n", argv[0]); - else if (wc_type == WCTYPE_WILDCARD) - targetshouldbedirectory = true; + wc_type = test_wildcard(argv[0], true); + if (wc_type == WCTYPE_NONEXISTENT) + bump("%s: No such file or directory\n", argv[0]); + else if (wc_type == WCTYPE_WILDCARD) + targetshouldbedirectory = true; } cmd = dupprintf("scp%s%s%s%s -t %s", - verbose ? " -v" : "", - recursive ? " -r" : "", - preserve ? " -p" : "", - targetshouldbedirectory ? " -d" : "", targ); + verbose ? " -v" : "", + recursive ? " -r" : "", + preserve ? " -p" : "", + targetshouldbedirectory ? " -d" : "", targ); do_cmd(host, user, cmd); sfree(cmd); if (scp_source_setup(targ, targetshouldbedirectory)) - return; + return; for (i = 0; i < argc - 1; i++) { - src = argv[i]; - if (colon(src) != NULL) { - tell_user(stderr, "%s: Remote to remote not supported\n", src); - errs++; - continue; - } + src = argv[i]; + if (colon(src) != NULL) { + tell_user(stderr, "%s: Remote to remote not supported\n", src); + errs++; + continue; + } - wc_type = test_wildcard(src, true); - if (wc_type == WCTYPE_NONEXISTENT) { - run_err("%s: No such file or directory", src); - continue; - } else if (wc_type == WCTYPE_FILENAME) { - source(src); - continue; - } else { - WildcardMatcher *wc; - char *filename; + wc_type = test_wildcard(src, true); + if (wc_type == WCTYPE_NONEXISTENT) { + run_err("%s: No such file or directory", src); + continue; + } else if (wc_type == WCTYPE_FILENAME) { + source(src); + continue; + } else { + WildcardMatcher *wc; + char *filename; - wc = begin_wildcard_matching(src); - if (wc == NULL) { - run_err("%s: No such file or directory", src); - continue; - } + wc = begin_wildcard_matching(src); + if (wc == NULL) { + run_err("%s: No such file or directory", src); + continue; + } - while ((filename = wildcard_get_filename(wc)) != NULL) { - source(filename); - sfree(filename); - } + while ((filename = wildcard_get_filename(wc)) != NULL) { + source(filename); + sfree(filename); + } - finish_wildcard_matching(wc); - } + finish_wildcard_matching(wc); + } } } @@ -2046,7 +2046,7 @@ static void tolocal(int argc, char *argv[]) uploading = false; if (argc != 2) - bump("More than one remote source not supported"); + bump("More than one remote source not supported"); wsrc = argv[0]; targ = argv[1]; @@ -2055,11 +2055,11 @@ static void tolocal(int argc, char *argv[]) host = wsrc; wsrc = colon(wsrc); if (wsrc == NULL) - bump("Local to local copy not supported"); + bump("Local to local copy not supported"); *wsrc++ = '\0'; /* Substitute "." for empty filename */ if (*wsrc == '\0') - src = "."; + src = "."; else src = wsrc; @@ -2067,24 +2067,24 @@ static void tolocal(int argc, char *argv[]) user = host; host = strrchr(host, '@'); if (host == NULL) { - host = user; - user = NULL; + host = user; + user = NULL; } else { - *host++ = '\0'; - if (*user == '\0') - user = NULL; + *host++ = '\0'; + if (*user == '\0') + user = NULL; } cmd = dupprintf("scp%s%s%s%s -f %s", - verbose ? " -v" : "", - recursive ? " -r" : "", - preserve ? " -p" : "", - targetshouldbedirectory ? " -d" : "", src); + verbose ? " -v" : "", + recursive ? " -r" : "", + preserve ? " -p" : "", + targetshouldbedirectory ? " -d" : "", src); do_cmd(host, user, cmd); sfree(cmd); if (scp_sink_setup(src, preserve, recursive)) - return; + return; sink(targ, src); } @@ -2106,11 +2106,11 @@ static void get_dir_list(int argc, char *argv[]) host = wsrc; wsrc = colon(wsrc); if (wsrc == NULL) - bump("Local file listing not supported"); + bump("Local file listing not supported"); *wsrc++ = '\0'; /* Substitute "." for empty filename */ if (*wsrc == '\0') - src = "."; + src = "."; else src = wsrc; @@ -2118,26 +2118,26 @@ static void get_dir_list(int argc, char *argv[]) user = host; host = strrchr(host, '@'); if (host == NULL) { - host = user; - user = NULL; + host = user; + user = NULL; } else { - *host++ = '\0'; - if (*user == '\0') - user = NULL; + *host++ = '\0'; + if (*user == '\0') + user = NULL; } cmd = snewn(4 * strlen(src) + 100, char); strcpy(cmd, "ls -la '"); p = cmd + strlen(cmd); for (q = src; *q; q++) { - if (*q == '\'') { - *p++ = '\''; - *p++ = '\\'; - *p++ = '\''; - *p++ = '\''; - } else { - *p++ = *q; - } + if (*q == '\'') { + *p++ = '\''; + *p++ = '\\'; + *p++ = '\''; + *p++ = '\''; + } else { + *p++ = *q; + } } *p++ = '\''; *p = '\0'; @@ -2146,7 +2146,7 @@ static void get_dir_list(int argc, char *argv[]) sfree(cmd); if (using_sftp) { - scp_sftp_listdir(src); + scp_sftp_listdir(src); } else { stdio_sink ss; stdio_sink_init(&ss, stdout); @@ -2167,7 +2167,7 @@ static void usage(void) printf("%s\n", ver); printf("Usage: pscp [options] [user@]host:source target\n"); printf - (" pscp [options] source [source...] [user@]host:target\n"); + (" pscp [options] source [source...] [user@]host:target\n"); printf(" pscp [options] -ls [user@]host:filespec\n"); printf("Options:\n"); printf(" -V print version information and exit\n"); @@ -2240,9 +2240,9 @@ int psftp_main(int argc, char *argv[]) flags = 0 #ifdef FLAG_SYNCAGENT - | FLAG_SYNCAGENT + | FLAG_SYNCAGENT #endif - ; + ; cmdline_tooltype = TOOLTYPE_FILETRANSFER; sk_init(); @@ -2252,54 +2252,54 @@ int psftp_main(int argc, char *argv[]) loaded_session = false; for (i = 1; i < argc; i++) { - int ret; - if (argv[i][0] != '-') - break; - ret = cmdline_process_param(argv[i], i+1 2) - targetshouldbedirectory = true; + if (argc < 2) + usage(); + if (argc > 2) + targetshouldbedirectory = true; - if (colon(argv[argc - 1]) != NULL) - toremote(argc, argv); - else - tolocal(argc, argv); + if (colon(argv[argc - 1]) != NULL) + toremote(argc, argv); + else + tolocal(argc, argv); } if (backend && backend_connected(backend)) { - char ch; + char ch; backend_special(backend, SS_EOF, 0); sent_eof = true; - ssh_scp_recv(&ch, 1); + ssh_scp_recv(&ch, 1); } random_save_seed(); diff --git a/psftp.c b/psftp.c index 6215eba9..73f58f3e 100644 --- a/psftp.c +++ b/psftp.c @@ -117,14 +117,14 @@ char *canonify(const char *name) struct sftp_request *req; if (name[0] == '/') { - fullname = dupstr(name); + fullname = dupstr(name); } else { - const char *slash; - if (pwd[strlen(pwd) - 1] == '/') - slash = ""; - else - slash = "/"; - fullname = dupcat(pwd, slash, name, NULL); + const char *slash; + if (pwd[strlen(pwd) - 1] == '/') + slash = ""; + else + slash = "/"; + fullname = dupcat(pwd, slash, name, NULL); } req = fxp_realpath_send(fullname); @@ -132,82 +132,82 @@ char *canonify(const char *name) canonname = fxp_realpath_recv(pktin, req); if (canonname) { - sfree(fullname); - return canonname; + 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). - */ + /* + * 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; + 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] != '/'); + 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; - } + /* + * 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) { - req = fxp_realpath_send("/"); - } else { - req = fxp_realpath_send(fullname); - } - pktin = sftp_wait_for_reply(req); - canonname = fxp_realpath_recv(pktin, req); + /* + * 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) { + req = fxp_realpath_send("/"); + } else { + req = fxp_realpath_send(fullname); + } + pktin = sftp_wait_for_reply(req); + canonname = fxp_realpath_recv(pktin, req); - if (!canonname) { - /* Even that failed. Restore our best guess at the - * constructed filename and give up */ - fullname[i] = '/'; /* restore slash and last component */ - return fullname; - } + if (!canonname) { + /* Even that failed. Restore our best guess at the + * constructed filename and give up */ + fullname[i] = '/'; /* restore slash and last component */ + return fullname; + } - /* - * 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; + /* + * 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; } } @@ -243,59 +243,59 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) * subsequent FXP_OPEN will return a usable error message.) */ if (recurse) { - bool result; + bool result; req = fxp_stat_send(fname); pktin = sftp_wait_for_reply(req); - result = fxp_stat_recv(pktin, req, &attrs); + result = fxp_stat_recv(pktin, req, &attrs); - if (result && - (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) && - (attrs.permissions & 0040000)) { + if (result && + (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) && + (attrs.permissions & 0040000)) { - struct fxp_handle *dirhandle; - size_t nnames, namesize; - struct fxp_name **ournames; - struct fxp_names *names; - int i; + struct fxp_handle *dirhandle; + size_t nnames, namesize; + struct fxp_name **ournames; + struct fxp_names *names; + int i; - /* - * First, attempt to create the destination directory, - * unless it already exists. - */ - if (file_type(outfname) != FILE_TYPE_DIRECTORY && - !create_directory(outfname)) { + /* + * First, attempt to create the destination directory, + * unless it already exists. + */ + if (file_type(outfname) != FILE_TYPE_DIRECTORY && + !create_directory(outfname)) { with_stripctrl(san, outfname) printf("%s: Cannot create directory\n", san); - return false; - } + return false; + } - /* - * Now get the list of filenames in the remote - * directory. - */ + /* + * Now get the list of filenames in the remote + * directory. + */ req = fxp_opendir_send(fname); pktin = sftp_wait_for_reply(req); - dirhandle = fxp_opendir_recv(pktin, req); + dirhandle = fxp_opendir_recv(pktin, req); - if (!dirhandle) { + if (!dirhandle) { with_stripctrl(san, fname) printf("%s: unable to open directory: %s\n", san, fxp_error()); - return false; - } - nnames = namesize = 0; - ournames = NULL; - while (1) { - int i; + return false; + } + nnames = namesize = 0; + ournames = NULL; + while (1) { + int i; - req = fxp_readdir_send(dirhandle); + req = fxp_readdir_send(dirhandle); pktin = sftp_wait_for_reply(req); - names = fxp_readdir_recv(pktin, req); + names = fxp_readdir_recv(pktin, req); - if (names == NULL) { - if (fxp_error_type() == SSH_FX_EOF) - break; + if (names == NULL) { + if (fxp_error_type() == SSH_FX_EOF) + break; with_stripctrl(san, fname) printf("%s: reading directory: %s\n", san, fxp_error()); @@ -304,51 +304,51 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) pktin = sftp_wait_for_reply(req); fxp_close_recv(pktin, req); - sfree(ournames); - return false; - } - if (names->nnames == 0) { - fxp_free_names(names); - break; - } + sfree(ournames); + return false; + } + if (names->nnames == 0) { + fxp_free_names(names); + break; + } sgrowarrayn(ournames, namesize, nnames, names->nnames); - for (i = 0; i < names->nnames; i++) - if (strcmp(names->names[i].filename, ".") && - strcmp(names->names[i].filename, "..")) { - if (!vet_filename(names->names[i].filename)) { + for (i = 0; i < names->nnames; i++) + if (strcmp(names->names[i].filename, ".") && + strcmp(names->names[i].filename, "..")) { + if (!vet_filename(names->names[i].filename)) { with_stripctrl(san, names->names[i].filename) printf("ignoring potentially dangerous server-" "supplied filename '%s'\n", san); - } else { - ournames[nnames++] = - fxp_dup_name(&names->names[i]); - } - } - fxp_free_names(names); - } - req = fxp_close_send(dirhandle); + } else { + ournames[nnames++] = + fxp_dup_name(&names->names[i]); + } + } + fxp_free_names(names); + } + req = fxp_close_send(dirhandle); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); + fxp_close_recv(pktin, req); - /* - * Sort the names into a clear order. This ought to - * make things more predictable when we're doing a - * reget of the same directory, just in case two - * readdirs on the same remote directory return a - * different order. - */ + /* + * Sort the names into a clear order. This ought to + * make things more predictable when we're doing a + * reget of the same directory, just in case two + * readdirs on the same remote directory return a + * different order. + */ if (nnames > 0) qsort(ournames, nnames, sizeof(*ournames), sftp_name_compare); - /* - * If we're in restart mode, find the last filename on - * this list that already exists. We may have to do a - * reget on _that_ file, but shouldn't have to do - * anything on the previous files. - * - * If none of them exists, of course, we start at 0. - */ - i = 0; + /* + * If we're in restart mode, find the last filename on + * this list that already exists. We may have to do a + * reget on _that_ file, but shouldn't have to do + * anything on the previous files. + * + * If none of them exists, of course, we start at 0. + */ + i = 0; if (restart) { while (i < nnames) { char *nextoutfname; @@ -366,42 +366,42 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) i--; } - /* - * Now we're ready to recurse. Starting at ournames[i] - * and continuing on to the end of the list, we - * construct a new source and target file name, and - * call sftp_get_file again. - */ - for (; i < nnames; i++) { - char *nextfname, *nextoutfname; - bool retd; - - nextfname = dupcat(fname, "/", ournames[i]->filename, NULL); + /* + * Now we're ready to recurse. Starting at ournames[i] + * and continuing on to the end of the list, we + * construct a new source and target file name, and + * call sftp_get_file again. + */ + for (; i < nnames; i++) { + char *nextfname, *nextoutfname; + bool retd; + + nextfname = dupcat(fname, "/", ournames[i]->filename, NULL); nextoutfname = dir_file_cat(outfname, ournames[i]->filename); - retd = sftp_get_file( + retd = sftp_get_file( nextfname, nextoutfname, recurse, restart); - restart = false; /* after first partial file, do full */ - sfree(nextoutfname); - sfree(nextfname); - if (!retd) { - for (i = 0; i < nnames; i++) { - fxp_free_name(ournames[i]); - } - sfree(ournames); - return false; - } - } + restart = false; /* after first partial file, do full */ + sfree(nextoutfname); + sfree(nextfname); + if (!retd) { + for (i = 0; i < nnames; i++) { + fxp_free_name(ournames[i]); + } + sfree(ournames); + return false; + } + } - /* - * Done this recursion level. Free everything. - */ - for (i = 0; i < nnames; i++) { - fxp_free_name(ournames[i]); - } - sfree(ournames); + /* + * Done this recursion level. Free everything. + */ + for (i = 0; i < nnames; i++) { + fxp_free_name(ournames[i]); + } + sfree(ournames); - return true; - } + return true; + } } req = fxp_stat_send(fname); @@ -416,13 +416,13 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) if (!fh) { with_stripctrl(san, fname) printf("%s: open for read: %s\n", san, fxp_error()); - return false; + return false; } if (restart) { - file = open_existing_wfile(outfname, NULL); + file = open_existing_wfile(outfname, NULL); } else { - file = open_new_file(outfname, GET_PERMISSIONS(attrs, -1)); + file = open_new_file(outfname, GET_PERMISSIONS(attrs, -1)); } if (!file) { @@ -431,27 +431,27 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) req = fxp_close_send(fh); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); + fxp_close_recv(pktin, req); - return false; + return false; } if (restart) { - if (seek_file(file, 0, FROM_END) == -1) { - close_wfile(file); + if (seek_file(file, 0, FROM_END) == -1) { + close_wfile(file); with_stripctrl(san, outfname) printf("reget: cannot restart %s - file too large\n", san); - req = fxp_close_send(fh); + req = fxp_close_send(fh); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); - - return false; - } - - offset = get_file_posn(file); - printf("reget: restarting at file position %"PRIu64"\n", offset); + fxp_close_recv(pktin, req); + + return false; + } + + offset = get_file_posn(file); + printf("reget: restarting at file position %"PRIu64"\n", offset); } else { - offset = 0; + offset = 0; } with_stripctrl(san, fname) { @@ -466,44 +466,44 @@ bool sftp_get_file(char *fname, char *outfname, bool recurse, bool restart) toret = true; xfer = xfer_download_init(fh, offset); while (!xfer_done(xfer)) { - void *vbuf; - int retd, len; - int wpos, wlen; + void *vbuf; + int retd, len; + int wpos, wlen; - xfer_download_queue(xfer); - pktin = sftp_recv(); - retd = xfer_download_gotpkt(xfer, pktin); - if (retd <= 0) { - if (!shown_err) { - printf("error while reading: %s\n", fxp_error()); - shown_err = true; - } + xfer_download_queue(xfer); + pktin = sftp_recv(); + retd = xfer_download_gotpkt(xfer, pktin); + if (retd <= 0) { + if (!shown_err) { + printf("error while reading: %s\n", fxp_error()); + shown_err = true; + } if (retd == INT_MIN) /* pktin not even freed */ sfree(pktin); toret = false; - } + } - while (xfer_download_data(xfer, &vbuf, &len)) { - unsigned char *buf = (unsigned char *)vbuf; + while (xfer_download_data(xfer, &vbuf, &len)) { + unsigned char *buf = (unsigned char *)vbuf; - wpos = 0; - while (wpos < len) { - wlen = write_to_file(file, buf + wpos, len - wpos); - if (wlen <= 0) { - printf("error while writing local file\n"); - toret = false; - xfer_set_error(xfer); - break; - } - wpos += wlen; - } - if (wpos < len) { /* we had an error */ - toret = false; - xfer_set_error(xfer); - } + wpos = 0; + while (wpos < len) { + wlen = write_to_file(file, buf + wpos, len - wpos); + if (wlen <= 0) { + printf("error while writing local file\n"); + toret = false; + xfer_set_error(xfer); + break; + } + wpos += wlen; + } + if (wpos < len) { /* we had an error */ + toret = false; + xfer_set_error(xfer); + } - sfree(vbuf); - } + sfree(vbuf); + } } xfer_cleanup(xfer); @@ -535,69 +535,69 @@ bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart) * subsequent fopen will return an error message.) */ if (recurse && file_type(fname) == FILE_TYPE_DIRECTORY) { - bool result; - size_t nnames, namesize; - char *name, **ournames; + bool result; + size_t nnames, namesize; + char *name, **ournames; const char *opendir_err; - DirHandle *dh; + DirHandle *dh; size_t i; - /* - * First, attempt to create the destination directory, - * unless it already exists. - */ - req = fxp_stat_send(outfname); + /* + * First, attempt to create the destination directory, + * unless it already exists. + */ + req = fxp_stat_send(outfname); pktin = sftp_wait_for_reply(req); - result = fxp_stat_recv(pktin, req, &attrs); - if (!result || - !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) || - !(attrs.permissions & 0040000)) { - req = fxp_mkdir_send(outfname, NULL); + result = fxp_stat_recv(pktin, req, &attrs); + if (!result || + !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) || + !(attrs.permissions & 0040000)) { + req = fxp_mkdir_send(outfname, NULL); pktin = sftp_wait_for_reply(req); - result = fxp_mkdir_recv(pktin, req); + result = fxp_mkdir_recv(pktin, req); - if (!result) { - printf("%s: create directory: %s\n", - outfname, fxp_error()); - return false; - } - } + if (!result) { + printf("%s: create directory: %s\n", + outfname, fxp_error()); + return false; + } + } - /* - * Now get the list of filenames in the local directory. - */ - nnames = namesize = 0; - ournames = NULL; + /* + * Now get the list of filenames in the local directory. + */ + nnames = namesize = 0; + ournames = NULL; - dh = open_directory(fname, &opendir_err); - if (!dh) { - printf("%s: unable to open directory: %s\n", fname, opendir_err); - return false; - } - while ((name = read_filename(dh)) != NULL) { + dh = open_directory(fname, &opendir_err); + if (!dh) { + printf("%s: unable to open directory: %s\n", fname, opendir_err); + return false; + } + while ((name = read_filename(dh)) != NULL) { sgrowarray(ournames, namesize, nnames); - ournames[nnames++] = name; - } - close_directory(dh); + ournames[nnames++] = name; + } + close_directory(dh); - /* - * Sort the names into a clear order. This ought to make - * things more predictable when we're doing a reput of the - * same directory, just in case two readdirs on the same - * local directory return a different order. - */ + /* + * Sort the names into a clear order. This ought to make + * things more predictable when we're doing a reput of the + * same directory, just in case two readdirs on the same + * local directory return a different order. + */ if (nnames > 0) qsort(ournames, nnames, sizeof(*ournames), bare_name_compare); - /* - * If we're in restart mode, find the last filename on this - * list that already exists. We may have to do a reput on - * _that_ file, but shouldn't have to do anything on the - * previous files. - * - * If none of them exists, of course, we start at 0. - */ - i = 0; + /* + * If we're in restart mode, find the last filename on this + * list that already exists. We may have to do a reput on + * _that_ file, but shouldn't have to do anything on the + * previous files. + * + * If none of them exists, of course, we start at 0. + */ + i = 0; if (restart) { while (i < nnames) { char *nextoutfname; @@ -616,51 +616,51 @@ bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart) /* * Now we're ready to recurse. Starting at ournames[i] - * and continuing on to the end of the list, we - * construct a new source and target file name, and - * call sftp_put_file again. - */ - for (; i < nnames; i++) { - char *nextfname, *nextoutfname; + * and continuing on to the end of the list, we + * construct a new source and target file name, and + * call sftp_put_file again. + */ + for (; i < nnames; i++) { + char *nextfname, *nextoutfname; bool retd; nextfname = dir_file_cat(fname, ournames[i]); - nextoutfname = dupcat(outfname, "/", ournames[i], NULL); - retd = sftp_put_file(nextfname, nextoutfname, recurse, restart); - restart = false; /* after first partial file, do full */ - sfree(nextoutfname); - sfree(nextfname); - if (!retd) { - for (size_t i = 0; i < nnames; i++) { - sfree(ournames[i]); - } - sfree(ournames); - return false; - } - } + nextoutfname = dupcat(outfname, "/", ournames[i], NULL); + retd = sftp_put_file(nextfname, nextoutfname, recurse, restart); + restart = false; /* after first partial file, do full */ + sfree(nextoutfname); + sfree(nextfname); + if (!retd) { + for (size_t i = 0; i < nnames; i++) { + sfree(ournames[i]); + } + sfree(ournames); + return false; + } + } - /* - * Done this recursion level. Free everything. - */ - for (size_t i = 0; i < nnames; i++) { - sfree(ournames[i]); - } - sfree(ournames); + /* + * Done this recursion level. Free everything. + */ + for (size_t i = 0; i < nnames; i++) { + sfree(ournames[i]); + } + sfree(ournames); - return true; + return true; } file = open_existing_file(fname, NULL, NULL, NULL, &permissions); if (!file) { - printf("local: unable to open %s\n", fname); - return false; + printf("local: unable to open %s\n", fname); + return false; } attrs.flags = 0; PUT_PERMISSIONS(attrs, permissions); if (restart) { - req = fxp_open_send(outfname, SSH_FXF_WRITE, &attrs); + req = fxp_open_send(outfname, SSH_FXF_WRITE, &attrs); } else { - req = fxp_open_send(outfname, + req = fxp_open_send(outfname, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC, &attrs); } @@ -668,34 +668,34 @@ bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart) fh = fxp_open_recv(pktin, req); if (!fh) { - close_rfile(file); - printf("%s: open for write: %s\n", outfname, fxp_error()); - return false; + close_rfile(file); + printf("%s: open for write: %s\n", outfname, fxp_error()); + return false; } if (restart) { - struct fxp_attrs attrs; + struct fxp_attrs attrs; bool retd; - req = fxp_fstat_send(fh); + req = fxp_fstat_send(fh); pktin = sftp_wait_for_reply(req); - retd = fxp_fstat_recv(pktin, req, &attrs); + retd = fxp_fstat_recv(pktin, req, &attrs); - if (!retd) { - printf("read size of %s: %s\n", outfname, fxp_error()); - err = true; + if (!retd) { + printf("read size of %s: %s\n", outfname, fxp_error()); + err = true; goto cleanup; - } - if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) { - printf("read size of %s: size was not given\n", outfname); - err = true; + } + if (!(attrs.flags & SSH_FILEXFER_ATTR_SIZE)) { + printf("read size of %s: size was not given\n", outfname); + err = true; goto cleanup; - } - offset = attrs.size; - printf("reput: restarting at file position %"PRIu64"\n", offset); + } + offset = attrs.size; + printf("reput: restarting at file position %"PRIu64"\n", offset); - if (seek_file((WFile *)file, offset, FROM_START) != 0) - seek_file((WFile *)file, 0, FROM_END); /* *shrug* */ + if (seek_file((WFile *)file, offset, FROM_START) != 0) + seek_file((WFile *)file, 0, FROM_END); /* *shrug* */ } else { offset = 0; } @@ -709,33 +709,33 @@ bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart) xfer = xfer_upload_init(fh, offset); eof = false; while ((!err && !eof) || !xfer_done(xfer)) { - char buffer[4096]; - int len, ret; + char buffer[4096]; + int len, ret; - while (xfer_upload_ready(xfer) && !err && !eof) { - len = read_from_file(file, buffer, sizeof(buffer)); - if (len == -1) { - printf("error while reading local file\n"); - err = true; - } else if (len == 0) { - eof = true; - } else { - xfer_upload_data(xfer, buffer, len); - } - } + while (xfer_upload_ready(xfer) && !err && !eof) { + len = read_from_file(file, buffer, sizeof(buffer)); + if (len == -1) { + printf("error while reading local file\n"); + err = true; + } else if (len == 0) { + eof = true; + } else { + xfer_upload_data(xfer, buffer, len); + } + } - if (!xfer_done(xfer)) { - pktin = sftp_recv(); - ret = xfer_upload_gotpkt(xfer, pktin); - if (ret <= 0) { + if (!xfer_done(xfer)) { + pktin = sftp_recv(); + ret = xfer_upload_gotpkt(xfer, pktin); + if (ret <= 0) { if (ret == INT_MIN) /* pktin not even freed */ sfree(pktin); if (!err) { printf("error while writing: %s\n", fxp_error()); err = true; } - } - } + } + } } xfer_cleanup(xfer); @@ -744,10 +744,10 @@ bool sftp_put_file(char *fname, char *outfname, bool recurse, bool restart) req = fxp_close_send(fh); pktin = sftp_wait_for_reply(req); if (!fxp_close_recv(pktin, req)) { - if (!err) { - printf("error while closing: %s", fxp_error()); - err = true; - } + if (!err) { + printf("error while closing: %s", fxp_error()); + err = true; + } } close_rfile(file); @@ -789,15 +789,15 @@ SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name) len = wildcard - name; unwcdir[len] = '\0'; if (len > 0 && unwcdir[len-1] == '/') - unwcdir[len-1] = '\0'; + unwcdir[len-1] = '\0'; tmpdir = snewn(1 + len, char); check = wc_unescape(tmpdir, unwcdir); sfree(tmpdir); if (!check) { - printf("Multiple-level wildcards are not supported\n"); - sfree(unwcdir); - return NULL; + printf("Multiple-level wildcards are not supported\n"); + sfree(unwcdir); + return NULL; } cdir = canonify(unwcdir); @@ -807,15 +807,15 @@ SftpWildcardMatcher *sftp_begin_wildcard_matching(char *name) dirh = fxp_opendir_recv(pktin, req); if (dirh) { - swcm = snew(SftpWildcardMatcher); - swcm->dirh = dirh; - swcm->names = NULL; - swcm->wildcard = dupstr(wildcard); - swcm->prefix = unwcdir; + swcm = snew(SftpWildcardMatcher); + swcm->dirh = dirh; + swcm->names = NULL; + swcm->wildcard = dupstr(wildcard); + swcm->prefix = unwcdir; } else { - printf("Unable to open %s: %s\n", cdir, fxp_error()); - swcm = NULL; - sfree(unwcdir); + printf("Unable to open %s: %s\n", cdir, fxp_error()); + swcm = NULL; + sfree(unwcdir); } sfree(cdir); @@ -830,24 +830,24 @@ char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm) struct sftp_request *req; while (1) { - if (swcm->names && swcm->namepos >= swcm->names->nnames) { - fxp_free_names(swcm->names); - swcm->names = NULL; - } + if (swcm->names && swcm->namepos >= swcm->names->nnames) { + fxp_free_names(swcm->names); + swcm->names = NULL; + } - if (!swcm->names) { - req = fxp_readdir_send(swcm->dirh); + if (!swcm->names) { + req = fxp_readdir_send(swcm->dirh); pktin = sftp_wait_for_reply(req); - swcm->names = fxp_readdir_recv(pktin, req); + swcm->names = fxp_readdir_recv(pktin, req); - if (!swcm->names) { - if (fxp_error_type() != SSH_FX_EOF) { + if (!swcm->names) { + if (fxp_error_type() != SSH_FX_EOF) { with_stripctrl(san, swcm->prefix) printf("%s: reading directory: %s\n", san, fxp_error()); } - return NULL; - } else if (swcm->names->nnames == 0) { + return NULL; + } else if (swcm->names->nnames == 0) { /* * Another failure mode which we treat as EOF is if * the server reports success from FXP_READDIR but @@ -859,34 +859,34 @@ char *sftp_wildcard_get_filename(SftpWildcardMatcher *swcm) return NULL; } - swcm->namepos = 0; - } + swcm->namepos = 0; + } - assert(swcm->names && swcm->namepos < swcm->names->nnames); + assert(swcm->names && swcm->namepos < swcm->names->nnames); - name = &swcm->names->names[swcm->namepos++]; + name = &swcm->names->names[swcm->namepos++]; - if (!strcmp(name->filename, ".") || !strcmp(name->filename, "..")) - continue; /* expected bad filenames */ + if (!strcmp(name->filename, ".") || !strcmp(name->filename, "..")) + continue; /* expected bad filenames */ - if (!vet_filename(name->filename)) { + if (!vet_filename(name->filename)) { with_stripctrl(san, name->filename) printf("ignoring potentially dangerous server-" "supplied filename '%s'\n", san); - continue; /* unexpected bad filename */ - } + continue; /* unexpected bad filename */ + } - if (!wc_match(swcm->wildcard, name->filename)) - continue; /* doesn't match the wildcard */ + if (!wc_match(swcm->wildcard, name->filename)) + continue; /* doesn't match the wildcard */ - /* - * We have a working filename. Return it. - */ - return dupprintf("%s%s%s", swcm->prefix, - (!swcm->prefix[0] || - swcm->prefix[strlen(swcm->prefix)-1]=='/' ? - "" : "/"), - name->filename); + /* + * We have a working filename. Return it. + */ + return dupprintf("%s%s%s", swcm->prefix, + (!swcm->prefix[0] || + swcm->prefix[strlen(swcm->prefix)-1]=='/' ? + "" : "/"), + name->filename); } } @@ -900,7 +900,7 @@ void sftp_finish_wildcard_matching(SftpWildcardMatcher *swcm) fxp_close_recv(pktin, req); if (swcm->names) - fxp_free_names(swcm->names); + fxp_free_names(swcm->names); sfree(swcm->prefix); sfree(swcm->wildcard); @@ -922,35 +922,35 @@ bool wildcard_iterate(char *filename, bool (*func)(void *, char *), void *ctx) is_wc = !wc_unescape(unwcfname, filename); if (is_wc) { - SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename); - bool matched = false; - sfree(unwcfname); + SftpWildcardMatcher *swcm = sftp_begin_wildcard_matching(filename); + bool matched = false; + sfree(unwcfname); - if (!swcm) - return false; + if (!swcm) + return false; - toret = true; + toret = true; - while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) { - cname = canonify(newname); + while ( (newname = sftp_wildcard_get_filename(swcm)) != NULL ) { + cname = canonify(newname); sfree(newname); - matched = true; + matched = true; if (!func(ctx, cname)) toret = false; - sfree(cname); - } + sfree(cname); + } - if (!matched) { - /* Politely warn the user that nothing matched. */ - printf("%s: nothing matched\n", filename); - } + if (!matched) { + /* Politely warn the user that nothing matched. */ + printf("%s: nothing matched\n", filename); + } - sftp_finish_wildcard_matching(swcm); + sftp_finish_wildcard_matching(swcm); } else { - cname = canonify(unwcfname); - toret = func(ctx, cname); - sfree(cname); - sfree(unwcfname); + cname = canonify(unwcfname); + toret = func(ctx, cname); + sfree(cname); + sfree(unwcfname); } return toret; @@ -973,18 +973,18 @@ bool is_wildcard(char *name) struct sftp_command { char **words; size_t 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) { - return 1; /* success */ + return 1; /* success */ } int sftp_cmd_unknown(struct sftp_command *cmd) { printf("psftp: unknown command \"%s\"\n", cmd->words[0]); - return 0; /* failure */ + return 0; /* failure */ } int sftp_cmd_quit(struct sftp_command *cmd) @@ -995,15 +995,15 @@ int sftp_cmd_quit(struct sftp_command *cmd) int sftp_cmd_close(struct sftp_command *cmd) { if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (backend_connected(backend)) { - char ch; + char ch; backend_special(backend, SS_EOF, 0); sent_eof = true; - sftp_recvdata(&ch, 1); + sftp_recvdata(&ch, 1); } do_sftp_cleanup(); @@ -1035,40 +1035,40 @@ int sftp_cmd_ls(struct sftp_command *cmd) struct sftp_request *req; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 2) - dir = "."; + dir = "."; else - dir = cmd->words[1]; + dir = cmd->words[1]; unwcdir = snewn(1 + strlen(dir), char); if (wc_unescape(unwcdir, dir)) { - dir = unwcdir; - wildcard = NULL; + dir = unwcdir; + wildcard = NULL; } else { - char *tmpdir; - int len; + char *tmpdir; + int len; bool check; sfree(unwcdir); - wildcard = stripslashes(dir, false); - unwcdir = dupstr(dir); - len = wildcard - dir; - unwcdir[len] = '\0'; - if (len > 0 && unwcdir[len-1] == '/') - unwcdir[len-1] = '\0'; - tmpdir = snewn(1 + len, char); - check = wc_unescape(tmpdir, unwcdir); - sfree(tmpdir); - if (!check) { - printf("Multiple-level wildcards are not supported\n"); - sfree(unwcdir); - return 0; - } - dir = unwcdir; + wildcard = stripslashes(dir, false); + unwcdir = dupstr(dir); + len = wildcard - dir; + unwcdir[len] = '\0'; + if (len > 0 && unwcdir[len-1] == '/') + unwcdir[len-1] = '\0'; + tmpdir = snewn(1 + len, char); + check = wc_unescape(tmpdir, unwcdir); + sfree(tmpdir); + if (!check) { + printf("Multiple-level wildcards are not supported\n"); + sfree(unwcdir); + return 0; + } + dir = unwcdir; } cdir = canonify(dir); @@ -1081,41 +1081,41 @@ int sftp_cmd_ls(struct sftp_command *cmd) dirh = fxp_opendir_recv(pktin, req); if (dirh == NULL) { - printf("Unable to open %s: %s\n", dir, fxp_error()); - sfree(cdir); - sfree(unwcdir); - return 0; + printf("Unable to open %s: %s\n", dir, fxp_error()); + sfree(cdir); + sfree(unwcdir); + return 0; } else { struct list_directory_from_sftp_ctx *ctx = list_directory_from_sftp_new(); - while (1) { + while (1) { - req = fxp_readdir_send(dirh); + req = fxp_readdir_send(dirh); pktin = sftp_wait_for_reply(req); - names = fxp_readdir_recv(pktin, req); + names = fxp_readdir_recv(pktin, req); - if (names == NULL) { - if (fxp_error_type() == SSH_FX_EOF) - break; - printf("Reading directory %s: %s\n", dir, fxp_error()); - break; - } - if (names->nnames == 0) { - fxp_free_names(names); - break; - } + if (names == NULL) { + if (fxp_error_type() == SSH_FX_EOF) + break; + printf("Reading directory %s: %s\n", dir, fxp_error()); + break; + } + if (names->nnames == 0) { + fxp_free_names(names); + break; + } - for (size_t i = 0; i < names->nnames; i++) - if (!wildcard || wc_match(wildcard, names->names[i].filename)) + for (size_t i = 0; i < names->nnames; i++) + if (!wildcard || wc_match(wildcard, names->names[i].filename)) list_directory_from_sftp_feed(ctx, &names->names[i]); - fxp_free_names(names); - } + fxp_free_names(names); + } - req = fxp_close_send(dirh); + req = fxp_close_send(dirh); pktin = sftp_wait_for_reply(req); - fxp_close_recv(pktin, req); + fxp_close_recv(pktin, req); list_directory_from_sftp_finish(ctx); list_directory_from_sftp_free(ctx); @@ -1139,14 +1139,14 @@ int sftp_cmd_cd(struct sftp_command *cmd) char *dir; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 2) - dir = dupstr(homedir); + dir = dupstr(homedir); else { - dir = canonify(cmd->words[1]); + dir = canonify(cmd->words[1]); } req = fxp_opendir_send(dir); @@ -1156,8 +1156,8 @@ int sftp_cmd_cd(struct sftp_command *cmd) if (!dirh) { with_stripctrl(san, dir) printf("Directory %s: %s\n", san, fxp_error()); - sfree(dir); - return 0; + sfree(dir); + return 0; } req = fxp_close_send(dirh); @@ -1178,8 +1178,8 @@ int sftp_cmd_cd(struct sftp_command *cmd) int sftp_cmd_pwd(struct sftp_command *cmd) { if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } with_stripctrl(san, pwd) @@ -1203,80 +1203,80 @@ int sftp_general_get(struct sftp_command *cmd, bool restart, bool multiple) bool recurse = false; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } i = 1; while (i < cmd->nwords && cmd->words[i][0] == '-') { - if (!strcmp(cmd->words[i], "--")) { - /* finish processing options */ - i++; - break; - } else if (!strcmp(cmd->words[i], "-r")) { - recurse = true; - } else { - printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]); - return 0; - } - i++; + if (!strcmp(cmd->words[i], "--")) { + /* finish processing options */ + i++; + break; + } else if (!strcmp(cmd->words[i], "-r")) { + recurse = true; + } else { + printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]); + return 0; + } + i++; } if (i >= cmd->nwords) { - printf("%s: expects a filename\n", cmd->words[0]); - return 0; + printf("%s: expects a filename\n", cmd->words[0]); + return 0; } toret = 1; do { - SftpWildcardMatcher *swcm; + SftpWildcardMatcher *swcm; - origfname = cmd->words[i++]; - unwcfname = snewn(strlen(origfname)+1, char); + origfname = cmd->words[i++]; + unwcfname = snewn(strlen(origfname)+1, char); - if (multiple && !wc_unescape(unwcfname, origfname)) { - swcm = sftp_begin_wildcard_matching(origfname); - if (!swcm) { - sfree(unwcfname); - continue; - } - origwfname = sftp_wildcard_get_filename(swcm); - if (!origwfname) { - /* Politely warn the user that nothing matched. */ - printf("%s: nothing matched\n", origfname); - sftp_finish_wildcard_matching(swcm); - sfree(unwcfname); - continue; - } - } else { - origwfname = origfname; - swcm = NULL; - } + if (multiple && !wc_unescape(unwcfname, origfname)) { + swcm = sftp_begin_wildcard_matching(origfname); + if (!swcm) { + sfree(unwcfname); + continue; + } + origwfname = sftp_wildcard_get_filename(swcm); + if (!origwfname) { + /* Politely warn the user that nothing matched. */ + printf("%s: nothing matched\n", origfname); + sftp_finish_wildcard_matching(swcm); + sfree(unwcfname); + continue; + } + } else { + origwfname = origfname; + swcm = NULL; + } - while (origwfname) { - fname = canonify(origwfname); + while (origwfname) { + fname = canonify(origwfname); - if (!multiple && i < cmd->nwords) - outfname = cmd->words[i++]; - else - outfname = stripslashes(origwfname, false); + if (!multiple && i < cmd->nwords) + outfname = cmd->words[i++]; + else + outfname = stripslashes(origwfname, false); - toret = sftp_get_file(fname, outfname, recurse, restart); + toret = sftp_get_file(fname, outfname, recurse, restart); - sfree(fname); + sfree(fname); - if (swcm) { - sfree(origwfname); - origwfname = sftp_wildcard_get_filename(swcm); - } else { - origwfname = NULL; - } - } - sfree(unwcfname); - if (swcm) - sftp_finish_wildcard_matching(swcm); - if (!toret) - return toret; + if (swcm) { + sfree(origwfname); + origwfname = sftp_wildcard_get_filename(swcm); + } else { + origwfname = NULL; + } + } + sfree(unwcfname); + if (swcm) + sftp_finish_wildcard_matching(swcm); + if (!toret) + return toret; } while (multiple && i < cmd->nwords); @@ -1312,72 +1312,72 @@ int sftp_general_put(struct sftp_command *cmd, bool restart, bool multiple) bool recurse = false; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } i = 1; while (i < cmd->nwords && cmd->words[i][0] == '-') { - if (!strcmp(cmd->words[i], "--")) { - /* finish processing options */ - i++; - break; - } else if (!strcmp(cmd->words[i], "-r")) { - recurse = true; - } else { - printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]); - return 0; - } - i++; + if (!strcmp(cmd->words[i], "--")) { + /* finish processing options */ + i++; + break; + } else if (!strcmp(cmd->words[i], "-r")) { + recurse = true; + } else { + printf("%s: unrecognised option '%s'\n", cmd->words[0], cmd->words[i]); + return 0; + } + i++; } if (i >= cmd->nwords) { - printf("%s: expects a filename\n", cmd->words[0]); - return 0; + printf("%s: expects a filename\n", cmd->words[0]); + return 0; } toret = 1; do { - WildcardMatcher *wcm; - fname = cmd->words[i++]; + WildcardMatcher *wcm; + fname = cmd->words[i++]; - if (multiple && test_wildcard(fname, false) == WCTYPE_WILDCARD) { - wcm = begin_wildcard_matching(fname); - wfname = wildcard_get_filename(wcm); - if (!wfname) { - /* Politely warn the user that nothing matched. */ - printf("%s: nothing matched\n", fname); - finish_wildcard_matching(wcm); - continue; - } - } else { - wfname = fname; - wcm = NULL; - } + if (multiple && test_wildcard(fname, false) == WCTYPE_WILDCARD) { + wcm = begin_wildcard_matching(fname); + wfname = wildcard_get_filename(wcm); + if (!wfname) { + /* Politely warn the user that nothing matched. */ + printf("%s: nothing matched\n", fname); + finish_wildcard_matching(wcm); + continue; + } + } else { + wfname = fname; + wcm = NULL; + } - while (wfname) { - if (!multiple && i < cmd->nwords) - origoutfname = cmd->words[i++]; - else - origoutfname = stripslashes(wfname, true); + while (wfname) { + if (!multiple && i < cmd->nwords) + origoutfname = cmd->words[i++]; + else + origoutfname = stripslashes(wfname, true); - outfname = canonify(origoutfname); - toret = sftp_put_file(wfname, outfname, recurse, restart); - sfree(outfname); + outfname = canonify(origoutfname); + toret = sftp_put_file(wfname, outfname, recurse, restart); + sfree(outfname); - if (wcm) { - sfree(wfname); - wfname = wildcard_get_filename(wcm); - } else { - wfname = NULL; - } - } + if (wcm) { + sfree(wfname); + wfname = wildcard_get_filename(wcm); + } else { + wfname = NULL; + } + } - if (wcm) - finish_wildcard_matching(wcm); + if (wcm) + finish_wildcard_matching(wcm); - if (!toret) - return toret; + if (!toret) + return toret; } while (multiple && i < cmd->nwords); @@ -1405,32 +1405,32 @@ int sftp_cmd_mkdir(struct sftp_command *cmd) int i, ret; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 2) { - printf("mkdir: expects a directory\n"); - return 0; + printf("mkdir: expects a directory\n"); + return 0; } ret = 1; for (i = 1; i < cmd->nwords; i++) { - dir = canonify(cmd->words[i]); + dir = canonify(cmd->words[i]); - req = fxp_mkdir_send(dir, NULL); + req = fxp_mkdir_send(dir, NULL); pktin = sftp_wait_for_reply(req); - result = fxp_mkdir_recv(pktin, req); + result = fxp_mkdir_recv(pktin, req); - if (!result) { + if (!result) { with_stripctrl(san, dir) printf("mkdir %s: %s\n", san, fxp_error()); - ret = 0; - } else + ret = 0; + } else with_stripctrl(san, dir) printf("mkdir %s: OK\n", san); - sfree(dir); + sfree(dir); } return ret; @@ -1447,8 +1447,8 @@ static bool sftp_action_rmdir(void *vctx, char *dir) result = fxp_rmdir_recv(pktin, req); if (!result) { - printf("rmdir %s: %s\n", dir, fxp_error()); - return false; + printf("rmdir %s: %s\n", dir, fxp_error()); + return false; } printf("rmdir %s: OK\n", dir); @@ -1461,18 +1461,18 @@ int sftp_cmd_rmdir(struct sftp_command *cmd) int i, ret; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 2) { - printf("rmdir: expects a directory\n"); - return 0; + printf("rmdir: expects a directory\n"); + return 0; } ret = 1; for (i = 1; i < cmd->nwords; i++) - ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL); + ret &= wildcard_iterate(cmd->words[i], sftp_action_rmdir, NULL); return ret; } @@ -1488,8 +1488,8 @@ static bool sftp_action_rm(void *vctx, char *fname) result = fxp_remove_recv(pktin, req); if (!result) { - printf("rm %s: %s\n", fname, fxp_error()); - return false; + printf("rm %s: %s\n", fname, fxp_error()); + return false; } printf("rm %s: OK\n", fname); @@ -1502,18 +1502,18 @@ int sftp_cmd_rm(struct sftp_command *cmd) int i, ret; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 2) { - printf("rm: expects a filename\n"); - return 0; + printf("rm: expects a filename\n"); + return 0; } ret = 1; for (i = 1; i < cmd->nwords; i++) - ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL); + ret &= wildcard_iterate(cmd->words[i], sftp_action_rm, NULL); return ret; } @@ -1530,11 +1530,11 @@ static bool check_is_dir(char *dstfname) result = fxp_stat_recv(pktin, req, &attrs); if (result && - (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) && - (attrs.permissions & 0040000)) - return true; + (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) && + (attrs.permissions & 0040000)) + return true; else - return false; + return false; } struct sftp_context_mv { @@ -1552,18 +1552,18 @@ static bool sftp_action_mv(void *vctx, char *srcfname) bool toret, result; if (ctx->dest_is_dir) { - char *p; - char *newname; + char *p; + char *newname; - p = srcfname + strlen(srcfname); - while (p > srcfname && p[-1] != '/') p--; - newname = dupcat(ctx->dstfname, "/", p, NULL); - newcanon = canonify(newname); - sfree(newname); + p = srcfname + strlen(srcfname); + while (p > srcfname && p[-1] != '/') p--; + newname = dupcat(ctx->dstfname, "/", p, NULL); + newcanon = canonify(newname); + sfree(newname); - finalfname = newcanon; + finalfname = newcanon; } else { - finalfname = ctx->dstfname; + finalfname = ctx->dstfname; } req = fxp_rename_send(srcfname, finalfname); @@ -1575,11 +1575,11 @@ static bool sftp_action_mv(void *vctx, char *srcfname) if (error) { with_stripctrl(san, finalfname) printf("mv %s %s: %s\n", srcfname, san, error); - toret = false; + toret = false; } else { with_stripctrl(san, finalfname) printf("%s -> %s\n", srcfname, san); - toret = true; + toret = true; } sfree(newcanon); @@ -1592,13 +1592,13 @@ int sftp_cmd_mv(struct sftp_command *cmd) int i, ret; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 3) { - printf("mv: expects two filenames\n"); - return 0; + printf("mv: expects two filenames\n"); + return 0; } ctx->dstfname = canonify(cmd->words[cmd->nwords-1]); @@ -1610,10 +1610,10 @@ int sftp_cmd_mv(struct sftp_command *cmd) */ ctx->dest_is_dir = check_is_dir(ctx->dstfname); if ((cmd->nwords > 3 || is_wildcard(cmd->words[1])) && !ctx->dest_is_dir) { - printf("mv: multiple or wildcard arguments require the destination" - " to be a directory\n"); - sfree(ctx->dstfname); - return 0; + printf("mv: multiple or wildcard arguments require the destination" + " to be a directory\n"); + sfree(ctx->dstfname); + return 0; } /* @@ -1621,7 +1621,7 @@ int sftp_cmd_mv(struct sftp_command *cmd) */ ret = 1; for (i = 1; i < cmd->nwords-1; i++) - ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx); + ret &= wildcard_iterate(cmd->words[i], sftp_action_mv, ctx); sfree(ctx->dstfname); return ret; @@ -1645,9 +1645,9 @@ static bool sftp_action_chmod(void *vctx, char *fname) result = fxp_stat_recv(pktin, req, &attrs); if (!result || !(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) { - printf("get attrs for %s: %s\n", fname, - result ? "file permissions not provided" : fxp_error()); - return false; + printf("get attrs for %s: %s\n", fname, + result ? "file permissions not provided" : fxp_error()); + return false; } attrs.flags = SSH_FILEXFER_ATTR_PERMISSIONS; /* perms _only_ */ @@ -1657,15 +1657,15 @@ static bool sftp_action_chmod(void *vctx, char *fname) newperms = attrs.permissions & 07777; if (oldperms == newperms) - return true; /* no need to do anything! */ + return true; /* no need to do anything! */ req = fxp_setstat_send(fname, attrs); pktin = sftp_wait_for_reply(req); result = fxp_setstat_recv(pktin, req); if (!result) { - printf("set attrs for %s: %s\n", fname, fxp_error()); - return false; + printf("set attrs for %s: %s\n", fname, fxp_error()); + return false; } printf("%s: %04o -> %04o\n", fname, oldperms, newperms); @@ -1680,13 +1680,13 @@ int sftp_cmd_chmod(struct sftp_command *cmd) struct sftp_context_chmod actx, *ctx = &actx; if (!backend) { - not_connected(); - return 0; + not_connected(); + return 0; } if (cmd->nwords < 3) { - printf("chmod: expects a mode specifier and a filename\n"); - return 0; + printf("chmod: expects a mode specifier and a filename\n"); + return 0; } /* @@ -1703,100 +1703,100 @@ int sftp_cmd_chmod(struct sftp_command *cmd) ctx->attrs_clr = ctx->attrs_xor = 0; mode = cmd->words[1]; if (mode[0] >= '0' && mode[0] <= '9') { - if (mode[strspn(mode, "01234567")]) { - printf("chmod: numeric file modes should" - " contain digits 0-7 only\n"); - return 0; - } - ctx->attrs_clr = 07777; - sscanf(mode, "%o", &ctx->attrs_xor); - ctx->attrs_xor &= ctx->attrs_clr; + if (mode[strspn(mode, "01234567")]) { + printf("chmod: numeric file modes should" + " contain digits 0-7 only\n"); + return 0; + } + ctx->attrs_clr = 07777; + sscanf(mode, "%o", &ctx->attrs_xor); + ctx->attrs_xor &= ctx->attrs_clr; } else { - while (*mode) { - char *modebegin = mode; - unsigned subset, perms; - int action; + while (*mode) { + char *modebegin = mode; + unsigned subset, perms; + int action; - subset = 0; - while (*mode && *mode != ',' && - *mode != '+' && *mode != '-' && *mode != '=') { - switch (*mode) { - case 'u': subset |= 04700; break; /* setuid, user perms */ - case 'g': subset |= 02070; break; /* setgid, group perms */ - case 'o': subset |= 00007; break; /* just other perms */ - case 'a': subset |= 06777; break; /* all of the above */ - default: - printf("chmod: file mode '%.*s' contains unrecognised" - " user/group/other specifier '%c'\n", - (int)strcspn(modebegin, ","), modebegin, *mode); - return 0; - } - mode++; - } - if (!*mode || *mode == ',') { - printf("chmod: file mode '%.*s' is incomplete\n", - (int)strcspn(modebegin, ","), modebegin); - return 0; - } - action = *mode++; - if (!*mode || *mode == ',') { - printf("chmod: file mode '%.*s' is incomplete\n", - (int)strcspn(modebegin, ","), modebegin); - return 0; - } - perms = 0; - while (*mode && *mode != ',') { - switch (*mode) { - case 'r': perms |= 00444; break; - case 'w': perms |= 00222; break; - case 'x': perms |= 00111; break; - case 't': perms |= 01000; subset |= 01000; break; - case 's': - if ((subset & 06777) != 04700 && - (subset & 06777) != 02070) { - printf("chmod: file mode '%.*s': set[ug]id bit should" - " be used with exactly one of u or g only\n", - (int)strcspn(modebegin, ","), modebegin); - return 0; - } - perms |= 06000; - break; - default: - printf("chmod: file mode '%.*s' contains unrecognised" - " permission specifier '%c'\n", - (int)strcspn(modebegin, ","), modebegin, *mode); - return 0; - } - mode++; - } - if (!(subset & 06777) && (perms &~ subset)) { - printf("chmod: file mode '%.*s' contains no user/group/other" - " specifier and permissions other than 't' \n", - (int)strcspn(modebegin, ","), modebegin); - return 0; - } - perms &= subset; - switch (action) { - case '+': - ctx->attrs_clr |= perms; - ctx->attrs_xor |= perms; - break; - case '-': - ctx->attrs_clr |= perms; - ctx->attrs_xor &= ~perms; - break; - case '=': - ctx->attrs_clr |= subset; - ctx->attrs_xor |= perms; - break; - } - if (*mode) mode++; /* eat comma */ - } + subset = 0; + while (*mode && *mode != ',' && + *mode != '+' && *mode != '-' && *mode != '=') { + switch (*mode) { + case 'u': subset |= 04700; break; /* setuid, user perms */ + case 'g': subset |= 02070; break; /* setgid, group perms */ + case 'o': subset |= 00007; break; /* just other perms */ + case 'a': subset |= 06777; break; /* all of the above */ + default: + printf("chmod: file mode '%.*s' contains unrecognised" + " user/group/other specifier '%c'\n", + (int)strcspn(modebegin, ","), modebegin, *mode); + return 0; + } + mode++; + } + if (!*mode || *mode == ',') { + printf("chmod: file mode '%.*s' is incomplete\n", + (int)strcspn(modebegin, ","), modebegin); + return 0; + } + action = *mode++; + if (!*mode || *mode == ',') { + printf("chmod: file mode '%.*s' is incomplete\n", + (int)strcspn(modebegin, ","), modebegin); + return 0; + } + perms = 0; + while (*mode && *mode != ',') { + switch (*mode) { + case 'r': perms |= 00444; break; + case 'w': perms |= 00222; break; + case 'x': perms |= 00111; break; + case 't': perms |= 01000; subset |= 01000; break; + case 's': + if ((subset & 06777) != 04700 && + (subset & 06777) != 02070) { + printf("chmod: file mode '%.*s': set[ug]id bit should" + " be used with exactly one of u or g only\n", + (int)strcspn(modebegin, ","), modebegin); + return 0; + } + perms |= 06000; + break; + default: + printf("chmod: file mode '%.*s' contains unrecognised" + " permission specifier '%c'\n", + (int)strcspn(modebegin, ","), modebegin, *mode); + return 0; + } + mode++; + } + if (!(subset & 06777) && (perms &~ subset)) { + printf("chmod: file mode '%.*s' contains no user/group/other" + " specifier and permissions other than 't' \n", + (int)strcspn(modebegin, ","), modebegin); + return 0; + } + perms &= subset; + switch (action) { + case '+': + ctx->attrs_clr |= perms; + ctx->attrs_xor |= perms; + break; + case '-': + ctx->attrs_clr |= perms; + ctx->attrs_xor &= ~perms; + break; + case '=': + ctx->attrs_clr |= subset; + ctx->attrs_xor |= perms; + break; + } + if (*mode) mode++; /* eat comma */ + } } ret = 1; for (i = 2; i < cmd->nwords; i++) - ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx); + ret &= wildcard_iterate(cmd->words[i], sftp_action_chmod, ctx); return ret; } @@ -1806,27 +1806,27 @@ static int sftp_cmd_open(struct sftp_command *cmd) int portnumber; if (backend) { - printf("psftp: already connected\n"); - return 0; + printf("psftp: already connected\n"); + return 0; } if (cmd->nwords < 2) { - printf("open: expects a host name\n"); - return 0; + printf("open: expects a host name\n"); + return 0; } if (cmd->nwords > 2) { - portnumber = atoi(cmd->words[2]); - if (portnumber == 0) { - printf("open: invalid port number\n"); - return 0; - } + portnumber = atoi(cmd->words[2]); + if (portnumber == 0) { + printf("open: invalid port number\n"); + return 0; + } } else - portnumber = 0; + portnumber = 0; if (psftp_connect(cmd->words[1], NULL, portnumber)) { backend = NULL; /* connection is already closed */ - return -1; /* this is fatal */ + return -1; /* this is fatal */ } do_sftp_init(); return 1; @@ -1837,15 +1837,15 @@ static int sftp_cmd_lcd(struct sftp_command *cmd) char *currdir, *errmsg; if (cmd->nwords < 2) { - printf("lcd: expects a local directory name\n"); - return 0; + printf("lcd: expects a local directory name\n"); + return 0; } errmsg = psftp_lcd(cmd->words[1]); if (errmsg) { - printf("lcd: unable to change directory: %s\n", errmsg); - sfree(errmsg); - return 0; + printf("lcd: unable to change directory: %s\n", errmsg); + sfree(errmsg); + return 0; } currdir = psftp_getcwd(); @@ -1880,12 +1880,12 @@ static struct sftp_cmd_lookup { const char *name; /* * For help purposes, there are two kinds of command: - * + * * - primary commands, in which `longhelp' is non-NULL. In * this case `shorthelp' is descriptive text, and `longhelp' * is longer descriptive text intended to be printed after * the command name. - * + * * - alias commands, in which `longhelp' is NULL. In this case * `shorthelp' is the name of a primary command, which * contains the help that should double up for this command. @@ -1900,218 +1900,218 @@ static struct sftp_cmd_lookup { * in ASCII order. */ { - "!", true, "run a local command", - "\n" - /* FIXME: this example is crap for non-Windows. */ - " Runs a local command. For example, \"!del myfile\".\n", - sftp_cmd_pling + "!", true, "run a local command", + "\n" + /* FIXME: this example is crap for non-Windows. */ + " Runs a local command. For example, \"!del myfile\".\n", + sftp_cmd_pling }, { - "bye", true, "finish your SFTP session", - "\n" - " Terminates your SFTP session and quits the PSFTP program.\n", - sftp_cmd_quit + "bye", true, "finish your SFTP session", + "\n" + " Terminates your SFTP session and quits the PSFTP program.\n", + sftp_cmd_quit }, { - "cd", true, "change your remote working directory", - " [ ]\n" - " Change the remote working directory for your SFTP session.\n" - " If a new working directory is not supplied, you will be\n" - " returned to your home directory.\n", - sftp_cmd_cd + "cd", true, "change your remote working directory", + " [ ]\n" + " Change the remote working directory for your SFTP session.\n" + " If a new working directory is not supplied, you will be\n" + " returned to your home directory.\n", + sftp_cmd_cd }, { - "chmod", true, "change file permissions and modes", - " [ ... ]\n" - " Change the file permissions on one or more remote files or\n" - " directories.\n" - " can be any octal Unix permission specifier.\n" - " Alternatively, can include the following modifiers:\n" - " u+r make file readable by owning user\n" - " u+w make file writable by owning user\n" - " u+x make file executable by owning user\n" - " u-r make file not readable by owning user\n" - " [also u-w, u-x]\n" - " g+r make file readable by members of owning group\n" - " [also g+w, g+x, g-r, g-w, g-x]\n" - " o+r make file readable by all other users\n" - " [also o+w, o+x, o-r, o-w, o-x]\n" - " a+r make file readable by absolutely everybody\n" - " [also a+w, a+x, a-r, a-w, a-x]\n" - " u+s enable the Unix set-user-ID bit\n" - " u-s disable the Unix set-user-ID bit\n" - " g+s enable the Unix set-group-ID bit\n" - " g-s disable the Unix set-group-ID bit\n" - " +t enable the Unix \"sticky bit\"\n" - " You can give more than one modifier for the same user (\"g-rwx\"), and\n" - " more than one user for the same modifier (\"ug+w\"). You can\n" - " use commas to separate different modifiers (\"u+rwx,g+s\").\n", - sftp_cmd_chmod + "chmod", true, "change file permissions and modes", + " [ ... ]\n" + " Change the file permissions on one or more remote files or\n" + " directories.\n" + " can be any octal Unix permission specifier.\n" + " Alternatively, can include the following modifiers:\n" + " u+r make file readable by owning user\n" + " u+w make file writable by owning user\n" + " u+x make file executable by owning user\n" + " u-r make file not readable by owning user\n" + " [also u-w, u-x]\n" + " g+r make file readable by members of owning group\n" + " [also g+w, g+x, g-r, g-w, g-x]\n" + " o+r make file readable by all other users\n" + " [also o+w, o+x, o-r, o-w, o-x]\n" + " a+r make file readable by absolutely everybody\n" + " [also a+w, a+x, a-r, a-w, a-x]\n" + " u+s enable the Unix set-user-ID bit\n" + " u-s disable the Unix set-user-ID bit\n" + " g+s enable the Unix set-group-ID bit\n" + " g-s disable the Unix set-group-ID bit\n" + " +t enable the Unix \"sticky bit\"\n" + " You can give more than one modifier for the same user (\"g-rwx\"), and\n" + " more than one user for the same modifier (\"ug+w\"). You can\n" + " use commas to separate different modifiers (\"u+rwx,g+s\").\n", + sftp_cmd_chmod }, { - "close", true, "finish your SFTP session but do not quit PSFTP", - "\n" - " Terminates your SFTP session, but does not quit the PSFTP\n" - " program. You can then use \"open\" to start another SFTP\n" - " session, to the same server or to a different one.\n", - sftp_cmd_close + "close", true, "finish your SFTP session but do not quit PSFTP", + "\n" + " Terminates your SFTP session, but does not quit the PSFTP\n" + " program. You can then use \"open\" to start another SFTP\n" + " session, to the same server or to a different one.\n", + sftp_cmd_close }, { - "del", true, "delete files on the remote server", - " [ ... ]\n" - " Delete a file or files from the server.\n", - sftp_cmd_rm + "del", true, "delete files on the remote server", + " [ ... ]\n" + " Delete a file or files from the server.\n", + sftp_cmd_rm }, { - "delete", false, "del", NULL, sftp_cmd_rm + "delete", false, "del", NULL, sftp_cmd_rm }, { - "dir", true, "list remote files", - " [ ]/[ ]\n" - " List the contents of a specified directory on the server.\n" - " If is not given, the current working directory\n" - " is assumed.\n" - " If is given, it is treated as a set of files to\n" - " list; otherwise, all files are listed.\n", - sftp_cmd_ls + "dir", true, "list remote files", + " [ ]/[ ]\n" + " List the contents of a specified directory on the server.\n" + " If is not given, the current working directory\n" + " is assumed.\n" + " If is given, it is treated as a set of files to\n" + " list; otherwise, all files are listed.\n", + sftp_cmd_ls }, { - "exit", true, "bye", NULL, sftp_cmd_quit + "exit", true, "bye", NULL, sftp_cmd_quit }, { - "get", true, "download a file from the server to your local machine", - " [ -r ] [ -- ] [ ]\n" - " Downloads a file on the server and stores it locally under\n" - " the same name, or under a different one if you supply the\n" - " argument .\n" - " If -r specified, recursively fetch a directory.\n", - sftp_cmd_get + "get", true, "download a file from the server to your local machine", + " [ -r ] [ -- ] [ ]\n" + " Downloads a file on the server and stores it locally under\n" + " the same name, or under a different one if you supply the\n" + " argument .\n" + " If -r specified, recursively fetch a directory.\n", + sftp_cmd_get }, { - "help", true, "give help", - " [ [ ... ] ]\n" - " Give general help if no commands are specified.\n" - " If one or more commands are specified, give specific help on\n" - " those particular commands.\n", - sftp_cmd_help + "help", true, "give help", + " [ [ ... ] ]\n" + " Give general help if no commands are specified.\n" + " If one or more commands are specified, give specific help on\n" + " those particular commands.\n", + sftp_cmd_help }, { - "lcd", true, "change local working directory", - " \n" - " Change the local working directory of the PSFTP program (the\n" - " default location where the \"get\" command will save files).\n", - sftp_cmd_lcd + "lcd", true, "change local working directory", + " \n" + " Change the local working directory of the PSFTP program (the\n" + " default location where the \"get\" command will save files).\n", + sftp_cmd_lcd }, { - "lpwd", true, "print local working directory", - "\n" - " Print the local working directory of the PSFTP program (the\n" - " default location where the \"get\" command will save files).\n", - sftp_cmd_lpwd + "lpwd", true, "print local working directory", + "\n" + " Print the local working directory of the PSFTP program (the\n" + " default location where the \"get\" command will save files).\n", + sftp_cmd_lpwd }, { - "ls", true, "dir", NULL, - sftp_cmd_ls + "ls", true, "dir", NULL, + sftp_cmd_ls }, { - "mget", true, "download multiple files at once", - " [ -r ] [ -- ] [ ... ]\n" - " Downloads many files from the server, storing each one under\n" - " the same name it has on the server side. You can use wildcards\n" - " such as \"*.c\" to specify lots of files at once.\n" - " If -r specified, recursively fetch files and directories.\n", - sftp_cmd_mget + "mget", true, "download multiple files at once", + " [ -r ] [ -- ] [ ... ]\n" + " Downloads many files from the server, storing each one under\n" + " the same name it has on the server side. You can use wildcards\n" + " such as \"*.c\" to specify lots of files at once.\n" + " If -r specified, recursively fetch files and directories.\n", + sftp_cmd_mget }, { - "mkdir", true, "create directories on the remote server", - " [ ... ]\n" - " Creates directories with the given names on the server.\n", - sftp_cmd_mkdir + "mkdir", true, "create directories on the remote server", + " [ ... ]\n" + " Creates directories with the given names on the server.\n", + sftp_cmd_mkdir }, { - "mput", true, "upload multiple files at once", - " [ -r ] [ -- ] [ ... ]\n" - " Uploads many files to the server, storing each one under the\n" - " same name it has on the client side. You can use wildcards\n" - " such as \"*.c\" to specify lots of files at once.\n" - " If -r specified, recursively store files and directories.\n", - sftp_cmd_mput + "mput", true, "upload multiple files at once", + " [ -r ] [ -- ] [ ... ]\n" + " Uploads many files to the server, storing each one under the\n" + " same name it has on the client side. You can use wildcards\n" + " such as \"*.c\" to specify lots of files at once.\n" + " If -r specified, recursively store files and directories.\n", + sftp_cmd_mput }, { - "mv", true, "move or rename file(s) on the remote server", - " [ ... ] \n" - " Moves or renames (s) on the server to ,\n" - " also on the server.\n" - " If specifies an existing directory, then \n" - " may be a wildcard, and multiple s may be given; all\n" - " source files are moved into .\n" - " Otherwise, must specify a single file, which is moved\n" - " or renamed so that it is accessible under the name .\n", - sftp_cmd_mv + "mv", true, "move or rename file(s) on the remote server", + " [ ... ] \n" + " Moves or renames (s) on the server to ,\n" + " also on the server.\n" + " If specifies an existing directory, then \n" + " may be a wildcard, and multiple s may be given; all\n" + " source files are moved into .\n" + " Otherwise, must specify a single file, which is moved\n" + " or renamed so that it is accessible under the name .\n", + sftp_cmd_mv }, { - "open", true, "connect to a host", - " [@] []\n" - " Establishes an SFTP connection to a given host. Only usable\n" - " when you are not already connected to a server.\n", - sftp_cmd_open + "open", true, "connect to a host", + " [@] []\n" + " Establishes an SFTP connection to a given host. Only usable\n" + " when you are not already connected to a server.\n", + sftp_cmd_open }, { - "put", true, "upload a file from your local machine to the server", - " [ -r ] [ -- ] [ ]\n" - " Uploads a file to the server and stores it there under\n" - " the same name, or under a different one if you supply the\n" - " argument .\n" - " If -r specified, recursively store a directory.\n", - sftp_cmd_put + "put", true, "upload a file from your local machine to the server", + " [ -r ] [ -- ] [ ]\n" + " Uploads a file to the server and stores it there under\n" + " the same name, or under a different one if you supply the\n" + " argument .\n" + " If -r specified, recursively store a directory.\n", + sftp_cmd_put }, { - "pwd", true, "print your remote working directory", - "\n" - " Print the current remote working directory for your SFTP session.\n", - sftp_cmd_pwd + "pwd", true, "print your remote working directory", + "\n" + " Print the current remote working directory for your SFTP session.\n", + sftp_cmd_pwd }, { - "quit", true, "bye", NULL, - sftp_cmd_quit + "quit", true, "bye", NULL, + sftp_cmd_quit }, { - "reget", true, "continue downloading files", - " [ -r ] [ -- ] [ ]\n" - " Works exactly like the \"get\" command, but the local file\n" - " must already exist. The download will begin at the end of the\n" - " file. This is for resuming a download that was interrupted.\n" - " If -r specified, resume interrupted \"get -r\".\n", - sftp_cmd_reget + "reget", true, "continue downloading files", + " [ -r ] [ -- ] [ ]\n" + " Works exactly like the \"get\" command, but the local file\n" + " must already exist. The download will begin at the end of the\n" + " file. This is for resuming a download that was interrupted.\n" + " If -r specified, resume interrupted \"get -r\".\n", + sftp_cmd_reget }, { - "ren", true, "mv", NULL, - sftp_cmd_mv + "ren", true, "mv", NULL, + sftp_cmd_mv }, { - "rename", false, "mv", NULL, - sftp_cmd_mv + "rename", false, "mv", NULL, + sftp_cmd_mv }, { - "reput", true, "continue uploading files", - " [ -r ] [ -- ] [ ]\n" - " Works exactly like the \"put\" command, but the remote file\n" - " must already exist. The upload will begin at the end of the\n" - " file. This is for resuming an upload that was interrupted.\n" - " If -r specified, resume interrupted \"put -r\".\n", - sftp_cmd_reput + "reput", true, "continue uploading files", + " [ -r ] [ -- ] [ ]\n" + " Works exactly like the \"put\" command, but the remote file\n" + " must already exist. The upload will begin at the end of the\n" + " file. This is for resuming an upload that was interrupted.\n" + " If -r specified, resume interrupted \"put -r\".\n", + sftp_cmd_reput }, { - "rm", true, "del", NULL, - sftp_cmd_rm + "rm", true, "del", NULL, + sftp_cmd_rm }, { - "rmdir", true, "remove directories on the remote server", - " [ ... ]\n" - " Removes the directory with the given name on the server.\n" - " The directory will not be removed unless it is empty.\n" - " Wildcards may be used to specify multiple directories.\n", - sftp_cmd_rmdir + "rmdir", true, "remove directories on the remote server", + " [ ... ]\n" + " Removes the directory with the given name on the server.\n" + " The directory will not be removed unless it is empty.\n" + " Wildcards may be used to specify multiple directories.\n", + sftp_cmd_rmdir } }; @@ -2122,15 +2122,15 @@ const struct sftp_cmd_lookup *lookup_command(const char *name) i = -1; j = lenof(sftp_lookup); while (j - i > 1) { - k = (j + i) / 2; - cmp = strcmp(name, sftp_lookup[k].name); - if (cmp < 0) - j = k; - else if (cmp > 0) - i = k; - else { - return &sftp_lookup[k]; - } + k = (j + i) / 2; + cmp = strcmp(name, sftp_lookup[k].name); + if (cmp < 0) + j = k; + else if (cmp > 0) + i = k; + else { + return &sftp_lookup[k]; + } } return NULL; } @@ -2139,45 +2139,45 @@ static int sftp_cmd_help(struct sftp_command *cmd) { int i; if (cmd->nwords == 1) { - /* - * Give short help on each command. - */ - int maxlen; - maxlen = 0; - for (i = 0; i < lenof(sftp_lookup); i++) { - int len; - if (!sftp_lookup[i].listed) - continue; - len = strlen(sftp_lookup[i].name); - if (maxlen < len) - maxlen = len; - } - for (i = 0; i < lenof(sftp_lookup); i++) { - const struct sftp_cmd_lookup *lookup; - if (!sftp_lookup[i].listed) - continue; - lookup = &sftp_lookup[i]; - printf("%-*s", maxlen+2, lookup->name); - if (lookup->longhelp == NULL) - lookup = lookup_command(lookup->shorthelp); - printf("%s\n", lookup->shorthelp); - } + /* + * Give short help on each command. + */ + int maxlen; + maxlen = 0; + for (i = 0; i < lenof(sftp_lookup); i++) { + int len; + if (!sftp_lookup[i].listed) + continue; + len = strlen(sftp_lookup[i].name); + if (maxlen < len) + maxlen = len; + } + for (i = 0; i < lenof(sftp_lookup); i++) { + const struct sftp_cmd_lookup *lookup; + if (!sftp_lookup[i].listed) + continue; + lookup = &sftp_lookup[i]; + printf("%-*s", maxlen+2, lookup->name); + if (lookup->longhelp == NULL) + lookup = lookup_command(lookup->shorthelp); + printf("%s\n", lookup->shorthelp); + } } else { - /* - * Give long help on specific commands. - */ - for (i = 1; i < cmd->nwords; i++) { - const struct sftp_cmd_lookup *lookup; - lookup = lookup_command(cmd->words[i]); - if (!lookup) { - printf("help: %s: command not found\n", cmd->words[i]); - } else { - printf("%s", lookup->name); - if (lookup->longhelp == NULL) - lookup = lookup_command(lookup->shorthelp); - printf("%s", lookup->longhelp); - } - } + /* + * Give long help on specific commands. + */ + for (i = 1; i < cmd->nwords; i++) { + const struct sftp_cmd_lookup *lookup; + lookup = lookup_command(cmd->words[i]); + if (!lookup) { + printf("help: %s: command not found\n", cmd->words[i]); + } else { + printf("%s", lookup->name); + if (lookup->longhelp == NULL) + lookup = lookup_command(lookup->shorthelp); + printf("%s", lookup->longhelp); + } + } } return 1; } @@ -2200,90 +2200,90 @@ struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags) line = NULL; if (fp) { - if (modeflags & 1) - printf("psftp> "); - line = fgetline(fp); + if (modeflags & 1) + printf("psftp> "); + line = fgetline(fp); } else { line = ssh_sftp_get_cmdline("psftp> ", !backend); } if (!line || !*line) { - cmd->obey = sftp_cmd_quit; - if ((mode == 0) || (modeflags & 1)) - printf("quit\n"); + cmd->obey = sftp_cmd_quit; + if ((mode == 0) || (modeflags & 1)) + printf("quit\n"); sfree(line); - return cmd; /* eof */ + return cmd; /* eof */ } line[strcspn(line, "\r\n")] = '\0'; if (modeflags & 1) { - printf("%s\n", line); + printf("%s\n", line); } p = line; while (*p && (*p == ' ' || *p == '\t')) - p++; + p++; if (*p == '!') { - /* - * Special case: the ! command. This is always parsed as - * exactly two words: one containing the !, and the second - * containing everything else on the line. - */ + /* + * Special case: the ! command. This is always parsed as + * exactly two words: one containing the !, and the second + * containing everything else on the line. + */ cmd->nwords = 2; sgrowarrayn(cmd->words, cmd->wordssize, cmd->nwords, 0); - cmd->words[0] = dupstr("!"); - cmd->words[1] = dupstr(p+1); + cmd->words[0] = dupstr("!"); + cmd->words[1] = dupstr(p+1); } else if (*p == '#') { - /* - * Special case: comment. Entire line is ignored. - */ - cmd->nwords = cmd->wordssize = 0; + /* + * Special case: comment. Entire line is ignored. + */ + cmd->nwords = cmd->wordssize = 0; } else { - /* - * Parse the command line into words. The syntax is: - * - double quotes are removed, but cause spaces within to be - * treated as non-separating. - * - a double-doublequote pair is a literal double quote, inside - * _or_ outside quotes. Like this: - * - * firstword "second word" "this has ""quotes"" in" and""this"" - * - * becomes - * - * >firstword< - * >second word< - * >this has "quotes" in< - * >and"this"< - */ - while (1) { - /* skip whitespace */ - while (*p && (*p == ' ' || *p == '\t')) - p++; + /* + * Parse the command line into words. The syntax is: + * - double quotes are removed, but cause spaces within to be + * treated as non-separating. + * - a double-doublequote pair is a literal double quote, inside + * _or_ outside quotes. Like this: + * + * firstword "second word" "this has ""quotes"" in" and""this"" + * + * becomes + * + * >firstword< + * >second word< + * >this has "quotes" in< + * >and"this"< + */ + while (1) { + /* skip whitespace */ + while (*p && (*p == ' ' || *p == '\t')) + p++; /* terminate loop */ if (!*p) break; - /* mark start of word */ - q = r = p; /* q sits at start, r writes word */ - quoting = false; - while (*p) { - if (!quoting && (*p == ' ' || *p == '\t')) - break; /* reached end of word */ - else if (*p == '"' && p[1] == '"') - p += 2, *r++ = '"'; /* a literal quote */ - else if (*p == '"') - p++, quoting = !quoting; - else - *r++ = *p++; - } - if (*p) - p++; /* skip over the whitespace */ - *r = '\0'; + /* mark start of word */ + q = r = p; /* q sits at start, r writes word */ + quoting = false; + while (*p) { + if (!quoting && (*p == ' ' || *p == '\t')) + break; /* reached end of word */ + else if (*p == '"' && p[1] == '"') + p += 2, *r++ = '"'; /* a literal quote */ + else if (*p == '"') + p++, quoting = !quoting; + else + *r++ = *p++; + } + if (*p) + p++; /* skip over the whitespace */ + *r = '\0'; sgrowarray(cmd->words, cmd->wordssize, cmd->nwords); - cmd->words[cmd->nwords++] = dupstr(q); - } + cmd->words[cmd->nwords++] = dupstr(q); + } } sfree(line); @@ -2293,14 +2293,14 @@ struct sftp_command *sftp_getcmd(FILE *fp, int mode, int modeflags) */ if (cmd->nwords == 0) - cmd->obey = sftp_cmd_null; + cmd->obey = sftp_cmd_null; else { - const struct sftp_cmd_lookup *lookup; - lookup = lookup_command(cmd->words[0]); - if (!lookup) - cmd->obey = sftp_cmd_unknown; - else - cmd->obey = lookup->obey; + const struct sftp_cmd_lookup *lookup; + lookup = lookup_command(cmd->words[0]); + if (!lookup) + cmd->obey = sftp_cmd_unknown; + else + cmd->obey = lookup->obey; } return cmd; @@ -2312,12 +2312,12 @@ static int do_sftp_init(void) struct sftp_request *req; /* - * Do protocol initialisation. + * Do protocol initialisation. */ if (!fxp_init()) { - fprintf(stderr, - "Fatal: unable to initialise SFTP: %s\n", fxp_error()); - return 1; /* failure */ + fprintf(stderr, + "Fatal: unable to initialise SFTP: %s\n", fxp_error()); + return 1; /* failure */ } /* @@ -2328,10 +2328,10 @@ static int do_sftp_init(void) homedir = fxp_realpath_recv(pktin, req); if (!homedir) { - fprintf(stderr, - "Warning: failed to resolve home directory: %s\n", - fxp_error()); - homedir = dupstr("."); + fprintf(stderr, + "Warning: failed to resolve home directory: %s\n", + fxp_error()); + homedir = dupstr("."); } else { with_stripctrl(san, homedir) printf("Remote working directory is %s\n", san); @@ -2346,18 +2346,18 @@ static void do_sftp_cleanup(void) if (backend) { backend_special(backend, SS_EOF, 0); sent_eof = true; - sftp_recvdata(&ch, 1); + sftp_recvdata(&ch, 1); backend_free(backend); - sftp_cleanup_request(); + sftp_cleanup_request(); backend = NULL; } if (pwd) { - sfree(pwd); - pwd = NULL; + sfree(pwd); + pwd = NULL; } if (homedir) { - sfree(homedir); - homedir = NULL; + sfree(homedir); + homedir = NULL; } } @@ -2375,47 +2375,47 @@ int do_sftp(int mode, int modeflags, char *batchfile) * Now we're ready to do Real Stuff. */ while (1) { - struct sftp_command *cmd; - cmd = sftp_getcmd(NULL, 0, 0); - if (!cmd) - break; - ret = cmd->obey(cmd); - if (cmd->words) { - int i; - for(i = 0; i < cmd->nwords; i++) - sfree(cmd->words[i]); - sfree(cmd->words); - } - sfree(cmd); - if (ret < 0) - break; - } + struct sftp_command *cmd; + cmd = sftp_getcmd(NULL, 0, 0); + if (!cmd) + break; + ret = cmd->obey(cmd); + if (cmd->words) { + int i; + for(i = 0; i < cmd->nwords; i++) + sfree(cmd->words[i]); + sfree(cmd->words); + } + sfree(cmd); + if (ret < 0) + break; + } } else { fp = fopen(batchfile, "r"); if (!fp) { - printf("Fatal: unable to open %s\n", batchfile); - return 1; + printf("Fatal: unable to open %s\n", batchfile); + return 1; } - ret = 0; + ret = 0; while (1) { - struct sftp_command *cmd; - cmd = sftp_getcmd(fp, mode, modeflags); - if (!cmd) - break; - ret = cmd->obey(cmd); - if (ret < 0) - break; - if (ret == 0) { - if (!(modeflags & 2)) - break; - } + struct sftp_command *cmd; + cmd = sftp_getcmd(fp, mode, modeflags); + if (!cmd) + break; + ret = cmd->obey(cmd); + if (ret < 0) + break; + if (ret == 0) { + if (!(modeflags & 2)) + break; + } } - fclose(fp); - /* - * In batch mode, and if exit on command failure is enabled, - * any command failure causes the whole of PSFTP to fail. - */ - if (ret == 0 && !(modeflags & 2)) return 2; + fclose(fp); + /* + * In batch mode, and if exit on command failure is enabled, + * any command failure causes the whole of PSFTP to fail. + */ + if (ret == 0 && !(modeflags & 2)) return 2; } return 0; } @@ -2433,7 +2433,7 @@ void ldisc_echoedit_update(Ldisc *ldisc) { } * never-called stub. */ void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len) + void *callback_ctx, void *data, int len) { assert(!"We shouldn't be here"); } @@ -2457,7 +2457,7 @@ static size_t psftp_output( */ if (is_stderr) { put_data(stderr_bs, data, len); - return 0; + return 0; } bufchain_add(&received_data, data, len); @@ -2562,14 +2562,14 @@ static int psftp_connect(char *userhost, char *user, int portnumber) host = userhost; host = strrchr(host, '@'); if (host == NULL) { - host = userhost; + host = userhost; } else { - *host++ = '\0'; - if (user) { - printf("psftp: multiple usernames specified; using \"%s\"\n", - user); - } else - user = userhost; + *host++ = '\0'; + if (user) { + printf("psftp: multiple usernames specified; using \"%s\"\n", + user); + } else + user = userhost; } /* @@ -2577,23 +2577,23 @@ static int psftp_connect(char *userhost, char *user, int portnumber) * try looking for a session called "host". */ if (!loaded_session) { - /* Try to load settings for `host' into a temporary config */ - Conf *conf2 = conf_new(); - conf_set_str(conf2, CONF_host, ""); - do_defaults(host, conf2); - if (conf_get_str(conf2, CONF_host)[0] != '\0') { - /* Settings present and include hostname */ - /* Re-load data into the real config. */ - do_defaults(host, conf); - } else { - /* Session doesn't exist or mention a hostname. */ - /* Use `host' as a bare hostname. */ - conf_set_str(conf, CONF_host, host); - } + /* Try to load settings for `host' into a temporary config */ + Conf *conf2 = conf_new(); + conf_set_str(conf2, CONF_host, ""); + do_defaults(host, conf2); + if (conf_get_str(conf2, CONF_host)[0] != '\0') { + /* Settings present and include hostname */ + /* Re-load data into the real config. */ + do_defaults(host, conf); + } else { + /* Session doesn't exist or mention a hostname. */ + /* Use `host' as a bare hostname. */ + conf_set_str(conf, CONF_host, host); + } conf_free(conf2); } else { - /* Patch in hostname `host' to session details. */ - conf_set_str(conf, CONF_host, host); + /* Patch in hostname `host' to session details. */ + conf_set_str(conf, CONF_host, host); } /* @@ -2612,7 +2612,7 @@ static int psftp_connect(char *userhost, char *user, int portnumber) * But if it says `2 only' or `2', respect which. */ if ((conf_get_int(conf, CONF_sshprot) & ~1) != 2) /* is it 2 or 3? */ - conf_set_int(conf, CONF_sshprot, 2); + conf_set_int(conf, CONF_sshprot, 2); /* * Enact command-line overrides. @@ -2623,51 +2623,51 @@ static int psftp_connect(char *userhost, char *user, int portnumber) * Muck about with the hostname in various ways. */ { - char *hostbuf = dupstr(conf_get_str(conf, CONF_host)); - char *host = hostbuf; - char *p, *q; + char *hostbuf = dupstr(conf_get_str(conf, CONF_host)); + char *host = hostbuf; + char *p, *q; - /* - * Trim leading whitespace. - */ - host += strspn(host, " \t"); + /* + * Trim leading whitespace. + */ + host += strspn(host, " \t"); - /* - * See if host is of the form user@host, and separate out - * the username if so. - */ - if (host[0] != '\0') { - char *atsign = strrchr(host, '@'); - if (atsign) { - *atsign = '\0'; - conf_set_str(conf, CONF_username, host); - host = atsign + 1; - } - } + /* + * See if host is of the form user@host, and separate out + * the username if so. + */ + if (host[0] != '\0') { + char *atsign = strrchr(host, '@'); + if (atsign) { + *atsign = '\0'; + conf_set_str(conf, CONF_username, host); + host = atsign + 1; + } + } - /* - * Remove any remaining whitespace. - */ - p = hostbuf; - q = host; - while (*q) { - if (*q != ' ' && *q != '\t') - *p++ = *q; - q++; - } - *p = '\0'; + /* + * Remove any remaining whitespace. + */ + p = hostbuf; + q = host; + while (*q) { + if (*q != ' ' && *q != '\t') + *p++ = *q; + q++; + } + *p = '\0'; - conf_set_str(conf, CONF_host, hostbuf); - sfree(hostbuf); + conf_set_str(conf, CONF_host, hostbuf); + sfree(hostbuf); } /* Set username */ if (user != NULL && user[0] != '\0') { - conf_set_str(conf, CONF_username, user); + conf_set_str(conf, CONF_username, user); } if (portnumber) - conf_set_int(conf, CONF_port, portnumber); + conf_set_int(conf, CONF_port, portnumber); /* * Disable scary things which shouldn't be enabled for simple @@ -2678,9 +2678,9 @@ static int psftp_connect(char *userhost, char *user, int portnumber) conf_set_bool(conf, CONF_agentfwd, false); conf_set_bool(conf, CONF_ssh_simple, true); { - char *key; - while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL) - conf_del_str_str(conf, CONF_portfwd, key); + char *key; + while ((key = conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) != NULL) + conf_del_str_str(conf, CONF_portfwd, key); } /* Set up subsystem name. */ @@ -2696,21 +2696,21 @@ static int psftp_connect(char *userhost, char *user, int portnumber) * try to find sftp-server in various places (the obvious * systemwide spots /usr/lib and /usr/local/lib, and then the * user's PATH) and finally give up. - * + * * test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server * test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server * exec sftp-server - * + * * the idea being that this will attempt to use either of the * obvious pathnames and then give up, and when it does give up * it will print the preferred pathname in the error messages. */ conf_set_str(conf, CONF_remote_cmd2, - "test -x /usr/lib/sftp-server &&" - " exec /usr/lib/sftp-server\n" - "test -x /usr/local/lib/sftp-server &&" - " exec /usr/local/lib/sftp-server\n" - "exec sftp-server"); + "test -x /usr/lib/sftp-server &&" + " exec /usr/lib/sftp-server\n" + "test -x /usr/local/lib/sftp-server &&" + " exec /usr/local/lib/sftp-server\n" + "exec sftp-server"); conf_set_bool(conf, CONF_ssh_subsys2, false); psftp_logctx = log_init(default_logpolicy, conf); @@ -2723,21 +2723,21 @@ static int psftp_connect(char *userhost, char *user, int portnumber) &realhost, 0, conf_get_bool(conf, CONF_tcp_keepalives)); if (err != NULL) { - fprintf(stderr, "ssh_init: %s\n", err); - return 1; + fprintf(stderr, "ssh_init: %s\n", err); + return 1; } while (!backend_sendok(backend)) { if (backend_exitcode(backend) >= 0) - return 1; - if (ssh_sftp_loop_iteration() < 0) { - fprintf(stderr, "ssh_init: error during SSH connection setup\n"); - return 1; - } + return 1; + if (ssh_sftp_loop_iteration() < 0) { + fprintf(stderr, "ssh_init: error during SSH connection setup\n"); + return 1; + } } if (verbose && realhost != NULL) - printf("Connected to %s\n", realhost); + printf("Connected to %s\n", realhost); if (realhost != NULL) - sfree(realhost); + sfree(realhost); return 0; } @@ -2773,9 +2773,9 @@ int psftp_main(int argc, char *argv[]) flags = FLAG_INTERACTIVE #ifdef FLAG_SYNCAGENT - | FLAG_SYNCAGENT + | FLAG_SYNCAGENT #endif - ; + ; cmdline_tooltype = TOOLTYPE_FILETRANSFER; sk_init(); @@ -2787,52 +2787,52 @@ int psftp_main(int argc, char *argv[]) loaded_session = false; for (i = 1; i < argc; i++) { - int ret; - if (argv[i][0] != '-') { + int ret; + if (argv[i][0] != '-') { if (userhost) usage(); else userhost = dupstr(argv[i]); - continue; - } - ret = cmdline_process_param(argv[i], i+1 /* for wchar_t */ +#include /* for wchar_t */ #include /* for INT_MAX */ /* @@ -28,7 +28,7 @@ * clip some values so that the resulting number of ticks does not overflow an * integer value. */ -#define MAX_TICK_MINS (INT_MAX / (60 * TICKSPERSEC)) +#define MAX_TICK_MINS (INT_MAX / (60 * TICKSPERSEC)) /* * Fingerprints of the current and previous PGP master keys, to @@ -43,7 +43,7 @@ #define PGP_PREV_MASTER_KEY_FP \ "440D E3B5 B7A1 CA85 B3CC 1718 AB58 5DC6 0467 6F7C" -/* Three attribute types: +/* Three attribute types: * The ATTRs (normal attributes) are stored with the characters in * the main display arrays * @@ -52,7 +52,7 @@ * * The LATTRs (line attributes) are an entirely disjoint space of * flags. - * + * * The DATTRs (display attributes) are internal to terminal.c (but * defined here because their values have to match the others * here); they reuse the TATTR_* space but are always masked off @@ -61,10 +61,10 @@ * ATTR_INVALID is an illegal colour combination. */ -#define TATTR_ACTCURS 0x40000000UL /* active cursor (block) */ -#define TATTR_PASCURS 0x20000000UL /* passive cursor (box) */ -#define TATTR_RIGHTCURS 0x10000000UL /* cursor-on-RHS */ -#define TATTR_COMBINING 0x80000000UL /* combining characters */ +#define TATTR_ACTCURS 0x40000000UL /* active cursor (block) */ +#define TATTR_PASCURS 0x20000000UL /* passive cursor (box) */ +#define TATTR_RIGHTCURS 0x10000000UL /* cursor-on-RHS */ +#define TATTR_COMBINING 0x80000000UL /* combining characters */ #define DATTR_STARTRUN 0x80000000UL /* start of redraw run */ @@ -79,8 +79,8 @@ #define LATTR_MODE 0x00000003UL #define LATTR_WRAPPED 0x00000010UL /* this line wraps to next */ #define LATTR_WRAPPED2 0x00000020UL /* with WRAPPED: CJK wide character - wrapped to next line, so last - single-width cell is empty */ + wrapped to next line, so last + single-width cell is empty */ #define ATTR_INVALID 0x03FFFFU @@ -98,7 +98,7 @@ #define DIRECT_CHAR(c) ((c&0xFFFFFC00)==0xD800) #define DIRECT_FONT(c) ((c&0xFFFFFE00)==0xF000) -#define UCSERR (CSET_LINEDRW|'a') /* UCS Format error character. */ +#define UCSERR (CSET_LINEDRW|'a') /* UCS Format error character. */ /* * UCSWIDE is a special value used in the terminal data to signify * the character cell containing the right-hand half of a CJK wide @@ -107,7 +107,7 @@ * to input it via UTF-8 because our UTF-8 decoder correctly * rejects surrogates). */ -#define UCSWIDE 0xDFFF +#define UCSWIDE 0xDFFF #define ATTR_NARROW 0x0800000U #define ATTR_WIDE 0x0400000U @@ -125,7 +125,7 @@ /* * The definitive list of colour numbers stored in terminal * attribute words is kept here. It is: - * + * * - 0-7 are ANSI colours (KRGYBMCW). * - 8-15 are the bold versions of those colours. * - 16-255 are the remains of the xterm 256-colour mode (a @@ -148,7 +148,7 @@ struct sesslist { int nsessions; const char **sessions; - char *buffer; /* so memory can be freed later */ + char *buffer; /* so memory can be freed later */ }; struct unicode_data { @@ -164,14 +164,14 @@ struct unicode_data { unsigned char unitab_ctrl[256]; }; -#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 traffic */ -#define LGTYP_PACKETS 3 /* logmode: SSH data packets */ -#define LGTYP_SSHRAW 4 /* logmode: SSH raw data */ +#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 traffic */ +#define LGTYP_PACKETS 3 /* logmode: SSH data packets */ +#define LGTYP_SSHRAW 4 /* logmode: SSH raw data */ /* * Enumeration of 'special commands' that can be sent during a @@ -228,8 +228,8 @@ typedef enum { * backend_get_specials() will use them to specify the structure * of the GUI specials menu. */ - SS_SEP, /* Separator */ - SS_SUBMENU, /* Start a new submenu with specified name */ + SS_SEP, /* Separator */ + SS_SUBMENU, /* Start a new submenu with specified name */ SS_EXITMENU, /* Exit current submenu, or end of entire specials list */ } SessionSpecialCode; @@ -259,32 +259,32 @@ typedef enum { /* Keyboard modifiers -- keys the user is actually holding down */ -#define PKM_SHIFT 0x01 -#define PKM_CONTROL 0x02 -#define PKM_META 0x04 -#define PKM_ALT 0x08 +#define PKM_SHIFT 0x01 +#define PKM_CONTROL 0x02 +#define PKM_META 0x04 +#define PKM_ALT 0x08 /* Keyboard flags that aren't really modifiers */ -#define PKF_CAPSLOCK 0x10 -#define PKF_NUMLOCK 0x20 -#define PKF_REPEAT 0x40 +#define PKF_CAPSLOCK 0x10 +#define PKF_NUMLOCK 0x20 +#define PKF_REPEAT 0x40 /* Stand-alone keysyms for function keys */ typedef enum { - PK_NULL, /* No symbol for this key */ + PK_NULL, /* No symbol for this key */ /* Main keypad keys */ PK_ESCAPE, PK_TAB, PK_BACKSPACE, PK_RETURN, PK_COMPOSE, /* Editing keys */ PK_HOME, PK_INSERT, PK_DELETE, PK_END, PK_PAGEUP, PK_PAGEDOWN, /* Cursor keys */ PK_UP, PK_DOWN, PK_RIGHT, PK_LEFT, PK_REST, - /* Numeric keypad */ /* Real one looks like: */ - PK_PF1, PK_PF2, PK_PF3, PK_PF4, /* PF1 PF2 PF3 PF4 */ - PK_KPCOMMA, PK_KPMINUS, PK_KPDECIMAL, /* 7 8 9 - */ - PK_KP0, PK_KP1, PK_KP2, PK_KP3, PK_KP4, /* 4 5 6 , */ - PK_KP5, PK_KP6, PK_KP7, PK_KP8, PK_KP9, /* 1 2 3 en- */ - PK_KPBIGPLUS, PK_KPENTER, /* 0 . ter */ + /* Numeric keypad */ /* Real one looks like: */ + PK_PF1, PK_PF2, PK_PF3, PK_PF4, /* PF1 PF2 PF3 PF4 */ + PK_KPCOMMA, PK_KPMINUS, PK_KPDECIMAL, /* 7 8 9 - */ + PK_KP0, PK_KP1, PK_KP2, PK_KP3, PK_KP4, /* 4 5 6 , */ + PK_KP5, PK_KP6, PK_KP7, PK_KP8, PK_KP9, /* 1 2 3 en- */ + PK_KPBIGPLUS, PK_KPENTER, /* 0 . ter */ /* Top row */ PK_F1, PK_F2, PK_F3, PK_F4, PK_F5, PK_F6, PK_F7, PK_F8, PK_F9, PK_F10, @@ -293,10 +293,10 @@ typedef enum { PK_PAUSE } Key_Sym; -#define PK_ISEDITING(k) ((k) >= PK_HOME && (k) <= PK_PAGEDOWN) -#define PK_ISCURSOR(k) ((k) >= PK_UP && (k) <= PK_REST) -#define PK_ISKEYPAD(k) ((k) >= PK_PF1 && (k) <= PK_KPENTER) -#define PK_ISFKEY(k) ((k) >= PK_F1 && (k) <= PK_F20) +#define PK_ISEDITING(k) ((k) >= PK_HOME && (k) <= PK_PAGEDOWN) +#define PK_ISCURSOR(k) ((k) >= PK_UP && (k) <= PK_REST) +#define PK_ISKEYPAD(k) ((k) >= PK_PF1 && (k) <= PK_KPENTER) +#define PK_ISFKEY(k) ((k) >= PK_F1 && (k) <= PK_F20) enum { VT_XWINDOWS, VT_OEMANSI, VT_OEMONLY, VT_POORMAN, VT_UNICODE @@ -331,14 +331,14 @@ enum { /* * SSH ciphers (both SSH-1 and SSH-2) */ - CIPHER_WARN, /* pseudo 'cipher' */ + CIPHER_WARN, /* pseudo 'cipher' */ CIPHER_3DES, CIPHER_BLOWFISH, - CIPHER_AES, /* (SSH-2 only) */ + CIPHER_AES, /* (SSH-2 only) */ CIPHER_DES, CIPHER_ARCFOUR, CIPHER_CHACHA20, - CIPHER_MAX /* no. ciphers (inc warn) */ + CIPHER_MAX /* no. ciphers (inc warn) */ }; enum TriState { @@ -366,7 +366,7 @@ enum { /* * Line discipline options which the backend might try to control. */ - LD_EDIT, /* local line editing */ + LD_EDIT, /* local line editing */ LD_ECHO, /* local echo */ LD_N_OPTIONS }; @@ -580,18 +580,18 @@ extern const char *const appname; /* * Some global flags denoting the type of application. - * + * * FLAG_VERBOSE is set when the user requests verbose details. - * + * * FLAG_INTERACTIVE is set when a full interactive shell session is * being run, _either_ because no remote command has been provided * _or_ because the application is GUI and can't run non- * interactively. - * + * * These flags describe the type of _application_ - they wouldn't * vary between individual sessions - and so it's OK to have this * variable be GLOBAL. - * + * * Note that additional flags may be defined in platform-specific * headers. It's probably best if those ones start from 0x1000, to * avoid collision. @@ -668,16 +668,16 @@ typedef struct { */ bool from_server; - char *name; /* Short description, perhaps for dialog box title */ + char *name; /* Short description, perhaps for dialog box title */ bool name_reqd; /* Display of `name' required or optional? */ - char *instruction; /* Long description, maybe with embedded newlines */ + char *instruction; /* Long description, maybe with embedded newlines */ bool instr_reqd; /* Display of `instruction' required or optional? */ size_t n_prompts; /* May be zero (in which case display the foregoing, * if any, and return success) */ size_t prompts_size; /* allocated storage capacity for prompts[] */ prompt_t **prompts; - void *data; /* slot for housekeeping data, managed by - * seat_get_userpass_input(); initially NULL */ + void *data; /* slot for housekeeping data, managed by + * seat_get_userpass_input(); initially NULL */ } prompts_t; prompts_t *new_prompts(); void add_prompt(prompts_t *p, char *promptstr, bool echo); @@ -741,11 +741,11 @@ enum { ALL_CLIPBOARDS(CLIP_ID) N_CLIPBOARDS }; * by seat_set_busy_status. Initial state is assumed to be * BUSY_NOT. */ typedef enum BusyStatus { - BUSY_NOT, /* Not busy, all user interaction OK */ + BUSY_NOT, /* Not busy, all user interaction OK */ BUSY_WAITING, /* Waiting for something; local event loops still - running so some local interaction (e.g. menus) - OK, but network stuff is suspended */ - BUSY_CPU /* Locally busy (e.g. crypto); user interaction + running so some local interaction (e.g. menus) + OK, but network stuff is suspended */ + BUSY_CPU /* Locally busy (e.g. crypto); user interaction * suspended */ } BusyStatus; @@ -1494,7 +1494,7 @@ enum config_primary_key { CONFIG_OPTIONS(CONF_ENUM_DEF) N_CONFIG_OPTIONS }; #define NCFGCOLOURS 22 /* number of colours in CONF_colours above */ /* Functions handling configuration structures. */ -Conf *conf_new(void); /* create an empty configuration */ +Conf *conf_new(void); /* create an empty configuration */ void conf_free(Conf *conf); Conf *conf_copy(Conf *oldconf); void conf_copy_into(Conf *dest, Conf *src); @@ -1521,7 +1521,7 @@ void conf_set_int(Conf *conf, int key, int value); void conf_set_int_int(Conf *conf, int key, int subkey, int value); void conf_set_str(Conf *conf, int key, const char *value); void conf_set_str_str(Conf *conf, int key, - const char *subkey, const char *val); + const char *subkey, const char *val); void conf_del_str_str(Conf *conf, int key, const char *subkey); void conf_set_filename(Conf *conf, int key, const Filename *val); void conf_set_fontspec(Conf *conf, int key, const FontSpec *val); @@ -1590,7 +1590,7 @@ void registry_cleanup(void); /* * Functions used by settings.c to provide platform-specific * default settings. - * + * * (The integer one is expected to return `def' if it has no clear * opinion of its own. This is because there's no integer value * which I can reliably set aside to indicate `nil'. The string @@ -1621,9 +1621,9 @@ void term_scroll_to_selection(Terminal *, int); void term_pwron(Terminal *, bool); void term_clrsb(Terminal *); void term_mouse(Terminal *, Mouse_Button, Mouse_Button, Mouse_Action, - int, int, bool, bool, bool); + int, int, bool, bool, bool); void term_key(Terminal *, Key_Sym, wchar_t *, size_t, unsigned int, - unsigned int); + unsigned int); void term_lost_clipboard_ownership(Terminal *, int clipboard); void term_update(Terminal *); void term_invalidate(Terminal *); @@ -1634,7 +1634,7 @@ void term_copyall(Terminal *, const int *, int); void term_reconfig(Terminal *, Conf *); void term_request_copy(Terminal *, const int *clipboards, int n_clipboards); void term_request_paste(Terminal *, int clipboard); -void term_seen_key_event(Terminal *); +void term_seen_key_event(Terminal *); size_t term_data(Terminal *, bool is_stderr, const void *data, size_t len); void term_provide_backend(Terminal *term, Backend *backend); void term_provide_logctx(Terminal *term, LogContext *logctx); @@ -1732,9 +1732,9 @@ struct logblank_t { int type; }; void log_packet(LogContext *logctx, int direction, int type, - const char *texttype, const void *data, size_t len, - int n_blanks, const struct logblank_t *blanks, - const unsigned long *sequence, + const char *texttype, const void *data, size_t len, + int n_blanks, const struct logblank_t *blanks, + const unsigned long *sequence, unsigned downstream_id, const char *additional_log_text); /* This is defined by applications that have an obvious logging @@ -1834,7 +1834,7 @@ void prepare_session(Conf *conf); * Exports from sercfg.c. */ void ser_setup_config_box(struct controlbox *b, bool midsession, - int parity_mask, int flow_mask); + int parity_mask, int flow_mask); /* * Exports from version.c. @@ -1851,10 +1851,10 @@ extern const char commitid[]; /* void init_ucs(void); -- this is now in platform-specific headers */ bool is_dbcs_leadbyte(int codepage, char byte); int mb_to_wc(int codepage, int flags, const char *mbstr, int mblen, - wchar_t *wcstr, int wclen); + wchar_t *wcstr, int wclen); int wc_to_mb(int codepage, int flags, const wchar_t *wcstr, int wclen, - char *mbstr, int mblen, const char *defchr, - struct unicode_data *ucsdata); + char *mbstr, int mblen, const char *defchr, + struct unicode_data *ucsdata); wchar_t xlat_uskbd2cyrllic(int ch); int check_compose(int first, int second); int decode_codepage(char *cp_name); @@ -1872,12 +1872,12 @@ int mk_wcswidth_cjk(const unsigned int *pwcs, size_t n); /* * Exports from pageantc.c. - * + * * agent_query returns NULL for here's-a-response, and non-NULL for * query-in- progress. In the latter case there will be a call to * `callback' at some future point, passing callback_ctx as the first * parameter and the actual reply data as the second and third. - * + * * The response may be a NULL pointer (in either of the synchronous * or asynchronous cases), which indicates failure to receive a * response. @@ -1975,21 +1975,21 @@ void cmdline_error(const char *, ...); struct controlbox; union control; void conf_radiobutton_handler(union control *ctrl, dlgparam *dlg, - void *data, int event); + void *data, int event); #define CHECKBOX_INVERT (1<<30) void conf_checkbox_handler(union control *ctrl, dlgparam *dlg, - void *data, int event); + void *data, int event); void conf_editbox_handler(union control *ctrl, dlgparam *dlg, - void *data, int event); + void *data, int event); void conf_filesel_handler(union control *ctrl, dlgparam *dlg, - void *data, int event); + void *data, int event); void conf_fontsel_handler(union control *ctrl, dlgparam *dlg, - void *data, int event); + void *data, int event); /* Much more special-purpose function needed by sercfg.c */ void config_protocolbuttons_handler(union control *, dlgparam *, void *, int); void setup_config_box(struct controlbox *b, bool midsession, - int protocol, int protcfginfo); + int protocol, int protcfginfo); /* * Exports from minibidi.c. @@ -2009,7 +2009,7 @@ bool is_rtl(int c); enum { X11_NO_AUTH, X11_MIT, /* MIT-MAGIC-COOKIE-1 */ - X11_XDM, /* XDM-AUTHORIZATION-1 */ + X11_XDM, /* XDM-AUTHORIZATION-1 */ X11_NAUTHS }; extern const char *const x11_authnames[]; /* declared in x11fwd.c */ @@ -2038,7 +2038,7 @@ Filename *filename_copy(const Filename *fn); void filename_free(Filename *fn); void filename_serialise(BinarySink *bs, const Filename *f); Filename *filename_deserialise(BinarySource *src); -char *get_username(void); /* return value needs freeing */ +char *get_username(void); /* return value needs freeing */ char *get_random_data(int bytes, const char *device); /* used in cmdgen.c */ char filename_char_sanitise(char c); /* rewrite special pathname chars */ bool open_for_write_would_lose_data(const Filename *fn); @@ -2056,24 +2056,24 @@ bool open_for_write_would_lose_data(const Filename *fn); * structure as the time when that event is due. The first time a * callback function gives you that value or more as `now', you do * the thing. - * + * * expire_timer_context() drops all current timers associated with * a given value of ctx (for when you're about to free ctx). - * + * * run_timers() is called from the front end when it has reason to * think some timers have reached their moment, or when it simply * needs to know how long to wait next. We pass it the time we * think it is. It returns true and places the time when the next * timer needs to go off in `next', or alternatively it returns * false if there are no timers at all pending. - * + * * timer_change_notify() must be supplied by the front end; it * notifies the front end that a new timer has been added to the * list which is sooner than any existing ones. It provides the * time when that timer needs to go off. - * + * * *** FRONT END IMPLEMENTORS NOTE: - * + * * There's an important subtlety in the front-end implementation of * the timer interface. When a front end is given a `next' value, * either returned from run_timers() or via timer_change_notify(), @@ -2081,7 +2081,7 @@ bool open_for_write_would_lose_data(const Filename *fn); * parameter to its next run_timers call. It should _not_ simply * call GETTICKCOUNT() to get the `now' parameter when invoking * run_timers(). - * + * * The reason for this is that an OS's system clock might not agree * exactly with the timing mechanisms it supplies to wait for a * given interval. I'll illustrate this by the simple example of @@ -2090,7 +2090,7 @@ bool open_for_write_would_lose_data(const Filename *fn); * Suppose, for the sake of argument, that this wait() function * tends to return early by 1%. Then a possible sequence of actions * is: - * + * * - run_timers() tells the front end that the next timer firing * is 10000ms from now. * - Front end calls wait(10000ms), but according to @@ -2103,29 +2103,29 @@ bool open_for_write_would_lose_data(const Filename *fn); * - Front end calls run_timers() yet again, passing time T-1ms. * - run_timers() says there's still 1ms to wait. * - Front end calls wait(1ms). - * + * * If you're _lucky_ at this point, wait(1ms) will actually wait * for 1ms and you'll only have woken the program up three times. * If you're unlucky, wait(1ms) might do nothing at all due to * being below some minimum threshold, and you might find your * program spends the whole of the last millisecond tight-looping * between wait() and run_timers(). - * + * * Instead, what you should do is to _save_ the precise `next' * value provided by run_timers() or via timer_change_notify(), and * use that precise value as the input to the next run_timers() * call. So: - * + * * - run_timers() tells the front end that the next timer firing * is at time T, 10000ms from now. * - Front end calls wait(10000ms). * - Front end then immediately calls run_timers() and passes it * time T, without stopping to check GETTICKCOUNT() at all. - * + * * This guarantees that the program wakes up only as many times as * there are actual timer actions to be taken, and that the timing * mechanism will never send it into a tight loop. - * + * * (It does also mean that the timer action in the above example * will occur 100ms early, but this is not generally critical. And * the hypothetical 1% error in wait() will be partially corrected diff --git a/puttymem.h b/puttymem.h index ac1bd681..6513d6cf 100644 --- a/puttymem.h +++ b/puttymem.h @@ -5,8 +5,8 @@ #ifndef PUTTY_PUTTYMEM_H #define PUTTY_PUTTYMEM_H -#include /* for size_t */ -#include /* for memcpy() */ +#include /* for size_t */ +#include /* for memcpy() */ #include "defs.h" diff --git a/raw.c b/raw.c index 883a074c..abea744a 100644 --- a/raw.c +++ b/raw.c @@ -34,7 +34,7 @@ static void c_write(Raw *raw, const void *buf, size_t len) } static void raw_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { Raw *raw = container_of(plug, Raw, plug); backend_socket_log(raw->seat, raw->logctx, type, addr, port, @@ -57,7 +57,7 @@ static void raw_check_close(Raw *raw) } static void raw_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { Raw *raw = container_of(plug, Raw, plug); @@ -113,7 +113,7 @@ static const PlugVtable Raw_plugvt = { /* * Called to set up the raw connection. - * + * * Returns an error message, or NULL on success. * * Also places the canonical host name into `realhost'. It must be @@ -121,7 +121,7 @@ static const PlugVtable Raw_plugvt = { */ static const char *raw_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, - const char *host, int port, char **realhost, + const char *host, int port, char **realhost, bool nodelay, bool keepalive) { SockAddr *addr; @@ -154,12 +154,12 @@ static const char *raw_init(Seat *seat, Backend **backend_handle, addr = name_lookup(host, port, realhost, conf, addressfamily, raw->logctx, "main connection"); if ((err = sk_addr_error(addr)) != NULL) { - sk_addr_free(addr); - return err; + sk_addr_free(addr); + return err; } if (port < 0) - port = 23; /* default telnet port */ + port = 23; /* default telnet port */ /* * Open socket. @@ -167,18 +167,18 @@ static const char *raw_init(Seat *seat, Backend **backend_handle, raw->s = new_connection(addr, *realhost, port, false, true, nodelay, keepalive, &raw->plug, conf); if ((err = sk_socket_error(raw->s)) != NULL) - return err; + return err; loghost = conf_get_str(conf, CONF_loghost); if (*loghost) { - char *colon; + char *colon; - sfree(*realhost); - *realhost = dupstr(loghost); + sfree(*realhost); + *realhost = dupstr(loghost); - colon = host_strrchr(*realhost, ':'); - if (colon) - *colon++ = '\0'; + colon = host_strrchr(*realhost, ':'); + if (colon) + *colon++ = '\0'; } return NULL; @@ -189,7 +189,7 @@ static void raw_free(Backend *be) Raw *raw = container_of(be, Raw, backend); if (raw->s) - sk_close(raw->s); + sk_close(raw->s); conf_free(raw->conf); sfree(raw); } @@ -209,7 +209,7 @@ static size_t raw_send(Backend *be, const char *buf, size_t len) Raw *raw = container_of(be, Raw, backend); if (raw->s == NULL) - return 0; + return 0; raw->bufsize = sk_write(raw->s, buf, len); @@ -278,7 +278,7 @@ static void raw_unthrottle(Backend *be, size_t backlog) static bool raw_ldisc(Backend *be, int option) { if (option == LD_EDIT || option == LD_ECHO) - return true; + return true; return false; } diff --git a/release.pl b/release.pl index e27db47c..1c83f78f 100755 --- a/release.pl +++ b/release.pl @@ -10,7 +10,7 @@ use File::Find; use File::Temp qw/tempdir/; use LWP::UserAgent; -my $version = undef; +my $version = undef; my $setver = 0; my $upload = 0; my $precheck = 0; diff --git a/resource.h b/resource.h index 07d5008a..e856d6b9 100644 --- a/resource.h +++ b/resource.h @@ -4,7 +4,7 @@ // // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 diff --git a/rlogin.c b/rlogin.c index 7a8a3baf..e03210e5 100644 --- a/rlogin.c +++ b/rlogin.c @@ -38,7 +38,7 @@ static void c_write(Rlogin *rlogin, const void *buf, size_t len) } static void rlogin_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { Rlogin *rlogin = container_of(plug, Rlogin, plug); backend_socket_log(rlogin->seat, rlogin->logctx, type, addr, port, @@ -47,7 +47,7 @@ static void rlogin_log(Plug *plug, int type, SockAddr *addr, int port, } static void rlogin_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { Rlogin *rlogin = container_of(plug, Rlogin, plug); @@ -62,13 +62,13 @@ static void rlogin_closing(Plug *plug, const char *error_msg, int error_code, rlogin->s = NULL; if (error_msg) rlogin->closed_on_socket_error = true; - seat_notify_remote_exit(rlogin->seat); + seat_notify_remote_exit(rlogin->seat); } if (error_msg) { - /* A socket error has occurred. */ + /* A socket error has occurred. */ logevent(rlogin->logctx, error_msg); seat_connection_fatal(rlogin->seat, "%s", error_msg); - } /* Otherwise, the remote side closed the connection normally. */ + } /* Otherwise, the remote side closed the connection normally. */ } static void rlogin_receive( @@ -78,35 +78,35 @@ static void rlogin_receive( if (len == 0) return; if (urgent == 2) { - char c; + char c; - c = *data++; - len--; - if (c == '\x80') { - rlogin->cansize = true; + c = *data++; + len--; + if (c == '\x80') { + rlogin->cansize = true; backend_size(&rlogin->backend, rlogin->term_width, rlogin->term_height); } - /* - * 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... - */ + /* + * 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. - */ - if (rlogin->firstbyte) { - if (data[0] == '\0') { - data++; - len--; - } - rlogin->firstbyte = false; - } - if (len > 0) + /* + * Main rlogin protocol. This is really simple: the first + * byte is expected to be NULL and is ignored, and the rest + * is printed. + */ + if (rlogin->firstbyte) { + if (data[0] == '\0') { + data++; + len--; + } + rlogin->firstbyte = false; + } + if (len > 0) c_write(rlogin, data, len); } } @@ -147,7 +147,7 @@ static const PlugVtable Rlogin_plugvt = { /* * Called to set up the rlogin connection. - * + * * Returns an error message, or NULL on success. * * Also places the canonical host name into `realhost'. It must be @@ -155,8 +155,8 @@ static const PlugVtable Rlogin_plugvt = { */ static const char *rlogin_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, - const char *host, int port, char **realhost, - bool nodelay, bool keepalive) + const char *host, int port, char **realhost, + bool nodelay, bool keepalive) { SockAddr *addr; const char *err; @@ -187,31 +187,31 @@ static const char *rlogin_init(Seat *seat, Backend **backend_handle, addr = name_lookup(host, port, realhost, conf, addressfamily, rlogin->logctx, "rlogin connection"); if ((err = sk_addr_error(addr)) != NULL) { - sk_addr_free(addr); - return err; + sk_addr_free(addr); + return err; } if (port < 0) - port = 513; /* default rlogin port */ + port = 513; /* default rlogin port */ /* * Open socket. */ rlogin->s = new_connection(addr, *realhost, port, true, false, - nodelay, keepalive, &rlogin->plug, conf); + nodelay, keepalive, &rlogin->plug, conf); if ((err = sk_socket_error(rlogin->s)) != NULL) - return err; + return err; loghost = conf_get_str(conf, CONF_loghost); if (*loghost) { - char *colon; + char *colon; - sfree(*realhost); - *realhost = dupstr(loghost); + sfree(*realhost); + *realhost = dupstr(loghost); - colon = host_strrchr(*realhost, ':'); - if (colon) - *colon++ = '\0'; + colon = host_strrchr(*realhost, ':'); + if (colon) + *colon++ = '\0'; } /* @@ -232,7 +232,7 @@ static const char *rlogin_init(Seat *seat, Backend **backend_handle, rlogin->prompt->to_server = true; rlogin->prompt->from_server = false; rlogin->prompt->name = dupstr("Rlogin login name"); - add_prompt(rlogin->prompt, dupstr("rlogin username: "), true); + add_prompt(rlogin->prompt, dupstr("rlogin username: "), true); ret = seat_get_userpass_input(rlogin->seat, rlogin->prompt, NULL); if (ret >= 0) { /* Next terminal output will come from server */ @@ -251,7 +251,7 @@ static void rlogin_free(Backend *be) if (rlogin->prompt) free_prompts(rlogin->prompt); if (rlogin->s) - sk_close(rlogin->s); + sk_close(rlogin->s); conf_free(rlogin->conf); sfree(rlogin); } @@ -272,7 +272,7 @@ static size_t rlogin_send(Backend *be, const char *buf, size_t len) bufchain bc; if (rlogin->s == NULL) - return 0; + return 0; bufchain_init(&bc); bufchain_add(&bc, buf, len); @@ -326,7 +326,7 @@ static void rlogin_size(Backend *be, int width, int height) rlogin->term_height = height; if (rlogin->s == NULL || !rlogin->cansize) - return; + return; b[6] = rlogin->term_width >> 8; b[7] = rlogin->term_width & 0xFF; diff --git a/scpserver.c b/scpserver.c index da047823..02e2fd07 100644 --- a/scpserver.c +++ b/scpserver.c @@ -458,7 +458,7 @@ static void scp_source_abort(ScpSource *scp, const char *fmt, ...) static void scp_source_push_name( ScpSource *scp, ptrlen pathname, struct fxp_attrs attrs, const char *wc) { - if (!(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) { + if (!(attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS)) { scp_source_err(scp, "unable to read file permissions for %.*s", PTRLEN_PRINTF(pathname)); return; @@ -555,7 +555,7 @@ static void scp_source_send_CD( while ((slash = memchr(name.ptr, '/', name.len)) != NULL) name = make_ptrlen( slash+1, name.len - (slash+1 - (const char *)name.ptr)); - + scp->pending_commands[scp->n_pending_commands++] = cmd = strbuf_new(); strbuf_catf(cmd, "%c%04o %"PRIu64" %.*s\012", cmdchar, (unsigned)(attrs.permissions & 07777), diff --git a/sercfg.c b/sercfg.c index a5a3e3f4..9cd0e063 100644 --- a/sercfg.c +++ b/sercfg.c @@ -17,149 +17,149 @@ #include "storage.h" static void serial_parity_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { static const struct { - const char *name; - int val; + const char *name; + int val; } parities[] = { - {"None", SER_PAR_NONE}, - {"Odd", SER_PAR_ODD}, - {"Even", SER_PAR_EVEN}, - {"Mark", SER_PAR_MARK}, - {"Space", SER_PAR_SPACE}, + {"None", SER_PAR_NONE}, + {"Odd", SER_PAR_ODD}, + {"Even", SER_PAR_EVEN}, + {"Mark", SER_PAR_MARK}, + {"Space", SER_PAR_SPACE}, }; int mask = ctrl->listbox.context.i; int i, j; Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - /* Fetching this once at the start of the function ensures we - * remember what the right value is supposed to be when - * operations below cause reentrant calls to this function. */ - int oldparity = conf_get_int(conf, CONF_serparity); + /* Fetching this once at the start of the function ensures we + * remember what the right value is supposed to be when + * operations below cause reentrant calls to this function. */ + int oldparity = conf_get_int(conf, CONF_serparity); - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < lenof(parities); i++) { - if (mask & (1 << i)) - dlg_listbox_addwithid(ctrl, dlg, parities[i].name, - parities[i].val); - } - for (i = j = 0; i < lenof(parities); i++) { - if (mask & (1 << i)) { - if (oldparity == parities[i].val) { - dlg_listbox_select(ctrl, dlg, j); - break; - } - j++; - } - } - if (i == lenof(parities)) { /* an unsupported setting was chosen */ - dlg_listbox_select(ctrl, dlg, 0); - oldparity = SER_PAR_NONE; - } - dlg_update_done(ctrl, dlg); - conf_set_int(conf, CONF_serparity, oldparity); /* restore */ + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < lenof(parities); i++) { + if (mask & (1 << i)) + dlg_listbox_addwithid(ctrl, dlg, parities[i].name, + parities[i].val); + } + for (i = j = 0; i < lenof(parities); i++) { + if (mask & (1 << i)) { + if (oldparity == parities[i].val) { + dlg_listbox_select(ctrl, dlg, j); + break; + } + j++; + } + } + if (i == lenof(parities)) { /* an unsupported setting was chosen */ + dlg_listbox_select(ctrl, dlg, 0); + oldparity = SER_PAR_NONE; + } + dlg_update_done(ctrl, dlg); + conf_set_int(conf, CONF_serparity, oldparity); /* restore */ } else if (event == EVENT_SELCHANGE) { - int i = dlg_listbox_index(ctrl, dlg); - if (i < 0) - i = SER_PAR_NONE; - else - i = dlg_listbox_getid(ctrl, dlg, i); - conf_set_int(conf, CONF_serparity, i); + int i = dlg_listbox_index(ctrl, dlg); + if (i < 0) + i = SER_PAR_NONE; + else + i = dlg_listbox_getid(ctrl, dlg, i); + conf_set_int(conf, CONF_serparity, i); } } static void serial_flow_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { static const struct { - const char *name; - int val; + const char *name; + int val; } flows[] = { - {"None", SER_FLOW_NONE}, - {"XON/XOFF", SER_FLOW_XONXOFF}, - {"RTS/CTS", SER_FLOW_RTSCTS}, - {"DSR/DTR", SER_FLOW_DSRDTR}, + {"None", SER_FLOW_NONE}, + {"XON/XOFF", SER_FLOW_XONXOFF}, + {"RTS/CTS", SER_FLOW_RTSCTS}, + {"DSR/DTR", SER_FLOW_DSRDTR}, }; int mask = ctrl->listbox.context.i; int i, j; Conf *conf = (Conf *)data; if (event == EVENT_REFRESH) { - /* Fetching this once at the start of the function ensures we - * remember what the right value is supposed to be when - * operations below cause reentrant calls to this function. */ - int oldflow = conf_get_int(conf, CONF_serflow); + /* Fetching this once at the start of the function ensures we + * remember what the right value is supposed to be when + * operations below cause reentrant calls to this function. */ + int oldflow = conf_get_int(conf, CONF_serflow); - dlg_update_start(ctrl, dlg); - dlg_listbox_clear(ctrl, dlg); - for (i = 0; i < lenof(flows); i++) { - if (mask & (1 << i)) - dlg_listbox_addwithid(ctrl, dlg, flows[i].name, flows[i].val); - } - for (i = j = 0; i < lenof(flows); i++) { - if (mask & (1 << i)) { - if (oldflow == flows[i].val) { - dlg_listbox_select(ctrl, dlg, j); - break; - } - j++; - } - } - if (i == lenof(flows)) { /* an unsupported setting was chosen */ - dlg_listbox_select(ctrl, dlg, 0); - oldflow = SER_FLOW_NONE; - } - dlg_update_done(ctrl, dlg); - conf_set_int(conf, CONF_serflow, oldflow);/* restore */ + dlg_update_start(ctrl, dlg); + dlg_listbox_clear(ctrl, dlg); + for (i = 0; i < lenof(flows); i++) { + if (mask & (1 << i)) + dlg_listbox_addwithid(ctrl, dlg, flows[i].name, flows[i].val); + } + for (i = j = 0; i < lenof(flows); i++) { + if (mask & (1 << i)) { + if (oldflow == flows[i].val) { + dlg_listbox_select(ctrl, dlg, j); + break; + } + j++; + } + } + if (i == lenof(flows)) { /* an unsupported setting was chosen */ + dlg_listbox_select(ctrl, dlg, 0); + oldflow = SER_FLOW_NONE; + } + dlg_update_done(ctrl, dlg); + conf_set_int(conf, CONF_serflow, oldflow);/* restore */ } else if (event == EVENT_SELCHANGE) { - int i = dlg_listbox_index(ctrl, dlg); - if (i < 0) - i = SER_FLOW_NONE; - else - i = dlg_listbox_getid(ctrl, dlg, i); - conf_set_int(conf, CONF_serflow, i); + int i = dlg_listbox_index(ctrl, dlg); + if (i < 0) + i = SER_FLOW_NONE; + else + i = dlg_listbox_getid(ctrl, dlg, i); + conf_set_int(conf, CONF_serflow, i); } } void ser_setup_config_box(struct controlbox *b, bool midsession, - int parity_mask, int flow_mask) + int parity_mask, int flow_mask) { struct controlset *s; union control *c; if (!midsession) { - int i; + int i; - /* - * Add the serial back end to the protocols list at the - * top of the config box. - */ - s = ctrl_getset(b, "Session", "hostport", - "Specify the destination you want to connect to"); + /* + * Add the serial back end to the protocols list at the + * top of the config box. + */ + s = ctrl_getset(b, "Session", "hostport", + "Specify the destination you want to connect to"); for (i = 0; i < s->ncontrols; i++) { c = s->ctrls[i]; - if (c->generic.type == CTRL_RADIO && - c->generic.handler == config_protocolbuttons_handler) { - c->radio.nbuttons++; - c->radio.ncolumns++; - c->radio.buttons = - sresize(c->radio.buttons, c->radio.nbuttons, char *); - c->radio.buttons[c->radio.nbuttons-1] = - dupstr("Serial"); - c->radio.buttondata = - sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); - c->radio.buttondata[c->radio.nbuttons-1] = I(PROT_SERIAL); - if (c->radio.shortcuts) { - c->radio.shortcuts = - sresize(c->radio.shortcuts, c->radio.nbuttons, char); - c->radio.shortcuts[c->radio.nbuttons-1] = 'r'; - } - } - } + if (c->generic.type == CTRL_RADIO && + c->generic.handler == config_protocolbuttons_handler) { + c->radio.nbuttons++; + c->radio.ncolumns++; + c->radio.buttons = + sresize(c->radio.buttons, c->radio.nbuttons, char *); + c->radio.buttons[c->radio.nbuttons-1] = + dupstr("Serial"); + c->radio.buttondata = + sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); + c->radio.buttondata[c->radio.nbuttons-1] = I(PROT_SERIAL); + if (c->radio.shortcuts) { + c->radio.shortcuts = + sresize(c->radio.shortcuts, c->radio.nbuttons, char); + c->radio.shortcuts[c->radio.nbuttons-1] = 'r'; + } + } + } } /* @@ -167,38 +167,38 @@ void ser_setup_config_box(struct controlbox *b, bool midsession, * configuration. */ ctrl_settitle(b, "Connection/Serial", - "Options controlling local serial lines"); + "Options controlling local serial lines"); if (!midsession) { - /* - * We don't permit switching to a different serial port in - * midflight, although we do allow all other - * reconfiguration. - */ - s = ctrl_getset(b, "Connection/Serial", "serline", - "Select a serial line"); - ctrl_editbox(s, "Serial line to connect to", 'l', 40, - HELPCTX(serial_line), - conf_editbox_handler, I(CONF_serline), I(1)); + /* + * We don't permit switching to a different serial port in + * midflight, although we do allow all other + * reconfiguration. + */ + s = ctrl_getset(b, "Connection/Serial", "serline", + "Select a serial line"); + ctrl_editbox(s, "Serial line to connect to", 'l', 40, + HELPCTX(serial_line), + conf_editbox_handler, I(CONF_serline), I(1)); } s = ctrl_getset(b, "Connection/Serial", "sercfg", "Configure the serial line"); ctrl_editbox(s, "Speed (baud)", 's', 40, - HELPCTX(serial_speed), - conf_editbox_handler, I(CONF_serspeed), I(-1)); + HELPCTX(serial_speed), + conf_editbox_handler, I(CONF_serspeed), I(-1)); ctrl_editbox(s, "Data bits", 'b', 40, - HELPCTX(serial_databits), - conf_editbox_handler, I(CONF_serdatabits), I(-1)); + HELPCTX(serial_databits), + conf_editbox_handler, I(CONF_serdatabits), I(-1)); /* * Stop bits come in units of one half. */ ctrl_editbox(s, "Stop bits", 't', 40, - HELPCTX(serial_stopbits), - conf_editbox_handler, I(CONF_serstopbits), I(-2)); + HELPCTX(serial_stopbits), + conf_editbox_handler, I(CONF_serstopbits), I(-2)); ctrl_droplist(s, "Parity", 'p', 40, - HELPCTX(serial_parity), - serial_parity_handler, I(parity_mask)); + HELPCTX(serial_parity), + serial_parity_handler, I(parity_mask)); ctrl_droplist(s, "Flow control", 'f', 40, - HELPCTX(serial_flow), - serial_flow_handler, I(flow_mask)); + HELPCTX(serial_flow), + serial_flow_handler, I(flow_mask)); } diff --git a/sesschan.c b/sesschan.c index ecb34f4c..f9ea1418 100644 --- a/sesschan.c +++ b/sesschan.c @@ -368,7 +368,7 @@ static int xfwd_accepting(Plug *p, accept_fn_t constructor, accept_ctx_t ctx) chan = portfwd_raw_new(sess->c->cl, &plug); s = constructor(ctx, plug); if ((err = sk_socket_error(s)) != NULL) { - portfwd_raw_free(chan); + portfwd_raw_free(chan); return 1; } pi = sk_peer_info(s); @@ -444,7 +444,7 @@ static int agentfwd_accepting( chan = portfwd_raw_new(sess->c->cl, &plug); s = constructor(ctx, plug); if ((err = sk_socket_error(s)) != NULL) { - portfwd_raw_free(chan); + portfwd_raw_free(chan); return 1; } portfwd_raw_setup(chan, s, ssh_serverside_agent_open(sess->c->cl, chan)); diff --git a/settings.c b/settings.c index 2c767a7a..d7c85e23 100644 --- a/settings.c +++ b/settings.c @@ -56,12 +56,12 @@ static const struct keyvalwhere hknames[] = { * gppmap() invocation for "TerminalModes". */ const char *const ttymodes[] = { - "INTR", "QUIT", "ERASE", "KILL", "EOF", - "EOL", "EOL2", "START", "STOP", "SUSP", - "DSUSP", "REPRINT", "WERASE", "LNEXT", "FLUSH", - "SWTCH", "STATUS", "DISCARD", "IGNPAR", "PARMRK", - "INPCK", "ISTRIP", "INLCR", "IGNCR", "ICRNL", - "IUCLC", "IXON", "IXANY", "IXOFF", "IMAXBEL", + "INTR", "QUIT", "ERASE", "KILL", "EOF", + "EOL", "EOL2", "START", "STOP", "SUSP", + "DSUSP", "REPRINT", "WERASE", "LNEXT", "FLUSH", + "SWTCH", "STATUS", "DISCARD", "IGNPAR", "PARMRK", + "INPCK", "ISTRIP", "INLCR", "IGNCR", "ICRNL", + "IUCLC", "IXON", "IXANY", "IXOFF", "IMAXBEL", "IUTF8", "ISIG", "ICANON", "XCASE", "ECHO", "ECHOE", "ECHOK", "ECHONL", "NOFLSH", "TOSTOP", "IEXTEN", "ECHOCTL", "ECHOKE", "PENDIN", "OPOST", @@ -78,8 +78,8 @@ const struct BackendVtable *backend_vt_from_name(const char *name) { const struct BackendVtable *const *p; for (p = backends; *p != NULL; p++) - if (!strcmp((*p)->name, name)) - return *p; + if (!strcmp((*p)->name, name)) + return *p; return NULL; } @@ -87,8 +87,8 @@ const struct BackendVtable *backend_vt_from_proto(int proto) { const struct BackendVtable *const *p; for (p = backends; *p != NULL; p++) - if ((*p)->protocol == proto) - return *p; + if ((*p)->protocol == proto) + return *p; return NULL; } @@ -96,12 +96,12 @@ char *get_remote_username(Conf *conf) { char *username = conf_get_str(conf, CONF_username); if (*username) { - return dupstr(username); + return dupstr(username); } else if (conf_get_bool(conf, CONF_username_from_env)) { - /* Use local username. */ - return get_username(); /* might still be NULL */ + /* Use local username. */ + return get_username(); /* might still be NULL */ } else { - return NULL; + return NULL; } } @@ -109,14 +109,14 @@ static char *gpps_raw(settings_r *sesskey, const char *name, const char *def) { char *ret = read_setting_s(sesskey, name); if (!ret) - ret = platform_default_s(name); + ret = platform_default_s(name); if (!ret) - ret = def ? dupstr(def) : NULL; /* permit NULL as final fallback */ + ret = def ? dupstr(def) : NULL; /* permit NULL as final fallback */ return ret; } static void gpps(settings_r *sesskey, const char *name, const char *def, - Conf *conf, int primary) + Conf *conf, int primary) { char *val = gpps_raw(sesskey, name, def); conf_set_str(conf, primary, val); @@ -142,7 +142,7 @@ static void gppfile(settings_r *sesskey, const char *name, { Filename *result = read_setting_filename(sesskey, name); if (!result) - result = platform_default_filename(name); + result = platform_default_filename(name); conf_set_filename(conf, primary, result); filename_free(result); } @@ -195,27 +195,27 @@ static bool gppmap(settings_r *sesskey, const char *name, */ buf = gpps_raw(sesskey, name, NULL); if (!buf) - return false; + return false; p = buf; while (*p) { - q = buf; - val = NULL; - while (*p && *p != ',') { - int c = *p++; - if (c == '=') - c = '\0'; - if (c == '\\') - c = *p++; - *q++ = c; - if (!c) - val = q; - } - if (*p == ',') - p++; - if (!val) - val = q; - *q = '\0'; + q = buf; + val = NULL; + while (*p && *p != ',') { + int c = *p++; + if (c == '=') + c = '\0'; + if (c == '\\') + c = *p++; + *q++ = c; + if (!c) + val = q; + } + if (*p == ',') + p++; + if (!val) + val = q; + *q = '\0'; if (primary == CONF_portfwd && strchr(buf, 'D') != NULL) { /* @@ -253,19 +253,19 @@ static void wmap(settings_w *sesskey, char const *outkey, Conf *conf, const char *val, *q; int len; - len = 1; /* allow for NUL */ + len = 1; /* allow for NUL */ for (val = conf_get_str_strs(conf, primary, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, primary, key, &key)) - len += 2 + 2 * (strlen(key) + strlen(val)); /* allow for escaping */ + val != NULL; + val = conf_get_str_strs(conf, primary, key, &key)) + len += 2 + 2 * (strlen(key) + strlen(val)); /* allow for escaping */ buf = snewn(len, char); p = buf; for (val = conf_get_str_strs(conf, primary, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, primary, key, &key)) { + val != NULL; + val = conf_get_str_strs(conf, primary, key, &key)) { if (primary == CONF_portfwd && !strcmp(val, "D")) { /* @@ -286,13 +286,13 @@ static void wmap(settings_w *sesskey, char const *outkey, Conf *conf, realkey = NULL; } - if (p != buf) - *p++ = ','; - for (q = key; *q; q++) { - if (*q == '=' || *q == ',' || *q == '\\') - *p++ = '\\'; - *p++ = *q; - } + if (p != buf) + *p++ = ','; + for (q = key; *q; q++) { + if (*q == '=' || *q == ',' || *q == '\\') + *p++ = '\\'; + *p++ = *q; + } if (include_values) { *p++ = '='; for (q = val; *q; q++) { @@ -317,7 +317,7 @@ static int key2val(const struct keyvalwhere *mapping, { int i; for (i = 0; i < nmaps; i++) - if (!strcmp(mapping[i].s, key)) return mapping[i].v; + if (!strcmp(mapping[i].s, key)) return mapping[i].v; return -1; } @@ -326,7 +326,7 @@ static const char *val2key(const struct keyvalwhere *mapping, { int i; for (i = 0; i < nmaps; i++) - if (mapping[i].v == val) return mapping[i].s; + if (mapping[i].v == val) return mapping[i].s; return NULL; } @@ -337,13 +337,13 @@ static const char *val2key(const struct keyvalwhere *mapping, * XXX: assumes vals in 'mapping' are small +ve integers */ static void gprefs_from_str(const char *str, - const struct keyvalwhere *mapping, int nvals, - Conf *conf, int primary) + const struct keyvalwhere *mapping, int nvals, + Conf *conf, int primary) { char *commalist = dupstr(str); char *p, *q; int i, j, n, v, pos; - unsigned long seen = 0; /* bitmap for weeding dups etc */ + unsigned long seen = 0; /* bitmap for weeding dups etc */ /* * Go through that list and convert it into values. @@ -361,10 +361,10 @@ static void gprefs_from_str(const char *str, v = key2val(mapping, nvals, q); if (v != -1 && !(seen & (1 << v))) { - seen |= (1 << v); + seen |= (1 << v); conf_set_int_int(conf, primary, n, v); n++; - } + } } sfree(commalist); @@ -377,10 +377,10 @@ static void gprefs_from_str(const char *str, */ while (n < nvals) { for (i = 0; i < nvals; i++) { - assert(mapping[i].v >= 0); - assert(mapping[i].v < 32); + assert(mapping[i].v >= 0); + assert(mapping[i].v < 32); - if (!(seen & (1 << mapping[i].v))) { + if (!(seen & (1 << mapping[i].v))) { /* * This element needs adding. But can we add it yet? */ @@ -420,8 +420,8 @@ static void gprefs_from_str(const char *str, * Read a preference list. */ static void gprefs(settings_r *sesskey, const char *name, const char *def, - const struct keyvalwhere *mapping, int nvals, - Conf *conf, int primary) + const struct keyvalwhere *mapping, int nvals, + Conf *conf, int primary) { /* * Fetch the string which we'll parse as a comma-separated list. @@ -431,20 +431,20 @@ static void gprefs(settings_r *sesskey, const char *name, const char *def, sfree(value); } -/* +/* * Write out a preference list. */ static void wprefs(settings_w *sesskey, const char *name, - const struct keyvalwhere *mapping, int nvals, - Conf *conf, int primary) + const struct keyvalwhere *mapping, int nvals, + Conf *conf, int primary) { char *buf, *p; int i, maxlen; for (maxlen = i = 0; i < nvals; i++) { - const char *s = val2key(mapping, nvals, + const char *s = val2key(mapping, nvals, conf_get_int_int(conf, primary, i)); - if (s) { + if (s) { maxlen += (maxlen > 0 ? 1 : 0) + strlen(s); } } @@ -453,11 +453,11 @@ static void wprefs(settings_w *sesskey, const char *name, p = buf; for (i = 0; i < nvals; i++) { - const char *s = val2key(mapping, nvals, + const char *s = val2key(mapping, nvals, conf_get_int_int(conf, primary, i)); - if (s) { + if (s) { p += sprintf(p, "%s%s", (p > buf ? "," : ""), s); - } + } } assert(p - buf == maxlen); @@ -529,7 +529,7 @@ char *save_settings(const char *section, Conf *conf) sesskey = open_settings_w(section, &errmsg); if (!sesskey) - return errmsg; + return errmsg; save_open_settings(sesskey, conf); close_settings_w(sesskey); return NULL; @@ -562,8 +562,8 @@ void save_open_settings(settings_w *sesskey, Conf *conf) * the standard FORCE_ON / FORCE_OFF / AUTO. */ write_setting_i(sesskey, "CloseOnExit", (conf_get_int(conf, CONF_close_on_exit)+2)%3); write_setting_b(sesskey, "WarnOnClose", !!conf_get_bool(conf, CONF_warn_on_close)); - write_setting_i(sesskey, "PingInterval", conf_get_int(conf, CONF_ping_interval) / 60); /* minutes */ - write_setting_i(sesskey, "PingIntervalSecs", conf_get_int(conf, CONF_ping_interval) % 60); /* seconds */ + write_setting_i(sesskey, "PingInterval", conf_get_int(conf, CONF_ping_interval) / 60); /* minutes */ + write_setting_i(sesskey, "PingIntervalSecs", conf_get_int(conf, CONF_ping_interval) % 60); /* seconds */ write_setting_b(sesskey, "TCPNoDelay", conf_get_bool(conf, CONF_tcp_nodelay)); write_setting_b(sesskey, "TCPKeepalives", conf_get_bool(conf, CONF_tcp_keepalives)); write_setting_s(sesskey, "TerminalType", conf_get_str(conf, CONF_termtype)); @@ -666,14 +666,14 @@ void save_open_settings(settings_w *sesskey, Conf *conf) write_setting_i(sesskey, "BellOverloadN", conf_get_int(conf, CONF_bellovl_n)); write_setting_i(sesskey, "BellOverloadT", conf_get_int(conf, CONF_bellovl_t) #ifdef PUTTY_UNIX_H - * 1000 + * 1000 #endif - ); + ); write_setting_i(sesskey, "BellOverloadS", conf_get_int(conf, CONF_bellovl_s) #ifdef PUTTY_UNIX_H - * 1000 + * 1000 #endif - ); + ); write_setting_i(sesskey, "ScrollbackLines", conf_get_int(conf, CONF_savelines)); write_setting_b(sesskey, "DECOriginMode", conf_get_bool(conf, CONF_dec_om)); write_setting_b(sesskey, "AutoWrapMode", conf_get_bool(conf, CONF_wrap_mode)); @@ -696,13 +696,13 @@ void save_open_settings(settings_w *sesskey, Conf *conf) write_setting_i(sesskey, "BoldAsColour", conf_get_int(conf, CONF_bold_style)-1); for (i = 0; i < 22; i++) { - char buf[20], buf2[30]; - sprintf(buf, "Colour%d", i); - sprintf(buf2, "%d,%d,%d", - conf_get_int_int(conf, CONF_colours, i*3+0), - conf_get_int_int(conf, CONF_colours, i*3+1), - conf_get_int_int(conf, CONF_colours, i*3+2)); - write_setting_s(sesskey, buf, buf2); + char buf[20], buf2[30]; + sprintf(buf, "Colour%d", i); + sprintf(buf2, "%d,%d,%d", + conf_get_int_int(conf, CONF_colours, i*3+0), + conf_get_int_int(conf, CONF_colours, i*3+1), + conf_get_int_int(conf, CONF_colours, i*3+2)); + write_setting_s(sesskey, buf, buf2); } write_setting_b(sesskey, "RawCNP", conf_get_bool(conf, CONF_rawcnp)); write_setting_b(sesskey, "UTF8linedraw", conf_get_bool(conf, CONF_utf8linedraw)); @@ -712,16 +712,16 @@ void save_open_settings(settings_w *sesskey, Conf *conf) write_setting_b(sesskey, "PasteControls", conf_get_bool(conf, CONF_paste_controls)); write_setting_b(sesskey, "MouseOverride", conf_get_bool(conf, CONF_mouse_override)); 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", - (*buf2 ? "," : ""), - conf_get_int_int(conf, CONF_wordness, j)); - } - write_setting_s(sesskey, buf, buf2); + 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", + (*buf2 ? "," : ""), + conf_get_int_int(conf, CONF_wordness, j)); + } + write_setting_s(sesskey, buf, buf2); } write_setting_b(sesskey, "MouseAutocopy", conf_get_bool(conf, CONF_mouseautocopy)); @@ -826,8 +826,8 @@ void load_open_settings(settings_r *sesskey, Conf *conf) const struct BackendVtable *vt = backend_vt_from_name(prot); if (vt) { conf_set_int(conf, CONF_protocol, vt->protocol); - gppi(sesskey, "PortNumber", default_port, conf, CONF_port); - } + gppi(sesskey, "PortNumber", default_port, conf, CONF_port); + } } sfree(prot); @@ -839,65 +839,65 @@ void load_open_settings(settings_r *sesskey, Conf *conf) i = gppi_raw(sesskey, "CloseOnExit", 1); conf_set_int(conf, CONF_close_on_exit, (i+1)%3); gppb(sesskey, "WarnOnClose", true, conf, CONF_warn_on_close); { - /* This is two values for backward compatibility with 0.50/0.51 */ - int pingmin, pingsec; - pingmin = gppi_raw(sesskey, "PingInterval", 0); - pingsec = gppi_raw(sesskey, "PingIntervalSecs", 0); - conf_set_int(conf, CONF_ping_interval, pingmin * 60 + pingsec); + /* This is two values for backward compatibility with 0.50/0.51 */ + int pingmin, pingsec; + pingmin = gppi_raw(sesskey, "PingInterval", 0); + pingsec = gppi_raw(sesskey, "PingIntervalSecs", 0); + conf_set_int(conf, CONF_ping_interval, pingmin * 60 + pingsec); } gppb(sesskey, "TCPNoDelay", true, conf, CONF_tcp_nodelay); gppb(sesskey, "TCPKeepalives", false, conf, CONF_tcp_keepalives); gpps(sesskey, "TerminalType", "xterm", conf, CONF_termtype); gpps(sesskey, "TerminalSpeed", "38400,38400", conf, CONF_termspeed); if (gppmap(sesskey, "TerminalModes", conf, CONF_ttymodes)) { - /* - * Backwards compatibility with old saved settings. - * - * From the invention of this setting through 0.67, the set of - * terminal modes was fixed, and absence of a mode from this - * setting meant the user had explicitly removed it from the - * UI and we shouldn't send it. - * - * In 0.68, the IUTF8 mode was added, and in handling old - * settings we inadvertently removed the ability to not send - * a mode. Any mode not mentioned was treated as if it was - * set to 'auto' (A). - * - * After 0.68, we added explicit notation to the setting format - * when the user removes a known terminal mode from the list. - * - * So: if any of the modes from the original set is missing, we - * assume this was an intentional removal by the user and add - * an explicit removal ('N'); but if IUTF8 (or any other mode - * added after 0.67) is missing, we assume that its absence is - * due to the setting being old rather than intentional, and - * add it with its default setting. - * - * (This does mean that if a 0.68 user explicitly removed IUTF8, - * we add it back; but removing IUTF8 had no effect in 0.68, so - * we're preserving behaviour, which is the best we can do.) - */ - for (i = 0; ttymodes[i]; i++) { - if (!conf_get_str_str_opt(conf, CONF_ttymodes, ttymodes[i])) { - /* Mode not mentioned in setting. */ - const char *def; - if (!strcmp(ttymodes[i], "IUTF8")) { - /* Any new modes we add in future should be treated - * this way too. */ - def = "A"; /* same as new-setting default below */ - } else { - /* One of the original modes. Absence is probably - * deliberate. */ - def = "N"; /* don't send */ - } - conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], def); - } - } + /* + * Backwards compatibility with old saved settings. + * + * From the invention of this setting through 0.67, the set of + * terminal modes was fixed, and absence of a mode from this + * setting meant the user had explicitly removed it from the + * UI and we shouldn't send it. + * + * In 0.68, the IUTF8 mode was added, and in handling old + * settings we inadvertently removed the ability to not send + * a mode. Any mode not mentioned was treated as if it was + * set to 'auto' (A). + * + * After 0.68, we added explicit notation to the setting format + * when the user removes a known terminal mode from the list. + * + * So: if any of the modes from the original set is missing, we + * assume this was an intentional removal by the user and add + * an explicit removal ('N'); but if IUTF8 (or any other mode + * added after 0.67) is missing, we assume that its absence is + * due to the setting being old rather than intentional, and + * add it with its default setting. + * + * (This does mean that if a 0.68 user explicitly removed IUTF8, + * we add it back; but removing IUTF8 had no effect in 0.68, so + * we're preserving behaviour, which is the best we can do.) + */ + for (i = 0; ttymodes[i]; i++) { + if (!conf_get_str_str_opt(conf, CONF_ttymodes, ttymodes[i])) { + /* Mode not mentioned in setting. */ + const char *def; + if (!strcmp(ttymodes[i], "IUTF8")) { + /* Any new modes we add in future should be treated + * this way too. */ + def = "A"; /* same as new-setting default below */ + } else { + /* One of the original modes. Absence is probably + * deliberate. */ + def = "N"; /* don't send */ + } + conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], def); + } + } } else { - /* This hardcodes a big set of defaults in any new saved - * sessions. Let's hope we don't change our mind. */ - for (i = 0; ttymodes[i]; i++) - conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], "A"); + /* This hardcodes a big set of defaults in any new saved + * sessions. Let's hope we don't change our mind. */ + for (i = 0; ttymodes[i]; i++) + conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], "A"); } /* proxy settings */ @@ -929,7 +929,7 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gpps(sesskey, "ProxyUsername", "", conf, CONF_proxy_username); gpps(sesskey, "ProxyPassword", "", conf, CONF_proxy_password); gpps(sesskey, "ProxyTelnetCommand", "connect %host %port\\n", - conf, CONF_proxy_telnet_command); + conf, CONF_proxy_telnet_command); gppi(sesskey, "ProxyLogToTerm", FORCE_OFF, conf, CONF_proxy_log_to_term); gppmap(sesskey, "Environment", conf, CONF_environmt); gpps(sesskey, "UserName", "", conf, CONF_username); @@ -945,53 +945,53 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gppb(sesskey, "GssapiFwd", false, conf, CONF_gssapifwd); #endif gprefs(sesskey, "Cipher", "\0", - ciphernames, CIPHER_MAX, conf, CONF_ssh_cipherlist); + ciphernames, CIPHER_MAX, conf, CONF_ssh_cipherlist); { - /* Backward-compatibility: before 0.58 (when the "KEX" - * preference was first added), we had an option to - * disable gex under the "bugs" panel after one report of - * a server which offered it then choked, but we never got - * a server version string or any other reports. */ - const char *default_kexes, - *normal_default = "ecdh,dh-gex-sha1,dh-group14-sha1,rsa," - "WARN,dh-group1-sha1", - *bugdhgex2_default = "ecdh,dh-group14-sha1,rsa," - "WARN,dh-group1-sha1,dh-gex-sha1"; - char *raw; - i = 2 - gppi_raw(sesskey, "BugDHGEx2", 0); - if (i == FORCE_ON) + /* Backward-compatibility: before 0.58 (when the "KEX" + * preference was first added), we had an option to + * disable gex under the "bugs" panel after one report of + * a server which offered it then choked, but we never got + * a server version string or any other reports. */ + const char *default_kexes, + *normal_default = "ecdh,dh-gex-sha1,dh-group14-sha1,rsa," + "WARN,dh-group1-sha1", + *bugdhgex2_default = "ecdh,dh-group14-sha1,rsa," + "WARN,dh-group1-sha1,dh-gex-sha1"; + char *raw; + i = 2 - gppi_raw(sesskey, "BugDHGEx2", 0); + if (i == FORCE_ON) default_kexes = bugdhgex2_default; - else + else default_kexes = normal_default; - /* Migration: after 0.67 we decided we didn't like - * dh-group1-sha1. If it looks like the user never changed - * the defaults, quietly upgrade their settings to demote it. - * (If they did, they're on their own.) */ - raw = gpps_raw(sesskey, "KEX", default_kexes); - assert(raw != NULL); - /* Lack of 'ecdh' tells us this was saved by 0.58-0.67 - * inclusive. If it was saved by a later version, we need - * to leave it alone. */ - if (strcmp(raw, "dh-group14-sha1,dh-group1-sha1,rsa," - "WARN,dh-gex-sha1") == 0) { - /* Previously migrated from BugDHGEx2. */ - sfree(raw); - raw = dupstr(bugdhgex2_default); - } else if (strcmp(raw, "dh-gex-sha1,dh-group14-sha1," - "dh-group1-sha1,rsa,WARN") == 0) { - /* Untouched old default setting. */ - sfree(raw); - raw = dupstr(normal_default); - } - /* (For the record: after 0.70, the default algorithm list - * very briefly contained the string 'gss-sha1-krb5'; this was - * never used in any committed version of code, but was left - * over from a pre-commit version of GSS key exchange. - * Mentioned here as it is remotely possible that it will turn - * up in someone's saved settings in future.) */ + /* Migration: after 0.67 we decided we didn't like + * dh-group1-sha1. If it looks like the user never changed + * the defaults, quietly upgrade their settings to demote it. + * (If they did, they're on their own.) */ + raw = gpps_raw(sesskey, "KEX", default_kexes); + assert(raw != NULL); + /* Lack of 'ecdh' tells us this was saved by 0.58-0.67 + * inclusive. If it was saved by a later version, we need + * to leave it alone. */ + if (strcmp(raw, "dh-group14-sha1,dh-group1-sha1,rsa," + "WARN,dh-gex-sha1") == 0) { + /* Previously migrated from BugDHGEx2. */ + sfree(raw); + raw = dupstr(bugdhgex2_default); + } else if (strcmp(raw, "dh-gex-sha1,dh-group14-sha1," + "dh-group1-sha1,rsa,WARN") == 0) { + /* Untouched old default setting. */ + sfree(raw); + raw = dupstr(normal_default); + } + /* (For the record: after 0.70, the default algorithm list + * very briefly contained the string 'gss-sha1-krb5'; this was + * never used in any committed version of code, but was left + * over from a pre-commit version of GSS key exchange. + * Mentioned here as it is remotely possible that it will turn + * up in someone's saved settings in future.) */ gprefs_from_str(raw, kexnames, KEX_MAX, conf, CONF_ssh_kexlist); - sfree(raw); + sfree(raw); } gprefs(sesskey, "HostKey", "ed25519,ecdsa,rsa,dsa,WARN", hknames, HK_MAX, conf, CONF_ssh_hklist); @@ -1001,13 +1001,13 @@ void load_open_settings(settings_r *sesskey, Conf *conf) #endif gpps(sesskey, "RekeyBytes", "1G", conf, CONF_ssh_rekey_data); { - /* SSH-2 only by default */ - int sshprot = gppi_raw(sesskey, "SshProt", 3); - /* Old sessions may contain the values corresponding to the fallbacks - * we used to allow; migrate them */ - if (sshprot == 1) sshprot = 0; /* => "SSH-1 only" */ - else if (sshprot == 2) sshprot = 3; /* => "SSH-2 only" */ - conf_set_int(conf, CONF_sshprot, sshprot); + /* SSH-2 only by default */ + int sshprot = gppi_raw(sesskey, "SshProt", 3); + /* Old sessions may contain the values corresponding to the fallbacks + * we used to allow; migrate them */ + if (sshprot == 1) sshprot = 0; /* => "SSH-1 only" */ + else if (sshprot == 2) sshprot = 3; /* => "SSH-2 only" */ + conf_set_int(conf, CONF_sshprot, sshprot); } gpps(sesskey, "LogHost", "", conf, CONF_loghost); gppb(sesskey, "SSH2DES", false, conf, CONF_ssh2_des_cbc); @@ -1019,7 +1019,7 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gppb(sesskey, "AuthGSSAPI", true, conf, CONF_try_gssapi_auth); gppb(sesskey, "AuthGSSAPIKEX", true, conf, CONF_try_gssapi_kex); gprefs(sesskey, "GSSLibs", "\0", - gsslibkeywords, ngsslibs, conf, CONF_ssh_gsslist); + gsslibkeywords, ngsslibs, conf, CONF_ssh_gsslist); gppfile(sesskey, "GSSCustom", conf, CONF_ssh_gss_custom); #endif gppb(sesskey, "SshNoShell", false, conf, CONF_ssh_no_shell); @@ -1039,14 +1039,14 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gppb(sesskey, "NoRemoteClearScroll", false, conf, CONF_no_remote_clearscroll); { - /* Backward compatibility */ - int no_remote_qtitle = gppi_raw(sesskey, "NoRemoteQTitle", 1); - /* We deliberately interpret the old setting of "no response" as - * "empty string". This changes the behaviour, but hopefully for - * the better; the user can always recover the old behaviour. */ - gppi(sesskey, "RemoteQTitleAction", - no_remote_qtitle ? TITLE_EMPTY : TITLE_REAL, - conf, CONF_remote_qtitle_action); + /* Backward compatibility */ + int no_remote_qtitle = gppi_raw(sesskey, "NoRemoteQTitle", 1); + /* We deliberately interpret the old setting of "no response" as + * "empty string". This changes the behaviour, but hopefully for + * the better; the user can always recover the old behaviour. */ + gppi(sesskey, "RemoteQTitleAction", + no_remote_qtitle ? TITLE_EMPTY : TITLE_REAL, + conf, CONF_remote_qtitle_action); } gppb(sesskey, "NoDBackspace", false, conf, CONF_no_dbackspace); gppb(sesskey, "NoRemoteCharset", false, conf, CONF_no_remote_charset); @@ -1083,24 +1083,24 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gppi(sesskey, "BellOverloadN", 5, conf, CONF_bellovl_n); i = gppi_raw(sesskey, "BellOverloadT", 2*TICKSPERSEC #ifdef PUTTY_UNIX_H - *1000 + *1000 #endif - ); + ); conf_set_int(conf, CONF_bellovl_t, i #ifdef PUTTY_UNIX_H - / 1000 + / 1000 #endif - ); + ); i = gppi_raw(sesskey, "BellOverloadS", 5*TICKSPERSEC #ifdef PUTTY_UNIX_H - *1000 + *1000 #endif - ); + ); conf_set_int(conf, CONF_bellovl_s, i #ifdef PUTTY_UNIX_H - / 1000 + / 1000 #endif - ); + ); gppi(sesskey, "ScrollbackLines", 2000, conf, CONF_savelines); gppb(sesskey, "DECOriginMode", false, conf, CONF_dec_om); gppb(sesskey, "AutoWrapMode", true, conf, CONF_wrap_mode); @@ -1123,23 +1123,23 @@ void load_open_settings(settings_r *sesskey, Conf *conf) i = gppi_raw(sesskey, "BoldAsColour", 1); conf_set_int(conf, CONF_bold_style, i+1); for (i = 0; i < 22; i++) { - static const char *const 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; - int c0, c1, c2; - sprintf(buf, "Colour%d", i); - buf2 = gpps_raw(sesskey, buf, defaults[i]); - if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) { - conf_set_int_int(conf, CONF_colours, i*3+0, c0); - conf_set_int_int(conf, CONF_colours, i*3+1, c1); - conf_set_int_int(conf, CONF_colours, i*3+2, c2); - } - sfree(buf2); + static const char *const 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; + int c0, c1, c2; + sprintf(buf, "Colour%d", i); + buf2 = gpps_raw(sesskey, buf, defaults[i]); + if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) { + conf_set_int_int(conf, CONF_colours, i*3+0, c0); + conf_set_int_int(conf, CONF_colours, i*3+1, c1); + conf_set_int_int(conf, CONF_colours, i*3+2, c2); + } + sfree(buf2); } gppb(sesskey, "RawCNP", false, conf, CONF_rawcnp); gppb(sesskey, "UTF8linedraw", false, conf, CONF_utf8linedraw); @@ -1149,30 +1149,30 @@ void load_open_settings(settings_r *sesskey, Conf *conf) gppb(sesskey, "PasteControls", false, conf, CONF_paste_controls); gppb(sesskey, "MouseOverride", true, conf, CONF_mouse_override); for (i = 0; i < 256; i += 32) { - static const char *const 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", - "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", - "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", - "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", - "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", - "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", - "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" - }; - char buf[20], *buf2, *p; - int j; - sprintf(buf, "Wordness%d", i); - buf2 = gpps_raw(sesskey, buf, defaults[i / 32]); - p = buf2; - for (j = i; j < i + 32; j++) { - char *q = p; - while (*p && *p != ',') - p++; - if (*p == ',') - *p++ = '\0'; - conf_set_int_int(conf, CONF_wordness, j, atoi(q)); - } - sfree(buf2); + static const char *const 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", + "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", + "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", + "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", + "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", + "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", + "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" + }; + char buf[20], *buf2, *p; + int j; + sprintf(buf, "Wordness%d", i); + buf2 = gpps_raw(sesskey, buf, defaults[i / 32]); + p = buf2; + for (j = i; j < i + 32; j++) { + char *q = p; + while (*p && *p != ',') + p++; + if (*p == ',') + *p++ = '\0'; + conf_set_int_int(conf, CONF_wordness, j, atoi(q)); + } + sfree(buf2); } gppb(sesskey, "MouseAutocopy", CLIPUI_DEFAULT_AUTOCOPY, conf, CONF_mouseautocopy); @@ -1213,13 +1213,13 @@ void load_open_settings(settings_r *sesskey, Conf *conf) i = gppi_raw(sesskey, "BugRSA1", 0); conf_set_int(conf, CONF_sshbug_rsa1, 2-i); i = gppi_raw(sesskey, "BugIgnore2", 0); conf_set_int(conf, CONF_sshbug_ignore2, 2-i); { - int i; - i = gppi_raw(sesskey, "BugHMAC2", 0); conf_set_int(conf, CONF_sshbug_hmac2, 2-i); - if (2-i == AUTO) { - i = gppi_raw(sesskey, "BuggyMAC", 0); - if (i == 1) - conf_set_int(conf, CONF_sshbug_hmac2, FORCE_ON); - } + int i; + i = gppi_raw(sesskey, "BugHMAC2", 0); conf_set_int(conf, CONF_sshbug_hmac2, 2-i); + if (2-i == AUTO) { + i = gppi_raw(sesskey, "BuggyMAC", 0); + if (i == 1) + conf_set_int(conf, CONF_sshbug_hmac2, FORCE_ON); + } } i = gppi_raw(sesskey, "BugDeriveKey2", 0); conf_set_int(conf, CONF_sshbug_derivekey2, 2-i); i = gppi_raw(sesskey, "BugRSAPad2", 0); conf_set_int(conf, CONF_sshbug_rsapad2, 2-i); @@ -1269,14 +1269,14 @@ static int sessioncmp(const void *av, const void *bv) * 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 +1; /* b comes first */ /* * FIXME: perhaps we should ignore the first & in determining * sort order. */ - return strcmp(a, b); /* otherwise, compare normally */ + return strcmp(a, b); /* otherwise, compare normally */ } void get_sesslist(struct sesslist *list, bool allocate) @@ -1288,47 +1288,47 @@ void get_sesslist(struct sesslist *list, bool allocate) if (allocate) { strbuf *sb = strbuf_new(); - if ((handle = enum_settings_start()) != NULL) { + if ((handle = enum_settings_start()) != NULL) { while (enum_settings_next(handle, sb)) put_byte(sb, '\0'); - enum_settings_finish(handle); - } + enum_settings_finish(handle); + } put_byte(sb, '\0'); - list->buffer = strbuf_to_str(sb); + list->buffer = strbuf_to_str(sb); - /* - * Now set up the list of sessions. Note that "Default - * Settings" must always be claimed to exist, even if it - * doesn't really. - */ + /* + * Now set up the list of sessions. Note that "Default + * Settings" must always be claimed to exist, even if it + * doesn't really. + */ - p = list->buffer; - list->nsessions = 1; /* "Default Settings" counts as one */ - while (*p) { - if (strcmp(p, "Default Settings")) - list->nsessions++; - while (*p) - p++; - p++; - } + p = list->buffer; + list->nsessions = 1; /* "Default Settings" counts as one */ + while (*p) { + if (strcmp(p, "Default Settings")) + list->nsessions++; + while (*p) + p++; + p++; + } - list->sessions = snewn(list->nsessions + 1, const char *); - list->sessions[0] = "Default Settings"; - p = list->buffer; - i = 1; - while (*p) { - if (strcmp(p, "Default Settings")) - list->sessions[i++] = p; - while (*p) - p++; - p++; - } + list->sessions = snewn(list->nsessions + 1, const char *); + list->sessions[0] = "Default Settings"; + p = list->buffer; + i = 1; + while (*p) { + if (strcmp(p, "Default Settings")) + list->sessions[i++] = p; + while (*p) + p++; + p++; + } - qsort(list->sessions, i, sizeof(const char *), sessioncmp); + qsort(list->sessions, i, sizeof(const char *), sessioncmp); } else { - sfree(list->buffer); - sfree(list->sessions); - list->buffer = NULL; - list->sessions = NULL; + sfree(list->buffer); + sfree(list->sessions); + list->buffer = NULL; + list->sessions = NULL; } } diff --git a/sftp.c b/sftp.c index 4efcf7a1..0b9355d3 100644 --- a/sftp.c +++ b/sftp.c @@ -36,18 +36,18 @@ struct sftp_packet *sftp_recv(void) char x[4]; if (!sftp_recvdata(x, 4)) - return NULL; + return NULL; pkt = sftp_recv_prepare(GET_32BIT_MSB_FIRST(x)); if (!sftp_recvdata(pkt->data, pkt->length)) { - sftp_pkt_free(pkt); - return NULL; + sftp_pkt_free(pkt); + return NULL; } if (!sftp_recv_finish(pkt)) { - sftp_pkt_free(pkt); - return NULL; + sftp_pkt_free(pkt); + return NULL; } return pkt; @@ -70,9 +70,9 @@ static int sftp_reqcmp(void *av, void *bv) struct sftp_request *a = (struct sftp_request *)av; struct sftp_request *b = (struct sftp_request *)bv; if (a->id < b->id) - return -1; + return -1; if (a->id > b->id) - return +1; + return +1; return 0; } static int sftp_reqfind(void *av, void *bv) @@ -80,9 +80,9 @@ static int sftp_reqfind(void *av, void *bv) unsigned *a = (unsigned *) av; struct sftp_request *b = (struct sftp_request *)bv; if (*a < b->id) - return -1; + return -1; if (*a > b->id) - return +1; + return +1; return 0; } @@ -95,7 +95,7 @@ static struct sftp_request *sftp_alloc_request(void) struct sftp_request *r; if (sftp_requests == NULL) - sftp_requests = newtree234(sftp_reqcmp); + sftp_requests = newtree234(sftp_reqcmp); /* * First-fit allocation of request IDs: always pick the lowest @@ -110,20 +110,20 @@ static struct sftp_request *sftp_alloc_request(void) low = -1; high = tsize; while (high - low > 1) { - mid = (high + low) / 2; - r = index234(sftp_requests, mid); - if (r->id == mid + REQUEST_ID_OFFSET) - low = mid; /* this one is fine */ - else - high = mid; /* this one is past it */ + mid = (high + low) / 2; + r = index234(sftp_requests, mid); + if (r->id == mid + REQUEST_ID_OFFSET) + low = mid; /* this one is fine */ + else + high = mid; /* this one is past it */ } /* * Now low points to either -1, or the tree index of the * largest ID in the initial sequence. */ { - unsigned i = low + 1 + REQUEST_ID_OFFSET; - assert(NULL == find234(sftp_requests, &i, sftp_reqfind)); + unsigned i = low + 1 + REQUEST_ID_OFFSET; + assert(NULL == find234(sftp_requests, &i, sftp_reqfind)); } /* @@ -141,8 +141,8 @@ static struct sftp_request *sftp_alloc_request(void) void sftp_cleanup_request(void) { if (sftp_requests != NULL) { - freetree234(sftp_requests); - sftp_requests = NULL; + freetree234(sftp_requests); + sftp_requests = NULL; } } @@ -157,20 +157,20 @@ struct sftp_request *sftp_find_request(struct sftp_packet *pktin) struct sftp_request *req; if (!pktin) { - fxp_internal_error("did not receive a valid SFTP packet\n"); - return NULL; + fxp_internal_error("did not receive a valid SFTP packet\n"); + return NULL; } id = get_uint32(pktin); if (get_err(pktin)) { - fxp_internal_error("did not receive a valid SFTP packet\n"); - return NULL; + fxp_internal_error("did not receive a valid SFTP packet\n"); + return NULL; } req = find234(sftp_requests, &id, sftp_reqfind); if (!req || !req->registered) { - fxp_internal_error("request ID mismatch\n"); - return NULL; + fxp_internal_error("request ID mismatch\n"); + return NULL; } del234(sftp_requests, req); @@ -190,42 +190,42 @@ struct sftp_request *sftp_find_request(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 - * success, so this is actually an error message! */ - "unexpected OK response", - "end of file", - "no such file or directory", - "permission denied", - "failure", - "bad message", - "no connection", - "connection lost", - "operation unsupported", + /* SSH_FX_OK. The only time we will display a _message_ for this + * is if we were expecting something other than FXP_STATUS on + * success, so this is actually an error message! */ + "unexpected OK response", + "end of file", + "no such file or directory", + "permission denied", + "failure", + "bad message", + "no connection", + "connection lost", + "operation unsupported", }; if (pktin->type != SSH_FXP_STATUS) { - fxp_error_message = "expected FXP_STATUS packet"; - fxp_errtype = -1; + fxp_error_message = "expected FXP_STATUS packet"; + fxp_errtype = -1; } else { - fxp_errtype = get_uint32(pktin); - if (get_err(pktin)) { - fxp_error_message = "malformed FXP_STATUS packet"; - fxp_errtype = -1; - } else { - if (fxp_errtype < 0 || fxp_errtype >= lenof(messages)) - fxp_error_message = "unknown error code"; - else - fxp_error_message = messages[fxp_errtype]; - } + fxp_errtype = get_uint32(pktin); + if (get_err(pktin)) { + fxp_error_message = "malformed FXP_STATUS packet"; + fxp_errtype = -1; + } else { + if (fxp_errtype < 0 || fxp_errtype >= lenof(messages)) + fxp_error_message = "unknown error code"; + else + fxp_error_message = messages[fxp_errtype]; + } } if (fxp_errtype == SSH_FX_OK) - return 1; + return 1; else if (fxp_errtype == SSH_FX_EOF) - return 0; + return 0; else - return -1; + return -1; } static void fxp_internal_error(const char *msg) @@ -258,25 +258,25 @@ bool fxp_init(void) pktin = sftp_recv(); if (!pktin) { - fxp_internal_error("could not connect"); - return false; + fxp_internal_error("could not connect"); + return false; } if (pktin->type != SSH_FXP_VERSION) { - fxp_internal_error("did not receive FXP_VERSION"); + fxp_internal_error("did not receive FXP_VERSION"); sftp_pkt_free(pktin); - return false; + return false; } remotever = get_uint32(pktin); if (get_err(pktin)) { - fxp_internal_error("malformed FXP_VERSION packet"); + fxp_internal_error("malformed FXP_VERSION packet"); sftp_pkt_free(pktin); - return false; + return false; } 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"); sftp_pkt_free(pktin); - return false; + return false; } /* * In principle, this packet might also contain extension- @@ -310,29 +310,29 @@ char *fxp_realpath_recv(struct sftp_packet *pktin, struct sftp_request *req) sfree(req); if (pktin->type == SSH_FXP_NAME) { - unsigned long count; + unsigned long count; char *path; ptrlen name; count = get_uint32(pktin); - if (get_err(pktin) || count != 1) { - fxp_internal_error("REALPATH did not return name count of 1\n"); + if (get_err(pktin) || count != 1) { + fxp_internal_error("REALPATH did not return name count of 1\n"); sftp_pkt_free(pktin); - return NULL; - } + return NULL; + } name = get_string(pktin); - if (get_err(pktin)) { - fxp_internal_error("REALPATH returned malformed FXP_NAME\n"); + if (get_err(pktin)) { + fxp_internal_error("REALPATH returned malformed FXP_NAME\n"); sftp_pkt_free(pktin); - return NULL; - } + return NULL; + } path = mkstr(name); - sftp_pkt_free(pktin); + sftp_pkt_free(pktin); return path; } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return NULL; + return NULL; } } @@ -374,16 +374,16 @@ static struct fxp_handle *fxp_got_handle(struct sftp_packet *pktin) } struct fxp_handle *fxp_open_recv(struct sftp_packet *pktin, - struct sftp_request *req) + struct sftp_request *req) { sfree(req); if (pktin->type == SSH_FXP_HANDLE) { return fxp_got_handle(pktin); } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return NULL; + return NULL; } } @@ -404,15 +404,15 @@ struct sftp_request *fxp_opendir_send(const char *path) } struct fxp_handle *fxp_opendir_recv(struct sftp_packet *pktin, - struct sftp_request *req) + struct sftp_request *req) { sfree(req); if (pktin->type == SSH_FXP_HANDLE) { return fxp_got_handle(pktin); } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return NULL; + return NULL; } } @@ -565,15 +565,15 @@ static bool fxp_got_attrs(struct sftp_packet *pktin, struct fxp_attrs *attrs) } bool fxp_stat_recv(struct sftp_packet *pktin, struct sftp_request *req, - struct fxp_attrs *attrs) + struct fxp_attrs *attrs) { sfree(req); if (pktin->type == SSH_FXP_ATTRS) { return fxp_got_attrs(pktin, attrs); } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return false; + return false; } } @@ -597,9 +597,9 @@ bool fxp_fstat_recv(struct sftp_packet *pktin, struct sftp_request *req, if (pktin->type == SSH_FXP_ATTRS) { return fxp_got_attrs(pktin, attrs); } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return false; + return false; } } @@ -631,7 +631,7 @@ bool fxp_setstat_recv(struct sftp_packet *pktin, struct sftp_request *req) } struct sftp_request *fxp_fsetstat_send(struct fxp_handle *handle, - struct fxp_attrs attrs) + struct fxp_attrs attrs) { struct sftp_request *req = sftp_alloc_request(); struct sftp_packet *pktout; @@ -661,7 +661,7 @@ bool fxp_fsetstat_recv(struct sftp_packet *pktin, struct sftp_request *req) * error indicator. It might even depend on the SFTP server.) */ struct sftp_request *fxp_read_send(struct fxp_handle *handle, - uint64_t offset, int len) + uint64_t offset, int len) { struct sftp_request *req = sftp_alloc_request(); struct sftp_packet *pktout; @@ -677,32 +677,32 @@ struct sftp_request *fxp_read_send(struct fxp_handle *handle, } int fxp_read_recv(struct sftp_packet *pktin, struct sftp_request *req, - char *buffer, int len) + char *buffer, int len) { sfree(req); if (pktin->type == SSH_FXP_DATA) { ptrlen data; data = get_string(pktin); - if (get_err(pktin)) { - fxp_internal_error("READ returned malformed SSH_FXP_DATA packet"); + if (get_err(pktin)) { + fxp_internal_error("READ returned malformed SSH_FXP_DATA packet"); sftp_pkt_free(pktin); - return -1; - } + return -1; + } - if (data.len > len) { - fxp_internal_error("READ returned more bytes than requested"); + if (data.len > len) { + fxp_internal_error("READ returned more bytes than requested"); sftp_pkt_free(pktin); - return -1; - } + return -1; + } - memcpy(buffer, data.ptr, data.len); + memcpy(buffer, data.ptr, data.len); sftp_pkt_free(pktin); - return data.len; + return data.len; } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return -1; + return -1; } } @@ -723,50 +723,50 @@ struct sftp_request *fxp_readdir_send(struct fxp_handle *handle) } struct fxp_names *fxp_readdir_recv(struct sftp_packet *pktin, - struct sftp_request *req) + struct sftp_request *req) { sfree(req); if (pktin->type == SSH_FXP_NAME) { - struct fxp_names *ret; - unsigned long i; + struct fxp_names *ret; + unsigned long i; i = get_uint32(pktin); - /* - * Sanity-check the number of names. Minimum is obviously - * zero. Maximum is the remaining space in the packet - * divided by the very minimum length of a name, which is - * 12 bytes (4 for an empty filename, 4 for an empty - * longname, 4 for a set of attribute flags indicating that - * no other attributes are supplied). - */ - if (get_err(pktin) || i > get_avail(pktin) / 12) { - fxp_internal_error("malformed FXP_NAME packet"); - sftp_pkt_free(pktin); - return NULL; - } + /* + * Sanity-check the number of names. Minimum is obviously + * zero. Maximum is the remaining space in the packet + * divided by the very minimum length of a name, which is + * 12 bytes (4 for an empty filename, 4 for an empty + * longname, 4 for a set of attribute flags indicating that + * no other attributes are supplied). + */ + if (get_err(pktin) || i > get_avail(pktin) / 12) { + fxp_internal_error("malformed FXP_NAME packet"); + sftp_pkt_free(pktin); + return NULL; + } - /* - * Ensure the implicit multiplication in the snewn() call - * doesn't suffer integer overflow and cause us to malloc - * too little space. - */ - if (i > INT_MAX / sizeof(struct fxp_name)) { - fxp_internal_error("unreasonably large FXP_NAME packet"); - sftp_pkt_free(pktin); - return NULL; - } + /* + * Ensure the implicit multiplication in the snewn() call + * doesn't suffer integer overflow and cause us to malloc + * too little space. + */ + if (i > INT_MAX / sizeof(struct fxp_name)) { + fxp_internal_error("unreasonably large FXP_NAME packet"); + sftp_pkt_free(pktin); + return NULL; + } - ret = snew(struct fxp_names); - ret->nnames = i; - ret->names = snewn(ret->nnames, struct fxp_name); - for (i = 0; i < (unsigned long)ret->nnames; i++) { - ret->names[i].filename = mkstr(get_string(pktin)); - ret->names[i].longname = mkstr(get_string(pktin)); + ret = snew(struct fxp_names); + ret->nnames = i; + ret->names = snewn(ret->nnames, struct fxp_name); + for (i = 0; i < (unsigned long)ret->nnames; i++) { + ret->names[i].filename = mkstr(get_string(pktin)); + ret->names[i].longname = mkstr(get_string(pktin)); get_fxp_attrs(pktin, &ret->names[i].attrs); } - if (get_err(pktin)) { + if (get_err(pktin)) { fxp_internal_error("malformed FXP_NAME packet"); for (i = 0; i < (unsigned long)ret->nnames; i++) { sfree(ret->names[i].filename); @@ -776,13 +776,13 @@ struct fxp_names *fxp_readdir_recv(struct sftp_packet *pktin, sfree(ret); sfree(pktin); return NULL; - } + } sftp_pkt_free(pktin); - return ret; + return ret; } else { - fxp_got_status(pktin); + fxp_got_status(pktin); sftp_pkt_free(pktin); - return NULL; + return NULL; } } @@ -790,7 +790,7 @@ struct fxp_names *fxp_readdir_recv(struct sftp_packet *pktin, * Write to a file. Returns 0 on error, 1 on OK. */ struct sftp_request *fxp_write_send(struct fxp_handle *handle, - void *buffer, uint64_t offset, int len) + void *buffer, uint64_t offset, int len) { struct sftp_request *req = sftp_alloc_request(); struct sftp_packet *pktout; @@ -821,8 +821,8 @@ void fxp_free_names(struct fxp_names *names) int i; for (i = 0; i < names->nnames; i++) { - sfree(names->names[i].filename); - sfree(names->names[i].longname); + sfree(names->names[i].filename); + sfree(names->names[i].longname); } sfree(names->names); sfree(names); @@ -837,7 +837,7 @@ struct fxp_name *fxp_dup_name(struct fxp_name *name) ret = snew(struct fxp_name); ret->filename = dupstr(name->filename); ret->longname = dupstr(name->longname); - ret->attrs = name->attrs; /* structure copy */ + ret->attrs = name->attrs; /* structure copy */ return ret; } @@ -912,33 +912,33 @@ bool xfer_done(struct fxp_xfer *xfer) void xfer_download_queue(struct fxp_xfer *xfer) { while (xfer->req_totalsize < xfer->req_maxsize && - !xfer->eof && !xfer->err) { - /* - * Queue a new read request. - */ - struct req *rr; - struct sftp_request *req; + !xfer->eof && !xfer->err) { + /* + * Queue a new read request. + */ + struct req *rr; + struct sftp_request *req; - rr = snew(struct req); - rr->offset = xfer->offset; - rr->complete = 0; - if (xfer->tail) { - xfer->tail->next = rr; - rr->prev = xfer->tail; - } else { - xfer->head = rr; - rr->prev = NULL; - } - xfer->tail = rr; - rr->next = NULL; + rr = snew(struct req); + rr->offset = xfer->offset; + rr->complete = 0; + if (xfer->tail) { + xfer->tail->next = rr; + rr->prev = xfer->tail; + } else { + xfer->head = rr; + rr->prev = NULL; + } + xfer->tail = rr; + rr->next = NULL; - rr->len = 32768; - rr->buffer = snewn(rr->len, char); - sftp_register(req = fxp_read_send(xfer->fh, rr->offset, rr->len)); - fxp_set_userdata(req, rr); + rr->len = 32768; + rr->buffer = snewn(rr->len, char); + sftp_register(req = fxp_read_send(xfer->fh, rr->offset, rr->len)); + fxp_set_userdata(req, rr); - xfer->offset += rr->len; - xfer->req_totalsize += rr->len; + xfer->offset += rr->len; + xfer->req_totalsize += rr->len; #ifdef DEBUG_DOWNLOAD printf("queueing read request %p at %"PRIu64"\n", rr, rr->offset); @@ -971,7 +971,7 @@ int xfer_download_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin) rr = (struct req *)fxp_get_userdata(rreq); if (!rr) { fxp_internal_error("request ID is not part of the current download"); - return INT_MIN; /* this packet isn't ours */ + return INT_MIN; /* this packet isn't ours */ } rr->retlen = fxp_read_recv(pktin, rreq, rr->buffer, rr->len); #ifdef DEBUG_DOWNLOAD @@ -979,17 +979,17 @@ int xfer_download_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin) #endif if ((rr->retlen < 0 && fxp_error_type()==SSH_FX_EOF) || rr->retlen == 0) { - xfer->eof = true; + xfer->eof = true; rr->retlen = 0; - rr->complete = -1; + rr->complete = -1; #ifdef DEBUG_DOWNLOAD - printf("setting eof\n"); + printf("setting eof\n"); #endif } else if (rr->retlen < 0) { - /* some error other than EOF; signal it back to caller */ - xfer_set_error(xfer); - rr->complete = -1; - return -1; + /* some error other than EOF; signal it back to caller */ + xfer_set_error(xfer); + rr->complete = -1; + return -1; } rr->complete = 1; @@ -1007,31 +1007,31 @@ int xfer_download_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin) * the first place... */ if (rr->retlen > 0 && xfer->furthestdata < rr->offset) { - xfer->furthestdata = rr->offset; + xfer->furthestdata = rr->offset; #ifdef DEBUG_DOWNLOAD - printf("setting furthestdata = %"PRIu64"\n", xfer->furthestdata); + printf("setting furthestdata = %"PRIu64"\n", xfer->furthestdata); #endif } if (rr->retlen < rr->len) { - uint64_t filesize = rr->offset + (rr->retlen < 0 ? 0 : rr->retlen); + uint64_t filesize = rr->offset + (rr->retlen < 0 ? 0 : rr->retlen); #ifdef DEBUG_DOWNLOAD - printf("short block! trying filesize = %"PRIu64"\n", filesize); + printf("short block! trying filesize = %"PRIu64"\n", filesize); #endif - if (xfer->filesize > filesize) { - xfer->filesize = filesize; + if (xfer->filesize > filesize) { + xfer->filesize = filesize; #ifdef DEBUG_DOWNLOAD - printf("actually changing filesize\n"); -#endif - } + printf("actually changing filesize\n"); +#endif + } } if (xfer->furthestdata > xfer->filesize) { - fxp_error_message = "received a short buffer from FXP_READ, but not" - " at EOF"; - fxp_errtype = -1; - xfer_set_error(xfer); - return -1; + fxp_error_message = "received a short buffer from FXP_READ, but not" + " at EOF"; + fxp_errtype = -1; + xfer_set_error(xfer); + return -1; } return 1; @@ -1052,35 +1052,35 @@ bool xfer_download_data(struct fxp_xfer *xfer, void **buf, int *len) * 0; return the first thing with complete > 0. */ while (xfer->head && xfer->head->complete && !retbuf) { - struct req *rr = xfer->head; + struct req *rr = xfer->head; - if (rr->complete > 0) { - retbuf = rr->buffer; - retlen = rr->retlen; + if (rr->complete > 0) { + retbuf = rr->buffer; + retlen = rr->retlen; #ifdef DEBUG_DOWNLOAD - printf("handing back data from read request %p\n", rr); + printf("handing back data from read request %p\n", rr); #endif - } + } #ifdef DEBUG_DOWNLOAD - else - printf("skipping failed read request %p\n", rr); + else + printf("skipping failed read request %p\n", rr); #endif - xfer->head = xfer->head->next; - if (xfer->head) - xfer->head->prev = NULL; - else - xfer->tail = NULL; - xfer->req_totalsize -= rr->len; - sfree(rr); + xfer->head = xfer->head->next; + if (xfer->head) + xfer->head->prev = NULL; + else + xfer->tail = NULL; + xfer->req_totalsize -= rr->len; + sfree(rr); } if (retbuf) { - *buf = retbuf; - *len = retlen; - return true; + *buf = retbuf; + *len = retlen; + return true; } else - return false; + return false; } struct fxp_xfer *xfer_upload_init(struct fxp_handle *fh, uint64_t offset) @@ -1114,11 +1114,11 @@ void xfer_upload_data(struct fxp_xfer *xfer, char *buffer, int len) rr->offset = xfer->offset; rr->complete = 0; if (xfer->tail) { - xfer->tail->next = rr; - rr->prev = xfer->tail; + xfer->tail->next = rr; + rr->prev = xfer->tail; } else { - xfer->head = rr; - rr->prev = NULL; + xfer->head = rr; + rr->prev = NULL; } xfer->tail = rr; rr->next = NULL; @@ -1153,7 +1153,7 @@ int xfer_upload_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin) rr = (struct req *)fxp_get_userdata(rreq); if (!rr) { fxp_internal_error("request ID is not part of the current upload"); - return INT_MIN; /* this packet isn't ours */ + return INT_MIN; /* this packet isn't ours */ } ret = fxp_write_recv(pktin, rreq); #ifdef DEBUG_UPLOAD @@ -1166,18 +1166,18 @@ int xfer_upload_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin) prev = rr->prev; next = rr->next; if (prev) - prev->next = next; + prev->next = next; else - xfer->head = next; + xfer->head = next; if (next) - next->prev = prev; + next->prev = prev; else - xfer->tail = prev; + xfer->tail = prev; xfer->req_totalsize -= rr->len; sfree(rr); if (!ret) - return -1; + return -1; return 1; } @@ -1186,10 +1186,10 @@ void xfer_cleanup(struct fxp_xfer *xfer) { struct req *rr; while (xfer->head) { - rr = xfer->head; - xfer->head = xfer->head->next; - sfree(rr->buffer); - sfree(rr); + rr = xfer->head; + xfer->head = xfer->head->next; + sfree(rr->buffer); + sfree(rr); } sfree(xfer); } diff --git a/sftp.h b/sftp.h index 0b4ad92d..5835c16b 100644 --- a/sftp.h +++ b/sftp.h @@ -4,31 +4,31 @@ #include "defs.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 @@ -60,11 +60,11 @@ /* * External references. The sftp client module sftp.c expects to be * able to get at these functions. - * + * * sftp_recvdata must never return less than len. It either blocks * until len is available and then returns true, or it returns false * for failure. - * + * * sftp_senddata returns true on success, false on failure. * * sftp_sendbuffer returns the size of the backlog of data in the @@ -182,14 +182,14 @@ char *fxp_realpath_recv(struct sftp_packet *pktin, struct sftp_request *req); struct sftp_request *fxp_open_send(const char *path, int type, const struct fxp_attrs *attrs); struct fxp_handle *fxp_open_recv(struct sftp_packet *pktin, - struct sftp_request *req); + struct sftp_request *req); /* * Open a directory. */ struct sftp_request *fxp_opendir_send(const char *path); struct fxp_handle *fxp_opendir_recv(struct sftp_packet *pktin, - struct sftp_request *req); + struct sftp_request *req); /* * Close a file/dir. Returns true on success, false on error. @@ -240,14 +240,14 @@ struct sftp_request *fxp_setstat_send(const char *fname, struct fxp_attrs attrs); bool fxp_setstat_recv(struct sftp_packet *pktin, struct sftp_request *req); struct sftp_request *fxp_fsetstat_send(struct fxp_handle *handle, - struct fxp_attrs attrs); + struct fxp_attrs attrs); bool fxp_fsetstat_recv(struct sftp_packet *pktin, struct sftp_request *req); /* * Read from a file. */ struct sftp_request *fxp_read_send(struct fxp_handle *handle, - uint64_t offset, int len); + uint64_t offset, int len); int fxp_read_recv(struct sftp_packet *pktin, struct sftp_request *req, char *buffer, int len); @@ -255,7 +255,7 @@ int fxp_read_recv(struct sftp_packet *pktin, struct sftp_request *req, * Write to a file. */ struct sftp_request *fxp_write_send(struct fxp_handle *handle, - void *buffer, uint64_t offset, int len); + void *buffer, uint64_t offset, int len); bool fxp_write_recv(struct sftp_packet *pktin, struct sftp_request *req); /* @@ -263,7 +263,7 @@ bool fxp_write_recv(struct sftp_packet *pktin, struct sftp_request *req); */ struct sftp_request *fxp_readdir_send(struct fxp_handle *handle); struct fxp_names *fxp_readdir_recv(struct sftp_packet *pktin, - struct sftp_request *req); + struct sftp_request *req); /* * Free up an fxp_names structure. diff --git a/sftpcommon.c b/sftpcommon.c index 43b65755..f2f9a3bc 100644 --- a/sftpcommon.c +++ b/sftpcommon.c @@ -42,23 +42,23 @@ void BinarySink_put_fxp_attrs(BinarySink *bs, struct fxp_attrs attrs) { put_uint32(bs, attrs.flags); if (attrs.flags & SSH_FILEXFER_ATTR_SIZE) - put_uint64(bs, attrs.size); + put_uint64(bs, attrs.size); if (attrs.flags & SSH_FILEXFER_ATTR_UIDGID) { - put_uint32(bs, attrs.uid); - put_uint32(bs, attrs.gid); + put_uint32(bs, attrs.uid); + put_uint32(bs, attrs.gid); } if (attrs.flags & SSH_FILEXFER_ATTR_PERMISSIONS) { - put_uint32(bs, attrs.permissions); + put_uint32(bs, attrs.permissions); } if (attrs.flags & SSH_FILEXFER_ATTR_ACMODTIME) { - put_uint32(bs, attrs.atime); - put_uint32(bs, attrs.mtime); + put_uint32(bs, attrs.atime); + put_uint32(bs, attrs.mtime); } if (attrs.flags & SSH_FILEXFER_ATTR_EXTENDED) { - /* - * We currently don't support sending any extended - * attributes. - */ + /* + * We currently don't support sending any extended + * attributes. + */ } } @@ -73,31 +73,31 @@ bool BinarySource_get_fxp_attrs(BinarySource *src, struct fxp_attrs *attrs) if (attrs->flags & SSH_FILEXFER_ATTR_SIZE) attrs->size = get_uint64(src); if (attrs->flags & SSH_FILEXFER_ATTR_UIDGID) { - attrs->uid = get_uint32(src); - attrs->gid = get_uint32(src); + attrs->uid = get_uint32(src); + attrs->gid = get_uint32(src); } if (attrs->flags & SSH_FILEXFER_ATTR_PERMISSIONS) - attrs->permissions = get_uint32(src); + attrs->permissions = get_uint32(src); if (attrs->flags & SSH_FILEXFER_ATTR_ACMODTIME) { - attrs->atime = get_uint32(src); - attrs->mtime = get_uint32(src); + attrs->atime = get_uint32(src); + attrs->mtime = get_uint32(src); } if (attrs->flags & SSH_FILEXFER_ATTR_EXTENDED) { - unsigned long count = get_uint32(src); - while (count--) { - if (get_err(src)) { - /* Truncated packet. Don't waste time looking for - * attributes that aren't there. Caller should spot - * the truncation. */ - break; - } - /* - * We should try to analyse these, if we ever find one - * we recognise. - */ - get_string(src); - get_string(src); - } + unsigned long count = get_uint32(src); + while (count--) { + if (get_err(src)) { + /* Truncated packet. Don't waste time looking for + * attributes that aren't there. Caller should spot + * the truncation. */ + break; + } + /* + * We should try to analyse these, if we ever find one + * we recognise. + */ + get_string(src); + get_string(src); + } } return true; } @@ -105,7 +105,7 @@ bool BinarySource_get_fxp_attrs(BinarySource *src, struct fxp_attrs *attrs) void sftp_pkt_free(struct sftp_packet *pkt) { if (pkt->data) - sfree(pkt->data); + sfree(pkt->data); sfree(pkt); } diff --git a/sign.sh b/sign.sh index 2d81c635..f3300322 100755 --- a/sign.sh +++ b/sign.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/sh # Generate GPG signatures on a PuTTY release/snapshot directory as # delivered by Buildscr. diff --git a/ssh.c b/ssh.c index f7957bb0..417d6c11 100644 --- a/ssh.c +++ b/ssh.c @@ -22,11 +22,11 @@ #ifndef NO_GSSAPI #include "sshgssc.h" #include "sshgss.h" -#define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */ -#define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */ +#define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */ +#define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */ #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */ -#define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */ -#define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */ +#define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */ +#define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */ #endif struct Ssh { @@ -240,7 +240,7 @@ static void ssh_got_ssh_version(struct ssh_version_receiver *rcv, #endif connection_layer = ssh2_connection_new( - ssh, ssh->connshare, is_simple, ssh->conf, + ssh, ssh->connshare, is_simple, ssh->conf, ssh_verstring_get_remote(old_bpp), &ssh->cl); ssh_connect_ppl(ssh, connection_layer); @@ -596,7 +596,7 @@ static void ssh_socket_log(Plug *plug, int type, SockAddr *addr, int port, } static void ssh_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { Ssh *ssh = container_of(plug, Ssh, plug); if (error_msg) { @@ -613,8 +613,8 @@ static void ssh_receive(Plug *plug, int urgent, const char *data, size_t len) /* Log raw data, if we're in that mode. */ if (ssh->logctx) - log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len, - 0, NULL, NULL, 0, NULL); + log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len, + 0, NULL, NULL, 0, NULL); bufchain_add(&ssh->in_raw, data, len); if (!ssh->logically_frozen && ssh->bpp) @@ -633,7 +633,7 @@ static void ssh_sent(Plug *plug, size_t bufsize) * some more data off its bufchain. */ if (bufsize < SSH_MAX_BACKLOG) { - ssh_throttle_all(ssh, false, bufsize); + ssh_throttle_all(ssh, false, bufsize); queue_idempotent_callback(&ssh->ic_out_raw); } } @@ -647,31 +647,31 @@ static void ssh_hostport_setup(const char *host, int port, Conf *conf, *loghost_ret = loghost; if (*loghost) { - char *tmphost; + char *tmphost; char *colon; tmphost = dupstr(loghost); - *savedport = 22; /* default ssh port */ + *savedport = 22; /* default ssh port */ - /* - * A colon suffix on the hostname string also lets us affect - * savedport. (Unless there are multiple colons, in which case - * we assume this is an unbracketed IPv6 literal.) - */ - colon = host_strrchr(tmphost, ':'); - if (colon && colon == host_strchr(tmphost, ':')) { - *colon++ = '\0'; - if (*colon) - *savedport = atoi(colon); - } + /* + * A colon suffix on the hostname string also lets us affect + * savedport. (Unless there are multiple colons, in which case + * we assume this is an unbracketed IPv6 literal.) + */ + colon = host_strrchr(tmphost, ':'); + if (colon && colon == host_strchr(tmphost, ':')) { + *colon++ = '\0'; + if (*colon) + *savedport = atoi(colon); + } *savedhost = host_strduptrim(tmphost); sfree(tmphost); } else { - *savedhost = host_strduptrim(host); - if (port < 0) - port = 22; /* default ssh port */ - *savedport = port; + *savedhost = host_strduptrim(host); + if (port < 0) + port = 22; /* default ssh port */ + *savedport = port; } } @@ -786,11 +786,11 @@ static const char *connect_to_host( sshprot = conf_get_int(ssh->conf, CONF_sshprot); assert(sshprot == 0 || sshprot == 3); if (sshprot == 0) - /* SSH-1 only */ - ssh->version = 1; + /* SSH-1 only */ + ssh->version = 1; if (sshprot == 3 || ssh->bare_connection) { - /* SSH-2 only */ - ssh->version = 2; + /* SSH-2 only */ + ssh->version = 2; } /* @@ -810,8 +810,8 @@ static const char *connect_to_host( * loghost, if configured, overrides realhost. */ if (*loghost) { - sfree(*realhost); - *realhost = dupstr(loghost); + sfree(*realhost); + *realhost = dupstr(loghost); } return NULL; @@ -847,7 +847,7 @@ void ssh_throttle_conn(Ssh *ssh, int adjust) static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize) { if (enable == ssh->throttled_all) - return; + return; ssh->throttled_all = enable; ssh->overall_bufsize = bufsize; @@ -868,7 +868,7 @@ static void ssh_cache_conf_values(Ssh *ssh) static const char *ssh_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, const char *host, int port, char **realhost, - bool nodelay, bool keepalive) + bool nodelay, bool keepalive) { const char *p; Ssh *ssh; @@ -907,7 +907,7 @@ static const char *ssh_init(Seat *seat, Backend **backend_handle, * the random seed won't be re-saved. */ ssh->need_random_unref = false; random_unref(); - return p; + return p; } return NULL; @@ -929,13 +929,13 @@ static void ssh_free(Backend *be) #ifndef NO_GSSAPI if (ssh->gss_state.srv_name) - ssh->gss_state.lib->release_name( + ssh->gss_state.lib->release_name( ssh->gss_state.lib, &ssh->gss_state.srv_name); if (ssh->gss_state.ctx != NULL) ssh->gss_state.lib->release_cred( ssh->gss_state.lib, &ssh->gss_state.ctx); if (ssh->gss_state.libs) - ssh_gss_cleanup(ssh->gss_state.libs); + ssh_gss_cleanup(ssh->gss_state.libs); #endif sfree(ssh->deferred_abort_message); @@ -974,7 +974,7 @@ static size_t ssh_send(Backend *be, const char *buf, size_t len) Ssh *ssh = container_of(be, Ssh, backend); if (ssh == NULL || ssh->s == NULL) - return 0; + return 0; bufchain_add(&ssh->user_input, buf, len); if (ssh->base_layer) @@ -992,7 +992,7 @@ static size_t ssh_sendbuffer(Backend *be) size_t backlog; if (!ssh || !ssh->s || !ssh->cl) - return 0; + return 0; backlog = ssh_stdin_backlog(ssh->cl); @@ -1003,7 +1003,7 @@ static size_t ssh_sendbuffer(Backend *be) * size on that to any individual buffer on the stdin channel. */ if (ssh->throttled_all) - backlog += ssh->overall_bufsize; + backlog += ssh->overall_bufsize; return backlog; } @@ -1110,7 +1110,7 @@ void ssh_ldisc_update(Ssh *ssh) /* Called when the connection layer wants to propagate an update * to the line discipline options */ if (ssh->ldisc) - ldisc_echoedit_update(ssh->ldisc); + ldisc_echoedit_update(ssh->ldisc); } static bool ssh_ldisc(Backend *be, int option) @@ -1148,11 +1148,11 @@ static int ssh_cfg_info(Backend *be) { Ssh *ssh = container_of(be, Ssh, backend); if (ssh->version == 0) - return 0; /* don't know yet */ + return 0; /* don't know yet */ else if (ssh->bare_connection) - return -1; + return -1; else - return ssh->version; + return ssh->version; } /* diff --git a/ssh.h b/ssh.h index b6dd71ec..06725247 100644 --- a/ssh.h +++ b/ssh.h @@ -624,7 +624,7 @@ struct ssh_cipheralg { * different. */ int padded_keybytes; unsigned int flags; -#define SSH_CIPHER_IS_CBC 1 +#define SSH_CIPHER_IS_CBC 1 #define SSH_CIPHER_SEPARATE_LENGTH 2 const char *text_name; /* If set, this takes priority over other MAC. */ @@ -879,7 +879,7 @@ static inline const ssh_compression_alg *ssh_decompressor_alg( struct ssh2_userkey { ssh_key *key; /* the key itself */ - char *comment; /* the key comment */ + char *comment; /* the key comment */ }; /* The maximum length of any hash algorithm. (bytes) */ @@ -965,7 +965,7 @@ bool platform_sha256_hw_available(void); bool platform_sha1_hw_available(void); /* - * PuTTY version number formatted as an SSH version string. + * PuTTY version number formatted as an SSH version string. */ extern const char sshver[]; @@ -1105,7 +1105,7 @@ char *platform_get_x_display(void); * calling this function to do the rest of the work. */ void x11_get_auth_from_authfile(struct X11Display *display, - const char *authfilename); + const char *authfilename); void x11_format_auth_for_authfile( BinarySink *bs, SockAddr *addr, int display_no, ptrlen authproto, ptrlen authdata); @@ -1217,7 +1217,7 @@ bool import_possible(int type); int import_target_type(int type); bool import_encrypted(const Filename *filename, int type, char **comment); int import_ssh1(const Filename *filename, int type, - RSAKey *key, char *passphrase, const char **errmsg_p); + RSAKey *key, char *passphrase, const char **errmsg_p); ssh2_userkey *import_ssh2(const Filename *filename, int type, char *passphrase, const char **errmsg_p); bool export_ssh1(const Filename *filename, int type, @@ -1228,9 +1228,9 @@ bool export_ssh2(const Filename *filename, int type, void des3_decrypt_pubkey(const void *key, void *blk, int len); void des3_encrypt_pubkey(const void *key, void *blk, int len); void des3_decrypt_pubkey_ossh(const void *key, const void *iv, - void *blk, int len); + void *blk, int len); void des3_encrypt_pubkey_ossh(const void *key, const void *iv, - void *blk, int len); + void *blk, int len); void aes256_encrypt_pubkey(const void *key, void *blk, int len); void aes256_decrypt_pubkey(const void *key, void *blk, int len); @@ -1253,9 +1253,9 @@ void openssh_bcrypt(const char *passphrase, typedef void (*progfn_t) (void *param, int action, int phase, int progress); int rsa_generate(RSAKey *key, int bits, progfn_t pfn, - void *pfnparam); + void *pfnparam); int dsa_generate(struct dss_key *key, int bits, progfn_t pfn, - void *pfnparam); + void *pfnparam); int ecdsa_generate(struct ecdsa_key *key, int bits, progfn_t pfn, void *pfnparam); int eddsa_generate(struct eddsa_key *key, int bits, progfn_t pfn, @@ -1328,16 +1328,16 @@ void platform_ssh_share_cleanup(const char *name); X(y, SSH1_CMSG_AUTH_CCARD_RESPONSE, 72) \ /* end of list */ -#define SSH1_AUTH_RHOSTS 1 /* 0x1 */ -#define SSH1_AUTH_RSA 2 /* 0x2 */ -#define SSH1_AUTH_PASSWORD 3 /* 0x3 */ -#define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */ -#define SSH1_AUTH_TIS 5 /* 0x5 */ -#define SSH1_AUTH_CCARD 16 /* 0x10 */ +#define SSH1_AUTH_RHOSTS 1 /* 0x1 */ +#define SSH1_AUTH_RSA 2 /* 0x2 */ +#define SSH1_AUTH_PASSWORD 3 /* 0x3 */ +#define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */ +#define SSH1_AUTH_TIS 5 /* 0x5 */ +#define SSH1_AUTH_CCARD 16 /* 0x10 */ -#define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */ +#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 SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */ /* * List macro defining SSH-2 message type codes. Some of these depend @@ -1423,7 +1423,7 @@ enum { #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 SSH-1 and OpenSSH's SSH-2. @@ -1445,28 +1445,28 @@ enum { /* * Assorted other SSH-related enumerations. */ -#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 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 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 */ enum { /* TTY modes with opcodes defined consistently in the SSH specs. */ diff --git a/ssh1bpp.c b/ssh1bpp.c index 381da1e3..0bc729e7 100644 --- a/ssh1bpp.c +++ b/ssh1bpp.c @@ -286,7 +286,7 @@ static void ssh1_bpp_handle_input(BinaryPacketProtocol *bpp) static PktOut *ssh1_bpp_new_pktout(int pkt_type) { PktOut *pkt = ssh_new_packet(); - pkt->length = 4 + 8; /* space for length + max padding */ + pkt->length = 4 + 8; /* space for length + max padding */ put_byte(pkt, pkt_type); pkt->prefix = pkt->length; pkt->type = pkt_type; diff --git a/ssh1connection-client.c b/ssh1connection-client.c index 40107dc3..850a94fe 100644 --- a/ssh1connection-client.c +++ b/ssh1connection-client.c @@ -468,16 +468,16 @@ static void ssh1_rportfwd_response(struct ssh1_connection_state *s, struct ssh_rportfwd *rpf = (struct ssh_rportfwd *)ctx; if (success) { - ppl_logevent("Remote port forwarding from %s enabled", + ppl_logevent("Remote port forwarding from %s enabled", rpf->log_description); } else { - ppl_logevent("Remote port forwarding from %s refused", + ppl_logevent("Remote port forwarding from %s refused", rpf->log_description); - struct ssh_rportfwd *realpf = del234(s->rportfwds, rpf); - assert(realpf == rpf); + struct ssh_rportfwd *realpf = del234(s->rportfwds, rpf); + assert(realpf == rpf); portfwdmgr_close(s->portfwdmgr, rpf->pfr); - free_rportfwd(rpf); + free_rportfwd(rpf); } } diff --git a/ssh1connection.c b/ssh1connection.c index 501ab2a3..01df6e52 100644 --- a/ssh1connection.c +++ b/ssh1connection.c @@ -19,15 +19,15 @@ static int ssh1_rportfwd_cmp(void *av, void *bv) struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv; int i; if ( (i = strcmp(a->dhost, b->dhost)) != 0) - return i < 0 ? -1 : +1; + return i < 0 ? -1 : +1; if (a->dport > b->dport) - return +1; + return +1; if (a->dport < b->dport) - return -1; + return -1; return 0; } -static void ssh1_connection_free(PacketProtocolLayer *); +static void ssh1_connection_free(PacketProtocolLayer *); static void ssh1_connection_process_queue(PacketProtocolLayer *); static void ssh1_connection_special_cmd(PacketProtocolLayer *ppl, SessionSpecialCode code, int arg); @@ -134,9 +134,9 @@ static int ssh1_channelcmp(void *av, void *bv) const struct ssh1_channel *a = (const struct ssh1_channel *) av; const struct ssh1_channel *b = (const struct ssh1_channel *) bv; if (a->localid < b->localid) - return -1; + return -1; if (a->localid > b->localid) - return +1; + return +1; return 0; } @@ -145,9 +145,9 @@ static int ssh1_channelfind(void *av, void *bv) const unsigned *a = (const unsigned *) av; const struct ssh1_channel *b = (const struct ssh1_channel *) bv; if (*a < b->localid) - return -1; + return -1; if (*a > b->localid) - return +1; + return +1; return 0; } @@ -201,7 +201,7 @@ static void ssh1_connection_free(PacketProtocolLayer *ppl) chan_free(s->mainchan_chan); if (s->x11disp) - x11_free_display(s->x11disp); + x11_free_display(s->x11disp); while ((auth = delpos234(s->x11authtree, 0)) != NULL) x11_free_fake_auth(auth); freetree234(s->x11authtree); @@ -270,7 +270,7 @@ static bool ssh1_connection_filter_queue(struct ssh1_connection_state *s) localid); return true; } - + switch (pktin->type) { case SSH1_MSG_CHANNEL_OPEN_CONFIRMATION: assert(c->halfopen); @@ -427,19 +427,19 @@ static void ssh1_connection_process_queue(PacketProtocolLayer *ppl) while (1) { - /* - * By this point, most incoming packets are already being - * handled by filter_queue, and we need only pay attention to - * the unusual ones. - */ + /* + * By this point, most incoming packets are already being + * handled by filter_queue, and we need only pay attention to + * the unusual ones. + */ - if ((pktin = ssh1_connection_pop(s)) != NULL) { + if ((pktin = ssh1_connection_pop(s)) != NULL) { ssh_proto_error(s->ppl.ssh, "Unexpected packet received, " "type %d (%s)", pktin->type, ssh1_pkt_type(pktin->type)); return; - } - crReturnV; + } + crReturnV; } crFinishV; @@ -462,7 +462,7 @@ static void ssh1_channel_check_close(struct ssh1_channel *c) if ((!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes) || chan_want_close(c->chan, (c->closes & CLOSES_SENT_CLOSE), (c->closes & CLOSES_RCVD_CLOSE))) && - !(c->closes & CLOSES_SENT_CLOSECONF)) { + !(c->closes & CLOSES_SENT_CLOSECONF)) { /* * We have both sent and received CLOSE (or the channel type * doesn't need us to), which means the channel is in final @@ -625,8 +625,8 @@ static void ssh1channel_unthrottle(SshChannel *sc, size_t bufsize) struct ssh1_connection_state *s = c->connlayer; if (c->throttling_conn && bufsize <= SSH1_BUFFER_LIMIT) { - c->throttling_conn = false; - ssh_throttle_conn(s->ppl.ssh, -1); + c->throttling_conn = false; + ssh_throttle_conn(s->ppl.ssh, -1); } } diff --git a/ssh1connection.h b/ssh1connection.h index 1ee5465d..cb9bbe96 100644 --- a/ssh1connection.h +++ b/ssh1connection.h @@ -10,7 +10,7 @@ struct ssh1_connection_state { Conf *conf; int local_protoflags, remote_protoflags; - tree234 *channels; /* indexed by local id */ + tree234 *channels; /* indexed by local id */ /* In SSH-1, the main session doesn't take the form of a 'channel' * according to the wire protocol. But we want to use the same API diff --git a/ssh1login-server.c b/ssh1login-server.c index 10d9a37b..e7ff93de 100644 --- a/ssh1login-server.c +++ b/ssh1login-server.c @@ -43,7 +43,7 @@ struct ssh1_login_server_state { PacketProtocolLayer ppl; }; -static void ssh1_login_server_free(PacketProtocolLayer *); +static void ssh1_login_server_free(PacketProtocolLayer *); static void ssh1_login_server_process_queue(PacketProtocolLayer *); static bool ssh1_login_server_get_specials( diff --git a/ssh1login.c b/ssh1login.c index 1922820e..98b7fb5b 100644 --- a/ssh1login.c +++ b/ssh1login.c @@ -63,7 +63,7 @@ struct ssh1_login_state { PacketProtocolLayer ppl; }; -static void ssh1_login_free(PacketProtocolLayer *); +static void ssh1_login_free(PacketProtocolLayer *); static void ssh1_login_process_queue(PacketProtocolLayer *); static void ssh1_login_dialog_callback(void *, int); static void ssh1_login_special_cmd(PacketProtocolLayer *ppl, @@ -292,8 +292,8 @@ static void ssh1_login_process_queue(PacketProtocolLayer *ppl) bool cipher_chosen = false, warn = false; const char *cipher_string = NULL; int i; - for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) { - int next_cipher = conf_get_int_int( + for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) { + int next_cipher = conf_get_int_int( s->conf, CONF_ssh_cipherlist, i); if (next_cipher == CIPHER_WARN) { /* If/when we choose a cipher, warn about it */ @@ -953,29 +953,29 @@ static void ssh1_login_process_queue(PacketProtocolLayer *ppl) * 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 can't deal with SSH1_MSG_IGNORE, at * least in this context. 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. - * + * * A few servers can deal with neither SSH1_MSG_IGNORE * here _nor_ a padded password string. * For these servers we are left with no defences @@ -1015,7 +1015,7 @@ static void ssh1_login_process_queue(PacketProtocolLayer *ppl) } } ppl_logevent("Sending password with camouflage packets"); - } + } else if (!(s->ppl.remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can't deal with SSH1_MSG_IGNORE @@ -1070,7 +1070,7 @@ static void ssh1_login_process_queue(PacketProtocolLayer *ppl) put_uint32(pkt, 6); /* gzip compression level */ pq_push(s->ppl.out_pq, pkt); crMaybeWaitUntilV((pktin = ssh1_login_pop(s)) != NULL); - if (pktin->type == SSH1_SMSG_SUCCESS) { + if (pktin->type == SSH1_SMSG_SUCCESS) { /* * We don't have to actually do anything here: the SSH-1 * BPP will take care of automatically starting the @@ -1079,15 +1079,15 @@ static void ssh1_login_process_queue(PacketProtocolLayer *ppl) * easiest way to avoid race conditions if other packets * cross in transit.) */ - } else if (pktin->type == SSH1_SMSG_FAILURE) { + } else if (pktin->type == SSH1_SMSG_FAILURE) { ppl_logevent("Server refused to enable compression"); - ppl_printf("Server refused to compress\r\n"); + ppl_printf("Server refused to compress\r\n"); } else { ssh_proto_error(s->ppl.ssh, "Received unexpected packet" " in response to compression request, type %d " "(%s)", pktin->type, ssh1_pkt_type(pktin->type)); return; - } + } } ssh1_connection_set_protoflags( diff --git a/ssh2connection-client.c b/ssh2connection-client.c index 6a7a6064..d9e909d2 100644 --- a/ssh2connection-client.c +++ b/ssh2connection-client.c @@ -181,11 +181,11 @@ static int ssh2_rportfwd_cmp(void *av, void *bv) struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv; int i; if ( (i = strcmp(a->shost, b->shost)) != 0) - return i < 0 ? -1 : +1; + return i < 0 ? -1 : +1; if (a->sport > b->sport) - return +1; + return +1; if (a->sport < b->sport) - return -1; + return -1; return 0; } @@ -196,16 +196,16 @@ static void ssh2_rportfwd_globreq_response(struct ssh2_connection_state *s, struct ssh_rportfwd *rpf = (struct ssh_rportfwd *)ctx; if (pktin->type == SSH2_MSG_REQUEST_SUCCESS) { - ppl_logevent("Remote port forwarding from %s enabled", + ppl_logevent("Remote port forwarding from %s enabled", rpf->log_description); } else { - ppl_logevent("Remote port forwarding from %s refused", + ppl_logevent("Remote port forwarding from %s refused", rpf->log_description); - struct ssh_rportfwd *realpf = del234(s->rportfwds, rpf); - assert(realpf == rpf); + struct ssh_rportfwd *realpf = del234(s->rportfwds, rpf); + assert(realpf == rpf); portfwdmgr_close(s->portfwdmgr, rpf->pfr); - free_rportfwd(rpf); + free_rportfwd(rpf); } } @@ -410,8 +410,8 @@ void ssh2channel_request_pty( put_stringz(pktout, conf_get_str(conf, CONF_termtype)); put_uint32(pktout, w); put_uint32(pktout, h); - put_uint32(pktout, 0); /* pixel width */ - put_uint32(pktout, 0); /* pixel height */ + put_uint32(pktout, 0); /* pixel width */ + put_uint32(pktout, 0); /* pixel height */ modebuf = strbuf_new(); write_ttymodes_to_packet( BinarySink_UPCAST(modebuf), 2, @@ -470,8 +470,8 @@ void ssh2channel_send_terminal_size_change(SshChannel *sc, int w, int h) PktOut *pktout = ssh2_chanreq_init(c, "window-change", NULL, NULL); put_uint32(pktout, w); put_uint32(pktout, h); - put_uint32(pktout, 0); /* pixel width */ - put_uint32(pktout, 0); /* pixel height */ + put_uint32(pktout, 0); /* pixel width */ + put_uint32(pktout, 0); /* pixel height */ pq_push(s->ppl.out_pq, pktout); } diff --git a/ssh2connection.c b/ssh2connection.c index 78bb0ad6..28054d43 100644 --- a/ssh2connection.c +++ b/ssh2connection.c @@ -12,7 +12,7 @@ #include "sshcr.h" #include "ssh2connection.h" -static void ssh2_connection_free(PacketProtocolLayer *); +static void ssh2_connection_free(PacketProtocolLayer *); static void ssh2_connection_process_queue(PacketProtocolLayer *); static bool ssh2_connection_get_specials( PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx); @@ -191,9 +191,9 @@ static int ssh2_channelcmp(void *av, void *bv) const struct ssh2_channel *a = (const struct ssh2_channel *) av; const struct ssh2_channel *b = (const struct ssh2_channel *) bv; if (a->localid < b->localid) - return -1; + return -1; if (a->localid > b->localid) - return +1; + return +1; return 0; } @@ -202,9 +202,9 @@ static int ssh2_channelfind(void *av, void *bv) const unsigned *a = (const unsigned *) av; const struct ssh2_channel *b = (const struct ssh2_channel *) bv; if (*a < b->localid) - return -1; + return -1; if (*a > b->localid) - return +1; + return +1; return 0; } @@ -410,7 +410,7 @@ static bool ssh2_connection_filter_queue(struct ssh2_connection_state *s) put_uint32(pktout, c->remoteid); put_uint32(pktout, chanopen_result.u.failure.reason_code); put_stringz(pktout, chanopen_result.u.failure.wire_message); - put_stringz(pktout, "en"); /* language tag */ + put_stringz(pktout, "en"); /* language tag */ pq_push(s->ppl.out_pq, pktout); ppl_logevent("Rejected channel open: %s", chanopen_result.u.failure.wire_message); @@ -481,7 +481,7 @@ static bool ssh2_connection_filter_queue(struct ssh2_connection_state *s) localid); return true; } - + switch (pktin->type) { case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION: assert(c->halfopen); @@ -856,7 +856,7 @@ static bool ssh2_connection_filter_queue(struct ssh2_connection_state *s) } static void ssh2_handle_winadj_response(struct ssh2_channel *c, - PktIn *pktin, void *ctx) + PktIn *pktin, void *ctx) { unsigned *sizep = ctx; @@ -876,7 +876,7 @@ static void ssh2_handle_winadj_response(struct ssh2_channel *c, * complete. */ if (c->throttle_state == UNTHROTTLING) - c->throttle_state = UNTHROTTLED; + c->throttle_state = UNTHROTTLED; } static void ssh2_set_window(struct ssh2_channel *c, int newwin) @@ -890,7 +890,7 @@ static void ssh2_set_window(struct ssh2_channel *c, int newwin) * CLOSE. */ if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE)) - return; + return; /* * If the client-side Channel is in an initial setup phase with a @@ -907,7 +907,7 @@ static void ssh2_set_window(struct ssh2_channel *c, int newwin) * window as well). */ if ((s->ppl.remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT) - newwin = OUR_V2_MAXPKT; + newwin = OUR_V2_MAXPKT; /* * Only send a WINDOW_ADJUST if there's significantly more window @@ -917,39 +917,39 @@ static void ssh2_set_window(struct ssh2_channel *c, int newwin) * "Significant" is arbitrarily defined as half the window size. */ if (newwin / 2 >= c->locwindow) { - PktOut *pktout; - unsigned *up; + PktOut *pktout; + unsigned *up; - /* - * In order to keep track of how much window the client - * actually has available, we'd like it to acknowledge each - * WINDOW_ADJUST. We can't do that directly, so we accompany - * it with a CHANNEL_REQUEST that has to be acknowledged. - * - * This is only necessary if we're opening the window wide. - * If we're not, then throughput is being constrained by - * something other than the maximum window size anyway. - */ - if (newwin == c->locmaxwin && + /* + * In order to keep track of how much window the client + * actually has available, we'd like it to acknowledge each + * WINDOW_ADJUST. We can't do that directly, so we accompany + * it with a CHANNEL_REQUEST that has to be acknowledged. + * + * This is only necessary if we're opening the window wide. + * If we're not, then throughput is being constrained by + * something other than the maximum window size anyway. + */ + if (newwin == c->locmaxwin && !(s->ppl.remote_bugs & BUG_CHOKES_ON_WINADJ)) { - up = snew(unsigned); - *up = newwin - c->locwindow; - pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org", - ssh2_handle_winadj_response, up); - pq_push(s->ppl.out_pq, pktout); + up = snew(unsigned); + *up = newwin - c->locwindow; + pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org", + ssh2_handle_winadj_response, up); + pq_push(s->ppl.out_pq, pktout); - if (c->throttle_state != UNTHROTTLED) - c->throttle_state = UNTHROTTLING; - } else { - /* Pretend the WINDOW_ADJUST was acked immediately. */ - c->remlocwin = newwin; - c->throttle_state = THROTTLED; - } - pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_WINDOW_ADJUST); - put_uint32(pktout, c->remoteid); - put_uint32(pktout, newwin - c->locwindow); - pq_push(s->ppl.out_pq, pktout); - c->locwindow = newwin; + if (c->throttle_state != UNTHROTTLED) + c->throttle_state = UNTHROTTLING; + } else { + /* Pretend the WINDOW_ADJUST was acked immediately. */ + c->remlocwin = newwin; + c->throttle_state = THROTTLED; + } + pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_WINDOW_ADJUST); + put_uint32(pktout, c->remoteid); + put_uint32(pktout, newwin - c->locwindow); + pq_push(s->ppl.out_pq, pktout); + c->locwindow = newwin; } } @@ -1027,13 +1027,13 @@ static void ssh2_connection_process_queue(PacketProtocolLayer *ppl) */ while (1) { - if ((pktin = ssh2_connection_pop(s)) != NULL) { + if ((pktin = ssh2_connection_pop(s)) != NULL) { - /* - * _All_ the connection-layer packets we expect to - * receive are now handled by the dispatch table. - * Anything that reaches here must be bogus. - */ + /* + * _All_ the connection-layer packets we expect to + * receive are now handled by the dispatch table. + * Anything that reaches here must be bogus. + */ ssh_proto_error(s->ppl.ssh, "Received unexpected connection-layer " "packet, type %d (%s)", pktin->type, @@ -1041,8 +1041,8 @@ static void ssh2_connection_process_queue(PacketProtocolLayer *ppl) s->ppl.bpp->pls->actx, pktin->type)); return; - } - crReturnV; + } + crReturnV; } crFinishV; @@ -1064,22 +1064,22 @@ static void ssh2_channel_check_close(struct ssh2_channel *c) if (chan_want_close(c->chan, (c->closes & CLOSES_SENT_EOF), (c->closes & CLOSES_RCVD_EOF)) && - !c->chanreq_head && - !(c->closes & CLOSES_SENT_CLOSE)) { + !c->chanreq_head && + !(c->closes & CLOSES_SENT_CLOSE)) { /* * We have both sent and received EOF (or the channel is a * zombie), and we have no outstanding channel requests, which * means the channel is in final wind-up. But we haven't sent * CLOSE, so let's do so now. */ - pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_CLOSE); - put_uint32(pktout, c->remoteid); - pq_push(s->ppl.out_pq, pktout); + pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_CLOSE); + put_uint32(pktout, c->remoteid); + pq_push(s->ppl.out_pq, pktout); c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE; } if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) { - assert(c->chanreq_head == NULL); + assert(c->chanreq_head == NULL); /* * We have both sent and received CLOSE, which means we're * completely done with the channel. @@ -1164,7 +1164,7 @@ static void ssh2_try_send_and_unthrottle(struct ssh2_channel *c) { int bufsize; if (c->closes & CLOSES_SENT_EOF) - return; /* don't send on channels we've EOFed */ + return; /* don't send on channels we've EOFed */ bufsize = ssh2_try_send(c); if (bufsize == 0) { c->throttled_by_backlog = false; @@ -1388,8 +1388,8 @@ static void ssh2channel_unthrottle(SshChannel *sc, size_t bufsize) ssh2_set_window(c, buflimit - bufsize); if (c->throttling_conn && bufsize <= buflimit) { - c->throttling_conn = false; - ssh_throttle_conn(s->ppl.ssh, -1); + c->throttling_conn = false; + ssh_throttle_conn(s->ppl.ssh, -1); } } @@ -1616,7 +1616,7 @@ static void ssh2_connection_special_cmd(PacketProtocolLayer *ppl, pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_IGNORE); put_stringz(pktout, ""); pq_push(s->ppl.out_pq, pktout); - } + } } else if (s->mainchan) { mainchan_special_cmd(s->mainchan, code, arg); } diff --git a/ssh2connection.h b/ssh2connection.h index 82145fca..69975d7f 100644 --- a/ssh2connection.h +++ b/ssh2connection.h @@ -24,7 +24,7 @@ struct ssh2_connection_state { Conf *conf; - tree234 *channels; /* indexed by local id */ + tree234 *channels; /* indexed by local id */ bool all_channels_throttled; bool X11_fwd_enabled; diff --git a/ssh2kex-server.c b/ssh2kex-server.c index d83d2336..40377153 100644 --- a/ssh2kex-server.c +++ b/ssh2kex-server.c @@ -261,9 +261,9 @@ void ssh2kex_coroutine(struct ssh2_transport_state *s, bool *aborted) if (!s->rsa_kex_key) { ppl_logevent("Generating a %d-bit RSA key", extra->minklen); - s->rsa_kex_key = snew(RSAKey); - rsa_generate(s->rsa_kex_key, extra->minklen, no_progress, NULL); - s->rsa_kex_key->comment = NULL; + s->rsa_kex_key = snew(RSAKey); + rsa_generate(s->rsa_kex_key, extra->minklen, no_progress, NULL); + s->rsa_kex_key->comment = NULL; s->rsa_kex_key_needs_freeing = true; } diff --git a/ssh2transport.c b/ssh2transport.c index 4a6b8c7b..1ed0edd7 100644 --- a/ssh2transport.c +++ b/ssh2transport.c @@ -1579,7 +1579,7 @@ static void ssh2_transport_timer(void *ctx, unsigned long now) mins = sanitise_rekey_time(conf_get_int(s->conf, CONF_ssh_rekey_time), 60); if (mins == 0) - return; + return; /* Rekey if enough time has elapsed */ ticks = mins * 60 * TICKSPERSEC; @@ -1884,18 +1884,18 @@ static void ssh2_transport_special_cmd(PacketProtocolLayer *ppl, container_of(ppl, struct ssh2_transport_state, ppl); if (code == SS_REKEY) { - if (!s->kex_in_progress) { + if (!s->kex_in_progress) { s->rekey_reason = "at user request"; s->rekey_class = RK_NORMAL; queue_idempotent_callback(&s->ppl.ic_process_queue); - } + } } else if (code == SS_XCERT) { - if (!s->kex_in_progress) { + if (!s->kex_in_progress) { s->cross_certifying = s->hostkey_alg = ssh2_hostkey_algs[arg].alg; s->rekey_reason = "cross-certifying new host key"; s->rekey_class = RK_NORMAL; queue_idempotent_callback(&s->ppl.ic_process_queue); - } + } } else { /* Send everything else to the next layer up. This includes * SS_PING/SS_NOP, which we _could_ handle here - but it's @@ -1938,7 +1938,7 @@ static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf) old_max_data_size = s->max_data_size; ssh2_transport_set_max_data_size(s); if (old_max_data_size != s->max_data_size && - s->max_data_size != 0) { + s->max_data_size != 0) { if (s->max_data_size < old_max_data_size) { unsigned long diff = old_max_data_size - s->max_data_size; @@ -1956,19 +1956,19 @@ static void ssh2_transport_reconfigure(PacketProtocolLayer *ppl, Conf *conf) } if (conf_get_bool(s->conf, CONF_compression) != - conf_get_bool(conf, CONF_compression)) { + conf_get_bool(conf, CONF_compression)) { rekey_reason = "compression setting changed"; rekey_mandatory = true; } for (i = 0; i < CIPHER_MAX; i++) - if (conf_get_int_int(s->conf, CONF_ssh_cipherlist, i) != - conf_get_int_int(conf, CONF_ssh_cipherlist, i)) { + if (conf_get_int_int(s->conf, CONF_ssh_cipherlist, i) != + conf_get_int_int(conf, CONF_ssh_cipherlist, i)) { rekey_reason = "cipher settings changed"; rekey_mandatory = true; } if (conf_get_bool(s->conf, CONF_ssh2_des_cbc) != - conf_get_bool(conf, CONF_ssh2_des_cbc)) { + conf_get_bool(conf, CONF_ssh2_des_cbc)) { rekey_reason = "cipher settings changed"; rekey_mandatory = true; } diff --git a/ssh2userauth.c b/ssh2userauth.c index 89e62252..833fde8f 100644 --- a/ssh2userauth.c +++ b/ssh2userauth.c @@ -89,7 +89,7 @@ struct ssh2_userauth_state { PacketProtocolLayer ppl; }; -static void ssh2_userauth_free(PacketProtocolLayer *); +static void ssh2_userauth_free(PacketProtocolLayer *); static void ssh2_userauth_process_queue(PacketProtocolLayer *); static bool ssh2_userauth_get_specials( PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx); @@ -372,16 +372,16 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) * beginning to try another username, if this is configured on. * (If they specify a username in the config, they are never * asked, even if they do give a wrong password.) - * + * * I think this best serves the needs of - * + * * - the people who have no configuration, no keys, and just * want to try repeated (username,password) pairs until they * type both correctly - * + * * - people who have keys and configuration but occasionally * need to fall back to passwords - * + * * - people with a key held in Pageant, who might not have * logged in to a particular machine before; so they want to * type a username, and then _either_ their key will be @@ -405,7 +405,7 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) s->cur_prompt->to_server = true; s->cur_prompt->from_server = false; s->cur_prompt->name = dupstr("SSH login name"); - add_prompt(s->cur_prompt, dupstr("login as: "), true); + add_prompt(s->cur_prompt, dupstr("login as: "), true); s->userpass_ret = seat_get_userpass_input( s->ppl.seat, s->cur_prompt, NULL); while (1) { @@ -1199,7 +1199,7 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) put_stringz(s->pktout, ""); /* lang */ put_stringz(s->pktout, ""); /* submethods */ pq_push(s->ppl.out_pq, s->pktout); - + ppl_logevent("Attempting keyboard-interactive authentication"); if (!s->ki_scc_initialised) { @@ -1492,7 +1492,7 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) { - /* + /* * We're being asked for a new password * (perhaps not for the first time). * Loop until the server accepts it. @@ -1500,7 +1500,7 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) bool got_new = false; /* not live over crReturn */ ptrlen prompt; /* not live over crReturn */ - + { const char *msg; if (changereq_first_time) @@ -1620,7 +1620,7 @@ static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl) s->pktout->minlen = 256; pq_push(s->ppl.out_pq, s->pktout); ppl_logevent("Sent new password"); - + /* * Now see what the server has to say about it. * (If it's CHANGEREQ again, it's not happy with the @@ -1752,42 +1752,42 @@ static void ssh2_userauth_add_sigblob( if ((s->ppl.remote_bugs & BUG_SSH2_RSA_PADDING) && ptrlen_eq_string(get_string(pk), "ssh-rsa") && ptrlen_eq_string(get_string(sig), "ssh-rsa")) { - ptrlen mod_mp, sig_mp; + ptrlen mod_mp, sig_mp; size_t sig_prefix_len; - /* - * Find the modulus and signature integers. - */ + /* + * Find the modulus and signature integers. + */ get_string(pk); /* skip over exponent */ mod_mp = get_string(pk); /* remember modulus */ sig_prefix_len = sig->pos; - sig_mp = get_string(sig); + sig_mp = get_string(sig); if (get_err(pk) || get_err(sig)) goto give_up; /* * Find the byte length of the modulus, not counting leading - * zeroes. + * zeroes. */ - while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) { + while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) { mod_mp.len--; mod_mp.ptr = (const char *)mod_mp.ptr + 1; } - /* debug("modulus length is %d\n", len); */ - /* debug("signature length is %d\n", siglen); */ + /* debug("modulus length is %d\n", len); */ + /* debug("signature length is %d\n", siglen); */ - if (mod_mp.len != sig_mp.len) { + if (mod_mp.len != sig_mp.len) { strbuf *substr = strbuf_new(); - put_data(substr, sigblob.ptr, sig_prefix_len); - put_uint32(substr, mod_mp.len); - put_padding(substr, mod_mp.len - sig_mp.len, 0); - put_datapl(substr, sig_mp); + put_data(substr, sigblob.ptr, sig_prefix_len); + put_uint32(substr, mod_mp.len); + put_padding(substr, mod_mp.len - sig_mp.len, 0); + put_datapl(substr, sig_mp); put_stringsb(pkt, substr); - return; - } + return; + } - /* Otherwise fall through and do it the easy way. We also come + /* Otherwise fall through and do it the easy way. We also come * here as a fallback if we discover above that the key blob * is misformatted in some way. */ give_up:; diff --git a/sshaes.c b/sshaes.c index 1fce4d2f..a04ea588 100644 --- a/sshaes.c +++ b/sshaes.c @@ -856,7 +856,7 @@ static void aes_sliced_key_setup( * Prepare a word of round key in the low 4 bits of each * integer in slices[]. */ - if (i < key_words) { + if (i < key_words) { memcpy(inblk, key + 4*i, 4); TO_BITSLICES(slices, inblk, uint16_t, =, 0); } else { @@ -905,7 +905,7 @@ static void aes_sliced_key_setup( prevslices = sk->roundkeys_serial + 8 * (wordindex >> 2); for (size_t i = 0; i < 8; i++) slices[i] ^= prevslices[i] >> bitshift; - } + } /* * Now copy it into sk. @@ -1321,10 +1321,10 @@ static FUNC_ISA void aes_ni_key_expand( unsigned rconpos = 0; for (size_t i = 0; i < sched_words; i++) { - if (i < key_words) { + if (i < key_words) { sched[i] = GET_32BIT_LSB_FIRST(key + 4 * i); } else { - uint32_t temp = sched[i - 1]; + uint32_t temp = sched[i - 1]; bool rotate_and_round_constant = (i % key_words == 0); bool only_sub = (key_words == 8 && i % 8 == 4); @@ -1343,7 +1343,7 @@ static FUNC_ISA void aes_ni_key_expand( } sched[i] = sched[i - key_words] ^ temp; - } + } } /* @@ -1625,10 +1625,10 @@ static FUNC_ISA void aes_neon_key_expand( unsigned rconpos = 0; for (size_t i = 0; i < sched_words; i++) { - if (i < key_words) { + if (i < key_words) { sched[i] = GET_32BIT_LSB_FIRST(key + 4 * i); } else { - uint32_t temp = sched[i - 1]; + uint32_t temp = sched[i - 1]; bool rotate_and_round_constant = (i % key_words == 0); bool sub = rotate_and_round_constant || @@ -1651,7 +1651,7 @@ static FUNC_ISA void aes_neon_key_expand( } sched[i] = sched[i - key_words] ^ temp; - } + } } /* diff --git a/ssharcf.c b/ssharcf.c index 15be97d8..dd163d4f 100644 --- a/ssharcf.c +++ b/ssharcf.c @@ -22,16 +22,16 @@ static void arcfour_block(void *handle, void *vblk, int len) s = ctx->s; i = ctx->i; j = ctx->j; for (k = 0; (int)k < len; k++) { - i = (i + 1) & 0xff; - j = (j + s[i]) & 0xff; - tmp = s[i]; s[i] = s[j]; s[j] = tmp; - blk[k] ^= s[(s[i]+s[j]) & 0xff]; + i = (i + 1) & 0xff; + j = (j + s[i]) & 0xff; + tmp = s[i]; s[i] = s[j]; s[j] = tmp; + blk[k] ^= s[(s[i]+s[j]) & 0xff]; } ctx->i = i; ctx->j = j; } static void arcfour_setkey(ArcfourContext *ctx, unsigned char const *key, - unsigned keybytes) + unsigned keybytes) { unsigned char tmp, k[256], *s; unsigned i, j; @@ -40,13 +40,13 @@ static void arcfour_setkey(ArcfourContext *ctx, unsigned char const *key, assert(keybytes <= 256); ctx->i = ctx->j = 0; for (i = 0; i < 256; i++) { - s[i] = i; - k[i] = key[i % keybytes]; + s[i] = i; + k[i] = key[i % keybytes]; } j = 0; for (i = 0; i < 256; i++) { - j = (j + s[i] + k[i]) & 0xff; - tmp = s[i]; s[i] = s[j]; s[j] = tmp; + j = (j + s[i] + k[i]) & 0xff; + tmp = s[i]; s[i] = s[j]; s[j] = tmp; } } @@ -56,7 +56,7 @@ static void arcfour_setkey(ArcfourContext *ctx, unsigned char const *key, * We don't implement Arcfour in SSH-1 because it's utterly insecure in * several ways. See CERT Vulnerability Notes VU#25309, VU#665372, * and VU#565052. - * + * * We don't implement the "arcfour" algorithm in SSH-2 because it doesn't * stir the cipher state before emitting keystream, and hence is likely * to leak data about the key. diff --git a/sshauxcrypt.c b/sshauxcrypt.c index c1da04a8..1367d691 100644 --- a/sshauxcrypt.c +++ b/sshauxcrypt.c @@ -88,7 +88,7 @@ static ssh_cipher *des3_pubkey_ossh_cipher(const void *vkey, const void *viv) } void des3_decrypt_pubkey_ossh(const void *vkey, const void *viv, - void *vblk, int len) + void *vblk, int len) { ssh_cipher *c = des3_pubkey_ossh_cipher(vkey, viv); ssh_cipher_decrypt(c, vblk, len); @@ -96,7 +96,7 @@ void des3_decrypt_pubkey_ossh(const void *vkey, const void *viv, } void des3_encrypt_pubkey_ossh(const void *vkey, const void *viv, - void *vblk, int len) + void *vblk, int len) { ssh_cipher *c = des3_pubkey_ossh_cipher(vkey, viv); ssh_cipher_encrypt(c, vblk, len); @@ -119,14 +119,14 @@ static ssh_cipher *des_xdmauth_cipher(const void *vkeydata) nbits = 0; j = 0; for (i = 0; i < 8; i++) { - if (nbits < 7) { - bits = (bits << 8) | keydata[j]; - nbits += 8; - j++; - } - key[i] = (bits >> (nbits - 7)) << 1; - bits &= ~(0x7F << (nbits - 7)); - nbits -= 7; + if (nbits < 7) { + bits = (bits << 8) | keydata[j]; + nbits += 8; + j++; + } + key[i] = (bits >> (nbits - 7)) << 1; + bits &= ~(0x7F << (nbits - 7)); + nbits -= 7; } ssh_cipher *c = ssh_cipher_new(&ssh_des); diff --git a/sshblowf.c b/sshblowf.c index 9417c0d4..a48401b6 100644 --- a/sshblowf.c +++ b/sshblowf.c @@ -11,7 +11,7 @@ struct BlowfishContext { uint32_t S0[256], S1[256], S2[256], S3[256], P[18]; - uint32_t iv0, iv1; /* for CBC mode */ + uint32_t iv0, iv1; /* for CBC mode */ }; /* @@ -234,7 +234,7 @@ static const uint32_t sbox3[] = { #define ROUND(n) ( xL ^= P[n], t = xL, xL = F(xL) ^ xR, xR = t ) static void blowfish_encrypt(uint32_t xL, uint32_t xR, uint32_t *output, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t *S0 = ctx->S0; uint32_t *S1 = ctx->S1; @@ -267,7 +267,7 @@ static void blowfish_encrypt(uint32_t xL, uint32_t xR, uint32_t *output, } static void blowfish_decrypt(uint32_t xL, uint32_t xR, uint32_t *output, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t *S0 = ctx->S0; uint32_t *S1 = ctx->S1; @@ -310,17 +310,17 @@ static void blowfish_lsb_encrypt_cbc(unsigned char *blk, int len, 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; @@ -335,18 +335,18 @@ void blowfish_lsb_encrypt_ecb(void *vblk, int len, BlowfishContext * ctx) assert((len & 7) == 0); while (len > 0) { - xL = GET_32BIT_LSB_FIRST(blk); - xR = GET_32BIT_LSB_FIRST(blk + 4); - blowfish_encrypt(xL, xR, out, ctx); - PUT_32BIT_LSB_FIRST(blk, out[0]); - PUT_32BIT_LSB_FIRST(blk + 4, out[1]); - blk += 8; - len -= 8; + xL = GET_32BIT_LSB_FIRST(blk); + xR = GET_32BIT_LSB_FIRST(blk + 4); + blowfish_encrypt(xL, xR, out, ctx); + PUT_32BIT_LSB_FIRST(blk, out[0]); + PUT_32BIT_LSB_FIRST(blk + 4, out[1]); + blk += 8; + len -= 8; } } static void blowfish_lsb_decrypt_cbc(unsigned char *blk, int len, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t xL, xR, out[2], iv0, iv1; @@ -356,17 +356,17 @@ static void blowfish_lsb_decrypt_cbc(unsigned char *blk, int len, 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; @@ -374,7 +374,7 @@ static void blowfish_lsb_decrypt_cbc(unsigned char *blk, int len, } static void blowfish_msb_encrypt_cbc(unsigned char *blk, int len, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t xL, xR, out[2], iv0, iv1; @@ -384,17 +384,17 @@ static void blowfish_msb_encrypt_cbc(unsigned char *blk, int len, 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; @@ -402,7 +402,7 @@ static void blowfish_msb_encrypt_cbc(unsigned char *blk, int len, } static void blowfish_msb_decrypt_cbc(unsigned char *blk, int len, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t xL, xR, out[2], iv0, iv1; @@ -412,17 +412,17 @@ static void blowfish_msb_decrypt_cbc(unsigned char *blk, int len, 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; @@ -430,7 +430,7 @@ static void blowfish_msb_decrypt_cbc(unsigned char *blk, int len, } static void blowfish_msb_sdctr(unsigned char *blk, int len, - BlowfishContext * ctx) + BlowfishContext * ctx) { uint32_t b[2], iv0, iv1, tmp; @@ -440,15 +440,15 @@ static void blowfish_msb_sdctr(unsigned char *blk, int len, iv1 = ctx->iv1; while (len > 0) { - blowfish_encrypt(iv0, iv1, b, ctx); - tmp = GET_32BIT_MSB_FIRST(blk); - PUT_32BIT_MSB_FIRST(blk, tmp ^ b[0]); - tmp = GET_32BIT_MSB_FIRST(blk + 4); - PUT_32BIT_MSB_FIRST(blk + 4, tmp ^ b[1]); - if ((iv1 = (iv1 + 1) & 0xffffffff) == 0) - iv0 = (iv0 + 1) & 0xffffffff; - blk += 8; - len -= 8; + blowfish_encrypt(iv0, iv1, b, ctx); + tmp = GET_32BIT_MSB_FIRST(blk); + PUT_32BIT_MSB_FIRST(blk, tmp ^ b[0]); + tmp = GET_32BIT_MSB_FIRST(blk + 4); + PUT_32BIT_MSB_FIRST(blk + 4, tmp ^ b[1]); + if ((iv1 = (iv1 + 1) & 0xffffffff) == 0) + iv0 = (iv0 + 1) & 0xffffffff; + blk += 8; + len -= 8; } ctx->iv0 = iv0; @@ -460,14 +460,14 @@ void blowfish_initkey(BlowfishContext *ctx) int i; for (i = 0; i < 18; i++) { - ctx->P[i] = parray[i]; + ctx->P[i] = parray[i]; } for (i = 0; i < 256; i++) { - ctx->S0[i] = sbox0[i]; - ctx->S1[i] = sbox1[i]; - ctx->S2[i] = sbox2[i]; - ctx->S3[i] = sbox3[i]; + ctx->S0[i] = sbox0[i]; + ctx->S1[i] = sbox1[i]; + ctx->S2[i] = sbox2[i]; + ctx->S3[i] = sbox3[i]; } } @@ -495,13 +495,13 @@ void blowfish_expandkey(BlowfishContext * ctx, } for (i = 0; i < 18; i++) { - P[i] ^= - ((uint32_t) (unsigned char) (key[(i * 4 + 0) % keybytes])) << 24; - P[i] ^= - ((uint32_t) (unsigned char) (key[(i * 4 + 1) % keybytes])) << 16; - P[i] ^= - ((uint32_t) (unsigned char) (key[(i * 4 + 2) % keybytes])) << 8; - P[i] ^= ((uint32_t) (unsigned char) (key[(i * 4 + 3) % keybytes])); + P[i] ^= + ((uint32_t) (unsigned char) (key[(i * 4 + 0) % keybytes])) << 24; + P[i] ^= + ((uint32_t) (unsigned char) (key[(i * 4 + 1) % keybytes])) << 16; + P[i] ^= + ((uint32_t) (unsigned char) (key[(i * 4 + 2) % keybytes])) << 8; + P[i] ^= ((uint32_t) (unsigned char) (key[(i * 4 + 3) % keybytes])); } str[0] = str[1] = 0; @@ -510,38 +510,38 @@ void blowfish_expandkey(BlowfishContext * ctx, for (j = 0; j < 8; j++) str[j/4] ^= ((uint32_t)salt[saltpos++ % saltbytes]) << (24-8*(j%4)); - 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) { for (j = 0; j < 8; j++) str[j/4] ^= ((uint32_t)salt[saltpos++ % saltbytes]) << (24-8*(j%4)); - 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) { for (j = 0; j < 8; j++) str[j/4] ^= ((uint32_t)salt[saltpos++ % saltbytes]) << (24-8*(j%4)); - 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) { for (j = 0; j < 8; j++) str[j/4] ^= ((uint32_t)salt[saltpos++ % saltbytes]) << (24-8*(j%4)); - 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) { for (j = 0; j < 8; j++) str[j/4] ^= ((uint32_t)salt[saltpos++ % saltbytes]) << (24-8*(j%4)); - 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]; } } diff --git a/sshbpp.h b/sshbpp.h index 380c41a8..8192d4e2 100644 --- a/sshbpp.h +++ b/sshbpp.h @@ -6,7 +6,7 @@ #define PUTTY_SSHBPP_H struct BinaryPacketProtocolVtable { - void (*free)(BinaryPacketProtocol *); + void (*free)(BinaryPacketProtocol *); void (*handle_input)(BinaryPacketProtocol *); void (*handle_output)(BinaryPacketProtocol *); PktOut *(*new_pktout)(int type); diff --git a/sshcr.h b/sshcr.h index 5abf4c17..8406ef39 100644 --- a/sshcr.h +++ b/sshcr.h @@ -8,16 +8,16 @@ /* * If these macros look impenetrable to you, you might find it helpful * to read - * + * * https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html - * + * * which explains the theory behind these macros. - * + * * In particular, if you are getting `case expression not constant' * errors when building with MS Visual Studio, this is because MS's * Edit and Continue debugging feature causes their compiler to * violate ANSI C. To disable Edit and Continue debugging: - * + * * - right-click ssh.c in the FileView * - click Settings * - select the C/C++ tab and the General category diff --git a/sshcrcda.c b/sshcrcda.c index bfebf73a..33dedadd 100644 --- a/sshcrcda.c +++ b/sshcrcda.c @@ -1,4 +1,4 @@ -/* $OpenBSD: deattack.c,v 1.14 2001/06/23 15:12:18 itojun Exp $ */ +/* $OpenBSD: deattack.c,v 1.14 2001/06/23 15:12:18 itojun Exp $ */ /* * Cryptographic attack detector for ssh - source code @@ -17,7 +17,7 @@ * * Ariel Futoransky * - * + * * Modified for use in PuTTY by Simon Tatham */ @@ -26,23 +26,23 @@ #include "ssh.h" /* SSH Constants */ -#define SSH_MAXBLOCKS (32 * 1024) -#define SSH_BLOCKSIZE (8) +#define SSH_MAXBLOCKS (32 * 1024) +#define SSH_BLOCKSIZE (8) /* Hashing constants */ -#define HASH_MINSIZE (8 * 1024) -#define HASH_ENTRYSIZE (sizeof(uint16_t)) -#define HASH_FACTOR(x) ((x)*3/2) -#define HASH_UNUSEDCHAR (0xff) -#define HASH_UNUSED (0xffff) -#define HASH_IV (0xfffe) +#define HASH_MINSIZE (8 * 1024) +#define HASH_ENTRYSIZE (sizeof(uint16_t)) +#define HASH_FACTOR(x) ((x)*3/2) +#define HASH_UNUSEDCHAR (0xff) +#define HASH_UNUSED (0xffff) +#define HASH_IV (0xfffe) -#define HASH_MINBLOCKS (7*SSH_BLOCKSIZE) +#define HASH_MINBLOCKS (7*SSH_BLOCKSIZE) /* Hash function (Input keys are cipher results) */ -#define HASH(x) GET_32BIT_MSB_FIRST(x) +#define HASH(x) GET_32BIT_MSB_FIRST(x) -#define CMP(a, b) (memcmp(a, b, SSH_BLOCKSIZE)) +#define CMP(a, b) (memcmp(a, b, SSH_BLOCKSIZE)) uint8_t ONE[4] = { 1, 0, 0, 0 }; uint8_t ZERO[4] = { 0, 0, 0, 0 }; @@ -63,9 +63,9 @@ struct crcda_ctx *crcda_make_context(void) void crcda_free_context(struct crcda_ctx *ctx) { if (ctx) { - sfree(ctx->h); - ctx->h = NULL; - sfree(ctx); + sfree(ctx->h); + ctx->h = NULL; + sfree(ctx); } } diff --git a/sshdes.c b/sshdes.c index 44feb877..8d4b9399 100644 --- a/sshdes.c +++ b/sshdes.c @@ -583,7 +583,7 @@ static inline LR des_round(LR in, const des_keysched *sched, size_t round) static inline LR des_inner_cipher(LR lr, const des_keysched *sched, size_t start, size_t step) -{ +{ lr = des_round(lr, sched, start+0x0*step); lr = des_round(lr, sched, start+0x1*step); lr = des_round(lr, sched, start+0x2*step); diff --git a/sshdh.c b/sshdh.c index 8e822199..b3756120 100644 --- a/sshdh.c +++ b/sshdh.c @@ -194,13 +194,13 @@ void dh_cleanup(dh_ctx *ctx) /* * DH stage 1: invent a number x between 1 and q, and compute e = * g^x mod p. Return e. - * + * * If `nbits' is greater than zero, it is used as an upper limit * for the number of bits in x. This is safe provided that (a) you * use twice as many bits in x as the number of bits you expect to * use in your session key, and (b) the DH group is a safe prime * (which SSH demands that it must be). - * + * * P. C. van Oorschot, M. J. Wiener * "On Diffie-Hellman Key Agreement with Short Exponents". * Advances in Cryptology: Proceedings of Eurocrypt '96 diff --git a/sshdss.c b/sshdss.c index 6af3c254..2bf26d9a 100644 --- a/sshdss.c +++ b/sshdss.c @@ -19,7 +19,7 @@ static ssh_key *dss_new_pub(const ssh_keyalg *self, ptrlen data) BinarySource_BARE_INIT_PL(src, data); if (!ptrlen_eq_string(get_string(src), "ssh-dss")) - return NULL; + return NULL; dss = snew(struct dss_key); dss->sshk.vt = &ssh_dss; @@ -73,7 +73,7 @@ static char *dss_cache_str(ssh_key *key) strbuf *sb = strbuf_new(); if (!dss->p) - return NULL; + return NULL; append_hex_to_strbuf(sb, dss->p); append_hex_to_strbuf(sb, dss->q); @@ -97,7 +97,7 @@ static bool dss_verify(ssh_key *key, ptrlen sig, ptrlen data) bool toret; if (!dss->p) - return false; + return false; BinarySource_BARE_INIT_PL(src, sig); @@ -113,7 +113,7 @@ static bool dss_verify(ssh_key *key, ptrlen sig, ptrlen data) * else is assumed to be RFC-compliant. */ if (sig.len != 40) { /* bug not present; read admin fields */ - ptrlen type = get_string(src); + ptrlen type = get_string(src); sig = get_string(src); if (get_err(src) || !ptrlen_eq_string(type, "ssh-dss") || @@ -129,7 +129,7 @@ static bool dss_verify(ssh_key *key, ptrlen sig, ptrlen data) mp_free(r); if (s) mp_free(s); - return false; + return false; } /* Basic sanity checks: 0 < r,s < q */ @@ -238,15 +238,15 @@ static ssh_key *dss_new_priv(const ssh_keyalg *self, ptrlen pub, ptrlen priv) */ hash = get_string(src); if (hash.len == 20) { - ssh_hash *h = ssh_hash_new(&ssh_sha1); - put_mp_ssh2(h, dss->p); - put_mp_ssh2(h, dss->q); - put_mp_ssh2(h, dss->g); - ssh_hash_final(h, digest); - if (!smemeq(hash.ptr, digest, 20)) { - dss_freekey(&dss->sshk); - return NULL; - } + ssh_hash *h = ssh_hash_new(&ssh_sha1); + put_mp_ssh2(h, dss->p); + put_mp_ssh2(h, dss->q); + put_mp_ssh2(h, dss->g); + ssh_hash_final(h, digest); + if (!smemeq(hash.ptr, digest, 20)) { + dss_freekey(&dss->sshk); + return NULL; + } } /* @@ -255,8 +255,8 @@ static ssh_key *dss_new_priv(const ssh_keyalg *self, ptrlen pub, ptrlen priv) ytest = mp_modpow(dss->g, dss->x, dss->p); if (!mp_cmp_eq(ytest, dss->y)) { mp_free(ytest); - dss_freekey(&dss->sshk); - return NULL; + dss_freekey(&dss->sshk); + return NULL; } mp_free(ytest); @@ -321,59 +321,59 @@ mp_int *dss_gen_k(const char *id_string, mp_int *modulus, { /* * The basic DSS signing algorithm is: - * + * * - invent a random k between 1 and q-1 (exclusive). * - Compute r = (g^k mod p) mod q. * - Compute s = k^-1 * (hash + x*r) mod q. - * + * * This has the dangerous properties that: - * + * * - if an attacker in possession of the public key _and_ the * signature (for example, the host you just authenticated * to) can guess your k, he can reverse the computation of s * and work out x = r^-1 * (s*k - hash) mod q. That is, he * can deduce the private half of your key, and masquerade * as you for as long as the key is still valid. - * + * * - since r is a function purely of k and the public key, if * the attacker only has a _range of possibilities_ for k * it's easy for him to work through them all and check each * one against r; he'll never be unsure of whether he's got * the right one. - * + * * - if you ever sign two different hashes with the same k, it * will be immediately obvious because the two signatures * will have the same r, and moreover an attacker in * possession of both signatures (and the public key of * course) can compute k = (hash1-hash2) * (s1-s2)^-1 mod q, * and from there deduce x as before. - * + * * - the Bleichenbacher attack on DSA makes use of methods of * generating k which are significantly non-uniformly * distributed; in particular, generating a 160-bit random * number and reducing it mod q is right out. - * + * * For this reason we must be pretty careful about how we * generate our k. Since this code runs on Windows, with no * particularly good system entropy sources, we can't trust our * RNG itself to produce properly unpredictable data. Hence, we * use a totally different scheme instead. - * + * * What we do is to take a SHA-512 (_big_) hash of the private * key x, and then feed this into another SHA-512 hash that * also includes the message hash being signed. That is: - * + * * proto_k = SHA512 ( SHA512(x) || SHA160(message) ) - * + * * This number is 512 bits long, so reducing it mod q won't be * noticeably non-uniform. So - * + * * k = proto_k mod q - * + * * This has the interesting property that it's _deterministic_: * signing the same hash twice with the same key yields the * same signature. - * + * * Despite this determinism, it's still not predictable to an * attacker, because in order to repeat the SHA-512 * construction that created it, the attacker would have to @@ -384,7 +384,7 @@ mp_int *dss_gen_k(const char *id_string, mp_int *modulus, * Reuse of k is left to chance; all it does is prevent * _excessively high_ chances of reuse of k due to entropy * problems.) - * + * * Thanks to Colin Plumb for the general idea of using x to * ensure k is hard to guess, and to the Cambridge University * Computer Security Group for helping to argue out all the @@ -458,7 +458,7 @@ static void dss_sign(ssh_key *key, ptrlen data, unsigned flags, BinarySink *bs) put_stringz(bs, "ssh-dss"); put_uint32(bs, 40); for (i = 0; i < 20; i++) - put_byte(bs, mp_get_byte(r, 19 - i)); + put_byte(bs, mp_get_byte(r, 19 - i)); for (i = 0; i < 20; i++) put_byte(bs, mp_get_byte(s, 19 - i)); mp_free(r); diff --git a/sshdssg.c b/sshdssg.c index 091a51e6..2d957734 100644 --- a/sshdssg.c +++ b/sshdssg.c @@ -7,7 +7,7 @@ #include "mpint.h" int dsa_generate(struct dss_key *key, int bits, progfn_t pfn, - void *pfnparam) + void *pfnparam) { /* * Set up the phase limits for the progress report. We do this @@ -31,7 +31,7 @@ int dsa_generate(struct dss_key *key, int bits, progfn_t pfn, * P(1-P), in three with probability P(1-P)^2, etc. The * probability that we have still not managed to find a prime * after N attempts is (1-P)^N. - * + * * We therefore inform the progress indicator of the number B * (29.34/B), so that it knows how much to increment by each * time. We do this in 16-bit fixed point, so 29.34 becomes @@ -79,10 +79,10 @@ int dsa_generate(struct dss_key *key, int bits, progfn_t pfn, int progress = 0; mp_int *g; while (1) { - pfn(pfnparam, PROGFN_PROGRESS, 3, ++progress); - g = mp_modpow(h, power, p); - if (mp_hs_integer(g, 2)) - break; /* got one */ + pfn(pfnparam, PROGFN_PROGRESS, 3, ++progress); + g = mp_modpow(h, power, p); + if (mp_hs_integer(g, 2)) + break; /* got one */ mp_free(g); mp_add_integer_into(h, h, 1); } diff --git a/sshgss.h b/sshgss.h index b1c04a35..c640636d 100644 --- a/sshgss.h +++ b/sshgss.h @@ -20,9 +20,9 @@ typedef enum Ssh_gss_stat { #define SSH_GSS_S_COMPLETE SSH_GSS_OK -#define SSH_GSS_CLEAR_BUF(buf) do { \ - (*buf).length = 0; \ - (*buf).value = NULL; \ +#define SSH_GSS_CLEAR_BUF(buf) do { \ + (*buf).length = 0; \ + (*buf).value = NULL; \ } while (0) typedef gss_buffer_desc Ssh_gss_buf; @@ -30,7 +30,7 @@ typedef gss_name_t Ssh_gss_name; #define GSS_NO_EXPIRATION ((time_t)-1) -#define GSS_DEF_REKEY_MINS 2 /* Default minutes between GSS cache checks */ +#define GSS_DEF_REKEY_MINS 2 /* Default minutes between GSS cache checks */ /* Functions, provided by either wingss.c or sshgssc.c */ @@ -61,7 +61,7 @@ void ssh_gss_cleanup(struct ssh_gss_liblist *list); * use. buf->data is not dynamically allocated. */ typedef Ssh_gss_stat (*t_ssh_gss_indicate_mech)(struct ssh_gss_library *lib, - Ssh_gss_buf *buf); + Ssh_gss_buf *buf); /* * Converts a name such as a hostname into a GSSAPI internal form, @@ -69,14 +69,14 @@ typedef Ssh_gss_stat (*t_ssh_gss_indicate_mech)(struct ssh_gss_library *lib, * ssh_gss_release_name(). */ typedef Ssh_gss_stat (*t_ssh_gss_import_name)(struct ssh_gss_library *lib, - char *in, Ssh_gss_name *out); + char *in, Ssh_gss_name *out); /* * Frees the contents of an Ssh_gss_name structure filled in by * ssh_gss_import_name(). */ typedef Ssh_gss_stat (*t_ssh_gss_release_name)(struct ssh_gss_library *lib, - Ssh_gss_name *name); + Ssh_gss_name *name); /* * The main GSSAPI security context setup function. The "out" @@ -96,7 +96,7 @@ typedef Ssh_gss_stat (*t_ssh_gss_init_sec_context) * way. */ typedef Ssh_gss_stat (*t_ssh_gss_free_tok)(struct ssh_gss_library *lib, - Ssh_gss_buf *); + Ssh_gss_buf *); /* * Acquires the credentials to perform authentication in the first @@ -111,14 +111,14 @@ typedef Ssh_gss_stat (*t_ssh_gss_acquire_cred)(struct ssh_gss_library *lib, * ssh_gss_acquire_cred(). */ typedef Ssh_gss_stat (*t_ssh_gss_release_cred)(struct ssh_gss_library *lib, - Ssh_gss_ctx *); + Ssh_gss_ctx *); /* * Gets a MIC for some input data. "out" needs to be freed by * ssh_gss_free_mic(). */ typedef Ssh_gss_stat (*t_ssh_gss_get_mic)(struct ssh_gss_library *lib, - Ssh_gss_ctx ctx, Ssh_gss_buf *in, + Ssh_gss_ctx ctx, Ssh_gss_buf *in, Ssh_gss_buf *out); /* @@ -137,17 +137,17 @@ typedef Ssh_gss_stat (*t_ssh_gss_verify_mic)(struct ssh_gss_library *lib, * way. */ typedef Ssh_gss_stat (*t_ssh_gss_free_mic)(struct ssh_gss_library *lib, - Ssh_gss_buf *); + Ssh_gss_buf *); /* * Return an error message after authentication failed. The * message string is returned in "buf", with buf->len giving the * number of characters of printable message text and buf->data * containing one more character which is a trailing NUL. - * buf->data should be manually freed by the caller. + * buf->data should be manually freed by the caller. */ typedef Ssh_gss_stat (*t_ssh_gss_display_status)(struct ssh_gss_library *lib, - Ssh_gss_ctx, Ssh_gss_buf *buf); + Ssh_gss_ctx, Ssh_gss_buf *buf); struct ssh_gss_library { /* @@ -185,12 +185,12 @@ struct ssh_gss_library { * Additional data for the wrapper layers. */ union { - struct gssapi_functions gssapi; - /* - * The SSPI wrappers don't need to store their Windows API - * function pointers in this structure, because there can't - * be more than one set of them available. - */ + struct gssapi_functions gssapi; + /* + * The SSPI wrappers don't need to store their Windows API + * function pointers in this structure, because there can't + * be more than one set of them available. + */ } u; /* diff --git a/sshgssc.c b/sshgssc.c index 26d301b7..adbb4377 100644 --- a/sshgssc.c +++ b/sshgssc.c @@ -8,7 +8,7 @@ #ifndef NO_GSSAPI static Ssh_gss_stat ssh_gssapi_indicate_mech(struct ssh_gss_library *lib, - Ssh_gss_buf *mech) + Ssh_gss_buf *mech) { /* Copy constant into mech */ mech->length = GSS_MECH_KRB5->length; @@ -17,8 +17,8 @@ static Ssh_gss_stat ssh_gssapi_indicate_mech(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_import_name(struct ssh_gss_library *lib, - char *host, - Ssh_gss_name *srv_name) + char *host, + Ssh_gss_name *srv_name) { struct gssapi_functions *gss = &lib->u.gssapi; OM_uint32 min_stat,maj_stat; @@ -31,7 +31,7 @@ static Ssh_gss_stat ssh_gssapi_import_name(struct ssh_gss_library *lib, host_buf.length = strlen(pStr); maj_stat = gss->import_name(&min_stat, &host_buf, - GSS_C_NT_HOSTBASED_SERVICE, srv_name); + GSS_C_NT_HOSTBASED_SERVICE, srv_name); /* Release buffer */ sfree(pStr); if (maj_stat == GSS_S_COMPLETE) return SSH_GSS_OK; @@ -101,10 +101,10 @@ static Ssh_gss_stat ssh_gssapi_acquire_cred(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_init_sec_context(struct ssh_gss_library *lib, - Ssh_gss_ctx *ctx, - Ssh_gss_name srv_name, - int to_deleg, - Ssh_gss_buf *recv_tok, + Ssh_gss_ctx *ctx, + Ssh_gss_name srv_name, + int to_deleg, + Ssh_gss_buf *recv_tok, Ssh_gss_buf *send_tok, time_t *expiry, unsigned long *lifetime) @@ -116,18 +116,18 @@ static Ssh_gss_stat ssh_gssapi_init_sec_context(struct ssh_gss_library *lib, if (to_deleg) to_deleg = GSS_C_DELEG_FLAG; gssctx->maj_stat = gss->init_sec_context(&gssctx->min_stat, - GSS_C_NO_CREDENTIAL, - &gssctx->ctx, - srv_name, - (gss_OID) GSS_MECH_KRB5, - GSS_C_MUTUAL_FLAG | - GSS_C_INTEG_FLAG | to_deleg, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - recv_tok, - NULL, /* ignore mech type */ - send_tok, - &ret_flags, + GSS_C_NO_CREDENTIAL, + &gssctx->ctx, + srv_name, + (gss_OID) GSS_MECH_KRB5, + GSS_C_MUTUAL_FLAG | + GSS_C_INTEG_FLAG | to_deleg, + 0, + GSS_C_NO_CHANNEL_BINDINGS, + recv_tok, + NULL, /* ignore mech type */ + send_tok, + &ret_flags, &lifetime_rec); if (lifetime) { @@ -149,8 +149,8 @@ static Ssh_gss_stat ssh_gssapi_init_sec_context(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_display_status(struct ssh_gss_library *lib, - Ssh_gss_ctx ctx, - Ssh_gss_buf *buf) + Ssh_gss_ctx ctx, + Ssh_gss_buf *buf) { struct gssapi_functions *gss = &lib->u.gssapi; gssapi_ssh_gss_ctx *gssctx = (gssapi_ssh_gss_ctx *) ctx; @@ -193,7 +193,7 @@ static Ssh_gss_stat ssh_gssapi_display_status(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_free_tok(struct ssh_gss_library *lib, - Ssh_gss_buf *send_tok) + Ssh_gss_buf *send_tok) { struct gssapi_functions *gss = &lib->u.gssapi; OM_uint32 min_stat,maj_stat; @@ -204,7 +204,7 @@ static Ssh_gss_stat ssh_gssapi_free_tok(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_release_cred(struct ssh_gss_library *lib, - Ssh_gss_ctx *ctx) + Ssh_gss_ctx *ctx) { struct gssapi_functions *gss = &lib->u.gssapi; gssapi_ssh_gss_ctx *gssctx = (gssapi_ssh_gss_ctx *) *ctx; @@ -223,7 +223,7 @@ static Ssh_gss_stat ssh_gssapi_release_cred(struct ssh_gss_library *lib, static Ssh_gss_stat ssh_gssapi_release_name(struct ssh_gss_library *lib, - Ssh_gss_name *srv_name) + Ssh_gss_name *srv_name) { struct gssapi_functions *gss = &lib->u.gssapi; OM_uint32 min_stat,maj_stat; @@ -234,8 +234,8 @@ static Ssh_gss_stat ssh_gssapi_release_name(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_get_mic(struct ssh_gss_library *lib, - Ssh_gss_ctx ctx, Ssh_gss_buf *buf, - Ssh_gss_buf *hash) + Ssh_gss_ctx ctx, Ssh_gss_buf *buf, + Ssh_gss_buf *hash) { struct gssapi_functions *gss = &lib->u.gssapi; gssapi_ssh_gss_ctx *gssctx = (gssapi_ssh_gss_ctx *) ctx; @@ -254,7 +254,7 @@ static Ssh_gss_stat ssh_gssapi_verify_mic(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_gssapi_free_mic(struct ssh_gss_library *lib, - Ssh_gss_buf *hash) + Ssh_gss_buf *hash) { /* On Unix this is the same freeing process as ssh_gssapi_free_tok. */ return ssh_gssapi_free_tok(lib, hash); diff --git a/sshmd5.c b/sshmd5.c index 504211f8..04de6816 100644 --- a/sshmd5.c +++ b/sshmd5.c @@ -154,32 +154,32 @@ static void MD5_BinarySink_write(BinarySink *bs, const void *data, size_t len) s->len += lenw; if (s->blkused + len < BLKSIZE) { - /* - * Trivial case: just add to the block. - */ - memcpy(s->block + s->blkused, q, len); - s->blkused += len; + /* + * 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_t) s->block[i * 4 + 3]) << 24) | - (((uint32_t) s->block[i * 4 + 2]) << 16) | - (((uint32_t) s->block[i * 4 + 1]) << 8) | - (((uint32_t) 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_t) s->block[i * 4 + 3]) << 24) | + (((uint32_t) s->block[i * 4 + 2]) << 16) | + (((uint32_t) s->block[i * 4 + 1]) << 8) | + (((uint32_t) s->block[i * 4 + 0]) << 0); + } + MD5_Block(&s->core, wordblock); + s->blkused = 0; + } + memcpy(s->block, q, len); + s->blkused = len; } } @@ -191,9 +191,9 @@ void MD5Final(unsigned char output[16], struct MD5Context *s) uint64_t len; if (s->blkused >= 56) - pad = 56 + 64 - s->blkused; + pad = 56 + 64 - s->blkused; else - pad = 56 - s->blkused; + pad = 56 - s->blkused; len = (s->len << 3); @@ -206,10 +206,10 @@ void MD5Final(unsigned char output[16], struct MD5Context *s) put_data(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; } } diff --git a/sshppl.h b/sshppl.h index baae1d83..4d55d380 100644 --- a/sshppl.h +++ b/sshppl.h @@ -10,7 +10,7 @@ typedef void (*packet_handler_fn_t)(PacketProtocolLayer *ppl, PktIn *pktin); struct PacketProtocolLayerVtable { - void (*free)(PacketProtocolLayer *); + void (*free)(PacketProtocolLayer *); void (*process_queue)(PacketProtocolLayer *ppl); bool (*get_specials)( PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx); diff --git a/sshprime.c b/sshprime.c index 44ab386e..cab601df 100644 --- a/sshprime.c +++ b/sshprime.c @@ -9,18 +9,18 @@ /* * This prime generation algorithm is pretty much cribbed from * OpenSSL. The algorithm is: - * + * * - invent a B-bit random number and ensure the top and bottom * bits are set (so it's definitely B-bit, and it's definitely * odd) - * + * * - see if it's coprime to all primes below 2^16; increment it by * two until it is (this shouldn't take long in general) - * + * * - perform the Miller-Rabin primality test enough times to * ensure the probability of it being composite is 2^-80 or * less - * + * * - go back to square one if any M-R test fails. */ @@ -29,30 +29,30 @@ * test. The Fermat test just checks that a^(p-1) == 1 mod p; this * is vulnerable to Carmichael numbers. Miller-Rabin considers how * that 1 is derived as well. - * + * * Lemma: if a^2 == 1 (mod p), and p is prime, then either a == 1 * or a == -1 (mod p). - * + * * Proof: p divides a^2-1, i.e. p divides (a+1)(a-1). Hence, * since p is prime, either p divides (a+1) or p divides (a-1). * But this is the same as saying that either a is congruent to * -1 mod p or a is congruent to +1 mod p. [] - * + * * Comment: This fails when p is not prime. Consider p=mn, so * that mn divides (a+1)(a-1). Now we could have m dividing (a+1) * and n dividing (a-1), without the whole of mn dividing either. * For example, consider a=10 and p=99. 99 = 9 * 11; 9 divides * 10-1 and 11 divides 10+1, so a^2 is congruent to 1 mod p * without a having to be congruent to either 1 or -1. - * + * * So the Miller-Rabin test, as well as considering a^(p-1), * considers a^((p-1)/2), a^((p-1)/4), and so on as far as it can * go. In other words. we write p-1 as q * 2^k, with k as large as * possible (i.e. q must be odd), and we consider the powers - * + * * a^(q*2^0) a^(q*2^1) ... a^(q*2^(k-1)) a^(q*2^k) * i.e. a^((n-1)/2^k) a^((n-1)/2^(k-1)) ... a^((n-1)/2) a^(n-1) - * + * * If p is to be prime, the last of these must be 1. Therefore, by * the above lemma, the one before it must be either 1 or -1. And * _if_ it's 1, then the one before that must be either 1 or -1, @@ -61,27 +61,27 @@ * 1s will be as long as the list so we'll never get to see what * lies before it. This doesn't count as a test failure because it * hasn't _proved_ that p is not prime.) - * + * * For example, consider a=2 and p=1729. 1729 is a Carmichael * number: although it's not prime, it satisfies a^(p-1) == 1 mod p * for any a coprime to it. So the Fermat test wouldn't have a * problem with it at all, unless we happened to stumble on an a * which had a common factor. - * + * * So. 1729 - 1 equals 27 * 2^6. So we look at - * + * * 2^27 mod 1729 == 645 * 2^108 mod 1729 == 1065 * 2^216 mod 1729 == 1 * 2^432 mod 1729 == 1 * 2^864 mod 1729 == 1 * 2^1728 mod 1729 == 1 - * + * * We do have a trailing string of 1s, so the Fermat test would * have been happy. But this trailing string of 1s is preceded by * 1065; whereas if 1729 were prime, we'd expect to see it preceded * by -1 (i.e. 1728.). Guards! Seize this impostor. - * + * * (If we were unlucky, we might have tried a=16 instead of a=2; * now 16^27 mod 1729 == 1, so we would have seen a long string of * 1s and wouldn't have seen the thing _before_ the 1s. So, just @@ -89,16 +89,16 @@ * of a which fail to show up its compositeness. So we try several, * just like the Fermat test. The difference is that Miller-Rabin * is not _in general_ fooled by Carmichael numbers.) - * + * * Put simply, then, the Miller-Rabin test requires us to: - * + * * 1. write p-1 as q * 2^k, with q odd * 2. compute z = (a^q) mod p. * 3. report success if z == 1 or z == -1. * 4. square z at most k-1 times, and report success if it becomes * -1 at any point. * 5. report failure otherwise. - * + * * (We expect z to become -1 after at most k-1 squarings, because * if it became -1 after k squarings then a^(p-1) would fail to be * 1. And we don't need to investigate what happens after we see a @@ -155,10 +155,10 @@ static unsigned short mp_mod_short(mp_int *x, unsigned short modulus) /* * Generate a prime. We can deal with various extra properties of * the prime: - * + * * - to speed up use in RSA, we can arrange to select a prime with * the property (prime % modulus) != residue. - * + * * - for use in DSA, we can arrange to select a prime which is one * more than a multiple of a dirty great bignum. In this case * `bits' gives the size of the factor by which we _multiply_ @@ -204,10 +204,10 @@ mp_int *primegen( mp_set_bit(p, bits-fbsize + i, 1 & (firstbits >> i)); if (factor) { - mp_int *tmp = p; - p = mp_mul(tmp, factor); - mp_free(tmp); - assert(mp_get_bit(p, 0) == 0); + mp_int *tmp = p; + p = mp_mul(tmp, factor); + mp_free(tmp); + assert(mp_get_bit(p, 0) == 0); mp_set_bit(p, 0, 1); } @@ -222,7 +222,7 @@ mp_int *primegen( /* List the moduli */ unsigned long moduli[NPRIMES + 1]; for (size_t i = 0; i < NPRIMES; i++) - moduli[i] = primes[i]; + moduli[i] = primes[i]; moduli[NPRIMES] = modulus; /* Find the residue of our starting number mod each of them. Also @@ -231,11 +231,11 @@ mp_int *primegen( * we're incrementing by multiples of factor). */ unsigned long residues[NPRIMES + 1], multipliers[NPRIMES + 1]; for (size_t i = 0; i < lenof(moduli); i++) { - residues[i] = mp_mod_short(p, moduli[i]); - if (factor) - multipliers[i] = mp_mod_short(factor, moduli[i]); - else - multipliers[i] = 1; + residues[i] = mp_mod_short(p, moduli[i]); + if (factor) + multipliers[i] = mp_mod_short(factor, moduli[i]); + else + multipliers[i] = 1; } /* Adjust the last entry so that it avoids a residue other than zero */ @@ -249,9 +249,9 @@ mp_int *primegen( */ unsigned delta = 0; while (1) { - for (size_t i = 0; i < lenof(moduli); i++) - if (!((residues[i] + delta * multipliers[i]) % moduli[i])) - goto found_a_zero; + for (size_t i = 0; i < lenof(moduli); i++) + if (!((residues[i] + delta * multipliers[i]) % moduli[i])) + goto found_a_zero; /* If we didn't exit that loop by goto, we've got our candidate. */ break; @@ -268,7 +268,7 @@ mp_int *primegen( * Having found a plausible increment, actually add it on. */ if (factor) { - mp_int *d = mp_from_integer(delta); + mp_int *d = mp_from_integer(delta); mp_int *df = mp_mul(d, factor); mp_add_into(p, p, df); mp_free(d); @@ -292,7 +292,7 @@ mp_int *primegen( */ size_t k; for (k = 0; mp_get_bit(p, k) == !k; k++) - continue; /* find first 1 bit in p-1 */ + continue; /* find first 1 bit in p-1 */ mp_int *q = mp_rshift_safe(p, k); /* @@ -310,27 +310,27 @@ mp_int *primegen( * Now, for each check ... */ for (unsigned check = 0; check < checks && !known_bad; check++) { - /* - * Invent a random number between 1 and p-1. - */ + /* + * Invent a random number between 1 and p-1. + */ mp_int *w = mp_random_in_range(two, pm1); monty_import_into(mc, w, w); - pfn(pfnparam, PROGFN_PROGRESS, phase, ++progress); + pfn(pfnparam, PROGFN_PROGRESS, phase, ++progress); - /* - * Compute w^q mod p. - */ - mp_int *wqp = monty_pow(mc, w, q); - mp_free(w); + /* + * Compute w^q mod p. + */ + mp_int *wqp = monty_pow(mc, w, q); + mp_free(w); - /* - * See if this is 1, or if it is -1, or if it becomes -1 - * when squared at most k-1 times. - */ + /* + * See if this is 1, or if it is -1, or if it becomes -1 + * when squared at most k-1 times. + */ bool passed = false; - if (mp_cmp_eq(wqp, monty_identity(mc)) || mp_cmp_eq(wqp, m_pm1)) { + if (mp_cmp_eq(wqp, monty_identity(mc)) || mp_cmp_eq(wqp, m_pm1)) { passed = true; } else { for (size_t i = 0; i < k - 1; i++) { @@ -340,12 +340,12 @@ mp_int *primegen( break; } } - } + } if (!passed) known_bad = true; - mp_free(wqp); + mp_free(wqp); } mp_free(q); diff --git a/sshpubk.c b/sshpubk.c index e4b2281a..442fb5ed 100644 --- a/sshpubk.c +++ b/sshpubk.c @@ -67,12 +67,12 @@ static int rsa_ssh1_load_main(FILE * fp, RSAKey *key, bool pub_only, * stopped after the \n.) */ if (get_byte(src) != 0) - goto end; + goto end; /* One byte giving encryption type, and one reserved uint32. */ ciphertype = get_byte(src); if (ciphertype != 0 && ciphertype != SSH1_CIPHER_3DES) - goto end; + goto end; if (get_uint32(src) != 0) goto end; /* reserved field nonzero, panic! */ @@ -82,19 +82,19 @@ static int rsa_ssh1_load_main(FILE * fp, RSAKey *key, bool pub_only, /* Next, the comment field. */ comment = get_string(src); if (commentptr) - *commentptr = mkstr(comment); + *commentptr = mkstr(comment); if (key) - key->comment = mkstr(comment); + key->comment = mkstr(comment); if (pub_only) { - ret = 1; - goto end; + ret = 1; + goto end; } if (!key) { - ret = ciphertype != 0; - *error = NULL; - goto end; + ret = ciphertype != 0; + *error = NULL; + goto end; } /* @@ -108,8 +108,8 @@ static int rsa_ssh1_load_main(FILE * fp, RSAKey *key, bool pub_only, goto end; hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf); - des3_decrypt_pubkey(keybuf, buf->u + src->pos, enclen); - smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */ + des3_decrypt_pubkey(keybuf, buf->u + src->pos, enclen); + smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */ } /* @@ -139,11 +139,11 @@ static int rsa_ssh1_load_main(FILE * fp, RSAKey *key, bool pub_only, key->p = get_mp_ssh1(src); if (!rsa_verify(key)) { - *error = "rsa_verify failed"; - freersakey(key); - ret = 0; + *error = "rsa_verify failed"; + freersakey(key); + ret = 0; } else - ret = 1; + ret = 1; end: strbuf_free(buf); @@ -160,8 +160,8 @@ int rsa_ssh1_loadkey(const Filename *filename, RSAKey *key, fp = f_open(filename, "rb", false); if (!fp) { - error = "can't open file"; - goto end; + error = "can't open file"; + goto end; } /* @@ -169,12 +169,12 @@ int rsa_ssh1_loadkey(const Filename *filename, RSAKey *key, * key file. */ if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) { - /* - * This routine will take care of calling fclose() for us. - */ - ret = rsa_ssh1_load_main(fp, key, false, NULL, passphrase, &error); - fp = NULL; - goto end; + /* + * This routine will take care of calling fclose() for us. + */ + ret = rsa_ssh1_load_main(fp, key, false, NULL, passphrase, &error); + fp = NULL; + goto end; } /* @@ -184,9 +184,9 @@ int rsa_ssh1_loadkey(const Filename *filename, RSAKey *key, end: if (fp) - fclose(fp); + fclose(fp); if ((ret != 1) && errorstr) - *errorstr = error; + *errorstr = error; return ret; } @@ -201,18 +201,18 @@ bool rsa_ssh1_encrypted(const Filename *filename, char **comment) fp = f_open(filename, "rb", false); if (!fp) - return false; /* doesn't even exist */ + return false; /* 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)) { - const char *dummy; - /* - * This routine will take care of calling fclose() for us. - */ - return rsa_ssh1_load_main(fp, NULL, false, comment, NULL, &dummy) == 1; + const char *dummy; + /* + * This routine will take care of calling fclose() for us. + */ + return rsa_ssh1_load_main(fp, NULL, false, comment, NULL, &dummy) == 1; } fclose(fp); return false; /* wasn't the right kind of file */ @@ -236,8 +236,8 @@ int rsa_ssh1_loadpub(const Filename *filename, BinarySink *bs, fp = f_open(filename, "rb", false); if (!fp) { - error = "can't open file"; - goto end; + error = "can't open file"; + goto end; } /* @@ -245,13 +245,13 @@ int rsa_ssh1_loadpub(const Filename *filename, BinarySink *bs, * key file. */ if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) { - memset(&key, 0, sizeof(key)); - if (rsa_ssh1_load_main(fp, &key, true, commentptr, NULL, &error)) { + memset(&key, 0, sizeof(key)); + if (rsa_ssh1_load_main(fp, &key, true, commentptr, NULL, &error)) { rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST); - freersakey(&key); - ret = 1; - } - fp = NULL; /* rsa_ssh1_load_main unconditionally closes fp */ + freersakey(&key); + ret = 1; + } + fp = NULL; /* rsa_ssh1_load_main unconditionally closes fp */ } else { /* * Try interpreting the file as an SSH-1 public key. @@ -285,7 +285,7 @@ int rsa_ssh1_loadpub(const Filename *filename, BinarySink *bs, commentp = NULL; } - memset(&key, 0, sizeof(key)); + memset(&key, 0, sizeof(key)); key.exponent = mp_from_decimal(expp); key.modulus = mp_from_decimal(modp); if (atoi(bitsp) != mp_get_nbits(key.modulus)) { @@ -305,14 +305,14 @@ int rsa_ssh1_loadpub(const Filename *filename, BinarySink *bs, not_public_either: sfree(line); - error = "not an SSH-1 RSA file"; + error = "not an SSH-1 RSA file"; } end: if (fp) - fclose(fp); + fclose(fp); if ((ret != 1) && errorstr) - *errorstr = error; + *errorstr = error; return ret; } @@ -372,11 +372,11 @@ bool rsa_ssh1_savekey(const Filename *filename, RSAKey *key, if (passphrase) { unsigned char keybuf[16]; - ssh_hash *h = ssh_hash_new(&ssh_md5); - put_data(h, passphrase, strlen(passphrase)); - ssh_hash_final(h, keybuf); - des3_encrypt_pubkey(keybuf, buf->u + estart, buf->len - estart); - smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */ + ssh_hash *h = ssh_hash_new(&ssh_md5); + put_data(h, passphrase, strlen(passphrase)); + ssh_hash_final(h, keybuf); + des3_encrypt_pubkey(keybuf, buf->u + estart, buf->len - estart); + smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */ } /* @@ -437,7 +437,7 @@ bool rsa_ssh1_savekey(const Filename *filename, RSAKey *key, * * mpint x (the private key parameter) * [ string hash 20-byte hash of mpints p || q || g only in old format ] - * + * * Finally, there is a line saying "Private-MAC: " plus a hex * representation of a HMAC-SHA-1 of: * @@ -448,9 +448,9 @@ bool rsa_ssh1_savekey(const Filename *filename, RSAKey *key, * string private-plaintext (the plaintext version of the * private part, including the final * padding) - * + * * The key to the MAC is itself a SHA-1 hash of: - * + * * data "putty-private-key-file-mac-key" * data passphrase * @@ -482,20 +482,20 @@ static bool read_header(FILE * fp, char *header) int c; while (1) { - c = fgetc(fp); - if (c == '\n' || c == '\r' || c == EOF) - return false; /* failure */ - if (c == ':') { - c = fgetc(fp); - if (c != ' ') - return false; - *header = '\0'; - return true; /* success! */ - } - if (len == 0) - return false; /* failure */ - *header++ = c; - len--; + c = fgetc(fp); + if (c == '\n' || c == '\r' || c == EOF) + return false; /* failure */ + if (c == ':') { + c = fgetc(fp); + if (c != ' ') + return false; + *header = '\0'; + return true; /* success! */ + } + if (len == 0) + return false; /* failure */ + *header++ = c; + len--; } return false; /* failure */ } @@ -505,16 +505,16 @@ static char *read_body(FILE * fp) strbuf *buf = strbuf_new_nm(); while (1) { - int c = fgetc(fp); - if (c == '\r' || c == '\n' || c == EOF) { - if (c != EOF) { - c = fgetc(fp); - if (c != '\r' && c != '\n') - ungetc(c, fp); - } - return strbuf_to_str(buf); - } - put_byte(buf, c); + int c = fgetc(fp); + if (c == '\r' || c == '\n' || c == EOF) { + if (c != EOF) { + c = fgetc(fp); + if (c != '\r' && c != '\n') + ungetc(c, fp); + } + return strbuf_to_str(buf); + } + put_byte(buf, c); } } @@ -530,28 +530,28 @@ static bool read_blob(FILE *fp, int nlines, BinarySink *bs) blob = snewn(48 * nlines, unsigned char); for (i = 0; i < nlines; i++) { - line = read_body(fp); - if (!line) { - sfree(blob); - return false; - } - linelen = strlen(line); - if (linelen % 4 != 0 || linelen > 64) { - sfree(blob); - sfree(line); - return false; - } - for (j = 0; j < linelen; j += 4) { + line = read_body(fp); + if (!line) { + sfree(blob); + return false; + } + linelen = strlen(line); + if (linelen % 4 != 0 || linelen > 64) { + sfree(blob); + sfree(line); + return false; + } + for (j = 0; j < linelen; j += 4) { unsigned char decoded[3]; - k = base64_decode_atom(line + j, decoded); - if (!k) { - sfree(line); - sfree(blob); - return false; - } - put_data(bs, decoded, k); - } - sfree(line); + k = base64_decode_atom(line + j, decoded); + if (!k) { + sfree(line); + sfree(blob); + return false; + } + put_data(bs, decoded, k); + } + sfree(line); } sfree(blob); return true; @@ -565,9 +565,9 @@ ssh2_userkey ssh2_wrong_passphrase = { NULL, NULL }; const ssh_keyalg *find_pubkey_alg_len(ptrlen name) { if (ptrlen_eq_string(name, "ssh-rsa")) - return &ssh_rsa; + return &ssh_rsa; else if (ptrlen_eq_string(name, "ssh-dss")) - return &ssh_dss; + return &ssh_dss; else if (ptrlen_eq_string(name, "ecdsa-sha2-nistp256")) return &ssh_ecdsa_nistp256; else if (ptrlen_eq_string(name, "ecdsa-sha2-nistp384")) @@ -577,7 +577,7 @@ const ssh_keyalg *find_pubkey_alg_len(ptrlen name) else if (ptrlen_eq_string(name, "ssh-ed25519")) return &ssh_ecdsa_ed25519; else - return NULL; + return NULL; } const ssh_keyalg *find_pubkey_alg(const char *name) @@ -622,107 +622,107 @@ ssh2_userkey *ssh2_load_userkey( int passlen = passphrase ? strlen(passphrase) : 0; const char *error = NULL; - ret = NULL; /* return NULL for most errors */ + ret = NULL; /* return NULL for most errors */ encryption = comment = mac = NULL; public_blob = private_blob = NULL; fp = f_open(filename, "rb", false); if (!fp) { - error = "can't open file"; - goto error; + error = "can't open file"; + goto error; } /* Read the first header line which contains the key type. */ if (!read_header(fp, header)) { - error = "no header line found in key file"; - goto error; + error = "no header line found in key file"; + goto error; } if (0 == strcmp(header, "PuTTY-User-Key-File-2")) { - old_fmt = false; + old_fmt = false; } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) { - /* this is an old key file; warn and then continue */ - old_keyfile_warning(); - old_fmt = true; + /* this is an old key file; warn and then continue */ + old_keyfile_warning(); + old_fmt = true; } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) { - /* this is a key file FROM THE FUTURE; refuse it, but with a + /* this is a key file FROM THE FUTURE; refuse it, but with a * more specific error message than the generic one below */ - error = "PuTTY key format too new"; - goto error; + error = "PuTTY key format too new"; + goto error; } else { - error = "not a PuTTY SSH-2 private key"; - goto error; + error = "not a PuTTY SSH-2 private key"; + goto error; } error = "file format error"; if ((b = read_body(fp)) == NULL) - goto error; + goto error; /* Select key algorithm structure. */ alg = find_pubkey_alg(b); if (!alg) { - sfree(b); - goto error; + sfree(b); + goto error; } sfree(b); /* Read the Encryption header line. */ if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) - goto error; + goto error; if ((encryption = read_body(fp)) == NULL) - goto error; + goto error; if (!strcmp(encryption, "aes256-cbc")) { - cipher = 1; - cipherblk = 16; + cipher = 1; + cipherblk = 16; } else if (!strcmp(encryption, "none")) { - cipher = 0; - cipherblk = 1; + cipher = 0; + cipherblk = 1; } else { - goto error; + goto error; } /* Read the Comment header line. */ if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) - goto error; + goto error; if ((comment = read_body(fp)) == NULL) - goto error; + goto error; /* Read the Public-Lines header line and the public blob. */ if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines")) - goto error; + goto error; if ((b = read_body(fp)) == NULL) - goto error; + goto error; i = userkey_parse_line_counter(b); sfree(b); if (i < 0) goto error; public_blob = strbuf_new(); if (!read_blob(fp, i, BinarySink_UPCAST(public_blob))) - goto error; + goto error; /* Read the Private-Lines header line and the Private blob. */ if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines")) - goto error; + goto error; if ((b = read_body(fp)) == NULL) - goto error; + goto error; i = userkey_parse_line_counter(b); sfree(b); if (i < 0) goto error; private_blob = strbuf_new_nm(); if (!read_blob(fp, i, BinarySink_UPCAST(private_blob))) - goto error; + goto error; /* Read the Private-MAC or Private-Hash header line. */ if (!read_header(fp, header)) - goto error; + goto error; if (0 == strcmp(header, "Private-MAC")) { - if ((mac = read_body(fp)) == NULL) - goto error; - is_mac = true; + if ((mac = read_body(fp)) == NULL) + goto error; + is_mac = true; } else if (0 == strcmp(header, "Private-Hash") && old_fmt) { - if ((mac = read_body(fp)) == NULL) - goto error; - is_mac = false; + if ((mac = read_body(fp)) == NULL) + goto error; + is_mac = false; } else - goto error; + goto error; fclose(fp); fp = NULL; @@ -731,84 +731,84 @@ ssh2_userkey *ssh2_load_userkey( * Decrypt the private blob. */ if (cipher) { - unsigned char key[40]; + unsigned char key[40]; - if (!passphrase) - goto error; - if (private_blob->len % cipherblk) - goto error; + if (!passphrase) + goto error; + if (private_blob->len % cipherblk) + goto error; ssh2_ppk_derivekey(ptrlen_from_asciz(passphrase), key); - aes256_decrypt_pubkey(key, private_blob->u, private_blob->len); + aes256_decrypt_pubkey(key, private_blob->u, private_blob->len); } /* * Verify the MAC. */ { - char realmac[41]; - unsigned char binary[20]; - strbuf *macdata; + char realmac[41]; + unsigned char binary[20]; + strbuf *macdata; bool free_macdata; - if (old_fmt) { - /* MAC (or hash) only covers the private blob. */ - macdata = private_blob; - free_macdata = false; - } else { + if (old_fmt) { + /* MAC (or hash) only covers the private blob. */ + macdata = private_blob; + free_macdata = false; + } else { macdata = strbuf_new_nm(); - put_stringz(macdata, alg->ssh_id); - put_stringz(macdata, encryption); - put_stringz(macdata, comment); - put_string(macdata, public_blob->s, + put_stringz(macdata, alg->ssh_id); + put_stringz(macdata, encryption); + put_stringz(macdata, comment); + put_string(macdata, public_blob->s, public_blob->len); - put_string(macdata, private_blob->s, + put_string(macdata, private_blob->s, private_blob->len); - free_macdata = true; - } + free_macdata = true; + } - if (is_mac) { + if (is_mac) { ssh_hash *hash; ssh2_mac *mac; - unsigned char mackey[20]; - char header[] = "putty-private-key-file-mac-key"; + unsigned char mackey[20]; + char header[] = "putty-private-key-file-mac-key"; hash = ssh_hash_new(&ssh_sha1); - put_data(hash, header, sizeof(header)-1); - if (cipher && passphrase) - put_data(hash, passphrase, passlen); - ssh_hash_final(hash, mackey); + put_data(hash, header, sizeof(header)-1); + if (cipher && passphrase) + put_data(hash, passphrase, passlen); + ssh_hash_final(hash, mackey); - mac = ssh2_mac_new(&ssh_hmac_sha1, NULL); + mac = ssh2_mac_new(&ssh_hmac_sha1, NULL); ssh2_mac_setkey(mac, make_ptrlen(mackey, 20)); ssh2_mac_start(mac); put_data(mac, macdata->s, macdata->len); ssh2_mac_genresult(mac, binary); ssh2_mac_free(mac); - smemclr(mackey, sizeof(mackey)); - } else { - hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary); - } + smemclr(mackey, sizeof(mackey)); + } else { + hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary); + } - if (free_macdata) - strbuf_free(macdata); + if (free_macdata) + strbuf_free(macdata); - for (i = 0; i < 20; i++) - sprintf(realmac + 2 * i, "%02x", binary[i]); + for (i = 0; i < 20; i++) + sprintf(realmac + 2 * i, "%02x", binary[i]); - if (strcmp(mac, realmac)) { - /* An incorrect MAC is an unconditional Error if the key is - * unencrypted. Otherwise, it means Wrong Passphrase. */ - if (cipher) { - error = "wrong passphrase"; - ret = SSH2_WRONG_PASSPHRASE; - } else { - error = "MAC failed"; - ret = NULL; - } - goto error; - } + if (strcmp(mac, realmac)) { + /* An incorrect MAC is an unconditional Error if the key is + * unencrypted. Otherwise, it means Wrong Passphrase. */ + if (cipher) { + error = "wrong passphrase"; + ret = SSH2_WRONG_PASSPHRASE; + } else { + error = "MAC failed"; + ret = NULL; + } + goto error; + } } sfree(mac); mac = NULL; @@ -822,16 +822,16 @@ ssh2_userkey *ssh2_load_userkey( alg, ptrlen_from_strbuf(public_blob), ptrlen_from_strbuf(private_blob)); if (!ret->key) { - sfree(ret); - ret = NULL; - error = "createkey failed"; - goto error; + sfree(ret); + ret = NULL; + error = "createkey failed"; + goto error; } strbuf_free(public_blob); strbuf_free(private_blob); sfree(encryption); if (errorstr) - *errorstr = NULL; + *errorstr = NULL; return ret; /* @@ -839,19 +839,19 @@ ssh2_userkey *ssh2_load_userkey( */ error: if (fp) - fclose(fp); + fclose(fp); if (comment) - sfree(comment); + sfree(comment); if (encryption) - sfree(encryption); + sfree(encryption); if (mac) - sfree(mac); + sfree(mac); if (public_blob) - strbuf_free(public_blob); + strbuf_free(public_blob); if (private_blob) strbuf_free(private_blob); if (errorstr) - *errorstr = error; + *errorstr = error; return ret; } @@ -1071,8 +1071,8 @@ bool ssh2_userkey_loadpub(const Filename *filename, char **algorithm, fp = f_open(filename, "rb", false); if (!fp) { - error = "can't open file"; - goto error; + error = "can't open file"; + goto error; } /* Initially, check if this is a public-only key file. Sometimes @@ -1093,57 +1093,57 @@ bool ssh2_userkey_loadpub(const Filename *filename, char **algorithm, /* Read the first header line which contains the key type. */ if (!read_header(fp, header) - || (0 != strcmp(header, "PuTTY-User-Key-File-2") && - 0 != strcmp(header, "PuTTY-User-Key-File-1"))) { + || (0 != strcmp(header, "PuTTY-User-Key-File-2") && + 0 != strcmp(header, "PuTTY-User-Key-File-1"))) { if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) error = "PuTTY key format too new"; else error = "not a PuTTY SSH-2 private key"; - goto error; + goto error; } error = "file format error"; if ((b = read_body(fp)) == NULL) - goto error; + goto error; /* Select key algorithm structure. */ alg = find_pubkey_alg(b); sfree(b); if (!alg) { - goto error; + goto error; } /* Read the Encryption header line. */ if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) - goto error; + goto error; if ((b = read_body(fp)) == NULL) - goto error; - sfree(b); /* we don't care */ + goto error; + sfree(b); /* we don't care */ /* Read the Comment header line. */ if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) - goto error; + goto error; if ((comment = read_body(fp)) == NULL) - goto error; + goto error; if (commentptr) - *commentptr = comment; + *commentptr = comment; else - sfree(comment); + sfree(comment); /* Read the Public-Lines header line and the public blob. */ if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines")) - goto error; + goto error; if ((b = read_body(fp)) == NULL) - goto error; + goto error; i = userkey_parse_line_counter(b); sfree(b); if (i < 0) goto error; if (!read_blob(fp, i, bs)) - goto error; + goto error; fclose(fp); if (algorithm) - *algorithm = dupstr(alg->ssh_id); + *algorithm = dupstr(alg->ssh_id); return true; /* @@ -1151,9 +1151,9 @@ bool ssh2_userkey_loadpub(const Filename *filename, char **algorithm, */ error: if (fp) - fclose(fp); + fclose(fp); if (errorstr) - *errorstr = error; + *errorstr = error; if (comment && commentptr) { sfree(comment); *commentptr = NULL; @@ -1168,54 +1168,54 @@ bool ssh2_userkey_encrypted(const Filename *filename, char **commentptr) bool ret; if (commentptr) - *commentptr = NULL; + *commentptr = NULL; fp = f_open(filename, "rb", false); if (!fp) - return false; + return false; if (!read_header(fp, header) - || (0 != strcmp(header, "PuTTY-User-Key-File-2") && - 0 != strcmp(header, "PuTTY-User-Key-File-1"))) { - fclose(fp); - return false; + || (0 != strcmp(header, "PuTTY-User-Key-File-2") && + 0 != strcmp(header, "PuTTY-User-Key-File-1"))) { + fclose(fp); + return false; } if ((b = read_body(fp)) == NULL) { - fclose(fp); - return false; + fclose(fp); + return false; } - sfree(b); /* we don't care about key type here */ + 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 false; + fclose(fp); + return false; } if ((b = read_body(fp)) == NULL) { - fclose(fp); - return false; + fclose(fp); + return false; } /* Read the Comment header line. */ if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) { - fclose(fp); - sfree(b); - return true; + fclose(fp); + sfree(b); + return true; } if ((comment = read_body(fp)) == NULL) { - fclose(fp); - sfree(b); - return true; + fclose(fp); + sfree(b); + return true; } if (commentptr) - *commentptr = comment; + *commentptr = comment; else sfree(comment); fclose(fp); if (!strcmp(b, "aes256-cbc")) - ret = true; + ret = true; else - ret = false; + ret = false; sfree(b); return ret; } @@ -1233,18 +1233,18 @@ void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl) int n, i; while (datalen > 0) { - n = (datalen < 3 ? datalen : 3); - base64_encode_atom(data, n, out); - data += n; - datalen -= n; - for (i = 0; i < 4; i++) { - if (linelen >= cpl) { - linelen = 0; - fputc('\n', fp); - } - fputc(out[i], fp); - linelen++; - } + n = (datalen < 3 ? datalen : 3); + base64_encode_atom(data, n, out); + data += n; + datalen -= n; + for (i = 0; i < 4; i++) { + if (linelen >= cpl) { + linelen = 0; + fputc('\n', fp); + } + fputc(out[i], fp); + linelen++; + } } fputc('\n', fp); } @@ -1273,11 +1273,11 @@ bool ssh2_save_userkey( * Determine encryption details, and encrypt the private blob. */ if (passphrase) { - cipherstr = "aes256-cbc"; - cipherblk = 16; + cipherstr = "aes256-cbc"; + cipherblk = 16; } else { - cipherstr = "none"; - cipherblk = 1; + cipherstr = "none"; + cipherblk = 1; } priv_encrypted_len = priv_blob->len + cipherblk - 1; priv_encrypted_len -= priv_encrypted_len % cipherblk; @@ -1289,39 +1289,39 @@ bool ssh2_save_userkey( hash_simple(&ssh_sha1, ptrlen_from_strbuf(priv_blob), priv_mac); assert(priv_encrypted_len - priv_blob->len < 20); memcpy(priv_blob_encrypted + priv_blob->len, priv_mac, - priv_encrypted_len - priv_blob->len); + priv_encrypted_len - priv_blob->len); /* Now create the MAC. */ { - strbuf *macdata; - unsigned char mackey[20]; - char header[] = "putty-private-key-file-mac-key"; + strbuf *macdata; + unsigned char mackey[20]; + char header[] = "putty-private-key-file-mac-key"; - macdata = strbuf_new_nm(); - put_stringz(macdata, ssh_key_ssh_id(key->key)); - put_stringz(macdata, cipherstr); - put_stringz(macdata, key->comment); - put_string(macdata, pub_blob->s, pub_blob->len); - put_string(macdata, priv_blob_encrypted, priv_encrypted_len); + macdata = strbuf_new_nm(); + put_stringz(macdata, ssh_key_ssh_id(key->key)); + put_stringz(macdata, cipherstr); + put_stringz(macdata, key->comment); + put_string(macdata, pub_blob->s, pub_blob->len); + put_string(macdata, priv_blob_encrypted, priv_encrypted_len); ssh_hash *h = ssh_hash_new(&ssh_sha1); - put_data(h, header, sizeof(header)-1); - if (passphrase) - put_data(h, passphrase, strlen(passphrase)); - ssh_hash_final(h, mackey); - mac_simple(&ssh_hmac_sha1, make_ptrlen(mackey, 20), + put_data(h, header, sizeof(header)-1); + if (passphrase) + put_data(h, passphrase, strlen(passphrase)); + ssh_hash_final(h, mackey); + mac_simple(&ssh_hmac_sha1, make_ptrlen(mackey, 20), ptrlen_from_strbuf(macdata), priv_mac); - strbuf_free(macdata); - smemclr(mackey, sizeof(mackey)); + strbuf_free(macdata); + smemclr(mackey, sizeof(mackey)); } if (passphrase) { - unsigned char key[40]; + unsigned char key[40]; ssh2_ppk_derivekey(ptrlen_from_asciz(passphrase), key); - aes256_encrypt_pubkey(key, priv_blob_encrypted, priv_encrypted_len); + aes256_encrypt_pubkey(key, priv_blob_encrypted, priv_encrypted_len); - smemclr(key, sizeof(key)); + smemclr(key, sizeof(key)); } fp = f_open(filename, "w", true); @@ -1341,7 +1341,7 @@ bool ssh2_save_userkey( base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64); fprintf(fp, "Private-MAC: "); for (i = 0; i < 20; i++) - fprintf(fp, "%02x", priv_mac[i]); + fprintf(fp, "%02x", priv_mac[i]); fprintf(fp, "\n"); fclose(fp); @@ -1551,34 +1551,34 @@ static int key_type_fp(FILE *fp) rewind(fp); if (i < 0) - return SSH_KEYTYPE_UNOPENABLE; + return SSH_KEYTYPE_UNOPENABLE; if (i < 32) - return SSH_KEYTYPE_UNKNOWN; + return SSH_KEYTYPE_UNKNOWN; assert(i > 0 && i < sizeof(buf)); buf[i] = '\0'; if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1)) - return SSH_KEYTYPE_SSH1; + return SSH_KEYTYPE_SSH1; if (!memcmp(buf, public_std_sig, sizeof(public_std_sig)-1)) - return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716; + return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716; if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1)) - return SSH_KEYTYPE_SSH2; + return SSH_KEYTYPE_SSH2; if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1)) - return SSH_KEYTYPE_OPENSSH_NEW; + return SSH_KEYTYPE_OPENSSH_NEW; if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1)) - return SSH_KEYTYPE_OPENSSH_PEM; + return SSH_KEYTYPE_OPENSSH_PEM; if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1)) - return SSH_KEYTYPE_SSHCOM; + return SSH_KEYTYPE_SSHCOM; if ((p = buf + strspn(buf, "0123456789"), *p == ' ') && (p = p+1 + strspn(p+1, "0123456789"), *p == ' ') && (p = p+1 + strspn(p+1, "0123456789"), *p == ' ' || *p == '\n' || !*p)) - return SSH_KEYTYPE_SSH1_PUBLIC; + return SSH_KEYTYPE_SSH1_PUBLIC; if ((p = buf + strcspn(buf, " "), find_pubkey_alg_len(make_ptrlen(buf, p-buf))) && (p = p+1 + strspn(p+1, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij" "klmnopqrstuvwxyz+/="), *p == ' ' || *p == '\n' || !*p)) - return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH; - return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */ + return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH; + return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */ } int key_type(const Filename *filename) @@ -1588,7 +1588,7 @@ int key_type(const Filename *filename) fp = f_open(filename, "r", false); if (!fp) - return SSH_KEYTYPE_UNOPENABLE; + return SSH_KEYTYPE_UNOPENABLE; ret = key_type_fp(fp); fclose(fp); return ret; diff --git a/sshrand.c b/sshrand.c index ad93576e..387a068a 100644 --- a/sshrand.c +++ b/sshrand.c @@ -38,7 +38,7 @@ static unsigned long next_noise_collection; void random_add_noise(NoiseSourceId source, const void *noise, int length) { if (!random_active) - return; + return; prng_add_entropy(global_prng, source, make_ptrlen(noise, length)); } @@ -46,9 +46,9 @@ void random_add_noise(NoiseSourceId source, const void *noise, int length) static void random_timer(void *ctx, unsigned long now) { if (random_active > 0 && now == next_noise_collection) { - noise_regular(); - next_noise_collection = - schedule_timer(NOISE_REGULAR_INTERVAL, random_timer, + noise_regular(); + next_noise_collection = + schedule_timer(NOISE_REGULAR_INTERVAL, random_timer, &random_timer_ctx); } } @@ -85,9 +85,9 @@ void random_save_seed(void) void *data; if (random_active) { - random_get_savedata(&data, &len); - write_random_seed(data, len); - sfree(data); + random_get_savedata(&data, &len); + write_random_seed(data, len); + sfree(data); } } diff --git a/sshrsa.c b/sshrsa.c index 4d26f9f6..e30ca474 100644 --- a/sshrsa.c +++ b/sshrsa.c @@ -50,7 +50,7 @@ bool rsa_ssh1_encrypt(unsigned char *data, int length, RSAKey *key) unsigned char *p; if (key->bytes < length + 4) - return false; /* RSA key too short! */ + return false; /* RSA key too short! */ memmove(data + key->bytes - length, data, length); data[0] = 0; @@ -95,7 +95,7 @@ bool rsa_ssh1_encrypt(unsigned char *data, int length, RSAKey *key) p = data; for (i = key->bytes; i--;) { - *p++ = mp_get_byte(b2, i); + *p++ = mp_get_byte(b2, i); } mp_free(b1); @@ -280,7 +280,7 @@ char *rsa_ssh1_fingerprint(RSAKey *key) out = strbuf_new(); strbuf_catf(out, "%d ", mp_get_nbits(key->modulus)); for (i = 0; i < 16; i++) - strbuf_catf(out, "%s%02x", i ? ":" : "", digest[i]); + strbuf_catf(out, "%s%02x", i ? ":" : "", digest[i]); if (key->comment) strbuf_catf(out, " %s", key->comment); return strbuf_to_str(out); @@ -370,7 +370,7 @@ int rsa_ssh1_public_blob_len(ptrlen data) mp_free(get_mp_ssh1(src)); if (get_err(src)) - return -1; + return -1; /* Return the number of bytes consumed. */ return src->pos; @@ -379,19 +379,19 @@ int rsa_ssh1_public_blob_len(ptrlen data) void freersapriv(RSAKey *key) { if (key->private_exponent) { - mp_free(key->private_exponent); + mp_free(key->private_exponent); key->private_exponent = NULL; } if (key->p) { - mp_free(key->p); + mp_free(key->p); key->p = NULL; } if (key->q) { - mp_free(key->q); + mp_free(key->q); key->q = NULL; } if (key->iqmp) { - mp_free(key->iqmp); + mp_free(key->iqmp); key->iqmp = NULL; } } @@ -400,21 +400,21 @@ void freersakey(RSAKey *key) { freersapriv(key); if (key->modulus) { - mp_free(key->modulus); + mp_free(key->modulus); key->modulus = NULL; } if (key->exponent) { - mp_free(key->exponent); + mp_free(key->exponent); key->exponent = NULL; } if (key->comment) { - sfree(key->comment); + sfree(key->comment); key->comment = NULL; } } /* ---------------------------------------------------------------------- - * Implementation of the ssh-rsa signing key type. + * Implementation of the ssh-rsa signing key type. */ static void rsa2_freekey(ssh_key *key); /* forward reference */ @@ -426,7 +426,7 @@ static ssh_key *rsa2_new_pub(const ssh_keyalg *self, ptrlen data) BinarySource_BARE_INIT_PL(src, data); if (!ptrlen_eq_string(get_string(src), "ssh-rsa")) - return NULL; + return NULL; rsa = snew(RSAKey); rsa->sshk.vt = &ssh_rsa; @@ -437,8 +437,8 @@ static ssh_key *rsa2_new_pub(const ssh_keyalg *self, ptrlen data) rsa->comment = NULL; if (get_err(src)) { - rsa2_freekey(&rsa->sshk); - return NULL; + rsa2_freekey(&rsa->sshk); + return NULL; } return &rsa->sshk; @@ -495,8 +495,8 @@ static ssh_key *rsa2_new_priv(const ssh_keyalg *self, rsa->iqmp = get_mp_ssh2(src); if (get_err(src) || !rsa_verify(rsa)) { - rsa2_freekey(&rsa->sshk); - return NULL; + rsa2_freekey(&rsa->sshk); + return NULL; } return &rsa->sshk; @@ -519,8 +519,8 @@ static ssh_key *rsa2_new_priv_openssh(const ssh_keyalg *self, rsa->q = get_mp_ssh2(src); if (get_err(src) || !rsa_verify(rsa)) { - rsa2_freekey(&rsa->sshk); - return NULL; + rsa2_freekey(&rsa->sshk); + return NULL; } return &rsa->sshk; @@ -704,7 +704,7 @@ static bool rsa2_verify(ssh_key *key, ptrlen sig, ptrlen data) */ in_pl = get_string(src); if (get_err(src) || !ptrlen_eq_string(type, "ssh-rsa")) - return false; + return false; in = mp_from_bytes_be(in_pl); out = mp_modpow(in, rsa->exponent, rsa->modulus); @@ -748,7 +748,7 @@ static void rsa2_sign(ssh_key *key, ptrlen data, nbytes = (mp_get_nbits(out) + 7) / 8; put_uint32(bs, nbytes); for (size_t i = 0; i < nbytes; i++) - put_byte(bs, mp_get_byte(out, nbytes - 1 - i)); + put_byte(bs, mp_get_byte(out, nbytes - 1 - i)); mp_free(out); } @@ -809,7 +809,7 @@ int ssh_rsakex_klen(RSAKey *rsa) } static void oaep_mask(const ssh_hashalg *h, void *seed, int seedlen, - void *vdata, int datalen) + void *vdata, int datalen) { unsigned char *data = (unsigned char *)vdata; unsigned count = 0; @@ -819,7 +819,7 @@ static void oaep_mask(const ssh_hashalg *h, void *seed, int seedlen, ssh_hash *s; unsigned char hash[MAX_HASH_LEN]; - assert(h->hlen <= MAX_HASH_LEN); + assert(h->hlen <= MAX_HASH_LEN); s = ssh_hash_new(h); put_data(s, seed, seedlen); put_uint32(s, count); @@ -843,26 +843,26 @@ strbuf *ssh_rsakex_encrypt(RSAKey *rsa, const ssh_hashalg *h, ptrlen in) /* * Here we encrypt using RSAES-OAEP. Essentially this means: - * + * * - we have a SHA-based `mask generation function' which * creates a pseudo-random stream of mask data * deterministically from an input chunk of data. - * + * * - we have a random chunk of data called a seed. - * + * * - we use the seed to generate a mask which we XOR with our * plaintext. - * + * * - then we use _the masked plaintext_ to generate a mask * which we XOR with the seed. - * + * * - then we concatenate the masked seed and the masked * plaintext, and RSA-encrypt that lot. - * + * * The result is that the data input to the encryption function * is random-looking and (hopefully) contains no exploitable * structure such as PKCS1-v1_5 does. - * + * * For a precise specification, see RFC 3447, section 7.1.1. * Some of the variable names below are derived from that, so * it'd probably help to read it anyway. @@ -917,7 +917,7 @@ strbuf *ssh_rsakex_encrypt(RSAKey *rsa, const ssh_hashalg *h, ptrlen in) b2 = mp_modpow(b1, rsa->exponent, rsa->modulus); p = (char *)out; for (i = outlen; i--;) { - *p++ = mp_get_byte(b2, i); + *p++ = mp_get_byte(b2, i); } mp_free(b1); mp_free(b2); diff --git a/sshrsag.c b/sshrsag.c index 2d88fef9..fe96c994 100644 --- a/sshrsag.c +++ b/sshrsag.c @@ -7,10 +7,10 @@ #include "ssh.h" #include "mpint.h" -#define RSA_EXPONENT 37 /* we like this prime */ +#define RSA_EXPONENT 37 /* we like this prime */ int rsa_generate(RSAKey *key, int bits, progfn_t pfn, - void *pfnparam) + void *pfnparam) { unsigned pfirst, qfirst; @@ -38,7 +38,7 @@ int rsa_generate(RSAKey *key, int bits, progfn_t pfn, * P(1-P), in three with probability P(1-P)^2, etc. The * probability that we have still not managed to find a prime * after N attempts is (1-P)^N. - * + * * We therefore inform the progress indicator of the number B * (29.34/B), so that it knows how much to increment by each * time. We do this in 16-bit fixed point, so 29.34 becomes diff --git a/sshserver.c b/sshserver.c index 876e1c0b..7889b7d4 100644 --- a/sshserver.c +++ b/sshserver.c @@ -148,8 +148,8 @@ static void server_receive( /* Log raw data, if we're in that mode. */ if (srv->logctx) - log_packet(srv->logctx, PKT_INCOMING, -1, NULL, data, len, - 0, NULL, NULL, 0, NULL); + log_packet(srv->logctx, PKT_INCOMING, -1, NULL, data, len, + 0, NULL, NULL, 0, NULL); bufchain_add(&srv->in_raw, data, len); if (!srv->frozen && srv->bpp) @@ -168,7 +168,7 @@ static void server_sent(Plug *plug, size_t bufsize) * some more data off its bufchain. */ if (bufsize < SSH_MAX_BACKLOG) { - srv_throttle_all(srv, 0, bufsize); + srv_throttle_all(srv, 0, bufsize); queue_idempotent_callback(&srv->ic_out_raw); } #endif @@ -497,7 +497,7 @@ static void server_got_ssh_version(struct ssh_version_receiver *rcv, server_connect_bpp(srv); connection_layer = ssh2_connection_new( - &srv->ssh, NULL, false, srv->conf, + &srv->ssh, NULL, false, srv->conf, ssh_verstring_get_local(old_bpp), &srv->cl); ssh2connection_server_configure(connection_layer, srv->sftpserver_vt, srv->ssc); diff --git a/sshsh256.c b/sshsh256.c index cb138f63..1e445171 100644 --- a/sshsh256.c +++ b/sshsh256.c @@ -1,6 +1,6 @@ /* * SHA-256 algorithm as described at - * + * * http://csrc.nist.gov/cryptval/shs.html */ @@ -241,20 +241,20 @@ static void sha256_sw_block(uint32_t *core, const uint8_t *block) w[t] = GET_32BIT_MSB_FIRST(block + 4*t); for (size_t t = 16; t < SHA256_ROUNDS; t++) - w[t] = sigma_1(w[t-2]) + w[t-7] + sigma_0(w[t-15]) + w[t-16]; + w[t] = sigma_1(w[t-2]) + w[t-7] + sigma_0(w[t-15]) + w[t-16]; a = core[0]; b = core[1]; c = core[2]; d = core[3]; e = core[4]; f = core[5]; g = core[6]; h = core[7]; for (size_t t = 0; t < SHA256_ROUNDS; t += 8) { - sha256_sw_round(t+0, w, &a,&b,&c,&d,&e,&f,&g,&h); - sha256_sw_round(t+1, w, &h,&a,&b,&c,&d,&e,&f,&g); - sha256_sw_round(t+2, w, &g,&h,&a,&b,&c,&d,&e,&f); - sha256_sw_round(t+3, w, &f,&g,&h,&a,&b,&c,&d,&e); - sha256_sw_round(t+4, w, &e,&f,&g,&h,&a,&b,&c,&d); - sha256_sw_round(t+5, w, &d,&e,&f,&g,&h,&a,&b,&c); - sha256_sw_round(t+6, w, &c,&d,&e,&f,&g,&h,&a,&b); - sha256_sw_round(t+7, w, &b,&c,&d,&e,&f,&g,&h,&a); + sha256_sw_round(t+0, w, &a,&b,&c,&d,&e,&f,&g,&h); + sha256_sw_round(t+1, w, &h,&a,&b,&c,&d,&e,&f,&g); + sha256_sw_round(t+2, w, &g,&h,&a,&b,&c,&d,&e,&f); + sha256_sw_round(t+3, w, &f,&g,&h,&a,&b,&c,&d,&e); + sha256_sw_round(t+4, w, &e,&f,&g,&h,&a,&b,&c,&d); + sha256_sw_round(t+5, w, &d,&e,&f,&g,&h,&a,&b,&c); + sha256_sw_round(t+6, w, &c,&d,&e,&f,&g,&h,&a,&b); + sha256_sw_round(t+7, w, &b,&c,&d,&e,&f,&g,&h,&a); } core[0] += a; core[1] += b; core[2] += c; core[3] += d; @@ -370,7 +370,7 @@ const ssh_hashalg ssh_sha256_sw = { static bool sha256_hw_available(void) { unsigned int CPUInfo[4]; - GET_CPU_ID_0(CPUInfo); + GET_CPU_ID_0(CPUInfo); if (CPUInfo[0] < 7) return false; diff --git a/sshsh512.c b/sshsh512.c index 30c1a09d..6712047c 100644 --- a/sshsh512.c +++ b/sshsh512.c @@ -1,6 +1,6 @@ /* * SHA-512 algorithm as described at - * + * * http://csrc.nist.gov/cryptval/shs.html * * Modifications made for SHA-384 also @@ -42,30 +42,30 @@ typedef struct { #define Ch(r,t,x,y,z) ( not(t,x), and(r,t,z), and(t,x,y), xor(r,r,t) ) #define Maj(r,t,x,y,z) ( and(r,x,y), and(t,x,z), xor(r,r,t), \ - and(t,y,z), xor(r,r,t) ) + and(t,y,z), xor(r,r,t) ) #define bigsigma0(r,t,x) ( rorL(r,x,28), rorB(t,x,34), xor(r,r,t), \ - rorB(t,x,39), xor(r,r,t) ) + rorB(t,x,39), xor(r,r,t) ) #define bigsigma1(r,t,x) ( rorL(r,x,14), rorL(t,x,18), xor(r,r,t), \ - rorB(t,x,41), xor(r,r,t) ) + rorB(t,x,41), xor(r,r,t) ) #define smallsigma0(r,t,x) ( rorL(r,x,1), rorL(t,x,8), xor(r,r,t), \ - shrL(t,x,7), xor(r,r,t) ) + shrL(t,x,7), xor(r,r,t) ) #define smallsigma1(r,t,x) ( rorL(r,x,19), rorB(t,x,61), xor(r,r,t), \ - shrL(t,x,6), xor(r,r,t) ) + shrL(t,x,6), xor(r,r,t) ) static void SHA512_Core_Init(SHA512_State *s) { static const uint64_t iv[] = { - INIT(0x6a09e667, 0xf3bcc908), - INIT(0xbb67ae85, 0x84caa73b), - INIT(0x3c6ef372, 0xfe94f82b), - INIT(0xa54ff53a, 0x5f1d36f1), - INIT(0x510e527f, 0xade682d1), - INIT(0x9b05688c, 0x2b3e6c1f), - INIT(0x1f83d9ab, 0xfb41bd6b), - INIT(0x5be0cd19, 0x137e2179), + INIT(0x6a09e667, 0xf3bcc908), + INIT(0xbb67ae85, 0x84caa73b), + INIT(0x3c6ef372, 0xfe94f82b), + INIT(0xa54ff53a, 0x5f1d36f1), + INIT(0x510e527f, 0xade682d1), + INIT(0x9b05688c, 0x2b3e6c1f), + INIT(0x1f83d9ab, 0xfb41bd6b), + INIT(0x5be0cd19, 0x137e2179), }; int i; for (i = 0; i < 8; i++) - s->h[i] = iv[i]; + s->h[i] = iv[i]; } static void SHA384_Core_Init(SHA512_State *s) { @@ -88,46 +88,46 @@ static void SHA512_Block(SHA512_State *s, uint64_t *block) { uint64_t w[80]; uint64_t a,b,c,d,e,f,g,h; static const uint64_t k[] = { - INIT(0x428a2f98, 0xd728ae22), INIT(0x71374491, 0x23ef65cd), - INIT(0xb5c0fbcf, 0xec4d3b2f), INIT(0xe9b5dba5, 0x8189dbbc), - INIT(0x3956c25b, 0xf348b538), INIT(0x59f111f1, 0xb605d019), - INIT(0x923f82a4, 0xaf194f9b), INIT(0xab1c5ed5, 0xda6d8118), - INIT(0xd807aa98, 0xa3030242), INIT(0x12835b01, 0x45706fbe), - INIT(0x243185be, 0x4ee4b28c), INIT(0x550c7dc3, 0xd5ffb4e2), - INIT(0x72be5d74, 0xf27b896f), INIT(0x80deb1fe, 0x3b1696b1), - INIT(0x9bdc06a7, 0x25c71235), INIT(0xc19bf174, 0xcf692694), - INIT(0xe49b69c1, 0x9ef14ad2), INIT(0xefbe4786, 0x384f25e3), - INIT(0x0fc19dc6, 0x8b8cd5b5), INIT(0x240ca1cc, 0x77ac9c65), - INIT(0x2de92c6f, 0x592b0275), INIT(0x4a7484aa, 0x6ea6e483), - INIT(0x5cb0a9dc, 0xbd41fbd4), INIT(0x76f988da, 0x831153b5), - INIT(0x983e5152, 0xee66dfab), INIT(0xa831c66d, 0x2db43210), - INIT(0xb00327c8, 0x98fb213f), INIT(0xbf597fc7, 0xbeef0ee4), - INIT(0xc6e00bf3, 0x3da88fc2), INIT(0xd5a79147, 0x930aa725), - INIT(0x06ca6351, 0xe003826f), INIT(0x14292967, 0x0a0e6e70), - INIT(0x27b70a85, 0x46d22ffc), INIT(0x2e1b2138, 0x5c26c926), - INIT(0x4d2c6dfc, 0x5ac42aed), INIT(0x53380d13, 0x9d95b3df), - INIT(0x650a7354, 0x8baf63de), INIT(0x766a0abb, 0x3c77b2a8), - INIT(0x81c2c92e, 0x47edaee6), INIT(0x92722c85, 0x1482353b), - INIT(0xa2bfe8a1, 0x4cf10364), INIT(0xa81a664b, 0xbc423001), - INIT(0xc24b8b70, 0xd0f89791), INIT(0xc76c51a3, 0x0654be30), - INIT(0xd192e819, 0xd6ef5218), INIT(0xd6990624, 0x5565a910), - INIT(0xf40e3585, 0x5771202a), INIT(0x106aa070, 0x32bbd1b8), - INIT(0x19a4c116, 0xb8d2d0c8), INIT(0x1e376c08, 0x5141ab53), - INIT(0x2748774c, 0xdf8eeb99), INIT(0x34b0bcb5, 0xe19b48a8), - INIT(0x391c0cb3, 0xc5c95a63), INIT(0x4ed8aa4a, 0xe3418acb), - INIT(0x5b9cca4f, 0x7763e373), INIT(0x682e6ff3, 0xd6b2b8a3), - INIT(0x748f82ee, 0x5defb2fc), INIT(0x78a5636f, 0x43172f60), - INIT(0x84c87814, 0xa1f0ab72), INIT(0x8cc70208, 0x1a6439ec), - INIT(0x90befffa, 0x23631e28), INIT(0xa4506ceb, 0xde82bde9), - INIT(0xbef9a3f7, 0xb2c67915), INIT(0xc67178f2, 0xe372532b), - INIT(0xca273ece, 0xea26619c), INIT(0xd186b8c7, 0x21c0c207), - INIT(0xeada7dd6, 0xcde0eb1e), INIT(0xf57d4f7f, 0xee6ed178), - INIT(0x06f067aa, 0x72176fba), INIT(0x0a637dc5, 0xa2c898a6), - INIT(0x113f9804, 0xbef90dae), INIT(0x1b710b35, 0x131c471b), - INIT(0x28db77f5, 0x23047d84), INIT(0x32caab7b, 0x40c72493), - INIT(0x3c9ebe0a, 0x15c9bebc), INIT(0x431d67c4, 0x9c100d4c), - INIT(0x4cc5d4be, 0xcb3e42b6), INIT(0x597f299c, 0xfc657e2a), - INIT(0x5fcb6fab, 0x3ad6faec), INIT(0x6c44198c, 0x4a475817), + INIT(0x428a2f98, 0xd728ae22), INIT(0x71374491, 0x23ef65cd), + INIT(0xb5c0fbcf, 0xec4d3b2f), INIT(0xe9b5dba5, 0x8189dbbc), + INIT(0x3956c25b, 0xf348b538), INIT(0x59f111f1, 0xb605d019), + INIT(0x923f82a4, 0xaf194f9b), INIT(0xab1c5ed5, 0xda6d8118), + INIT(0xd807aa98, 0xa3030242), INIT(0x12835b01, 0x45706fbe), + INIT(0x243185be, 0x4ee4b28c), INIT(0x550c7dc3, 0xd5ffb4e2), + INIT(0x72be5d74, 0xf27b896f), INIT(0x80deb1fe, 0x3b1696b1), + INIT(0x9bdc06a7, 0x25c71235), INIT(0xc19bf174, 0xcf692694), + INIT(0xe49b69c1, 0x9ef14ad2), INIT(0xefbe4786, 0x384f25e3), + INIT(0x0fc19dc6, 0x8b8cd5b5), INIT(0x240ca1cc, 0x77ac9c65), + INIT(0x2de92c6f, 0x592b0275), INIT(0x4a7484aa, 0x6ea6e483), + INIT(0x5cb0a9dc, 0xbd41fbd4), INIT(0x76f988da, 0x831153b5), + INIT(0x983e5152, 0xee66dfab), INIT(0xa831c66d, 0x2db43210), + INIT(0xb00327c8, 0x98fb213f), INIT(0xbf597fc7, 0xbeef0ee4), + INIT(0xc6e00bf3, 0x3da88fc2), INIT(0xd5a79147, 0x930aa725), + INIT(0x06ca6351, 0xe003826f), INIT(0x14292967, 0x0a0e6e70), + INIT(0x27b70a85, 0x46d22ffc), INIT(0x2e1b2138, 0x5c26c926), + INIT(0x4d2c6dfc, 0x5ac42aed), INIT(0x53380d13, 0x9d95b3df), + INIT(0x650a7354, 0x8baf63de), INIT(0x766a0abb, 0x3c77b2a8), + INIT(0x81c2c92e, 0x47edaee6), INIT(0x92722c85, 0x1482353b), + INIT(0xa2bfe8a1, 0x4cf10364), INIT(0xa81a664b, 0xbc423001), + INIT(0xc24b8b70, 0xd0f89791), INIT(0xc76c51a3, 0x0654be30), + INIT(0xd192e819, 0xd6ef5218), INIT(0xd6990624, 0x5565a910), + INIT(0xf40e3585, 0x5771202a), INIT(0x106aa070, 0x32bbd1b8), + INIT(0x19a4c116, 0xb8d2d0c8), INIT(0x1e376c08, 0x5141ab53), + INIT(0x2748774c, 0xdf8eeb99), INIT(0x34b0bcb5, 0xe19b48a8), + INIT(0x391c0cb3, 0xc5c95a63), INIT(0x4ed8aa4a, 0xe3418acb), + INIT(0x5b9cca4f, 0x7763e373), INIT(0x682e6ff3, 0xd6b2b8a3), + INIT(0x748f82ee, 0x5defb2fc), INIT(0x78a5636f, 0x43172f60), + INIT(0x84c87814, 0xa1f0ab72), INIT(0x8cc70208, 0x1a6439ec), + INIT(0x90befffa, 0x23631e28), INIT(0xa4506ceb, 0xde82bde9), + INIT(0xbef9a3f7, 0xb2c67915), INIT(0xc67178f2, 0xe372532b), + INIT(0xca273ece, 0xea26619c), INIT(0xd186b8c7, 0x21c0c207), + INIT(0xeada7dd6, 0xcde0eb1e), INIT(0xf57d4f7f, 0xee6ed178), + INIT(0x06f067aa, 0x72176fba), INIT(0x0a637dc5, 0xa2c898a6), + INIT(0x113f9804, 0xbef90dae), INIT(0x1b710b35, 0x131c471b), + INIT(0x28db77f5, 0x23047d84), INIT(0x32caab7b, 0x40c72493), + INIT(0x3c9ebe0a, 0x15c9bebc), INIT(0x431d67c4, 0x9c100d4c), + INIT(0x4cc5d4be, 0xcb3e42b6), INIT(0x597f299c, 0xfc657e2a), + INIT(0x5fcb6fab, 0x3ad6faec), INIT(0x6c44198c, 0x4a475817), }; int t; @@ -136,12 +136,12 @@ static void SHA512_Block(SHA512_State *s, uint64_t *block) { w[t] = block[t]; for (t = 16; t < 80; t++) { - uint64_t p, q, r, tmp; - smallsigma1(p, tmp, w[t-2]); - smallsigma0(q, tmp, w[t-15]); - add(r, p, q); - add(p, r, w[t-7]); - add(w[t], p, w[t-16]); + uint64_t p, q, r, tmp; + smallsigma1(p, tmp, w[t-2]); + smallsigma0(q, tmp, w[t-15]); + add(r, p, q); + add(p, r, w[t-7]); + add(w[t], p, w[t-16]); } a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; @@ -151,36 +151,36 @@ static void SHA512_Block(SHA512_State *s, uint64_t *block) { uint64_t tmp, p, q, r; #define ROUND(j,a,b,c,d,e,f,g,h) \ - bigsigma1(p, tmp, e); \ - Ch(q, tmp, e, f, g); \ - add(r, p, q); \ - add(p, r, k[j]) ; \ - add(q, p, w[j]); \ - add(r, q, h); \ - bigsigma0(p, tmp, a); \ - Maj(tmp, q, a, b, c); \ - add(q, tmp, p); \ - add(p, r, d); \ - d = p; \ - add(h, q, r); + bigsigma1(p, tmp, e); \ + Ch(q, tmp, e, f, g); \ + add(r, p, q); \ + add(p, r, k[j]) ; \ + add(q, p, w[j]); \ + add(r, q, h); \ + bigsigma0(p, tmp, a); \ + Maj(tmp, q, a, b, c); \ + add(q, tmp, p); \ + add(p, r, d); \ + d = p; \ + add(h, q, r); - ROUND(t+0, a,b,c,d,e,f,g,h); - ROUND(t+1, h,a,b,c,d,e,f,g); - ROUND(t+2, g,h,a,b,c,d,e,f); - ROUND(t+3, f,g,h,a,b,c,d,e); - ROUND(t+4, e,f,g,h,a,b,c,d); - ROUND(t+5, d,e,f,g,h,a,b,c); - ROUND(t+6, c,d,e,f,g,h,a,b); - ROUND(t+7, b,c,d,e,f,g,h,a); + ROUND(t+0, a,b,c,d,e,f,g,h); + ROUND(t+1, h,a,b,c,d,e,f,g); + ROUND(t+2, g,h,a,b,c,d,e,f); + ROUND(t+3, f,g,h,a,b,c,d,e); + ROUND(t+4, e,f,g,h,a,b,c,d); + ROUND(t+5, d,e,f,g,h,a,b,c); + ROUND(t+6, c,d,e,f,g,h,a,b); + ROUND(t+7, b,c,d,e,f,g,h,a); } { - uint64_t tmp; + uint64_t tmp; #define UPDATE(state, local) ( tmp = state, add(state, tmp, local) ) - UPDATE(s->h[0], a); UPDATE(s->h[1], b); - UPDATE(s->h[2], c); UPDATE(s->h[3], d); - UPDATE(s->h[4], e); UPDATE(s->h[5], f); - UPDATE(s->h[6], g); UPDATE(s->h[7], h); + UPDATE(s->h[0], a); UPDATE(s->h[1], b); + UPDATE(s->h[2], c); UPDATE(s->h[3], d); + UPDATE(s->h[4], e); UPDATE(s->h[5], f); + UPDATE(s->h[6], g); UPDATE(s->h[7], h); } } diff --git a/sshsha.c b/sshsha.c index d2bd7c5f..0b8b58f5 100644 --- a/sshsha.c +++ b/sshsha.c @@ -1,6 +1,6 @@ /* * SHA-1 algorithm as described at - * + * * http://csrc.nist.gov/cryptval/shs.html */ @@ -206,7 +206,7 @@ static void sha1_sw_block(uint32_t *core, const uint8_t *block) w[t] = GET_32BIT_MSB_FIRST(block + 4*t); for (size_t t = 16; t < SHA1_ROUNDS; t++) - w[t] = rol(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1); + w[t] = rol(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1); a = core[0]; b = core[1]; c = core[2]; d = core[3]; e = core[4]; @@ -354,7 +354,7 @@ const ssh_hashalg ssh_sha1_sw = { static bool sha1_hw_available(void) { unsigned int CPUInfo[4]; - GET_CPU_ID_0(CPUInfo); + GET_CPU_ID_0(CPUInfo); if (CPUInfo[0] < 7) return false; diff --git a/sshshare.c b/sshshare.c index d2553e40..c70d5da1 100644 --- a/sshshare.c +++ b/sshshare.c @@ -344,12 +344,12 @@ static unsigned share_find_unused_id low = low_orig; high = high_orig = count234(sharestate->connections); while (high - low > 1) { - mid = (high + low) / 2; - cs = index234(sharestate->connections, mid); - if (cs->id == first + (mid - low_orig)) - low = mid; /* this one is still in the sequence */ - else - high = mid; /* this one is past the end */ + mid = (high + low) / 2; + cs = index234(sharestate->connections, mid); + if (cs->id == first + (mid - low_orig)) + low = mid; /* this one is still in the sequence */ + else + high = mid; /* this one is past the end */ } /* @@ -368,7 +368,7 @@ static unsigned share_find_unused_id { struct ssh_sharing_connstate dummy; dummy.id = ret; - assert(NULL == find234(sharestate->connections, &dummy, NULL)); + assert(NULL == find234(sharestate->connections, &dummy, NULL)); } return ret; } @@ -581,7 +581,7 @@ static struct share_channel *share_add_channel if (chan->state != UNACKNOWLEDGED) { if (add234(cs->channels_by_server, chan) != chan) { del234(cs->channels_by_us, chan); - sfree(chan); + sfree(chan); return NULL; } } @@ -938,7 +938,7 @@ static void share_disconnect(struct ssh_sharing_connstate *cs, } static void share_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { struct ssh_sharing_connstate *cs = container_of( plug, struct ssh_sharing_connstate, plug); @@ -1523,7 +1523,7 @@ static void share_got_pkt_from_downstream(struct ssh_sharing_connstate *cs, err = dupprintf("CHANNEL_OPEN_CONFIRMATION packet cited unknown channel %u", (unsigned)server_id); goto confused; } - + PUT_32BIT_MSB_FIRST(pkt + id_pos, new_id); chan = share_add_channel(cs, old_id, new_id, server_id, OPEN, maxpkt); @@ -1846,7 +1846,7 @@ static void share_sent(Plug *plug, size_t bufsize) } static void share_listen_closing(Plug *plug, const char *error_msg, - int error_code, bool calling_back) + int error_code, bool calling_back) { ssh_sharing_state *sharestate = container_of(plug, ssh_sharing_state, plug); @@ -1937,7 +1937,7 @@ static int share_listen_accepting(Plug *plug, cs->sock = constructor(ctx, &cs->plug); if ((err = sk_socket_error(cs->sock)) != NULL) { sfree(cs); - return err != NULL; + return err != NULL; } sk_set_frozen(cs->sock, 0); diff --git a/sshzlib.c b/sshzlib.c index d7a78c67..af559d68 100644 --- a/sshzlib.c +++ b/sshzlib.c @@ -1,18 +1,18 @@ /* * Zlib (RFC1950 / RFC1951) compression for PuTTY. - * + * * There will no doubt be criticism of my decision to reimplement * Zlib compression from scratch instead of using the existing zlib * code. People will cry `reinventing the wheel'; they'll claim * that the `fundamental basis of OSS' is code reuse; they'll want * to see a really good reason for me having chosen not to use the * existing code. - * + * * Well, here are my reasons. Firstly, I don't want to link the * whole of zlib into the PuTTY binary; PuTTY is justifiably proud * of its small size and I think zlib contains a lot of unnecessary * baggage for the kind of compression that SSH requires. - * + * * Secondly, I also don't like the alternative of using zlib.dll. * Another thing PuTTY is justifiably proud of is its ease of * installation, and the last thing I want to do is to start @@ -20,7 +20,7 @@ * zlib.dll kicking around, one with C calling conventions on the * exported functions and another with WINAPI conventions, and * there would be a significant danger of getting the wrong one. - * + * * Thirdly, there seems to be a difference of opinion on the IETF * secsh mailing list about the correct way to round off a * compressed packet and start the next. In particular, there's @@ -28,7 +28,7 @@ * capable of supporting (see below for an explanation). Given that * sort of uncertainty, I thought it might be better to have code * that will support even the zlib-incompatible worst case. - * + * * Fourthly, it's a _second implementation_. Second implementations * are fundamentally a Good Thing in standardisation efforts. The * difference of opinion mentioned above has arisen _precisely_ @@ -71,15 +71,15 @@ static int lz77_init(struct LZ77Context *ctx); * instead call literal() for everything. */ static void lz77_compress(struct LZ77Context *ctx, - const unsigned char *data, int len); + const unsigned char *data, int len); /* * Modifiable parameters. */ -#define WINSIZE 32768 /* window size. Must be power of 2! */ -#define HASHMAX 2039 /* one more than max hash value */ -#define MAXMATCH 32 /* how many matches we track */ -#define HASHCHARS 3 /* how many chars make a hash */ +#define WINSIZE 32768 /* window size. Must be power of 2! */ +#define HASHMAX 2039 /* one more than max hash value */ +#define MAXMATCH 32 /* how many matches we track */ +#define HASHCHARS 3 /* how many chars make a hash */ /* * This compressor takes a less slapdash approach than the @@ -90,14 +90,14 @@ static void lz77_compress(struct LZ77Context *ctx, * byte), we can carefully remove the hash chain entry. */ -#define INVALID -1 /* invalid hash _and_ invalid offset */ +#define INVALID -1 /* invalid hash _and_ invalid offset */ struct WindowEntry { - short next, prev; /* array indices within the window */ + short next, prev; /* array indices within the window */ short hashval; }; struct HashEntry { - short first; /* window index of first in chain */ + short first; /* window index of first in chain */ }; struct Match { @@ -125,14 +125,14 @@ static int lz77_init(struct LZ77Context *ctx) st = snew(struct LZ77InternalContext); if (!st) - return 0; + return 0; ctx->ictx = st; for (i = 0; i < WINSIZE; i++) - st->win[i].next = st->win[i].prev = st->win[i].hashval = INVALID; + st->win[i].next = st->win[i].prev = st->win[i].hashval = INVALID; for (i = 0; i < HASHMAX; i++) - st->hashtab[i].first = INVALID; + st->hashtab[i].first = INVALID; st->winpos = 0; st->npending = 0; @@ -141,7 +141,7 @@ 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; @@ -150,9 +150,9 @@ static void lz77_advance(struct LZ77InternalContext *st, * or empty the chain if it's the only thing on the chain. */ if (st->win[st->winpos].prev != INVALID) { - st->win[st->win[st->winpos].prev].next = INVALID; + st->win[st->win[st->winpos].prev].next = INVALID; } else if (st->win[st->winpos].hashval != INVALID) { - st->hashtab[st->win[st->winpos].hashval].first = INVALID; + st->hashtab[st->win[st->winpos].hashval].first = INVALID; } /* @@ -164,7 +164,7 @@ static void lz77_advance(struct LZ77InternalContext *st, off = st->win[st->winpos].next = st->hashtab[hash].first; st->hashtab[hash].first = st->winpos; if (off != INVALID) - st->win[off].prev = st->winpos; + st->win[off].prev = st->winpos; st->data[st->winpos] = c; /* @@ -176,7 +176,7 @@ static void lz77_advance(struct LZ77InternalContext *st, #define CHARAT(k) ( (k)<0 ? st->data[(st->winpos+k)&(WINSIZE-1)] : data[k] ) static void lz77_compress(struct LZ77Context *ctx, - const unsigned char *data, int len) + const unsigned char *data, int len) { struct LZ77InternalContext *st = ctx->ictx; int i, distance, off, nmatch, matchlen, advance; @@ -195,18 +195,18 @@ static void lz77_compress(struct LZ77Context *ctx, * HASHCHARS in size. */ for (i = 0; i < st->npending; i++) { - unsigned char foo[HASHCHARS]; - int j; - if (len + st->npending - i < HASHCHARS) { - /* Update the pending array. */ - for (j = i; j < st->npending; 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] : - data[i + j - st->npending]); - lz77_advance(st, foo[0], lz77_hash(foo)); + unsigned char foo[HASHCHARS]; + int j; + if (len + st->npending - i < HASHCHARS) { + /* Update the pending array. */ + for (j = i; j < st->npending; 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] : + data[i + j - st->npending]); + lz77_advance(st, foo[0], lz77_hash(foo)); } st->npending -= i; @@ -215,115 +215,115 @@ static void lz77_compress(struct LZ77Context *ctx, deferchr = '\0'; while (len > 0) { - if (len >= HASHCHARS) { - /* - * Hash the next few characters. - */ - int hash = lz77_hash(data); + if (len >= HASHCHARS) { + /* + * Hash the next few characters. + */ + int 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; - } + /* + * 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; + } - if (nmatch > 0) { - /* - * We've now filled up matches[] with nmatch potential - * matches. Follow them down to find the longest. (We - * assume here that it's always worth favouring a - * longer match over a shorter one.) - */ - matchlen = HASHCHARS; - while (matchlen < len) { - int j; - for (i = j = 0; i < nmatch; i++) { - if (CHARAT(matchlen) == - CHARAT(matchlen - matches[i].distance)) { - matches[j++] = matches[i]; - } - } - if (j == 0) - break; - matchlen++; - nmatch = j; - } + if (nmatch > 0) { + /* + * We've now filled up matches[] with nmatch potential + * matches. Follow them down to find the longest. (We + * assume here that it's always worth favouring a + * longer match over a shorter one.) + */ + matchlen = HASHCHARS; + while (matchlen < len) { + int j; + for (i = j = 0; i < nmatch; i++) { + if (CHARAT(matchlen) == + CHARAT(matchlen - matches[i].distance)) { + matches[j++] = matches[i]; + } + } + if (j == 0) + break; + matchlen++; + nmatch = j; + } - /* - * We've now got all the longest matches. We favour the - * shorter distances, which means we go with matches[0]. - * So see if we want to defer it or throw it away. - */ - matches[0].len = matchlen; - if (defermatch.len > 0) { - 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); - defermatch = matches[0]; - deferchr = data[0]; - advance = 1; - } else { - /* We don't have a better match. Do the deferred one. */ - ctx->match(ctx, defermatch.distance, defermatch.len); - advance = defermatch.len - 1; - defermatch.len = 0; - } - } else { - /* There was no deferred match. Defer this one. */ - defermatch = matches[0]; - deferchr = data[0]; - advance = 1; - } - } else { - /* - * We found no matches. Emit the deferred match, if - * any; otherwise emit a literal. - */ - if (defermatch.len > 0) { - ctx->match(ctx, defermatch.distance, defermatch.len); - advance = defermatch.len - 1; - defermatch.len = 0; - } else { - ctx->literal(ctx, data[0]); - advance = 1; - } - } + /* + * We've now got all the longest matches. We favour the + * shorter distances, which means we go with matches[0]. + * So see if we want to defer it or throw it away. + */ + matches[0].len = matchlen; + if (defermatch.len > 0) { + 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); + defermatch = matches[0]; + deferchr = data[0]; + advance = 1; + } else { + /* We don't have a better match. Do the deferred one. */ + ctx->match(ctx, defermatch.distance, defermatch.len); + advance = defermatch.len - 1; + defermatch.len = 0; + } + } else { + /* There was no deferred match. Defer this one. */ + defermatch = matches[0]; + deferchr = data[0]; + advance = 1; + } + } else { + /* + * We found no matches. Emit the deferred match, if + * any; otherwise emit a literal. + */ + if (defermatch.len > 0) { + ctx->match(ctx, defermatch.distance, defermatch.len); + advance = defermatch.len - 1; + defermatch.len = 0; + } else { + ctx->literal(ctx, data[0]); + advance = 1; + } + } - /* - * Now advance the position by `advance' characters, - * keeping the window and hash chains consistent. - */ - while (advance > 0) { - if (len >= HASHCHARS) { - lz77_advance(st, *data, lz77_hash(data)); - } else { + /* + * Now advance the position by `advance' characters, + * keeping the window and hash chains consistent. + */ + while (advance > 0) { + if (len >= HASHCHARS) { + lz77_advance(st, *data, lz77_hash(data)); + } else { assert(st->npending < HASHCHARS); - st->pending[st->npending++] = *data; - } - data++; - len--; - advance--; - } + st->pending[st->npending++] = *data; + } + data++; + len--; + advance--; + } } } @@ -334,7 +334,7 @@ static void lz77_compress(struct LZ77Context *ctx, * compressing a large file under no significant time constraint, * but when you're compressing little bits in real time, things get * hairier. - * + * * I suppose it's possible that I could compute Huffman trees based * on the frequencies in the _previous_ block, as a sort of * heuristic, but I'm not confident that the gain would balance out @@ -355,8 +355,8 @@ static void outbits(struct Outbuf *out, unsigned long bits, int nbits) out->noutbits += nbits; while (out->noutbits >= 8) { put_byte(out->outbuf, out->outbits & 0xFF); - out->outbits >>= 8; - out->noutbits -= 8; + out->outbits >>= 8; + out->noutbits -= 8; } } @@ -470,11 +470,11 @@ static void zlib_literal(struct LZ77Context *ectx, unsigned char c) struct Outbuf *out = (struct Outbuf *) ectx->userdata; 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); } } @@ -485,86 +485,86 @@ static void zlib_match(struct LZ77Context *ectx, int distance, int len) struct Outbuf *out = (struct Outbuf *) ectx->userdata; 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 - * several steps, with 258 or less in each step. - * - * Specifically: if len >= 261, we can transmit 258 and be - * sure of having at least 3 left for the next step. And if - * 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; + /* + * We can transmit matches of lengths 3 through 258 + * inclusive. So if len exceeds 258, we must transmit in + * several steps, with 258 or less in each step. + * + * Specifically: if len >= 261, we can transmit 258 and be + * sure of having at least 3 left for the next step. And if + * 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 = lenof(lencodes); - while (1) { - assert(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! */ - } - } + /* + * Binary-search to find which length code we're + * transmitting. + */ + i = -1; + j = lenof(lencodes); + while (1) { + assert(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 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); + /* + * 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 = lenof(distcodes); - while (1) { - assert(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! */ - } - } + /* + * Binary-search to find which distance code we're + * transmitting. + */ + i = -1; + j = lenof(distcodes); + while (1) { + assert(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 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); + /* + * Transmit the extra bits. + */ + if (d->extrabits) + outbits(out, distance - d->min, d->extrabits); } } @@ -623,12 +623,12 @@ void zlib_compress_block(ssh_compressor *sc, * algorithm.) */ if (out->firstblock) { - outbits(out, 0x9C78, 16); - out->firstblock = false; + outbits(out, 0x9C78, 16); + out->firstblock = false; - in_block = false; + in_block = false; } else - in_block = true; + in_block = true; if (!in_block) { /* @@ -668,9 +668,9 @@ void zlib_compress_block(ssh_compressor *sc, * * For the moment, we will use Zlib partial flush. */ - outbits(out, 0, 7); /* close block */ + outbits(out, 0, 7); /* close block */ outbits(out, 2, 3 + 7); /* empty static block */ - outbits(out, 2, 3); /* open new block */ + outbits(out, 2, 3); /* open new block */ /* * If we've been asked to pad out the compressed data until it's @@ -678,8 +678,8 @@ void zlib_compress_block(ssh_compressor *sc, * blocks. */ while (out->outbuf->len < minlen) { - outbits(out, 0, 7); /* close block */ - outbits(out, 2, 3); /* open new static block */ + outbits(out, 0, 7); /* close block */ + outbits(out, 2, 3); /* open new static block */ } *outlen = out->outbuf->len; @@ -710,7 +710,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; }; @@ -723,8 +723,8 @@ 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 = snew(struct zlib_table); int pfxmask = (1 << pfxbits) - 1; @@ -734,34 +734,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; @@ -771,7 +771,7 @@ 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) + int nlengths) { int count[MAXCODELEN], startcode[MAXCODELEN], codes[MAXSYMS]; int code, maxlen; @@ -780,27 +780,27 @@ static struct zlib_table *zlib_mktable(unsigned char *lengths, /* Count the codes of each length. */ maxlen = 0; for (i = 1; i < MAXCODELEN; i++) - count[i] = 0; + 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; + } } /* @@ -808,7 +808,7 @@ static struct zlib_table *zlib_mktable(unsigned char *lengths, * 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) @@ -817,16 +817,16 @@ static int zlib_freetable(struct zlib_table **ztab) int code; if (ztab == NULL) - return -1; + return -1; if (*ztab == NULL) - return 0; + return 0; tab = *ztab; for (code = 0; code <= tab->mask; code++) - if (tab->table[code].nexttable != NULL) - zlib_freetable(&tab->table[code].nexttable); + if (tab->table[code].nexttable != NULL) + zlib_freetable(&tab->table[code].nexttable); sfree(tab->table); tab->table = NULL; @@ -841,13 +841,13 @@ 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; + lenrep; int uncomplen; unsigned char lenlen[19]; @@ -916,7 +916,7 @@ ssh_decompressor *zlib_decompress_init(void) 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; @@ -933,11 +933,11 @@ void zlib_decompress_cleanup(ssh_decompressor *dc) container_of(dc, struct zlib_decompress_ctx, dc); if (dctx->currlentable && dctx->currlentable != dctx->staticlentable) - zlib_freetable(&dctx->currlentable); + zlib_freetable(&dctx->currlentable); if (dctx->currdisttable && dctx->currdisttable != dctx->staticdisttable) - zlib_freetable(&dctx->currdisttable); + zlib_freetable(&dctx->currdisttable); if (dctx->lenlentable) - zlib_freetable(&dctx->lenlentable); + zlib_freetable(&dctx->lenlentable); zlib_freetable(&dctx->staticlentable); zlib_freetable(&dctx->staticdisttable); if (dctx->outblk) @@ -946,34 +946,34 @@ void zlib_decompress_cleanup(ssh_decompressor *dc) } static int zlib_huflookup(unsigned long *bitsp, int *nbitsp, - struct zlib_table *tab) + 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; + } - if (!tab) { - /* - * There was a missing entry in the table, presumably - * due to an invalid Huffman table description, and the - * subsequent data has attempted to use the missing - * entry. Return a decoding failure. - */ - return -2; - } + if (!tab) { + /* + * There was a missing entry in the table, presumably + * due to an invalid Huffman table description, and the + * subsequent data has attempted to use the missing + * entry. Return a decoding failure. + */ + return -2; + } } } @@ -995,23 +995,23 @@ bool zlib_decompress_block(ssh_decompressor *dc, const coderecord *rec; int code, blktype, rep, dist, nlen, header; 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 }; assert(!dctx->outblk); dctx->outblk = strbuf_new_nm(); 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. */ - if (dctx->nbits < 16) - goto finished; /* done all we can */ + 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. */ + if (dctx->nbits < 16) + goto finished; /* done all we can */ /* * The header is stored as a big-endian 16-bit integer, @@ -1038,194 +1038,194 @@ bool zlib_decompress_block(ssh_decompressor *dc, (header % 31) != 0) goto decode_error; - 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; - 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); - zlib_freetable(&dctx->lenlentable); - dctx->lenlentable = NULL; - dctx->state = INBLK; - break; - } - code = - zlib_huflookup(&dctx->bits, &dctx->nbits, dctx->lenlentable); - if (code == -1) - goto finished; - if (code == -2) - goto decode_error; - 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 == -2) - goto decode_error; - if (code < 256) - zlib_emit_char(dctx, code); - else if (code == 256) { - dctx->state = OUTSIDEBLK; - if (dctx->currlentable != dctx->staticlentable) { - zlib_freetable(&dctx->currlentable); - dctx->currlentable = NULL; - } - if (dctx->currdisttable != dctx->staticdisttable) { - zlib_freetable(&dctx->currdisttable); - dctx->currdisttable = NULL; - } - } else if (code < 286) { - dctx->state = GOTLENSYM; - dctx->sym = code; - } else { + 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; + 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); + zlib_freetable(&dctx->lenlentable); + dctx->lenlentable = NULL; + dctx->state = INBLK; + break; + } + code = + zlib_huflookup(&dctx->bits, &dctx->nbits, dctx->lenlentable); + if (code == -1) + goto finished; + if (code == -2) + goto decode_error; + 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 == -2) + goto decode_error; + if (code < 256) + zlib_emit_char(dctx, code); + else if (code == 256) { + dctx->state = OUTSIDEBLK; + if (dctx->currlentable != dctx->staticlentable) { + zlib_freetable(&dctx->currlentable); + dctx->currlentable = NULL; + } + if (dctx->currdisttable != dctx->staticdisttable) { + zlib_freetable(&dctx->currdisttable); + dctx->currdisttable = NULL; + } + } else if (code < 286) { + dctx->state = GOTLENSYM; + dctx->sym = code; + } else { /* literal/length symbols 286 and 287 are invalid */ goto decode_error; } - 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; - if (code == -2) - goto decode_error; - if (code >= 30) /* dist symbols 30 and 31 are invalid */ - goto decode_error; - 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, dctx->window[(dctx->winpos - dist) & - (WINSIZE - 1)]); - break; - case UNCOMP_LEN: - /* - * Uncompressed block. We expect to see a 16-bit LEN. - */ - if (dctx->nbits < 16) - goto finished; - dctx->uncomplen = dctx->bits & 0xFFFF; - EATBITS(16); - dctx->state = UNCOMP_NLEN; - break; - case UNCOMP_NLEN: - /* - * Uncompressed block. We expect to see a 16-bit NLEN, - * which should be the one's complement of the previous - * LEN. - */ - if (dctx->nbits < 16) - goto finished; - nlen = dctx->bits & 0xFFFF; - EATBITS(16); - if (dctx->uncomplen != (nlen ^ 0xFFFF)) - goto decode_error; - if (dctx->uncomplen == 0) - dctx->state = OUTSIDEBLK; /* block is empty */ - else - dctx->state = UNCOMP_DATA; - break; - case UNCOMP_DATA: - if (dctx->nbits < 8) - goto finished; - zlib_emit_char(dctx, dctx->bits & 0xFF); - EATBITS(8); - if (--dctx->uncomplen == 0) - dctx->state = OUTSIDEBLK; /* end of uncompressed block */ - break; - } + 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; + if (code == -2) + goto decode_error; + if (code >= 30) /* dist symbols 30 and 31 are invalid */ + goto decode_error; + 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, dctx->window[(dctx->winpos - dist) & + (WINSIZE - 1)]); + break; + case UNCOMP_LEN: + /* + * Uncompressed block. We expect to see a 16-bit LEN. + */ + if (dctx->nbits < 16) + goto finished; + dctx->uncomplen = dctx->bits & 0xFFFF; + EATBITS(16); + dctx->state = UNCOMP_NLEN; + break; + case UNCOMP_NLEN: + /* + * Uncompressed block. We expect to see a 16-bit NLEN, + * which should be the one's complement of the previous + * LEN. + */ + if (dctx->nbits < 16) + goto finished; + nlen = dctx->bits & 0xFFFF; + EATBITS(16); + if (dctx->uncomplen != (nlen ^ 0xFFFF)) + goto decode_error; + if (dctx->uncomplen == 0) + dctx->state = OUTSIDEBLK; /* block is empty */ + else + dctx->state = UNCOMP_DATA; + break; + case UNCOMP_DATA: + if (dctx->nbits < 8) + goto finished; + zlib_emit_char(dctx, dctx->bits & 0xFF); + EATBITS(8); + if (--dctx->uncomplen == 0) + dctx->state = OUTSIDEBLK; /* end of uncompressed block */ + break; + } } finished: diff --git a/storage.h b/storage.h index 41e4b5c9..6464b69d 100644 --- a/storage.h +++ b/storage.h @@ -25,7 +25,7 @@ * A given key will be written at most once while saving a session. * Keys may be up to 255 characters long. String values have no length * limit. - * + * * Any returned error message must be freed after use. */ settings_w *open_settings_w(const char *sessionname, char **errmsg); @@ -42,12 +42,12 @@ void close_settings_w(settings_w *handle); * open_setting_r() to get a `void *' handle, then pass that to a * number of calls to read_setting_s() and read_setting_i(), and * then close it using close_settings_r(). - * + * * read_setting_s() returns a dynamically allocated string which the * caller must free. read_setting_filename() and * read_setting_fontspec() likewise return dynamically allocated * structures. - * + * * If a particular string setting is not present in the session, * read_setting_s() can return NULL, in which case the caller * should invent a sensible default. If an integer setting is not @@ -82,14 +82,14 @@ void enum_settings_finish(settings_e *handle); * or 2 (entry exists in database and is different). */ int verify_host_key(const char *hostname, int port, - const char *keytype, const char *key); + const char *keytype, const char *key); /* * Write a host key into the database, overwriting any previous * entry that might have been there. */ void store_host_key(const char *hostname, int port, - const char *keytype, const char *key); + const char *keytype, const char *key); /* ---------------------------------------------------------------------- * Functions to access PuTTY's random number seed file. diff --git a/telnet.c b/telnet.c index e5996953..034de3a6 100644 --- a/telnet.c +++ b/telnet.c @@ -8,27 +8,27 @@ #include "putty.h" -#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 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 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 TELOPTS(X) \ X(BINARY, 0) /* 8-bit data path */ \ @@ -90,9 +90,9 @@ enum { TELOPTS(telnet_enum) dummy=0 }; #undef telnet_enum -#define TELQUAL_IS 0 /* option is... */ -#define TELQUAL_SEND 1 /* send option */ -#define TELQUAL_INFO 2 /* ENVIRON: informational version of IS */ +#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 @@ -103,28 +103,28 @@ enum { TELOPTS(telnet_enum) dummy=0 }; #define NUL 0 #define iswritable(x) \ - ( (x) != IAC && \ - (telnet->opt_states[o_we_bin.index] == ACTIVE || (x) != CR)) + ( (x) != IAC && \ + (telnet->opt_states[o_we_bin.index] == ACTIVE || (x) != CR)) static const char *telopt(int opt) { #define telnet_str(x,y) case TELOPT_##x: return #x; switch (opt) { - TELOPTS(telnet_str) + TELOPTS(telnet_str) default: - return ""; + return ""; } #undef telnet_str } struct Opt { - int send; /* what we initially send */ - int nsend; /* -ve send if requested to stop it */ - int ack, nak; /* +ve and -ve acknowledgements */ - int option; /* the option code */ - int index; /* index into telnet->opt_states[] */ + int send; /* what we initially send */ + int nsend; /* -ve send if requested to stop it */ + int ack, nak; /* +ve and -ve acknowledgements */ + int option; /* the option code */ + int index; /* index into telnet->opt_states[] */ enum { - REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE + REQUESTED, ACTIVE, INACTIVE, REALLY_INACTIVE } initial_state; }; @@ -189,8 +189,8 @@ struct Telnet { bool session_started; enum { - TOP_LEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT, - SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR + TOP_LEVEL, SEENIAC, SEENWILL, SEENWONT, SEENDO, SEENDONT, + SEENSB, SUBNEGOT, SUBNEG_IAC, SEENCR } state; Conf *conf; @@ -238,8 +238,8 @@ static void send_opt(Telnet *telnet, int cmd, int option) static void deactivate_option(Telnet *telnet, const struct Opt *o) { if (telnet->opt_states[o->index] == REQUESTED || - telnet->opt_states[o->index] == ACTIVE) - send_opt(telnet, o->nsend, o->option); + telnet->opt_states[o->index] == ACTIVE) + send_opt(telnet, o->nsend, o->option); telnet->opt_states[o->index] = REALLY_INACTIVE; } @@ -250,27 +250,27 @@ static void option_side_effects( Telnet *telnet, const struct Opt *o, bool enabled) { if (o->option == TELOPT_ECHO && o->send == DO) - telnet->echoing = !enabled; + telnet->echoing = !enabled; else if (o->option == TELOPT_SGA && o->send == DO) - telnet->editing = !enabled; - if (telnet->ldisc) /* cause ldisc to notice the change */ - ldisc_echoedit_update(telnet->ldisc); + telnet->editing = !enabled; + if (telnet->ldisc) /* cause ldisc to notice the change */ + ldisc_echoedit_update(telnet->ldisc); /* Ensure we get the minimum options */ if (!telnet->activated) { - if (telnet->opt_states[o_echo.index] == INACTIVE) { - telnet->opt_states[o_echo.index] = REQUESTED; - send_opt(telnet, o_echo.send, o_echo.option); - } - if (telnet->opt_states[o_we_sga.index] == INACTIVE) { - telnet->opt_states[o_we_sga.index] = REQUESTED; - send_opt(telnet, o_we_sga.send, o_we_sga.option); - } - if (telnet->opt_states[o_they_sga.index] == INACTIVE) { - telnet->opt_states[o_they_sga.index] = REQUESTED; - send_opt(telnet, o_they_sga.send, o_they_sga.option); - } - telnet->activated = true; + if (telnet->opt_states[o_echo.index] == INACTIVE) { + telnet->opt_states[o_echo.index] = REQUESTED; + send_opt(telnet, o_echo.send, o_echo.option); + } + if (telnet->opt_states[o_we_sga.index] == INACTIVE) { + telnet->opt_states[o_we_sga.index] = REQUESTED; + send_opt(telnet, o_we_sga.send, o_we_sga.option); + } + if (telnet->opt_states[o_they_sga.index] == INACTIVE) { + telnet->opt_states[o_they_sga.index] = REQUESTED; + send_opt(telnet, o_they_sga.send, o_they_sga.option); + } + telnet->activated = true; } } @@ -280,14 +280,14 @@ static void activate_option(Telnet *telnet, const struct Opt *o) backend_size(&telnet->backend, telnet->term_width, telnet->term_height); if (o->send == WILL && - (o->option == TELOPT_NEW_ENVIRON || - o->option == TELOPT_OLD_ENVIRON)) { - /* - * We may only have one kind of ENVIRON going at a time. - * This is a hack, but who cares. - */ - deactivate_option(telnet, o->option == - TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv); + (o->option == TELOPT_NEW_ENVIRON || + o->option == TELOPT_OLD_ENVIRON)) { + /* + * We may only have one kind of ENVIRON going at a time. + * This is a hack, but who cares. + */ + deactivate_option(telnet, o->option == + TELOPT_NEW_ENVIRON ? &o_oenv : &o_nenv); } option_side_effects(telnet, o, true); } @@ -295,9 +295,9 @@ static void activate_option(Telnet *telnet, const struct Opt *o) static void refused_option(Telnet *telnet, const struct Opt *o) { if (o->send == WILL && o->option == TELOPT_NEW_ENVIRON && - telnet->opt_states[o_oenv.index] == INACTIVE) { - send_opt(telnet, WILL, TELOPT_OLD_ENVIRON); - telnet->opt_states[o_oenv.index] = REQUESTED; + telnet->opt_states[o_oenv.index] == INACTIVE) { + send_opt(telnet, WILL, TELOPT_OLD_ENVIRON); + telnet->opt_states[o_oenv.index] = REQUESTED; } option_side_effects(telnet, o, false); } @@ -308,41 +308,41 @@ static void proc_rec_opt(Telnet *telnet, int cmd, int option) log_option(telnet, "server", cmd, option); for (o = opts; *o; o++) { - if ((*o)->option == option && (*o)->ack == cmd) { - switch (telnet->opt_states[(*o)->index]) { - case REQUESTED: - telnet->opt_states[(*o)->index] = ACTIVE; - activate_option(telnet, *o); - break; - case ACTIVE: - break; - case INACTIVE: - telnet->opt_states[(*o)->index] = ACTIVE; - send_opt(telnet, (*o)->send, option); - activate_option(telnet, *o); - break; - case REALLY_INACTIVE: - send_opt(telnet, (*o)->nsend, option); - break; - } - return; - } else if ((*o)->option == option && (*o)->nak == cmd) { - switch (telnet->opt_states[(*o)->index]) { - case REQUESTED: - telnet->opt_states[(*o)->index] = INACTIVE; - refused_option(telnet, *o); - break; - case ACTIVE: - telnet->opt_states[(*o)->index] = INACTIVE; - send_opt(telnet, (*o)->nsend, option); - option_side_effects(telnet, *o, false); - break; - case INACTIVE: - case REALLY_INACTIVE: - break; - } - return; - } + if ((*o)->option == option && (*o)->ack == cmd) { + switch (telnet->opt_states[(*o)->index]) { + case REQUESTED: + telnet->opt_states[(*o)->index] = ACTIVE; + activate_option(telnet, *o); + break; + case ACTIVE: + break; + case INACTIVE: + telnet->opt_states[(*o)->index] = ACTIVE; + send_opt(telnet, (*o)->send, option); + activate_option(telnet, *o); + break; + case REALLY_INACTIVE: + send_opt(telnet, (*o)->nsend, option); + break; + } + return; + } else if ((*o)->option == option && (*o)->nak == cmd) { + switch (telnet->opt_states[(*o)->index]) { + case REQUESTED: + telnet->opt_states[(*o)->index] = INACTIVE; + refused_option(telnet, *o); + break; + case ACTIVE: + telnet->opt_states[(*o)->index] = INACTIVE; + send_opt(telnet, (*o)->nsend, option); + option_side_effects(telnet, *o, false); + break; + case INACTIVE: + case REALLY_INACTIVE: + break; + } + return; + } } /* * If we reach here, the option was one we weren't prepared to @@ -362,145 +362,145 @@ static void process_subneg(Telnet *telnet) switch (telnet->sb_opt) { case TELOPT_TSPEED: - if (telnet->sb_buf->len == 1 && telnet->sb_buf->u[0] == TELQUAL_SEND) { - char *termspeed = conf_get_str(telnet->conf, CONF_termspeed); - b = snewn(20 + strlen(termspeed), unsigned char); - b[0] = IAC; - b[1] = SB; - b[2] = TELOPT_TSPEED; - b[3] = TELQUAL_IS; - strcpy((char *)(b + 4), termspeed); - n = 4 + strlen(termspeed); - b[n] = IAC; - b[n + 1] = SE; - telnet->bufsize = sk_write(telnet->s, b, n + 2); + if (telnet->sb_buf->len == 1 && telnet->sb_buf->u[0] == TELQUAL_SEND) { + char *termspeed = conf_get_str(telnet->conf, CONF_termspeed); + b = snewn(20 + strlen(termspeed), unsigned char); + b[0] = IAC; + b[1] = SB; + b[2] = TELOPT_TSPEED; + b[3] = TELQUAL_IS; + strcpy((char *)(b + 4), termspeed); + n = 4 + strlen(termspeed); + b[n] = IAC; + b[n + 1] = SE; + telnet->bufsize = sk_write(telnet->s, b, n + 2); logevent(telnet->logctx, "server:\tSB TSPEED SEND"); logeventf(telnet->logctx, "client:\tSB TSPEED IS %s", termspeed); - sfree(b); - } else + sfree(b); + } else logevent(telnet->logctx, "server:\tSB TSPEED "); - break; + break; case TELOPT_TTYPE: - if (telnet->sb_buf->len == 1 && telnet->sb_buf->u[0] == TELQUAL_SEND) { - char *termtype = conf_get_str(telnet->conf, CONF_termtype); - b = snewn(20 + strlen(termtype), unsigned char); - b[0] = IAC; - b[1] = SB; - b[2] = TELOPT_TTYPE; - b[3] = TELQUAL_IS; - for (n = 0; termtype[n]; n++) - b[n + 4] = (termtype[n] >= 'a' && termtype[n] <= 'z' ? - termtype[n] + 'A' - 'a' : - termtype[n]); - b[n + 4] = IAC; - b[n + 5] = SE; - telnet->bufsize = sk_write(telnet->s, b, n + 6); - b[n + 4] = 0; + if (telnet->sb_buf->len == 1 && telnet->sb_buf->u[0] == TELQUAL_SEND) { + char *termtype = conf_get_str(telnet->conf, CONF_termtype); + b = snewn(20 + strlen(termtype), unsigned char); + b[0] = IAC; + b[1] = SB; + b[2] = TELOPT_TTYPE; + b[3] = TELQUAL_IS; + for (n = 0; termtype[n]; n++) + b[n + 4] = (termtype[n] >= 'a' && termtype[n] <= 'z' ? + termtype[n] + 'A' - 'a' : + termtype[n]); + b[n + 4] = IAC; + b[n + 5] = SE; + telnet->bufsize = sk_write(telnet->s, b, n + 6); + b[n + 4] = 0; logevent(telnet->logctx, "server:\tSB TTYPE SEND"); logeventf(telnet->logctx, "client:\tSB TTYPE IS %s", b + 4); - sfree(b); - } else + sfree(b); + } else logevent(telnet->logctx, "server:\tSB TTYPE \r\n"); - break; + break; case TELOPT_OLD_ENVIRON: case TELOPT_NEW_ENVIRON: - p = telnet->sb_buf->u; - q = p + telnet->sb_buf->len; - if (p < q && *p == TELQUAL_SEND) { - p++; + p = telnet->sb_buf->u; + q = p + telnet->sb_buf->len; + if (p < q && *p == TELQUAL_SEND) { + p++; logeventf(telnet->logctx, "server:\tSB %s SEND", telopt(telnet->sb_opt)); - if (telnet->sb_opt == TELOPT_OLD_ENVIRON) { - if (conf_get_bool(telnet->conf, CONF_rfc_environ)) { - value = RFC_VALUE; - var = RFC_VAR; - } else { - value = BSD_VALUE; - var = BSD_VAR; - } - /* - * Try to guess the sense of VAR and VALUE. - */ - while (p < q) { - if (*p == RFC_VAR) { - value = RFC_VALUE; - var = RFC_VAR; - } else if (*p == BSD_VAR) { - value = BSD_VALUE; - var = BSD_VAR; - } - p++; - } - } else { - /* - * With NEW_ENVIRON, the sense of VAR and VALUE - * isn't in doubt. - */ - value = RFC_VALUE; - var = RFC_VAR; - } - bsize = 20; - for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, - NULL, &ekey); - eval != NULL; - eval = conf_get_str_strs(telnet->conf, CONF_environmt, - ekey, &ekey)) - bsize += strlen(ekey) + strlen(eval) + 2; - user = get_remote_username(telnet->conf); - if (user) - bsize += 6 + strlen(user); + if (telnet->sb_opt == TELOPT_OLD_ENVIRON) { + if (conf_get_bool(telnet->conf, CONF_rfc_environ)) { + value = RFC_VALUE; + var = RFC_VAR; + } else { + value = BSD_VALUE; + var = BSD_VAR; + } + /* + * Try to guess the sense of VAR and VALUE. + */ + while (p < q) { + if (*p == RFC_VAR) { + value = RFC_VALUE; + var = RFC_VAR; + } else if (*p == BSD_VAR) { + value = BSD_VALUE; + var = BSD_VAR; + } + p++; + } + } else { + /* + * With NEW_ENVIRON, the sense of VAR and VALUE + * isn't in doubt. + */ + value = RFC_VALUE; + var = RFC_VAR; + } + bsize = 20; + for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, + NULL, &ekey); + eval != NULL; + eval = conf_get_str_strs(telnet->conf, CONF_environmt, + ekey, &ekey)) + bsize += strlen(ekey) + strlen(eval) + 2; + user = get_remote_username(telnet->conf); + if (user) + bsize += 6 + strlen(user); - b = snewn(bsize, unsigned char); - b[0] = IAC; - b[1] = SB; - b[2] = telnet->sb_opt; - b[3] = TELQUAL_IS; - n = 4; - for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, - NULL, &ekey); - eval != NULL; - eval = conf_get_str_strs(telnet->conf, CONF_environmt, - ekey, &ekey)) { - b[n++] = var; - for (e = ekey; *e; e++) - b[n++] = *e; - b[n++] = value; - for (e = eval; *e; e++) - b[n++] = *e; - } - if (user) { - b[n++] = var; - b[n++] = 'U'; - b[n++] = 'S'; - b[n++] = 'E'; - b[n++] = 'R'; - b[n++] = value; - for (e = user; *e; e++) - b[n++] = *e; - } - b[n++] = IAC; - b[n++] = SE; - telnet->bufsize = sk_write(telnet->s, b, n); - if (n == 6) { + b = snewn(bsize, unsigned char); + b[0] = IAC; + b[1] = SB; + b[2] = telnet->sb_opt; + b[3] = TELQUAL_IS; + n = 4; + for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, + NULL, &ekey); + eval != NULL; + eval = conf_get_str_strs(telnet->conf, CONF_environmt, + ekey, &ekey)) { + b[n++] = var; + for (e = ekey; *e; e++) + b[n++] = *e; + b[n++] = value; + for (e = eval; *e; e++) + b[n++] = *e; + } + if (user) { + b[n++] = var; + b[n++] = 'U'; + b[n++] = 'S'; + b[n++] = 'E'; + b[n++] = 'R'; + b[n++] = value; + for (e = user; *e; e++) + b[n++] = *e; + } + b[n++] = IAC; + b[n++] = SE; + telnet->bufsize = sk_write(telnet->s, b, n); + if (n == 6) { logeventf(telnet->logctx, "client:\tSB %s IS ", telopt(telnet->sb_opt)); - } else { + } else { logeventf(telnet->logctx, "client:\tSB %s IS:", telopt(telnet->sb_opt)); - for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, - NULL, &ekey); - eval != NULL; - eval = conf_get_str_strs(telnet->conf, CONF_environmt, - ekey, &ekey)) { + for (eval = conf_get_str_strs(telnet->conf, CONF_environmt, + NULL, &ekey); + eval != NULL; + eval = conf_get_str_strs(telnet->conf, CONF_environmt, + ekey, &ekey)) { logeventf(telnet->logctx, "\t%s=%s", ekey, eval); - } + } if (user) logeventf(telnet->logctx, "\tUSER=%s", user); - } - sfree(b); - sfree(user); - } - break; + } + sfree(b); + sfree(user); + } + break; } } @@ -509,98 +509,98 @@ static void do_telnet_read(Telnet *telnet, const char *buf, size_t len) strbuf *outbuf = strbuf_new_nm(); while (len--) { - int c = (unsigned char) *buf++; + int c = (unsigned char) *buf++; - switch (telnet->state) { - case TOP_LEVEL: - case SEENCR: - if (c == NUL && telnet->state == SEENCR) - telnet->state = TOP_LEVEL; - else if (c == IAC) - telnet->state = SEENIAC; - else { - if (!telnet->in_synch) - put_byte(outbuf, c); + switch (telnet->state) { + case TOP_LEVEL: + case SEENCR: + if (c == NUL && telnet->state == SEENCR) + telnet->state = TOP_LEVEL; + else if (c == IAC) + telnet->state = SEENIAC; + else { + if (!telnet->in_synch) + put_byte(outbuf, c); #if 1 - /* I can't get the F***ing winsock to insert the urgent IAC - * into the right position! Even with SO_OOBINLINE it gives - * it to recv too soon. And of course the DM byte (that - * arrives in the same packet!) appears several K later!! - * - * 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) - telnet->in_synch = false; + /* I can't get the F***ing winsock to insert the urgent IAC + * into the right position! Even with SO_OOBINLINE it gives + * it to recv too soon. And of course the DM byte (that + * arrives in the same packet!) appears several K later!! + * + * 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) + telnet->in_synch = false; #endif - if (c == CR && telnet->opt_states[o_they_bin.index] != ACTIVE) - telnet->state = SEENCR; - else - telnet->state = TOP_LEVEL; - } - 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; - else if (c == DM) { - telnet->in_synch = false; - telnet->state = TOP_LEVEL; - } else { - /* ignore everything else; print it if it's IAC */ - if (c == IAC) { - put_byte(outbuf, c); - } - telnet->state = TOP_LEVEL; - } - break; - case SEENWILL: - proc_rec_opt(telnet, WILL, c); - telnet->state = TOP_LEVEL; - break; - case SEENWONT: - proc_rec_opt(telnet, WONT, c); - telnet->state = TOP_LEVEL; - break; - case SEENDO: - proc_rec_opt(telnet, DO, c); - telnet->state = TOP_LEVEL; - break; - case SEENDONT: - proc_rec_opt(telnet, DONT, c); - telnet->state = TOP_LEVEL; - break; - case SEENSB: - telnet->sb_opt = c; - telnet->sb_buf->len = 0; - telnet->state = SUBNEGOT; - break; - case SUBNEGOT: - if (c == IAC) - telnet->state = SUBNEG_IAC; - else { - subneg_addchar: - put_byte(telnet->sb_buf, c); - telnet->state = SUBNEGOT; /* in case we came here by goto */ - } - break; - case SUBNEG_IAC: - if (c != SE) - goto subneg_addchar; /* yes, it's a hack, I know, but... */ - else { - process_subneg(telnet); - telnet->state = TOP_LEVEL; - } - break; - } + if (c == CR && telnet->opt_states[o_they_bin.index] != ACTIVE) + telnet->state = SEENCR; + else + telnet->state = TOP_LEVEL; + } + 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; + else if (c == DM) { + telnet->in_synch = false; + telnet->state = TOP_LEVEL; + } else { + /* ignore everything else; print it if it's IAC */ + if (c == IAC) { + put_byte(outbuf, c); + } + telnet->state = TOP_LEVEL; + } + break; + case SEENWILL: + proc_rec_opt(telnet, WILL, c); + telnet->state = TOP_LEVEL; + break; + case SEENWONT: + proc_rec_opt(telnet, WONT, c); + telnet->state = TOP_LEVEL; + break; + case SEENDO: + proc_rec_opt(telnet, DO, c); + telnet->state = TOP_LEVEL; + break; + case SEENDONT: + proc_rec_opt(telnet, DONT, c); + telnet->state = TOP_LEVEL; + break; + case SEENSB: + telnet->sb_opt = c; + telnet->sb_buf->len = 0; + telnet->state = SUBNEGOT; + break; + case SUBNEGOT: + if (c == IAC) + telnet->state = SUBNEG_IAC; + else { + subneg_addchar: + put_byte(telnet->sb_buf, c); + telnet->state = SUBNEGOT; /* in case we came here by goto */ + } + break; + case SUBNEG_IAC: + if (c != SE) + goto subneg_addchar; /* yes, it's a hack, I know, but... */ + else { + process_subneg(telnet); + telnet->state = TOP_LEVEL; + } + break; + } if (outbuf->len >= 4096) { c_write(telnet, outbuf->u, outbuf->len); @@ -609,12 +609,12 @@ static void do_telnet_read(Telnet *telnet, const char *buf, size_t len) } if (outbuf->len) - c_write(telnet, outbuf->u, outbuf->len); + c_write(telnet, outbuf->u, outbuf->len); strbuf_free(outbuf); } static void telnet_log(Plug *plug, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { Telnet *telnet = container_of(plug, Telnet, plug); backend_socket_log(telnet->seat, telnet->logctx, type, addr, port, @@ -623,7 +623,7 @@ static void telnet_log(Plug *plug, int type, SockAddr *addr, int port, } static void telnet_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { Telnet *telnet = container_of(plug, Telnet, plug); @@ -638,11 +638,11 @@ static void telnet_closing(Plug *plug, const char *error_msg, int error_code, telnet->s = NULL; if (error_msg) telnet->closed_on_socket_error = true; - seat_notify_remote_exit(telnet->seat); + seat_notify_remote_exit(telnet->seat); } if (error_msg) { logevent(telnet->logctx, error_msg); - seat_connection_fatal(telnet->seat, "%s", error_msg); + seat_connection_fatal(telnet->seat, "%s", error_msg); } /* Otherwise, the remote side closed the connection normally. */ } @@ -652,7 +652,7 @@ static void telnet_receive( { Telnet *telnet = container_of(plug, Telnet, plug); if (urgent) - telnet->in_synch = true; + telnet->in_synch = true; telnet->session_started = true; do_telnet_read(telnet, data, len); } @@ -681,7 +681,7 @@ static const PlugVtable Telnet_plugvt = { static const char *telnet_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, const char *host, int port, - char **realhost, bool nodelay, bool keepalive) + char **realhost, bool nodelay, bool keepalive) { SockAddr *addr; const char *err; @@ -719,12 +719,12 @@ static const char *telnet_init(Seat *seat, Backend **backend_handle, addr = name_lookup(host, port, realhost, telnet->conf, addressfamily, telnet->logctx, "Telnet connection"); if ((err = sk_addr_error(addr)) != NULL) { - sk_addr_free(addr); - return err; + sk_addr_free(addr); + return err; } if (port < 0) - port = 23; /* default telnet port */ + port = 23; /* default telnet port */ /* * Open socket. @@ -732,7 +732,7 @@ static const char *telnet_init(Seat *seat, Backend **backend_handle, telnet->s = new_connection(addr, *realhost, port, false, true, nodelay, keepalive, &telnet->plug, telnet->conf); if ((err = sk_socket_error(telnet->s)) != NULL) - return err; + return err; telnet->pinger = pinger_new(telnet->conf, &telnet->backend); @@ -740,19 +740,19 @@ static const char *telnet_init(Seat *seat, Backend **backend_handle, * Initialise option states. */ if (conf_get_bool(telnet->conf, CONF_passive_telnet)) { - const struct Opt *const *o; + const struct Opt *const *o; - for (o = opts; *o; o++) - telnet->opt_states[(*o)->index] = INACTIVE; + for (o = opts; *o; o++) + telnet->opt_states[(*o)->index] = INACTIVE; } else { - const struct Opt *const *o; + const struct Opt *const *o; - for (o = opts; *o; o++) { - telnet->opt_states[(*o)->index] = (*o)->initial_state; - if (telnet->opt_states[(*o)->index] == REQUESTED) - send_opt(telnet, (*o)->send, (*o)->option); - } - telnet->activated = true; + for (o = opts; *o; o++) { + telnet->opt_states[(*o)->index] = (*o)->initial_state; + if (telnet->opt_states[(*o)->index] == REQUESTED) + send_opt(telnet, (*o)->send, (*o)->option); + } + telnet->activated = true; } /* @@ -770,14 +770,14 @@ static const char *telnet_init(Seat *seat, Backend **backend_handle, */ loghost = conf_get_str(telnet->conf, CONF_loghost); if (*loghost) { - char *colon; + char *colon; - sfree(*realhost); - *realhost = dupstr(loghost); + sfree(*realhost); + *realhost = dupstr(loghost); - colon = host_strrchr(*realhost, ':'); - if (colon) - *colon++ = '\0'; + colon = host_strrchr(*realhost, ':'); + if (colon) + *colon++ = '\0'; } return NULL; @@ -789,9 +789,9 @@ static void telnet_free(Backend *be) strbuf_free(telnet->sb_buf); if (telnet->s) - sk_close(telnet->s); + sk_close(telnet->s); if (telnet->pinger) - pinger_free(telnet->pinger); + pinger_free(telnet->pinger); conf_free(telnet->conf); sfree(telnet); } @@ -822,22 +822,22 @@ static size_t telnet_send(Backend *be, const char *buf, size_t len) #endif if (telnet->s == NULL) - return 0; + return 0; p = (unsigned char *)buf; end = (unsigned char *)(buf + len); while (p < end) { - unsigned char *q = p; + unsigned char *q = p; - while (p < end && iswritable(*p)) - p++; - telnet->bufsize = sk_write(telnet->s, q, p - q); + while (p < end && iswritable(*p)) + p++; + telnet->bufsize = sk_write(telnet->s, q, p - q); - while (p < end && !iswritable(*p)) { - telnet->bufsize = - sk_write(telnet->s, *p == IAC ? iac : cr, 2); - p++; - } + while (p < end && !iswritable(*p)) { + telnet->bufsize = + sk_write(telnet->s, *p == IAC ? iac : cr, 2); + p++; + } } return telnet->bufsize; @@ -865,7 +865,7 @@ static void telnet_size(Backend *be, int width, int height) telnet->term_height = height; if (telnet->s == NULL || telnet->opt_states[o_naws.index] != ACTIVE) - return; + return; n = 0; b[n++] = IAC; b[n++] = SB; @@ -894,101 +894,101 @@ static void telnet_special(Backend *be, SessionSpecialCode code, int arg) unsigned char b[2]; if (telnet->s == NULL) - return; + return; b[0] = IAC; switch (code) { case SS_AYT: - b[1] = AYT; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = AYT; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_BRK: - b[1] = BREAK; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = BREAK; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_EC: - b[1] = EC; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = EC; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_EL: - b[1] = EL; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = EL; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_GA: - b[1] = GA; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = GA; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_NOP: - b[1] = NOP; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = NOP; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_ABORT: - b[1] = ABORT; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = ABORT; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_AO: - b[1] = AO; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = AO; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_IP: - b[1] = IP; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = IP; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_SUSP: - b[1] = SUSP; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = SUSP; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_EOR: - b[1] = EOR; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = EOR; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_EOF: - b[1] = xEOF; - telnet->bufsize = sk_write(telnet->s, b, 2); - break; + b[1] = xEOF; + telnet->bufsize = sk_write(telnet->s, b, 2); + break; case SS_EOL: - /* In BINARY mode, CR-LF becomes just CR - - * and without the NUL suffix too. */ - if (telnet->opt_states[o_we_bin.index] == ACTIVE) - telnet->bufsize = sk_write(telnet->s, "\r", 1); - else - telnet->bufsize = sk_write(telnet->s, "\r\n", 2); - break; + /* In BINARY mode, CR-LF becomes just CR - + * and without the NUL suffix too. */ + if (telnet->opt_states[o_we_bin.index] == ACTIVE) + telnet->bufsize = sk_write(telnet->s, "\r", 1); + else + telnet->bufsize = sk_write(telnet->s, "\r\n", 2); + break; case SS_SYNCH: - b[1] = DM; - telnet->bufsize = sk_write(telnet->s, b, 1); - telnet->bufsize = sk_write_oob(telnet->s, b + 1, 1); - break; + b[1] = DM; + telnet->bufsize = sk_write(telnet->s, b, 1); + telnet->bufsize = sk_write_oob(telnet->s, b + 1, 1); + break; case SS_PING: - if (telnet->opt_states[o_they_sga.index] == ACTIVE) { - b[1] = NOP; - telnet->bufsize = sk_write(telnet->s, b, 2); - } - break; + if (telnet->opt_states[o_they_sga.index] == ACTIVE) { + b[1] = NOP; + telnet->bufsize = sk_write(telnet->s, b, 2); + } + break; default: - break; /* never heard of it */ + break; /* never heard of it */ } } static const SessionSpecial *telnet_get_specials(Backend *be) { static const SessionSpecial specials[] = { - {"Are You There", SS_AYT}, - {"Break", SS_BRK}, - {"Synch", SS_SYNCH}, - {"Erase Character", SS_EC}, - {"Erase Line", SS_EL}, - {"Go Ahead", SS_GA}, - {"No Operation", SS_NOP}, - {NULL, SS_SEP}, - {"Abort Process", SS_ABORT}, - {"Abort Output", SS_AO}, - {"Interrupt Process", SS_IP}, - {"Suspend Process", SS_SUSP}, - {NULL, SS_SEP}, - {"End Of Record", SS_EOR}, - {"End Of File", SS_EOF}, - {NULL, SS_EXITMENU} + {"Are You There", SS_AYT}, + {"Break", SS_BRK}, + {"Synch", SS_SYNCH}, + {"Erase Character", SS_EC}, + {"Erase Line", SS_EL}, + {"Go Ahead", SS_GA}, + {"No Operation", SS_NOP}, + {NULL, SS_SEP}, + {"Abort Process", SS_ABORT}, + {"Abort Output", SS_AO}, + {"Interrupt Process", SS_IP}, + {"Suspend Process", SS_SUSP}, + {NULL, SS_SEP}, + {"End Of Record", SS_EOR}, + {"End Of File", SS_EOF}, + {NULL, SS_EXITMENU} }; return specials; } @@ -1015,9 +1015,9 @@ static bool telnet_ldisc(Backend *be, int option) { Telnet *telnet = container_of(be, Telnet, backend); if (option == LD_ECHO) - return telnet->echoing; + return telnet->echoing; if (option == LD_EDIT) - return telnet->editing; + return telnet->editing; return false; } diff --git a/terminal.c b/terminal.c index 9637498a..6f93c78e 100644 --- a/terminal.c +++ b/terminal.c @@ -15,27 +15,27 @@ #define VT52_PLUS -#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) -#define TM_VT102 (TM_VT100AVO|CL_VT102) -#define TM_VT220 (TM_VT102|CL_VT220) -#define TM_VTXXX (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320) -#define TM_SCOANSI (CL_ANSIMIN|CL_SCOANSI) +#define TM_VT100 (CL_ANSIMIN|CL_VT100) +#define TM_VT100AVO (TM_VT100|CL_VT100AVO) +#define TM_VT102 (TM_VT100AVO|CL_VT102) +#define TM_VT220 (TM_VT102|CL_VT220) +#define TM_VTXXX (TM_VT220|CL_VT340TEXT|CL_VT510|CL_VT420|CL_VT320) +#define TM_SCOANSI (CL_ANSIMIN|CL_SCOANSI) -#define TM_PUTTY (0xFFFF) +#define TM_PUTTY (0xFFFF) #define UPDATE_DELAY ((TICKSPERSEC+49)/50)/* ticks to defer window update */ #define TBLINK_DELAY ((TICKSPERSEC*9+19)/20)/* ticks between text blinks*/ @@ -43,14 +43,14 @@ #define VBELL_DELAY (VBELL_TIMEOUT) /* visual bell timeout in ticks */ #define compatibility(x) \ - if ( ((CL_##x)&term->compatibility_level) == 0 ) { \ - term->termstate=TOPLEVEL; \ - break; \ + if ( ((CL_##x)&term->compatibility_level) == 0 ) { \ + term->termstate=TOPLEVEL; \ + break; \ } #define compatibility2(x,y) \ if ( ((CL_##x|CL_##y)&term->compatibility_level) == 0 ) { \ - term->termstate=TOPLEVEL; \ - break; \ + term->termstate=TOPLEVEL; \ + break; \ } #define has_compat(x) ( ((CL_##x)&term->compatibility_level) != 0 ) @@ -75,7 +75,7 @@ const wchar_t sel_nl[] = SEL_NL; * Detect the various aliases of U+0020 SPACE. */ #define IS_SPACE_CHR(chr) \ - ((chr) == 0x20 || (DIRECT_CHAR(chr) && ((chr) & 0xFF) == 0x20)) + ((chr) == 0x20 || (DIRECT_CHAR(chr) && ((chr) & 0xFF) == 0x20)) /* * Spot magic CSETs. @@ -108,7 +108,7 @@ static termline *newtermline(Terminal *term, int cols, bool bce) line = snew(termline); line->chars = snewn(cols, termchar); for (j = 0; j < cols; j++) - line->chars[j] = (bce ? term->erase_char : term->basic_erase_char); + line->chars[j] = (bce ? term->erase_char : term->basic_erase_char); line->cols = line->size = cols; line->lattr = LATTR_NORM; line->trusted = false; @@ -121,22 +121,22 @@ static termline *newtermline(Terminal *term, int cols, bool bce) static void freetermline(termline *line) { if (line) { - sfree(line->chars); - sfree(line); + sfree(line->chars); + sfree(line); } } static void unlineptr(termline *line) { if (line->temporary) - freetermline(line); + freetermline(line); } #ifdef TERM_CC_DIAGS /* * Diagnostic function: verify that a termline has a correct * combining character structure. - * + * * This is a performance-intensive check, so it's no longer enabled * by default. */ @@ -150,34 +150,34 @@ static void cc_check(termline *line) flags = snewn(line->size, unsigned char); for (i = 0; i < line->size; i++) - flags[i] = (i < line->cols); + flags[i] = (i < line->cols); for (i = 0; i < line->cols; i++) { - j = i; - while (line->chars[j].cc_next) { - j += line->chars[j].cc_next; - assert(j >= line->cols && j < line->size); - assert(!flags[j]); - flags[j] = true; - } + j = i; + while (line->chars[j].cc_next) { + j += line->chars[j].cc_next; + assert(j >= line->cols && j < line->size); + assert(!flags[j]); + flags[j] = true; + } } j = line->cc_free; if (j) { - while (1) { - assert(j >= line->cols && j < line->size); - assert(!flags[j]); - flags[j] = true; - if (line->chars[j].cc_next) - j += line->chars[j].cc_next; - else - break; - } + while (1) { + assert(j >= line->cols && j < line->size); + assert(!flags[j]); + flags[j] = true; + if (line->chars[j].cc_next) + j += line->chars[j].cc_next; + else + break; + } } j = 0; for (i = 0; i < line->size; i++) - j += (flags[i] != 0); + j += (flags[i] != 0); assert(j == line->size); @@ -213,7 +213,7 @@ static void add_cc(termline *line, int col, unsigned long chr) size_t ncc = 0; int origcol = col; while (line->chars[col].cc_next) { - col += line->chars[col].cc_next; + col += line->chars[col].cc_next; if (++ncc >= CC_LIMIT) { /* * There are already too many combining characters in this @@ -242,21 +242,21 @@ static void add_cc(termline *line, int col, unsigned long chr) * Extend the cols array if the free list is empty. */ if (!line->cc_free) { - int n = line->size; + int n = line->size; size_t tmpsize = line->size; sgrowarray(line->chars, tmpsize, tmpsize); assert(tmpsize <= INT_MAX); line->size = tmpsize; - line->cc_free = n; - while (n < line->size) { - if (n+1 < line->size) - line->chars[n].cc_next = 1; - else - line->chars[n].cc_next = 0; - n++; - } + line->cc_free = n; + while (n < line->size) { + if (n+1 < line->size) + line->chars[n].cc_next = 1; + else + line->chars[n].cc_next = 0; + n++; + } } /* @@ -265,9 +265,9 @@ static void add_cc(termline *line, int col, unsigned long chr) */ newcc = line->cc_free; if (line->chars[newcc].cc_next) - line->cc_free = newcc + line->chars[newcc].cc_next; + line->cc_free = newcc + line->chars[newcc].cc_next; else - line->cc_free = 0; + line->cc_free = 0; line->chars[newcc].cc_next = 0; line->chars[newcc].chr = chr; line->chars[col].cc_next = newcc - col; @@ -287,16 +287,16 @@ static void clear_cc(termline *line, int col) assert(col >= 0 && col < line->cols); if (!line->chars[col].cc_next) - return; /* nothing needs doing */ + return; /* nothing needs doing */ oldfree = line->cc_free; line->cc_free = col + line->chars[col].cc_next; while (line->chars[col].cc_next) - col += line->chars[col].cc_next; + col += line->chars[col].cc_next; if (oldfree) - line->chars[col].cc_next = oldfree - col; + line->chars[col].cc_next = oldfree - col; else - line->chars[col].cc_next = 0; + line->chars[col].cc_next = 0; line->chars[origcol].cc_next = 0; @@ -315,18 +315,18 @@ static bool termchars_equal_override(termchar *a, termchar *b, { /* FULL-TERMCHAR */ if (!truecolour_equal(a->truecolour, b->truecolour)) - return false; + return false; if (a->chr != bchr) - return false; + return false; if ((a->attr &~ DATTR_MASK) != (battr &~ DATTR_MASK)) - return false; + return false; while (a->cc_next || b->cc_next) { - if (!a->cc_next || !b->cc_next) - return false; /* one cc-list ends, other does not */ - a += a->cc_next; - b += b->cc_next; - if (a->chr != b->chr) - return false; + if (!a->cc_next || !b->cc_next) + return false; /* one cc-list ends, other does not */ + a += a->cc_next; + b += b->cc_next; + if (a->chr != b->chr) + return false; } return true; } @@ -344,12 +344,12 @@ static void copy_termchar(termline *destline, int x, termchar *src) { clear_cc(destline, x); - destline->chars[x] = *src; /* copy everything except cc-list */ + destline->chars[x] = *src; /* copy everything except cc-list */ destline->chars[x].cc_next = 0; /* and make sure this is zero */ while (src->cc_next) { - src += src->cc_next; - add_cc(destline, x, src->chr); + src += src->cc_next; + add_cc(destline, x, src->chr); } #ifdef TERM_CC_DIAGS @@ -366,9 +366,9 @@ static void move_termchar(termline *line, termchar *dest, termchar *src) clear_cc(line, dest - line->chars); /* Move the character cell and adjust its cc_next. */ - *dest = *src; /* copy everything except cc-list */ + *dest = *src; /* copy everything except cc-list */ if (src->cc_next) - dest->cc_next = src->cc_next - (dest-src); + dest->cc_next = src->cc_next - (dest-src); /* Ensure the original cell doesn't have a cc list. */ src->cc_next = 0; @@ -388,8 +388,8 @@ static void move_termchar(termline *line, termchar *dest, termchar *src) * features are in constant use.) */ static void makerle(strbuf *b, termline *ldata, - void (*makeliteral)(strbuf *b, termchar *c, - unsigned long *state)) + void (*makeliteral)(strbuf *b, termchar *c, + unsigned long *state)) { int hdrpos, hdrsize, n, prevlen, prevpos, thislen, thispos; bool prev2; @@ -405,121 +405,121 @@ static void makerle(strbuf *b, termline *ldata, prev2 = false; while (n-- > 0) { - thispos = b->len; - makeliteral(b, c++, &state); - thislen = b->len - thispos; - if (thislen == prevlen && - !memcmp(b->u + prevpos, b->u + thispos, thislen)) { - /* - * This literal precisely matches the previous one. - * Turn it into a run if it's worthwhile. - * - * With one-byte literals, it costs us two bytes to - * encode a run, plus another byte to write the header - * to resume normal output; so a three-element run is - * neutral, and anything beyond that is unconditionally - * worthwhile. With two-byte literals or more, even a - * 2-run is a win. - */ - if (thislen > 1 || prev2) { - int runpos, runlen; + thispos = b->len; + makeliteral(b, c++, &state); + thislen = b->len - thispos; + if (thislen == prevlen && + !memcmp(b->u + prevpos, b->u + thispos, thislen)) { + /* + * This literal precisely matches the previous one. + * Turn it into a run if it's worthwhile. + * + * With one-byte literals, it costs us two bytes to + * encode a run, plus another byte to write the header + * to resume normal output; so a three-element run is + * neutral, and anything beyond that is unconditionally + * worthwhile. With two-byte literals or more, even a + * 2-run is a win. + */ + if (thislen > 1 || prev2) { + int runpos, runlen; - /* - * It's worth encoding a run. Start at prevpos, - * unless hdrsize==0 in which case we can back up - * another one and start by overwriting hdrpos. - */ + /* + * It's worth encoding a run. Start at prevpos, + * unless hdrsize==0 in which case we can back up + * another one and start by overwriting hdrpos. + */ - hdrsize--; /* remove the literal at prevpos */ - if (prev2) { - assert(hdrsize > 0); - hdrsize--; - prevpos -= prevlen;/* and possibly another one */ - } + hdrsize--; /* remove the literal at prevpos */ + if (prev2) { + assert(hdrsize > 0); + hdrsize--; + prevpos -= prevlen;/* and possibly another one */ + } - if (hdrsize == 0) { - assert(prevpos == hdrpos + 1); - runpos = hdrpos; - b->len = prevpos+prevlen; - } else { - memmove(b->u + prevpos+1, b->u + prevpos, prevlen); - runpos = prevpos; - b->len = prevpos+prevlen+1; - /* - * Terminate the previous run of ordinary - * literals. - */ - assert(hdrsize >= 1 && hdrsize <= 128); - b->u[hdrpos] = hdrsize - 1; - } + if (hdrsize == 0) { + assert(prevpos == hdrpos + 1); + runpos = hdrpos; + b->len = prevpos+prevlen; + } else { + memmove(b->u + prevpos+1, b->u + prevpos, prevlen); + runpos = prevpos; + b->len = prevpos+prevlen+1; + /* + * Terminate the previous run of ordinary + * literals. + */ + assert(hdrsize >= 1 && hdrsize <= 128); + b->u[hdrpos] = hdrsize - 1; + } - runlen = prev2 ? 3 : 2; + runlen = prev2 ? 3 : 2; - while (n > 0 && runlen < 129) { - int tmppos, tmplen; - tmppos = b->len; - oldstate = state; - makeliteral(b, c, &state); - tmplen = b->len - tmppos; - b->len = tmppos; - if (tmplen != thislen || - memcmp(b->u + runpos+1, b->u + tmppos, tmplen)) { - state = oldstate; - break; /* run over */ - } - n--, c++, runlen++; - } + while (n > 0 && runlen < 129) { + int tmppos, tmplen; + tmppos = b->len; + oldstate = state; + makeliteral(b, c, &state); + tmplen = b->len - tmppos; + b->len = tmppos; + if (tmplen != thislen || + memcmp(b->u + runpos+1, b->u + tmppos, tmplen)) { + state = oldstate; + break; /* run over */ + } + n--, c++, runlen++; + } - assert(runlen >= 2 && runlen <= 129); - b->u[runpos] = runlen + 0x80 - 2; + assert(runlen >= 2 && runlen <= 129); + b->u[runpos] = runlen + 0x80 - 2; - hdrpos = b->len; - hdrsize = 0; - put_byte(b, 0); - /* And ensure this run doesn't interfere with the next. */ - prevlen = prevpos = 0; - prev2 = false; + hdrpos = b->len; + hdrsize = 0; + put_byte(b, 0); + /* And ensure this run doesn't interfere with the next. */ + prevlen = prevpos = 0; + prev2 = false; - continue; - } else { - /* - * Just flag that the previous two literals were - * identical, in case we find a third identical one - * we want to turn into a run. - */ - prev2 = true; - prevlen = thislen; - prevpos = thispos; - } - } else { - prev2 = false; - prevlen = thislen; - prevpos = thispos; - } + continue; + } else { + /* + * Just flag that the previous two literals were + * identical, in case we find a third identical one + * we want to turn into a run. + */ + prev2 = true; + prevlen = thislen; + prevpos = thispos; + } + } else { + prev2 = false; + prevlen = thislen; + prevpos = thispos; + } - /* - * This character isn't (yet) part of a run. Add it to - * hdrsize. - */ - hdrsize++; - if (hdrsize == 128) { - b->u[hdrpos] = hdrsize - 1; - hdrpos = b->len; - hdrsize = 0; - put_byte(b, 0); - prevlen = prevpos = 0; - prev2 = false; - } + /* + * This character isn't (yet) part of a run. Add it to + * hdrsize. + */ + hdrsize++; + if (hdrsize == 128) { + b->u[hdrpos] = hdrsize - 1; + hdrpos = b->len; + hdrsize = 0; + put_byte(b, 0); + prevlen = prevpos = 0; + prev2 = false; + } } /* * Clean up. */ if (hdrsize > 0) { - assert(hdrsize <= 128); - b->u[hdrpos] = hdrsize - 1; + assert(hdrsize <= 128); + b->u[hdrpos] = hdrsize - 1; } else { - b->len = hdrpos; + b->len = hdrpos; } } static void makeliteral_chr(strbuf *b, termchar *c, unsigned long *state) @@ -535,20 +535,20 @@ static void makeliteral_chr(strbuf *b, termchar *c, unsigned long *state) * day use values 0x80000000-0xFFFFFFFF for interesting * purposes, so unlike UTF-8 I need a full 32-bit range. * Accordingly, here is my encoding: - * + * * 00000000-0000007F: 0xxxxxxx (but see below) * 00000080-00003FFF: 10xxxxxx xxxxxxxx * 00004000-001FFFFF: 110xxxxx xxxxxxxx xxxxxxxx * 00200000-0FFFFFFF: 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx * 10000000-FFFFFFFF: 11110ZZZ xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx - * + * * (`Z' is like `x' but is always going to be zero since the * values I'm encoding don't go above 2^32. In principle the * five-byte form of the encoding could extend to 2^35, and * there could be six-, seven-, eight- and nine-byte forms as * well to allow up to 64-bit values to be encoded. But that's * completely unnecessary for these purposes!) - * + * * The encoding as written above would be very simple, except * that 7-bit ASCII can occur in several different ways in the * terminal data; sometimes it crops up in the D800 page @@ -560,20 +560,20 @@ static void makeliteral_chr(strbuf *b, termchar *c, unsigned long *state) * instead. */ if ((c->chr & ~0x7F) == *state) { - put_byte(b, (unsigned char)(c->chr & 0x7F)); + put_byte(b, (unsigned char)(c->chr & 0x7F)); } else if (c->chr < 0x4000) { - put_byte(b, (unsigned char)(((c->chr >> 8) & 0x3F) | 0x80)); - put_byte(b, (unsigned char)(c->chr & 0xFF)); + put_byte(b, (unsigned char)(((c->chr >> 8) & 0x3F) | 0x80)); + put_byte(b, (unsigned char)(c->chr & 0xFF)); } else if (c->chr < 0x200000) { - put_byte(b, (unsigned char)(((c->chr >> 16) & 0x1F) | 0xC0)); - put_uint16(b, c->chr & 0xFFFF); + put_byte(b, (unsigned char)(((c->chr >> 16) & 0x1F) | 0xC0)); + put_uint16(b, c->chr & 0xFFFF); } else if (c->chr < 0x10000000) { - put_byte(b, (unsigned char)(((c->chr >> 24) & 0x0F) | 0xE0)); - put_byte(b, (unsigned char)((c->chr >> 16) & 0xFF)); - put_uint16(b, c->chr & 0xFFFF); + put_byte(b, (unsigned char)(((c->chr >> 24) & 0x0F) | 0xE0)); + put_byte(b, (unsigned char)((c->chr >> 16) & 0xFF)); + put_uint16(b, c->chr & 0xFFFF); } else { - put_byte(b, 0xF0); - put_uint32(b, c->chr); + put_byte(b, 0xF0); + put_uint32(b, c->chr); } *state = c->chr & ~0xFF; } @@ -585,7 +585,7 @@ static void makeliteral_attr(strbuf *b, termchar *c, unsigned long *state) * store a two-byte value with the top bit clear (indicating * just that value), or a four-byte value with the top bit set * (indicating the same value with its top bit clear). - * + * * However, first I permute the bits of the attribute value, so * that the eight bits of colour (four in each of fg and bg) * which are never non-zero unless xterm 256-colour mode is in @@ -604,20 +604,20 @@ static void makeliteral_attr(strbuf *b, termchar *c, unsigned long *state) colourbits |= (attr >> (ATTR_FGSHIFT + 4)) & 0xF; attr = (((attr >> (ATTR_BGSHIFT + 8)) << (ATTR_BGSHIFT + 4)) | - (attr & ((1 << (ATTR_BGSHIFT + 4))-1))); + (attr & ((1 << (ATTR_BGSHIFT + 4))-1))); attr = (((attr >> (ATTR_FGSHIFT + 8)) << (ATTR_FGSHIFT + 4)) | - (attr & ((1 << (ATTR_FGSHIFT + 4))-1))); + (attr & ((1 << (ATTR_FGSHIFT + 4))-1))); attr |= (colourbits << (32-9)); if (attr < 0x8000) { - put_byte(b, (unsigned char)((attr >> 8) & 0xFF)); - put_byte(b, (unsigned char)(attr & 0xFF)); + put_byte(b, (unsigned char)((attr >> 8) & 0xFF)); + put_byte(b, (unsigned char)(attr & 0xFF)); } else { - put_byte(b, (unsigned char)(((attr >> 24) & 0x7F) | 0x80)); - put_byte(b, (unsigned char)((attr >> 16) & 0xFF)); - put_byte(b, (unsigned char)((attr >> 8) & 0xFF)); - put_byte(b, (unsigned char)(attr & 0xFF)); + put_byte(b, (unsigned char)(((attr >> 24) & 0x7F) | 0x80)); + put_byte(b, (unsigned char)((attr >> 16) & 0xFF)); + put_byte(b, (unsigned char)((attr >> 8) & 0xFF)); + put_byte(b, (unsigned char)(attr & 0xFF)); } } static void makeliteral_truecolour(strbuf *b, termchar *c, unsigned long *state) @@ -628,14 +628,14 @@ static void makeliteral_truecolour(strbuf *b, termchar *c, unsigned long *state) put_byte(b, ((c->truecolour.fg.enabled ? 1 : 0) | (c->truecolour.bg.enabled ? 2 : 0))); if (c->truecolour.fg.enabled) { - put_byte(b, c->truecolour.fg.r); - put_byte(b, c->truecolour.fg.g); - put_byte(b, c->truecolour.fg.b); + put_byte(b, c->truecolour.fg.r); + put_byte(b, c->truecolour.fg.g); + put_byte(b, c->truecolour.fg.b); } if (c->truecolour.bg.enabled) { - put_byte(b, c->truecolour.bg.r); - put_byte(b, c->truecolour.bg.g); - put_byte(b, c->truecolour.bg.b); + put_byte(b, c->truecolour.bg.r); + put_byte(b, c->truecolour.bg.g); + put_byte(b, c->truecolour.bg.b); } } static void makeliteral_cc(strbuf *b, termchar *c, unsigned long *state) @@ -645,19 +645,19 @@ static void makeliteral_cc(strbuf *b, termchar *c, unsigned long *state) * chars using makeliteral_chr, and terminate with a \0 * character (which I know won't come up as a combining char * itself). - * + * * I don't use the stateful encoding in makeliteral_chr. */ unsigned long zstate; termchar z; while (c->cc_next) { - c += c->cc_next; + c += c->cc_next; - assert(c->chr != 0); + assert(c->chr != 0); - zstate = 0; - makeliteral_chr(b, c, &zstate); + zstate = 0; + makeliteral_chr(b, c, &zstate); } z.chr = 0; @@ -684,12 +684,12 @@ static compressed_scrollback_line *compressline(termline *ldata) * the last. */ { - int n = ldata->cols; - while (n >= 128) { - put_byte(b, (unsigned char)((n & 0x7F) | 0x80)); - n >>= 7; - } - put_byte(b, (unsigned char)(n)); + int n = ldata->cols; + while (n >= 128) { + put_byte(b, (unsigned char)((n & 0x7F) | 0x80)); + n >>= 7; + } + put_byte(b, (unsigned char)(n)); } /* @@ -697,25 +697,25 @@ static compressed_scrollback_line *compressline(termline *ldata) * this to indicate the trust state of the line. */ { - int n = ldata->lattr | (ldata->trusted ? 0x10000 : 0); - while (n >= 128) { - put_byte(b, (unsigned char)((n & 0x7F) | 0x80)); - n >>= 7; - } - put_byte(b, (unsigned char)(n)); + int n = ldata->lattr | (ldata->trusted ? 0x10000 : 0); + while (n >= 128) { + put_byte(b, (unsigned char)((n & 0x7F) | 0x80)); + n >>= 7; + } + put_byte(b, (unsigned char)(n)); } /* * Now we store a sequence of separate run-length encoded * fragments, each containing exactly as many symbols as there * are columns in the ldata. - * + * * All of these have a common basic format: - * + * * - a byte 00-7F indicates that X+1 literals follow it - * - a byte 80-FF indicates that a single literal follows it - * and expects to be repeated (X-0x80)+2 times. - * + * - a byte 80-FF indicates that a single literal follows it + * and expects to be repeated (X-0x80)+2 times. + * * The format of the `literals' varies between the fragments. */ makerle(b, ldata, makeliteral_chr); @@ -726,35 +726,35 @@ static compressed_scrollback_line *compressline(termline *ldata) /* * Diagnostics: ensure that the compressed data really does * decompress to the right thing. - * + * * This is a bit performance-heavy for production code. */ #ifdef TERM_CC_DIAGS #ifndef CHECK_SB_COMPRESSION { - termline *dcl; - int i; + termline *dcl; + int i; #ifdef DIAGNOSTIC_SB_COMPRESSION - for (i = 0; i < b->len; i++) { - printf(" %02x ", b->data[i]); - } - printf("\n"); + for (i = 0; i < b->len; i++) { + printf(" %02x ", b->data[i]); + } + printf("\n"); #endif - dcl = decompressline((compressed_scrollback_line *)b->u); - assert(ldata->cols == dcl->cols); - assert(ldata->lattr == dcl->lattr); - for (i = 0; i < ldata->cols; i++) - assert(termchars_equal(&ldata->chars[i], &dcl->chars[i])); + dcl = decompressline((compressed_scrollback_line *)b->u); + assert(ldata->cols == dcl->cols); + assert(ldata->lattr == dcl->lattr); + for (i = 0; i < ldata->cols; i++) + assert(termchars_equal(&ldata->chars[i], &dcl->chars[i])); #ifdef DIAGNOSTIC_SB_COMPRESSION - printf("%d cols (%d bytes) -> %d bytes (factor of %g)\n", - ldata->cols, 4 * ldata->cols, dused, - (double)dused / (4 * ldata->cols)); + printf("%d cols (%d bytes) -> %d bytes (factor of %g)\n", + ldata->cols, 4 * ldata->cols, dused, + (double)dused / (4 * ldata->cols)); #endif - freetermline(dcl); + freetermline(dcl); } #endif #endif /* TERM_CC_DIAGS */ @@ -767,41 +767,41 @@ static compressed_scrollback_line *compressline(termline *ldata) } static void readrle(BinarySource *bs, termline *ldata, - void (*readliteral)(BinarySource *bs, termchar *c, - termline *ldata, unsigned long *state)) + void (*readliteral)(BinarySource *bs, termchar *c, + termline *ldata, unsigned long *state)) { int n = 0; unsigned long state = 0; while (n < ldata->cols) { - int hdr = get_byte(bs); + int hdr = get_byte(bs); - if (hdr >= 0x80) { - /* A run. */ + if (hdr >= 0x80) { + /* A run. */ - size_t pos = bs->pos, count = hdr + 2 - 0x80; - while (count--) { - assert(n < ldata->cols); - bs->pos = pos; - readliteral(bs, ldata->chars + n, ldata, &state); - n++; - } - } else { - /* Just a sequence of consecutive literals. */ + size_t pos = bs->pos, count = hdr + 2 - 0x80; + while (count--) { + assert(n < ldata->cols); + bs->pos = pos; + readliteral(bs, ldata->chars + n, ldata, &state); + n++; + } + } else { + /* Just a sequence of consecutive literals. */ - int count = hdr + 1; - while (count--) { - assert(n < ldata->cols); - readliteral(bs, ldata->chars + n, ldata, &state); - n++; - } - } + int count = hdr + 1; + while (count--) { + assert(n < ldata->cols); + readliteral(bs, ldata->chars + n, ldata, &state); + n++; + } + } } assert(n == ldata->cols); } static void readliteral_chr(BinarySource *bs, termchar *c, termline *ldata, - unsigned long *state) + unsigned long *state) { int byte; @@ -815,43 +815,43 @@ static void readliteral_chr(BinarySource *bs, termchar *c, termline *ldata, byte = get_byte(bs); if (byte < 0x80) { - c->chr = byte | *state; + c->chr = byte | *state; } else if (byte < 0xC0) { - c->chr = (byte &~ 0xC0) << 8; - c->chr |= get_byte(bs); + c->chr = (byte &~ 0xC0) << 8; + c->chr |= get_byte(bs); } else if (byte < 0xE0) { - c->chr = (byte &~ 0xE0) << 16; - c->chr |= get_uint16(bs); + c->chr = (byte &~ 0xE0) << 16; + c->chr |= get_uint16(bs); } else if (byte < 0xF0) { - c->chr = (byte &~ 0xF0) << 24; - c->chr |= get_byte(bs) << 16; - c->chr |= get_uint16(bs); + c->chr = (byte &~ 0xF0) << 24; + c->chr |= get_byte(bs) << 16; + c->chr |= get_uint16(bs); } else { - assert(byte == 0xF0); - c->chr = get_uint32(bs); + assert(byte == 0xF0); + c->chr = get_uint32(bs); } *state = c->chr & ~0xFF; } static void readliteral_attr(BinarySource *bs, termchar *c, termline *ldata, - unsigned long *state) + unsigned long *state) { unsigned val, attr, colourbits; val = get_uint16(bs); if (val >= 0x8000) { - val &= ~0x8000; - val <<= 16; - val |= get_uint16(bs); + val &= ~0x8000; + val <<= 16; + val |= get_uint16(bs); } colourbits = (val >> (32-9)) & 0xFF; attr = (val & ((1<<(32-9))-1)); attr = (((attr >> (ATTR_FGSHIFT + 4)) << (ATTR_FGSHIFT + 8)) | - (attr & ((1 << (ATTR_FGSHIFT + 4))-1))); + (attr & ((1 << (ATTR_FGSHIFT + 4))-1))); attr = (((attr >> (ATTR_BGSHIFT + 4)) << (ATTR_BGSHIFT + 8)) | - (attr & ((1 << (ATTR_BGSHIFT + 4))-1))); + (attr & ((1 << (ATTR_BGSHIFT + 4))-1))); attr |= (colourbits >> 4) << (ATTR_BGSHIFT + 4); attr |= (colourbits & 0xF) << (ATTR_FGSHIFT + 4); @@ -865,24 +865,24 @@ static void readliteral_truecolour( if (flags & 1) { c->truecolour.fg.enabled = true; - c->truecolour.fg.r = get_byte(bs); - c->truecolour.fg.g = get_byte(bs); - c->truecolour.fg.b = get_byte(bs); + c->truecolour.fg.r = get_byte(bs); + c->truecolour.fg.g = get_byte(bs); + c->truecolour.fg.b = get_byte(bs); } else { - c->truecolour.fg = optionalrgb_none; + c->truecolour.fg = optionalrgb_none; } if (flags & 2) { c->truecolour.bg.enabled = true; - c->truecolour.bg.r = get_byte(bs); - c->truecolour.bg.g = get_byte(bs); - c->truecolour.bg.b = get_byte(bs); + c->truecolour.bg.r = get_byte(bs); + c->truecolour.bg.g = get_byte(bs); + c->truecolour.bg.b = get_byte(bs); } else { - c->truecolour.bg = optionalrgb_none; + c->truecolour.bg = optionalrgb_none; } } static void readliteral_cc(BinarySource *bs, termchar *c, termline *ldata, - unsigned long *state) + unsigned long *state) { termchar n; unsigned long zstate; @@ -891,11 +891,11 @@ static void readliteral_cc(BinarySource *bs, termchar *c, termline *ldata, c->cc_next = 0; while (1) { - zstate = 0; - readliteral_chr(bs, &n, ldata, &zstate); - if (!n.chr) - break; - add_cc(ldata, x, n.chr); + zstate = 0; + readliteral_chr(bs, &n, ldata, &zstate); + if (!n.chr) + break; + add_cc(ldata, x, n.chr); } } @@ -912,9 +912,9 @@ static termline *decompressline(compressed_scrollback_line *line) */ ncols = shift = 0; do { - byte = get_byte(bs); - ncols |= (byte & 0x7F) << shift; - shift += 7; + byte = get_byte(bs); + ncols |= (byte & 0x7F) << shift; + shift += 7; } while (byte & 0x80); /* @@ -933,9 +933,9 @@ static termline *decompressline(compressed_scrollback_line *line) * building it up. */ { - int i; - for (i = 0; i < ldata->cols; i++) - ldata->chars[i].cc_next = 0; + int i; + for (i = 0; i < ldata->cols; i++) + ldata->chars[i].cc_next = 0; } /* @@ -943,9 +943,9 @@ static termline *decompressline(compressed_scrollback_line *line) */ int lattr = shift = 0; do { - byte = get_byte(bs); - lattr |= (byte & 0x7F) << shift; - shift += 7; + byte = get_byte(bs); + lattr |= (byte & 0x7F) << shift; + shift += 7; } while (byte & 0x80); ldata->lattr = lattr & 0xFFFF; ldata->trusted = (lattr & 0x10000) != 0; @@ -975,70 +975,70 @@ static void resizeline(Terminal *term, termline *line, int cols) if (line->cols != cols) { - oldcols = line->cols; + oldcols = line->cols; - /* - * This line is the wrong length, which probably means it - * hasn't been accessed since a resize. Resize it now. - * - * First, go through all the characters that will be thrown - * out in the resize (if we're shrinking the line) and - * return their cc lists to the cc free list. - */ - for (i = cols; i < oldcols; i++) - clear_cc(line, i); + /* + * This line is the wrong length, which probably means it + * hasn't been accessed since a resize. Resize it now. + * + * First, go through all the characters that will be thrown + * out in the resize (if we're shrinking the line) and + * return their cc lists to the cc free list. + */ + for (i = cols; i < oldcols; i++) + clear_cc(line, i); - /* - * If we're shrinking the line, we now bodily move the - * entire cc section from where it started to where it now - * needs to be. (We have to do this before the resize, so - * that the data we're copying is still there. However, if - * we're expanding, we have to wait until _after_ the - * resize so that the space we're copying into is there.) - */ - if (cols < oldcols) - memmove(line->chars + cols, line->chars + oldcols, - (line->size - line->cols) * TSIZE); + /* + * If we're shrinking the line, we now bodily move the + * entire cc section from where it started to where it now + * needs to be. (We have to do this before the resize, so + * that the data we're copying is still there. However, if + * we're expanding, we have to wait until _after_ the + * resize so that the space we're copying into is there.) + */ + if (cols < oldcols) + memmove(line->chars + cols, line->chars + oldcols, + (line->size - line->cols) * TSIZE); - /* - * Now do the actual resize, leaving the _same_ amount of - * cc space as there was to begin with. - */ - line->size += cols - oldcols; - line->chars = sresize(line->chars, line->size, TTYPE); - line->cols = cols; + /* + * Now do the actual resize, leaving the _same_ amount of + * cc space as there was to begin with. + */ + line->size += cols - oldcols; + line->chars = sresize(line->chars, line->size, TTYPE); + line->cols = cols; - /* - * If we're expanding the line, _now_ we move the cc - * section. - */ - if (cols > oldcols) - memmove(line->chars + cols, line->chars + oldcols, - (line->size - line->cols) * TSIZE); + /* + * If we're expanding the line, _now_ we move the cc + * section. + */ + if (cols > oldcols) + memmove(line->chars + cols, line->chars + oldcols, + (line->size - line->cols) * TSIZE); - /* - * Go through what's left of the original line, and adjust - * the first cc_next pointer in each list. (All the - * subsequent ones are still valid because they are - * relative offsets within the cc block.) Also do the same - * to the head of the cc_free list. - */ - for (i = 0; i < oldcols && i < cols; i++) - if (line->chars[i].cc_next) - line->chars[i].cc_next += cols - oldcols; - if (line->cc_free) - line->cc_free += cols - oldcols; + /* + * Go through what's left of the original line, and adjust + * the first cc_next pointer in each list. (All the + * subsequent ones are still valid because they are + * relative offsets within the cc block.) Also do the same + * to the head of the cc_free list. + */ + for (i = 0; i < oldcols && i < cols; i++) + if (line->chars[i].cc_next) + line->chars[i].cc_next += cols - oldcols; + if (line->cc_free) + line->cc_free += cols - oldcols; - /* - * And finally fill in the new space with erase chars. (We - * don't have to worry about cc lists here, because we - * _know_ the erase char doesn't have one.) - */ - for (i = oldcols; i < cols; i++) - line->chars[i] = term->basic_erase_char; + /* + * And finally fill in the new space with erase chars. (We + * don't have to worry about cc lists here, because we + * _know_ the erase char doesn't have one.) + */ + for (i = oldcols; i < cols; i++) + line->chars[i] = term->basic_erase_char; #ifdef TERM_CC_DIAGS - cc_check(line); + cc_check(line); #endif } } @@ -1050,8 +1050,8 @@ static int sblines(Terminal *term) { int sblines = count234(term->scrollback); if (term->erase_to_scrollback && - term->alt_which && term->alt_screen) { - sblines += term->alt_sblines; + term->alt_which && term->alt_screen) { + sblines += term->alt_sblines; } return sblines; } @@ -1088,33 +1088,33 @@ static termline *lineptr(Terminal *term, int y, int lineno, int screen) int treeindex; if (y >= 0) { - whichtree = term->screen; - treeindex = y; + whichtree = term->screen; + treeindex = y; } else { - int altlines = 0; + int altlines = 0; - assert(!screen); + assert(!screen); - if (term->erase_to_scrollback && - term->alt_which && term->alt_screen) { - altlines = term->alt_sblines; - } - if (y < -altlines) { - whichtree = term->scrollback; - treeindex = y + altlines + count234(term->scrollback); - } else { - whichtree = term->alt_screen; - treeindex = y + term->alt_sblines; - /* treeindex = y + count234(term->alt_screen); */ - } + if (term->erase_to_scrollback && + term->alt_which && term->alt_screen) { + altlines = term->alt_sblines; + } + if (y < -altlines) { + whichtree = term->scrollback; + treeindex = y + altlines + count234(term->scrollback); + } else { + whichtree = term->alt_screen; + treeindex = y + term->alt_sblines; + /* treeindex = y + count234(term->alt_screen); */ + } } if (whichtree == term->scrollback) { - compressed_scrollback_line *cline = index234(whichtree, treeindex); + compressed_scrollback_line *cline = index234(whichtree, treeindex); if (!cline) null_line_error(term, y, lineno, whichtree, treeindex, "cline"); - line = decompressline(cline); + line = decompressline(cline); } else { - line = index234(whichtree, treeindex); + line = index234(whichtree, treeindex); } /* We assume that we don't screw up and retrieve something out of range. */ @@ -1173,34 +1173,34 @@ static void term_timer(void *ctx, unsigned long now) bool update = false; if (term->tblink_pending && now == term->next_tblink) { - term->tblinker = !term->tblinker; - term->tblink_pending = false; - term_schedule_tblink(term); - update = true; + term->tblinker = !term->tblinker; + term->tblink_pending = false; + term_schedule_tblink(term); + update = true; } if (term->cblink_pending && now == term->next_cblink) { - term->cblinker = !term->cblinker; - term->cblink_pending = false; - term_schedule_cblink(term); - update = true; + term->cblinker = !term->cblinker; + term->cblink_pending = false; + term_schedule_cblink(term); + update = true; } if (term->in_vbell && now == term->vbell_end) { - term->in_vbell = false; - update = true; + term->in_vbell = false; + update = true; } if (update || - (term->window_update_pending && now == term->next_update)) - term_update(term); + (term->window_update_pending && now == term->next_update)) + term_update(term); } static void term_schedule_update(Terminal *term) { if (!term->window_update_pending) { - term->window_update_pending = true; - term->next_update = schedule_timer(UPDATE_DELAY, term_timer, term); + term->window_update_pending = true; + term->next_update = schedule_timer(UPDATE_DELAY, term_timer, term); } } @@ -1221,12 +1221,12 @@ static void seen_disp_event(Terminal *term) static void term_schedule_tblink(Terminal *term) { if (term->blink_is_real) { - if (!term->tblink_pending) - term->next_tblink = schedule_timer(TBLINK_DELAY, term_timer, term); - term->tblink_pending = true; + if (!term->tblink_pending) + term->next_tblink = schedule_timer(TBLINK_DELAY, term_timer, term); + term->tblink_pending = true; } else { - term->tblinker = true; /* reset when not in use */ - term->tblink_pending = false; + term->tblinker = true; /* reset when not in use */ + term->tblink_pending = false; } } @@ -1236,12 +1236,12 @@ static void term_schedule_tblink(Terminal *term) static void term_schedule_cblink(Terminal *term) { if (term->blink_cur && term->has_focus) { - if (!term->cblink_pending) - term->next_cblink = schedule_timer(CBLINK_DELAY, term_timer, term); - term->cblink_pending = true; + if (!term->cblink_pending) + term->next_cblink = schedule_timer(CBLINK_DELAY, term_timer, term); + term->cblink_pending = true; } else { - term->cblinker = true; /* reset when not in use */ - term->cblink_pending = false; + term->cblinker = true; /* reset when not in use */ + term->cblink_pending = false; } } @@ -1260,21 +1260,21 @@ static void term_reset_cblink(Terminal *term) * Call to begin a visual bell. */ static void term_schedule_vbell(Terminal *term, bool already_started, - long startpoint) + long startpoint) { long ticks_already_gone; if (already_started) - ticks_already_gone = GETTICKCOUNT() - startpoint; + ticks_already_gone = GETTICKCOUNT() - startpoint; else - ticks_already_gone = 0; + ticks_already_gone = 0; if (ticks_already_gone < VBELL_DELAY) { - term->in_vbell = true; - term->vbell_end = schedule_timer(VBELL_DELAY - ticks_already_gone, - term_timer, term); + term->in_vbell = true; + term->vbell_end = schedule_timer(VBELL_DELAY - ticks_already_gone, + term_timer, term); } else { - term->in_vbell = false; + term->in_vbell = false; } } @@ -1291,13 +1291,13 @@ static void power_on(Terminal *term, bool clear) term->alt_savecurs.x = term->alt_savecurs.y = 0; term->alt_t = term->marg_t = 0; if (term->rows != -1) - term->alt_b = term->marg_b = term->rows - 1; + term->alt_b = term->marg_b = term->rows - 1; else - term->alt_b = term->marg_b = 0; + term->alt_b = term->marg_b = 0; if (term->cols != -1) { - int i; - for (i = 0; i < term->cols; i++) - term->tabs[i] = (i % 8 == 0 ? true : false); + int i; + for (i = 0; i < term->cols; i++) + term->tabs[i] = (i % 8 == 0 ? true : false); } term->alt_om = term->dec_om = conf_get_bool(term->conf, CONF_dec_om); term->alt_ins = false; @@ -1322,7 +1322,7 @@ static void power_on(Terminal *term, bool clear) term->cursor_on = true; term->big_cursor = false; term->default_attr = term->save_attr = - term->alt_save_attr = term->curr_attr = ATTR_DEFAULT; + term->alt_save_attr = term->curr_attr = ATTR_DEFAULT; term->curr_truecolour.fg = term->curr_truecolour.bg = optionalrgb_none; term->save_truecolour = term->alt_save_truecolour = term->curr_truecolour; term->app_cursor_keys = conf_get_bool(term->conf, CONF_app_cursor); @@ -1339,23 +1339,23 @@ static void power_on(Terminal *term, bool clear) term->bracketed_paste = false; term->srm_echo = false; { - int i; - for (i = 0; i < 256; i++) - term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i); + int i; + for (i = 0; i < 256; i++) + term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i); } if (term->screen) { - swap_screen(term, 1, false, false); - erase_lots(term, false, true, true); - swap_screen(term, 0, false, false); - if (clear) - erase_lots(term, false, true, true); - term->curs.y = find_last_nonempty_line(term, term->screen) + 1; - if (term->curs.y == term->rows) { - term->curs.y--; - scroll(term, 0, term->rows - 1, 1, true); - } + swap_screen(term, 1, false, false); + erase_lots(term, false, true, true); + swap_screen(term, 0, false, false); + if (clear) + erase_lots(term, false, true, true); + term->curs.y = find_last_nonempty_line(term, term->screen) + 1; + if (term->curs.y == term->rows) { + term->curs.y--; + scroll(term, 0, term->rows - 1, 1, true); + } } else { - term->curs.y = 0; + term->curs.y = 0; } term->curs.x = 0; term_schedule_tblink(term); @@ -1370,19 +1370,19 @@ void term_update(Terminal *term) term->window_update_pending = false; if (win_setup_draw_ctx(term->win)) { - bool need_sbar_update = term->seen_disp_event; - if (term->seen_disp_event && term->scroll_on_disp) { - term->disptop = 0; /* return to main screen */ - term->seen_disp_event = false; - need_sbar_update = true; - } + bool need_sbar_update = term->seen_disp_event; + if (term->seen_disp_event && term->scroll_on_disp) { + term->disptop = 0; /* return to main screen */ + term->seen_disp_event = false; + need_sbar_update = true; + } - if (need_sbar_update) - update_sbar(term); - do_paint(term); - win_set_cursor_pos( + if (need_sbar_update) + update_sbar(term); + do_paint(term); + win_set_cursor_pos( term->win, term->curs.x, term->curs.y - term->disptop); - win_free_draw_ctx(term->win); + win_free_draw_ctx(term->win); } } @@ -1401,9 +1401,9 @@ void term_seen_key_event(Terminal *term) */ term->beep_overloaded = false; while (term->beephead) { - struct beeptime *tmp = term->beephead; - term->beephead = tmp->next; - sfree(tmp); + struct beeptime *tmp = term->beephead; + term->beephead = tmp->next; + sfree(tmp); } term->beeptail = NULL; term->nbeeps = 0; @@ -1412,8 +1412,8 @@ void term_seen_key_event(Terminal *term) * Reset the scrollback on keypress, if we're doing that. */ if (term->scroll_on_key) { - term->disptop = 0; /* return to main screen */ - seen_disp_event(term); + term->disptop = 0; /* return to main screen */ + seen_disp_event(term); } } @@ -1423,8 +1423,8 @@ void term_seen_key_event(Terminal *term) void term_pwron(Terminal *term, bool clear) { power_on(term, clear); - if (term->ldisc) /* cause ldisc to notice changes */ - ldisc_echoedit_update(term->ldisc); + if (term->ldisc) /* cause ldisc to notice changes */ + ldisc_echoedit_update(term->ldisc); term->disptop = 0; deselect(term); term_update(term); @@ -1434,8 +1434,8 @@ static void set_erase_char(Terminal *term) { term->erase_char = term->basic_erase_char; if (term->use_bce) { - term->erase_char.attr = (term->curr_attr & - (ATTR_FGMASK | ATTR_BGMASK)); + term->erase_char.attr = (term->curr_attr & + (ATTR_FGMASK | ATTR_BGMASK)); term->erase_char.truecolour.bg = term->curr_truecolour.bg; } } @@ -1494,22 +1494,22 @@ void term_copy_stuff_from_conf(Terminal *term) * answerback string. */ { - char *answerback = conf_get_str(term->conf, CONF_answerback); - int maxlen = strlen(answerback); + char *answerback = conf_get_str(term->conf, CONF_answerback); + int maxlen = strlen(answerback); - term->answerback = snewn(maxlen, char); - term->answerbacklen = 0; + term->answerback = snewn(maxlen, char); + term->answerbacklen = 0; - while (*answerback) { - char *n; - char c = ctrlparse(answerback, &n); - if (n) { - term->answerback[term->answerbacklen++] = c; - answerback = n; - } else { - term->answerback[term->answerbacklen++] = *answerback++; - } - } + while (*answerback) { + char *n; + char c = ctrlparse(answerback, &n); + if (n) { + term->answerback[term->answerbacklen++] = c; + answerback = n; + } else { + term->answerback[term->answerbacklen++] = *answerback++; + } + } } } @@ -1532,68 +1532,68 @@ void term_reconfig(Terminal *term, Conf *conf) int i; reset_wrap = (conf_get_bool(term->conf, CONF_wrap_mode) != - conf_get_bool(conf, CONF_wrap_mode)); + conf_get_bool(conf, CONF_wrap_mode)); reset_decom = (conf_get_bool(term->conf, CONF_dec_om) != - conf_get_bool(conf, CONF_dec_om)); + conf_get_bool(conf, CONF_dec_om)); reset_bce = (conf_get_bool(term->conf, CONF_bce) != - conf_get_bool(conf, CONF_bce)); + conf_get_bool(conf, CONF_bce)); reset_tblink = (conf_get_bool(term->conf, CONF_blinktext) != - conf_get_bool(conf, CONF_blinktext)); + conf_get_bool(conf, CONF_blinktext)); reset_charclass = false; for (i = 0; i < 256; i++) - if (conf_get_int_int(term->conf, CONF_wordness, i) != - conf_get_int_int(conf, CONF_wordness, i)) - reset_charclass = true; + if (conf_get_int_int(term->conf, CONF_wordness, i) != + conf_get_int_int(conf, CONF_wordness, i)) + reset_charclass = true; /* * If the bidi or shaping settings have changed, flush the bidi * cache completely. */ if (conf_get_bool(term->conf, CONF_no_arabicshaping) != - conf_get_bool(conf, CONF_no_arabicshaping) || - conf_get_bool(term->conf, CONF_no_bidi) != - conf_get_bool(conf, CONF_no_bidi)) { - for (i = 0; i < term->bidi_cache_size; i++) { - sfree(term->pre_bidi_cache[i].chars); - sfree(term->post_bidi_cache[i].chars); - term->pre_bidi_cache[i].width = -1; - term->pre_bidi_cache[i].chars = NULL; - term->post_bidi_cache[i].width = -1; - term->post_bidi_cache[i].chars = NULL; - } + conf_get_bool(conf, CONF_no_arabicshaping) || + conf_get_bool(term->conf, CONF_no_bidi) != + conf_get_bool(conf, CONF_no_bidi)) { + for (i = 0; i < term->bidi_cache_size; i++) { + sfree(term->pre_bidi_cache[i].chars); + sfree(term->post_bidi_cache[i].chars); + term->pre_bidi_cache[i].width = -1; + term->pre_bidi_cache[i].chars = NULL; + term->post_bidi_cache[i].width = -1; + term->post_bidi_cache[i].chars = NULL; + } } conf_free(term->conf); term->conf = conf_copy(conf); if (reset_wrap) - term->alt_wrap = term->wrap = conf_get_bool(term->conf, CONF_wrap_mode); + term->alt_wrap = term->wrap = conf_get_bool(term->conf, CONF_wrap_mode); if (reset_decom) - term->alt_om = term->dec_om = conf_get_bool(term->conf, CONF_dec_om); + term->alt_om = term->dec_om = conf_get_bool(term->conf, CONF_dec_om); if (reset_bce) { - term->use_bce = conf_get_bool(term->conf, CONF_bce); - set_erase_char(term); + term->use_bce = conf_get_bool(term->conf, CONF_bce); + set_erase_char(term); } if (reset_tblink) { - term->blink_is_real = conf_get_bool(term->conf, CONF_blinktext); + term->blink_is_real = conf_get_bool(term->conf, CONF_blinktext); } if (reset_charclass) - for (i = 0; i < 256; i++) - term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i); + for (i = 0; i < 256; i++) + term->wordness[i] = conf_get_int_int(term->conf, CONF_wordness, i); if (conf_get_bool(term->conf, CONF_no_alt_screen)) - swap_screen(term, 0, false, false); + swap_screen(term, 0, false, false); if (conf_get_bool(term->conf, CONF_no_mouse_rep)) { - term->xterm_mouse = 0; - win_set_raw_mouse_mode(term->win, 0); + term->xterm_mouse = 0; + win_set_raw_mouse_mode(term->win, 0); } if (conf_get_bool(term->conf, CONF_no_remote_charset)) { - term->cset_attr[0] = term->cset_attr[1] = CSET_ASCII; - term->sco_acs = term->alt_sco_acs = 0; - term->utf = false; + term->cset_attr[0] = term->cset_attr[1] = CSET_ASCII; + term->sco_acs = term->alt_sco_acs = 0; + term->utf = false; } if (!conf_get_str(term->conf, CONF_printer)) { - term_print_finish(term); + term_print_finish(term); } term_schedule_tblink(term); term_schedule_cblink(term); @@ -1618,7 +1618,7 @@ void term_clrsb(Terminal *term) * Clear the actual scrollback. */ while ((line = delpos234(term->scrollback, 0)) != NULL) { - sfree(line); /* this is compressed data, not a termline */ + sfree(line); /* this is compressed data, not a termline */ } /* @@ -1758,27 +1758,27 @@ void term_free(Terminal *term) int i; while ((line = delpos234(term->scrollback, 0)) != NULL) - sfree(line); /* compressed data, not a termline */ + sfree(line); /* compressed data, not a termline */ freetree234(term->scrollback); while ((line = delpos234(term->screen, 0)) != NULL) - freetermline(line); + freetermline(line); freetree234(term->screen); while ((line = delpos234(term->alt_screen, 0)) != NULL) - freetermline(line); + freetermline(line); freetree234(term->alt_screen); if (term->disptext) { - for (i = 0; i < term->rows; i++) - freetermline(term->disptext[i]); + for (i = 0; i < term->rows; i++) + freetermline(term->disptext[i]); } sfree(term->disptext); while (term->beephead) { - beep = term->beephead; - term->beephead = beep->next; - sfree(beep); + beep = term->beephead; + term->beephead = beep->next; + sfree(beep); } bufchain_clear(&term->inbuf); if(term->print_job) - printer_finish_job(term->print_job); + printer_finish_job(term->print_job); bufchain_clear(&term->printer_buf); sfree(term->paste_buffer); sfree(term->ltemp); @@ -1787,8 +1787,8 @@ void term_free(Terminal *term) sfree(term->answerback); for (i = 0; i < term->bidi_cache_size; i++) { - sfree(term->pre_bidi_cache[i].chars); - sfree(term->post_bidi_cache[i].chars); + sfree(term->pre_bidi_cache[i].chars); + sfree(term->post_bidi_cache[i].chars); sfree(term->post_bidi_cache[i].forward); sfree(term->post_bidi_cache[i].backward); } @@ -1822,8 +1822,8 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) int save_alt_which = term->alt_which; if (newrows == term->rows && newcols == term->cols && - newsavelines == term->savelines) - return; /* nothing to do */ + newsavelines == term->savelines) + return; /* nothing to do */ /* Behave sensibly if we're given zero (or negative) rows/cols */ @@ -1837,10 +1837,10 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) term->alt_b = term->marg_b = newrows - 1; if (term->rows == -1) { - term->scrollback = newtree234(NULL); - term->screen = newtree234(NULL); - term->tempsblines = 0; - term->rows = 0; + term->scrollback = newtree234(NULL); + term->screen = newtree234(NULL); + term->tempsblines = 0; + term->rows = 0; } /* @@ -1848,7 +1848,7 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) * lines around within our data structures, because lineptr() * will take care of resizing each individual line if * necessary. So: - * + * * - If the new screen is longer, we shunt lines in from temporary * scrollback if possible, otherwise we add new blank lines at * the bottom. @@ -1857,7 +1857,7 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) * the bottom if possible, otherwise shunt lines above the cursor * to scrollback if possible, otherwise delete lines below the * cursor. - * + * * - Then, if the new scrollback length is less than the * amount of scrollback we actually have, we must throw some * away. @@ -1866,57 +1866,57 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) /* Do this loop to expand the screen if newrows > rows */ assert(term->rows == count234(term->screen)); while (term->rows < newrows) { - if (term->tempsblines > 0) { - compressed_scrollback_line *cline; - /* Insert a line from the scrollback at the top of the screen. */ - assert(sblen >= term->tempsblines); - cline = delpos234(term->scrollback, --sblen); - line = decompressline(cline); - sfree(cline); - line->temporary = false; /* reconstituted line is now real */ - term->tempsblines -= 1; - addpos234(term->screen, line, 0); - term->curs.y += 1; - term->savecurs.y += 1; - term->alt_y += 1; - term->alt_savecurs.y += 1; - } else { - /* Add a new blank line at the bottom of the screen. */ - line = newtermline(term, newcols, false); - addpos234(term->screen, line, count234(term->screen)); - } - term->rows += 1; + if (term->tempsblines > 0) { + compressed_scrollback_line *cline; + /* Insert a line from the scrollback at the top of the screen. */ + assert(sblen >= term->tempsblines); + cline = delpos234(term->scrollback, --sblen); + line = decompressline(cline); + sfree(cline); + line->temporary = false; /* reconstituted line is now real */ + term->tempsblines -= 1; + addpos234(term->screen, line, 0); + term->curs.y += 1; + term->savecurs.y += 1; + term->alt_y += 1; + term->alt_savecurs.y += 1; + } else { + /* Add a new blank line at the bottom of the screen. */ + line = newtermline(term, newcols, false); + addpos234(term->screen, line, count234(term->screen)); + } + term->rows += 1; } /* Do this loop to shrink the screen if newrows < rows */ while (term->rows > newrows) { - if (term->curs.y < term->rows - 1) { - /* delete bottom row, unless it contains the cursor */ + if (term->curs.y < term->rows - 1) { + /* delete bottom row, unless it contains the cursor */ line = delpos234(term->screen, term->rows - 1); freetermline(line); - } else { - /* push top row to scrollback */ - line = delpos234(term->screen, 0); - addpos234(term->scrollback, compressline(line), sblen++); - freetermline(line); - term->tempsblines += 1; - term->curs.y -= 1; - term->savecurs.y -= 1; - term->alt_y -= 1; - term->alt_savecurs.y -= 1; - } - term->rows -= 1; + } else { + /* push top row to scrollback */ + line = delpos234(term->screen, 0); + addpos234(term->scrollback, compressline(line), sblen++); + freetermline(line); + term->tempsblines += 1; + term->curs.y -= 1; + term->savecurs.y -= 1; + term->alt_y -= 1; + term->alt_savecurs.y -= 1; + } + term->rows -= 1; } assert(term->rows == newrows); assert(count234(term->screen) == newrows); /* Delete any excess lines from the scrollback. */ while (sblen > newsavelines) { - line = delpos234(term->scrollback, 0); - sfree(line); - sblen--; + line = delpos234(term->scrollback, 0); + sfree(line); + sblen--; } if (sblen < term->tempsblines) - term->tempsblines = sblen; + term->tempsblines = sblen; assert(count234(term->scrollback) <= newsavelines); assert(count234(term->scrollback) >= term->tempsblines); term->disptop = 0; @@ -1924,13 +1924,13 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) /* Make a new displayed text buffer. */ newdisp = snewn(newrows, termline *); for (i = 0; i < newrows; i++) { - newdisp[i] = newtermline(term, newcols, false); - for (j = 0; j < newcols; j++) - newdisp[i]->chars[j].attr = ATTR_INVALID; + newdisp[i] = newtermline(term, newcols, false); + for (j = 0; j < newcols; j++) + newdisp[i]->chars[j].attr = ATTR_INVALID; } if (term->disptext) { - for (i = 0; i < oldrows; i++) - freetermline(term->disptext[i]); + for (i = 0; i < oldrows; i++) + freetermline(term->disptext[i]); } sfree(term->disptext); term->disptext = newdisp; @@ -1939,49 +1939,49 @@ void term_size(Terminal *term, int newrows, int newcols, int newsavelines) /* Make a new alternate screen. */ newalt = newtree234(NULL); for (i = 0; i < newrows; i++) { - line = newtermline(term, newcols, true); - addpos234(newalt, line, i); + line = newtermline(term, newcols, true); + addpos234(newalt, line, i); } if (term->alt_screen) { - while (NULL != (line = delpos234(term->alt_screen, 0))) - freetermline(line); - freetree234(term->alt_screen); + while (NULL != (line = delpos234(term->alt_screen, 0))) + freetermline(line); + freetree234(term->alt_screen); } term->alt_screen = newalt; term->alt_sblines = 0; term->tabs = sresize(term->tabs, newcols, unsigned char); { - int i; - for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++) - term->tabs[i] = (i % 8 == 0 ? true : false); + int i; + for (i = (term->cols > 0 ? term->cols : 0); i < newcols; i++) + term->tabs[i] = (i % 8 == 0 ? true : false); } /* Check that the cursor positions are still valid. */ if (term->savecurs.y < 0) - term->savecurs.y = 0; + term->savecurs.y = 0; if (term->savecurs.y >= newrows) - term->savecurs.y = newrows - 1; + term->savecurs.y = newrows - 1; if (term->savecurs.x >= newcols) - term->savecurs.x = newcols - 1; + term->savecurs.x = newcols - 1; if (term->alt_savecurs.y < 0) - term->alt_savecurs.y = 0; + term->alt_savecurs.y = 0; if (term->alt_savecurs.y >= newrows) - term->alt_savecurs.y = newrows - 1; + term->alt_savecurs.y = newrows - 1; if (term->alt_savecurs.x >= newcols) - term->alt_savecurs.x = newcols - 1; + term->alt_savecurs.x = newcols - 1; if (term->curs.y < 0) - term->curs.y = 0; + term->curs.y = 0; if (term->curs.y >= newrows) - term->curs.y = newrows - 1; + term->curs.y = newrows - 1; if (term->curs.x >= newcols) - term->curs.x = newcols - 1; + term->curs.x = newcols - 1; if (term->alt_y < 0) - term->alt_y = 0; + term->alt_y = 0; if (term->alt_y >= newrows) - term->alt_y = newrows - 1; + term->alt_y = newrows - 1; if (term->alt_x >= newcols) - term->alt_x = newcols - 1; + term->alt_x = newcols - 1; term->alt_x = term->alt_y = 0; term->wrapnext = false; term->alt_wnext = false; @@ -2011,17 +2011,17 @@ void term_provide_backend(Terminal *term, Backend *backend) /* Find the bottom line on the screen that has any content. * If only the top line has content, returns 0. * If no lines have content, return -1. - */ + */ static int find_last_nonempty_line(Terminal * term, tree234 * screen) { int i; for (i = count234(screen) - 1; i >= 0; i--) { - termline *line = index234(screen, i); - int j; - for (j = 0; j < line->cols; j++) - if (!termchars_equal(&line->chars[j], &term->erase_char)) - break; - if (j != line->cols) break; + termline *line = index234(screen, i); + int j; + for (j = 0; j < line->cols; j++) + if (!termchars_equal(&line->chars[j], &term->erase_char)) + break; + if (j != line->cols) break; } return i; } @@ -2043,55 +2043,55 @@ static void swap_screen(Terminal *term, int which, tree234 *ttr; if (!which) - reset = false; /* do no weird resetting if which==0 */ + reset = false; /* do no weird resetting if which==0 */ if (which != term->alt_which) { - term->alt_which = which; + term->alt_which = which; - ttr = term->alt_screen; - term->alt_screen = term->screen; - term->screen = ttr; - term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1; - t = term->curs.x; - if (!reset && !keep_cur_pos) - term->curs.x = term->alt_x; - term->alt_x = t; - t = term->curs.y; - if (!reset && !keep_cur_pos) - term->curs.y = term->alt_y; - term->alt_y = t; - t = term->marg_t; - if (!reset) term->marg_t = term->alt_t; - term->alt_t = t; - t = term->marg_b; - if (!reset) term->marg_b = term->alt_b; - term->alt_b = t; - bt = term->dec_om; - if (!reset) term->dec_om = term->alt_om; - term->alt_om = bt; - bt = term->wrap; - if (!reset) term->wrap = term->alt_wrap; - term->alt_wrap = bt; - bt = term->wrapnext; - if (!reset) term->wrapnext = term->alt_wnext; - term->alt_wnext = bt; - bt = term->insert; - if (!reset) term->insert = term->alt_ins; - term->alt_ins = bt; - t = term->cset; - if (!reset) term->cset = term->alt_cset; - term->alt_cset = t; - bt = term->utf; - if (!reset) term->utf = term->alt_utf; - term->alt_utf = bt; - t = term->sco_acs; - if (!reset) term->sco_acs = term->alt_sco_acs; - term->alt_sco_acs = t; + ttr = term->alt_screen; + term->alt_screen = term->screen; + term->screen = ttr; + term->alt_sblines = find_last_nonempty_line(term, term->alt_screen) + 1; + t = term->curs.x; + if (!reset && !keep_cur_pos) + term->curs.x = term->alt_x; + term->alt_x = t; + t = term->curs.y; + if (!reset && !keep_cur_pos) + term->curs.y = term->alt_y; + term->alt_y = t; + t = term->marg_t; + if (!reset) term->marg_t = term->alt_t; + term->alt_t = t; + t = term->marg_b; + if (!reset) term->marg_b = term->alt_b; + term->alt_b = t; + bt = term->dec_om; + if (!reset) term->dec_om = term->alt_om; + term->alt_om = bt; + bt = term->wrap; + if (!reset) term->wrap = term->alt_wrap; + term->alt_wrap = bt; + bt = term->wrapnext; + if (!reset) term->wrapnext = term->alt_wnext; + term->alt_wnext = bt; + bt = term->insert; + if (!reset) term->insert = term->alt_ins; + term->alt_ins = bt; + t = term->cset; + if (!reset) term->cset = term->alt_cset; + term->alt_cset = t; + bt = term->utf; + if (!reset) term->utf = term->alt_utf; + term->alt_utf = bt; + t = term->sco_acs; + if (!reset) term->sco_acs = term->alt_sco_acs; + term->alt_sco_acs = t; - tp = term->savecurs; - if (!reset && !keep_cur_pos) - term->savecurs = term->alt_savecurs; - term->alt_savecurs = tp; + tp = term->savecurs; + if (!reset && !keep_cur_pos) + term->savecurs = term->alt_savecurs; + term->alt_savecurs = tp; t = term->save_cset; if (!reset && !keep_cur_pos) term->save_cset = term->alt_save_cset; @@ -2123,10 +2123,10 @@ static void swap_screen(Terminal *term, int which, } if (reset && term->screen) { - /* - * Yes, this _is_ supposed to honour background-colour-erase. - */ - erase_lots(term, false, true, true); + /* + * Yes, this _is_ supposed to honour background-colour-erase. + */ + erase_lots(term, false, true, true); } } @@ -2147,7 +2147,7 @@ static void update_sbar(Terminal *term) static void check_selection(Terminal *term, pos from, pos to) { if (poslt(from, term->selend) && poslt(term->selstart, to)) - deselect(term); + deselect(term); } static void clear_line(Terminal *term, termline *line) @@ -2184,7 +2184,7 @@ static void scroll(Terminal *term, int topline, int botline, int seltop, scrollwinsize; if (topline != 0 || term->alt_which != 0) - sb = false; + sb = false; scrollwinsize = botline - topline + 1; @@ -2192,116 +2192,116 @@ static void scroll(Terminal *term, int topline, int botline, lines = -lines; if (lines > scrollwinsize) lines = scrollwinsize; - while (lines-- > 0) { - line = delpos234(term->screen, botline); + while (lines-- > 0) { + line = delpos234(term->screen, botline); resizeline(term, line, term->cols); clear_line(term, line); - addpos234(term->screen, line, topline); + addpos234(term->screen, line, topline); - if (term->selstart.y >= topline && term->selstart.y <= botline) { - term->selstart.y++; - if (term->selstart.y > botline) { - term->selstart.y = botline + 1; - term->selstart.x = 0; - } - } - if (term->selend.y >= topline && term->selend.y <= botline) { - term->selend.y++; - if (term->selend.y > botline) { - term->selend.y = botline + 1; - term->selend.x = 0; - } - } - } + if (term->selstart.y >= topline && term->selstart.y <= botline) { + term->selstart.y++; + if (term->selstart.y > botline) { + term->selstart.y = botline + 1; + term->selstart.x = 0; + } + } + if (term->selend.y >= topline && term->selend.y <= botline) { + term->selend.y++; + if (term->selend.y > botline) { + term->selend.y = botline + 1; + term->selend.x = 0; + } + } + } } else { if (lines > scrollwinsize) lines = scrollwinsize; - while (lines-- > 0) { - line = delpos234(term->screen, topline); + while (lines-- > 0) { + line = delpos234(term->screen, topline); #ifdef TERM_CC_DIAGS - cc_check(line); + cc_check(line); #endif - if (sb && term->savelines > 0) { - int sblen = count234(term->scrollback); - /* - * We must add this line to the scrollback. We'll - * remove a line from the top of the scrollback if - * the scrollback is full. - */ - if (sblen == term->savelines) { - unsigned char *cline; + if (sb && term->savelines > 0) { + int sblen = count234(term->scrollback); + /* + * We must add this line to the scrollback. We'll + * remove a line from the top of the scrollback if + * the scrollback is full. + */ + if (sblen == term->savelines) { + unsigned char *cline; - sblen--; - cline = delpos234(term->scrollback, 0); - sfree(cline); - } else - term->tempsblines += 1; + sblen--; + cline = delpos234(term->scrollback, 0); + sfree(cline); + } else + term->tempsblines += 1; - addpos234(term->scrollback, compressline(line), sblen); + addpos234(term->scrollback, compressline(line), sblen); - /* now `line' itself can be reused as the bottom line */ + /* now `line' itself can be reused as the bottom line */ - /* - * If the user is currently looking at part of the - * scrollback, and they haven't enabled any options - * that are going to reset the scrollback as a - * result of this movement, then the chances are - * they'd like to keep looking at the same line. So - * we move their viewpoint at the same rate as the - * scroll, at least until their viewpoint hits the - * top end of the scrollback buffer, at which point - * we don't have the choice any more. - * - * Thanks to Jan Holmen Holsten for the idea and - * initial implementation. - */ - if (term->disptop > -term->savelines && term->disptop < 0) - term->disptop--; - } + /* + * If the user is currently looking at part of the + * scrollback, and they haven't enabled any options + * that are going to reset the scrollback as a + * result of this movement, then the chances are + * they'd like to keep looking at the same line. So + * we move their viewpoint at the same rate as the + * scroll, at least until their viewpoint hits the + * top end of the scrollback buffer, at which point + * we don't have the choice any more. + * + * Thanks to Jan Holmen Holsten for the idea and + * initial implementation. + */ + if (term->disptop > -term->savelines && term->disptop < 0) + term->disptop--; + } resizeline(term, line, term->cols); clear_line(term, line); check_trust_status(term, line); - addpos234(term->screen, line, botline); + addpos234(term->screen, line, botline); - /* - * If the selection endpoints move into the scrollback, - * we keep them moving until they hit the top. However, - * of course, if the line _hasn't_ moved into the - * scrollback then we don't do this, and cut them off - * at the top of the scroll region. - * - * This applies to selstart and selend (for an existing - * selection), and also selanchor (for one being - * selected as we speak). - */ - seltop = sb ? -term->savelines : topline; + /* + * If the selection endpoints move into the scrollback, + * we keep them moving until they hit the top. However, + * of course, if the line _hasn't_ moved into the + * scrollback then we don't do this, and cut them off + * at the top of the scroll region. + * + * This applies to selstart and selend (for an existing + * selection), and also selanchor (for one being + * selected as we speak). + */ + seltop = sb ? -term->savelines : topline; - if (term->selstate != NO_SELECTION) { - if (term->selstart.y >= seltop && - term->selstart.y <= botline) { - term->selstart.y--; - if (term->selstart.y < seltop) { - term->selstart.y = seltop; - term->selstart.x = 0; - } - } - if (term->selend.y >= seltop && term->selend.y <= botline) { - term->selend.y--; - if (term->selend.y < seltop) { - term->selend.y = seltop; - term->selend.x = 0; - } - } - if (term->selanchor.y >= seltop && - term->selanchor.y <= botline) { - term->selanchor.y--; - if (term->selanchor.y < seltop) { - term->selanchor.y = seltop; - term->selanchor.x = 0; - } - } - } - } + if (term->selstate != NO_SELECTION) { + if (term->selstart.y >= seltop && + term->selstart.y <= botline) { + term->selstart.y--; + if (term->selstart.y < seltop) { + term->selstart.y = seltop; + term->selstart.x = 0; + } + } + if (term->selend.y >= seltop && term->selend.y <= botline) { + term->selend.y--; + if (term->selend.y < seltop) { + term->selend.y = seltop; + term->selend.x = 0; + } + } + if (term->selanchor.y >= seltop && + term->selanchor.y <= botline) { + term->selanchor.y--; + if (term->selanchor.y < seltop) { + term->selanchor.y = seltop; + term->selanchor.x = 0; + } + } + } + } } } @@ -2314,21 +2314,21 @@ static void scroll(Terminal *term, int topline, int botline, static void move(Terminal *term, int x, int y, int marg_clip) { if (x < 0) - x = 0; + x = 0; if (x >= term->cols) - x = term->cols - 1; + x = term->cols - 1; if (marg_clip) { - if ((term->curs.y >= term->marg_t || marg_clip == 2) && - y < term->marg_t) - y = term->marg_t; - if ((term->curs.y <= term->marg_b || marg_clip == 2) && - y > term->marg_b) - y = term->marg_b; + if ((term->curs.y >= term->marg_t || marg_clip == 2) && + y < term->marg_t) + y = term->marg_t; + if ((term->curs.y <= term->marg_b || marg_clip == 2) && + y > term->marg_b) + y = term->marg_b; } if (y < 0) - y = 0; + y = 0; if (y >= term->rows) - y = term->rows - 1; + y = term->rows - 1; term->curs.x = x; term->curs.y = y; term->wrapnext = false; @@ -2340,36 +2340,36 @@ static void move(Terminal *term, int x, int y, int marg_clip) static void save_cursor(Terminal *term, bool save) { if (save) { - term->savecurs = term->curs; - term->save_attr = term->curr_attr; - term->save_truecolour = term->curr_truecolour; - term->save_cset = term->cset; - term->save_utf = term->utf; - term->save_wnext = term->wrapnext; - term->save_csattr = term->cset_attr[term->cset]; - term->save_sco_acs = term->sco_acs; + term->savecurs = term->curs; + term->save_attr = term->curr_attr; + term->save_truecolour = term->curr_truecolour; + term->save_cset = term->cset; + term->save_utf = term->utf; + term->save_wnext = term->wrapnext; + term->save_csattr = term->cset_attr[term->cset]; + term->save_sco_acs = term->sco_acs; } else { - term->curs = term->savecurs; - /* Make sure the window hasn't shrunk since the save */ - if (term->curs.x >= term->cols) - term->curs.x = term->cols - 1; - if (term->curs.y >= term->rows) - term->curs.y = term->rows - 1; + term->curs = term->savecurs; + /* Make sure the window hasn't shrunk since the save */ + if (term->curs.x >= term->cols) + term->curs.x = term->cols - 1; + if (term->curs.y >= term->rows) + term->curs.y = term->rows - 1; - term->curr_attr = term->save_attr; - term->curr_truecolour = term->save_truecolour; - term->cset = term->save_cset; - term->utf = term->save_utf; - term->wrapnext = term->save_wnext; - /* - * wrapnext might reset to False if the x position is no - * longer at the rightmost edge. - */ - if (term->wrapnext && term->curs.x < term->cols-1) - term->wrapnext = false; - term->cset_attr[term->cset] = term->save_csattr; - term->sco_acs = term->save_sco_acs; - set_erase_char(term); + term->curr_attr = term->save_attr; + term->curr_truecolour = term->save_truecolour; + term->cset = term->save_cset; + term->utf = term->save_utf; + term->wrapnext = term->save_wnext; + /* + * wrapnext might reset to False if the x position is no + * longer at the rightmost edge. + */ + if (term->wrapnext && term->curs.x < term->cols-1) + term->wrapnext = false; + term->cset_attr[term->cset] = term->save_csattr; + term->sco_acs = term->save_sco_acs; + set_erase_char(term); } } @@ -2378,17 +2378,17 @@ static void save_cursor(Terminal *term, bool save) * only part of a line of text. It is used to mark the boundary * between two character positions, and it indicates that some sort * of effect is going to happen on only one side of that boundary. - * + * * The effect of this function is to check whether a CJK * double-width character is straddling the boundary, and to remove * it and replace it with two spaces if so. (Of course, one or * other of those spaces is then likely to be replaced with * something else again, as a result of whatever happens next.) - * + * * Also, if the boundary is at the right-hand _edge_ of the screen, * it implies something deliberate is being done to the rightmost * column position; hence we must clear LATTR_WRAPPED2. - * + * * The input to the function is the coordinates of the _second_ * character of the pair. */ @@ -2398,20 +2398,20 @@ static void check_boundary(Terminal *term, int x, int y) /* Validate input coordinates, just in case. */ if (x <= 0 || x > term->cols) - return; + return; ldata = scrlineptr(y); check_trust_status(term, ldata); check_line_size(term, ldata); if (x == term->cols) { - ldata->lattr &= ~LATTR_WRAPPED2; + ldata->lattr &= ~LATTR_WRAPPED2; } else { - if (ldata->chars[x].chr == UCSWIDE) { - clear_cc(ldata, x-1); - clear_cc(ldata, x); - ldata->chars[x-1].chr = ' ' | CSET_ASCII; - ldata->chars[x] = ldata->chars[x-1]; - } + if (ldata->chars[x].chr == UCSWIDE) { + clear_cc(ldata, x-1); + clear_cc(ldata, x); + ldata->chars[x-1].chr = ' ' | CSET_ASCII; + ldata->chars[x] = ldata->chars[x-1]; + } } } @@ -2420,24 +2420,24 @@ static void check_boundary(Terminal *term, int x, int y) * whole line, or parts thereof. */ static void erase_lots(Terminal *term, - bool line_only, bool from_begin, bool to_end) + bool line_only, bool from_begin, bool to_end) { pos start, end; bool erase_lattr; bool erasing_lines_from_top = false; if (line_only) { - start.y = term->curs.y; - start.x = 0; - end.y = term->curs.y + 1; - end.x = 0; - erase_lattr = false; + start.y = term->curs.y; + start.x = 0; + end.y = term->curs.y + 1; + end.x = 0; + erase_lattr = false; } else { - start.y = 0; - start.x = 0; - end.y = term->rows; - end.x = 0; - erase_lattr = true; + start.y = 0; + start.x = 0; + end.y = term->rows; + end.x = 0; + erase_lattr = true; } /* This is the endpoint of the clearing operation that is not @@ -2463,7 +2463,7 @@ static void erase_lots(Terminal *term, if (term->wrapnext) incpos(boundary); - start = boundary; + start = boundary; } if (!to_end) { /* @@ -2477,57 +2477,57 @@ static void erase_lots(Terminal *term, * should be careful of a straddling wide character. */ incpos(boundary); - end = boundary; + end = boundary; } if (!from_begin || !to_end) - check_boundary(term, boundary.x, boundary.y); + check_boundary(term, boundary.x, boundary.y); check_selection(term, start, end); /* Clear screen also forces a full window redraw, just in case. */ if (start.y == 0 && start.x == 0 && end.y == term->rows) - term_invalidate(term); + term_invalidate(term); /* Lines scrolled away shouldn't be brought back on if the terminal * resizes. */ if (start.y == 0 && start.x == 0 && end.x == 0 && erase_lattr) - erasing_lines_from_top = true; + erasing_lines_from_top = true; if (term->erase_to_scrollback && erasing_lines_from_top) { - /* If it's a whole number of lines, starting at the top, and - * we're fully erasing them, erase by scrolling and keep the - * lines in the scrollback. */ - int scrolllines = end.y; - if (end.y == term->rows) { - /* Shrink until we find a non-empty row.*/ - scrolllines = find_last_nonempty_line(term, term->screen) + 1; - } - if (scrolllines > 0) - scroll(term, 0, scrolllines - 1, scrolllines, true); + /* If it's a whole number of lines, starting at the top, and + * we're fully erasing them, erase by scrolling and keep the + * lines in the scrollback. */ + int scrolllines = end.y; + if (end.y == term->rows) { + /* Shrink until we find a non-empty row.*/ + scrolllines = find_last_nonempty_line(term, term->screen) + 1; + } + if (scrolllines > 0) + scroll(term, 0, scrolllines - 1, scrolllines, true); } else { - termline *ldata = scrlineptr(start.y); + termline *ldata = scrlineptr(start.y); check_trust_status(term, ldata); - while (poslt(start, end)) { + while (poslt(start, end)) { check_line_size(term, ldata); - if (start.x == term->cols) { - if (!erase_lattr) - ldata->lattr &= ~(LATTR_WRAPPED | LATTR_WRAPPED2); - else - ldata->lattr = LATTR_NORM; - } else { - copy_termchar(ldata, start.x, &term->erase_char); - } - if (incpos(start) && start.y < term->rows) { - ldata = scrlineptr(start.y); + if (start.x == term->cols) { + if (!erase_lattr) + ldata->lattr &= ~(LATTR_WRAPPED | LATTR_WRAPPED2); + else + ldata->lattr = LATTR_NORM; + } else { + copy_termchar(ldata, start.x, &term->erase_char); + } + if (incpos(start) && start.y < term->rows) { + ldata = scrlineptr(start.y); check_trust_status(term, ldata); - } - } + } + } } /* After an erase of lines from the top of the screen, we shouldn't * bring the lines back again if the terminal enlarges (since the user or * application has explicitly thrown them away). */ if (erasing_lines_from_top && !(term->alt_which)) - term->tempsblines = 0; + term->tempsblines = 0; } /* @@ -2543,7 +2543,7 @@ static void insch(Terminal *term, int n) n = (n < 0 ? -n : n); if (n > term->cols - term->curs.x) - n = term->cols - term->curs.x; + n = term->cols - term->curs.x; m = term->cols - term->curs.x - n; /* @@ -2585,23 +2585,23 @@ static void insch(Terminal *term, int n) check_boundary(term, term->curs.x, term->curs.y); if (dir < 0) - check_boundary(term, term->curs.x + n, term->curs.y); + check_boundary(term, term->curs.x + n, term->curs.y); ldata = scrlineptr(term->curs.y); check_trust_status(term, ldata); if (dir < 0) { - for (j = 0; j < m; j++) - move_termchar(ldata, - ldata->chars + term->curs.x + j, - ldata->chars + term->curs.x + j + n); - while (n--) - copy_termchar(ldata, term->curs.x + m++, &term->erase_char); + for (j = 0; j < m; j++) + move_termchar(ldata, + ldata->chars + term->curs.x + j, + ldata->chars + term->curs.x + j + n); + while (n--) + copy_termchar(ldata, term->curs.x + m++, &term->erase_char); } else { - for (j = m; j-- ;) - move_termchar(ldata, - ldata->chars + term->curs.x + j + n, - ldata->chars + term->curs.x + j); - while (n--) - copy_termchar(ldata, term->curs.x + n, &term->erase_char); + for (j = m; j-- ;) + move_termchar(ldata, + ldata->chars + term->curs.x + j + n, + ldata->chars + term->curs.x + j); + while (n--) + copy_termchar(ldata, term->curs.x + n, &term->erase_char); } } @@ -2612,126 +2612,126 @@ static void insch(Terminal *term, int n) static void toggle_mode(Terminal *term, int mode, int query, bool state) { if (query == 1) { - switch (mode) { - case 1: /* DECCKM: application cursor keys */ - term->app_cursor_keys = state; - break; - case 2: /* DECANM: VT52 mode */ - term->vt52_mode = !state; - if (term->vt52_mode) { - term->blink_is_real = false; - term->vt52_bold = false; - } else { - term->blink_is_real = term->blinktext; - } - term_schedule_tblink(term); - break; - case 3: /* DECCOLM: 80/132 columns */ - deselect(term); - if (!term->no_remote_resize) - win_request_resize(term->win, state ? 132 : 80, term->rows); - term->reset_132 = state; - term->alt_t = term->marg_t = 0; - term->alt_b = term->marg_b = term->rows - 1; - move(term, 0, 0, 0); - erase_lots(term, false, true, true); - break; - case 5: /* DECSCNM: 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. - */ - if (term->rvideo && !state) { - /* This is an OFF, so set up a vbell */ - term_schedule_vbell(term, true, term->rvbell_startpoint); - } else if (!term->rvideo && state) { - /* This is an ON, so we notice the time and save it. */ - term->rvbell_startpoint = GETTICKCOUNT(); - } - term->rvideo = state; - seen_disp_event(term); - break; - case 6: /* DECOM: DEC origin mode */ - term->dec_om = state; - break; - case 7: /* DECAWM: auto wrap */ - term->wrap = state; - break; - case 8: /* DECARM: auto key repeat */ - term->repeat_off = !state; - break; - case 25: /* DECTCEM: enable/disable cursor */ - compatibility2(OTHER, VT220); - term->cursor_on = state; - seen_disp_event(term); - break; - case 47: /* alternate screen */ - compatibility(OTHER); - deselect(term); - swap_screen(term, term->no_alt_screen ? 0 : state, false, false); + switch (mode) { + case 1: /* DECCKM: application cursor keys */ + term->app_cursor_keys = state; + break; + case 2: /* DECANM: VT52 mode */ + term->vt52_mode = !state; + if (term->vt52_mode) { + term->blink_is_real = false; + term->vt52_bold = false; + } else { + term->blink_is_real = term->blinktext; + } + term_schedule_tblink(term); + break; + case 3: /* DECCOLM: 80/132 columns */ + deselect(term); + if (!term->no_remote_resize) + win_request_resize(term->win, state ? 132 : 80, term->rows); + term->reset_132 = state; + term->alt_t = term->marg_t = 0; + term->alt_b = term->marg_b = term->rows - 1; + move(term, 0, 0, 0); + erase_lots(term, false, true, true); + break; + case 5: /* DECSCNM: 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. + */ + if (term->rvideo && !state) { + /* This is an OFF, so set up a vbell */ + term_schedule_vbell(term, true, term->rvbell_startpoint); + } else if (!term->rvideo && state) { + /* This is an ON, so we notice the time and save it. */ + term->rvbell_startpoint = GETTICKCOUNT(); + } + term->rvideo = state; + seen_disp_event(term); + break; + case 6: /* DECOM: DEC origin mode */ + term->dec_om = state; + break; + case 7: /* DECAWM: auto wrap */ + term->wrap = state; + break; + case 8: /* DECARM: auto key repeat */ + term->repeat_off = !state; + break; + case 25: /* DECTCEM: enable/disable cursor */ + compatibility2(OTHER, VT220); + term->cursor_on = state; + seen_disp_event(term); + break; + case 47: /* alternate screen */ + compatibility(OTHER); + deselect(term); + swap_screen(term, term->no_alt_screen ? 0 : state, false, false); if (term->scroll_on_disp) term->disptop = 0; - break; - case 1000: /* xterm mouse 1 (normal) */ - term->xterm_mouse = state ? 1 : 0; - win_set_raw_mouse_mode(term->win, state); - break; - case 1002: /* xterm mouse 2 (inc. button drags) */ - term->xterm_mouse = state ? 2 : 0; - win_set_raw_mouse_mode(term->win, state); - break; - case 1006: /* xterm extended mouse */ - term->xterm_extended_mouse = state; - break; - case 1015: /* urxvt extended mouse */ - term->urxvt_extended_mouse = state; - break; - case 1047: /* alternate screen */ - compatibility(OTHER); - deselect(term); - swap_screen(term, term->no_alt_screen ? 0 : state, true, true); + break; + case 1000: /* xterm mouse 1 (normal) */ + term->xterm_mouse = state ? 1 : 0; + win_set_raw_mouse_mode(term->win, state); + break; + case 1002: /* xterm mouse 2 (inc. button drags) */ + term->xterm_mouse = state ? 2 : 0; + win_set_raw_mouse_mode(term->win, state); + break; + case 1006: /* xterm extended mouse */ + term->xterm_extended_mouse = state; + break; + case 1015: /* urxvt extended mouse */ + term->urxvt_extended_mouse = state; + break; + case 1047: /* alternate screen */ + compatibility(OTHER); + deselect(term); + swap_screen(term, term->no_alt_screen ? 0 : state, true, true); if (term->scroll_on_disp) term->disptop = 0; - break; - case 1048: /* save/restore cursor */ - if (!term->no_alt_screen) + break; + case 1048: /* save/restore cursor */ + if (!term->no_alt_screen) + save_cursor(term, state); + if (!state) seen_disp_event(term); + break; + case 1049: /* cursor & alternate screen */ + if (state && !term->no_alt_screen) + save_cursor(term, state); + if (!state) seen_disp_event(term); + compatibility(OTHER); + deselect(term); + swap_screen(term, term->no_alt_screen ? 0 : state, true, false); + if (!state && !term->no_alt_screen) save_cursor(term, state); - if (!state) seen_disp_event(term); - break; - case 1049: /* cursor & alternate screen */ - if (state && !term->no_alt_screen) - save_cursor(term, state); - if (!state) seen_disp_event(term); - compatibility(OTHER); - deselect(term); - swap_screen(term, term->no_alt_screen ? 0 : state, true, false); - if (!state && !term->no_alt_screen) - save_cursor(term, state); if (term->scroll_on_disp) term->disptop = 0; - break; - case 2004: /* xterm bracketed paste */ - term->bracketed_paste = state ? true : false; - break; + break; + case 2004: /* xterm bracketed paste */ + term->bracketed_paste = state ? true : false; + break; } } else if (query == 0) { - switch (mode) { - case 4: /* IRM: set insert mode */ - compatibility(VT102); - term->insert = state; - break; - case 12: /* SRM: set echo mode */ + switch (mode) { + case 4: /* IRM: set insert mode */ + compatibility(VT102); + term->insert = state; + break; + case 12: /* SRM: set echo mode */ term->srm_echo = !state; - break; - case 20: /* LNM: Return sends ... */ - term->cr_lf_return = state; - break; - case 34: /* WYULCURM: Make cursor BIG */ - compatibility2(OTHER, VT220); - term->big_cursor = !state; - } + break; + case 20: /* LNM: Return sends ... */ + term->cr_lf_return = state; + break; + case 34: /* WYULCURM: Make cursor BIG */ + compatibility2(OTHER, VT220); + term->big_cursor = !state; + } } } @@ -2741,24 +2741,24 @@ static void toggle_mode(Terminal *term, int mode, int query, bool state) static void do_osc(Terminal *term) { if (term->osc_w) { - while (term->osc_strlen--) - term->wordness[(unsigned char) - term->osc_string[term->osc_strlen]] = term->esc_args[0]; + while (term->osc_strlen--) + term->wordness[(unsigned char) + term->osc_string[term->osc_strlen]] = term->esc_args[0]; } else { - term->osc_string[term->osc_strlen] = '\0'; - switch (term->esc_args[0]) { - case 0: - case 1: - if (!term->no_remote_wintitle) - win_set_icon_title(term->win, term->osc_string); - if (term->esc_args[0] == 1) - break; - /* fall through: parameter 0 means set both */ - case 2: - case 21: - if (!term->no_remote_wintitle) - win_set_title(term->win, term->osc_string); - break; + term->osc_string[term->osc_strlen] = '\0'; + switch (term->esc_args[0]) { + case 0: + case 1: + if (!term->no_remote_wintitle) + win_set_icon_title(term->win, term->osc_string); + if (term->esc_args[0] == 1) + break; + /* fall through: parameter 0 means set both */ + case 2: + case 21: + if (!term->no_remote_wintitle) + win_set_title(term->win, term->osc_string); + break; case 4: if (term->ldisc && !strcmp(term->osc_string, "?")) { int r, g, b; @@ -2776,7 +2776,7 @@ static void do_osc(Terminal *term) } } break; - } + } } } @@ -2792,11 +2792,11 @@ static void term_print_flush(Terminal *term) { size_t size; while ((size = bufchain_size(&term->printer_buf)) > 5) { - ptrlen data = bufchain_prefix(&term->printer_buf); - if (data.len > size-5) - data.len = size-5; - printer_job_data(term->print_job, data.ptr, data.len); - bufchain_consume(&term->printer_buf, data.len); + ptrlen data = bufchain_prefix(&term->printer_buf); + if (data.len > size-5) + data.len = size-5; + printer_job_data(term->print_job, data.ptr, data.len); + bufchain_consume(&term->printer_buf, data.len); } } static void term_print_finish(Terminal *term) @@ -2805,19 +2805,19 @@ static void term_print_finish(Terminal *term) char c; if (!term->printing && !term->only_printing) - return; /* we need do nothing */ + return; /* we need do nothing */ term_print_flush(term); while ((size = bufchain_size(&term->printer_buf)) > 0) { - ptrlen data = bufchain_prefix(&term->printer_buf); - c = *(char *)data.ptr; - if (c == '\033' || c == '\233') { - bufchain_consume(&term->printer_buf, size); - break; - } else { - printer_job_data(term->print_job, &c, 1); - bufchain_consume(&term->printer_buf, 1); - } + ptrlen data = bufchain_prefix(&term->printer_buf); + c = *(char *)data.ptr; + if (c == '\033' || c == '\233') { + bufchain_consume(&term->printer_buf, size); + break; + } else { + printer_job_data(term->print_job, &c, 1); + bufchain_consume(&term->printer_buf, 1); + } } printer_finish_job(term->print_job); term->print_job = NULL; @@ -3164,7 +3164,7 @@ unsigned long term_translate( return 0xFFFD; /* The UTF-16 surrogates are not nice either. */ - /* The standard give the option of decoding these: + /* The standard give the option of decoding these: * I don't want to! */ if (t >= 0xD800 && t < 0xE000) return UCSINVALID; @@ -3186,7 +3186,7 @@ unsigned long term_translate( return t; } - } else if (term->sco_acs && + } else if (term->sco_acs && (c!='\033' && c!='\012' && c!='\015' && c!='\b')) { /* Are we in the nasty ACS mode? Note: no sco in utf mode. */ if (term->sco_acs == 2) @@ -3195,7 +3195,7 @@ unsigned long term_translate( return c | CSET_SCOACS; } else { switch (term->cset_attr[term->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 @@ -3243,73 +3243,73 @@ static void term_out(Terminal *term) unget = -1; - chars = NULL; /* placate compiler warnings */ + chars = NULL; /* placate compiler warnings */ while (nchars > 0 || unget != -1 || bufchain_size(&term->inbuf) > 0) { - if (unget == -1) { - if (nchars == 0) { + if (unget == -1) { + if (nchars == 0) { ptrlen data = bufchain_prefix(&term->inbuf); - if (data.len > sizeof(localbuf)) - data.len = sizeof(localbuf); - memcpy(localbuf, data.ptr, data.len); - bufchain_consume(&term->inbuf, data.len); + if (data.len > sizeof(localbuf)) + data.len = sizeof(localbuf); + memcpy(localbuf, data.ptr, data.len); + bufchain_consume(&term->inbuf, data.len); nchars = data.len; - chars = localbuf; - assert(chars != NULL); - assert(nchars > 0); - } - c = *chars++; - nchars--; + chars = localbuf; + assert(chars != NULL); + assert(nchars > 0); + } + c = *chars++; + nchars--; - /* - * Optionally log the session traffic to a file. Useful for - * debugging and possibly also useful for actual logging. - */ - if (term->logtype == LGTYP_DEBUG && term->logctx) - logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG); - } else { - c = unget; - unget = -1; - } + /* + * Optionally log the session traffic to a file. Useful for + * debugging and possibly also useful for actual logging. + */ + if (term->logtype == LGTYP_DEBUG && term->logctx) + logtraffic(term->logctx, (unsigned char) c, LGTYP_DEBUG); + } else { + c = unget; + unget = -1; + } - /* 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. - */ + /* 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 we're printing, add the character to the printer - * buffer. - */ - if (term->printing) { - bufchain_add(&term->printer_buf, &c, 1); + /* + * If we're printing, add the character to the printer + * buffer. + */ + if (term->printing) { + bufchain_add(&term->printer_buf, &c, 1); - /* - * If we're in print-only mode, we use a much simpler - * state machine designed only to recognise the ESC[4i - * termination sequence. - */ - if (term->only_printing) { - if (c == '\033') - term->print_state = 1; - else if (c == (unsigned char)'\233') - term->print_state = 2; - else if (c == '[' && term->print_state == 1) - term->print_state = 2; - else if (c == '4' && term->print_state == 2) - term->print_state = 3; - else if (c == 'i' && term->print_state == 3) - term->print_state = 4; - else - term->print_state = 0; - if (term->print_state == 4) { - term_print_finish(term); - } - continue; - } - } + /* + * If we're in print-only mode, we use a much simpler + * state machine designed only to recognise the ESC[4i + * termination sequence. + */ + if (term->only_printing) { + if (c == '\033') + term->print_state = 1; + else if (c == (unsigned char)'\233') + term->print_state = 2; + else if (c == '[' && term->print_state == 1) + term->print_state = 2; + else if (c == '4' && term->print_state == 2) + term->print_state = 3; + else if (c == 'i' && term->print_state == 3) + term->print_state = 4; + else + term->print_state = 0; + if (term->print_state == 4) { + term_print_finish(term); + } + continue; + } + } - /* Do character-set translation. */ - if (term->termstate == TOPLEVEL) { + /* Do character-set translation. */ + if (term->termstate == TOPLEVEL) { unsigned long t = term_translate(term, &term->utf8, c); switch (t) { case UCSINCOMPLETE: @@ -3324,483 +3324,483 @@ static void term_out(Terminal *term) c = t; break; } - } + } - /* - * How about C1 controls? - * Explicitly ignore SCI (0x9a), which we don't translate to DECID. - */ - if ((c & -32) == 0x80 && term->termstate < DO_CTRLS && - !term->vt52_mode && has_compat(VT220)) { - if (c == 0x9a) - c = 0; - else { - term->termstate = SEEN_ESC; - term->esc_query = 0; - c = '@' + (c & 0x1F); - } - } + /* + * How about C1 controls? + * Explicitly ignore SCI (0x9a), which we don't translate to DECID. + */ + if ((c & -32) == 0x80 && term->termstate < DO_CTRLS && + !term->vt52_mode && has_compat(VT220)) { + if (c == 0x9a) + c = 0; + else { + term->termstate = SEEN_ESC; + term->esc_query = 0; + c = '@' + (c & 0x1F); + } + } - /* Or the GL control. */ - if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) { - if (term->curs.x && !term->wrapnext) - term->curs.x--; - term->wrapnext = false; - /* destructive backspace might be disabled */ - if (!term->no_dbackspace) { - check_boundary(term, term->curs.x, term->curs.y); - check_boundary(term, term->curs.x+1, term->curs.y); - copy_termchar(scrlineptr(term->curs.y), - term->curs.x, &term->erase_char); - } - } else - /* Or normal C0 controls. */ - if ((c & ~0x1F) == 0 && term->termstate < DO_CTRLS) { - switch (c) { - case '\005': /* ENQ: terminal type query */ - /* - * Strictly speaking this is VT100 but a VT100 defaults to - * no response. Other terminals respond at their option. - * - * Don't put a CR in the default string as this tends to - * upset some weird software. - */ - compatibility(ANSIMIN); - if (term->ldisc) { + /* Or the GL control. */ + if (c == '\177' && term->termstate < DO_CTRLS && has_compat(OTHER)) { + if (term->curs.x && !term->wrapnext) + term->curs.x--; + term->wrapnext = false; + /* destructive backspace might be disabled */ + if (!term->no_dbackspace) { + check_boundary(term, term->curs.x, term->curs.y); + check_boundary(term, term->curs.x+1, term->curs.y); + copy_termchar(scrlineptr(term->curs.y), + term->curs.x, &term->erase_char); + } + } else + /* Or normal C0 controls. */ + if ((c & ~0x1F) == 0 && term->termstate < DO_CTRLS) { + switch (c) { + case '\005': /* ENQ: terminal type query */ + /* + * Strictly speaking this is VT100 but a VT100 defaults to + * no response. Other terminals respond at their option. + * + * Don't put a CR in the default string as this tends to + * upset some weird software. + */ + compatibility(ANSIMIN); + if (term->ldisc) { strbuf *buf = term_input_data_from_charset( term, DEFAULT_CODEPAGE, term->answerback, term->answerbacklen); ldisc_send(term->ldisc, buf->s, buf->len, false); strbuf_free(buf); - } - break; - case '\007': /* BEL: Bell */ - { - struct beeptime *newbeep; - unsigned long ticks; + } + break; + case '\007': /* BEL: Bell */ + { + struct beeptime *newbeep; + unsigned long ticks; - ticks = GETTICKCOUNT(); + ticks = GETTICKCOUNT(); - if (!term->beep_overloaded) { - newbeep = snew(struct beeptime); - newbeep->ticks = ticks; - newbeep->next = NULL; - if (!term->beephead) - term->beephead = newbeep; - else - term->beeptail->next = newbeep; - term->beeptail = newbeep; - term->nbeeps++; - } + if (!term->beep_overloaded) { + newbeep = snew(struct beeptime); + newbeep->ticks = ticks; + newbeep->next = NULL; + if (!term->beephead) + term->beephead = newbeep; + else + term->beeptail->next = newbeep; + term->beeptail = newbeep; + term->nbeeps++; + } - /* - * Throw out any beeps that happened more than - * t seconds ago. - */ - while (term->beephead && - term->beephead->ticks < ticks - term->bellovl_t) { - struct beeptime *tmp = term->beephead; - term->beephead = tmp->next; - sfree(tmp); - if (!term->beephead) - term->beeptail = NULL; - term->nbeeps--; - } + /* + * Throw out any beeps that happened more than + * t seconds ago. + */ + while (term->beephead && + term->beephead->ticks < ticks - term->bellovl_t) { + struct beeptime *tmp = term->beephead; + term->beephead = tmp->next; + sfree(tmp); + if (!term->beephead) + term->beeptail = NULL; + term->nbeeps--; + } - if (term->bellovl && term->beep_overloaded && - ticks - term->lastbeep >= (unsigned)term->bellovl_s) { - /* - * If we're currently overloaded and the - * last beep was more than s seconds ago, - * leave overload mode. - */ - term->beep_overloaded = false; - } else if (term->bellovl && !term->beep_overloaded && - term->nbeeps >= term->bellovl_n) { - /* - * Now, if we have n or more beeps - * remaining in the queue, go into overload - * mode. - */ - term->beep_overloaded = true; - } - term->lastbeep = ticks; + if (term->bellovl && term->beep_overloaded && + ticks - term->lastbeep >= (unsigned)term->bellovl_s) { + /* + * If we're currently overloaded and the + * last beep was more than s seconds ago, + * leave overload mode. + */ + term->beep_overloaded = false; + } else if (term->bellovl && !term->beep_overloaded && + term->nbeeps >= term->bellovl_n) { + /* + * Now, if we have n or more beeps + * remaining in the queue, go into overload + * mode. + */ + term->beep_overloaded = true; + } + term->lastbeep = ticks; - /* - * Perform an actual beep if we're not overloaded. - */ - if (!term->bellovl || !term->beep_overloaded) { - win_bell(term->win, term->beep); + /* + * Perform an actual beep if we're not overloaded. + */ + if (!term->bellovl || !term->beep_overloaded) { + win_bell(term->win, term->beep); - if (term->beep == BELL_VISUAL) { - term_schedule_vbell(term, false, 0); - } - } - seen_disp_event(term); - } - break; - case '\b': /* BS: Back space */ - if (term->curs.x == 0 && (term->curs.y == 0 || !term->wrap)) - /* do nothing */ ; - else if (term->curs.x == 0 && term->curs.y > 0) - term->curs.x = term->cols - 1, term->curs.y--; - else if (term->wrapnext) - term->wrapnext = false; - else - term->curs.x--; - seen_disp_event(term); - break; - case '\016': /* LS1: Locking-shift one */ - compatibility(VT100); - term->cset = 1; - break; - case '\017': /* LS0: Locking-shift zero */ - compatibility(VT100); - term->cset = 0; - break; - case '\033': /* ESC: Escape */ - if (term->vt52_mode) - term->termstate = VT52_ESC; - else { - compatibility(ANSIMIN); - term->termstate = SEEN_ESC; - term->esc_query = 0; - } - break; - case '\015': /* CR: Carriage return */ - term->curs.x = 0; - term->wrapnext = false; - seen_disp_event(term); + if (term->beep == BELL_VISUAL) { + term_schedule_vbell(term, false, 0); + } + } + seen_disp_event(term); + } + break; + case '\b': /* BS: Back space */ + if (term->curs.x == 0 && (term->curs.y == 0 || !term->wrap)) + /* do nothing */ ; + else if (term->curs.x == 0 && term->curs.y > 0) + term->curs.x = term->cols - 1, term->curs.y--; + else if (term->wrapnext) + term->wrapnext = false; + else + term->curs.x--; + seen_disp_event(term); + break; + case '\016': /* LS1: Locking-shift one */ + compatibility(VT100); + term->cset = 1; + break; + case '\017': /* LS0: Locking-shift zero */ + compatibility(VT100); + term->cset = 0; + break; + case '\033': /* ESC: Escape */ + if (term->vt52_mode) + term->termstate = VT52_ESC; + else { + compatibility(ANSIMIN); + term->termstate = SEEN_ESC; + term->esc_query = 0; + } + break; + case '\015': /* CR: Carriage return */ + term->curs.x = 0; + term->wrapnext = false; + seen_disp_event(term); - if (term->crhaslf) { - if (term->curs.y == term->marg_b) - scroll(term, term->marg_t, term->marg_b, 1, true); - else if (term->curs.y < term->rows - 1) - term->curs.y++; - } - if (term->logctx) - logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII); - break; - case '\014': /* FF: Form feed */ - if (has_compat(SCOANSI)) { - move(term, 0, 0, 0); - erase_lots(term, false, false, true); + if (term->crhaslf) { + if (term->curs.y == term->marg_b) + scroll(term, term->marg_t, term->marg_b, 1, true); + else if (term->curs.y < term->rows - 1) + term->curs.y++; + } + if (term->logctx) + logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII); + break; + case '\014': /* FF: Form feed */ + if (has_compat(SCOANSI)) { + move(term, 0, 0, 0); + erase_lots(term, false, false, true); if (term->scroll_on_disp) term->disptop = 0; - term->wrapnext = false; - seen_disp_event(term); - break; - } - case '\013': /* VT: Line tabulation */ - compatibility(VT100); - case '\012': /* LF: Line feed */ - if (term->curs.y == term->marg_b) - scroll(term, term->marg_t, term->marg_b, 1, true); - else if (term->curs.y < term->rows - 1) - term->curs.y++; - if (term->lfhascr) - term->curs.x = 0; - term->wrapnext = false; - seen_disp_event(term); - if (term->logctx) - logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII); - break; - case '\t': /* HT: Character tabulation */ - { - pos old_curs = term->curs; - termline *ldata = scrlineptr(term->curs.y); + term->wrapnext = false; + seen_disp_event(term); + break; + } + case '\013': /* VT: Line tabulation */ + compatibility(VT100); + case '\012': /* LF: Line feed */ + if (term->curs.y == term->marg_b) + scroll(term, term->marg_t, term->marg_b, 1, true); + else if (term->curs.y < term->rows - 1) + term->curs.y++; + if (term->lfhascr) + term->curs.x = 0; + term->wrapnext = false; + seen_disp_event(term); + if (term->logctx) + logtraffic(term->logctx, (unsigned char) c, LGTYP_ASCII); + break; + case '\t': /* HT: Character tabulation */ + { + pos old_curs = term->curs; + termline *ldata = scrlineptr(term->curs.y); - do { - term->curs.x++; - } while (term->curs.x < term->cols - 1 && - !term->tabs[term->curs.x]); + do { + term->curs.x++; + } while (term->curs.x < term->cols - 1 && + !term->tabs[term->curs.x]); - if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) { - if (term->curs.x >= term->cols / 2) - term->curs.x = term->cols / 2 - 1; - } else { - if (term->curs.x >= term->cols) - term->curs.x = term->cols - 1; - } + if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) { + if (term->curs.x >= term->cols / 2) + term->curs.x = term->cols / 2 - 1; + } else { + if (term->curs.x >= term->cols) + term->curs.x = term->cols - 1; + } - check_selection(term, old_curs, term->curs); - } - seen_disp_event(term); - break; - } - } else - switch (term->termstate) { - case TOPLEVEL: - /* Only graphic characters get this far; - * ctrls are stripped above */ - term_display_graphic_char(term, c); + check_selection(term, old_curs, term->curs); + } + seen_disp_event(term); + break; + } + } else + switch (term->termstate) { + case TOPLEVEL: + /* Only graphic characters get this far; + * ctrls are stripped above */ + term_display_graphic_char(term, c); term->last_graphic_char = c; - break; + 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(term); - term->termstate = TOPLEVEL; - break; - } - /* else fall through */ - case SEEN_ESC: - if (c >= ' ' && c <= '/') { - if (term->esc_query) - term->esc_query = -1; - else - term->esc_query = c; - break; - } - term->termstate = TOPLEVEL; - switch (ANSI(c, term->esc_query)) { - case '[': /* enter CSI mode */ - term->termstate = SEEN_CSI; - term->esc_nargs = 1; - term->esc_args[0] = ARG_DEFAULT; - term->esc_query = 0; - break; - case ']': /* OSC: xterm escape sequences */ - /* Compatibility is nasty here, xterm, linux, decterm yuk! */ - compatibility(OTHER); - term->termstate = SEEN_OSC; - term->esc_args[0] = 0; + 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(term); + term->termstate = TOPLEVEL; + break; + } + /* else fall through */ + case SEEN_ESC: + if (c >= ' ' && c <= '/') { + if (term->esc_query) + term->esc_query = -1; + else + term->esc_query = c; + break; + } + term->termstate = TOPLEVEL; + switch (ANSI(c, term->esc_query)) { + case '[': /* enter CSI mode */ + term->termstate = SEEN_CSI; term->esc_nargs = 1; - break; - case '7': /* DECSC: save cursor */ - compatibility(VT100); - save_cursor(term, true); - break; - case '8': /* DECRC: restore cursor */ - compatibility(VT100); - save_cursor(term, false); - seen_disp_event(term); - break; - case '=': /* DECKPAM: Keypad application mode */ - compatibility(VT100); - term->app_keypad_keys = true; - break; - case '>': /* DECKPNM: Keypad numeric mode */ - compatibility(VT100); - term->app_keypad_keys = false; - break; - case 'D': /* IND: exactly equivalent to LF */ - compatibility(VT100); - if (term->curs.y == term->marg_b) - scroll(term, term->marg_t, term->marg_b, 1, true); - else if (term->curs.y < term->rows - 1) - term->curs.y++; - term->wrapnext = false; - seen_disp_event(term); - break; - case 'E': /* NEL: exactly equivalent to CR-LF */ - compatibility(VT100); - term->curs.x = 0; - if (term->curs.y == term->marg_b) - scroll(term, term->marg_t, term->marg_b, 1, true); - else if (term->curs.y < term->rows - 1) - term->curs.y++; - term->wrapnext = false; - seen_disp_event(term); - break; - case 'M': /* RI: reverse index - backwards LF */ - compatibility(VT100); - if (term->curs.y == term->marg_t) - scroll(term, term->marg_t, term->marg_b, -1, true); - else if (term->curs.y > 0) - term->curs.y--; - term->wrapnext = false; - seen_disp_event(term); - break; - case 'Z': /* DECID: terminal type query */ - compatibility(VT100); - if (term->ldisc && term->id_string[0]) - ldisc_send(term->ldisc, term->id_string, - strlen(term->id_string), false); - break; - case 'c': /* RIS: restore power-on settings */ - compatibility(VT100); - power_on(term, true); - if (term->ldisc) /* cause ldisc to notice changes */ - ldisc_echoedit_update(term->ldisc); - if (term->reset_132) { - if (!term->no_remote_resize) - win_request_resize(term->win, 80, term->rows); - term->reset_132 = false; - } + term->esc_args[0] = ARG_DEFAULT; + term->esc_query = 0; + break; + case ']': /* OSC: xterm escape sequences */ + /* Compatibility is nasty here, xterm, linux, decterm yuk! */ + compatibility(OTHER); + term->termstate = SEEN_OSC; + term->esc_args[0] = 0; + term->esc_nargs = 1; + break; + case '7': /* DECSC: save cursor */ + compatibility(VT100); + save_cursor(term, true); + break; + case '8': /* DECRC: restore cursor */ + compatibility(VT100); + save_cursor(term, false); + seen_disp_event(term); + break; + case '=': /* DECKPAM: Keypad application mode */ + compatibility(VT100); + term->app_keypad_keys = true; + break; + case '>': /* DECKPNM: Keypad numeric mode */ + compatibility(VT100); + term->app_keypad_keys = false; + break; + case 'D': /* IND: exactly equivalent to LF */ + compatibility(VT100); + if (term->curs.y == term->marg_b) + scroll(term, term->marg_t, term->marg_b, 1, true); + else if (term->curs.y < term->rows - 1) + term->curs.y++; + term->wrapnext = false; + seen_disp_event(term); + break; + case 'E': /* NEL: exactly equivalent to CR-LF */ + compatibility(VT100); + term->curs.x = 0; + if (term->curs.y == term->marg_b) + scroll(term, term->marg_t, term->marg_b, 1, true); + else if (term->curs.y < term->rows - 1) + term->curs.y++; + term->wrapnext = false; + seen_disp_event(term); + break; + case 'M': /* RI: reverse index - backwards LF */ + compatibility(VT100); + if (term->curs.y == term->marg_t) + scroll(term, term->marg_t, term->marg_b, -1, true); + else if (term->curs.y > 0) + term->curs.y--; + term->wrapnext = false; + seen_disp_event(term); + break; + case 'Z': /* DECID: terminal type query */ + compatibility(VT100); + if (term->ldisc && term->id_string[0]) + ldisc_send(term->ldisc, term->id_string, + strlen(term->id_string), false); + break; + case 'c': /* RIS: restore power-on settings */ + compatibility(VT100); + power_on(term, true); + if (term->ldisc) /* cause ldisc to notice changes */ + ldisc_echoedit_update(term->ldisc); + if (term->reset_132) { + if (!term->no_remote_resize) + win_request_resize(term->win, 80, term->rows); + term->reset_132 = false; + } if (term->scroll_on_disp) term->disptop = 0; - seen_disp_event(term); - break; - case 'H': /* HTS: set a tab */ - compatibility(VT100); - term->tabs[term->curs.x] = true; - break; + seen_disp_event(term); + break; + case 'H': /* HTS: set a tab */ + compatibility(VT100); + term->tabs[term->curs.x] = true; + break; - case ANSI('8', '#'): /* DECALN: fills screen with Es :-) */ - compatibility(VT100); - { - termline *ldata; - int i, j; - pos scrtop, scrbot; + case ANSI('8', '#'): /* DECALN: fills screen with Es :-) */ + compatibility(VT100); + { + termline *ldata; + int i, j; + pos scrtop, scrbot; - for (i = 0; i < term->rows; i++) { - ldata = scrlineptr(i); + for (i = 0; i < term->rows; i++) { + ldata = scrlineptr(i); check_line_size(term, ldata); - for (j = 0; j < term->cols; j++) { - copy_termchar(ldata, j, - &term->basic_erase_char); - ldata->chars[j].chr = 'E'; - } - ldata->lattr = LATTR_NORM; - } + for (j = 0; j < term->cols; j++) { + copy_termchar(ldata, j, + &term->basic_erase_char); + ldata->chars[j].chr = 'E'; + } + ldata->lattr = LATTR_NORM; + } if (term->scroll_on_disp) term->disptop = 0; - seen_disp_event(term); - scrtop.x = scrtop.y = 0; - scrbot.x = 0; - scrbot.y = term->rows; - check_selection(term, scrtop, scrbot); - } - break; + seen_disp_event(term); + scrtop.x = scrtop.y = 0; + scrbot.x = 0; + scrbot.y = term->rows; + check_selection(term, scrtop, scrbot); + } + break; - case ANSI('3', '#'): - case ANSI('4', '#'): - case ANSI('5', '#'): - case ANSI('6', '#'): - compatibility(VT100); - { - int nlattr; - termline *ldata; + case ANSI('3', '#'): + case ANSI('4', '#'): + case ANSI('5', '#'): + case ANSI('6', '#'): + compatibility(VT100); + { + int nlattr; + termline *ldata; - switch (ANSI(c, term->esc_query)) { - case ANSI('3', '#'): /* DECDHL: 2*height, top */ - nlattr = LATTR_TOP; - break; - case ANSI('4', '#'): /* DECDHL: 2*height, bottom */ - nlattr = LATTR_BOT; - break; - case ANSI('5', '#'): /* DECSWL: normal */ - nlattr = LATTR_NORM; - break; - default: /* case ANSI('6', '#'): DECDWL: 2*width */ - nlattr = LATTR_WIDE; - break; - } - ldata = scrlineptr(term->curs.y); + switch (ANSI(c, term->esc_query)) { + case ANSI('3', '#'): /* DECDHL: 2*height, top */ + nlattr = LATTR_TOP; + break; + case ANSI('4', '#'): /* DECDHL: 2*height, bottom */ + nlattr = LATTR_BOT; + break; + case ANSI('5', '#'): /* DECSWL: normal */ + nlattr = LATTR_NORM; + break; + default: /* case ANSI('6', '#'): DECDWL: 2*width */ + nlattr = LATTR_WIDE; + break; + } + ldata = scrlineptr(term->curs.y); check_line_size(term, ldata); check_trust_status(term, ldata); ldata->lattr = nlattr; - } - break; - /* GZD4: G0 designate 94-set */ - case ANSI('A', '('): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[0] = CSET_GBCHR; - break; - case ANSI('B', '('): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[0] = CSET_ASCII; - break; - case ANSI('0', '('): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[0] = CSET_LINEDRW; - break; - case ANSI('U', '('): - compatibility(OTHER); - if (!term->no_remote_charset) - term->cset_attr[0] = CSET_SCOACS; - break; - /* G1D4: G1-designate 94-set */ - case ANSI('A', ')'): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[1] = CSET_GBCHR; - break; - case ANSI('B', ')'): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[1] = CSET_ASCII; - break; - case ANSI('0', ')'): - compatibility(VT100); - if (!term->no_remote_charset) - term->cset_attr[1] = CSET_LINEDRW; - break; - case ANSI('U', ')'): - compatibility(OTHER); - if (!term->no_remote_charset) - term->cset_attr[1] = CSET_SCOACS; - break; - /* DOCS: Designate other coding system */ - case ANSI('8', '%'): /* Old Linux code */ - case ANSI('G', '%'): - compatibility(OTHER); - if (!term->no_remote_charset) - term->utf = true; - break; - case ANSI('@', '%'): - compatibility(OTHER); - if (!term->no_remote_charset) - term->utf = false; - break; - } - break; - case SEEN_CSI: - term->termstate = TOPLEVEL; /* default */ - if (isdigit(c)) { - if (term->esc_nargs <= ARGS_MAX) { - if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT) - term->esc_args[term->esc_nargs - 1] = 0; - if (term->esc_args[term->esc_nargs - 1] <= - UINT_MAX / 10 && - term->esc_args[term->esc_nargs - 1] * 10 <= - UINT_MAX - c - '0') - term->esc_args[term->esc_nargs - 1] = - 10 * term->esc_args[term->esc_nargs - 1] + - c - '0'; - else - term->esc_args[term->esc_nargs - 1] = UINT_MAX; - } - term->termstate = SEEN_CSI; - } else if (c == ';') { - if (term->esc_nargs < ARGS_MAX) - term->esc_args[term->esc_nargs++] = ARG_DEFAULT; - term->termstate = SEEN_CSI; - } else if (c < '@') { - if (term->esc_query) - term->esc_query = -1; - else if (c == '?') - term->esc_query = 1; - else - term->esc_query = c; - term->termstate = SEEN_CSI; - } else + } + break; + /* GZD4: G0 designate 94-set */ + case ANSI('A', '('): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[0] = CSET_GBCHR; + break; + case ANSI('B', '('): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[0] = CSET_ASCII; + break; + case ANSI('0', '('): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[0] = CSET_LINEDRW; + break; + case ANSI('U', '('): + compatibility(OTHER); + if (!term->no_remote_charset) + term->cset_attr[0] = CSET_SCOACS; + break; + /* G1D4: G1-designate 94-set */ + case ANSI('A', ')'): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[1] = CSET_GBCHR; + break; + case ANSI('B', ')'): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[1] = CSET_ASCII; + break; + case ANSI('0', ')'): + compatibility(VT100); + if (!term->no_remote_charset) + term->cset_attr[1] = CSET_LINEDRW; + break; + case ANSI('U', ')'): + compatibility(OTHER); + if (!term->no_remote_charset) + term->cset_attr[1] = CSET_SCOACS; + break; + /* DOCS: Designate other coding system */ + case ANSI('8', '%'): /* Old Linux code */ + case ANSI('G', '%'): + compatibility(OTHER); + if (!term->no_remote_charset) + term->utf = true; + break; + case ANSI('@', '%'): + compatibility(OTHER); + if (!term->no_remote_charset) + term->utf = false; + break; + } + break; + case SEEN_CSI: + term->termstate = TOPLEVEL; /* default */ + if (isdigit(c)) { + if (term->esc_nargs <= ARGS_MAX) { + if (term->esc_args[term->esc_nargs - 1] == ARG_DEFAULT) + term->esc_args[term->esc_nargs - 1] = 0; + if (term->esc_args[term->esc_nargs - 1] <= + UINT_MAX / 10 && + term->esc_args[term->esc_nargs - 1] * 10 <= + UINT_MAX - c - '0') + term->esc_args[term->esc_nargs - 1] = + 10 * term->esc_args[term->esc_nargs - 1] + + c - '0'; + else + term->esc_args[term->esc_nargs - 1] = UINT_MAX; + } + term->termstate = SEEN_CSI; + } else if (c == ';') { + if (term->esc_nargs < ARGS_MAX) + term->esc_args[term->esc_nargs++] = ARG_DEFAULT; + term->termstate = SEEN_CSI; + } else if (c < '@') { + if (term->esc_query) + term->esc_query = -1; + else if (c == '?') + term->esc_query = 1; + else + term->esc_query = c; + term->termstate = SEEN_CSI; + } else #define CLAMP(arg, lim) ((arg) = ((arg) > (lim)) ? (lim) : (arg)) - switch (ANSI(c, term->esc_query)) { - case 'A': /* CUU: move up N lines */ - CLAMP(term->esc_args[0], term->rows); - move(term, term->curs.x, - term->curs.y - def(term->esc_args[0], 1), 1); - seen_disp_event(term); - break; - case 'e': /* VPR: move down N lines */ - compatibility(ANSI); - /* FALLTHROUGH */ - case 'B': /* CUD: Cursor down */ - CLAMP(term->esc_args[0], term->rows); - move(term, term->curs.x, - term->curs.y + def(term->esc_args[0], 1), 1); - seen_disp_event(term); - break; + switch (ANSI(c, term->esc_query)) { + case 'A': /* CUU: move up N lines */ + CLAMP(term->esc_args[0], term->rows); + move(term, term->curs.x, + term->curs.y - def(term->esc_args[0], 1), 1); + seen_disp_event(term); + break; + case 'e': /* VPR: move down N lines */ + compatibility(ANSI); + /* FALLTHROUGH */ + case 'B': /* CUD: Cursor down */ + CLAMP(term->esc_args[0], term->rows); + move(term, term->curs.x, + term->curs.y + def(term->esc_args[0], 1), 1); + seen_disp_event(term); + break; case 'b': /* REP: repeat previous grap */ CLAMP(term->esc_args[0], term->rows * term->cols); if (term->last_graphic_char) { @@ -3810,397 +3810,397 @@ static void term_out(Terminal *term) term, term->last_graphic_char); } break; - case ANSI('c', '>'): /* DA: report xterm version */ - compatibility(OTHER); - /* this reports xterm version 136 so that VIM can - use the drag messages from the mouse reporting */ - if (term->ldisc) - ldisc_send(term->ldisc, "\033[>0;136;0c", 11, + case ANSI('c', '>'): /* DA: report xterm version */ + compatibility(OTHER); + /* this reports xterm version 136 so that VIM can + use the drag messages from the mouse reporting */ + if (term->ldisc) + ldisc_send(term->ldisc, "\033[>0;136;0c", 11, false); - break; - case 'a': /* HPR: move right N cols */ - compatibility(ANSI); - /* FALLTHROUGH */ - case 'C': /* CUF: Cursor right */ - CLAMP(term->esc_args[0], term->cols); - move(term, term->curs.x + def(term->esc_args[0], 1), - term->curs.y, 1); - seen_disp_event(term); - break; - case 'D': /* CUB: move left N cols */ - CLAMP(term->esc_args[0], term->cols); - move(term, term->curs.x - def(term->esc_args[0], 1), - term->curs.y, 1); - seen_disp_event(term); - break; - case 'E': /* CNL: move down N lines and CR */ - compatibility(ANSI); - CLAMP(term->esc_args[0], term->rows); - move(term, 0, - term->curs.y + def(term->esc_args[0], 1), 1); - seen_disp_event(term); - break; - case 'F': /* CPL: move up N lines and CR */ - compatibility(ANSI); - CLAMP(term->esc_args[0], term->rows); - move(term, 0, - term->curs.y - def(term->esc_args[0], 1), 1); - seen_disp_event(term); - break; - case 'G': /* CHA */ - case '`': /* HPA: set horizontal posn */ - compatibility(ANSI); - CLAMP(term->esc_args[0], term->cols); - move(term, def(term->esc_args[0], 1) - 1, - term->curs.y, 0); - seen_disp_event(term); - break; - case 'd': /* VPA: set vertical posn */ - compatibility(ANSI); - CLAMP(term->esc_args[0], term->rows); - move(term, term->curs.x, - ((term->dec_om ? term->marg_t : 0) + - def(term->esc_args[0], 1) - 1), - (term->dec_om ? 2 : 0)); - seen_disp_event(term); - break; - case 'H': /* CUP */ - case 'f': /* HVP: set horz and vert posns at once */ - if (term->esc_nargs < 2) - term->esc_args[1] = ARG_DEFAULT; - CLAMP(term->esc_args[0], term->rows); - CLAMP(term->esc_args[1], term->cols); - move(term, def(term->esc_args[1], 1) - 1, - ((term->dec_om ? term->marg_t : 0) + - def(term->esc_args[0], 1) - 1), - (term->dec_om ? 2 : 0)); - seen_disp_event(term); - break; - case 'J': /* ED: erase screen or parts of it */ - { - unsigned int i = def(term->esc_args[0], 0); - if (i == 3) { - /* Erase Saved Lines (xterm) - * This follows Thomas Dickey's xterm. */ + break; + case 'a': /* HPR: move right N cols */ + compatibility(ANSI); + /* FALLTHROUGH */ + case 'C': /* CUF: Cursor right */ + CLAMP(term->esc_args[0], term->cols); + move(term, term->curs.x + def(term->esc_args[0], 1), + term->curs.y, 1); + seen_disp_event(term); + break; + case 'D': /* CUB: move left N cols */ + CLAMP(term->esc_args[0], term->cols); + move(term, term->curs.x - def(term->esc_args[0], 1), + term->curs.y, 1); + seen_disp_event(term); + break; + case 'E': /* CNL: move down N lines and CR */ + compatibility(ANSI); + CLAMP(term->esc_args[0], term->rows); + move(term, 0, + term->curs.y + def(term->esc_args[0], 1), 1); + seen_disp_event(term); + break; + case 'F': /* CPL: move up N lines and CR */ + compatibility(ANSI); + CLAMP(term->esc_args[0], term->rows); + move(term, 0, + term->curs.y - def(term->esc_args[0], 1), 1); + seen_disp_event(term); + break; + case 'G': /* CHA */ + case '`': /* HPA: set horizontal posn */ + compatibility(ANSI); + CLAMP(term->esc_args[0], term->cols); + move(term, def(term->esc_args[0], 1) - 1, + term->curs.y, 0); + seen_disp_event(term); + break; + case 'd': /* VPA: set vertical posn */ + compatibility(ANSI); + CLAMP(term->esc_args[0], term->rows); + move(term, term->curs.x, + ((term->dec_om ? term->marg_t : 0) + + def(term->esc_args[0], 1) - 1), + (term->dec_om ? 2 : 0)); + seen_disp_event(term); + break; + case 'H': /* CUP */ + case 'f': /* HVP: set horz and vert posns at once */ + if (term->esc_nargs < 2) + term->esc_args[1] = ARG_DEFAULT; + CLAMP(term->esc_args[0], term->rows); + CLAMP(term->esc_args[1], term->cols); + move(term, def(term->esc_args[1], 1) - 1, + ((term->dec_om ? term->marg_t : 0) + + def(term->esc_args[0], 1) - 1), + (term->dec_om ? 2 : 0)); + seen_disp_event(term); + break; + case 'J': /* ED: erase screen or parts of it */ + { + unsigned int i = def(term->esc_args[0], 0); + if (i == 3) { + /* Erase Saved Lines (xterm) + * This follows Thomas Dickey's xterm. */ if (!term->no_remote_clearscroll) term_clrsb(term); - } else { - i++; - if (i > 3) - i = 0; - erase_lots(term, false, !!(i & 2), !!(i & 1)); - } - } - if (term->scroll_on_disp) + } else { + i++; + if (i > 3) + i = 0; + erase_lots(term, false, !!(i & 2), !!(i & 1)); + } + } + if (term->scroll_on_disp) term->disptop = 0; - seen_disp_event(term); - break; - case 'K': /* EL: erase line or parts of it */ - { - unsigned int i = def(term->esc_args[0], 0) + 1; - if (i > 3) - i = 0; - erase_lots(term, true, !!(i & 2), !!(i & 1)); - } - seen_disp_event(term); - break; - case 'L': /* IL: insert lines */ - compatibility(VT102); - CLAMP(term->esc_args[0], term->rows); - if (term->curs.y <= term->marg_b) - scroll(term, term->curs.y, term->marg_b, - -def(term->esc_args[0], 1), false); - seen_disp_event(term); - break; - case 'M': /* DL: delete lines */ - compatibility(VT102); - CLAMP(term->esc_args[0], term->rows); - if (term->curs.y <= term->marg_b) - scroll(term, term->curs.y, term->marg_b, - def(term->esc_args[0], 1), - true); - seen_disp_event(term); - break; - case '@': /* ICH: insert chars */ - /* XXX VTTEST says this is vt220, vt510 manual says vt102 */ - compatibility(VT102); - CLAMP(term->esc_args[0], term->cols); - insch(term, def(term->esc_args[0], 1)); - seen_disp_event(term); - break; - case 'P': /* DCH: delete chars */ - compatibility(VT102); - CLAMP(term->esc_args[0], term->cols); - insch(term, -def(term->esc_args[0], 1)); - seen_disp_event(term); - break; - case 'c': /* DA: terminal type query */ - compatibility(VT100); - /* This is the response for a VT102 */ - if (term->ldisc && term->id_string[0]) - ldisc_send(term->ldisc, term->id_string, + seen_disp_event(term); + break; + case 'K': /* EL: erase line or parts of it */ + { + unsigned int i = def(term->esc_args[0], 0) + 1; + if (i > 3) + i = 0; + erase_lots(term, true, !!(i & 2), !!(i & 1)); + } + seen_disp_event(term); + break; + case 'L': /* IL: insert lines */ + compatibility(VT102); + CLAMP(term->esc_args[0], term->rows); + if (term->curs.y <= term->marg_b) + scroll(term, term->curs.y, term->marg_b, + -def(term->esc_args[0], 1), false); + seen_disp_event(term); + break; + case 'M': /* DL: delete lines */ + compatibility(VT102); + CLAMP(term->esc_args[0], term->rows); + if (term->curs.y <= term->marg_b) + scroll(term, term->curs.y, term->marg_b, + def(term->esc_args[0], 1), + true); + seen_disp_event(term); + break; + case '@': /* ICH: insert chars */ + /* XXX VTTEST says this is vt220, vt510 manual says vt102 */ + compatibility(VT102); + CLAMP(term->esc_args[0], term->cols); + insch(term, def(term->esc_args[0], 1)); + seen_disp_event(term); + break; + case 'P': /* DCH: delete chars */ + compatibility(VT102); + CLAMP(term->esc_args[0], term->cols); + insch(term, -def(term->esc_args[0], 1)); + seen_disp_event(term); + break; + case 'c': /* DA: terminal type query */ + compatibility(VT100); + /* This is the response for a VT102 */ + if (term->ldisc && term->id_string[0]) + ldisc_send(term->ldisc, term->id_string, strlen(term->id_string), false); - break; - case 'n': /* DSR: cursor position query */ - if (term->ldisc) { - if (term->esc_args[0] == 6) { - char buf[32]; - sprintf(buf, "\033[%d;%dR", term->curs.y + 1, - term->curs.x + 1); - ldisc_send(term->ldisc, buf, strlen(buf), + break; + case 'n': /* DSR: cursor position query */ + if (term->ldisc) { + if (term->esc_args[0] == 6) { + char buf[32]; + sprintf(buf, "\033[%d;%dR", term->curs.y + 1, + term->curs.x + 1); + ldisc_send(term->ldisc, buf, strlen(buf), false); - } else if (term->esc_args[0] == 5) { - ldisc_send(term->ldisc, "\033[0n", 4, false); - } - } - break; - case 'h': /* SM: toggle modes to high */ - case ANSI_QUE('h'): - compatibility(VT100); - { - int i; - for (i = 0; i < term->esc_nargs; i++) - toggle_mode(term, term->esc_args[i], - term->esc_query, true); - } - break; - case 'i': /* MC: Media copy */ - case ANSI_QUE('i'): - compatibility(VT100); - { - char *printer; - if (term->esc_nargs != 1) break; - if (term->esc_args[0] == 5 && - (printer = conf_get_str(term->conf, - CONF_printer))[0]) { - term->printing = true; - term->only_printing = !term->esc_query; - term->print_state = 0; - term_print_setup(term, printer); - } else if (term->esc_args[0] == 4 && - term->printing) { - term_print_finish(term); - } - } - break; - case 'l': /* RM: toggle modes to low */ - case ANSI_QUE('l'): - compatibility(VT100); - { - int i; - for (i = 0; i < term->esc_nargs; i++) - toggle_mode(term, term->esc_args[i], - term->esc_query, false); - } - break; - case 'g': /* TBC: clear tabs */ - compatibility(VT100); - if (term->esc_nargs == 1) { - if (term->esc_args[0] == 0) { - term->tabs[term->curs.x] = false; - } else if (term->esc_args[0] == 3) { - int i; - for (i = 0; i < term->cols; i++) - term->tabs[i] = false; - } - } - break; - case 'r': /* DECSTBM: set scroll margins */ - compatibility(VT100); - if (term->esc_nargs <= 2) { - int top, bot; - CLAMP(term->esc_args[0], term->rows); - CLAMP(term->esc_args[1], term->rows); - top = def(term->esc_args[0], 1) - 1; - bot = (term->esc_nargs <= 1 - || term->esc_args[1] == 0 ? - term->rows : - def(term->esc_args[1], term->rows)) - 1; - if (bot >= term->rows) - bot = term->rows - 1; - /* VTTEST Bug 9 - if region is less than 2 lines - * don't change region. - */ - if (bot - top > 0) { - term->marg_t = top; - term->marg_b = bot; - term->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 - */ - term->curs.y = (term->dec_om ? - term->marg_t : 0); - seen_disp_event(term); - } - } - break; - case 'm': /* SGR: 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 sometimes DIM, eg on the - * GIGI and Linux - * case 8: - * This is sometimes INVIS various ANSI. - * 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 < term->esc_nargs; i++) { - switch (def(term->esc_args[i], 0)) { - case 0: /* restore defaults */ - term->curr_attr = term->default_attr; - term->curr_truecolour = + } else if (term->esc_args[0] == 5) { + ldisc_send(term->ldisc, "\033[0n", 4, false); + } + } + break; + case 'h': /* SM: toggle modes to high */ + case ANSI_QUE('h'): + compatibility(VT100); + { + int i; + for (i = 0; i < term->esc_nargs; i++) + toggle_mode(term, term->esc_args[i], + term->esc_query, true); + } + break; + case 'i': /* MC: Media copy */ + case ANSI_QUE('i'): + compatibility(VT100); + { + char *printer; + if (term->esc_nargs != 1) break; + if (term->esc_args[0] == 5 && + (printer = conf_get_str(term->conf, + CONF_printer))[0]) { + term->printing = true; + term->only_printing = !term->esc_query; + term->print_state = 0; + term_print_setup(term, printer); + } else if (term->esc_args[0] == 4 && + term->printing) { + term_print_finish(term); + } + } + break; + case 'l': /* RM: toggle modes to low */ + case ANSI_QUE('l'): + compatibility(VT100); + { + int i; + for (i = 0; i < term->esc_nargs; i++) + toggle_mode(term, term->esc_args[i], + term->esc_query, false); + } + break; + case 'g': /* TBC: clear tabs */ + compatibility(VT100); + if (term->esc_nargs == 1) { + if (term->esc_args[0] == 0) { + term->tabs[term->curs.x] = false; + } else if (term->esc_args[0] == 3) { + int i; + for (i = 0; i < term->cols; i++) + term->tabs[i] = false; + } + } + break; + case 'r': /* DECSTBM: set scroll margins */ + compatibility(VT100); + if (term->esc_nargs <= 2) { + int top, bot; + CLAMP(term->esc_args[0], term->rows); + CLAMP(term->esc_args[1], term->rows); + top = def(term->esc_args[0], 1) - 1; + bot = (term->esc_nargs <= 1 + || term->esc_args[1] == 0 ? + term->rows : + def(term->esc_args[1], term->rows)) - 1; + if (bot >= term->rows) + bot = term->rows - 1; + /* VTTEST Bug 9 - if region is less than 2 lines + * don't change region. + */ + if (bot - top > 0) { + term->marg_t = top; + term->marg_b = bot; + term->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 + */ + term->curs.y = (term->dec_om ? + term->marg_t : 0); + seen_disp_event(term); + } + } + break; + case 'm': /* SGR: 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 sometimes DIM, eg on the + * GIGI and Linux + * case 8: + * This is sometimes INVIS various ANSI. + * 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 < term->esc_nargs; i++) { + switch (def(term->esc_args[i], 0)) { + case 0: /* restore defaults */ + term->curr_attr = term->default_attr; + term->curr_truecolour = term->basic_erase_char.truecolour; - break; - case 1: /* enable bold */ - compatibility(VT100AVO); - term->curr_attr |= ATTR_BOLD; - break; - case 2: /* enable dim */ - compatibility(OTHER); - term->curr_attr |= ATTR_DIM; - break; - case 21: /* (enable double underline) */ - compatibility(OTHER); - case 4: /* enable underline */ - compatibility(VT100AVO); - term->curr_attr |= ATTR_UNDER; - break; - case 5: /* enable blink */ - compatibility(VT100AVO); - term->curr_attr |= ATTR_BLINK; - break; - case 6: /* SCO light bkgrd */ - compatibility(SCOANSI); - term->blink_is_real = false; - term->curr_attr |= ATTR_BLINK; - term_schedule_tblink(term); - break; - case 7: /* enable reverse video */ - term->curr_attr |= ATTR_REVERSE; - break; - case 10: /* SCO acs off */ - compatibility(SCOANSI); - if (term->no_remote_charset) break; - term->sco_acs = 0; break; - case 11: /* SCO acs on */ - compatibility(SCOANSI); - if (term->no_remote_charset) break; - term->sco_acs = 1; break; - case 12: /* SCO acs on, |0x80 */ - compatibility(SCOANSI); - if (term->no_remote_charset) break; - term->sco_acs = 2; break; - case 22: /* disable bold and dim */ - compatibility2(OTHER, VT220); - term->curr_attr &= ~(ATTR_BOLD | ATTR_DIM); - break; - case 24: /* disable underline */ - compatibility2(OTHER, VT220); - term->curr_attr &= ~ATTR_UNDER; - break; - case 25: /* disable blink */ - compatibility2(OTHER, VT220); - term->curr_attr &= ~ATTR_BLINK; - break; - case 27: /* disable reverse video */ - compatibility2(OTHER, VT220); - term->curr_attr &= ~ATTR_REVERSE; - break; - case 30: - case 31: - case 32: - case 33: - case 34: - case 35: - case 36: - case 37: - /* foreground */ - term->curr_truecolour.fg.enabled = false; - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr |= - (term->esc_args[i] - 30)<curr_truecolour.fg.enabled = false; - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr |= - ((term->esc_args[i] - 90 + 8) + break; + case 1: /* enable bold */ + compatibility(VT100AVO); + term->curr_attr |= ATTR_BOLD; + break; + case 2: /* enable dim */ + compatibility(OTHER); + term->curr_attr |= ATTR_DIM; + break; + case 21: /* (enable double underline) */ + compatibility(OTHER); + case 4: /* enable underline */ + compatibility(VT100AVO); + term->curr_attr |= ATTR_UNDER; + break; + case 5: /* enable blink */ + compatibility(VT100AVO); + term->curr_attr |= ATTR_BLINK; + break; + case 6: /* SCO light bkgrd */ + compatibility(SCOANSI); + term->blink_is_real = false; + term->curr_attr |= ATTR_BLINK; + term_schedule_tblink(term); + break; + case 7: /* enable reverse video */ + term->curr_attr |= ATTR_REVERSE; + break; + case 10: /* SCO acs off */ + compatibility(SCOANSI); + if (term->no_remote_charset) break; + term->sco_acs = 0; break; + case 11: /* SCO acs on */ + compatibility(SCOANSI); + if (term->no_remote_charset) break; + term->sco_acs = 1; break; + case 12: /* SCO acs on, |0x80 */ + compatibility(SCOANSI); + if (term->no_remote_charset) break; + term->sco_acs = 2; break; + case 22: /* disable bold and dim */ + compatibility2(OTHER, VT220); + term->curr_attr &= ~(ATTR_BOLD | ATTR_DIM); + break; + case 24: /* disable underline */ + compatibility2(OTHER, VT220); + term->curr_attr &= ~ATTR_UNDER; + break; + case 25: /* disable blink */ + compatibility2(OTHER, VT220); + term->curr_attr &= ~ATTR_BLINK; + break; + case 27: /* disable reverse video */ + compatibility2(OTHER, VT220); + term->curr_attr &= ~ATTR_REVERSE; + break; + case 30: + case 31: + case 32: + case 33: + case 34: + case 35: + case 36: + case 37: + /* foreground */ + term->curr_truecolour.fg.enabled = false; + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr |= + (term->esc_args[i] - 30)<curr_truecolour.fg.enabled = false; + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr |= + ((term->esc_args[i] - 90 + 8) << ATTR_FGSHIFT); - break; - case 39: /* default-foreground */ - term->curr_truecolour.fg.enabled = false; - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr |= ATTR_DEFFG; - break; - case 40: - case 41: - case 42: - case 43: - case 44: - case 45: - case 46: - case 47: - /* background */ - term->curr_truecolour.bg.enabled = false; - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr |= - (term->esc_args[i] - 40)<curr_truecolour.bg.enabled = false; - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr |= - ((term->esc_args[i] - 100 + 8) + break; + case 39: /* default-foreground */ + term->curr_truecolour.fg.enabled = false; + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr |= ATTR_DEFFG; + break; + case 40: + case 41: + case 42: + case 43: + case 44: + case 45: + case 46: + case 47: + /* background */ + term->curr_truecolour.bg.enabled = false; + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr |= + (term->esc_args[i] - 40)<curr_truecolour.bg.enabled = false; + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr |= + ((term->esc_args[i] - 100 + 8) << ATTR_BGSHIFT); - break; - case 49: /* default-background */ - term->curr_truecolour.bg.enabled = false; - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr |= ATTR_DEFBG; - break; + break; + case 49: /* default-background */ + term->curr_truecolour.bg.enabled = false; + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr |= ATTR_DEFBG; + break; /* * 256-colour and true-colour @@ -4215,505 +4215,505 @@ static void term_out(Terminal *term) * cases selects the same colour * as the background. */ - case 38: - if (i+2 < term->esc_nargs && - term->esc_args[i+1] == 5) { - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr |= - ((term->esc_args[i+2] & 0xFF) - << ATTR_FGSHIFT); + case 38: + if (i+2 < term->esc_nargs && + term->esc_args[i+1] == 5) { + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr |= + ((term->esc_args[i+2] & 0xFF) + << ATTR_FGSHIFT); term->curr_truecolour.fg = optionalrgb_none; - i += 2; - } - if (i + 4 < term->esc_nargs && - term->esc_args[i + 1] == 2) { - parse_optionalrgb( + i += 2; + } + if (i + 4 < term->esc_nargs && + term->esc_args[i + 1] == 2) { + parse_optionalrgb( &term->curr_truecolour.fg, term->esc_args + (i+2)); - i += 4; - } - break; - case 48: - if (i+2 < term->esc_nargs && - term->esc_args[i+1] == 5) { - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr |= - ((term->esc_args[i+2] & 0xFF) - << ATTR_BGSHIFT); + i += 4; + } + break; + case 48: + if (i+2 < term->esc_nargs && + term->esc_args[i+1] == 5) { + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr |= + ((term->esc_args[i+2] & 0xFF) + << ATTR_BGSHIFT); term->curr_truecolour.bg = optionalrgb_none; - i += 2; - } - if (i + 4 < term->esc_nargs && - term->esc_args[i+1] == 2) { - parse_optionalrgb( + i += 2; + } + if (i + 4 < term->esc_nargs && + term->esc_args[i+1] == 2) { + parse_optionalrgb( &term->curr_truecolour.bg, term->esc_args + (i+2)); - i += 4; - } - break; - } - } - set_erase_char(term); - } - break; - case 's': /* save cursor */ - save_cursor(term, true); - break; - case 'u': /* restore cursor */ - save_cursor(term, false); - seen_disp_event(term); - break; - case 't': /* DECSLPP: 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. - */ - if (term->esc_nargs <= 1 - && (term->esc_args[0] < 1 || - term->esc_args[0] >= 24)) { - compatibility(VT340TEXT); - if (!term->no_remote_resize) - win_request_resize(term->win, term->cols, + i += 4; + } + break; + } + } + set_erase_char(term); + } + break; + case 's': /* save cursor */ + save_cursor(term, true); + break; + case 'u': /* restore cursor */ + save_cursor(term, false); + seen_disp_event(term); + break; + case 't': /* DECSLPP: 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. + */ + if (term->esc_nargs <= 1 + && (term->esc_args[0] < 1 || + term->esc_args[0] >= 24)) { + compatibility(VT340TEXT); + if (!term->no_remote_resize) + win_request_resize(term->win, term->cols, def(term->esc_args[0], 24)); - deselect(term); - } else if (term->esc_nargs >= 1 && - term->esc_args[0] >= 1 && - term->esc_args[0] < 24) { - compatibility(OTHER); + deselect(term); + } else if (term->esc_nargs >= 1 && + term->esc_args[0] >= 1 && + term->esc_args[0] < 24) { + compatibility(OTHER); - switch (term->esc_args[0]) { - int x, y, len; - char buf[80]; + switch (term->esc_args[0]) { + int x, y, len; + char buf[80]; const char *p; - case 1: - win_set_minimised(term->win, false); - break; - case 2: - win_set_minimised(term->win, true); - break; - case 3: - if (term->esc_nargs >= 3) { - if (!term->no_remote_resize) - win_move(term->win, + case 1: + win_set_minimised(term->win, false); + break; + case 2: + win_set_minimised(term->win, true); + break; + case 3: + if (term->esc_nargs >= 3) { + if (!term->no_remote_resize) + win_move(term->win, def(term->esc_args[1], 0), def(term->esc_args[2], 0)); - } - break; - case 4: - /* We should resize the window to a given - * size in pixels here, but currently our - * resizing code isn't healthy enough to - * manage it. */ - break; - case 5: - /* move to top */ - win_set_zorder(term->win, true); - break; - case 6: - /* move to bottom */ - win_set_zorder(term->win, false); - break; - case 7: - win_refresh(term->win); - break; - case 8: - if (term->esc_nargs >= 3) { - if (!term->no_remote_resize) - win_request_resize( + } + break; + case 4: + /* We should resize the window to a given + * size in pixels here, but currently our + * resizing code isn't healthy enough to + * manage it. */ + break; + case 5: + /* move to top */ + win_set_zorder(term->win, true); + break; + case 6: + /* move to bottom */ + win_set_zorder(term->win, false); + break; + case 7: + win_refresh(term->win); + break; + case 8: + if (term->esc_nargs >= 3) { + if (!term->no_remote_resize) + win_request_resize( term->win, def(term->esc_args[2], term->conf_width), def(term->esc_args[1], term->conf_height)); - } - break; - case 9: - if (term->esc_nargs >= 2) - win_set_maximised( + } + break; + case 9: + if (term->esc_nargs >= 2) + win_set_maximised( term->win, term->esc_args[1] ? true : false); - break; - case 11: - if (term->ldisc) - ldisc_send(term->ldisc, - win_is_minimised(term->win) ? - "\033[2t" : "\033[1t", 4, + break; + case 11: + if (term->ldisc) + ldisc_send(term->ldisc, + win_is_minimised(term->win) ? + "\033[2t" : "\033[1t", 4, false); - break; - case 13: - if (term->ldisc) { - win_get_pos(term->win, &x, &y); - len = sprintf(buf, "\033[3;%u;%ut", + break; + case 13: + if (term->ldisc) { + win_get_pos(term->win, &x, &y); + len = sprintf(buf, "\033[3;%u;%ut", (unsigned)x, (unsigned)y); - ldisc_send(term->ldisc, buf, len, false); - } - break; - case 14: - if (term->ldisc) { - win_get_pixels(term->win, &x, &y); - len = sprintf(buf, "\033[4;%d;%dt", y, x); - ldisc_send(term->ldisc, buf, len, false); - } - break; - case 18: - if (term->ldisc) { - len = sprintf(buf, "\033[8;%d;%dt", - term->rows, term->cols); - ldisc_send(term->ldisc, buf, len, false); - } - break; - case 19: - /* - * Hmmm. Strictly speaking we - * should return `the size of the - * screen in characters', but - * that's not easy: (a) window - * furniture being what it is it's - * hard to compute, and (b) in - * resize-font mode maximising the - * window wouldn't change the - * number of characters. *shrug*. I - * think we'll ignore it for the - * moment and see if anyone - * complains, and then ask them - * what they would like it to do. - */ - break; - case 20: - if (term->ldisc && - term->remote_qtitle_action != TITLE_NONE) { - if(term->remote_qtitle_action == TITLE_REAL) - p = win_get_title(term->win, true); - else - p = EMPTY_WINDOW_TITLE; - len = strlen(p); - ldisc_send(term->ldisc, "\033]L", 3, + ldisc_send(term->ldisc, buf, len, false); + } + break; + case 14: + if (term->ldisc) { + win_get_pixels(term->win, &x, &y); + len = sprintf(buf, "\033[4;%d;%dt", y, x); + ldisc_send(term->ldisc, buf, len, false); + } + break; + case 18: + if (term->ldisc) { + len = sprintf(buf, "\033[8;%d;%dt", + term->rows, term->cols); + ldisc_send(term->ldisc, buf, len, false); + } + break; + case 19: + /* + * Hmmm. Strictly speaking we + * should return `the size of the + * screen in characters', but + * that's not easy: (a) window + * furniture being what it is it's + * hard to compute, and (b) in + * resize-font mode maximising the + * window wouldn't change the + * number of characters. *shrug*. I + * think we'll ignore it for the + * moment and see if anyone + * complains, and then ask them + * what they would like it to do. + */ + break; + case 20: + if (term->ldisc && + term->remote_qtitle_action != TITLE_NONE) { + if(term->remote_qtitle_action == TITLE_REAL) + p = win_get_title(term->win, true); + else + p = EMPTY_WINDOW_TITLE; + len = strlen(p); + ldisc_send(term->ldisc, "\033]L", 3, false); if (len > 0) ldisc_send(term->ldisc, p, len, false); - ldisc_send(term->ldisc, "\033\\", 2, + ldisc_send(term->ldisc, "\033\\", 2, false); - } - break; - case 21: - if (term->ldisc && - term->remote_qtitle_action != TITLE_NONE) { - if(term->remote_qtitle_action == TITLE_REAL) - p = win_get_title(term->win, false); - else - p = EMPTY_WINDOW_TITLE; - len = strlen(p); - ldisc_send(term->ldisc, "\033]l", 3, + } + break; + case 21: + if (term->ldisc && + term->remote_qtitle_action != TITLE_NONE) { + if(term->remote_qtitle_action == TITLE_REAL) + p = win_get_title(term->win, false); + else + p = EMPTY_WINDOW_TITLE; + len = strlen(p); + ldisc_send(term->ldisc, "\033]l", 3, false); if (len > 0) ldisc_send(term->ldisc, p, len, false); - ldisc_send(term->ldisc, "\033\\", 2, + ldisc_send(term->ldisc, "\033\\", 2, false); - } - break; - } - } - break; - case 'S': /* SU: Scroll up */ - CLAMP(term->esc_args[0], term->rows); - compatibility(SCOANSI); - scroll(term, term->marg_t, term->marg_b, - def(term->esc_args[0], 1), true); - term->wrapnext = false; - seen_disp_event(term); - break; - case 'T': /* SD: Scroll down */ - CLAMP(term->esc_args[0], term->rows); - compatibility(SCOANSI); - scroll(term, term->marg_t, term->marg_b, - -def(term->esc_args[0], 1), true); - term->wrapnext = false; - seen_disp_event(term); - break; - case ANSI('|', '*'): /* 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 (term->esc_nargs == 1 && term->esc_args[0] > 0) { - if (!term->no_remote_resize) - win_request_resize(term->win, term->cols, + } + break; + } + } + break; + case 'S': /* SU: Scroll up */ + CLAMP(term->esc_args[0], term->rows); + compatibility(SCOANSI); + scroll(term, term->marg_t, term->marg_b, + def(term->esc_args[0], 1), true); + term->wrapnext = false; + seen_disp_event(term); + break; + case 'T': /* SD: Scroll down */ + CLAMP(term->esc_args[0], term->rows); + compatibility(SCOANSI); + scroll(term, term->marg_t, term->marg_b, + -def(term->esc_args[0], 1), true); + term->wrapnext = false; + seen_disp_event(term); + break; + case ANSI('|', '*'): /* 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 (term->esc_nargs == 1 && term->esc_args[0] > 0) { + if (!term->no_remote_resize) + win_request_resize(term->win, term->cols, def(term->esc_args[0], term->conf_height)); - deselect(term); - } - break; - case ANSI('|', '$'): /* DECSCPP */ - /* - * Set number of columns per page - * Docs imply range is only 80 or 132, but - * I'll allow any. - */ - compatibility(VT340TEXT); - if (term->esc_nargs <= 1) { - if (!term->no_remote_resize) - win_request_resize( + deselect(term); + } + break; + case ANSI('|', '$'): /* DECSCPP */ + /* + * Set number of columns per page + * Docs imply range is only 80 or 132, but + * I'll allow any. + */ + compatibility(VT340TEXT); + if (term->esc_nargs <= 1) { + if (!term->no_remote_resize) + win_request_resize( term->win, def(term->esc_args[0], term->conf_width), term->rows); - deselect(term); - } - break; - case 'X': /* ECH: write N spaces w/o moving cursor */ - /* XXX VTTEST says this is vt220, vt510 manual - * says vt100 */ - compatibility(ANSIMIN); - CLAMP(term->esc_args[0], term->cols); - { - int n = def(term->esc_args[0], 1); - pos cursplus; - int p = term->curs.x; - termline *cline = scrlineptr(term->curs.y); + deselect(term); + } + break; + case 'X': /* ECH: write N spaces w/o moving cursor */ + /* XXX VTTEST says this is vt220, vt510 manual + * says vt100 */ + compatibility(ANSIMIN); + CLAMP(term->esc_args[0], term->cols); + { + int n = def(term->esc_args[0], 1); + pos cursplus; + int p = term->curs.x; + termline *cline = scrlineptr(term->curs.y); check_trust_status(term, cline); - if (n > term->cols - term->curs.x) - n = term->cols - term->curs.x; - cursplus = term->curs; - cursplus.x += n; - check_boundary(term, term->curs.x, term->curs.y); - check_boundary(term, term->curs.x+n, term->curs.y); - check_selection(term, term->curs, cursplus); - while (n--) - copy_termchar(cline, p++, - &term->erase_char); - seen_disp_event(term); - } - break; - case 'x': /* DECREQTPARM: report terminal characteristics */ - compatibility(VT100); - if (term->ldisc) { - char buf[32]; - int i = def(term->esc_args[0], 0); - if (i == 0 || i == 1) { - strcpy(buf, "\033[2;1;1;112;112;1;0x"); - buf[2] += i; - ldisc_send(term->ldisc, buf, 20, false); - } - } - break; - case 'Z': /* CBT */ - compatibility(OTHER); - CLAMP(term->esc_args[0], term->cols); - { - int i = def(term->esc_args[0], 1); - pos old_curs = term->curs; + if (n > term->cols - term->curs.x) + n = term->cols - term->curs.x; + cursplus = term->curs; + cursplus.x += n; + check_boundary(term, term->curs.x, term->curs.y); + check_boundary(term, term->curs.x+n, term->curs.y); + check_selection(term, term->curs, cursplus); + while (n--) + copy_termchar(cline, p++, + &term->erase_char); + seen_disp_event(term); + } + break; + case 'x': /* DECREQTPARM: report terminal characteristics */ + compatibility(VT100); + if (term->ldisc) { + char buf[32]; + int i = def(term->esc_args[0], 0); + if (i == 0 || i == 1) { + strcpy(buf, "\033[2;1;1;112;112;1;0x"); + buf[2] += i; + ldisc_send(term->ldisc, buf, 20, false); + } + } + break; + case 'Z': /* CBT */ + compatibility(OTHER); + CLAMP(term->esc_args[0], term->cols); + { + int i = def(term->esc_args[0], 1); + pos old_curs = term->curs; - for(;i>0 && term->curs.x>0; i--) { - do { - term->curs.x--; - } while (term->curs.x >0 && - !term->tabs[term->curs.x]); - } - check_selection(term, old_curs, term->curs); - } - break; - case ANSI('c', '='): /* Hide or Show Cursor */ - compatibility(SCOANSI); - switch(term->esc_args[0]) { - case 0: /* hide cursor */ - term->cursor_on = false; - break; - case 1: /* restore cursor */ - term->big_cursor = false; - term->cursor_on = true; - break; - case 2: /* block cursor */ - term->big_cursor = true; - term->cursor_on = true; - break; - } - break; - case ANSI('C', '='): - /* - * set cursor start on scanline esc_args[0] and - * end on scanline esc_args[1].If you set - * the bottom scan line to a value less than - * the top scan line, the cursor will disappear. - */ - compatibility(SCOANSI); - if (term->esc_nargs >= 2) { - if (term->esc_args[0] > term->esc_args[1]) - term->cursor_on = false; - else - term->cursor_on = true; - } - break; - case ANSI('D', '='): - compatibility(SCOANSI); - term->blink_is_real = false; - term_schedule_tblink(term); - if (term->esc_args[0]>=1) - term->curr_attr |= ATTR_BLINK; - else - term->curr_attr &= ~ATTR_BLINK; - break; - case ANSI('E', '='): - compatibility(SCOANSI); - term->blink_is_real = (term->esc_args[0] >= 1); - term_schedule_tblink(term); - break; - case ANSI('F', '='): /* set normal foreground */ - compatibility(SCOANSI); - if (term->esc_args[0] < 16) { - long colour = - (sco2ansicolour[term->esc_args[0] & 0x7] | - (term->esc_args[0] & 0x8)) << - ATTR_FGSHIFT; - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr |= colour; + for(;i>0 && term->curs.x>0; i--) { + do { + term->curs.x--; + } while (term->curs.x >0 && + !term->tabs[term->curs.x]); + } + check_selection(term, old_curs, term->curs); + } + break; + case ANSI('c', '='): /* Hide or Show Cursor */ + compatibility(SCOANSI); + switch(term->esc_args[0]) { + case 0: /* hide cursor */ + term->cursor_on = false; + break; + case 1: /* restore cursor */ + term->big_cursor = false; + term->cursor_on = true; + break; + case 2: /* block cursor */ + term->big_cursor = true; + term->cursor_on = true; + break; + } + break; + case ANSI('C', '='): + /* + * set cursor start on scanline esc_args[0] and + * end on scanline esc_args[1].If you set + * the bottom scan line to a value less than + * the top scan line, the cursor will disappear. + */ + compatibility(SCOANSI); + if (term->esc_nargs >= 2) { + if (term->esc_args[0] > term->esc_args[1]) + term->cursor_on = false; + else + term->cursor_on = true; + } + break; + case ANSI('D', '='): + compatibility(SCOANSI); + term->blink_is_real = false; + term_schedule_tblink(term); + if (term->esc_args[0]>=1) + term->curr_attr |= ATTR_BLINK; + else + term->curr_attr &= ~ATTR_BLINK; + break; + case ANSI('E', '='): + compatibility(SCOANSI); + term->blink_is_real = (term->esc_args[0] >= 1); + term_schedule_tblink(term); + break; + case ANSI('F', '='): /* set normal foreground */ + compatibility(SCOANSI); + if (term->esc_args[0] < 16) { + long colour = + (sco2ansicolour[term->esc_args[0] & 0x7] | + (term->esc_args[0] & 0x8)) << + ATTR_FGSHIFT; + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr |= colour; term->curr_truecolour.fg = optionalrgb_none; - term->default_attr &= ~ATTR_FGMASK; - term->default_attr |= colour; - set_erase_char(term); - } - break; - case ANSI('G', '='): /* set normal background */ - compatibility(SCOANSI); - if (term->esc_args[0] < 16) { - long colour = - (sco2ansicolour[term->esc_args[0] & 0x7] | - (term->esc_args[0] & 0x8)) << - ATTR_BGSHIFT; - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr |= colour; + term->default_attr &= ~ATTR_FGMASK; + term->default_attr |= colour; + set_erase_char(term); + } + break; + case ANSI('G', '='): /* set normal background */ + compatibility(SCOANSI); + if (term->esc_args[0] < 16) { + long colour = + (sco2ansicolour[term->esc_args[0] & 0x7] | + (term->esc_args[0] & 0x8)) << + ATTR_BGSHIFT; + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr |= colour; term->curr_truecolour.bg = optionalrgb_none; - term->default_attr &= ~ATTR_BGMASK; - term->default_attr |= colour; - set_erase_char(term); - } - break; - case ANSI('L', '='): - compatibility(SCOANSI); - term->use_bce = (term->esc_args[0] <= 0); - set_erase_char(term); - break; - case ANSI('p', '"'): /* DECSCL: set compat level */ - /* - * 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,50 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! - */ + term->default_attr &= ~ATTR_BGMASK; + term->default_attr |= colour; + set_erase_char(term); + } + break; + case ANSI('L', '='): + compatibility(SCOANSI); + term->use_bce = (term->esc_args[0] <= 0); + set_erase_char(term); + break; + case ANSI('p', '"'): /* DECSCL: set compat level */ + /* + * 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,50 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 (term->esc_args[0]) { - case 61: - term->compatibility_level &= ~TM_VTXXX; - term->compatibility_level |= TM_VT102; - break; - case 62: - term->compatibility_level &= ~TM_VTXXX; - term->compatibility_level |= TM_VT220; - break; + switch (term->esc_args[0]) { + case 61: + term->compatibility_level &= ~TM_VTXXX; + term->compatibility_level |= TM_VT102; + break; + case 62: + term->compatibility_level &= ~TM_VTXXX; + term->compatibility_level |= TM_VT220; + break; - default: - if (term->esc_args[0] > 60 && - term->esc_args[0] < 70) - term->compatibility_level |= TM_VTXXX; - break; + default: + if (term->esc_args[0] > 60 && + term->esc_args[0] < 70) + term->compatibility_level |= TM_VTXXX; + break; - case 40: - term->compatibility_level &= TM_VTXXX; - break; - case 41: - term->compatibility_level = TM_PUTTY; - break; - case 42: - term->compatibility_level = TM_SCOANSI; - break; + case 40: + term->compatibility_level &= TM_VTXXX; + break; + case 41: + term->compatibility_level = TM_PUTTY; + break; + case 42: + term->compatibility_level = TM_SCOANSI; + break; - case ARG_DEFAULT: - term->compatibility_level = TM_PUTTY; - break; - case 50: - break; - } + case ARG_DEFAULT: + term->compatibility_level = TM_PUTTY; + break; + case 50: + break; + } - /* Change the response to CSI c */ - if (term->esc_args[0] == 50) { - int i; - char lbuf[64]; - strcpy(term->id_string, "\033[?"); - for (i = 1; i < term->esc_nargs; i++) { - if (i != 1) - strcat(term->id_string, ";"); - sprintf(lbuf, "%u", term->esc_args[i]); - strcat(term->id_string, lbuf); - } - strcat(term->id_string, "c"); - } + /* Change the response to CSI c */ + if (term->esc_args[0] == 50) { + int i; + char lbuf[64]; + strcpy(term->id_string, "\033[?"); + for (i = 1; i < term->esc_nargs; i++) { + if (i != 1) + strcat(term->id_string, ";"); + sprintf(lbuf, "%u", term->esc_args[i]); + strcat(term->id_string, lbuf); + } + strcat(term->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 (!term->no_remote_resize) { - if (term->reset_132) - win_request_resize(term->win, 132, 24); - else - win_request_resize(term->win, 80, 24); - } - } + /* Is this a good idea ? + * Well we should do a soft reset at this point ... + */ + if (!has_compat(VT420) && has_compat(VT100)) { + if (!term->no_remote_resize) { + if (term->reset_132) + win_request_resize(term->win, 132, 24); + else + win_request_resize(term->win, 80, 24); + } + } #endif - break; - } - break; - case SEEN_OSC: - term->osc_w = false; - switch (c) { - case 'P': /* Linux palette sequence */ - term->termstate = SEEN_OSC_P; - term->osc_strlen = 0; - break; - case 'R': /* Linux palette reset */ - win_palette_reset(term->win); - term_invalidate(term); - term->termstate = TOPLEVEL; - break; - case 'W': /* word-set */ - term->termstate = SEEN_OSC_W; - term->osc_w = true; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (term->esc_args[term->esc_nargs-1] <= UINT_MAX / 10 && - term->esc_args[term->esc_nargs-1] * 10 <= UINT_MAX - c - '0') - term->esc_args[term->esc_nargs-1] = + break; + } + break; + case SEEN_OSC: + term->osc_w = false; + switch (c) { + case 'P': /* Linux palette sequence */ + term->termstate = SEEN_OSC_P; + term->osc_strlen = 0; + break; + case 'R': /* Linux palette reset */ + win_palette_reset(term->win); + term_invalidate(term); + term->termstate = TOPLEVEL; + break; + case 'W': /* word-set */ + term->termstate = SEEN_OSC_W; + term->osc_w = true; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (term->esc_args[term->esc_nargs-1] <= UINT_MAX / 10 && + term->esc_args[term->esc_nargs-1] * 10 <= UINT_MAX - c - '0') + term->esc_args[term->esc_nargs-1] = 10 * term->esc_args[term->esc_nargs-1] + c - '0'; - else - term->esc_args[term->esc_nargs-1] = UINT_MAX; - break; + else + term->esc_args[term->esc_nargs-1] = UINT_MAX; + break; default: /* * _Most_ other characters here terminate the @@ -4741,345 +4741,345 @@ static void term_out(Terminal *term) term->termstate = OSC_STRING; term->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 == '\012' || c == '\015') { - term->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(term); - term->termstate = TOPLEVEL; - } else if (c == '\033') - term->termstate = OSC_MAYBE_ST; - else if (term->osc_strlen < OSC_STR_MAX) - term->osc_string[term->osc_strlen++] = (char)c; - break; - case SEEN_OSC_P: - { - int max = (term->osc_strlen == 0 ? 21 : 15); - int val; - if ((int)c >= '0' && (int)c <= '9') - val = c - '0'; - else if ((int)c >= 'A' && (int)c <= 'A' + max - 10) - val = c - 'A' + 10; - else if ((int)c >= 'a' && (int)c <= 'a' + max - 10) - val = c - 'a' + 10; - else { - term->termstate = TOPLEVEL; - break; - } - term->osc_string[term->osc_strlen++] = val; - if (term->osc_strlen >= 7) { - win_palette_set( + } + 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 == '\012' || c == '\015') { + term->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(term); + term->termstate = TOPLEVEL; + } else if (c == '\033') + term->termstate = OSC_MAYBE_ST; + else if (term->osc_strlen < OSC_STR_MAX) + term->osc_string[term->osc_strlen++] = (char)c; + break; + case SEEN_OSC_P: + { + int max = (term->osc_strlen == 0 ? 21 : 15); + int val; + if ((int)c >= '0' && (int)c <= '9') + val = c - '0'; + else if ((int)c >= 'A' && (int)c <= 'A' + max - 10) + val = c - 'A' + 10; + else if ((int)c >= 'a' && (int)c <= 'a' + max - 10) + val = c - 'a' + 10; + else { + term->termstate = TOPLEVEL; + break; + } + term->osc_string[term->osc_strlen++] = val; + if (term->osc_strlen >= 7) { + win_palette_set( term->win, term->osc_string[0], term->osc_string[1] * 16 + term->osc_string[2], term->osc_string[3] * 16 + term->osc_string[4], term->osc_string[5] * 16 + term->osc_string[6]); - term_invalidate(term); - term->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': - if (term->esc_args[0] <= UINT_MAX / 10 && - term->esc_args[0] * 10 <= UINT_MAX - c - '0') - term->esc_args[0] = 10 * term->esc_args[0] + c - '0'; - else - term->esc_args[0] = UINT_MAX; - break; - default: - term->termstate = OSC_STRING; - term->osc_strlen = 0; - } - break; - case VT52_ESC: - term->termstate = TOPLEVEL; - seen_disp_event(term); - switch (c) { - case 'A': - move(term, term->curs.x, term->curs.y - 1, 1); - break; - case 'B': - move(term, term->curs.x, term->curs.y + 1, 1); - break; - case 'C': - move(term, term->curs.x + 1, term->curs.y, 1); - break; - case 'D': - move(term, term->curs.x - 1, term->curs.y, 1); - break; - /* - * From the VT100 Manual - * NOTE: The special graphics characters in the VT100 - * are different from those in the VT52 - * - * From VT102 manual: - * 137 _ Blank - Same - * 140 ` Reserved - Humm. - * 141 a Solid rectangle - Similar - * 142 b 1/ - Top half of fraction for the - * 143 c 3/ - subscript numbers below. - * 144 d 5/ - * 145 e 7/ - * 146 f Degrees - Same - * 147 g Plus or minus - Same - * 150 h Right arrow - * 151 i Ellipsis (dots) - * 152 j Divide by - * 153 k Down arrow - * 154 l Bar at scan 0 - * 155 m Bar at scan 1 - * 156 n Bar at scan 2 - * 157 o Bar at scan 3 - Similar - * 160 p Bar at scan 4 - Similar - * 161 q Bar at scan 5 - Similar - * 162 r Bar at scan 6 - Same - * 163 s Bar at scan 7 - Similar - * 164 t Subscript 0 - * 165 u Subscript 1 - * 166 v Subscript 2 - * 167 w Subscript 3 - * 170 x Subscript 4 - * 171 y Subscript 5 - * 172 z Subscript 6 - * 173 { Subscript 7 - * 174 | Subscript 8 - * 175 } Subscript 9 - * 176 ~ Paragraph - * - */ - case 'F': - term->cset_attr[term->cset = 0] = CSET_LINEDRW; - break; - case 'G': - term->cset_attr[term->cset = 0] = CSET_ASCII; - break; - case 'H': - move(term, 0, 0, 0); - break; - case 'I': - if (term->curs.y == 0) - scroll(term, 0, term->rows - 1, -1, true); - else if (term->curs.y > 0) - term->curs.y--; - term->wrapnext = false; - break; - case 'J': - erase_lots(term, false, false, true); + term_invalidate(term); + term->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': + if (term->esc_args[0] <= UINT_MAX / 10 && + term->esc_args[0] * 10 <= UINT_MAX - c - '0') + term->esc_args[0] = 10 * term->esc_args[0] + c - '0'; + else + term->esc_args[0] = UINT_MAX; + break; + default: + term->termstate = OSC_STRING; + term->osc_strlen = 0; + } + break; + case VT52_ESC: + term->termstate = TOPLEVEL; + seen_disp_event(term); + switch (c) { + case 'A': + move(term, term->curs.x, term->curs.y - 1, 1); + break; + case 'B': + move(term, term->curs.x, term->curs.y + 1, 1); + break; + case 'C': + move(term, term->curs.x + 1, term->curs.y, 1); + break; + case 'D': + move(term, term->curs.x - 1, term->curs.y, 1); + break; + /* + * From the VT100 Manual + * NOTE: The special graphics characters in the VT100 + * are different from those in the VT52 + * + * From VT102 manual: + * 137 _ Blank - Same + * 140 ` Reserved - Humm. + * 141 a Solid rectangle - Similar + * 142 b 1/ - Top half of fraction for the + * 143 c 3/ - subscript numbers below. + * 144 d 5/ + * 145 e 7/ + * 146 f Degrees - Same + * 147 g Plus or minus - Same + * 150 h Right arrow + * 151 i Ellipsis (dots) + * 152 j Divide by + * 153 k Down arrow + * 154 l Bar at scan 0 + * 155 m Bar at scan 1 + * 156 n Bar at scan 2 + * 157 o Bar at scan 3 - Similar + * 160 p Bar at scan 4 - Similar + * 161 q Bar at scan 5 - Similar + * 162 r Bar at scan 6 - Same + * 163 s Bar at scan 7 - Similar + * 164 t Subscript 0 + * 165 u Subscript 1 + * 166 v Subscript 2 + * 167 w Subscript 3 + * 170 x Subscript 4 + * 171 y Subscript 5 + * 172 z Subscript 6 + * 173 { Subscript 7 + * 174 | Subscript 8 + * 175 } Subscript 9 + * 176 ~ Paragraph + * + */ + case 'F': + term->cset_attr[term->cset = 0] = CSET_LINEDRW; + break; + case 'G': + term->cset_attr[term->cset = 0] = CSET_ASCII; + break; + case 'H': + move(term, 0, 0, 0); + break; + case 'I': + if (term->curs.y == 0) + scroll(term, 0, term->rows - 1, -1, true); + else if (term->curs.y > 0) + term->curs.y--; + term->wrapnext = false; + break; + case 'J': + erase_lots(term, false, false, true); if (term->scroll_on_disp) term->disptop = 0; - break; - case 'K': - erase_lots(term, true, false, true); - break; + break; + case 'K': + erase_lots(term, true, false, true); + break; #if 0 - case 'V': - /* XXX Print cursor line */ - break; - case 'W': - /* XXX Start controller mode */ - break; - case 'X': - /* XXX Stop controller mode */ - break; + case 'V': + /* XXX Print cursor line */ + break; + case 'W': + /* XXX Start controller mode */ + break; + case 'X': + /* XXX Stop controller mode */ + break; #endif - case 'Y': - term->termstate = VT52_Y1; - break; - case 'Z': - if (term->ldisc) - ldisc_send(term->ldisc, "\033/Z", 3, false); - break; - case '=': - term->app_keypad_keys = true; - break; - case '>': - term->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. - */ - term->vt52_mode = false; - term->blink_is_real = term->blinktext; - term_schedule_tblink(term); - break; + case 'Y': + term->termstate = VT52_Y1; + break; + case 'Z': + if (term->ldisc) + ldisc_send(term->ldisc, "\033/Z", 3, false); + break; + case '=': + term->app_keypad_keys = true; + break; + case '>': + term->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. + */ + term->vt52_mode = false; + term->blink_is_real = term->blinktext; + term_schedule_tblink(term); + break; #if 0 - case '^': - /* XXX Enter auto print mode */ - break; - case '_': - /* XXX Exit auto print mode */ - break; - case ']': - /* XXX Print screen */ - break; + case '^': + /* XXX Enter auto print mode */ + break; + case '_': + /* XXX Exit auto print mode */ + break; + case ']': + /* XXX Print screen */ + break; #endif #ifdef VT52_PLUS - case 'E': - /* compatibility(ATARI) */ - move(term, 0, 0, 0); - erase_lots(term, false, false, true); + case 'E': + /* compatibility(ATARI) */ + move(term, 0, 0, 0); + erase_lots(term, false, false, true); if (term->scroll_on_disp) term->disptop = 0; - break; - case 'L': - /* compatibility(ATARI) */ - if (term->curs.y <= term->marg_b) - scroll(term, term->curs.y, term->marg_b, -1, false); - break; - case 'M': - /* compatibility(ATARI) */ - if (term->curs.y <= term->marg_b) - scroll(term, term->curs.y, term->marg_b, 1, true); - break; - case 'b': - /* compatibility(ATARI) */ - term->termstate = VT52_FG; - break; - case 'c': - /* compatibility(ATARI) */ - term->termstate = VT52_BG; - break; - case 'd': - /* compatibility(ATARI) */ - erase_lots(term, false, true, false); + break; + case 'L': + /* compatibility(ATARI) */ + if (term->curs.y <= term->marg_b) + scroll(term, term->curs.y, term->marg_b, -1, false); + break; + case 'M': + /* compatibility(ATARI) */ + if (term->curs.y <= term->marg_b) + scroll(term, term->curs.y, term->marg_b, 1, true); + break; + case 'b': + /* compatibility(ATARI) */ + term->termstate = VT52_FG; + break; + case 'c': + /* compatibility(ATARI) */ + term->termstate = VT52_BG; + break; + case 'd': + /* compatibility(ATARI) */ + erase_lots(term, false, true, false); if (term->scroll_on_disp) term->disptop = 0; - break; - case 'e': - /* compatibility(ATARI) */ - term->cursor_on = true; - break; - case 'f': - /* compatibility(ATARI) */ - term->cursor_on = false; - break; - /* case 'j': Save cursor position - broken on ST */ - /* case 'k': Restore cursor position */ - case 'l': - /* compatibility(ATARI) */ - erase_lots(term, true, true, true); - term->curs.x = 0; - term->wrapnext = false; - break; - case 'o': - /* compatibility(ATARI) */ - erase_lots(term, true, true, false); - break; - case 'p': - /* compatibility(ATARI) */ - term->curr_attr |= ATTR_REVERSE; - break; - case 'q': - /* compatibility(ATARI) */ - term->curr_attr &= ~ATTR_REVERSE; - break; - case 'v': /* wrap Autowrap on - Wyse style */ - /* compatibility(ATARI) */ - term->wrap = true; - break; - case 'w': /* Autowrap off */ - /* compatibility(ATARI) */ - term->wrap = false; - break; + break; + case 'e': + /* compatibility(ATARI) */ + term->cursor_on = true; + break; + case 'f': + /* compatibility(ATARI) */ + term->cursor_on = false; + break; + /* case 'j': Save cursor position - broken on ST */ + /* case 'k': Restore cursor position */ + case 'l': + /* compatibility(ATARI) */ + erase_lots(term, true, true, true); + term->curs.x = 0; + term->wrapnext = false; + break; + case 'o': + /* compatibility(ATARI) */ + erase_lots(term, true, true, false); + break; + case 'p': + /* compatibility(ATARI) */ + term->curr_attr |= ATTR_REVERSE; + break; + case 'q': + /* compatibility(ATARI) */ + term->curr_attr &= ~ATTR_REVERSE; + break; + case 'v': /* wrap Autowrap on - Wyse style */ + /* compatibility(ATARI) */ + term->wrap = true; + break; + case 'w': /* Autowrap off */ + /* compatibility(ATARI) */ + term->wrap = false; + break; - case 'R': - /* compatibility(OTHER) */ - term->vt52_bold = false; - term->curr_attr = ATTR_DEFAULT; + case 'R': + /* compatibility(OTHER) */ + term->vt52_bold = false; + term->curr_attr = ATTR_DEFAULT; term->curr_truecolour.fg = optionalrgb_none; term->curr_truecolour.bg = optionalrgb_none; - set_erase_char(term); - break; - case 'S': - /* compatibility(VI50) */ - term->curr_attr |= ATTR_UNDER; - break; - case 'W': - /* compatibility(VI50) */ - term->curr_attr &= ~ATTR_UNDER; - break; - case 'U': - /* compatibility(VI50) */ - term->vt52_bold = true; - term->curr_attr |= ATTR_BOLD; - break; - case 'T': - /* compatibility(VI50) */ - term->vt52_bold = false; - term->curr_attr &= ~ATTR_BOLD; - break; + set_erase_char(term); + break; + case 'S': + /* compatibility(VI50) */ + term->curr_attr |= ATTR_UNDER; + break; + case 'W': + /* compatibility(VI50) */ + term->curr_attr &= ~ATTR_UNDER; + break; + case 'U': + /* compatibility(VI50) */ + term->vt52_bold = true; + term->curr_attr |= ATTR_BOLD; + break; + case 'T': + /* compatibility(VI50) */ + term->vt52_bold = false; + term->curr_attr &= ~ATTR_BOLD; + break; #endif - } - break; - case VT52_Y1: - term->termstate = VT52_Y2; - move(term, term->curs.x, c - ' ', 0); - break; - case VT52_Y2: - term->termstate = TOPLEVEL; - move(term, c - ' ', term->curs.y, 0); - break; + } + break; + case VT52_Y1: + term->termstate = VT52_Y2; + move(term, term->curs.x, c - ' ', 0); + break; + case VT52_Y2: + term->termstate = TOPLEVEL; + move(term, c - ' ', term->curs.y, 0); + break; #ifdef VT52_PLUS - case VT52_FG: - term->termstate = TOPLEVEL; - term->curr_attr &= ~ATTR_FGMASK; - term->curr_attr &= ~ATTR_BOLD; - term->curr_attr |= (c & 0xF) << ATTR_FGSHIFT; - set_erase_char(term); - break; - case VT52_BG: - term->termstate = TOPLEVEL; - term->curr_attr &= ~ATTR_BGMASK; - term->curr_attr &= ~ATTR_BLINK; - term->curr_attr |= (c & 0xF) << ATTR_BGSHIFT; - set_erase_char(term); - break; + case VT52_FG: + term->termstate = TOPLEVEL; + term->curr_attr &= ~ATTR_FGMASK; + term->curr_attr &= ~ATTR_BOLD; + term->curr_attr |= (c & 0xF) << ATTR_FGSHIFT; + set_erase_char(term); + break; + case VT52_BG: + term->termstate = TOPLEVEL; + term->curr_attr &= ~ATTR_BGMASK; + term->curr_attr &= ~ATTR_BLINK; + term->curr_attr |= (c & 0xF) << ATTR_BGSHIFT; + set_erase_char(term); + break; #endif - default: break; /* placate gcc warning about enum use */ - } - if (term->selstate != NO_SELECTION) { - pos cursplus = term->curs; - incpos(cursplus); - check_selection(term, term->curs, cursplus); - } + default: break; /* placate gcc warning about enum use */ + } + if (term->selstate != NO_SELECTION) { + pos cursplus = term->curs; + incpos(cursplus); + check_selection(term, term->curs, cursplus); + } } term_print_flush(term); if (term->logflush && term->logctx) - logflush(term->logctx); + logflush(term->logctx); } /* @@ -5106,52 +5106,52 @@ static bool term_bidi_cache_hit(Terminal *term, int line, int i; if (!term->pre_bidi_cache) - return false; /* cache doesn't even exist yet! */ + return false; /* cache doesn't even exist yet! */ if (line >= term->bidi_cache_size) - return false; /* cache doesn't have this many lines */ + return false; /* cache doesn't have this many lines */ if (!term->pre_bidi_cache[line].chars) - return false; /* cache doesn't contain _this_ line */ + return false; /* cache doesn't contain _this_ line */ if (term->pre_bidi_cache[line].width != width) - return false; /* line is wrong width */ + return false; /* line is wrong width */ if (term->pre_bidi_cache[line].trusted != trusted) - return false; /* line has wrong trust state */ + return false; /* line has wrong trust state */ for (i = 0; i < width; i++) - if (!termchars_equal(term->pre_bidi_cache[line].chars+i, lbefore+i)) - return false; /* line doesn't match cache */ + if (!termchars_equal(term->pre_bidi_cache[line].chars+i, lbefore+i)) + return false; /* line doesn't match cache */ - return true; /* it didn't match. */ + return true; /* it didn't match. */ } static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore, - termchar *lafter, bidi_char *wcTo, - int width, int size, bool trusted) + termchar *lafter, bidi_char *wcTo, + int width, int size, bool trusted) { size_t i, j; if (!term->pre_bidi_cache || term->bidi_cache_size <= line) { j = term->bidi_cache_size; sgrowarray(term->pre_bidi_cache, term->bidi_cache_size, line); - term->post_bidi_cache = sresize(term->post_bidi_cache, - term->bidi_cache_size, - struct bidi_cache_entry); - while (j < term->bidi_cache_size) { - term->pre_bidi_cache[j].chars = - term->post_bidi_cache[j].chars = NULL; - term->pre_bidi_cache[j].width = - term->post_bidi_cache[j].width = -1; - term->pre_bidi_cache[j].trusted = false; + term->post_bidi_cache = sresize(term->post_bidi_cache, + term->bidi_cache_size, + struct bidi_cache_entry); + while (j < term->bidi_cache_size) { + term->pre_bidi_cache[j].chars = + term->post_bidi_cache[j].chars = NULL; + term->pre_bidi_cache[j].width = + term->post_bidi_cache[j].width = -1; + term->pre_bidi_cache[j].trusted = false; term->post_bidi_cache[j].trusted = false; - term->pre_bidi_cache[j].forward = - term->post_bidi_cache[j].forward = NULL; - term->pre_bidi_cache[j].backward = - term->post_bidi_cache[j].backward = NULL; - j++; - } + term->pre_bidi_cache[j].forward = + term->post_bidi_cache[j].forward = NULL; + term->pre_bidi_cache[j].backward = + term->post_bidi_cache[j].backward = NULL; + j++; + } } sfree(term->pre_bidi_cache[line].chars); @@ -5174,7 +5174,7 @@ static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore, memset(term->post_bidi_cache[line].backward, 0, width * sizeof(int)); for (i = j = 0; j < width; j += wcTo[i].nchars, i++) { - int p = wcTo[i].index; + int p = wcTo[i].index; if (p != BIDI_CHAR_INDEX_NONE) { assert(0 <= p && p < width); @@ -5196,7 +5196,7 @@ static void term_bidi_cache_store(Terminal *term, int line, termchar *lbefore, * term->post_bidi_cache[scr_y].*. */ static termchar *term_bidi_line(Terminal *term, struct termline *ldata, - int scr_y) + int scr_y) { termchar *lchars; int it; @@ -5205,48 +5205,48 @@ static termchar *term_bidi_line(Terminal *term, struct termline *ldata, if (!term->no_bidi || !term->no_arabicshaping || (ldata->trusted && term->cols > TRUST_SIGIL_WIDTH)) { - if (!term_bidi_cache_hit(term, scr_y, ldata->chars, term->cols, + if (!term_bidi_cache_hit(term, scr_y, ldata->chars, term->cols, ldata->trusted)) { - if (term->wcFromTo_size < term->cols) { - term->wcFromTo_size = term->cols; - term->wcFrom = sresize(term->wcFrom, term->wcFromTo_size, - bidi_char); - term->wcTo = sresize(term->wcTo, term->wcFromTo_size, - bidi_char); - } + if (term->wcFromTo_size < term->cols) { + term->wcFromTo_size = term->cols; + term->wcFrom = sresize(term->wcFrom, term->wcFromTo_size, + bidi_char); + term->wcTo = sresize(term->wcTo, term->wcFromTo_size, + bidi_char); + } - for(it=0; itcols ; it++) - { - unsigned long uc = (ldata->chars[it].chr); + for(it=0; itcols ; it++) + { + unsigned long uc = (ldata->chars[it].chr); - switch (uc & CSET_MASK) { - case CSET_LINEDRW: - if (!term->rawcnp) { - uc = term->ucsdata->unitab_xterm[uc & 0xFF]; - break; - } - case CSET_ASCII: - uc = term->ucsdata->unitab_line[uc & 0xFF]; - break; - case CSET_SCOACS: - uc = term->ucsdata->unitab_scoacs[uc&0xFF]; - break; - } - switch (uc & CSET_MASK) { - case CSET_ACP: - uc = term->ucsdata->unitab_font[uc & 0xFF]; - break; - case CSET_OEMCP: - uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; - break; - } + switch (uc & CSET_MASK) { + case CSET_LINEDRW: + if (!term->rawcnp) { + uc = term->ucsdata->unitab_xterm[uc & 0xFF]; + break; + } + case CSET_ASCII: + uc = term->ucsdata->unitab_line[uc & 0xFF]; + break; + case CSET_SCOACS: + uc = term->ucsdata->unitab_scoacs[uc&0xFF]; + break; + } + switch (uc & CSET_MASK) { + case CSET_ACP: + uc = term->ucsdata->unitab_font[uc & 0xFF]; + break; + case CSET_OEMCP: + uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; + break; + } - term->wcFrom[it].origwc = term->wcFrom[it].wc = - (unsigned int)uc; - term->wcFrom[it].index = it; - term->wcFrom[it].nchars = 1; - } + term->wcFrom[it].origwc = term->wcFrom[it].wc = + (unsigned int)uc; + term->wcFrom[it].index = it; + term->wcFrom[it].nchars = 1; + } if (ldata->trusted && term->cols > TRUST_SIGIL_WIDTH) { memmove( @@ -5271,27 +5271,27 @@ static termchar *term_bidi_line(Terminal *term, struct termline *ldata, nbc++; } - if(!term->no_bidi) - do_bidi(term->wcFrom, nbc); + if(!term->no_bidi) + do_bidi(term->wcFrom, nbc); - if(!term->no_arabicshaping) { - do_shape(term->wcFrom, term->wcTo, nbc); + if(!term->no_arabicshaping) { + do_shape(term->wcFrom, term->wcTo, nbc); } else { /* If we're not calling do_shape, we must copy the * data into wcTo anyway, unchanged */ memcpy(term->wcTo, term->wcFrom, nbc * sizeof(*term->wcTo)); } - if (term->ltemp_size < ldata->size) { - term->ltemp_size = ldata->size; - term->ltemp = sresize(term->ltemp, term->ltemp_size, - termchar); - } + if (term->ltemp_size < ldata->size) { + term->ltemp_size = ldata->size; + term->ltemp = sresize(term->ltemp, term->ltemp_size, + termchar); + } - memcpy(term->ltemp, ldata->chars, ldata->size * TSIZE); + memcpy(term->ltemp, ldata->chars, ldata->size * TSIZE); int opos = 0; - for (it=0; itwcTo[it].index; for (int j = 0; j < term->wcTo[it].nchars; j++) { if (ipos != BIDI_CHAR_INDEX_NONE) { @@ -5310,18 +5310,18 @@ static termchar *term_bidi_line(Terminal *term, struct termline *ldata, } opos++; } - } + } assert(opos == term->cols); - term_bidi_cache_store(term, scr_y, ldata->chars, - term->ltemp, term->wcTo, + term_bidi_cache_store(term, scr_y, ldata->chars, + term->ltemp, term->wcTo, term->cols, ldata->size, ldata->trusted); - lchars = term->ltemp; - } else { - lchars = term->post_bidi_cache[scr_y].chars; - } + lchars = term->ltemp; + } else { + lchars = term->post_bidi_cache[scr_y].chars; + } } else { - lchars = NULL; + lchars = NULL; } return lchars; @@ -5369,50 +5369,50 @@ static void do_paint(Terminal *term) /* Depends on: * screen array, disptop, scrtop, - * selection, rv, - * blinkpc, blink_is_real, tblinker, + * selection, rv, + * blinkpc, blink_is_real, tblinker, * curs.y, curs.x, cblinker, blink_cur, cursor_on, has_focus, wrapnext */ /* Has the cursor position or type changed ? */ if (term->cursor_on) { - if (term->has_focus) { - if (term->cblinker || !term->blink_cur) - cursor = TATTR_ACTCURS; - else - cursor = 0; - } else - cursor = TATTR_PASCURS; - if (term->wrapnext) - cursor |= TATTR_RIGHTCURS; + if (term->has_focus) { + if (term->cblinker || !term->blink_cur) + cursor = TATTR_ACTCURS; + else + cursor = 0; + } else + cursor = TATTR_PASCURS; + if (term->wrapnext) + cursor |= TATTR_RIGHTCURS; } else - cursor = 0; + cursor = 0; our_curs_y = term->curs.y - term->disptop; { - /* - * Adjust the cursor position: - * - for bidi - * - in the case where it's resting on the right-hand half - * of a CJK wide character. xterm's behaviour here, - * which seems adequate to me, is to display the cursor - * covering the _whole_ character, exactly as if it were - * one space to the left. - */ - termline *ldata = lineptr(term->curs.y); - termchar *lchars; + /* + * Adjust the cursor position: + * - for bidi + * - in the case where it's resting on the right-hand half + * of a CJK wide character. xterm's behaviour here, + * which seems adequate to me, is to display the cursor + * covering the _whole_ character, exactly as if it were + * one space to the left. + */ + termline *ldata = lineptr(term->curs.y); + termchar *lchars; - our_curs_x = term->curs.x; + our_curs_x = term->curs.x; - if ( (lchars = term_bidi_line(term, ldata, our_curs_y)) != NULL) { - our_curs_x = term->post_bidi_cache[our_curs_y].forward[our_curs_x]; - } else - lchars = ldata->chars; + if ( (lchars = term_bidi_line(term, ldata, our_curs_y)) != NULL) { + our_curs_x = term->post_bidi_cache[our_curs_y].forward[our_curs_x]; + } else + lchars = ldata->chars; - if (our_curs_x > 0 && - lchars[our_curs_x].chr == UCSWIDE) - our_curs_x--; + if (our_curs_x > 0 && + lchars[our_curs_x].chr == UCSWIDE) + our_curs_x--; - unlineptr(ldata); + unlineptr(ldata); } /* @@ -5421,73 +5421,73 @@ static void do_paint(Terminal *term) * previous position. */ if (term->dispcursy >= 0 && - (term->curstype != cursor || - term->dispcursy != our_curs_y || - term->dispcursx != our_curs_x)) { - termchar *dispcurs = term->disptext[term->dispcursy]->chars + - term->dispcursx; + (term->curstype != cursor || + term->dispcursy != our_curs_y || + term->dispcursx != our_curs_x)) { + termchar *dispcurs = term->disptext[term->dispcursy]->chars + + term->dispcursx; - if (term->dispcursx > 0 && dispcurs->chr == UCSWIDE) - dispcurs[-1].attr |= ATTR_INVALID; - if (term->dispcursx < term->cols-1 && dispcurs[1].chr == UCSWIDE) - dispcurs[1].attr |= ATTR_INVALID; - dispcurs->attr |= ATTR_INVALID; + if (term->dispcursx > 0 && dispcurs->chr == UCSWIDE) + dispcurs[-1].attr |= ATTR_INVALID; + if (term->dispcursx < term->cols-1 && dispcurs[1].chr == UCSWIDE) + dispcurs[1].attr |= ATTR_INVALID; + dispcurs->attr |= ATTR_INVALID; - term->curstype = 0; + term->curstype = 0; } term->dispcursx = term->dispcursy = -1; /* The normal screen data */ for (i = 0; i < term->rows; i++) { - termline *ldata; - termchar *lchars; - bool dirty_line, dirty_run, selected; - unsigned long attr = 0, cset = 0; - int start = 0; - int ccount = 0; - bool last_run_dirty = false; - int laststart; + termline *ldata; + termchar *lchars; + bool dirty_line, dirty_run, selected; + unsigned long attr = 0, cset = 0; + int start = 0; + int ccount = 0; + bool last_run_dirty = false; + int laststart; bool dirtyrect; - int *backward; + int *backward; truecolour tc; - scrpos.y = i + term->disptop; - ldata = lineptr(scrpos.y); + scrpos.y = i + term->disptop; + ldata = lineptr(scrpos.y); - /* Do Arabic shaping and bidi. */ - lchars = term_bidi_line(term, ldata, i); - if (lchars) { - backward = term->post_bidi_cache[i].backward; - } else { - lchars = ldata->chars; - backward = NULL; - } + /* Do Arabic shaping and bidi. */ + lchars = term_bidi_line(term, ldata, i); + if (lchars) { + backward = term->post_bidi_cache[i].backward; + } else { + lchars = ldata->chars; + backward = NULL; + } - /* - * First loop: work along the line deciding what we want - * each character cell to look like. - */ - for (j = 0; j < term->cols; j++) { - unsigned long tattr, tchar; - termchar *d = lchars + j; - scrpos.x = backward ? backward[j] : j; + /* + * First loop: work along the line deciding what we want + * each character cell to look like. + */ + for (j = 0; j < term->cols; j++) { + unsigned long tattr, tchar; + termchar *d = lchars + j; + scrpos.x = backward ? backward[j] : j; - tchar = d->chr; - tattr = d->attr; + tchar = d->chr; + tattr = d->attr; if (!term->ansi_colour) - tattr = (tattr & ~(ATTR_FGMASK | ATTR_BGMASK)) | + tattr = (tattr & ~(ATTR_FGMASK | ATTR_BGMASK)) | ATTR_DEFFG | ATTR_DEFBG; - if (!term->xterm_256_colour) { - int colour; - colour = (tattr & ATTR_FGMASK) >> ATTR_FGSHIFT; - if (colour >= 16 && colour < 256) - tattr = (tattr &~ ATTR_FGMASK) | ATTR_DEFFG; - colour = (tattr & ATTR_BGMASK) >> ATTR_BGSHIFT; - if (colour >= 16 && colour < 256) - tattr = (tattr &~ ATTR_BGMASK) | ATTR_DEFBG; - } + if (!term->xterm_256_colour) { + int colour; + colour = (tattr & ATTR_FGMASK) >> ATTR_FGSHIFT; + if (colour >= 16 && colour < 256) + tattr = (tattr &~ ATTR_FGMASK) | ATTR_DEFFG; + colour = (tattr & ATTR_BGMASK) >> ATTR_BGSHIFT; + if (colour >= 16 && colour < 256) + tattr = (tattr &~ ATTR_BGMASK) | ATTR_DEFBG; + } if (term->true_colour) { tc = d->truecolour; @@ -5495,153 +5495,153 @@ static void do_paint(Terminal *term) tc.fg = tc.bg = optionalrgb_none; } - switch (tchar & CSET_MASK) { - case CSET_ASCII: - tchar = term->ucsdata->unitab_line[tchar & 0xFF]; - break; - case CSET_LINEDRW: - tchar = term->ucsdata->unitab_xterm[tchar & 0xFF]; - break; - case CSET_SCOACS: - tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; - break; - } - if (j < term->cols-1 && d[1].chr == UCSWIDE) - tattr |= ATTR_WIDE; + switch (tchar & CSET_MASK) { + case CSET_ASCII: + tchar = term->ucsdata->unitab_line[tchar & 0xFF]; + break; + case CSET_LINEDRW: + tchar = term->ucsdata->unitab_xterm[tchar & 0xFF]; + break; + case CSET_SCOACS: + tchar = term->ucsdata->unitab_scoacs[tchar&0xFF]; + break; + } + if (j < term->cols-1 && d[1].chr == UCSWIDE) + tattr |= ATTR_WIDE; - /* Video reversing things */ - if (term->selstate == DRAGGING || term->selstate == SELECTED) { - if (term->seltype == LEXICOGRAPHIC) - selected = (posle(term->selstart, scrpos) && - poslt(scrpos, term->selend)); - else - selected = (posPle(term->selstart, scrpos) && - posPle_left(scrpos, term->selend)); - } else - selected = false; - tattr = (tattr ^ rv - ^ (selected ? ATTR_REVERSE : 0)); + /* Video reversing things */ + if (term->selstate == DRAGGING || term->selstate == SELECTED) { + if (term->seltype == LEXICOGRAPHIC) + selected = (posle(term->selstart, scrpos) && + poslt(scrpos, term->selend)); + else + selected = (posPle(term->selstart, scrpos) && + posPle_left(scrpos, term->selend)); + } else + selected = false; + tattr = (tattr ^ rv + ^ (selected ? ATTR_REVERSE : 0)); - /* 'Real' blinking ? */ - if (term->blink_is_real && (tattr & ATTR_BLINK)) { - if (term->has_focus && term->tblinker) { - tchar = term->ucsdata->unitab_line[(unsigned char)' ']; - } - tattr &= ~ATTR_BLINK; - } + /* 'Real' blinking ? */ + if (term->blink_is_real && (tattr & ATTR_BLINK)) { + if (term->has_focus && term->tblinker) { + tchar = term->ucsdata->unitab_line[(unsigned char)' ']; + } + tattr &= ~ATTR_BLINK; + } - /* - * Check the font we'll _probably_ be using to see if - * the character is wide when we don't want it to be. - */ - if (tchar != term->disptext[i]->chars[j].chr || - tattr != (term->disptext[i]->chars[j].attr &~ - (ATTR_NARROW | DATTR_MASK))) { - if ((tattr & ATTR_WIDE) == 0 && + /* + * Check the font we'll _probably_ be using to see if + * the character is wide when we don't want it to be. + */ + if (tchar != term->disptext[i]->chars[j].chr || + tattr != (term->disptext[i]->chars[j].attr &~ + (ATTR_NARROW | DATTR_MASK))) { + if ((tattr & ATTR_WIDE) == 0 && win_char_width(term->win, tchar) == 2) - tattr |= ATTR_NARROW; - } else if (term->disptext[i]->chars[j].attr & ATTR_NARROW) - tattr |= ATTR_NARROW; + tattr |= ATTR_NARROW; + } else if (term->disptext[i]->chars[j].attr & ATTR_NARROW) + tattr |= ATTR_NARROW; - if (i == our_curs_y && j == our_curs_x) { - tattr |= cursor; - term->curstype = cursor; - term->dispcursx = j; - term->dispcursy = i; - } + if (i == our_curs_y && j == our_curs_x) { + tattr |= cursor; + term->curstype = cursor; + term->dispcursx = j; + term->dispcursy = i; + } - /* FULL-TERMCHAR */ - newline[j].attr = tattr; - newline[j].chr = tchar; - newline[j].truecolour = tc; - /* Combining characters are still read from lchars */ - newline[j].cc_next = 0; - } + /* FULL-TERMCHAR */ + newline[j].attr = tattr; + newline[j].chr = tchar; + newline[j].truecolour = tc; + /* Combining characters are still read from lchars */ + newline[j].cc_next = 0; + } - /* - * Now loop over the line again, noting where things have - * changed. - * - * During this loop, we keep track of where we last saw - * DATTR_STARTRUN. Any mismatch automatically invalidates - * _all_ of the containing run that was last printed: that - * is, any rectangle that was drawn in one go in the - * previous update should be either left completely alone - * or overwritten in its entirety. This, along with the - * expectation that front ends clip all text runs to their - * bounding rectangle, should solve any possible problems - * with fonts that overflow their character cells. - */ - laststart = 0; - dirtyrect = false; - for (j = 0; j < term->cols; j++) { - if (term->disptext[i]->chars[j].attr & DATTR_STARTRUN) { - laststart = j; - dirtyrect = false; - } + /* + * Now loop over the line again, noting where things have + * changed. + * + * During this loop, we keep track of where we last saw + * DATTR_STARTRUN. Any mismatch automatically invalidates + * _all_ of the containing run that was last printed: that + * is, any rectangle that was drawn in one go in the + * previous update should be either left completely alone + * or overwritten in its entirety. This, along with the + * expectation that front ends clip all text runs to their + * bounding rectangle, should solve any possible problems + * with fonts that overflow their character cells. + */ + laststart = 0; + dirtyrect = false; + for (j = 0; j < term->cols; j++) { + if (term->disptext[i]->chars[j].attr & DATTR_STARTRUN) { + laststart = j; + dirtyrect = false; + } - if (term->disptext[i]->chars[j].chr != newline[j].chr || - (term->disptext[i]->chars[j].attr &~ DATTR_MASK) - != newline[j].attr) { - int k; + if (term->disptext[i]->chars[j].chr != newline[j].chr || + (term->disptext[i]->chars[j].attr &~ DATTR_MASK) + != newline[j].attr) { + int k; - if (!dirtyrect) { - for (k = laststart; k < j; k++) - term->disptext[i]->chars[k].attr |= ATTR_INVALID; + if (!dirtyrect) { + for (k = laststart; k < j; k++) + term->disptext[i]->chars[k].attr |= ATTR_INVALID; - dirtyrect = true; - } - } + dirtyrect = true; + } + } - if (dirtyrect) - term->disptext[i]->chars[j].attr |= ATTR_INVALID; - } + if (dirtyrect) + term->disptext[i]->chars[j].attr |= ATTR_INVALID; + } - /* - * Finally, loop once more and actually do the drawing. - */ - dirty_run = dirty_line = (ldata->lattr != - term->disptext[i]->lattr); - term->disptext[i]->lattr = ldata->lattr; + /* + * Finally, loop once more and actually do the drawing. + */ + dirty_run = dirty_line = (ldata->lattr != + term->disptext[i]->lattr); + term->disptext[i]->lattr = ldata->lattr; - tc = term->erase_char.truecolour; - for (j = 0; j < term->cols; j++) { - unsigned long tattr, tchar; - bool break_run, do_copy; - termchar *d = lchars + j; + tc = term->erase_char.truecolour; + for (j = 0; j < term->cols; j++) { + unsigned long tattr, tchar; + bool break_run, do_copy; + termchar *d = lchars + j; - tattr = newline[j].attr; - tchar = newline[j].chr; + tattr = newline[j].attr; + tchar = newline[j].chr; - if ((term->disptext[i]->chars[j].attr ^ tattr) & ATTR_WIDE) - dirty_line = true; + if ((term->disptext[i]->chars[j].attr ^ tattr) & ATTR_WIDE) + dirty_line = true; - break_run = ((tattr ^ attr) & term->attr_mask) != 0; + break_run = ((tattr ^ attr) & term->attr_mask) != 0; if (!truecolour_equal(newline[j].truecolour, tc)) break_run = true; #ifdef USES_VTLINE_HACK - /* Special hack for VT100 Linedraw glyphs */ - if ((tchar >= 0x23BA && tchar <= 0x23BD) || + /* Special hack for VT100 Linedraw glyphs */ + if ((tchar >= 0x23BA && tchar <= 0x23BD) || (j > 0 && (newline[j-1].chr >= 0x23BA && newline[j-1].chr <= 0x23BD))) - break_run = true; + break_run = true; #endif - /* - * Separate out sequences of characters that have the - * same CSET, if that CSET is a magic one. - */ - if (CSET_OF(tchar) != cset) - break_run = true; + /* + * Separate out sequences of characters that have the + * same CSET, if that CSET is a magic one. + */ + if (CSET_OF(tchar) != cset) + break_run = true; - /* - * Break on both sides of any combined-character cell. - */ - if (d->cc_next != 0 || - (j > 0 && d[-1].cc_next != 0)) - break_run = true; + /* + * Break on both sides of any combined-character cell. + */ + if (d->cc_next != 0 || + (j > 0 && d[-1].cc_next != 0)) + break_run = true; /* * Break on both sides of a trust sigil. @@ -5651,108 +5651,108 @@ static void do_paint(Terminal *term) d[-2].chr == TRUST_SIGIL_CHAR)) break_run = true; - if (!term->ucsdata->dbcs_screenfont && !dirty_line) { - if (term->disptext[i]->chars[j].chr == tchar && - (term->disptext[i]->chars[j].attr &~ DATTR_MASK) == tattr) - break_run = true; - else if (!dirty_run && ccount == 1) - break_run = true; - } + if (!term->ucsdata->dbcs_screenfont && !dirty_line) { + if (term->disptext[i]->chars[j].chr == tchar && + (term->disptext[i]->chars[j].attr &~ DATTR_MASK) == tattr) + break_run = true; + else if (!dirty_run && ccount == 1) + break_run = true; + } - if (break_run) { - if ((dirty_run || last_run_dirty) && ccount > 0) + if (break_run) { + if ((dirty_run || last_run_dirty) && ccount > 0) do_paint_draw(term, ldata, start, i, ch, ccount, attr, tc); - start = j; - ccount = 0; - attr = tattr; - tc = newline[j].truecolour; - cset = CSET_OF(tchar); - if (term->ucsdata->dbcs_screenfont) - last_run_dirty = dirty_run; - dirty_run = dirty_line; - } + start = j; + ccount = 0; + attr = tattr; + tc = newline[j].truecolour; + cset = CSET_OF(tchar); + if (term->ucsdata->dbcs_screenfont) + last_run_dirty = dirty_run; + dirty_run = dirty_line; + } - do_copy = false; - if (!termchars_equal_override(&term->disptext[i]->chars[j], - d, tchar, tattr)) { - do_copy = true; - dirty_run = true; - } + do_copy = false; + if (!termchars_equal_override(&term->disptext[i]->chars[j], + d, tchar, tattr)) { + do_copy = true; + dirty_run = true; + } sgrowarrayn(ch, chlen, ccount, 2); #ifdef PLATFORM_IS_UTF16 - if (tchar > 0x10000 && tchar < 0x110000) { - ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(tchar); - ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(tchar); - } else + if (tchar > 0x10000 && tchar < 0x110000) { + ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(tchar); + ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(tchar); + } else #endif /* PLATFORM_IS_UTF16 */ - ch[ccount++] = (wchar_t) tchar; + ch[ccount++] = (wchar_t) tchar; - if (d->cc_next) { - termchar *dd = d; + if (d->cc_next) { + termchar *dd = d; - while (dd->cc_next) { - unsigned long schar; + while (dd->cc_next) { + unsigned long schar; - dd += dd->cc_next; + dd += dd->cc_next; - schar = dd->chr; - switch (schar & CSET_MASK) { - case CSET_ASCII: - schar = term->ucsdata->unitab_line[schar & 0xFF]; - break; - case CSET_LINEDRW: - schar = term->ucsdata->unitab_xterm[schar & 0xFF]; - break; - case CSET_SCOACS: - schar = term->ucsdata->unitab_scoacs[schar&0xFF]; - break; - } + schar = dd->chr; + switch (schar & CSET_MASK) { + case CSET_ASCII: + schar = term->ucsdata->unitab_line[schar & 0xFF]; + break; + case CSET_LINEDRW: + schar = term->ucsdata->unitab_xterm[schar & 0xFF]; + break; + case CSET_SCOACS: + schar = term->ucsdata->unitab_scoacs[schar&0xFF]; + break; + } sgrowarrayn(ch, chlen, ccount, 2); #ifdef PLATFORM_IS_UTF16 - if (schar > 0x10000 && schar < 0x110000) { - ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(schar); - ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(schar); - } else + if (schar > 0x10000 && schar < 0x110000) { + ch[ccount++] = (wchar_t) HIGH_SURROGATE_OF(schar); + ch[ccount++] = (wchar_t) LOW_SURROGATE_OF(schar); + } else #endif /* PLATFORM_IS_UTF16 */ - ch[ccount++] = (wchar_t) schar; - } + ch[ccount++] = (wchar_t) schar; + } - attr |= TATTR_COMBINING; - } + attr |= TATTR_COMBINING; + } - if (do_copy) { - copy_termchar(term->disptext[i], j, d); - term->disptext[i]->chars[j].chr = tchar; - term->disptext[i]->chars[j].attr = tattr; - term->disptext[i]->chars[j].truecolour = tc; - if (start == j) - term->disptext[i]->chars[j].attr |= DATTR_STARTRUN; - } + if (do_copy) { + copy_termchar(term->disptext[i], j, d); + term->disptext[i]->chars[j].chr = tchar; + term->disptext[i]->chars[j].attr = tattr; + term->disptext[i]->chars[j].truecolour = tc; + if (start == j) + term->disptext[i]->chars[j].attr |= DATTR_STARTRUN; + } - /* If it's a wide char step along to the next one. */ - if (tattr & ATTR_WIDE) { - if (++j < term->cols) { - d++; - /* - * By construction above, the cursor should not - * be on the right-hand half of this character. - * Ever. - */ - assert(!(i == our_curs_y && j == our_curs_x)); - if (!termchars_equal(&term->disptext[i]->chars[j], d)) - dirty_run = true; - copy_termchar(term->disptext[i], j, d); - } - } - } - if (dirty_run && ccount > 0) + /* If it's a wide char step along to the next one. */ + if (tattr & ATTR_WIDE) { + if (++j < term->cols) { + d++; + /* + * By construction above, the cursor should not + * be on the right-hand half of this character. + * Ever. + */ + assert(!(i == our_curs_y && j == our_curs_x)); + if (!termchars_equal(&term->disptext[i]->chars[j], d)) + dirty_run = true; + copy_termchar(term->disptext[i], j, d); + } + } + } + if (dirty_run && ccount > 0) do_paint_draw(term, ldata, start, i, ch, ccount, attr, tc); - unlineptr(ldata); + unlineptr(ldata); } sfree(newline); @@ -5767,8 +5767,8 @@ void term_invalidate(Terminal *term) int i, j; for (i = 0; i < term->rows; i++) - for (j = 0; j < term->cols; j++) - term->disptext[i]->chars[j].attr |= ATTR_INVALID; + for (j = 0; j < term->cols; j++) + term->disptext[i]->chars[j].attr |= ATTR_INVALID; term_schedule_update(term); } @@ -5777,7 +5777,7 @@ void term_invalidate(Terminal *term) * Paint the window in response to a WM_PAINT message. */ void term_paint(Terminal *term, - int left, int top, int right, int bottom, bool immediately) + int left, int top, int right, int bottom, bool immediately) { int i, j; if (left < 0) left = 0; @@ -5786,18 +5786,18 @@ void term_paint(Terminal *term, if (bottom >= term->rows) bottom = term->rows-1; for (i = top; i <= bottom && i < term->rows; i++) { - if ((term->disptext[i]->lattr & LATTR_MODE) == LATTR_NORM) - for (j = left; j <= right && j < term->cols; j++) - term->disptext[i]->chars[j].attr |= ATTR_INVALID; - else - for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++) - term->disptext[i]->chars[j].attr |= ATTR_INVALID; + if ((term->disptext[i]->lattr & LATTR_MODE) == LATTR_NORM) + for (j = left; j <= right && j < term->cols; j++) + term->disptext[i]->chars[j].attr |= ATTR_INVALID; + else + for (j = left / 2; j <= right / 2 + 1 && j < term->cols; j++) + term->disptext[i]->chars[j].attr |= ATTR_INVALID; } if (immediately) { do_paint(term); } else { - term_schedule_update(term); + term_schedule_update(term); } } @@ -5814,9 +5814,9 @@ void term_scroll(Terminal *term, int rel, int where) term->disptop = (rel < 0 ? 0 : rel > 0 ? sbtop : term->disptop) + where; if (term->disptop < sbtop) - term->disptop = sbtop; + term->disptop = sbtop; if (term->disptop > 0) - term->disptop = 0; + term->disptop = 0; update_sbar(term); term_update(term); } @@ -5832,17 +5832,17 @@ void term_scroll_to_selection(Terminal *term, int which_end) int sbtop = -sblines(term); if (term->selstate != SELECTED) - return; + return; if (which_end) - target = term->selend; + target = term->selend; else - target = term->selstart; + target = term->selstart; y = target.y - term->rows/2; if (y < sbtop) - y = sbtop; + y = sbtop; else if (y > 0) - y = 0; + y = 0; term_scroll(term, -1, y); } @@ -5852,23 +5852,23 @@ void term_scroll_to_selection(Terminal *term, int which_end) typedef struct { size_t bufsize; /* amount of allocated space in textbuf/attrbuf */ size_t bufpos; /* amount of actual data */ - wchar_t *textbuf; /* buffer for copied text */ - wchar_t *textptr; /* = textbuf + bufpos (current insertion point) */ - int *attrbuf; /* buffer for copied attributes */ - int *attrptr; /* = attrbuf + bufpos */ - truecolour *tcbuf; /* buffer for copied colours */ - truecolour *tcptr; /* = tcbuf + bufpos */ + wchar_t *textbuf; /* buffer for copied text */ + wchar_t *textptr; /* = textbuf + bufpos (current insertion point) */ + int *attrbuf; /* buffer for copied attributes */ + int *attrptr; /* = attrbuf + bufpos */ + truecolour *tcbuf; /* buffer for copied colours */ + truecolour *tcptr; /* = tcbuf + bufpos */ } clip_workbuf; static void clip_addchar(clip_workbuf *b, wchar_t chr, int attr, truecolour tc) { if (b->bufpos >= b->bufsize) { sgrowarray(b->textbuf, b->bufsize, b->bufpos); - b->textptr = b->textbuf + b->bufpos; - b->attrbuf = sresize(b->attrbuf, b->bufsize, int); - b->attrptr = b->attrbuf + b->bufpos; - b->tcbuf = sresize(b->tcbuf, b->bufsize, truecolour); - b->tcptr = b->tcbuf + b->bufpos; + b->textptr = b->textbuf + b->bufpos; + b->attrbuf = sresize(b->attrbuf, b->bufsize, int); + b->attrptr = b->attrbuf + b->bufpos; + b->tcbuf = sresize(b->tcbuf, b->bufsize, truecolour); + b->tcptr = b->tcbuf + b->bufpos; } *b->textptr++ = chr; *b->attrptr++ = attr; @@ -5890,36 +5890,36 @@ static void clipme(Terminal *term, pos top, pos bottom, bool rect, bool desel, buf.attrptr = buf.attrbuf = snewn(buf.bufsize, int); buf.tcptr = buf.tcbuf = snewn(buf.bufsize, truecolour); - old_top_x = top.x; /* needed for rect==1 */ + old_top_x = top.x; /* needed for rect==1 */ while (poslt(top, bottom)) { - bool nl = false; - termline *ldata = lineptr(top.y); - pos nlpos; + bool nl = false; + termline *ldata = lineptr(top.y); + pos nlpos; - /* - * nlpos will point at the maximum position on this line we - * should copy up to. So we start it at the end of the - * line... - */ - nlpos.y = top.y; - nlpos.x = term->cols; + /* + * nlpos will point at the maximum position on this line we + * should copy up to. So we start it at the end of the + * line... + */ + nlpos.y = top.y; + nlpos.x = term->cols; - /* - * ... move it backwards if there's unused space at the end - * of the line (and also set `nl' if this is the case, - * because in normal selection mode this means we need a - * newline at the end)... - */ - if (!(ldata->lattr & LATTR_WRAPPED)) { - while (nlpos.x && - IS_SPACE_CHR(ldata->chars[nlpos.x - 1].chr) && - !ldata->chars[nlpos.x - 1].cc_next && - poslt(top, nlpos)) - decpos(nlpos); - if (poslt(nlpos, bottom)) - nl = true; - } else { + /* + * ... move it backwards if there's unused space at the end + * of the line (and also set `nl' if this is the case, + * because in normal selection mode this means we need a + * newline at the end)... + */ + if (!(ldata->lattr & LATTR_WRAPPED)) { + while (nlpos.x && + IS_SPACE_CHR(ldata->chars[nlpos.x - 1].chr) && + !ldata->chars[nlpos.x - 1].cc_next && + poslt(top, nlpos)) + decpos(nlpos); + if (poslt(nlpos, bottom)) + nl = true; + } else { if (ldata->trusted) { /* A wrapped line with a trust sigil on it terminates * a few characters earlier. */ @@ -5930,117 +5930,117 @@ static void clipme(Terminal *term, pos top, pos bottom, bool rect, bool desel, /* Ignore the last char on the line in a WRAPPED2 line. */ decpos(nlpos); } - } + } - /* - * ... and then clip it to the terminal x coordinate if - * we're doing rectangular selection. (In this case we - * still did the above, so that copying e.g. the right-hand - * column from a table doesn't fill with spaces on the - * right.) - */ - if (rect) { - if (nlpos.x > bottom.x) - nlpos.x = bottom.x; - nl = (top.y < bottom.y); - } + /* + * ... and then clip it to the terminal x coordinate if + * we're doing rectangular selection. (In this case we + * still did the above, so that copying e.g. the right-hand + * column from a table doesn't fill with spaces on the + * right.) + */ + if (rect) { + if (nlpos.x > bottom.x) + nlpos.x = bottom.x; + nl = (top.y < bottom.y); + } - while (poslt(top, bottom) && poslt(top, nlpos)) { + while (poslt(top, bottom) && poslt(top, nlpos)) { #if 0 - char cbuf[16], *p; - sprintf(cbuf, "", (ldata[top.x] & 0xFFFF)); + char cbuf[16], *p; + sprintf(cbuf, "", (ldata[top.x] & 0xFFFF)); #else - wchar_t cbuf[16], *p; - int c; - int x = top.x; + wchar_t cbuf[16], *p; + int c; + int x = top.x; - if (ldata->chars[x].chr == UCSWIDE) { - top.x++; - continue; - } + if (ldata->chars[x].chr == UCSWIDE) { + top.x++; + continue; + } - while (1) { - int uc = ldata->chars[x].chr; + while (1) { + int uc = ldata->chars[x].chr; attr = ldata->chars[x].attr; - tc = ldata->chars[x].truecolour; + tc = ldata->chars[x].truecolour; - switch (uc & CSET_MASK) { - case CSET_LINEDRW: - if (!term->rawcnp) { - uc = term->ucsdata->unitab_xterm[uc & 0xFF]; - break; - } - case CSET_ASCII: - uc = term->ucsdata->unitab_line[uc & 0xFF]; - break; - case CSET_SCOACS: - uc = term->ucsdata->unitab_scoacs[uc&0xFF]; - break; - } - switch (uc & CSET_MASK) { - case CSET_ACP: - uc = term->ucsdata->unitab_font[uc & 0xFF]; - break; - case CSET_OEMCP: - uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; - break; - } + switch (uc & CSET_MASK) { + case CSET_LINEDRW: + if (!term->rawcnp) { + uc = term->ucsdata->unitab_xterm[uc & 0xFF]; + break; + } + case CSET_ASCII: + uc = term->ucsdata->unitab_line[uc & 0xFF]; + break; + case CSET_SCOACS: + uc = term->ucsdata->unitab_scoacs[uc&0xFF]; + break; + } + switch (uc & CSET_MASK) { + case CSET_ACP: + uc = term->ucsdata->unitab_font[uc & 0xFF]; + break; + case CSET_OEMCP: + uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; + break; + } - c = (uc & ~CSET_MASK); + c = (uc & ~CSET_MASK); #ifdef PLATFORM_IS_UTF16 - if (uc > 0x10000 && uc < 0x110000) { - cbuf[0] = 0xD800 | ((uc - 0x10000) >> 10); - cbuf[1] = 0xDC00 | ((uc - 0x10000) & 0x3FF); - cbuf[2] = 0; - } else + if (uc > 0x10000 && uc < 0x110000) { + cbuf[0] = 0xD800 | ((uc - 0x10000) >> 10); + cbuf[1] = 0xDC00 | ((uc - 0x10000) & 0x3FF); + cbuf[2] = 0; + } else #endif - { - cbuf[0] = uc; - cbuf[1] = 0; - } + { + cbuf[0] = uc; + cbuf[1] = 0; + } - if (DIRECT_FONT(uc)) { - if (c >= ' ' && c != 0x7F) { - char buf[4]; - WCHAR wbuf[4]; - int rv; - if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) { - buf[0] = c; - buf[1] = (char) (0xFF & ldata->chars[top.x + 1].chr); - rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4); - top.x++; - } else { - buf[0] = c; - rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4); - } + if (DIRECT_FONT(uc)) { + if (c >= ' ' && c != 0x7F) { + char buf[4]; + WCHAR wbuf[4]; + int rv; + if (is_dbcs_leadbyte(term->ucsdata->font_codepage, (BYTE) c)) { + buf[0] = c; + buf[1] = (char) (0xFF & ldata->chars[top.x + 1].chr); + rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 2, wbuf, 4); + top.x++; + } else { + buf[0] = c; + rv = mb_to_wc(term->ucsdata->font_codepage, 0, buf, 1, wbuf, 4); + } - if (rv > 0) { - memcpy(cbuf, wbuf, rv * sizeof(wchar_t)); - cbuf[rv] = 0; - } - } - } + if (rv > 0) { + memcpy(cbuf, wbuf, rv * sizeof(wchar_t)); + cbuf[rv] = 0; + } + } + } #endif - for (p = cbuf; *p; p++) - clip_addchar(&buf, *p, attr, tc); + for (p = cbuf; *p; p++) + clip_addchar(&buf, *p, attr, tc); - if (ldata->chars[x].cc_next) - x += ldata->chars[x].cc_next; - else - break; - } - top.x++; - } - if (nl) { - int i; - for (i = 0; i < sel_nl_sz; i++) - clip_addchar(&buf, sel_nl[i], 0, term->basic_erase_char.truecolour); - } - top.y++; - top.x = rect ? old_top_x : 0; + if (ldata->chars[x].cc_next) + x += ldata->chars[x].cc_next; + else + break; + } + top.x++; + } + if (nl) { + int i; + for (i = 0; i < sel_nl_sz; i++) + clip_addchar(&buf, sel_nl[i], 0, term->basic_erase_char.truecolour); + } + top.y++; + top.x = rect ? old_top_x : 0; - unlineptr(ldata); + unlineptr(ldata); } #if SELECTION_NUL_TERMINATED clip_addchar(&buf, 0, 0, term->basic_erase_char.truecolour); @@ -6128,107 +6128,107 @@ void term_request_paste(Terminal *term, int clipboard) static int wordtype(Terminal *term, int uc) { struct ucsword { - int start, end, ctype; + int start, end, ctype; }; static const struct ucsword ucs_words[] = { - { - 128, 160, 0}, { - 161, 191, 1}, { - 215, 215, 1}, { - 247, 247, 1}, { - 0x037e, 0x037e, 1}, /* Greek question mark */ - { - 0x0387, 0x0387, 1}, /* Greek ano teleia */ - { - 0x055a, 0x055f, 1}, /* Armenian punctuation */ - { - 0x0589, 0x0589, 1}, /* Armenian full stop */ - { - 0x0700, 0x070d, 1}, /* Syriac punctuation */ - { - 0x104a, 0x104f, 1}, /* Myanmar punctuation */ - { - 0x10fb, 0x10fb, 1}, /* Georgian punctuation */ - { - 0x1361, 0x1368, 1}, /* Ethiopic punctuation */ - { - 0x166d, 0x166e, 1}, /* Canadian Syl. punctuation */ - { - 0x17d4, 0x17dc, 1}, /* Khmer punctuation */ - { - 0x1800, 0x180a, 1}, /* Mongolian punctuation */ - { - 0x2000, 0x200a, 0}, /* Various spaces */ - { - 0x2070, 0x207f, 2}, /* superscript */ - { - 0x2080, 0x208f, 2}, /* subscript */ - { - 0x200b, 0x27ff, 1}, /* punctuation and symbols */ - { - 0x3000, 0x3000, 0}, /* ideographic space */ - { - 0x3001, 0x3020, 1}, /* ideographic punctuation */ - { - 0x303f, 0x309f, 3}, /* Hiragana */ - { - 0x30a0, 0x30ff, 3}, /* Katakana */ - { - 0x3300, 0x9fff, 3}, /* CJK Ideographs */ - { - 0xac00, 0xd7a3, 3}, /* Hangul Syllables */ - { - 0xf900, 0xfaff, 3}, /* CJK Ideographs */ - { - 0xfe30, 0xfe6b, 1}, /* punctuation forms */ - { - 0xff00, 0xff0f, 1}, /* half/fullwidth ASCII */ - { - 0xff1a, 0xff20, 1}, /* half/fullwidth ASCII */ - { - 0xff3b, 0xff40, 1}, /* half/fullwidth ASCII */ - { - 0xff5b, 0xff64, 1}, /* half/fullwidth ASCII */ - { - 0xfff0, 0xffff, 0}, /* half/fullwidth ASCII */ - { - 0, 0, 0} + { + 128, 160, 0}, { + 161, 191, 1}, { + 215, 215, 1}, { + 247, 247, 1}, { + 0x037e, 0x037e, 1}, /* Greek question mark */ + { + 0x0387, 0x0387, 1}, /* Greek ano teleia */ + { + 0x055a, 0x055f, 1}, /* Armenian punctuation */ + { + 0x0589, 0x0589, 1}, /* Armenian full stop */ + { + 0x0700, 0x070d, 1}, /* Syriac punctuation */ + { + 0x104a, 0x104f, 1}, /* Myanmar punctuation */ + { + 0x10fb, 0x10fb, 1}, /* Georgian punctuation */ + { + 0x1361, 0x1368, 1}, /* Ethiopic punctuation */ + { + 0x166d, 0x166e, 1}, /* Canadian Syl. punctuation */ + { + 0x17d4, 0x17dc, 1}, /* Khmer punctuation */ + { + 0x1800, 0x180a, 1}, /* Mongolian punctuation */ + { + 0x2000, 0x200a, 0}, /* Various spaces */ + { + 0x2070, 0x207f, 2}, /* superscript */ + { + 0x2080, 0x208f, 2}, /* subscript */ + { + 0x200b, 0x27ff, 1}, /* punctuation and symbols */ + { + 0x3000, 0x3000, 0}, /* ideographic space */ + { + 0x3001, 0x3020, 1}, /* ideographic punctuation */ + { + 0x303f, 0x309f, 3}, /* Hiragana */ + { + 0x30a0, 0x30ff, 3}, /* Katakana */ + { + 0x3300, 0x9fff, 3}, /* CJK Ideographs */ + { + 0xac00, 0xd7a3, 3}, /* Hangul Syllables */ + { + 0xf900, 0xfaff, 3}, /* CJK Ideographs */ + { + 0xfe30, 0xfe6b, 1}, /* punctuation forms */ + { + 0xff00, 0xff0f, 1}, /* half/fullwidth ASCII */ + { + 0xff1a, 0xff20, 1}, /* half/fullwidth ASCII */ + { + 0xff3b, 0xff40, 1}, /* half/fullwidth ASCII */ + { + 0xff5b, 0xff64, 1}, /* half/fullwidth ASCII */ + { + 0xfff0, 0xffff, 0}, /* half/fullwidth ASCII */ + { + 0, 0, 0} }; const struct ucsword *wptr; switch (uc & CSET_MASK) { case CSET_LINEDRW: - uc = term->ucsdata->unitab_xterm[uc & 0xFF]; - break; + uc = term->ucsdata->unitab_xterm[uc & 0xFF]; + break; case CSET_ASCII: - uc = term->ucsdata->unitab_line[uc & 0xFF]; - break; - case CSET_SCOACS: - uc = term->ucsdata->unitab_scoacs[uc&0xFF]; - break; + uc = term->ucsdata->unitab_line[uc & 0xFF]; + break; + case CSET_SCOACS: + uc = term->ucsdata->unitab_scoacs[uc&0xFF]; + break; } switch (uc & CSET_MASK) { case CSET_ACP: - uc = term->ucsdata->unitab_font[uc & 0xFF]; - break; + uc = term->ucsdata->unitab_font[uc & 0xFF]; + break; case CSET_OEMCP: - uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; - break; + uc = term->ucsdata->unitab_oemcp[uc & 0xFF]; + break; } /* For DBCS fonts I can't do anything useful. Even this will sometimes * fail as there's such a thing as a double width space. :-( */ if (term->ucsdata->dbcs_screenfont && - term->ucsdata->font_codepage == term->ucsdata->line_codepage) - return (uc != ' '); + term->ucsdata->font_codepage == term->ucsdata->line_codepage) + return (uc != ' '); if (uc < 0x80) - return term->wordness[uc]; + return term->wordness[uc]; for (wptr = ucs_words; wptr->start; wptr++) { - if (uc >= wptr->start && uc <= wptr->end) - return wptr->ctype; + if (uc >= wptr->start && uc <= wptr->end) + return wptr->ctype; } return 2; @@ -6260,91 +6260,91 @@ static pos sel_spread_half(Terminal *term, pos p, int dir) switch (term->selmode) { case SM_CHAR: - /* - * In this mode, every character is a separate unit, except - * for runs of spaces at the end of a non-wrapping line. - */ - if (!(ldata->lattr & LATTR_WRAPPED)) { - termchar *q = ldata->chars + line_cols(term, ldata); - while (q > ldata->chars && - IS_SPACE_CHR(q[-1].chr) && !q[-1].cc_next) - q--; - if (q == ldata->chars + term->cols) - q--; - if (p.x >= q - ldata->chars) - p.x = (dir == -1 ? q - ldata->chars : term->cols - 1); - } - break; + /* + * In this mode, every character is a separate unit, except + * for runs of spaces at the end of a non-wrapping line. + */ + if (!(ldata->lattr & LATTR_WRAPPED)) { + termchar *q = ldata->chars + line_cols(term, ldata); + while (q > ldata->chars && + IS_SPACE_CHR(q[-1].chr) && !q[-1].cc_next) + q--; + if (q == ldata->chars + term->cols) + q--; + if (p.x >= q - ldata->chars) + p.x = (dir == -1 ? q - ldata->chars : term->cols - 1); + } + break; case SM_WORD: - /* - * In this mode, the units are maximal runs of characters - * whose `wordness' has the same value. - */ - wvalue = wordtype(term, UCSGET(ldata->chars, p.x)); - if (dir == +1) { - while (1) { - int maxcols = line_cols(term, ldata); - if (p.x < maxcols-1) { - if (wordtype(term, UCSGET(ldata->chars, p.x+1)) == wvalue) - p.x++; - else - break; - } else { - if (p.y+1 < term->rows && + /* + * In this mode, the units are maximal runs of characters + * whose `wordness' has the same value. + */ + wvalue = wordtype(term, UCSGET(ldata->chars, p.x)); + if (dir == +1) { + while (1) { + int maxcols = line_cols(term, ldata); + if (p.x < maxcols-1) { + if (wordtype(term, UCSGET(ldata->chars, p.x+1)) == wvalue) + p.x++; + else + break; + } else { + if (p.y+1 < term->rows && (ldata->lattr & LATTR_WRAPPED)) { - termline *ldata2; - ldata2 = lineptr(p.y+1); - if (wordtype(term, UCSGET(ldata2->chars, 0)) - == wvalue) { - p.x = 0; - p.y++; - unlineptr(ldata); - ldata = ldata2; - } else { - unlineptr(ldata2); - break; - } - } else - break; - } - } - } else { - while (1) { - if (p.x > 0) { - if (wordtype(term, UCSGET(ldata->chars, p.x-1)) == wvalue) - p.x--; - else - break; - } else { - termline *ldata2; - int maxcols; - if (p.y <= topy) - break; - ldata2 = lineptr(p.y-1); - maxcols = line_cols(term, ldata2); - if (ldata2->lattr & LATTR_WRAPPED) { - if (wordtype(term, UCSGET(ldata2->chars, maxcols-1)) - == wvalue) { - p.x = maxcols-1; - p.y--; - unlineptr(ldata); - ldata = ldata2; - } else { - unlineptr(ldata2); - break; - } - } else - break; - } - } - } - break; + termline *ldata2; + ldata2 = lineptr(p.y+1); + if (wordtype(term, UCSGET(ldata2->chars, 0)) + == wvalue) { + p.x = 0; + p.y++; + unlineptr(ldata); + ldata = ldata2; + } else { + unlineptr(ldata2); + break; + } + } else + break; + } + } + } else { + while (1) { + if (p.x > 0) { + if (wordtype(term, UCSGET(ldata->chars, p.x-1)) == wvalue) + p.x--; + else + break; + } else { + termline *ldata2; + int maxcols; + if (p.y <= topy) + break; + ldata2 = lineptr(p.y-1); + maxcols = line_cols(term, ldata2); + if (ldata2->lattr & LATTR_WRAPPED) { + if (wordtype(term, UCSGET(ldata2->chars, maxcols-1)) + == wvalue) { + p.x = maxcols-1; + p.y--; + unlineptr(ldata); + ldata = ldata2; + } else { + unlineptr(ldata2); + break; + } + } else + break; + } + } + } + break; case SM_LINE: - /* - * In this mode, every line is a unit. - */ - p.x = (dir == -1 ? 0 : term->cols - 1); - break; + /* + * In this mode, every line is a unit. + */ + p.x = (dir == -1 ? 0 : term->cols - 1); + break; } unlineptr(ldata); @@ -6354,10 +6354,10 @@ static pos sel_spread_half(Terminal *term, pos p, int dir) static void sel_spread(Terminal *term) { if (term->seltype == LEXICOGRAPHIC) { - term->selstart = sel_spread_half(term, term->selstart, -1); - decpos(term->selend); - term->selend = sel_spread_half(term, term->selend, +1); - incpos(term->selend); + term->selstart = sel_spread_half(term, term->selstart, -1); + decpos(term->selend); + term->selend = sel_spread_half(term, term->selend, +1); + incpos(term->selend); } } @@ -6366,26 +6366,26 @@ static void term_paste_callback(void *vterm) Terminal *term = (Terminal *)vterm; if (term->paste_len == 0) - return; + return; while (term->paste_pos < term->paste_len) { - int n = 0; - while (n + term->paste_pos < term->paste_len) { - if (term->paste_buffer[term->paste_pos + n++] == '\015') - break; - } - if (term->ldisc) { + int n = 0; + while (n + term->paste_pos < term->paste_len) { + if (term->paste_buffer[term->paste_pos + n++] == '\015') + break; + } + if (term->ldisc) { strbuf *buf = term_input_data_from_unicode( term, term->paste_buffer + term->paste_pos, n); term_keyinput_internal(term, buf->s, buf->len, false); strbuf_free(buf); } - term->paste_pos += n; + term->paste_pos += n; - if (term->paste_pos < term->paste_len) { + if (term->paste_pos < term->paste_len) { queue_toplevel_callback(term_paste_callback, term); - return; - } + return; + } } term_bracketed_paste_stop(term); sfree(term->paste_buffer); @@ -6492,7 +6492,7 @@ void term_do_paste(Terminal *term, const wchar_t *data, int len) } void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, - Mouse_Action a, int x, int y, bool shift, bool ctrl, bool alt) + Mouse_Action a, int x, int y, bool shift, bool ctrl, bool alt) { pos selpoint; termline *ldata; @@ -6502,17 +6502,17 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, int default_seltype; if (y < 0) { - y = 0; - if (a == MA_DRAG && !raw_mouse) - term_scroll(term, 0, -1); + y = 0; + if (a == MA_DRAG && !raw_mouse) + term_scroll(term, 0, -1); } if (y >= term->rows) { - y = term->rows - 1; - if (a == MA_DRAG && !raw_mouse) - term_scroll(term, 0, +1); + y = term->rows - 1; + if (a == MA_DRAG && !raw_mouse) + term_scroll(term, 0, +1); } if (x < 0) { - if (y > 0 && !raw_mouse && term->seltype != RECTANGULAR) { + if (y > 0 && !raw_mouse && term->seltype != RECTANGULAR) { /* * When we're using the mouse for normal raster-based * selection, dragging off the left edge of a terminal row @@ -6524,26 +6524,26 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, * anything else - rectangular selection, or xterm mouse * tracking - then we disable this special treatment. */ - x = term->cols - 1; - y--; - } else - x = 0; + x = term->cols - 1; + y--; + } else + x = 0; } if (x >= term->cols) - x = term->cols - 1; + x = term->cols - 1; selpoint.y = y + term->disptop; ldata = lineptr(selpoint.y); if ((ldata->lattr & LATTR_MODE) != LATTR_NORM) - x /= 2; + x /= 2; /* * Transform x through the bidi algorithm to find the _logical_ * click point from the physical one. */ if (term_bidi_line(term, ldata, y) != NULL) { - x = term->post_bidi_cache[y].backward[x]; + x = term->post_bidi_cache[y].backward[x]; } selpoint.x = x; @@ -6558,38 +6558,38 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, * presses. */ if (raw_mouse && - (term->selstate != ABOUT_TO) && (term->selstate != DRAGGING)) { - int encstate = 0, r, c; + (term->selstate != ABOUT_TO) && (term->selstate != DRAGGING)) { + int encstate = 0, r, c; bool wheel; - char abuf[32]; - int len = 0; + char abuf[32]; + int len = 0; - if (term->ldisc) { + if (term->ldisc) { - switch (braw) { - case MBT_LEFT: - encstate = 0x00; /* left button down */ + switch (braw) { + case MBT_LEFT: + encstate = 0x00; /* left button down */ wheel = false; - break; - case MBT_MIDDLE: - encstate = 0x01; + break; + case MBT_MIDDLE: + encstate = 0x01; wheel = false; - break; - case MBT_RIGHT: - encstate = 0x02; + break; + case MBT_RIGHT: + encstate = 0x02; wheel = false; - break; - case MBT_WHEEL_UP: - encstate = 0x40; + break; + case MBT_WHEEL_UP: + encstate = 0x40; wheel = true; - break; - case MBT_WHEEL_DOWN: - encstate = 0x41; + break; + case MBT_WHEEL_DOWN: + encstate = 0x41; wheel = true; - break; - default: + break; + default: return; - } + } if (wheel) { /* For mouse wheel buttons, we only ever expect to see * MA_CLICK actions, and we don't try to keep track of @@ -6598,44 +6598,44 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, if (a != MA_CLICK) return; } else switch (a) { - case MA_DRAG: - if (term->xterm_mouse == 1) - return; - encstate += 0x20; - break; - case MA_RELEASE: - /* If multiple extensions are enabled, the xterm 1006 is used, so it's okay to check for only that */ - if (!term->xterm_extended_mouse) - encstate = 0x03; - term->mouse_is_down = 0; - break; - case MA_CLICK: - if (term->mouse_is_down == braw) - return; - term->mouse_is_down = braw; - break; + case MA_DRAG: + if (term->xterm_mouse == 1) + return; + encstate += 0x20; + break; + case MA_RELEASE: + /* If multiple extensions are enabled, the xterm 1006 is used, so it's okay to check for only that */ + if (!term->xterm_extended_mouse) + encstate = 0x03; + term->mouse_is_down = 0; + break; + case MA_CLICK: + if (term->mouse_is_down == braw) + return; + term->mouse_is_down = braw; + break; default: return; - } - if (shift) - encstate += 0x04; - if (ctrl) - encstate += 0x10; - r = y + 1; - c = x + 1; + } + if (shift) + encstate += 0x04; + if (ctrl) + encstate += 0x10; + r = y + 1; + c = x + 1; - /* Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. */ - if (term->xterm_extended_mouse) { - len = sprintf(abuf, "\033[<%d;%d;%d%c", encstate, c, r, a == MA_RELEASE ? 'm' : 'M'); - } else if (term->urxvt_extended_mouse) { - len = sprintf(abuf, "\033[%d;%d;%dM", encstate + 32, c, r); - } else if (c <= 223 && r <= 223) { - len = sprintf(abuf, "\033[M%c%c%c", encstate + 32, c + 32, r + 32); - } + /* Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. */ + if (term->xterm_extended_mouse) { + len = sprintf(abuf, "\033[<%d;%d;%d%c", encstate, c, r, a == MA_RELEASE ? 'm' : 'M'); + } else if (term->urxvt_extended_mouse) { + len = sprintf(abuf, "\033[%d;%d;%dM", encstate + 32, c, r); + } else if (c <= 223 && r <= 223) { + len = sprintf(abuf, "\033[M%c%c%c", encstate + 32, c + 32, r + 32); + } if (len > 0) ldisc_send(term->ldisc, abuf, len, false); - } - return; + } + return; } /* @@ -6643,30 +6643,30 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, * of a selection attempt, from the state of Alt. */ if (!alt ^ !term->rect_select) - default_seltype = RECTANGULAR; + default_seltype = RECTANGULAR; else - default_seltype = LEXICOGRAPHIC; - + default_seltype = LEXICOGRAPHIC; + if (term->selstate == NO_SELECTION) { - term->seltype = default_seltype; + term->seltype = default_seltype; } if (bcooked == MBT_SELECT && a == MA_CLICK) { - deselect(term); - term->selstate = ABOUT_TO; - term->seltype = default_seltype; - term->selanchor = selpoint; - term->selmode = SM_CHAR; + deselect(term); + term->selstate = ABOUT_TO; + term->seltype = default_seltype; + term->selanchor = selpoint; + term->selmode = SM_CHAR; } else if (bcooked == MBT_SELECT && (a == MA_2CLK || a == MA_3CLK)) { - deselect(term); - term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE); - term->selstate = DRAGGING; - term->selstart = term->selanchor = selpoint; - term->selend = term->selstart; - incpos(term->selend); - sel_spread(term); + deselect(term); + term->selmode = (a == MA_2CLK ? SM_WORD : SM_LINE); + term->selstate = DRAGGING; + term->selstart = term->selanchor = selpoint; + term->selend = term->selstart; + incpos(term->selend); + sel_spread(term); } else if ((bcooked == MBT_SELECT && a == MA_DRAG) || - (bcooked == MBT_EXTEND && a != MA_RELEASE)) { + (bcooked == MBT_EXTEND && a != MA_RELEASE)) { if (a == MA_DRAG && (term->selstate == NO_SELECTION || term->selstate == SELECTED)) { /* @@ -6680,91 +6680,91 @@ void term_mouse(Terminal *term, Mouse_Button braw, Mouse_Button bcooked, */ return; } - if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint)) - return; - if (bcooked == MBT_EXTEND && a != MA_DRAG && - term->selstate == SELECTED) { - if (term->seltype == LEXICOGRAPHIC) { - /* - * For normal selection, we extend by moving - * whichever end of the current selection is closer - * to the mouse. - */ - if (posdiff(selpoint, term->selstart) < - posdiff(term->selend, term->selstart) / 2) { - term->selanchor = term->selend; - decpos(term->selanchor); - } else { - term->selanchor = term->selstart; - } - } else { - /* - * For rectangular selection, we have a choice of - * _four_ places to put selanchor and selpoint: the - * four corners of the selection. - */ - if (2*selpoint.x < term->selstart.x + term->selend.x) - term->selanchor.x = term->selend.x-1; - else - term->selanchor.x = term->selstart.x; + if (term->selstate == ABOUT_TO && poseq(term->selanchor, selpoint)) + return; + if (bcooked == MBT_EXTEND && a != MA_DRAG && + term->selstate == SELECTED) { + if (term->seltype == LEXICOGRAPHIC) { + /* + * For normal selection, we extend by moving + * whichever end of the current selection is closer + * to the mouse. + */ + if (posdiff(selpoint, term->selstart) < + posdiff(term->selend, term->selstart) / 2) { + term->selanchor = term->selend; + decpos(term->selanchor); + } else { + term->selanchor = term->selstart; + } + } else { + /* + * For rectangular selection, we have a choice of + * _four_ places to put selanchor and selpoint: the + * four corners of the selection. + */ + if (2*selpoint.x < term->selstart.x + term->selend.x) + term->selanchor.x = term->selend.x-1; + else + term->selanchor.x = term->selstart.x; - if (2*selpoint.y < term->selstart.y + term->selend.y) - term->selanchor.y = term->selend.y; - else - term->selanchor.y = term->selstart.y; - } - term->selstate = DRAGGING; - } - if (term->selstate != ABOUT_TO && term->selstate != DRAGGING) - term->selanchor = selpoint; - term->selstate = DRAGGING; - if (term->seltype == LEXICOGRAPHIC) { - /* - * For normal selection, we set (selstart,selend) to - * (selpoint,selanchor) in some order. - */ - if (poslt(selpoint, term->selanchor)) { - term->selstart = selpoint; - term->selend = term->selanchor; - incpos(term->selend); - } else { - term->selstart = term->selanchor; - term->selend = selpoint; - incpos(term->selend); - } - } else { - /* - * For rectangular selection, we may need to - * interchange x and y coordinates (if the user has - * dragged in the -x and +y directions, or vice versa). - */ - term->selstart.x = min(term->selanchor.x, selpoint.x); - term->selend.x = 1+max(term->selanchor.x, selpoint.x); - term->selstart.y = min(term->selanchor.y, selpoint.y); - term->selend.y = max(term->selanchor.y, selpoint.y); - } - sel_spread(term); + if (2*selpoint.y < term->selstart.y + term->selend.y) + term->selanchor.y = term->selend.y; + else + term->selanchor.y = term->selstart.y; + } + term->selstate = DRAGGING; + } + if (term->selstate != ABOUT_TO && term->selstate != DRAGGING) + term->selanchor = selpoint; + term->selstate = DRAGGING; + if (term->seltype == LEXICOGRAPHIC) { + /* + * For normal selection, we set (selstart,selend) to + * (selpoint,selanchor) in some order. + */ + if (poslt(selpoint, term->selanchor)) { + term->selstart = selpoint; + term->selend = term->selanchor; + incpos(term->selend); + } else { + term->selstart = term->selanchor; + term->selend = selpoint; + incpos(term->selend); + } + } else { + /* + * For rectangular selection, we may need to + * interchange x and y coordinates (if the user has + * dragged in the -x and +y directions, or vice versa). + */ + term->selstart.x = min(term->selanchor.x, selpoint.x); + term->selend.x = 1+max(term->selanchor.x, selpoint.x); + term->selstart.y = min(term->selanchor.y, selpoint.y); + term->selend.y = max(term->selanchor.y, selpoint.y); + } + sel_spread(term); } else if ((bcooked == MBT_SELECT || bcooked == MBT_EXTEND) && - a == MA_RELEASE) { - if (term->selstate == DRAGGING) { - /* - * We've completed a selection. We now transfer the - * data to the clipboard. - */ - clipme(term, term->selstart, term->selend, - (term->seltype == RECTANGULAR), false, + a == MA_RELEASE) { + if (term->selstate == DRAGGING) { + /* + * We've completed a selection. We now transfer the + * data to the clipboard. + */ + clipme(term, term->selstart, term->selend, + (term->seltype == RECTANGULAR), false, term->mouse_select_clipboards, term->n_mouse_select_clipboards); - term->selstate = SELECTED; - } else - term->selstate = NO_SELECTION; + term->selstate = SELECTED; + } else + term->selstate = NO_SELECTION; } else if (bcooked == MBT_PASTE - && (a == MA_CLICK + && (a == MA_CLICK #if MULTICLICK_ONLY_EVENT - || a == MA_2CLK || a == MA_3CLK + || a == MA_2CLK || a == MA_3CLK #endif - )) { - term_request_paste(term, term->mouse_paste_clipboard); + )) { + term_request_paste(term, term->mouse_paste_clipboard); } /* @@ -6782,32 +6782,32 @@ int format_arrow_key(char *buf, Terminal *term, int xkey, bool ctrl) char *p = buf; if (term->vt52_mode) - p += sprintf(p, "\x1B%c", xkey); + p += sprintf(p, "\x1B%c", xkey); else { - bool app_flg = (term->app_cursor_keys && !term->no_applic_c); + bool app_flg = (term->app_cursor_keys && !term->no_applic_c); #if 0 - /* - * RDB: VT100 & VT102 manuals both state the app cursor - * keys only work if the app keypad is on. - * - * SGT: That may well be true, but xterm disagrees and so - * does at least one application, so I've #if'ed this out - * and the behaviour is back to PuTTY's original: app - * cursor and app keypad are independently switchable - * modes. If anyone complains about _this_ I'll have to - * put in a configurable option. - */ - if (!term->app_keypad_keys) - app_flg = 0; + /* + * RDB: VT100 & VT102 manuals both state the app cursor + * keys only work if the app keypad is on. + * + * SGT: That may well be true, but xterm disagrees and so + * does at least one application, so I've #if'ed this out + * and the behaviour is back to PuTTY's original: app + * cursor and app keypad are independently switchable + * modes. If anyone complains about _this_ I'll have to + * put in a configurable option. + */ + if (!term->app_keypad_keys) + app_flg = 0; #endif - /* Useful mapping of Ctrl-arrows */ - if (ctrl) - app_flg = !app_flg; + /* Useful mapping of Ctrl-arrows */ + if (ctrl) + app_flg = !app_flg; - if (app_flg) - p += sprintf(p, "\x1BO%c", xkey); - else - p += sprintf(p, "\x1B[%c", xkey); + if (app_flg) + p += sprintf(p, "\x1BO%c", xkey); + else + p += sprintf(p, "\x1B[%c", xkey); } return p - buf; @@ -6943,12 +6943,12 @@ int format_numeric_keypad_key(char *buf, Terminal *term, char key, case '\r': xkey = 'M'; break; case '+': - /* - * Keypad + is tricky. It covers a space that would - * be taken up on the VT100 by _two_ keys; so we - * let Shift select between the two. Worse still, - * in xterm function key mode we change which two... - */ + /* + * Keypad + is tricky. It covers a space that would + * be taken up on the VT100 by _two_ keys; so we + * let Shift select between the two. Worse still, + * in xterm function key mode we change which two... + */ if (term->funky_type == FUNKY_XTERM) xkey = shift ? 'l' : 'k'; else @@ -7014,7 +7014,7 @@ void term_keyinput(Terminal *term, int codepage, const void *str, int len) void term_nopaste(Terminal *term) { if (term->paste_len == 0) - return; + return; sfree(term->paste_buffer); term_bracketed_paste_stop(term); term->paste_buffer = NULL; @@ -7048,16 +7048,16 @@ void term_lost_clipboard_ownership(Terminal *term, int clipboard) static void term_added_data(Terminal *term) { if (!term->in_term_out) { - term->in_term_out = true; - term_reset_cblink(term); - /* - * During drag-selects, we do not process terminal input, - * because the user will want the screen to hold still to - * be selected. - */ - if (term->selstate != DRAGGING) - term_out(term); - term->in_term_out = false; + term->in_term_out = true; + term_reset_cblink(term); + /* + * During drag-selects, we do not process terminal input, + * because the user will want the screen to hold still to + * be selected. + */ + if (term->selstate != DRAGGING) + term_out(term); + term->in_term_out = false; } } @@ -7107,9 +7107,9 @@ char *term_get_ttymode(Terminal *term, const char *mode) { const char *val = NULL; if (strcmp(mode, "ERASE") == 0) { - val = term->bksp_is_delete ? "^?" : "^H"; + val = term->bksp_is_delete ? "^?" : "^H"; } else if (strcmp(mode, "IUTF8") == 0) { - val = win_is_utf8(term->win) ? "yes" : "no"; + val = win_is_utf8(term->win) ? "yes" : "no"; } /* FIXME: perhaps we should set ONLCR based on lfhascr as well? */ /* FIXME: or ECHO and friends based on local echo state? */ @@ -7119,7 +7119,7 @@ char *term_get_ttymode(Terminal *term, const char *mode) struct term_userpass_state { size_t curr_prompt; bool done_prompt; /* printed out prompt yet? */ - size_t pos; /* cursor position */ + size_t pos; /* cursor position */ }; /* Tiny wrapper to make it easier to write lots of little strings */ @@ -7136,113 +7136,113 @@ int term_get_userpass_input(Terminal *term, prompts_t *p, bufchain *input) { struct term_userpass_state *s = (struct term_userpass_state *)p->data; if (!s) { - /* - * First call. Set some stuff up. - */ - p->data = s = snew(struct term_userpass_state); - s->curr_prompt = 0; - s->done_prompt = false; - /* We only print the `name' caption if we have to... */ - if (p->name_reqd && p->name) { + /* + * First call. Set some stuff up. + */ + p->data = s = snew(struct term_userpass_state); + s->curr_prompt = 0; + s->done_prompt = false; + /* We only print the `name' caption if we have to... */ + if (p->name_reqd && p->name) { ptrlen plname = ptrlen_from_asciz(p->name); term_write(term, plname); if (!ptrlen_endswith(plname, PTRLEN_LITERAL("\n"), NULL)) term_write(term, PTRLEN_LITERAL("\r\n")); - } - /* ...but we always print any `instruction'. */ - if (p->instruction) { + } + /* ...but we always print any `instruction'. */ + if (p->instruction) { ptrlen plinst = ptrlen_from_asciz(p->instruction); term_write(term, plinst); if (!ptrlen_endswith(plinst, PTRLEN_LITERAL("\n"), NULL)) term_write(term, PTRLEN_LITERAL("\r\n")); - } - /* - * Zero all the results, in case we abort half-way through. - */ - { - int i; - for (i = 0; i < (int)p->n_prompts; i++) + } + /* + * Zero all the results, in case we abort half-way through. + */ + { + int i; + for (i = 0; i < (int)p->n_prompts; i++) prompt_set_result(p->prompts[i], ""); - } + } } while (s->curr_prompt < p->n_prompts) { - prompt_t *pr = p->prompts[s->curr_prompt]; - bool finished_prompt = false; + prompt_t *pr = p->prompts[s->curr_prompt]; + bool finished_prompt = false; - if (!s->done_prompt) { - term_write(term, ptrlen_from_asciz(pr->prompt)); - s->done_prompt = true; - s->pos = 0; - } + if (!s->done_prompt) { + term_write(term, ptrlen_from_asciz(pr->prompt)); + s->done_prompt = true; + s->pos = 0; + } - /* Breaking out here ensures that the prompt is printed even - * if we're now waiting for user data. */ - if (!input || !bufchain_size(input)) break; + /* Breaking out here ensures that the prompt is printed even + * if we're now waiting for user data. */ + if (!input || !bufchain_size(input)) break; - /* FIXME: should we be using local-line-editing code instead? */ - while (!finished_prompt && bufchain_size(input) > 0) { - char c; + /* FIXME: should we be using local-line-editing code instead? */ + while (!finished_prompt && bufchain_size(input) > 0) { + char c; bufchain_fetch_consume(input, &c, 1); - switch (c) { - case 10: - case 13: - term_write(term, PTRLEN_LITERAL("\r\n")); + switch (c) { + case 10: + case 13: + term_write(term, PTRLEN_LITERAL("\r\n")); prompt_ensure_result_size(pr, s->pos + 1); - pr->result[s->pos] = '\0'; - /* go to next prompt, if any */ - s->curr_prompt++; - s->done_prompt = false; - finished_prompt = true; /* break out */ - break; - case 8: - case 127: - if (s->pos > 0) { - if (pr->echo) - term_write(term, PTRLEN_LITERAL("\b \b")); - s->pos--; - } - break; - case 21: - case 27: - while (s->pos > 0) { - if (pr->echo) - term_write(term, PTRLEN_LITERAL("\b \b")); - s->pos--; - } - break; - case 3: - case 4: - /* Immediate abort. */ - term_write(term, PTRLEN_LITERAL("\r\n")); - sfree(s); - p->data = NULL; - return 0; /* user abort */ - default: - /* - * This simplistic check for printability is disabled - * when we're doing password input, because some people - * have control characters in their passwords. - */ - if (!pr->echo || (c >= ' ' && c <= '~') || - ((unsigned char) c >= 160)) { + pr->result[s->pos] = '\0'; + /* go to next prompt, if any */ + s->curr_prompt++; + s->done_prompt = false; + finished_prompt = true; /* break out */ + break; + case 8: + case 127: + if (s->pos > 0) { + if (pr->echo) + term_write(term, PTRLEN_LITERAL("\b \b")); + s->pos--; + } + break; + case 21: + case 27: + while (s->pos > 0) { + if (pr->echo) + term_write(term, PTRLEN_LITERAL("\b \b")); + s->pos--; + } + break; + case 3: + case 4: + /* Immediate abort. */ + term_write(term, PTRLEN_LITERAL("\r\n")); + sfree(s); + p->data = NULL; + return 0; /* user abort */ + default: + /* + * This simplistic check for printability is disabled + * when we're doing password input, because some people + * have control characters in their passwords. + */ + if (!pr->echo || (c >= ' ' && c <= '~') || + ((unsigned char) c >= 160)) { prompt_ensure_result_size(pr, s->pos + 1); - pr->result[s->pos++] = c; - if (pr->echo) - term_write(term, make_ptrlen(&c, 1)); - } - break; - } - } - + pr->result[s->pos++] = c; + if (pr->echo) + term_write(term, make_ptrlen(&c, 1)); + } + break; + } + } + } if (s->curr_prompt < p->n_prompts) { - return -1; /* more data required */ + return -1; /* more data required */ } else { - sfree(s); - p->data = NULL; - return +1; /* all done */ + sfree(s); + p->data = NULL; + return +1; /* all done */ } } diff --git a/terminal.h b/terminal.h index 1ed0b17d..1bfeecfa 100644 --- a/terminal.h +++ b/terminal.h @@ -40,11 +40,11 @@ struct termchar { * The cc_next field is used to link multiple termchars * together into a list, so as to fit more than one character * into a character cell (Unicode combining characters). - * + * * cc_next is a relative offset into the current array of * termchars. I.e. to advance to the next character in a list, * one does `tc += tc->next'. - * + * * Zero means end of list. */ int cc_next; @@ -52,11 +52,11 @@ struct termchar { struct termline { unsigned short lattr; - int cols; /* number of real columns on the line */ - int size; /* number of allocated termchars - * (cc-lists may make this > cols) */ + int cols; /* number of real columns on the line */ + int size; /* number of allocated termchars + * (cc-lists may make this > cols) */ bool temporary; /* true if decompressed from scrollback */ - int cc_free; /* offset to first cc in free list */ + int cc_free; /* offset to first cc in free list */ struct termchar *chars; bool trusted; }; @@ -65,7 +65,7 @@ struct bidi_cache_entry { int width; bool trusted; struct termchar *chars; - int *forward, *backward; /* the permutations of line positions */ + int *forward, *backward; /* the permutations of line positions */ }; struct term_utf8_decode { @@ -78,17 +78,17 @@ struct terminal_tag { int compatibility_level; - tree234 *scrollback; /* lines scrolled off top of screen */ - tree234 *screen; /* lines on primary screen */ - tree234 *alt_screen; /* lines on alternate screen */ - int disptop; /* distance scrolled back (0 or -ve) */ - int tempsblines; /* number of lines of .scrollback that - can be retrieved onto the terminal - ("temporary scrollback") */ + tree234 *scrollback; /* lines scrolled off top of screen */ + tree234 *screen; /* lines on primary screen */ + tree234 *alt_screen; /* lines on alternate screen */ + int disptop; /* distance scrolled back (0 or -ve) */ + int tempsblines; /* number of lines of .scrollback that + can be retrieved onto the terminal + ("temporary scrollback") */ - termline **disptext; /* buffer of text on real screen */ - int dispcursx, dispcursy; /* location of cursor on real screen */ - int curstype; /* type of cursor on real screen */ + termline **disptext; /* buffer of text on real screen */ + int dispcursx, dispcursy; /* location of cursor on real screen */ + int curstype; /* type of cursor on real screen */ #define VBELL_TIMEOUT (TICKSPERSEC/10) /* visual bell lasts 1/10 sec */ @@ -104,16 +104,16 @@ struct terminal_tag { truecolour curr_truecolour, save_truecolour; termchar basic_erase_char, erase_char; - bufchain inbuf; /* terminal input buffer */ + bufchain inbuf; /* terminal input buffer */ - pos curs; /* cursor */ - pos savecurs; /* saved cursor position */ - int marg_t, marg_b; /* scroll margins */ + pos curs; /* cursor */ + pos savecurs; /* saved cursor position */ + int marg_t, marg_b; /* scroll margins */ bool dec_om; /* DEC origin mode flag */ bool wrap, wrapnext; /* wrap flags */ bool insert; /* insert-mode flag */ - int cset; /* 0 or 1: which char set */ - int save_cset, save_csattr; /* saved with cursor position */ + int cset; /* 0 or 1: which char set */ + int save_cset, save_csattr; /* saved with cursor position */ bool save_utf, save_wnext; /* saved with cursor position */ bool rvideo; /* global reverse video flag */ unsigned long rvbell_startpoint; /* for ESC[?5hESC[?5l vbell */ @@ -123,13 +123,13 @@ struct terminal_tag { bool cblinker; /* When blinking is the cursor on ? */ bool tblinker; /* When the blinking text is on */ bool blink_is_real; /* Actually blink blinking text */ - int sco_acs, save_sco_acs; /* CSI 10,11,12m -> OEM charset */ + int sco_acs, save_sco_acs; /* CSI 10,11,12m -> OEM charset */ bool vt52_bold; /* Force bold on non-bold colours */ bool utf; /* Are we in toggleable UTF-8 mode? */ term_utf8_decode utf8; /* If so, here's our decoding state */ bool printing, only_printing; /* Are we doing ANSI printing? */ - int print_state; /* state of print-end-sequence scan */ - bufchain printer_buf; /* buffered data for printer */ + int print_state; /* state of print-end-sequence scan */ + bufchain printer_buf; /* buffered data for printer */ printer_job *print_job; /* ESC 7 saved state for the alternate screen */ @@ -150,10 +150,10 @@ struct terminal_tag { bool seen_disp_event; bool big_cursor; - int xterm_mouse; /* send mouse messages to host */ + int xterm_mouse; /* send mouse messages to host */ bool xterm_extended_mouse; bool urxvt_extended_mouse; - int mouse_is_down; /* used while tracking mouse buttons */ + int mouse_is_down; /* used while tracking mouse buttons */ bool bracketed_paste, bracketed_paste_active; @@ -171,14 +171,14 @@ struct terminal_tag { int alt_which; int alt_sblines; /* # of lines on alternate screen that should be used for scrollback. */ -#define ARGS_MAX 32 /* max # of esc sequence arguments */ -#define ARG_DEFAULT 0 /* if an arg isn't specified */ +#define ARGS_MAX 32 /* max # of esc sequence arguments */ +#define ARG_DEFAULT 0 /* if an arg isn't specified */ #define def(a,d) ( (a) == ARG_DEFAULT ? (d) : (a) ) unsigned esc_args[ARGS_MAX]; int esc_nargs; int esc_query; -#define ANSI(x,y) ((x)+((y)*256)) -#define ANSI_QUE(x) ANSI(x,1) +#define ANSI(x,y) ((x)+((y)*256)) +#define ANSI_QUE(x) ANSI(x,1) #define OSC_STR_MAX 2048 int osc_strlen; @@ -190,31 +190,31 @@ struct terminal_tag { unsigned char *tabs; enum { - TOPLEVEL, - SEEN_ESC, - SEEN_CSI, - SEEN_OSC, - SEEN_OSC_W, + TOPLEVEL, + SEEN_ESC, + SEEN_CSI, + SEEN_OSC, + SEEN_OSC_W, - DO_CTRLS, + DO_CTRLS, - SEEN_OSC_P, - OSC_STRING, OSC_MAYBE_ST, - VT52_ESC, - VT52_Y1, - VT52_Y2, - VT52_FG, - VT52_BG + SEEN_OSC_P, + OSC_STRING, OSC_MAYBE_ST, + VT52_ESC, + VT52_Y1, + VT52_Y2, + VT52_FG, + VT52_BG } termstate; enum { - NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED + NO_SELECTION, ABOUT_TO, DRAGGING, SELECTED } selstate; enum { - LEXICOGRAPHIC, RECTANGULAR + LEXICOGRAPHIC, RECTANGULAR } seltype; enum { - SM_CHAR, SM_WORD, SM_LINE + SM_CHAR, SM_WORD, SM_LINE } selmode; pos selstart, selend, selanchor; diff --git a/test/cryptsuite.py b/test/cryptsuite.py index 20b8b7b9..7bc43052 100755 --- a/test/cryptsuite.py +++ b/test/cryptsuite.py @@ -1738,7 +1738,7 @@ class standard_test_vectors(MyTestBase): '1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7')) self.assertEqualBin(hash_str('sha384', "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), unhex( + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), unhex( '09330c33f71147e83d192fc782cd1b4753111b173b3b05d2' '2fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039')) self.assertEqualBin(hash_str_iter('sha384', @@ -1776,7 +1776,7 @@ class standard_test_vectors(MyTestBase): '2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')) self.assertEqualBin(hash_str('sha512', "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), unhex( + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), unhex( '8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018' '501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909')) self.assertEqualBin(hash_str_iter('sha512', diff --git a/test/desref.py b/test/desref.py index a79dec63..e09a07a1 100755 --- a/test/desref.py +++ b/test/desref.py @@ -138,9 +138,9 @@ class DES(DESBase): ] P = [ 0x07, 0x1c, 0x15, 0x0a, 0x1a, 0x02, 0x13, 0x0d, - 0x17, 0x1d, 0x05, 0x00, 0x12, 0x08, 0x18, 0x1e, + 0x17, 0x1d, 0x05, 0x00, 0x12, 0x08, 0x18, 0x1e, 0x16, 0x01, 0x0e, 0x1b, 0x06, 0x09, 0x11, 0x1f, - 0x0f, 0x04, 0x14, 0x03, 0x0b, 0x0c, 0x19, 0x10, + 0x0f, 0x04, 0x14, 0x03, 0x0b, 0x0c, 0x19, 0x10, ] sbox_index_offsets = [4*i-1 for i in range(8)] diff --git a/testback.c b/testback.c index 8abcaeb4..f26f395c 100644 --- a/testback.c +++ b/testback.c @@ -11,10 +11,10 @@ * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -74,8 +74,8 @@ struct loop_state { static const char *null_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, - const char *host, int port, char **realhost, - int nodelay, int keepalive) { + const char *host, int port, char **realhost, + int nodelay, int keepalive) { /* No local authentication phase in this protocol */ seat_set_trust_status(seat, false); diff --git a/testcrypt.c b/testcrypt.c index b8d18aed..277fd3d2 100644 --- a/testcrypt.c +++ b/testcrypt.c @@ -89,7 +89,7 @@ enum ValueType { #define VALTYPE_ENUM(n,t,f) VT_##n, VALUE_TYPES(VALTYPE_ENUM) #undef VALTYPE_ENUM -}; +}; typedef enum ValueType ValueType; diff --git a/testzlib.c b/testzlib.c index 2fda76b5..95419e9a 100644 --- a/testzlib.c +++ b/testzlib.c @@ -85,10 +85,10 @@ int main(int argc, char **argv) } while (1) { - ret = fread(buf, 1, sizeof(buf), fp); - if (ret <= 0) - break; - ssh_decompressor_decompress(handle, buf, ret, &outbuf, &outlen); + ret = fread(buf, 1, sizeof(buf), fp); + if (ret <= 0) + break; + ssh_decompressor_decompress(handle, buf, ret, &outbuf, &outlen); if (outbuf) { if (outlen) fwrite(outbuf, 1, outlen, stdout); diff --git a/timing.c b/timing.c index 8036e438..7281634a 100644 --- a/timing.c +++ b/timing.c @@ -1,6 +1,6 @@ /* * timing.c - * + * * This module tracks any timers set up by schedule_timer(). It * keeps all the currently active timers in a list; it informs the * front end of when the next timer is due to go off if that @@ -52,9 +52,9 @@ static int compare_timers(void *av, void *bv) long bt = b->now - now; if (at < bt) - return -1; + return -1; else if (at > bt) - return +1; + return +1; /* * Failing that, compare on the other two fields, just so that @@ -63,21 +63,21 @@ static int compare_timers(void *av, void *bv) #if defined(__LCC__) || defined(__clang__) /* lcc won't let us compare function pointers. Legal, but annoying. */ { - int c = memcmp(&a->fn, &b->fn, sizeof(a->fn)); - if (c) - return c; + int c = memcmp(&a->fn, &b->fn, sizeof(a->fn)); + if (c) + return c; } -#else +#else if (a->fn < b->fn) - return -1; + return -1; else if (a->fn > b->fn) - return +1; + return +1; #endif if (a->ctx < b->ctx) - return -1; + return -1; else if (a->ctx > b->ctx) - return +1; + return +1; /* * Failing _that_, the two entries genuinely are equal, and we @@ -91,18 +91,18 @@ static int compare_timer_contexts(void *av, void *bv) char *a = (char *)av; char *b = (char *)bv; if (a < b) - return -1; + return -1; else if (a > b) - return +1; + return +1; return 0; } static void init_timers(void) { if (!timers) { - timers = newtree234(compare_timers); - timer_contexts = newtree234(compare_timer_contexts); - now = GETTICKCOUNT(); + timers = newtree234(compare_timers); + timer_contexts = newtree234(compare_timer_contexts); + now = GETTICKCOUNT(); } } @@ -122,7 +122,7 @@ unsigned long schedule_timer(int ticks, timer_fn_t fn, void *ctx) * past, we instead schedule it for the immediate future. */ if (when - now <= 0) - when = now + 1; + when = now + 1; t = snew(struct timer); t->fn = fn; @@ -131,18 +131,18 @@ unsigned long schedule_timer(int ticks, timer_fn_t fn, void *ctx) t->when_set = now; if (t != add234(timers, t)) { - sfree(t); /* identical timer already exists */ + sfree(t); /* identical timer already exists */ } else { - add234(timer_contexts, t->ctx);/* don't care if this fails */ + add234(timer_contexts, t->ctx);/* don't care if this fails */ } first = (struct timer *)index234(timers, 0); if (first == t) { - /* - * This timer is the very first on the list, so we must - * notify the front end. - */ - timer_change_notify(first->now); + /* + * This timer is the very first on the list, so we must + * notify the front end. + */ + timer_change_notify(first->now); } return when; @@ -173,35 +173,35 @@ bool run_timers(unsigned long anow, unsigned long *next) now = GETTICKCOUNT(); while (1) { - first = (struct timer *)index234(timers, 0); + first = (struct timer *)index234(timers, 0); - if (!first) - return false; /* no timers remaining */ + if (!first) + return false; /* no timers remaining */ - if (find234(timer_contexts, first->ctx, NULL) == NULL) { - /* - * This timer belongs to a context that has been - * expired. Delete it without running. - */ - delpos234(timers, 0); - sfree(first); - } else if (now - (first->when_set - 10) > - first->now - (first->when_set - 10)) { - /* - * This timer is active and has reached its running - * time. Run it. - */ - delpos234(timers, 0); - first->fn(first->ctx, first->now); - sfree(first); - } else { - /* - * This is the first still-active timer that is in the - * future. Return how long it has yet to go. - */ - *next = first->now; - return true; - } + if (find234(timer_contexts, first->ctx, NULL) == NULL) { + /* + * This timer belongs to a context that has been + * expired. Delete it without running. + */ + delpos234(timers, 0); + sfree(first); + } else if (now - (first->when_set - 10) > + first->now - (first->when_set - 10)) { + /* + * This timer is active and has reached its running + * time. Run it. + */ + delpos234(timers, 0); + first->fn(first->ctx, first->now); + sfree(first); + } else { + /* + * This is the first still-active timer that is in the + * future. Return how long it has yet to go. + */ + *next = first->now; + return true; + } } } diff --git a/tree234.c b/tree234.c index 57866fd3..0ec2b520 100644 --- a/tree234.c +++ b/tree234.c @@ -1,8 +1,8 @@ /* * tree234.c: reasonably generic counted 2-3-4 tree routines. - * + * * This file is copyright 1999-2001 Simon Tatham. - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,10 +11,10 @@ * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -77,7 +77,7 @@ tree234 *newtree234(cmpfn234 cmp) static void freenode234(node234 * n) { if (!n) - return; + return; freenode234(n->kids[0]); freenode234(n->kids[1]); freenode234(n->kids[2]); @@ -99,12 +99,12 @@ static int countnode234(node234 * n) int count = 0; int i; if (!n) - return 0; + return 0; for (i = 0; i < 4; i++) - count += n->counts[i]; + count += n->counts[i]; for (i = 0; i < 3; i++) - if (n->elems[i]) - count++; + if (n->elems[i]) + count++; return count; } @@ -126,9 +126,9 @@ static int elements234(node234 *n) int count234(tree234 * t) { if (t->root) - return countnode234(t->root); + return countnode234(t->root); else - return 0; + return 0; } /* @@ -143,85 +143,85 @@ static void *add234_internal(tree234 * t, void *e, int index) LOG(("adding node %p to tree %p\n", e, t)); if (t->root == NULL) { - t->root = snew(node234); - t->root->elems[1] = t->root->elems[2] = NULL; - t->root->kids[0] = t->root->kids[1] = NULL; - t->root->kids[2] = t->root->kids[3] = NULL; - t->root->counts[0] = t->root->counts[1] = 0; - t->root->counts[2] = t->root->counts[3] = 0; - t->root->parent = NULL; - t->root->elems[0] = e; - LOG((" created root %p\n", t->root)); - return orig_e; + t->root = snew(node234); + t->root->elems[1] = t->root->elems[2] = NULL; + t->root->kids[0] = t->root->kids[1] = NULL; + t->root->kids[2] = t->root->kids[3] = NULL; + t->root->counts[0] = t->root->counts[1] = 0; + t->root->counts[2] = t->root->counts[3] = 0; + t->root->parent = NULL; + t->root->elems[0] = e; + LOG((" created root %p\n", t->root)); + return orig_e; } n = NULL; /* placate gcc; will always be set below since t->root != NULL */ np = &t->root; while (*np) { - int childnum; - n = *np; - LOG((" node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%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])); - if (index >= 0) { - if (!n->kids[0]) { - /* - * Leaf node. We want to insert at kid position - * equal to the index: - * - * 0 A 1 B 2 C 3 - */ - childnum = index; - } else { - /* - * Internal node. We always descend through it (add - * always starts at the bottom, never in the - * middle). - */ - do { /* this is a do ... while (0) to allow `break' */ - if (index <= n->counts[0]) { - childnum = 0; - break; - } - index -= n->counts[0] + 1; - if (index <= n->counts[1]) { - childnum = 1; - break; - } - index -= n->counts[1] + 1; - if (index <= n->counts[2]) { - childnum = 2; - break; - } - index -= n->counts[2] + 1; - if (index <= n->counts[3]) { - childnum = 3; - break; - } - return NULL; /* error: index out of range */ - } while (0); - } - } else { - 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; - 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; - else if (c == 0) - return n->elems[2]; /* already exists */ - else - childnum = 3; - } - np = &n->kids[childnum]; - LOG((" moving to child %d (%p)\n", childnum, *np)); + int childnum; + n = *np; + LOG((" node %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%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])); + if (index >= 0) { + if (!n->kids[0]) { + /* + * Leaf node. We want to insert at kid position + * equal to the index: + * + * 0 A 1 B 2 C 3 + */ + childnum = index; + } else { + /* + * Internal node. We always descend through it (add + * always starts at the bottom, never in the + * middle). + */ + do { /* this is a do ... while (0) to allow `break' */ + if (index <= n->counts[0]) { + childnum = 0; + break; + } + index -= n->counts[0] + 1; + if (index <= n->counts[1]) { + childnum = 1; + break; + } + index -= n->counts[1] + 1; + if (index <= n->counts[2]) { + childnum = 2; + break; + } + index -= n->counts[2] + 1; + if (index <= n->counts[3]) { + childnum = 3; + break; + } + return NULL; /* error: index out of range */ + } while (0); + } + } else { + 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; + 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; + else if (c == 0) + return n->elems[2]; /* already exists */ + else + childnum = 3; + } + np = &n->kids[childnum]; + LOG((" moving to child %d (%p)\n", childnum, *np)); } /* @@ -232,193 +232,193 @@ static void *add234_internal(tree234 * t, void *e, int index) right = NULL; rcount = 0; while (n) { - LOG((" at %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%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])); - LOG((" need to insert %p/%d [%p] %p/%d at position %d\n", - left, lcount, e, right, rcount, (int)(np - n->kids))); - if (n->elems[1] == NULL) { - /* - * Insert in a 2-node; simple. - */ - 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->elems[1] = n->elems[0]; - 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] */ - LOG((" inserting on right of 2-node\n")); - n->kids[2] = right; - n->counts[2] = rcount; - n->elems[1] = e; - 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; - LOG((" done\n")); - break; - } else if (n->elems[2] == NULL) { - /* - * Insert in a 3-node; simple. - */ - 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->elems[2] = n->elems[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->elems[0] = e; - 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->elems[2] = n->elems[1]; - 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] */ - LOG((" inserting on right of 3-node\n")); - n->kids[3] = right; - n->counts[3] = rcount; - n->elems[2] = e; - 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; - LOG((" done\n")); - break; - } else { - node234 *m = snew(node234); - m->parent = n->parent; - LOG((" splitting a 4-node; created new node %p\n", m)); - /* - * Insert in a 4-node; split into a 2-node and a - * 3-node, and move focus up a level. - * - * I don't think it matters which way round we put the - * 2 and the 3. For simplicity, we'll put the 3 first - * always. - */ - if (np == &n->kids[0]) { - m->kids[0] = left; - m->counts[0] = lcount; - m->elems[0] = e; - 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]; - e = n->elems[1]; - 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]; - } else if (np == &n->kids[1]) { - 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->elems[1] = e; - 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->elems[0] = n->elems[2]; - 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->elems[0] = n->elems[0]; - 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; - /* e = e; */ - 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]; - m->elems[0] = n->elems[0]; - 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; - n->elems[0] = e; - 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; - 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], - m->kids[2], m->counts[2])); - 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); - } - if (n->parent) - np = (n->parent->kids[0] == n ? &n->parent->kids[0] : - n->parent->kids[1] == n ? &n->parent->kids[1] : - n->parent->kids[2] == n ? &n->parent->kids[2] : - &n->parent->kids[3]); - n = n->parent; + LOG((" at %p: %p/%d [%p] %p/%d [%p] %p/%d [%p] %p/%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])); + LOG((" need to insert %p/%d [%p] %p/%d at position %d\n", + left, lcount, e, right, rcount, (int)(np - n->kids))); + if (n->elems[1] == NULL) { + /* + * Insert in a 2-node; simple. + */ + 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->elems[1] = n->elems[0]; + 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] */ + LOG((" inserting on right of 2-node\n")); + n->kids[2] = right; + n->counts[2] = rcount; + n->elems[1] = e; + 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; + LOG((" done\n")); + break; + } else if (n->elems[2] == NULL) { + /* + * Insert in a 3-node; simple. + */ + 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->elems[2] = n->elems[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->elems[0] = e; + 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->elems[2] = n->elems[1]; + 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] */ + LOG((" inserting on right of 3-node\n")); + n->kids[3] = right; + n->counts[3] = rcount; + n->elems[2] = e; + 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; + LOG((" done\n")); + break; + } else { + node234 *m = snew(node234); + m->parent = n->parent; + LOG((" splitting a 4-node; created new node %p\n", m)); + /* + * Insert in a 4-node; split into a 2-node and a + * 3-node, and move focus up a level. + * + * I don't think it matters which way round we put the + * 2 and the 3. For simplicity, we'll put the 3 first + * always. + */ + if (np == &n->kids[0]) { + m->kids[0] = left; + m->counts[0] = lcount; + m->elems[0] = e; + 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]; + e = n->elems[1]; + 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]; + } else if (np == &n->kids[1]) { + 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->elems[1] = e; + 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->elems[0] = n->elems[2]; + 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->elems[0] = n->elems[0]; + 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; + /* e = e; */ + 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]; + m->elems[0] = n->elems[0]; + 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; + n->elems[0] = e; + 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; + 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], + m->kids[2], m->counts[2])); + 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); + } + if (n->parent) + np = (n->parent->kids[0] == n ? &n->parent->kids[0] : + n->parent->kids[1] == n ? &n->parent->kids[1] : + n->parent->kids[2] == n ? &n->parent->kids[2] : + &n->parent->kids[3]); + n = n->parent; } /* @@ -428,37 +428,37 @@ static void *add234_internal(tree234 * t, void *e, int index) * need to create a new root for the tree because the old one * has just split into two. */ if (n) { - while (n->parent) { - int count = countnode234(n); - int childnum; - childnum = (n->parent->kids[0] == n ? 0 : - n->parent->kids[1] == n ? 1 : - n->parent->kids[2] == n ? 2 : 3); - n->parent->counts[childnum] = count; - n = n->parent; - } + while (n->parent) { + int count = countnode234(n); + int childnum; + childnum = (n->parent->kids[0] == n ? 0 : + n->parent->kids[1] == n ? 1 : + n->parent->kids[2] == n ? 2 : 3); + n->parent->counts[childnum] = count; + n = n->parent; + } } else { - LOG((" root is overloaded, split into two\n")); - t->root = snew(node234); - 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->elems[1] = NULL; - 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->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; - 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])); + LOG((" root is overloaded, split into two\n")); + t->root = snew(node234); + 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->elems[1] = NULL; + 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->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; + 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])); } return orig_e; @@ -466,18 +466,18 @@ static void *add234_internal(tree234 * t, void *e, int index) void *add234(tree234 * t, void *e) { - if (!t->cmp) /* tree is unsorted */ - return NULL; + if (!t->cmp) /* tree is unsorted */ + return NULL; return add234_internal(t, e, -1); } void *addpos234(tree234 * t, void *e, int index) { - if (index < 0 || /* index out of range */ - t->cmp) /* tree is sorted */ - return NULL; /* return failure */ + 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 */ } /* @@ -489,28 +489,28 @@ void *index234(tree234 * t, int index) node234 *n; if (!t->root) - return NULL; /* tree is empty */ + return NULL; /* tree is empty */ if (index < 0 || index >= countnode234(t->root)) - return NULL; /* out of range */ + return NULL; /* out of range */ n = t->root; while (n) { - if (index < n->counts[0]) - n = n->kids[0]; - else if (index -= n->counts[0] + 1, index < 0) - return n->elems[0]; - else if (index < n->counts[1]) - n = n->kids[1]; - else if (index -= n->counts[1] + 1, index < 0) - return n->elems[1]; - else if (index < n->counts[2]) - n = n->kids[2]; - else if (index -= n->counts[2] + 1, index < 0) - return n->elems[2]; - else - n = n->kids[3]; + if (index < n->counts[0]) + n = n->kids[0]; + else if (index -= n->counts[0] + 1, index < 0) + return n->elems[0]; + else if (index < n->counts[1]) + n = n->kids[1]; + else if (index -= n->counts[1] + 1, index < 0) + return n->elems[1]; + else if (index < n->counts[2]) + n = n->kids[2]; + else if (index -= n->counts[2] + 1, index < 0) + return n->elems[2]; + else + n = n->kids[3]; } /* We shouldn't ever get here. I wonder how we did. */ @@ -525,7 +525,7 @@ void *index234(tree234 * t, int index) * will be used. */ void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp, - int relation, int *index) + int relation, int *index) { search234_state ss; int reldir = (relation == REL234_LT || relation == REL234_LE ? -1 : @@ -537,7 +537,7 @@ void *findrelpos234(tree234 * t, void *e, cmpfn234 cmp, assert(!(equal_permitted && !e)); if (cmp == NULL) - cmp = t->cmp; + cmp = t->cmp; search234_start(&ss, t); while (ss.element) { @@ -698,345 +698,345 @@ static void *delpos234_internal(tree234 * t, int index) n = t->root; LOG(("deleting item %d from tree %p\n", index, t)); while (1) { - while (n) { - int ki; - node234 *sub; + while (n) { + 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)); - if (index < n->counts[0]) { - ki = 0; - } 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[2]) { - ki = 2; - } else if (index -= n->counts[2] + 1, index < 0) { - ei = 2; - break; - } else { - ki = 3; - } - /* - * Recurse down to subtree ki. If it has only one element, - * we have to do some transformation to start with. - */ - LOG((" moving to subtree %d\n", ki)); - sub = n->kids[ki]; - if (!sub->elems[1]) { - LOG((" subtree has only one element!\n")); - 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 - * more. So we need to move a subtree from ki-1 - * to ki. - * - * . C . . B . - * / \ -> / \ - * [more] a A b B c d D e [more] a A b c C d D e - */ - node234 *sib = n->kids[ki - 1]; - int lastelem = (sib->elems[2] ? 2 : - sib->elems[1] ? 1 : 0); - sub->kids[2] = sub->kids[1]; - sub->counts[2] = sub->counts[1]; - 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; - 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]) { - /* - * Case 3a, right-handed variant. ki has only - * one element but ki+1 has two or more. Move a - * subtree from ki+1 to ki. - * - * . B . . C . - * / \ -> / \ - * a A b c C d D e [more] a A b B c d D e [more] - */ - 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; - 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]; - } - 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); - LOG((" case 3a right\n")); - } else { - /* - * Case 3b. ki has only one element, and has no - * neighbour with more than one. So pick a - * neighbour and merge it with ki, taking an - * element down from n to go in the middle. - * - * . B . . - * / \ -> | - * a A b c C d a A b B c C d - * - * (Since at all points we have avoided - * descending to a node with only one element, - * we can be sure that n is not reduced to - * nothingness by this move, _unless_ it was - * the very first node, ie the root of the - * tree. In that case we remove the now-empty - * root and replace it with its single large - * child as shown.) - */ - node234 *sib; - int j; + 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[1]) { + ki = 1; + } 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 { + ki = 3; + } + /* + * Recurse down to subtree ki. If it has only one element, + * we have to do some transformation to start with. + */ + LOG((" moving to subtree %d\n", ki)); + sub = n->kids[ki]; + if (!sub->elems[1]) { + LOG((" subtree has only one element!\n")); + 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 + * more. So we need to move a subtree from ki-1 + * to ki. + * + * . C . . B . + * / \ -> / \ + * [more] a A b B c d D e [more] a A b c C d D e + */ + node234 *sib = n->kids[ki - 1]; + int lastelem = (sib->elems[2] ? 2 : + sib->elems[1] ? 1 : 0); + sub->kids[2] = sub->kids[1]; + sub->counts[2] = sub->counts[1]; + 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; + 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]) { + /* + * Case 3a, right-handed variant. ki has only + * one element but ki+1 has two or more. Move a + * subtree from ki+1 to ki. + * + * . B . . C . + * / \ -> / \ + * a A b c C d D e [more] a A b B c d D e [more] + */ + 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; + 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]; + } + 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); + LOG((" case 3a right\n")); + } else { + /* + * Case 3b. ki has only one element, and has no + * neighbour with more than one. So pick a + * neighbour and merge it with ki, taking an + * element down from n to go in the middle. + * + * . B . . + * / \ -> | + * a A b c C d a A b B c C d + * + * (Since at all points we have avoided + * descending to a node with only one element, + * we can be sure that n is not reduced to + * nothingness by this move, _unless_ it was + * the very first node, ie the root of the + * tree. In that case we remove the now-empty + * root and replace it with its single large + * child as shown.) + */ + node234 *sib; + int j; - if (ki > 0) { - ki--; - index += n->counts[ki] + 1; - } - sib = n->kids[ki]; - sub = n->kids[ki + 1]; + if (ki > 0) { + ki--; + index += n->counts[ki] + 1; + } + sib = n->kids[ki]; + sub = n->kids[ki + 1]; - sub->kids[3] = sub->kids[1]; - sub->counts[3] = sub->counts[1]; - sub->elems[2] = sub->elems[0]; - sub->kids[2] = sub->kids[0]; - sub->counts[2] = sub->counts[0]; - 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; - 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; + sub->kids[3] = sub->kids[1]; + sub->counts[3] = sub->counts[1]; + sub->elems[2] = sub->elems[0]; + sub->kids[2] = sub->kids[0]; + sub->counts[2] = sub->counts[0]; + 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; + 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; - n->counts[ki + 1] = countnode234(sub); + n->counts[ki + 1] = countnode234(sub); - sfree(sib); + sfree(sib); - /* - * 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; - } - n->kids[j] = NULL; - n->counts[j] = 0; - if (j < 3) - n->elems[j] = NULL; - LOG((" case 3b ki=%d\n", ki)); + /* + * 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; + } + n->kids[j] = NULL; + n->counts[j] = 0; + if (j < 3) + n->elems[j] = NULL; + LOG((" case 3b ki=%d\n", ki)); - if (!n->elems[0]) { - /* - * The root is empty and needs to be - * removed. - */ - LOG((" shifting root!\n")); - t->root = sub; - sub->parent = NULL; - sfree(n); - } - } - } - n = sub; - } - if (!retval) - retval = n->elems[ei]; + if (!n->elems[0]) { + /* + * The root is empty and needs to be + * removed. + */ + LOG((" shifting root!\n")); + t->root = sub; + sub->parent = NULL; + sfree(n); + } + } + } + n = sub; + } + if (!retval) + retval = n->elems[ei]; - if (ei == -1) - return NULL; /* although this shouldn't happen */ + if (ei == -1) + return NULL; /* although this shouldn't happen */ - /* - * Treat special case: this is the one remaining item in - * the tree. n is the tree root (no parent), has one - * element (no elems[1]), and has no kids (no kids[0]). - */ - if (!n->parent && !n->elems[1] && !n->kids[0]) { - LOG((" removed last element in tree\n")); - sfree(n); - t->root = NULL; - return retval; - } + /* + * Treat special case: this is the one remaining item in + * the tree. n is the tree root (no parent), has one + * element (no elems[1]), and has no kids (no kids[0]). + */ + if (!n->parent && !n->elems[1] && !n->kids[0]) { + LOG((" removed last element in tree\n")); + sfree(n); + t->root = NULL; + return retval; + } - /* - * Now we have the element we want, as n->elems[ei], and we - * have also arranged for that element not to be the only - * one in its node. So... - */ + /* + * Now we have the element we want, as n->elems[ei], and we + * have also arranged for that element not to be the only + * one in its node. So... + */ - if (!n->kids[0] && n->elems[1]) { - /* - * Case 1. n is a leaf node with more than one element, - * so it's _really easy_. Just delete the thing and - * we're done. - */ - int i; - LOG((" case 1\n")); - 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 - * the tree fixing the counts. - */ - while (n->parent) { - int childnum; - childnum = (n->parent->kids[0] == n ? 0 : - n->parent->kids[1] == n ? 1 : - n->parent->kids[2] == n ? 2 : 3); - n->parent->counts[childnum]--; - n = n->parent; - } - return retval; /* finished! */ - } else if (n->kids[ei]->elems[1]) { - /* - * Case 2a. n is an internal node, and the root of the - * subtree to the left of e has more than one element. - * So find the predecessor p to e (ie the largest node - * in that subtree), place it where e currently is, and - * then start the deletion process over again on the - * subtree with p as target. - */ - node234 *m = n->kids[ei]; - void *target; - LOG((" case 2a\n")); - 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]); - } - 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; - n = n->kids[ei]; - } 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]; - void *target; - LOG((" case 2b\n")); - while (m->kids[0]) { - m = m->kids[0]; - } - target = m->elems[0]; - n->elems[ei] = target; - n = n->kids[ei + 1]; - index = 0; - } else { - /* - * Case 2c. n is an internal node, and the subtrees to - * the left and right of e both have only one element. - * So combine the two subnodes into a single big node - * with their own elements on the left and right and e - * 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]; - int j; + if (!n->kids[0] && n->elems[1]) { + /* + * Case 1. n is a leaf node with more than one element, + * so it's _really easy_. Just delete the thing and + * we're done. + */ + int i; + LOG((" case 1\n")); + 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 + * the tree fixing the counts. + */ + while (n->parent) { + int childnum; + childnum = (n->parent->kids[0] == n ? 0 : + n->parent->kids[1] == n ? 1 : + n->parent->kids[2] == n ? 2 : 3); + n->parent->counts[childnum]--; + n = n->parent; + } + return retval; /* finished! */ + } else if (n->kids[ei]->elems[1]) { + /* + * Case 2a. n is an internal node, and the root of the + * subtree to the left of e has more than one element. + * So find the predecessor p to e (ie the largest node + * in that subtree), place it where e currently is, and + * then start the deletion process over again on the + * subtree with p as target. + */ + node234 *m = n->kids[ei]; + void *target; + LOG((" case 2a\n")); + 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]); + } + 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; + n = n->kids[ei]; + } 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]; + void *target; + LOG((" case 2b\n")); + while (m->kids[0]) { + m = m->kids[0]; + } + target = m->elems[0]; + n->elems[ei] = target; + n = n->kids[ei + 1]; + index = 0; + } else { + /* + * Case 2c. n is an internal node, and the subtrees to + * the left and right of e both have only one element. + * So combine the two subnodes into a single big node + * with their own elements on the left and right and e + * 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]; + 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; - 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; - 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]; - } - 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); - } - /* - * Now go round the deletion process again, with n - * pointing at the new big node and e still the same. - */ - n = a; - index = a->counts[0] + a->counts[1] + 1; - } + 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; + 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; + 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]; + } + 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); + } + /* + * Now go round the deletion process again, with n + * pointing at the new big node and e still the same. + */ + n = a; + index = a->counts[0] + a->counts[1] + 1; + } } } void *delpos234(tree234 * t, int index) { if (index < 0 || index >= countnode234(t->root)) - return NULL; + return NULL; return delpos234_internal(t, index); } 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 NULL; /* it wasn't in there anyway */ + return delpos234_internal(t, index); /* it's there; delete it. */ } #ifdef TEST @@ -1097,7 +1097,7 @@ typedef struct { } chkctx; int chknode(chkctx * ctx, int level, node234 * node, - void *lowbound, void *highbound) + void *lowbound, void *highbound) { int nkids, nelems; int i; @@ -1107,51 +1107,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); } /* @@ -1167,15 +1167,15 @@ int chknode(chkctx * ctx, int level, node234 * node, * everything and > everything. IYSWIM.) */ 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]); - if (lower && higher && cmp(lower, higher) >= 0) { - error("node %p: kid comparison [%d=%s,%d=%s] failed", - node, i, lower, i + 1, higher); - } - } + for (i = -1; i < nelems; i++) { + void *lower = (i == -1 ? lowbound : node->elems[i]); + 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); + } + } } /* @@ -1183,10 +1183,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); + } /* @@ -1195,15 +1195,15 @@ 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); - 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; + 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; } return count; @@ -1215,38 +1215,38 @@ void verify(void) 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); + if (tree->root->parent != NULL) + error("root->parent is %p should be null", tree->root->parent); + 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", - ctx.elemcount, i); + error("tree really contains %d elements, count234 gave %d", + ctx.elemcount, i); } } @@ -1256,20 +1256,20 @@ void internal_addtest(void *elem, int index, void *realret) void *retval; if (arraysize < arraylen + 1) { - arraysize = arraylen + 1 + 256; - array = sresize(array, arraysize, void *); + arraysize = arraylen + 1 + 256; + array = sresize(array, arraysize, void *); } 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(); @@ -1284,14 +1284,14 @@ 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 */ - if (realret != retval) { - error("add: retval was %p expected %p", realret, retval); - } + void *retval = array[i]; /* expect that returned not elem */ + if (realret != retval) { + error("add: retval was %p expected %p", realret, retval); + } } else - internal_addtest(elem, i, realret); + internal_addtest(elem, i, realret); } void addpostest(void *elem, int i) @@ -1310,18 +1310,18 @@ void delpostest(int i) /* i points to the right element */ while (i < arraylen - 1) { - array[i] = array[i + 1]; - i++; + array[i] = array[i + 1]; + i++; } - arraylen--; /* delete elem from array */ + arraylen--; /* delete elem from array */ if (tree->cmp) - ret = del234(tree, elem); + ret = del234(tree, elem); else - ret = delpos234(tree, index); + ret = delpos234(tree, index); if (ret != elem) { - error("del returned %p, expected %p", ret, elem); + error("del returned %p, expected %p", ret, elem); } verify(); @@ -1333,9 +1333,9 @@ void deltest(void *elem) 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); } @@ -1382,90 +1382,90 @@ char *strings[] = { int findtest(void) { const static int rels[] = { - REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT + REL234_EQ, REL234_GE, REL234_LE, REL234_LT, REL234_GT }; const static char *const relnames[] = { - "EQ", "GE", "LE", "LT", "GT" + "EQ", "GE", "LE", "LT", "GT" }; int i, j, rel, index; char *p, *ret, *realret, *realret2; int lo, hi, mid, c; for (i = 0; i < NSTR; i++) { - p = strings[i]; - for (j = 0; j < sizeof(rels) / sizeof(*rels); j++) { - rel = rels[j]; + p = strings[i]; + for (j = 0; j < sizeof(rels) / sizeof(*rels); j++) { + rel = rels[j]; - lo = 0; - hi = arraylen - 1; - while (lo <= hi) { - mid = (lo + hi) / 2; - c = strcmp(p, array[mid]); - if (c < 0) - hi = mid - 1; - else if (c > 0) - lo = mid + 1; - else - break; - } + lo = 0; + hi = arraylen - 1; + while (lo <= hi) { + mid = (lo + hi) / 2; + c = strcmp(p, array[mid]); + if (c < 0) + hi = mid - 1; + else if (c > 0) + lo = mid + 1; + else + break; + } - if (c == 0) { - if (rel == REL234_LT) - ret = (mid > 0 ? array[--mid] : NULL); - else if (rel == REL234_GT) - ret = (mid < arraylen - 1 ? array[++mid] : NULL); - else - ret = array[mid]; - } else { - assert(lo == hi + 1); - if (rel == REL234_LT || rel == REL234_LE) { - mid = hi; - ret = (hi >= 0 ? array[hi] : NULL); - } else if (rel == REL234_GT || rel == REL234_GE) { - mid = lo; - ret = (lo < arraylen ? array[lo] : NULL); - } else - ret = NULL; - } + if (c == 0) { + if (rel == REL234_LT) + ret = (mid > 0 ? array[--mid] : NULL); + else if (rel == REL234_GT) + ret = (mid < arraylen - 1 ? array[++mid] : NULL); + else + ret = array[mid]; + } else { + assert(lo == hi + 1); + if (rel == REL234_LT || rel == REL234_LE) { + mid = hi; + ret = (hi >= 0 ? array[hi] : NULL); + } else if (rel == REL234_GT || rel == REL234_GE) { + mid = lo; + ret = (lo < arraylen ? array[lo] : NULL); + } else + ret = NULL; + } - realret = findrelpos234(tree, p, NULL, rel, &index); - if (realret != ret) { - error("find(\"%s\",%s) gave %s should be %s", - p, relnames[j], realret, ret); - } - if (realret && index != mid) { - error("find(\"%s\",%s) gave %d should be %d", - p, relnames[j], index, mid); - } - if (realret && rel == REL234_EQ) { - realret2 = index234(tree, index); - if (realret2 != realret) { - error("find(\"%s\",%s) gave %s(%d) but %d -> %s", - p, relnames[j], realret, index, index, realret2); - } - } + realret = findrelpos234(tree, p, NULL, rel, &index); + if (realret != ret) { + error("find(\"%s\",%s) gave %s should be %s", + p, relnames[j], realret, ret); + } + if (realret && index != mid) { + error("find(\"%s\",%s) gave %d should be %d", + p, relnames[j], index, mid); + } + if (realret && rel == REL234_EQ) { + realret2 = index234(tree, index); + if (realret2 != realret) { + error("find(\"%s\",%s) gave %s(%d) but %d -> %s", + p, relnames[j], realret, index, index, realret2); + } + } #if 0 - printf("find(\"%s\",%s) gave %s(%d)\n", p, relnames[j], - realret, index); + printf("find(\"%s\",%s) gave %s(%d)\n", p, relnames[j], + realret, index); #endif - } + } } realret = findrelpos234(tree, NULL, NULL, REL234_GT, &index); if (arraylen && (realret != array[0] || index != 0)) { - error("find(NULL,GT) gave %s(%d) should be %s(0)", - realret, index, array[0]); + 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]); + && (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); } } @@ -1543,7 +1543,7 @@ int main(void) unsigned seed = 0; for (i = 0; i < NSTR; i++) - in[i] = 0; + in[i] = 0; array = NULL; arraylen = arraysize = 0; tree = newtree234(mycmp); @@ -1552,26 +1552,26 @@ int main(void) verify(); searchtest(); 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; - } - findtest(); + 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(); searchtest(); } while (arraylen > 0) { - j = randomnumber(&seed); - j %= arraylen; - deltest(array[j]); + j = randomnumber(&seed); + j %= arraylen; + deltest(array[j]); } freetree234(tree); @@ -1587,21 +1587,21 @@ int main(void) cmp = NULL; verify(); for (i = 0; i < 1000; i++) { - printf("trial: %d\n", i); - j = randomnumber(&seed); - j %= NSTR; - k = randomnumber(&seed); - k %= count234(tree) + 1; - printf("adding string %s at index %d\n", strings[j], k); - addpostest(strings[j], k); + printf("trial: %d\n", i); + j = randomnumber(&seed); + j %= NSTR; + k = randomnumber(&seed); + k %= count234(tree) + 1; + printf("adding string %s at index %d\n", strings[j], k); + addpostest(strings[j], k); } while (count234(tree) > 0) { - printf("cleanup: tree size %d\n", count234(tree)); - j = randomnumber(&seed); - j %= count234(tree); - printf("deleting string %s from index %d\n", + printf("cleanup: tree size %d\n", count234(tree)); + j = randomnumber(&seed); + j %= count234(tree); + printf("deleting string %s from index %d\n", (const char *)array[j], j); - delpostest(j); + delpostest(j); } printf("%d errors found\n", n_errors); diff --git a/tree234.h b/tree234.h index 55cbe360..0f2012d0 100644 --- a/tree234.h +++ b/tree234.h @@ -1,8 +1,8 @@ /* * tree234.h: header defining functions in tree234.c. - * + * * This file is copyright 1999-2001 Simon Tatham. - * + * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without @@ -11,10 +11,10 @@ * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -57,7 +57,7 @@ void *add234(tree234 * t, void *e); * Add an element e to an unsorted 2-3-4 tree t. Returns e on * success, NULL on failure. (Failure should only occur if the * index is out of range or the tree is sorted.) - * + * * Index range can be from 0 to the tree's current element count, * inclusive. */ @@ -66,14 +66,14 @@ void *addpos234(tree234 * t, void *e, int index); /* * Look up the element at a given numeric index in a 2-3-4 tree. * Returns NULL if the index is out of range. - * + * * One obvious use for this function is in iterating over the whole * of a tree (sorted or unsorted): - * + * * for (i = 0; (p = index234(tree, i)) != NULL; i++) consume(p); - * + * * or - * + * * int maxcount = count234(tree); * for (i = 0; i < maxcount; i++) { * p = index234(tree, i); @@ -89,36 +89,36 @@ void *index234(tree234 * t, int index); * can be an asymmetric function if desired. cmp can also be passed * as NULL, in which case the compare function from the tree proper * will be used. - * + * * Three of these functions are special cases of findrelpos234. The * non-`pos' variants lack the `index' parameter: if the parameter * is present and non-NULL, it must point to an integer variable * which will be filled with the numeric index of the returned * element. - * + * * The non-`rel' variants lack the `relation' parameter. This * parameter allows you to specify what relation the element you * provide has to the element you're looking for. This parameter * can be: - * + * * REL234_EQ - find only an element that compares equal to e * REL234_LT - find the greatest element that compares < e * REL234_LE - find the greatest element that compares <= e * REL234_GT - find the smallest element that compares > e * REL234_GE - find the smallest element that compares >= e - * + * * Non-`rel' variants assume REL234_EQ. - * + * * If `rel' is REL234_GT or REL234_LT, the `e' parameter may be * NULL. In this case, REL234_GT will return the smallest element * in the tree, and REL234_LT will return the greatest. This gives * an alternative means of iterating over a sorted tree, instead of * using index234: - * + * * // to loop forwards * for (p = NULL; (p = findrel234(tree, p, NULL, REL234_GT)) != NULL ;) * consume(p); - * + * * // to loop backwards * for (p = NULL; (p = findrel234(tree, p, NULL, REL234_LT)) != NULL ;) * consume(p); @@ -130,7 +130,7 @@ 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); + int *index); /* * A more general search type still. Use search234_start() to @@ -170,15 +170,15 @@ void search234_step(search234_state *state, int direction); /* * 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. - * + * * delpos234 deletes the element at a particular tree index: it * works on both sorted and unsorted trees. - * + * * del234 deletes the element passed to it, so it only works on * sorted trees. (It's equivalent to using findpos234 to determine * the index of an element, and then passing that index to * delpos234.) - * + * * Both functions return a pointer to the element they delete, for * the user to free or pass on elsewhere or whatever. If the index * is out of range (delpos234) or the element is already not in the @@ -192,4 +192,4 @@ void *delpos234(tree234 * t, int index); */ int count234(tree234 * t); -#endif /* TREE234_H */ +#endif /* TREE234_H */ diff --git a/unix/gtkcfg.c b/unix/gtkcfg.c index 8b0ea31f..93c48ce6 100644 --- a/unix/gtkcfg.c +++ b/unix/gtkcfg.c @@ -11,10 +11,10 @@ #include "storage.h" static void about_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { if (event == EVENT_ACTION) { - about_box(ctrl->generic.context.p); + about_box(ctrl->generic.context.p); } } @@ -25,13 +25,13 @@ void gtk_setup_config_box(struct controlbox *b, bool midsession, void *win) int i; if (!midsession) { - /* - * Add the About button to the standard panel. - */ - s = ctrl_getset(b, "", "", ""); - c = ctrl_pushbutton(s, "About", 'a', HELPCTX(no_help), - about_handler, P(win)); - c->generic.column = 0; + /* + * Add the About button to the standard panel. + */ + s = ctrl_getset(b, "", "", ""); + c = ctrl_pushbutton(s, "About", 'a', HELPCTX(no_help), + about_handler, P(win)); + c->generic.column = 0; } /* @@ -39,10 +39,10 @@ void gtk_setup_config_box(struct controlbox *b, bool midsession, void *win) * than Windows does! */ s = ctrl_getset(b, "Window", "scrollback", - "Control the scrollback in the window"); + "Control the scrollback in the window"); ctrl_checkbox(s, "Scrollbar on left", 'l', - HELPCTX(no_help), - conf_checkbox_handler, + HELPCTX(no_help), + conf_checkbox_handler, I(CONF_scrollbar_on_left)); /* * Really this wants to go just after `Display scrollbar'. See @@ -89,29 +89,29 @@ void gtk_setup_config_box(struct controlbox *b, bool midsession, void *win) s = ctrl_getset(b, "Window/Fonts", "font", "Fonts for displaying non-bold text"); ctrl_fontsel(s, "Font used for ordinary text", 'f', - HELPCTX(no_help), - conf_fontsel_handler, I(CONF_font)); + HELPCTX(no_help), + conf_fontsel_handler, I(CONF_font)); ctrl_fontsel(s, "Font used for wide (CJK) text", 'w', - HELPCTX(no_help), - conf_fontsel_handler, I(CONF_widefont)); + HELPCTX(no_help), + conf_fontsel_handler, I(CONF_widefont)); s = ctrl_getset(b, "Window/Fonts", "fontbold", "Fonts for displaying bolded text"); ctrl_fontsel(s, "Font used for bolded text", 'b', - HELPCTX(no_help), - conf_fontsel_handler, I(CONF_boldfont)); + HELPCTX(no_help), + conf_fontsel_handler, I(CONF_boldfont)); ctrl_fontsel(s, "Font used for bold wide text", 'i', - HELPCTX(no_help), - conf_fontsel_handler, I(CONF_wideboldfont)); + HELPCTX(no_help), + conf_fontsel_handler, I(CONF_wideboldfont)); ctrl_checkbox(s, "Use shadow bold instead of bold fonts", 'u', - HELPCTX(no_help), - conf_checkbox_handler, - I(CONF_shadowbold)); + HELPCTX(no_help), + conf_checkbox_handler, + I(CONF_shadowbold)); ctrl_text(s, "(Note that bold fonts or shadow bolding are only" - " used if you have not requested bolding to be done by" - " changing the text colour.)", + " used if you have not requested bolding to be done by" + " changing the text colour.)", HELPCTX(no_help)); ctrl_editbox(s, "Horizontal offset for shadow bold:", 'z', 20, - HELPCTX(no_help), conf_editbox_handler, + HELPCTX(no_help), conf_editbox_handler, I(CONF_shadowboldoffset), I(-1)); /* @@ -123,11 +123,11 @@ void gtk_setup_config_box(struct controlbox *b, bool midsession, void *win) * here's an override option in the Translation panel. */ s = ctrl_getset(b, "Window/Translation", "trans", - "Character set translation on received data"); + "Character set translation on received data"); ctrl_checkbox(s, "Override with UTF-8 if locale says so", 'l', - HELPCTX(translation_utf8_override), - conf_checkbox_handler, - I(CONF_utf8_override)); + HELPCTX(translation_utf8_override), + conf_checkbox_handler, + I(CONF_utf8_override)); #ifdef OSX_META_KEY_CONFIG /* @@ -136,13 +136,13 @@ void gtk_setup_config_box(struct controlbox *b, bool midsession, void *win) * key, or whether they should have their normal OS functions. */ s = ctrl_getset(b, "Terminal/Keyboard", "meta", - "Choose the Meta key:"); + "Choose the Meta key:"); ctrl_checkbox(s, "Option key acts as Meta", 'p', - HELPCTX(no_help), - conf_checkbox_handler, I(CONF_osx_option_meta)); + HELPCTX(no_help), + conf_checkbox_handler, I(CONF_osx_option_meta)); ctrl_checkbox(s, "Command key acts as Meta", 'm', - HELPCTX(no_help), - conf_checkbox_handler, I(CONF_osx_command_meta)); + HELPCTX(no_help), + conf_checkbox_handler, I(CONF_osx_command_meta)); #endif if (!midsession) { diff --git a/unix/gtkcols.c b/unix/gtkcols.c index bbc6e28a..35c02875 100644 --- a/unix/gtkcols.c +++ b/unix/gtkcols.c @@ -88,18 +88,18 @@ GType columns_get_type(void) if (!columns_type) { static const GTypeInfo columns_info = { sizeof(ColumnsClass), - NULL, - NULL, + NULL, + NULL, (GClassInitFunc) columns_class_init, - NULL, - NULL, + NULL, + NULL, sizeof(Columns), - 0, + 0, (GInstanceInitFunc)columns_init, }; columns_type = g_type_register_static(GTK_TYPE_CONTAINER, "Columns", - &columns_info, 0); + &columns_info, 0); } return columns_type; @@ -107,7 +107,7 @@ GType columns_get_type(void) #endif static gint (*columns_inherited_focus)(FOCUS_METHOD_SUPERCLASS *container, - GtkDirectionType direction); + GtkDirectionType direction); static void columns_class_init(ColumnsClass *klass) { @@ -153,7 +153,7 @@ static void columns_class_init(ColumnsClass *klass) /* Save the previous value of this method. */ if (!columns_inherited_focus) - columns_inherited_focus = FOCUS_METHOD_LOCATION->focus; + columns_inherited_focus = FOCUS_METHOD_LOCATION->focus; FOCUS_METHOD_LOCATION->focus = columns_focus; } @@ -230,7 +230,7 @@ static void columns_map(GtkWidget *widget) children && (child = children->data); children = children->next) { if (child->widget && - gtk_widget_get_visible(child->widget) && + gtk_widget_get_visible(child->widget) && !gtk_widget_get_mapped(child->widget)) gtk_widget_map(child->widget); } @@ -251,7 +251,7 @@ static void columns_unmap(GtkWidget *widget) children && (child = children->data); children = children->next) { if (child->widget && - gtk_widget_get_visible(child->widget) && + gtk_widget_get_visible(child->widget) && gtk_widget_get_mapped(child->widget)) gtk_widget_unmap(child->widget); } @@ -274,7 +274,7 @@ static void columns_draw(GtkWidget *widget, GdkRectangle *area) children && (child = children->data); children = children->next) { if (child->widget && - GTK_WIDGET_DRAWABLE(child->widget) && + GTK_WIDGET_DRAWABLE(child->widget) && gtk_widget_intersect(child->widget, area, &child_area)) gtk_widget_draw(child->widget, &child_area); } @@ -299,7 +299,7 @@ static gint columns_expose(GtkWidget *widget, GdkEventExpose *event) children && (child = children->data); children = children->next) { if (child->widget && - GTK_WIDGET_DRAWABLE(child->widget) && + GTK_WIDGET_DRAWABLE(child->widget) && GTK_WIDGET_NO_WINDOW(child->widget) && gtk_widget_intersect(child->widget, &event->area, &child_event.area)) @@ -401,8 +401,8 @@ static void columns_forall(GtkContainer *container, gboolean include_internals, * callback. */ next = children->next; - if (child->widget) - callback(child->widget, callback_data); + if (child->widget) + callback(child->widget, callback_data); } } @@ -550,7 +550,7 @@ void columns_taborder_last(Columns *cols, GtkWidget *widget) cols->taborder = g_list_remove_link(cols->taborder, children); g_list_free(children); - cols->taborder = g_list_append(cols->taborder, widget); + cols->taborder = g_list_append(cols->taborder, widget); break; } } @@ -571,52 +571,52 @@ static gint columns_focus(FOCUS_METHOD_SUPERCLASS *super, GtkDirectionType dir) cols = COLUMNS(super); if (!gtk_widget_is_drawable(GTK_WIDGET(cols)) || - !gtk_widget_is_sensitive(GTK_WIDGET(cols))) - return false; + !gtk_widget_is_sensitive(GTK_WIDGET(cols))) + return false; if (!gtk_widget_get_can_focus(GTK_WIDGET(cols)) && - (dir == GTK_DIR_TAB_FORWARD || dir == GTK_DIR_TAB_BACKWARD)) { + (dir == GTK_DIR_TAB_FORWARD || dir == GTK_DIR_TAB_BACKWARD)) { - focuschild = gtk_container_get_focus_child(GTK_CONTAINER(cols)); - gtk_container_set_focus_child(GTK_CONTAINER(cols), NULL); + focuschild = gtk_container_get_focus_child(GTK_CONTAINER(cols)); + gtk_container_set_focus_child(GTK_CONTAINER(cols), NULL); - if (dir == GTK_DIR_TAB_FORWARD) - pos = cols->taborder; - else - pos = g_list_last(cols->taborder); + if (dir == GTK_DIR_TAB_FORWARD) + pos = cols->taborder; + else + pos = g_list_last(cols->taborder); - while (pos) { - GtkWidget *child = pos->data; + while (pos) { + GtkWidget *child = pos->data; - if (focuschild) { - if (focuschild == child) { - focuschild = NULL; /* now we can start looking in here */ - if (gtk_widget_is_drawable(child) && - GTK_IS_CONTAINER(child) && - !gtk_widget_has_focus(child)) { - if (CHILD_FOCUS(child, dir)) - return true; - } - } - } else if (gtk_widget_is_drawable(child)) { - if (GTK_IS_CONTAINER(child)) { - if (CHILD_FOCUS(child, dir)) - return true; - } else if (gtk_widget_get_can_focus(child)) { - gtk_widget_grab_focus(child); - return true; - } - } + if (focuschild) { + if (focuschild == child) { + focuschild = NULL; /* now we can start looking in here */ + if (gtk_widget_is_drawable(child) && + GTK_IS_CONTAINER(child) && + !gtk_widget_has_focus(child)) { + if (CHILD_FOCUS(child, dir)) + return true; + } + } + } else if (gtk_widget_is_drawable(child)) { + if (GTK_IS_CONTAINER(child)) { + if (CHILD_FOCUS(child, dir)) + return true; + } else if (gtk_widget_get_can_focus(child)) { + gtk_widget_grab_focus(child); + return true; + } + } - if (dir == GTK_DIR_TAB_FORWARD) - pos = pos->next; - else - pos = pos->prev; - } + if (dir == GTK_DIR_TAB_FORWARD) + pos = pos->next; + else + pos = pos->prev; + } - return false; + return false; } else - return columns_inherited_focus(super, dir); + return columns_inherited_focus(super, dir); } /* @@ -650,19 +650,19 @@ static gint columns_compute_width(Columns *cols, widget_dim_fn_t get_width) children && (child = children->data); children = children->next) { - if (!child->widget) { - /* Column reconfiguration. */ - ncols = child->ncols; - percentages = child->percentages; - continue; - } + if (!child->widget) { + /* Column reconfiguration. */ + ncols = child->ncols; + percentages = child->percentages; + continue; + } /* Only take visible widgets into account. */ if (!gtk_widget_get_visible(child->widget)) continue; childwidth = get_width(child); - colspan = child->colspan ? child->colspan : ncols-child->colstart; + colspan = child->colspan ? child->colspan : ncols-child->colstart; assert(colspan > 0); #ifdef COLUMNS_WIDTH_DIAGNOSTICS @@ -753,41 +753,41 @@ static void columns_alloc_horiz(Columns *cols, gint ourwidth, children && (child = children->data); children = children->next) { - if (!child->widget) { - gint percent; + if (!child->widget) { + gint percent; - /* Column reconfiguration. */ - ncols = child->ncols; - colxpos = g_renew(gint, colxpos, ncols + 1); - colxpos[0] = 0; - percent = 0; - for (i = 0; i < ncols; i++) { - percent += child->percentages[i]; - colxpos[i+1] = (((ourwidth - 2*border) + cols->spacing) - * percent / 100); - } - continue; - } + /* Column reconfiguration. */ + ncols = child->ncols; + colxpos = g_renew(gint, colxpos, ncols + 1); + colxpos[0] = 0; + percent = 0; + for (i = 0; i < ncols; i++) { + percent += child->percentages[i]; + colxpos[i+1] = (((ourwidth - 2*border) + cols->spacing) + * percent / 100); + } + continue; + } /* Only take visible widgets into account. */ if (!gtk_widget_get_visible(child->widget)) continue; childwidth = get_width(child); - colspan = child->colspan ? child->colspan : ncols-child->colstart; + colspan = child->colspan ? child->colspan : ncols-child->colstart; /* * Starting x position is cols[colstart]. * Ending x position is cols[colstart+colspan] - spacing. - * - * Unless we're forcing left, in which case the width is - * exactly the requisition width. + * + * Unless we're forcing left, in which case the width is + * exactly the requisition width. */ child->x = colxpos[child->colstart]; - if (child->force_left) - child->w = childwidth; - else - child->w = (colxpos[child->colstart+colspan] - + if (child->force_left) + child->w = childwidth; + else + child->w = (colxpos[child->colstart+colspan] - colxpos[child->colstart] - cols->spacing); } @@ -810,18 +810,18 @@ static gint columns_compute_height(Columns *cols, widget_dim_fn_t get_height) children && (child = children->data); children = children->next) { - if (!child->widget) { - /* Column reconfiguration. */ - for (i = 1; i < ncols; i++) { - if (colypos[0] < colypos[i]) - colypos[0] = colypos[i]; - } - ncols = child->ncols; - colypos = g_renew(gint, colypos, ncols); - for (i = 1; i < ncols; i++) - colypos[i] = colypos[0]; - continue; - } + if (!child->widget) { + /* Column reconfiguration. */ + for (i = 1; i < ncols; i++) { + if (colypos[0] < colypos[i]) + colypos[0] = colypos[i]; + } + ncols = child->ncols; + colypos = g_renew(gint, colypos, ncols); + for (i = 1; i < ncols; i++) + colypos[i] = colypos[0]; + continue; + } /* Only take visible widgets into account. */ if (!gtk_widget_get_visible(child->widget)) @@ -833,7 +833,7 @@ static gint columns_compute_height(Columns *cols, widget_dim_fn_t get_height) if (childheight < childheight2) childheight = childheight2; } - colspan = child->colspan ? child->colspan : ncols-child->colstart; + colspan = child->colspan ? child->colspan : ncols-child->colstart; /* * To compute height: the widget's top will be positioned at @@ -883,18 +883,18 @@ static void columns_alloc_vert(Columns *cols, gint ourheight, for (children = cols->children; children && (child = children->data); children = children->next) { - if (!child->widget) { - /* Column reconfiguration. */ - for (i = 1; i < ncols; i++) { - if (colypos[0] < colypos[i]) - colypos[0] = colypos[i]; - } - ncols = child->ncols; - colypos = g_renew(gint, colypos, ncols); - for (i = 1; i < ncols; i++) - colypos[i] = colypos[0]; - continue; - } + if (!child->widget) { + /* Column reconfiguration. */ + for (i = 1; i < ncols; i++) { + if (colypos[0] < colypos[i]) + colypos[0] = colypos[i]; + } + ncols = child->ncols; + colypos = g_renew(gint, colypos, ncols); + for (i = 1; i < ncols; i++) + colypos[i] = colypos[0]; + continue; + } /* Only take visible widgets into account. */ if (!gtk_widget_get_visible(child->widget)) @@ -906,7 +906,7 @@ static void columns_alloc_vert(Columns *cols, gint ourheight, if (fakeheight < childheight2) fakeheight = childheight2; } - colspan = child->colspan ? child->colspan : ncols-child->colstart; + colspan = child->colspan ? child->colspan : ncols-child->colstart; /* * To compute height: the widget's top will be positioned @@ -932,7 +932,7 @@ static void columns_alloc_vert(Columns *cols, gint ourheight, } } - g_free(colypos); + g_free(colypos); } /* diff --git a/unix/gtkcols.h b/unix/gtkcols.h index 32653b8d..e589cf79 100644 --- a/unix/gtkcols.h +++ b/unix/gtkcols.h @@ -28,8 +28,8 @@ typedef struct ColumnsChild_tag ColumnsChild; struct Columns_tag { GtkContainer container; /* private after here */ - GList *children; /* this holds ColumnsChild structures */ - GList *taborder; /* this just holds GtkWidgets */ + GList *children; /* this holds ColumnsChild structures */ + GList *taborder; /* this just holds GtkWidgets */ gint spacing; }; diff --git a/unix/gtkcomm.c b/unix/gtkcomm.c index 265cdda3..fa52bfb4 100644 --- a/unix/gtkcomm.c +++ b/unix/gtkcomm.c @@ -152,7 +152,7 @@ static gint timer_trigger(gpointer data) * Destroy the timer we got here on. */ if (timer_id) { - g_source_remove(timer_id); + g_source_remove(timer_id); timer_id = 0; } @@ -163,13 +163,13 @@ static gint timer_trigger(gpointer data) * still needs to be done, we do it ourselves. */ if (run_timers(now, &next) && !timer_id) { - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; - timer_id = g_timeout_add(ticks, timer_trigger, LONG_TO_GPOINTER(next)); + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; + timer_id = g_timeout_add(ticks, timer_trigger, LONG_TO_GPOINTER(next)); } /* @@ -185,11 +185,11 @@ void timer_change_notify(unsigned long next) long ticks; if (timer_id) - g_source_remove(timer_id); + g_source_remove(timer_id); ticks = next - GETTICKCOUNT(); if (ticks <= 0) - ticks = 1; /* just in case */ + ticks = 1; /* just in case */ timer_id = g_timeout_add(ticks, timer_trigger, LONG_TO_GPOINTER(next)); } diff --git a/unix/gtkdlg.c b/unix/gtkdlg.c index fc72c0b8..b2f44242 100644 --- a/unix/gtkdlg.c +++ b/unix/gtkdlg.c @@ -28,7 +28,7 @@ #endif #ifdef TESTMODE -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #endif #include "storage.h" @@ -60,9 +60,9 @@ struct uctrl { GtkWidget *entry; /* for editbox, filesel, fontsel */ GtkWidget *button; /* for filesel, fontsel */ #if !GTK_CHECK_VERSION(2,4,0) - GtkWidget *list; /* for listbox (in GTK1), combobox (<=GTK2.3) */ - GtkWidget *menu; /* for optionmenu (==droplist) */ - GtkWidget *optmenu; /* also for optionmenu */ + GtkWidget *list; /* for listbox (in GTK1), combobox (<=GTK2.3) */ + GtkWidget *menu; /* for optionmenu (==droplist) */ + GtkWidget *optmenu; /* also for optionmenu */ #else GtkWidget *combo; /* for combo box (either editable or not) */ #endif @@ -70,7 +70,7 @@ struct uctrl { GtkWidget *treeview; /* for listbox (GTK2), droplist+combo (>=2.4) */ GtkListStore *listmodel; /* for all types of list box */ #endif - GtkWidget *text; /* for text */ + GtkWidget *text; /* for text */ GtkWidget *label; /* for dlg_label_change */ GtkAdjustment *adj; /* for the scrollbar in a list box */ struct selparam *sp; /* which switchable pane of the box we're in */ @@ -108,13 +108,13 @@ struct dlgparam { #define FLAG_UPDATING_COMBO_LIST 1 #define FLAG_UPDATING_LISTBOX 2 -enum { /* values for Shortcut.action */ - SHORTCUT_EMPTY, /* no shortcut on this key */ - SHORTCUT_TREE, /* focus a tree item */ - SHORTCUT_FOCUS, /* focus the supplied widget */ - SHORTCUT_UCTRL, /* do something sane with uctrl */ - SHORTCUT_UCTRL_UP, /* uctrl is a draglist, move Up */ - SHORTCUT_UCTRL_DOWN, /* uctrl is a draglist, move Down */ +enum { /* values for Shortcut.action */ + SHORTCUT_EMPTY, /* no shortcut on this key */ + SHORTCUT_TREE, /* focus a tree item */ + SHORTCUT_FOCUS, /* focus the supplied widget */ + SHORTCUT_UCTRL, /* do something sane with uctrl */ + SHORTCUT_UCTRL_UP, /* uctrl is a draglist, move Up */ + SHORTCUT_UCTRL_DOWN, /* uctrl is a draglist, move Down */ }; #if GTK_CHECK_VERSION(2,0,0) @@ -131,17 +131,17 @@ enum { static gboolean widget_focus(GtkWidget *widget, GdkEventFocus *event, gpointer data); static void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw, - int chr, int action, void *ptr); + int chr, int action, void *ptr); static void shortcut_highlight(GtkWidget *label, int chr); #if !GTK_CHECK_VERSION(2,0,0) static gboolean listitem_single_key(GtkWidget *item, GdkEventKey *event, - gpointer data); + gpointer data); static gboolean listitem_multi_key(GtkWidget *item, GdkEventKey *event, - gpointer data); + gpointer data); static gboolean listitem_button_press(GtkWidget *item, GdkEventButton *event, - gpointer data); + gpointer data); static gboolean listitem_button_release(GtkWidget *item, GdkEventButton *event, - gpointer data); + gpointer data); #endif #if !GTK_CHECK_VERSION(2,4,0) static void menuitem_activate(GtkMenuItem *item, gpointer data); @@ -161,9 +161,9 @@ static int uctrl_cmp_byctrl(void *av, void *bv) struct uctrl *a = (struct uctrl *)av; struct uctrl *b = (struct uctrl *)bv; if (a->ctrl < b->ctrl) - return -1; + return -1; else if (a->ctrl > b->ctrl) - return +1; + return +1; return 0; } @@ -172,9 +172,9 @@ static int uctrl_cmp_byctrl_find(void *av, void *bv) union control *a = (union control *)av; struct uctrl *b = (struct uctrl *)bv; if (a < b->ctrl) - return -1; + return -1; else if (a > b->ctrl) - return +1; + return +1; return 0; } @@ -183,9 +183,9 @@ static int uctrl_cmp_bywidget(void *av, void *bv) struct uctrl *a = (struct uctrl *)av; struct uctrl *b = (struct uctrl *)bv; if (a->toplevel < b->toplevel) - return -1; + return -1; else if (a->toplevel > b->toplevel) - return +1; + return +1; return 0; } @@ -194,9 +194,9 @@ static int uctrl_cmp_bywidget_find(void *av, void *bv) GtkWidget *a = (GtkWidget *)av; struct uctrl *b = (struct uctrl *)bv; if (a < b->toplevel) - return -1; + return -1; else if (a > b->toplevel) - return +1; + return +1; return 0; } @@ -219,12 +219,12 @@ static void dlg_cleanup(struct dlgparam *dp) { struct uctrl *uc; - freetree234(dp->byctrl); /* doesn't free the uctrls inside */ + freetree234(dp->byctrl); /* doesn't free the uctrls inside */ dp->byctrl = NULL; while ( (uc = index234(dp->bywidget, 0)) != NULL) { - del234(dp->bywidget, uc); - sfree(uc->buttons); - sfree(uc); + del234(dp->bywidget, uc); + sfree(uc->buttons); + sfree(uc); } freetree234(dp->bywidget); dp->bywidget = NULL; @@ -242,7 +242,7 @@ static void dlg_add_uctrl(struct dlgparam *dp, struct uctrl *uc) static struct uctrl *dlg_find_byctrl(struct dlgparam *dp, union control *ctrl) { if (!dp->byctrl) - return NULL; + return NULL; return find234(dp->byctrl, ctrl, uctrl_cmp_byctrl_find); } @@ -250,12 +250,12 @@ static struct uctrl *dlg_find_bywidget(struct dlgparam *dp, GtkWidget *w) { struct uctrl *ret = NULL; if (!dp->bywidget) - return NULL; + return NULL; do { - ret = find234(dp->bywidget, w, uctrl_cmp_bywidget_find); - if (ret) - return ret; - w = gtk_widget_get_parent(w); + ret = find234(dp->bywidget, w, uctrl_cmp_bywidget_find); + if (ret) + return ret; + w = gtk_widget_get_parent(w); } while (w); return ret; } @@ -284,9 +284,9 @@ int dlg_radiobutton_get(union control *ctrl, dlgparam *dp) assert(uc->ctrl->generic.type == CTRL_RADIO); assert(uc->buttons != NULL); for (i = 0; i < uc->nbuttons; i++) - if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(uc->buttons[i]))) - return i; - return 0; /* got to return something */ + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(uc->buttons[i]))) + return i; + return 0; /* got to return something */ } void dlg_checkbox_set(union control *ctrl, dlgparam *dp, bool checked) @@ -312,7 +312,7 @@ void dlg_editbox_set(union control *ctrl, dlgparam *dp, char const *text) #if GTK_CHECK_VERSION(2,4,0) if (uc->combo) - entry = gtk_bin_get_child(GTK_BIN(uc->combo)); + entry = gtk_bin_get_child(GTK_BIN(uc->combo)); else #endif entry = uc->entry; @@ -348,13 +348,13 @@ char *dlg_editbox_get(union control *ctrl, dlgparam *dp) #if GTK_CHECK_VERSION(2,4,0) if (uc->combo) { - return dupstr(gtk_entry_get_text - (GTK_ENTRY(gtk_bin_get_child(GTK_BIN(uc->combo))))); + return dupstr(gtk_entry_get_text + (GTK_ENTRY(gtk_bin_get_child(GTK_BIN(uc->combo))))); } #endif if (uc->entry) { - return dupstr(gtk_entry_get_text(GTK_ENTRY(uc->entry))); + return dupstr(gtk_entry_get_text(GTK_ENTRY(uc->entry))); } assert(!"We shouldn't get here"); @@ -375,24 +375,24 @@ void dlg_listbox_clear(union control *ctrl, dlgparam *dp) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu) { - gtk_container_foreach(GTK_CONTAINER(uc->menu), - container_remove_and_destroy, - GTK_CONTAINER(uc->menu)); - return; + gtk_container_foreach(GTK_CONTAINER(uc->menu), + container_remove_and_destroy, + GTK_CONTAINER(uc->menu)); + return; } if (uc->list) { - gtk_list_clear_items(GTK_LIST(uc->list), 0, -1); - return; + gtk_list_clear_items(GTK_LIST(uc->list), 0, -1); + return; } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->listmodel) { - gtk_list_store_clear(uc->listmodel); - return; + gtk_list_store_clear(uc->listmodel); + return; } #endif assert(!"We shouldn't get here"); @@ -403,30 +403,30 @@ void dlg_listbox_del(union control *ctrl, dlgparam *dp, int index) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu) { - gtk_container_remove - (GTK_CONTAINER(uc->menu), - g_list_nth_data(GTK_MENU_SHELL(uc->menu)->children, index)); - return; + gtk_container_remove + (GTK_CONTAINER(uc->menu), + g_list_nth_data(GTK_MENU_SHELL(uc->menu)->children, index)); + return; } if (uc->list) { - gtk_list_clear_items(GTK_LIST(uc->list), index, index+1); - return; + gtk_list_clear_items(GTK_LIST(uc->list), index, index+1); + return; } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->listmodel) { - GtkTreePath *path; - GtkTreeIter iter; - assert(uc->listmodel != NULL); - path = gtk_tree_path_new_from_indices(index, -1); - gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path); - gtk_list_store_remove(uc->listmodel, &iter); - gtk_tree_path_free(path); - return; + GtkTreePath *path; + GtkTreeIter iter; + assert(uc->listmodel != NULL); + path = gtk_tree_path_new_from_indices(index, -1); + gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path); + gtk_list_store_remove(uc->listmodel, &iter); + gtk_tree_path_free(path); + return; } #endif assert(!"We shouldn't get here"); @@ -445,12 +445,12 @@ void dlg_listbox_add(union control *ctrl, dlgparam *dp, char const *text) * IDs and expect to get meaningful results back. */ void dlg_listbox_addwithid(union control *ctrl, dlgparam *dp, - char const *text, int id) + char const *text, int id) { struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); /* * This routine is long and complicated in both GTK 1 and 2, @@ -460,86 +460,86 @@ void dlg_listbox_addwithid(union control *ctrl, dlgparam *dp, #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu) { - /* - * List item in a drop-down (but non-combo) list. Tabs are - * ignored; we just provide a standard menu item with the - * text. - */ - GtkWidget *menuitem = gtk_menu_item_new_with_label(text); + /* + * List item in a drop-down (but non-combo) list. Tabs are + * ignored; we just provide a standard menu item with the + * text. + */ + GtkWidget *menuitem = gtk_menu_item_new_with_label(text); - gtk_container_add(GTK_CONTAINER(uc->menu), menuitem); - gtk_widget_show(menuitem); + gtk_container_add(GTK_CONTAINER(uc->menu), menuitem); + gtk_widget_show(menuitem); g_object_set_data(G_OBJECT(menuitem), "user-data", GINT_TO_POINTER(id)); g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(menuitem_activate), dp); - goto done; + goto done; } if (uc->list && uc->entry) { - /* - * List item in a combo-box list, which means the sensible - * thing to do is make it a perfectly normal label. Hence - * tabs are disregarded. - */ - GtkWidget *listitem = gtk_list_item_new_with_label(text); + /* + * List item in a combo-box list, which means the sensible + * thing to do is make it a perfectly normal label. Hence + * tabs are disregarded. + */ + GtkWidget *listitem = gtk_list_item_new_with_label(text); - gtk_container_add(GTK_CONTAINER(uc->list), listitem); - gtk_widget_show(listitem); + gtk_container_add(GTK_CONTAINER(uc->list), listitem); + gtk_widget_show(listitem); g_object_set_data(G_OBJECT(listitem), "user-data", GINT_TO_POINTER(id)); - goto done; + goto done; } #endif #if !GTK_CHECK_VERSION(2,0,0) if (uc->list) { - /* - * List item in a non-combo-box list box. We make all of - * these Columns containing GtkLabels. This allows us to do - * the nasty force_left hack irrespective of whether there - * are tabs in the thing. - */ - GtkWidget *listitem = gtk_list_item_new(); - GtkWidget *cols = columns_new(10); - gint *percents; - int i, ncols; + /* + * List item in a non-combo-box list box. We make all of + * these Columns containing GtkLabels. This allows us to do + * the nasty force_left hack irrespective of whether there + * are tabs in the thing. + */ + GtkWidget *listitem = gtk_list_item_new(); + GtkWidget *cols = columns_new(10); + gint *percents; + int i, ncols; - /* Count the tabs in the text, and hence determine # of columns. */ - ncols = 1; - for (i = 0; text[i]; i++) - if (text[i] == '\t') - ncols++; + /* Count the tabs in the text, and hence determine # of columns. */ + ncols = 1; + for (i = 0; text[i]; i++) + if (text[i] == '\t') + ncols++; - assert(ncols <= - (uc->ctrl->listbox.ncols ? uc->ctrl->listbox.ncols : 1)); - percents = snewn(ncols, gint); - percents[ncols-1] = 100; - for (i = 0; i < ncols-1; i++) { - percents[i] = uc->ctrl->listbox.percentages[i]; - percents[ncols-1] -= percents[i]; - } - columns_set_cols(COLUMNS(cols), ncols, percents); - sfree(percents); + assert(ncols <= + (uc->ctrl->listbox.ncols ? uc->ctrl->listbox.ncols : 1)); + percents = snewn(ncols, gint); + percents[ncols-1] = 100; + for (i = 0; i < ncols-1; i++) { + percents[i] = uc->ctrl->listbox.percentages[i]; + percents[ncols-1] -= percents[i]; + } + columns_set_cols(COLUMNS(cols), ncols, percents); + sfree(percents); - for (i = 0; i < ncols; i++) { - int len = strcspn(text, "\t"); - char *dup = dupprintf("%.*s", len, text); - GtkWidget *label; + for (i = 0; i < ncols; i++) { + int len = strcspn(text, "\t"); + char *dup = dupprintf("%.*s", len, text); + GtkWidget *label; - text += len; - if (*text) text++; - label = gtk_label_new(dup); - sfree(dup); + text += len; + if (*text) text++; + label = gtk_label_new(dup); + sfree(dup); - columns_add(COLUMNS(cols), label, i, 1); - columns_force_left_align(COLUMNS(cols), label); - gtk_widget_show(label); - } - gtk_container_add(GTK_CONTAINER(listitem), cols); - gtk_widget_show(cols); - gtk_container_add(GTK_CONTAINER(uc->list), listitem); - gtk_widget_show(listitem); + columns_add(COLUMNS(cols), label, i, 1); + columns_force_left_align(COLUMNS(cols), label); + gtk_widget_show(label); + } + gtk_container_add(GTK_CONTAINER(listitem), cols); + gtk_widget_show(cols); + gtk_container_add(GTK_CONTAINER(uc->list), listitem); + gtk_widget_show(listitem); if (ctrl->listbox.multisel) { g_signal_connect(G_OBJECT(listitem), "key_press_event", @@ -556,35 +556,35 @@ void dlg_listbox_addwithid(union control *ctrl, dlgparam *dp, G_CALLBACK(listitem_button_release), dp); g_object_set_data(G_OBJECT(listitem), "user-data", GINT_TO_POINTER(id)); - goto done; + goto done; } #else if (uc->listmodel) { - GtkTreeIter iter; - int i, cols; + GtkTreeIter iter; + int i, cols; - dp->flags |= FLAG_UPDATING_LISTBOX;/* inhibit drag-list update */ - gtk_list_store_append(uc->listmodel, &iter); - dp->flags &= ~FLAG_UPDATING_LISTBOX; - gtk_list_store_set(uc->listmodel, &iter, 0, id, -1); + dp->flags |= FLAG_UPDATING_LISTBOX;/* inhibit drag-list update */ + gtk_list_store_append(uc->listmodel, &iter); + dp->flags &= ~FLAG_UPDATING_LISTBOX; + gtk_list_store_set(uc->listmodel, &iter, 0, id, -1); - /* - * Now go through text and divide it into columns at the tabs, - * as necessary. - */ - cols = (uc->ctrl->generic.type == CTRL_LISTBOX ? ctrl->listbox.ncols : 1); - cols = cols ? cols : 1; - for (i = 0; i < cols; i++) { - int collen = strcspn(text, "\t"); - char *tmpstr = snewn(collen+1, char); - memcpy(tmpstr, text, collen); - tmpstr[collen] = '\0'; - gtk_list_store_set(uc->listmodel, &iter, i+1, tmpstr, -1); - sfree(tmpstr); - text += collen; - if (*text) text++; - } - goto done; + /* + * Now go through text and divide it into columns at the tabs, + * as necessary. + */ + cols = (uc->ctrl->generic.type == CTRL_LISTBOX ? ctrl->listbox.ncols : 1); + cols = cols ? cols : 1; + for (i = 0; i < cols; i++) { + int collen = strcspn(text, "\t"); + char *tmpstr = snewn(collen+1, char); + memcpy(tmpstr, text, collen); + tmpstr[collen] = '\0'; + gtk_list_store_set(uc->listmodel, &iter, i+1, tmpstr, -1); + sfree(tmpstr); + text += collen; + if (*text) text++; + } + goto done; } #endif assert(!"We shouldn't get here"); @@ -597,37 +597,37 @@ int dlg_listbox_getid(union control *ctrl, dlgparam *dp, int index) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu || uc->list) { - GList *children; + GList *children; GObject *item; - children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : - uc->list)); + children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : + uc->list)); item = G_OBJECT(g_list_nth_data(children, index)); - g_list_free(children); + g_list_free(children); return GPOINTER_TO_INT(g_object_get_data(G_OBJECT(item), "user-data")); } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->listmodel) { - GtkTreePath *path; - GtkTreeIter iter; - int ret; + GtkTreePath *path; + GtkTreeIter iter; + int ret; - path = gtk_tree_path_new_from_indices(index, -1); - gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path); - gtk_tree_model_get(GTK_TREE_MODEL(uc->listmodel), &iter, 0, &ret, -1); - gtk_tree_path_free(path); + path = gtk_tree_path_new_from_indices(index, -1); + gtk_tree_model_get_iter(GTK_TREE_MODEL(uc->listmodel), &iter, path); + gtk_tree_model_get(GTK_TREE_MODEL(uc->listmodel), &iter, 0, &ret, -1); + gtk_tree_path_free(path); - return ret; + return ret; } #endif assert(!"We shouldn't get here"); - return -1; /* placate dataflow analysis */ + return -1; /* placate dataflow analysis */ } /* dlg_listbox_index returns <0 if no single element is selected. */ @@ -636,83 +636,83 @@ int dlg_listbox_index(union control *ctrl, dlgparam *dp) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu || uc->list) { - GList *children; - GtkWidget *item, *activeitem; - int i; - int selected = -1; + GList *children; + GtkWidget *item, *activeitem; + int i; + int selected = -1; - if (uc->menu) - activeitem = gtk_menu_get_active(GTK_MENU(uc->menu)); - else - activeitem = NULL; /* unnecessarily placate gcc */ + if (uc->menu) + activeitem = gtk_menu_get_active(GTK_MENU(uc->menu)); + else + activeitem = NULL; /* unnecessarily placate gcc */ - children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : - uc->list)); - for (i = 0; children!=NULL && (item = GTK_WIDGET(children->data))!=NULL; - i++, children = children->next) { - if (uc->menu ? activeitem == item : - GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED) { - if (selected == -1) - selected = i; - else - selected = -2; - } - } - g_list_free(children); - return selected < 0 ? -1 : selected; + children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : + uc->list)); + for (i = 0; children!=NULL && (item = GTK_WIDGET(children->data))!=NULL; + i++, children = children->next) { + if (uc->menu ? activeitem == item : + GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED) { + if (selected == -1) + selected = i; + else + selected = -2; + } + } + g_list_free(children); + return selected < 0 ? -1 : selected; } #else if (uc->combo) { - /* - * This API function already does the right thing in the - * case of no current selection. - */ - return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo)); + /* + * This API function already does the right thing in the + * case of no current selection. + */ + return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo)); } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->treeview) { - GtkTreeSelection *treesel; - GtkTreePath *path; - GtkTreeModel *model; - GList *sellist; - gint *indices; - int ret; + GtkTreeSelection *treesel; + GtkTreePath *path; + GtkTreeModel *model; + GList *sellist; + gint *indices; + int ret; - assert(uc->treeview != NULL); - treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); + assert(uc->treeview != NULL); + treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); - if (gtk_tree_selection_count_selected_rows(treesel) != 1) - return -1; + if (gtk_tree_selection_count_selected_rows(treesel) != 1) + return -1; - sellist = gtk_tree_selection_get_selected_rows(treesel, &model); + sellist = gtk_tree_selection_get_selected_rows(treesel, &model); - assert(sellist && sellist->data); - path = sellist->data; + assert(sellist && sellist->data); + path = sellist->data; - if (gtk_tree_path_get_depth(path) != 1) { - ret = -1; - } else { - indices = gtk_tree_path_get_indices(path); - if (!indices) { - ret = -1; - } else { - ret = indices[0]; - } - } + if (gtk_tree_path_get_depth(path) != 1) { + ret = -1; + } else { + indices = gtk_tree_path_get_indices(path); + if (!indices) { + ret = -1; + } else { + ret = indices[0]; + } + } - g_list_foreach(sellist, (GFunc)gtk_tree_path_free, NULL); - g_list_free(sellist); + g_list_foreach(sellist, (GFunc)gtk_tree_path_free, NULL); + g_list_free(sellist); - return ret; + return ret; } #endif assert(!"We shouldn't get here"); - return -1; /* placate dataflow analysis */ + return -1; /* placate dataflow analysis */ } bool dlg_listbox_issel(union control *ctrl, dlgparam *dp, int index) @@ -720,52 +720,52 @@ bool dlg_listbox_issel(union control *ctrl, dlgparam *dp, int index) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->menu || uc->list) { - GList *children; - GtkWidget *item, *activeitem; + GList *children; + GtkWidget *item, *activeitem; - assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); - assert(uc->menu != NULL || uc->list != NULL); + assert(uc->ctrl->generic.type == CTRL_EDITBOX || + uc->ctrl->generic.type == CTRL_LISTBOX); + assert(uc->menu != NULL || uc->list != NULL); - children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : - uc->list)); - item = GTK_WIDGET(g_list_nth_data(children, index)); - g_list_free(children); + children = gtk_container_children(GTK_CONTAINER(uc->menu ? uc->menu : + uc->list)); + item = GTK_WIDGET(g_list_nth_data(children, index)); + g_list_free(children); - if (uc->menu) { - activeitem = gtk_menu_get_active(GTK_MENU(uc->menu)); - return item == activeitem; - } else { - return GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED; - } + if (uc->menu) { + activeitem = gtk_menu_get_active(GTK_MENU(uc->menu)); + return item == activeitem; + } else { + return GTK_WIDGET_STATE(item) == GTK_STATE_SELECTED; + } } #else if (uc->combo) { - /* - * This API function already does the right thing in the - * case of no current selection. - */ - return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo)) == index; + /* + * This API function already does the right thing in the + * case of no current selection. + */ + return gtk_combo_box_get_active(GTK_COMBO_BOX(uc->combo)) == index; } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->treeview) { - GtkTreeSelection *treesel; - GtkTreePath *path; - bool ret; + GtkTreeSelection *treesel; + GtkTreePath *path; + bool ret; - assert(uc->treeview != NULL); - treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); + assert(uc->treeview != NULL); + treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); - path = gtk_tree_path_new_from_indices(index, -1); - ret = gtk_tree_selection_path_is_selected(treesel, path); - gtk_tree_path_free(path); + path = gtk_tree_path_new_from_indices(index, -1); + ret = gtk_tree_selection_path_is_selected(treesel, path); + gtk_tree_path_free(path); - return ret; + return ret; } #endif assert(!"We shouldn't get here"); @@ -777,19 +777,19 @@ void dlg_listbox_select(union control *ctrl, dlgparam *dp, int index) struct uctrl *uc = dlg_find_byctrl(dp, ctrl); assert(uc->ctrl->generic.type == CTRL_EDITBOX || - uc->ctrl->generic.type == CTRL_LISTBOX); + uc->ctrl->generic.type == CTRL_LISTBOX); #if !GTK_CHECK_VERSION(2,4,0) if (uc->optmenu) { - gtk_option_menu_set_history(GTK_OPTION_MENU(uc->optmenu), index); - return; - } + gtk_option_menu_set_history(GTK_OPTION_MENU(uc->optmenu), index); + return; + } if (uc->list) { int nitems; GList *items; gdouble newtop, newbot; - gtk_list_select_item(GTK_LIST(uc->list), index); + gtk_list_select_item(GTK_LIST(uc->list), index); /* * Scroll the list box if necessary to ensure the newly @@ -814,27 +814,27 @@ void dlg_listbox_select(union control *ctrl, dlgparam *dp, int index) if (modified) gtk_adjustment_value_changed(uc->adj); } - return; + return; } #else if (uc->combo) { - gtk_combo_box_set_active(GTK_COMBO_BOX(uc->combo), index); - return; + gtk_combo_box_set_active(GTK_COMBO_BOX(uc->combo), index); + return; } #endif #if GTK_CHECK_VERSION(2,0,0) if (uc->treeview) { - GtkTreeSelection *treesel; - GtkTreePath *path; + GtkTreeSelection *treesel; + GtkTreePath *path; - treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); + treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview)); - path = gtk_tree_path_new_from_indices(index, -1); - gtk_tree_selection_select_path(treesel, path); - gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(uc->treeview), - path, NULL, false, 0.0, 0.0); - gtk_tree_path_free(path); - return; + path = gtk_tree_path_new_from_indices(index, -1); + gtk_tree_selection_select_path(treesel, path); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(uc->treeview), + path, NULL, false, 0.0, 0.0); + gtk_tree_path_free(path); + return; } #endif assert(!"We shouldn't get here"); @@ -856,36 +856,36 @@ void dlg_label_change(union control *ctrl, dlgparam *dp, char const *text) switch (uc->ctrl->generic.type) { case CTRL_BUTTON: - gtk_label_set_text(GTK_LABEL(uc->toplevel), text); - shortcut_highlight(uc->toplevel, ctrl->button.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->toplevel), text); + shortcut_highlight(uc->toplevel, ctrl->button.shortcut); + break; case CTRL_CHECKBOX: - gtk_label_set_text(GTK_LABEL(uc->toplevel), text); - shortcut_highlight(uc->toplevel, ctrl->checkbox.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->toplevel), text); + shortcut_highlight(uc->toplevel, ctrl->checkbox.shortcut); + break; case CTRL_RADIO: - gtk_label_set_text(GTK_LABEL(uc->label), text); - shortcut_highlight(uc->label, ctrl->radio.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->label), text); + shortcut_highlight(uc->label, ctrl->radio.shortcut); + break; case CTRL_EDITBOX: - gtk_label_set_text(GTK_LABEL(uc->label), text); - shortcut_highlight(uc->label, ctrl->editbox.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->label), text); + shortcut_highlight(uc->label, ctrl->editbox.shortcut); + break; case CTRL_FILESELECT: - gtk_label_set_text(GTK_LABEL(uc->label), text); - shortcut_highlight(uc->label, ctrl->fileselect.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->label), text); + shortcut_highlight(uc->label, ctrl->fileselect.shortcut); + break; case CTRL_FONTSELECT: - gtk_label_set_text(GTK_LABEL(uc->label), text); - shortcut_highlight(uc->label, ctrl->fontselect.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->label), text); + shortcut_highlight(uc->label, ctrl->fontselect.shortcut); + break; case CTRL_LISTBOX: - gtk_label_set_text(GTK_LABEL(uc->label), text); - shortcut_highlight(uc->label, ctrl->listbox.shortcut); - break; + gtk_label_set_text(GTK_LABEL(uc->label), text); + shortcut_highlight(uc->label, ctrl->listbox.shortcut); + break; default: - assert(!"This shouldn't happen"); - break; + assert(!"This shouldn't happen"); + break; } } @@ -963,15 +963,15 @@ void dlg_set_focus(union control *ctrl, dlgparam *dp) case CTRL_FILESELECT: case CTRL_FONTSELECT: case CTRL_EDITBOX: - if (uc->entry) { - /* Anything containing an edit box gets that focused. */ - gtk_widget_grab_focus(uc->entry); - } + if (uc->entry) { + /* Anything containing an edit box gets that focused. */ + gtk_widget_grab_focus(uc->entry); + } #if GTK_CHECK_VERSION(2,4,0) - else if (uc->combo) { - /* Failing that, there'll be a combo box. */ - gtk_widget_grab_focus(uc->combo); - } + else if (uc->combo) { + /* Failing that, there'll be a combo box. */ + gtk_widget_grab_focus(uc->combo); + } #endif break; case CTRL_RADIO: @@ -992,31 +992,31 @@ void dlg_set_focus(union control *ctrl, dlgparam *dp) #if !GTK_CHECK_VERSION(2,4,0) if (uc->optmenu) { gtk_widget_grab_focus(uc->optmenu); - break; + break; } #else - if (uc->combo) { - gtk_widget_grab_focus(uc->combo); - break; - } + if (uc->combo) { + gtk_widget_grab_focus(uc->combo); + break; + } #endif #if !GTK_CHECK_VERSION(2,0,0) - if (uc->list) { - /* - * For GTK-1 style list boxes, we tell it to focus one - * of its children, which appears to do the Right - * Thing. - */ + if (uc->list) { + /* + * For GTK-1 style list boxes, we tell it to focus one + * of its children, which appears to do the Right + * Thing. + */ gtk_container_focus(GTK_CONTAINER(uc->list), GTK_DIR_TAB_FORWARD); - break; - } + break; + } #else - if (uc->treeview) { - gtk_widget_grab_focus(uc->treeview); - break; - } + if (uc->treeview) { + gtk_widget_grab_focus(uc->treeview); + break; + } #endif - assert(!"We shouldn't get here"); + assert(!"We shouldn't get here"); break; } } @@ -1090,17 +1090,17 @@ void dlg_refresh(union control *ctrl, dlgparam *dp) struct uctrl *uc; if (ctrl) { - if (ctrl->generic.handler != NULL) - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); + if (ctrl->generic.handler != NULL) + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); } else { - int i; + int i; - for (i = 0; (uc = index234(dp->byctrl, i)) != NULL; i++) { - assert(uc->ctrl != NULL); - if (uc->ctrl->generic.handler != NULL) - uc->ctrl->generic.handler(uc->ctrl, dp, - dp->data, EVENT_REFRESH); - } + for (i = 0; (uc = index234(dp->byctrl, i)) != NULL; i++) { + assert(uc->ctrl != NULL); + if (uc->ctrl->generic.handler != NULL) + uc->ctrl->generic.handler(uc->ctrl, dp, + dp->data, EVENT_REFRESH); + } } } @@ -1110,13 +1110,13 @@ void dlg_coloursel_start(union control *ctrl, dlgparam *dp, int r, int g, int b) #if GTK_CHECK_VERSION(3,0,0) GtkWidget *coloursel = - gtk_color_chooser_dialog_new("Select a colour", + gtk_color_chooser_dialog_new("Select a colour", GTK_WINDOW(dp->window)); gtk_color_chooser_set_use_alpha(GTK_COLOR_CHOOSER(coloursel), false); #else GtkWidget *okbutton, *cancelbutton; GtkWidget *coloursel = - gtk_color_selection_dialog_new("Select a colour"); + gtk_color_selection_dialog_new("Select a colour"); GtkColorSelectionDialog *ccs = GTK_COLOR_SELECTION_DIALOG(coloursel); GtkColorSelection *cs = GTK_COLOR_SELECTION (gtk_color_selection_dialog_get_color_selection(ccs)); @@ -1150,7 +1150,7 @@ void dlg_coloursel_start(union control *ctrl, dlgparam *dp, int r, int g, int b) cvals[0] = r / 255.0; cvals[1] = g / 255.0; cvals[2] = b / 255.0; - cvals[3] = 1.0; /* fully opaque! */ + cvals[3] = 1.0; /* fully opaque! */ gtk_color_selection_set_color(cs, cvals); } #endif @@ -1172,9 +1172,9 @@ void dlg_coloursel_start(union control *ctrl, dlgparam *dp, int r, int g, int b) cancelbutton = ccs->cancel_button; #endif g_object_set_data(G_OBJECT(okbutton), "user-data", - (gpointer)coloursel); + (gpointer)coloursel); g_object_set_data(G_OBJECT(cancelbutton), "user-data", - (gpointer)coloursel); + (gpointer)coloursel); g_signal_connect(G_OBJECT(okbutton), "clicked", G_CALLBACK(coloursel_ok), (gpointer)dp); g_signal_connect(G_OBJECT(cancelbutton), "clicked", @@ -1193,12 +1193,12 @@ bool dlg_coloursel_results(union control *ctrl, dlgparam *dp, int *r, int *g, int *b) { if (dp->coloursel_result.ok) { - *r = dp->coloursel_result.r; - *g = dp->coloursel_result.g; - *b = dp->coloursel_result.b; - return true; + *r = dp->coloursel_result.r; + *g = dp->coloursel_result.g; + *b = dp->coloursel_result.b; + return true; } else - return false; + return false; } /* ---------------------------------------------------------------------- @@ -1240,7 +1240,7 @@ static void button_toggled(GtkToggleButton *tb, gpointer data) } static gboolean editbox_key(GtkWidget *widget, GdkEventKey *event, - gpointer data) + gpointer data) { /* * GtkEntry has a nasty habit of eating the Return key, which @@ -1253,11 +1253,11 @@ static gboolean editbox_key(GtkWidget *widget, GdkEventKey *event, */ GtkWidget *parent = gtk_widget_get_parent(widget); if (event->keyval == GDK_KEY_Return && parent != NULL) { - gboolean return_val; + gboolean return_val; g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event"); - g_signal_emit_by_name(G_OBJECT(parent), "key_press_event", + g_signal_emit_by_name(G_OBJECT(parent), "key_press_event", event, &return_val); - return return_val; + return return_val; } return false; } @@ -1266,13 +1266,13 @@ static void editbox_changed(GtkEditable *ed, gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; if (!(dp->flags & FLAG_UPDATING_COMBO_LIST)) { - struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(ed)); - uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_VALCHANGE); + struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(ed)); + uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_VALCHANGE); } } static gboolean editbox_lostfocus(GtkWidget *ed, GdkEventFocus *event, - gpointer data) + gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(ed)); @@ -1287,7 +1287,7 @@ static gboolean editbox_lostfocus(GtkWidget *ed, GdkEventFocus *event, */ static gboolean listitem_key(GtkWidget *item, GdkEventKey *event, - gpointer data, bool multiple) + gpointer data, bool multiple) { GtkAdjustment *adj = GTK_ADJUSTMENT(data); @@ -1298,7 +1298,7 @@ static gboolean listitem_key(GtkWidget *item, GdkEventKey *event, /* * Up, Down, PgUp or PgDn have been pressed on a ListItem * in a list box. So, if the list box is single-selection: - * + * * - if the list item in question isn't already selected, * we simply select it. * - otherwise, we find the next one (or next @@ -1307,7 +1307,7 @@ static gboolean listitem_key(GtkWidget *item, GdkEventKey *event, * + in this case, we must also fiddle with the * scrollbar to ensure the newly selected item is * actually visible. - * + * * If it's multiple-selection, we do all of the above * except actually selecting anything, so we move the focus * and fiddle the scrollbar to follow it. @@ -1325,7 +1325,7 @@ static gboolean listitem_key(GtkWidget *item, GdkEventKey *event, event->keyval==GDK_Page_Up || event->keyval==GDK_KP_Page_Up) ? -1 : +1; int step = - (event->keyval==GDK_Page_Down || + (event->keyval==GDK_Page_Down || event->keyval==GDK_KP_Page_Down || event->keyval==GDK_Page_Up || event->keyval==GDK_KP_Page_Up) ? 2 : 1; @@ -1381,19 +1381,19 @@ static gboolean listitem_key(GtkWidget *item, GdkEventKey *event, } static gboolean listitem_single_key(GtkWidget *item, GdkEventKey *event, - gpointer data) + gpointer data) { return listitem_key(item, event, data, false); } static gboolean listitem_multi_key(GtkWidget *item, GdkEventKey *event, - gpointer data) + gpointer data) { return listitem_key(item, event, data, true); } static gboolean listitem_button_press(GtkWidget *item, GdkEventButton *event, - gpointer data) + gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(item)); @@ -1407,12 +1407,12 @@ static gboolean listitem_button_press(GtkWidget *item, GdkEventButton *event, } static gboolean listitem_button_release(GtkWidget *item, GdkEventButton *event, - gpointer data) + gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(item)); if (uc->nclicks>1) { - uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION); + uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION); return true; } return false; @@ -1433,10 +1433,10 @@ static void draglist_move(struct dlgparam *dp, struct uctrl *uc, int direction) GtkWidget *child; if ((index < 0) || - (index == 0 && direction < 0) || - (index == g_list_length(children)-1 && direction > 0)) { - gdk_display_beep(gdk_display_get_default()); - return; + (index == 0 && direction < 0) || + (index == g_list_length(children)-1 && direction > 0)) { + gdk_display_beep(gdk_display_get_default()); + return; } child = g_list_nth_data(children, index); @@ -1472,22 +1472,22 @@ static void draglist_down(GtkButton *button, gpointer data) */ static void listbox_doubleclick(GtkTreeView *treeview, GtkTreePath *path, - GtkTreeViewColumn *column, gpointer data) + GtkTreeViewColumn *column, gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(treeview)); if (uc) - uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION); + uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_ACTION); } static void listbox_selchange(GtkTreeSelection *treeselection, - gpointer data) + gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; GtkTreeView *tree = gtk_tree_selection_get_tree_view(treeselection); struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(tree)); if (uc) - uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE); + uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE); } struct draglist_valchange_ctx { @@ -1498,10 +1498,10 @@ struct draglist_valchange_ctx { static gboolean draglist_valchange(gpointer data) { struct draglist_valchange_ctx *ctx = - (struct draglist_valchange_ctx *)data; + (struct draglist_valchange_ctx *)data; ctx->uc->ctrl->generic.handler(ctx->uc->ctrl, ctx->dp, - ctx->dp->data, EVENT_VALCHANGE); + ctx->dp->data, EVENT_VALCHANGE); sfree(ctx); @@ -1509,39 +1509,39 @@ static gboolean draglist_valchange(gpointer data) } static void listbox_reorder(GtkTreeModel *treemodel, GtkTreePath *path, - GtkTreeIter *iter, gpointer data) + GtkTreeIter *iter, gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; gpointer tree; struct uctrl *uc; if (dp->flags & FLAG_UPDATING_LISTBOX) - return; /* not a user drag operation */ + return; /* not a user drag operation */ tree = g_object_get_data(G_OBJECT(treemodel), "user-data"); uc = dlg_find_bywidget(dp, GTK_WIDGET(tree)); if (uc) { - /* - * We should cause EVENT_VALCHANGE on the list box, now - * that its rows have been reordered. However, the GTK 2 - * docs say that at the point this signal is received the - * new row might not have actually been filled in yet. - * - * (So what smegging use is it then, eh? Don't suppose it - * occurred to you at any point that letting the - * application know _after_ the reordering was compelete - * might be helpful to someone?) - * - * To get round this, I schedule an idle function, which I - * hope won't be called until the main event loop is - * re-entered after the drag-and-drop handler has finished - * furtling with the list store. - */ - struct draglist_valchange_ctx *ctx = - snew(struct draglist_valchange_ctx); - ctx->uc = uc; - ctx->dp = dp; - g_idle_add(draglist_valchange, ctx); + /* + * We should cause EVENT_VALCHANGE on the list box, now + * that its rows have been reordered. However, the GTK 2 + * docs say that at the point this signal is received the + * new row might not have actually been filled in yet. + * + * (So what smegging use is it then, eh? Don't suppose it + * occurred to you at any point that letting the + * application know _after_ the reordering was compelete + * might be helpful to someone?) + * + * To get round this, I schedule an idle function, which I + * hope won't be called until the main event loop is + * re-entered after the drag-and-drop handler has finished + * furtling with the list store. + */ + struct draglist_valchange_ctx *ctx = + snew(struct draglist_valchange_ctx); + ctx->uc = uc; + ctx->dp = dp; + g_idle_add(draglist_valchange, ctx); } } @@ -1565,7 +1565,7 @@ static void droplist_selchange(GtkComboBox *combo, gpointer data) struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, GTK_WIDGET(combo)); if (uc) - uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE); + uc->ctrl->generic.handler(uc->ctrl, dp, dp->data, EVENT_SELCHANGE); } #endif /* !GTK_CHECK_VERSION(2,4,0) */ @@ -1590,7 +1590,7 @@ static void filesel_ok(GtkButton *button, gpointer data) gpointer filesel = g_object_get_data(G_OBJECT(button), "user-data"); struct uctrl *uc = g_object_get_data(G_OBJECT(filesel), "user-data"); const char *name = gtk_file_selection_get_filename - (GTK_FILE_SELECTION(filesel)); + (GTK_FILE_SELECTION(filesel)); gtk_entry_set_text(GTK_ENTRY(uc->entry), name); } #endif @@ -1604,7 +1604,7 @@ static void fontsel_ok(GtkButton *button, gpointer data) gpointer fontsel = g_object_get_data(G_OBJECT(button), "user-data"); struct uctrl *uc = g_object_get_data(G_OBJECT(fontsel), "user-data"); const char *name = gtk_font_selection_dialog_get_font_name - (GTK_FONT_SELECTION_DIALOG(fontsel)); + (GTK_FONT_SELECTION_DIALOG(fontsel)); gtk_entry_set_text(GTK_ENTRY(uc->entry), name); #else @@ -1705,18 +1705,18 @@ static void filefont_clicked(GtkButton *button, gpointer data) STANDARD_CANCEL_LABEL, GTK_RESPONSE_CANCEL, STANDARD_OPEN_LABEL, GTK_RESPONSE_ACCEPT, (const gchar *)NULL); - gtk_window_set_modal(GTK_WINDOW(filechoose), true); - g_object_set_data(G_OBJECT(filechoose), "user-data", (gpointer)uc); - g_signal_connect(G_OBJECT(filechoose), "response", + gtk_window_set_modal(GTK_WINDOW(filechoose), true); + g_object_set_data(G_OBJECT(filechoose), "user-data", (gpointer)uc); + g_signal_connect(G_OBJECT(filechoose), "response", G_CALLBACK(filechoose_response), (gpointer)dp); - gtk_widget_show(filechoose); + gtk_widget_show(filechoose); #else - GtkWidget *filesel = - gtk_file_selection_new(uc->ctrl->fileselect.title); - gtk_window_set_modal(GTK_WINDOW(filesel), true); + GtkWidget *filesel = + gtk_file_selection_new(uc->ctrl->fileselect.title); + gtk_window_set_modal(GTK_WINDOW(filesel), true); g_object_set_data (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "user-data", - (gpointer)filesel); + (gpointer)filesel); g_object_set_data(G_OBJECT(filesel), "user-data", (gpointer)uc); g_signal_connect (G_OBJECT(GTK_FILE_SELECTION(filesel)->ok_button), "clicked", @@ -1727,7 +1727,7 @@ static void filefont_clicked(GtkButton *button, gpointer data) g_signal_connect_swapped (G_OBJECT(GTK_FILE_SELECTION(filesel)->cancel_button), "clicked", G_CALLBACK(gtk_widget_destroy), (gpointer)filesel); - gtk_widget_show(filesel); + gtk_widget_show(filesel); #endif } @@ -1736,20 +1736,20 @@ static void filefont_clicked(GtkButton *button, gpointer data) #if !GTK_CHECK_VERSION(2,0,0) - /* - * Use the GTK 1 standard font selector. - */ + /* + * Use the GTK 1 standard font selector. + */ - gchar *spacings[] = { "c", "m", NULL }; - GtkWidget *fontsel = - gtk_font_selection_dialog_new("Select a font"); - gtk_window_set_modal(GTK_WINDOW(fontsel), true); - gtk_font_selection_dialog_set_filter - (GTK_FONT_SELECTION_DIALOG(fontsel), - GTK_FONT_FILTER_BASE, GTK_FONT_ALL, - NULL, NULL, NULL, NULL, spacings, NULL); - if (!gtk_font_selection_dialog_set_font_name - (GTK_FONT_SELECTION_DIALOG(fontsel), fontname)) { + gchar *spacings[] = { "c", "m", NULL }; + GtkWidget *fontsel = + gtk_font_selection_dialog_new("Select a font"); + gtk_window_set_modal(GTK_WINDOW(fontsel), true); + gtk_font_selection_dialog_set_filter + (GTK_FONT_SELECTION_DIALOG(fontsel), + GTK_FONT_FILTER_BASE, GTK_FONT_ALL, + NULL, NULL, NULL, NULL, spacings, NULL); + if (!gtk_font_selection_dialog_set_font_name + (GTK_FONT_SELECTION_DIALOG(fontsel), fontname)) { /* * If the font name wasn't found as it was, try opening * it and extracting its FONT property. This should @@ -1765,7 +1765,7 @@ static void filefont_clicked(GtkButton *button, gpointer data) assert(disp); /* this is GTK1! */ - gdk_font_ref(font); + gdk_font_ref(font); if (XGetFontProperty(xfs, fontprop, &ret)) { char *name = XGetAtomName(disp, (Atom)ret); if (name) @@ -1777,7 +1777,7 @@ static void filefont_clicked(GtkButton *button, gpointer data) } g_object_set_data (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button), - "user-data", (gpointer)fontsel); + "user-data", (gpointer)fontsel); g_object_set_data(G_OBJECT(fontsel), "user-data", (gpointer)uc); g_signal_connect (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button), @@ -1785,27 +1785,27 @@ static void filefont_clicked(GtkButton *button, gpointer data) g_signal_connect_swapped (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->ok_button), "clicked", G_CALLBACK(gtk_widget_destroy), - (gpointer)fontsel); + (gpointer)fontsel); g_signal_connect_swapped (G_OBJECT(GTK_FONT_SELECTION_DIALOG(fontsel)->cancel_button), "clicked", G_CALLBACK(gtk_widget_destroy), - (gpointer)fontsel); - gtk_widget_show(fontsel); + (gpointer)fontsel); + gtk_widget_show(fontsel); #else /* !GTK_CHECK_VERSION(2,0,0) */ - /* - * Use the unifontsel code provided in gtkfont.c. - */ + /* + * Use the unifontsel code provided in gtkfont.c. + */ - unifontsel *fontsel = unifontsel_new("Select a font"); + unifontsel *fontsel = unifontsel_new("Select a font"); + + gtk_window_set_modal(fontsel->window, true); + unifontsel_set_name(fontsel, fontname); - gtk_window_set_modal(fontsel->window, true); - unifontsel_set_name(fontsel, fontname); - g_object_set_data(G_OBJECT(fontsel->ok_button), "user-data", (gpointer)fontsel); - fontsel->user_data = uc; + fontsel->user_data = uc; g_signal_connect(G_OBJECT(fontsel->ok_button), "clicked", G_CALLBACK(fontsel_ok), (gpointer)dp); g_signal_connect_swapped(G_OBJECT(fontsel->ok_button), "clicked", @@ -1815,7 +1815,7 @@ static void filefont_clicked(GtkButton *button, gpointer data) G_CALLBACK(unifontsel_destroy), (gpointer)fontsel); - gtk_widget_show(GTK_WIDGET(fontsel->window)); + gtk_widget_show(GTK_WIDGET(fontsel->window)); #endif /* !GTK_CHECK_VERSION(2,0,0) */ @@ -1824,7 +1824,7 @@ static void filefont_clicked(GtkButton *button, gpointer data) #if !GTK_CHECK_VERSION(3,0,0) static void label_sizealloc(GtkWidget *widget, GtkAllocation *alloc, - gpointer data) + gpointer data) { struct dlgparam *dp = (struct dlgparam *)data; struct uctrl *uc = dlg_find_bywidget(dp, widget); @@ -1843,7 +1843,7 @@ static void label_sizealloc(GtkWidget *widget, GtkAllocation *alloc, * might be a GtkFrame containing a Columns; whatever it is, it's * definitely a GtkWidget and should probably be added to a * GtkVbox.) - * + * * `win' is required for setting the default button. If it is * non-NULL, all buttons created will be default-capable (so they * have extra space round them for the default highlight). @@ -1885,9 +1885,9 @@ GtkWidget *layout_ctrls( * and add them to the Columns. */ for (i = 0; i < s->ncontrols; i++) { - union control *ctrl = s->ctrls[i]; - struct uctrl *uc; - bool left = false; + union control *ctrl = s->ctrls[i]; + struct uctrl *uc; + bool left = false; GtkWidget *w = NULL; switch (ctrl->generic.type) { @@ -1900,42 +1900,42 @@ GtkWidget *layout_ctrls( } continue; /* no actual control created */ case CTRL_TABDELAY: - { - struct uctrl *uc = dlg_find_byctrl(dp, ctrl->tabdelay.ctrl); - if (uc) - columns_taborder_last(cols, uc->toplevel); - } + { + struct uctrl *uc = dlg_find_byctrl(dp, ctrl->tabdelay.ctrl); + if (uc) + columns_taborder_last(cols, uc->toplevel); + } continue; /* no actual control created */ - } + } - uc = snew(struct uctrl); + uc = snew(struct uctrl); uc->sp = sp; - uc->ctrl = ctrl; - uc->buttons = NULL; - uc->entry = NULL; + uc->ctrl = ctrl; + uc->buttons = NULL; + uc->entry = NULL; #if !GTK_CHECK_VERSION(2,4,0) - uc->list = uc->menu = uc->optmenu = NULL; + uc->list = uc->menu = uc->optmenu = NULL; #else - uc->combo = NULL; + uc->combo = NULL; #endif #if GTK_CHECK_VERSION(2,0,0) - uc->treeview = NULL; - uc->listmodel = NULL; + uc->treeview = NULL; + uc->listmodel = NULL; #endif - uc->button = uc->text = NULL; - uc->label = NULL; + uc->button = uc->text = NULL; + uc->label = NULL; uc->nclicks = 0; switch (ctrl->generic.type) { case CTRL_BUTTON: w = gtk_button_new_with_label(ctrl->generic.label); - if (win) { - gtk_widget_set_can_default(w, true); - if (ctrl->button.isdefault) - gtk_window_set_default(win, w); - if (ctrl->button.iscancel) - dp->cancelbutton = w; - } + if (win) { + gtk_widget_set_can_default(w, true); + if (ctrl->button.isdefault) + gtk_window_set_default(win, w); + if (ctrl->button.iscancel) + dp->cancelbutton = w; + } g_signal_connect(G_OBJECT(w), "clicked", G_CALLBACK(button_clicked), dp); g_signal_connect(G_OBJECT(w), "focus_in_event", @@ -1951,7 +1951,7 @@ GtkWidget *layout_ctrls( G_CALLBACK(widget_focus), dp); shortcut_add(scs, gtk_bin_get_child(GTK_BIN(w)), ctrl->checkbox.shortcut, SHORTCUT_UCTRL, uc); - left = true; + left = true; break; case CTRL_RADIO: /* @@ -1966,11 +1966,11 @@ GtkWidget *layout_ctrls( if (ctrl->generic.label) { GtkWidget *label = gtk_label_new(ctrl->generic.label); columns_add(COLUMNS(w), label, 0, 1); - columns_force_left_align(COLUMNS(w), label); + columns_force_left_align(COLUMNS(w), label); gtk_widget_show(label); - shortcut_add(scs, label, ctrl->radio.shortcut, - SHORTCUT_UCTRL, uc); - uc->label = label; + shortcut_add(scs, label, ctrl->radio.shortcut, + SHORTCUT_UCTRL, uc); + uc->label = label; } percentages = g_new(gint, ctrl->radio.ncolumns); for (i = 0; i < ctrl->radio.ncolumns; i++) { @@ -1983,8 +1983,8 @@ GtkWidget *layout_ctrls( g_free(percentages); group = NULL; - uc->nbuttons = ctrl->radio.nbuttons; - uc->buttons = snewn(uc->nbuttons, GtkWidget *); + uc->nbuttons = ctrl->radio.nbuttons; + uc->buttons = snewn(uc->nbuttons, GtkWidget *); for (i = 0; i < ctrl->radio.nbuttons; i++) { GtkWidget *b; @@ -1992,63 +1992,63 @@ GtkWidget *layout_ctrls( b = (gtk_radio_button_new_with_label (group, ctrl->radio.buttons[i])); - uc->buttons[i] = b; + uc->buttons[i] = b; group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(b)); colstart = i % ctrl->radio.ncolumns; columns_add(COLUMNS(w), b, colstart, (i == ctrl->radio.nbuttons-1 ? ctrl->radio.ncolumns - colstart : 1)); - columns_force_left_align(COLUMNS(w), b); + columns_force_left_align(COLUMNS(w), b); gtk_widget_show(b); g_signal_connect(G_OBJECT(b), "toggled", G_CALLBACK(button_toggled), dp); g_signal_connect(G_OBJECT(b), "focus_in_event", G_CALLBACK(widget_focus), dp); - if (ctrl->radio.shortcuts) { - shortcut_add(scs, gtk_bin_get_child(GTK_BIN(b)), - ctrl->radio.shortcuts[i], - SHORTCUT_UCTRL, uc); - } + if (ctrl->radio.shortcuts) { + shortcut_add(scs, gtk_bin_get_child(GTK_BIN(b)), + ctrl->radio.shortcuts[i], + SHORTCUT_UCTRL, uc); + } } } break; case CTRL_EDITBOX: - { - GtkWidget *signalobject; + { + GtkWidget *signalobject; - if (ctrl->editbox.has_list) { + if (ctrl->editbox.has_list) { #if !GTK_CHECK_VERSION(2,4,0) - /* - * GTK 1 combo box. - */ - w = gtk_combo_new(); - gtk_combo_set_value_in_list(GTK_COMBO(w), false, true); - uc->entry = GTK_COMBO(w)->entry; - uc->list = GTK_COMBO(w)->list; - signalobject = uc->entry; + /* + * GTK 1 combo box. + */ + w = gtk_combo_new(); + gtk_combo_set_value_in_list(GTK_COMBO(w), false, true); + uc->entry = GTK_COMBO(w)->entry; + uc->list = GTK_COMBO(w)->list; + signalobject = uc->entry; #else - /* - * GTK 2 combo box. - */ - uc->listmodel = gtk_list_store_new(2, G_TYPE_INT, - G_TYPE_STRING); - w = gtk_combo_box_new_with_model_and_entry - (GTK_TREE_MODEL(uc->listmodel)); + /* + * GTK 2 combo box. + */ + uc->listmodel = gtk_list_store_new(2, G_TYPE_INT, + G_TYPE_STRING); + w = gtk_combo_box_new_with_model_and_entry + (GTK_TREE_MODEL(uc->listmodel)); g_object_set(G_OBJECT(w), "entry-text-column", 1, (const char *)NULL); - /* We cannot support password combo boxes. */ - assert(!ctrl->editbox.password); - uc->combo = w; - signalobject = uc->combo; + /* We cannot support password combo boxes. */ + assert(!ctrl->editbox.password); + uc->combo = w; + signalobject = uc->combo; #endif - } else { - w = gtk_entry_new(); - if (ctrl->editbox.password) - gtk_entry_set_visibility(GTK_ENTRY(w), false); - uc->entry = w; - signalobject = w; - } - uc->entrysig = + } else { + w = gtk_entry_new(); + if (ctrl->editbox.password) + gtk_entry_set_visibility(GTK_ENTRY(w), false); + uc->entry = w; + signalobject = w; + } + uc->entrysig = g_signal_connect(G_OBJECT(signalobject), "changed", G_CALLBACK(editbox_changed), dp); g_signal_connect(G_OBJECT(signalobject), "key_press_event", @@ -2061,12 +2061,12 @@ GtkWidget *layout_ctrls( G_CALLBACK(editbox_lostfocus), dp); #if !GTK_CHECK_VERSION(3,0,0) - /* - * Edit boxes, for some strange reason, have a minimum - * width of 150 in GTK 1.2. We don't want this - we'd - * rather the edit boxes acquired their natural width - * from the column layout of the rest of the box. - */ + /* + * Edit boxes, for some strange reason, have a minimum + * width of 150 in GTK 1.2. We don't want this - we'd + * rather the edit boxes acquired their natural width + * from the column layout of the rest of the box. + */ { GtkRequisition req; gtk_widget_size_request(w, &req); @@ -2081,37 +2081,37 @@ GtkWidget *layout_ctrls( gtk_entry_set_width_chars(GTK_ENTRY(w), 1); #endif - if (ctrl->generic.label) { - GtkWidget *label, *container; + if (ctrl->generic.label) { + GtkWidget *label, *container; - label = gtk_label_new(ctrl->generic.label); + label = gtk_label_new(ctrl->generic.label); - shortcut_add(scs, label, ctrl->editbox.shortcut, - SHORTCUT_FOCUS, uc->entry); + shortcut_add(scs, label, ctrl->editbox.shortcut, + SHORTCUT_FOCUS, uc->entry); - container = columns_new(4); - if (ctrl->editbox.percentwidth == 100) { - columns_add(COLUMNS(container), label, 0, 1); - columns_force_left_align(COLUMNS(container), label); - columns_add(COLUMNS(container), w, 0, 1); - } else { - gint percentages[2]; - percentages[1] = ctrl->editbox.percentwidth; - percentages[0] = 100 - ctrl->editbox.percentwidth; - columns_set_cols(COLUMNS(container), 2, percentages); - columns_add(COLUMNS(container), label, 0, 1); - columns_force_left_align(COLUMNS(container), label); - columns_add(COLUMNS(container), w, 1, 1); + container = columns_new(4); + if (ctrl->editbox.percentwidth == 100) { + columns_add(COLUMNS(container), label, 0, 1); + columns_force_left_align(COLUMNS(container), label); + columns_add(COLUMNS(container), w, 0, 1); + } else { + gint percentages[2]; + percentages[1] = ctrl->editbox.percentwidth; + percentages[0] = 100 - ctrl->editbox.percentwidth; + columns_set_cols(COLUMNS(container), 2, percentages); + columns_add(COLUMNS(container), label, 0, 1); + columns_force_left_align(COLUMNS(container), label); + columns_add(COLUMNS(container), w, 1, 1); columns_force_same_height(COLUMNS(container), label, w); - } - gtk_widget_show(label); - gtk_widget_show(w); + } + gtk_widget_show(label); + gtk_widget_show(w); - w = container; - uc->label = label; - } - } + w = container; + uc->label = label; + } + } break; case CTRL_FILESELECT: case CTRL_FONTSELECT: @@ -2128,14 +2128,14 @@ GtkWidget *layout_ctrls( if (ctrl->generic.label) { ww = gtk_label_new(ctrl->generic.label); columns_add(COLUMNS(w), ww, 0, 2); - columns_force_left_align(COLUMNS(w), ww); + columns_force_left_align(COLUMNS(w), ww); gtk_widget_show(ww); - shortcut_add(scs, ww, - (ctrl->generic.type == CTRL_FILESELECT ? - ctrl->fileselect.shortcut : - ctrl->fontselect.shortcut), - SHORTCUT_UCTRL, uc); - uc->label = ww; + shortcut_add(scs, ww, + (ctrl->generic.type == CTRL_FILESELECT ? + ctrl->fileselect.shortcut : + ctrl->fontselect.shortcut), + SHORTCUT_UCTRL, uc); + uc->label = ww; } uc->entry = ww = gtk_entry_new(); @@ -2159,7 +2159,7 @@ GtkWidget *layout_ctrls( g_signal_connect(G_OBJECT(uc->entry), "key_press_event", G_CALLBACK(editbox_key), dp); - uc->entrysig = + uc->entrysig = g_signal_connect(G_OBJECT(uc->entry), "changed", G_CALLBACK(editbox_changed), dp); g_signal_connect(G_OBJECT(uc->entry), "focus_in_event", @@ -2173,89 +2173,89 @@ GtkWidget *layout_ctrls( case CTRL_LISTBOX: #if GTK_CHECK_VERSION(2,0,0) - /* - * First construct the list data store, with the right - * number of columns. - */ + /* + * First construct the list data store, with the right + * number of columns. + */ # if !GTK_CHECK_VERSION(2,4,0) - /* (For GTK 2.0 to 2.3, we do this for full listboxes only, - * because combo boxes are still done the old GTK1 way.) */ - if (ctrl->listbox.height > 0) + /* (For GTK 2.0 to 2.3, we do this for full listboxes only, + * because combo boxes are still done the old GTK1 way.) */ + if (ctrl->listbox.height > 0) # endif - { - GType *types; - int i; - int cols; + { + GType *types; + int i; + int cols; - cols = ctrl->listbox.ncols; - cols = cols ? cols : 1; - types = snewn(1 + cols, GType); + cols = ctrl->listbox.ncols; + cols = cols ? cols : 1; + types = snewn(1 + cols, GType); - types[0] = G_TYPE_INT; - for (i = 0; i < cols; i++) - types[i+1] = G_TYPE_STRING; + types[0] = G_TYPE_INT; + for (i = 0; i < cols; i++) + types[i+1] = G_TYPE_STRING; - uc->listmodel = gtk_list_store_newv(1 + cols, types); + uc->listmodel = gtk_list_store_newv(1 + cols, types); - sfree(types); - } + sfree(types); + } #endif - /* - * See if it's a drop-down list (non-editable combo - * box). - */ - if (ctrl->listbox.height == 0) { + /* + * See if it's a drop-down list (non-editable combo + * box). + */ + if (ctrl->listbox.height == 0) { #if !GTK_CHECK_VERSION(2,4,0) - /* - * GTK1 and early-GTK2 option-menu style of - * drop-down list. - */ + /* + * GTK1 and early-GTK2 option-menu style of + * drop-down list. + */ uc->optmenu = w = gtk_option_menu_new(); - uc->menu = gtk_menu_new(); - gtk_option_menu_set_menu(GTK_OPTION_MENU(w), uc->menu); + uc->menu = gtk_menu_new(); + gtk_option_menu_set_menu(GTK_OPTION_MENU(w), uc->menu); g_object_set_data(G_OBJECT(uc->menu), "user-data", (gpointer)uc->optmenu); g_signal_connect(G_OBJECT(uc->optmenu), "focus_in_event", G_CALLBACK(widget_focus), dp); #else - /* - * Late-GTK2 style using a GtkComboBox. - */ - GtkCellRenderer *cr; + /* + * Late-GTK2 style using a GtkComboBox. + */ + GtkCellRenderer *cr; - /* - * Create a non-editable GtkComboBox (that is, not - * its subclass GtkComboBoxEntry). - */ - w = gtk_combo_box_new_with_model - (GTK_TREE_MODEL(uc->listmodel)); - uc->combo = w; + /* + * Create a non-editable GtkComboBox (that is, not + * its subclass GtkComboBoxEntry). + */ + w = gtk_combo_box_new_with_model + (GTK_TREE_MODEL(uc->listmodel)); + uc->combo = w; - /* - * Tell it how to render a list item (i.e. which - * column to look at in the list model). - */ - cr = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(w), cr, true); - gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(w), cr, - "text", 1, NULL); + /* + * Tell it how to render a list item (i.e. which + * column to look at in the list model). + */ + cr = gtk_cell_renderer_text_new(); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(w), cr, true); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(w), cr, + "text", 1, NULL); - /* - * And tell it to notify us when the selection - * changes. - */ - g_signal_connect(G_OBJECT(w), "changed", - G_CALLBACK(droplist_selchange), dp); + /* + * And tell it to notify us when the selection + * changes. + */ + g_signal_connect(G_OBJECT(w), "changed", + G_CALLBACK(droplist_selchange), dp); g_signal_connect(G_OBJECT(w), "focus_in_event", G_CALLBACK(widget_focus), dp); #endif } else { #if !GTK_CHECK_VERSION(2,0,0) - /* - * GTK1-style full list box. - */ + /* + * GTK1-style full list box. + */ uc->list = gtk_list_new(); if (ctrl->listbox.multisel == 2) { gtk_list_set_selection_mode(GTK_LIST(uc->list), @@ -2285,7 +2285,7 @@ GtkWidget *layout_ctrls( /* * Adjust the height of the scrolled window to the * minimum given by the height parameter. - * + * * This piece of guesswork is a horrid hack based * on looking inside the GTK 1.2 sources * (specifically gtkviewport.c, which appears to be @@ -2294,13 +2294,13 @@ GtkWidget *layout_ctrls( * do this in a way which isn't at risk from GTK * upgrades, I'd be grateful. */ - { - int edge; - edge = GTK_WIDGET(uc->list)->style->klass->ythickness; + { + int edge; + edge = GTK_WIDGET(uc->list)->style->klass->ythickness; gtk_widget_set_size_request(w, 10, 2*edge + (ctrl->listbox.height * - get_listitemheight(w))); - } + get_listitemheight(w))); + } if (ctrl->listbox.draglist) { /* @@ -2335,53 +2335,53 @@ GtkWidget *layout_ctrls( w = cols; } #else - /* - * GTK2 treeview-based full list box. - */ - GtkTreeSelection *sel; + /* + * GTK2 treeview-based full list box. + */ + GtkTreeSelection *sel; - /* - * Create the list box itself, its columns, and - * its containing scrolled window. - */ - w = gtk_tree_view_new_with_model - (GTK_TREE_MODEL(uc->listmodel)); - g_object_set_data(G_OBJECT(uc->listmodel), "user-data", - (gpointer)w); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), false); - sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(w)); - gtk_tree_selection_set_mode - (sel, ctrl->listbox.multisel ? GTK_SELECTION_MULTIPLE : - GTK_SELECTION_SINGLE); - uc->treeview = w; + /* + * Create the list box itself, its columns, and + * its containing scrolled window. + */ + w = gtk_tree_view_new_with_model + (GTK_TREE_MODEL(uc->listmodel)); + g_object_set_data(G_OBJECT(uc->listmodel), "user-data", + (gpointer)w); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), false); + sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(w)); + gtk_tree_selection_set_mode + (sel, ctrl->listbox.multisel ? GTK_SELECTION_MULTIPLE : + GTK_SELECTION_SINGLE); + uc->treeview = w; g_signal_connect(G_OBJECT(w), "row-activated", G_CALLBACK(listbox_doubleclick), dp); g_signal_connect(G_OBJECT(w), "focus_in_event", G_CALLBACK(widget_focus), dp); - g_signal_connect(G_OBJECT(sel), "changed", - G_CALLBACK(listbox_selchange), dp); + g_signal_connect(G_OBJECT(sel), "changed", + G_CALLBACK(listbox_selchange), dp); - if (ctrl->listbox.draglist) { - gtk_tree_view_set_reorderable(GTK_TREE_VIEW(w), true); - g_signal_connect(G_OBJECT(uc->listmodel), "row-inserted", - G_CALLBACK(listbox_reorder), dp); - } + if (ctrl->listbox.draglist) { + gtk_tree_view_set_reorderable(GTK_TREE_VIEW(w), true); + g_signal_connect(G_OBJECT(uc->listmodel), "row-inserted", + G_CALLBACK(listbox_reorder), dp); + } - { - int i; - int cols; + { + int i; + int cols; - cols = ctrl->listbox.ncols; - cols = cols ? cols : 1; - for (i = 0; i < cols; i++) { - GtkTreeViewColumn *column; + cols = ctrl->listbox.ncols; + cols = cols ? cols : 1; + for (i = 0; i < cols; i++) { + GtkTreeViewColumn *column; GtkCellRenderer *cellrend; - /* - * It appears that GTK 2 doesn't leave us any - * particularly sensible way to honour the - * "percentages" specification in the ctrl - * structure. - */ + /* + * It appears that GTK 2 doesn't leave us any + * particularly sensible way to honour the + * "percentages" specification in the ctrl + * structure. + */ cellrend = gtk_cell_renderer_text_new(); if (!ctrl->listbox.hscroll) { g_object_set(G_OBJECT(cellrend), @@ -2389,98 +2389,98 @@ GtkWidget *layout_ctrls( "ellipsize-set", true, (const char *)NULL); } - column = gtk_tree_view_column_new_with_attributes - ("heading", cellrend, "text", i+1, (char *)NULL); - gtk_tree_view_column_set_sizing - (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY); - gtk_tree_view_append_column(GTK_TREE_VIEW(w), column); - } - } + column = gtk_tree_view_column_new_with_attributes + ("heading", cellrend, "text", i+1, (char *)NULL); + gtk_tree_view_column_set_sizing + (column, GTK_TREE_VIEW_COLUMN_GROW_ONLY); + gtk_tree_view_append_column(GTK_TREE_VIEW(w), column); + } + } - { - GtkWidget *scroll; + { + GtkWidget *scroll; - scroll = gtk_scrolled_window_new(NULL, NULL); - gtk_scrolled_window_set_shadow_type - (GTK_SCROLLED_WINDOW(scroll), GTK_SHADOW_IN); - gtk_widget_show(w); - gtk_container_add(GTK_CONTAINER(scroll), w); - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), - GTK_POLICY_AUTOMATIC, - GTK_POLICY_ALWAYS); - gtk_widget_set_size_request - (scroll, -1, - ctrl->listbox.height * get_listitemheight(w)); + scroll = gtk_scrolled_window_new(NULL, NULL); + gtk_scrolled_window_set_shadow_type + (GTK_SCROLLED_WINDOW(scroll), GTK_SHADOW_IN); + gtk_widget_show(w); + gtk_container_add(GTK_CONTAINER(scroll), w); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), + GTK_POLICY_AUTOMATIC, + GTK_POLICY_ALWAYS); + gtk_widget_set_size_request + (scroll, -1, + ctrl->listbox.height * get_listitemheight(w)); - w = scroll; - } + w = scroll; + } #endif } - if (ctrl->generic.label) { - GtkWidget *label, *container; + if (ctrl->generic.label) { + GtkWidget *label, *container; - label = gtk_label_new(ctrl->generic.label); + label = gtk_label_new(ctrl->generic.label); #if GTK_CHECK_VERSION(3,0,0) gtk_label_set_width_chars(GTK_LABEL(label), 3); #endif - shortcut_add(scs, label, ctrl->listbox.shortcut, - SHORTCUT_UCTRL, uc); + shortcut_add(scs, label, ctrl->listbox.shortcut, + SHORTCUT_UCTRL, uc); - container = columns_new(4); - if (ctrl->listbox.percentwidth == 100) { - columns_add(COLUMNS(container), label, 0, 1); - columns_force_left_align(COLUMNS(container), label); - columns_add(COLUMNS(container), w, 0, 1); - } else { - gint percentages[2]; - percentages[1] = ctrl->listbox.percentwidth; - percentages[0] = 100 - ctrl->listbox.percentwidth; - columns_set_cols(COLUMNS(container), 2, percentages); - columns_add(COLUMNS(container), label, 0, 1); - columns_force_left_align(COLUMNS(container), label); - columns_add(COLUMNS(container), w, 1, 1); + container = columns_new(4); + if (ctrl->listbox.percentwidth == 100) { + columns_add(COLUMNS(container), label, 0, 1); + columns_force_left_align(COLUMNS(container), label); + columns_add(COLUMNS(container), w, 0, 1); + } else { + gint percentages[2]; + percentages[1] = ctrl->listbox.percentwidth; + percentages[0] = 100 - ctrl->listbox.percentwidth; + columns_set_cols(COLUMNS(container), 2, percentages); + columns_add(COLUMNS(container), label, 0, 1); + columns_force_left_align(COLUMNS(container), label); + columns_add(COLUMNS(container), w, 1, 1); columns_force_same_height(COLUMNS(container), label, w); - } - gtk_widget_show(label); - gtk_widget_show(w); + } + gtk_widget_show(label); + gtk_widget_show(w); - w = container; - uc->label = label; - } + w = container; + uc->label = label; + } - break; + break; case CTRL_TEXT: #if !GTK_CHECK_VERSION(3,0,0) - /* - * Wrapping text widgets don't sit well with the GTK2 - * layout model, in which widgets state a minimum size - * and the whole window then adjusts to the smallest - * size it can sensibly take given its contents. A - * wrapping text widget _has_ no clear minimum size; - * instead it has a range of possibilities. It can be - * one line deep but 2000 wide, or two lines deep and - * 1000 pixels, or three by 867, or four by 500 and so - * on. It can be as short as you like provided you - * don't mind it being wide, or as narrow as you like - * provided you don't mind it being tall. - * - * Therefore, it fits very badly into the layout model. - * Hence the only thing to do is pick a width and let - * it choose its own number of lines. To do this I'm - * going to cheat a little. All new wrapping text - * widgets will be created with a minimal text content - * "X"; then, after the rest of the dialog box is set - * up and its size calculated, the text widgets will be - * told their width and given their real text, which - * will cause the size to be recomputed in the y - * direction (because many of them will expand to more - * than one line). - */ + /* + * Wrapping text widgets don't sit well with the GTK2 + * layout model, in which widgets state a minimum size + * and the whole window then adjusts to the smallest + * size it can sensibly take given its contents. A + * wrapping text widget _has_ no clear minimum size; + * instead it has a range of possibilities. It can be + * one line deep but 2000 wide, or two lines deep and + * 1000 pixels, or three by 867, or four by 500 and so + * on. It can be as short as you like provided you + * don't mind it being wide, or as narrow as you like + * provided you don't mind it being tall. + * + * Therefore, it fits very badly into the layout model. + * Hence the only thing to do is pick a width and let + * it choose its own number of lines. To do this I'm + * going to cheat a little. All new wrapping text + * widgets will be created with a minimal text content + * "X"; then, after the rest of the dialog box is set + * up and its size calculated, the text widgets will be + * told their width and given their real text, which + * will cause the size to be recomputed in the y + * direction (because many of them will expand to more + * than one line). + */ uc->text = w = gtk_label_new("X"); - uc->textsig = + uc->textsig = g_signal_connect(G_OBJECT(w), "size-allocate", G_CALLBACK(label_sizealloc), dp); #else @@ -2497,17 +2497,17 @@ GtkWidget *layout_ctrls( break; } - assert(w != NULL); + assert(w != NULL); - columns_add(cols, w, - COLUMN_START(ctrl->generic.column), - COLUMN_SPAN(ctrl->generic.column)); - if (left) - columns_force_left_align(cols, w); - gtk_widget_show(w); + columns_add(cols, w, + COLUMN_START(ctrl->generic.column), + COLUMN_SPAN(ctrl->generic.column)); + if (left) + columns_force_left_align(cols, w); + gtk_widget_show(w); - uc->toplevel = w; - dlg_add_uctrl(dp, uc); + uc->toplevel = w; + dlg_add_uctrl(dp, uc); } return ret; @@ -2528,7 +2528,7 @@ struct selparam { #if GTK_CHECK_VERSION(2,0,0) static void treeselection_changed(GtkTreeSelection *treeselection, - gpointer data) + gpointer data) { struct selparam **sps = (struct selparam **)data, *sp; GtkTreeModel *treemodel; @@ -2537,7 +2537,7 @@ static void treeselection_changed(GtkTreeSelection *treeselection, gint page_num; if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter)) - return; + return; gtk_tree_model_get(treemodel, &treeiter, TREESTORE_PARAMS, &spindex, -1); sp = sps[spindex]; @@ -2622,119 +2622,119 @@ gint win_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) if (event->keyval == GDK_KEY_Escape && dp->cancelbutton) { g_signal_emit_by_name(G_OBJECT(dp->cancelbutton), "clicked"); - return true; + return true; } if ((event->state & GDK_MOD1_MASK) && - (unsigned char)event->string[0] > 0 && - (unsigned char)event->string[0] <= 127) { - int schr = (unsigned char)event->string[0]; - struct Shortcut *sc = &dp->shortcuts->sc[schr]; + (unsigned char)event->string[0] > 0 && + (unsigned char)event->string[0] <= 127) { + int schr = (unsigned char)event->string[0]; + struct Shortcut *sc = &dp->shortcuts->sc[schr]; - switch (sc->action) { - case SHORTCUT_TREE: + switch (sc->action) { + case SHORTCUT_TREE: #if GTK_CHECK_VERSION(2,0,0) - gtk_widget_grab_focus(sc->widget); + gtk_widget_grab_focus(sc->widget); #else - tree_grab_focus(dp); + tree_grab_focus(dp); #endif - break; - case SHORTCUT_FOCUS: - gtk_widget_grab_focus(sc->widget); - break; - case SHORTCUT_UCTRL: - /* - * We must do something sensible with a uctrl. - * Precisely what this is depends on the type of - * control. - */ - switch (sc->uc->ctrl->generic.type) { - case CTRL_CHECKBOX: - case CTRL_BUTTON: - /* Check boxes and buttons get the focus _and_ get toggled. */ - gtk_widget_grab_focus(sc->uc->toplevel); - g_signal_emit_by_name(G_OBJECT(sc->uc->toplevel), "clicked"); - break; - case CTRL_FILESELECT: - case CTRL_FONTSELECT: - /* File/font selectors have their buttons pressed (ooer), - * and focus transferred to the edit box. */ - g_signal_emit_by_name(G_OBJECT(sc->uc->button), "clicked"); - gtk_widget_grab_focus(sc->uc->entry); - break; - case CTRL_RADIO: - /* - * Radio buttons are fun, because they have - * multiple shortcuts. We must find whether the - * activated shortcut is the shortcut for the whole - * group, or for a particular button. In the former - * case, we find the currently selected button and - * focus it; in the latter, we focus-and-click the - * button whose shortcut was pressed. - */ - if (schr == sc->uc->ctrl->radio.shortcut) { - int i; - for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++) - if (gtk_toggle_button_get_active - (GTK_TOGGLE_BUTTON(sc->uc->buttons[i]))) { - gtk_widget_grab_focus(sc->uc->buttons[i]); - } - } else if (sc->uc->ctrl->radio.shortcuts) { - int i; - for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++) - if (schr == sc->uc->ctrl->radio.shortcuts[i]) { - gtk_widget_grab_focus(sc->uc->buttons[i]); + break; + case SHORTCUT_FOCUS: + gtk_widget_grab_focus(sc->widget); + break; + case SHORTCUT_UCTRL: + /* + * We must do something sensible with a uctrl. + * Precisely what this is depends on the type of + * control. + */ + switch (sc->uc->ctrl->generic.type) { + case CTRL_CHECKBOX: + case CTRL_BUTTON: + /* Check boxes and buttons get the focus _and_ get toggled. */ + gtk_widget_grab_focus(sc->uc->toplevel); + g_signal_emit_by_name(G_OBJECT(sc->uc->toplevel), "clicked"); + break; + case CTRL_FILESELECT: + case CTRL_FONTSELECT: + /* File/font selectors have their buttons pressed (ooer), + * and focus transferred to the edit box. */ + g_signal_emit_by_name(G_OBJECT(sc->uc->button), "clicked"); + gtk_widget_grab_focus(sc->uc->entry); + break; + case CTRL_RADIO: + /* + * Radio buttons are fun, because they have + * multiple shortcuts. We must find whether the + * activated shortcut is the shortcut for the whole + * group, or for a particular button. In the former + * case, we find the currently selected button and + * focus it; in the latter, we focus-and-click the + * button whose shortcut was pressed. + */ + if (schr == sc->uc->ctrl->radio.shortcut) { + int i; + for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++) + if (gtk_toggle_button_get_active + (GTK_TOGGLE_BUTTON(sc->uc->buttons[i]))) { + gtk_widget_grab_focus(sc->uc->buttons[i]); + } + } else if (sc->uc->ctrl->radio.shortcuts) { + int i; + for (i = 0; i < sc->uc->ctrl->radio.nbuttons; i++) + if (schr == sc->uc->ctrl->radio.shortcuts[i]) { + gtk_widget_grab_focus(sc->uc->buttons[i]); g_signal_emit_by_name (G_OBJECT(sc->uc->buttons[i]), "clicked"); - } - } - break; - case CTRL_LISTBOX: + } + } + break; + case CTRL_LISTBOX: #if !GTK_CHECK_VERSION(2,4,0) - if (sc->uc->optmenu) { - GdkEventButton bev; - gint returnval; + if (sc->uc->optmenu) { + GdkEventButton bev; + gint returnval; - gtk_widget_grab_focus(sc->uc->optmenu); - /* Option menus don't work using the "clicked" signal. - * We need to manufacture a button press event :-/ */ - bev.type = GDK_BUTTON_PRESS; - bev.button = 1; + gtk_widget_grab_focus(sc->uc->optmenu); + /* Option menus don't work using the "clicked" signal. + * We need to manufacture a button press event :-/ */ + bev.type = GDK_BUTTON_PRESS; + bev.button = 1; g_signal_emit_by_name(G_OBJECT(sc->uc->optmenu), "button_press_event", &bev, &returnval); - break; - } + break; + } #else - if (sc->uc->combo) { - gtk_widget_grab_focus(sc->uc->combo); - gtk_combo_box_popup(GTK_COMBO_BOX(sc->uc->combo)); - break; - } + if (sc->uc->combo) { + gtk_widget_grab_focus(sc->uc->combo); + gtk_combo_box_popup(GTK_COMBO_BOX(sc->uc->combo)); + break; + } #endif #if !GTK_CHECK_VERSION(2,0,0) - if (sc->uc->list) { - /* - * For GTK-1 style list boxes, we tell it to - * focus one of its children, which appears to - * do the Right Thing. - */ + if (sc->uc->list) { + /* + * For GTK-1 style list boxes, we tell it to + * focus one of its children, which appears to + * do the Right Thing. + */ gtk_container_focus(GTK_CONTAINER(sc->uc->list), GTK_DIR_TAB_FORWARD); - break; - } + break; + } #else - if (sc->uc->treeview) { - gtk_widget_grab_focus(sc->uc->treeview); - break; - } + if (sc->uc->treeview) { + gtk_widget_grab_focus(sc->uc->treeview); + break; + } #endif - assert(!"We shouldn't get here"); - break; - } - break; - } + assert(!"We shouldn't get here"); + break; + } + break; + } } return false; @@ -2750,37 +2750,37 @@ gint tree_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) int dir, i, j = -1; for (i = 0; i < dp->ntreeitems; i++) if (widget == dp->treeitems[i]) - break; - if (i < dp->ntreeitems) { - if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up) - dir = -1; - else - dir = +1; + break; + if (i < dp->ntreeitems) { + if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up) + dir = -1; + else + dir = +1; - while (1) { - i += dir; - if (i < 0 || i >= dp->ntreeitems) - break; /* nothing in that dir to select */ - /* - * Determine if this tree item is visible. - */ - { - GtkWidget *w = dp->treeitems[i]; + while (1) { + i += dir; + if (i < 0 || i >= dp->ntreeitems) + break; /* nothing in that dir to select */ + /* + * Determine if this tree item is visible. + */ + { + GtkWidget *w = dp->treeitems[i]; bool vis = true; - while (w && (GTK_IS_TREE_ITEM(w) || GTK_IS_TREE(w))) { - if (!GTK_WIDGET_VISIBLE(w)) { - vis = false; - break; - } - w = w->parent; - } - if (vis) { - j = i; /* got one */ - break; - } - } - } - } + while (w && (GTK_IS_TREE_ITEM(w) || GTK_IS_TREE(w))) { + if (!GTK_WIDGET_VISIBLE(w)) { + vis = false; + break; + } + w = w->parent; + } + if (vis) { + j = i; /* got one */ + break; + } + } + } + } g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event"); if (j >= 0) { g_signal_emit_by_name(G_OBJECT(dp->treeitems[j]), "toggle"); @@ -2795,13 +2795,13 @@ gint tree_key_press(GtkWidget *widget, GdkEventKey *event, gpointer data) */ if (event->keyval == GDK_Left || event->keyval == GDK_KP_Left) { g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event"); - gtk_tree_item_collapse(GTK_TREE_ITEM(widget)); - return true; + gtk_tree_item_collapse(GTK_TREE_ITEM(widget)); + return true; } if (event->keyval == GDK_Right || event->keyval == GDK_KP_Right) { g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event"); - gtk_tree_item_expand(GTK_TREE_ITEM(widget)); - return true; + gtk_tree_item_expand(GTK_TREE_ITEM(widget)); + return true; } return false; @@ -2826,19 +2826,19 @@ static void shortcut_highlight(GtkWidget *labelw, int chr) #endif for (i = 0; currstr[i]; i++) - if (tolower((unsigned char)currstr[i]) == chr) { - pattern = dupprintf("%*s_", i, ""); - gtk_label_set_pattern(label, pattern); - sfree(pattern); - break; - } + if (tolower((unsigned char)currstr[i]) == chr) { + pattern = dupprintf("%*s_", i, ""); + gtk_label_set_pattern(label, pattern); + sfree(pattern); + break; + } } void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw, - int chr, int action, void *ptr) + int chr, int action, void *ptr) { if (chr == NO_SHORTCUT) - return; + return; chr = tolower((unsigned char)chr); @@ -2847,11 +2847,11 @@ void shortcut_add(struct Shortcuts *scs, GtkWidget *labelw, scs->sc[chr].action = action; if (action == SHORTCUT_FOCUS || action == SHORTCUT_TREE) { - scs->sc[chr].uc = NULL; - scs->sc[chr].widget = (GtkWidget *)ptr; + scs->sc[chr].uc = NULL; + scs->sc[chr].widget = (GtkWidget *)ptr; } else { - scs->sc[chr].widget = NULL; - scs->sc[chr].uc = (struct uctrl *)ptr; + scs->sc[chr].widget = NULL; + scs->sc[chr].uc = (struct uctrl *)ptr; } shortcut_highlight(labelw, chr); @@ -2921,7 +2921,7 @@ GtkWidget *create_config_box(const char *title, Conf *conf, post_dialog_fn_t after, void *afterctx) { GtkWidget *window, *hbox, *vbox, *cols, *label, - *tree, *treescroll, *panels, *panelvbox; + *tree, *treescroll, *panels, *panelvbox; int index, level, protocol; char *path; #if GTK_CHECK_VERSION(2,0,0) @@ -2947,7 +2947,7 @@ GtkWidget *create_config_box(const char *title, Conf *conf, dlg_init(dp); for (index = 0; index < lenof(scs.sc); index++) { - scs.sc[index].action = SHORTCUT_EMPTY; + scs.sc[index].action = SHORTCUT_EMPTY; } window = our_dialog_new(); @@ -2976,12 +2976,12 @@ GtkWidget *create_config_box(const char *title, Conf *conf, treescroll = gtk_scrolled_window_new(NULL, NULL); #if GTK_CHECK_VERSION(2,0,0) treestore = gtk_tree_store_new - (TREESTORE_NUM, G_TYPE_STRING, G_TYPE_INT); + (TREESTORE_NUM, G_TYPE_STRING, G_TYPE_INT); tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(treestore)); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), false); treerenderer = gtk_cell_renderer_text_new(); treecolumn = gtk_tree_view_column_new_with_attributes - ("Label", treerenderer, "text", 0, NULL); + ("Label", treerenderer, "text", 0, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), treecolumn); treeselection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree)); gtk_tree_selection_set_mode(treeselection, GTK_SELECTION_BROWSE); @@ -3007,144 +3007,144 @@ GtkWidget *create_config_box(const char *title, Conf *conf, path = NULL; level = 0; for (index = 0; index < dp->ctrlbox->nctrlsets; index++) { - struct controlset *s = dp->ctrlbox->ctrlsets[index]; - GtkWidget *w; + struct controlset *s = dp->ctrlbox->ctrlsets[index]; + GtkWidget *w; - if (!*s->pathname) { - w = layout_ctrls(dp, NULL, &scs, s, GTK_WINDOW(window)); + if (!*s->pathname) { + w = layout_ctrls(dp, NULL, &scs, s, GTK_WINDOW(window)); - our_dialog_set_action_area(GTK_WINDOW(window), w); - } else { - int j = path ? ctrl_path_compare(s->pathname, path) : 0; - if (j != INT_MAX) { /* add to treeview, start new panel */ - char *c; + our_dialog_set_action_area(GTK_WINDOW(window), w); + } else { + int j = path ? ctrl_path_compare(s->pathname, path) : 0; + if (j != INT_MAX) { /* add to treeview, start new panel */ + char *c; #if GTK_CHECK_VERSION(2,0,0) - GtkTreeIter treeiter; + GtkTreeIter treeiter; #else - GtkWidget *treeitem; + GtkWidget *treeitem; #endif - bool first; + bool first; - /* - * We expect never to find an implicit path - * component. For example, we expect never to see - * A/B/C followed by A/D/E, because that would - * _implicitly_ create A/D. All our path prefixes - * are expected to contain actual controls and be - * selectable in the treeview; so we would expect - * to see A/D _explicitly_ before encountering - * A/D/E. - */ - assert(j == ctrl_path_elements(s->pathname) - 1); + /* + * We expect never to find an implicit path + * component. For example, we expect never to see + * A/B/C followed by A/D/E, because that would + * _implicitly_ create A/D. All our path prefixes + * are expected to contain actual controls and be + * selectable in the treeview; so we would expect + * to see A/D _explicitly_ before encountering + * A/D/E. + */ + assert(j == ctrl_path_elements(s->pathname) - 1); - c = strrchr(s->pathname, '/'); - if (!c) - c = s->pathname; - else - c++; + c = strrchr(s->pathname, '/'); + if (!c) + c = s->pathname; + else + c++; - path = s->pathname; + path = s->pathname; - first = (panelvbox == NULL); + first = (panelvbox == NULL); - panelvbox = gtk_vbox_new(false, 4); - gtk_widget_show(panelvbox); - gtk_notebook_append_page(GTK_NOTEBOOK(panels), panelvbox, - NULL); + panelvbox = gtk_vbox_new(false, 4); + gtk_widget_show(panelvbox); + gtk_notebook_append_page(GTK_NOTEBOOK(panels), panelvbox, + NULL); struct selparam *sp = snew(struct selparam); - if (first) { - gint page_num; + if (first) { + gint page_num; - page_num = gtk_notebook_page_num(GTK_NOTEBOOK(panels), - panelvbox); - gtk_notebook_set_current_page(GTK_NOTEBOOK(panels), + page_num = gtk_notebook_page_num(GTK_NOTEBOOK(panels), + panelvbox); + gtk_notebook_set_current_page(GTK_NOTEBOOK(panels), page_num); dp->curr_panel = sp; - } + } sgrowarray(selparams, selparamsize, nselparams); - selparams[nselparams] = sp; - sp->dp = dp; - sp->panels = GTK_NOTEBOOK(panels); - sp->panel = panelvbox; - sp->shortcuts = scs; /* structure copy */ + selparams[nselparams] = sp; + sp->dp = dp; + sp->panels = GTK_NOTEBOOK(panels); + sp->panel = panelvbox; + sp->shortcuts = scs; /* structure copy */ - assert(j-1 < level); + assert(j-1 < level); #if GTK_CHECK_VERSION(2,0,0) - if (j > 0) - /* treeiterlevels[j-1] will always be valid because we - * don't allow implicit path components; see above. - */ - gtk_tree_store_append(treestore, &treeiter, - &treeiterlevels[j-1]); - else - gtk_tree_store_append(treestore, &treeiter, NULL); - gtk_tree_store_set(treestore, &treeiter, - TREESTORE_PATH, c, - TREESTORE_PARAMS, nselparams, - -1); - treeiterlevels[j] = treeiter; + if (j > 0) + /* treeiterlevels[j-1] will always be valid because we + * don't allow implicit path components; see above. + */ + gtk_tree_store_append(treestore, &treeiter, + &treeiterlevels[j-1]); + else + gtk_tree_store_append(treestore, &treeiter, NULL); + gtk_tree_store_set(treestore, &treeiter, + TREESTORE_PATH, c, + TREESTORE_PARAMS, nselparams, + -1); + treeiterlevels[j] = treeiter; - sp->depth = j; - if (j > 0) { - sp->treepath = gtk_tree_model_get_path( + sp->depth = j; + if (j > 0) { + sp->treepath = gtk_tree_model_get_path( GTK_TREE_MODEL(treestore), &treeiterlevels[j-1]); - /* - * We are going to collapse all tree branches - * at depth greater than 2, but not _yet_; see - * the comment at the call to - * gtk_tree_view_collapse_row below. - */ - gtk_tree_view_expand_row(GTK_TREE_VIEW(tree), - sp->treepath, false); - } else { - sp->treepath = NULL; - } + /* + * We are going to collapse all tree branches + * at depth greater than 2, but not _yet_; see + * the comment at the call to + * gtk_tree_view_collapse_row below. + */ + gtk_tree_view_expand_row(GTK_TREE_VIEW(tree), + sp->treepath, false); + } else { + sp->treepath = NULL; + } #else - treeitem = gtk_tree_item_new_with_label(c); - if (j > 0) { - if (!treelevels[j-1]) { - treelevels[j-1] = GTK_TREE(gtk_tree_new()); - gtk_tree_item_set_subtree - (treeitemlevels[j-1], - GTK_WIDGET(treelevels[j-1])); + treeitem = gtk_tree_item_new_with_label(c); + if (j > 0) { + if (!treelevels[j-1]) { + treelevels[j-1] = GTK_TREE(gtk_tree_new()); + gtk_tree_item_set_subtree + (treeitemlevels[j-1], + GTK_WIDGET(treelevels[j-1])); if (j < 2) gtk_tree_item_expand(treeitemlevels[j-1]); else gtk_tree_item_collapse(treeitemlevels[j-1]); - } - gtk_tree_append(treelevels[j-1], treeitem); - } else { - gtk_tree_append(GTK_TREE(tree), treeitem); - } - treeitemlevels[j] = GTK_TREE_ITEM(treeitem); - treelevels[j] = NULL; + } + gtk_tree_append(treelevels[j-1], treeitem); + } else { + gtk_tree_append(GTK_TREE(tree), treeitem); + } + treeitemlevels[j] = GTK_TREE_ITEM(treeitem); + treelevels[j] = NULL; g_signal_connect(G_OBJECT(treeitem), "key_press_event", G_CALLBACK(tree_key_press), dp); g_signal_connect(G_OBJECT(treeitem), "focus_in_event", G_CALLBACK(widget_focus), dp); - gtk_widget_show(treeitem); + gtk_widget_show(treeitem); - if (first) - gtk_tree_select_child(GTK_TREE(tree), treeitem); - sp->treeitem = treeitem; + if (first) + gtk_tree_select_child(GTK_TREE(tree), treeitem); + sp->treeitem = treeitem; #endif - level = j+1; - nselparams++; - } + level = j+1; + nselparams++; + } - w = layout_ctrls(dp, selparams[nselparams-1], + w = layout_ctrls(dp, selparams[nselparams-1], &selparams[nselparams-1]->shortcuts, s, NULL); - gtk_box_pack_start(GTK_BOX(panelvbox), w, false, false, 0); + gtk_box_pack_start(GTK_BOX(panelvbox), w, false, false, 0); gtk_widget_show(w); - } + } } #if GTK_CHECK_VERSION(2,0,0) @@ -3171,10 +3171,10 @@ GtkWidget *create_config_box(const char *title, Conf *conf, /* * In GTK2, we can just do the job right now. */ - GtkRequisition req; - gtk_widget_size_request(tree, &req); + GtkRequisition req; + gtk_widget_size_request(tree, &req); initial_treeview_collapse(dp, tree); - gtk_widget_set_size_request(tree, req.width, -1); + gtk_widget_set_size_request(tree, req.width, -1); } #else /* @@ -3188,7 +3188,7 @@ GtkWidget *create_config_box(const char *title, Conf *conf, #if GTK_CHECK_VERSION(2,0,0) g_signal_connect(G_OBJECT(treeselection), "changed", - G_CALLBACK(treeselection_changed), selparams); + G_CALLBACK(treeselection_changed), selparams); #else dp->ntreeitems = nselparams; dp->treeitems = snewn(dp->ntreeitems, GtkWidget *); @@ -3215,11 +3215,11 @@ GtkWidget *create_config_box(const char *title, Conf *conf, #if !GTK_CHECK_VERSION(2,0,0) gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(treescroll), - tree); + tree); #endif gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(treescroll), - GTK_POLICY_NEVER, - GTK_POLICY_AUTOMATIC); + GTK_POLICY_NEVER, + GTK_POLICY_AUTOMATIC); gtk_widget_show(tree); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); @@ -3229,11 +3229,11 @@ GtkWidget *create_config_box(const char *title, Conf *conf, * Set focus into the first available control. */ for (index = 0; index < dp->ctrlbox->nctrlsets; index++) { - struct controlset *s = dp->ctrlbox->ctrlsets[index]; + struct controlset *s = dp->ctrlbox->ctrlsets[index]; bool done = false; int j; - if (*s->pathname) { + if (*s->pathname) { for (j = 0; j < s->ncontrols; j++) if (s->ctrls[j]->generic.type != CTRL_TABDELAY && s->ctrls[j]->generic.type != CTRL_COLUMNS && @@ -3276,7 +3276,7 @@ static void dlgparam_destroy(GtkWidget *widget, gpointer data) } static void messagebox_handler(union control *ctrl, dlgparam *dp, - void *data, int event) + void *data, int event) { if (event == EVENT_ACTION) dlg_end(dp, ctrl->generic.context.i); @@ -3315,7 +3315,7 @@ GtkWidget *create_message_box( dlg_init(dp); for (index = 0; index < lenof(scs.sc); index++) { - scs.sc[index].action = SHORTCUT_EMPTY; + scs.sc[index].action = SHORTCUT_EMPTY; } dp->ctrlbox = ctrl_new_box(); @@ -3328,7 +3328,7 @@ GtkWidget *create_message_box( min_type = +1; for (i = 0; i < buttons->nbuttons; i++) { const struct message_box_button *button = &buttons->buttons[i]; - ncols++; + ncols++; if (min_type > button->type) min_type = button->type; assert(button->value >= 0); /* <0 means no return value available */ @@ -3339,16 +3339,16 @@ GtkWidget *create_message_box( c->columns.ncols = s0->ncolumns = ncols; c->columns.percentages = sresize(c->columns.percentages, ncols, int); for (index = 0; index < ncols; index++) - c->columns.percentages[index] = (index+1)*100/ncols - index*100/ncols; + c->columns.percentages[index] = (index+1)*100/ncols - index*100/ncols; index = 0; for (i = 0; i < buttons->nbuttons; i++) { const struct message_box_button *button = &buttons->buttons[i]; - c = ctrl_pushbutton(s0, button->title, button->shortcut, + c = ctrl_pushbutton(s0, button->title, button->shortcut, HELPCTX(no_help), messagebox_handler, I(button->value)); - c->generic.column = index++; - if (button->type > 0) - c->button.isdefault = true; + c->generic.column = index++; + if (button->type > 0) + c->button.isdefault = true; /* We always arrange that _some_ button is labelled as * 'iscancel', so that pressing Escape will always cause @@ -3359,8 +3359,8 @@ GtkWidget *create_message_box( * no will be picked, and if there's only one option (a box * that really is just showing a _message_ and not even asking * a question) then that will be picked. */ - if (button->type == min_type) - c->button.iscancel = true; + if (button->type == min_type) + c->button.iscancel = true; } s1 = ctrl_getset(dp->ctrlbox, "x", "", ""); @@ -3404,10 +3404,10 @@ GtkWidget *create_message_box( if (parentwin) { set_transient_window_pos(parentwin, window); - gtk_window_set_transient_for(GTK_WINDOW(window), - GTK_WINDOW(parentwin)); + gtk_window_set_transient_for(GTK_WINDOW(window), + GTK_WINDOW(parentwin)); } else - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); + gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_container_set_focus_child(GTK_CONTAINER(window), NULL); gtk_widget_show(window); gtk_window_set_focus(GTK_WINDOW(window), NULL); @@ -3481,31 +3481,31 @@ int gtk_seat_verify_ssh_host_key( void (*callback)(void *ctx, int result), void *ctx) { static const char absenttxt[] = - "The server's host key is not cached. You have no guarantee " - "that the server is the computer you think it is.\n" - "The server's %s key fingerprint is:\n" - "%s\n" - "If you trust this host, press \"Accept\" to add the key to " - "PuTTY's cache and carry on connecting.\n" - "If you want to carry on connecting just once, without " - "adding the key to the cache, press \"Connect Once\".\n" - "If you do not trust this host, press \"Cancel\" to abandon the " - "connection."; + "The server's host key is not cached. You have no guarantee " + "that the server is the computer you think it is.\n" + "The server's %s key fingerprint is:\n" + "%s\n" + "If you trust this host, press \"Accept\" to add the key to " + "PuTTY's cache and carry on connecting.\n" + "If you want to carry on connecting just once, without " + "adding the key to the cache, press \"Connect Once\".\n" + "If you do not trust this host, press \"Cancel\" to abandon the " + "connection."; static const char wrongtxt[] = - "WARNING - POTENTIAL SECURITY BREACH!\n" - "The server's host key does not match the one PuTTY has " - "cached. This means that either the server administrator " - "has changed the host key, or you have actually connected " - "to another computer pretending to be the server.\n" - "The new %s key fingerprint is:\n" - "%s\n" - "If you were expecting this change and trust the new key, " - "press \"Accept\" to update PuTTY's cache and continue connecting.\n" - "If you want to carry on connecting but without updating " - "the cache, press \"Connect Once\".\n" - "If you want to abandon the connection completely, press " - "\"Cancel\" to cancel. Pressing \"Cancel\" is the ONLY guaranteed " - "safe choice."; + "WARNING - POTENTIAL SECURITY BREACH!\n" + "The server's host key does not match the one PuTTY has " + "cached. This means that either the server administrator " + "has changed the host key, or you have actually connected " + "to another computer pretending to be the server.\n" + "The new %s key fingerprint is:\n" + "%s\n" + "If you were expecting this change and trust the new key, " + "press \"Accept\" to update PuTTY's cache and continue connecting.\n" + "If you want to carry on connecting but without updating " + "the cache, press \"Connect Once\".\n" + "If you want to abandon the connection completely, press " + "\"Cancel\" to cancel. Pressing \"Cancel\" is the ONLY guaranteed " + "safe choice."; static const struct message_box_button button_array_hostkey[] = { {"Accept", 'a', 0, 2}, {"Connect Once", 'o', 0, 1}, @@ -3525,8 +3525,8 @@ int gtk_seat_verify_ssh_host_key( */ ret = verify_host_key(host, port, keytype, keystr); - if (ret == 0) /* success - key matched OK */ - return 1; + if (ret == 0) /* success - key matched OK */ + return 1; text = dupprintf((ret == 2 ? wrongtxt : absenttxt), keytype, fingerprint); @@ -3583,9 +3583,9 @@ int gtk_seat_confirm_weak_crypto_primitive( void (*callback)(void *ctx, int result), void *ctx) { static const char msg[] = - "The first %s supported by the server is " - "%s, which is below the configured warning threshold.\n" - "Continue with connection?"; + "The first %s supported by the server is " + "%s, which is below the configured warning threshold.\n" + "Continue with connection?"; char *text; struct simple_prompt_result_ctx *result_ctx; @@ -3616,12 +3616,12 @@ int gtk_seat_confirm_weak_cached_hostkey( void (*callback)(void *ctx, int result), void *ctx) { static const char msg[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Continue with connection?"; + "Continue with connection?"; char *text; struct simple_prompt_result_ctx *result_ctx; @@ -3714,7 +3714,7 @@ void about_box(void *window) if (aboutbox) { gtk_widget_grab_focus(aboutbox); - return; + return; } aboutbox = our_dialog_new(); @@ -3801,27 +3801,27 @@ static void eventlog_destroy(GtkWidget *widget, gpointer data) ctrl_free_box(es->eventbox); } static void eventlog_ok_handler(union control *ctrl, dlgparam *dp, - void *data, int event) + void *data, int event) { if (event == EVENT_ACTION) dlg_end(dp, 0); } static void eventlog_list_handler(union control *ctrl, dlgparam *dp, - void *data, int event) + void *data, int event) { eventlog_stuff *es = (eventlog_stuff *)data; if (event == EVENT_REFRESH) { - int i; + int i; dlg_update_start(ctrl, dp); dlg_listbox_clear(ctrl, dp); - for (i = 0; i < es->ninitial; i++) { + for (i = 0; i < es->ninitial; i++) { dlg_listbox_add(ctrl, dp, es->events_initial[i]); - } - for (i = 0; i < es->ncircular; i++) { + } + for (i = 0; i < es->ncircular; i++) { dlg_listbox_add(ctrl, dp, es->events_circular[(es->circular_first + i) % LOGEVENT_CIRCULAR_MAX]); - } + } dlg_update_done(ctrl, dp); } else if (event == EVENT_SELCHANGE) { int i; @@ -3887,7 +3887,7 @@ gint eventlog_selection_clear(GtkWidget *widget, GdkEventSelection *seldata, #else assert(uc->treeview); gtk_tree_selection_unselect_all - (gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview))); + (gtk_tree_view_get_selection(GTK_TREE_VIEW(uc->treeview))); #endif es->ignore_selchange = false; @@ -3905,13 +3905,13 @@ void showeventlog(eventlog_stuff *es, void *parentwin) if (es->window) { gtk_widget_grab_focus(es->window); - return; + return; } dlg_init(&es->dp); for (index = 0; index < lenof(es->scs.sc); index++) { - es->scs.sc[index].action = SHORTCUT_EMPTY; + es->scs.sc[index].action = SHORTCUT_EMPTY; } es->eventbox = ctrl_new_box(); @@ -3919,13 +3919,13 @@ void showeventlog(eventlog_stuff *es, void *parentwin) s0 = ctrl_getset(es->eventbox, "", "", ""); ctrl_columns(s0, 3, 33, 34, 33); c = ctrl_pushbutton(s0, "Close", 'c', HELPCTX(no_help), - eventlog_ok_handler, P(NULL)); + eventlog_ok_handler, P(NULL)); c->button.column = 1; c->button.isdefault = true; s1 = ctrl_getset(es->eventbox, "x", "", ""); es->listctrl = c = ctrl_listbox(s1, NULL, NO_SHORTCUT, HELPCTX(no_help), - eventlog_list_handler, P(es)); + eventlog_list_handler, P(es)); c->listbox.height = 10; c->listbox.multisel = 2; c->listbox.ncols = 3; @@ -3960,10 +3960,10 @@ void showeventlog(eventlog_stuff *es, void *parentwin) if (parent) { set_transient_window_pos(parent, window); - gtk_window_set_transient_for(GTK_WINDOW(window), - GTK_WINDOW(parent)); + gtk_window_set_transient_for(GTK_WINDOW(window), + GTK_WINDOW(parent)); } else - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); + gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_widget_show(window); g_signal_connect(G_OBJECT(window), "destroy", @@ -4030,7 +4030,7 @@ void logevent_dlg(eventlog_stuff *es, const char *string) sfree(*location); *location = dupcat(timebuf, string, NULL); if (es->window) { - dlg_listbox_add(es->listctrl, &es->dp, *location); + dlg_listbox_add(es->listctrl, &es->dp, *location); } if (es->ninitial < LOGEVENT_INITIAL_MAX) { es->ninitial++; @@ -4047,10 +4047,10 @@ int gtkdlg_askappend(Seat *seat, Filename *filename, void (*callback)(void *ctx, int result), void *ctx) { static const char msgtemplate[] = - "The session log file \"%.*s\" already exists. " - "You can overwrite it with a new session log, " - "append your session log to the end of it, " - "or disable session logging for this session."; + "The session log file \"%.*s\" already exists. " + "You can overwrite it with a new session log, " + "append your session log to the end of it, " + "or disable session logging for this session."; static const struct message_box_button button_array_append[] = { {"Overwrite", 'o', 1, 2}, {"Append", 'a', 0, 1}, diff --git a/unix/gtkfont.c b/unix/gtkfont.c index f37a0d5d..db3dc589 100644 --- a/unix/gtkfont.c +++ b/unix/gtkfont.c @@ -1,6 +1,6 @@ /* * Unified font management for GTK. - * + * * PuTTY is willing to use both old-style X server-side bitmap * fonts _and_ GTK2/Pango client-side fonts. This requires us to * do a bit of work to wrap the two wildly different APIs into @@ -36,7 +36,7 @@ /* * Future work: - * + * * - it would be nice to have a display of the current font name, * and in particular whether it's client- or server-side, * during the progress of the font selector. @@ -50,7 +50,7 @@ /* * Ad-hoc vtable mechanism to allow font structures to be * polymorphic. - * + * * Any instance of `unifont' used in the vtable functions will * actually be an element of a larger structure containing data * specific to the subtype. @@ -64,10 +64,10 @@ #define FONTFLAG_SORT_MASK 0x0007 /* used to disambiguate font families */ typedef void (*fontsel_add_entry)(void *ctx, const char *realfontname, - const char *family, const char *charset, - const char *style, const char *stylekey, - int size, int flags, - const struct UnifontVtable *fontclass); + const char *family, const char *charset, + const char *style, const char *stylekey, + int size, int flags, + const struct UnifontVtable *fontclass); struct UnifontVtable { /* @@ -87,9 +87,9 @@ struct UnifontVtable { int x, int y, const wchar_t *string, int len, bool wide, bool bold, int cellwidth); void (*enum_fonts)(GtkWidget *widget, - fontsel_add_entry callback, void *callback_ctx); + fontsel_add_entry callback, void *callback_ctx); char *(*canonify_fontname)(GtkWidget *widget, const char *name, int *size, - int *flags, bool resolve_aliases); + int *flags, bool resolve_aliases); char *(*scale_fontname)(GtkWidget *widget, const char *name, int size); char *(*size_increment)(unifont *font, int increment); @@ -116,16 +116,16 @@ static void x11font_draw_combining(unifont_drawctx *ctx, unifont *font, int len, bool wide, bool bold, int cellwidth); static unifont *x11font_create(GtkWidget *widget, const char *name, - bool wide, bool bold, - int shadowoffset, bool shadowalways); + bool wide, bool bold, + int shadowoffset, bool shadowalways); static void x11font_destroy(unifont *font); static void x11font_enum_fonts(GtkWidget *widget, - fontsel_add_entry callback, void *callback_ctx); + fontsel_add_entry callback, void *callback_ctx); static char *x11font_canonify_fontname(GtkWidget *widget, const char *name, - int *size, int *flags, - bool resolve_aliases); + int *size, int *flags, + bool resolve_aliases); static char *x11font_scale_fontname(GtkWidget *widget, const char *name, - int size); + int size); static char *x11font_size_increment(unifont *font, int increment); #ifdef DRAW_TEXT_CAIRO @@ -320,7 +320,7 @@ static char *x11_guess_derived_font_name(Display *disp, XFontStruct *xfs, Atom fontprop = XInternAtom(disp, "FONT", False); unsigned long ret; if (XGetFontProperty(xfs, fontprop, &ret)) { - char *name = XGetAtomName(disp, (Atom)ret); + char *name = XGetAtomName(disp, (Atom)ret); struct xlfd_decomposed *xlfd = xlfd_decompose(name); if (!xlfd) return NULL; @@ -349,12 +349,12 @@ static char *x11_guess_derived_font_name(Display *disp, XFontStruct *xfs, static int x11_font_width(XFontStruct *xfs, bool sixteen_bit) { if (sixteen_bit) { - XChar2b space; - space.byte1 = 0; - space.byte2 = '0'; - return XTextWidth16(xfs, &space, 1); + XChar2b space; + space.byte1 = 0; + space.byte2 = '0'; + return XTextWidth16(xfs, &space, 1); } else { - return XTextWidth(xfs, "0", 1); + return XTextWidth(xfs, "0", 1); } } @@ -429,8 +429,8 @@ static bool x11_font_has_glyph( } static unifont *x11font_create(GtkWidget *widget, const char *name, - bool wide, bool bold, - int shadowoffset, bool shadowalways) + bool wide, bool bold, + int shadowoffset, bool shadowalways) { struct x11font *xfont; XFontStruct *xfs; @@ -446,7 +446,7 @@ static unifont *x11font_create(GtkWidget *widget, const char *name, xfs = XLoadQueryFont(disp, name); if (!xfs) - return NULL; + return NULL; charset_registry = XInternAtom(disp, "CHARSET_REGISTRY", False); charset_encoding = XInternAtom(disp, "CHARSET_ENCODING", False); @@ -456,32 +456,32 @@ static unifont *x11font_create(GtkWidget *widget, const char *name, variable = true; if (XGetFontProperty(xfs, charset_registry, ®istry_ret) && - XGetFontProperty(xfs, charset_encoding, &encoding_ret)) { - char *reg, *enc; - reg = XGetAtomName(disp, (Atom)registry_ret); - enc = XGetAtomName(disp, (Atom)encoding_ret); - if (reg && enc) { - char *encoding = dupcat(reg, "-", enc, NULL); - pubcs = realcs = charset_from_xenc(encoding); + XGetFontProperty(xfs, charset_encoding, &encoding_ret)) { + char *reg, *enc; + reg = XGetAtomName(disp, (Atom)registry_ret); + enc = XGetAtomName(disp, (Atom)encoding_ret); + if (reg && enc) { + char *encoding = dupcat(reg, "-", enc, NULL); + pubcs = realcs = charset_from_xenc(encoding); - /* - * iso10646-1 is the only wide font encoding we - * support. In this case, we expect clients to give us - * UTF-8, which this module must internally convert - * into 16-bit Unicode. - */ - if (!strcasecmp(encoding, "iso10646-1")) { - sixteen_bit = true; - pubcs = realcs = CS_UTF8; - } + /* + * iso10646-1 is the only wide font encoding we + * support. In this case, we expect clients to give us + * UTF-8, which this module must internally convert + * into 16-bit Unicode. + */ + if (!strcasecmp(encoding, "iso10646-1")) { + sixteen_bit = true; + pubcs = realcs = CS_UTF8; + } - /* - * Hack for X line-drawing characters: if the primary font - * is encoded as ISO-8859-1, and has valid glyphs in the - * low character positions, it is assumed that those - * glyphs are the VT100 line-drawing character set. - */ - if (pubcs == CS_ISO8859_1) { + /* + * Hack for X line-drawing characters: if the primary font + * is encoded as ISO-8859-1, and has valid glyphs in the + * low character positions, it is assumed that those + * glyphs are the VT100 line-drawing character set. + */ + if (pubcs == CS_ISO8859_1) { int ch; for (ch = 1; ch < 32; ch++) if (!x11_font_has_glyph(xfs, 0, ch)) @@ -490,17 +490,17 @@ static unifont *x11font_create(GtkWidget *widget, const char *name, realcs = CS_ISO8859_1_X11; } - sfree(encoding); - } + sfree(encoding); + } } spacing = XInternAtom(disp, "SPACING", False); if (XGetFontProperty(xfs, spacing, &spacing_ret)) { - char *spc; - spc = XGetAtomName(disp, (Atom)spacing_ret); + char *spc; + spc = XGetAtomName(disp, (Atom)spacing_ret); - if (spc && strchr("CcMm", spc[0])) - variable = false; + if (spc && strchr("CcMm", spc[0])) + variable = false; } xfont = snew(struct x11font); @@ -528,13 +528,13 @@ static unifont *x11font_create(GtkWidget *widget, const char *name, xfont->shadowalways = shadowalways; for (i = 0; i < lenof(xfont->fonts); i++) { - xfont->fonts[i].xfs = NULL; - xfont->fonts[i].allocated = false; + xfont->fonts[i].xfs = NULL; + xfont->fonts[i].allocated = false; #ifdef DRAW_TEXT_CAIRO - xfont->fonts[i].glyphcache = NULL; - xfont->fonts[i].nglyphs = 0; - xfont->fonts[i].pixmap = None; - xfont->fonts[i].gc = None; + xfont->fonts[i].glyphcache = NULL; + xfont->fonts[i].nglyphs = 0; + xfont->fonts[i].pixmap = None; + xfont->fonts[i].gc = None; #endif } xfont->fonts[0].xfs = xfs; @@ -550,14 +550,14 @@ static void x11font_destroy(unifont *font) int i; for (i = 0; i < lenof(xfont->fonts); i++) { - if (xfont->fonts[i].xfs) - XFreeFont(disp, xfont->fonts[i].xfs); + if (xfont->fonts[i].xfs) + XFreeFont(disp, xfont->fonts[i].xfs); #ifdef DRAW_TEXT_CAIRO - if (xfont->fonts[i].gc != None) - XFreeGC(disp, xfont->fonts[i].gc); - if (xfont->fonts[i].pixmap != None) - XFreePixmap(disp, xfont->fonts[i].pixmap); - if (xfont->fonts[i].glyphcache) { + if (xfont->fonts[i].gc != None) + XFreeGC(disp, xfont->fonts[i].gc); + if (xfont->fonts[i].pixmap != None) + XFreePixmap(disp, xfont->fonts[i].pixmap); + if (xfont->fonts[i].glyphcache) { int j; for (j = 0; j < xfont->fonts[i].nglyphs; j++) { cairo_surface_destroy(xfont->fonts[i].glyphcache[j].surface); @@ -574,7 +574,7 @@ static void x11_alloc_subfont(struct x11font *xfont, int sfid) { Display *disp = xfont->disp; char *derived_name = x11_guess_derived_font_name - (disp, xfont->fonts[0].xfs, sfid & 1, !!(sfid & 2)); + (disp, xfont->fonts[0].xfs, sfid & 1, !!(sfid & 2)); xfont->fonts[sfid].xfs = XLoadQueryFont(disp, derived_name); xfont->fonts[sfid].allocated = true; sfree(derived_name); @@ -586,10 +586,10 @@ static bool x11font_has_glyph(unifont *font, wchar_t glyph) struct x11font *xfont = container_of(font, struct x11font, u); if (xfont->sixteen_bit) { - /* - * This X font has 16-bit character indices, which means - * we can directly use our Unicode input value. - */ + /* + * This X font has 16-bit character indices, which means + * we can directly use our Unicode input value. + */ return x11_font_has_glyph(xfont->fonts[0].xfs, glyph >> 8, glyph & 0xFF); } else { @@ -861,13 +861,13 @@ static void x11font_really_draw_text( bool centre; if (fontvariable) { - /* - * In a variable-pitch font, we draw one character at a - * time, and centre it in the character cell. - */ - step = 1; - nsteps = nchars; - centre = true; + /* + * In a variable-pitch font, we draw one character at a + * time, and centre it in the character cell. + */ + step = 1; + nsteps = nchars; + centre = true; } else { /* * In a fixed-pitch font, we can draw the whole lot in one go. @@ -880,23 +880,23 @@ static void x11font_really_draw_text( dfns->setup(ctx, xfi, disp); while (nsteps-- > 0) { - int X = x; - if (centre) - X += (cellwidth - dfns->width(ctx, xfi, string, start, step)) / 2; + int X = x; + if (centre) + X += (cellwidth - dfns->width(ctx, xfi, string, start, step)) / 2; dfns->draw(ctx, xfi, disp, X, y, string, start, step); - if (shadowoffset) + if (shadowoffset) dfns->draw(ctx, xfi, disp, X + shadowoffset, y, string, start, step); - x += cellwidth; + x += cellwidth; start += step; } } static void x11font_draw_text(unifont_drawctx *ctx, unifont *font, - int x, int y, const wchar_t *string, int len, - bool wide, bool bold, int cellwidth) + int x, int y, const wchar_t *string, int len, + bool wide, bool bold, int cellwidth) { struct x11font *xfont = container_of(font, struct x11font, u); int sfid; @@ -912,42 +912,42 @@ static void x11font_draw_text(unifont_drawctx *ctx, unifont *font, * use shadow bold. */ if (xfont->shadowalways && bold) { - shadowoffset = xfont->shadowoffset; - bold = false; + shadowoffset = xfont->shadowoffset; + bold = false; } sfid = 2 * wide + bold; if (!xfont->fonts[sfid].allocated) - x11_alloc_subfont(xfont, sfid); + x11_alloc_subfont(xfont, sfid); if (bold && !xfont->fonts[sfid].xfs) { - bold = false; - shadowoffset = xfont->shadowoffset; - sfid = 2 * wide + bold; - if (!xfont->fonts[sfid].allocated) - x11_alloc_subfont(xfont, sfid); + bold = false; + shadowoffset = xfont->shadowoffset; + sfid = 2 * wide + bold; + if (!xfont->fonts[sfid].allocated) + x11_alloc_subfont(xfont, sfid); } if (!xfont->fonts[sfid].xfs) - return; /* we've tried our best, but no luck */ + return; /* we've tried our best, but no luck */ if (xfont->sixteen_bit) { - /* - * This X font has 16-bit character indices, which means - * we can directly use our Unicode input string. - */ - XChar2b *xcs; - int i; + /* + * This X font has 16-bit character indices, which means + * we can directly use our Unicode input string. + */ + XChar2b *xcs; + int i; - xcs = snewn(len, XChar2b); - for (i = 0; i < len; i++) { - xcs[i].byte1 = string[i] >> 8; - xcs[i].byte2 = string[i]; - } + xcs = snewn(len, XChar2b); + for (i = 0; i < len; i++) { + xcs[i].byte1 = string[i] >> 8; + xcs[i].byte2 = string[i]; + } - x11font_really_draw_text(x11font_drawfuncs + index + 1, ctx, + x11font_really_draw_text(x11font_drawfuncs + index + 1, ctx, &xfont->fonts[sfid], xfont->disp, x, y, xcs, len, shadowoffset, xfont->variable, cellwidth * mult); - sfree(xcs); + sfree(xcs); } else { /* * This X font has 8-bit indices, so we must convert to the @@ -956,10 +956,10 @@ static void x11font_draw_text(unifont_drawctx *ctx, unifont *font, char *sbstring = snewn(len+1, char); int sblen = wc_to_mb(xfont->real_charset, 0, string, len, sbstring, len+1, ".", NULL); - x11font_really_draw_text(x11font_drawfuncs + index + 0, ctx, + x11font_really_draw_text(x11font_drawfuncs + index + 0, ctx, &xfont->fonts[sfid], xfont->disp, x, y, - sbstring, sblen, shadowoffset, - xfont->variable, cellwidth * mult); + sbstring, sblen, shadowoffset, + xfont->variable, cellwidth * mult); sfree(sbstring); } } @@ -980,7 +980,7 @@ static void x11font_draw_combining(unifont_drawctx *ctx, unifont *font, } static void x11font_enum_fonts(GtkWidget *widget, - fontsel_add_entry callback, void *callback_ctx) + fontsel_add_entry callback, void *callback_ctx) { Display *disp; char **fontnames; @@ -992,106 +992,106 @@ static void x11font_enum_fonts(GtkWidget *widget, max = 32768; while (1) { - fontnames = XListFonts(disp, "*", max, &nnames); - if (nnames >= max) { - XFreeFontNames(fontnames); - max *= 2; - } else - break; + fontnames = XListFonts(disp, "*", max, &nnames); + if (nnames >= max) { + XFreeFontNames(fontnames); + max *= 2; + } else + break; } tmpsize = 0; for (i = 0; i < nnames; i++) { struct xlfd_decomposed *xlfd = xlfd_decompose(fontnames[i]); - if (xlfd) { + if (xlfd) { char *p, *font, *style, *stylekey, *charset; int weightkey, slantkey, setwidthkey; int thistmpsize; - /* - * Convert a dismembered XLFD into the format we'll be - * using in the font selector. - */ + /* + * Convert a dismembered XLFD into the format we'll be + * using in the font selector. + */ thistmpsize = 4 * strlen(fontnames[i]) + 256; if (tmpsize < thistmpsize) { tmpsize = thistmpsize; tmp = sresize(tmp, tmpsize, char); } - p = tmp; + p = tmp; - /* - * Font name is in the form "family (foundry)". (This is - * what the GTK 1.2 X font selector does, and it seems to - * come out looking reasonably sensible.) - */ - font = p; - p += 1 + sprintf(p, "%s (%s)", xlfd->family_name, xlfd->foundry); + /* + * Font name is in the form "family (foundry)". (This is + * what the GTK 1.2 X font selector does, and it seems to + * come out looking reasonably sensible.) + */ + font = p; + p += 1 + sprintf(p, "%s (%s)", xlfd->family_name, xlfd->foundry); - /* - * Character set. - */ - charset = p; - p += 1 + sprintf(p, "%s-%s", xlfd->charset_registry, + /* + * Character set. + */ + charset = p; + p += 1 + sprintf(p, "%s-%s", xlfd->charset_registry, xlfd->charset_encoding); - /* - * Style is a mixture of quite a lot of the fields, - * with some strange formatting. - */ - style = p; - p += sprintf(p, "%s", xlfd->weight_name[0] ? xlfd->weight_name : - "regular"); - if (!g_ascii_strcasecmp(xlfd->slant, "i")) - p += sprintf(p, " italic"); - else if (!g_ascii_strcasecmp(xlfd->slant, "o")) - p += sprintf(p, " oblique"); - else if (!g_ascii_strcasecmp(xlfd->slant, "ri")) - p += sprintf(p, " reverse italic"); - else if (!g_ascii_strcasecmp(xlfd->slant, "ro")) - p += sprintf(p, " reverse oblique"); - else if (!g_ascii_strcasecmp(xlfd->slant, "ot")) - p += sprintf(p, " other-slant"); - if (xlfd->setwidth_name[0] && + /* + * Style is a mixture of quite a lot of the fields, + * with some strange formatting. + */ + style = p; + p += sprintf(p, "%s", xlfd->weight_name[0] ? xlfd->weight_name : + "regular"); + if (!g_ascii_strcasecmp(xlfd->slant, "i")) + p += sprintf(p, " italic"); + else if (!g_ascii_strcasecmp(xlfd->slant, "o")) + p += sprintf(p, " oblique"); + else if (!g_ascii_strcasecmp(xlfd->slant, "ri")) + p += sprintf(p, " reverse italic"); + else if (!g_ascii_strcasecmp(xlfd->slant, "ro")) + p += sprintf(p, " reverse oblique"); + else if (!g_ascii_strcasecmp(xlfd->slant, "ot")) + p += sprintf(p, " other-slant"); + if (xlfd->setwidth_name[0] && g_ascii_strcasecmp(xlfd->setwidth_name, "normal")) - p += sprintf(p, " %s", xlfd->setwidth_name); - if (!g_ascii_strcasecmp(xlfd->spacing, "m")) - p += sprintf(p, " [M]"); - if (!g_ascii_strcasecmp(xlfd->spacing, "c")) - p += sprintf(p, " [C]"); - if (xlfd->add_style_name[0]) - p += sprintf(p, " %s", xlfd->add_style_name); + p += sprintf(p, " %s", xlfd->setwidth_name); + if (!g_ascii_strcasecmp(xlfd->spacing, "m")) + p += sprintf(p, " [M]"); + if (!g_ascii_strcasecmp(xlfd->spacing, "c")) + p += sprintf(p, " [C]"); + if (xlfd->add_style_name[0]) + p += sprintf(p, " %s", xlfd->add_style_name); - /* - * Style key is the same stuff as above, but with a - * couple of transformations done on it to make it - * sort more sensibly. - */ - p++; - stylekey = p; - if (!g_ascii_strcasecmp(xlfd->weight_name, "medium") || - !g_ascii_strcasecmp(xlfd->weight_name, "regular") || - !g_ascii_strcasecmp(xlfd->weight_name, "normal") || - !g_ascii_strcasecmp(xlfd->weight_name, "book")) - weightkey = 0; - else if (!g_ascii_strncasecmp(xlfd->weight_name, "demi", 4) || - !g_ascii_strncasecmp(xlfd->weight_name, "semi", 4)) - weightkey = 1; - else - weightkey = 2; - if (!g_ascii_strcasecmp(xlfd->slant, "r")) - slantkey = 0; - else if (!g_ascii_strncasecmp(xlfd->slant, "r", 1)) - slantkey = 2; - else - slantkey = 1; - if (!g_ascii_strcasecmp(xlfd->setwidth_name, "normal")) - setwidthkey = 0; - else - setwidthkey = 1; + /* + * Style key is the same stuff as above, but with a + * couple of transformations done on it to make it + * sort more sensibly. + */ + p++; + stylekey = p; + if (!g_ascii_strcasecmp(xlfd->weight_name, "medium") || + !g_ascii_strcasecmp(xlfd->weight_name, "regular") || + !g_ascii_strcasecmp(xlfd->weight_name, "normal") || + !g_ascii_strcasecmp(xlfd->weight_name, "book")) + weightkey = 0; + else if (!g_ascii_strncasecmp(xlfd->weight_name, "demi", 4) || + !g_ascii_strncasecmp(xlfd->weight_name, "semi", 4)) + weightkey = 1; + else + weightkey = 2; + if (!g_ascii_strcasecmp(xlfd->slant, "r")) + slantkey = 0; + else if (!g_ascii_strncasecmp(xlfd->slant, "r", 1)) + slantkey = 2; + else + slantkey = 1; + if (!g_ascii_strcasecmp(xlfd->setwidth_name, "normal")) + setwidthkey = 0; + else + setwidthkey = 1; - p += sprintf( + p += sprintf( p, "%04d%04d%s%04d%04d%s%04d%04d%s%04d%s%04d%s", weightkey, (int)strlen(xlfd->weight_name), xlfd->weight_name, slantkey, (int)strlen(xlfd->slant), xlfd->slant, @@ -1100,51 +1100,51 @@ static void x11font_enum_fonts(GtkWidget *widget, (int)strlen(xlfd->spacing), xlfd->spacing, (int)strlen(xlfd->add_style_name), xlfd->add_style_name); - assert(p - tmp < thistmpsize); + assert(p - tmp < thistmpsize); - /* - * Flags: we need to know whether this is a monospaced - * font, which we do by examining the spacing field - * again. - */ - flags = FONTFLAG_SERVERSIDE; - if (!strchr("CcMm", xlfd->spacing[0])) - flags |= FONTFLAG_NONMONOSPACED; + /* + * Flags: we need to know whether this is a monospaced + * font, which we do by examining the spacing field + * again. + */ + flags = FONTFLAG_SERVERSIDE; + if (!strchr("CcMm", xlfd->spacing[0])) + flags |= FONTFLAG_NONMONOSPACED; - /* - * Some fonts have a pixel size of zero, meaning they're - * treated as scalable. For these purposes, we only want - * fonts whose pixel size we actually know, so filter - * those out. - */ - if (xlfd->pixel_size) + /* + * Some fonts have a pixel size of zero, meaning they're + * treated as scalable. For these purposes, we only want + * fonts whose pixel size we actually know, so filter + * those out. + */ + if (xlfd->pixel_size) callback(callback_ctx, fontnames[i], font, charset, style, stylekey, xlfd->pixel_size, flags, &x11font_vtable); sfree(xlfd); - } else { - /* - * This isn't an XLFD, so it must be an alias. - * Transmit it with mostly null data. - * - * It would be nice to work out if it's monospaced - * here, but at the moment I can't see that being - * anything but computationally hideous. Ah well. - */ - callback(callback_ctx, fontnames[i], fontnames[i], NULL, - NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable); + } else { + /* + * This isn't an XLFD, so it must be an alias. + * Transmit it with mostly null data. + * + * It would be nice to work out if it's monospaced + * here, but at the moment I can't see that being + * anything but computationally hideous. Ah well. + */ + callback(callback_ctx, fontnames[i], fontnames[i], NULL, + NULL, NULL, 0, FONTFLAG_SERVERALIAS, &x11font_vtable); sfree(xlfd); - } + } } XFreeFontNames(fontnames); sfree(tmp); } static char *x11font_canonify_fontname(GtkWidget *widget, const char *name, - int *size, int *flags, - bool resolve_aliases) + int *size, int *flags, + bool resolve_aliases) { /* * When given an X11 font name to try to make sense of for a @@ -1152,7 +1152,7 @@ static char *x11font_canonify_fontname(GtkWidget *widget, const char *name, * exists), and then canonify it by extracting its FONT * property, which should give its full XLFD even if what we * originally had was a wildcard. - * + * * However, we must carefully avoid canonifying font * _aliases_, unless specifically asked to, because the font * selector treats them as worthwhile in their own right. @@ -1168,40 +1168,40 @@ static char *x11font_canonify_fontname(GtkWidget *widget, const char *name, xfs = XLoadQueryFont(disp, name); if (!xfs) - return NULL; /* didn't make sense to us, sorry */ + return NULL; /* didn't make sense to us, sorry */ fontprop = XInternAtom(disp, "FONT", False); if (XGetFontProperty(xfs, fontprop, &ret)) { - char *newname = XGetAtomName(disp, (Atom)ret); - if (newname) { - unsigned long fsize = 12; + char *newname = XGetAtomName(disp, (Atom)ret); + if (newname) { + unsigned long fsize = 12; - fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False); - if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) { - *size = fsize; + fontprop2 = XInternAtom(disp, "PIXEL_SIZE", False); + if (XGetFontProperty(xfs, fontprop2, &fsize) && fsize > 0) { + *size = fsize; XFreeFont(disp, xfs); - if (flags) { - if (name[0] == '-' || resolve_aliases) - *flags = FONTFLAG_SERVERSIDE; - else - *flags = FONTFLAG_SERVERALIAS; - } - return dupstr(name[0] == '-' || resolve_aliases ? - newname : name); - } - } + if (flags) { + if (name[0] == '-' || resolve_aliases) + *flags = FONTFLAG_SERVERSIDE; + else + *flags = FONTFLAG_SERVERALIAS; + } + return dupstr(name[0] == '-' || resolve_aliases ? + newname : name); + } + } } XFreeFont(disp, xfs); - return NULL; /* something went wrong */ + return NULL; /* something went wrong */ } static char *x11font_scale_fontname(GtkWidget *widget, const char *name, - int size) + int size) { - return NULL; /* shan't */ + return NULL; /* shan't */ } static char *x11font_size_increment(unifont *font, int increment) @@ -1301,7 +1301,7 @@ static char *x11font_size_increment(unifont *font, int increment) */ #if defined PANGO_PRE_1POINT4 && !defined PANGO_PRE_1POINT6 -#define PANGO_PRE_1POINT6 /* make life easier for pre-1.4 folk */ +#define PANGO_PRE_1POINT6 /* make life easier for pre-1.4 folk */ #endif static bool pangofont_has_glyph(unifont *font, wchar_t glyph); @@ -1313,19 +1313,19 @@ static void pangofont_draw_combining(unifont_drawctx *ctx, unifont *font, int len, bool wide, bool bold, int cellwidth); static unifont *pangofont_create(GtkWidget *widget, const char *name, - bool wide, bool bold, - int shadowoffset, bool shadowalways); + bool wide, bool bold, + int shadowoffset, bool shadowalways); static unifont *pangofont_create_fallback(GtkWidget *widget, int height, bool wide, bool bold, int shadowoffset, bool shadowalways); static void pangofont_destroy(unifont *font); static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback, - void *callback_ctx); + void *callback_ctx); static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name, - int *size, int *flags, - bool resolve_aliases); + int *size, int *flags, + bool resolve_aliases); static char *pangofont_scale_fontname(GtkWidget *widget, const char *name, - int size); + int size); static char *pangofont_size_increment(unifont *font, int increment); struct pangofont { @@ -1399,7 +1399,7 @@ static bool pangofont_check_desc_makes_sense(PangoContext *ctx, #ifndef PANGO_PRE_1POINT6 map = pango_context_get_font_map(ctx); if (!map) - return false; + return false; pango_font_map_list_families(map, &families, &nfamilies); #else pango_context_list_families(ctx, &families, &nfamilies); @@ -1407,11 +1407,11 @@ static bool pangofont_check_desc_makes_sense(PangoContext *ctx, matched = false; for (i = 0; i < nfamilies; i++) { - if (!g_ascii_strcasecmp(pango_font_family_get_name(families[i]), - pango_font_description_get_family(desc))) { - matched = true; - break; - } + if (!g_ascii_strcasecmp(pango_font_family_get_name(families[i]), + pango_font_description_get_family(desc))) { + matched = true; + break; + } } g_free(families); @@ -1434,31 +1434,31 @@ static unifont *pangofont_create_internal(GtkWidget *widget, #ifndef PANGO_PRE_1POINT6 map = pango_context_get_font_map(ctx); if (!map) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } fset = pango_font_map_load_fontset(map, ctx, desc, - pango_context_get_language(ctx)); + pango_context_get_language(ctx)); #else fset = pango_context_load_fontset(ctx, desc, pango_context_get_language(ctx)); #endif if (!fset) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } metrics = pango_fontset_get_metrics(fset); if (!metrics || - pango_font_metrics_get_approximate_digit_width(metrics) == 0) { - pango_font_description_free(desc); - g_object_unref(fset); - return NULL; + pango_font_metrics_get_approximate_digit_width(metrics) == 0) { + pango_font_description_free(desc); + g_object_unref(fset); + return NULL; } pfont = snew(struct pangofont); pfont->u.vt = &pangofont_vtable; pfont->u.width = - PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics)); + PANGO_PIXELS(pango_font_metrics_get_approximate_digit_width(metrics)); pfont->u.ascent = PANGO_PIXELS(pango_font_metrics_get_ascent(metrics)); pfont->u.descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics)); pfont->u.height = pfont->u.ascent + pfont->u.descent; @@ -1487,23 +1487,23 @@ static unifont *pangofont_create_internal(GtkWidget *widget, } static unifont *pangofont_create(GtkWidget *widget, const char *name, - bool wide, bool bold, - int shadowoffset, bool shadowalways) + bool wide, bool bold, + int shadowoffset, bool shadowalways) { PangoContext *ctx; PangoFontDescription *desc; desc = pango_font_description_from_string(name); if (!desc) - return NULL; + return NULL; ctx = gtk_widget_get_pango_context(widget); if (!ctx) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } if (!pangofont_check_desc_makes_sense(ctx, desc)) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } return pangofont_create_internal(widget, ctx, desc, wide, bold, shadowoffset, shadowalways); @@ -1518,11 +1518,11 @@ static unifont *pangofont_create_fallback(GtkWidget *widget, int height, desc = pango_font_description_from_string("Monospace"); if (!desc) - return NULL; + return NULL; ctx = gtk_widget_get_pango_context(widget); if (!ctx) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } pango_font_description_set_absolute_size(desc, height * PANGO_SCALE); return pangofont_create_internal(widget, ctx, desc, wide, bold, @@ -1617,21 +1617,21 @@ static void pangofont_draw_internal(unifont_drawctx *ctx, unifont *font, assert(draw_layout); if (wide) - cellwidth *= 2; + cellwidth *= 2; y -= pfont->u.ascent; layout = pango_layout_new(gtk_widget_get_pango_context(pfont->widget)); pango_layout_set_font_description(layout, pfont->desc); if (bold && !pfont->bold) { - if (pfont->shadowalways) - shadowbold = true; - else { - PangoFontDescription *desc2 = - pango_font_description_copy_static(pfont->desc); - pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD); - pango_layout_set_font_description(layout, desc2); - } + if (pfont->shadowalways) + shadowbold = true; + else { + PangoFontDescription *desc2 = + pango_font_description_copy_static(pfont->desc); + pango_font_description_set_weight(desc2, PANGO_WEIGHT_BOLD); + pango_layout_set_font_description(layout, desc2); + } } /* @@ -1644,32 +1644,32 @@ static void pangofont_draw_internal(unifont_drawctx *ctx, unifont *font, utfptr = utfstring; while (utflen > 0) { - int clen, n; + int clen, n; int desired = cellwidth * PANGO_SCALE; - /* - * We want to display every character from this string in - * the centre of its own character cell. In the worst case, - * this requires a separate text-drawing call for each - * character; but in the common case where the font is - * properly fixed-width, we can draw many characters in one - * go which is much faster. - * - * This still isn't really ideal. If you look at what - * happens in the X protocol as a result of all of this, you - * find - naturally enough - that each call to - * gdk_draw_layout() generates a separate set of X RENDER - * operations involving creating a picture, setting a clip - * rectangle, doing some drawing and undoing the whole lot. - * In an ideal world, we should _always_ be able to turn the - * contents of this loop into a single RenderCompositeGlyphs - * operation which internally specifies inter-character - * deltas to get the spacing right, which would give us full - * speed _even_ in the worst case of a non-fixed-width font. - * However, Pango's architecture and documentation are so - * unhelpful that I have no idea how if at all to persuade - * them to do that. - */ + /* + * We want to display every character from this string in + * the centre of its own character cell. In the worst case, + * this requires a separate text-drawing call for each + * character; but in the common case where the font is + * properly fixed-width, we can draw many characters in one + * go which is much faster. + * + * This still isn't really ideal. If you look at what + * happens in the X protocol as a result of all of this, you + * find - naturally enough - that each call to + * gdk_draw_layout() generates a separate set of X RENDER + * operations involving creating a picture, setting a clip + * rectangle, doing some drawing and undoing the whole lot. + * In an ideal world, we should _always_ be able to turn the + * contents of this loop into a single RenderCompositeGlyphs + * operation which internally specifies inter-character + * deltas to get the spacing right, which would give us full + * speed _even_ in the worst case of a non-fixed-width font. + * However, Pango's architecture and documentation are so + * unhelpful that I have no idea how if at all to persuade + * them to do that. + */ if (combining) { /* @@ -1707,7 +1707,7 @@ static void pangofont_draw_internal(unifont_drawctx *ctx, unifont *font, */ while (clen < utflen) { int oldclen = clen; - clen++; /* skip UTF-8 introducer byte */ + clen++; /* skip UTF-8 introducer byte */ while (clen < utflen && (unsigned char)utfptr[clen] >= 0x80 && (unsigned char)utfptr[clen] < 0xC0) @@ -1725,21 +1725,21 @@ static void pangofont_draw_internal(unifont_drawctx *ctx, unifont *font, } } - pango_layout_set_text(layout, utfptr, clen); - pango_layout_get_pixel_extents(layout, NULL, &rect); - - draw_layout(ctx, + pango_layout_set_text(layout, utfptr, clen); + pango_layout_get_pixel_extents(layout, NULL, &rect); + + draw_layout(ctx, x + (n*cellwidth - rect.width)/2, y + (pfont->u.height - rect.height)/2, layout); - if (shadowbold) - draw_layout(ctx, + if (shadowbold) + draw_layout(ctx, x + (n*cellwidth - rect.width)/2 + pfont->shadowoffset, y + (pfont->u.height - rect.height)/2, layout); - utflen -= clen; - utfptr += clen; + utflen -= clen; + utfptr += clen; string += n; - x += n * cellwidth; + x += n * cellwidth; } sfree(utfstring); @@ -1786,7 +1786,7 @@ static void pangofont_draw_combining(unifont_drawctx *ctx, unifont *font, #define PANGO_DUMMY_SIZE 12 static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback, - void *callback_ctx) + void *callback_ctx) { PangoContext *ctx; #ifndef PANGO_PRE_1POINT6 @@ -1797,7 +1797,7 @@ static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback, ctx = gtk_widget_get_pango_context(widget); if (!ctx) - return; + return; /* * Ask Pango for a list of font families, and iterate through @@ -1806,62 +1806,62 @@ static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback, #ifndef PANGO_PRE_1POINT6 map = pango_context_get_font_map(ctx); if (!map) - return; + return; pango_font_map_list_families(map, &families, &nfamilies); #else pango_context_list_families(ctx, &families, &nfamilies); #endif for (i = 0; i < nfamilies; i++) { - PangoFontFamily *family = families[i]; - const char *familyname; - int flags; - PangoFontFace **faces; - int j, nfaces; + PangoFontFamily *family = families[i]; + const char *familyname; + int flags; + PangoFontFace **faces; + int j, nfaces; - /* - * Set up our flags for this font family, and get the name - * string. - */ - flags = FONTFLAG_CLIENTSIDE; + /* + * Set up our flags for this font family, and get the name + * string. + */ + flags = FONTFLAG_CLIENTSIDE; #ifndef PANGO_PRE_1POINT4 /* * In very early versions of Pango, we can't tell * monospaced fonts from non-monospaced. */ - if (!pango_font_family_is_monospace(family)) - flags |= FONTFLAG_NONMONOSPACED; + if (!pango_font_family_is_monospace(family)) + flags |= FONTFLAG_NONMONOSPACED; #endif - familyname = pango_font_family_get_name(family); + familyname = pango_font_family_get_name(family); - /* - * Go through the available font faces in this family. - */ - pango_font_family_list_faces(family, &faces, &nfaces); - for (j = 0; j < nfaces; j++) { - PangoFontFace *face = faces[j]; - PangoFontDescription *desc; - const char *facename; - int *sizes; - int k, nsizes, dummysize; + /* + * Go through the available font faces in this family. + */ + pango_font_family_list_faces(family, &faces, &nfaces); + for (j = 0; j < nfaces; j++) { + PangoFontFace *face = faces[j]; + PangoFontDescription *desc; + const char *facename; + int *sizes; + int k, nsizes, dummysize; - /* - * Get the face name string. - */ - facename = pango_font_face_get_face_name(face); + /* + * Get the face name string. + */ + facename = pango_font_face_get_face_name(face); - /* - * Set up a font description with what we've got so - * far. We'll fill in the size field manually and then - * call pango_font_description_to_string() to give the - * full real name of the specific font. - */ - desc = pango_font_face_describe(face); + /* + * Set up a font description with what we've got so + * far. We'll fill in the size field manually and then + * call pango_font_description_to_string() to give the + * full real name of the specific font. + */ + desc = pango_font_face_describe(face); - /* - * See if this font has a list of specific sizes. - */ + /* + * See if this font has a list of specific sizes. + */ #ifndef PANGO_PRE_1POINT4 - pango_font_face_list_sizes(face, &sizes, &nsizes); + pango_font_face_list_sizes(face, &sizes, &nsizes); #else /* * In early versions of Pango, that call wasn't @@ -1870,78 +1870,78 @@ static void pangofont_enum_fonts(GtkWidget *widget, fontsel_add_entry callback, */ sizes = NULL; #endif - if (!sizes) { - /* - * Write a single entry with a dummy size. - */ - dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE; - sizes = &dummysize; - nsizes = 1; - } + if (!sizes) { + /* + * Write a single entry with a dummy size. + */ + dummysize = PANGO_DUMMY_SIZE * PANGO_SCALE; + sizes = &dummysize; + nsizes = 1; + } - /* - * If so, go through them one by one. - */ - for (k = 0; k < nsizes; k++) { - char *fullname, *stylekey; + /* + * If so, go through them one by one. + */ + for (k = 0; k < nsizes; k++) { + char *fullname, *stylekey; - pango_font_description_set_size(desc, sizes[k]); + pango_font_description_set_size(desc, sizes[k]); - fullname = pango_font_description_to_string(desc); + fullname = pango_font_description_to_string(desc); - /* - * Construct the sorting key for font styles. - */ - { + /* + * Construct the sorting key for font styles. + */ + { strbuf *buf = strbuf_new(); - int weight = pango_font_description_get_weight(desc); - /* Weight: normal, then lighter, then bolder */ - if (weight <= PANGO_WEIGHT_NORMAL) - weight = PANGO_WEIGHT_NORMAL - weight; - strbuf_catf(buf, "%4d", weight); + int weight = pango_font_description_get_weight(desc); + /* Weight: normal, then lighter, then bolder */ + if (weight <= PANGO_WEIGHT_NORMAL) + weight = PANGO_WEIGHT_NORMAL - weight; + strbuf_catf(buf, "%4d", weight); - strbuf_catf(buf, " %2d", + strbuf_catf(buf, " %2d", pango_font_description_get_style(desc)); - int stretch = pango_font_description_get_stretch(desc); - /* Stretch: closer to normal sorts earlier */ - stretch = 2 * abs(PANGO_STRETCH_NORMAL - stretch) + - (stretch < PANGO_STRETCH_NORMAL); - strbuf_catf(buf, " %2d", stretch); + int stretch = pango_font_description_get_stretch(desc); + /* Stretch: closer to normal sorts earlier */ + stretch = 2 * abs(PANGO_STRETCH_NORMAL - stretch) + + (stretch < PANGO_STRETCH_NORMAL); + strbuf_catf(buf, " %2d", stretch); - strbuf_catf(buf, " %2d", + strbuf_catf(buf, " %2d", pango_font_description_get_variant(desc)); stylekey = strbuf_to_str(buf); - } + } - /* - * Got everything. Hand off to the callback. - * (The charset string is NULL, because only - * server-side X fonts use it.) - */ - callback(callback_ctx, fullname, familyname, NULL, facename, - stylekey, - (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])), - flags, &pangofont_vtable); + /* + * Got everything. Hand off to the callback. + * (The charset string is NULL, because only + * server-side X fonts use it.) + */ + callback(callback_ctx, fullname, familyname, NULL, facename, + stylekey, + (sizes == &dummysize ? 0 : PANGO_PIXELS(sizes[k])), + flags, &pangofont_vtable); sfree(stylekey); - g_free(fullname); - } - if (sizes != &dummysize) - g_free(sizes); + g_free(fullname); + } + if (sizes != &dummysize) + g_free(sizes); - pango_font_description_free(desc); - } - g_free(faces); + pango_font_description_free(desc); + } + g_free(faces); } g_free(families); } static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name, - int *size, int *flags, - bool resolve_aliases) + int *size, int *flags, + bool resolve_aliases) { /* * When given a Pango font name to try to make sense of for a @@ -1959,38 +1959,38 @@ static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name, desc = pango_font_description_from_string(name); if (!desc) - return NULL; + return NULL; ctx = gtk_widget_get_pango_context(widget); if (!ctx) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } if (!pangofont_check_desc_makes_sense(ctx, desc)) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } #ifndef PANGO_PRE_1POINT6 map = pango_context_get_font_map(ctx); if (!map) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } fset = pango_font_map_load_fontset(map, ctx, desc, - pango_context_get_language(ctx)); + pango_context_get_language(ctx)); #else fset = pango_context_load_fontset(ctx, desc, pango_context_get_language(ctx)); #endif if (!fset) { - pango_font_description_free(desc); - return NULL; + pango_font_description_free(desc); + return NULL; } metrics = pango_fontset_get_metrics(fset); if (!metrics || - pango_font_metrics_get_approximate_digit_width(metrics) == 0) { - pango_font_description_free(desc); - g_object_unref(fset); - return NULL; + pango_font_metrics_get_approximate_digit_width(metrics) == 0) { + pango_font_description_free(desc); + g_object_unref(fset); + return NULL; } *size = PANGO_PIXELS(pango_font_description_get_size(desc)); @@ -2008,14 +2008,14 @@ static char *pangofont_canonify_fontname(GtkWidget *widget, const char *name, } static char *pangofont_scale_fontname(GtkWidget *widget, const char *name, - int size) + int size) { PangoFontDescription *desc; char *newname, *retname; desc = pango_font_description_from_string(name); if (!desc) - return NULL; + return NULL; pango_font_description_set_size(desc, size * PANGO_SCALE); newname = pango_font_description_to_string(desc); retname = dupstr(newname); @@ -2080,11 +2080,11 @@ static const struct UnifontVtable *unifont_types[] = { * scheme prefix. Returns the tail of the font name suitable for * passing to individual font scheme functions, and also provides * a subrange of the unifont_types[] array above. - * + * * The return values `start' and `end' denote a half-open interval * in unifont_types[]; that is, the correct way to iterate over * them is - * + * * for (i = start; i < end; i++) {...} */ static const char *unifont_do_prefix(const char *name, int *start, int *end) @@ -2093,48 +2093,48 @@ static const char *unifont_do_prefix(const char *name, int *start, int *end) int i; if (name[colonpos]) { - /* - * There's a colon prefix on the font name. Use it to work - * out which subclass to use. - */ - for (i = 0; i < lenof(unifont_types); i++) { - if (strlen(unifont_types[i]->prefix) == colonpos && - !strncmp(unifont_types[i]->prefix, name, colonpos)) { - *start = i; - *end = i+1; - return name + colonpos + 1; - } - } - /* - * None matched, so return an empty scheme list to prevent - * any scheme from being called at all. - */ - *start = *end = 0; - return name + colonpos + 1; + /* + * There's a colon prefix on the font name. Use it to work + * out which subclass to use. + */ + for (i = 0; i < lenof(unifont_types); i++) { + if (strlen(unifont_types[i]->prefix) == colonpos && + !strncmp(unifont_types[i]->prefix, name, colonpos)) { + *start = i; + *end = i+1; + return name + colonpos + 1; + } + } + /* + * None matched, so return an empty scheme list to prevent + * any scheme from being called at all. + */ + *start = *end = 0; + return name + colonpos + 1; } else { - /* - * No colon prefix, so just use all the subclasses. - */ - *start = 0; - *end = lenof(unifont_types); - return name; + /* + * No colon prefix, so just use all the subclasses. + */ + *start = 0; + *end = lenof(unifont_types); + return name; } } unifont *unifont_create(GtkWidget *widget, const char *name, bool wide, - bool bold, int shadowoffset, bool shadowalways) + bool bold, int shadowoffset, bool shadowalways) { int i, start, end; name = unifont_do_prefix(name, &start, &end); for (i = start; i < end; i++) { - unifont *ret = unifont_types[i]->create(widget, name, wide, bold, - shadowoffset, shadowalways); - if (ret) - return ret; + unifont *ret = unifont_types[i]->create(widget, name, wide, bold, + shadowoffset, shadowalways); + if (ret) + return ret; } - return NULL; /* font not found in any scheme */ + return NULL; /* font not found in any scheme */ } void unifont_destroy(unifont *font) @@ -2143,8 +2143,8 @@ void unifont_destroy(unifont *font) } void unifont_draw_text(unifont_drawctx *ctx, unifont *font, - int x, int y, const wchar_t *string, int len, - bool wide, bool bold, int cellwidth) + int x, int y, const wchar_t *string, int len, + bool wide, bool bold, int cellwidth) { font->vt->draw_text(ctx, font, x, y, string, len, wide, bold, cellwidth); } @@ -2221,7 +2221,7 @@ unifont *multifont_create(GtkWidget *widget, const char *name, fallback = NULL; if (font->want_fallback) { - for (i = 0; i < lenof(unifont_types); i++) { + for (i = 0; i < lenof(unifont_types); i++) { if (unifont_types[i]->create_fallback) { fallback = unifont_types[i]->create_fallback (widget, font->height, wide, bold, @@ -2390,13 +2390,13 @@ static int strnullcasecmp(const char *a, const char *b) * the other one. */ if ((i = (!b) - (!a)) != 0) - return i; + return i; /* * NULL compares equal. */ if (!a) - return 0; + return 0; /* * Otherwise, ordinary strcasecmp. @@ -2411,10 +2411,10 @@ static int fontinfo_realname_compare(void *av, void *bv) int i; if ((i = strnullcasecmp(a->realname, b->realname)) != 0) - return i; + return i; if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK)) - return ((a->flags & FONTFLAG_SORT_MASK) < - (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); + return ((a->flags & FONTFLAG_SORT_MASK) < + (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); return 0; } @@ -2425,10 +2425,10 @@ static int fontinfo_realname_find(void *av, void *bv) int i; if ((i = strnullcasecmp(a->realname, b->realname)) != 0) - return i; + return i; if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK)) - return ((a->flags & FONTFLAG_SORT_MASK) < - (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); + return ((a->flags & FONTFLAG_SORT_MASK) < + (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); return 0; } @@ -2438,24 +2438,24 @@ static int fontinfo_selorder_compare(void *av, void *bv) fontinfo *b = (fontinfo *)bv; int i; if ((i = strnullcasecmp(a->family, b->family)) != 0) - return i; + return i; /* * Font class comes immediately after family, so that fonts * from different classes with the same family */ if ((a->flags & FONTFLAG_SORT_MASK) != (b->flags & FONTFLAG_SORT_MASK)) - return ((a->flags & FONTFLAG_SORT_MASK) < - (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); + return ((a->flags & FONTFLAG_SORT_MASK) < + (b->flags & FONTFLAG_SORT_MASK) ? -1 : +1); if ((i = strnullcasecmp(a->charset, b->charset)) != 0) - return i; + return i; if ((i = strnullcasecmp(a->stylekey, b->stylekey)) != 0) - return i; + return i; if ((i = strnullcasecmp(a->style, b->style)) != 0) - return i; + return i; if (a->size != b->size) - return (a->size < b->size ? -1 : +1); + return (a->size < b->size ? -1 : +1); if (a->index != b->index) - return (a->index < b->index ? -1 : +1); + return (a->index < b->index ? -1 : +1); return 0; } @@ -2490,39 +2490,39 @@ static void unifontsel_setup_familylist(unifontsel_internal *fs) * name to the list box. */ for (i = 0 ;; i++) { - info = (fontinfo *)index234(fs->fonts_by_selorder, i); - /* - * info may be NULL if we've just run off the end of the - * tree. We must still do a processing pass in that - * situation, in case we had an unfinished font record in - * progress. - */ - if (info && (info->flags &~ fs->filter_flags)) { - info->familyindex = -1; - continue; /* we're filtering out this font */ - } - if (!info || strnullcasecmp(currfamily, info->family) || - currflags != (info->flags & FONTFLAG_SORT_MASK)) { - /* - * We've either finished a family, or started a new - * one, or both. - */ - if (currfamily) { - gtk_list_store_append(fs->family_model, &iter); - gtk_list_store_set(fs->family_model, &iter, - 0, currfamily, 1, minpos, 2, maxpos+1, -1); - listindex++; - } - if (info) { - minpos = i; - currfamily = info->family; - currflags = info->flags & FONTFLAG_SORT_MASK; - } - } - if (!info) - break; /* now we're done */ - info->familyindex = listindex; - maxpos = i; + info = (fontinfo *)index234(fs->fonts_by_selorder, i); + /* + * info may be NULL if we've just run off the end of the + * tree. We must still do a processing pass in that + * situation, in case we had an unfinished font record in + * progress. + */ + if (info && (info->flags &~ fs->filter_flags)) { + info->familyindex = -1; + continue; /* we're filtering out this font */ + } + if (!info || strnullcasecmp(currfamily, info->family) || + currflags != (info->flags & FONTFLAG_SORT_MASK)) { + /* + * We've either finished a family, or started a new + * one, or both. + */ + if (currfamily) { + gtk_list_store_append(fs->family_model, &iter); + gtk_list_store_set(fs->family_model, &iter, + 0, currfamily, 1, minpos, 2, maxpos+1, -1); + listindex++; + } + if (info) { + minpos = i; + currfamily = info->family; + currflags = info->flags & FONTFLAG_SORT_MASK; + } + } + if (!info) + break; /* now we're done */ + info->familyindex = listindex; + maxpos = i; } /* @@ -2530,13 +2530,13 @@ static void unifontsel_setup_familylist(unifontsel_internal *fs) * deselect it thoroughly. */ if (fs->selected && fs->selected->familyindex < 0) - unifontsel_deselect(fs); + unifontsel_deselect(fs); fs->inhibit_response = false; } static void unifontsel_setup_stylelist(unifontsel_internal *fs, - int start, int end) + int start, int end) { GtkTreeIter iter; int i, listindex, minpos = -1, maxpos = -1; @@ -2554,58 +2554,58 @@ static void unifontsel_setup_stylelist(unifontsel_internal *fs, * and/or style name to the list box. */ for (i = start; i <= end; i++) { - if (i == end) - info = NULL; - else - info = (fontinfo *)index234(fs->fonts_by_selorder, i); - /* - * info may be NULL if we've just run off the end of the - * relevant data. We must still do a processing pass in - * that situation, in case we had an unfinished font - * record in progress. - */ - if (info && (info->flags &~ fs->filter_flags)) { - info->styleindex = -1; - continue; /* we're filtering out this font */ - } - if (!info || !started || strnullcasecmp(currcs, info->charset) || - strnullcasecmp(currstyle, info->style)) { - /* - * We've either finished a style/charset, or started a - * new one, or both. - */ - started = true; - if (currstyle) { - gtk_list_store_append(fs->style_model, &iter); - gtk_list_store_set(fs->style_model, &iter, - 0, currstyle, 1, minpos, 2, maxpos+1, - 3, true, 4, PANGO_WEIGHT_NORMAL, -1); - listindex++; - } - if (info) { - minpos = i; - if (info->charset && strnullcasecmp(currcs, info->charset)) { - gtk_list_store_append(fs->style_model, &iter); - gtk_list_store_set(fs->style_model, &iter, - 0, info->charset, 1, -1, 2, -1, - 3, false, 4, PANGO_WEIGHT_BOLD, -1); - listindex++; - } - currcs = info->charset; - currstyle = info->style; - } - } - if (!info) - break; /* now we're done */ - info->styleindex = listindex; - maxpos = i; + if (i == end) + info = NULL; + else + info = (fontinfo *)index234(fs->fonts_by_selorder, i); + /* + * info may be NULL if we've just run off the end of the + * relevant data. We must still do a processing pass in + * that situation, in case we had an unfinished font + * record in progress. + */ + if (info && (info->flags &~ fs->filter_flags)) { + info->styleindex = -1; + continue; /* we're filtering out this font */ + } + if (!info || !started || strnullcasecmp(currcs, info->charset) || + strnullcasecmp(currstyle, info->style)) { + /* + * We've either finished a style/charset, or started a + * new one, or both. + */ + started = true; + if (currstyle) { + gtk_list_store_append(fs->style_model, &iter); + gtk_list_store_set(fs->style_model, &iter, + 0, currstyle, 1, minpos, 2, maxpos+1, + 3, true, 4, PANGO_WEIGHT_NORMAL, -1); + listindex++; + } + if (info) { + minpos = i; + if (info->charset && strnullcasecmp(currcs, info->charset)) { + gtk_list_store_append(fs->style_model, &iter); + gtk_list_store_set(fs->style_model, &iter, + 0, info->charset, 1, -1, 2, -1, + 3, false, 4, PANGO_WEIGHT_BOLD, -1); + listindex++; + } + currcs = info->charset; + currstyle = info->style; + } + } + if (!info) + break; /* now we're done */ + info->styleindex = listindex; + maxpos = i; } } static const int unifontsel_default_sizes[] = { 10, 12, 14, 16, 20, 24, 32 }; static void unifontsel_setup_sizelist(unifontsel_internal *fs, - int start, int end) + int start, int end) { GtkTreeIter iter; int i, listindex; @@ -2621,32 +2621,32 @@ static void unifontsel_setup_sizelist(unifontsel_internal *fs, * name to the list box. */ for (i = start; i < end; i++) { - info = (fontinfo *)index234(fs->fonts_by_selorder, i); - if (info->flags &~ fs->filter_flags) { - info->sizeindex = -1; - continue; /* we're filtering out this font */ - } - if (info->size) { - sprintf(sizetext, "%d", info->size); - info->sizeindex = listindex; - gtk_list_store_append(fs->size_model, &iter); - gtk_list_store_set(fs->size_model, &iter, - 0, sizetext, 1, i, 2, info->size, -1); - listindex++; - } else { - int j; + info = (fontinfo *)index234(fs->fonts_by_selorder, i); + if (info->flags &~ fs->filter_flags) { + info->sizeindex = -1; + continue; /* we're filtering out this font */ + } + if (info->size) { + sprintf(sizetext, "%d", info->size); + info->sizeindex = listindex; + gtk_list_store_append(fs->size_model, &iter); + gtk_list_store_set(fs->size_model, &iter, + 0, sizetext, 1, i, 2, info->size, -1); + listindex++; + } else { + int j; - assert(i == start); - assert(i+1 == end); + assert(i == start); + assert(i+1 == end); - for (j = 0; j < lenof(unifontsel_default_sizes); j++) { - sprintf(sizetext, "%d", unifontsel_default_sizes[j]); - gtk_list_store_append(fs->size_model, &iter); - gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i, - 2, unifontsel_default_sizes[j], -1); - listindex++; - } - } + for (j = 0; j < lenof(unifontsel_default_sizes); j++) { + sprintf(sizetext, "%d", unifontsel_default_sizes[j]); + gtk_list_store_append(fs->size_model, &iter); + gtk_list_store_set(fs->size_model, &iter, 0, sizetext, 1, i, + 2, unifontsel_default_sizes[j], -1); + listindex++; + } + } } } @@ -2657,9 +2657,9 @@ static void unifontsel_set_filter_buttons(unifontsel_internal *fs) for (i = 0; i < fs->n_filter_buttons; i++) { int flagbit = GPOINTER_TO_INT(g_object_get_data (G_OBJECT(fs->filter_buttons[i]), - "user-data")); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]), - !!(fs->filter_flags & flagbit)); + "user-data")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fs->filter_buttons[i]), + !!(fs->filter_flags & flagbit)); } } @@ -2671,13 +2671,13 @@ static void unifontsel_draw_preview_text_inner(unifont_drawctx *dctx, fontinfo *info = fs->selected; if (info) { - sizename = info->fontclass->scale_fontname - (GTK_WIDGET(fs->u.window), info->realname, fs->selsize); - font = info->fontclass->create(GTK_WIDGET(fs->u.window), - sizename ? sizename : info->realname, - false, false, 0, 0); + sizename = info->fontclass->scale_fontname + (GTK_WIDGET(fs->u.window), info->realname, fs->selsize); + font = info->fontclass->create(GTK_WIDGET(fs->u.window), + sizename ? sizename : info->realname, + false, false, 0, 0); } else - font = NULL; + font = NULL; #ifdef DRAW_TEXT_GDK if (dctx->type == DRAWTYPE_GDK) { @@ -2748,7 +2748,7 @@ static void unifontsel_draw_preview_text_inner(unifont_drawctx *dctx, L"0123456789!?,.:;<>()[]{}\\/`'\"+*-=~#_@|%&^$", 42, false, false, font->width); - info->fontclass->destroy(font); + info->fontclass->destroy(font); } sfree(sizename); @@ -2818,8 +2818,8 @@ static void unifontsel_draw_preview_text(unifontsel_internal *fs) } static void unifontsel_select_font(unifontsel_internal *fs, - fontinfo *info, int size, int leftlist, - bool size_is_explicit) + fontinfo *info, int size, int leftlist, + bool size_is_explicit) { int index; int minval, maxval; @@ -2832,12 +2832,12 @@ static void unifontsel_select_font(unifontsel_internal *fs, fs->selected = info; fs->selsize = size; if (size_is_explicit) - fs->intendedsize = size; + fs->intendedsize = size; gtk_widget_set_sensitive(fs->u.ok_button, true); /* - * Find the index of this fontinfo in the selorder list. + * Find the index of this fontinfo in the selorder list. */ index = -1; findpos234(fs->fonts_by_selorder, info, NULL, &index); @@ -2848,10 +2848,10 @@ static void unifontsel_select_font(unifontsel_internal *fs, * list box, if necessary. */ if (leftlist <= 0 && - (fs->filter_flags | info->flags) != fs->filter_flags) { - fs->filter_flags |= info->flags; - unifontsel_set_filter_buttons(fs); - unifontsel_setup_familylist(fs); + (fs->filter_flags | info->flags) != fs->filter_flags) { + fs->filter_flags |= info->flags; + unifontsel_set_filter_buttons(fs); + unifontsel_setup_familylist(fs); } /* @@ -2860,10 +2860,10 @@ static void unifontsel_select_font(unifontsel_internal *fs, assert(info->familyindex >= 0); treepath = gtk_tree_path_new_from_indices(info->familyindex, -1); gtk_tree_selection_select_path - (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)), - treepath); + (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->family_list)), + treepath); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->family_list), - treepath, NULL, false, 0.0, 0.0); + treepath, NULL, false, 0.0, 0.0); success = gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, treepath); assert(success); @@ -2873,72 +2873,72 @@ static void unifontsel_select_font(unifontsel_internal *fs, * Now set up the font style list. */ gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, - 1, &minval, 2, &maxval, -1); + 1, &minval, 2, &maxval, -1); if (leftlist <= 1) - unifontsel_setup_stylelist(fs, minval, maxval); + unifontsel_setup_stylelist(fs, minval, maxval); /* * Find the appropriate style name and select it in the list. */ if (info->style) { - assert(info->styleindex >= 0); - treepath = gtk_tree_path_new_from_indices(info->styleindex, -1); - gtk_tree_selection_select_path - (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)), - treepath); - gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list), - treepath, NULL, false, 0.0, 0.0); - gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model), - &iter, treepath); - gtk_tree_path_free(treepath); + assert(info->styleindex >= 0); + treepath = gtk_tree_path_new_from_indices(info->styleindex, -1); + gtk_tree_selection_select_path + (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->style_list)), + treepath); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->style_list), + treepath, NULL, false, 0.0, 0.0); + gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->style_model), + &iter, treepath); + gtk_tree_path_free(treepath); - /* - * And set up the size list. - */ - gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter, - 1, &minval, 2, &maxval, -1); - if (leftlist <= 2) - unifontsel_setup_sizelist(fs, minval, maxval); + /* + * And set up the size list. + */ + gtk_tree_model_get(GTK_TREE_MODEL(fs->style_model), &iter, + 1, &minval, 2, &maxval, -1); + if (leftlist <= 2) + unifontsel_setup_sizelist(fs, minval, maxval); - /* - * Find the appropriate size, and select it in the list. - */ - if (info->size) { - assert(info->sizeindex >= 0); - treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1); - gtk_tree_selection_select_path - (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)), - treepath); - gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list), - treepath, NULL, false, 0.0, 0.0); - gtk_tree_path_free(treepath); - size = info->size; - } else { - int j; - for (j = 0; j < lenof(unifontsel_default_sizes); j++) - if (unifontsel_default_sizes[j] == size) { - treepath = gtk_tree_path_new_from_indices(j, -1); - gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list), - treepath, NULL, false); - gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list), - treepath, NULL, false, 0.0, - 0.0); - gtk_tree_path_free(treepath); - } - } + /* + * Find the appropriate size, and select it in the list. + */ + if (info->size) { + assert(info->sizeindex >= 0); + treepath = gtk_tree_path_new_from_indices(info->sizeindex, -1); + gtk_tree_selection_select_path + (gtk_tree_view_get_selection(GTK_TREE_VIEW(fs->size_list)), + treepath); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list), + treepath, NULL, false, 0.0, 0.0); + gtk_tree_path_free(treepath); + size = info->size; + } else { + int j; + for (j = 0; j < lenof(unifontsel_default_sizes); j++) + if (unifontsel_default_sizes[j] == size) { + treepath = gtk_tree_path_new_from_indices(j, -1); + gtk_tree_view_set_cursor(GTK_TREE_VIEW(fs->size_list), + treepath, NULL, false); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(fs->size_list), + treepath, NULL, false, 0.0, + 0.0); + gtk_tree_path_free(treepath); + } + } - /* - * And set up the font size text entry box. - */ - { - char sizetext[40]; - sprintf(sizetext, "%d", size); - gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext); - } + /* + * And set up the font size text entry box. + */ + { + char sizetext[40]; + sprintf(sizetext, "%d", size); + gtk_entry_set_text(GTK_ENTRY(fs->size_entry), sizetext); + } } else { - if (leftlist <= 2) - unifontsel_setup_sizelist(fs, 0, 0); - gtk_entry_set_text(GTK_ENTRY(fs->size_entry), ""); + if (leftlist <= 2) + unifontsel_setup_sizelist(fs, 0, 0); + gtk_entry_set_text(GTK_ENTRY(fs->size_entry), ""); } /* @@ -2963,21 +2963,21 @@ static void unifontsel_button_toggled(GtkToggleButton *tb, gpointer data) "user-data")); if (newstate) - newflags = fs->filter_flags | flagbit; + newflags = fs->filter_flags | flagbit; else - newflags = fs->filter_flags & ~flagbit; + newflags = fs->filter_flags & ~flagbit; if (fs->filter_flags != newflags) { - fs->filter_flags = newflags; - unifontsel_setup_familylist(fs); + fs->filter_flags = newflags; + unifontsel_setup_familylist(fs); } } static void unifontsel_add_entry(void *ctx, const char *realfontname, - const char *family, const char *charset, - const char *style, const char *stylekey, - int size, int flags, - const struct UnifontVtable *fontclass) + const char *family, const char *charset, + const char *style, const char *stylekey, + int size, int flags, + const struct UnifontVtable *fontclass) { unifontsel_internal *fs = (unifontsel_internal *)ctx; fontinfo *info; @@ -2985,8 +2985,8 @@ static void unifontsel_add_entry(void *ctx, const char *realfontname, char *p; totalsize = sizeof(fontinfo) + strlen(realfontname) + - (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) + - (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10; + (family ? strlen(family) : 0) + (charset ? strlen(charset) : 0) + + (style ? strlen(style) : 0) + (stylekey ? strlen(stylekey) : 0) + 10; info = (fontinfo *)smalloc(totalsize); info->fontclass = fontclass; p = (char *)info + sizeof(fontinfo); @@ -2994,29 +2994,29 @@ static void unifontsel_add_entry(void *ctx, const char *realfontname, strcpy(p, realfontname); p += 1+strlen(p); if (family) { - info->family = p; - strcpy(p, family); - p += 1+strlen(p); + info->family = p; + strcpy(p, family); + p += 1+strlen(p); } else - info->family = NULL; + info->family = NULL; if (charset) { - info->charset = p; - strcpy(p, charset); - p += 1+strlen(p); + info->charset = p; + strcpy(p, charset); + p += 1+strlen(p); } else - info->charset = NULL; + info->charset = NULL; if (style) { - info->style = p; - strcpy(p, style); - p += 1+strlen(p); + info->style = p; + strcpy(p, style); + p += 1+strlen(p); } else - info->style = NULL; + info->style = NULL; if (stylekey) { - info->stylekey = p; - strcpy(p, stylekey); - p += 1+strlen(p); + info->stylekey = p; + strcpy(p, stylekey); + p += 1+strlen(p); } else - info->stylekey = NULL; + info->stylekey = NULL; assert(p - (char *)info <= totalsize); info->size = size; info->flags = flags; @@ -3028,8 +3028,8 @@ static void unifontsel_add_entry(void *ctx, const char *realfontname, * in which case we should silently drop the new one. */ if (add234(fs->fonts_by_realname, info) != info) { - sfree(info); - return; + sfree(info); + return; } /* * However, we should never get a duplicate key in the @@ -3040,7 +3040,7 @@ static void unifontsel_add_entry(void *ctx, const char *realfontname, } static fontinfo *update_for_intended_size(unifontsel_internal *fs, - fontinfo *info) + fontinfo *info) { fontinfo info2, *below, *above; int pos; @@ -3059,7 +3059,7 @@ static fontinfo *update_for_intended_size(unifontsel_internal *fs, * best approximates the size the user last requested. */ below = findrelpos234(fs->fonts_by_selorder, &info2, NULL, - REL234_LE, &pos); + REL234_LE, &pos); if (!below) pos = -1; above = index234(fs->fonts_by_selorder, pos+1); @@ -3070,7 +3070,7 @@ static fontinfo *update_for_intended_size(unifontsel_internal *fs, * because we did a REL234_LE rather than REL234_LT search. */ if (below && !fontinfo_selorder_compare(&info2, below)) - return below; + return below; /* * Now we've either found two suitable fonts, one smaller and @@ -3082,16 +3082,16 @@ static fontinfo *update_for_intended_size(unifontsel_internal *fs, * extreme ends of the font list. */ if (below) { - info2.size = below->size; - info2.index = below->index; - if (fontinfo_selorder_compare(&info2, below)) - below = NULL; + info2.size = below->size; + info2.index = below->index; + if (fontinfo_selorder_compare(&info2, below)) + below = NULL; } if (above) { - info2.size = above->size; - info2.index = above->index; - if (fontinfo_selorder_compare(&info2, above)) - above = NULL; + info2.size = above->size; + info2.index = above->index; + if (fontinfo_selorder_compare(&info2, above)) + above = NULL; } /* @@ -3099,9 +3099,9 @@ static fontinfo *update_for_intended_size(unifontsel_internal *fs, * that's unambiguous. */ if (!above) - return below; + return below; if (!below) - return above; + return above; /* * And now we really do have to make a choice about whether to @@ -3109,9 +3109,9 @@ static fontinfo *update_for_intended_size(unifontsel_internal *fs, * breaking ties by rounding up. */ if (above->size - fs->intendedsize <= fs->intendedsize - below->size) - return above; + return above; else - return below; + return below; } static void family_changed(GtkTreeSelection *treeselection, gpointer data) @@ -3122,21 +3122,21 @@ static void family_changed(GtkTreeSelection *treeselection, gpointer data) int minval; fontinfo *info; - if (fs->inhibit_response) /* we made this change ourselves */ - return; + if (fs->inhibit_response) /* we made this change ourselves */ + return; if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter)) - return; + return; gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1); info = (fontinfo *)index234(fs->fonts_by_selorder, minval); info = update_for_intended_size(fs, info); if (!info) - return; /* _shouldn't_ happen unless font list is completely funted */ + return; /* _shouldn't_ happen unless font list is completely funted */ if (!info->size) - fs->selsize = fs->intendedsize; /* font is scalable */ + fs->selsize = fs->intendedsize; /* font is scalable */ unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize, - 1, false); + 1, false); } static void style_changed(GtkTreeSelection *treeselection, gpointer data) @@ -3147,11 +3147,11 @@ static void style_changed(GtkTreeSelection *treeselection, gpointer data) int minval; fontinfo *info; - if (fs->inhibit_response) /* we made this change ourselves */ - return; + if (fs->inhibit_response) /* we made this change ourselves */ + return; if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter)) - return; + return; gtk_tree_model_get(treemodel, &treeiter, 1, &minval, -1); if (minval < 0) @@ -3159,11 +3159,11 @@ static void style_changed(GtkTreeSelection *treeselection, gpointer data) info = (fontinfo *)index234(fs->fonts_by_selorder, minval); info = update_for_intended_size(fs, info); if (!info) - return; /* _shouldn't_ happen unless font list is completely funted */ + return; /* _shouldn't_ happen unless font list is completely funted */ if (!info->size) - fs->selsize = fs->intendedsize; /* font is scalable */ + fs->selsize = fs->intendedsize; /* font is scalable */ unifontsel_select_font(fs, info, info->size ? info->size : fs->selsize, - 2, false); + 2, false); } static void size_changed(GtkTreeSelection *treeselection, gpointer data) @@ -3174,11 +3174,11 @@ static void size_changed(GtkTreeSelection *treeselection, gpointer data) int minval, size; fontinfo *info; - if (fs->inhibit_response) /* we made this change ourselves */ - return; + if (fs->inhibit_response) /* we made this change ourselves */ + return; if (!gtk_tree_selection_get_selected(treeselection, &treemodel, &treeiter)) - return; + return; gtk_tree_model_get(treemodel, &treeiter, 1, &minval, 2, &size, -1); info = (fontinfo *)index234(fs->fonts_by_selorder, minval); @@ -3191,20 +3191,20 @@ static void size_entry_changed(GtkEditable *ed, gpointer data) const char *text; int size; - if (fs->inhibit_response) /* we made this change ourselves */ - return; + if (fs->inhibit_response) /* we made this change ourselves */ + return; text = gtk_entry_get_text(GTK_ENTRY(ed)); size = atoi(text); if (size > 0) { - assert(fs->selected->size == 0); - unifontsel_select_font(fs, fs->selected, size, 3, true); + assert(fs->selected->size == 0); + unifontsel_select_font(fs, fs->selected, size, 3, true); } } static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path, - GtkTreeViewColumn *column, gpointer data) + GtkTreeViewColumn *column, gpointer data) { unifontsel_internal *fs = (unifontsel_internal *)data; GtkTreeIter iter; @@ -3212,31 +3212,31 @@ static void alias_resolve(GtkTreeView *treeview, GtkTreePath *path, fontinfo *info, *newinfo; char *newname; - if (fs->inhibit_response) /* we made this change ourselves */ - return; + if (fs->inhibit_response) /* we made this change ourselves */ + return; gtk_tree_model_get_iter(GTK_TREE_MODEL(fs->family_model), &iter, path); gtk_tree_model_get(GTK_TREE_MODEL(fs->family_model), &iter, 1,&minval, -1); info = (fontinfo *)index234(fs->fonts_by_selorder, minval); if (info) { - int flags; - struct fontinfo_realname_find f; + int flags; + struct fontinfo_realname_find f; - newname = info->fontclass->canonify_fontname - (GTK_WIDGET(fs->u.window), info->realname, &newsize, &flags, true); + newname = info->fontclass->canonify_fontname + (GTK_WIDGET(fs->u.window), info->realname, &newsize, &flags, true); - f.realname = newname; - f.flags = flags; - newinfo = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); + f.realname = newname; + f.flags = flags; + newinfo = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); - sfree(newname); - if (!newinfo) - return; /* font name not in our index */ - if (newinfo == info) - return; /* didn't change under canonification => not an alias */ - unifontsel_select_font(fs, newinfo, - newinfo->size ? newinfo->size : newsize, - 1, true); + sfree(newname); + if (!newinfo) + return; /* font name not in our index */ + if (newinfo == info) + return; /* didn't change under canonification => not an alias */ + unifontsel_select_font(fs, newinfo, + newinfo->size ? newinfo->size : newsize, + 1, true); } } @@ -3255,19 +3255,19 @@ static gint unifontsel_draw_area(GtkWidget *widget, cairo_t *cr, gpointer data) } #else static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event, - gpointer data) + gpointer data) { unifontsel_internal *fs = (unifontsel_internal *)data; #ifndef NO_BACKING_PIXMAPS if (fs->preview_pixmap) { gdk_draw_pixmap(gtk_widget_get_window(widget), - (gtk_widget_get_style(widget)->fg_gc + (gtk_widget_get_style(widget)->fg_gc [gtk_widget_get_state(widget)]), - fs->preview_pixmap, - event->area.x, event->area.y, - event->area.x, event->area.y, - event->area.width, event->area.height); + fs->preview_pixmap, + event->area.x, event->area.y, + event->area.x, event->area.y, + event->area.width, event->area.height); } #else unifontsel_draw_preview_text(fs); @@ -3278,7 +3278,7 @@ static gint unifontsel_expose_area(GtkWidget *widget, GdkEventExpose *event, #endif static gint unifontsel_configure_area(GtkWidget *widget, - GdkEventConfigure *event, gpointer data) + GdkEventConfigure *event, gpointer data) { #ifndef NO_BACKING_PIXMAPS unifontsel_internal *fs = (unifontsel_internal *)data; @@ -3292,17 +3292,17 @@ static gint unifontsel_configure_area(GtkWidget *widget, x = event->width; y = event->height; if (x > ox || y > oy) { - if (fs->preview_pixmap) - gdk_pixmap_unref(fs->preview_pixmap); - - nx = (x > ox ? x : ox); - ny = (y > oy ? y : oy); - fs->preview_pixmap = gdk_pixmap_new(gtk_widget_get_window(widget), - nx, ny, -1); - fs->preview_width = nx; - fs->preview_height = ny; + if (fs->preview_pixmap) + gdk_pixmap_unref(fs->preview_pixmap); - unifontsel_draw_preview_text(fs); + nx = (x > ox ? x : ox); + ny = (y > oy ? y : oy); + fs->preview_pixmap = gdk_pixmap_new(gtk_widget_get_window(widget), + nx, ny, -1); + fs->preview_width = nx; + fs->preview_height = ny; + + unifontsel_draw_preview_text(fs); } #endif @@ -3326,20 +3326,20 @@ unifontsel *unifontsel_new(const char *wintitle) { int width, height; - /* - * Invent some magic size constants. - */ - get_label_text_dimensions("Quite Long Font Name (Foundry)", + /* + * Invent some magic size constants. + */ + get_label_text_dimensions("Quite Long Font Name (Foundry)", &width, &height); - font_width = width; - lists_height = 14 * height; - preview_height = 5 * height; + font_width = width; + lists_height = 14 * height; + preview_height = 5 * height; - get_label_text_dimensions("Italic Extra Condensed", &width, &height); - style_width = width; + get_label_text_dimensions("Italic Extra Condensed", &width, &height); + style_width = width; - get_label_text_dimensions("48000", &width, &height); - size_width = width; + get_label_text_dimensions("48000", &width, &height); + size_width = width; } /* @@ -3350,9 +3350,9 @@ unifontsel *unifontsel_new(const char *wintitle) fs->u.window = GTK_WINDOW(gtk_dialog_new()); gtk_window_set_title(fs->u.window, wintitle); fs->u.cancel_button = gtk_dialog_add_button - (GTK_DIALOG(fs->u.window), STANDARD_CANCEL_LABEL, GTK_RESPONSE_CANCEL); + (GTK_DIALOG(fs->u.window), STANDARD_CANCEL_LABEL, GTK_RESPONSE_CANCEL); fs->u.ok_button = gtk_dialog_add_button - (GTK_DIALOG(fs->u.window), STANDARD_OK_LABEL, GTK_RESPONSE_OK); + (GTK_DIALOG(fs->u.window), STANDARD_OK_LABEL, GTK_RESPONSE_OK); gtk_widget_grab_default(fs->u.ok_button); /* @@ -3386,7 +3386,7 @@ unifontsel *unifontsel_new(const char *wintitle) gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area (GTK_DIALOG(fs->u.window))), - w, true, true, 0); + w, true, true, 0); label = gtk_label_new_with_mnemonic("_Font:"); gtk_widget_show(label); @@ -3409,29 +3409,29 @@ unifontsel *unifontsel_new(const char *wintitle) gtk_label_set_mnemonic_widget(GTK_LABEL(label), w); gtk_widget_show(w); column = gtk_tree_view_column_new_with_attributes - ("Font", gtk_cell_renderer_text_new(), - "text", 0, (char *)NULL); + ("Font", gtk_cell_renderer_text_new(), + "text", 0, (char *)NULL); gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_append_column(GTK_TREE_VIEW(w), column); g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))), - "changed", G_CALLBACK(family_changed), fs); + "changed", G_CALLBACK(family_changed), fs); g_signal_connect(G_OBJECT(w), "row-activated", - G_CALLBACK(alias_resolve), fs); + G_CALLBACK(alias_resolve), fs); scroll = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll), - GTK_SHADOW_IN); + GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(scroll), w); gtk_widget_show(scroll); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), - GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); gtk_widget_set_size_request(scroll, font_width, lists_height); #if GTK_CHECK_VERSION(3,0,0) gtk_grid_attach(GTK_GRID(table), scroll, 0, 1, 1, 2); g_object_set(G_OBJECT(scroll), "expand", true, (const char *)NULL); #else gtk_table_attach(GTK_TABLE(table), scroll, 0, 1, 1, 3, GTK_FILL, - GTK_EXPAND | GTK_FILL, 0, 0); + GTK_EXPAND | GTK_FILL, 0, 0); #endif fs->family_model = model; fs->family_list = w; @@ -3454,33 +3454,33 @@ unifontsel *unifontsel_new(const char *wintitle) * by default, we add a further column to change their style. */ model = gtk_list_store_new(5, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT, - G_TYPE_BOOLEAN, G_TYPE_INT); + G_TYPE_BOOLEAN, G_TYPE_INT); w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model)); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), false); gtk_label_set_mnemonic_widget(GTK_LABEL(label), w); gtk_widget_show(w); column = gtk_tree_view_column_new_with_attributes - ("Style", gtk_cell_renderer_text_new(), - "text", 0, "sensitive", 3, "weight", 4, (char *)NULL); + ("Style", gtk_cell_renderer_text_new(), + "text", 0, "sensitive", 3, "weight", 4, (char *)NULL); gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_append_column(GTK_TREE_VIEW(w), column); g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))), - "changed", G_CALLBACK(style_changed), fs); + "changed", G_CALLBACK(style_changed), fs); scroll = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll), - GTK_SHADOW_IN); + GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(scroll), w); gtk_widget_show(scroll); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), - GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); gtk_widget_set_size_request(scroll, style_width, lists_height); #if GTK_CHECK_VERSION(3,0,0) gtk_grid_attach(GTK_GRID(table), scroll, 1, 1, 1, 2); g_object_set(G_OBJECT(scroll), "expand", true, (const char *)NULL); #else gtk_table_attach(GTK_TABLE(table), scroll, 1, 2, 1, 3, GTK_FILL, - GTK_EXPAND | GTK_FILL, 0, 0); + GTK_EXPAND | GTK_FILL, 0, 0); #endif fs->style_model = model; fs->style_list = w; @@ -3511,33 +3511,33 @@ unifontsel *unifontsel_new(const char *wintitle) gtk_table_attach(GTK_TABLE(table), w, 2, 3, 1, 2, GTK_FILL, 0, 0, 0); #endif g_signal_connect(G_OBJECT(w), "changed", G_CALLBACK(size_entry_changed), - fs); + fs); model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT); w = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model)); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(w), false); gtk_widget_show(w); column = gtk_tree_view_column_new_with_attributes - ("Size", gtk_cell_renderer_text_new(), - "text", 0, (char *)NULL); + ("Size", gtk_cell_renderer_text_new(), + "text", 0, (char *)NULL); gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_append_column(GTK_TREE_VIEW(w), column); g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(w))), - "changed", G_CALLBACK(size_changed), fs); + "changed", G_CALLBACK(size_changed), fs); scroll = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll), - GTK_SHADOW_IN); + GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(scroll), w); gtk_widget_show(scroll); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), - GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); + GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS); #if GTK_CHECK_VERSION(3,0,0) gtk_grid_attach(GTK_GRID(table), scroll, 2, 2, 1, 1); g_object_set(G_OBJECT(scroll), "expand", true, (const char *)NULL); #else gtk_table_attach(GTK_TABLE(table), scroll, 2, 3, 2, 3, GTK_FILL, - GTK_EXPAND | GTK_FILL, 0, 0); + GTK_EXPAND | GTK_FILL, 0, 0); #endif fs->size_model = model; fs->size_list = w; @@ -3556,9 +3556,9 @@ unifontsel *unifontsel_new(const char *wintitle) fs->preview_bg.red = fs->preview_bg.green = fs->preview_bg.blue = 0xFFFF; #if !GTK_CHECK_VERSION(3,0,0) gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_fg, - false, false); + false, false); gdk_colormap_alloc_color(gdk_colormap_get_system(), &fs->preview_bg, - false, false); + false, false); #endif #if GTK_CHECK_VERSION(3,0,0) g_signal_connect(G_OBJECT(fs->preview_area), "draw", @@ -3598,7 +3598,7 @@ unifontsel *unifontsel_new(const char *wintitle) g_object_set(G_OBJECT(w), "expand", true, (const char *)NULL); #else gtk_table_attach(GTK_TABLE(table), w, 0, 3, 3, 4, - GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 8); + GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 8); #endif /* @@ -3665,7 +3665,7 @@ unifontsel *unifontsel_new(const char *wintitle) assert(fs->n_filter_buttons <= lenof(fs->filter_buttons)); fs->filter_flags = FONTFLAG_CLIENTSIDE | FONTFLAG_SERVERSIDE | - FONTFLAG_SERVERALIAS; + FONTFLAG_SERVERALIAS; unifontsel_set_filter_buttons(fs); /* @@ -3675,8 +3675,8 @@ unifontsel *unifontsel_new(const char *wintitle) fs->fonts_by_realname = newtree234(fontinfo_realname_compare); fs->fonts_by_selorder = newtree234(fontinfo_selorder_compare); for (i = 0; i < lenof(unifont_types); i++) - unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window), - unifontsel_add_entry, fs); + unifont_types[i]->enum_fonts(GTK_WIDGET(fs->u.window), + unifontsel_add_entry, fs); /* * And set up the initial font names list. @@ -3696,12 +3696,12 @@ void unifontsel_destroy(unifontsel *fontsel) #ifndef NO_BACKING_PIXMAPS if (fs->preview_pixmap) - gdk_pixmap_unref(fs->preview_pixmap); + gdk_pixmap_unref(fs->preview_pixmap); #endif freetree234(fs->fonts_by_selorder); while ((info = delpos234(fs->fonts_by_realname, 0)) != NULL) - sfree(info); + sfree(info); freetree234(fs->fonts_by_realname); gtk_widget_destroy(GTK_WIDGET(fs->u.window)); @@ -3719,29 +3719,29 @@ void unifontsel_set_name(unifontsel *fontsel, const char *fontname) * Provide a default if given an empty or null font name. */ if (!fontname || !*fontname) - fontname = DEFAULT_GTK_FONT; + fontname = DEFAULT_GTK_FONT; /* * Call the canonify_fontname function. */ fontname = unifont_do_prefix(fontname, &start, &end); for (i = start; i < end; i++) { - fontname2 = unifont_types[i]->canonify_fontname - (GTK_WIDGET(fs->u.window), fontname, &size, &flags, false); - if (fontname2) - break; + fontname2 = unifont_types[i]->canonify_fontname + (GTK_WIDGET(fs->u.window), fontname, &size, &flags, false); + if (fontname2) + break; } if (i == end) - return; /* font name not recognised */ + return; /* font name not recognised */ /* * Now look up the canonified font name in our index. */ { - struct fontinfo_realname_find f; - f.realname = fontname2; - f.flags = flags; - info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); + struct fontinfo_realname_find f; + f.realname = fontname2; + f.flags = flags; + info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); } /* @@ -3751,13 +3751,13 @@ void unifontsel_set_name(unifontsel *fontsel, const char *fontname) * font name instead. */ if (!info || (info->size != size && info->size != 0)) { - struct fontinfo_realname_find f; - f.realname = fontname; - f.flags = flags; + struct fontinfo_realname_find f; + f.realname = fontname; + f.flags = flags; - info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); - if (!info || info->size != size) - return; /* font name not in our index */ + info = find234(fs->fonts_by_realname, &f, fontinfo_realname_find); + if (!info || info->size != size) + return; /* font name not in our index */ } /* @@ -3774,21 +3774,21 @@ char *unifontsel_get_name(unifontsel *fontsel) char *name; if (!fs->selected) - return NULL; + return NULL; if (fs->selected->size == 0) { - name = fs->selected->fontclass->scale_fontname - (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize); - if (name) { - char *ret = dupcat(fs->selected->fontclass->prefix, ":", - name, NULL); - sfree(name); - return ret; - } + name = fs->selected->fontclass->scale_fontname + (GTK_WIDGET(fs->u.window), fs->selected->realname, fs->selsize); + if (name) { + char *ret = dupcat(fs->selected->fontclass->prefix, ":", + name, NULL); + sfree(name); + return ret; + } } return dupcat(fs->selected->fontclass->prefix, ":", - fs->selected->realname, NULL); + fs->selected->realname, NULL); } #endif /* GTK_CHECK_VERSION(2,0,0) */ diff --git a/unix/gtkfont.h b/unix/gtkfont.h index ff91929e..5b70a3f0 100644 --- a/unix/gtkfont.h +++ b/unix/gtkfont.h @@ -49,7 +49,7 @@ /* * Exports from gtkfont.c. */ -struct UnifontVtable; /* contents internal to gtkfont.c */ +struct UnifontVtable; /* contents internal to gtkfont.c */ typedef struct unifont { const struct UnifontVtable *vt; /* @@ -134,8 +134,8 @@ typedef struct unifont_drawctx { } unifont_drawctx; unifont *unifont_create(GtkWidget *widget, const char *name, - bool wide, bool bold, - int shadowoffset, bool shadowalways); + bool wide, bool bold, + int shadowoffset, bool shadowalways); void unifont_destroy(unifont *font); void unifont_draw_text(unifont_drawctx *ctx, unifont *font, int x, int y, const wchar_t *string, int len, @@ -166,13 +166,13 @@ unifont *multifont_create(GtkWidget *widget, const char *name, * Unified font selector dialog. I can't be bothered to do a * proper GTK subclassing today, so this will just be an ordinary * data structure with some useful members. - * + * * (Of course, these aren't the only members; this structure is * contained within a bigger one which holds data visible only to * the implementation.) */ typedef struct unifontsel { - void *user_data; /* settable by the user */ + void *user_data; /* settable by the user */ GtkWindow *window; GtkWidget *ok_button, *cancel_button; } unifontsel; diff --git a/unix/gtkmain.c b/unix/gtkmain.c index f687e76f..520cd6ee 100644 --- a/unix/gtkmain.c +++ b/unix/gtkmain.c @@ -67,7 +67,7 @@ void fork_and_exec_self(int fd_to_close, ...) * Re-execing ourself is not an exact science under Unix. I do * the best I can by using /proc/self/exe if available and by * assuming argv[0] can be found on $PATH if not. - * + * * Note that we also have to reconstruct the elements of the * original argv which gtk swallowed, since the user wants the * new session to appear on the same X display as the old one. @@ -81,17 +81,17 @@ void fork_and_exec_self(int fd_to_close, ...) * Collect the arguments with which to re-exec ourself. */ va_start(ap, fd_to_close); - n = 2; /* progname and terminating NULL */ + n = 2; /* progname and terminating NULL */ n += ngtkargs; while (va_arg(ap, char *) != NULL) - n++; + n++; va_end(ap); args = snewn(n, char *); args[0] = progname; args[n-1] = NULL; for (i = 0; i < ngtkargs; i++) - args[i+1] = gtkargvstart[i]; + args[i+1] = gtkargvstart[i]; i++; va_start(ap, fd_to_close); @@ -105,43 +105,43 @@ void fork_and_exec_self(int fd_to_close, ...) */ pid = fork(); if (pid < 0) { - perror("fork"); + perror("fork"); sfree(args); - return; + return; } if (pid == 0) { - int pid2 = fork(); - if (pid2 < 0) { - perror("fork"); - _exit(1); - } else if (pid2 > 0) { - /* - * First child has successfully forked second child. My - * Work Here Is Done. Note the use of _exit rather than - * exit: the latter appears to cause destroy messages - * to be sent to the X server. I suspect gtk uses - * atexit. - */ - _exit(0); - } + int pid2 = fork(); + if (pid2 < 0) { + perror("fork"); + _exit(1); + } else if (pid2 > 0) { + /* + * First child has successfully forked second child. My + * Work Here Is Done. Note the use of _exit rather than + * exit: the latter appears to cause destroy messages + * to be sent to the X server. I suspect gtk uses + * atexit. + */ + _exit(0); + } - /* - * If we reach here, we are the second child, so we now - * actually perform the exec. - */ - if (fd_to_close >= 0) - close(fd_to_close); + /* + * If we reach here, we are the second child, so we now + * actually perform the exec. + */ + if (fd_to_close >= 0) + close(fd_to_close); - execv("/proc/self/exe", args); - execvp(progname, args); - perror("exec"); - _exit(127); + execv("/proc/self/exe", args); + execvp(progname, args); + perror("exec"); + _exit(127); } else { - int status; + int status; sfree(args); - waitpid(pid, &status, 0); + waitpid(pid, &status, 0); } } @@ -159,15 +159,15 @@ void launch_duplicate_session(Conf *conf) int pipefd[2]; if (pipe(pipefd) < 0) { - perror("pipe"); - return; + perror("pipe"); + return; } serialised = strbuf_new(); conf_serialise(BinarySink_UPCAST(serialised), conf); if (use_pty_argv && pty_argv) - for (i = 0; pty_argv[i]; i++) + for (i = 0; pty_argv[i]; i++) put_asciz(serialised, pty_argv[i]); sprintf(option, "---[%d,%zu]", pipefd[0], serialised->len); @@ -179,9 +179,9 @@ void launch_duplicate_session(Conf *conf) while (i < serialised->len && (ret = write(pipefd[1], serialised->s + i, serialised->len - i)) > 0) - i += ret; + i += ret; if (ret < 0) - perror("write to pipe"); + perror("write to pipe"); close(pipefd[1]); strbuf_free(serialised); } @@ -203,21 +203,21 @@ int read_dupsession_data(Conf *conf, char *arg) BinarySource src[1]; if (sscanf(arg, "---[%d,%d]", &fd, &size) != 2) { - fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg); - exit(1); + fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg); + exit(1); } data = snewn(size, char); i = ret = 0; while (i < size && (ret = read(fd, data + i, size - i)) > 0) - i += ret; + i += ret; if (ret < 0) { - perror("read from pipe"); - exit(1); + perror("read from pipe"); + exit(1); } else if (i < size) { - fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n", - appname); - exit(1); + fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n", + appname); + exit(1); } BinarySource_BARE_INIT(src, data, size); @@ -226,7 +226,7 @@ int read_dupsession_data(Conf *conf, char *arg) exit(1); } if (use_pty_argv) { - int pty_argc = 0; + int pty_argc = 0; size_t argv_startpos = src->pos; while (get_asciz(src), !get_err(src)) @@ -274,9 +274,9 @@ static void help(FILE *fp) { " -nethack Map numeric keypad to hjklyubn direction keys\n" " -xrm RESOURCE-STRING Set an X resource\n" " -e COMMAND [ARGS...] Execute command (consumes all remaining args)\n" - ) < 0 || fflush(fp) < 0) { - perror("output error"); - exit(1); + ) < 0 || fflush(fp) < 0) { + perror("output error"); + exit(1); } } @@ -284,8 +284,8 @@ static void version(FILE *fp) { char *buildinfo_text = buildinfo("\n"); if(fprintf(fp, "%s: %s\n%s\n", appname, ver, buildinfo_text) < 0 || fflush(fp) < 0) { - perror("output error"); - exit(1); + perror("output error"); + exit(1); } sfree(buildinfo_text); } @@ -324,92 +324,92 @@ bool do_cmdline(int argc, char **argv, bool do_everything, Conf *conf) */ #define EXPECTS_ARG { \ if (--argc <= 0) { \ - err = true; \ - fprintf(stderr, "%s: %s expects an argument\n", appname, p); \ + err = true; \ + fprintf(stderr, "%s: %s expects an argument\n", appname, p); \ continue; \ } else \ - val = *++argv; \ + val = *++argv; \ } #define SECOND_PASS_ONLY do { if (!do_everything) continue; } while (0) while (--argc > 0) { - const char *p = *++argv; + const char *p = *++argv; int ret; - /* - * Shameless cheating. Debian requires all X terminal - * emulators to support `-T title'; but - * cmdline_process_param will eat -T (it means no-pty) and - * complain that pterm doesn't support it. So, in pterm - * only, we convert -T into -title. - */ - if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) && - !strcmp(p, "-T")) - p = "-title"; + /* + * Shameless cheating. Debian requires all X terminal + * emulators to support `-T title'; but + * cmdline_process_param will eat -T (it means no-pty) and + * complain that pterm doesn't support it. So, in pterm + * only, we convert -T into -title. + */ + if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) && + !strcmp(p, "-T")) + p = "-title"; ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), do_everything ? 1 : -1, conf); - if (ret == -2) { - cmdline_error("option \"%s\" requires an argument", p); - } else if (ret == 2) { - --argc, ++argv; /* skip next argument */ + if (ret == -2) { + cmdline_error("option \"%s\" requires an argument", p); + } else if (ret == 2) { + --argc, ++argv; /* skip next argument */ continue; - } else if (ret == 1) { + } else if (ret == 1) { continue; } - if (!strcmp(p, "-fn") || !strcmp(p, "-font")) { - FontSpec *fs; - EXPECTS_ARG; - SECOND_PASS_ONLY; + if (!strcmp(p, "-fn") || !strcmp(p, "-font")) { + FontSpec *fs; + EXPECTS_ARG; + SECOND_PASS_ONLY; fs = fontspec_new(val); - conf_set_fontspec(conf, CONF_font, fs); + conf_set_fontspec(conf, CONF_font, fs); fontspec_free(fs); - } else if (!strcmp(p, "-fb")) { - FontSpec *fs; - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-fb")) { + FontSpec *fs; + EXPECTS_ARG; + SECOND_PASS_ONLY; fs = fontspec_new(val); - conf_set_fontspec(conf, CONF_boldfont, fs); + conf_set_fontspec(conf, CONF_boldfont, fs); fontspec_free(fs); - } else if (!strcmp(p, "-fw")) { - FontSpec *fs; - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-fw")) { + FontSpec *fs; + EXPECTS_ARG; + SECOND_PASS_ONLY; fs = fontspec_new(val); - conf_set_fontspec(conf, CONF_widefont, fs); + conf_set_fontspec(conf, CONF_widefont, fs); fontspec_free(fs); - } else if (!strcmp(p, "-fwb")) { - FontSpec *fs; - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-fwb")) { + FontSpec *fs; + EXPECTS_ARG; + SECOND_PASS_ONLY; fs = fontspec_new(val); - conf_set_fontspec(conf, CONF_wideboldfont, fs); + conf_set_fontspec(conf, CONF_wideboldfont, fs); fontspec_free(fs); - } else if (!strcmp(p, "-cs")) { - EXPECTS_ARG; - SECOND_PASS_ONLY; - conf_set_str(conf, CONF_line_codepage, val); + } else if (!strcmp(p, "-cs")) { + EXPECTS_ARG; + SECOND_PASS_ONLY; + conf_set_str(conf, CONF_line_codepage, val); - } else if (!strcmp(p, "-geometry")) { - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-geometry")) { + EXPECTS_ARG; + SECOND_PASS_ONLY; geometry_string = val; - } else if (!strcmp(p, "-sl")) { - EXPECTS_ARG; - SECOND_PASS_ONLY; - conf_set_int(conf, CONF_savelines, atoi(val)); + } else if (!strcmp(p, "-sl")) { + EXPECTS_ARG; + SECOND_PASS_ONLY; + conf_set_int(conf, CONF_savelines, atoi(val)); - } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") || - !strcmp(p, "-bfg") || !strcmp(p, "-bbg") || - !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) { - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") || + !strcmp(p, "-bfg") || !strcmp(p, "-bbg") || + !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) { + EXPECTS_ARG; + SECOND_PASS_ONLY; { #if GTK_CHECK_VERSION(3,0,0) @@ -450,86 +450,86 @@ bool do_cmdline(int argc, char **argv, bool do_everything, Conf *conf) } } - } else if (use_pty_argv && !strcmp(p, "-e")) { - /* This option swallows all further arguments. */ - if (!do_everything) - break; + } else if (use_pty_argv && !strcmp(p, "-e")) { + /* This option swallows all further arguments. */ + if (!do_everything) + break; - if (--argc > 0) { - int i; - pty_argv = snewn(argc+1, char *); - ++argv; - for (i = 0; i < argc; i++) - pty_argv[i] = argv[i]; - pty_argv[argc] = NULL; - break; /* finished command-line processing */ - } else - err = true, fprintf(stderr, "%s: -e expects an argument\n", + if (--argc > 0) { + int i; + pty_argv = snewn(argc+1, char *); + ++argv; + for (i = 0; i < argc; i++) + pty_argv[i] = argv[i]; + pty_argv[argc] = NULL; + break; /* finished command-line processing */ + } else + err = true, fprintf(stderr, "%s: -e expects an argument\n", appname); - } else if (!strcmp(p, "-title")) { - EXPECTS_ARG; - SECOND_PASS_ONLY; - conf_set_str(conf, CONF_wintitle, val); + } else if (!strcmp(p, "-title")) { + EXPECTS_ARG; + SECOND_PASS_ONLY; + conf_set_str(conf, CONF_wintitle, val); - } else if (!strcmp(p, "-log")) { - Filename *fn; - EXPECTS_ARG; - SECOND_PASS_ONLY; + } else if (!strcmp(p, "-log")) { + Filename *fn; + EXPECTS_ARG; + SECOND_PASS_ONLY; fn = filename_from_str(val); - conf_set_filename(conf, CONF_logfilename, fn); - conf_set_int(conf, CONF_logtype, LGTYP_DEBUG); + conf_set_filename(conf, CONF_logfilename, fn); + conf_set_int(conf, CONF_logtype, LGTYP_DEBUG); filename_free(fn); - } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_stamp_utmp, false); + } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_stamp_utmp, false); - } else if (!strcmp(p, "-ut")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_stamp_utmp, true); + } else if (!strcmp(p, "-ut")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_stamp_utmp, true); - } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_login_shell, false); + } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_login_shell, false); - } else if (!strcmp(p, "-ls")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_login_shell, true); + } else if (!strcmp(p, "-ls")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_login_shell, true); - } else if (!strcmp(p, "-nethack")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_nethack_keypad, true); + } else if (!strcmp(p, "-nethack")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_nethack_keypad, true); - } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_scrollbar, false); + } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_scrollbar, false); - } else if (!strcmp(p, "-sb")) { - SECOND_PASS_ONLY; - conf_set_bool(conf, CONF_scrollbar, true); + } else if (!strcmp(p, "-sb")) { + SECOND_PASS_ONLY; + conf_set_bool(conf, CONF_scrollbar, true); - } else if (!strcmp(p, "-name")) { - EXPECTS_ARG; - app_name = val; + } else if (!strcmp(p, "-name")) { + EXPECTS_ARG; + app_name = val; - } else if (!strcmp(p, "-xrm")) { - EXPECTS_ARG; - provide_xrm_string(val, appname); + } else if (!strcmp(p, "-xrm")) { + EXPECTS_ARG; + provide_xrm_string(val, appname); - } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) { - help(stdout); - exit(0); + } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) { + help(stdout); + exit(0); - } else if(!strcmp(p, "-version") || !strcmp(p, "--version")) { - version(stdout); - exit(0); + } else if(!strcmp(p, "-version") || !strcmp(p, "--version")) { + version(stdout); + exit(0); } else if (!strcmp(p, "-pgpfp")) { pgp_fingerprints(); exit(1); - } else if (p[0] != '-') { + } else if (p[0] != '-') { /* Non-option arguments not handled by cmdline.c are errors. */ if (do_everything) { err = true; @@ -537,10 +537,10 @@ bool do_cmdline(int argc, char **argv, bool do_everything, Conf *conf) appname, p); } - } else { - err = true; - fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p); - } + } else { + err = true; + fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p); + } } return err; @@ -598,13 +598,13 @@ int main(int argc, char **argv) * it. It will be required later. */ { - int i, oldargc; + int i, oldargc; gtkargvstart = snewn(argc-1, char *); - for (i = 1; i < argc; i++) - gtkargvstart[i-1] = dupstr(argv[i]); - oldargc = argc; - gtk_init(&argc, &argv); - ngtkargs = oldargc - argc; + for (i = 1; i < argc; i++) + gtkargvstart[i-1] = dupstr(argv[i]); + oldargc = argc; + gtk_init(&argc, &argv); + ngtkargs = oldargc - argc; } conf = conf_new(); @@ -620,20 +620,20 @@ int main(int argc, char **argv) block_signal(SIGPIPE, true); if (argc > 1 && !strncmp(argv[1], "---", 3)) { - read_dupsession_data(conf, argv[1]); - /* Splatter this argument so it doesn't clutter a ps listing */ - smemclr(argv[1], strlen(argv[1])); + read_dupsession_data(conf, argv[1]); + /* Splatter this argument so it doesn't clutter a ps listing */ + smemclr(argv[1], strlen(argv[1])); assert(!dup_check_launchable || conf_launchable(conf)); need_config_box = false; } else { - if (do_cmdline(argc, argv, false, conf)) - exit(1); /* pre-defaults pass to get -class */ - do_defaults(NULL, conf); - if (do_cmdline(argc, argv, true, conf)) - exit(1); /* post-defaults, do everything */ + if (do_cmdline(argc, argv, false, conf)) + exit(1); /* pre-defaults pass to get -class */ + do_defaults(NULL, conf); + if (do_cmdline(argc, argv, true, conf)) + exit(1); /* post-defaults, do everything */ - cmdline_run_saved(conf); + cmdline_run_saved(conf); if (cmdline_tooltype & TOOLTYPE_HOST_ARG) need_config_box = !cmdline_host_ok(conf); diff --git a/unix/gtkwin.c b/unix/gtkwin.c index 3bcbb4be..0da96184 100644 --- a/unix/gtkwin.c +++ b/unix/gtkwin.c @@ -27,7 +27,7 @@ #include #endif -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #define MAY_REFER_TO_GTK_IN_HEADERS @@ -98,7 +98,7 @@ struct GtkFrontend { GtkBox *hbox; GtkAdjustment *sbar_adjust; GtkWidget *menu, *specialsmenu, *specialsitem1, *specialsitem2, - *restartitem; + *restartitem; GtkWidget *sessionsmenu; #ifndef NOT_X_WINDOWS Display *disp; @@ -280,7 +280,7 @@ static void gtk_seat_connection_fatal(Seat *seat, const char *msg) FontSpec *platform_default_fontspec(const char *name) { if (!strcmp(name, "Font")) - return fontspec_new(DEFAULT_GTK_FONT); + return fontspec_new(DEFAULT_GTK_FONT); else return fontspec_new(""); } @@ -288,15 +288,15 @@ FontSpec *platform_default_fontspec(const char *name) Filename *platform_default_filename(const char *name) { if (!strcmp(name, "LogFileName")) - return filename_from_str("putty.log"); + return filename_from_str("putty.log"); else - return filename_from_str(""); + return filename_from_str(""); } char *platform_default_s(const char *name) { if (!strcmp(name, "SerialLine")) - return dupstr("/dev/ttyS0"); + return dupstr("/dev/ttyS0"); return NULL; } @@ -304,7 +304,7 @@ bool platform_default_b(const char *name, bool def) { if (!strcmp(name, "WinNameAlways")) { /* X natively supports icon titles, so use 'em by default */ - return false; + return false; } return def; } @@ -312,7 +312,7 @@ bool platform_default_b(const char *name, bool def) int platform_default_i(const char *name, int def) { if (!strcmp(name, "CloseOnExit")) - return 2; /* maps to FORCE_ON after painful rearrangement :-( */ + return 2; /* maps to FORCE_ON after painful rearrangement :-( */ return def; } @@ -342,7 +342,7 @@ static int gtk_seat_get_userpass_input(Seat *seat, prompts_t *p, int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = term_get_userpass_input(inst->term, p, input); + ret = term_get_userpass_input(inst->term, p, input); return ret; } @@ -432,7 +432,7 @@ static const LogPolicyVtable gtk_logpolicy_vt = { /* * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT) * into a cooked one (SELECT, EXTEND, PASTE). - * + * * In Unix, this is not configurable; the X button arrangement is * rock-solid across all applications, everyone has a three-button * mouse or a means of faking it, and there is no need to switch @@ -441,12 +441,12 @@ static const LogPolicyVtable gtk_logpolicy_vt = { static Mouse_Button translate_button(Mouse_Button button) { if (button == MBT_LEFT) - return MBT_SELECT; + return MBT_SELECT; if (button == MBT_MIDDLE) - return MBT_PASTE; + return MBT_PASTE; if (button == MBT_RIGHT) - return MBT_EXTEND; - return 0; /* shouldn't happen */ + return MBT_EXTEND; + return 0; /* shouldn't happen */ } /* @@ -495,9 +495,9 @@ static void gtkwin_set_minimised(TermWin *tw, bool minimised) #if GTK_CHECK_VERSION(2,0,0) GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (minimised) - gtk_window_iconify(GTK_WINDOW(inst->window)); + gtk_window_iconify(GTK_WINDOW(inst->window)); else - gtk_window_deiconify(GTK_WINDOW(inst->window)); + gtk_window_deiconify(GTK_WINDOW(inst->window)); #endif } @@ -529,9 +529,9 @@ static void gtkwin_set_zorder(TermWin *tw, bool top) { GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (top) - gdk_window_raise(gtk_widget_get_window(inst->window)); + gdk_window_raise(gtk_widget_get_window(inst->window)); else - gdk_window_lower(gtk_widget_get_window(inst->window)); + gdk_window_lower(gtk_widget_get_window(inst->window)); } /* @@ -555,9 +555,9 @@ static void gtkwin_set_maximised(TermWin *tw, bool maximised) #if GTK_CHECK_VERSION(2,0,0) GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (maximised) - gtk_window_maximize(GTK_WINDOW(inst->window)); + gtk_window_maximize(GTK_WINDOW(inst->window)); else - gtk_window_unmaximize(GTK_WINDOW(inst->window)); + gtk_window_unmaximize(GTK_WINDOW(inst->window)); #endif } @@ -679,32 +679,32 @@ static void update_mouseptr(GtkFrontend *inst) { switch (inst->busy_status) { case BUSY_NOT: - if (!inst->mouseptr_visible) { - gdk_window_set_cursor(gtk_widget_get_window(inst->area), + if (!inst->mouseptr_visible) { + gdk_window_set_cursor(gtk_widget_get_window(inst->area), inst->blankcursor); - } else if (inst->send_raw_mouse) { - gdk_window_set_cursor(gtk_widget_get_window(inst->area), + } else if (inst->send_raw_mouse) { + gdk_window_set_cursor(gtk_widget_get_window(inst->area), inst->rawcursor); - } else { - gdk_window_set_cursor(gtk_widget_get_window(inst->area), + } else { + gdk_window_set_cursor(gtk_widget_get_window(inst->area), inst->textcursor); - } - break; + } + break; case BUSY_WAITING: /* XXX can we do better? */ case BUSY_CPU: - /* We always display these cursors. */ - gdk_window_set_cursor(gtk_widget_get_window(inst->area), + /* We always display these cursors. */ + gdk_window_set_cursor(gtk_widget_get_window(inst->area), inst->waitcursor); - break; + break; default: - unreachable("Bad busy_status"); + unreachable("Bad busy_status"); } } static void show_mouseptr(GtkFrontend *inst, bool show) { if (!conf_get_bool(inst->conf, CONF_hide_mouseptr)) - show = true; + show = true; inst->mouseptr_visible = show; update_mouseptr(inst); } @@ -725,10 +725,10 @@ static void drawing_area_setup(GtkFrontend *inst, int width, int height) /* * Update conf. */ - inst->width = w; - inst->height = h; - conf_set_int(inst->conf, CONF_width, inst->width); - conf_set_int(inst->conf, CONF_height, inst->height); + inst->width = w; + inst->height = h; + conf_set_int(inst->conf, CONF_width, inst->width); + conf_set_int(inst->conf, CONF_height, inst->height); /* * We'll need to tell terminal.c about the resize below. */ @@ -736,13 +736,13 @@ static void drawing_area_setup(GtkFrontend *inst, int width, int height) /* * And we must refresh the window's backing image. */ - inst->drawing_area_setup_needed = true; + inst->drawing_area_setup_needed = true; } #if GTK_CHECK_VERSION(3,10,0) new_scale = gtk_widget_get_scale_factor(inst->area); if (new_scale != inst->scale) - inst->drawing_area_setup_needed = true; + inst->drawing_area_setup_needed = true; #else new_scale = 1; #endif @@ -789,11 +789,11 @@ static void drawing_area_setup(GtkFrontend *inst, int width, int height) draw_backing_rect(inst); if (need_size && inst->term) { - term_size(inst->term, h, w, conf_get_int(inst->conf, CONF_savelines)); + term_size(inst->term, h, w, conf_get_int(inst->conf, CONF_savelines)); } if (inst->term) - term_invalidate(inst->term); + term_invalidate(inst->term); #if GTK_CHECK_VERSION(2,0,0) gtk_im_context_set_client_window( @@ -948,13 +948,13 @@ gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data) * backing pixmap. */ if (inst->pixmap) { - gdk_draw_pixmap(gtk_widget_get_window(widget), - (gtk_widget_get_style(widget)->fg_gc + gdk_draw_pixmap(gtk_widget_get_window(widget), + (gtk_widget_get_style(widget)->fg_gc [gtk_widget_get_state(widget)]), - inst->pixmap, - event->area.x, event->area.y, - event->area.x, event->area.y, - event->area.width, event->area.height); + inst->pixmap, + event->area.x, event->area.y, + event->area.x, event->area.y, + event->area.width, event->area.height); } #else /* @@ -966,7 +966,7 @@ gint expose_area(GtkWidget *widget, GdkEventExpose *event, gpointer data) cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_set_source_surface(cr, inst->surface, 0, 0); cairo_rectangle(cr, event->area.x, event->area.y, - event->area.width, event->area.height); + event->area.width, event->area.height); cairo_fill(cr); cairo_destroy(cr); } @@ -1127,7 +1127,7 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) /* * If Alt is being released after typing an Alt+numberpad * sequence, we should generate the code that was typed. - * + * * Note that we only do this if more than one key was actually * pressed - I don't think Alt+NumPad4 should be ^D or that * Alt+NumPad3 should be ^C, for example. There's no serious @@ -1171,63 +1171,63 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } if (event->type == GDK_KEY_PRESS) { - /* - * If Alt has just been pressed, we start potentially - * accumulating an Alt+numberpad code. We do this by - * setting alt_keycode to -1 (nothing yet but plausible). - */ - if ((event->keyval == GDK_KEY_Meta_L || - event->keyval == GDK_KEY_Meta_R || + /* + * If Alt has just been pressed, we start potentially + * accumulating an Alt+numberpad code. We do this by + * setting alt_keycode to -1 (nothing yet but plausible). + */ + if ((event->keyval == GDK_KEY_Meta_L || + event->keyval == GDK_KEY_Meta_R || event->keyval == GDK_KEY_Alt_L || event->keyval == GDK_KEY_Alt_R)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - modifier press potentially begins Alt+numberpad " "input\n"); #endif - inst->alt_keycode = -1; + inst->alt_keycode = -1; inst->alt_digits = 0; - goto done; /* this generates nothing else */ - } + goto done; /* this generates nothing else */ + } - /* - * If we're seeing a numberpad key press with Meta down, - * consider adding it to alt_keycode if that's sensible. - * Anything _else_ with Meta down cancels any possibility - * of an ALT keycode: we set alt_keycode to -2. - */ - if ((event->state & inst->meta_mod_mask) && inst->alt_keycode != -2) { - int digit = -1; - switch (event->keyval) { - case GDK_KEY_KP_0: case GDK_KEY_KP_Insert: digit = 0; break; - case GDK_KEY_KP_1: case GDK_KEY_KP_End: digit = 1; break; - case GDK_KEY_KP_2: case GDK_KEY_KP_Down: digit = 2; break; - case GDK_KEY_KP_3: case GDK_KEY_KP_Page_Down: digit = 3; break; - case GDK_KEY_KP_4: case GDK_KEY_KP_Left: digit = 4; break; - case GDK_KEY_KP_5: case GDK_KEY_KP_Begin: digit = 5; break; - case GDK_KEY_KP_6: case GDK_KEY_KP_Right: digit = 6; break; - case GDK_KEY_KP_7: case GDK_KEY_KP_Home: digit = 7; break; - case GDK_KEY_KP_8: case GDK_KEY_KP_Up: digit = 8; break; - case GDK_KEY_KP_9: case GDK_KEY_KP_Page_Up: digit = 9; break; - } - if (digit < 0) - inst->alt_keycode = -2; /* it's invalid */ - else { + /* + * If we're seeing a numberpad key press with Meta down, + * consider adding it to alt_keycode if that's sensible. + * Anything _else_ with Meta down cancels any possibility + * of an ALT keycode: we set alt_keycode to -2. + */ + if ((event->state & inst->meta_mod_mask) && inst->alt_keycode != -2) { + int digit = -1; + switch (event->keyval) { + case GDK_KEY_KP_0: case GDK_KEY_KP_Insert: digit = 0; break; + case GDK_KEY_KP_1: case GDK_KEY_KP_End: digit = 1; break; + case GDK_KEY_KP_2: case GDK_KEY_KP_Down: digit = 2; break; + case GDK_KEY_KP_3: case GDK_KEY_KP_Page_Down: digit = 3; break; + case GDK_KEY_KP_4: case GDK_KEY_KP_Left: digit = 4; break; + case GDK_KEY_KP_5: case GDK_KEY_KP_Begin: digit = 5; break; + case GDK_KEY_KP_6: case GDK_KEY_KP_Right: digit = 6; break; + case GDK_KEY_KP_7: case GDK_KEY_KP_Home: digit = 7; break; + case GDK_KEY_KP_8: case GDK_KEY_KP_Up: digit = 8; break; + case GDK_KEY_KP_9: case GDK_KEY_KP_Page_Up: digit = 9; break; + } + if (digit < 0) + inst->alt_keycode = -2; /* it's invalid */ + else { #ifdef KEY_EVENT_DIAGNOSTICS int old_keycode = inst->alt_keycode; #endif - if (inst->alt_keycode == -1) - inst->alt_keycode = digit; /* one-digit code */ - else - inst->alt_keycode = inst->alt_keycode * 10 + digit; + if (inst->alt_keycode == -1) + inst->alt_keycode = digit; /* one-digit code */ + else + inst->alt_keycode = inst->alt_keycode * 10 + digit; inst->alt_digits++; #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Alt+numberpad digit %d added to keycode %d" " gives %d\n", digit, old_keycode, inst->alt_keycode); #endif - /* Having used this digit, we now do nothing more with it. */ - goto done; - } - } + /* Having used this digit, we now do nothing more with it. */ + goto done; + } + } if (event->keyval == GDK_KEY_greater && (event->state & GDK_CONTROL_MASK)) { @@ -1246,10 +1246,10 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) return true; } - /* - * Shift-PgUp and Shift-PgDn don't even generate keystrokes - * at all. - */ + /* + * Shift-PgUp and Shift-PgDn don't even generate keystrokes + * at all. + */ if (event->keyval == GDK_KEY_Page_Up && ((event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) == (GDK_CONTROL_MASK | GDK_SHIFT_MASK))) { @@ -1259,22 +1259,22 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) term_scroll(inst->term, 1, 0); return true; } - if (event->keyval == GDK_KEY_Page_Up && + if (event->keyval == GDK_KEY_Page_Up && (event->state & GDK_SHIFT_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Shift-PgUp scroll\n"); #endif - term_scroll(inst->term, 0, -inst->height/2); - return true; - } - if (event->keyval == GDK_KEY_Page_Up && + term_scroll(inst->term, 0, -inst->height/2); + return true; + } + if (event->keyval == GDK_KEY_Page_Up && (event->state & GDK_CONTROL_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-PgUp scroll\n"); #endif - term_scroll(inst->term, 0, -1); - return true; - } + term_scroll(inst->term, 0, -1); + return true; + } if (event->keyval == GDK_KEY_Page_Down && ((event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) == (GDK_CONTROL_MASK | GDK_SHIFT_MASK))) { @@ -1284,27 +1284,27 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) term_scroll(inst->term, -1, 0); return true; } - if (event->keyval == GDK_KEY_Page_Down && + if (event->keyval == GDK_KEY_Page_Down && (event->state & GDK_SHIFT_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Shift-PgDn scroll\n"); #endif - term_scroll(inst->term, 0, +inst->height/2); - return true; - } - if (event->keyval == GDK_KEY_Page_Down && + term_scroll(inst->term, 0, +inst->height/2); + return true; + } + if (event->keyval == GDK_KEY_Page_Down && (event->state & GDK_CONTROL_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-PgDn scroll\n"); #endif - term_scroll(inst->term, 0, +1); - return true; - } + term_scroll(inst->term, 0, +1); + return true; + } - /* - * Neither do Shift-Ins or Ctrl-Ins (if enabled). - */ - if (event->keyval == GDK_KEY_Insert && + /* + * Neither do Shift-Ins or Ctrl-Ins (if enabled). + */ + if (event->keyval == GDK_KEY_Insert && (event->state & GDK_SHIFT_MASK)) { int cfgval = conf_get_int(inst->conf, CONF_ctrlshiftins); @@ -1333,8 +1333,8 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif break; } - } - if (event->keyval == GDK_KEY_Insert && + } + if (event->keyval == GDK_KEY_Insert && (event->state & GDK_CONTROL_MASK)) { static const int clips_clipboard[] = { CLIP_CLIPBOARD }; int cfgval = conf_get_int(inst->conf, CONF_ctrlshiftins); @@ -1366,12 +1366,12 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif break; } - } + } /* * Another pair of copy-paste keys. */ - if ((event->state & GDK_SHIFT_MASK) && + if ((event->state & GDK_SHIFT_MASK) && (event->state & GDK_CONTROL_MASK) && (event->keyval == GDK_KEY_C || event->keyval == GDK_KEY_c || event->keyval == GDK_KEY_V || event->keyval == GDK_KEY_v)) { @@ -1422,23 +1422,23 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } return true; } - } + } - special = false; - use_ucsoutput = false; + special = false; + use_ucsoutput = false; - /* ALT+things gives leading Escape. */ - output[0] = '\033'; + /* ALT+things gives leading Escape. */ + output[0] = '\033'; #if !GTK_CHECK_VERSION(2,0,0) - /* - * In vanilla X, and hence also GDK 1.2, the string received - * as part of a keyboard event is assumed to be in - * ISO-8859-1. (Seems woefully shortsighted in i18n terms, - * but it's true: see the man page for XLookupString(3) for - * confirmation.) - */ - output_charset = CS_ISO8859_1; - strncpy(output+1, event->string, lenof(output)-1); + /* + * In vanilla X, and hence also GDK 1.2, the string received + * as part of a keyboard event is assumed to be in + * ISO-8859-1. (Seems woefully shortsighted in i18n terms, + * but it's true: see the man page for XLookupString(3) for + * confirmation.) + */ + output_charset = CS_ISO8859_1; + strncpy(output+1, event->string, lenof(output)-1); #else /* !GTK_CHECK_VERSION(2,0,0) */ /* * Most things can now be passed to @@ -1483,7 +1483,7 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) case GDK_KEY_KP_Decimal: num_keypad_key = '.'; numeric = true; break; case GDK_KEY_KP_Delete: num_keypad_key = '.'; break; } - if ((app_keypad_mode && num_keypad_key && + if ((app_keypad_mode && num_keypad_key && (numeric || inst->term->funky_type != FUNKY_XTERM)) || (nethack_mode && num_keypad_key >= '1' && num_keypad_key <= '9')) { /* In these modes, we override the keypad handling: @@ -1527,28 +1527,28 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } } - /* - * GDK 2.0 arranges to have done some translation for us: in - * GDK 2.0, event->string is encoded in the current locale. - * - * So we use the standard C library function mbstowcs() to - * convert from the current locale into Unicode; from there - * we can convert to whatever PuTTY is currently working in. - * (In fact I convert straight back to UTF-8 from - * wide-character Unicode, for the sake of simplicity: that - * way we can still use exactly the same code to manipulate - * the string, such as prefixing ESC.) - */ - output_charset = CS_UTF8; - { - wchar_t widedata[32]; + /* + * GDK 2.0 arranges to have done some translation for us: in + * GDK 2.0, event->string is encoded in the current locale. + * + * So we use the standard C library function mbstowcs() to + * convert from the current locale into Unicode; from there + * we can convert to whatever PuTTY is currently working in. + * (In fact I convert straight back to UTF-8 from + * wide-character Unicode, for the sake of simplicity: that + * way we can still use exactly the same code to manipulate + * the string, such as prefixing ESC.) + */ + output_charset = CS_UTF8; + { + wchar_t widedata[32]; const wchar_t *wp; - int wlen; - int ulen; + int wlen; + int ulen; - wlen = mb_to_wc(DEFAULT_CODEPAGE, 0, - event->string, strlen(event->string), - widedata, lenof(widedata)-1); + wlen = mb_to_wc(DEFAULT_CODEPAGE, 0, + event->string, strlen(event->string), + widedata, lenof(widedata)-1); #ifdef KEY_EVENT_DIAGNOSTICS { @@ -1568,9 +1568,9 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } #endif - wp = widedata; - ulen = charset_from_unicode(&wp, &wlen, output+1, lenof(output)-2, - CS_UTF8, NULL, NULL, 0); + wp = widedata; + ulen = charset_from_unicode(&wp, &wlen, output+1, lenof(output)-2, + CS_UTF8, NULL, NULL, 0); #ifdef KEY_EVENT_DIAGNOSTICS { @@ -1590,27 +1590,27 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } #endif - output[1+ulen] = '\0'; - } + output[1+ulen] = '\0'; + } #endif /* !GTK_CHECK_VERSION(2,0,0) */ - if (!output[1] && - (ucsval = keysym_to_unicode(event->keyval)) >= 0) { - ucsoutput[0] = '\033'; - ucsoutput[1] = ucsval; + if (!output[1] && + (ucsval = keysym_to_unicode(event->keyval)) >= 0) { + ucsoutput[0] = '\033'; + ucsoutput[1] = ucsval; #ifdef KEY_EVENT_DIAGNOSTICS debug(" - keysym_to_unicode gave %04x\n", (unsigned)ucsoutput[1]); #endif - use_ucsoutput = true; - end = 2; - } else { - output[lenof(output)-1] = '\0'; - end = strlen(output); - } - if (event->state & inst->meta_mod_mask) { - start = 0; - if (end == 1) end = 0; + use_ucsoutput = true; + end = 2; + } else { + output[lenof(output)-1] = '\0'; + end = strlen(output); + } + if (event->state & inst->meta_mod_mask) { + start = 0; + if (end == 1) end = 0; #ifdef META_MANUAL_MASK if (event->state & META_MANUAL_MASK) { @@ -1647,19 +1647,19 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) } } #endif - } else - start = 1; + } else + start = 1; - /* Control-` is the same as Control-\ (unless gtk has a better idea) */ - if (!output[1] && event->keyval == '`' && - (event->state & GDK_CONTROL_MASK)) { + /* Control-` is the same as Control-\ (unless gtk has a better idea) */ + if (!output[1] && event->keyval == '`' && + (event->state & GDK_CONTROL_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-` special case, translating as 1c\n"); #endif - output[1] = '\x1C'; - use_ucsoutput = false; - end = 2; - } + output[1] = '\x1C'; + use_ucsoutput = false; + end = 2; + } /* Some GTK backends (e.g. Quartz) do not change event->string * in response to the Control modifier. So we do it ourselves @@ -1700,100 +1700,100 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif } - /* Control-Break sends a Break special to the backend */ - if (event->keyval == GDK_KEY_Break && - (event->state & GDK_CONTROL_MASK)) { + /* Control-Break sends a Break special to the backend */ + if (event->keyval == GDK_KEY_Break && + (event->state & GDK_CONTROL_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-Break special case, sending SS_BRK\n"); #endif if (inst->backend) backend_special(inst->backend, SS_BRK, 0); - return true; - } + return true; + } - /* We handle Return ourselves, because it needs to be flagged as - * special to ldisc. */ - if (event->keyval == GDK_KEY_Return) { + /* We handle Return ourselves, because it needs to be flagged as + * special to ldisc. */ + if (event->keyval == GDK_KEY_Return) { end = return_key(inst, output, &special); use_ucsoutput = false; - } + } - /* Control-2, Control-Space and Control-@ are NUL */ - if (!output[1] && - (event->keyval == ' ' || event->keyval == '2' || - event->keyval == '@') && - (event->state & (GDK_SHIFT_MASK | - GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) { + /* Control-2, Control-Space and Control-@ are NUL */ + if (!output[1] && + (event->keyval == ' ' || event->keyval == '2' || + event->keyval == '@') && + (event->state & (GDK_SHIFT_MASK | + GDK_CONTROL_MASK)) == GDK_CONTROL_MASK) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-{space,2,@} special case, translating as 00\n"); #endif - output[1] = '\0'; - use_ucsoutput = false; - end = 2; - } + output[1] = '\0'; + use_ucsoutput = false; + end = 2; + } - /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */ - if (!output[1] && event->keyval == ' ' && - (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) == - (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) { + /* Control-Shift-Space is 160 (ISO8859 nonbreaking space) */ + if (!output[1] && event->keyval == ' ' && + (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) == + (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Ctrl-Shift-space special case, translating as 00a0\n"); #endif - output[1] = '\240'; - output_charset = CS_ISO8859_1; - use_ucsoutput = false; - end = 2; - } + output[1] = '\240'; + output_charset = CS_ISO8859_1; + use_ucsoutput = false; + end = 2; + } - /* We don't let GTK tell us what Backspace is! We know better. */ - if (event->keyval == GDK_KEY_BackSpace && - !(event->state & GDK_SHIFT_MASK)) { - output[1] = conf_get_bool(inst->conf, CONF_bksp_is_delete) ? - '\x7F' : '\x08'; + /* We don't let GTK tell us what Backspace is! We know better. */ + if (event->keyval == GDK_KEY_BackSpace && + !(event->state & GDK_SHIFT_MASK)) { + output[1] = conf_get_bool(inst->conf, CONF_bksp_is_delete) ? + '\x7F' : '\x08'; #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Backspace, translating as %02x\n", (unsigned)output[1]); #endif - use_ucsoutput = false; - end = 2; - special = true; - } - /* For Shift Backspace, do opposite of what is configured. */ - if (event->keyval == GDK_KEY_BackSpace && - (event->state & GDK_SHIFT_MASK)) { - output[1] = conf_get_bool(inst->conf, CONF_bksp_is_delete) ? - '\x08' : '\x7F'; + use_ucsoutput = false; + end = 2; + special = true; + } + /* For Shift Backspace, do opposite of what is configured. */ + if (event->keyval == GDK_KEY_BackSpace && + (event->state & GDK_SHIFT_MASK)) { + output[1] = conf_get_bool(inst->conf, CONF_bksp_is_delete) ? + '\x08' : '\x7F'; #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Shift-Backspace, translating as %02x\n", (unsigned)output[1]); #endif - use_ucsoutput = false; - end = 2; - special = true; - } + use_ucsoutput = false; + end = 2; + special = true; + } - /* Shift-Tab is ESC [ Z */ - if (event->keyval == GDK_KEY_ISO_Left_Tab || - (event->keyval == GDK_KEY_Tab && + /* Shift-Tab is ESC [ Z */ + if (event->keyval == GDK_KEY_ISO_Left_Tab || + (event->keyval == GDK_KEY_Tab && (event->state & GDK_SHIFT_MASK))) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Shift-Tab, translating as ESC [ Z\n"); #endif - end = 1 + sprintf(output+1, "\033[Z"); - use_ucsoutput = false; - } - /* And normal Tab is Tab, if the keymap hasn't already told us. - * (Curiously, at least one version of the MacOS 10.5 X server - * doesn't translate Tab for us. */ - if (event->keyval == GDK_KEY_Tab && end <= 1) { + end = 1 + sprintf(output+1, "\033[Z"); + use_ucsoutput = false; + } + /* And normal Tab is Tab, if the keymap hasn't already told us. + * (Curiously, at least one version of the MacOS 10.5 X server + * doesn't translate Tab for us. */ + if (event->keyval == GDK_KEY_Tab && end <= 1) { #ifdef KEY_EVENT_DIAGNOSTICS debug(" - Tab, translating as 09\n"); #endif - output[1] = '\t'; - end = 2; - } + output[1] = '\t'; + end = 2; + } - if (num_keypad_key && force_format_numeric_keypad) { + if (num_keypad_key && force_format_numeric_keypad) { end = 1 + format_numeric_keypad_key( output+1, inst->term, num_keypad_key, event->state & GDK_SHIFT_MASK, @@ -1803,7 +1803,7 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif use_ucsoutput = false; goto done; - } + } switch (event->keyval) { int fkey_number; @@ -1862,7 +1862,7 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) use_ucsoutput = false; goto done; - int xkey; + int xkey; case GDK_KEY_Up: case GDK_KEY_KP_Up: xkey = 'A'; goto arrow_key; case GDK_KEY_Down: case GDK_KEY_KP_Down: @@ -1881,9 +1881,9 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif use_ucsoutput = false; goto done; - } + } - if (num_keypad_key) { + if (num_keypad_key) { end = 1 + format_numeric_keypad_key( output+1, inst->term, num_keypad_key, event->state & GDK_SHIFT_MASK, @@ -1902,15 +1902,15 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) use_ucsoutput = false; goto done; - } + } - goto done; + goto done; } done: if (end-start > 0) { - if (special) { + if (special) { #ifdef KEY_EVENT_DIAGNOSTICS char *string_string = dupstr(""); int i; @@ -1926,15 +1926,15 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) charset_to_localenc(output_charset), string_string); sfree(string_string); #endif - /* - * For special control characters, the character set - * should never matter. - */ - output[end] = '\0'; /* NUL-terminate */ + /* + * For special control characters, the character set + * should never matter. + */ + output[end] = '\0'; /* NUL-terminate */ generated_something = true; term_keyinput(inst->term, -1, output+start, -2); - } else if (!inst->direct_to_font) { - if (!use_ucsoutput) { + } else if (!inst->direct_to_font) { + if (!use_ucsoutput) { #ifdef KEY_EVENT_DIAGNOSTICS char *string_string = dupstr(""); int i; @@ -1953,7 +1953,7 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) generated_something = true; term_keyinput(inst->term, output_charset, output+start, end-start); - } else { + } else { #ifdef KEY_EVENT_DIAGNOSTICS char *string_string = dupstr(""); int i; @@ -1970,18 +1970,18 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) sfree(string_string); #endif - /* - * We generated our own Unicode key data from the - * keysym, so use that instead. - */ + /* + * We generated our own Unicode key data from the + * keysym, so use that instead. + */ generated_something = true; term_keyinputw(inst->term, ucsoutput+start, end-start); - } - } else { - /* - * In direct-to-font mode, we just send the string - * exactly as we received it. - */ + } + } else { + /* + * In direct-to-font mode, we just send the string + * exactly as we received it. + */ #ifdef KEY_EVENT_DIAGNOSTICS char *string_string = dupstr(""); int i; @@ -1999,9 +1999,9 @@ gint key_event(GtkWidget *widget, GdkEventKey *event, gpointer data) #endif generated_something = true; term_keyinput(inst->term, -1, output+start, end-start); - } + } - show_mouseptr(inst, false); + show_mouseptr(inst, false); } if (generated_something) @@ -2039,7 +2039,7 @@ void input_method_commit_event(GtkIMContext *imc, gchar *str, gpointer data) #if GTK_CHECK_VERSION(3,4,0) gboolean scroll_internal(GtkFrontend *inst, gdouble delta, guint state, - gdouble ex, gdouble ey) + gdouble ex, gdouble ey) { int x, y; bool shift, ctrl, alt, raw_mouse_mode; @@ -2124,43 +2124,43 @@ static gboolean button_internal(GtkFrontend *inst, GdkEventButton *event) if (event->button == 3 && ctrl) { #if GTK_CHECK_VERSION(3,22,0) - gtk_menu_popup_at_pointer(GTK_MENU(inst->menu), (GdkEvent *)event); + gtk_menu_popup_at_pointer(GTK_MENU(inst->menu), (GdkEvent *)event); #else - gtk_menu_popup(GTK_MENU(inst->menu), NULL, NULL, NULL, NULL, - event->button, event->time); + gtk_menu_popup(GTK_MENU(inst->menu), NULL, NULL, NULL, NULL, + event->button, event->time); #endif - return true; + return true; } if (event->button == 1) - button = MBT_LEFT; + button = MBT_LEFT; else if (event->button == 2) - button = MBT_MIDDLE; + button = MBT_MIDDLE; else if (event->button == 3) - button = MBT_RIGHT; + button = MBT_RIGHT; else if (event->button == 4) - button = MBT_WHEEL_UP; + button = MBT_WHEEL_UP; else if (event->button == 5) - button = MBT_WHEEL_DOWN; + button = MBT_WHEEL_DOWN; else - return false; /* don't even know what button! */ + return false; /* don't even know what button! */ switch (event->type) { case GDK_BUTTON_PRESS: act = MA_CLICK; break; case GDK_BUTTON_RELEASE: act = MA_RELEASE; break; case GDK_2BUTTON_PRESS: act = MA_2CLK; break; case GDK_3BUTTON_PRESS: act = MA_3CLK; break; - default: return false; /* don't know this event type */ + default: return false; /* don't know this event type */ } if (raw_mouse_mode && act != MA_CLICK && act != MA_RELEASE) - return true; /* we ignore these in raw mouse mode */ + return true; /* we ignore these in raw mouse mode */ x = (event->x - inst->window_border) / inst->font_width; y = (event->y - inst->window_border) / inst->font_height; term_mouse(inst->term, button, translate_button(button), act, - x, y, shift, ctrl, alt); + x, y, shift, ctrl, alt); return true; } @@ -2193,11 +2193,11 @@ gboolean scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer data) gboolean ret; if (event->direction == GDK_SCROLL_UP) - button = 4; + button = 4; else if (event->direction == GDK_SCROLL_DOWN) - button = 5; + button = 5; else - return false; + return false; event_button = (GdkEventButton *)gdk_event_new(GDK_BUTTON_PRESS); event_button->window = g_object_ref(event->window); @@ -2236,19 +2236,19 @@ gint motion_event(GtkWidget *widget, GdkEventMotion *event, gpointer data) ctrl = event->state & GDK_CONTROL_MASK; alt = event->state & inst->meta_mod_mask; if (event->state & GDK_BUTTON1_MASK) - button = MBT_LEFT; + button = MBT_LEFT; else if (event->state & GDK_BUTTON2_MASK) - button = MBT_MIDDLE; + button = MBT_MIDDLE; else if (event->state & GDK_BUTTON3_MASK) - button = MBT_RIGHT; + button = MBT_RIGHT; else - return false; /* don't even know what button! */ + return false; /* don't even know what button! */ x = (event->x - inst->window_border) / inst->font_width; y = (event->y - inst->window_border) / inst->font_height; term_mouse(inst->term, button, translate_button(button), MA_DRAG, - x, y, shift, ctrl, alt); + x, y, shift, ctrl, alt); return true; } @@ -2281,9 +2281,9 @@ static void exit_callback(void *vctx) (exitcode = backend_exitcode(inst->backend)) >= 0) { destroy_inst_connection(inst); - close_on_exit = conf_get_int(inst->conf, CONF_close_on_exit); - if (close_on_exit == FORCE_ON || - (close_on_exit == AUTO && exitcode == 0)) { + close_on_exit = conf_get_int(inst->conf, CONF_close_on_exit); + if (close_on_exit == FORCE_ON || + (close_on_exit == AUTO && exitcode == 0)) { gtk_widget_destroy(inst->window); } } @@ -2481,7 +2481,7 @@ static void gtkwin_request_resize(TermWin *tw, int w, int h) gtk_widget_set_size_request(inst->area, area_x, area_y); #if GTK_CHECK_VERSION(2,0,0) gtk_window_resize(GTK_WINDOW(inst->window), - area_x + offset_x, area_y + offset_y); + area_x + offset_x, area_y + offset_y); #else gtk_drawing_area_size(GTK_DRAWING_AREA(inst->area), area_x, area_y); /* @@ -2492,7 +2492,7 @@ static void gtkwin_request_resize(TermWin *tw, int w, int h) * prevent gratuitous resize processing on the window given * that we're about to resize it anyway, but I have no idea * why that's so incredibly vital. - * + * * I've tried removing the call, and nothing seems to go * wrong. I've backtracked to r3092 and tried removing the * call there, and still nothing goes wrong. So I'm going to @@ -2503,7 +2503,7 @@ static void gtkwin_request_resize(TermWin *tw, int w, int h) */ gtk_container_dequeue_resize_handler(GTK_CONTAINER(inst->window)); gdk_window_resize(gtk_widget_get_window(inst->window), - area_x + offset_x, area_y + offset_y); + area_x + offset_x, area_y + offset_y); #endif #else /* GTK_CHECK_VERSION(3,0,0) */ @@ -2553,11 +2553,11 @@ void set_gtk_widget_background(GtkWidget *widget, const GdkColor *col) GtkCssProvider *provider = gtk_css_provider_new(); char *col_css = colour_to_css(col); char *data = dupprintf( - "#drawing-area, #top-level { background-color: %s; }\n", col_css); + "#drawing-area, #top-level { background-color: %s; }\n", col_css); gtk_css_provider_load_from_data(provider, data, -1, NULL); GtkStyleContext *context = gtk_widget_get_style_context(widget); gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), - GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); free(data); free(col_css); #else @@ -2573,25 +2573,25 @@ void set_gtk_widget_background(GtkWidget *widget, const GdkColor *col) void set_window_background(GtkFrontend *inst) { if (inst->area) - set_gtk_widget_background(GTK_WIDGET(inst->area), &inst->cols[258]); + set_gtk_widget_background(GTK_WIDGET(inst->area), &inst->cols[258]); if (inst->window) - set_gtk_widget_background(GTK_WIDGET(inst->window), &inst->cols[258]); + set_gtk_widget_background(GTK_WIDGET(inst->window), &inst->cols[258]); } static void gtkwin_palette_set(TermWin *tw, int n, int r, int g, int b) { GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (n >= 16) - n += 256 - 16; + n += 256 - 16; if (n >= NALLCOLOURS) - return; + return; real_palette_set(inst, n, r, g, b); if (n == 258) { - /* Default Background changed. Ensure space between text area and - * window border is redrawn */ - set_window_background(inst); - draw_backing_rect(inst); - gtk_widget_queue_draw(inst->area); + /* Default Background changed. Ensure space between text area and + * window border is redrawn */ + set_window_background(inst); + draw_backing_rect(inst); + gtk_widget_queue_draw(inst->area); } } @@ -2599,7 +2599,7 @@ static bool gtkwin_palette_get(TermWin *tw, int n, int *r, int *g, int *b) { GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (n < 0 || n >= NALLCOLOURS) - return false; + return false; *r = inst->cols[n].red >> 8; *g = inst->cols[n].green >> 8; *b = inst->cols[n].blue >> 8; @@ -2611,9 +2611,9 @@ static void gtkwin_palette_reset(TermWin *tw) GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); /* This maps colour indices in inst->conf to those used in inst->cols. */ static const int ww[] = { - 256, 257, 258, 259, 260, 261, - 0, 8, 1, 9, 2, 10, 3, 11, - 4, 12, 5, 13, 6, 14, 7, 15 + 256, 257, 258, 259, 260, 261, + 0, 8, 1, 9, 2, 10, 3, 11, + 4, 12, 5, 13, 6, 14, 7, 15 }; int i; @@ -2621,33 +2621,33 @@ static void gtkwin_palette_reset(TermWin *tw) #if !GTK_CHECK_VERSION(3,0,0) if (!inst->colmap) { - inst->colmap = gdk_colormap_get_system(); + inst->colmap = gdk_colormap_get_system(); } else { - gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS); + gdk_colormap_free_colors(inst->colmap, inst->cols, NALLCOLOURS); } #endif for (i = 0; i < NCFGCOLOURS; i++) { - inst->cols[ww[i]].red = - conf_get_int_int(inst->conf, CONF_colours, i*3+0) * 0x0101; - inst->cols[ww[i]].green = - conf_get_int_int(inst->conf, CONF_colours, i*3+1) * 0x0101; - inst->cols[ww[i]].blue = - conf_get_int_int(inst->conf, CONF_colours, i*3+2) * 0x0101; + inst->cols[ww[i]].red = + conf_get_int_int(inst->conf, CONF_colours, i*3+0) * 0x0101; + inst->cols[ww[i]].green = + conf_get_int_int(inst->conf, CONF_colours, i*3+1) * 0x0101; + inst->cols[ww[i]].blue = + conf_get_int_int(inst->conf, CONF_colours, i*3+2) * 0x0101; } for (i = 0; i < NEXTCOLOURS; i++) { - if (i < 216) { - int r = i / 36, g = (i / 6) % 6, b = i % 6; - inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0; - inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0; - inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0; - } else { - int shade = i - 216; - shade = shade * 0x0a0a + 0x0808; - inst->cols[i+16].red = inst->cols[i+16].green = - inst->cols[i+16].blue = shade; - } + if (i < 216) { + int r = i / 36, g = (i / 6) % 6, b = i % 6; + inst->cols[i+16].red = r ? r * 0x2828 + 0x3737 : 0; + inst->cols[i+16].green = g ? g * 0x2828 + 0x3737 : 0; + inst->cols[i+16].blue = b ? b * 0x2828 + 0x3737 : 0; + } else { + int shade = i - 216; + shade = shade * 0x0a0a + 0x0808; + inst->cols[i+16].red = inst->cols[i+16].green = + inst->cols[i+16].blue = shade; + } } #if !GTK_CHECK_VERSION(3,0,0) @@ -2670,8 +2670,8 @@ static void gtkwin_palette_reset(TermWin *tw) * between text area and window border is refreshed. */ set_window_background(inst); if (inst->area && gtk_widget_get_window(inst->area)) { - draw_backing_rect(inst); - gtk_widget_queue_draw(inst->area); + draw_backing_rect(inst); + gtk_widget_queue_draw(inst->area); } } @@ -2891,8 +2891,8 @@ static char *retrieve_cutbuffer(GtkFrontend *inst, int *nbytes) } ptr = XFetchBytes(inst->disp, nbytes); if (*nbytes <= 0 && ptr != 0) { - XFree(ptr); - ptr = 0; + XFree(ptr); + ptr = 0; } return ptr; #else @@ -2909,76 +2909,76 @@ static void gtkwin_clip_write( struct clipboard_state *state = &inst->clipstates[clipboard]; if (state->pasteout_data) - sfree(state->pasteout_data); + sfree(state->pasteout_data); if (state->pasteout_data_ctext) - sfree(state->pasteout_data_ctext); + sfree(state->pasteout_data_ctext); if (state->pasteout_data_utf8) - sfree(state->pasteout_data_utf8); + sfree(state->pasteout_data_utf8); /* * Set up UTF-8 and compound text paste data. This only happens * if we aren't in direct-to-font mode using the D800 hack. */ if (!inst->direct_to_font) { - const wchar_t *tmp = data; - int tmplen = len; + const wchar_t *tmp = data; + int tmplen = len; #ifndef NOT_X_WINDOWS - XTextProperty tp; - char *list[1]; + XTextProperty tp; + char *list[1]; #endif - state->pasteout_data_utf8 = snewn(len*6, char); - state->pasteout_data_utf8_len = len*6; - state->pasteout_data_utf8_len = - charset_from_unicode(&tmp, &tmplen, state->pasteout_data_utf8, - state->pasteout_data_utf8_len, - CS_UTF8, NULL, NULL, 0); - if (state->pasteout_data_utf8_len == 0) { - sfree(state->pasteout_data_utf8); - state->pasteout_data_utf8 = NULL; - } else { - state->pasteout_data_utf8 = - sresize(state->pasteout_data_utf8, - state->pasteout_data_utf8_len + 1, char); - state->pasteout_data_utf8[state->pasteout_data_utf8_len] = '\0'; - } + state->pasteout_data_utf8 = snewn(len*6, char); + state->pasteout_data_utf8_len = len*6; + state->pasteout_data_utf8_len = + charset_from_unicode(&tmp, &tmplen, state->pasteout_data_utf8, + state->pasteout_data_utf8_len, + CS_UTF8, NULL, NULL, 0); + if (state->pasteout_data_utf8_len == 0) { + sfree(state->pasteout_data_utf8); + state->pasteout_data_utf8 = NULL; + } else { + state->pasteout_data_utf8 = + sresize(state->pasteout_data_utf8, + state->pasteout_data_utf8_len + 1, char); + state->pasteout_data_utf8[state->pasteout_data_utf8_len] = '\0'; + } - /* - * Now let Xlib convert our UTF-8 data into compound text. - */ + /* + * Now let Xlib convert our UTF-8 data into compound text. + */ #ifndef NOT_X_WINDOWS - list[0] = state->pasteout_data_utf8; - if (inst->disp && Xutf8TextListToTextProperty( + list[0] = state->pasteout_data_utf8; + if (inst->disp && Xutf8TextListToTextProperty( inst->disp, list, 1, XCompoundTextStyle, &tp) == 0) { - state->pasteout_data_ctext = snewn(tp.nitems+1, char); - memcpy(state->pasteout_data_ctext, tp.value, tp.nitems); - state->pasteout_data_ctext_len = tp.nitems; - XFree(tp.value); - } else + state->pasteout_data_ctext = snewn(tp.nitems+1, char); + memcpy(state->pasteout_data_ctext, tp.value, tp.nitems); + state->pasteout_data_ctext_len = tp.nitems; + XFree(tp.value); + } else #endif { state->pasteout_data_ctext = NULL; state->pasteout_data_ctext_len = 0; } } else { - state->pasteout_data_utf8 = NULL; - state->pasteout_data_utf8_len = 0; - state->pasteout_data_ctext = NULL; - state->pasteout_data_ctext_len = 0; + state->pasteout_data_utf8 = NULL; + state->pasteout_data_utf8_len = 0; + state->pasteout_data_ctext = NULL; + state->pasteout_data_ctext_len = 0; } state->pasteout_data = snewn(len*6, char); state->pasteout_data_len = len*6; state->pasteout_data_len = wc_to_mb(inst->ucsdata.line_codepage, 0, - data, len, state->pasteout_data, - state->pasteout_data_len, - NULL, NULL); + data, len, state->pasteout_data, + state->pasteout_data_len, + NULL, NULL); if (state->pasteout_data_len == 0) { - sfree(state->pasteout_data); - state->pasteout_data = NULL; + sfree(state->pasteout_data); + state->pasteout_data = NULL; } else { - state->pasteout_data = - sresize(state->pasteout_data, state->pasteout_data_len, char); + state->pasteout_data = + sresize(state->pasteout_data, state->pasteout_data_len, char); } /* The legacy X cut buffers go with PRIMARY, not any other clipboard */ @@ -2986,22 +2986,22 @@ static void gtkwin_clip_write( store_cutbuffer(inst, state->pasteout_data, state->pasteout_data_len); if (gtk_selection_owner_set(inst->area, state->atom, - inst->input_event_time)) { + inst->input_event_time)) { #if GTK_CHECK_VERSION(2,0,0) - gtk_selection_clear_targets(inst->area, state->atom); + gtk_selection_clear_targets(inst->area, state->atom); #endif - gtk_selection_add_target(inst->area, state->atom, - GDK_SELECTION_TYPE_STRING, 1); - if (state->pasteout_data_ctext) - gtk_selection_add_target(inst->area, state->atom, - compound_text_atom, 1); - if (state->pasteout_data_utf8) - gtk_selection_add_target(inst->area, state->atom, - utf8_string_atom, 1); + gtk_selection_add_target(inst->area, state->atom, + GDK_SELECTION_TYPE_STRING, 1); + if (state->pasteout_data_ctext) + gtk_selection_add_target(inst->area, state->atom, + compound_text_atom, 1); + if (state->pasteout_data_utf8) + gtk_selection_add_target(inst->area, state->atom, + utf8_string_atom, 1); } if (must_deselect) - term_lost_clipboard_ownership(inst->term, clipboard); + term_lost_clipboard_ownership(inst->term, clipboard); } static void selection_get(GtkWidget *widget, GtkSelectionData *seldata, @@ -3016,17 +3016,17 @@ static void selection_get(GtkWidget *widget, GtkSelectionData *seldata, return; if (target == utf8_string_atom) - gtk_selection_data_set(seldata, target, 8, + gtk_selection_data_set(seldata, target, 8, (unsigned char *)state->pasteout_data_utf8, - state->pasteout_data_utf8_len); + state->pasteout_data_utf8_len); else if (target == compound_text_atom) - gtk_selection_data_set(seldata, target, 8, + gtk_selection_data_set(seldata, target, 8, (unsigned char *)state->pasteout_data_ctext, - state->pasteout_data_ctext_len); + state->pasteout_data_ctext_len); else - gtk_selection_data_set(seldata, target, 8, + gtk_selection_data_set(seldata, target, 8, (unsigned char *)state->pasteout_data, - state->pasteout_data_len); + state->pasteout_data_len); } static gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata, @@ -3041,11 +3041,11 @@ static gint selection_clear(GtkWidget *widget, GdkEventSelection *seldata, term_lost_clipboard_ownership(inst->term, state->clipboard); if (state->pasteout_data) - sfree(state->pasteout_data); + sfree(state->pasteout_data); if (state->pasteout_data_ctext) - sfree(state->pasteout_data_ctext); + sfree(state->pasteout_data_ctext); if (state->pasteout_data_utf8) - sfree(state->pasteout_data_utf8); + sfree(state->pasteout_data_utf8); state->pasteout_data = NULL; state->pasteout_data_len = 0; state->pasteout_data_ctext = NULL; @@ -3067,21 +3067,21 @@ static void gtkwin_clip_request_paste(TermWin *tw, int clipboard) */ if (!inst->direct_to_font) { - /* - * First we attempt to retrieve the selection as a UTF-8 - * string (which we will convert to the correct code page - * before sending to the session, of course). If that - * fails, selection_received() will be informed and will - * fall back to an ordinary string. - */ - gtk_selection_convert(inst->area, state->atom, utf8_string_atom, - inst->input_event_time); + /* + * First we attempt to retrieve the selection as a UTF-8 + * string (which we will convert to the correct code page + * before sending to the session, of course). If that + * fails, selection_received() will be informed and will + * fall back to an ordinary string. + */ + gtk_selection_convert(inst->area, state->atom, utf8_string_atom, + inst->input_event_time); } else { - /* - * If we're in direct-to-font mode, we disable UTF-8 - * pasting, and go straight to ordinary string data. - */ - gtk_selection_convert(inst->area, state->atom, + /* + * If we're in direct-to-font mode, we disable UTF-8 + * pasting, and go straight to ordinary string data. + */ + gtk_selection_convert(inst->area, state->atom, GDK_SELECTION_TYPE_STRING, inst->input_event_time); } @@ -3112,25 +3112,25 @@ static void selection_received(GtkWidget *widget, GtkSelectionData *seldata, return; if (seldata_target == utf8_string_atom && seldata_length <= 0) { - /* - * Failed to get a UTF-8 selection string. Try compound - * text next. - */ - gtk_selection_convert(inst->area, state->atom, - compound_text_atom, - inst->input_event_time); - return; + /* + * Failed to get a UTF-8 selection string. Try compound + * text next. + */ + gtk_selection_convert(inst->area, state->atom, + compound_text_atom, + inst->input_event_time); + return; } if (seldata_target == compound_text_atom && seldata_length <= 0) { - /* - * Failed to get UTF-8 or compound text. Try an ordinary - * string. - */ - gtk_selection_convert(inst->area, state->atom, - GDK_SELECTION_TYPE_STRING, - inst->input_event_time); - return; + /* + * Failed to get UTF-8 or compound text. Try an ordinary + * string. + */ + gtk_selection_convert(inst->area, state->atom, + GDK_SELECTION_TYPE_STRING, + inst->input_event_time); + return; } /* @@ -3138,42 +3138,42 @@ static void selection_received(GtkWidget *widget, GtkSelectionData *seldata, * we have to ignore the data. */ if (seldata_length > 0 && - seldata_type != GDK_SELECTION_TYPE_STRING && - seldata_type != compound_text_atom && - seldata_type != utf8_string_atom) - return; + seldata_type != GDK_SELECTION_TYPE_STRING && + seldata_type != compound_text_atom && + seldata_type != utf8_string_atom) + return; /* * If we have no data, try looking in a cut buffer. */ if (seldata_length <= 0) { #ifndef NOT_X_WINDOWS - text = retrieve_cutbuffer(inst, &length); - if (length == 0) - return; - /* Xterm is rumoured to expect Latin-1, though I havn't checked the - * source, so use that as a de-facto standard. */ - charset = CS_ISO8859_1; - free_required = true; + text = retrieve_cutbuffer(inst, &length); + if (length == 0) + return; + /* Xterm is rumoured to expect Latin-1, though I havn't checked the + * source, so use that as a de-facto standard. */ + charset = CS_ISO8859_1; + free_required = true; #else return; #endif } else { - /* - * Convert COMPOUND_TEXT into UTF-8. - */ - if (seldata_type == compound_text_atom) { + /* + * Convert COMPOUND_TEXT into UTF-8. + */ + if (seldata_type == compound_text_atom) { #ifndef NOT_X_WINDOWS XTextProperty tp; int ret, count; - tp.value = (unsigned char *)seldata_data; - tp.encoding = (Atom) seldata_type; - tp.format = gtk_selection_data_get_format(seldata); - tp.nitems = seldata_length; - ret = inst->disp == NULL ? -1 : + tp.value = (unsigned char *)seldata_data; + tp.encoding = (Atom) seldata_type; + tp.format = gtk_selection_data_get_format(seldata); + tp.nitems = seldata_length; + ret = inst->disp == NULL ? -1 : Xutf8TextPropertyToTextList(inst->disp, &tp, &list, &count); - if (ret == 0 && count == 1) { + if (ret == 0 && count == 1) { text = list[0]; length = strlen(list[0]); charset = CS_UTF8; @@ -3181,20 +3181,20 @@ static void selection_received(GtkWidget *widget, GtkSelectionData *seldata, } else #endif { - /* - * Compound text failed; fall back to STRING. - */ - gtk_selection_convert(inst->area, state->atom, - GDK_SELECTION_TYPE_STRING, - inst->input_event_time); - return; - } - } else { - text = (char *)seldata_data; - length = seldata_length; - charset = (seldata_type == utf8_string_atom ? - CS_UTF8 : inst->ucsdata.line_codepage); - } + /* + * Compound text failed; fall back to STRING. + */ + gtk_selection_convert(inst->area, state->atom, + GDK_SELECTION_TYPE_STRING, + inst->input_event_time); + return; + } + } else { + text = (char *)seldata_data; + length = seldata_length; + charset = (seldata_type == utf8_string_atom ? + CS_UTF8 : inst->ucsdata.line_codepage); + } } paste = snewn(length, wchar_t); @@ -3206,9 +3206,9 @@ static void selection_received(GtkWidget *widget, GtkSelectionData *seldata, #ifndef NOT_X_WINDOWS if (free_list_required) - XFreeStringList(list); + XFreeStringList(list); if (free_required) - XFree(text); + XFree(text); #endif } @@ -3295,7 +3295,7 @@ static void set_window_titles(GtkFrontend *inst) */ gtk_window_set_title(GTK_WINDOW(inst->window), inst->wintitle); if (!conf_get_bool(inst->conf, CONF_win_name_always)) - gdk_window_set_icon_name(gtk_widget_get_window(inst->window), + gdk_window_set_icon_name(gtk_widget_get_window(inst->window), inst->icontitle); } @@ -3328,7 +3328,7 @@ static void gtkwin_set_scrollbar(TermWin *tw, int total, int start, int page) { GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (!conf_get_bool(inst->conf, CONF_scrollbar)) - return; + return; inst->ignore_sbar = true; gtk_adjustment_set_lower(inst->sbar_adjust, 0); gtk_adjustment_set_upper(inst->sbar_adjust, total); @@ -3345,9 +3345,9 @@ static void gtkwin_set_scrollbar(TermWin *tw, int total, int start, int page) void scrollbar_moved(GtkAdjustment *adj, GtkFrontend *inst) { if (!conf_get_bool(inst->conf, CONF_scrollbar)) - return; + return; if (!inst->ignore_sbar) - term_scroll(inst->term, 1, (int)gtk_adjustment_get_value(adj)); + term_scroll(inst->term, 1, (int)gtk_adjustment_get_value(adj)); } static void show_scrollbar(GtkFrontend *inst, gboolean visible) @@ -3393,7 +3393,7 @@ static bool gtkwin_setup_draw_ctx(TermWin *tw) GtkFrontend *inst = container_of(tw, GtkFrontend, termwin); if (!gtk_widget_get_window(inst->area)) - return false; + return false; inst->uctx.type = inst->drawtype; #ifdef DRAW_TEXT_GDK @@ -3509,16 +3509,16 @@ static void draw_set_colour_rgb(GtkFrontend *inst, optionalrgb orgb, bool dim) #ifdef DRAW_TEXT_GDK if (inst->uctx.type == DRAWTYPE_GDK) { #if GTK_CHECK_VERSION(2,0,0) - GdkColor color; - color.red = orgb.r * 256; - color.green = orgb.g * 256; - color.blue = orgb.b * 256; + GdkColor color; + color.red = orgb.r * 256; + color.green = orgb.g * 256; + color.blue = orgb.b * 256; if (dim) { color.red = color.red * 2 / 3; color.green = color.green * 2 / 3; color.blue = color.blue * 2 / 3; } - gdk_gc_set_rgb_fg_color(inst->uctx.u.gdk.gc, &color); + gdk_gc_set_rgb_fg_color(inst->uctx.u.gdk.gc, &color); #else /* Poor GTK1 fallback */ gdk_gc_set_foreground(inst->uctx.u.gdk.gc, &inst->cols[256]); @@ -3562,12 +3562,12 @@ static void draw_clip(GtkFrontend *inst, int x, int y, int w, int h) { #ifdef DRAW_TEXT_GDK if (inst->uctx.type == DRAWTYPE_GDK) { - GdkRectangle r; + GdkRectangle r; - r.x = x; - r.y = y; - r.width = w; - r.height = h; + r.x = x; + r.y = y; + r.width = w; + r.height = h; gdk_gc_set_clip_rectangle(inst->uctx.u.gdk.gc, &r); } @@ -3658,15 +3658,15 @@ static void draw_stretch_after(GtkFrontend *inst, int x, int y, #ifdef DRAW_TEXT_GDK #ifndef NO_BACKING_PIXMAPS if (inst->uctx.type == DRAWTYPE_GDK) { - /* - * I can't find any plausible StretchBlt equivalent in the X - * server, so I'm going to do this the slow and painful way. - * This will involve repeated calls to gdk_draw_pixmap() to - * stretch the text horizontally. It's O(N^2) in time and O(N) - * in network bandwidth, but you try thinking of a better way. - * :-( - */ - int i; + /* + * I can't find any plausible StretchBlt equivalent in the X + * server, so I'm going to do this the slow and painful way. + * This will involve repeated calls to gdk_draw_pixmap() to + * stretch the text horizontally. It's O(N^2) in time and O(N) + * in network bandwidth, but you try thinking of a better way. + * :-( + */ + int i; if (wdouble) { for (i = 0; i < w; i++) { gdk_draw_pixmap(inst->uctx.u.gdk.target, @@ -3679,22 +3679,22 @@ static void draw_stretch_after(GtkFrontend *inst, int x, int y, w *= 2; } - if (hdouble) { - int dt, db; - /* Now stretch vertically, in the same way. */ - if (hbothalf) - dt = 0, db = 1; - else - dt = 1, db = 0; - for (i = 0; i < h; i += 2) { - gdk_draw_pixmap(inst->uctx.u.gdk.target, + if (hdouble) { + int dt, db; + /* Now stretch vertically, in the same way. */ + if (hbothalf) + dt = 0, db = 1; + else + dt = 1, db = 0; + for (i = 0; i < h; i += 2) { + gdk_draw_pixmap(inst->uctx.u.gdk.target, inst->uctx.u.gdk.gc, inst->uctx.u.gdk.target, x, y + dt*i + db, - x, y + dt*(i+1), - w, h-i-1); - } - } + x, y + dt*(i+1), + w, h-i-1); + } + } } #else #error No way to implement stretching in GDK without a reliable backing pixmap @@ -3740,10 +3740,10 @@ static void do_text_internal( gdk_visual_get_depth(gtk_widget_get_visual(inst->area)) == 1; if (attr & TATTR_COMBINING) { - ncombining = len; - len = 1; + ncombining = len; + len = 1; } else - ncombining = 1; + ncombining = 1; if (monochrome) truecolour.fg = truecolour.bg = optionalrgb_none; @@ -3753,74 +3753,74 @@ static void do_text_internal( if (!!(attr & ATTR_REVERSE) ^ (monochrome && (attr & TATTR_ACTCURS))) { struct optionalrgb trgb; - t = nfg; - nfg = nbg; - nbg = t; + t = nfg; + nfg = nbg; + nbg = t; trgb = truecolour.fg; truecolour.fg = truecolour.bg; truecolour.bg = trgb; } if ((inst->bold_style & 2) && (attr & ATTR_BOLD)) { - if (nfg < 16) nfg |= 8; - else if (nfg >= 256) nfg |= 1; + if (nfg < 16) nfg |= 8; + else if (nfg >= 256) nfg |= 1; } if ((inst->bold_style & 2) && (attr & ATTR_BLINK)) { - if (nbg < 16) nbg |= 8; - else if (nbg >= 256) nbg |= 1; + if (nbg < 16) nbg |= 8; + else if (nbg >= 256) nbg |= 1; } if ((attr & TATTR_ACTCURS) && !monochrome) { truecolour.fg = truecolour.bg = optionalrgb_none; - nfg = 260; - nbg = 261; + nfg = 260; + nbg = 261; attr &= ~ATTR_DIM; /* don't dim the cursor */ } fontid = 0; if (attr & ATTR_WIDE) { - widefactor = 2; - fontid |= 2; + widefactor = 2; + fontid |= 2; } else { - widefactor = 1; + widefactor = 1; } if ((attr & ATTR_BOLD) && (inst->bold_style & 1)) { - bold = true; - fontid |= 1; + bold = true; + fontid |= 1; } else { - bold = false; + bold = false; } if (!inst->fonts[fontid]) { - int i; - /* - * Fall back through font ids with subsets of this one's - * set bits, in order. - */ - for (i = fontid; i-- > 0 ;) { - if (i & ~fontid) - continue; /* some other bit is set */ - if (inst->fonts[i]) { - fontid = i; - break; - } - } - assert(inst->fonts[fontid]); /* we should at least have hit zero */ + int i; + /* + * Fall back through font ids with subsets of this one's + * set bits, in order. + */ + for (i = fontid; i-- > 0 ;) { + if (i & ~fontid) + continue; /* some other bit is set */ + if (inst->fonts[i]) { + fontid = i; + break; + } + } + assert(inst->fonts[fontid]); /* we should at least have hit zero */ } if ((lattr & LATTR_MODE) != LATTR_NORM) { - x *= 2; - if (x >= inst->term->cols) - return; - if (x + len*2*widefactor > inst->term->cols) { - len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ + x *= 2; + if (x >= inst->term->cols) + return; + if (x + len*2*widefactor > inst->term->cols) { + len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ if (len == 0) return; /* rounded down half a double-width char to zero */ } - rlen = len * 2; + rlen = len * 2; } else - rlen = len; + rlen = len; draw_clip(inst, x*inst->font_width+inst->window_border, @@ -3839,18 +3839,18 @@ static void do_text_internal( } if (truecolour.bg.enabled) - draw_set_colour_rgb(inst, truecolour.bg, attr & ATTR_DIM); + draw_set_colour_rgb(inst, truecolour.bg, attr & ATTR_DIM); else - draw_set_colour(inst, nbg, attr & ATTR_DIM); + draw_set_colour(inst, nbg, attr & ATTR_DIM); draw_rectangle(inst, true, x*inst->font_width+inst->window_border, y*inst->font_height+inst->window_border, rlen*widefactor*inst->font_width, inst->font_height); if (truecolour.fg.enabled) - draw_set_colour_rgb(inst, truecolour.fg, attr & ATTR_DIM); + draw_set_colour_rgb(inst, truecolour.fg, attr & ATTR_DIM); else - draw_set_colour(inst, nfg, attr & ATTR_DIM); + draw_set_colour(inst, nfg, attr & ATTR_DIM); if (ncombining > 1) { assert(len == 1); unifont_draw_combining(&inst->uctx, inst->fonts[fontid], @@ -3869,9 +3869,9 @@ static void do_text_internal( } if (attr & ATTR_UNDER) { - int uheight = inst->fonts[0]->ascent + 1; - if (uheight >= inst->font_height) - uheight = inst->font_height - 1; + int uheight = inst->fonts[0]->ascent + 1; + if (uheight >= inst->font_height) + uheight = inst->font_height - 1; draw_line(inst, x*inst->font_width+inst->window_border, y*inst->font_height + uheight + inst->window_border, (x+len)*widefactor*inst->font_width-1+inst->window_border, @@ -3899,18 +3899,18 @@ static void gtkwin_draw_text( do_text_internal(inst, x, y, text, len, attr, lattr, truecolour); if (attr & ATTR_WIDE) { - widefactor = 2; + widefactor = 2; } else { - widefactor = 1; + widefactor = 1; } if ((lattr & LATTR_MODE) != LATTR_NORM) { - x *= 2; - if (x >= inst->term->cols) - return; - if (x + len*2*widefactor > inst->term->cols) - len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ - len *= 2; + x *= 2; + if (x >= inst->term->cols) + return; + if (x + len*2*widefactor > inst->term->cols) + len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ + len *= 2; } draw_update(inst, @@ -3928,94 +3928,94 @@ static void gtkwin_draw_cursor( int widefactor; if (attr & TATTR_PASCURS) { - attr &= ~TATTR_PASCURS; - passive = true; + attr &= ~TATTR_PASCURS; + passive = true; } else - passive = false; + passive = false; if ((attr & TATTR_ACTCURS) && inst->cursor_type != 0) { - attr &= ~TATTR_ACTCURS; + attr &= ~TATTR_ACTCURS; active = true; } else active = false; do_text_internal(inst, x, y, text, len, attr, lattr, truecolour); if (attr & TATTR_COMBINING) - len = 1; + len = 1; if (attr & ATTR_WIDE) { - widefactor = 2; + widefactor = 2; } else { - widefactor = 1; + widefactor = 1; } if ((lattr & LATTR_MODE) != LATTR_NORM) { - x *= 2; - if (x >= inst->term->cols) - return; - if (x + len*2*widefactor > inst->term->cols) - len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ - len *= 2; + x *= 2; + if (x >= inst->term->cols) + return; + if (x + len*2*widefactor > inst->term->cols) + len = (inst->term->cols-x)/2/widefactor;/* trim to LH half */ + len *= 2; } if (inst->cursor_type == 0) { - /* - * An active block cursor will already have been done by - * the above do_text call, so we only need to do anything - * if it's passive. - */ - if (passive) { + /* + * An active block cursor will already have been done by + * the above do_text call, so we only need to do anything + * if it's passive. + */ + if (passive) { draw_set_colour(inst, 261, false); draw_rectangle(inst, false, x*inst->font_width+inst->window_border, y*inst->font_height+inst->window_border, len*widefactor*inst->font_width-1, inst->font_height-1); - } + } } else { - int uheight; - int startx, starty, dx, dy, length, i; + int uheight; + int startx, starty, dx, dy, length, i; - int char_width; + int char_width; - if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM) - char_width = 2*inst->font_width; - else - char_width = inst->font_width; + if ((attr & ATTR_WIDE) || (lattr & LATTR_MODE) != LATTR_NORM) + char_width = 2*inst->font_width; + else + char_width = inst->font_width; - if (inst->cursor_type == 1) { - uheight = inst->fonts[0]->ascent + 1; - if (uheight >= inst->font_height) - uheight = inst->font_height - 1; + if (inst->cursor_type == 1) { + uheight = inst->fonts[0]->ascent + 1; + if (uheight >= inst->font_height) + uheight = inst->font_height - 1; - startx = x * inst->font_width + inst->window_border; - starty = y * inst->font_height + inst->window_border + uheight; - dx = 1; - dy = 0; - length = len * widefactor * char_width; - } else { - int xadjust = 0; - if (attr & TATTR_RIGHTCURS) - xadjust = char_width - 1; - startx = x * inst->font_width + inst->window_border + xadjust; - starty = y * inst->font_height + inst->window_border; - dx = 0; - dy = 1; - length = inst->font_height; - } + startx = x * inst->font_width + inst->window_border; + starty = y * inst->font_height + inst->window_border + uheight; + dx = 1; + dy = 0; + length = len * widefactor * char_width; + } else { + int xadjust = 0; + if (attr & TATTR_RIGHTCURS) + xadjust = char_width - 1; + startx = x * inst->font_width + inst->window_border + xadjust; + starty = y * inst->font_height + inst->window_border; + dx = 0; + dy = 1; + length = inst->font_height; + } draw_set_colour(inst, 261, false); - if (passive) { - for (i = 0; i < length; i++) { - if (i % 2 == 0) { - draw_point(inst, startx, starty); - } - startx += dx; - starty += dy; - } - } else if (active) { - draw_line(inst, startx, starty, + if (passive) { + for (i = 0; i < length; i++) { + if (i % 2 == 0) { + draw_point(inst, startx, starty); + } + startx += dx; + starty += dy; + } + } else if (active) { + draw_line(inst, startx, starty, startx + (length-1) * dx, starty + (length-1) * dy); - } /* else no cursor (e.g., blinked off) */ + } /* else no cursor (e.g., blinked off) */ } draw_update(inst, @@ -4251,43 +4251,43 @@ char *setup_fonts_ucs(GtkFrontend *inst) fs = conf_get_fontspec(inst->conf, CONF_boldfont); if (shadowbold || !fs->name[0]) { - fonts[1] = NULL; + fonts[1] = NULL; } else { - fonts[1] = multifont_create(inst->area, fs->name, false, true, + fonts[1] = multifont_create(inst->area, fs->name, false, true, shadowboldoffset, shadowbold); - if (!fonts[1]) { + if (!fonts[1]) { if (fonts[0]) unifont_destroy(fonts[0]); - return dupprintf("unable to load bold font \"%s\"", fs->name); - } + return dupprintf("unable to load bold font \"%s\"", fs->name); + } } fs = conf_get_fontspec(inst->conf, CONF_widefont); if (fs->name[0]) { - fonts[2] = multifont_create(inst->area, fs->name, true, false, + fonts[2] = multifont_create(inst->area, fs->name, true, false, shadowboldoffset, shadowbold); - if (!fonts[2]) { + if (!fonts[2]) { for (i = 0; i < 2; i++) if (fonts[i]) unifont_destroy(fonts[i]); return dupprintf("unable to load wide font \"%s\"", fs->name); - } + } } else { - fonts[2] = NULL; + fonts[2] = NULL; } fs = conf_get_fontspec(inst->conf, CONF_wideboldfont); if (shadowbold || !fs->name[0]) { - fonts[3] = NULL; + fonts[3] = NULL; } else { - fonts[3] = multifont_create(inst->area, fs->name, true, true, + fonts[3] = multifont_create(inst->area, fs->name, true, true, shadowboldoffset, shadowbold); - if (!fonts[3]) { + if (!fonts[3]) { for (i = 0; i < 3; i++) if (fonts[i]) unifont_destroy(fonts[i]); - return dupprintf("unable to load wide bold font \"%s\"", fs->name); - } + return dupprintf("unable to load wide bold font \"%s\"", fs->name); + } } /* @@ -4315,10 +4315,10 @@ char *setup_fonts_ucs(GtkFrontend *inst) } inst->direct_to_font = init_ucs(&inst->ucsdata, - conf_get_str(inst->conf, CONF_line_codepage), - conf_get_bool(inst->conf, CONF_utf8_override), - inst->fonts[0]->public_charset, - conf_get_int(inst->conf, CONF_vtmode)); + conf_get_str(inst->conf, CONF_line_codepage), + conf_get_bool(inst->conf, CONF_utf8_override), + inst->fonts[0]->public_charset, + conf_get_int(inst->conf, CONF_vtmode)); inst->drawtype = inst->fonts[0]->preferred_drawtype; @@ -4474,7 +4474,7 @@ void reset_terminal_menuitem(GtkMenuItem *item, gpointer data) GtkFrontend *inst = (GtkFrontend *)data; term_pwron(inst->term, true); if (inst->ldisc) - ldisc_echoedit_update(inst->ldisc); + ldisc_echoedit_update(inst->ldisc); } void copy_clipboard_menuitem(GtkMenuItem *item, gpointer data) @@ -4615,9 +4615,9 @@ static void after_change_settings_dialog(void *vctx, int retval) { /* This maps colour indices in inst->conf to those used in inst->cols. */ static const int ww[] = { - 256, 257, 258, 259, 260, 261, - 0, 8, 1, 9, 2, 10, 3, 11, - 4, 12, 5, 13, 6, 14, 7, 15 + 256, 257, 258, 259, 260, 261, + 0, 8, 1, 9, 2, 10, 3, 11, + 4, 12, 5, 13, 6, 14, 7, 15 }; struct after_change_settings_dialog_ctx ctx = *(struct after_change_settings_dialog_ctx *)vctx; @@ -4652,7 +4652,7 @@ static void after_change_settings_dialog(void *vctx, int retval) if (inst->backend) backend_reconfig(inst->backend, inst->conf); - cache_conf_values(inst); + cache_conf_values(inst); /* * Just setting inst->conf is sufficient to cause colour @@ -4663,26 +4663,26 @@ static void after_change_settings_dialog(void *vctx, int retval) * most likely to want an immediate update. */ for (i = 0; i < NCFGCOLOURS; i++) { - for (j = 0; j < 3; j++) - if (conf_get_int_int(oldconf, CONF_colours, i*3+j) != - conf_get_int_int(newconf, CONF_colours, i*3+j)) - break; - if (j < 3) { + for (j = 0; j < 3; j++) + if (conf_get_int_int(oldconf, CONF_colours, i*3+j) != + conf_get_int_int(newconf, CONF_colours, i*3+j)) + break; + if (j < 3) { real_palette_set(inst, ww[i], - conf_get_int_int(newconf,CONF_colours,i*3+0), - conf_get_int_int(newconf,CONF_colours,i*3+1), - conf_get_int_int(newconf,CONF_colours,i*3+2)); + conf_get_int_int(newconf,CONF_colours,i*3+0), + conf_get_int_int(newconf,CONF_colours,i*3+1), + conf_get_int_int(newconf,CONF_colours,i*3+2)); - /* - * If the default background has changed, we must - * repaint the space in between the window border - * and the text area. - */ - if (ww[i] == 258) { - set_window_background(inst); - draw_backing_rect(inst); - } - } + /* + * If the default background has changed, we must + * repaint the space in between the window border + * and the text area. + */ + if (ww[i] == 258) { + set_window_background(inst); + draw_backing_rect(inst); + } + } } need_size = false; @@ -4692,48 +4692,48 @@ static void after_change_settings_dialog(void *vctx, int retval) * from one end to the other of the window, do so now. */ if (conf_get_bool(oldconf, CONF_scrollbar) != - conf_get_bool(newconf, CONF_scrollbar)) { + conf_get_bool(newconf, CONF_scrollbar)) { show_scrollbar(inst, conf_get_bool(newconf, CONF_scrollbar)); need_size = true; } if (conf_get_bool(oldconf, CONF_scrollbar_on_left) != - conf_get_bool(newconf, CONF_scrollbar_on_left)) { + conf_get_bool(newconf, CONF_scrollbar_on_left)) { gtk_box_reorder_child(inst->hbox, inst->sbar, conf_get_bool(newconf, CONF_scrollbar_on_left) - ? 0 : 1); + ? 0 : 1); } /* * Change the window title, if required. */ if (strcmp(conf_get_str(oldconf, CONF_wintitle), - conf_get_str(newconf, CONF_wintitle))) + conf_get_str(newconf, CONF_wintitle))) win_set_title(&inst->termwin, conf_get_str(newconf, CONF_wintitle)); - set_window_titles(inst); + set_window_titles(inst); /* * Redo the whole tangled fonts and Unicode mess if * necessary. */ if (strcmp(conf_get_fontspec(oldconf, CONF_font)->name, - conf_get_fontspec(newconf, CONF_font)->name) || - strcmp(conf_get_fontspec(oldconf, CONF_boldfont)->name, - conf_get_fontspec(newconf, CONF_boldfont)->name) || - strcmp(conf_get_fontspec(oldconf, CONF_widefont)->name, - conf_get_fontspec(newconf, CONF_widefont)->name) || - strcmp(conf_get_fontspec(oldconf, CONF_wideboldfont)->name, - conf_get_fontspec(newconf, CONF_wideboldfont)->name) || - strcmp(conf_get_str(oldconf, CONF_line_codepage), - conf_get_str(newconf, CONF_line_codepage)) || - conf_get_bool(oldconf, CONF_utf8_override) != - conf_get_bool(newconf, CONF_utf8_override) || - conf_get_int(oldconf, CONF_vtmode) != - conf_get_int(newconf, CONF_vtmode) || - conf_get_bool(oldconf, CONF_shadowbold) != - conf_get_bool(newconf, CONF_shadowbold) || - conf_get_int(oldconf, CONF_shadowboldoffset) != - conf_get_int(newconf, CONF_shadowboldoffset)) { + conf_get_fontspec(newconf, CONF_font)->name) || + strcmp(conf_get_fontspec(oldconf, CONF_boldfont)->name, + conf_get_fontspec(newconf, CONF_boldfont)->name) || + strcmp(conf_get_fontspec(oldconf, CONF_widefont)->name, + conf_get_fontspec(newconf, CONF_widefont)->name) || + strcmp(conf_get_fontspec(oldconf, CONF_wideboldfont)->name, + conf_get_fontspec(newconf, CONF_wideboldfont)->name) || + strcmp(conf_get_str(oldconf, CONF_line_codepage), + conf_get_str(newconf, CONF_line_codepage)) || + conf_get_bool(oldconf, CONF_utf8_override) != + conf_get_bool(newconf, CONF_utf8_override) || + conf_get_int(oldconf, CONF_vtmode) != + conf_get_int(newconf, CONF_vtmode) || + conf_get_bool(oldconf, CONF_shadowbold) != + conf_get_bool(newconf, CONF_shadowbold) || + conf_get_int(oldconf, CONF_shadowboldoffset) != + conf_get_int(newconf, CONF_shadowboldoffset)) { char *errmsg = setup_fonts_ucs(inst); if (errmsg) { char *msgboxtext = @@ -4754,41 +4754,41 @@ static void after_change_settings_dialog(void *vctx, int retval) * Resize the window. */ if (conf_get_int(oldconf, CONF_width) != - conf_get_int(newconf, CONF_width) || - conf_get_int(oldconf, CONF_height) != - conf_get_int(newconf, CONF_height) || - conf_get_int(oldconf, CONF_window_border) != - conf_get_int(newconf, CONF_window_border) || - need_size) { + conf_get_int(newconf, CONF_width) || + conf_get_int(oldconf, CONF_height) != + conf_get_int(newconf, CONF_height) || + conf_get_int(oldconf, CONF_window_border) != + conf_get_int(newconf, CONF_window_border) || + need_size) { set_geom_hints(inst); win_request_resize(&inst->termwin, conf_get_int(newconf, CONF_width), conf_get_int(newconf, CONF_height)); } else { - /* - * The above will have caused a call to term_size() for - * us if it happened. If the user has fiddled with only - * the scrollback size, the above will not have - * happened and we will need an explicit term_size() - * here. - */ - if (conf_get_int(oldconf, CONF_savelines) != - conf_get_int(newconf, CONF_savelines)) - term_size(inst->term, inst->term->rows, inst->term->cols, - conf_get_int(newconf, CONF_savelines)); - } + /* + * The above will have caused a call to term_size() for + * us if it happened. If the user has fiddled with only + * the scrollback size, the above will not have + * happened and we will need an explicit term_size() + * here. + */ + if (conf_get_int(oldconf, CONF_savelines) != + conf_get_int(newconf, CONF_savelines)) + term_size(inst->term, inst->term->rows, inst->term->cols, + conf_get_int(newconf, CONF_savelines)); + } term_invalidate(inst->term); - /* - * We do an explicit full redraw here to ensure the window - * border has been redrawn as well as the text area. - */ - gtk_widget_queue_draw(inst->area); + /* + * We do an explicit full redraw here to ensure the window + * border has been redrawn as well as the text area. + */ + gtk_widget_queue_draw(inst->area); - conf_free(oldconf); + conf_free(oldconf); } else { - conf_free(newconf); + conf_free(newconf); } } @@ -4871,9 +4871,9 @@ void restart_session_menuitem(GtkMenuItem *item, gpointer data) if (!inst->backend) { logevent(inst->logctx, "----- Session restarted -----"); - term_pwron(inst->term, false); - start_backend(inst); - inst->exited = false; + term_pwron(inst->term, false); + start_backend(inst); + inst->exited = false; } } @@ -4932,15 +4932,15 @@ static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data) int i; gtk_container_foreach(GTK_CONTAINER(inst->sessionsmenu), - (GtkCallback)gtk_widget_destroy, NULL); + (GtkCallback)gtk_widget_destroy, NULL); get_sesslist(&sesslist, true); /* skip sesslist.sessions[0] == Default Settings */ for (i = 1; i < sesslist.nsessions; i++) { - GtkWidget *menuitem = - gtk_menu_item_new_with_label(sesslist.sessions[i]); - gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem); - gtk_widget_show(menuitem); + GtkWidget *menuitem = + gtk_menu_item_new_with_label(sesslist.sessions[i]); + gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem); + gtk_widget_show(menuitem); g_object_set_data(G_OBJECT(menuitem), "user-data", dupstr(sesslist.sessions[i])); g_signal_connect(G_OBJECT(menuitem), "activate", @@ -4951,17 +4951,17 @@ static void update_savedsess_menu(GtkMenuItem *menuitem, gpointer data) inst); } if (sesslist.nsessions <= 1) { - GtkWidget *menuitem = - gtk_menu_item_new_with_label("(No sessions)"); - gtk_widget_set_sensitive(menuitem, false); - gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem); - gtk_widget_show(menuitem); + GtkWidget *menuitem = + gtk_menu_item_new_with_label("(No sessions)"); + gtk_widget_set_sensitive(menuitem, false); + gtk_container_add(GTK_CONTAINER(inst->sessionsmenu), menuitem); + gtk_widget_show(menuitem); } get_sesslist(&sesslist, false); /* free up */ } void set_window_icon(GtkWidget *window, const char *const *const *icon, - int n_icon) + int n_icon) { #if GTK_CHECK_VERSION(2,0,0) GList *iconlist; @@ -4972,7 +4972,7 @@ void set_window_icon(GtkWidget *window, const char *const *const *icon, #endif if (!n_icon) - return; + return; gtk_widget_realize(window); #if GTK_CHECK_VERSION(2,0,0) @@ -4987,10 +4987,10 @@ void set_window_icon(GtkWidget *window, const char *const *const *icon, #if GTK_CHECK_VERSION(2,0,0) iconlist = NULL; for (n = 0; n < n_icon; n++) { - iconlist = - g_list_append(iconlist, - gdk_pixbuf_new_from_xpm_data((const gchar **) - icon[n])); + iconlist = + g_list_append(iconlist, + gdk_pixbuf_new_from_xpm_data((const gchar **) + icon[n])); } gtk_window_set_icon_list(GTK_WINDOW(window), iconlist); #endif @@ -5006,43 +5006,43 @@ static void gtk_seat_update_specials_menu(Seat *seat) if (inst->backend) specials = backend_get_specials(inst->backend); else - specials = NULL; + specials = NULL; /* I believe this disposes of submenus too. */ gtk_container_foreach(GTK_CONTAINER(inst->specialsmenu), - (GtkCallback)gtk_widget_destroy, NULL); + (GtkCallback)gtk_widget_destroy, NULL); if (specials) { - int i; - GtkWidget *menu = inst->specialsmenu; - /* A lame "stack" for submenus that will do for now. */ - GtkWidget *saved_menu = NULL; - int nesting = 1; - for (i = 0; nesting > 0; i++) { - GtkWidget *menuitem = NULL; - switch (specials[i].code) { - case SS_SUBMENU: - assert (nesting < 2); - saved_menu = menu; /* XXX lame stacking */ - menu = gtk_menu_new(); - menuitem = gtk_menu_item_new_with_label(specials[i].name); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu); - gtk_container_add(GTK_CONTAINER(saved_menu), menuitem); - gtk_widget_show(menuitem); - menuitem = NULL; - nesting++; - break; - case SS_EXITMENU: - nesting--; - if (nesting) { - menu = saved_menu; /* XXX lame stacking */ - saved_menu = NULL; - } - break; - case SS_SEP: - menuitem = gtk_menu_item_new(); - break; - default: - menuitem = gtk_menu_item_new_with_label(specials[i].name); + int i; + GtkWidget *menu = inst->specialsmenu; + /* A lame "stack" for submenus that will do for now. */ + GtkWidget *saved_menu = NULL; + int nesting = 1; + for (i = 0; nesting > 0; i++) { + GtkWidget *menuitem = NULL; + switch (specials[i].code) { + case SS_SUBMENU: + assert (nesting < 2); + saved_menu = menu; /* XXX lame stacking */ + menu = gtk_menu_new(); + menuitem = gtk_menu_item_new_with_label(specials[i].name); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), menu); + gtk_container_add(GTK_CONTAINER(saved_menu), menuitem); + gtk_widget_show(menuitem); + menuitem = NULL; + nesting++; + break; + case SS_EXITMENU: + nesting--; + if (nesting) { + menu = saved_menu; /* XXX lame stacking */ + saved_menu = NULL; + } + break; + case SS_SEP: + menuitem = gtk_menu_item_new(); + break; + default: + menuitem = gtk_menu_item_new_with_label(specials[i].name); { SessionSpecial *sc = snew(SessionSpecial); *sc = specials[i]; /* structure copy */ @@ -5051,18 +5051,18 @@ static void gtk_seat_update_specials_menu(Seat *seat) } g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(special_menuitem), inst); - break; - } - if (menuitem) { - gtk_container_add(GTK_CONTAINER(menu), menuitem); - gtk_widget_show(menuitem); - } - } - gtk_widget_show(inst->specialsitem1); - gtk_widget_show(inst->specialsitem2); + break; + } + if (menuitem) { + gtk_container_add(GTK_CONTAINER(menu), menuitem); + gtk_widget_show(menuitem); + } + } + gtk_widget_show(inst->specialsitem1); + gtk_widget_show(inst->specialsitem2); } else { - gtk_widget_hide(inst->specialsitem1); - gtk_widget_hide(inst->specialsitem2); + gtk_widget_hide(inst->specialsitem1); + gtk_widget_hide(inst->specialsitem2); } } @@ -5085,20 +5085,20 @@ static void start_backend(GtkFrontend *inst) conf_get_bool(inst->conf, CONF_tcp_keepalives)); if (error) { - seat_connection_fatal(&inst->seat, + seat_connection_fatal(&inst->seat, "Unable to open connection to %s:\n%s", - conf_dest(inst->conf), error); - inst->exited = true; + conf_dest(inst->conf), error); + inst->exited = true; return; } s = conf_get_str(inst->conf, CONF_wintitle); if (s[0]) { - set_title_and_icon(inst, s, s); + set_title_and_icon(inst, s, s); } else { - char *title = make_default_wintitle(realhost); - set_title_and_icon(inst, title, title); - sfree(title); + char *title = make_default_wintitle(realhost); + set_title_and_icon(inst, title, title); + sfree(title); } sfree(realhost); @@ -5119,9 +5119,9 @@ static void get_monitor_geometry(GtkWidget *widget, GdkRectangle *geometry) # if GTK_CHECK_VERSION(3,22,0) GdkMonitor *monitor; if (gdkwindow) - monitor = gdk_display_get_monitor_at_window(display, gdkwindow); + monitor = gdk_display_get_monitor_at_window(display, gdkwindow); else - monitor = gdk_display_get_monitor(display, 0); + monitor = gdk_display_get_monitor(display, 0); gdk_monitor_get_geometry(monitor, geometry); # else GdkScreen *screen = gdk_display_get_default_screen(display); @@ -5348,7 +5348,7 @@ void new_session_window(Conf *conf, const char *geometry_string) if (inst->gravity & 2) y += (monitor_geometry.height - hp); gtk_window_set_gravity(GTK_WINDOW(inst->window), gravities[inst->gravity & 3]); - gtk_window_move(GTK_WINDOW(inst->window), x, y); + gtk_window_move(GTK_WINDOW(inst->window), x, y); } #else if (inst->gotpos) { @@ -5357,8 +5357,8 @@ void new_session_window(Conf *conf, const char *geometry_string) gtk_widget_size_request(GTK_WIDGET(inst->window), &req); if (inst->gravity & 1) x += gdk_screen_width() - req.width; if (inst->gravity & 2) y += gdk_screen_height() - req.height; - gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE); - gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y); + gtk_window_set_position(GTK_WINDOW(inst->window), GTK_WIN_POS_NONE); + gtk_widget_set_uposition(GTK_WIDGET(inst->window), x, y); } #endif @@ -5407,9 +5407,9 @@ void new_session_window(Conf *conf, const char *geometry_string) g_signal_connect(G_OBJECT(inst->sbar_adjust), "value_changed", G_CALLBACK(scrollbar_moved), inst); gtk_widget_add_events(GTK_WIDGET(inst->area), - GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | - GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | - GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK + GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | + GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | + GDK_POINTER_MOTION_MASK | GDK_BUTTON_MOTION_MASK #if GTK_CHECK_VERSION(3,4,0) | GDK_SMOOTH_SCROLL_MASK #endif @@ -5425,10 +5425,10 @@ void new_session_window(Conf *conf, const char *geometry_string) * Set up the Ctrl+rightclick context menu. */ { - GtkWidget *menuitem; - char *s; + GtkWidget *menuitem; + char *s; - inst->menu = gtk_menu_new(); + inst->menu = gtk_menu_new(); #define MKMENUITEM(title, func) do \ { \ @@ -5453,45 +5453,45 @@ void new_session_window(Conf *conf, const char *geometry_string) gtk_widget_show(menuitem); \ } while (0) - if (new_session) - MKMENUITEM("New Session...", new_session_menuitem); + if (new_session) + MKMENUITEM("New Session...", new_session_menuitem); MKMENUITEM("Restart Session", restart_session_menuitem); - inst->restartitem = menuitem; - gtk_widget_set_sensitive(inst->restartitem, false); + inst->restartitem = menuitem; + gtk_widget_set_sensitive(inst->restartitem, false); MKMENUITEM("Duplicate Session", dup_session_menuitem); - if (saved_sessions) { - inst->sessionsmenu = gtk_menu_new(); - /* sessionsmenu will be updated when it's invoked */ - /* XXX is this the right way to do dynamic menus in Gtk? */ - MKMENUITEM("Saved Sessions", update_savedsess_menu); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), - inst->sessionsmenu); - } - MKSEP(); + if (saved_sessions) { + inst->sessionsmenu = gtk_menu_new(); + /* sessionsmenu will be updated when it's invoked */ + /* XXX is this the right way to do dynamic menus in Gtk? */ + MKMENUITEM("Saved Sessions", update_savedsess_menu); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), + inst->sessionsmenu); + } + MKSEP(); MKMENUITEM("Change Settings...", change_settings_menuitem); - MKSEP(); - if (use_event_log) - MKMENUITEM("Event Log", event_log_menuitem); - MKSUBMENU("Special Commands"); - inst->specialsmenu = gtk_menu_new(); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu); - inst->specialsitem1 = menuitem; - MKSEP(); - inst->specialsitem2 = menuitem; - gtk_widget_hide(inst->specialsitem1); - gtk_widget_hide(inst->specialsitem2); - MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem); - MKMENUITEM("Reset Terminal", reset_terminal_menuitem); - MKSEP(); - MKMENUITEM("Copy to " CLIPNAME_EXPLICIT_OBJECT, + MKSEP(); + if (use_event_log) + MKMENUITEM("Event Log", event_log_menuitem); + MKSUBMENU("Special Commands"); + inst->specialsmenu = gtk_menu_new(); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), inst->specialsmenu); + inst->specialsitem1 = menuitem; + MKSEP(); + inst->specialsitem2 = menuitem; + gtk_widget_hide(inst->specialsitem1); + gtk_widget_hide(inst->specialsitem2); + MKMENUITEM("Clear Scrollback", clear_scrollback_menuitem); + MKMENUITEM("Reset Terminal", reset_terminal_menuitem); + MKSEP(); + MKMENUITEM("Copy to " CLIPNAME_EXPLICIT_OBJECT, copy_clipboard_menuitem); - MKMENUITEM("Paste from " CLIPNAME_EXPLICIT_OBJECT, + MKMENUITEM("Paste from " CLIPNAME_EXPLICIT_OBJECT, paste_clipboard_menuitem); - MKMENUITEM("Copy All", copy_all_menuitem); - MKSEP(); - s = dupcat("About ", appname, NULL); - MKMENUITEM(s, about_menuitem); - sfree(s); + MKMENUITEM("Copy All", copy_all_menuitem); + MKSEP(); + s = dupcat("About ", appname, NULL); + MKMENUITEM(s, about_menuitem); + sfree(s); #undef MKMENUITEM #undef MKSUBMENU #undef MKSEP @@ -5512,7 +5512,7 @@ void new_session_window(Conf *conf, const char *geometry_string) term_provide_logctx(inst->term, inst->logctx); term_size(inst->term, inst->height, inst->width, - conf_get_int(inst->conf, CONF_savelines)); + conf_get_int(inst->conf, CONF_savelines)); inst->exited = false; diff --git a/unix/pterm.plist b/unix/pterm.plist index e8bd943d..03e57b88 100644 --- a/unix/pterm.plist +++ b/unix/pterm.plist @@ -2,29 +2,29 @@ - CFBundleIconFile - Pterm.icns - CFBundleName - Pterm - CFBundleDisplayName - Pterm - CFBundleExecutable - Pterm - CFBundleVersion - Unidentified build - CFBundleShortVersionString - Unidentified build - CFBundleDevelopmentRegion - en - CFBundleIdentifier - org.tartarus.projects.putty.macpterm - CFBundleInfoDictionaryVersion - 6.0 - CFBundlePackageType - APPL - CFBundleSignature - ???? - NSHumanReadableCopyright - © 1997-2015 Simon Tatham. All rights reserved. + CFBundleIconFile + Pterm.icns + CFBundleName + Pterm + CFBundleDisplayName + Pterm + CFBundleExecutable + Pterm + CFBundleVersion + Unidentified build + CFBundleShortVersionString + Unidentified build + CFBundleDevelopmentRegion + en + CFBundleIdentifier + org.tartarus.projects.putty.macpterm + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + NSHumanReadableCopyright + © 1997-2015 Simon Tatham. All rights reserved. diff --git a/unix/putty.plist b/unix/putty.plist index cf8d53db..9ec6b7a6 100644 --- a/unix/putty.plist +++ b/unix/putty.plist @@ -2,29 +2,29 @@ - CFBundleIconFile - PuTTY.icns - CFBundleName - PuTTY - CFBundleDisplayName - PuTTY - CFBundleExecutable - PuTTY - CFBundleVersion - Unidentified build - CFBundleShortVersionString - Unidentified build - CFBundleDevelopmentRegion - en - CFBundleIdentifier - org.tartarus.projects.putty.macputty - CFBundleInfoDictionaryVersion - 6.0 - CFBundlePackageType - APPL - CFBundleSignature - ???? - NSHumanReadableCopyright - © 1997-2015 Simon Tatham. All rights reserved. + CFBundleIconFile + PuTTY.icns + CFBundleName + PuTTY + CFBundleDisplayName + PuTTY + CFBundleExecutable + PuTTY + CFBundleVersion + Unidentified build + CFBundleShortVersionString + Unidentified build + CFBundleDevelopmentRegion + en + CFBundleIdentifier + org.tartarus.projects.putty.macputty + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + NSHumanReadableCopyright + © 1997-2015 Simon Tatham. All rights reserved. diff --git a/unix/unix.h b/unix/unix.h index 31e633f2..adaebea6 100644 --- a/unix/unix.h +++ b/unix/unix.h @@ -5,10 +5,10 @@ # include "uxconfig.h" /* Space to hide it from mkfiles.pl */ #endif -#include /* for FILENAME_MAX */ -#include /* C99 int types */ +#include /* for FILENAME_MAX */ +#include /* C99 int types */ #ifndef NO_LIBDL -#include /* Dynamic library loading */ +#include /* Dynamic library loading */ #endif /* NO_LIBDL */ #include "charset.h" #include /* for mode_t */ @@ -95,8 +95,8 @@ extern const struct BackendVtable pty_backend; /* Simple wraparound timer function */ unsigned long getticks(void); #define GETTICKCOUNT getticks -#define TICKSPERSEC 1000 /* we choose to use milliseconds */ -#define CURSORBLINK 450 /* no standard way to set this */ +#define TICKSPERSEC 1000 /* we choose to use milliseconds */ +#define CURSORBLINK 450 /* no standard way to set this */ #define WCHAR wchar_t #define BYTE unsigned char @@ -341,7 +341,7 @@ void gtk_setup_config_box( * from the command line or config files is assumed to be encoded). */ #define DEFAULT_CODEPAGE 0xFFFF -#define CP_UTF8 CS_UTF8 /* from libcharset */ +#define CP_UTF8 CS_UTF8 /* from libcharset */ #define strnicmp strncasecmp #define stricmp strcasecmp diff --git a/unix/ux_x11.c b/unix/ux_x11.c index a9c2b0bc..bef036b4 100644 --- a/unix/ux_x11.c +++ b/unix/ux_x11.c @@ -25,17 +25,17 @@ void platform_get_x11_auth(struct X11Display *disp, Conf *conf) needs_free = false; xauthfile = getenv("XAUTHORITY"); if (!xauthfile) { - xauthfile = getenv("HOME"); - if (xauthfile) { - xauthfile = dupcat(xauthfile, "/.Xauthority", NULL); - needs_free = true; - } + xauthfile = getenv("HOME"); + if (xauthfile) { + xauthfile = dupcat(xauthfile, "/.Xauthority", NULL); + needs_free = true; + } } if (xauthfile) { - x11_get_auth_from_authfile(disp, xauthfile); - if (needs_free) - sfree(xauthfile); + x11_get_auth_from_authfile(disp, xauthfile); + if (needs_free) + sfree(xauthfile); } } diff --git a/unix/uxagentc.c b/unix/uxagentc.c index 097bdbb0..30c2244d 100644 --- a/unix/uxagentc.c +++ b/unix/uxagentc.c @@ -19,7 +19,7 @@ bool agent_exists(void) { const char *p = getenv("SSH_AUTH_SOCK"); if (p && *p) - return true; + return true; return false; } @@ -37,9 +37,9 @@ static int agent_conncmp(void *av, void *bv) agent_pending_query *a = (agent_pending_query *) av; agent_pending_query *b = (agent_pending_query *) bv; if (a->fd < b->fd) - return -1; + return -1; if (a->fd > b->fd) - return +1; + return +1; return 0; } static int agent_connfind(void *av, void *bv) @@ -47,9 +47,9 @@ static int agent_connfind(void *av, void *bv) int afd = *(int *) av; agent_pending_query *b = (agent_pending_query *) bv; if (afd < b->fd) - return -1; + return -1; if (afd > b->fd) - return +1; + return +1; return 0; } @@ -66,26 +66,26 @@ static bool agent_try_read(agent_pending_query *conn) ret = read(conn->fd, conn->retbuf+conn->retlen, conn->retsize-conn->retlen); if (ret <= 0) { - if (conn->retbuf != conn->sizebuf) sfree(conn->retbuf); - conn->retbuf = NULL; - conn->retlen = 0; + if (conn->retbuf != conn->sizebuf) sfree(conn->retbuf); + conn->retbuf = NULL; + conn->retlen = 0; return true; } conn->retlen += ret; if (conn->retsize == 4 && conn->retlen == 4) { - conn->retsize = toint(GET_32BIT_MSB_FIRST(conn->retbuf) + 4); - if (conn->retsize <= 0) { - conn->retbuf = NULL; - conn->retlen = 0; + conn->retsize = toint(GET_32BIT_MSB_FIRST(conn->retbuf) + 4); + if (conn->retsize <= 0) { + conn->retbuf = NULL; + conn->retlen = 0; return true; /* way too large */ - } - assert(conn->retbuf == conn->sizebuf); - conn->retbuf = snewn(conn->retsize, char); - memcpy(conn->retbuf, conn->sizebuf, 4); + } + assert(conn->retbuf == conn->sizebuf); + conn->retbuf = snewn(conn->retsize, char); + memcpy(conn->retbuf, conn->sizebuf, 4); } if (conn->retlen < conn->retsize) - return false; /* more data to come */ + return false; /* more data to come */ return true; } @@ -108,12 +108,12 @@ static void agent_select_result(int fd, int event) conn = find234(agent_pending_queries, &fd, agent_connfind); if (!conn) { - uxsel_del(fd); - return; + uxsel_del(fd); + return; } if (!agent_try_read(conn)) - return; /* more data to come */ + return; /* more data to come */ /* * We have now completed the agent query. Do the callback. @@ -137,12 +137,12 @@ agent_pending_query *agent_query( name = getenv("SSH_AUTH_SOCK"); if (!name || strlen(name) >= sizeof(addr.sun_path)) - goto failure; + goto failure; sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { - perror("socket(PF_UNIX)"); - exit(1); + perror("socket(PF_UNIX)"); + exit(1); } cloexec(sock); @@ -150,20 +150,20 @@ agent_pending_query *agent_query( addr.sun_family = AF_UNIX; strcpy(addr.sun_path, name); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { - close(sock); - goto failure; + close(sock); + goto failure; } strbuf_finalise_agent_query(query); for (done = 0; done < query->len ;) { - int ret = write(sock, query->s + done, + int ret = write(sock, query->s + done, query->len - done); - if (ret <= 0) { - close(sock); - goto failure; - } - done += ret; + if (ret <= 0) { + close(sock); + goto failure; + } + done += ret; } conn = snew(agent_pending_query); @@ -200,7 +200,7 @@ agent_pending_query *agent_query( * select_result comes back to us. */ if (!agent_pending_queries) - agent_pending_queries = newtree234(agent_conncmp); + agent_pending_queries = newtree234(agent_conncmp); add234(agent_pending_queries, conn); uxsel_set(sock, SELECT_R, agent_select_result); diff --git a/unix/uxcfg.c b/unix/uxcfg.c index 7c24603a..6856bbfe 100644 --- a/unix/uxcfg.c +++ b/unix/uxcfg.c @@ -36,36 +36,36 @@ void unix_setup_config_box(struct controlbox *b, bool midsession, int protocol) * adjust the text on the `Telnet command' control. */ if (!midsession) { - int i; + int i; s = ctrl_getset(b, "Connection/Proxy", "basics", NULL); - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_RADIO && - c->generic.context.i == CONF_proxy_type) { - assert(c->generic.handler == conf_radiobutton_handler); - c->radio.nbuttons++; - c->radio.buttons = - sresize(c->radio.buttons, c->radio.nbuttons, char *); - c->radio.buttons[c->radio.nbuttons-1] = - dupstr("Local"); - c->radio.buttondata = - sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); - c->radio.buttondata[c->radio.nbuttons-1] = I(PROXY_CMD); - break; - } - } + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_RADIO && + c->generic.context.i == CONF_proxy_type) { + assert(c->generic.handler == conf_radiobutton_handler); + c->radio.nbuttons++; + c->radio.buttons = + sresize(c->radio.buttons, c->radio.nbuttons, char *); + c->radio.buttons[c->radio.nbuttons-1] = + dupstr("Local"); + c->radio.buttondata = + sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); + c->radio.buttondata[c->radio.nbuttons-1] = I(PROXY_CMD); + break; + } + } - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_EDITBOX && - c->generic.context.i == CONF_proxy_telnet_command) { - assert(c->generic.handler == conf_editbox_handler); - sfree(c->generic.label); - c->generic.label = dupstr("Telnet command, or local" - " proxy command"); - break; - } - } + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_EDITBOX && + c->generic.context.i == CONF_proxy_telnet_command) { + assert(c->generic.handler == conf_editbox_handler); + sfree(c->generic.label); + c->generic.label = dupstr("Telnet command, or local" + " proxy command"); + break; + } + } } /* diff --git a/unix/uxcons.c b/unix/uxcons.c index 3780c896..4811c177 100644 --- a/unix/uxcons.c +++ b/unix/uxcons.c @@ -27,22 +27,22 @@ void stderr_tty_init() { /* Ensure that if stderr is a tty, we can get it back to a sane state. */ if ((flags & FLAG_STDERR_TTY) && isatty(STDERR_FILENO)) { - stderr_is_a_tty = true; - tcgetattr(STDERR_FILENO, &orig_termios_stderr); + stderr_is_a_tty = true; + tcgetattr(STDERR_FILENO, &orig_termios_stderr); } } void premsg(struct termios *cf) { if (stderr_is_a_tty) { - tcgetattr(STDERR_FILENO, cf); - tcsetattr(STDERR_FILENO, TCSADRAIN, &orig_termios_stderr); + tcgetattr(STDERR_FILENO, cf); + tcsetattr(STDERR_FILENO, TCSADRAIN, &orig_termios_stderr); } } void postmsg(struct termios *cf) { if (stderr_is_a_tty) - tcsetattr(STDERR_FILENO, TCSADRAIN, cf); + tcsetattr(STDERR_FILENO, TCSADRAIN, cf); } /* @@ -161,49 +161,49 @@ int console_verify_ssh_host_key( int ret; static const char absentmsg_batch[] = - "The server's host key is not cached. You have no guarantee\n" - "that the server is the computer you think it is.\n" - "The server's %s key fingerprint is:\n" - "%s\n" - "Connection abandoned.\n"; + "The server's host key is not cached. You have no guarantee\n" + "that the server is the computer you think it is.\n" + "The server's %s key fingerprint is:\n" + "%s\n" + "Connection abandoned.\n"; static const char absentmsg[] = - "The server's host key is not cached. You have no guarantee\n" - "that the server is the computer you think it is.\n" - "The server's %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 want to carry on connecting just once, without\n" - "adding the key to the cache, enter \"n\".\n" - "If you do not trust this host, press Return to abandon the\n" - "connection.\n" - "Store key in cache? (y/n) "; + "The server's host key is not cached. You have no guarantee\n" + "that the server is the computer you think it is.\n" + "The server's %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 want to carry on connecting just once, without\n" + "adding the key to the cache, enter \"n\".\n" + "If you do not trust this host, press Return to abandon the\n" + "connection.\n" + "Store key in cache? (y/n) "; static const char wrongmsg_batch[] = - "WARNING - POTENTIAL SECURITY BREACH!\n" - "The server's host key does not match the one PuTTY has\n" - "cached. This means that either the server administrator\n" - "has changed the host key, or you have actually connected\n" - "to another computer pretending to be the server.\n" - "The new %s key fingerprint is:\n" - "%s\n" - "Connection abandoned.\n"; + "WARNING - POTENTIAL SECURITY BREACH!\n" + "The server's host key does not match the one PuTTY has\n" + "cached. This means that either the server administrator\n" + "has changed the host key, or you have actually connected\n" + "to another computer pretending to be the server.\n" + "The new %s key fingerprint is:\n" + "%s\n" + "Connection abandoned.\n"; static const char wrongmsg[] = - "WARNING - POTENTIAL SECURITY BREACH!\n" - "The server's host key does not match the one PuTTY has\n" - "cached. This means that either the server administrator\n" - "has changed the host key, or you have actually connected\n" - "to another computer pretending to be the server.\n" - "The new %s 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. This means that either the server administrator\n" + "has changed the host key, or you have actually connected\n" + "to another computer pretending to be the server.\n" + "The new %s 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"; @@ -215,47 +215,47 @@ int console_verify_ssh_host_key( */ ret = verify_host_key(host, port, keytype, keystr); - if (ret == 0) /* success - key matched OK */ - return 1; + if (ret == 0) /* success - key matched OK */ + return 1; premsg(&cf); - if (ret == 2) { /* key was different */ - if (console_batch_mode) { - fprintf(stderr, wrongmsg_batch, keytype, fingerprint); - return 0; - } - fprintf(stderr, wrongmsg, keytype, fingerprint); - fflush(stderr); + if (ret == 2) { /* key was different */ + if (console_batch_mode) { + fprintf(stderr, wrongmsg_batch, keytype, fingerprint); + return 0; + } + fprintf(stderr, wrongmsg, keytype, fingerprint); + fflush(stderr); } - if (ret == 1) { /* key was absent */ - if (console_batch_mode) { - fprintf(stderr, absentmsg_batch, keytype, fingerprint); - return 0; - } - fprintf(stderr, absentmsg, keytype, fingerprint); - fflush(stderr); + if (ret == 1) { /* key was absent */ + if (console_batch_mode) { + fprintf(stderr, absentmsg_batch, keytype, fingerprint); + return 0; + } + fprintf(stderr, absentmsg, keytype, fingerprint); + fflush(stderr); } { - struct termios oldmode, newmode; - tcgetattr(0, &oldmode); - newmode = oldmode; - newmode.c_lflag |= ECHO | ISIG | ICANON; - tcsetattr(0, TCSANOW, &newmode); - line[0] = '\0'; - if (block_and_read(0, line, sizeof(line) - 1) <= 0) - /* handled below */; - tcsetattr(0, TCSANOW, &oldmode); + struct termios oldmode, newmode; + tcgetattr(0, &oldmode); + newmode = oldmode; + newmode.c_lflag |= ECHO | ISIG | ICANON; + tcsetattr(0, TCSANOW, &newmode); + line[0] = '\0'; + if (block_and_read(0, line, sizeof(line) - 1) <= 0) + /* handled below */; + tcsetattr(0, TCSANOW, &oldmode); } if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') { - if (line[0] == 'y' || line[0] == 'Y') - store_host_key(host, port, keytype, keystr); - postmsg(&cf); + if (line[0] == 'y' || line[0] == 'Y') + store_host_key(host, port, keytype, keystr); + postmsg(&cf); return 1; } else { - fprintf(stderr, abandoned); - postmsg(&cf); + fprintf(stderr, abandoned); + postmsg(&cf); return 0; } } @@ -265,13 +265,13 @@ int console_confirm_weak_crypto_primitive( void (*callback)(void *ctx, int result), void *ctx) { static const char msg[] = - "The first %s supported by the server is\n" - "%s, which is below the configured warning threshold.\n" - "Continue with connection? (y/n) "; + "The first %s supported by the server is\n" + "%s, which is below the configured warning threshold.\n" + "Continue with connection? (y/n) "; static const char msg_batch[] = - "The first %s supported by the server is\n" - "%s, which is below the configured warning threshold.\n" - "Connection abandoned.\n"; + "The first %s supported by the server is\n" + "%s, which is below the configured warning threshold.\n" + "Connection abandoned.\n"; static const char abandoned[] = "Connection abandoned.\n"; char line[32]; @@ -279,32 +279,32 @@ int console_confirm_weak_crypto_primitive( premsg(&cf); if (console_batch_mode) { - fprintf(stderr, msg_batch, algtype, algname); - return 0; + fprintf(stderr, msg_batch, algtype, algname); + return 0; } fprintf(stderr, msg, algtype, algname); fflush(stderr); { - struct termios oldmode, newmode; - tcgetattr(0, &oldmode); - newmode = oldmode; - newmode.c_lflag |= ECHO | ISIG | ICANON; - tcsetattr(0, TCSANOW, &newmode); - line[0] = '\0'; - if (block_and_read(0, line, sizeof(line) - 1) <= 0) - /* handled below */; - tcsetattr(0, TCSANOW, &oldmode); + struct termios oldmode, newmode; + tcgetattr(0, &oldmode); + newmode = oldmode; + newmode.c_lflag |= ECHO | ISIG | ICANON; + tcsetattr(0, TCSANOW, &newmode); + line[0] = '\0'; + if (block_and_read(0, line, sizeof(line) - 1) <= 0) + /* handled below */; + tcsetattr(0, TCSANOW, &oldmode); } if (line[0] == 'y' || line[0] == 'Y') { - postmsg(&cf); - return 1; + postmsg(&cf); + return 1; } else { - fprintf(stderr, abandoned); - postmsg(&cf); - return 0; + fprintf(stderr, abandoned); + postmsg(&cf); + return 0; } } @@ -313,19 +313,19 @@ int console_confirm_weak_cached_hostkey( void (*callback)(void *ctx, int result), void *ctx) { static const char msg[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Continue with connection? (y/n) "; + "Continue with connection? (y/n) "; static const char msg_batch[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Connection abandoned.\n"; + "Connection abandoned.\n"; static const char abandoned[] = "Connection abandoned.\n"; char line[32]; @@ -333,32 +333,32 @@ int console_confirm_weak_cached_hostkey( premsg(&cf); if (console_batch_mode) { - fprintf(stderr, msg_batch, algname, betteralgs); - return 0; + fprintf(stderr, msg_batch, algname, betteralgs); + return 0; } fprintf(stderr, msg, algname, betteralgs); fflush(stderr); { - struct termios oldmode, newmode; - tcgetattr(0, &oldmode); - newmode = oldmode; - newmode.c_lflag |= ECHO | ISIG | ICANON; - tcsetattr(0, TCSANOW, &newmode); - line[0] = '\0'; - if (block_and_read(0, line, sizeof(line) - 1) <= 0) - /* handled below */; - tcsetattr(0, TCSANOW, &oldmode); + struct termios oldmode, newmode; + tcgetattr(0, &oldmode); + newmode = oldmode; + newmode.c_lflag |= ECHO | ISIG | ICANON; + tcsetattr(0, TCSANOW, &newmode); + line[0] = '\0'; + if (block_and_read(0, line, sizeof(line) - 1) <= 0) + /* handled below */; + tcsetattr(0, TCSANOW, &oldmode); } if (line[0] == 'y' || line[0] == 'Y') { - postmsg(&cf); - return 1; + postmsg(&cf); + return 1; } else { - fprintf(stderr, abandoned); - postmsg(&cf); - return 0; + fprintf(stderr, abandoned); + postmsg(&cf); + return 0; } } @@ -371,49 +371,49 @@ static int console_askappend(LogPolicy *lp, Filename *filename, void *ctx) { static const char msgtemplate[] = - "The session log file \"%.*s\" already exists.\n" - "You can overwrite it with a new session log,\n" - "append your session log to the end of it,\n" - "or disable session logging for this session.\n" - "Enter \"y\" to wipe the file, \"n\" to append to it,\n" - "or just press Return to disable logging.\n" - "Wipe the log file? (y/n, Return cancels logging) "; + "The session log file \"%.*s\" already exists.\n" + "You can overwrite it with a new session log,\n" + "append your session log to the end of it,\n" + "or disable session logging for this session.\n" + "Enter \"y\" to wipe the file, \"n\" to append to it,\n" + "or just press Return to disable logging.\n" + "Wipe the log file? (y/n, Return cancels logging) "; static const char msgtemplate_batch[] = - "The session log file \"%.*s\" already exists.\n" - "Logging will not be enabled.\n"; + "The session log file \"%.*s\" already exists.\n" + "Logging will not be enabled.\n"; char line[32]; struct termios cf; premsg(&cf); if (console_batch_mode) { - fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path); - fflush(stderr); - return 0; + fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path); + fflush(stderr); + return 0; } fprintf(stderr, msgtemplate, FILENAME_MAX, filename->path); fflush(stderr); { - struct termios oldmode, newmode; - tcgetattr(0, &oldmode); - newmode = oldmode; - newmode.c_lflag |= ECHO | ISIG | ICANON; - tcsetattr(0, TCSANOW, &newmode); - line[0] = '\0'; - if (block_and_read(0, line, sizeof(line) - 1) <= 0) - /* handled below */; - tcsetattr(0, TCSANOW, &oldmode); + struct termios oldmode, newmode; + tcgetattr(0, &oldmode); + newmode = oldmode; + newmode.c_lflag |= ECHO | ISIG | ICANON; + tcsetattr(0, TCSANOW, &newmode); + line[0] = '\0'; + if (block_and_read(0, line, sizeof(line) - 1) <= 0) + /* handled below */; + tcsetattr(0, TCSANOW, &oldmode); } postmsg(&cf); if (line[0] == 'y' || line[0] == 'Y') - return 2; + return 2; else if (line[0] == 'n' || line[0] == 'N') - return 1; + return 1; else - return 0; + return 0; } bool console_antispoof_prompt = true; @@ -441,7 +441,7 @@ bool console_set_trust_status(Seat *seat, bool trusted) /* * Warn about the obsolescent key file format. - * + * * Uniquely among these functions, this one does _not_ expect a * frontend handle. This means that if PuTTY is ported to a * platform which requires frontend handles, this function will be @@ -452,15 +452,15 @@ bool console_set_trust_status(Seat *seat, bool trusted) void old_keyfile_warning(void) { static const char message[] = - "You are loading an SSH-2 private key which has an\n" - "old version of the file format. This means your key\n" - "file is not fully tamperproof. Future versions of\n" - "PuTTY may stop supporting this private key format,\n" - "so we recommend you convert your key to the new\n" - "format.\n" - "\n" - "Once the key is loaded into PuTTYgen, you can perform\n" - "this conversion simply by saving it again.\n"; + "You are loading an SSH-2 private key which has an\n" + "old version of the file format. This means your key\n" + "file is not fully tamperproof. Future versions of\n" + "PuTTY may stop supporting this private key format,\n" + "so we recommend you convert your key to the new\n" + "format.\n" + "\n" + "Once the key is loaded into PuTTYgen, you can perform\n" + "this conversion simply by saving it again.\n"; struct termios cf; premsg(&cf); @@ -535,13 +535,13 @@ int console_get_userpass_input(prompts_t *p) * Zero all the results, in case we abort half-way through. */ { - int i; - for (i = 0; i < p->n_prompts; i++) + int i; + for (i = 0; i < p->n_prompts; i++) prompt_set_result(p->prompts[i], ""); } if (p->n_prompts && console_batch_mode) - return 0; + return 0; console_open(&outfp, &infd); @@ -550,35 +550,35 @@ int console_get_userpass_input(prompts_t *p) */ /* We only print the `name' caption if we have to... */ if (p->name_reqd && p->name) { - ptrlen plname = ptrlen_from_asciz(p->name); - console_write(outfp, plname); + ptrlen plname = ptrlen_from_asciz(p->name); + console_write(outfp, plname); if (!ptrlen_endswith(plname, PTRLEN_LITERAL("\n"), NULL)) - console_write(outfp, PTRLEN_LITERAL("\n")); + console_write(outfp, PTRLEN_LITERAL("\n")); } /* ...but we always print any `instruction'. */ if (p->instruction) { - ptrlen plinst = ptrlen_from_asciz(p->instruction); - console_write(outfp, plinst); + ptrlen plinst = ptrlen_from_asciz(p->instruction); + console_write(outfp, plinst); if (!ptrlen_endswith(plinst, PTRLEN_LITERAL("\n"), NULL)) - console_write(outfp, PTRLEN_LITERAL("\n")); + console_write(outfp, PTRLEN_LITERAL("\n")); } for (curr_prompt = 0; curr_prompt < p->n_prompts; curr_prompt++) { - struct termios oldmode, newmode; - int len; - prompt_t *pr = p->prompts[curr_prompt]; + struct termios oldmode, newmode; + int len; + prompt_t *pr = p->prompts[curr_prompt]; - tcgetattr(infd, &oldmode); - newmode = oldmode; - newmode.c_lflag |= ISIG | ICANON; - if (!pr->echo) - newmode.c_lflag &= ~ECHO; - else - newmode.c_lflag |= ECHO; - tcsetattr(infd, TCSANOW, &newmode); + tcgetattr(infd, &oldmode); + newmode = oldmode; + newmode.c_lflag |= ISIG | ICANON; + if (!pr->echo) + newmode.c_lflag &= ~ECHO; + else + newmode.c_lflag |= ECHO; + tcsetattr(infd, TCSANOW, &newmode); - console_write(outfp, ptrlen_from_asciz(pr->prompt)); + console_write(outfp, ptrlen_from_asciz(pr->prompt)); len = 0; while (1) { @@ -597,9 +597,9 @@ int console_get_userpass_input(prompts_t *p) } } - tcsetattr(infd, TCSANOW, &oldmode); + tcsetattr(infd, TCSANOW, &oldmode); - if (!pr->echo) + if (!pr->echo) console_write(outfp, PTRLEN_LITERAL("\n")); if (len < 0) { @@ -607,7 +607,7 @@ int console_get_userpass_input(prompts_t *p) return 0; /* failure due to read error */ } - pr->result[len] = '\0'; + pr->result[len] = '\0'; } console_close(outfp, infd); diff --git a/unix/uxfdsock.c b/unix/uxfdsock.c index c7cab247..2dde8338 100644 --- a/unix/uxfdsock.c +++ b/unix/uxfdsock.c @@ -44,9 +44,9 @@ static int fdsocket_infd_cmp(void *av, void *bv) FdSocket *a = (FdSocket *)av; FdSocket *b = (FdSocket *)bv; if (a->infd < b->infd) - return -1; + return -1; if (a->infd > b->infd) - return +1; + return +1; return 0; } static int fdsocket_infd_find(void *av, void *bv) @@ -54,9 +54,9 @@ static int fdsocket_infd_find(void *av, void *bv) int a = *(int *)av; FdSocket *b = (FdSocket *)bv; if (a < b->infd) - return -1; + return -1; if (a > b->infd) - return +1; + return +1; return 0; } static int fdsocket_inerrfd_cmp(void *av, void *bv) @@ -64,9 +64,9 @@ static int fdsocket_inerrfd_cmp(void *av, void *bv) FdSocket *a = (FdSocket *)av; FdSocket *b = (FdSocket *)bv; if (a->inerrfd < b->inerrfd) - return -1; + return -1; if (a->inerrfd > b->inerrfd) - return +1; + return +1; return 0; } static int fdsocket_inerrfd_find(void *av, void *bv) @@ -74,9 +74,9 @@ static int fdsocket_inerrfd_find(void *av, void *bv) int a = *(int *)av; FdSocket *b = (FdSocket *)bv; if (a < b->inerrfd) - return -1; + return -1; if (a > b->inerrfd) - return +1; + return +1; return 0; } static int fdsocket_outfd_cmp(void *av, void *bv) @@ -84,9 +84,9 @@ static int fdsocket_outfd_cmp(void *av, void *bv) FdSocket *a = (FdSocket *)av; FdSocket *b = (FdSocket *)bv; if (a->outfd < b->outfd) - return -1; + return -1; if (a->outfd > b->outfd) - return +1; + return +1; return 0; } static int fdsocket_outfd_find(void *av, void *bv) @@ -94,9 +94,9 @@ static int fdsocket_outfd_find(void *av, void *bv) int a = *(int *)av; FdSocket *b = (FdSocket *)bv; if (a < b->outfd) - return -1; + return -1; if (a > b->outfd) - return +1; + return +1; return 0; } @@ -105,7 +105,7 @@ static Plug *fdsocket_plug(Socket *s, Plug *p) FdSocket *fds = container_of(s, FdSocket, sock); Plug *ret = fds->plug; if (p) - fds->plug = p; + fds->plug = p; return ret; } @@ -164,21 +164,21 @@ static int fdsocket_try_send(FdSocket *fds) while (bufchain_size(&fds->pending_output_data) > 0) { ssize_t ret; - ptrlen data = bufchain_prefix(&fds->pending_output_data); - ret = write(fds->outfd, data.ptr, data.len); + ptrlen data = bufchain_prefix(&fds->pending_output_data); + ret = write(fds->outfd, data.ptr, data.len); noise_ultralight(NOISE_SOURCE_IOID, ret); - if (ret < 0 && errno != EWOULDBLOCK) { + if (ret < 0 && errno != EWOULDBLOCK) { if (!fds->pending_error) { fds->pending_error = errno; queue_toplevel_callback(fdsocket_error_callback, fds); } return 0; - } else if (ret <= 0) { - break; - } else { - bufchain_consume(&fds->pending_output_data, ret); - sent += ret; - } + } else if (ret <= 0) { + break; + } else { + bufchain_consume(&fds->pending_output_data, ret); + sent += ret; + } } if (fds->outgoingeof == EOF_PENDING) { @@ -190,9 +190,9 @@ static int fdsocket_try_send(FdSocket *fds) } if (bufchain_size(&fds->pending_output_data) == 0) - uxsel_del(fds->outfd); + uxsel_del(fds->outfd); else - uxsel_set(fds->outfd, SELECT_W, fdsocket_select_result_output); + uxsel_set(fds->outfd, SELECT_W, fdsocket_select_result_output); return sent; } @@ -237,9 +237,9 @@ static void fdsocket_set_frozen(Socket *s, bool is_frozen) return; if (is_frozen) - uxsel_del(fds->infd); + uxsel_del(fds->infd); else - uxsel_set(fds->infd, SELECT_R, fdsocket_select_result_input); + uxsel_set(fds->infd, SELECT_R, fdsocket_select_result_input); } static const char *fdsocket_socket_error(Socket *s) diff --git a/unix/uxgen.c b/unix/uxgen.c index ed14188d..da5e8f05 100644 --- a/unix/uxgen.c +++ b/unix/uxgen.c @@ -39,23 +39,23 @@ char *get_random_data(int len, const char *device) fd = open(device, O_RDONLY); if (fd < 0) { - sfree(buf); - fprintf(stderr, "puttygen: %s: open: %s\n", + sfree(buf); + fprintf(stderr, "puttygen: %s: open: %s\n", device, strerror(errno)); - return NULL; + return NULL; } ngot = 0; while (ngot < len) { - ret = read(fd, buf+ngot, len-ngot); - if (ret < 0) { - close(fd); + ret = read(fd, buf+ngot, len-ngot); + if (ret < 0) { + close(fd); sfree(buf); fprintf(stderr, "puttygen: %s: read: %s\n", device, strerror(errno)); - return NULL; - } - ngot += ret; + return NULL; + } + ngot += ret; } close(fd); diff --git a/unix/uxgss.c b/unix/uxgss.c index 47c59172..2d71c543 100644 --- a/unix/uxgss.c +++ b/unix/uxgss.c @@ -29,7 +29,7 @@ const struct keyvalwhere gsslibkeywords[] = { */ static void gss_init(struct ssh_gss_library *lib, void *dlhandle, - int id, const char *msg) + int id, const char *msg) { lib->id = id; lib->gsslogmsg = msg; @@ -67,25 +67,25 @@ struct ssh_gss_liblist *ssh_gss_setup(Conf *conf) /* Heimdal's GSSAPI Library */ if ((gsslib = dlopen("libgssapi.so.2", RTLD_LAZY)) != NULL) - gss_init(&list->libraries[list->nlibraries++], gsslib, - 0, "Using GSSAPI from libgssapi.so.2"); + gss_init(&list->libraries[list->nlibraries++], gsslib, + 0, "Using GSSAPI from libgssapi.so.2"); /* MIT Kerberos's GSSAPI Library */ if ((gsslib = dlopen("libgssapi_krb5.so.2", RTLD_LAZY)) != NULL) - gss_init(&list->libraries[list->nlibraries++], gsslib, - 1, "Using GSSAPI from libgssapi_krb5.so.2"); + gss_init(&list->libraries[list->nlibraries++], gsslib, + 1, "Using GSSAPI from libgssapi_krb5.so.2"); /* Sun's GSSAPI Library */ if ((gsslib = dlopen("libgss.so.1", RTLD_LAZY)) != NULL) - gss_init(&list->libraries[list->nlibraries++], gsslib, - 2, "Using GSSAPI from libgss.so.1"); + gss_init(&list->libraries[list->nlibraries++], gsslib, + 2, "Using GSSAPI from libgss.so.1"); /* User-specified GSSAPI library */ gsspath = conf_get_filename(conf, CONF_ssh_gss_custom)->path; if (*gsspath && (gsslib = dlopen(gsspath, RTLD_LAZY)) != NULL) - gss_init(&list->libraries[list->nlibraries++], gsslib, - 3, dupprintf("Using GSSAPI from user-specified" - " library '%s'", gsspath)); + gss_init(&list->libraries[list->nlibraries++], gsslib, + 3, dupprintf("Using GSSAPI from user-specified" + " library '%s'", gsspath)); return list; } @@ -103,12 +103,12 @@ void ssh_gss_cleanup(struct ssh_gss_liblist *list) * using it. */ for (i = 0; i < list->nlibraries; i++) { - dlclose(list->libraries[i].handle); - if (list->libraries[i].id == 3) { - /* The 'custom' id involves a dynamically allocated message. - * Note that we must cast away the 'const' to free it. */ - sfree((char *)list->libraries[i].gsslogmsg); - } + dlclose(list->libraries[i].handle); + if (list->libraries[i].id == 3) { + /* The 'custom' id involves a dynamically allocated message. + * Note that we must cast away the 'const' to free it. */ + sfree((char *)list->libraries[i].gsslogmsg); + } } sfree(list->libraries); sfree(list); diff --git a/unix/uxmisc.c b/unix/uxmisc.c index 00c19779..57df7b7a 100644 --- a/unix/uxmisc.c +++ b/unix/uxmisc.c @@ -96,7 +96,7 @@ static FILE *debug_fp = NULL; void dputs(const char *buf) { if (!debug_fp) { - debug_fp = fopen("debug.log", "w"); + debug_fp = fopen("debug.log", "w"); } if (write(1, buf, strlen(buf)) < 0) {} /* 'error check' to placate gcc */ @@ -123,25 +123,25 @@ char *get_username(void) setpwent(); #endif if (user) - p = getpwnam(user); + p = getpwnam(user); else - p = NULL; + p = NULL; if (p && p->pw_uid == uid) { - /* - * The result of getlogin() really does correspond to - * our uid. Fine. - */ - ret = user; + /* + * The result of getlogin() really does correspond to + * our uid. Fine. + */ + ret = user; } else { - /* - * If that didn't work, for whatever reason, we'll do - * the simpler version: look up our uid in the password - * file and map it straight to a name. - */ - p = getpwuid(uid); - if (!p) - return NULL; - ret = p->pw_name; + /* + * If that didn't work, for whatever reason, we'll do + * the simpler version: look up our uid in the password + * file and map it straight to a name. + */ + p = getpwuid(uid); + if (!p) + return NULL; + ret = p->pw_name; } #if HAVE_ENDPWENT endpwent(); @@ -158,16 +158,16 @@ char *get_username(void) void pgp_fingerprints(void) { fputs("These are the fingerprints of the PuTTY PGP Master Keys. They can\n" - "be used to establish a trust path from this executable to another\n" - "one. See the manual for more information.\n" - "(Note: these fingerprints have nothing to do with SSH!)\n" - "\n" - "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR + "be used to establish a trust path from this executable to another\n" + "one. See the manual for more information.\n" + "(Note: these fingerprints have nothing to do with SSH!)\n" + "\n" + "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR " (" PGP_MASTER_KEY_DETAILS "):\n" - " " PGP_MASTER_KEY_FP "\n\n" - "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR + " " PGP_MASTER_KEY_FP "\n\n" + "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR ", " PGP_PREV_MASTER_KEY_DETAILS "):\n" - " " PGP_PREV_MASTER_KEY_FP "\n", stdout); + " " PGP_PREV_MASTER_KEY_FP "\n", stdout); } /* @@ -240,15 +240,15 @@ bool no_nonblock(int fd) { FILE *f_open(const Filename *filename, char const *mode, bool is_private) { if (!is_private) { - return fopen(filename->path, mode); + return fopen(filename->path, mode); } else { - int fd; - assert(mode[0] == 'w'); /* is_private is meaningless for read, - and tricky for append */ - fd = open(filename->path, O_WRONLY | O_CREAT | O_TRUNC, 0600); - if (fd < 0) - return NULL; - return fdopen(fd, mode); + int fd; + assert(mode[0] == 'w'); /* is_private is meaningless for read, + and tricky for append */ + fd = open(filename->path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) + return NULL; + return fdopen(fd, mode); } } diff --git a/unix/uxnet.c b/unix/uxnet.c index 3b55772e..a1db9ca3 100644 --- a/unix/uxnet.c +++ b/unix/uxnet.c @@ -32,7 +32,7 @@ # define X11_UNIX_PATH "/tmp/.X11-unix/X" #endif -/* +/* * Access to sockaddr types without breaking C strict aliasing rules. */ union sockaddr_union { @@ -53,7 +53,7 @@ union sockaddr_union { typedef struct SockAddrStep_tag SockAddrStep; struct SockAddrStep_tag { #ifndef NO_IPV6 - struct addrinfo *ai; /* steps along addr->ais */ + struct addrinfo *ai; /* steps along addr->ais */ #endif int curraddr; }; @@ -74,7 +74,7 @@ struct NetSocket { bool oobinline; enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof; bool incomingeof; - int pending_error; /* in case send() returns error */ + int pending_error; /* in case send() returns error */ bool listener; bool nodelay, keepalive; /* for connect()-type sockets */ bool privport; @@ -97,12 +97,12 @@ struct SockAddr { const char *error; enum { UNRESOLVED, UNIX, IP } superfamily; #ifndef NO_IPV6 - struct addrinfo *ais; /* Addresses IPv6 style. */ + struct addrinfo *ais; /* Addresses IPv6 style. */ #else - unsigned long *addresses; /* Addresses IPv4 style. */ + unsigned long *addresses; /* Addresses IPv4 style. */ int naddresses; #endif - char hostname[512]; /* Store an unresolved host name. */ + char hostname[512]; /* Store an unresolved host name. */ }; /* @@ -146,9 +146,9 @@ static int cmpfortree(void *av, void *bv) NetSocket *a = (NetSocket *) av, *b = (NetSocket *) bv; int as = a->s, bs = b->s; if (as < bs) - return -1; + return -1; if (as > bs) - return +1; + return +1; if (a < b) return -1; if (a > b) @@ -161,9 +161,9 @@ static int cmpforsearch(void *av, void *bv) NetSocket *b = (NetSocket *) bv; int as = *(int *)av, bs = b->s; if (as < bs) - return -1; + return -1; if (as > bs) - return +1; + return +1; return 0; } @@ -178,9 +178,9 @@ void sk_cleanup(void) int i; if (sktree) { - for (i = 0; (s = index234(sktree, i)) != NULL; i++) { - close(s->s); - } + for (i = 0; (s = index234(sktree, i)) != NULL; i++) { + close(s->s); + } } } @@ -206,8 +206,8 @@ SockAddr *sk_namelookup(const char *host, char **canonicalname, int address_fami #ifndef NO_IPV6 hints.ai_flags = AI_CANONNAME; hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET : - address_family == ADDRTYPE_IPV6 ? AF_INET6 : - AF_UNSPEC); + address_family == ADDRTYPE_IPV6 ? AF_INET6 : + AF_UNSPEC); hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = 0; hints.ai_addrlen = 0; @@ -220,58 +220,58 @@ SockAddr *sk_namelookup(const char *host, char **canonicalname, int address_fami sfree(trimmed_host); } if (err != 0) { - ret->error = gai_strerror(err); + ret->error = gai_strerror(err); strbuf_free(realhost); - return ret; + return ret; } ret->superfamily = IP; if (ret->ais->ai_canonname != NULL) - strbuf_catf(realhost, "%s", ret->ais->ai_canonname); + strbuf_catf(realhost, "%s", ret->ais->ai_canonname); else - strbuf_catf(realhost, "%s", host); + strbuf_catf(realhost, "%s", host); #else if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) { - /* - * Otherwise use the IPv4-only gethostbyname... (NOTE: - * we don't use gethostbyname as a fallback!) - */ - if (ret->superfamily == UNRESOLVED) { - /*debug("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host); */ - if ( (h = gethostbyname(host)) ) - ret->superfamily = IP; - } - if (ret->superfamily == UNRESOLVED) { - ret->error = (h_errno == HOST_NOT_FOUND || - h_errno == NO_DATA || - h_errno == NO_ADDRESS ? "Host does not exist" : - h_errno == TRY_AGAIN ? - "Temporary name service failure" : - "gethostbyname: unknown error"); + /* + * Otherwise use the IPv4-only gethostbyname... (NOTE: + * we don't use gethostbyname as a fallback!) + */ + if (ret->superfamily == UNRESOLVED) { + /*debug("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host); */ + if ( (h = gethostbyname(host)) ) + ret->superfamily = IP; + } + if (ret->superfamily == UNRESOLVED) { + ret->error = (h_errno == HOST_NOT_FOUND || + h_errno == NO_DATA || + h_errno == NO_ADDRESS ? "Host does not exist" : + h_errno == TRY_AGAIN ? + "Temporary name service failure" : + "gethostbyname: unknown error"); strbuf_free(realhost); - return ret; - } - /* This way we are always sure the h->h_name is valid :) */ + return ret; + } + /* This way we are always sure the h->h_name is valid :) */ realhost->len = 0; - strbuf_catf(realhost, "%s", h->h_name); - for (n = 0; h->h_addr_list[n]; n++); - ret->addresses = snewn(n, unsigned long); - ret->naddresses = n; - for (n = 0; n < ret->naddresses; n++) { - memcpy(&a, h->h_addr_list[n], sizeof(a)); - ret->addresses[n] = ntohl(a); - } + strbuf_catf(realhost, "%s", h->h_name); + for (n = 0; h->h_addr_list[n]; n++); + ret->addresses = snewn(n, unsigned long); + ret->naddresses = n; + for (n = 0; n < ret->naddresses; n++) { + memcpy(&a, h->h_addr_list[n], sizeof(a)); + ret->addresses[n] = ntohl(a); + } } else { - /* - * This must be a numeric IPv4 address because it caused a - * success return from inet_addr. - */ - ret->superfamily = IP; + /* + * This must be a numeric IPv4 address because it caused a + * success return from inet_addr. + */ + ret->superfamily = IP; realhost->len = 0; - strbuf_catf(realhost, "%s", host); - ret->addresses = snew(unsigned long); - ret->naddresses = 1; - ret->addresses[0] = ntohl(a); + strbuf_catf(realhost, "%s", host); + ret->addresses = snew(unsigned long); + ret->naddresses = 1; + ret->addresses[0] = ntohl(a); } #endif *canonicalname = strbuf_to_str(realhost); @@ -298,40 +298,40 @@ static bool sk_nextaddr(SockAddr *addr, SockAddrStep *step) { #ifndef NO_IPV6 if (step->ai && step->ai->ai_next) { - step->ai = step->ai->ai_next; - return true; + step->ai = step->ai->ai_next; + return true; } else - return false; + return false; #else if (step->curraddr+1 < addr->naddresses) { - step->curraddr++; - return true; + step->curraddr++; + return true; } else { - return false; + return false; } -#endif +#endif } void sk_getaddr(SockAddr *addr, char *buf, int buflen) { if (addr->superfamily == UNRESOLVED || addr->superfamily == UNIX) { - strncpy(buf, addr->hostname, buflen); - buf[buflen-1] = '\0'; + strncpy(buf, addr->hostname, buflen); + buf[buflen-1] = '\0'; } else { #ifndef NO_IPV6 - if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen, - NULL, 0, NI_NUMERICHOST) != 0) { - buf[0] = '\0'; - strncat(buf, "", buflen - 1); - } + if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen, + NULL, 0, NI_NUMERICHOST) != 0) { + buf[0] = '\0'; + strncat(buf, "", buflen - 1); + } #else - struct in_addr a; - SockAddrStep step; - START_STEP(addr, step); - assert(SOCKADDR_FAMILY(addr, step) == AF_INET); - a.s_addr = htonl(addr->addresses[0]); - strncpy(buf, inet_ntoa(a), buflen); - buf[buflen-1] = '\0'; + struct in_addr a; + SockAddrStep step; + START_STEP(addr, step); + assert(SOCKADDR_FAMILY(addr, step) == AF_INET); + a.s_addr = htonl(addr->addresses[0]); + strncpy(buf, inet_ntoa(a), buflen); + buf[buflen-1] = '\0'; #endif } } @@ -356,7 +356,7 @@ static SockAddr sk_extractaddr_tmp( #ifndef NO_IPV6 toret.ais = step->ai; #else - assert(SOCKADDR_FAMILY(addr, *step) == AF_INET); + assert(SOCKADDR_FAMILY(addr, *step) == AF_INET); toret.addresses += step->curraddr; #endif } @@ -376,8 +376,8 @@ bool sk_addr_needs_port(SockAddr *addr) bool sk_hostname_is_local(const char *name) { return !strcmp(name, "localhost") || - !strcmp(name, "::1") || - !strncmp(name, "127.", 4); + !strcmp(name, "::1") || + !strncmp(name, "127.", 4); } #define ipv4_is_loopback(addr) \ @@ -388,34 +388,34 @@ static bool sockaddr_is_loopback(struct sockaddr *sa) union sockaddr_union *u = (union sockaddr_union *)sa; switch (u->sa.sa_family) { case AF_INET: - return ipv4_is_loopback(u->sin.sin_addr); + return ipv4_is_loopback(u->sin.sin_addr); #ifndef NO_IPV6 case AF_INET6: - return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr); + return IN6_IS_ADDR_LOOPBACK(&u->sin6.sin6_addr); #endif case AF_UNIX: - return true; + return true; default: - return false; + return false; } } bool sk_address_is_local(SockAddr *addr) { if (addr->superfamily == UNRESOLVED) - return false; /* we don't know; assume not */ + return false; /* we don't know; assume not */ else if (addr->superfamily == UNIX) - return true; + return true; else { #ifndef NO_IPV6 - return sockaddr_is_loopback(addr->ais->ai_addr); + return sockaddr_is_loopback(addr->ais->ai_addr); #else - struct in_addr a; - SockAddrStep step; - START_STEP(addr, step); - assert(SOCKADDR_FAMILY(addr, step) == AF_INET); - a.s_addr = htonl(addr->addresses[0]); - return ipv4_is_loopback(a); + struct in_addr a; + SockAddrStep step; + START_STEP(addr, step); + assert(SOCKADDR_FAMILY(addr, step) == AF_INET); + a.s_addr = htonl(addr->addresses[0]); + return ipv4_is_loopback(a); #endif } } @@ -434,9 +434,9 @@ int sk_addrtype(SockAddr *addr) return (family == AF_INET ? ADDRTYPE_IPV4 : #ifndef NO_IPV6 - family == AF_INET6 ? ADDRTYPE_IPV6 : + family == AF_INET6 ? ADDRTYPE_IPV6 : #endif - ADDRTYPE_NAME); + ADDRTYPE_NAME); } void sk_addrcopy(SockAddr *addr, char *buf) @@ -448,13 +448,13 @@ void sk_addrcopy(SockAddr *addr, char *buf) #ifndef NO_IPV6 if (family == AF_INET) - memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr, - sizeof(struct in_addr)); + memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr, + sizeof(struct in_addr)); else if (family == AF_INET6) - memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr, - sizeof(struct in6_addr)); + memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr, + sizeof(struct in6_addr)); else - unreachable("bad address family in sk_addrcopy"); + unreachable("bad address family in sk_addrcopy"); #else struct in_addr a; @@ -467,10 +467,10 @@ void sk_addrcopy(SockAddr *addr, char *buf) void sk_addr_free(SockAddr *addr) { if (--addr->refcount > 0) - return; + return; #ifndef NO_IPV6 if (addr->ais != NULL) - freeaddrinfo(addr->ais); + freeaddrinfo(addr->ais); #else sfree(addr->addresses); #endif @@ -488,7 +488,7 @@ static Plug *sk_net_plug(Socket *sock, Plug *p) NetSocket *s = container_of(sock, NetSocket, sock); Plug *ret = s->plug; if (p) - s->plug = p; + s->plug = p; return ret; } @@ -540,8 +540,8 @@ static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug) ret->s = sockfd; if (ret->s < 0) { - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } ret->oobinline = false; @@ -587,15 +587,15 @@ static int try_connect(NetSocket *sock) sock->s = s; if (s < 0) { - err = errno; - goto ret; + err = errno; + goto ret; } cloexec(s); if (sock->oobinline) { - int b = 1; - if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, + int b = 1; + if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b)) < 0) { err = errno; close(s); @@ -604,8 +604,8 @@ static int try_connect(NetSocket *sock) } if (sock->nodelay) { - int b = 1; - if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, + int b = 1; + if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b)) < 0) { err = errno; close(s); @@ -614,8 +614,8 @@ static int try_connect(NetSocket *sock) } if (sock->keepalive) { - int b = 1; - if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, + int b = 1; + if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b)) < 0) { err = errno; close(s); @@ -627,9 +627,9 @@ static int try_connect(NetSocket *sock) * Bind to local address. */ if (sock->privport) - localport = 1023; /* count from 1023 downwards */ + localport = 1023; /* count from 1023 downwards */ else - localport = 0; /* just use port 0 (ie kernel picks) */ + localport = 0; /* just use port 0 (ie kernel picks) */ /* BSD IP stacks need sockaddr_in zeroed before filling in */ memset(&u,'\0',sizeof(u)); @@ -637,44 +637,44 @@ static int try_connect(NetSocket *sock) /* We don't try to bind to a local address for UNIX domain sockets. (Why * do we bother doing the bind when localport == 0 anyway?) */ if (family != AF_UNIX) { - /* Loop round trying to bind */ - while (1) { - int retcode; + /* Loop round trying to bind */ + while (1) { + int retcode; #ifndef NO_IPV6 - if (family == AF_INET6) { - /* XXX use getaddrinfo to get a local address? */ - u.sin6.sin6_family = AF_INET6; - u.sin6.sin6_addr = in6addr_any; - u.sin6.sin6_port = htons(localport); - retcode = bind(s, &u.sa, sizeof(u.sin6)); - } else + if (family == AF_INET6) { + /* XXX use getaddrinfo to get a local address? */ + u.sin6.sin6_family = AF_INET6; + u.sin6.sin6_addr = in6addr_any; + u.sin6.sin6_port = htons(localport); + retcode = bind(s, &u.sa, sizeof(u.sin6)); + } else #endif - { - assert(family == AF_INET); - u.sin.sin_family = AF_INET; - u.sin.sin_addr.s_addr = htonl(INADDR_ANY); - u.sin.sin_port = htons(localport); - retcode = bind(s, &u.sa, sizeof(u.sin)); - } - if (retcode >= 0) { - err = 0; - break; /* done */ - } else { - err = errno; - if (err != EADDRINUSE) /* 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) - goto ret; + { + assert(family == AF_INET); + u.sin.sin_family = AF_INET; + u.sin.sin_addr.s_addr = htonl(INADDR_ANY); + u.sin.sin_port = htons(localport); + retcode = bind(s, &u.sa, sizeof(u.sin)); + } + if (retcode >= 0) { + err = 0; + break; /* done */ + } else { + err = errno; + if (err != EADDRINUSE) /* 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) + goto ret; } /* @@ -683,55 +683,55 @@ static int try_connect(NetSocket *sock) switch(family) { #ifndef NO_IPV6 case AF_INET: - /* XXX would be better to have got getaddrinfo() to fill in the port. */ - ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port = - htons(sock->port); - sa = (const union sockaddr_union *)sock->step.ai->ai_addr; - salen = sock->step.ai->ai_addrlen; - break; + /* XXX would be better to have got getaddrinfo() to fill in the port. */ + ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port = + htons(sock->port); + sa = (const union sockaddr_union *)sock->step.ai->ai_addr; + salen = sock->step.ai->ai_addrlen; + break; case AF_INET6: - ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port = - htons(sock->port); - sa = (const union sockaddr_union *)sock->step.ai->ai_addr; - salen = sock->step.ai->ai_addrlen; - break; + ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port = + htons(sock->port); + sa = (const union sockaddr_union *)sock->step.ai->ai_addr; + salen = sock->step.ai->ai_addrlen; + break; #else case AF_INET: - u.sin.sin_family = AF_INET; - u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]); - u.sin.sin_port = htons((short) sock->port); - sa = &u; - salen = sizeof u.sin; - break; + u.sin.sin_family = AF_INET; + u.sin.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]); + u.sin.sin_port = htons((short) sock->port); + sa = &u; + salen = sizeof u.sin; + break; #endif case AF_UNIX: - assert(sock->port == 0); /* to catch confused people */ - assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path); - u.su.sun_family = AF_UNIX; - strcpy(u.su.sun_path, sock->addr->hostname); - sa = &u; - salen = sizeof u.su; - break; + assert(sock->port == 0); /* to catch confused people */ + assert(strlen(sock->addr->hostname) < sizeof u.su.sun_path); + u.su.sun_family = AF_UNIX; + strcpy(u.su.sun_path, sock->addr->hostname); + sa = &u; + salen = sizeof u.su; + break; default: - unreachable("unknown address family"); - exit(1); /* XXX: GCC doesn't understand assert() on some systems. */ + unreachable("unknown address family"); + exit(1); /* XXX: GCC doesn't understand assert() on some systems. */ } nonblock(s); if ((connect(s, &(sa->sa), salen)) < 0) { - if ( errno != EINPROGRESS ) { - err = errno; - goto ret; - } + if ( errno != EINPROGRESS ) { + err = errno; + goto ret; + } } else { - /* - * If we _don't_ get EWOULDBLOCK, the connect has completed - * and we should set the socket as connected and writable. - */ - sock->connected = true; - sock->writable = true; + /* + * If we _don't_ get EWOULDBLOCK, the connect has completed + * and we should set the socket as connected and writable. + */ + sock->connected = true; + sock->writable = true; } uxsel_tell(sock); @@ -746,7 +746,7 @@ static int try_connect(NetSocket *sock) if (err) { SockAddr thisaddr = sk_extractaddr_tmp( sock->addr, &sock->step); - plug_log(sock->plug, 1, &thisaddr, sock->port, strerror(err), err); + plug_log(sock->plug, 1, &thisaddr, sock->port, strerror(err), err); } return err; } @@ -838,9 +838,9 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, */ address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET : #ifndef NO_IPV6 - orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 : + orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 : #endif - AF_UNSPEC); + AF_UNSPEC); #ifndef NO_IPV6 /* Let's default to IPv6. @@ -859,14 +859,14 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, #ifndef NO_IPV6 /* If the host doesn't support IPv6 try fallback to IPv4. */ if (s < 0 && address_family == AF_INET6) { - address_family = AF_INET; - s = socket(address_family, SOCK_STREAM, 0); + address_family = AF_INET; + s = socket(address_family, SOCK_STREAM, 0); } #endif if (s < 0) { - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } cloexec(s); @@ -893,17 +893,17 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, hints.ai_addr = NULL; hints.ai_canonname = NULL; hints.ai_next = NULL; - assert(port >= 0 && port <= 99999); + assert(port >= 0 && port <= 99999); sprintf(portstr, "%d", port); { char *trimmed_addr = host_strduptrim(srcaddr); retcode = getaddrinfo(trimmed_addr, portstr, &hints, &ai); sfree(trimmed_addr); } - if (retcode == 0) { - addr = (union sockaddr_union *)ai->ai_addr; - addrlen = ai->ai_addrlen; - } + if (retcode == 0) { + addr = (union sockaddr_union *)ai->ai_addr; + addrlen = ai->ai_addrlen; + } #else memset(&u,'\0',sizeof u); u.sin.sin_family = AF_INET; @@ -936,10 +936,10 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, { u.sin.sin_family = AF_INET; u.sin.sin_port = htons(port); - if (local_host_only) - u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - else - u.sin.sin_addr.s_addr = htonl(INADDR_ANY); + if (local_host_only) + u.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + else + u.sin.sin_addr.s_addr = htonl(INADDR_ANY); addr = &u; addrlen = sizeof(u.sin); } @@ -954,14 +954,14 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, if (retcode < 0) { close(s); - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } if (listen(s, SOMAXCONN) < 0) { close(s); - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } #ifndef NO_IPV6 @@ -1033,42 +1033,42 @@ void *sk_getxdmdata(Socket *sock, int *lenp) * downcasting it. */ if (sock->vt != &NetSocket_sockvt) - return NULL; /* failure */ + return NULL; /* failure */ s = container_of(sock, NetSocket, sock); addrlen = sizeof(u); if (getsockname(s->s, &u.sa, &addrlen) < 0) - return NULL; + return NULL; switch(u.sa.sa_family) { case AF_INET: - *lenp = 6; - buf = snewn(*lenp, char); - PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr)); - PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port)); - break; + *lenp = 6; + buf = snewn(*lenp, char); + PUT_32BIT_MSB_FIRST(buf, ntohl(u.sin.sin_addr.s_addr)); + PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin.sin_port)); + break; #ifndef NO_IPV6 case AF_INET6: - *lenp = 6; - buf = snewn(*lenp, char); - if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) { - memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4); - PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port)); - } else - /* This is stupid, but it's what XLib does. */ - memset(buf, 0, 6); - break; + *lenp = 6; + buf = snewn(*lenp, char); + if (IN6_IS_ADDR_V4MAPPED(&u.sin6.sin6_addr)) { + memcpy(buf, u.sin6.sin6_addr.s6_addr + 12, 4); + PUT_16BIT_MSB_FIRST(buf+4, ntohs(u.sin6.sin6_port)); + } else + /* This is stupid, but it's what XLib does. */ + memset(buf, 0, 6); + break; #endif case AF_UNIX: - *lenp = 6; - buf = snewn(*lenp, char); - PUT_32BIT_MSB_FIRST(buf, unix_addr--); + *lenp = 6; + buf = snewn(*lenp, char); + PUT_32BIT_MSB_FIRST(buf, unix_addr--); PUT_16BIT_MSB_FIRST(buf+4, getpid()); - break; + break; - /* XXX IPV6 */ + /* XXX IPV6 */ default: - return NULL; + return NULL; } return buf; @@ -1101,43 +1101,43 @@ static void socket_error_callback(void *vs) void try_send(NetSocket *s) { while (s->sending_oob || bufchain_size(&s->output_data) > 0) { - int nsent; - int err; - const void *data; - size_t len; + int nsent; + int err; + const void *data; + size_t len; int urgentflag; - if (s->sending_oob) { - urgentflag = MSG_OOB; - len = s->sending_oob; - data = &s->oobdata; - } else { - urgentflag = 0; + if (s->sending_oob) { + urgentflag = MSG_OOB; + len = s->sending_oob; + data = &s->oobdata; + } else { + urgentflag = 0; ptrlen bufdata = bufchain_prefix(&s->output_data); data = bufdata.ptr; len = bufdata.len; - } - nsent = send(s->s, data, len, urgentflag); - noise_ultralight(NOISE_SOURCE_IOLEN, nsent); - if (nsent <= 0) { - err = (nsent < 0 ? errno : 0); - if (err == EWOULDBLOCK) { - /* - * Perfectly normal: we've sent all we can for the moment. - */ - s->writable = false; - return; - } else { - /* - * We unfortunately can't just call plug_closing(), - * because it's quite likely that we're currently - * _in_ a call from the code we'd be calling back - * to, so we'd have to make half the SSH code - * reentrant. Instead we flag a pending error on - * the socket, to be dealt with (by calling - * plug_closing()) at some suitable future moment. - */ - s->pending_error = err; + } + nsent = send(s->s, data, len, urgentflag); + noise_ultralight(NOISE_SOURCE_IOLEN, nsent); + if (nsent <= 0) { + err = (nsent < 0 ? errno : 0); + if (err == EWOULDBLOCK) { + /* + * Perfectly normal: we've sent all we can for the moment. + */ + s->writable = false; + return; + } else { + /* + * We unfortunately can't just call plug_closing(), + * because it's quite likely that we're currently + * _in_ a call from the code we'd be calling back + * to, so we'd have to make half the SSH code + * reentrant. Instead we flag a pending error on + * the socket, to be dealt with (by calling + * plug_closing()) at some suitable future moment. + */ + s->pending_error = err; /* * Immediately cease selecting on this socket, so that * we don't tight-loop repeatedly trying to do @@ -1149,20 +1149,20 @@ void try_send(NetSocket *s) * deal with the error condition on this socket. */ queue_toplevel_callback(socket_error_callback, s); - return; - } - } else { - if (s->sending_oob) { - if (nsent < len) { - memmove(s->oobdata, s->oobdata+nsent, len-nsent); - s->sending_oob = len - nsent; - } else { - s->sending_oob = 0; - } - } else { - bufchain_consume(&s->output_data, nsent); - } - } + return; + } + } else { + if (s->sending_oob) { + if (nsent < len) { + memmove(s->oobdata, s->oobdata+nsent, len-nsent); + s->sending_oob = len - nsent; + } else { + s->sending_oob = 0; + } + } else { + bufchain_consume(&s->output_data, nsent); + } + } } /* @@ -1196,7 +1196,7 @@ static size_t sk_net_write(Socket *sock, const void *buf, size_t len) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); /* * Update the select() status to correctly reflect whether or @@ -1225,7 +1225,7 @@ static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); /* * Update the select() status to correctly reflect whether or @@ -1251,7 +1251,7 @@ static void sk_net_write_eof(Socket *sock) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); /* * Update the select() status to correctly reflect whether or @@ -1263,33 +1263,33 @@ static void sk_net_write_eof(Socket *sock) static void net_select_result(int fd, int event) { int ret; - char buf[20480]; /* nice big buffer for plenty of speed */ + char buf[20480]; /* nice big buffer for plenty of speed */ NetSocket *s; bool atmark = true; /* Find the Socket structure */ s = find234(sktree, &fd, cmpforsearch); if (!s) - return; /* boggle */ + return; /* boggle */ noise_ultralight(NOISE_SOURCE_IOID, fd); switch (event) { case SELECT_X: /* exceptional */ - if (!s->oobinline) { - /* - * On a non-oobinline socket, this 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(NOISE_SOURCE_IOLEN, ret); - if (ret <= 0) { + if (!s->oobinline) { + /* + * On a non-oobinline socket, this 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(NOISE_SOURCE_IOLEN, ret); + if (ret <= 0) { plug_closing(s->plug, - ret == 0 ? "Internal networking trouble" : - strerror(errno), errno, 0); - } else { + ret == 0 ? "Internal networking trouble" : + strerror(errno), errno, 0); + } else { /* * Receiving actual data on a socket means we can * stop falling back through the candidate @@ -1299,87 +1299,87 @@ static void net_select_result(int fd, int event) sk_addr_free(s->addr); s->addr = NULL; } - plug_receive(s->plug, 2, buf, ret); - } - break; - } + plug_receive(s->plug, 2, buf, ret); + } + break; + } - /* - * If we reach here, this is an oobinline socket, which - * means we should set s->oobpending and then deal with it - * when we get called for the readability event (which - * should also occur). - */ - s->oobpending = true; + /* + * If we reach here, this is an oobinline socket, which + * means we should set s->oobpending and then deal with it + * when we get called for the readability event (which + * should also occur). + */ + s->oobpending = true; break; case SELECT_R: /* readable; also acceptance */ - if (s->listener) { - /* - * On a listening socket, the readability event means a - * connection is ready to be accepted. - */ - union sockaddr_union su; - socklen_t addrlen = sizeof(su); + if (s->listener) { + /* + * On a listening socket, the readability event means a + * connection is ready to be accepted. + */ + union sockaddr_union su; + socklen_t addrlen = sizeof(su); accept_ctx_t actx; - int t; /* socket of connection */ + int t; /* socket of connection */ - memset(&su, 0, addrlen); - t = accept(s->s, &su.sa, &addrlen); - if (t < 0) { - break; - } + memset(&su, 0, addrlen); + t = accept(s->s, &su.sa, &addrlen); + if (t < 0) { + break; + } nonblock(t); actx.i = t; - if ((!s->addr || s->addr->superfamily != UNIX) && + if ((!s->addr || s->addr->superfamily != UNIX) && s->localhost_only && !sockaddr_is_loopback(&su.sa)) { - close(t); /* someone let nonlocal through?! */ - } else if (plug_accepting(s->plug, sk_net_accept, actx)) { - close(t); /* denied or error */ - } - break; - } + close(t); /* someone let nonlocal through?! */ + } else if (plug_accepting(s->plug, sk_net_accept, actx)) { + close(t); /* denied or error */ + } + break; + } - /* - * If we reach here, this is not a listening socket, so - * readability really means readability. - */ + /* + * If we reach here, this is not a listening socket, so + * readability really means readability. + */ - /* In the case the socket is still frozen, we don't even bother */ - if (s->frozen) - break; + /* In the case the socket is still frozen, we don't even bother */ + if (s->frozen) + break; - /* - * 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 && s->oobpending) { + /* + * 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 && s->oobpending) { int atmark_from_ioctl; - if (ioctl(s->s, SIOCATMARK, &atmark_from_ioctl) == 0) { + if (ioctl(s->s, SIOCATMARK, &atmark_from_ioctl) == 0) { atmark = atmark_from_ioctl; if (atmark) s->oobpending = false; /* clear this indicator */ } - } else - atmark = true; + } else + atmark = true; - ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0); - noise_ultralight(NOISE_SOURCE_IOLEN, ret); - if (ret < 0) { - if (errno == EWOULDBLOCK) { - break; - } - } - if (ret < 0) { + ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0); + noise_ultralight(NOISE_SOURCE_IOLEN, ret); + if (ret < 0) { + if (errno == EWOULDBLOCK) { + break; + } + } + if (ret < 0) { plug_closing(s->plug, strerror(errno), errno, 0); - } else if (0 == ret) { + } else if (0 == ret) { s->incomingeof = true; /* stop trying to read now */ uxsel_tell(s); - plug_closing(s->plug, NULL, 0, 0); - } else { + plug_closing(s->plug, NULL, 0, 0); + } else { /* * Receiving actual data on a socket means we can * stop falling back through the candidate @@ -1389,16 +1389,16 @@ static void net_select_result(int fd, int event) sk_addr_free(s->addr); s->addr = NULL; } - plug_receive(s->plug, atmark ? 0 : 1, buf, ret); - } - break; + plug_receive(s->plug, atmark ? 0 : 1, buf, ret); + } + break; case SELECT_W: /* writable */ - if (!s->connected) { - /* - * select/poll reports a socket as _writable_ when an - * asynchronous connect() attempt either completes or - * fails. So first we must find out which. - */ + if (!s->connected) { + /* + * select/poll reports a socket as _writable_ when an + * asynchronous connect() attempt either completes or + * fails. So first we must find out which. + */ { int err; socklen_t errlen = sizeof(err); @@ -1442,19 +1442,19 @@ static void net_select_result(int fd, int event) sk_addr_free(s->addr); s->addr = NULL; } - s->connected = true; + s->connected = true; s->writable = true; - uxsel_tell(s); - } else { - size_t bufsize_before, bufsize_after; - s->writable = true; - bufsize_before = s->sending_oob + bufchain_size(&s->output_data); - try_send(s); - bufsize_after = s->sending_oob + bufchain_size(&s->output_data); - if (bufsize_after < bufsize_before) - plug_sent(s->plug, bufsize_after); - } - break; + uxsel_tell(s); + } else { + size_t bufsize_before, bufsize_after; + s->writable = true; + bufsize_before = s->sending_oob + bufchain_size(&s->output_data); + try_send(s); + bufsize_after = s->sending_oob + bufchain_size(&s->output_data); + if (bufsize_after < bufsize_before) + plug_sent(s->plug, bufsize_after); + } + break; } } @@ -1477,7 +1477,7 @@ static void sk_net_set_frozen(Socket *sock, bool is_frozen) { NetSocket *s = container_of(sock, NetSocket, sock); if (s->frozen == is_frozen) - return; + return; s->frozen = is_frozen; uxsel_tell(s); } @@ -1578,9 +1578,9 @@ int net_service_lookup(char *service) struct servent *se; se = getservbyname(service, NULL); if (se != NULL) - return ntohs(se->s_port); + return ntohs(se->s_port); else - return 0; + return 0; } char *get_hostname(void) @@ -1589,11 +1589,11 @@ char *get_hostname(void) char *hostname = NULL; do { sgrowarray(hostname, size, size); - if ((gethostname(hostname, size) < 0) && (errno != ENAMETOOLONG)) { - sfree(hostname); - hostname = NULL; - break; - } + if ((gethostname(hostname, size) < 0) && (errno != ENAMETOOLONG)) { + sfree(hostname); + hostname = NULL; + break; + } } while (strlen(hostname) >= size-1); return hostname; } @@ -1610,17 +1610,17 @@ SockAddr *platform_get_x11_unix_address(const char *sockpath, int displaynum) * have been passed an explicit Unix socket path. */ if (sockpath) { - n = snprintf(ret->hostname, sizeof ret->hostname, - "%s", sockpath); + n = snprintf(ret->hostname, sizeof ret->hostname, + "%s", sockpath); } else { - n = snprintf(ret->hostname, sizeof ret->hostname, - "%s%d", X11_UNIX_PATH, displaynum); + n = snprintf(ret->hostname, sizeof ret->hostname, + "%s%d", X11_UNIX_PATH, displaynum); } if (n < 0) - ret->error = "snprintf failed"; + ret->error = "snprintf failed"; else if (n >= sizeof ret->hostname) - ret->error = "X11 UNIX name too long"; + ret->error = "X11 UNIX name too long"; #ifndef NO_IPV6 ret->ais = NULL; @@ -1642,10 +1642,10 @@ SockAddr *unix_sock_addr(const char *path) n = snprintf(ret->hostname, sizeof ret->hostname, "%s", path); if (n < 0) - ret->error = "snprintf failed"; + ret->error = "snprintf failed"; else if (n >= sizeof ret->hostname || n >= sizeof(((struct sockaddr_un *)0)->sun_path)) - ret->error = "socket pathname too long"; + ret->error = "socket pathname too long"; #ifndef NO_IPV6 ret->ais = NULL; @@ -1694,8 +1694,8 @@ Socket *new_unix_listener(SockAddr *listenaddr, Plug *plug) */ s = socket(AF_UNIX, SOCK_STREAM, 0); if (s < 0) { - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } cloexec(s); @@ -1717,21 +1717,21 @@ Socket *new_unix_listener(SockAddr *listenaddr, Plug *plug) if (unlink(u.su.sun_path) < 0 && errno != ENOENT) { close(s); - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } retcode = bind(s, &addr->sa, addrlen); if (retcode < 0) { close(s); - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } if (listen(s, SOMAXCONN) < 0) { close(s); - ret->error = strerror(errno); - return &ret->sock; + ret->error = strerror(errno); + return &ret->sock; } ret->s = s; diff --git a/unix/uxnoise.c b/unix/uxnoise.c index fb6c7c2c..0fbf8c4d 100644 --- a/unix/uxnoise.c +++ b/unix/uxnoise.c @@ -23,16 +23,16 @@ static bool read_dev_urandom(char *buf, int len) fd = open("/dev/urandom", O_RDONLY); if (fd < 0) - return false; + return false; ngot = 0; while (ngot < len) { - ret = read(fd, buf+ngot, len-ngot); - if (ret < 0) { - close(fd); - return false; - } - ngot += ret; + ret = read(fd, buf+ngot, len-ngot); + if (ret < 0) { + close(fd); + return false; + } + ngot += ret; } close(fd); @@ -55,30 +55,30 @@ void noise_get_heavy(void (*func) (void *, int)) bool got_dev_urandom = false; if (read_dev_urandom(buf, 32)) { - got_dev_urandom = true; - func(buf, 32); + got_dev_urandom = true; + func(buf, 32); } fp = popen("ps -axu 2>/dev/null", "r"); if (fp) { - while ( (ret = fread(buf, 1, sizeof(buf), fp)) > 0) - func(buf, ret); - pclose(fp); + while ( (ret = fread(buf, 1, sizeof(buf), fp)) > 0) + func(buf, ret); + pclose(fp); } else if (!got_dev_urandom) { - fprintf(stderr, "popen: %s\n" - "Unable to access fallback entropy source\n", strerror(errno)); - exit(1); + fprintf(stderr, "popen: %s\n" + "Unable to access fallback entropy source\n", strerror(errno)); + exit(1); } fp = popen("ls -al /tmp 2>/dev/null", "r"); if (fp) { - while ( (ret = fread(buf, 1, sizeof(buf), fp)) > 0) - func(buf, ret); - pclose(fp); + while ( (ret = fread(buf, 1, sizeof(buf), fp)) > 0) + func(buf, ret); + pclose(fp); } else if (!got_dev_urandom) { - fprintf(stderr, "popen: %s\n" - "Unable to access fallback entropy source\n", strerror(errno)); - exit(1); + fprintf(stderr, "popen: %s\n" + "Unable to access fallback entropy source\n", strerror(errno)); + exit(1); } read_random_seed(func); @@ -96,14 +96,14 @@ void noise_regular(void) struct rusage rusage; if ((fd = open("/proc/meminfo", O_RDONLY)) >= 0) { - while ( (ret = read(fd, buf, sizeof(buf))) > 0) - random_add_noise(NOISE_SOURCE_MEMINFO, buf, ret); - close(fd); + while ( (ret = read(fd, buf, sizeof(buf))) > 0) + random_add_noise(NOISE_SOURCE_MEMINFO, buf, ret); + close(fd); } if ((fd = open("/proc/stat", O_RDONLY)) >= 0) { - while ( (ret = read(fd, buf, sizeof(buf))) > 0) - random_add_noise(NOISE_SOURCE_STAT, buf, ret); - close(fd); + while ( (ret = read(fd, buf, sizeof(buf))) > 0) + random_add_noise(NOISE_SOURCE_STAT, buf, ret); + close(fd); } getrusage(RUSAGE_SELF, &rusage); random_add_noise(NOISE_SOURCE_RUSAGE, &rusage, sizeof(rusage)); diff --git a/unix/uxpgnt.c b/unix/uxpgnt.c index ac33a55c..9c5f4942 100644 --- a/unix/uxpgnt.c +++ b/unix/uxpgnt.c @@ -14,7 +14,7 @@ #include #include -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #include "putty.h" #include "ssh.h" #include "misc.h" @@ -153,11 +153,11 @@ void chan_no_request_response(Channel *chan, bool success) {} * it's time to terminate. */ static void x11_log(Plug *p, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) {} + const char *error_msg, int error_code) {} static void x11_receive(Plug *plug, int urgent, const char *data, size_t len) {} static void x11_sent(Plug *plug, size_t bufsize) {} static void x11_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { time_to_die = true; } @@ -864,8 +864,8 @@ void run_agent(void) pollwrapper *pw = pollwrap_new(); while (!time_to_die) { - int rwx; - int ret; + int rwx; + int ret; unsigned long next; pollwrap_clear(pw); @@ -874,24 +874,24 @@ void run_agent(void) pollwrap_add_fd_rwx(pw, signalpipe[0], SELECT_R); } - /* Count the currently active fds. */ - i = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) i++; + /* Count the currently active fds. */ + i = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) i++; - /* Expand the fdlist buffer if necessary. */ + /* Expand the fdlist buffer if necessary. */ sgrowarray(fdlist, fdsize, i); - /* - * Add all currently open fds to pw, and store them in fdlist - * as well. - */ - int fdcount = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) { - fdlist[fdcount++] = fd; + /* + * Add all currently open fds to pw, and store them in fdlist + * as well. + */ + int fdcount = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) { + fdlist[fdcount++] = fd; pollwrap_add_fd_rwx(pw, fd, rwx); - } + } if (toplevel_callback_pending()) { ret = pollwrap_poll_instant(pw); @@ -924,10 +924,10 @@ void run_agent(void) if (ret < 0 && errno == EINTR) continue; - if (ret < 0) { - perror("poll"); - exit(1); - } + if (ret < 0) { + perror("poll"); + exit(1); + } if (life == LIFE_TTY) { /* @@ -943,21 +943,21 @@ void run_agent(void) } } - for (i = 0; i < fdcount; i++) { - fd = fdlist[i]; + for (i = 0; i < fdcount; i++) { + fd = fdlist[i]; int rwx = pollwrap_get_fd_rwx(pw, fd); /* * We must process exceptional notifications before * ordinary readability ones, or we may go straight * past the urgent marker. */ - if (rwx & SELECT_X) - select_result(fd, SELECT_X); - if (rwx & SELECT_R) - select_result(fd, SELECT_R); - if (rwx & SELECT_W) - select_result(fd, SELECT_W); - } + if (rwx & SELECT_X) + select_result(fd, SELECT_X); + if (rwx & SELECT_R) + select_result(fd, SELECT_R); + if (rwx & SELECT_W) + select_result(fd, SELECT_W); + } if (signalpipe[0] >= 0 && pollwrap_check_fd_rwx(pw, signalpipe[0], SELECT_R)) { @@ -1002,11 +1002,11 @@ int main(int argc, char **argv) * Process the command line. */ while (--argc > 0) { - char *p = *++argv; - if (*p == '-' && doing_opts) { + char *p = *++argv; + if (*p == '-' && doing_opts) { if (!strcmp(p, "-V") || !strcmp(p, "--version")) { version(); - } else if (!strcmp(p, "--help")) { + } else if (!strcmp(p, "--help")) { usage(); exit(0); } else if (!strcmp(p, "-v")) { diff --git a/unix/uxplink.c b/unix/uxplink.c index 13f4a898..02014316 100644 --- a/unix/uxplink.c +++ b/unix/uxplink.c @@ -15,7 +15,7 @@ #include #include -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #include "putty.h" #include "storage.h" #include "tree234.h" @@ -46,9 +46,9 @@ Conf *conf; char *platform_default_s(const char *name) { if (!strcmp(name, "TermType")) - return dupstr(getenv("TERM")); + return dupstr(getenv("TERM")); if (!strcmp(name, "SerialLine")) - return dupstr("/dev/ttyS0"); + return dupstr("/dev/ttyS0"); return NULL; } @@ -70,14 +70,14 @@ FontSpec *platform_default_fontspec(const char *name) Filename *platform_default_filename(const char *name) { if (!strcmp(name, "LogFileName")) - return filename_from_str("putty.log"); + return filename_from_str("putty.log"); else - return filename_from_str(""); + return filename_from_str(""); } char *x_get_default(const char *key) { - return NULL; /* this is a stub */ + return NULL; /* this is a stub */ } static void plink_echoedit_update(Seat *seat, bool echo, bool edit) { @@ -89,29 +89,29 @@ static void plink_echoedit_update(Seat *seat, bool echo, bool edit) mode = orig_termios; if (echo) - mode.c_lflag |= ECHO; + mode.c_lflag |= ECHO; else - mode.c_lflag &= ~ECHO; + mode.c_lflag &= ~ECHO; if (edit) { - mode.c_iflag |= ICRNL; - mode.c_lflag |= ISIG | ICANON; - mode.c_oflag |= OPOST; + mode.c_iflag |= ICRNL; + mode.c_lflag |= ISIG | ICANON; + mode.c_oflag |= OPOST; } else { - mode.c_iflag &= ~ICRNL; - mode.c_lflag &= ~(ISIG | ICANON); - mode.c_oflag &= ~OPOST; - /* Solaris sets these to unhelpful values */ - mode.c_cc[VMIN] = 1; - mode.c_cc[VTIME] = 0; - /* FIXME: perhaps what we do with IXON/IXOFF should be an - * argument to the echoedit_update() method, to allow - * implementation of SSH-2 "xon-xoff" and Rlogin's - * equivalent? */ - mode.c_iflag &= ~IXON; - mode.c_iflag &= ~IXOFF; + mode.c_iflag &= ~ICRNL; + mode.c_lflag &= ~(ISIG | ICANON); + mode.c_oflag &= ~OPOST; + /* Solaris sets these to unhelpful values */ + mode.c_cc[VMIN] = 1; + mode.c_cc[VTIME] = 0; + /* FIXME: perhaps what we do with IXON/IXOFF should be an + * argument to the echoedit_update() method, to allow + * implementation of SSH-2 "xon-xoff" and Rlogin's + * equivalent? */ + mode.c_iflag &= ~IXON; + mode.c_iflag &= ~IXOFF; } - /* + /* * Mark parity errors and (more important) BREAK on input. This * is more complex than it need be because POSIX-2001 suggests * that escaping of valid 0xff in the input stream is dependent on @@ -132,7 +132,7 @@ static char *get_ttychar(struct termios *t, int index) cc_t c = t->c_cc[index]; #if defined(_POSIX_VDISABLE) if (c == _POSIX_VDISABLE) - return dupstr(""); + return dupstr(""); #endif return dupprintf("^<%d>", c); } @@ -147,16 +147,16 @@ static char *plink_get_ttymode(Seat *seat, const char *mode) #define GET_CHAR(ourname, uxname) \ do { \ - if (strcmp(mode, ourname) == 0) \ - return get_ttychar(&orig_termios, uxname); \ + if (strcmp(mode, ourname) == 0) \ + return get_ttychar(&orig_termios, uxname); \ } while(0) #define GET_BOOL(ourname, uxname, uxmemb, transform) \ do { \ - if (strcmp(mode, ourname) == 0) { \ - bool b = (orig_termios.uxmemb & uxname) != 0; \ - transform; \ - return dupprintf("%d", b); \ - } \ + if (strcmp(mode, ourname) == 0) { \ + bool b = (orig_termios.uxmemb & uxname) != 0; \ + transform; \ + return dupprintf("%d", b); \ + } \ } while (0) /* @@ -312,7 +312,7 @@ static char *plink_get_ttymode(Seat *seat, const char *mode) void cleanup_termios(void) { if (local_tty) - tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios); + tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios); } bufchain stdout_data, stderr_data; @@ -375,7 +375,7 @@ static int plink_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = console_get_userpass_input(p); + ret = console_get_userpass_input(p); return ret; } @@ -411,59 +411,59 @@ static void from_tty(void *vbuf, unsigned len) p = buf; end = buf + len; while (p < end) { - switch (state) { - case NORMAL: - if (*p == '\xff') { - p++; - state = FF; - } else { - q = memchr(p, '\xff', end - p); - if (q == NULL) q = end; + switch (state) { + case NORMAL: + if (*p == '\xff') { + p++; + state = FF; + } else { + q = memchr(p, '\xff', end - p); + if (q == NULL) q = end; backend_send(backend, p, q - p); - p = q; - } - break; - case FF: - if (*p == '\xff') { + p = q; + } + break; + case FF: + if (*p == '\xff') { backend_send(backend, p, 1); - p++; - state = NORMAL; - } else if (*p == '\0') { - p++; - state = FF00; - } else abort(); - break; - case FF00: - if (*p == '\0') { + p++; + state = NORMAL; + } else if (*p == '\0') { + p++; + state = FF00; + } else abort(); + break; + case FF00: + if (*p == '\0') { backend_special(backend, SS_BRK, 0); - } else { - /* - * Pretend that PARMRK wasn't set. This involves - * faking what INPCK and IGNPAR would have done if - * we hadn't overridden them. Unfortunately, we - * can't do this entirely correctly because INPCK - * distinguishes between framing and parity - * errors, but PARMRK format represents both in - * the same way. We assume that parity errors are - * more common than framing errors, and hence - * treat all input errors as being subject to - * INPCK. - */ - if (orig_termios.c_iflag & INPCK) { - /* If IGNPAR is set, we throw away the character. */ - if (!(orig_termios.c_iflag & IGNPAR)) { - /* PE/FE get passed on as NUL. */ - *p = 0; + } else { + /* + * Pretend that PARMRK wasn't set. This involves + * faking what INPCK and IGNPAR would have done if + * we hadn't overridden them. Unfortunately, we + * can't do this entirely correctly because INPCK + * distinguishes between framing and parity + * errors, but PARMRK format represents both in + * the same way. We assume that parity errors are + * more common than framing errors, and hence + * treat all input errors as being subject to + * INPCK. + */ + if (orig_termios.c_iflag & INPCK) { + /* If IGNPAR is set, we throw away the character. */ + if (!(orig_termios.c_iflag & IGNPAR)) { + /* PE/FE get passed on as NUL. */ + *p = 0; backend_send(backend, p, 1); - } - } else { - /* INPCK not set. Assume we got a parity error. */ + } + } else { + /* INPCK not set. Assume we got a parity error. */ backend_send(backend, p, 1); - } - } - p++; - state = NORMAL; - } + } + } + p++; + state = NORMAL; + } } } @@ -472,7 +472,7 @@ int signalpipe[2]; void sigwinch(int signum) { if (write(signalpipe[1], "x", 1) <= 0) - /* not much we can do about it */; + /* not much we can do about it */; } /* @@ -611,22 +611,22 @@ int main(int argc, char **argv) default_port = conf_get_int(conf, CONF_port); errors = false; { - /* - * Override the default protocol if PLINK_PROTOCOL is set. - */ - char *p = getenv("PLINK_PROTOCOL"); - if (p) { + /* + * Override the default protocol if PLINK_PROTOCOL is set. + */ + char *p = getenv("PLINK_PROTOCOL"); + if (p) { const struct BackendVtable *vt = backend_vt_from_name(p); if (vt) { default_protocol = vt->protocol; default_port = vt->default_port; - conf_set_int(conf, CONF_protocol, default_protocol); - conf_set_int(conf, CONF_port, default_port); - } - } + conf_set_int(conf, CONF_protocol, default_protocol); + conf_set_int(conf, CONF_port, default_port); + } + } } while (--argc) { - char *p = *++argv; + char *p = *++argv; int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1, conf); if (ret == -2) { @@ -682,7 +682,7 @@ int main(int argc, char **argv) sanitise_stderr = FORCE_OFF; } else if (!strcmp(p, "-no-antispoof")) { console_antispoof_prompt = false; - } else if (*p != '-') { + } else if (*p != '-') { strbuf *cmdbuf = strbuf_new(); while (argc > 0) { @@ -698,18 +698,18 @@ int main(int argc, char **argv) conf_set_bool(conf, CONF_nopty, true); /* command => no tty */ strbuf_free(cmdbuf); - break; /* done with cmdline */ + break; /* done with cmdline */ } else { fprintf(stderr, "plink: unknown option \"%s\"\n", p); errors = true; - } + } } if (errors) - return 1; + return 1; if (!cmdline_host_ok(conf)) { - usage(); + usage(); } prepare_session(conf); @@ -724,11 +724,11 @@ int main(int argc, char **argv) * one, as 'ssh' does. */ if (conf_get_str(conf, CONF_username)[0] == '\0') { - char *user = get_username(); - if (user) { - conf_set_str(conf, CONF_username, user); - sfree(user); - } + char *user = get_username(); + if (user) { + conf_set_str(conf, CONF_username, user); + sfree(user); + } } /* @@ -738,9 +738,9 @@ int main(int argc, char **argv) conf_set_bool(conf, CONF_ssh_subsys, true); if (!*conf_get_str(conf, CONF_remote_cmd) && - !*conf_get_str(conf, CONF_remote_cmd2) && - !*conf_get_str(conf, CONF_ssh_nc_host)) - flags |= FLAG_INTERACTIVE; + !*conf_get_str(conf, CONF_remote_cmd2) && + !*conf_get_str(conf, CONF_ssh_nc_host)) + flags |= FLAG_INTERACTIVE; /* * Select protocol. This is farmed out into a table in a @@ -748,9 +748,9 @@ int main(int argc, char **argv) */ backvt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol)); if (!backvt) { - fprintf(stderr, - "Internal fault: Unsupported protocol found\n"); - return 1; + fprintf(stderr, + "Internal fault: Unsupported protocol found\n"); + return 1; } /* @@ -763,8 +763,8 @@ int main(int argc, char **argv) * Set up the pipe we'll use to tell us about SIGWINCH. */ if (pipe(signalpipe) < 0) { - perror("pipe"); - exit(1); + perror("pipe"); + exit(1); } /* We don't want the signal handler to block if the pipe's full. */ nonblock(signalpipe[0]); @@ -778,8 +778,8 @@ int main(int argc, char **argv) * out the initial terminal size. */ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) { - conf_set_int(conf, CONF_width, size.ws_col); - conf_set_int(conf, CONF_height, size.ws_row); + conf_set_int(conf, CONF_width, size.ws_col); + conf_set_int(conf, CONF_height, size.ws_row); } /* @@ -818,10 +818,10 @@ int main(int argc, char **argv) * the "simple" flag. */ if (conf_get_int(conf, CONF_protocol) == PROT_SSH && - !conf_get_bool(conf, CONF_x11_forward) && - !conf_get_bool(conf, CONF_agentfwd) && - !conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) - conf_set_bool(conf, CONF_ssh_simple, true); + !conf_get_bool(conf, CONF_x11_forward) && + !conf_get_bool(conf, CONF_agentfwd) && + !conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) + conf_set_bool(conf, CONF_ssh_simple, true); if (just_test_share_exists) { if (!backvt->test_for_upstream) { @@ -841,14 +841,14 @@ int main(int argc, char **argv) */ logctx = log_init(default_logpolicy, conf); { - const char *error; - char *realhost; - /* nodelay is only useful if stdin is a terminal device */ - bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && isatty(0); + const char *error; + char *realhost; + /* nodelay is only useful if stdin is a terminal device */ + bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && isatty(0); - /* This is a good place for a fuzzer to fork us. */ + /* This is a good place for a fuzzer to fork us. */ #ifdef __AFL_HAVE_MANUAL_CONTROL - __AFL_INIT(); + __AFL_INIT(); #endif error = backend_init(backvt, plink_seat, &backend, logctx, conf, @@ -856,12 +856,12 @@ int main(int argc, char **argv) conf_get_int(conf, CONF_port), &realhost, nodelay, conf_get_bool(conf, CONF_tcp_keepalives)); - if (error) { - fprintf(stderr, "Unable to open connection:\n%s\n", error); - return 1; - } + if (error) { + fprintf(stderr, "Unable to open connection:\n%s\n", error); + return 1; + } ldisc_create(conf, NULL, backend, plink_seat); - sfree(realhost); + sfree(realhost); } /* @@ -878,50 +878,50 @@ int main(int argc, char **argv) pollwrapper *pw = pollwrap_new(); while (1) { - int rwx; - int ret; + int rwx; + int ret; unsigned long next; pollwrap_clear(pw); - pollwrap_add_fd_rwx(pw, signalpipe[0], SELECT_R); + pollwrap_add_fd_rwx(pw, signalpipe[0], SELECT_R); - if (!sending && + if (!sending && backend_connected(backend) && backend_sendok(backend) && backend_sendbuffer(backend) < MAX_STDIN_BACKLOG) { - /* If we're OK to send, then try to read from stdin. */ + /* If we're OK to send, then try to read from stdin. */ pollwrap_add_fd_rwx(pw, STDIN_FILENO, SELECT_R); - } + } - if (bufchain_size(&stdout_data) > 0) { - /* If we have data for stdout, try to write to stdout. */ + if (bufchain_size(&stdout_data) > 0) { + /* If we have data for stdout, try to write to stdout. */ pollwrap_add_fd_rwx(pw, STDOUT_FILENO, SELECT_W); - } + } - if (bufchain_size(&stderr_data) > 0) { - /* If we have data for stderr, try to write to stderr. */ + if (bufchain_size(&stderr_data) > 0) { + /* If we have data for stderr, try to write to stderr. */ pollwrap_add_fd_rwx(pw, STDERR_FILENO, SELECT_W); - } + } - /* Count the currently active fds. */ - i = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) i++; + /* Count the currently active fds. */ + i = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) i++; - /* Expand the fdlist buffer if necessary. */ + /* Expand the fdlist buffer if necessary. */ sgrowarray(fdlist, fdsize, i); - /* - * Add all currently open fds to pw, and store them in fdlist - * as well. - */ - int fdcount = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) { - fdlist[fdcount++] = fd; + /* + * Add all currently open fds to pw, and store them in fdlist + * as well. + */ + int fdcount = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) { + fdlist[fdcount++] = fd; pollwrap_add_fd_rwx(pw, fd, rwx); - } + } if (toplevel_callback_pending()) { ret = pollwrap_poll_instant(pw); @@ -930,12 +930,12 @@ int main(int argc, char **argv) unsigned long then; long ticks; - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; bool overflow = false; if (ticks > INT_MAX) { @@ -956,79 +956,79 @@ int main(int argc, char **argv) if (ret < 0 && errno == EINTR) continue; - if (ret < 0) { - perror("poll"); - exit(1); - } + if (ret < 0) { + perror("poll"); + exit(1); + } - for (i = 0; i < fdcount; i++) { - fd = fdlist[i]; + for (i = 0; i < fdcount; i++) { + fd = fdlist[i]; int rwx = pollwrap_get_fd_rwx(pw, fd); /* * We must process exceptional notifications before * ordinary readability ones, or we may go straight * past the urgent marker. */ - if (rwx & SELECT_X) - select_result(fd, SELECT_X); - if (rwx & SELECT_R) - select_result(fd, SELECT_R); - if (rwx & SELECT_W) - select_result(fd, SELECT_W); - } + if (rwx & SELECT_X) + select_result(fd, SELECT_X); + if (rwx & SELECT_R) + select_result(fd, SELECT_R); + if (rwx & SELECT_W) + select_result(fd, SELECT_W); + } - if (pollwrap_check_fd_rwx(pw, signalpipe[0], SELECT_R)) { - char c[1]; - struct winsize size; - if (read(signalpipe[0], c, 1) <= 0) - /* ignore error */; - /* ignore its value; it'll be `x' */ - if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0) + if (pollwrap_check_fd_rwx(pw, signalpipe[0], SELECT_R)) { + char c[1]; + struct winsize size; + if (read(signalpipe[0], c, 1) <= 0) + /* ignore error */; + /* ignore its value; it'll be `x' */ + if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0) backend_size(backend, size.ws_col, size.ws_row); - } + } - if (pollwrap_check_fd_rwx(pw, STDIN_FILENO, SELECT_R)) { - char buf[4096]; - int ret; + if (pollwrap_check_fd_rwx(pw, STDIN_FILENO, SELECT_R)) { + char buf[4096]; + int ret; if (backend_connected(backend)) { - ret = read(STDIN_FILENO, buf, sizeof(buf)); + ret = read(STDIN_FILENO, buf, sizeof(buf)); noise_ultralight(NOISE_SOURCE_IOLEN, ret); - if (ret < 0) { - perror("stdin: read"); - exit(1); - } else if (ret == 0) { + if (ret < 0) { + perror("stdin: read"); + exit(1); + } else if (ret == 0) { backend_special(backend, SS_EOF, 0); - sending = false; /* send nothing further after this */ - } else { - if (local_tty) - from_tty(buf, ret); - else + sending = false; /* send nothing further after this */ + } else { + if (local_tty) + from_tty(buf, ret); + else backend_send(backend, buf, ret); - } - } - } + } + } + } - if (pollwrap_check_fd_rwx(pw, STDOUT_FILENO, SELECT_W)) { + if (pollwrap_check_fd_rwx(pw, STDOUT_FILENO, SELECT_W)) { backend_unthrottle(backend, try_output(false)); - } + } - if (pollwrap_check_fd_rwx(pw, STDERR_FILENO, SELECT_W)) { + if (pollwrap_check_fd_rwx(pw, STDERR_FILENO, SELECT_W)) { backend_unthrottle(backend, try_output(true)); - } + } run_toplevel_callbacks(); if (!backend_connected(backend) && - bufchain_size(&stdout_data) == 0 && - bufchain_size(&stderr_data) == 0) - break; /* we closed the connection */ + bufchain_size(&stdout_data) == 0 && + bufchain_size(&stderr_data) == 0) + break; /* we closed the connection */ } exitcode = backend_exitcode(backend); if (exitcode < 0) { - fprintf(stderr, "Remote process exit code unavailable\n"); - exitcode = 1; /* this is an error condition */ + fprintf(stderr, "Remote process exit code unavailable\n"); + exitcode = 1; /* this is an error condition */ } cleanup_exit(exitcode); - return exitcode; /* shouldn't happen, but placates gcc */ + return exitcode; /* shouldn't happen, but placates gcc */ } diff --git a/unix/uxprint.c b/unix/uxprint.c index 2a111e65..3de6d21b 100644 --- a/unix/uxprint.c +++ b/unix/uxprint.c @@ -19,8 +19,8 @@ printer_job *printer_start_job(char *printer) */ ret->fp = popen(printer, "w"); if (!ret->fp) { - sfree(ret); - ret = NULL; + sfree(ret); + ret = NULL; } return ret; } @@ -28,16 +28,16 @@ printer_job *printer_start_job(char *printer) void printer_job_data(printer_job *pj, const void *data, size_t len) { if (!pj) - return; + return; if (fwrite(data, 1, len, pj->fp) < len) - /* ignore */; + /* ignore */; } void printer_finish_job(printer_job *pj) { if (!pj) - return; + return; pclose(pj->fp); sfree(pj); diff --git a/unix/uxproxy.c b/unix/uxproxy.c index 8e7b76da..7fb46efd 100644 --- a/unix/uxproxy.c +++ b/unix/uxproxy.c @@ -26,10 +26,10 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, proxytype = conf_get_int(conf, CONF_proxy_type); if (proxytype != PROXY_CMD && proxytype != PROXY_FUZZ) - return NULL; + return NULL; if (proxytype == PROXY_CMD) { - cmd = format_telnet_command(addr, port, conf); + cmd = format_telnet_command(addr, port, conf); { char *logmsg = dupprintf("Starting local proxy command: %s", cmd); @@ -37,65 +37,65 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, sfree(logmsg); } - /* - * Create the pipes to the proxy command, and spawn the proxy - * command process. - */ - if (pipe(to_cmd_pipe) < 0 || - pipe(from_cmd_pipe) < 0 || + /* + * Create the pipes to the proxy command, and spawn the proxy + * command process. + */ + if (pipe(to_cmd_pipe) < 0 || + pipe(from_cmd_pipe) < 0 || pipe(cmd_err_pipe) < 0) { - sfree(cmd); + sfree(cmd); return new_error_socket_fmt(plug, "pipe: %s", strerror(errno)); - } - cloexec(to_cmd_pipe[1]); - cloexec(from_cmd_pipe[0]); + } + cloexec(to_cmd_pipe[1]); + cloexec(from_cmd_pipe[0]); cloexec(cmd_err_pipe[0]); - pid = fork(); + pid = fork(); if (pid == 0) { - close(0); - close(1); - dup2(to_cmd_pipe[0], 0); - dup2(from_cmd_pipe[1], 1); - close(to_cmd_pipe[0]); - close(from_cmd_pipe[1]); + close(0); + close(1); + dup2(to_cmd_pipe[0], 0); + dup2(from_cmd_pipe[1], 1); + close(to_cmd_pipe[0]); + close(from_cmd_pipe[1]); dup2(cmd_err_pipe[1], 2); - noncloexec(0); - noncloexec(1); - execl("/bin/sh", "sh", "-c", cmd, (void *)NULL); - _exit(255); - } + noncloexec(0); + noncloexec(1); + execl("/bin/sh", "sh", "-c", cmd, (void *)NULL); + _exit(255); + } - sfree(cmd); + sfree(cmd); - if (pid < 0) + if (pid < 0) return new_error_socket_fmt(plug, "fork: %s", strerror(errno)); - close(to_cmd_pipe[0]); - close(from_cmd_pipe[1]); + close(to_cmd_pipe[0]); + close(from_cmd_pipe[1]); close(cmd_err_pipe[1]); - outfd = to_cmd_pipe[1]; - infd = from_cmd_pipe[0]; - inerrfd = cmd_err_pipe[0]; + outfd = to_cmd_pipe[1]; + infd = from_cmd_pipe[0]; + inerrfd = cmd_err_pipe[0]; } else { - cmd = format_telnet_command(addr, port, conf); - outfd = open("/dev/null", O_WRONLY); - if (outfd == -1) { - sfree(cmd); - return new_error_socket_fmt( + cmd = format_telnet_command(addr, port, conf); + outfd = open("/dev/null", O_WRONLY); + if (outfd == -1) { + sfree(cmd); + return new_error_socket_fmt( plug, "/dev/null: %s", strerror(errno)); - } - infd = open(cmd, O_RDONLY); - if (infd == -1) { + } + infd = open(cmd, O_RDONLY); + if (infd == -1) { Socket *toret = new_error_socket_fmt( plug, "%s: %s", cmd, strerror(errno)); - sfree(cmd); + sfree(cmd); close(outfd); - return toret; - } - sfree(cmd); - inerrfd = -1; + return toret; + } + sfree(cmd); + inerrfd = -1; } /* We are responsible for this and don't need it any more */ diff --git a/unix/uxpty.c b/unix/uxpty.c index 6b324e35..e57770f5 100644 --- a/unix/uxpty.c +++ b/unix/uxpty.c @@ -106,9 +106,9 @@ static int ptyfd_compare(void *av, void *bv) PtyFd *b = (PtyFd *)bv; if (a->fd < b->fd) - return -1; + return -1; else if (a->fd > b->fd) - return +1; + return +1; return 0; } @@ -118,9 +118,9 @@ static int ptyfd_find(void *av, void *bv) PtyFd *b = (PtyFd *)bv; if (a < b->fd) - return -1; + return -1; else if (a > b->fd) - return +1; + return +1; return 0; } @@ -138,9 +138,9 @@ static int pty_compare_by_pid(void *av, void *bv) Pty *b = (Pty *)bv; if (a->child_pid < b->child_pid) - return -1; + return -1; else if (a->child_pid > b->child_pid) - return +1; + return +1; return 0; } @@ -150,9 +150,9 @@ static int pty_find_by_pid(void *av, void *bv) Pty *b = (Pty *)bv; if (a < b->child_pid) - return -1; + return -1; else if (a > b->child_pid) - return +1; + return +1; return 0; } @@ -163,12 +163,12 @@ static tree234 *ptys_by_pid = NULL; * allocated a pty structure, which we must then return from * pty_init() rather than allocating a new one. Here we store that * structure between allocation and use. - * + * * Note that although most of this module is entirely capable of * handling multiple ptys in a single process, pty_pre_init() is * fundamentally _dependent_ on there being at most one pty per * process, so the normal static-data constraints don't apply. - * + * * Likewise, since utmp is only used via pty_pre_init, it too must * be single-instance, so we can declare utmp-related variables * here. @@ -240,9 +240,9 @@ static void setup_utmp(char *ttyname, char *location) strncpy(lastlog_entry.ll_host, location, lenof(lastlog_entry.ll_host)); time(&lastlog_entry.ll_time); if ((lastlog = fopen(LASTLOG_FILE, "r+")) != NULL) { - fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET); - fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog); - fclose(lastlog); + fseek(lastlog, sizeof(lastlog_entry) * getuid(), SEEK_SET); + fwrite(&lastlog_entry, 1, sizeof(lastlog_entry), lastlog); + fclose(lastlog); } #endif @@ -255,7 +255,7 @@ static void cleanup_utmp(void) struct timeval tv; if (!pty_stamped_utmp) - return; + return; utmp_entry.ut_type = DEAD_PROCESS; memset(utmp_entry.ut_user, 0, lenof(utmp_entry.ut_user)); @@ -280,7 +280,7 @@ static void cleanup_utmp(void) static void sigchld_handler(int signum) { if (write(pty_signal_pipe[1], "x", 1) <= 0) - /* not much we can do about it */; + /* not much we can do about it */; } static void pty_setup_sigchld_handler(void) @@ -304,7 +304,7 @@ static void fatal_sig_handler(int signum) static int pty_open_slave(Pty *pty) { if (pty->slave_fd < 0) { - pty->slave_fd = open(pty->name, O_RDWR); + pty->slave_fd = open(pty->name, O_RDWR); cloexec(pty->slave_fd); } @@ -321,34 +321,34 @@ static void pty_open_master(Pty *pty) struct group *gp; for (p1 = chars1; *p1; p1++) - for (p2 = chars2; *p2; p2++) { - sprintf(master_name, "/dev/pty%c%c", *p1, *p2); - pty->master_fd = open(master_name, O_RDWR); - if (pty->master_fd >= 0) { - if (geteuid() == 0 || - access(master_name, R_OK | W_OK) == 0) { - /* - * We must also check at this point that we are - * able to open the slave side of the pty. We - * wouldn't want to allocate the wrong master, - * get all the way down to forking, and _then_ - * find we're unable to open the slave. - */ - strcpy(pty->name, master_name); - pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */ + for (p2 = chars2; *p2; p2++) { + sprintf(master_name, "/dev/pty%c%c", *p1, *p2); + pty->master_fd = open(master_name, O_RDWR); + if (pty->master_fd >= 0) { + if (geteuid() == 0 || + access(master_name, R_OK | W_OK) == 0) { + /* + * We must also check at this point that we are + * able to open the slave side of the pty. We + * wouldn't want to allocate the wrong master, + * get all the way down to forking, and _then_ + * find we're unable to open the slave. + */ + strcpy(pty->name, master_name); + pty->name[5] = 't'; /* /dev/ptyXX -> /dev/ttyXX */ cloexec(pty->master_fd); - if (pty_open_slave(pty) >= 0 && - access(pty->name, R_OK | W_OK) == 0) - goto got_one; - if (pty->slave_fd > 0) - close(pty->slave_fd); - pty->slave_fd = -1; - } - close(pty->master_fd); - } - } + if (pty_open_slave(pty) >= 0 && + access(pty->name, R_OK | W_OK) == 0) + goto got_one; + if (pty->slave_fd > 0) + close(pty->slave_fd); + pty->slave_fd = -1; + } + close(pty->master_fd); + } + } /* If we get here, we couldn't get a tty at all. */ fprintf(stderr, "pterm: unable to open a pseudo-terminal device\n"); @@ -383,26 +383,26 @@ static void pty_open_master(Pty *pty) #endif if (pty->master_fd < 0) { - perror("posix_openpt"); - exit(1); + perror("posix_openpt"); + exit(1); } #else pty->master_fd = open("/dev/ptmx", flags); if (pty->master_fd < 0) { - perror("/dev/ptmx: open"); - exit(1); + perror("/dev/ptmx: open"); + exit(1); } #endif if (grantpt(pty->master_fd) < 0) { - perror("grantpt"); - exit(1); + perror("grantpt"); + exit(1); } - + if (unlockpt(pty->master_fd) < 0) { - perror("unlockpt"); - exit(1); + perror("unlockpt"); + exit(1); } cloexec(pty->master_fd); @@ -460,7 +460,7 @@ void pty_pre_init(void) #endif if (geteuid() != getuid() || getegid() != getgid()) { - pty_open_master(pty); + pty_open_master(pty); #ifndef OMIT_UTMP /* @@ -489,7 +489,7 @@ void pty_pre_init(void) dlen = 0; while (1) { - + ret = read(pipefd[0], buffer, lenof(buffer)); if (ret <= 0) { cleanup_utmp(); @@ -565,23 +565,23 @@ void pty_pre_init(void) /* Drop privs. */ { #ifndef HAVE_NO_SETRESUID - int gid = getgid(), uid = getuid(); - int setresgid(gid_t, gid_t, gid_t); - int setresuid(uid_t, uid_t, uid_t); - if (setresgid(gid, gid, gid) < 0) { + int gid = getgid(), uid = getuid(); + int setresgid(gid_t, gid_t, gid_t); + int setresuid(uid_t, uid_t, uid_t); + if (setresgid(gid, gid, gid) < 0) { perror("setresgid"); exit(1); } - if (setresuid(uid, uid, uid) < 0) { + if (setresuid(uid, uid, uid) < 0) { perror("setresuid"); exit(1); } #else - if (setgid(getgid()) < 0) { + if (setgid(getgid()) < 0) { perror("setgid"); exit(1); } - if (setuid(getuid()) < 0) { + if (setuid(getuid()) < 0) { perror("setuid"); exit(1); } @@ -601,13 +601,13 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) bool finished = false; if (event < 0) { - /* - * We've been called because our child process did - * something. `status' tells us what. - */ - if ((WIFEXITED(status) || WIFSIGNALED(status))) { - /* - * The primary child process died. + /* + * We've been called because our child process did + * something. `status' tells us what. + */ + if ((WIFEXITED(status) || WIFSIGNALED(status))) { + /* + * The primary child process died. */ pty->child_dead = true; del234(ptys_by_pid, pty); @@ -615,24 +615,24 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) /* * If this is an ordinary pty session, this is also the - * moment to terminate the whole backend. + * moment to terminate the whole backend. * * We _could_ instead keep the terminal open for remaining - * subprocesses to output to, but conventional wisdom - * seems to feel that that's the Wrong Thing for an - * xterm-alike, so we bail out now (though we don't - * necessarily _close_ the window, depending on the state - * of Close On Exit). This would be easy enough to change - * or make configurable if necessary. - */ + * subprocesses to output to, but conventional wisdom + * seems to feel that that's the Wrong Thing for an + * xterm-alike, so we bail out now (though we don't + * necessarily _close_ the window, depending on the state + * of Close On Exit). This would be easy enough to change + * or make configurable if necessary. + */ if (pty->master_fd >= 0) finished = true; - } + } } else { - if (event == SELECT_R) { + if (event == SELECT_R) { bool is_stdout = (fd == pty->master_o); - ret = read(fd, buf, sizeof(buf)); + ret = read(fd, buf, sizeof(buf)); /* * Treat EIO on a pty master as equivalent to EOF (because @@ -643,7 +643,7 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) if (fd == pty->master_fd && ret < 0 && errno == EIO) ret = 0; - if (ret == 0) { + if (ret == 0) { /* * EOF on this input fd, so to begin with, we may as * well close it, and remove all references to it in @@ -673,13 +673,13 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) if (!pty->child_dead) pty->exit_code = 0; } - } else if (ret < 0) { - perror("read pty master"); - exit(1); - } else if (ret > 0) { - seat_output(pty->seat, !is_stdout, buf, ret); - } - } else if (event == SELECT_W) { + } else if (ret < 0) { + perror("read pty master"); + exit(1); + } else if (ret > 0) { + seat_output(pty->seat, !is_stdout, buf, ret); + } + } else if (event == SELECT_W) { /* * Attempt to send data down the pty. */ @@ -688,7 +688,7 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) } if (finished && !pty->finished) { - int close_on_exit; + int close_on_exit; int i; for (i = 0; i < 3; i++) @@ -697,29 +697,29 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) pty_close(pty); - pty->finished = true; + pty->finished = true; - /* - * This is a slight layering-violation sort of hack: only - * if we're not closing on exit (COE is set to Never, or to - * Only On Clean and it wasn't a clean exit) do we output a - * `terminated' message. - */ - close_on_exit = conf_get_int(pty->conf, CONF_close_on_exit); - if (close_on_exit == FORCE_OFF || - (close_on_exit == AUTO && pty->exit_code != 0)) { - char *message; + /* + * This is a slight layering-violation sort of hack: only + * if we're not closing on exit (COE is set to Never, or to + * Only On Clean and it wasn't a clean exit) do we output a + * `terminated' message. + */ + close_on_exit = conf_get_int(pty->conf, CONF_close_on_exit); + if (close_on_exit == FORCE_OFF || + (close_on_exit == AUTO && pty->exit_code != 0)) { + char *message; if (WIFEXITED(pty->exit_code)) { - message = dupprintf( + message = dupprintf( "\r\n[pterm: process terminated with exit code %d]\r\n", WEXITSTATUS(pty->exit_code)); } else if (WIFSIGNALED(pty->exit_code)) { #ifdef HAVE_NO_STRSIGNAL - message = dupprintf( + message = dupprintf( "\r\n[pterm: process terminated on signal %d]\r\n", WTERMSIG(pty->exit_code)); #else - message = dupprintf( + message = dupprintf( "\r\n[pterm: process terminated on signal %d (%s)]\r\n", WTERMSIG(pty->exit_code), strsignal(WTERMSIG(pty->exit_code))); @@ -729,12 +729,12 @@ static void pty_real_select_result(Pty *pty, int fd, int event, int status) * is better than no message at all */ message = dupprintf("\r\n[pterm: process terminated]\r\n"); } - seat_stdout_pl(pty->seat, ptrlen_from_asciz(message)); + seat_stdout_pl(pty->seat, ptrlen_from_asciz(message)); sfree(message); - } + } seat_eof(pty->seat); - seat_notify_remote_exit(pty->seat); + seat_notify_remote_exit(pty->seat); } } @@ -757,18 +757,18 @@ static void pty_try_wait(void) void pty_select_result(int fd, int event) { if (fd == pty_signal_pipe[0]) { - char c[1]; + char c[1]; - if (read(pty_signal_pipe[0], c, 1) <= 0) - /* ignore error */; - /* ignore its value; it'll be `x' */ + if (read(pty_signal_pipe[0], c, 1) <= 0) + /* ignore error */; + /* ignore its value; it'll be `x' */ pty_try_wait(); } else { PtyFd *ptyfd = find234(ptyfds, &fd, ptyfd_find); - if (ptyfd) - pty_real_select_result(ptyfd->pty, fd, event, 0); + if (ptyfd) + pty_real_select_result(ptyfd->pty, fd, event, 0); } } @@ -862,7 +862,7 @@ Backend *pty_backend_create( { int slavefd; pid_t pid, pgrp; -#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ +#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ bool got_windowid; long windowid; #endif @@ -873,13 +873,13 @@ Backend *pty_backend_create( seat_set_trust_status(seat, false); if (single_pty) { - pty = single_pty; + pty = single_pty; assert(pty->conf == NULL); } else { - pty = new_pty_struct(); - pty->master_fd = pty->slave_fd = -1; + pty = new_pty_struct(); + pty->master_fd = pty->slave_fd = -1; #ifndef OMIT_UTMP - pty_stamped_utmp = false; + pty_stamped_utmp = false; #endif } for (i = 0; i < 6; i++) @@ -968,7 +968,7 @@ Backend *pty_backend_create( add234(ptyfds, &pty->fds[0]); } -#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ +#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ got_windowid = seat_get_windowid(pty->seat, &windowid); #endif @@ -983,16 +983,16 @@ Backend *pty_backend_create( */ pid = fork(); if (pid < 0) { - perror("fork"); - exit(1); + perror("fork"); + exit(1); } if (pid == 0) { struct termios attrs; - /* - * We are the child. - */ + /* + * We are the child. + */ if (pty_osx_envrestore_prefix) { int plen = strlen(pty_osx_envrestore_prefix); @@ -1082,34 +1082,34 @@ Backend *pty_backend_create( } } - setpgid(pgrp, pgrp); + setpgid(pgrp, pgrp); if (!pipes_instead) { int ptyfd = open(pty->name, O_WRONLY, 0); if (ptyfd >= 0) close(ptyfd); } - setpgid(pgrp, pgrp); + setpgid(pgrp, pgrp); if (env_vars_to_unset) for (const char *const *p = env_vars_to_unset; *p; p++) unsetenv(*p); - if (!pipes_instead) { - char *term_env_var = dupprintf("TERM=%s", - conf_get_str(conf, CONF_termtype)); - putenv(term_env_var); - /* We mustn't free term_env_var, as putenv links it into the - * environment in place. - */ - } -#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ - if (got_windowid) { - char *windowid_env_var = dupprintf("WINDOWID=%ld", windowid); - putenv(windowid_env_var); - /* We mustn't free windowid_env_var, as putenv links it into the - * environment in place. - */ - } + if (!pipes_instead) { + char *term_env_var = dupprintf("TERM=%s", + conf_get_str(conf, CONF_termtype)); + putenv(term_env_var); + /* We mustn't free term_env_var, as putenv links it into the + * environment in place. + */ + } +#ifndef NOT_X_WINDOWS /* for Mac OS X native compilation */ + if (got_windowid) { + char *windowid_env_var = dupprintf("WINDOWID=%ld", windowid); + putenv(windowid_env_var); + /* We mustn't free windowid_env_var, as putenv links it into the + * environment in place. + */ + } { /* * In case we were invoked with a --display argument that @@ -1128,22 +1128,22 @@ Backend *pty_backend_create( } } #endif - { - char *key, *val; + { + char *key, *val; - for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key); - val != NULL; - val = conf_get_str_strs(conf, CONF_environmt, key, &key)) { - char *varval = dupcat(key, "=", val, NULL); - putenv(varval); - /* - * We must not free varval, since putenv links it - * into the environment _in place_. Weird, but - * there we go. Memory usage will be rationalised - * as soon as we exec anyway. - */ - } - } + for (val = conf_get_str_strs(conf, CONF_environmt, NULL, &key); + val != NULL; + val = conf_get_str_strs(conf, CONF_environmt, key, &key)) { + char *varval = dupcat(key, "=", val, NULL); + putenv(varval); + /* + * We must not free varval, since putenv links it + * into the environment _in place_. Weird, but + * there we go. Memory usage will be rationalised + * as soon as we exec anyway. + */ + } + } if (dir) { if (chdir(dir) < 0) { @@ -1152,18 +1152,18 @@ Backend *pty_backend_create( } } - /* - * SIGINT, SIGQUIT and SIGPIPE may have been set to ignored by - * our parent, particularly by things like sh -c 'pterm &' and - * some window or session managers. SIGPIPE was also - * (potentially) blocked by us during startup. Reverse all - * this for our child process. - */ - putty_signal(SIGINT, SIG_DFL); - putty_signal(SIGQUIT, SIG_DFL); - putty_signal(SIGPIPE, SIG_DFL); - block_signal(SIGPIPE, false); - if (argv || cmd) { + /* + * SIGINT, SIGQUIT and SIGPIPE may have been set to ignored by + * our parent, particularly by things like sh -c 'pterm &' and + * some window or session managers. SIGPIPE was also + * (potentially) blocked by us during startup. Reverse all + * this for our child process. + */ + putty_signal(SIGINT, SIG_DFL); + putty_signal(SIGQUIT, SIG_DFL); + putty_signal(SIGPIPE, SIG_DFL); + block_signal(SIGPIPE, false); + if (argv || cmd) { /* * If we were given a separated argument list, try to exec * it. @@ -1207,31 +1207,31 @@ Backend *pty_backend_create( execl(shell, shell, "-c", cmd, (void *)NULL); } } else { - char *shell = getenv("SHELL"); - char *shellname; - if (conf_get_bool(conf, CONF_login_shell)) { - char *p = strrchr(shell, '/'); - shellname = snewn(2+strlen(shell), char); - p = p ? p+1 : shell; - sprintf(shellname, "-%s", p); - } else - shellname = shell; - execl(getenv("SHELL"), shellname, (void *)NULL); - } + char *shell = getenv("SHELL"); + char *shellname; + if (conf_get_bool(conf, CONF_login_shell)) { + char *p = strrchr(shell, '/'); + shellname = snewn(2+strlen(shell), char); + p = p ? p+1 : shell; + sprintf(shellname, "-%s", p); + } else + shellname = shell; + execl(getenv("SHELL"), shellname, (void *)NULL); + } - /* - * If we're here, exec has gone badly foom. - */ - perror("exec"); - _exit(127); + /* + * If we're here, exec has gone badly foom. + */ + perror("exec"); + _exit(127); } else { - pty->child_pid = pid; - pty->child_dead = false; - pty->finished = false; - if (pty->slave_fd > 0) - close(pty->slave_fd); - if (!ptys_by_pid) - ptys_by_pid = newtree234(pty_compare_by_pid); + pty->child_pid = pid; + pty->child_dead = false; + pty->finished = false; + if (pty->slave_fd > 0) + close(pty->slave_fd); + if (!ptys_by_pid) + ptys_by_pid = newtree234(pty_compare_by_pid); if (pty->pipefds[0] >= 0) { close(pty->pipefds[0]); pty->pipefds[0] = -1; @@ -1244,16 +1244,16 @@ Backend *pty_backend_create( close(pty->pipefds[5]); pty->pipefds[5] = -1; } - add234(ptys_by_pid, pty); + add234(ptys_by_pid, pty); } if (pty_signal_pipe[0] < 0) { - if (pipe(pty_signal_pipe) < 0) { - perror("pipe"); - exit(1); - } - cloexec(pty_signal_pipe[0]); - cloexec(pty_signal_pipe[1]); + if (pipe(pty_signal_pipe) < 0) { + perror("pipe"); + exit(1); + } + cloexec(pty_signal_pipe[0]); + cloexec(pty_signal_pipe[1]); } pty_uxsel_setup(pty); @@ -1336,7 +1336,7 @@ static void pty_try_write(Pty *pty) while (bufchain_size(&pty->output_data) > 0) { ptrlen data = bufchain_prefix(&pty->output_data); - ret = write(pty->master_i, data.ptr, data.len); + ret = write(pty->master_i, data.ptr, data.len); if (ret < 0 && (errno == EWOULDBLOCK)) { /* @@ -1344,11 +1344,11 @@ static void pty_try_write(Pty *pty) */ break; } - if (ret < 0) { - perror("write pty master"); - exit(1); - } - bufchain_consume(&pty->output_data, ret); + if (ret < 0) { + perror("write pty master"); + exit(1); + } + bufchain_consume(&pty->output_data, ret); } if (pty->pending_eof && bufchain_size(&pty->output_data) == 0) { @@ -1373,7 +1373,7 @@ static size_t pty_send(Backend *be, const char *buf, size_t len) Pty *pty = container_of(be, Pty, backend); if (pty->master_i < 0 || pty->pending_eof) - return 0; /* ignore all writes if fd closed */ + return 0; /* ignore all writes if fd closed */ bufchain_add(&pty->output_data, buf, len); pty_try_write(pty); @@ -1393,8 +1393,8 @@ static void pty_close(Pty *pty) uxsel_del(pty->master_i); if (pty->master_fd >= 0) { - close(pty->master_fd); - pty->master_fd = -1; + close(pty->master_fd); + pty->master_fd = -1; } for (i = 0; i < 6; i++) { if (pty->pipefds[i] >= 0) @@ -1404,8 +1404,8 @@ static void pty_close(Pty *pty) pty->master_i = pty->master_o = pty->master_e = -1; #ifndef OMIT_UTMP if (pty_utmp_helper_pipe >= 0) { - close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */ - pty_utmp_helper_pipe = -1; + close(pty_utmp_helper_pipe); /* this causes utmp to be cleaned up */ + pty_utmp_helper_pipe = -1; } #endif } @@ -1536,7 +1536,7 @@ static int pty_exitcode(Backend *be) { Pty *pty = container_of(be, Pty, backend); if (!pty->finished) - return -1; /* not dead yet */ + return -1; /* not dead yet */ else if (WIFSIGNALED(pty->exit_code)) return 128 + WTERMSIG(pty->exit_code); else @@ -1548,7 +1548,7 @@ int pty_backend_exit_signum(Backend *be) Pty *pty = container_of(be, Pty, backend); if (!pty->finished || !WIFSIGNALED(pty->exit_code)) - return -1; + return -1; return WTERMSIG(pty->exit_code); } @@ -1559,7 +1559,7 @@ ptrlen pty_backend_exit_signame(Backend *be, char **aux_msg) int sig = pty_backend_exit_signum(be); if (sig < 0) - return PTRLEN_LITERAL(""); + return PTRLEN_LITERAL(""); #define TRANSLATE_SIGNAL(s) do \ { \ diff --git a/unix/uxputty.c b/unix/uxputty.c index 86ae8278..8142bdd0 100644 --- a/unix/uxputty.c +++ b/unix/uxputty.c @@ -21,7 +21,7 @@ * Stubs to avoid uxpty.c needing to be linked in. */ const bool use_pty_argv = false; -char **pty_argv; /* never used */ +char **pty_argv; /* never used */ char *pty_osx_envrestore_prefix; /* @@ -68,8 +68,8 @@ char *platform_get_x_display(void) { const char *display; /* Try to take account of --display and what have you. */ if (!(display = gdk_get_display())) - /* fall back to traditional method */ - display = getenv("DISPLAY"); + /* fall back to traditional method */ + display = getenv("DISPLAY"); return dupstr(display); } @@ -86,7 +86,7 @@ void setup(bool single) { const struct BackendVtable *vt = backend_vt_from_proto(default_protocol); - default_port = 0; /* illegal */ + default_port = 0; /* illegal */ if (vt) default_port = vt->default_port; } diff --git a/unix/uxsel.c b/unix/uxsel.c index c16d5714..eb3abed3 100644 --- a/unix/uxsel.c +++ b/unix/uxsel.c @@ -1,6 +1,6 @@ /* * uxsel.c - * + * * This module is a sort of all-purpose interchange for file * descriptors. At one end it talks to uxnet.c and pty.c and * anything else which might have one or more fds that need @@ -17,7 +17,7 @@ struct fd { int fd; - int rwx; /* 4=except 2=write 1=read */ + int rwx; /* 4=except 2=write 1=read */ uxsel_callback_fn callback; uxsel_id *id; /* for uxsel_input_remove */ }; @@ -29,9 +29,9 @@ static int uxsel_fd_cmp(void *av, void *bv) struct fd *a = (struct fd *)av; struct fd *b = (struct fd *)bv; if (a->fd < b->fd) - return -1; + return -1; if (a->fd > b->fd) - return +1; + return +1; return 0; } static int uxsel_fd_findcmp(void *av, void *bv) @@ -39,9 +39,9 @@ static int uxsel_fd_findcmp(void *av, void *bv) int *a = (int *)av; struct fd *b = (struct fd *)bv; if (*a < b->fd) - return -1; + return -1; if (*a > b->fd) - return +1; + return +1; return 0; } @@ -69,12 +69,12 @@ void uxsel_set(int fd, int rwx, uxsel_callback_fn callback) uxsel_del(fd); if (rwx) { - newfd = snew(struct fd); - newfd->fd = fd; - newfd->rwx = rwx; - newfd->callback = callback; - newfd->id = uxsel_input_add(fd, rwx); - add234(fds, newfd); + newfd = snew(struct fd); + newfd->fd = fd; + newfd->rwx = rwx; + newfd->callback = callback; + newfd->id = uxsel_input_add(fd, rwx); + add234(fds, newfd); } } @@ -82,16 +82,16 @@ void uxsel_del(int fd) { struct fd *oldfd = find234(fds, &fd, uxsel_fd_findcmp); if (oldfd) { - if (oldfd->id) + if (oldfd->id) uxsel_input_remove(oldfd->id); - del234(fds, oldfd); - sfree(oldfd); + del234(fds, oldfd); + sfree(oldfd); } } /* * And here is the interface to select-functionality-supplying - * modules. + * modules. */ int next_fd(int *state, int *rwx) @@ -99,10 +99,10 @@ int next_fd(int *state, int *rwx) struct fd *fd; fd = index234(fds, (*state)++); if (fd) { - *rwx = fd->rwx; - return fd->fd; + *rwx = fd->rwx; + return fd->fd; } else - return -1; + return -1; } int first_fd(int *state, int *rwx) diff --git a/unix/uxser.c b/unix/uxser.c index 135a658a..f2b1cadf 100644 --- a/unix/uxser.c +++ b/unix/uxser.c @@ -39,9 +39,9 @@ static int serial_compare_by_fd(void *av, void *bv) Serial *b = (Serial *)bv; if (a->fd < b->fd) - return -1; + return -1; else if (a->fd > b->fd) - return +1; + return +1; return 0; } @@ -51,9 +51,9 @@ static int serial_find_by_fd(void *av, void *bv) Serial *b = (Serial *)bv; if (a < b->fd) - return -1; + return -1; else if (a > b->fd) - return +1; + return +1; return 0; } @@ -70,7 +70,7 @@ static const char *serial_configure(Serial *serial, Conf *conf) const char *str; if (serial->fd < 0) - return "Unable to reconfigure already-closed serial connection"; + return "Unable to reconfigure already-closed serial connection"; tcgetattr(serial->fd, &options); @@ -195,9 +195,9 @@ static const char *serial_configure(Serial *serial, Conf *conf) conf_get_int(conf, CONF_serdatabits)); if (conf_get_int(conf, CONF_serstopbits) >= 4) { - options.c_cflag |= CSTOPB; + options.c_cflag |= CSTOPB; } else { - options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSTOPB; } logeventf(serial->logctx, "Configuring %d stop bits", (options.c_cflag & CSTOPB ? 2 : 1)); @@ -211,33 +211,33 @@ static const char *serial_configure(Serial *serial, Conf *conf) #endif flow = conf_get_int(conf, CONF_serflow); if (flow == SER_FLOW_XONXOFF) { - options.c_iflag |= IXON | IXOFF; - str = "XON/XOFF"; + options.c_iflag |= IXON | IXOFF; + str = "XON/XOFF"; } else if (flow == SER_FLOW_RTSCTS) { #ifdef CRTSCTS - options.c_cflag |= CRTSCTS; + options.c_cflag |= CRTSCTS; #endif #ifdef CNEW_RTSCTS - options.c_cflag |= CNEW_RTSCTS; + options.c_cflag |= CNEW_RTSCTS; #endif - str = "RTS/CTS"; + str = "RTS/CTS"; } else - str = "no"; + str = "no"; logeventf(serial->logctx, "Configuring %s flow control", str); /* Parity */ parity = conf_get_int(conf, CONF_serparity); if (parity == SER_PAR_ODD) { - options.c_cflag |= PARENB; - options.c_cflag |= PARODD; - str = "odd"; + options.c_cflag |= PARENB; + options.c_cflag |= PARODD; + str = "odd"; } else if (parity == SER_PAR_EVEN) { - options.c_cflag |= PARENB; - options.c_cflag &= ~PARODD; - str = "even"; + options.c_cflag |= PARENB; + options.c_cflag &= ~PARODD; + str = "even"; } else { - options.c_cflag &= ~PARENB; - str = "no"; + options.c_cflag &= ~PARENB; + str = "no"; } logeventf(serial->logctx, "Configuring %s parity", str); @@ -245,35 +245,35 @@ static const char *serial_configure(Serial *serial, Conf *conf) options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_iflag &= ~(ISTRIP | IGNCR | INLCR | ICRNL #ifdef IUCLC - | IUCLC + | IUCLC #endif - ); + ); options.c_oflag &= ~(OPOST #ifdef ONLCR - | ONLCR + | ONLCR #endif #ifdef OCRNL - | OCRNL + | OCRNL #endif #ifdef ONOCR - | ONOCR + | ONOCR #endif #ifdef ONLRET - | ONLRET + | ONLRET #endif - ); + ); options.c_cc[VMIN] = 1; options.c_cc[VTIME] = 0; if (tcsetattr(serial->fd, TCSANOW, &options) < 0) - return "Unable to configure serial port"; + return "Unable to configure serial port"; return NULL; } /* * Called to set up the serial connection. - * + * * Returns an error message, or NULL on success. * * Also places the canonical host name into `realhost'. It must be @@ -281,7 +281,7 @@ static const char *serial_configure(Serial *serial, Conf *conf) */ static const char *serial_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, - const char *host, int port, char **realhost, + const char *host, int port, char **realhost, bool nodelay, bool keepalive) { Serial *serial; @@ -306,18 +306,18 @@ static const char *serial_init(Seat *seat, Backend **backend_handle, serial->fd = open(line, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (serial->fd < 0) - return "Unable to open serial port"; + return "Unable to open serial port"; cloexec(serial->fd); err = serial_configure(serial, conf); if (err) - return err; + return err; *realhost = dupstr(line); if (!serial_by_fd) - serial_by_fd = newtree234(serial_compare_by_fd); + serial_by_fd = newtree234(serial_compare_by_fd); add234(serial_by_fd, serial); serial_uxsel_setup(serial); @@ -333,8 +333,8 @@ static const char *serial_init(Seat *seat, Backend **backend_handle, static void serial_close(Serial *serial) { if (serial->fd >= 0) { - close(serial->fd); - serial->fd = -1; + close(serial->fd); + serial->fd = -1; } } @@ -369,46 +369,46 @@ static void serial_select_result(int fd, int event) serial = find234(serial_by_fd, &fd, serial_find_by_fd); if (!serial) - return; /* spurious event; keep going */ + return; /* spurious event; keep going */ if (event == 1) { - ret = read(serial->fd, buf, sizeof(buf)); + ret = read(serial->fd, buf, sizeof(buf)); - if (ret == 0) { - /* - * Shouldn't happen on a real serial port, but I'm open - * to the idea that there might be two-way devices we - * can treat _like_ serial ports which can return EOF. - */ - finished = true; - } else if (ret < 0) { + if (ret == 0) { + /* + * Shouldn't happen on a real serial port, but I'm open + * to the idea that there might be two-way devices we + * can treat _like_ serial ports which can return EOF. + */ + finished = true; + } else if (ret < 0) { #ifdef EAGAIN - if (errno == EAGAIN) - return; /* spurious */ + if (errno == EAGAIN) + return; /* spurious */ #endif #ifdef EWOULDBLOCK - if (errno == EWOULDBLOCK) - return; /* spurious */ + if (errno == EWOULDBLOCK) + return; /* spurious */ #endif - perror("read serial port"); - exit(1); - } else if (ret > 0) { - serial->inbufsize = seat_stdout(serial->seat, buf, ret); - serial_uxsel_setup(serial); /* might acquire backlog and freeze */ - } + perror("read serial port"); + exit(1); + } else if (ret > 0) { + serial->inbufsize = seat_stdout(serial->seat, buf, ret); + serial_uxsel_setup(serial); /* might acquire backlog and freeze */ + } } else if (event == 2) { - /* - * Attempt to send data down the pty. - */ - serial_try_write(serial); + /* + * Attempt to send data down the pty. + */ + serial_try_write(serial); } if (finished) { - serial_close(serial); + serial_close(serial); - serial->finished = true; + serial->finished = true; - seat_notify_remote_exit(serial->seat); + seat_notify_remote_exit(serial->seat); } } @@ -417,7 +417,7 @@ static void serial_uxsel_setup(Serial *serial) int rwx = 0; if (serial->inbufsize <= SERIAL_MAX_BACKLOG) - rwx |= SELECT_R; + rwx |= SELECT_R; if (bufchain_size(&serial->output_data)) rwx |= SELECT_W; /* might also want to write to it */ uxsel_set(serial->fd, rwx, serial_select_result); @@ -431,7 +431,7 @@ static void serial_try_write(Serial *serial) while (bufchain_size(&serial->output_data) > 0) { ptrlen data = bufchain_prefix(&serial->output_data); - ret = write(serial->fd, data.ptr, data.len); + ret = write(serial->fd, data.ptr, data.len); if (ret < 0 && (errno == EWOULDBLOCK)) { /* @@ -439,11 +439,11 @@ static void serial_try_write(Serial *serial) */ break; } - if (ret < 0) { - perror("write serial port"); - exit(1); - } - bufchain_consume(&serial->output_data, ret); + if (ret < 0) { + perror("write serial port"); + exit(1); + } + bufchain_consume(&serial->output_data, ret); } serial_uxsel_setup(serial); @@ -457,7 +457,7 @@ static size_t serial_send(Backend *be, const char *buf, size_t len) Serial *serial = container_of(be, Serial, backend); if (serial->fd < 0) - return 0; + return 0; bufchain_add(&serial->output_data, buf, len); serial_try_write(serial); @@ -491,7 +491,7 @@ static void serial_special(Backend *be, SessionSpecialCode code, int arg) Serial *serial = container_of(be, Serial, backend); if (serial->fd >= 0 && code == SS_BRK) { - tcsendbreak(serial->fd, 0); + tcsendbreak(serial->fd, 0); logevent(serial->logctx, "Sending serial break at user request"); } @@ -505,8 +505,8 @@ static void serial_special(Backend *be, SessionSpecialCode code, int arg) static const SessionSpecial *serial_get_specials(Backend *be) { static const struct SessionSpecial specials[] = { - {"Break", SS_BRK}, - {NULL, SS_EXITMENU} + {"Break", SS_BRK}, + {NULL, SS_EXITMENU} }; return specials; } diff --git a/unix/uxserver.c b/unix/uxserver.c index 8fdc138f..b063e50e 100644 --- a/unix/uxserver.c +++ b/unix/uxserver.c @@ -38,7 +38,7 @@ #include #include -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #include "putty.h" #include "mpint.h" #include "ssh.h" @@ -93,7 +93,7 @@ Filename *platform_default_filename(const char *name) char *x_get_default(const char *key) { - return NULL; /* this is a stub */ + return NULL; /* this is a stub */ } /* @@ -486,7 +486,7 @@ static int server_accepting(Plug *p, accept_fn_t constructor, accept_ctx_t ctx) Plug *plug = server_conn_plug(cfg, &inst); s = constructor(ctx, plug); if ((err = sk_socket_error(s)) != NULL) - return 1; + return 1; SocketPeerInfo *pi = sk_peer_info(s); @@ -837,30 +837,30 @@ int main(int argc, char **argv) pollwrapper *pw = pollwrap_new(); while (!finished) { - int rwx; - int ret; + int rwx; + int ret; unsigned long next; pollwrap_clear(pw); - /* Count the currently active fds. */ - i = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) i++; + /* Count the currently active fds. */ + i = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) i++; - /* Expand the fdlist buffer if necessary. */ + /* Expand the fdlist buffer if necessary. */ sgrowarray(fdlist, fdsize, i); - /* - * Add all currently open fds to the select sets, and store - * them in fdlist as well. - */ - int fdcount = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) { - fdlist[fdcount++] = fd; + /* + * Add all currently open fds to the select sets, and store + * them in fdlist as well. + */ + int fdcount = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) { + fdlist[fdcount++] = fd; pollwrap_add_fd_rwx(pw, fd, rwx); - } + } if (toplevel_callback_pending()) { ret = pollwrap_poll_instant(pw); @@ -869,12 +869,12 @@ int main(int argc, char **argv) unsigned long then; long ticks; - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; bool overflow = false; if (ticks > INT_MAX) { @@ -895,26 +895,26 @@ int main(int argc, char **argv) if (ret < 0 && errno == EINTR) continue; - if (ret < 0) { - perror("poll"); - exit(1); - } + if (ret < 0) { + perror("poll"); + exit(1); + } - for (i = 0; i < fdcount; i++) { - fd = fdlist[i]; + for (i = 0; i < fdcount; i++) { + fd = fdlist[i]; int rwx = pollwrap_get_fd_rwx(pw, fd); /* * We must process exceptional notifications before * ordinary readability ones, or we may go straight * past the urgent marker. */ - if (rwx & SELECT_X) - select_result(fd, SELECT_X); - if (rwx & SELECT_R) - select_result(fd, SELECT_R); - if (rwx & SELECT_W) - select_result(fd, SELECT_W); - } + if (rwx & SELECT_X) + select_result(fd, SELECT_X); + if (rwx & SELECT_R) + select_result(fd, SELECT_R); + if (rwx & SELECT_W) + select_result(fd, SELECT_W); + } run_toplevel_callbacks(); } diff --git a/unix/uxsftp.c b/unix/uxsftp.c index 9b9592ea..de838f88 100644 --- a/unix/uxsftp.c +++ b/unix/uxsftp.c @@ -30,7 +30,7 @@ void uxsel_input_remove(uxsel_id *id) { } char *x_get_default(const char *key) { - return NULL; /* this is a stub */ + return NULL; /* this is a stub */ } void platform_get_x11_auth(struct X11Display *display, Conf *conf) @@ -65,9 +65,9 @@ FontSpec *platform_default_fontspec(const char *name) Filename *platform_default_filename(const char *name) { if (!strcmp(name, "LogFileName")) - return filename_from_str("putty.log"); + return filename_from_str("putty.log"); else - return filename_from_str(""); + return filename_from_str(""); } int filexfer_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) @@ -75,7 +75,7 @@ int filexfer_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = console_get_userpass_input(p); + ret = console_get_userpass_input(p); return ret; } @@ -86,9 +86,9 @@ int filexfer_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) char *psftp_lcd(char *dir) { if (chdir(dir) < 0) - return dupprintf("%s: chdir: %s", dir, strerror(errno)); + return dupprintf("%s: chdir: %s", dir, strerror(errno)); else - return NULL; + return NULL; } /* @@ -102,17 +102,17 @@ char *psftp_getcwd(void) buffer = snewn(size, char); while (1) { - ret = getcwd(buffer, size); - if (ret != NULL) - return ret; - if (errno != ERANGE) { - sfree(buffer); - return dupprintf("[cwd unavailable: %s]", strerror(errno)); - } - /* - * Otherwise, ERANGE was returned, meaning the buffer - * wasn't big enough. - */ + ret = getcwd(buffer, size); + if (ret != NULL) + return ret; + if (errno != ERANGE) { + sfree(buffer); + return dupprintf("[cwd unavailable: %s]", strerror(errno)); + } + /* + * Otherwise, ERANGE was returned, meaning the buffer + * wasn't big enough. + */ sgrowarray(buffer, size, size); } } @@ -122,7 +122,7 @@ struct RFile { }; RFile *open_existing_file(const char *name, uint64_t *size, - unsigned long *mtime, unsigned long *atime, + unsigned long *mtime, unsigned long *atime, long *perms) { int fd; @@ -130,29 +130,29 @@ RFile *open_existing_file(const char *name, uint64_t *size, fd = open(name, O_RDONLY); if (fd < 0) - return NULL; + return NULL; ret = snew(RFile); ret->fd = fd; if (size || mtime || atime || perms) { - struct stat statbuf; - if (fstat(fd, &statbuf) < 0) { - fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); - memset(&statbuf, 0, sizeof(statbuf)); - } + struct stat statbuf; + if (fstat(fd, &statbuf) < 0) { + fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); + memset(&statbuf, 0, sizeof(statbuf)); + } - if (size) - *size = statbuf.st_size; - - if (mtime) - *mtime = statbuf.st_mtime; + if (size) + *size = statbuf.st_size; - if (atime) - *atime = statbuf.st_atime; + if (mtime) + *mtime = statbuf.st_mtime; - if (perms) - *perms = statbuf.st_mode; + if (atime) + *atime = statbuf.st_atime; + + if (perms) + *perms = statbuf.st_mode; } return ret; @@ -182,7 +182,7 @@ WFile *open_new_file(const char *name, long perms) fd = open(name, O_CREAT | O_TRUNC | O_WRONLY, (mode_t)(perms ? perms : 0666)); if (fd < 0) - return NULL; + return NULL; ret = snew(WFile); ret->fd = fd; @@ -199,20 +199,20 @@ WFile *open_existing_wfile(const char *name, uint64_t *size) fd = open(name, O_APPEND | O_WRONLY); if (fd < 0) - return NULL; + return NULL; ret = snew(WFile); ret->fd = fd; ret->name = dupstr(name); if (size) { - struct stat statbuf; - if (fstat(fd, &statbuf) < 0) { - fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); - memset(&statbuf, 0, sizeof(statbuf)); - } + struct stat statbuf; + if (fstat(fd, &statbuf) < 0) { + fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); + memset(&statbuf, 0, sizeof(statbuf)); + } - *size = statbuf.st_size; + *size = statbuf.st_size; } return ret; @@ -225,17 +225,17 @@ int write_to_file(WFile *f, void *buffer, int length) /* Keep trying until we've really written as much as we can. */ while (length > 0) { - int ret = write(f->fd, p, length); + int ret = write(f->fd, p, length); - if (ret < 0) - return ret; + if (ret < 0) + return ret; - if (ret == 0) - break; + if (ret == 0) + break; - p += ret; - length -= ret; - so_far += ret; + p += ret; + length -= ret; + so_far += ret; } return so_far; @@ -264,19 +264,19 @@ void close_wfile(WFile *f) int seek_file(WFile *f, uint64_t offset, int whence) { int lseek_whence; - + switch (whence) { case FROM_START: - lseek_whence = SEEK_SET; - break; + lseek_whence = SEEK_SET; + break; case FROM_CURRENT: - lseek_whence = SEEK_CUR; - break; + lseek_whence = SEEK_CUR; + break; case FROM_END: - lseek_whence = SEEK_END; - break; + lseek_whence = SEEK_END; + break; default: - return -1; + return -1; } return lseek(f->fd, offset, lseek_whence) >= 0 ? 0 : -1; @@ -292,16 +292,16 @@ int file_type(const char *name) struct stat statbuf; if (stat(name, &statbuf) < 0) { - if (errno != ENOENT) - fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); - return FILE_TYPE_NONEXISTENT; + if (errno != ENOENT) + fprintf(stderr, "%s: stat: %s\n", name, strerror(errno)); + return FILE_TYPE_NONEXISTENT; } if (S_ISREG(statbuf.st_mode)) - return FILE_TYPE_FILE; + return FILE_TYPE_FILE; if (S_ISDIR(statbuf.st_mode)) - return FILE_TYPE_DIRECTORY; + return FILE_TYPE_DIRECTORY; return FILE_TYPE_WEIRD; } @@ -318,7 +318,7 @@ DirHandle *open_directory(const char *name, const char **errmsg) dir = opendir(name); if (!dir) { *errmsg = strerror(errno); - return NULL; + return NULL; } ret = snew(DirHandle); @@ -331,12 +331,12 @@ char *read_filename(DirHandle *dir) struct dirent *de; do { - de = readdir(dir->dir); - if (de == NULL) - return NULL; + de = readdir(dir->dir); + if (de == NULL) + return NULL; } while ((de->d_name[0] == '.' && - (de->d_name[1] == '\0' || - (de->d_name[1] == '.' && de->d_name[2] == '\0')))); + (de->d_name[1] == '\0' || + (de->d_name[1] == '.' && de->d_name[2] == '\0')))); return dupstr(de->d_name); } @@ -352,26 +352,26 @@ int test_wildcard(const char *name, bool cmdline) struct stat statbuf; if (stat(name, &statbuf) == 0) { - return WCTYPE_FILENAME; + return WCTYPE_FILENAME; } else if (cmdline) { - /* - * On Unix, we never need to parse wildcards coming from - * the command line, because the shell will have expanded - * them into a filename list already. - */ - return WCTYPE_NONEXISTENT; + /* + * On Unix, we never need to parse wildcards coming from + * the command line, because the shell will have expanded + * them into a filename list already. + */ + return WCTYPE_NONEXISTENT; } else { #if HAVE_GLOB_H - glob_t globbed; - int ret = WCTYPE_NONEXISTENT; + glob_t globbed; + int ret = WCTYPE_NONEXISTENT; - if (glob(name, GLOB_ERR, NULL, &globbed) == 0) { - if (globbed.gl_pathc > 0) - ret = WCTYPE_WILDCARD; - globfree(&globbed); - } + if (glob(name, GLOB_ERR, NULL, &globbed) == 0) { + if (globbed.gl_pathc > 0) + ret = WCTYPE_WILDCARD; + globfree(&globbed); + } - return ret; + return ret; #else /* On a system without glob.h, we just have to return a * failure code */ @@ -392,8 +392,8 @@ WildcardMatcher *begin_wildcard_matching(const char *name) { WildcardMatcher *ret = snew(WildcardMatcher); if (glob(name, 0, NULL, &ret->globbed) < 0) { - sfree(ret); - return NULL; + sfree(ret); + return NULL; } ret->i = 0; @@ -402,9 +402,9 @@ WildcardMatcher *begin_wildcard_matching(const char *name) { } char *wildcard_get_filename(WildcardMatcher *dir) { if (dir->i < dir->globbed.gl_pathc) { - return dupstr(dir->globbed.gl_pathv[dir->i++]); + return dupstr(dir->globbed.gl_pathv[dir->i++]); } else - return NULL; + return NULL; } void finish_wildcard_matching(WildcardMatcher *dir) { globfree(&dir->globbed); @@ -442,10 +442,10 @@ char *stripslashes(const char *str, bool local) bool vet_filename(const char *name) { if (strchr(name, '/')) - return false; + return false; if (name[0] == '.' && (!name[1] || (name[1] == '.' && !name[2]))) - return false; + return false; return true; } @@ -483,34 +483,34 @@ static int ssh_sftp_do_select(bool include_stdin, bool no_fds_ok) do { - /* Count the currently active fds. */ - i = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) i++; + /* Count the currently active fds. */ + i = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) i++; - if (i < 1 && !no_fds_ok && !toplevel_callback_pending()) { + if (i < 1 && !no_fds_ok && !toplevel_callback_pending()) { pollwrap_free(pw); - return -1; /* doom */ + return -1; /* doom */ } - /* Expand the fdlist buffer if necessary. */ + /* Expand the fdlist buffer if necessary. */ sgrowarray(fdlist, fdsize, i); pollwrap_clear(pw); - /* - * Add all currently open fds to the select sets, and store - * them in fdlist as well. - */ - fdcount = 0; - for (fd = first_fd(&fdstate, &rwx); fd >= 0; - fd = next_fd(&fdstate, &rwx)) { - fdlist[fdcount++] = fd; + /* + * Add all currently open fds to the select sets, and store + * them in fdlist as well. + */ + fdcount = 0; + for (fd = first_fd(&fdstate, &rwx); fd >= 0; + fd = next_fd(&fdstate, &rwx)) { + fdlist[fdcount++] = fd; pollwrap_add_fd_rwx(pw, fd, rwx); - } + } - if (include_stdin) - pollwrap_add_fd_rwx(pw, 0, SELECT_R); + if (include_stdin) + pollwrap_add_fd_rwx(pw, 0, SELECT_R); if (toplevel_callback_pending()) { ret = pollwrap_poll_instant(pw); @@ -521,12 +521,12 @@ static int ssh_sftp_do_select(bool include_stdin, bool no_fds_ok) unsigned long then; long ticks; - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; bool overflow = false; if (ticks > INT_MAX) { @@ -548,24 +548,24 @@ static int ssh_sftp_do_select(bool include_stdin, bool no_fds_ok) } while (ret == 0 && !done_something); if (ret < 0) { - perror("poll"); - exit(1); + perror("poll"); + exit(1); } for (i = 0; i < fdcount; i++) { - fd = fdlist[i]; + fd = fdlist[i]; int rwx = pollwrap_get_fd_rwx(pw, fd); - /* - * We must process exceptional notifications before - * ordinary readability ones, or we may go straight - * past the urgent marker. - */ - if (rwx & SELECT_X) - select_result(fd, SELECT_X); - if (rwx & SELECT_R) - select_result(fd, SELECT_R); - if (rwx & SELECT_W) - select_result(fd, SELECT_W); + /* + * We must process exceptional notifications before + * ordinary readability ones, or we may go straight + * past the urgent marker. + */ + if (rwx & SELECT_X) + select_result(fd, SELECT_X); + if (rwx & SELECT_R) + select_result(fd, SELECT_R); + if (rwx & SELECT_W) + select_result(fd, SELECT_W); } sfree(fdlist); @@ -601,31 +601,31 @@ char *ssh_sftp_get_cmdline(const char *prompt, bool no_fds_ok) buflen = bufsize = 0; while (1) { - ret = ssh_sftp_do_select(true, no_fds_ok); - if (ret < 0) { - printf("connection died\n"); + ret = ssh_sftp_do_select(true, no_fds_ok); + if (ret < 0) { + printf("connection died\n"); sfree(buf); - return NULL; /* woop woop */ - } - if (ret > 0) { + return NULL; /* woop woop */ + } + if (ret > 0) { sgrowarray(buf, bufsize, buflen); - ret = read(0, buf+buflen, 1); - if (ret < 0) { - perror("read"); + ret = read(0, buf+buflen, 1); + if (ret < 0) { + perror("read"); sfree(buf); - return NULL; - } - if (ret == 0) { - /* eof on stdin; no error, but no answer either */ + return NULL; + } + if (ret == 0) { + /* eof on stdin; no error, but no answer either */ sfree(buf); - return NULL; - } + return NULL; + } - if (buf[buflen++] == '\n') { - /* we have a full line */ - return buf; - } - } + if (buf[buflen++] == '\n') { + /* we have a full line */ + return buf; + } + } } } diff --git a/unix/uxsignal.c b/unix/uxsignal.c index 8edbfacd..d75cce43 100644 --- a/unix/uxsignal.c +++ b/unix/uxsignal.c @@ -17,13 +17,13 @@ void (*putty_signal(int sig, void (*func)(int)))(int) { struct sigaction sa; struct sigaction old; - + sa.sa_handler = func; if(sigemptyset(&sa.sa_mask) < 0) - return SIG_ERR; + return SIG_ERR; sa.sa_flags = SA_RESTART; if(sigaction(sig, &sa, &old) < 0) - return SIG_ERR; + return SIG_ERR; return old.sa_handler; } @@ -34,8 +34,8 @@ void block_signal(int sig, bool block_it) sigemptyset(&ss); sigaddset(&ss, sig); if(sigprocmask(block_it ? SIG_BLOCK : SIG_UNBLOCK, &ss, 0) < 0) { - perror("sigprocmask"); - exit(1); + perror("sigprocmask"); + exit(1); } } diff --git a/unix/uxstore.c b/unix/uxstore.c index 756b10c5..250db9a8 100644 --- a/unix/uxstore.c +++ b/unix/uxstore.c @@ -46,35 +46,35 @@ static void make_session_filename(const char *in, strbuf *out) * opt-in for safe characters rather than opt-out for * specific unsafe ones... */ - if (*in!='+' && *in!='-' && *in!='.' && *in!='@' && *in!='_' && + if (*in!='+' && *in!='-' && *in!='.' && *in!='@' && *in!='_' && !(*in >= '0' && *in <= '9') && !(*in >= 'A' && *in <= 'Z') && !(*in >= 'a' && *in <= 'z')) { - put_byte(out, '%'); - put_byte(out, hex[((unsigned char) *in) >> 4]); - put_byte(out, hex[((unsigned char) *in) & 15]); - } else - put_byte(out, *in); - in++; + put_byte(out, '%'); + put_byte(out, hex[((unsigned char) *in) >> 4]); + put_byte(out, hex[((unsigned char) *in) & 15]); + } else + put_byte(out, *in); + in++; } } static void decode_session_filename(const char *in, strbuf *out) { while (*in) { - if (*in == '%' && in[1] && in[2]) { - int i, j; + 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); - put_byte(out, (i << 4) + j); - in += 3; - } else { - put_byte(out, *in++); - } + put_byte(out, (i << 4) + j); + in += 3; + } else { + put_byte(out, *in++); + } } } @@ -87,15 +87,15 @@ static char *make_filename(int index, const char *subname) * specific subparts of it, by means of environment variables. */ if (index == INDEX_DIR) { - struct passwd *pwd; + struct passwd *pwd; char *xdg_dir, *old_dir, *old_dir2, *old_dir3, *home, *pwd_home; - env = getenv("PUTTYDIR"); - if (env) - return dupstr(env); + env = getenv("PUTTYDIR"); + if (env) + return dupstr(env); home = getenv("HOME"); - pwd = getpwuid(getuid()); + pwd = getpwuid(getuid()); if (pwd && pwd->pw_dir) { pwd_home = pwd->pw_dir; } else { @@ -162,45 +162,45 @@ static char *make_filename(int index, const char *subname) return ret; } if (index == INDEX_SESSIONDIR) { - env = getenv("PUTTYSESSIONS"); - if (env) - return dupstr(env); - tmp = make_filename(INDEX_DIR, NULL); - ret = dupprintf("%s/sessions", tmp); - sfree(tmp); - return ret; + env = getenv("PUTTYSESSIONS"); + if (env) + return dupstr(env); + tmp = make_filename(INDEX_DIR, NULL); + ret = dupprintf("%s/sessions", tmp); + sfree(tmp); + return ret; } if (index == INDEX_SESSION) { strbuf *sb = strbuf_new(); - tmp = make_filename(INDEX_SESSIONDIR, NULL); - strbuf_catf(sb, "%s/", tmp); - sfree(tmp); + tmp = make_filename(INDEX_SESSIONDIR, NULL); + strbuf_catf(sb, "%s/", tmp); + sfree(tmp); make_session_filename(subname, sb); return strbuf_to_str(sb); } if (index == INDEX_HOSTKEYS) { - env = getenv("PUTTYSSHHOSTKEYS"); - if (env) - return dupstr(env); - tmp = make_filename(INDEX_DIR, NULL); - ret = dupprintf("%s/sshhostkeys", tmp); - sfree(tmp); - return ret; + env = getenv("PUTTYSSHHOSTKEYS"); + if (env) + return dupstr(env); + tmp = make_filename(INDEX_DIR, NULL); + ret = dupprintf("%s/sshhostkeys", tmp); + sfree(tmp); + return ret; } if (index == INDEX_HOSTKEYS_TMP) { - tmp = make_filename(INDEX_HOSTKEYS, NULL); - ret = dupprintf("%s.tmp", tmp); - sfree(tmp); - return ret; + tmp = make_filename(INDEX_HOSTKEYS, NULL); + ret = dupprintf("%s.tmp", tmp); + sfree(tmp); + return ret; } if (index == INDEX_RANDSEED) { - env = getenv("PUTTYRANDOMSEED"); - if (env) - return dupstr(env); - tmp = make_filename(INDEX_DIR, NULL); - ret = dupprintf("%s/randomseed", tmp); - sfree(tmp); - return ret; + env = getenv("PUTTYRANDOMSEED"); + if (env) + return dupstr(env); + tmp = make_filename(INDEX_DIR, NULL); + ret = dupprintf("%s/randomseed", tmp); + sfree(tmp); + return ret; } tmp = make_filename(INDEX_DIR, NULL); ret = dupprintf("%s/ERROR", tmp); @@ -246,8 +246,8 @@ settings_w *open_settings_w(const char *sessionname, char **errmsg) if (!fp) { *errmsg = dupprintf("Unable to save session: open(\"%s\") " "returned '%s'", filename, strerror(errno)); - sfree(filename); - return NULL; /* can't open */ + sfree(filename); + return NULL; /* can't open */ } sfree(filename); @@ -309,30 +309,30 @@ void provide_xrm_string(const char *string, const char *progname) p = q = strchr(string, ':'); if (!q) { - fprintf(stderr, "%s: expected a colon in resource string" - " \"%s\"\n", progname, string); - return; + fprintf(stderr, "%s: expected a colon in resource string" + " \"%s\"\n", progname, string); + return; } q++; while (p > string && p[-1] != '.' && p[-1] != '*') - p--; + p--; xrms = snew(struct skeyval); key = snewn(q-p, char); memcpy(key, p, q-p); key[q-p-1] = '\0'; xrms->key = key; while (*q && isspace((unsigned char)*q)) - q++; + q++; xrms->value = dupstr(q); if (!xrmtree) - xrmtree = newtree234(keycmp); + xrmtree = newtree234(keycmp); ret = add234(xrmtree, xrms); if (ret) { - /* Override an existing string. */ - del234(xrmtree, ret); - add234(xrmtree, xrms); + /* Override an existing string. */ + del234(xrmtree, ret); + add234(xrmtree, xrms); } } @@ -341,9 +341,9 @@ static const char *get_setting(const char *key) struct skeyval tmp, *ret; tmp.key = key; if (xrmtree) { - ret = find234(xrmtree, &tmp, NULL); - if (ret) - return ret->value; + ret = find234(xrmtree, &tmp, NULL); + if (ret) + return ret->value; } return x_get_default(key); } @@ -368,7 +368,7 @@ settings_r *open_settings_r(const char *sessionname) fp = fopen(filename, "r"); sfree(filename); if (!fp) - return NULL; /* can't open */ + return NULL; /* can't open */ toret = snew(settings_r); toret->t = newtree234(keycmp); @@ -411,9 +411,9 @@ char *read_setting_s(settings_r *handle, const char *key) val = get_setting(key); if (!val) - return NULL; + return NULL; else - return dupstr(val); + return dupstr(val); } int read_setting_i(settings_r *handle, const char *key, int defvalue) @@ -430,9 +430,9 @@ int read_setting_i(settings_r *handle, const char *key, int defvalue) val = get_setting(key); if (!val) - return defvalue; + return defvalue; else - return atoi(val); + return atoi(val); } FontSpec *read_setting_fontspec(settings_r *handle, const char *name) @@ -441,7 +441,7 @@ FontSpec *read_setting_fontspec(settings_r *handle, const char *name) * In GTK1-only PuTTY, we used to store font names simply as a * valid X font description string (logical or alias), under a * bare key such as "Font". - * + * * In GTK2 PuTTY, we have a prefix system where "client:" * indicates a Pango font and "server:" an X one; existing * configuration needs to be reinterpreted as having the @@ -454,9 +454,9 @@ FontSpec *read_setting_fontspec(settings_r *handle, const char *name) if ((tmp = read_setting_s(handle, suffname)) != NULL) { FontSpec *fs = fontspec_new(tmp); - sfree(suffname); - sfree(tmp); - return fs; /* got new-style name */ + sfree(suffname); + sfree(tmp); + return fs; /* got new-style name */ } sfree(suffname); @@ -465,12 +465,12 @@ FontSpec *read_setting_fontspec(settings_r *handle, const char *name) if (tmp && *tmp) { char *tmp2 = dupcat("server:", tmp, NULL); FontSpec *fs = fontspec_new(tmp2); - sfree(tmp2); - sfree(tmp); - return fs; + sfree(tmp2); + sfree(tmp); + return fs; } else { - sfree(tmp); - return NULL; + sfree(tmp); + return NULL; } } Filename *read_setting_filename(settings_r *handle, const char *name) @@ -478,10 +478,10 @@ Filename *read_setting_filename(settings_r *handle, const char *name) char *tmp = read_setting_s(handle, name); if (tmp) { Filename *ret = filename_from_str(tmp); - sfree(tmp); - return ret; + sfree(tmp); + return ret; } else - return NULL; + return NULL; } void write_setting_fontspec(settings_w *handle, const char *name, FontSpec *fs) @@ -565,13 +565,13 @@ bool enum_settings_next(settings_e *handle, strbuf *out) while ( (de = readdir(handle->dp)) != NULL ) { fullpath->len = baselen; - put_datapl(fullpath, ptrlen_from_asciz(de->d_name)); + put_datapl(fullpath, ptrlen_from_asciz(de->d_name)); if (stat(fullpath->s, &st) < 0 || !S_ISREG(st.st_mode)) continue; /* try another one */ decode_session_filename(de->d_name, out); - strbuf_free(fullpath); + strbuf_free(fullpath); return true; } @@ -588,15 +588,15 @@ void enum_settings_finish(settings_e *handle) /* * Lines in the host keys file are of the form - * + * * type@port:hostname keydata - * + * * e.g. - * + * * rsa@22:foovax.example.org 0x23,0x293487364395345345....2343 */ int verify_host_key(const char *hostname, int port, - const char *keytype, const char *key) + const char *keytype, const char *key) { FILE *fp; char *filename; @@ -607,57 +607,57 @@ int verify_host_key(const char *hostname, int port, fp = fopen(filename, "r"); sfree(filename); if (!fp) - return 1; /* key does not exist */ + return 1; /* key does not exist */ ret = 1; while ( (line = fgetline(fp)) ) { - int i; - char *p = line; - char porttext[20]; + int i; + char *p = line; + char porttext[20]; - line[strcspn(line, "\n")] = '\0'; /* strip trailing newline */ + line[strcspn(line, "\n")] = '\0'; /* strip trailing newline */ - i = strlen(keytype); - if (strncmp(p, keytype, i)) - goto done; - p += i; + i = strlen(keytype); + if (strncmp(p, keytype, i)) + goto done; + p += i; - if (*p != '@') - goto done; - p++; + if (*p != '@') + goto done; + p++; - sprintf(porttext, "%d", port); - i = strlen(porttext); - if (strncmp(p, porttext, i)) - goto done; - p += i; + sprintf(porttext, "%d", port); + i = strlen(porttext); + if (strncmp(p, porttext, i)) + goto done; + p += i; - if (*p != ':') - goto done; - p++; + if (*p != ':') + goto done; + p++; - i = strlen(hostname); - if (strncmp(p, hostname, i)) - goto done; - p += i; + i = strlen(hostname); + if (strncmp(p, hostname, i)) + goto done; + p += i; - if (*p != ' ') - goto done; - p++; + if (*p != ' ') + goto done; + p++; - /* - * Found the key. Now just work out whether it's the right - * one or not. - */ - if (!strcmp(p, key)) - ret = 0; /* key matched OK */ - else - ret = 2; /* key mismatch */ + /* + * Found the key. Now just work out whether it's the right + * one or not. + */ + if (!strcmp(p, key)) + ret = 0; /* key matched OK */ + else + ret = 2; /* key mismatch */ - done: - sfree(line); - if (ret != 1) - break; + done: + sfree(line); + if (ret != 1) + break; } fclose(fp); @@ -675,7 +675,7 @@ bool have_ssh_host_key(const char *hostname, int port, } void store_host_key(const char *hostname, int port, - const char *keytype, const char *key) + const char *keytype, const char *key) { FILE *rfp, *wfp; char *newtext, *line; @@ -698,7 +698,7 @@ void store_host_key(const char *hostname, int port, sfree(tmpfilename); return; } - sfree(dir); + sfree(dir); wfp = fopen(tmpfilename, "w"); } @@ -754,11 +754,11 @@ void read_random_seed(noise_consumer_t consumer) fd = open(fname, O_RDONLY); sfree(fname); if (fd >= 0) { - char buf[512]; - int ret; - while ( (ret = read(fd, buf, sizeof(buf))) > 0) - consumer(buf, ret); - close(fd); + char buf[512]; + int ret; + while ( (ret = read(fd, buf, sizeof(buf))) > 0) + consumer(buf, ret); + close(fd); } } @@ -783,7 +783,7 @@ void write_random_seed(void *data, int len) } char *dir, *errmsg; - dir = make_filename(INDEX_DIR, NULL); + dir = make_filename(INDEX_DIR, NULL); if ((errmsg = make_dir_path(dir, 0700)) != NULL) { nonfatal("Unable to write random seed: %s", errmsg); sfree(errmsg); @@ -791,9 +791,9 @@ void write_random_seed(void *data, int len) sfree(dir); return; } - sfree(dir); + sfree(dir); - fd = open(fname, O_CREAT | O_WRONLY, 0600); + fd = open(fname, O_CREAT | O_WRONLY, 0600); if (fd < 0) { nonfatal("Unable to write random seed: open(\"%s\") " "returned '%s'", fname, strerror(errno)); @@ -803,14 +803,14 @@ void write_random_seed(void *data, int len) } while (len > 0) { - int ret = write(fd, data, len); - if (ret < 0) { + int ret = write(fd, data, len); + if (ret < 0) { nonfatal("Unable to write random seed: write " "returned '%s'", strerror(errno)); break; } - len -= ret; - data = (char *)data + len; + len -= ret; + data = (char *)data + len; } close(fd); diff --git a/unix/uxucs.c b/unix/uxucs.c index 3a34a969..a3d6f5ba 100644 --- a/unix/uxucs.c +++ b/unix/uxucs.c @@ -22,76 +22,76 @@ bool is_dbcs_leadbyte(int codepage, char byte) } int mb_to_wc(int codepage, int flags, const char *mbstr, int mblen, - wchar_t *wcstr, int wclen) + wchar_t *wcstr, int wclen) { if (codepage == DEFAULT_CODEPAGE) { - int n = 0; - mbstate_t state; + int n = 0; + mbstate_t state; - memset(&state, 0, sizeof state); + memset(&state, 0, sizeof state); - while (mblen > 0) { - size_t i = mbrtowc(wcstr+n, mbstr, (size_t)mblen, &state); - if (i == (size_t)-1 || i == (size_t)-2) - break; - n++; - mbstr += i; - mblen -= i; - } + while (mblen > 0) { + size_t i = mbrtowc(wcstr+n, mbstr, (size_t)mblen, &state); + if (i == (size_t)-1 || i == (size_t)-2) + break; + n++; + mbstr += i; + mblen -= i; + } - return n; + return n; } else if (codepage == CS_NONE) { - int n = 0; + int n = 0; - while (mblen > 0) { - wcstr[n] = 0xD800 | (mbstr[0] & 0xFF); - n++; - mbstr++; - mblen--; - } + while (mblen > 0) { + wcstr[n] = 0xD800 | (mbstr[0] & 0xFF); + n++; + mbstr++; + mblen--; + } - return n; + return n; } else - return charset_to_unicode(&mbstr, &mblen, wcstr, wclen, codepage, - NULL, NULL, 0); + return charset_to_unicode(&mbstr, &mblen, wcstr, wclen, codepage, + NULL, NULL, 0); } int wc_to_mb(int codepage, int flags, const wchar_t *wcstr, int wclen, - char *mbstr, int mblen, const char *defchr, - struct unicode_data *ucsdata) + char *mbstr, int mblen, const char *defchr, + struct unicode_data *ucsdata) { if (codepage == DEFAULT_CODEPAGE) { - char output[MB_LEN_MAX]; - mbstate_t state; - int n = 0; + char output[MB_LEN_MAX]; + mbstate_t state; + int n = 0; - memset(&state, 0, sizeof state); + memset(&state, 0, sizeof state); - while (wclen > 0) { - int i = wcrtomb(output, wcstr[0], &state); - if (i == (size_t)-1 || i > n - mblen) - break; - memcpy(mbstr+n, output, i); - n += i; - wcstr++; - wclen--; - } + while (wclen > 0) { + int i = wcrtomb(output, wcstr[0], &state); + if (i == (size_t)-1 || i > n - mblen) + break; + memcpy(mbstr+n, output, i); + n += i; + wcstr++; + wclen--; + } - return n; + return n; } else if (codepage == CS_NONE) { - int n = 0; - while (wclen > 0 && n < mblen) { - if (*wcstr >= 0xD800 && *wcstr < 0xD900) - mbstr[n++] = (*wcstr & 0xFF); - else if (defchr) - mbstr[n++] = *defchr; - wcstr++; - wclen--; - } - return n; + int n = 0; + while (wclen > 0 && n < mblen) { + if (*wcstr >= 0xD800 && *wcstr < 0xD900) + mbstr[n++] = (*wcstr & 0xFF); + else if (defchr) + mbstr[n++] = *defchr; + wcstr++; + wclen--; + } + return n; } else { - return charset_from_unicode(&wcstr, &wclen, mbstr, mblen, codepage, - NULL, defchr?defchr:NULL, defchr?1:0); + return charset_from_unicode(&wcstr, &wclen, mbstr, mblen, codepage, + NULL, defchr?defchr:NULL, defchr?1:0); } } @@ -119,13 +119,13 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, */ ucsdata->line_codepage = CS_NONE; if (utf8_override) { - const char *s; - if (((s = getenv("LC_ALL")) && *s) || - ((s = getenv("LC_CTYPE")) && *s) || - ((s = getenv("LANG")) && *s)) { - if (strstr(s, "UTF-8")) - ucsdata->line_codepage = CS_UTF8; - } + const char *s; + if (((s = getenv("LC_ALL")) && *s) || + ((s = getenv("LC_CTYPE")) && *s) || + ((s = getenv("LANG")) && *s)) { + if (strstr(s, "UTF-8")) + ucsdata->line_codepage = CS_UTF8; + } } /* @@ -133,7 +133,7 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, * specification in conf. */ if (ucsdata->line_codepage == CS_NONE) - ucsdata->line_codepage = decode_codepage(linecharset); + ucsdata->line_codepage = decode_codepage(linecharset); /* * If line_codepage is _still_ CS_NONE, we assume we're using @@ -143,64 +143,64 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, * fall back to using the D800 page. */ if (ucsdata->line_codepage == CS_NONE) - ucsdata->line_codepage = font_charset; + ucsdata->line_codepage = font_charset; if (ucsdata->line_codepage == CS_NONE) - ret = true; + ret = true; /* * Set up unitab_line, by translating each individual character * in the line codepage into Unicode. */ for (i = 0; i < 256; i++) { - char c[1]; + char c[1]; const char *p; - wchar_t wc[1]; - int len; - c[0] = i; - p = c; - len = 1; - if (ucsdata->line_codepage == CS_NONE) - ucsdata->unitab_line[i] = 0xD800 | i; - else if (1 == charset_to_unicode(&p, &len, wc, 1, - ucsdata->line_codepage, - NULL, L"", 0)) - ucsdata->unitab_line[i] = wc[0]; - else - ucsdata->unitab_line[i] = 0xFFFD; + wchar_t wc[1]; + int len; + c[0] = i; + p = c; + len = 1; + if (ucsdata->line_codepage == CS_NONE) + ucsdata->unitab_line[i] = 0xD800 | i; + else if (1 == charset_to_unicode(&p, &len, wc, 1, + ucsdata->line_codepage, + NULL, L"", 0)) + ucsdata->unitab_line[i] = wc[0]; + else + ucsdata->unitab_line[i] = 0xFFFD; } /* * Set up unitab_xterm. This is the same as unitab_line except * in the line-drawing regions, where it follows the Unicode * encoding. - * + * * (Note that the strange X encoding of line-drawing characters * in the bottom 32 glyphs of ISO8859-1 fonts is taken care of * by the font encoding, which will spot such a font and act as * if it were in a variant encoding of ISO8859-1.) */ for (i = 0; i < 256; i++) { - static const wchar_t unitab_xterm_std[32] = { - 0x2666, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, - 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, - 0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, - 0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x0020 - }; - static const wchar_t unitab_xterm_poorman[32] = - L"*#****o~**+++++-----++++|****L. "; + static const wchar_t unitab_xterm_std[32] = { + 0x2666, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, + 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, + 0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, + 0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x0020 + }; + static const wchar_t unitab_xterm_poorman[32] = + L"*#****o~**+++++-----++++|****L. "; - const wchar_t *ptr; + const wchar_t *ptr; - if (vtmode == VT_POORMAN) - ptr = unitab_xterm_poorman; - else - ptr = unitab_xterm_std; + if (vtmode == VT_POORMAN) + ptr = unitab_xterm_poorman; + else + ptr = unitab_xterm_std; - if (i >= 0x5F && i < 0x7F) - ucsdata->unitab_xterm[i] = ptr[i & 0x1F]; - else - ucsdata->unitab_xterm[i] = ucsdata->unitab_line[i]; + if (i >= 0x5F && i < 0x7F) + ucsdata->unitab_xterm[i] = ptr[i & 0x1F]; + else + ucsdata->unitab_xterm[i] = ucsdata->unitab_line[i]; } /* @@ -208,17 +208,17 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, * simply CP437. */ for (i = 0; i < 256; i++) { - char c[1]; + char c[1]; const char *p; - wchar_t wc[1]; - int len; - c[0] = i; - p = c; - len = 1; - if (1 == charset_to_unicode(&p, &len, wc, 1, CS_CP437, NULL, L"", 0)) - ucsdata->unitab_scoacs[i] = wc[0]; - else - ucsdata->unitab_scoacs[i] = 0xFFFD; + wchar_t wc[1]; + int len; + c[0] = i; + p = c; + len = 1; + if (1 == charset_to_unicode(&p, &len, wc, 1, CS_CP437, NULL, L"", 0)) + ucsdata->unitab_scoacs[i] = wc[0]; + else + ucsdata->unitab_scoacs[i] = 0xFFFD; } /* @@ -229,12 +229,12 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, * used in this way will be IBM or MS code pages anyway.) */ for (i = 0; i < 256; i++) { - int lineval = ucsdata->unitab_line[i]; - if (lineval < ' ' || (lineval >= 0x7F && lineval < 0xA0) || - (lineval >= 0xD800 && lineval < 0xD820) || (lineval == 0xD87F)) - ucsdata->unitab_ctrl[i] = i; - else - ucsdata->unitab_ctrl[i] = 0xFF; + int lineval = ucsdata->unitab_line[i]; + if (lineval < ' ' || (lineval >= 0x7F && lineval < 0xA0) || + (lineval >= 0xD800 && lineval < 0xD820) || (lineval == 0xD87F)) + ucsdata->unitab_ctrl[i] = i; + else + ucsdata->unitab_ctrl[i] = 0xFF; } return ret; @@ -243,7 +243,7 @@ bool init_ucs(struct unicode_data *ucsdata, char *linecharset, const char *cp_name(int codepage) { if (codepage == CS_NONE) - return "Use font encoding"; + return "Use font encoding"; return charset_to_localenc(codepage); } @@ -255,7 +255,7 @@ const char *cp_enumerate(int index) /* "Use font encoding" comes after all the named charsets */ if (charset_localenc_nth(index-1) != CS_NONE) return "Use font encoding"; - return NULL; + return NULL; } return charset_to_localenc(charset); } @@ -263,6 +263,6 @@ const char *cp_enumerate(int index) int decode_codepage(char *cp_name) { if (!cp_name || !*cp_name) - return CS_UTF8; + return CS_UTF8; return charset_from_localenc(cp_name); } diff --git a/unix/xkeysym.c b/unix/xkeysym.c index 45f6a0cb..aa9f9539 100644 --- a/unix/xkeysym.c +++ b/unix/xkeysym.c @@ -1,6 +1,6 @@ /* * xkeysym.c: mapping from X keysyms to Unicode values - * + * * The basic idea of this is shamelessly cribbed from xterm. The * actual character data is generated from Markus Kuhn's proposed * redraft of the X11 keysym mapping table, using the following @@ -999,13 +999,13 @@ int keysym_to_unicode(int keysym) j = lenof(keysyms); while (j - i >= 2) { - k = (j + i) / 2; - if (keysyms[k].keysym == keysym) - return keysyms[k].unicode; - else if (keysyms[k].keysym < keysym) - i = k; - else - j = k; + k = (j + i) / 2; + if (keysyms[k].keysym == keysym) + return keysyms[k].unicode; + else if (keysyms[k].keysym < keysym) + i = k; + else + j = k; } return -1; } diff --git a/utils.c b/utils.c index 9824110e..18193960 100644 --- a/utils.c +++ b/utils.c @@ -32,21 +32,21 @@ unsigned long parse_blocksize(const char *bs) char *suf; unsigned long r = strtoul(bs, &suf, 10); if (*suf != '\0') { - while (*suf && isspace((unsigned char)*suf)) suf++; - switch (*suf) { - case 'k': case 'K': - r *= 1024ul; - break; - case 'm': case 'M': - r *= 1024ul * 1024ul; - break; - case 'g': case 'G': - r *= 1024ul * 1024ul * 1024ul; - break; - case '\0': - default: - break; - } + while (*suf && isspace((unsigned char)*suf)) suf++; + switch (*suf) { + case 'k': case 'K': + r *= 1024ul; + break; + case 'm': case 'M': + r *= 1024ul * 1024ul; + break; + case 'g': case 'G': + r *= 1024ul * 1024ul * 1024ul; + break; + case '\0': + default: + break; + } } return r; } @@ -58,39 +58,39 @@ unsigned long parse_blocksize(const char *bs) * The precise current parsing is an oddity inherited from the terminal * answerback-string parsing code. All sequences start with ^; all except * ^<123> are two characters. The ones that are worth keeping are probably: - * ^? 127 - * ^@A-Z[\]^_ 0-31 - * a-z 1-26 - * specified by number (decimal, 0octal, 0xHEX) - * ~ ^ escape + * ^? 127 + * ^@A-Z[\]^_ 0-31 + * a-z 1-26 + * specified by number (decimal, 0octal, 0xHEX) + * ~ ^ escape */ char ctrlparse(char *s, char **next) { char c = 0; if (*s != '^') { - *next = NULL; + *next = NULL; } else { - s++; - if (*s == '\0') { - *next = NULL; - } else if (*s == '<') { - s++; - c = (char)strtol(s, next, 0); - if ((*next == s) || (**next != '>')) { - c = 0; - *next = NULL; - } else - (*next)++; - } else if (*s >= 'a' && *s <= 'z') { - c = (*s - ('a' - 1)); - *next = s+1; - } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) { - c = ('@' ^ *s); - *next = s+1; - } else if (*s == '~') { - c = '^'; - *next = s+1; - } + s++; + if (*s == '\0') { + *next = NULL; + } else if (*s == '<') { + s++; + c = (char)strtol(s, next, 0); + if ((*next == s) || (**next != '>')) { + c = 0; + *next = NULL; + } else + (*next)++; + } else if (*s >= 'a' && *s <= 'z') { + c = (*s - ('a' - 1)); + *next = s+1; + } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) { + c = ('@' ^ *s); + *next = s+1; + } else if (*s == '~') { + c = '^'; + *next = s+1; + } } return c; } @@ -258,10 +258,10 @@ char *dupcat(const char *s1, ...) len = strlen(s1); va_start(ap, s1); while (1) { - sn = va_arg(ap, char *); - if (!sn) - break; - len += strlen(sn); + sn = va_arg(ap, char *); + if (!sn) + break; + len += strlen(sn); } va_end(ap); @@ -271,11 +271,11 @@ char *dupcat(const char *s1, ...) va_start(ap, s1); while (1) { - sn = va_arg(ap, char *); - if (!sn) - break; - strcpy(q, sn); - q += strlen(q); + sn = va_arg(ap, char *); + if (!sn) + break; + strcpy(q, sn); + q += strlen(q); } va_end(ap); @@ -317,21 +317,21 @@ int string_length_for_printf(size_t s) /* * Do an sprintf(), but into a custom-allocated buffer. - * + * * Currently I'm doing this via vsnprintf. This has worked so far, * but it's not good, because vsnprintf is not available on all * platforms. There's an ifdef to use `_vsnprintf', which seems * to be the local name for it on Windows. Other platforms may * lack it completely, in which case it'll be time to rewrite * this function in a totally different way. - * + * * The only `properly' portable solution I can think of is to * implement my own format string scanner, which figures out an * upper bound for the length of each formatting directive, * allocates the buffer as it goes along, and calls sprintf() to * actually process each directive. If I ever need to actually do * this, some caveats: - * + * * - It's very hard to find a reliable upper bound for * floating-point values. %f, in particular, when supplied with * a number near to the upper or lower limit of representable @@ -340,10 +340,10 @@ int string_length_for_printf(size_t s) * constants in , or even to predict it dynamically by * looking at the exponent of the specific float provided, but * it won't be fun. - * + * * - Don't forget to _check_, after calling sprintf, that it's * used at most the amount of space we had available. - * + * * - Fault any formatting directive we don't fully understand. The * aim here is to _guarantee_ that we never overflow the buffer, * because this is a security-critical function. If we see a @@ -357,25 +357,25 @@ static char *dupvprintf_inner(char *buf, size_t oldlen, size_t *sizeptr, sgrowarrayn_nm(buf, size, oldlen, 512); while (1) { - va_list aq; - va_copy(aq, ap); - int len = vsnprintf(buf + oldlen, size - oldlen, fmt, aq); - va_end(aq); + va_list aq; + va_copy(aq, ap); + int len = vsnprintf(buf + oldlen, size - oldlen, fmt, aq); + va_end(aq); - if (len >= 0 && len < size) { - /* This is the C99-specified criterion for snprintf to have - * been completely successful. */ + if (len >= 0 && len < size) { + /* This is the C99-specified criterion for snprintf to have + * been completely successful. */ *sizeptr = size; - return buf; - } else if (len > 0) { - /* This is the C99 error condition: the returned length is - * the required buffer size not counting the NUL. */ - sgrowarrayn_nm(buf, size, oldlen + 1, len); - } else { - /* This is the pre-C99 glibc error condition: <0 means the - * buffer wasn't big enough, so we enlarge it a bit and hope. */ - sgrowarray_nm(buf, size, size); - } + return buf; + } else if (len > 0) { + /* This is the C99 error condition: the returned length is + * the required buffer size not counting the NUL. */ + sgrowarrayn_nm(buf, size, oldlen + 1, len); + } else { + /* This is the pre-C99 glibc error condition: <0 means the + * buffer wasn't big enough, so we enlarge it a bit and hope. */ + sgrowarray_nm(buf, size, size); + } } } @@ -491,14 +491,14 @@ char *fgetline(FILE *fp) char *ret = snewn(512, char); size_t size = 512, len = 0; while (fgets(ret + len, size - len, fp)) { - len += strlen(ret + len); - if (len > 0 && ret[len-1] == '\n') - break; /* got a newline, we're done */ + len += strlen(ret + len); + if (len > 0 && ret[len-1] == '\n') + break; /* got a newline, we're done */ sgrowarrayn_nm(ret, size, len, 512); } - if (len == 0) { /* first fgets returned NULL */ - sfree(ret); - return NULL; + if (len == 0) { /* first fgets returned NULL */ + sfree(ret); + return NULL; } ret[len] = '\0'; return ret; @@ -543,25 +543,25 @@ char *chomp(char *str) void base64_encode_atom(const unsigned char *data, int n, char *out) { static const char base64_chars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; unsigned word; word = data[0] << 16; if (n > 1) - word |= data[1] << 8; + word |= data[1] << 8; if (n > 2) - word |= data[2]; + word |= data[2]; out[0] = base64_chars[(word >> 18) & 0x3F]; out[1] = base64_chars[(word >> 12) & 0x3F]; if (n > 1) - out[2] = base64_chars[(word >> 6) & 0x3F]; + out[2] = base64_chars[(word >> 6) & 0x3F]; else - out[2] = '='; + out[2] = '='; if (n > 2) - out[3] = base64_chars[word & 0x3F]; + out[3] = base64_chars[word & 0x3F]; else - out[3] = '='; + out[3] = '='; } int base64_decode_atom(const char *atom, unsigned char *out) @@ -572,50 +572,50 @@ int base64_decode_atom(const char *atom, unsigned char *out) char c; for (i = 0; i < 4; i++) { - c = atom[i]; - if (c >= 'A' && c <= 'Z') - v = c - 'A'; - else if (c >= 'a' && c <= 'z') - v = c - 'a' + 26; - else if (c >= '0' && c <= '9') - v = c - '0' + 52; - else if (c == '+') - v = 62; - else if (c == '/') - v = 63; - else if (c == '=') - v = -1; - else - return 0; /* invalid atom */ - vals[i] = v; + c = atom[i]; + if (c >= 'A' && c <= 'Z') + v = c - 'A'; + else if (c >= 'a' && c <= 'z') + v = c - 'a' + 26; + else if (c >= '0' && c <= '9') + v = c - '0' + 52; + else if (c == '+') + v = 62; + else if (c == '/') + v = 63; + else if (c == '=') + v = -1; + else + return 0; /* invalid atom */ + vals[i] = v; } if (vals[0] == -1 || vals[1] == -1) - return 0; + return 0; if (vals[2] == -1 && vals[3] != -1) - return 0; + return 0; if (vals[3] != -1) - len = 3; + len = 3; else if (vals[2] != -1) - len = 2; + len = 2; else - len = 1; + 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; + out[1] = (word >> 8) & 0xFF; if (len > 2) - out[2] = word & 0xFF; + out[2] = word & 0xFF; return len; } /* ---------------------------------------------------------------------- * Generic routines to deal with send buffers: a linked list of * smallish blocks, with the operations - * + * * - add an arbitrary amount of data to the end of the list * - remove the first N bytes from the list * - return a (pointer,length) pair giving some initial data in @@ -649,10 +649,10 @@ void bufchain_clear(bufchain *ch) { struct bufchain_granule *b; while (ch->head) { - b = ch->head; - ch->head = ch->head->next; + b = ch->head; + ch->head = ch->head->next; smemclr(b, sizeof(*b)); - sfree(b); + sfree(b); } ch->tail = NULL; ch->buffersize = 0; @@ -680,28 +680,28 @@ void bufchain_add(bufchain *ch, const void *data, size_t len) ch->buffersize += len; while (len > 0) { - if (ch->tail && ch->tail->bufend < ch->tail->bufmax) { - size_t copylen = min(len, ch->tail->bufmax - ch->tail->bufend); - memcpy(ch->tail->bufend, buf, copylen); - buf += copylen; - len -= copylen; - ch->tail->bufend += copylen; - } - if (len > 0) { - size_t grainlen = - max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE); - struct bufchain_granule *newbuf; - newbuf = smalloc(grainlen); - newbuf->bufpos = newbuf->bufend = - (char *)newbuf + sizeof(struct bufchain_granule); - newbuf->bufmax = (char *)newbuf + grainlen; - newbuf->next = NULL; - if (ch->tail) - ch->tail->next = newbuf; - else - ch->head = newbuf; - ch->tail = newbuf; - } + if (ch->tail && ch->tail->bufend < ch->tail->bufmax) { + size_t copylen = min(len, ch->tail->bufmax - ch->tail->bufend); + memcpy(ch->tail->bufend, buf, copylen); + buf += copylen; + len -= copylen; + ch->tail->bufend += copylen; + } + if (len > 0) { + size_t grainlen = + max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE); + struct bufchain_granule *newbuf; + newbuf = smalloc(grainlen); + newbuf->bufpos = newbuf->bufend = + (char *)newbuf + sizeof(struct bufchain_granule); + newbuf->bufmax = (char *)newbuf + grainlen; + newbuf->next = NULL; + if (ch->tail) + ch->tail->next = newbuf; + else + ch->head = newbuf; + ch->tail = newbuf; + } } if (ch->ic) @@ -714,20 +714,20 @@ void bufchain_consume(bufchain *ch, size_t len) assert(ch->buffersize >= len); while (len > 0) { - int remlen = len; - assert(ch->head != NULL); - if (remlen >= ch->head->bufend - ch->head->bufpos) { - remlen = ch->head->bufend - ch->head->bufpos; - tmp = ch->head; - ch->head = tmp->next; - if (!ch->head) - ch->tail = NULL; + int remlen = len; + assert(ch->head != NULL); + if (remlen >= ch->head->bufend - ch->head->bufpos) { + remlen = ch->head->bufend - ch->head->bufpos; + tmp = ch->head; + ch->head = tmp->next; + if (!ch->head) + ch->tail = NULL; smemclr(tmp, sizeof(*tmp)); - sfree(tmp); - } else - ch->head->bufpos += remlen; - ch->buffersize -= remlen; - len -= remlen; + sfree(tmp); + } else + ch->head->bufpos += remlen; + ch->buffersize -= remlen; + len -= remlen; } } @@ -745,16 +745,16 @@ void bufchain_fetch(bufchain *ch, void *data, size_t len) assert(ch->buffersize >= len); while (len > 0) { - int remlen = len; + int remlen = len; - assert(tmp != NULL); - if (remlen >= tmp->bufend - tmp->bufpos) - remlen = tmp->bufend - tmp->bufpos; - memcpy(data_c, tmp->bufpos, remlen); + assert(tmp != NULL); + if (remlen >= tmp->bufend - tmp->bufpos) + remlen = tmp->bufend - tmp->bufpos; + memcpy(data_c, tmp->bufpos, remlen); - tmp = tmp->next; - len -= remlen; - data_c += remlen; + tmp = tmp->next; + len -= remlen; + data_c += remlen; } } @@ -808,36 +808,36 @@ void debug_memdump(const void *buf, int len, bool L) const unsigned char *p = buf; char foo[17]; if (L) { - int delta; - debug_printf("\t%d (0x%x) bytes:\n", len, len); - delta = 15 & (uintptr_t)p; - p -= delta; - len += delta; + int delta; + debug_printf("\t%d (0x%x) bytes:\n", len, len); + delta = 15 & (uintptr_t)p; + p -= delta; + len += delta; } for (; 0 < len; p += 16, len -= 16) { - dputs(" "); - if (L) - debug_printf("%p: ", p); - strcpy(foo, "................"); /* sixteen dots */ - for (i = 0; i < 16 && i < len; ++i) { - if (&p[i] < (unsigned char *) buf) { - dputs(" "); /* 3 spaces */ - foo[i] = ' '; - } else { - debug_printf("%c%02.2x", - &p[i] != (unsigned char *) buf - && i % 4 ? '.' : ' ', p[i] - ); - if (p[i] >= ' ' && p[i] <= '~') - foo[i] = (char) p[i]; - } - } - foo[i] = '\0'; - debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo); + dputs(" "); + if (L) + debug_printf("%p: ", p); + strcpy(foo, "................"); /* sixteen dots */ + for (i = 0; i < 16 && i < len; ++i) { + if (&p[i] < (unsigned char *) buf) { + dputs(" "); /* 3 spaces */ + foo[i] = ' '; + } else { + debug_printf("%c%02.2x", + &p[i] != (unsigned char *) buf + && i % 4 ? '.' : ' ', p[i] + ); + if (p[i] >= ' ' && p[i] <= '~') + foo[i] = (char) p[i]; + } + } + foo[i] = '\0'; + debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo); } } -#endif /* def DEBUG */ +#endif /* def DEBUG */ #ifndef PLATFORM_HAS_SMEMCLR /* diff --git a/wcwidth.c b/wcwidth.c index a6596aae..6de676a5 100644 --- a/wcwidth.c +++ b/wcwidth.c @@ -298,7 +298,7 @@ int mk_wcwidth(unsigned int ucs) /* binary search in table of non-spacing characters */ if (bisearch(ucs, combining, - sizeof(combining) / sizeof(struct interval) - 1)) + sizeof(combining) / sizeof(struct interval) - 1)) return 0; /* if we arrive here, ucs is not a combining or C0/C1 control character */ @@ -527,7 +527,7 @@ int mk_wcwidth_cjk(unsigned int ucs) /* binary search in table of non-spacing characters */ if (bisearch(ucs, ambiguous, - sizeof(ambiguous) / sizeof(struct interval) - 1)) + sizeof(ambiguous) / sizeof(struct interval) - 1)) return 2; return mk_wcwidth(ucs); diff --git a/wildcard.c b/wildcard.c index 9c560d0d..697feb9a 100644 --- a/wildcard.c +++ b/wildcard.c @@ -14,7 +14,7 @@ /* * Definition of wildcard syntax: - * + * * - * matches any sequence of characters, including zero. * - ? matches exactly one character which can be anything. * - [abc] matches exactly one character which is a, b or c. @@ -51,7 +51,7 @@ * absence of any other need for the NFA->DFA translation engine, * anything more than the simplest possible wildcard matcher is * vast code-size overkill. - * + * * Essentially, these wildcards are much simpler than regexps in * that they consist of a sequence of rigid fragments (? and [...] * can never match more or less than one character) separated by @@ -80,11 +80,11 @@ const char *wc_error(int value) value = abs(value); switch (value) { case WC_TRAILINGBACKSLASH: - return "'\' occurred at end of string (expected another character)"; + return "'\' occurred at end of string (expected another character)"; case WC_UNCLOSEDCLASS: - return "expected ']' to close character class"; + return "expected ']' to close character class"; case WC_INVALIDRANGE: - return "character range was not terminated (']' just after '-')"; + return "character range was not terminated (']' just after '-')"; } return "INTERNAL ERROR: unrecognised wildcard error number"; } @@ -109,93 +109,93 @@ static int wc_match_fragment(const char **fragment, const char **target, * the first (unescaped) *. */ while (*f && *f != '*' && t < target_end) { - /* - * Extract one character from t, and one character's worth - * of pattern from f, and step along both. Return 0 if they - * fail to match. - */ - if (*f == '\\') { - /* - * Backslash, which means f[1] is to be treated as a - * literal character no matter what it is. It may not - * be the end of the string. - */ - if (!f[1]) - return -WC_TRAILINGBACKSLASH; /* error */ - if (f[1] != *t) - return 0; /* failed to match */ - f += 2; - } else if (*f == '?') { - /* - * Question mark matches anything. - */ - f++; - } else if (*f == '[') { - bool invert = false; - bool matched = false; - /* - * Open bracket introduces a character class. - */ - f++; - if (*f == '^') { - invert = true; - f++; - } - while (*f != ']') { - if (*f == '\\') - f++; /* backslashes still work */ - if (!*f) - return -WC_UNCLOSEDCLASS; /* error again */ - if (f[1] == '-') { - int lower, upper, ourchr; - lower = (unsigned char) *f++; - f++; /* eat the minus */ - if (*f == ']') - return -WC_INVALIDRANGE; /* different error! */ - if (*f == '\\') - f++; /* backslashes _still_ work */ - if (!*f) - return -WC_UNCLOSEDCLASS; /* error again */ - upper = (unsigned char) *f++; - ourchr = (unsigned char) *t; - if (lower > upper) { - int t = lower; lower = upper; upper = t; - } - if (ourchr >= lower && ourchr <= upper) - matched = true; - } else { - matched |= (*t == *f++); - } - } - if (invert == matched) - return 0; /* failed to match character class */ - f++; /* eat the ] */ - } else { - /* - * Non-special character matches itself. - */ - if (*f != *t) - return 0; - f++; - } - /* - * Now we've done that, increment t past the character we - * matched. - */ - t++; + /* + * Extract one character from t, and one character's worth + * of pattern from f, and step along both. Return 0 if they + * fail to match. + */ + if (*f == '\\') { + /* + * Backslash, which means f[1] is to be treated as a + * literal character no matter what it is. It may not + * be the end of the string. + */ + if (!f[1]) + return -WC_TRAILINGBACKSLASH; /* error */ + if (f[1] != *t) + return 0; /* failed to match */ + f += 2; + } else if (*f == '?') { + /* + * Question mark matches anything. + */ + f++; + } else if (*f == '[') { + bool invert = false; + bool matched = false; + /* + * Open bracket introduces a character class. + */ + f++; + if (*f == '^') { + invert = true; + f++; + } + while (*f != ']') { + if (*f == '\\') + f++; /* backslashes still work */ + if (!*f) + return -WC_UNCLOSEDCLASS; /* error again */ + if (f[1] == '-') { + int lower, upper, ourchr; + lower = (unsigned char) *f++; + f++; /* eat the minus */ + if (*f == ']') + return -WC_INVALIDRANGE; /* different error! */ + if (*f == '\\') + f++; /* backslashes _still_ work */ + if (!*f) + return -WC_UNCLOSEDCLASS; /* error again */ + upper = (unsigned char) *f++; + ourchr = (unsigned char) *t; + if (lower > upper) { + int t = lower; lower = upper; upper = t; + } + if (ourchr >= lower && ourchr <= upper) + matched = true; + } else { + matched |= (*t == *f++); + } + } + if (invert == matched) + return 0; /* failed to match character class */ + f++; /* eat the ] */ + } else { + /* + * Non-special character matches itself. + */ + if (*f != *t) + return 0; + f++; + } + /* + * Now we've done that, increment t past the character we + * matched. + */ + t++; } if (!*f || *f == '*') { - /* - * We have reached the end of f without finding a mismatch; - * so we're done. Update the caller pointers and return 1. - */ - *fragment = f; - *target = t; - return 1; + /* + * We have reached the end of f without finding a mismatch; + * so we're done. Update the caller pointers and return 1. + */ + *fragment = f; + *target = t; + return 1; } /* * Otherwise, we must have reached the end of t before we - * reached the end of f; so we've failed. Return 0. + * reached the end of f; so we've failed. Return 0. */ return 0; } @@ -219,74 +219,74 @@ static int wc_match_inner( * routine once and give up if it fails. */ if (*wildcard != '*') { - ret = wc_match_fragment(&wildcard, &target, target_end); - if (ret <= 0) - return ret; /* pass back failure or error alike */ + ret = wc_match_fragment(&wildcard, &target, target_end); + if (ret <= 0) + return ret; /* pass back failure or error alike */ } while (*wildcard) { - assert(*wildcard == '*'); - while (*wildcard == '*') - wildcard++; + assert(*wildcard == '*'); + while (*wildcard == '*') + wildcard++; - /* - * It's possible we've just hit the end of the wildcard - * after seeing a *, in which case there's no need to - * bother searching any more because we've won. - */ - if (!*wildcard) - return 1; + /* + * It's possible we've just hit the end of the wildcard + * after seeing a *, in which case there's no need to + * bother searching any more because we've won. + */ + if (!*wildcard) + return 1; - /* - * Now `wildcard' points at the next fragment. So we - * attempt to match it against `target', and if that fails - * we increment `target' and try again, and so on. When we - * find we're about to try matching against the empty - * string, we give up and return 0. - */ - ret = 0; - while (*target) { - const char *save_w = wildcard, *save_t = target; + /* + * Now `wildcard' points at the next fragment. So we + * attempt to match it against `target', and if that fails + * we increment `target' and try again, and so on. When we + * find we're about to try matching against the empty + * string, we give up and return 0. + */ + ret = 0; + while (*target) { + const char *save_w = wildcard, *save_t = target; - ret = wc_match_fragment(&wildcard, &target, target_end); + ret = wc_match_fragment(&wildcard, &target, target_end); - if (ret < 0) - return ret; /* syntax error */ + if (ret < 0) + return ret; /* syntax error */ - if (ret > 0 && !*wildcard && target != target_end) { - /* - * Final special case - literally. - * - * This situation arises when we are matching a - * _terminal_ fragment of the wildcard (that is, - * there is nothing after it, e.g. "*a"), and it - * has matched _too early_. For example, matching - * "*a" against "parka" will match the "a" fragment - * against the _first_ a, and then (if it weren't - * for this special case) matching would fail - * because we're at the end of the wildcard but not - * at the end of the target string. - * - * In this case what we must do is measure the - * length of the fragment in the target (which is - * why we saved `target'), jump straight to that - * distance from the end of the string using - * strlen, and match the same fragment again there - * (which is why we saved `wildcard'). Then we - * return whatever that operation returns. - */ - target = target_end - (target - save_t); - wildcard = save_w; - return wc_match_fragment(&wildcard, &target, target_end); - } + if (ret > 0 && !*wildcard && target != target_end) { + /* + * Final special case - literally. + * + * This situation arises when we are matching a + * _terminal_ fragment of the wildcard (that is, + * there is nothing after it, e.g. "*a"), and it + * has matched _too early_. For example, matching + * "*a" against "parka" will match the "a" fragment + * against the _first_ a, and then (if it weren't + * for this special case) matching would fail + * because we're at the end of the wildcard but not + * at the end of the target string. + * + * In this case what we must do is measure the + * length of the fragment in the target (which is + * why we saved `target'), jump straight to that + * distance from the end of the string using + * strlen, and match the same fragment again there + * (which is why we saved `wildcard'). Then we + * return whatever that operation returns. + */ + target = target_end - (target - save_t); + wildcard = save_w; + return wc_match_fragment(&wildcard, &target, target_end); + } - if (ret > 0) - break; - target++; - } - if (ret > 0) - continue; - return 0; + if (ret > 0) + break; + target++; + } + if (ret > 0) + continue; + return 0; } /* @@ -314,7 +314,7 @@ int wc_match_pl(const char *wildcard, ptrlen target) * Expects a target string buffer of anything up to the length of * the original wildcard. You can also pass NULL as the output * buffer if you're only interested in the return value. - * + * * Returns true on success, or false if a wildcard character was * encountered. In the latter case the output string MAY not be * zero-terminated and you should not use it for anything! @@ -322,22 +322,22 @@ int wc_match_pl(const char *wildcard, ptrlen target) bool wc_unescape(char *output, const char *wildcard) { while (*wildcard) { - if (*wildcard == '\\') { - wildcard++; - /* We are lenient about trailing backslashes in non-wildcards. */ - if (*wildcard) { - if (output) - *output++ = *wildcard; - wildcard++; - } - } else if (*wildcard == '*' || *wildcard == '?' || - *wildcard == '[' || *wildcard == ']') { - return false; /* it's a wildcard! */ - } else { - if (output) - *output++ = *wildcard; - wildcard++; - } + if (*wildcard == '\\') { + wildcard++; + /* We are lenient about trailing backslashes in non-wildcards. */ + if (*wildcard) { + if (output) + *output++ = *wildcard; + wildcard++; + } + } else if (*wildcard == '*' || *wildcard == '?' || + *wildcard == '[' || *wildcard == ']') { + return false; /* it's a wildcard! */ + } else { + if (output) + *output++ = *wildcard; + wildcard++; + } } if (output) *output = '\0'; @@ -447,35 +447,35 @@ int main(void) fails = passes = 0; for (i = 0; i < sizeof(fragment_tests)/sizeof(*fragment_tests); i++) { - const char *f, *t; - int eret, aret; - f = fragment_tests[i].wildcard; - t = fragment_tests[i].target; - eret = fragment_tests[i].expected_result; - aret = wc_match_fragment(&f, &t, t + strlen(t)); - if (aret != eret) { - printf("failed test: /%s/ against /%s/ returned %d not %d\n", - fragment_tests[i].wildcard, fragment_tests[i].target, - aret, eret); - fails++; - } else - passes++; + const char *f, *t; + int eret, aret; + f = fragment_tests[i].wildcard; + t = fragment_tests[i].target; + eret = fragment_tests[i].expected_result; + aret = wc_match_fragment(&f, &t, t + strlen(t)); + if (aret != eret) { + printf("failed test: /%s/ against /%s/ returned %d not %d\n", + fragment_tests[i].wildcard, fragment_tests[i].target, + aret, eret); + fails++; + } else + passes++; } for (i = 0; i < sizeof(full_tests)/sizeof(*full_tests); i++) { - const char *f, *t; - int eret, aret; - f = full_tests[i].wildcard; - t = full_tests[i].target; - eret = full_tests[i].expected_result; - aret = wc_match(f, t); - if (aret != eret) { - printf("failed test: /%s/ against /%s/ returned %d not %d\n", - full_tests[i].wildcard, full_tests[i].target, - aret, eret); - fails++; - } else - passes++; + const char *f, *t; + int eret, aret; + f = full_tests[i].wildcard; + t = full_tests[i].target; + eret = full_tests[i].expected_result; + aret = wc_match(f, t); + if (aret != eret) { + printf("failed test: /%s/ against /%s/ returned %d not %d\n", + full_tests[i].wildcard, full_tests[i].target, + aret, eret); + fails++; + } else + passes++; } printf("passed %d, failed %d\n", passes, fails); diff --git a/windows/installer.wxs b/windows/installer.wxs index 914d78a2..b221320e 100644 --- a/windows/installer.wxs +++ b/windows/installer.wxs @@ -540,7 +540,7 @@ https://msdn.microsoft.com/en-us/library/windows/desktop/dd391569(v=vs.85).aspx 1 - WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 and NOT Installed diff --git a/windows/pageant.mft b/windows/pageant.mft index 78f7b8ff..fc1bef77 100644 --- a/windows/pageant.mft +++ b/windows/pageant.mft @@ -15,9 +15,9 @@ looking controls in the client area. --> diff --git a/windows/putty.mft b/windows/putty.mft index 53c06aad..fdd000d2 100644 --- a/windows/putty.mft +++ b/windows/putty.mft @@ -15,9 +15,9 @@ looking controls in the client area. --> diff --git a/windows/puttygen.mft b/windows/puttygen.mft index 2c59ba7c..5eb20e36 100644 --- a/windows/puttygen.mft +++ b/windows/puttygen.mft @@ -15,9 +15,9 @@ looking controls in the client area. --> diff --git a/windows/puttytel.mft b/windows/puttytel.mft index 2fda22dc..81b4ddaa 100644 --- a/windows/puttytel.mft +++ b/windows/puttytel.mft @@ -15,9 +15,9 @@ looking controls in the client area. --> diff --git a/windows/sizetip.c b/windows/sizetip.c index e91c5b90..cfc4c6ec 100644 --- a/windows/sizetip.c +++ b/windows/sizetip.c @@ -15,76 +15,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) snewn(wtlen + 1, TCHAR); - GetWindowText(hWnd, wt, wtlen + 1); + wtlen = GetWindowTextLength(hWnd); + wt = (LPTSTR) snewn(wtlen + 1, 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); @@ -98,46 +98,46 @@ void UpdateSizeTip(HWND src, int cx, int cy) TCHAR str[32]; if (!tip_enabled) - return; + return; if (!tip_wnd) { - NONCLIENTMETRICS nci; + NONCLIENTMETRICS nci; - /* First make sure the window class is registered */ + /* 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"; + 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); - } + 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 */ @@ -145,49 +145,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(bool bEnable) { if (tip_wnd && !bEnable) { - DestroyWindow(tip_wnd); - tip_wnd = NULL; + DestroyWindow(tip_wnd); + tip_wnd = NULL; } tip_enabled = bEnable; diff --git a/windows/wincapi.h b/windows/wincapi.h index f327be27..a4958d28 100644 --- a/windows/wincapi.h +++ b/windows/wincapi.h @@ -11,7 +11,7 @@ #endif DECL_WINDOWS_FUNCTION(WINCAPI_GLOBAL, BOOL, CryptProtectMemory, - (LPVOID,DWORD,DWORD)); + (LPVOID,DWORD,DWORD)); bool got_crypt(void); diff --git a/windows/wincfg.c b/windows/wincfg.c index 493e0006..7186778b 100644 --- a/windows/wincfg.c +++ b/windows/wincfg.c @@ -11,22 +11,22 @@ #include "storage.h" static void about_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { HWND *hwndp = (HWND *)ctrl->generic.context.p; if (event == EVENT_ACTION) { - modal_about_box(*hwndp); + modal_about_box(*hwndp); } } static void help_handler(union control *ctrl, dlgparam *dlg, - void *data, int event) + void *data, int event) { HWND *hwndp = (HWND *)ctrl->generic.context.p; if (event == EVENT_ACTION) { - show_help(*hwndp); + show_help(*hwndp); } } @@ -34,32 +34,32 @@ static void variable_pitch_handler(union control *ctrl, dlgparam *dlg, void *data, int event) { if (event == EVENT_REFRESH) { - dlg_checkbox_set(ctrl, dlg, !dlg_get_fixed_pitch_flag(dlg)); + dlg_checkbox_set(ctrl, dlg, !dlg_get_fixed_pitch_flag(dlg)); } else if (event == EVENT_VALCHANGE) { - dlg_set_fixed_pitch_flag(dlg, !dlg_checkbox_get(ctrl, dlg)); + dlg_set_fixed_pitch_flag(dlg, !dlg_checkbox_get(ctrl, dlg)); } } void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, - bool midsession, int protocol) + bool midsession, int protocol) { struct controlset *s; union control *c; char *str; if (!midsession) { - /* - * Add the About and Help buttons to the standard panel. - */ - s = ctrl_getset(b, "", "", ""); - c = ctrl_pushbutton(s, "About", 'a', HELPCTX(no_help), - about_handler, P(hwndp)); - c->generic.column = 0; - if (has_help) { - c = ctrl_pushbutton(s, "Help", 'h', HELPCTX(no_help), - help_handler, P(hwndp)); - c->generic.column = 1; - } + /* + * Add the About and Help buttons to the standard panel. + */ + s = ctrl_getset(b, "", "", ""); + c = ctrl_pushbutton(s, "About", 'a', HELPCTX(no_help), + about_handler, P(hwndp)); + c->generic.column = 0; + if (has_help) { + c = ctrl_pushbutton(s, "Help", 'h', HELPCTX(no_help), + help_handler, P(hwndp)); + c->generic.column = 1; + } } /* @@ -67,11 +67,11 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, * scrollbar_in_fullscreen is as well. */ s = ctrl_getset(b, "Window", "scrollback", - "Control the scrollback in the window"); + "Control the scrollback in the window"); ctrl_checkbox(s, "Display scrollbar in full screen mode", 'i', - HELPCTX(window_scrollback), - conf_checkbox_handler, - I(CONF_scrollbar_in_fullscreen)); + HELPCTX(window_scrollback), + conf_checkbox_handler, + I(CONF_scrollbar_in_fullscreen)); /* * Really this wants to go just after `Display scrollbar'. See * if we can find that control, and do some shuffling. @@ -102,20 +102,20 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, * specific options. */ s = ctrl_getset(b, "Terminal/Keyboard", "features", - "Enable extra keyboard features:"); + "Enable extra keyboard features:"); ctrl_checkbox(s, "AltGr acts as Compose key", 't', - HELPCTX(keyboard_compose), - conf_checkbox_handler, I(CONF_compose_key)); + HELPCTX(keyboard_compose), + conf_checkbox_handler, I(CONF_compose_key)); ctrl_checkbox(s, "Control-Alt is different from AltGr", 'd', - HELPCTX(keyboard_ctrlalt), - conf_checkbox_handler, I(CONF_ctrlaltkeys)); + HELPCTX(keyboard_ctrlalt), + conf_checkbox_handler, I(CONF_ctrlaltkeys)); /* * Windows allows an arbitrary .WAV to be played as a bell, and * also the use of the PC speaker. For this we must search the * existing controlset for the radio-button set controlling the * `beep' option, and add extra buttons to it. - * + * * Note that although this _looks_ like a hideous hack, it's * actually all above board. The well-defined interface to the * per-platform dialog box code is the _data structures_ `union @@ -129,74 +129,74 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, */ s = ctrl_getset(b, "Terminal/Bell", "style", "Set the style of bell"); { - int i; - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_RADIO && - c->generic.context.i == CONF_beep) { - assert(c->generic.handler == conf_radiobutton_handler); - c->radio.nbuttons += 2; - c->radio.buttons = - sresize(c->radio.buttons, c->radio.nbuttons, char *); - c->radio.buttons[c->radio.nbuttons-1] = - dupstr("Play a custom sound file"); - c->radio.buttons[c->radio.nbuttons-2] = - dupstr("Beep using the PC speaker"); - c->radio.buttondata = - sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); - c->radio.buttondata[c->radio.nbuttons-1] = I(BELL_WAVEFILE); - c->radio.buttondata[c->radio.nbuttons-2] = I(BELL_PCSPEAKER); - if (c->radio.shortcuts) { - c->radio.shortcuts = - sresize(c->radio.shortcuts, c->radio.nbuttons, char); - c->radio.shortcuts[c->radio.nbuttons-1] = NO_SHORTCUT; - c->radio.shortcuts[c->radio.nbuttons-2] = NO_SHORTCUT; - } - break; - } - } + int i; + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_RADIO && + c->generic.context.i == CONF_beep) { + assert(c->generic.handler == conf_radiobutton_handler); + c->radio.nbuttons += 2; + c->radio.buttons = + sresize(c->radio.buttons, c->radio.nbuttons, char *); + c->radio.buttons[c->radio.nbuttons-1] = + dupstr("Play a custom sound file"); + c->radio.buttons[c->radio.nbuttons-2] = + dupstr("Beep using the PC speaker"); + c->radio.buttondata = + sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); + c->radio.buttondata[c->radio.nbuttons-1] = I(BELL_WAVEFILE); + c->radio.buttondata[c->radio.nbuttons-2] = I(BELL_PCSPEAKER); + if (c->radio.shortcuts) { + c->radio.shortcuts = + sresize(c->radio.shortcuts, c->radio.nbuttons, char); + c->radio.shortcuts[c->radio.nbuttons-1] = NO_SHORTCUT; + c->radio.shortcuts[c->radio.nbuttons-2] = NO_SHORTCUT; + } + break; + } + } } ctrl_filesel(s, "Custom sound file to play as a bell:", NO_SHORTCUT, - FILTER_WAVE_FILES, false, "Select bell sound file", - HELPCTX(bell_style), - conf_filesel_handler, I(CONF_bell_wavefile)); + FILTER_WAVE_FILES, false, "Select bell sound file", + HELPCTX(bell_style), + conf_filesel_handler, I(CONF_bell_wavefile)); /* * While we've got this box open, taskbar flashing on a bell is * also Windows-specific. */ ctrl_radiobuttons(s, "Taskbar/caption indication on bell:", 'i', 3, - HELPCTX(bell_taskbar), - conf_radiobutton_handler, - I(CONF_beep_ind), - "Disabled", I(B_IND_DISABLED), - "Flashing", I(B_IND_FLASH), - "Steady", I(B_IND_STEADY), NULL); + HELPCTX(bell_taskbar), + conf_radiobutton_handler, + I(CONF_beep_ind), + "Disabled", I(B_IND_DISABLED), + "Flashing", I(B_IND_FLASH), + "Steady", I(B_IND_STEADY), NULL); /* * The sunken-edge border is a Windows GUI feature. */ s = ctrl_getset(b, "Window/Appearance", "border", - "Adjust the window border"); + "Adjust the window border"); ctrl_checkbox(s, "Sunken-edge border (slightly thicker)", 's', - HELPCTX(appearance_border), - conf_checkbox_handler, I(CONF_sunken_edge)); + HELPCTX(appearance_border), + conf_checkbox_handler, I(CONF_sunken_edge)); /* * Configurable font quality settings for Windows. */ s = ctrl_getset(b, "Window/Appearance", "font", - "Font settings"); + "Font settings"); ctrl_checkbox(s, "Allow selection of variable-pitch fonts", NO_SHORTCUT, HELPCTX(appearance_font), variable_pitch_handler, I(0)); ctrl_radiobuttons(s, "Font quality:", 'q', 2, - HELPCTX(appearance_font), - conf_radiobutton_handler, - I(CONF_font_quality), - "Antialiased", I(FQ_ANTIALIASED), - "Non-Antialiased", I(FQ_NONANTIALIASED), - "ClearType", I(FQ_CLEARTYPE), - "Default", I(FQ_DEFAULT), NULL); + HELPCTX(appearance_font), + conf_radiobutton_handler, + I(CONF_font_quality), + "Antialiased", I(FQ_ANTIALIASED), + "Non-Antialiased", I(FQ_NONANTIALIASED), + "ClearType", I(FQ_CLEARTYPE), + "Default", I(FQ_DEFAULT), NULL); /* * Cyrillic Lock is a horrid misfeature even on Windows, and @@ -205,19 +205,19 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, */ s = ctrl_getset(b, "Window/Translation", "tweaks", NULL); ctrl_checkbox(s, "Caps Lock acts as Cyrillic switch", 's', - HELPCTX(translation_cyrillic), - conf_checkbox_handler, - I(CONF_xlat_capslockcyr)); + HELPCTX(translation_cyrillic), + conf_checkbox_handler, + I(CONF_xlat_capslockcyr)); /* * On Windows we can use but not enumerate translation tables * from the operating system. Briefly document this. */ s = ctrl_getset(b, "Window/Translation", "trans", - "Character set translation on received data"); + "Character set translation on received data"); ctrl_text(s, "(Codepages supported by Windows but not listed here, " - "such as CP866 on many systems, can be entered manually)", - HELPCTX(translation_codepage)); + "such as CP866 on many systems, can be entered manually)", + HELPCTX(translation_codepage)); /* * Windows has the weird OEM font mode, which gives us some @@ -228,51 +228,51 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, s = ctrl_getset(b, "Window/Translation", "linedraw", str); sfree(str); { - int i; - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_RADIO && - c->generic.context.i == CONF_vtmode) { - assert(c->generic.handler == conf_radiobutton_handler); - c->radio.nbuttons += 3; - c->radio.buttons = - sresize(c->radio.buttons, c->radio.nbuttons, char *); - c->radio.buttons[c->radio.nbuttons-3] = - dupstr("Font has XWindows encoding"); - c->radio.buttons[c->radio.nbuttons-2] = - dupstr("Use font in both ANSI and OEM modes"); - c->radio.buttons[c->radio.nbuttons-1] = - dupstr("Use font in OEM mode only"); - c->radio.buttondata = - sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); - c->radio.buttondata[c->radio.nbuttons-3] = I(VT_XWINDOWS); - c->radio.buttondata[c->radio.nbuttons-2] = I(VT_OEMANSI); - c->radio.buttondata[c->radio.nbuttons-1] = I(VT_OEMONLY); - if (!c->radio.shortcuts) { - int j; - c->radio.shortcuts = snewn(c->radio.nbuttons, char); - for (j = 0; j < c->radio.nbuttons; j++) - c->radio.shortcuts[j] = NO_SHORTCUT; - } else { - c->radio.shortcuts = sresize(c->radio.shortcuts, - c->radio.nbuttons, char); - } - c->radio.shortcuts[c->radio.nbuttons-3] = 'x'; - c->radio.shortcuts[c->radio.nbuttons-2] = 'b'; - c->radio.shortcuts[c->radio.nbuttons-1] = 'e'; - break; - } - } + int i; + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_RADIO && + c->generic.context.i == CONF_vtmode) { + assert(c->generic.handler == conf_radiobutton_handler); + c->radio.nbuttons += 3; + c->radio.buttons = + sresize(c->radio.buttons, c->radio.nbuttons, char *); + c->radio.buttons[c->radio.nbuttons-3] = + dupstr("Font has XWindows encoding"); + c->radio.buttons[c->radio.nbuttons-2] = + dupstr("Use font in both ANSI and OEM modes"); + c->radio.buttons[c->radio.nbuttons-1] = + dupstr("Use font in OEM mode only"); + c->radio.buttondata = + sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); + c->radio.buttondata[c->radio.nbuttons-3] = I(VT_XWINDOWS); + c->radio.buttondata[c->radio.nbuttons-2] = I(VT_OEMANSI); + c->radio.buttondata[c->radio.nbuttons-1] = I(VT_OEMONLY); + if (!c->radio.shortcuts) { + int j; + c->radio.shortcuts = snewn(c->radio.nbuttons, char); + for (j = 0; j < c->radio.nbuttons; j++) + c->radio.shortcuts[j] = NO_SHORTCUT; + } else { + c->radio.shortcuts = sresize(c->radio.shortcuts, + c->radio.nbuttons, char); + } + c->radio.shortcuts[c->radio.nbuttons-3] = 'x'; + c->radio.shortcuts[c->radio.nbuttons-2] = 'b'; + c->radio.shortcuts[c->radio.nbuttons-1] = 'e'; + break; + } + } } /* * RTF paste is Windows-specific. */ s = ctrl_getset(b, "Window/Selection/Copy", "format", - "Formatting of copied characters"); + "Formatting of copied characters"); ctrl_checkbox(s, "Copy to clipboard in RTF as well as plain text", 'f', - HELPCTX(copy_rtf), - conf_checkbox_handler, I(CONF_rtf_paste)); + HELPCTX(copy_rtf), + conf_checkbox_handler, I(CONF_rtf_paste)); /* * Windows often has no middle button, so we supply a selection @@ -280,14 +280,14 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, * the right button instead. */ s = ctrl_getset(b, "Window/Selection", "mouse", - "Control use of mouse"); + "Control use of mouse"); ctrl_radiobuttons(s, "Action of mouse buttons:", 'm', 1, - HELPCTX(selection_buttons), - conf_radiobutton_handler, - I(CONF_mouse_is_xterm), - "Windows (Middle extends, Right brings up menu)", I(2), - "Compromise (Middle extends, Right pastes)", I(0), - "xterm (Right extends, Middle pastes)", I(1), NULL); + HELPCTX(selection_buttons), + conf_radiobutton_handler, + I(CONF_mouse_is_xterm), + "Windows (Middle extends, Right brings up menu)", I(2), + "Compromise (Middle extends, Right pastes)", I(0), + "xterm (Right extends, Middle pastes)", I(1), NULL); /* * This really ought to go at the _top_ of its box, not the * bottom, so we'll just do some shuffling now we've set it @@ -301,10 +301,10 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, * Logical palettes don't even make sense anywhere except Windows. */ s = ctrl_getset(b, "Window/Colours", "general", - "General options for colour usage"); + "General options for colour usage"); ctrl_checkbox(s, "Attempt to use logical palettes", 'l', - HELPCTX(colours_logpal), - conf_checkbox_handler, I(CONF_try_palette)); + HELPCTX(colours_logpal), + conf_checkbox_handler, I(CONF_try_palette)); ctrl_checkbox(s, "Use system colours", 's', HELPCTX(colours_system), conf_checkbox_handler, I(CONF_system_colour)); @@ -315,13 +315,13 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, */ s = ctrl_getset(b, "Window", "size", "Set the size of the window"); ctrl_radiobuttons(s, "When window is resized:", 'z', 1, - HELPCTX(window_resize), - conf_radiobutton_handler, - I(CONF_resize_action), - "Change the number of rows and columns", I(RESIZE_TERM), - "Change the size of the font", I(RESIZE_FONT), - "Change font size only when maximised", I(RESIZE_EITHER), - "Forbid resizing completely", I(RESIZE_DISABLED), NULL); + HELPCTX(window_resize), + conf_radiobutton_handler, + I(CONF_resize_action), + "Change the number of rows and columns", I(RESIZE_TERM), + "Change the size of the font", I(RESIZE_FONT), + "Change font size only when maximised", I(RESIZE_EITHER), + "Forbid resizing completely", I(RESIZE_DISABLED), NULL); /* * Most of the Window/Behaviour stuff is there to mimic Windows @@ -330,57 +330,57 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, */ s = ctrl_getset(b, "Window/Behaviour", "main", NULL); ctrl_checkbox(s, "Window closes on ALT-F4", '4', - HELPCTX(behaviour_altf4), - conf_checkbox_handler, I(CONF_alt_f4)); + HELPCTX(behaviour_altf4), + conf_checkbox_handler, I(CONF_alt_f4)); ctrl_checkbox(s, "System menu appears on ALT-Space", 'y', - HELPCTX(behaviour_altspace), - conf_checkbox_handler, I(CONF_alt_space)); + HELPCTX(behaviour_altspace), + conf_checkbox_handler, I(CONF_alt_space)); ctrl_checkbox(s, "System menu appears on ALT alone", 'l', - HELPCTX(behaviour_altonly), - conf_checkbox_handler, I(CONF_alt_only)); + HELPCTX(behaviour_altonly), + conf_checkbox_handler, I(CONF_alt_only)); ctrl_checkbox(s, "Ensure window is always on top", 'e', - HELPCTX(behaviour_alwaysontop), - conf_checkbox_handler, I(CONF_alwaysontop)); + HELPCTX(behaviour_alwaysontop), + conf_checkbox_handler, I(CONF_alwaysontop)); ctrl_checkbox(s, "Full screen on Alt-Enter", 'f', - HELPCTX(behaviour_altenter), - conf_checkbox_handler, - I(CONF_fullscreenonaltenter)); + HELPCTX(behaviour_altenter), + conf_checkbox_handler, + I(CONF_fullscreenonaltenter)); /* * Windows supports a local-command proxy. This also means we * must adjust the text on the `Telnet command' control. */ if (!midsession) { - int i; + int i; s = ctrl_getset(b, "Connection/Proxy", "basics", NULL); - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_RADIO && - c->generic.context.i == CONF_proxy_type) { - assert(c->generic.handler == conf_radiobutton_handler); - c->radio.nbuttons++; - c->radio.buttons = - sresize(c->radio.buttons, c->radio.nbuttons, char *); - c->radio.buttons[c->radio.nbuttons-1] = - dupstr("Local"); - c->radio.buttondata = - sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); - c->radio.buttondata[c->radio.nbuttons-1] = I(PROXY_CMD); - break; - } - } + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_RADIO && + c->generic.context.i == CONF_proxy_type) { + assert(c->generic.handler == conf_radiobutton_handler); + c->radio.nbuttons++; + c->radio.buttons = + sresize(c->radio.buttons, c->radio.nbuttons, char *); + c->radio.buttons[c->radio.nbuttons-1] = + dupstr("Local"); + c->radio.buttondata = + sresize(c->radio.buttondata, c->radio.nbuttons, intorptr); + c->radio.buttondata[c->radio.nbuttons-1] = I(PROXY_CMD); + break; + } + } - for (i = 0; i < s->ncontrols; i++) { - c = s->ctrls[i]; - if (c->generic.type == CTRL_EDITBOX && - c->generic.context.i == CONF_proxy_telnet_command) { - assert(c->generic.handler == conf_editbox_handler); - sfree(c->generic.label); - c->generic.label = dupstr("Telnet command, or local" - " proxy command"); - break; - } - } + for (i = 0; i < s->ncontrols; i++) { + c = s->ctrls[i]; + if (c->generic.type == CTRL_EDITBOX && + c->generic.context.i == CONF_proxy_telnet_command) { + assert(c->generic.handler == conf_editbox_handler); + sfree(c->generic.label); + c->generic.label = dupstr("Telnet command, or local" + " proxy command"); + break; + } + } } /* @@ -394,10 +394,10 @@ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, * means to override it. */ if (!midsession && backend_vt_from_proto(PROT_SSH)) { - s = ctrl_getset(b, "Connection/SSH/X11", "x11", "X11 forwarding"); - ctrl_filesel(s, "X authority file for local display", 't', - NULL, false, "Select X authority file", - HELPCTX(ssh_tunnels_xauthority), - conf_filesel_handler, I(CONF_xauthfile)); + s = ctrl_getset(b, "Connection/SSH/X11", "x11", "X11 forwarding"); + ctrl_filesel(s, "X authority file for local display", 't', + NULL, false, "Select X authority file", + HELPCTX(ssh_tunnels_xauthority), + conf_filesel_handler, I(CONF_xauthfile)); } } diff --git a/windows/wincons.c b/windows/wincons.c index b786372a..81df8cee 100644 --- a/windows/wincons.c +++ b/windows/wincons.c @@ -93,53 +93,53 @@ int console_verify_ssh_host_key( DWORD savemode, i; static const char absentmsg_batch[] = - "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 %s key fingerprint is:\n" - "%s\n" - "Connection abandoned.\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 %s key fingerprint is:\n" + "%s\n" + "Connection abandoned.\n"; 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 %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 want to carry on connecting just once, without\n" - "adding the key to the cache, enter \"n\".\n" - "If you do not trust this host, press Return to abandon the\n" - "connection.\n" - "Store key in cache? (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 %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 want to carry on connecting just once, without\n" + "adding the key to the cache, enter \"n\".\n" + "If you do not trust this host, press Return to abandon the\n" + "connection.\n" + "Store key in cache? (y/n) "; static const char wrongmsg_batch[] = - "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 %s key fingerprint is:\n" - "%s\n" - "Connection abandoned.\n"; + "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 %s key fingerprint is:\n" + "%s\n" + "Connection abandoned.\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 %s 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 %s 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"; @@ -150,24 +150,24 @@ int console_verify_ssh_host_key( */ ret = verify_host_key(host, port, keytype, keystr); - if (ret == 0) /* success - key matched OK */ - return 1; + if (ret == 0) /* success - key matched OK */ + return 1; - if (ret == 2) { /* key was different */ - if (console_batch_mode) { - fprintf(stderr, wrongmsg_batch, keytype, fingerprint); + if (ret == 2) { /* key was different */ + if (console_batch_mode) { + fprintf(stderr, wrongmsg_batch, keytype, fingerprint); return 0; - } - fprintf(stderr, wrongmsg, keytype, fingerprint); - fflush(stderr); + } + fprintf(stderr, wrongmsg, keytype, fingerprint); + fflush(stderr); } - if (ret == 1) { /* key was absent */ - if (console_batch_mode) { - fprintf(stderr, absentmsg_batch, keytype, fingerprint); + if (ret == 1) { /* key was absent */ + if (console_batch_mode) { + fprintf(stderr, absentmsg_batch, keytype, fingerprint); return 0; - } - fprintf(stderr, absentmsg, keytype, fingerprint); - fflush(stderr); + } + fprintf(stderr, absentmsg, keytype, fingerprint); + fflush(stderr); } line[0] = '\0'; /* fail safe if ReadFile returns no data */ @@ -175,16 +175,16 @@ int console_verify_ssh_host_key( hin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(hin, &savemode); SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT | - ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); + ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); ReadFile(hin, line, sizeof(line) - 1, &i, NULL); SetConsoleMode(hin, savemode); if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') { - if (line[0] == 'y' || line[0] == 'Y') - store_host_key(host, port, keytype, keystr); + if (line[0] == 'y' || line[0] == 'Y') + store_host_key(host, port, keytype, keystr); return 1; } else { - fprintf(stderr, abandoned); + fprintf(stderr, abandoned); return 0; } } @@ -197,20 +197,20 @@ int console_confirm_weak_crypto_primitive( DWORD savemode, i; static const char msg[] = - "The first %s supported by the server is\n" - "%s, which is below the configured warning threshold.\n" - "Continue with connection? (y/n) "; + "The first %s supported by the server is\n" + "%s, which is below the configured warning threshold.\n" + "Continue with connection? (y/n) "; static const char msg_batch[] = - "The first %s supported by the server is\n" - "%s, which is below the configured warning threshold.\n" - "Connection abandoned.\n"; + "The first %s supported by the server is\n" + "%s, which is below the configured warning threshold.\n" + "Connection abandoned.\n"; static const char abandoned[] = "Connection abandoned.\n"; char line[32]; if (console_batch_mode) { - fprintf(stderr, msg_batch, algtype, algname); - return 0; + fprintf(stderr, msg_batch, algtype, algname); + return 0; } fprintf(stderr, msg, algtype, algname); @@ -219,15 +219,15 @@ int console_confirm_weak_crypto_primitive( hin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(hin, &savemode); SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT | - ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); + ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); ReadFile(hin, line, sizeof(line) - 1, &i, NULL); SetConsoleMode(hin, savemode); if (line[0] == 'y' || line[0] == 'Y') { - return 1; + return 1; } else { - fprintf(stderr, abandoned); - return 0; + fprintf(stderr, abandoned); + return 0; } } @@ -239,26 +239,26 @@ int console_confirm_weak_cached_hostkey( DWORD savemode, i; static const char msg[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Continue with connection? (y/n) "; + "Continue with connection? (y/n) "; static const char msg_batch[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Connection abandoned.\n"; + "Connection abandoned.\n"; static const char abandoned[] = "Connection abandoned.\n"; char line[32]; if (console_batch_mode) { - fprintf(stderr, msg_batch, algname, betteralgs); - return 0; + fprintf(stderr, msg_batch, algname, betteralgs); + return 0; } fprintf(stderr, msg, algname, betteralgs); @@ -267,15 +267,15 @@ int console_confirm_weak_cached_hostkey( hin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(hin, &savemode); SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT | - ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); + ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); ReadFile(hin, line, sizeof(line) - 1, &i, NULL); SetConsoleMode(hin, savemode); if (line[0] == 'y' || line[0] == 'Y') { - return 1; + return 1; } else { - fprintf(stderr, abandoned); - return 0; + fprintf(stderr, abandoned); + return 0; } } @@ -319,24 +319,24 @@ static int console_askappend(LogPolicy *lp, Filename *filename, DWORD savemode, i; static const char msgtemplate[] = - "The session log file \"%.*s\" already exists.\n" - "You can overwrite it with a new session log,\n" - "append your session log to the end of it,\n" - "or disable session logging for this session.\n" - "Enter \"y\" to wipe the file, \"n\" to append to it,\n" - "or just press Return to disable logging.\n" - "Wipe the log file? (y/n, Return cancels logging) "; + "The session log file \"%.*s\" already exists.\n" + "You can overwrite it with a new session log,\n" + "append your session log to the end of it,\n" + "or disable session logging for this session.\n" + "Enter \"y\" to wipe the file, \"n\" to append to it,\n" + "or just press Return to disable logging.\n" + "Wipe the log file? (y/n, Return cancels logging) "; static const char msgtemplate_batch[] = - "The session log file \"%.*s\" already exists.\n" - "Logging will not be enabled.\n"; + "The session log file \"%.*s\" already exists.\n" + "Logging will not be enabled.\n"; char line[32]; if (console_batch_mode) { - fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path); - fflush(stderr); - return 0; + fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename->path); + fflush(stderr); + return 0; } fprintf(stderr, msgtemplate, FILENAME_MAX, filename->path); fflush(stderr); @@ -344,21 +344,21 @@ static int console_askappend(LogPolicy *lp, Filename *filename, hin = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(hin, &savemode); SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT | - ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); + ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT)); ReadFile(hin, line, sizeof(line) - 1, &i, NULL); SetConsoleMode(hin, savemode); if (line[0] == 'y' || line[0] == 'Y') - return 2; + return 2; else if (line[0] == 'n' || line[0] == 'N') - return 1; + return 1; else - return 0; + return 0; } /* * Warn about the obsolescent key file format. - * + * * Uniquely among these functions, this one does _not_ expect a * frontend handle. This means that if PuTTY is ported to a * platform which requires frontend handles, this function will be @@ -369,15 +369,15 @@ static int console_askappend(LogPolicy *lp, Filename *filename, void old_keyfile_warning(void) { static const char message[] = - "You are loading an SSH-2 private key which has an\n" - "old version of the file format. This means your key\n" - "file is not fully tamperproof. Future versions of\n" - "PuTTY may stop supporting this private key format,\n" - "so we recommend you convert your key to the new\n" - "format.\n" - "\n" - "Once the key is loaded into PuTTYgen, you can perform\n" - "this conversion simply by saving it again.\n"; + "You are loading an SSH-2 private key which has an\n" + "old version of the file format. This means your key\n" + "file is not fully tamperproof. Future versions of\n" + "PuTTY may stop supporting this private key format,\n" + "so we recommend you convert your key to the new\n" + "format.\n" + "\n" + "Once the key is loaded into PuTTYgen, you can perform\n" + "this conversion simply by saving it again.\n"; fputs(message, stderr); } @@ -388,16 +388,16 @@ void old_keyfile_warning(void) void pgp_fingerprints(void) { fputs("These are the fingerprints of the PuTTY PGP Master Keys. They can\n" - "be used to establish a trust path from this executable to another\n" - "one. See the manual for more information.\n" - "(Note: these fingerprints have nothing to do with SSH!)\n" - "\n" - "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR + "be used to establish a trust path from this executable to another\n" + "one. See the manual for more information.\n" + "(Note: these fingerprints have nothing to do with SSH!)\n" + "\n" + "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR " (" PGP_MASTER_KEY_DETAILS "):\n" - " " PGP_MASTER_KEY_FP "\n\n" - "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR + " " PGP_MASTER_KEY_FP "\n\n" + "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR ", " PGP_PREV_MASTER_KEY_DETAILS "):\n" - " " PGP_PREV_MASTER_KEY_FP "\n", stdout); + " " PGP_PREV_MASTER_KEY_FP "\n", stdout); } static void console_logging_error(LogPolicy *lp, const char *string) @@ -437,8 +437,8 @@ int console_get_userpass_input(prompts_t *p) * Zero all the results, in case we abort half-way through. */ { - int i; - for (i = 0; i < (int)p->n_prompts; i++) + int i; + for (i = 0; i < (int)p->n_prompts; i++) prompt_set_result(p->prompts[i], ""); } @@ -449,24 +449,24 @@ int console_get_userpass_input(prompts_t *p) * need to ensure that we're able to get the answers. */ if (p->n_prompts) { - if (console_batch_mode) - return 0; - hin = GetStdHandle(STD_INPUT_HANDLE); - if (hin == INVALID_HANDLE_VALUE) { - fprintf(stderr, "Cannot get standard input handle\n"); - cleanup_exit(1); - } + if (console_batch_mode) + return 0; + hin = GetStdHandle(STD_INPUT_HANDLE); + if (hin == INVALID_HANDLE_VALUE) { + fprintf(stderr, "Cannot get standard input handle\n"); + cleanup_exit(1); + } } /* * And if we have anything to print, we need standard output. */ if ((p->name_reqd && p->name) || p->instruction || p->n_prompts) { - hout = GetStdHandle(STD_OUTPUT_HANDLE); - if (hout == INVALID_HANDLE_VALUE) { - fprintf(stderr, "Cannot get standard output handle\n"); - cleanup_exit(1); - } + hout = GetStdHandle(STD_OUTPUT_HANDLE); + if (hout == INVALID_HANDLE_VALUE) { + fprintf(stderr, "Cannot get standard output handle\n"); + cleanup_exit(1); + } } /* @@ -474,34 +474,34 @@ int console_get_userpass_input(prompts_t *p) */ /* We only print the `name' caption if we have to... */ if (p->name_reqd && p->name) { - ptrlen plname = ptrlen_from_asciz(p->name); - console_write(hout, plname); + ptrlen plname = ptrlen_from_asciz(p->name); + console_write(hout, plname); if (!ptrlen_endswith(plname, PTRLEN_LITERAL("\n"), NULL)) - console_write(hout, PTRLEN_LITERAL("\n")); + console_write(hout, PTRLEN_LITERAL("\n")); } /* ...but we always print any `instruction'. */ if (p->instruction) { - ptrlen plinst = ptrlen_from_asciz(p->instruction); - console_write(hout, plinst); + ptrlen plinst = ptrlen_from_asciz(p->instruction); + console_write(hout, plinst); if (!ptrlen_endswith(plinst, PTRLEN_LITERAL("\n"), NULL)) - console_write(hout, PTRLEN_LITERAL("\n")); + console_write(hout, PTRLEN_LITERAL("\n")); } for (curr_prompt = 0; curr_prompt < p->n_prompts; curr_prompt++) { - DWORD savemode, newmode; + DWORD savemode, newmode; size_t len; - prompt_t *pr = p->prompts[curr_prompt]; + prompt_t *pr = p->prompts[curr_prompt]; - GetConsoleMode(hin, &savemode); - newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT; - if (!pr->echo) - newmode &= ~ENABLE_ECHO_INPUT; - else - newmode |= ENABLE_ECHO_INPUT; - SetConsoleMode(hin, newmode); + GetConsoleMode(hin, &savemode); + newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT; + if (!pr->echo) + newmode &= ~ENABLE_ECHO_INPUT; + else + newmode |= ENABLE_ECHO_INPUT; + SetConsoleMode(hin, newmode); - console_write(hout, ptrlen_from_asciz(pr->prompt)); + console_write(hout, ptrlen_from_asciz(pr->prompt)); len = 0; while (1) { @@ -523,16 +523,16 @@ int console_get_userpass_input(prompts_t *p) } } - SetConsoleMode(hin, savemode); + SetConsoleMode(hin, savemode); - if (!pr->echo) + if (!pr->echo) console_write(hout, PTRLEN_LITERAL("\r\n")); if (len == (size_t)-1) { return 0; /* failure due to read error */ } - pr->result[len] = '\0'; + pr->result[len] = '\0'; } return 1; /* success */ diff --git a/windows/winctrls.c b/windows/winctrls.c index 973ac89c..f30ccf39 100644 --- a/windows/winctrls.c +++ b/windows/winctrls.c @@ -54,7 +54,7 @@ void init_common_controls(void) } 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; @@ -72,7 +72,7 @@ void ctlposinit(struct ctlpos *cp, HWND hwnd, } HWND 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; /* @@ -89,26 +89,26 @@ HWND doctl(struct ctlpos *cp, RECT r, * without creating any actual controls. */ if (cp->hwnd) { - ctl = CreateWindowEx(exstyle, wclass, wtext, wstyle, - r.left, r.top, r.right, r.bottom, - cp->hwnd, (HMENU)(ULONG_PTR)wid, hinst, NULL); - SendMessage(ctl, WM_SETFONT, cp->font, MAKELPARAM(true, 0)); + ctl = CreateWindowEx(exstyle, wclass, wtext, wstyle, + r.left, r.top, r.right, r.bottom, + cp->hwnd, (HMENU)(ULONG_PTR)wid, hinst, NULL); + SendMessage(ctl, WM_SETFONT, cp->font, MAKELPARAM(true, 0)); - if (!strcmp(wclass, "LISTBOX")) { - /* - * Bizarre Windows bug: the list box calculates its - * number of lines based on the font it has at creation - * time, but sending it WM_SETFONT doesn't cause it to - * recalculate. So now, _after_ we've sent it - * WM_SETFONT, we explicitly resize it (to the same - * size it was already!) to force it to reconsider. - */ - SetWindowPos(ctl, NULL, 0, 0, r.right, r.bottom, - SWP_NOACTIVATE | SWP_NOCOPYBITS | - SWP_NOMOVE | SWP_NOZORDER); - } + if (!strcmp(wclass, "LISTBOX")) { + /* + * Bizarre Windows bug: the list box calculates its + * number of lines based on the font it has at creation + * time, but sending it WM_SETFONT doesn't cause it to + * recalculate. So now, _after_ we've sent it + * WM_SETFONT, we explicitly resize it (to the same + * size it was already!) to force it to reconsider. + */ + SetWindowPos(ctl, NULL, 0, 0, r.right, r.bottom, + SWP_NOACTIVATE | SWP_NOCOPYBITS | + SWP_NOMOVE | SWP_NOZORDER); + } } else - ctl = NULL; + ctl = NULL; return ctl; } @@ -134,9 +134,9 @@ 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->xoff += GAPXBOX; @@ -158,7 +158,7 @@ void endbox(struct ctlpos *cp) 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; } @@ -166,7 +166,7 @@ void endbox(struct ctlpos *cp) * A static line, followed by a full-width edit box. */ void editboxfw(struct ctlpos *cp, bool password, char *text, - int staticid, int editid) + int staticid, int editid) { RECT r; @@ -174,17 +174,17 @@ void editboxfw(struct ctlpos *cp, bool password, char *text, r.right = cp->width; if (text) { - r.top = cp->ypos; - r.bottom = STATICHEIGHT; - doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid); - cp->ypos += STATICHEIGHT + GAPWITHIN; + r.top = cp->ypos; + r.bottom = STATICHEIGHT; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid); + cp->ypos += STATICHEIGHT + GAPWITHIN; } r.top = cp->ypos; r.bottom = EDITHEIGHT; doctl(cp, r, "EDIT", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | - (password ? ES_PASSWORD : 0), - WS_EX_CLIENTEDGE, "", editid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | + (password ? ES_PASSWORD : 0), + WS_EX_CLIENTEDGE, "", editid); cp->ypos += EDITHEIGHT + GAPBETWEEN; } @@ -199,23 +199,23 @@ void combobox(struct ctlpos *cp, char *text, int staticid, int listid) r.right = cp->width; if (text) { - r.top = cp->ypos; - r.bottom = STATICHEIGHT; - doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid); - cp->ypos += STATICHEIGHT + GAPWITHIN; + r.top = cp->ypos; + r.bottom = STATICHEIGHT; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, text, staticid); + cp->ypos += STATICHEIGHT + GAPWITHIN; } r.top = cp->ypos; r.bottom = COMBOHEIGHT * 10; doctl(cp, r, "COMBOBOX", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | - CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", listid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | + CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", listid); cp->ypos += COMBOHEIGHT + GAPBETWEEN; } struct radio { char *text; int id; }; static void radioline_common(struct ctlpos *cp, char *text, int id, - int nacross, struct radio *buttons, int nbuttons) + int nacross, struct radio *buttons, int nbuttons) { RECT r; int group; @@ -223,37 +223,37 @@ static void radioline_common(struct ctlpos *cp, char *text, int id, int j; if (text) { - 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); + 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); } group = WS_GROUP; i = 0; for (j = 0; j < nbuttons; j++) { - char *btext = buttons[j].text; - int bid = buttons[j].id; + char *btext = buttons[j].text; + int bid = buttons[j].id; - if (i == nacross) { - cp->ypos += r.bottom + (nacross > 1 ? GAPBETWEEN : GAPWITHIN); - i = 0; - } - r.left = GAPBETWEEN + i * (cp->width + GAPBETWEEN) / nacross; - if (j < nbuttons-1) - 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_NOTIFY | BS_AUTORADIOBUTTON | WS_CHILD | - WS_VISIBLE | WS_TABSTOP | group, 0, btext, bid); - group = 0; - i++; + if (i == nacross) { + cp->ypos += r.bottom + (nacross > 1 ? GAPBETWEEN : GAPWITHIN); + i = 0; + } + r.left = GAPBETWEEN + i * (cp->width + GAPBETWEEN) / nacross; + if (j < nbuttons-1) + 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_NOTIFY | BS_AUTORADIOBUTTON | WS_CHILD | + WS_VISIBLE | WS_TABSTOP | group, 0, btext, bid); + group = 0; + i++; } cp->ypos += r.bottom + GAPBETWEEN; } @@ -264,12 +264,12 @@ static void radioline_common(struct ctlpos *cp, char *text, int id, * (you might want this not to equal the number of buttons if you * needed to line up some 2s and some 3s to look good in the same * panel). - * + * * There's a bit of a hack in here to ensure that if nacross * exceeds the actual number of buttons, the rightmost button * really does get all the space right to the edge of the line, so * you can do things like - * + * * (*) Button1 (*) Button2 (*) ButtonWithReallyLongTitle */ void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...) @@ -281,18 +281,18 @@ void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...) va_start(ap, nacross); nbuttons = 0; while (1) { - char *btext = va_arg(ap, char *); - if (!btext) - break; - (void) va_arg(ap, int); /* id */ - nbuttons++; + char *btext = va_arg(ap, char *); + if (!btext) + break; + (void) va_arg(ap, int); /* id */ + nbuttons++; } va_end(ap); buttons = snewn(nbuttons, struct radio); va_start(ap, nacross); for (i = 0; i < nbuttons; i++) { - buttons[i].text = va_arg(ap, char *); - buttons[i].id = va_arg(ap, int); + buttons[i].text = va_arg(ap, char *); + buttons[i].id = va_arg(ap, int); } va_end(ap); radioline_common(cp, text, id, nacross, buttons, nbuttons); @@ -312,18 +312,18 @@ void bareradioline(struct ctlpos *cp, int nacross, ...) va_start(ap, nacross); nbuttons = 0; while (1) { - char *btext = va_arg(ap, char *); - if (!btext) - break; - (void) va_arg(ap, int); /* id */ + char *btext = va_arg(ap, char *); + if (!btext) + break; + (void) va_arg(ap, int); /* id */ nbuttons++; } va_end(ap); buttons = snewn(nbuttons, struct radio); va_start(ap, nacross); for (i = 0; i < nbuttons; i++) { - buttons[i].text = va_arg(ap, char *); - buttons[i].id = va_arg(ap, int); + buttons[i].text = va_arg(ap, char *); + buttons[i].id = va_arg(ap, int); } va_end(ap); radioline_common(cp, NULL, 0, nacross, buttons, nbuttons); @@ -343,18 +343,18 @@ void radiobig(struct ctlpos *cp, char *text, int id, ...) va_start(ap, id); nbuttons = 0; while (1) { - char *btext = va_arg(ap, char *); - if (!btext) - break; - (void) va_arg(ap, int); /* id */ + char *btext = va_arg(ap, char *); + if (!btext) + break; + (void) va_arg(ap, int); /* id */ nbuttons++; } va_end(ap); buttons = snewn(nbuttons, struct radio); va_start(ap, id); for (i = 0; i < nbuttons; i++) { - buttons[i].text = va_arg(ap, char *); - buttons[i].id = va_arg(ap, int); + buttons[i].text = va_arg(ap, char *); + buttons[i].id = va_arg(ap, int); } va_end(ap); radioline_common(cp, text, id, 1, buttons, nbuttons); @@ -374,8 +374,8 @@ void checkbox(struct ctlpos *cp, char *text, int id) r.bottom = CHECKBOXHEIGHT; cp->ypos += r.bottom + GAPBETWEEN; doctl(cp, r, "BUTTON", - BS_NOTIFY | BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, - text, id); + BS_NOTIFY | BS_AUTOCHECKBOX | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, + text, id); } /* @@ -403,7 +403,7 @@ char *staticwrap(struct ctlpos *cp, HWND hwnd, char *text, int *lines) * the same adjustment that the `statictext' function itself * will perform. */ - SetMapMode(hdc, MM_TEXT); /* ensure logical units == pixels */ + SetMapMode(hdc, MM_TEXT); /* ensure logical units == pixels */ r.left = r.top = r.bottom = 0; r.right = cp->width; MapDialogRect(hwnd, &r); @@ -419,41 +419,41 @@ char *staticwrap(struct ctlpos *cp, HWND hwnd, char *text, int *lines) oldfont = SelectObject(hdc, newfont); while (*p) { - if (!GetTextExtentExPoint(hdc, p, strlen(p), width, - &nfit, pwidths, &size) || - (size_t)nfit >= strlen(p)) { - /* - * Either GetTextExtentExPoint returned failure, or the - * whole of the rest of the text fits on this line. - * Either way, we stop wrapping, copy the remainder of - * the input string unchanged to the output, and leave. - */ - strcpy(q, p); - break; - } + if (!GetTextExtentExPoint(hdc, p, strlen(p), width, + &nfit, pwidths, &size) || + (size_t)nfit >= strlen(p)) { + /* + * Either GetTextExtentExPoint returned failure, or the + * whole of the rest of the text fits on this line. + * Either way, we stop wrapping, copy the remainder of + * the input string unchanged to the output, and leave. + */ + strcpy(q, p); + break; + } - /* - * Now we search backwards along the string from `nfit', - * looking for a space at which to break the line. If we - * don't find one at all, that's fine - we'll just break - * the line at `nfit'. - */ - for (j = nfit; j > 0; j--) { - if (isspace((unsigned char)p[j])) { - nfit = j; - break; - } - } + /* + * Now we search backwards along the string from `nfit', + * looking for a space at which to break the line. If we + * don't find one at all, that's fine - we'll just break + * the line at `nfit'. + */ + for (j = nfit; j > 0; j--) { + if (isspace((unsigned char)p[j])) { + nfit = j; + break; + } + } - strncpy(q, p, nfit); - q[nfit] = '\n'; - q += nfit+1; + strncpy(q, p, nfit); + q[nfit] = '\n'; + q += nfit+1; - p += nfit; - while (*p && isspace((unsigned char)*p)) - p++; + p += nfit; + while (*p && isspace((unsigned char)*p)) + p++; - nlines++; + nlines++; } SelectObject(hdc, oldfont); @@ -479,8 +479,8 @@ void statictext(struct ctlpos *cp, char *text, int lines, int id) r.bottom = STATICHEIGHT * lines; cp->ypos += r.bottom + GAPBETWEEN; doctl(cp, r, "STATIC", - WS_CHILD | WS_VISIBLE | SS_LEFTNOWORDWRAP, - 0, text, id); + WS_CHILD | WS_VISIBLE | SS_LEFTNOWORDWRAP, + 0, text, id); } /* @@ -496,17 +496,17 @@ void paneltitle(struct ctlpos *cp, int id) r.bottom = TITLEHEIGHT; cp->ypos += r.bottom + GAPBETWEEN; doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_OWNERDRAW, - 0, NULL, id); + 0, NULL, 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; @@ -525,8 +525,8 @@ void staticbtn(struct ctlpos *cp, char *stext, int sid, r.right = rwid; r.bottom = PUSHBTNHEIGHT; doctl(cp, r, "BUTTON", - BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, - 0, btext, bid); + BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, + 0, btext, bid); cp->ypos += height + GAPBETWEEN; } @@ -546,12 +546,12 @@ void button(struct ctlpos *cp, char *btext, int bid, bool defbtn) /* Q67655: the _dialog box_ must know which button is default * as well as the button itself knowing */ if (defbtn && cp->hwnd) - SendMessage(cp->hwnd, DM_SETDEFID, bid, 0); + SendMessage(cp->hwnd, DM_SETDEFID, bid, 0); doctl(cp, r, "BUTTON", - BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | - (defbtn ? BS_DEFPUSHBUTTON : 0) | BS_PUSHBUTTON, - 0, btext, bid); + BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | + (defbtn ? BS_DEFPUSHBUTTON : 0) | BS_PUSHBUTTON, + 0, btext, bid); cp->ypos += PUSHBTNHEIGHT + GAPBETWEEN; } @@ -560,10 +560,10 @@ void button(struct ctlpos *cp, char *btext, int bid, bool defbtn) * Like staticbtn, but two buttons. */ void static2btn(struct ctlpos *cp, char *stext, int sid, - char *btext1, int bid1, char *btext2, int bid2) + char *btext1, int bid1, char *btext2, int bid2) { const int height = (PUSHBTNHEIGHT > STATICHEIGHT ? - PUSHBTNHEIGHT : STATICHEIGHT); + PUSHBTNHEIGHT : STATICHEIGHT); RECT r; int lwid, rwid1, rwid2, rpos1, rpos2; @@ -584,16 +584,16 @@ void static2btn(struct ctlpos *cp, char *stext, int sid, r.right = rwid1; r.bottom = PUSHBTNHEIGHT; doctl(cp, r, "BUTTON", - BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, - 0, btext1, bid1); + BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, + 0, btext1, bid1); r.left = rpos2; r.top = cp->ypos + (height - PUSHBTNHEIGHT) / 2; r.right = rwid2; r.bottom = PUSHBTNHEIGHT; doctl(cp, r, "BUTTON", - BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, - 0, btext2, bid2); + BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, + 0, btext2, bid2); cp->ypos += height + GAPBETWEEN; } @@ -602,16 +602,16 @@ void static2btn(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; + GAPBETWEEN + (100 - percentedit) * (cp->width + GAPBETWEEN) / 100; lwid = rpos - 2 * GAPBETWEEN; rwid = cp->width + GAPBETWEEN - rpos; @@ -626,20 +626,20 @@ static void staticedit_internal(struct ctlpos *cp, char *stext, 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); } @@ -649,15 +649,15 @@ void staticpassedit(struct ctlpos *cp, char *stext, * its left. */ void staticddl(struct ctlpos *cp, char *stext, - int sid, int lid, int percentlist) + int sid, int lid, int percentlist) { const int height = (COMBOHEIGHT > STATICHEIGHT ? - COMBOHEIGHT : STATICHEIGHT); + COMBOHEIGHT : STATICHEIGHT); RECT r; int lwid, rwid, rpos; rpos = - GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100; + GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100; lwid = rpos - 2 * GAPBETWEEN; rwid = cp->width + GAPBETWEEN - rpos; @@ -672,8 +672,8 @@ void staticddl(struct ctlpos *cp, char *stext, r.right = rwid; r.bottom = COMBOHEIGHT*4; doctl(cp, r, "COMBOBOX", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | - CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | + CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); cp->ypos += height + GAPBETWEEN; } @@ -682,15 +682,15 @@ void staticddl(struct ctlpos *cp, char *stext, * A combo box on the right hand side, with a static to its left. */ void staticcombo(struct ctlpos *cp, char *stext, - int sid, int lid, int percentlist) + int sid, int lid, int percentlist) { const int height = (COMBOHEIGHT > STATICHEIGHT ? - COMBOHEIGHT : STATICHEIGHT); + COMBOHEIGHT : STATICHEIGHT); RECT r; int lwid, rwid, rpos; rpos = - GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100; + GAPBETWEEN + (100 - percentlist) * (cp->width + GAPBETWEEN) / 100; lwid = rpos - 2 * GAPBETWEEN; rwid = cp->width + GAPBETWEEN - rpos; @@ -705,8 +705,8 @@ void staticcombo(struct ctlpos *cp, char *stext, r.right = rwid; r.bottom = COMBOHEIGHT*10; doctl(cp, r, "COMBOBOX", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | - CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | + CBS_DROPDOWN | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); cp->ypos += height + GAPBETWEEN; } @@ -715,17 +715,17 @@ void staticcombo(struct ctlpos *cp, char *stext, * A static, with a full-width drop-down list box below it. */ void staticddlbig(struct ctlpos *cp, char *stext, - int sid, int lid) + int sid, int lid) { RECT r; if (stext) { - r.left = GAPBETWEEN; - r.top = cp->ypos; - r.right = cp->width; - r.bottom = STATICHEIGHT; - doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid); - cp->ypos += STATICHEIGHT; + r.left = GAPBETWEEN; + r.top = cp->ypos; + r.right = cp->width; + r.bottom = STATICHEIGHT; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid); + cp->ypos += STATICHEIGHT; } r.left = GAPBETWEEN; @@ -733,8 +733,8 @@ void staticddlbig(struct ctlpos *cp, char *stext, r.right = cp->width; r.bottom = COMBOHEIGHT*4; doctl(cp, r, "COMBOBOX", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | - CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | + CBS_DROPDOWNLIST | CBS_HASSTRINGS, WS_EX_CLIENTEDGE, "", lid); cp->ypos += COMBOHEIGHT + GAPBETWEEN; } @@ -742,17 +742,17 @@ void staticddlbig(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; if (stext) { - 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 = STATICHEIGHT; + cp->ypos += r.bottom + GAPWITHIN; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid); } r.left = GAPBETWEEN; @@ -761,25 +761,25 @@ void bigeditctrl(struct ctlpos *cp, char *stext, 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 list box with a static labelling it. */ void listbox(struct ctlpos *cp, char *stext, - int sid, int lid, int lines, bool multi) + int sid, int lid, int lines, bool multi) { RECT r; if (stext != NULL) { - 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 = STATICHEIGHT; + cp->ypos += r.bottom + GAPWITHIN; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid); } r.left = GAPBETWEEN; @@ -788,10 +788,10 @@ void listbox(struct ctlpos *cp, char *stext, r.bottom = LISTHEIGHT + (lines - 1) * LISTINCREMENT; cp->ypos += r.bottom + GAPBETWEEN; doctl(cp, r, "LISTBOX", - WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | - LBS_NOTIFY | LBS_HASSTRINGS | LBS_USETABSTOPS | - (multi ? LBS_MULTIPLESEL : 0), - WS_EX_CLIENTEDGE, "", lid); + WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | + LBS_NOTIFY | LBS_HASSTRINGS | LBS_USETABSTOPS | + (multi ? LBS_MULTIPLESEL : 0), + WS_EX_CLIENTEDGE, "", lid); } /* @@ -800,7 +800,7 @@ void listbox(struct ctlpos *cp, char *stext, 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; @@ -823,8 +823,8 @@ void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id) 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; @@ -833,7 +833,7 @@ void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id) r.right = cp->width; r.bottom = 2; doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE | SS_ETCHEDHORZ, - 0, "", s2id); + 0, "", s2id); } /* @@ -841,10 +841,10 @@ void ersatztab(struct ctlpos *cp, char *stext, int sid, int lid, int s2id) * 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; @@ -864,16 +864,16 @@ void editbutton(struct ctlpos *cp, char *stext, int sid, 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; doctl(cp, r, "BUTTON", - BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, - 0, btext, bid); + BS_NOTIFY | WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON, + 0, btext, bid); cp->ypos += height + GAPBETWEEN; } @@ -884,7 +884,7 @@ void editbutton(struct ctlpos *cp, char *stext, int sid, * XXX: this is a rough hack and could be improved. */ void prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines, - char *stext, int sid, int listid, int upbid, int dnbid) + char *stext, int sid, int listid, int upbid, int dnbid) { const static int percents[] = { 5, 75, 20 }; RECT r; @@ -900,20 +900,20 @@ void prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines, /* The static label. */ if (stext != NULL) { - 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 = STATICHEIGHT; + cp->ypos += r.bottom + GAPWITHIN; + doctl(cp, r, "STATIC", WS_CHILD | WS_VISIBLE, 0, stext, sid); } if (listheight > BTNSHEIGHT) { totalheight = listheight; - buttonpos = (listheight - BTNSHEIGHT) / 2; + buttonpos = (listheight - BTNSHEIGHT) / 2; } else { totalheight = BTNSHEIGHT; - buttonpos = 0; + buttonpos = 0; } for (i=0; i<3; i++) { @@ -933,22 +933,22 @@ void prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines, HWND ctl; ctl = doctl(cp, r, "LISTBOX", WS_CHILD | WS_VISIBLE | WS_TABSTOP | - WS_VSCROLL | LBS_HASSTRINGS | LBS_USETABSTOPS, + WS_VSCROLL | LBS_HASSTRINGS | LBS_USETABSTOPS, WS_EX_CLIENTEDGE, "", listid); - p_MakeDragList(ctl); + p_MakeDragList(ctl); } break; case 2: /* The "Up" and "Down" buttons. */ - /* XXX worry about accelerators if we have more than one - * prefslist on a panel */ + /* XXX worry about accelerators if we have more than one + * prefslist on a panel */ r.left = left; r.right = wid; r.top = cp->ypos + buttonpos; r.bottom = PUSHBTNHEIGHT; doctl(cp, r, "BUTTON", BS_NOTIFY | WS_CHILD | WS_VISIBLE | - WS_TABSTOP | BS_PUSHBUTTON, + WS_TABSTOP | BS_PUSHBUTTON, 0, "&Up", upbid); r.left = left; r.right = wid; @@ -956,7 +956,7 @@ void prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines, r.bottom = PUSHBTNHEIGHT; doctl(cp, r, "BUTTON", BS_NOTIFY | WS_CHILD | WS_VISIBLE | - WS_TABSTOP | BS_PUSHBUTTON, + WS_TABSTOP | BS_PUSHBUTTON, 0, "&Down", dnbid); break; @@ -986,9 +986,9 @@ static void pl_moveitem(HWND hwnd, int listid, int src, int dst) SendDlgItemMessage (hwnd, listid, LB_DELETESTRING, src, 0); /* Insert it at new location. */ SendDlgItemMessage (hwnd, listid, LB_INSERTSTRING, dst, - (LPARAM) txt); + (LPARAM) txt); SendDlgItemMessage (hwnd, listid, LB_SETITEMDATA, dst, - (LPARAM) val); + (LPARAM) val); /* Set selection. */ SendDlgItemMessage (hwnd, listid, LB_SETCURSEL, dst, 0); sfree (txt); @@ -1013,28 +1013,28 @@ int pl_itemfrompt(HWND hwnd, POINT cursor, bool scroll) */ ret = p_LBItemFromPt(hwnd, cursor, scroll); if (ret == -1) - return ret; + return ret; ret = p_LBItemFromPt(hwnd, cursor, false); updist = downdist = 0; for (i = 1; i < 4096 && (!updist || !downdist); i++) { - uppoint = downpoint = cursor; - uppoint.y -= i; - downpoint.y += i; - upitem = p_LBItemFromPt(hwnd, uppoint, false); - downitem = p_LBItemFromPt(hwnd, downpoint, false); - if (!updist && upitem != ret) - updist = i; - if (!downdist && downitem != ret) - downdist = i; + uppoint = downpoint = cursor; + uppoint.y -= i; + downpoint.y += i; + upitem = p_LBItemFromPt(hwnd, uppoint, false); + downitem = p_LBItemFromPt(hwnd, downpoint, false); + if (!updist && upitem != ret) + updist = i; + if (!downdist && downitem != ret) + downdist = i; } if (downdist < updist) - ret++; + ret++; return ret; } /* * Handler for prefslist above. - * + * * Return value has bit 0 set if the dialog box procedure needs to * return true from handling this message; it has bit 1 set if a * change may have been made in the contents of the list. @@ -1042,7 +1042,7 @@ int pl_itemfrompt(HWND hwnd, POINT cursor, bool scroll) int handle_prefslist(struct prefslist *hdl, int *array, int maxmemb, bool is_dlmsg, HWND hwnd, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { int i; int ret = 0; @@ -1051,55 +1051,55 @@ int handle_prefslist(struct prefslist *hdl, if ((int)wParam == hdl->listid) { DRAGLISTINFO *dlm = (DRAGLISTINFO *)lParam; - int dest = 0; /* initialise to placate gcc */ + int dest = 0; /* initialise to placate gcc */ switch (dlm->uNotification) { case DL_BEGINDRAG: - /* Add a dummy item to make pl_itemfrompt() work - * better. - * FIXME: this causes scrollbar glitches if the count of - * listbox contains >= its height. */ - hdl->dummyitem = - SendDlgItemMessage(hwnd, hdl->listid, - LB_ADDSTRING, 0, (LPARAM) ""); + /* Add a dummy item to make pl_itemfrompt() work + * better. + * FIXME: this causes scrollbar glitches if the count of + * listbox contains >= its height. */ + hdl->dummyitem = + SendDlgItemMessage(hwnd, hdl->listid, + LB_ADDSTRING, 0, (LPARAM) ""); hdl->srcitem = p_LBItemFromPt(dlm->hWnd, dlm->ptCursor, true); - hdl->dragging = false; - /* XXX hack Q183115 */ - SetWindowLongPtr(hwnd, DWLP_MSGRESULT, true); + hdl->dragging = false; + /* XXX hack Q183115 */ + SetWindowLongPtr(hwnd, DWLP_MSGRESULT, true); ret |= 1; break; case DL_CANCELDRAG: - p_DrawInsert(hwnd, dlm->hWnd, -1); /* Clear arrow */ - SendDlgItemMessage(hwnd, hdl->listid, - LB_DELETESTRING, hdl->dummyitem, 0); - hdl->dragging = false; + p_DrawInsert(hwnd, dlm->hWnd, -1); /* Clear arrow */ + SendDlgItemMessage(hwnd, hdl->listid, + LB_DELETESTRING, hdl->dummyitem, 0); + hdl->dragging = false; ret |= 1; break; case DL_DRAGGING: - hdl->dragging = true; - dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, true); - if (dest > hdl->dummyitem) dest = hdl->dummyitem; - p_DrawInsert (hwnd, dlm->hWnd, dest); - if (dest >= 0) - SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_MOVECURSOR); - else - SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_STOPCURSOR); + hdl->dragging = true; + dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, true); + if (dest > hdl->dummyitem) dest = hdl->dummyitem; + p_DrawInsert (hwnd, dlm->hWnd, dest); + if (dest >= 0) + SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_MOVECURSOR); + else + SetWindowLongPtr(hwnd, DWLP_MSGRESULT, DL_STOPCURSOR); ret |= 1; break; case DL_DROPPED: - if (hdl->dragging) { - dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, true); - if (dest > hdl->dummyitem) dest = hdl->dummyitem; - p_DrawInsert (hwnd, dlm->hWnd, -1); - } - SendDlgItemMessage(hwnd, hdl->listid, - LB_DELETESTRING, hdl->dummyitem, 0); - if (hdl->dragging) { - hdl->dragging = false; - if (dest >= 0) { - /* Correct for "missing" item. */ - if (dest > hdl->srcitem) dest--; - pl_moveitem(hwnd, hdl->listid, hdl->srcitem, dest); - } - ret |= 2; - } + if (hdl->dragging) { + dest = pl_itemfrompt(dlm->hWnd, dlm->ptCursor, true); + if (dest > hdl->dummyitem) dest = hdl->dummyitem; + p_DrawInsert (hwnd, dlm->hWnd, -1); + } + SendDlgItemMessage(hwnd, hdl->listid, + LB_DELETESTRING, hdl->dummyitem, 0); + if (hdl->dragging) { + hdl->dragging = false; + if (dest >= 0) { + /* Correct for "missing" item. */ + if (dest > hdl->srcitem) dest--; + pl_moveitem(hwnd, hdl->listid, hdl->srcitem, dest); + } + ret |= 2; + } ret |= 1; break; } } @@ -1120,11 +1120,11 @@ int handle_prefslist(struct prefslist *hdl, /* Get the total number of items. */ nitems = SendDlgItemMessage (hwnd, hdl->listid, LB_GETCOUNT, 0, 0); /* Should we do anything? */ - if (LOWORD(wParam) == hdl->upbid && (selection > 0)) - pl_moveitem(hwnd, hdl->listid, selection, selection - 1); - else if (LOWORD(wParam) == hdl->dnbid && (selection < nitems - 1)) - pl_moveitem(hwnd, hdl->listid, selection, selection + 1); - ret |= 2; + if (LOWORD(wParam) == hdl->upbid && (selection > 0)) + pl_moveitem(hwnd, hdl->listid, selection, selection - 1); + else if (LOWORD(wParam) == hdl->dnbid && (selection < nitems - 1)) + pl_moveitem(hwnd, hdl->listid, selection, selection + 1); + ret |= 2; } } @@ -1132,10 +1132,10 @@ int handle_prefslist(struct prefslist *hdl, } if (array) { - /* Update array to match the list box. */ - for (i=0; i < maxmemb; i++) - array[i] = SendDlgItemMessage (hwnd, hdl->listid, LB_GETITEMDATA, - i, 0); + /* Update array to match the list box. */ + for (i=0; i < maxmemb; i++) + array[i] = SendDlgItemMessage (hwnd, hdl->listid, LB_GETITEMDATA, + i, 0); } return ret; @@ -1158,9 +1158,9 @@ void progressbar(struct ctlpos *cp, int id) 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); } /* ---------------------------------------------------------------------- @@ -1172,7 +1172,7 @@ void progressbar(struct ctlpos *cp, int id) * places a single (unescaped) ampersand in front of the first * occurrence of the given shortcut character (which may be * NO_SHORTCUT). - * + * * Return value is a malloc'ed copy of the processed version of the * string. */ @@ -1183,7 +1183,7 @@ static char *shortcut_escape(const char *text, char shortcut) char *q; if (!text) - return NULL; /* sfree won't choke on this */ + return NULL; /* sfree won't choke on this */ ret = snewn(2*strlen(text)+1, char); /* size potentially doubles! */ shortcut = tolower((unsigned char)shortcut); @@ -1191,14 +1191,14 @@ static char *shortcut_escape(const char *text, char shortcut) p = text; q = ret; while (*p) { - if (shortcut != NO_SHORTCUT && - tolower((unsigned char)*p) == shortcut) { - *q++ = '&'; - shortcut = NO_SHORTCUT; /* stop it happening twice */ - } else if (*p == '&') { - *q++ = '&'; - } - *q++ = *p++; + if (shortcut != NO_SHORTCUT && + tolower((unsigned char)*p) == shortcut) { + *q++ = '&'; + shortcut = NO_SHORTCUT; /* stop it happening twice */ + } else if (*p == '&') { + *q++ = '&'; + } + *q++ = *p++; } *q = '\0'; return ret; @@ -1208,22 +1208,22 @@ void winctrl_add_shortcuts(struct dlgparam *dp, struct winctrl *c) { int i; for (i = 0; i < lenof(c->shortcuts); i++) - if (c->shortcuts[i] != NO_SHORTCUT) { - unsigned char s = tolower((unsigned char)c->shortcuts[i]); - assert(!dp->shortcuts[s]); - dp->shortcuts[s] = true; - } + if (c->shortcuts[i] != NO_SHORTCUT) { + unsigned char s = tolower((unsigned char)c->shortcuts[i]); + assert(!dp->shortcuts[s]); + dp->shortcuts[s] = true; + } } void winctrl_rem_shortcuts(struct dlgparam *dp, struct winctrl *c) { int i; for (i = 0; i < lenof(c->shortcuts); i++) - if (c->shortcuts[i] != NO_SHORTCUT) { - unsigned char s = tolower((unsigned char)c->shortcuts[i]); - assert(dp->shortcuts[s]); - dp->shortcuts[s] = false; - } + if (c->shortcuts[i] != NO_SHORTCUT) { + unsigned char s = tolower((unsigned char)c->shortcuts[i]); + assert(dp->shortcuts[s]); + dp->shortcuts[s] = false; + } } static int winctrl_cmp_byctrl(void *av, void *bv) @@ -1231,44 +1231,44 @@ static int winctrl_cmp_byctrl(void *av, void *bv) struct winctrl *a = (struct winctrl *)av; struct winctrl *b = (struct winctrl *)bv; if (a->ctrl < b->ctrl) - return -1; + return -1; else if (a->ctrl > b->ctrl) - return +1; + return +1; else - return 0; + return 0; } static int winctrl_cmp_byid(void *av, void *bv) { struct winctrl *a = (struct winctrl *)av; struct winctrl *b = (struct winctrl *)bv; if (a->base_id < b->base_id) - return -1; + return -1; else if (a->base_id > b->base_id) - return +1; + return +1; else - return 0; + return 0; } static int winctrl_cmp_byctrl_find(void *av, void *bv) { union control *a = (union control *)av; struct winctrl *b = (struct winctrl *)bv; if (a < b->ctrl) - return -1; + return -1; else if (a > b->ctrl) - return +1; + return +1; else - return 0; + return 0; } static int winctrl_cmp_byid_find(void *av, void *bv) { int *a = (int *)av; struct winctrl *b = (struct winctrl *)bv; if (*a < b->base_id) - return -1; + return -1; else if (*a >= b->base_id + b->num_ids) - return +1; + return +1; else - return 0; + return 0; } void winctrl_init(struct winctrls *wc) @@ -1281,9 +1281,9 @@ void winctrl_cleanup(struct winctrls *wc) struct winctrl *c; while ((c = index234(wc->byid, 0)) != NULL) { - winctrl_remove(wc, c); - sfree(c->data); - sfree(c); + winctrl_remove(wc, c); + sfree(c->data); + sfree(c); } freetree234(wc->byctrl); @@ -1295,8 +1295,8 @@ void winctrl_add(struct winctrls *wc, struct winctrl *c) { struct winctrl *ret; if (c->ctrl) { - ret = add234(wc->byctrl, c); - assert(ret == c); + ret = add234(wc->byctrl, c); + assert(ret == c); } ret = add234(wc->byid, c); assert(ret == c); @@ -1326,7 +1326,7 @@ struct winctrl *winctrl_findbyindex(struct winctrls *wc, int index) } void winctrl_layout(struct dlgparam *dp, struct winctrls *wc, - struct ctlpos *cp, struct controlset *s, int *id) + struct ctlpos *cp, struct controlset *s, int *id) { struct ctlpos columns[16]; int ncols, colstart, colspan; @@ -1347,352 +1347,352 @@ void winctrl_layout(struct dlgparam *dp, struct winctrls *wc, /* Start a containing box, if we have a boxname. */ if (s->boxname && *s->boxname) { - struct winctrl *c = snew(struct winctrl); - c->ctrl = NULL; - c->base_id = base_id; - c->num_ids = 1; - c->data = NULL; - memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts)); - winctrl_add(wc, c); - beginbox(cp, s->boxtitle, base_id); - base_id++; + struct winctrl *c = snew(struct winctrl); + c->ctrl = NULL; + c->base_id = base_id; + c->num_ids = 1; + c->data = NULL; + memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts)); + winctrl_add(wc, c); + beginbox(cp, s->boxtitle, base_id); + base_id++; } /* Draw a title, if we have one. */ if (!s->boxname && s->boxtitle) { - struct winctrl *c = snew(struct winctrl); - c->ctrl = NULL; - c->base_id = base_id; - c->num_ids = 1; - c->data = dupstr(s->boxtitle); - memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts)); - winctrl_add(wc, c); - paneltitle(cp, base_id); - base_id++; + struct winctrl *c = snew(struct winctrl); + c->ctrl = NULL; + c->base_id = base_id; + c->num_ids = 1; + c->data = dupstr(s->boxtitle); + memset(c->shortcuts, NO_SHORTCUT, lenof(c->shortcuts)); + winctrl_add(wc, c); + paneltitle(cp, base_id); + base_id++; } /* Initially we have just one column. */ ncols = 1; - columns[0] = *cp; /* structure copy */ + columns[0] = *cp; /* structure copy */ /* And initially, there are no pending tab-delayed controls. */ ntabdelays = 0; /* Loop over each control in the controlset. */ for (i = 0; i < s->ncontrols; i++) { - union control *ctrl = s->ctrls[i]; + union control *ctrl = s->ctrls[i]; - /* - * Generic processing that pertains to all control types. - * At the end of this if statement, we'll have produced - * `ctrl' (a pointer to the control we have to create, or - * think about creating, in this iteration of the loop), - * `pos' (a suitable ctlpos with which to position it), and - * `c' (a winctrl structure to receive details of the - * dialog IDs). Or we'll have done a `continue', if it was - * CTRL_COLUMNS and doesn't require any control creation at - * all. - */ - if (ctrl->generic.type == CTRL_COLUMNS) { - assert((ctrl->columns.ncols == 1) ^ (ncols == 1)); + /* + * Generic processing that pertains to all control types. + * At the end of this if statement, we'll have produced + * `ctrl' (a pointer to the control we have to create, or + * think about creating, in this iteration of the loop), + * `pos' (a suitable ctlpos with which to position it), and + * `c' (a winctrl structure to receive details of the + * dialog IDs). Or we'll have done a `continue', if it was + * CTRL_COLUMNS and doesn't require any control creation at + * all. + */ + if (ctrl->generic.type == CTRL_COLUMNS) { + assert((ctrl->columns.ncols == 1) ^ (ncols == 1)); - if (ncols == 1) { - /* - * We're splitting into multiple columns. - */ - int lpercent, rpercent, lx, rx, i; + if (ncols == 1) { + /* + * We're splitting into multiple columns. + */ + int lpercent, rpercent, lx, rx, i; - ncols = ctrl->columns.ncols; - assert(ncols <= lenof(columns)); - for (i = 1; i < ncols; i++) - columns[i] = columns[0]; /* structure copy */ + ncols = ctrl->columns.ncols; + assert(ncols <= lenof(columns)); + for (i = 1; i < ncols; i++) + columns[i] = columns[0]; /* structure copy */ - lpercent = 0; - for (i = 0; i < ncols; i++) { - rpercent = lpercent + ctrl->columns.percentages[i]; - lx = columns[i].xoff + lpercent * - (columns[i].width + GAPBETWEEN) / 100; - rx = columns[i].xoff + rpercent * - (columns[i].width + GAPBETWEEN) / 100; - columns[i].xoff = lx; - columns[i].width = rx - lx - GAPBETWEEN; - lpercent = rpercent; - } - } else { - /* - * We're recombining the various columns into one. - */ - int maxy = columns[0].ypos; - int i; - for (i = 1; i < ncols; i++) - if (maxy < columns[i].ypos) - maxy = columns[i].ypos; - ncols = 1; - columns[0] = *cp; /* structure copy */ - columns[0].ypos = maxy; - } + lpercent = 0; + for (i = 0; i < ncols; i++) { + rpercent = lpercent + ctrl->columns.percentages[i]; + lx = columns[i].xoff + lpercent * + (columns[i].width + GAPBETWEEN) / 100; + rx = columns[i].xoff + rpercent * + (columns[i].width + GAPBETWEEN) / 100; + columns[i].xoff = lx; + columns[i].width = rx - lx - GAPBETWEEN; + lpercent = rpercent; + } + } else { + /* + * We're recombining the various columns into one. + */ + int maxy = columns[0].ypos; + int i; + for (i = 1; i < ncols; i++) + if (maxy < columns[i].ypos) + maxy = columns[i].ypos; + ncols = 1; + columns[0] = *cp; /* structure copy */ + columns[0].ypos = maxy; + } - continue; - } else if (ctrl->generic.type == CTRL_TABDELAY) { - int i; + continue; + } else if (ctrl->generic.type == CTRL_TABDELAY) { + int i; - assert(!ctrl->generic.tabdelay); - ctrl = ctrl->tabdelay.ctrl; + assert(!ctrl->generic.tabdelay); + ctrl = ctrl->tabdelay.ctrl; - for (i = 0; i < ntabdelays; i++) - if (tabdelayed[i] == ctrl) - break; - assert(i < ntabdelays); /* we have to have found it */ + for (i = 0; i < ntabdelays; i++) + if (tabdelayed[i] == ctrl) + break; + assert(i < ntabdelays); /* we have to have found it */ - pos = tabdelays[i]; /* structure copy */ + pos = tabdelays[i]; /* structure copy */ - colstart = colspan = -1; /* indicate this was tab-delayed */ + colstart = colspan = -1; /* indicate this was tab-delayed */ - } else { - /* - * If it wasn't one of those, it's a genuine control; - * so we'll have to compute a position for it now, by - * checking its column span. - */ - int col; + } else { + /* + * If it wasn't one of those, it's a genuine control; + * so we'll have to compute a position for it now, by + * checking its column span. + */ + int col; - colstart = COLUMN_START(ctrl->generic.column); - colspan = COLUMN_SPAN(ctrl->generic.column); + colstart = COLUMN_START(ctrl->generic.column); + colspan = COLUMN_SPAN(ctrl->generic.column); - pos = columns[colstart]; /* structure copy */ - pos.width = columns[colstart+colspan-1].width + - (columns[colstart+colspan-1].xoff - columns[colstart].xoff); + pos = columns[colstart]; /* structure copy */ + pos.width = columns[colstart+colspan-1].width + + (columns[colstart+colspan-1].xoff - columns[colstart].xoff); - for (col = colstart; col < colstart+colspan; col++) - if (pos.ypos < columns[col].ypos) - pos.ypos = columns[col].ypos; + for (col = colstart; col < colstart+colspan; col++) + if (pos.ypos < columns[col].ypos) + pos.ypos = columns[col].ypos; - /* - * If this control is to be tabdelayed, add it to the - * tabdelay list, and unset pos.hwnd to inhibit actual - * control creation. - */ - if (ctrl->generic.tabdelay) { - assert(ntabdelays < lenof(tabdelays)); - tabdelays[ntabdelays] = pos; /* structure copy */ - tabdelayed[ntabdelays] = ctrl; - ntabdelays++; - pos.hwnd = NULL; - } - } + /* + * If this control is to be tabdelayed, add it to the + * tabdelay list, and unset pos.hwnd to inhibit actual + * control creation. + */ + if (ctrl->generic.tabdelay) { + assert(ntabdelays < lenof(tabdelays)); + tabdelays[ntabdelays] = pos; /* structure copy */ + tabdelayed[ntabdelays] = ctrl; + ntabdelays++; + pos.hwnd = NULL; + } + } - /* Most controls don't need anything in c->data. */ - data = NULL; + /* Most controls don't need anything in c->data. */ + data = NULL; - /* And they all start off with no shortcuts registered. */ - memset(shortcuts, NO_SHORTCUT, lenof(shortcuts)); - nshortcuts = 0; + /* And they all start off with no shortcuts registered. */ + memset(shortcuts, NO_SHORTCUT, lenof(shortcuts)); + nshortcuts = 0; - /* Almost all controls start at base_id. */ - actual_base_id = base_id; + /* Almost all controls start at base_id. */ + actual_base_id = base_id; - /* - * Now we're ready to actually create the control, by - * switching on its type. - */ - switch (ctrl->generic.type) { - case CTRL_TEXT: - { - char *wrapped, *escaped; - int lines; - num_ids = 1; - wrapped = staticwrap(&pos, cp->hwnd, - ctrl->generic.label, &lines); - escaped = shortcut_escape(wrapped, NO_SHORTCUT); - statictext(&pos, escaped, lines, base_id); - sfree(escaped); - sfree(wrapped); - } - break; - case CTRL_EDITBOX: - num_ids = 2; /* static, edit */ - escaped = shortcut_escape(ctrl->editbox.label, - ctrl->editbox.shortcut); - shortcuts[nshortcuts++] = ctrl->editbox.shortcut; - if (ctrl->editbox.percentwidth == 100) { - if (ctrl->editbox.has_list) - combobox(&pos, escaped, - base_id, base_id+1); - else - editboxfw(&pos, ctrl->editbox.password, escaped, - base_id, base_id+1); - } else { - if (ctrl->editbox.has_list) { - staticcombo(&pos, escaped, base_id, base_id+1, - ctrl->editbox.percentwidth); - } else { - (ctrl->editbox.password ? staticpassedit : staticedit) - (&pos, escaped, base_id, base_id+1, - ctrl->editbox.percentwidth); - } - } - sfree(escaped); - break; - case CTRL_RADIO: - num_ids = ctrl->radio.nbuttons + 1; /* label as well */ - { - struct radio *buttons; - int i; + /* + * Now we're ready to actually create the control, by + * switching on its type. + */ + switch (ctrl->generic.type) { + case CTRL_TEXT: + { + char *wrapped, *escaped; + int lines; + num_ids = 1; + wrapped = staticwrap(&pos, cp->hwnd, + ctrl->generic.label, &lines); + escaped = shortcut_escape(wrapped, NO_SHORTCUT); + statictext(&pos, escaped, lines, base_id); + sfree(escaped); + sfree(wrapped); + } + break; + case CTRL_EDITBOX: + num_ids = 2; /* static, edit */ + escaped = shortcut_escape(ctrl->editbox.label, + ctrl->editbox.shortcut); + shortcuts[nshortcuts++] = ctrl->editbox.shortcut; + if (ctrl->editbox.percentwidth == 100) { + if (ctrl->editbox.has_list) + combobox(&pos, escaped, + base_id, base_id+1); + else + editboxfw(&pos, ctrl->editbox.password, escaped, + base_id, base_id+1); + } else { + if (ctrl->editbox.has_list) { + staticcombo(&pos, escaped, base_id, base_id+1, + ctrl->editbox.percentwidth); + } else { + (ctrl->editbox.password ? staticpassedit : staticedit) + (&pos, escaped, base_id, base_id+1, + ctrl->editbox.percentwidth); + } + } + sfree(escaped); + break; + case CTRL_RADIO: + num_ids = ctrl->radio.nbuttons + 1; /* label as well */ + { + struct radio *buttons; + int i; - escaped = shortcut_escape(ctrl->radio.label, - ctrl->radio.shortcut); - shortcuts[nshortcuts++] = ctrl->radio.shortcut; + escaped = shortcut_escape(ctrl->radio.label, + ctrl->radio.shortcut); + shortcuts[nshortcuts++] = ctrl->radio.shortcut; - buttons = snewn(ctrl->radio.nbuttons, struct radio); + buttons = snewn(ctrl->radio.nbuttons, struct radio); - for (i = 0; i < ctrl->radio.nbuttons; i++) { - buttons[i].text = - shortcut_escape(ctrl->radio.buttons[i], - (char)(ctrl->radio.shortcuts ? - ctrl->radio.shortcuts[i] : - NO_SHORTCUT)); - buttons[i].id = base_id + 1 + i; - if (ctrl->radio.shortcuts) { - assert(nshortcuts < MAX_SHORTCUTS_PER_CTRL); - shortcuts[nshortcuts++] = ctrl->radio.shortcuts[i]; - } - } + for (i = 0; i < ctrl->radio.nbuttons; i++) { + buttons[i].text = + shortcut_escape(ctrl->radio.buttons[i], + (char)(ctrl->radio.shortcuts ? + ctrl->radio.shortcuts[i] : + NO_SHORTCUT)); + buttons[i].id = base_id + 1 + i; + if (ctrl->radio.shortcuts) { + assert(nshortcuts < MAX_SHORTCUTS_PER_CTRL); + shortcuts[nshortcuts++] = ctrl->radio.shortcuts[i]; + } + } - radioline_common(&pos, escaped, base_id, - ctrl->radio.ncolumns, - buttons, ctrl->radio.nbuttons); + radioline_common(&pos, escaped, base_id, + ctrl->radio.ncolumns, + buttons, ctrl->radio.nbuttons); - for (i = 0; i < ctrl->radio.nbuttons; i++) { - sfree(buttons[i].text); - } - sfree(buttons); - sfree(escaped); - } - break; - case CTRL_CHECKBOX: - num_ids = 1; - escaped = shortcut_escape(ctrl->checkbox.label, - ctrl->checkbox.shortcut); - shortcuts[nshortcuts++] = ctrl->checkbox.shortcut; - checkbox(&pos, escaped, base_id); - sfree(escaped); - break; - case CTRL_BUTTON: - escaped = shortcut_escape(ctrl->button.label, - ctrl->button.shortcut); - shortcuts[nshortcuts++] = ctrl->button.shortcut; - if (ctrl->button.iscancel) - actual_base_id = IDCANCEL; - num_ids = 1; - button(&pos, escaped, actual_base_id, ctrl->button.isdefault); - sfree(escaped); - break; - case CTRL_LISTBOX: - num_ids = 2; - escaped = shortcut_escape(ctrl->listbox.label, - ctrl->listbox.shortcut); - shortcuts[nshortcuts++] = ctrl->listbox.shortcut; - if (ctrl->listbox.draglist) { - data = snew(struct prefslist); - num_ids = 4; - prefslist(data, &pos, ctrl->listbox.height, escaped, - base_id, base_id+1, base_id+2, base_id+3); - shortcuts[nshortcuts++] = 'u'; /* Up */ - shortcuts[nshortcuts++] = 'd'; /* Down */ - } else if (ctrl->listbox.height == 0) { - /* Drop-down list. */ - if (ctrl->listbox.percentwidth == 100) { - staticddlbig(&pos, escaped, - base_id, base_id+1); - } else { - staticddl(&pos, escaped, base_id, - base_id+1, ctrl->listbox.percentwidth); - } - } else { - /* Ordinary list. */ - listbox(&pos, escaped, base_id, base_id+1, - ctrl->listbox.height, ctrl->listbox.multisel); - } - if (ctrl->listbox.ncols) { - /* - * This method of getting the box width is a bit of - * a hack; we'd do better to try to retrieve the - * actual width in dialog units from doctl() just - * before MapDialogRect. But that's going to be no - * fun, and this should be good enough accuracy. - */ - int width = cp->width * ctrl->listbox.percentwidth; - int *tabarray; - int i, percent; + for (i = 0; i < ctrl->radio.nbuttons; i++) { + sfree(buttons[i].text); + } + sfree(buttons); + sfree(escaped); + } + break; + case CTRL_CHECKBOX: + num_ids = 1; + escaped = shortcut_escape(ctrl->checkbox.label, + ctrl->checkbox.shortcut); + shortcuts[nshortcuts++] = ctrl->checkbox.shortcut; + checkbox(&pos, escaped, base_id); + sfree(escaped); + break; + case CTRL_BUTTON: + escaped = shortcut_escape(ctrl->button.label, + ctrl->button.shortcut); + shortcuts[nshortcuts++] = ctrl->button.shortcut; + if (ctrl->button.iscancel) + actual_base_id = IDCANCEL; + num_ids = 1; + button(&pos, escaped, actual_base_id, ctrl->button.isdefault); + sfree(escaped); + break; + case CTRL_LISTBOX: + num_ids = 2; + escaped = shortcut_escape(ctrl->listbox.label, + ctrl->listbox.shortcut); + shortcuts[nshortcuts++] = ctrl->listbox.shortcut; + if (ctrl->listbox.draglist) { + data = snew(struct prefslist); + num_ids = 4; + prefslist(data, &pos, ctrl->listbox.height, escaped, + base_id, base_id+1, base_id+2, base_id+3); + shortcuts[nshortcuts++] = 'u'; /* Up */ + shortcuts[nshortcuts++] = 'd'; /* Down */ + } else if (ctrl->listbox.height == 0) { + /* Drop-down list. */ + if (ctrl->listbox.percentwidth == 100) { + staticddlbig(&pos, escaped, + base_id, base_id+1); + } else { + staticddl(&pos, escaped, base_id, + base_id+1, ctrl->listbox.percentwidth); + } + } else { + /* Ordinary list. */ + listbox(&pos, escaped, base_id, base_id+1, + ctrl->listbox.height, ctrl->listbox.multisel); + } + if (ctrl->listbox.ncols) { + /* + * This method of getting the box width is a bit of + * a hack; we'd do better to try to retrieve the + * actual width in dialog units from doctl() just + * before MapDialogRect. But that's going to be no + * fun, and this should be good enough accuracy. + */ + int width = cp->width * ctrl->listbox.percentwidth; + int *tabarray; + int i, percent; - tabarray = snewn(ctrl->listbox.ncols-1, int); - percent = 0; - for (i = 0; i < ctrl->listbox.ncols-1; i++) { - percent += ctrl->listbox.percentages[i]; - tabarray[i] = width * percent / 10000; - } - SendDlgItemMessage(cp->hwnd, base_id+1, LB_SETTABSTOPS, - ctrl->listbox.ncols-1, (LPARAM)tabarray); - sfree(tabarray); - } - sfree(escaped); - break; - case CTRL_FILESELECT: - num_ids = 3; - escaped = shortcut_escape(ctrl->fileselect.label, - ctrl->fileselect.shortcut); - shortcuts[nshortcuts++] = ctrl->fileselect.shortcut; - editbutton(&pos, escaped, base_id, base_id+1, - "Bro&wse...", base_id+2); - shortcuts[nshortcuts++] = 'w'; - sfree(escaped); - break; - case CTRL_FONTSELECT: - num_ids = 3; - escaped = shortcut_escape(ctrl->fontselect.label, - ctrl->fontselect.shortcut); - shortcuts[nshortcuts++] = ctrl->fontselect.shortcut; - statictext(&pos, escaped, 1, base_id); - staticbtn(&pos, "", base_id+1, "Change...", base_id+2); + tabarray = snewn(ctrl->listbox.ncols-1, int); + percent = 0; + for (i = 0; i < ctrl->listbox.ncols-1; i++) { + percent += ctrl->listbox.percentages[i]; + tabarray[i] = width * percent / 10000; + } + SendDlgItemMessage(cp->hwnd, base_id+1, LB_SETTABSTOPS, + ctrl->listbox.ncols-1, (LPARAM)tabarray); + sfree(tabarray); + } + sfree(escaped); + break; + case CTRL_FILESELECT: + num_ids = 3; + escaped = shortcut_escape(ctrl->fileselect.label, + ctrl->fileselect.shortcut); + shortcuts[nshortcuts++] = ctrl->fileselect.shortcut; + editbutton(&pos, escaped, base_id, base_id+1, + "Bro&wse...", base_id+2); + shortcuts[nshortcuts++] = 'w'; + sfree(escaped); + break; + case CTRL_FONTSELECT: + num_ids = 3; + escaped = shortcut_escape(ctrl->fontselect.label, + ctrl->fontselect.shortcut); + shortcuts[nshortcuts++] = ctrl->fontselect.shortcut; + statictext(&pos, escaped, 1, base_id); + staticbtn(&pos, "", base_id+1, "Change...", base_id+2); data = fontspec_new("", false, 0, 0); - sfree(escaped); - break; - default: - assert(!"Can't happen"); - num_ids = 0; /* placate gcc */ - break; - } + sfree(escaped); + break; + default: + assert(!"Can't happen"); + num_ids = 0; /* placate gcc */ + break; + } - /* - * Create a `struct winctrl' for this control, and advance - * the dialog ID counter, if it's actually been created - * (and isn't tabdelayed). - */ - if (pos.hwnd) { - struct winctrl *c = snew(struct winctrl); + /* + * Create a `struct winctrl' for this control, and advance + * the dialog ID counter, if it's actually been created + * (and isn't tabdelayed). + */ + if (pos.hwnd) { + struct winctrl *c = snew(struct winctrl); - c->ctrl = ctrl; - c->base_id = actual_base_id; - c->num_ids = num_ids; - c->data = data; - memcpy(c->shortcuts, shortcuts, sizeof(shortcuts)); - winctrl_add(wc, c); - winctrl_add_shortcuts(dp, c); - if (actual_base_id == base_id) - base_id += num_ids; - } else { + c->ctrl = ctrl; + c->base_id = actual_base_id; + c->num_ids = num_ids; + c->data = data; + memcpy(c->shortcuts, shortcuts, sizeof(shortcuts)); + winctrl_add(wc, c); + winctrl_add_shortcuts(dp, c); + if (actual_base_id == base_id) + base_id += num_ids; + } else { sfree(data); } - if (colstart >= 0) { - /* - * Update the ypos in all columns crossed by this - * control. - */ - int i; - for (i = colstart; i < colstart+colspan; i++) - columns[i].ypos = pos.ypos; - } + if (colstart >= 0) { + /* + * Update the ypos in all columns crossed by this + * control. + */ + int i; + for (i = colstart; i < colstart+colspan; i++) + columns[i].ypos = pos.ypos; + } } /* @@ -1701,24 +1701,24 @@ void winctrl_layout(struct dlgparam *dp, struct winctrls *wc, * any containing box, and return. */ for (i = 0; i < ncols; i++) - if (cp->ypos < columns[i].ypos) - cp->ypos = columns[i].ypos; + if (cp->ypos < columns[i].ypos) + cp->ypos = columns[i].ypos; *id = base_id; if (s->boxname && *s->boxname) - endbox(cp); + endbox(cp); } static void winctrl_set_focus(union control *ctrl, struct dlgparam *dp, - bool has_focus) + bool has_focus) { if (has_focus) { - if (dp->focused) - dp->lastfocused = dp->focused; - dp->focused = ctrl; + if (dp->focused) + dp->lastfocused = dp->focused; + dp->focused = ctrl; } else if (!has_focus && dp->focused == ctrl) { - dp->lastfocused = dp->focused; - dp->focused = NULL; + dp->lastfocused = dp->focused; + dp->focused = NULL; } } @@ -1745,50 +1745,50 @@ bool winctrl_handle_command(struct dlgparam *dp, UINT msg, * WM_COMMAND and the drag list message, and nothing else. */ if (draglistmsg == WM_NULL) - draglistmsg = RegisterWindowMessage (DRAGLISTMSGSTRING); + draglistmsg = RegisterWindowMessage (DRAGLISTMSGSTRING); if (msg != draglistmsg && msg != WM_COMMAND && msg != WM_DRAWITEM) - return false; + return false; /* * Look up the control ID in our data. */ c = NULL; for (i = 0; i < dp->nctrltrees; i++) { - c = winctrl_findbyid(dp->controltrees[i], LOWORD(wParam)); - if (c) - break; + c = winctrl_findbyid(dp->controltrees[i], LOWORD(wParam)); + if (c) + break; } if (!c) - return false; /* we have nothing to do */ + return false; /* we have nothing to do */ if (msg == WM_DRAWITEM) { - /* - * Owner-draw request for a panel title. - */ - LPDRAWITEMSTRUCT di = (LPDRAWITEMSTRUCT) lParam; - HDC hdc = di->hDC; - RECT r = di->rcItem; - SIZE s; + /* + * Owner-draw request for a panel title. + */ + LPDRAWITEMSTRUCT di = (LPDRAWITEMSTRUCT) lParam; + HDC hdc = di->hDC; + RECT r = di->rcItem; + SIZE s; - SetMapMode(hdc, MM_TEXT); /* ensure logical units == pixels */ + SetMapMode(hdc, MM_TEXT); /* ensure logical units == pixels */ - GetTextExtentPoint32(hdc, (char *)c->data, - strlen((char *)c->data), &s); - DrawEdge(hdc, &r, EDGE_ETCHED, BF_ADJUST | BF_RECT); - TextOut(hdc, - r.left + (r.right-r.left-s.cx)/2, - r.top + (r.bottom-r.top-s.cy)/2, - (char *)c->data, strlen((char *)c->data)); + GetTextExtentPoint32(hdc, (char *)c->data, + strlen((char *)c->data), &s); + DrawEdge(hdc, &r, EDGE_ETCHED, BF_ADJUST | BF_RECT); + TextOut(hdc, + r.left + (r.right-r.left-s.cx)/2, + r.top + (r.bottom-r.top-s.cy)/2, + (char *)c->data, strlen((char *)c->data)); - return true; + return true; } ctrl = c->ctrl; id = LOWORD(wParam) - c->base_id; if (!ctrl || !ctrl->generic.handler) - return false; /* nothing we can do here */ + return false; /* nothing we can do here */ /* * From here on we do not issue `return' statements until the @@ -1805,186 +1805,186 @@ bool winctrl_handle_command(struct dlgparam *dp, UINT msg, */ switch (ctrl->generic.type) { case CTRL_EDITBOX: - if (msg == WM_COMMAND && !ctrl->editbox.has_list && - (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS); - if (msg == WM_COMMAND && ctrl->editbox.has_list && - (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS); + if (msg == WM_COMMAND && !ctrl->editbox.has_list && + (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS); + if (msg == WM_COMMAND && ctrl->editbox.has_list && + (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS); - if (msg == WM_COMMAND && !ctrl->editbox.has_list && - HIWORD(wParam) == EN_CHANGE) - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - if (msg == WM_COMMAND && - ctrl->editbox.has_list) { - if (HIWORD(wParam) == CBN_SELCHANGE) { - int index, len; - char *text; + if (msg == WM_COMMAND && !ctrl->editbox.has_list && + HIWORD(wParam) == EN_CHANGE) + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + if (msg == WM_COMMAND && + ctrl->editbox.has_list) { + if (HIWORD(wParam) == CBN_SELCHANGE) { + int index, len; + char *text; - index = SendDlgItemMessage(dp->hwnd, c->base_id+1, - CB_GETCURSEL, 0, 0); - len = SendDlgItemMessage(dp->hwnd, c->base_id+1, - CB_GETLBTEXTLEN, index, 0); - text = snewn(len+1, char); - SendDlgItemMessage(dp->hwnd, c->base_id+1, CB_GETLBTEXT, - index, (LPARAM)text); - SetDlgItemText(dp->hwnd, c->base_id+1, text); - sfree(text); - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } else if (HIWORD(wParam) == CBN_EDITCHANGE) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } else if (HIWORD(wParam) == CBN_KILLFOCUS) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); - } + index = SendDlgItemMessage(dp->hwnd, c->base_id+1, + CB_GETCURSEL, 0, 0); + len = SendDlgItemMessage(dp->hwnd, c->base_id+1, + CB_GETLBTEXTLEN, index, 0); + text = snewn(len+1, char); + SendDlgItemMessage(dp->hwnd, c->base_id+1, CB_GETLBTEXT, + index, (LPARAM)text); + SetDlgItemText(dp->hwnd, c->base_id+1, text); + sfree(text); + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } else if (HIWORD(wParam) == CBN_EDITCHANGE) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } else if (HIWORD(wParam) == CBN_KILLFOCUS) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); + } - } - break; + } + break; case CTRL_RADIO: - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - /* - * We sometimes get spurious BN_CLICKED messages for the - * radio button that is just about to _lose_ selection, if - * we're switching using the arrow keys. Therefore we - * double-check that the button in wParam is actually - * checked before generating an event. - */ - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED) && - IsDlgButtonChecked(dp->hwnd, LOWORD(wParam))) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } - break; + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + /* + * We sometimes get spurious BN_CLICKED messages for the + * radio button that is just about to _lose_ selection, if + * we're switching using the arrow keys. Therefore we + * double-check that the button in wParam is actually + * checked before generating an event. + */ + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED) && + IsDlgButtonChecked(dp->hwnd, LOWORD(wParam))) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } + break; case CTRL_CHECKBOX: - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED)) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } - break; + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED)) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } + break; case CTRL_BUTTON: - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - if (msg == WM_COMMAND && - (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED)) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION); - } - break; + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + if (msg == WM_COMMAND && + (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED)) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION); + } + break; case CTRL_LISTBOX: - if (msg == WM_COMMAND && ctrl->listbox.height != 0 && - (HIWORD(wParam)==LBN_SETFOCUS || HIWORD(wParam)==LBN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == LBN_SETFOCUS); - if (msg == WM_COMMAND && ctrl->listbox.height == 0 && - (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS); - if (msg == WM_COMMAND && id >= 2 && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - if (ctrl->listbox.draglist) { - int pret; - pret = handle_prefslist(c->data, NULL, 0, (msg != WM_COMMAND), - dp->hwnd, wParam, lParam); - if (pret & 2) - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - ret = pret & 1; - } else { - if (msg == WM_COMMAND && HIWORD(wParam) == LBN_DBLCLK) { - SetCapture(dp->hwnd); - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION); - } else if (msg == WM_COMMAND && HIWORD(wParam) == LBN_SELCHANGE) { - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_SELCHANGE); - } - } - break; + if (msg == WM_COMMAND && ctrl->listbox.height != 0 && + (HIWORD(wParam)==LBN_SETFOCUS || HIWORD(wParam)==LBN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == LBN_SETFOCUS); + if (msg == WM_COMMAND && ctrl->listbox.height == 0 && + (HIWORD(wParam)==CBN_SETFOCUS || HIWORD(wParam)==CBN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == CBN_SETFOCUS); + if (msg == WM_COMMAND && id >= 2 && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + if (ctrl->listbox.draglist) { + int pret; + pret = handle_prefslist(c->data, NULL, 0, (msg != WM_COMMAND), + dp->hwnd, wParam, lParam); + if (pret & 2) + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + ret = pret & 1; + } else { + if (msg == WM_COMMAND && HIWORD(wParam) == LBN_DBLCLK) { + SetCapture(dp->hwnd); + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_ACTION); + } else if (msg == WM_COMMAND && HIWORD(wParam) == LBN_SELCHANGE) { + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_SELCHANGE); + } + } + break; case CTRL_FILESELECT: - if (msg == WM_COMMAND && id == 1 && - (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS); - if (msg == WM_COMMAND && id == 2 && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - if (msg == WM_COMMAND && id == 1 && HIWORD(wParam) == EN_CHANGE) - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - if (id == 2 && - (msg == WM_COMMAND && - (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED))) { - OPENFILENAME of; - char filename[FILENAME_MAX]; + if (msg == WM_COMMAND && id == 1 && + (HIWORD(wParam) == EN_SETFOCUS || HIWORD(wParam) == EN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == EN_SETFOCUS); + if (msg == WM_COMMAND && id == 2 && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + if (msg == WM_COMMAND && id == 1 && HIWORD(wParam) == EN_CHANGE) + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + if (id == 2 && + (msg == WM_COMMAND && + (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED))) { + OPENFILENAME of; + char filename[FILENAME_MAX]; - memset(&of, 0, sizeof(of)); - of.hwndOwner = dp->hwnd; - if (ctrl->fileselect.filter) - of.lpstrFilter = ctrl->fileselect.filter; - else - of.lpstrFilter = "All Files (*.*)\0*\0\0\0"; - of.lpstrCustomFilter = NULL; - of.nFilterIndex = 1; - of.lpstrFile = filename; - GetDlgItemText(dp->hwnd, c->base_id+1, filename, lenof(filename)); - filename[lenof(filename)-1] = '\0'; - of.nMaxFile = lenof(filename); - of.lpstrFileTitle = NULL; - of.lpstrTitle = ctrl->fileselect.title; - of.Flags = 0; - if (request_file(NULL, &of, false, ctrl->fileselect.for_writing)) { - SetDlgItemText(dp->hwnd, c->base_id + 1, filename); - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } - } - break; + memset(&of, 0, sizeof(of)); + of.hwndOwner = dp->hwnd; + if (ctrl->fileselect.filter) + of.lpstrFilter = ctrl->fileselect.filter; + else + of.lpstrFilter = "All Files (*.*)\0*\0\0\0"; + of.lpstrCustomFilter = NULL; + of.nFilterIndex = 1; + of.lpstrFile = filename; + GetDlgItemText(dp->hwnd, c->base_id+1, filename, lenof(filename)); + filename[lenof(filename)-1] = '\0'; + of.nMaxFile = lenof(filename); + of.lpstrFileTitle = NULL; + of.lpstrTitle = ctrl->fileselect.title; + of.Flags = 0; + if (request_file(NULL, &of, false, ctrl->fileselect.for_writing)) { + SetDlgItemText(dp->hwnd, c->base_id + 1, filename); + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } + } + break; case CTRL_FONTSELECT: - if (msg == WM_COMMAND && id == 2 && - (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) - winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); - if (id == 2 && - (msg == WM_COMMAND && - (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED))) { - CHOOSEFONT cf; - LOGFONT lf; - HDC hdc; - FontSpec *fs = (FontSpec *)c->data; + if (msg == WM_COMMAND && id == 2 && + (HIWORD(wParam) == BN_SETFOCUS || HIWORD(wParam) == BN_KILLFOCUS)) + winctrl_set_focus(ctrl, dp, HIWORD(wParam) == BN_SETFOCUS); + if (id == 2 && + (msg == WM_COMMAND && + (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED))) { + CHOOSEFONT cf; + LOGFONT lf; + HDC hdc; + FontSpec *fs = (FontSpec *)c->data; - hdc = GetDC(0); - lf.lfHeight = -MulDiv(fs->height, - GetDeviceCaps(hdc, LOGPIXELSY), 72); - ReleaseDC(0, hdc); - lf.lfWidth = lf.lfEscapement = lf.lfOrientation = 0; - lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0; - lf.lfWeight = (fs->isbold ? FW_BOLD : 0); - lf.lfCharSet = fs->charset; - lf.lfOutPrecision = OUT_DEFAULT_PRECIS; - lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; - lf.lfQuality = DEFAULT_QUALITY; - lf.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE; - strncpy(lf.lfFaceName, fs->name, - sizeof(lf.lfFaceName) - 1); - lf.lfFaceName[sizeof(lf.lfFaceName) - 1] = '\0'; + hdc = GetDC(0); + lf.lfHeight = -MulDiv(fs->height, + GetDeviceCaps(hdc, LOGPIXELSY), 72); + ReleaseDC(0, hdc); + lf.lfWidth = lf.lfEscapement = lf.lfOrientation = 0; + lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0; + lf.lfWeight = (fs->isbold ? FW_BOLD : 0); + lf.lfCharSet = fs->charset; + lf.lfOutPrecision = OUT_DEFAULT_PRECIS; + lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; + lf.lfQuality = DEFAULT_QUALITY; + lf.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE; + strncpy(lf.lfFaceName, fs->name, + sizeof(lf.lfFaceName) - 1); + lf.lfFaceName[sizeof(lf.lfFaceName) - 1] = '\0'; - cf.lStructSize = sizeof(cf); - cf.hwndOwner = dp->hwnd; - cf.lpLogFont = &lf; - cf.Flags = (dp->fixed_pitch_fonts ? CF_FIXEDPITCHONLY : 0) | + cf.lStructSize = sizeof(cf); + cf.hwndOwner = dp->hwnd; + cf.lpLogFont = &lf; + cf.Flags = (dp->fixed_pitch_fonts ? CF_FIXEDPITCHONLY : 0) | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS; - if (ChooseFont(&cf)) { + if (ChooseFont(&cf)) { fs = fontspec_new(lf.lfFaceName, (lf.lfWeight == FW_BOLD), cf.iPointSize / 10, lf.lfCharSet); - dlg_fontsel_set(ctrl, dp, fs); + dlg_fontsel_set(ctrl, dp, fs); fontspec_free(fs); - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); - } - } - break; + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_VALCHANGE); + } + } + break; } /* @@ -1992,27 +1992,27 @@ bool winctrl_handle_command(struct dlgparam *dp, UINT msg, * now is the time to generate one. */ if (dp->coloursel_wanted) { - static CHOOSECOLOR cc; - static DWORD custom[16] = { 0 }; /* zero initialisers */ - cc.lStructSize = sizeof(cc); - cc.hwndOwner = dp->hwnd; - cc.hInstance = (HWND) hinst; - cc.lpCustColors = custom; - cc.rgbResult = RGB(dp->coloursel_result.r, - dp->coloursel_result.g, - dp->coloursel_result.b); - cc.Flags = CC_FULLOPEN | CC_RGBINIT; - if (ChooseColor(&cc)) { - dp->coloursel_result.r = - (unsigned char) (cc.rgbResult & 0xFF); - dp->coloursel_result.g = - (unsigned char) (cc.rgbResult >> 8) & 0xFF; - dp->coloursel_result.b = - (unsigned char) (cc.rgbResult >> 16) & 0xFF; - dp->coloursel_result.ok = true; - } else - dp->coloursel_result.ok = false; - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_CALLBACK); + static CHOOSECOLOR cc; + static DWORD custom[16] = { 0 }; /* zero initialisers */ + cc.lStructSize = sizeof(cc); + cc.hwndOwner = dp->hwnd; + cc.hInstance = (HWND) hinst; + cc.lpCustColors = custom; + cc.rgbResult = RGB(dp->coloursel_result.r, + dp->coloursel_result.g, + dp->coloursel_result.b); + cc.Flags = CC_FULLOPEN | CC_RGBINIT; + if (ChooseColor(&cc)) { + dp->coloursel_result.r = + (unsigned char) (cc.rgbResult & 0xFF); + dp->coloursel_result.g = + (unsigned char) (cc.rgbResult >> 8) & 0xFF; + dp->coloursel_result.b = + (unsigned char) (cc.rgbResult >> 16) & 0xFF; + dp->coloursel_result.ok = true; + } else + dp->coloursel_result.ok = false; + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_CALLBACK); } return ret; @@ -2032,19 +2032,19 @@ bool winctrl_context_help(struct dlgparam *dp, HWND hwnd, int id) */ c = NULL; for (i = 0; i < dp->nctrltrees; i++) { - c = winctrl_findbyid(dp->controltrees[i], id); - if (c) - break; + c = winctrl_findbyid(dp->controltrees[i], id); + if (c) + break; } if (!c) - return false; /* we have nothing to do */ + return false; /* we have nothing to do */ /* * This is the Windows front end, so we're allowed to assume * `helpctx.p' is a context string. */ if (!c->ctrl || !c->ctrl->generic.helpctx.p) - return false; /* no help available for this ctrl */ + return false; /* no help available for this ctrl */ launch_help(hwnd, c->ctrl->generic.helpctx.p); return true; @@ -2060,9 +2060,9 @@ static struct winctrl *dlg_findbyctrl(struct dlgparam *dp, union control *ctrl) int i; for (i = 0; i < dp->nctrltrees; i++) { - struct winctrl *c = winctrl_findbyctrl(dp->controltrees[i], ctrl); - if (c) - return c; + struct winctrl *c = winctrl_findbyctrl(dp->controltrees[i], ctrl); + if (c) + return c; } return NULL; } @@ -2083,9 +2083,9 @@ void dlg_radiobutton_set(union control *ctrl, dlgparam *dp, int whichbutton) struct winctrl *c = dlg_findbyctrl(dp, ctrl); assert(c && c->ctrl->generic.type == CTRL_RADIO); CheckRadioButton(dp->hwnd, - c->base_id + 1, - c->base_id + c->ctrl->radio.nbuttons, - c->base_id + 1 + whichbutton); + c->base_id + 1, + c->base_id + c->ctrl->radio.nbuttons, + c->base_id + 1 + whichbutton); } int dlg_radiobutton_get(union control *ctrl, dlgparam *dp) @@ -2094,8 +2094,8 @@ int dlg_radiobutton_get(union control *ctrl, dlgparam *dp) int i; assert(c && c->ctrl->generic.type == CTRL_RADIO); for (i = 0; i < c->ctrl->radio.nbuttons; i++) - if (IsDlgButtonChecked(dp->hwnd, c->base_id + 1 + i)) - return i; + if (IsDlgButtonChecked(dp->hwnd, c->base_id + 1 + i)) + return i; assert(!"No radio button was checked?!"); return 0; } @@ -2134,11 +2134,11 @@ void dlg_listbox_clear(union control *ctrl, dlgparam *dp) struct winctrl *c = dlg_findbyctrl(dp, ctrl); int msg; assert(c && - (c->ctrl->generic.type == CTRL_LISTBOX || - (c->ctrl->generic.type == CTRL_EDITBOX && - c->ctrl->editbox.has_list))); + (c->ctrl->generic.type == CTRL_LISTBOX || + (c->ctrl->generic.type == CTRL_EDITBOX && + c->ctrl->editbox.has_list))); msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ? - LB_RESETCONTENT : CB_RESETCONTENT); + LB_RESETCONTENT : CB_RESETCONTENT); SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, 0); } @@ -2147,11 +2147,11 @@ void dlg_listbox_del(union control *ctrl, dlgparam *dp, int index) struct winctrl *c = dlg_findbyctrl(dp, ctrl); int msg; assert(c && - (c->ctrl->generic.type == CTRL_LISTBOX || - (c->ctrl->generic.type == CTRL_EDITBOX && - c->ctrl->editbox.has_list))); + (c->ctrl->generic.type == CTRL_LISTBOX || + (c->ctrl->generic.type == CTRL_EDITBOX && + c->ctrl->editbox.has_list))); msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ? - LB_DELETESTRING : CB_DELETESTRING); + LB_DELETESTRING : CB_DELETESTRING); SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0); } @@ -2160,11 +2160,11 @@ void dlg_listbox_add(union control *ctrl, dlgparam *dp, char const *text) struct winctrl *c = dlg_findbyctrl(dp, ctrl); int msg; assert(c && - (c->ctrl->generic.type == CTRL_LISTBOX || - (c->ctrl->generic.type == CTRL_EDITBOX && - c->ctrl->editbox.has_list))); + (c->ctrl->generic.type == CTRL_LISTBOX || + (c->ctrl->generic.type == CTRL_EDITBOX && + c->ctrl->editbox.has_list))); msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ? - LB_ADDSTRING : CB_ADDSTRING); + LB_ADDSTRING : CB_ADDSTRING); SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, (LPARAM)text); } @@ -2176,18 +2176,18 @@ void dlg_listbox_add(union control *ctrl, dlgparam *dp, char const *text) * IDs and expect to get meaningful results back. */ void dlg_listbox_addwithid(union control *ctrl, dlgparam *dp, - char const *text, int id) + char const *text, int id) { struct winctrl *c = dlg_findbyctrl(dp, ctrl); int msg, msg2, index; assert(c && - (c->ctrl->generic.type == CTRL_LISTBOX || - (c->ctrl->generic.type == CTRL_EDITBOX && - c->ctrl->editbox.has_list))); + (c->ctrl->generic.type == CTRL_LISTBOX || + (c->ctrl->generic.type == CTRL_EDITBOX && + c->ctrl->editbox.has_list))); msg = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ? - LB_ADDSTRING : CB_ADDSTRING); + LB_ADDSTRING : CB_ADDSTRING); msg2 = (c->ctrl->generic.type==CTRL_LISTBOX && c->ctrl->listbox.height!=0 ? - LB_SETITEMDATA : CB_SETITEMDATA); + LB_SETITEMDATA : CB_SETITEMDATA); index = SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, (LPARAM)text); SendDlgItemMessage(dp->hwnd, c->base_id+1, msg2, index, (LPARAM)id); } @@ -2199,7 +2199,7 @@ int dlg_listbox_getid(union control *ctrl, dlgparam *dp, int index) assert(c && c->ctrl->generic.type == CTRL_LISTBOX); msg = (c->ctrl->listbox.height != 0 ? LB_GETITEMDATA : CB_GETITEMDATA); return - SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0); + SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0); } /* dlg_listbox_index returns <0 if no single element is selected. */ @@ -2209,27 +2209,27 @@ int dlg_listbox_index(union control *ctrl, dlgparam *dp) int msg, ret; assert(c && c->ctrl->generic.type == CTRL_LISTBOX); if (c->ctrl->listbox.multisel) { - assert(c->ctrl->listbox.height != 0); /* not combo box */ - ret = SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSELCOUNT, 0, 0); - if (ret == LB_ERR || ret > 1) - return -1; + assert(c->ctrl->listbox.height != 0); /* not combo box */ + ret = SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSELCOUNT, 0, 0); + if (ret == LB_ERR || ret > 1) + return -1; } msg = (c->ctrl->listbox.height != 0 ? LB_GETCURSEL : CB_GETCURSEL); ret = SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, 0, 0); if (ret == LB_ERR) - return -1; + return -1; else - return ret; + return ret; } bool dlg_listbox_issel(union control *ctrl, dlgparam *dp, int index) { struct winctrl *c = dlg_findbyctrl(dp, ctrl); assert(c && c->ctrl->generic.type == CTRL_LISTBOX && - c->ctrl->listbox.multisel && - c->ctrl->listbox.height != 0); + c->ctrl->listbox.multisel && + c->ctrl->listbox.height != 0); return - SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSEL, index, 0); + SendDlgItemMessage(dp->hwnd, c->base_id+1, LB_GETSEL, index, 0); } void dlg_listbox_select(union control *ctrl, dlgparam *dp, int index) @@ -2237,7 +2237,7 @@ void dlg_listbox_select(union control *ctrl, dlgparam *dp, int index) struct winctrl *c = dlg_findbyctrl(dp, ctrl); int msg; assert(c && c->ctrl->generic.type == CTRL_LISTBOX && - !c->ctrl->listbox.multisel); + !c->ctrl->listbox.multisel); msg = (c->ctrl->listbox.height != 0 ? LB_SETCURSEL : CB_SETCURSEL); SendDlgItemMessage(dp->hwnd, c->base_id+1, msg, index, 0); } @@ -2258,40 +2258,40 @@ void dlg_label_change(union control *ctrl, dlgparam *dp, char const *text) assert(c); switch (c->ctrl->generic.type) { case CTRL_EDITBOX: - escaped = shortcut_escape(text, c->ctrl->editbox.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, c->ctrl->editbox.shortcut); + id = c->base_id; + break; case CTRL_RADIO: - escaped = shortcut_escape(text, c->ctrl->radio.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, c->ctrl->radio.shortcut); + id = c->base_id; + break; case CTRL_CHECKBOX: - escaped = shortcut_escape(text, ctrl->checkbox.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, ctrl->checkbox.shortcut); + id = c->base_id; + break; case CTRL_BUTTON: - escaped = shortcut_escape(text, ctrl->button.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, ctrl->button.shortcut); + id = c->base_id; + break; case CTRL_LISTBOX: - escaped = shortcut_escape(text, ctrl->listbox.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, ctrl->listbox.shortcut); + id = c->base_id; + break; case CTRL_FILESELECT: - escaped = shortcut_escape(text, ctrl->fileselect.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, ctrl->fileselect.shortcut); + id = c->base_id; + break; case CTRL_FONTSELECT: - escaped = shortcut_escape(text, ctrl->fontselect.shortcut); - id = c->base_id; - break; + escaped = shortcut_escape(text, ctrl->fontselect.shortcut); + id = c->base_id; + break; default: - assert(!"Can't happen"); - break; + assert(!"Can't happen"); + break; } if (escaped) { - SetDlgItemText(dp->hwnd, id, escaped); - sfree(escaped); + SetDlgItemText(dp->hwnd, id, escaped); + sfree(escaped); } } @@ -2325,11 +2325,11 @@ void dlg_fontsel_set(union control *ctrl, dlgparam *dp, FontSpec *fs) boldstr = (fs->isbold ? "bold, " : ""); if (fs->height == 0) - buf = dupprintf("Font: %s, %sdefault height", fs->name, boldstr); + buf = dupprintf("Font: %s, %sdefault height", fs->name, boldstr); else - buf = dupprintf("Font: %s, %s%d-%s", fs->name, boldstr, - (fs->height < 0 ? -fs->height : fs->height), - (fs->height < 0 ? "pixel" : "point")); + buf = dupprintf("Font: %s, %s%d-%s", fs->name, boldstr, + (fs->height < 0 ? -fs->height : fs->height), + (fs->height < 0 ? "pixel" : "point")); SetDlgItemText(dp->hwnd, c->base_id+1, buf); sfree(buf); @@ -2352,7 +2352,7 @@ void dlg_update_start(union control *ctrl, dlgparam *dp) { struct winctrl *c = dlg_findbyctrl(dp, ctrl); if (c && c->ctrl->generic.type == CTRL_LISTBOX) { - SendDlgItemMessage(dp->hwnd, c->base_id+1, WM_SETREDRAW, false, 0); + SendDlgItemMessage(dp->hwnd, c->base_id+1, WM_SETREDRAW, false, 0); } } @@ -2360,9 +2360,9 @@ void dlg_update_done(union control *ctrl, dlgparam *dp) { struct winctrl *c = dlg_findbyctrl(dp, ctrl); if (c && c->ctrl->generic.type == CTRL_LISTBOX) { - HWND hw = GetDlgItem(dp->hwnd, c->base_id+1); - SendMessage(hw, WM_SETREDRAW, true, 0); - InvalidateRect(hw, NULL, true); + HWND hw = GetDlgItem(dp->hwnd, c->base_id+1); + SendMessage(hw, WM_SETREDRAW, true, 0); + InvalidateRect(hw, NULL, true); } } @@ -2376,15 +2376,15 @@ void dlg_set_focus(union control *ctrl, dlgparam *dp) switch (ctrl->generic.type) { case CTRL_EDITBOX: id = c->base_id + 1; break; case CTRL_RADIO: - for (id = c->base_id + ctrl->radio.nbuttons; id > 1; id--) - if (IsDlgButtonChecked(dp->hwnd, id)) - break; - /* - * In the theoretically-unlikely case that no button was - * selected, id should come out of this as 1, which is a - * reasonable enough choice. - */ - break; + for (id = c->base_id + ctrl->radio.nbuttons; id > 1; id--) + if (IsDlgButtonChecked(dp->hwnd, id)) + break; + /* + * In the theoretically-unlikely case that no button was + * selected, id should come out of this as 1, which is a + * reasonable enough choice. + */ + break; case CTRL_CHECKBOX: id = c->base_id; break; case CTRL_BUTTON: id = c->base_id; break; case CTRL_LISTBOX: id = c->base_id + 1; break; @@ -2409,8 +2409,8 @@ void dlg_beep(dlgparam *dp) void dlg_error_msg(dlgparam *dp, const char *msg) { MessageBox(dp->hwnd, msg, - dp->errtitle ? dp->errtitle : NULL, - MB_OK | MB_ICONERROR); + dp->errtitle ? dp->errtitle : NULL, + MB_OK | MB_ICONERROR); } /* @@ -2430,24 +2430,24 @@ void dlg_refresh(union control *ctrl, dlgparam *dp) struct winctrl *c; if (!ctrl) { - /* - * Send EVENT_REFRESH to absolutely everything. - */ - for (j = 0; j < dp->nctrltrees; j++) { - for (i = 0; - (c = winctrl_findbyindex(dp->controltrees[j], i)) != NULL; - i++) { - if (c->ctrl && c->ctrl->generic.handler != NULL) - c->ctrl->generic.handler(c->ctrl, dp, - dp->data, EVENT_REFRESH); - } - } + /* + * Send EVENT_REFRESH to absolutely everything. + */ + for (j = 0; j < dp->nctrltrees; j++) { + for (i = 0; + (c = winctrl_findbyindex(dp->controltrees[j], i)) != NULL; + i++) { + if (c->ctrl && c->ctrl->generic.handler != NULL) + c->ctrl->generic.handler(c->ctrl, dp, + dp->data, EVENT_REFRESH); + } + } } else { - /* - * Send EVENT_REFRESH to a specific control. - */ - if (ctrl->generic.handler != NULL) - ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); + /* + * Send EVENT_REFRESH to a specific control. + */ + if (ctrl->generic.handler != NULL) + ctrl->generic.handler(ctrl, dp, dp->data, EVENT_REFRESH); } } @@ -2463,12 +2463,12 @@ bool dlg_coloursel_results(union control *ctrl, dlgparam *dp, int *r, int *g, int *b) { if (dp->coloursel_result.ok) { - *r = dp->coloursel_result.r; - *g = dp->coloursel_result.g; - *b = dp->coloursel_result.b; - return true; + *r = dp->coloursel_result.r; + *g = dp->coloursel_result.g; + *b = dp->coloursel_result.b; + return true; } else - return false; + return false; } void dlg_auto_set_fixed_pitch_flag(dlgparam *dp) diff --git a/windows/windefs.c b/windows/windefs.c index 308c29eb..006e8dc5 100644 --- a/windows/windefs.c +++ b/windows/windefs.c @@ -17,15 +17,15 @@ FontSpec *platform_default_fontspec(const char *name) Filename *platform_default_filename(const char *name) { if (!strcmp(name, "LogFileName")) - return filename_from_str("putty.log"); + return filename_from_str("putty.log"); else - return filename_from_str(""); + return filename_from_str(""); } char *platform_default_s(const char *name) { if (!strcmp(name, "SerialLine")) - return dupstr("COM1"); + return dupstr("COM1"); return NULL; } diff --git a/windows/windlg.c b/windows/windlg.c index c760c91a..faa56935 100644 --- a/windows/windlg.c +++ b/windows/windlg.c @@ -58,13 +58,13 @@ void force_normal(HWND hwnd) WINDOWPLACEMENT wp; if (recurse) - return; + return; recurse = true; wp.length = sizeof(wp); if (GetWindowPlacement(hwnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED) { - wp.showCmd = SW_SHOWNORMAL; - SetWindowPlacement(hwnd, &wp); + wp.showCmd = SW_SHOWNORMAL; + SetWindowPlacement(hwnd, &wp); } recurse = false; } @@ -85,93 +85,93 @@ static INT_PTR CALLBACK LogProc(HWND hwnd, UINT msg, switch (msg) { case WM_INITDIALOG: - { - char *str = dupprintf("%s Event Log", appname); - SetWindowText(hwnd, str); - sfree(str); - } - { - static int tabs[4] = { 78, 108 }; - SendDlgItemMessage(hwnd, IDN_LIST, LB_SETTABSTOPS, 2, - (LPARAM) tabs); - } - for (i = 0; i < ninitial; i++) - SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING, - 0, (LPARAM) events_initial[i]); - for (i = 0; i < ncircular; i++) - SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING, - 0, (LPARAM) events_circular[(circular_first + i) % LOGEVENT_CIRCULAR_MAX]); - return 1; + { + char *str = dupprintf("%s Event Log", appname); + SetWindowText(hwnd, str); + sfree(str); + } + { + static int tabs[4] = { 78, 108 }; + SendDlgItemMessage(hwnd, IDN_LIST, LB_SETTABSTOPS, 2, + (LPARAM) tabs); + } + for (i = 0; i < ninitial; i++) + SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING, + 0, (LPARAM) events_initial[i]); + for (i = 0; i < ncircular; i++) + SendDlgItemMessage(hwnd, IDN_LIST, LB_ADDSTRING, + 0, (LPARAM) events_circular[(circular_first + i) % LOGEVENT_CIRCULAR_MAX]); + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - logbox = NULL; - SetActiveWindow(GetParent(hwnd)); - DestroyWindow(hwnd); - return 0; - 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; - } + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + logbox = NULL; + SetActiveWindow(GetParent(hwnd)); + DestroyWindow(hwnd); + return 0; + 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 = snewn(selcount, 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; + selitems = snewn(selcount, 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; - } + if (count == 0) { /* can't copy zero stuff */ + MessageBeep(0); + break; + } - size = 0; - for (i = 0; i < count; i++) - size += - strlen(getevent(selitems[i])) + sizeof(sel_nl); + size = 0; + for (i = 0; i < count; i++) + size += + strlen(getevent(selitems[i])) + sizeof(sel_nl); - clipdata = snewn(size, char); - if (clipdata) { - char *p = clipdata; - for (i = 0; i < count; i++) { - char *q = getevent(selitems[i]); - int qlen = strlen(q); - memcpy(p, q, qlen); - p += qlen; - memcpy(p, sel_nl, sizeof(sel_nl)); - p += sizeof(sel_nl); - } - write_aclip(CLIP_SYSTEM, clipdata, size, true); - sfree(clipdata); - } - sfree(selitems); + clipdata = snewn(size, char); + if (clipdata) { + char *p = clipdata; + for (i = 0; i < count; i++) { + char *q = getevent(selitems[i]); + int qlen = strlen(q); + memcpy(p, q, qlen); + p += qlen; + memcpy(p, sel_nl, sizeof(sel_nl)); + p += sizeof(sel_nl); + } + write_aclip(CLIP_SYSTEM, clipdata, size, true); + sfree(clipdata); + } + sfree(selitems); - for (i = 0; i < (ninitial + ncircular); i++) - SendDlgItemMessage(hwnd, IDN_LIST, LB_SETSEL, - false, i); - } - } - return 0; - } - return 0; + for (i = 0; i < (ninitial + ncircular); i++) + SendDlgItemMessage(hwnd, IDN_LIST, LB_SETSEL, + false, i); + } + } + return 0; + } + return 0; case WM_CLOSE: - logbox = NULL; - SetActiveWindow(GetParent(hwnd)); - DestroyWindow(hwnd); - return 0; + logbox = NULL; + SetActiveWindow(GetParent(hwnd)); + DestroyWindow(hwnd); + return 0; } return 0; } @@ -181,24 +181,24 @@ static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg, { switch (msg) { case WM_INITDIALOG: - { - char *str = dupprintf("%s Licence", appname); - SetWindowText(hwnd, str); - sfree(str); + { + char *str = dupprintf("%s Licence", appname); + SetWindowText(hwnd, str); + sfree(str); SetDlgItemText(hwnd, IDA_TEXT, LICENCE_TEXT("\r\n\r\n")); - } - return 1; + } + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - EndDialog(hwnd, 1); - return 0; - } - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + EndDialog(hwnd, 1); + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 1); - return 0; + EndDialog(hwnd, 1); + return 0; } return 0; } @@ -210,9 +210,9 @@ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, switch (msg) { case WM_INITDIALOG: - str = dupprintf("About %s", appname); - SetWindowText(hwnd, str); - sfree(str); + str = dupprintf("About %s", appname); + SetWindowText(hwnd, str); + sfree(str); { char *buildinfo_text = buildinfo("\r\n"); char *text = dupprintf @@ -223,40 +223,40 @@ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, SetDlgItemText(hwnd, IDA_TEXT, text); sfree(text); } - return 1; + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - EndDialog(hwnd, true); - return 0; - case IDA_LICENCE: - EnableWindow(hwnd, 0); - DialogBox(hinst, MAKEINTRESOURCE(IDD_LICENCEBOX), - hwnd, LicenceProc); - EnableWindow(hwnd, 1); - SetActiveWindow(hwnd); - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + EndDialog(hwnd, true); + return 0; + case IDA_LICENCE: + EnableWindow(hwnd, 0); + DialogBox(hinst, MAKEINTRESOURCE(IDD_LICENCEBOX), + hwnd, LicenceProc); + EnableWindow(hwnd, 1); + SetActiveWindow(hwnd); + return 0; - case IDA_WEB: - /* Load web browser */ - ShellExecute(hwnd, "open", - "https://www.chiark.greenend.org.uk/~sgtatham/putty/", - 0, 0, SW_SHOWDEFAULT); - return 0; - } - return 0; + case IDA_WEB: + /* Load web browser */ + ShellExecute(hwnd, "open", + "https://www.chiark.greenend.org.uk/~sgtatham/putty/", + 0, 0, SW_SHOWDEFAULT); + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, true); - return 0; + EndDialog(hwnd, true); + return 0; } return 0; } static int SaneDialogBox(HINSTANCE hinst, - LPCTSTR tmpl, - HWND hwndparent, - DLGPROC lpDialogFunc) + LPCTSTR tmpl, + HWND hwndparent, + DLGPROC lpDialogFunc) { WNDCLASS wc; HWND hwnd; @@ -283,11 +283,11 @@ static int SaneDialogBox(HINSTANCE hinst, SetWindowLongPtr(hwnd, BOXRESULT, 0); /* result from SaneEndDialog */ while ((gm=GetMessage(&msg, NULL, 0, 0)) > 0) { - flags=GetWindowLongPtr(hwnd, BOXFLAGS); - if (!(flags & DF_END) && !IsDialogMessage(hwnd, &msg)) - DispatchMessage(&msg); - if (flags & DF_END) - break; + flags=GetWindowLongPtr(hwnd, BOXFLAGS); + if (!(flags & DF_END) && !IsDialogMessage(hwnd, &msg)) + DispatchMessage(&msg); + if (flags & DF_END) + break; } if (gm == 0) @@ -327,7 +327,7 @@ struct treeview_faff { }; static HTREEITEM treeview_insert(struct treeview_faff *faff, - int level, char *text, char *path) + int level, char *text, char *path) { TVINSERTSTRUCT ins; int i; @@ -345,11 +345,11 @@ static HTREEITEM treeview_insert(struct treeview_faff *faff, ins.INSITEM.lParam = (LPARAM)path; newitem = TreeView_InsertItem(faff->treeview, &ins); if (level > 0) - TreeView_Expand(faff->treeview, faff->lastat[level - 1], - (level > 1 ? TVE_COLLAPSE : TVE_EXPAND)); + TreeView_Expand(faff->treeview, faff->lastat[level - 1], + (level > 1 ? TVE_COLLAPSE : TVE_EXPAND)); faff->lastat[level] = newitem; for (i = level + 1; i < 4; i++) - faff->lastat[i] = NULL; + faff->lastat[i] = NULL; return newitem; } @@ -364,25 +364,25 @@ static void create_controls(HWND hwnd, char *path) struct winctrls *wc; if (!path[0]) { - /* - * Here we must create the basic standard controls. - */ - ctlposinit(&cp, hwnd, 3, 3, 235); - wc = &ctrls_base; - base_id = IDCX_STDBASE; + /* + * Here we must create the basic standard controls. + */ + ctlposinit(&cp, hwnd, 3, 3, 235); + wc = &ctrls_base; + base_id = IDCX_STDBASE; } else { - /* - * Otherwise, we're creating the controls for a particular - * panel. - */ - ctlposinit(&cp, hwnd, 100, 3, 13); - wc = &ctrls_panel; - base_id = IDCX_PANELBASE; + /* + * Otherwise, we're creating the controls for a particular + * panel. + */ + ctlposinit(&cp, hwnd, 100, 3, 13); + wc = &ctrls_panel; + base_id = IDCX_PANELBASE; } for (index=-1; (index = ctrl_find_path(ctrlbox, path, index)) >= 0 ;) { - struct controlset *s = ctrlbox->ctrlsets[index]; - winctrl_layout(&dp, wc, &cp, s, &base_id); + struct controlset *s = ctrlbox->ctrlsets[index]; + winctrl_layout(&dp, wc, &cp, s, &base_id); } } @@ -400,130 +400,130 @@ static INT_PTR CALLBACK GenericMainDlgProc(HWND hwnd, UINT msg, switch (msg) { case WM_INITDIALOG: - dp.hwnd = hwnd; - create_controls(hwnd, ""); /* Open and Cancel buttons etc */ - SetWindowText(hwnd, dp.wintitle); - SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); + dp.hwnd = hwnd; + create_controls(hwnd, ""); /* Open and Cancel buttons etc */ + SetWindowText(hwnd, dp.wintitle); + SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); if (has_help()) SetWindowLongPtr(hwnd, GWL_EXSTYLE, - GetWindowLongPtr(hwnd, GWL_EXSTYLE) | - WS_EX_CONTEXTHELP); + GetWindowLongPtr(hwnd, GWL_EXSTYLE) | + WS_EX_CONTEXTHELP); else { HWND item = GetDlgItem(hwnd, IDC_HELPBTN); if (item) DestroyWindow(item); } - SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, - (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(IDI_CFGICON))); - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; + SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, + (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(IDI_CFGICON))); + /* + * Centre the window. + */ + { /* centre the window */ + 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); - } + 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); + } - /* - * Create the tree view. - */ - { - RECT r; - WPARAM font; - HWND tvstatic; + /* + * Create the tree view. + */ + { + RECT r; + WPARAM font; + HWND tvstatic; - r.left = 3; - r.right = r.left + 95; - 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 + 95; + 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 + 95; - r.top = 13; - r.bottom = r.top + 219; - 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)); - } + r.left = 3; + r.right = r.left + 95; + r.top = 13; + r.bottom = r.top + 219; + 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)); + } - /* - * Set up the tree view contents. - */ - { - HTREEITEM hfirst = NULL; - int i; - char *path = NULL; + /* + * Set up the tree view contents. + */ + { + HTREEITEM hfirst = NULL; + int i; + char *path = NULL; char *firstpath = NULL; - for (i = 0; i < ctrlbox->nctrlsets; i++) { - struct controlset *s = ctrlbox->ctrlsets[i]; - HTREEITEM item; - int j; - char *c; + for (i = 0; i < ctrlbox->nctrlsets; i++) { + struct controlset *s = ctrlbox->ctrlsets[i]; + HTREEITEM item; + int j; + char *c; - if (!s->pathname[0]) - continue; - j = path ? ctrl_path_compare(s->pathname, path) : 0; - if (j == INT_MAX) - continue; /* same path, nothing to add to tree */ + if (!s->pathname[0]) + continue; + j = path ? ctrl_path_compare(s->pathname, path) : 0; + if (j == INT_MAX) + continue; /* same path, nothing to add to tree */ - /* - * We expect never to find an implicit path - * component. For example, we expect never to see - * A/B/C followed by A/D/E, because that would - * _implicitly_ create A/D. All our path prefixes - * are expected to contain actual controls and be - * selectable in the treeview; so we would expect - * to see A/D _explicitly_ before encountering - * A/D/E. - */ - assert(j == ctrl_path_elements(s->pathname) - 1); + /* + * We expect never to find an implicit path + * component. For example, we expect never to see + * A/B/C followed by A/D/E, because that would + * _implicitly_ create A/D. All our path prefixes + * are expected to contain actual controls and be + * selectable in the treeview; so we would expect + * to see A/D _explicitly_ before encountering + * A/D/E. + */ + assert(j == ctrl_path_elements(s->pathname) - 1); - c = strrchr(s->pathname, '/'); - if (!c) - c = s->pathname; - else - c++; + c = strrchr(s->pathname, '/'); + if (!c) + c = s->pathname; + else + c++; - item = treeview_insert(&tvfaff, j, c, s->pathname); - if (!hfirst) { - hfirst = item; + item = treeview_insert(&tvfaff, j, c, s->pathname); + if (!hfirst) { + hfirst = item; firstpath = s->pathname; } - path = s->pathname; - } + path = s->pathname; + } - /* - * Put the treeview selection on to the first panel in the - * ctrlbox. - */ - TreeView_SelectItem(treeview, hfirst); + /* + * Put the treeview selection on to the first panel in the + * ctrlbox. + */ + TreeView_SelectItem(treeview, hfirst); /* * And create the actual control set for that panel, to @@ -531,24 +531,24 @@ static INT_PTR CALLBACK GenericMainDlgProc(HWND hwnd, UINT msg, */ assert(firstpath); /* config.c must have given us _something_ */ create_controls(hwnd, firstpath); - dlg_refresh(NULL, &dp); /* and set up control values */ - } + dlg_refresh(NULL, &dp); /* and set up control values */ + } - /* - * Set focus into the first available control. - */ - { - int i; - struct winctrl *c; + /* + * Set focus into the first available control. + */ + { + int i; + struct winctrl *c; - for (i = 0; (c = winctrl_findbyindex(&ctrls_panel, i)) != NULL; - i++) { - if (c->ctrl) { - dlg_set_focus(c->ctrl, &dp); - break; - } - } - } + for (i = 0; (c = winctrl_findbyindex(&ctrls_panel, i)) != NULL; + i++) { + if (c->ctrl) { + dlg_set_focus(c->ctrl, &dp); + break; + } + } + } /* * Now we've finished creating our initial set of controls, @@ -562,20 +562,20 @@ static INT_PTR CALLBACK GenericMainDlgProc(HWND hwnd, UINT msg, * handlers below, which were disabled until now to avoid * spurious firing during the above setup procedure. */ - SetWindowLongPtr(hwnd, GWLP_USERDATA, 1); - return 0; + SetWindowLongPtr(hwnd, GWLP_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 (dp.ended) - SaneEndDialog(hwnd, dp.endresult ? 1 : 0); - break; + /* + * Button release should trigger WM_OK if there was a + * previous double click on the session list. + */ + ReleaseCapture(); + if (dp.ended) + SaneEndDialog(hwnd, dp.endresult ? 1 : 0); + break; case WM_NOTIFY: - if (LOWORD(wParam) == IDCX_TREEVIEW && - ((LPNMHDR) lParam)->code == TVN_SELCHANGED) { + if (LOWORD(wParam) == IDCX_TREEVIEW && + ((LPNMHDR) lParam)->code == TVN_SELCHANGED) { /* * Selection-change events on the treeview cause us to do * a flurry of control deletion and creation - but only @@ -583,79 +583,79 @@ static INT_PTR CALLBACK GenericMainDlgProc(HWND hwnd, UINT msg, * selection-change event(s) during treeview setup are * ignored. */ - HTREEITEM i; - TVITEM item; - char buffer[64]; + HTREEITEM i; + TVITEM item; + char buffer[64]; if (GetWindowLongPtr(hwnd, GWLP_USERDATA) != 1) return 0; i = TreeView_GetSelection(((LPNMHDR) lParam)->hwndFrom); - - SendMessage (hwnd, WM_SETREDRAW, false, 0); - - item.hItem = i; - item.pszText = buffer; - item.cchTextMax = sizeof(buffer); - item.mask = TVIF_TEXT | TVIF_PARAM; - TreeView_GetItem(((LPNMHDR) lParam)->hwndFrom, &item); - { - /* Destroy all controls in the currently visible panel. */ - int k; - HWND item; - struct winctrl *c; - while ((c = winctrl_findbyindex(&ctrls_panel, 0)) != NULL) { - for (k = 0; k < c->num_ids; k++) { - item = GetDlgItem(hwnd, c->base_id + k); - if (item) - DestroyWindow(item); - } - winctrl_rem_shortcuts(&dp, c); - winctrl_remove(&ctrls_panel, c); - sfree(c->data); - sfree(c); - } - } - create_controls(hwnd, (char *)item.lParam); + SendMessage (hwnd, WM_SETREDRAW, false, 0); - dlg_refresh(NULL, &dp); /* set up control values */ - - SendMessage (hwnd, WM_SETREDRAW, true, 0); - InvalidateRect (hwnd, NULL, true); + item.hItem = i; + item.pszText = buffer; + item.cchTextMax = sizeof(buffer); + item.mask = TVIF_TEXT | TVIF_PARAM; + TreeView_GetItem(((LPNMHDR) lParam)->hwndFrom, &item); + { + /* Destroy all controls in the currently visible panel. */ + int k; + HWND item; + struct winctrl *c; - SetFocus(((LPNMHDR) lParam)->hwndFrom); /* ensure focus stays */ - return 0; - } - break; + while ((c = winctrl_findbyindex(&ctrls_panel, 0)) != NULL) { + for (k = 0; k < c->num_ids; k++) { + item = GetDlgItem(hwnd, c->base_id + k); + if (item) + DestroyWindow(item); + } + winctrl_rem_shortcuts(&dp, c); + winctrl_remove(&ctrls_panel, c); + sfree(c->data); + sfree(c); + } + } + create_controls(hwnd, (char *)item.lParam); + + dlg_refresh(NULL, &dp); /* set up control values */ + + SendMessage (hwnd, WM_SETREDRAW, true, 0); + InvalidateRect (hwnd, NULL, true); + + SetFocus(((LPNMHDR) lParam)->hwndFrom); /* ensure focus stays */ + return 0; + } + break; case WM_COMMAND: case WM_DRAWITEM: - default: /* also handle drag list msg here */ - /* - * Only process WM_COMMAND once the dialog is fully formed. - */ - if (GetWindowLongPtr(hwnd, GWLP_USERDATA) == 1) { - ret = winctrl_handle_command(&dp, msg, wParam, lParam); - if (dp.ended && GetCapture() != hwnd) - SaneEndDialog(hwnd, dp.endresult ? 1 : 0); - } else - ret = 0; - return ret; + default: /* also handle drag list msg here */ + /* + * Only process WM_COMMAND once the dialog is fully formed. + */ + if (GetWindowLongPtr(hwnd, GWLP_USERDATA) == 1) { + ret = winctrl_handle_command(&dp, msg, wParam, lParam); + if (dp.ended && GetCapture() != hwnd) + SaneEndDialog(hwnd, dp.endresult ? 1 : 0); + } else + ret = 0; + return ret; case WM_HELP: - if (!winctrl_context_help(&dp, hwnd, - ((LPHELPINFO)lParam)->iCtrlId)) - MessageBeep(0); + if (!winctrl_context_help(&dp, hwnd, + ((LPHELPINFO)lParam)->iCtrlId)) + MessageBeep(0); break; case WM_CLOSE: - quit_help(hwnd); - SaneEndDialog(hwnd, 0); - return 0; + quit_help(hwnd); + SaneEndDialog(hwnd, 0); + return 0; - /* Grrr Explorer will maximize Dialogs! */ + /* Grrr Explorer will maximize Dialogs! */ case WM_SIZE: - if (wParam == SIZE_MAXIMIZED) - force_normal(hwnd); - return 0; + if (wParam == SIZE_MAXIMIZED) + force_normal(hwnd); + return 0; } return 0; @@ -682,12 +682,12 @@ void defuse_showwindow(void) * setting. */ { - HWND hwnd; - hwnd = CreateDialog(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), - NULL, NullDlgProc); - ShowWindow(hwnd, SW_HIDE); - SetActiveWindow(hwnd); - DestroyWindow(hwnd); + HWND hwnd; + hwnd = CreateDialog(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), + NULL, NullDlgProc); + ShowWindow(hwnd, SW_HIDE); + SetActiveWindow(hwnd); + DestroyWindow(hwnd); } } @@ -707,11 +707,11 @@ bool do_config(void) dp.errtitle = dupprintf("%s Error", appname); dp.data = conf; dlg_auto_set_fixed_pitch_flag(&dp); - dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */ + dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */ ret = - SaneDialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL, - GenericMainDlgProc); + SaneDialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL, + GenericMainDlgProc); ctrl_free_box(ctrlbox); winctrl_cleanup(&ctrls_panel); @@ -742,10 +742,10 @@ bool do_reconfig(HWND hwnd, int protcfginfo) dp.errtitle = dupprintf("%s Error", appname); dp.data = conf; dlg_auto_set_fixed_pitch_flag(&dp); - dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */ + dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */ ret = SaneDialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL, - GenericMainDlgProc); + GenericMainDlgProc); ctrl_free_box(ctrlbox); winctrl_cleanup(&ctrls_base); @@ -753,7 +753,7 @@ bool do_reconfig(HWND hwnd, int protcfginfo) dp_cleanup(&dp); if (!ret) - conf_copy_into(conf, backup_conf); + conf_copy_into(conf, backup_conf); conf_free(backup_conf); @@ -778,11 +778,11 @@ static void win_gui_eventlog(LogPolicy *lp, const char *string) sfree(*location); *location = dupcat(timebuf, string, (const char *)NULL); if (logbox) { - int count; - SendDlgItemMessage(logbox, IDN_LIST, LB_ADDSTRING, - 0, (LPARAM) *location); - 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) *location); + count = SendDlgItemMessage(logbox, IDN_LIST, LB_GETCOUNT, 0, 0); + SendDlgItemMessage(logbox, IDN_LIST, LB_SETTOPINDEX, count - 1, 0); } if (ninitial < LOGEVENT_INITIAL_MAX) { ninitial++; @@ -806,9 +806,9 @@ static void win_gui_logging_error(LogPolicy *lp, const char *event) 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); } @@ -826,34 +826,34 @@ int win_seat_verify_ssh_host_key( 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 %s key fingerprint is:\n" - "%s\n" - "If you trust this host, hit Yes to add the key to\n" - "%s's cache and carry on connecting.\n" - "If you want to carry on connecting just once, without\n" - "adding the key to the cache, hit No.\n" - "If you do not trust this host, hit Cancel 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 %s key fingerprint is:\n" + "%s\n" + "If you trust this host, hit Yes to add the key to\n" + "%s's cache and carry on connecting.\n" + "If you want to carry on connecting just once, without\n" + "adding the key to the cache, hit No.\n" + "If you do not trust this host, hit Cancel 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 %s 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 %s key fingerprint is:\n" - "%s\n" - "If you were expecting this change and trust the new key,\n" - "hit Yes to update %s'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 %s 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 %s key fingerprint is:\n" + "%s\n" + "If you were expecting this change and trust the new key,\n" + "hit Yes to update %s'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[] = "%s Security Alert"; @@ -862,41 +862,41 @@ int win_seat_verify_ssh_host_key( */ ret = verify_host_key(host, port, keytype, keystr); - if (ret == 0) /* success - key matched OK */ - return 1; - else if (ret == 2) { /* key was different */ - int mbret; - char *text = dupprintf(wrongmsg, appname, keytype, fingerprint, - appname); - char *caption = dupprintf(mbtitle, appname); - mbret = message_box(text, caption, - MB_ICONWARNING | MB_YESNOCANCEL | MB_DEFBUTTON3, - HELPCTXID(errors_hostkey_changed)); - assert(mbret==IDYES || mbret==IDNO || mbret==IDCANCEL); - sfree(text); - sfree(caption); - if (mbret == IDYES) { - store_host_key(host, port, keytype, keystr); - return 1; - } else if (mbret == IDNO) - return 1; - } else if (ret == 1) { /* key was absent */ - int mbret; - char *text = dupprintf(absentmsg, keytype, fingerprint, appname); - char *caption = dupprintf(mbtitle, appname); - mbret = message_box(text, caption, - MB_ICONWARNING | MB_YESNOCANCEL | MB_DEFBUTTON3, - HELPCTXID(errors_hostkey_absent)); - assert(mbret==IDYES || mbret==IDNO || mbret==IDCANCEL); - sfree(text); - sfree(caption); - if (mbret == IDYES) { - store_host_key(host, port, keytype, keystr); - return 1; - } else if (mbret == IDNO) - return 1; + if (ret == 0) /* success - key matched OK */ + return 1; + else if (ret == 2) { /* key was different */ + int mbret; + char *text = dupprintf(wrongmsg, appname, keytype, fingerprint, + appname); + char *caption = dupprintf(mbtitle, appname); + mbret = message_box(text, caption, + MB_ICONWARNING | MB_YESNOCANCEL | MB_DEFBUTTON3, + HELPCTXID(errors_hostkey_changed)); + assert(mbret==IDYES || mbret==IDNO || mbret==IDCANCEL); + sfree(text); + sfree(caption); + if (mbret == IDYES) { + store_host_key(host, port, keytype, keystr); + return 1; + } else if (mbret == IDNO) + return 1; + } else if (ret == 1) { /* key was absent */ + int mbret; + char *text = dupprintf(absentmsg, keytype, fingerprint, appname); + char *caption = dupprintf(mbtitle, appname); + mbret = message_box(text, caption, + MB_ICONWARNING | MB_YESNOCANCEL | MB_DEFBUTTON3, + HELPCTXID(errors_hostkey_absent)); + assert(mbret==IDYES || mbret==IDNO || mbret==IDCANCEL); + sfree(text); + sfree(caption); + if (mbret == IDYES) { + store_host_key(host, port, keytype, keystr); + return 1; + } else if (mbret == IDNO) + return 1; } - return 0; /* abandon the connection */ + return 0; /* abandon the connection */ } /* @@ -909,24 +909,24 @@ int win_seat_confirm_weak_crypto_primitive( { static const char mbtitle[] = "%s Security Alert"; static const char msg[] = - "The first %s supported by the server\n" - "is %s, which is below the configured\n" - "warning threshold.\n" - "Do you want to continue with this connection?\n"; + "The first %s supported by the server\n" + "is %s, which is below the configured\n" + "warning threshold.\n" + "Do you want to continue with this connection?\n"; char *message, *title; int mbret; message = dupprintf(msg, algtype, algname); title = dupprintf(mbtitle, appname); mbret = MessageBox(NULL, message, title, - MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); + MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); socket_reselect_all(); sfree(message); sfree(title); if (mbret == IDYES) - return 1; + return 1; else - return 0; + return 0; } int win_seat_confirm_weak_cached_hostkey( @@ -935,26 +935,26 @@ int win_seat_confirm_weak_cached_hostkey( { static const char mbtitle[] = "%s Security Alert"; static const char msg[] = - "The first host key type we have stored for this server\n" - "is %s, which is below the configured warning threshold.\n" - "The server also provides the following types of host key\n" + "The first host key type we have stored for this server\n" + "is %s, which is below the configured warning threshold.\n" + "The server also provides the following types of host key\n" "above the threshold, which we do not have stored:\n" "%s\n" - "Do you want to continue with this connection?\n"; + "Do you want to continue with this connection?\n"; char *message, *title; int mbret; message = dupprintf(msg, algname, betteralgs); title = dupprintf(mbtitle, appname); mbret = MessageBox(NULL, message, title, - MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); + MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); socket_reselect_all(); sfree(message); sfree(title); if (mbret == IDYES) - return 1; + return 1; else - return 0; + return 0; } /* @@ -966,12 +966,12 @@ static int win_gui_askappend(LogPolicy *lp, Filename *filename, void *ctx) { static const char msgtemplate[] = - "The session log file \"%.*s\" already exists.\n" - "You can overwrite it with a new session log,\n" - "append your session log to the end of it,\n" - "or disable session logging for this session.\n" - "Hit Yes to wipe the file, No to append to it,\n" - "or Cancel to disable logging."; + "The session log file \"%.*s\" already exists.\n" + "You can overwrite it with a new session log,\n" + "append your session log to the end of it,\n" + "or disable session logging for this session.\n" + "Hit Yes to wipe the file, No to append to it,\n" + "or Cancel to disable logging."; char *message; char *mbtitle; int mbret; @@ -980,7 +980,7 @@ static int win_gui_askappend(LogPolicy *lp, Filename *filename, mbtitle = dupprintf("%s Log to File", appname); mbret = MessageBox(NULL, message, mbtitle, - MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON3); + MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON3); socket_reselect_all(); @@ -988,11 +988,11 @@ static int win_gui_askappend(LogPolicy *lp, Filename *filename, sfree(mbtitle); if (mbret == IDYES) - return 2; + return 2; else if (mbret == IDNO) - return 1; + return 1; else - return 0; + return 0; } static const LogPolicyVtable default_logpolicy_vt = { @@ -1004,7 +1004,7 @@ LogPolicy default_logpolicy[1] = {{ &default_logpolicy_vt }}; /* * Warn about the obsolescent key file format. - * + * * Uniquely among these functions, this one does _not_ expect a * frontend handle. This means that if PuTTY is ported to a * platform which requires frontend handles, this function will be @@ -1016,15 +1016,15 @@ void old_keyfile_warning(void) { static const char mbtitle[] = "%s Key File Warning"; static const char message[] = - "You are loading an SSH-2 private key which has an\n" - "old version of the file format. This means your key\n" - "file is not fully tamperproof. Future versions of\n" - "%s may stop supporting this private key format,\n" - "so we recommend you convert your key to the new\n" - "format.\n" - "\n" - "You can perform this conversion by loading the key\n" - "into PuTTYgen and then saving it again."; + "You are loading an SSH-2 private key which has an\n" + "old version of the file format. This means your key\n" + "file is not fully tamperproof. Future versions of\n" + "%s may stop supporting this private key format,\n" + "so we recommend you convert your key to the new\n" + "format.\n" + "\n" + "You can perform this conversion by loading the key\n" + "into PuTTYgen and then saving it again."; char *msg, *title; msg = dupprintf(message, appname); diff --git a/windows/window.c b/windows/window.c index cf1d0e88..f9e09aa3 100644 --- a/windows/window.c +++ b/windows/window.c @@ -18,7 +18,7 @@ #define COMPILE_MULTIMON_STUBS #endif -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #include "putty.h" #include "terminal.h" #include "storage.h" @@ -51,7 +51,7 @@ #define IDM_ABOUT 0x0150 #define IDM_SAVEDSESS 0x0160 #define IDM_COPYALL 0x0170 -#define IDM_FULLSCREEN 0x0180 +#define IDM_FULLSCREEN 0x0180 #define IDM_COPY 0x0190 #define IDM_PASTE 0x01A0 #define IDM_SPECIALSEP 0x0200 @@ -77,7 +77,7 @@ /* Mouse wheel support. */ #ifndef WM_MOUSEWHEEL -#define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */ +#define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */ #endif #ifndef WHEEL_DELTA #define WHEEL_DELTA 120 @@ -91,7 +91,7 @@ static Mouse_Button translate_button(Mouse_Button button); static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, - unsigned char *output); + unsigned char *output); static void conftopalette(void); static void systopalette(void); static void init_palette(void); @@ -117,7 +117,7 @@ static bool font_dualwidth, font_varpitch; static int offset_width, offset_height; static bool was_zoomed = false; static int prev_rows, prev_cols; - + static void flash_window(int mode); static void sys_cursor_update(void); static bool get_fullscreen_rect(RECT * ss); @@ -169,17 +169,17 @@ struct agent_callback { #define FONT_BOLD 1 #define FONT_UNDERLINE 2 #define FONT_BOLDUND 3 -#define FONT_WIDE 0x04 -#define FONT_HIGH 0x08 -#define FONT_NARROW 0x10 +#define FONT_WIDE 0x04 +#define FONT_HIGH 0x08 +#define FONT_NARROW 0x10 -#define FONT_OEM 0x20 -#define FONT_OEMBOLD 0x21 -#define FONT_OEMUND 0x22 +#define FONT_OEM 0x20 +#define FONT_OEMBOLD 0x21 +#define FONT_OEMUND 0x22 #define FONT_OEMBOLDUND 0x23 -#define FONT_MAXNO 0x40 -#define FONT_SHIFT 5 +#define FONT_MAXNO 0x40 +#define FONT_SHIFT 5 static HFONT fonts[FONT_MAXNO]; static LOGFONT lfont; static bool fontflag[FONT_MAXNO]; @@ -378,11 +378,11 @@ static void start_backend(void) */ vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol)); if (!vt) { - char *str = dupprintf("%s Internal Error", appname); - MessageBox(NULL, "Unsupported protocol number found", - str, MB_OK | MB_ICONEXCLAMATION); - sfree(str); - cleanup_exit(1); + char *str = dupprintf("%s Internal Error", appname); + MessageBox(NULL, "Unsupported protocol number found", + str, MB_OK | MB_ICONEXCLAMATION); + sfree(str); + cleanup_exit(1); } seat_set_trust_status(win_seat, true); @@ -393,20 +393,20 @@ static void start_backend(void) conf_get_bool(conf, CONF_tcp_nodelay), conf_get_bool(conf, CONF_tcp_keepalives)); if (error) { - char *str = dupprintf("%s Error", appname); + char *str = dupprintf("%s Error", appname); char *msg = dupprintf("Unable to open connection to\n%s\n%s", conf_dest(conf), error); - MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK); - sfree(str); - sfree(msg); - exit(0); + MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK); + sfree(str); + sfree(msg); + exit(0); } window_name = icon_name = NULL; char *title_to_free = NULL; title = conf_get_str(conf, CONF_wintitle); if (!*title) { - title_to_free = dupprintf("%s - %s", realhost, appname); - title = title_to_free; + title_to_free = dupprintf("%s - %s", realhost, appname); + title = title_to_free; } sfree(realhost); win_set_title(wintw, title); @@ -430,7 +430,7 @@ static void start_backend(void) * whether it was us who removed it or not!) */ for (i = 0; i < lenof(popup_menus); i++) { - DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND); + DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND); } session_closed = false; @@ -450,14 +450,14 @@ static void close_session(void *ignored_context) sfree(newtitle); if (ldisc) { - ldisc_free(ldisc); - ldisc = NULL; + ldisc_free(ldisc); + ldisc = NULL; } if (backend) { backend_free(backend); backend = NULL; term_provide_backend(term, NULL); - seat_update_specials_menu(win_seat); + seat_update_specials_menu(win_seat); } /* @@ -465,9 +465,9 @@ static void close_session(void *ignored_context) * delete first to ensure we never end up with more than one. */ for (i = 0; i < lenof(popup_menus); i++) { - DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND); - InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED, - IDM_RESTART, "&Restart Session"); + DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND); + InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED, + IDM_RESTART, "&Restart Session"); } } @@ -505,8 +505,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * using instead. */ if (osMajorVersion < 4 || - (osMajorVersion == 4 && osPlatformId != VER_PLATFORM_WIN32_NT)) - wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG"); + (osMajorVersion == 4 && osPlatformId != VER_PLATFORM_WIN32_NT)) + wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG"); init_help(); @@ -520,44 +520,44 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) hr = CoInitialize(NULL); if (hr != S_OK && hr != S_FALSE) { char *str = dupprintf("%s Fatal Error", appname); - MessageBox(NULL, "Failed to initialize COM subsystem", - str, MB_OK | MB_ICONEXCLAMATION); - sfree(str); - return 1; + MessageBox(NULL, "Failed to initialize COM subsystem", + str, MB_OK | MB_ICONEXCLAMATION); + sfree(str); + return 1; } /* * Process the command line. */ { - char *p; + char *p; bool special_launchable_argument = false; - default_protocol = be_default_protocol; - /* Find the appropriate default port. */ - { + default_protocol = be_default_protocol; + /* Find the appropriate default port. */ + { const struct BackendVtable *vt = backend_vt_from_proto(default_protocol); - default_port = 0; /* illegal */ + default_port = 0; /* illegal */ if (vt) default_port = vt->default_port; - } - conf_set_int(conf, CONF_logtype, LGTYP_NONE); + } + conf_set_int(conf, CONF_logtype, LGTYP_NONE); - do_defaults(NULL, conf); + do_defaults(NULL, conf); - p = cmdline; + p = cmdline; - /* - * Process a couple of command-line options which are more - * easily dealt with before the line is broken up into words. - * These are the old-fashioned but convenient @sessionname and - * the internal-use-only &sharedmemoryhandle, plus the &R - * prefix for -restrict-acl, all of which are used by PuTTYs - * auto-launching each other via System-menu options. - */ - while (*p && isspace(*p)) - p++; + /* + * Process a couple of command-line options which are more + * easily dealt with before the line is broken up into words. + * These are the old-fashioned but convenient @sessionname and + * the internal-use-only &sharedmemoryhandle, plus the &R + * prefix for -restrict-acl, all of which are used by PuTTYs + * auto-launching each other via System-menu options. + */ + while (*p && isspace(*p)) + p++; if (*p == '&' && p[1] == 'R' && (!p[2] || p[2] == '@' || p[2] == '&')) { /* &R restrict-acl prefix */ @@ -566,7 +566,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) p += 2; } - if (*p == '@') { + if (*p == '@') { /* * An initial @ means that the whole of the rest of the * command line should be treated as the name of a saved @@ -574,109 +574,109 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * very convenient means of automated saved-session * launching, via IDM_SAVEDSESS or Windows 7 jump lists. */ - int i = strlen(p); - while (i > 1 && isspace(p[i - 1])) - i--; - p[i] = '\0'; - do_defaults(p + 1, conf); - if (!conf_launchable(conf) && !do_config()) { - cleanup_exit(0); - } + int i = strlen(p); + while (i > 1 && isspace(p[i - 1])) + i--; + p[i] = '\0'; + do_defaults(p + 1, conf); + if (!conf_launchable(conf) && !do_config()) { + cleanup_exit(0); + } special_launchable_argument = true; - } else if (*p == '&') { - /* - * An initial & means we've been given a command line - * containing the hex value of a HANDLE for a file - * mapping object, which we must then interpret as a - * serialised Conf. - */ - HANDLE filemap; - void *cp; - unsigned cpsize; - if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 && - (cp = MapViewOfFile(filemap, FILE_MAP_READ, - 0, 0, cpsize)) != NULL) { + } else if (*p == '&') { + /* + * An initial & means we've been given a command line + * containing the hex value of a HANDLE for a file + * mapping object, which we must then interpret as a + * serialised Conf. + */ + HANDLE filemap; + void *cp; + unsigned cpsize; + if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 && + (cp = MapViewOfFile(filemap, FILE_MAP_READ, + 0, 0, cpsize)) != NULL) { BinarySource src[1]; BinarySource_BARE_INIT(src, cp, cpsize); - if (!conf_deserialise(conf, src)) + if (!conf_deserialise(conf, src)) modalfatalbox("Serialised configuration data was invalid"); - UnmapViewOfFile(cp); - CloseHandle(filemap); - } else if (!do_config()) { - cleanup_exit(0); - } + UnmapViewOfFile(cp); + CloseHandle(filemap); + } else if (!do_config()) { + cleanup_exit(0); + } special_launchable_argument = true; - } else if (!*p) { + } else if (!*p) { /* Do-nothing case for an empty command line - or rather, * for a command line that's empty _after_ we strip off * the &R prefix. */ } else { - /* - * Otherwise, break up the command line and deal with - * it sensibly. - */ - int argc, i; - char **argv; - - split_into_argv(cmdline, &argc, &argv, NULL); + /* + * Otherwise, break up the command line and deal with + * it sensibly. + */ + int argc, i; + char **argv; - for (i = 0; i < argc; i++) { - char *p = argv[i]; - int ret; + split_into_argv(cmdline, &argc, &argv, NULL); - ret = cmdline_process_param(p, i+1 r.right - r.left) - guess_width = r.right - r.left; - if (guess_height > r.bottom - r.top) - guess_height = r.bottom - r.top; + RECT r; + get_fullscreen_rect(&r); + if (guess_width > r.right - r.left) + guess_width = r.right - r.left; + if (guess_height > r.bottom - r.top) + guess_height = r.bottom - r.top; } { - int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL; - int exwinmode = 0; + int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL; + int exwinmode = 0; wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname); - if (!conf_get_bool(conf, CONF_scrollbar)) - winmode &= ~(WS_VSCROLL); - if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) - winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); - if (conf_get_bool(conf, CONF_alwaysontop)) - exwinmode |= WS_EX_TOPMOST; - if (conf_get_bool(conf, CONF_sunken_edge)) - exwinmode |= WS_EX_CLIENTEDGE; - hwnd = CreateWindowExW(exwinmode, uappname, uappname, + if (!conf_get_bool(conf, CONF_scrollbar)) + winmode &= ~(WS_VSCROLL); + if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) + winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); + if (conf_get_bool(conf, CONF_alwaysontop)) + exwinmode |= WS_EX_TOPMOST; + if (conf_get_bool(conf, CONF_sunken_edge)) + exwinmode |= WS_EX_CLIENTEDGE; + hwnd = CreateWindowExW(exwinmode, uappname, uappname, winmode, CW_USEDEFAULT, CW_USEDEFAULT, guess_width, guess_height, NULL, NULL, inst, NULL); @@ -763,19 +763,19 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) logctx = log_init(default_logpolicy, conf); term_provide_logctx(term, logctx); term_size(term, conf_get_int(conf, CONF_height), - conf_get_int(conf, CONF_width), - conf_get_int(conf, CONF_savelines)); + conf_get_int(conf, CONF_width), + conf_get_int(conf, CONF_savelines)); /* * Correct the guesses for extra_{width,height}. */ { - RECT cr, wr; - GetWindowRect(hwnd, &wr); - GetClientRect(hwnd, &cr); - offset_width = offset_height = conf_get_int(conf, CONF_window_border); - extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; - extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; + RECT cr, wr; + GetWindowRect(hwnd, &wr); + GetClientRect(hwnd, &cr); + offset_width = offset_height = conf_get_int(conf, CONF_window_border); + extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; + extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; } /* @@ -785,18 +785,18 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) guess_width = extra_width + font_width * term->cols; guess_height = extra_height + font_height * term->rows; SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height, - SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER); + 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 = snewn(size, char); - 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 = snewn(size, char); + memset(bits, 0, size); + caretbm = CreateBitmap(font_width, font_height, 1, 1, bits); + sfree(bits); } CreateCaret(hwnd, caretbm, font_width, font_height); @@ -804,15 +804,15 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * Initialise the scroll bar. */ { - SCROLLINFO si; + SCROLLINFO si; - si.cbSize = sizeof(si); - si.fMask = SIF_ALL | SIF_DISABLENOSCROLL; - si.nMin = 0; - si.nMax = term->rows - 1; - si.nPage = term->rows; - si.nPos = 0; - SetScrollInfo(hwnd, SB_VERT, &si, false); + si.cbSize = sizeof(si); + si.fMask = SIF_ALL | SIF_DISABLENOSCROLL; + si.nMin = 0; + si.nMax = term->rows - 1; + si.nPage = term->rows; + si.nPos = 0; + SetScrollInfo(hwnd, SB_VERT, &si, false); } /* @@ -826,45 +826,45 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * Set up the session-control options on the system menu. */ { - HMENU m; - int j; - char *str; + HMENU m; + int j; + char *str; - popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, false); - popup_menus[CTXMENU].menu = CreatePopupMenu(); - AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_COPY, "&Copy"); - AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste"); + popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, false); + popup_menus[CTXMENU].menu = CreatePopupMenu(); + AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_COPY, "&Copy"); + AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste"); - savedsess_menu = CreateMenu(); - get_sesslist(&sesslist, true); - update_savedsess_menu(); + savedsess_menu = CreateMenu(); + get_sesslist(&sesslist, true); + update_savedsess_menu(); - for (j = 0; j < lenof(popup_menus); j++) { - m = popup_menus[j].menu; + for (j = 0; j < lenof(popup_menus); j++) { + m = popup_menus[j].menu; - 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(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu, - "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, (conf_get_int(conf, CONF_resize_action) - == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED, - IDM_FULLSCREEN, "&Full Screen"); - AppendMenu(m, MF_SEPARATOR, 0, 0); - if (has_help()) - AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help"); - str = dupprintf("&About %s", appname); - AppendMenu(m, MF_ENABLED, IDM_ABOUT, str); - sfree(str); - } + 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(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu, + "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, (conf_get_int(conf, CONF_resize_action) + == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED, + IDM_FULLSCREEN, "&Full Screen"); + AppendMenu(m, MF_SEPARATOR, 0, 0); + if (has_help()) + AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help"); + str = dupprintf("&About %s", appname); + AppendMenu(m, MF_ENABLED, IDM_ABOUT, str); + sfree(str); + } } if (restricted_acl) { @@ -895,8 +895,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) UpdateWindow(hwnd); while (1) { - HANDLE *handles; - int nhandles, n; + HANDLE *handles; + int nhandles, n; DWORD timeout; if (toplevel_callback_pending() || @@ -925,23 +925,23 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) term_set_focus(term, GetForegroundWindow() == hwnd); } - handles = handle_get_events(&nhandles); + handles = handle_get_events(&nhandles); - n = MsgWaitForMultipleObjects(nhandles, handles, false, + n = MsgWaitForMultipleObjects(nhandles, handles, false, timeout, QS_ALLINPUT); - if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) { - handle_got_event(handles[n - WAIT_OBJECT_0]); - sfree(handles); - } else - sfree(handles); + if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) { + handle_got_event(handles[n - WAIT_OBJECT_0]); + sfree(handles); + } else + sfree(handles); - while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { - if (msg.message == WM_QUIT) - goto finished; /* two-level break */ + while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { + if (msg.message == WM_QUIT) + goto finished; /* two-level break */ - if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg))) - DispatchMessageW(&msg); + if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg))) + DispatchMessageW(&msg); /* * WM_NETEVENT messages seem to jump ahead of others in @@ -964,14 +964,14 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) */ if (msg.message != WM_NETEVENT) break; - } + } run_toplevel_callbacks(); } finished: - cleanup_exit(msg.wParam); /* this doesn't return... */ - return msg.wParam; /* ... but optimiser doesn't know */ + cleanup_exit(msg.wParam); /* this doesn't return... */ + return msg.wParam; /* ... but optimiser doesn't know */ } static void setup_clipboards(Terminal *term, Conf *conf) @@ -1009,11 +1009,11 @@ void cleanup_exit(int code) deinit_fonts(); sfree(logpal); if (pal) - DeleteObject(pal); + DeleteObject(pal); sk_cleanup(); if (conf_get_int(conf, CONF_protocol) == PROT_SSH) { - random_save_seed(); + random_save_seed(); } shutdown_help(); @@ -1030,21 +1030,21 @@ char *do_select(SOCKET skt, bool startup) { int msg, events; if (startup) { - msg = WM_NETEVENT; - events = (FD_CONNECT | FD_READ | FD_WRITE | - FD_OOB | FD_CLOSE | FD_ACCEPT); + msg = WM_NETEVENT; + events = (FD_CONNECT | FD_READ | FD_WRITE | + FD_OOB | FD_CLOSE | FD_ACCEPT); } else { - msg = events = 0; + msg = events = 0; } if (!hwnd) - return "do_select(): internal error (hwnd==NULL)"; + return "do_select(): internal error (hwnd==NULL)"; if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) { - switch (p_WSAGetLastError()) { - case WSAENETDOWN: - return "Network is down"; - default: - return "WSAAsyncSelect(): unknown error"; - } + switch (p_WSAGetLastError()) { + case WSAENETDOWN: + return "Network is down"; + default: + return "WSAAsyncSelect(): unknown error"; + } } return NULL; } @@ -1058,14 +1058,14 @@ static void update_savedsess_menu(void) while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ; /* skip sesslist.sessions[0] == Default Settings */ for (i = 1; - i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions - : MENU_SAVED_MAX+1); - i++) - AppendMenu(savedsess_menu, MF_ENABLED, - IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP, - sesslist.sessions[i]); + i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions + : MENU_SAVED_MAX+1); + i++) + AppendMenu(savedsess_menu, MF_ENABLED, + IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP, + sesslist.sessions[i]); if (sesslist.nsessions <= 1) - AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)"); + AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)"); } /* @@ -1079,62 +1079,62 @@ static void win_seat_update_specials_menu(Seat *seat) if (backend) specials = backend_get_specials(backend); else - specials = NULL; + specials = NULL; if (specials) { - /* We can't use Windows to provide a stack for submenus, so - * here's a lame "stack" that will do for now. */ - HMENU saved_menu = NULL; - int nesting = 1; - new_menu = CreatePopupMenu(); - for (i = 0; nesting > 0; i++) { - assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX); - switch (specials[i].code) { - case SS_SEP: - AppendMenu(new_menu, MF_SEPARATOR, 0, 0); - break; - case SS_SUBMENU: - assert(nesting < 2); - nesting++; - saved_menu = new_menu; /* XXX lame stacking */ - new_menu = CreatePopupMenu(); - AppendMenu(saved_menu, MF_POPUP | MF_ENABLED, - (UINT_PTR) new_menu, specials[i].name); - break; - case SS_EXITMENU: - nesting--; - if (nesting) { - new_menu = saved_menu; /* XXX lame stacking */ - saved_menu = NULL; - } - break; - default: - AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i, - specials[i].name); - break; - } - } - /* Squirrel the highest special. */ - n_specials = i - 1; + /* We can't use Windows to provide a stack for submenus, so + * here's a lame "stack" that will do for now. */ + HMENU saved_menu = NULL; + int nesting = 1; + new_menu = CreatePopupMenu(); + for (i = 0; nesting > 0; i++) { + assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX); + switch (specials[i].code) { + case SS_SEP: + AppendMenu(new_menu, MF_SEPARATOR, 0, 0); + break; + case SS_SUBMENU: + assert(nesting < 2); + nesting++; + saved_menu = new_menu; /* XXX lame stacking */ + new_menu = CreatePopupMenu(); + AppendMenu(saved_menu, MF_POPUP | MF_ENABLED, + (UINT_PTR) new_menu, specials[i].name); + break; + case SS_EXITMENU: + nesting--; + if (nesting) { + new_menu = saved_menu; /* XXX lame stacking */ + saved_menu = NULL; + } + break; + default: + AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i, + specials[i].name); + break; + } + } + /* Squirrel the highest special. */ + n_specials = i - 1; } else { - new_menu = NULL; - n_specials = 0; + new_menu = NULL; + n_specials = 0; } for (j = 0; j < lenof(popup_menus); j++) { - if (specials_menu) { - /* XXX does this free up all submenus? */ - DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu, + if (specials_menu) { + /* XXX does this free up all submenus? */ + DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu, MF_BYCOMMAND); - DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND); - } - if (new_menu) { - InsertMenu(popup_menus[j].menu, IDM_SHOWLOG, - MF_BYCOMMAND | MF_POPUP | MF_ENABLED, - (UINT_PTR) new_menu, "S&pecial Command"); - InsertMenu(popup_menus[j].menu, IDM_SHOWLOG, - MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0); - } + DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND); + } + if (new_menu) { + InsertMenu(popup_menus[j].menu, IDM_SHOWLOG, + MF_BYCOMMAND | MF_POPUP | MF_ENABLED, + (UINT_PTR) new_menu, "S&pecial Command"); + InsertMenu(popup_menus[j].menu, IDM_SHOWLOG, + MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0); + } } specials_menu = new_menu; } @@ -1146,34 +1146,34 @@ static void update_mouse_pointer(void) static bool forced_visible = false; switch (busy_status) { case BUSY_NOT: - if (send_raw_mouse) - curstype = IDC_ARROW; - else - curstype = IDC_IBEAM; - break; + if (send_raw_mouse) + curstype = IDC_ARROW; + else + curstype = IDC_IBEAM; + break; case BUSY_WAITING: - curstype = IDC_APPSTARTING; /* this may be an abuse */ - force_visible = true; - break; + curstype = IDC_APPSTARTING; /* this may be an abuse */ + force_visible = true; + break; case BUSY_CPU: - curstype = IDC_WAIT; - force_visible = true; - break; + curstype = IDC_WAIT; + force_visible = true; + break; default: - unreachable("Bad busy_status"); + unreachable("Bad busy_status"); } { - HCURSOR cursor = LoadCursor(NULL, curstype); - SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor); - SetCursor(cursor); /* force redraw of cursor at current posn */ + HCURSOR cursor = LoadCursor(NULL, curstype); + SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor); + SetCursor(cursor); /* force redraw of cursor at current posn */ } if (force_visible != forced_visible) { - /* We want some cursor shapes to be visible always. - * Along with show_mouseptr(), this manages the ShowCursor() - * counter such that if we switch back to a non-force_visible - * cursor, the previous visibility state is restored. */ - ShowCursor(force_visible); - forced_visible = force_visible; + /* We want some cursor shapes to be visible always. + * Along with show_mouseptr(), this manages the ShowCursor() + * counter such that if we switch back to a non-force_visible + * cursor, the previous visibility state is restored. */ + ShowCursor(force_visible); + forced_visible = force_visible; } } @@ -1203,9 +1203,9 @@ static void win_seat_connection_fatal(Seat *seat, const char *msg) sfree(title); if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON) - PostQuitMessage(1); + PostQuitMessage(1); else { - queue_toplevel_callback(close_session, NULL); + queue_toplevel_callback(close_session, NULL); } } @@ -1245,29 +1245,29 @@ static void conftopalette(void) { int i; static const int ww[] = { - 256, 257, 258, 259, 260, 261, - 0, 8, 1, 9, 2, 10, 3, 11, - 4, 12, 5, 13, 6, 14, 7, 15 + 256, 257, 258, 259, 260, 261, + 0, 8, 1, 9, 2, 10, 3, 11, + 4, 12, 5, 13, 6, 14, 7, 15 }; for (i = 0; i < 22; i++) { - int w = ww[i]; - defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0); - defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1); - defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2); + int w = ww[i]; + defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0); + defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1); + defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2); } for (i = 0; i < NEXTCOLOURS; i++) { - if (i < 216) { - int r = i / 36, g = (i / 6) % 6, b = i % 6; - defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0; - defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0; - defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0; - } else { - int shade = i - 216; - shade = shade * 10 + 8; - defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen = - defpal[i+16].rgbtBlue = shade; - } + if (i < 216) { + int r = i / 36, g = (i / 6) % 6, b = i % 6; + defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0; + defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0; + defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0; + } else { + int shade = i - 216; + shade = shade * 10 + 8; + defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen = + defpal[i+16].rgbtBlue = shade; + } } /* Override with system colours if appropriate */ @@ -1286,20 +1286,20 @@ static void systopalette(void) int i; static const struct { int nIndex; int norm; int bold; } or[] = { - { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */ - { COLOR_WINDOW, 258, 259 }, /* Default Background */ - { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */ - { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */ + { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */ + { COLOR_WINDOW, 258, 259 }, /* Default Background */ + { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */ + { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */ }; for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) { - COLORREF colour = GetSysColor(or[i].nIndex); - defpal[or[i].norm].rgbtRed = - defpal[or[i].bold].rgbtRed = GetRValue(colour); - defpal[or[i].norm].rgbtGreen = - defpal[or[i].bold].rgbtGreen = GetGValue(colour); - defpal[or[i].norm].rgbtBlue = - defpal[or[i].bold].rgbtBlue = GetBValue(colour); + COLORREF colour = GetSysColor(or[i].nIndex); + defpal[or[i].norm].rgbtRed = + defpal[or[i].bold].rgbtRed = GetRValue(colour); + defpal[or[i].norm].rgbtGreen = + defpal[or[i].bold].rgbtGreen = GetGValue(colour); + defpal[or[i].norm].rgbtBlue = + defpal[or[i].bold].rgbtBlue = GetBValue(colour); } } @@ -1324,31 +1324,31 @@ static void init_palette(void) int i; HDC hdc = GetDC(hwnd); if (hdc) { - if (conf_get_bool(conf, CONF_try_palette) && - GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) { - /* - * This is a genuine case where we must use smalloc - * because the snew macros can't cope. - */ - logpal = smalloc(sizeof(*logpal) - - sizeof(logpal->palPalEntry) - + NALLCOLOURS * sizeof(PALETTEENTRY)); - logpal->palVersion = 0x300; - logpal->palNumEntries = NALLCOLOURS; - for (i = 0; i < NALLCOLOURS; i++) { - logpal->palPalEntry[i].peRed = defpal[i].rgbtRed; - logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen; - logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue; - logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE; - } - pal = CreatePalette(logpal); - if (pal) { - SelectPalette(hdc, pal, false); - RealizePalette(hdc); - SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), false); - } - } - ReleaseDC(hwnd, hdc); + if (conf_get_bool(conf, CONF_try_palette) && + GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) { + /* + * This is a genuine case where we must use smalloc + * because the snew macros can't cope. + */ + logpal = smalloc(sizeof(*logpal) + - sizeof(logpal->palPalEntry) + + NALLCOLOURS * sizeof(PALETTEENTRY)); + logpal->palVersion = 0x300; + logpal->palNumEntries = NALLCOLOURS; + for (i = 0; i < NALLCOLOURS; i++) { + logpal->palPalEntry[i].peRed = defpal[i].rgbtRed; + logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen; + logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue; + logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE; + } + pal = CreatePalette(logpal); + if (pal) { + SelectPalette(hdc, pal, false); + RealizePalette(hdc); + SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), false); + } + } + ReleaseDC(hwnd, hdc); } for (i = 0; i < NALLCOLOURS; i++) internal_set_colour(i, defpal[i].rgbtRed, @@ -1362,8 +1362,8 @@ static void init_palette(void) * characters it had put where. */ static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc, - unsigned short *lpString, UINT cbCount, - CONST INT *lpDx, bool opaque) + unsigned short *lpString, UINT cbCount, + CONST INT *lpDx, bool opaque) { #ifdef __LCC__ /* @@ -1387,11 +1387,11 @@ static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc, gcpr.lpClass = (void *)classbuffer; gcpr.nGlyphs = cbCount; GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr, - FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC); + FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC); ExtTextOut(hdc, x, y, - ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0), - lprc, buffer, cbCount, lpDx); + ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0), + lprc, buffer, cbCount, lpDx); } /* @@ -1404,8 +1404,8 @@ static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc, * before exact_textout() was introduced. */ static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc, - unsigned short *lpString, UINT cbCount, - CONST INT *lpDx, bool opaque) + unsigned short *lpString, UINT cbCount, + CONST INT *lpDx, bool opaque) { int i, j, xp, xn; int bkmode = 0; @@ -1414,32 +1414,32 @@ static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc, xp = xn = x; for (i = 0; i < (int)cbCount ;) { - bool rtl = is_rtl(lpString[i]); + bool rtl = is_rtl(lpString[i]); - xn += lpDx[i]; + xn += lpDx[i]; - for (j = i+1; j < (int)cbCount; j++) { - if (rtl != is_rtl(lpString[j])) - break; - xn += lpDx[j]; - } + for (j = i+1; j < (int)cbCount; j++) { + if (rtl != is_rtl(lpString[j])) + break; + xn += lpDx[j]; + } - /* - * Now [i,j) indicates a maximal substring of lpString - * which should be displayed using the same textout - * function. - */ - if (rtl) { - exact_textout(hdc, xp, y, lprc, lpString+i, j-i, + /* + * Now [i,j) indicates a maximal substring of lpString + * which should be displayed using the same textout + * function. + */ + if (rtl) { + exact_textout(hdc, xp, y, lprc, lpString+i, j-i, font_varpitch ? NULL : lpDx+i, opaque); - } else { - ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0), - lprc, lpString+i, j-i, + } else { + ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0), + lprc, lpString+i, j-i, font_varpitch ? NULL : lpDx+i); - } + } - i = j; - xp = xn; + i = j; + xp = xn; bkmode = GetBkMode(hdc); got_bkmode = true; @@ -1494,7 +1494,7 @@ static int get_font_width(HDC hdc, const TEXTMETRIC *tm) * * - verify that the bold font is the same width as the ordinary * one, and engage shadow bolding if not. - * + * * - verify that the underlined font is the same width as the * ordinary one (manual underlining by means of line drawing can * be done in a pinch). @@ -1513,41 +1513,41 @@ static void init_fonts(int pick_width, int pick_height) int fw_dontcare, fw_bold; for (i = 0; i < FONT_MAXNO; i++) - fonts[i] = NULL; + fonts[i] = NULL; bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ? - BOLD_FONT : BOLD_NONE; + BOLD_FONT : BOLD_NONE; bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? true : false; und_mode = UND_FONT; font = conf_get_fontspec(conf, CONF_font); if (font->isbold) { - fw_dontcare = FW_BOLD; - fw_bold = FW_HEAVY; + fw_dontcare = FW_BOLD; + fw_bold = FW_HEAVY; } else { - fw_dontcare = FW_DONTCARE; - fw_bold = FW_BOLD; + fw_dontcare = FW_DONTCARE; + fw_bold = FW_BOLD; } hdc = GetDC(hwnd); if (pick_height) - font_height = pick_height; + font_height = pick_height; else { - font_height = font->height; - if (font_height > 0) { - font_height = - -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72); - } + font_height = font->height; + if (font_height > 0) { + font_height = + -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72); + } } font_width = pick_width; quality = conf_get_int(conf, CONF_font_quality); #define f(i,c,w,u) \ fonts[i] = CreateFont (font_height, font_width, 0, 0, w, false, u, false, \ - c, OUT_DEFAULT_PRECIS, \ - CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \ - FIXED_PITCH | FF_DONTCARE, font->name) + c, OUT_DEFAULT_PRECIS, \ + CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \ + FIXED_PITCH | FF_DONTCARE, font->name) f(FONT_NORMAL, font->charset, fw_dontcare, false); @@ -1565,7 +1565,7 @@ static void init_fonts(int pick_width, int pick_height) font_dualwidth = true; } if (pick_width == 0 || pick_height == 0) { - font_height = tm.tmHeight; + font_height = tm.tmHeight; font_width = get_font_width(hdc, &tm); } @@ -1575,22 +1575,22 @@ static void init_fonts(int pick_width, int pick_height) #endif { - CHARSETINFO info; - DWORD cset = tm.tmCharSet; - memset(&info, 0xFF, sizeof(info)); + CHARSETINFO info; + DWORD cset = tm.tmCharSet; + memset(&info, 0xFF, sizeof(info)); - /* !!! Yes the next line is right */ - if (cset == OEM_CHARSET) - ucsdata.font_codepage = GetOEMCP(); - else - if (TranslateCharsetInfo ((DWORD *)(ULONG_PTR)cset, + /* !!! Yes the next line is right */ + if (cset == OEM_CHARSET) + ucsdata.font_codepage = GetOEMCP(); + else + if (TranslateCharsetInfo ((DWORD *)(ULONG_PTR)cset, &info, TCI_SRCCHARSET)) - ucsdata.font_codepage = info.ciACP; - else - ucsdata.font_codepage = -1; + ucsdata.font_codepage = info.ciACP; + else + ucsdata.font_codepage = -1; - GetCPInfo(ucsdata.font_codepage, &cpinfo); - ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1); + GetCPInfo(ucsdata.font_codepage, &cpinfo); + ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1); } f(FONT_UNDERLINE, font->charset, fw_dontcare, true); @@ -1613,76 +1613,76 @@ static void init_fonts(int pick_width, int pick_height) * down a single column of the bitmap, half way across.) */ { - HDC und_dc; - HBITMAP und_bm, und_oldbm; - int i; + HDC und_dc; + HBITMAP und_bm, und_oldbm; + int i; bool gotit; - COLORREF c; + 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); - if (!gotit) { - und_mode = UND_LINE; - DeleteObject(fonts[FONT_UNDERLINE]); - fonts[FONT_UNDERLINE] = 0; - } + 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); + if (!gotit) { + und_mode = UND_LINE; + DeleteObject(fonts[FONT_UNDERLINE]); + fonts[FONT_UNDERLINE] = 0; + } } if (bold_font_mode == BOLD_FONT) { - f(FONT_BOLD, font->charset, fw_bold, false); + f(FONT_BOLD, font->charset, fw_bold, false); } #undef f descent = tm.tmAscent + 1; if (descent >= font_height) - descent = font_height - 1; + descent = font_height - 1; for (i = 0; i < 3; i++) { - if (fonts[i]) { - if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm)) - fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight; - else - fontsize[i] = -i; - } else - fontsize[i] = -i; + if (fonts[i]) { + if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm)) + fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight; + else + fontsize[i] = -i; + } else + fontsize[i] = -i; } ReleaseDC(hwnd, hdc); if (trust_icon != INVALID_HANDLE_VALUE) { - DestroyIcon(trust_icon); + DestroyIcon(trust_icon); } trust_icon = LoadImage(hinst, MAKEINTRESOURCE(IDI_MAINICON), - IMAGE_ICON, font_width*2, font_height, - LR_DEFAULTCOLOR); + IMAGE_ICON, font_width*2, font_height, + LR_DEFAULTCOLOR); if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) { - und_mode = UND_LINE; - DeleteObject(fonts[FONT_UNDERLINE]); - fonts[FONT_UNDERLINE] = 0; + und_mode = UND_LINE; + DeleteObject(fonts[FONT_UNDERLINE]); + fonts[FONT_UNDERLINE] = 0; } if (bold_font_mode == BOLD_FONT && - fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) { - bold_font_mode = BOLD_SHADOW; - DeleteObject(fonts[FONT_BOLD]); - fonts[FONT_BOLD] = 0; + fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) { + bold_font_mode = BOLD_SHADOW; + DeleteObject(fonts[FONT_BOLD]); + fonts[FONT_BOLD] = 0; } fontflag[0] = true; fontflag[1] = true; @@ -1701,20 +1701,20 @@ static void another_font(int fontno) FontSpec *font; if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno]) - return; + return; basefont = (fontno & ~(FONT_BOLDUND)); if (basefont != fontno && !fontflag[basefont]) - another_font(basefont); + another_font(basefont); font = conf_get_fontspec(conf, CONF_font); if (font->isbold) { - fw_dontcare = FW_BOLD; - fw_bold = FW_HEAVY; + fw_dontcare = FW_BOLD; + fw_bold = FW_HEAVY; } else { - fw_dontcare = FW_DONTCARE; - fw_bold = FW_BOLD; + fw_dontcare = FW_DONTCARE; + fw_bold = FW_BOLD; } c = font->charset; @@ -1724,23 +1724,23 @@ static void another_font(int fontno) x = font_width; if (fontno & FONT_WIDE) - x *= 2; + x *= 2; if (fontno & FONT_NARROW) - x = (x+1)/2; + x = (x+1)/2; if (fontno & FONT_OEM) - c = OEM_CHARSET; + c = OEM_CHARSET; if (fontno & FONT_BOLD) - w = fw_bold; + w = fw_bold; if (fontno & FONT_UNDERLINE) - u = true; + u = true; quality = conf_get_int(conf, CONF_font_quality); fonts[fontno] = - CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w, - false, u, false, c, OUT_DEFAULT_PRECIS, - CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), - DEFAULT_PITCH | FF_DONTCARE, s); + CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w, + false, u, false, c, OUT_DEFAULT_PRECIS, + CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), + DEFAULT_PITCH | FF_DONTCARE, s); fontflag[fontno] = true; } @@ -1749,14 +1749,14 @@ static void deinit_fonts(void) { int i; for (i = 0; i < FONT_MAXNO; i++) { - if (fonts[i]) - DeleteObject(fonts[i]); - fonts[i] = 0; - fontflag[i] = false; + if (fonts[i]) + DeleteObject(fonts[i]); + fonts[i] = 0; + fontflag[i] = false; } if (trust_icon != INVALID_HANDLE_VALUE) { - DestroyIcon(trust_icon); + DestroyIcon(trust_icon); } trust_icon = INVALID_HANDLE_VALUE; } @@ -1767,8 +1767,8 @@ static void wintw_request_resize(TermWin *tw, int w, int h) /* If the window is maximized suppress resizing attempts */ if (IsZoomed(hwnd)) { - if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM) - return; + if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM) + return; } if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return; @@ -1776,52 +1776,52 @@ static void wintw_request_resize(TermWin *tw, int w, int h) /* Sanity checks ... */ { - static int first_time = 1; - static RECT ss; + static int first_time = 1; + static RECT ss; - switch (first_time) { - case 1: - /* Get the size of the screen */ - if (get_fullscreen_rect(&ss)) - /* first_time = 0 */ ; - else { - first_time = 2; - break; - } - case 0: - /* Make sure the values are sane */ - width = (ss.right - ss.left - extra_width) / 4; - height = (ss.bottom - ss.top - extra_height) / 6; + switch (first_time) { + case 1: + /* Get the size of the screen */ + if (get_fullscreen_rect(&ss)) + /* first_time = 0 */ ; + else { + first_time = 2; + break; + } + case 0: + /* Make sure the values are sane */ + width = (ss.right - ss.left - extra_width) / 4; + height = (ss.bottom - ss.top - extra_height) / 6; - if (w > width || h > height) - return; - if (w < 15) - w = 15; - if (h < 1) - h = 1; - } + if (w > width || h > height) + return; + if (w < 15) + w = 15; + if (h < 1) + h = 1; + } } term_size(term, h, w, conf_get_int(conf, CONF_savelines)); if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT && - !IsZoomed(hwnd)) { - width = extra_width + font_width * w; - height = extra_height + font_height * h; + !IsZoomed(hwnd)) { + 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); } else - reset_window(0); + reset_window(0); InvalidateRect(hwnd, NULL, true); } static void reset_window(int reinit) { /* - * This function decides how to resize or redraw when the - * user changes something. + * This function decides how to resize or redraw when the + * user changes something. * * This function doesn't like to change the terminal size but if the * font size is locked that may be it's only soluion. @@ -1844,71 +1844,71 @@ static void reset_window(int reinit) { window_border = conf_get_int(conf, CONF_window_border); if (resize_action == RESIZE_DISABLED) - reinit = 2; + reinit = 2; /* Are we being forced to reload the fonts ? */ if (reinit>1) { #ifdef RDB_DEBUG_PATCH - debug("reset_window() -- Forced deinit\n"); + debug("reset_window() -- Forced deinit\n"); #endif - deinit_fonts(); - init_fonts(0,0); + deinit_fonts(); + init_fonts(0,0); } /* Oh, looks like we're minimised */ if (win_width == 0 || win_height == 0) - return; + return; /* Is the window out of position ? */ - if ( !reinit && - (offset_width != (win_width-font_width*term->cols)/2 || - offset_height != (win_height-font_height*term->rows)/2) ){ - offset_width = (win_width-font_width*term->cols)/2; - offset_height = (win_height-font_height*term->rows)/2; - InvalidateRect(hwnd, NULL, true); + if ( !reinit && + (offset_width != (win_width-font_width*term->cols)/2 || + offset_height != (win_height-font_height*term->rows)/2) ){ + offset_width = (win_width-font_width*term->cols)/2; + offset_height = (win_height-font_height*term->rows)/2; + InvalidateRect(hwnd, NULL, true); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> Reposition terminal\n"); + debug("reset_window() -> Reposition terminal\n"); #endif } if (IsZoomed(hwnd)) { - /* We're fullscreen, this means we must not change the size of - * the window so it's the font size or the terminal itself. - */ + /* We're fullscreen, this means we must not change the size of + * the window so it's the font size or the terminal itself. + */ - extra_width = wr.right - wr.left - cr.right + cr.left; - extra_height = wr.bottom - wr.top - cr.bottom + cr.top; + extra_width = wr.right - wr.left - cr.right + cr.left; + extra_height = wr.bottom - wr.top - cr.bottom + cr.top; - if (resize_action != RESIZE_TERM) { - if (font_width != win_width/term->cols || - font_height != win_height/term->rows) { - deinit_fonts(); - init_fonts(win_width/term->cols, win_height/term->rows); - offset_width = (win_width-font_width*term->cols)/2; - offset_height = (win_height-font_height*term->rows)/2; - InvalidateRect(hwnd, NULL, true); + if (resize_action != RESIZE_TERM) { + if (font_width != win_width/term->cols || + font_height != win_height/term->rows) { + deinit_fonts(); + init_fonts(win_width/term->cols, win_height/term->rows); + offset_width = (win_width-font_width*term->cols)/2; + offset_height = (win_height-font_height*term->rows)/2; + InvalidateRect(hwnd, NULL, true); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> Z font resize to (%d, %d)\n", + debug("reset_window() -> Z font resize to (%d, %d)\n", font_width, font_height); #endif - } - } else { - if (font_width * term->cols != win_width || - font_height * term->rows != win_height) { - /* Our only choice at this point is to change the - * size of the terminal; Oh well. - */ - term_size(term, win_height/font_height, win_width/font_width, - conf_get_int(conf, CONF_savelines)); - offset_width = (win_width-font_width*term->cols)/2; - offset_height = (win_height-font_height*term->rows)/2; - InvalidateRect(hwnd, NULL, true); + } + } else { + if (font_width * term->cols != win_width || + font_height * term->rows != win_height) { + /* Our only choice at this point is to change the + * size of the terminal; Oh well. + */ + term_size(term, win_height/font_height, win_width/font_width, + conf_get_int(conf, CONF_savelines)); + offset_width = (win_width-font_width*term->cols)/2; + offset_height = (win_height-font_height*term->rows)/2; + InvalidateRect(hwnd, NULL, true); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> Zoomed term_size\n"); + debug("reset_window() -> Zoomed term_size\n"); #endif - } - } - return; + } + } + return; } /* Hmm, a force re-init means we should ignore the current window @@ -1916,112 +1916,112 @@ static void reset_window(int reinit) { */ if (reinit>0) { #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> Forced re-init\n"); + debug("reset_window() -> Forced re-init\n"); #endif - offset_width = offset_height = window_border; - extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; - extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; + offset_width = offset_height = window_border; + extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; + extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; - if (win_width != font_width*term->cols + offset_width*2 || - win_height != font_height*term->rows + offset_height*2) { + if (win_width != font_width*term->cols + offset_width*2 || + win_height != font_height*term->rows + offset_height*2) { - /* If this is too large windows will resize it to the maximum - * allowed window size, we will then be back in here and resize - * the font or terminal to fit. - */ - SetWindowPos(hwnd, NULL, 0, 0, - font_width*term->cols + extra_width, - font_height*term->rows + extra_height, - SWP_NOMOVE | SWP_NOZORDER); - } + /* If this is too large windows will resize it to the maximum + * allowed window size, we will then be back in here and resize + * the font or terminal to fit. + */ + SetWindowPos(hwnd, NULL, 0, 0, + font_width*term->cols + extra_width, + font_height*term->rows + extra_height, + SWP_NOMOVE | SWP_NOZORDER); + } - InvalidateRect(hwnd, NULL, true); - return; + InvalidateRect(hwnd, NULL, true); + return; } - /* Okay the user doesn't want us to change the font so we try the + /* Okay the user doesn't want us to change the font so we try the * window. But that may be too big for the screen which forces us * to change the terminal. */ if ((resize_action == RESIZE_TERM && reinit<=0) || (resize_action == RESIZE_EITHER && reinit<0) || - reinit>0) { - offset_width = offset_height = window_border; - extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; - extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; + reinit>0) { + offset_width = offset_height = window_border; + extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2; + extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2; - if (win_width != font_width*term->cols + offset_width*2 || - win_height != font_height*term->rows + offset_height*2) { + if (win_width != font_width*term->cols + offset_width*2 || + win_height != font_height*term->rows + offset_height*2) { - static RECT ss; - int width, height; - - get_fullscreen_rect(&ss); + static RECT ss; + int width, height; - width = (ss.right - ss.left - extra_width) / font_width; - height = (ss.bottom - ss.top - extra_height) / font_height; + get_fullscreen_rect(&ss); - /* Grrr too big */ - if ( term->rows > height || term->cols > width ) { - if (resize_action == RESIZE_EITHER) { - /* Make the font the biggest we can */ - if (term->cols > width) - font_width = (ss.right - ss.left - extra_width) - / term->cols; - if (term->rows > height) - font_height = (ss.bottom - ss.top - extra_height) - / term->rows; + width = (ss.right - ss.left - extra_width) / font_width; + height = (ss.bottom - ss.top - extra_height) / font_height; - deinit_fonts(); - init_fonts(font_width, font_height); + /* Grrr too big */ + if ( term->rows > height || term->cols > width ) { + if (resize_action == RESIZE_EITHER) { + /* Make the font the biggest we can */ + if (term->cols > width) + font_width = (ss.right - ss.left - extra_width) + / term->cols; + if (term->rows > height) + font_height = (ss.bottom - ss.top - extra_height) + / term->rows; - width = (ss.right - ss.left - extra_width) / font_width; - height = (ss.bottom - ss.top - extra_height) / font_height; - } else { - if ( height > term->rows ) height = term->rows; - if ( width > term->cols ) width = term->cols; - term_size(term, height, width, - conf_get_int(conf, CONF_savelines)); + deinit_fonts(); + init_fonts(font_width, font_height); + + width = (ss.right - ss.left - extra_width) / font_width; + height = (ss.bottom - ss.top - extra_height) / font_height; + } else { + if ( height > term->rows ) height = term->rows; + if ( width > term->cols ) width = term->cols; + term_size(term, height, width, + conf_get_int(conf, CONF_savelines)); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> term resize to (%d,%d)\n", + debug("reset_window() -> term resize to (%d,%d)\n", height, width); #endif - } - } - - SetWindowPos(hwnd, NULL, 0, 0, - font_width*term->cols + extra_width, - font_height*term->rows + extra_height, - SWP_NOMOVE | SWP_NOZORDER); + } + } - InvalidateRect(hwnd, NULL, true); + SetWindowPos(hwnd, NULL, 0, 0, + font_width*term->cols + extra_width, + font_height*term->rows + extra_height, + SWP_NOMOVE | SWP_NOZORDER); + + InvalidateRect(hwnd, NULL, true); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> window resize to (%d,%d)\n", + debug("reset_window() -> window resize to (%d,%d)\n", font_width*term->cols + extra_width, font_height*term->rows + extra_height); #endif - } - return; + } + return; } /* We're allowed to or must change the font but do we want to ? */ - if (font_width != (win_width-window_border*2)/term->cols || - font_height != (win_height-window_border*2)/term->rows) { + if (font_width != (win_width-window_border*2)/term->cols || + font_height != (win_height-window_border*2)/term->rows) { - deinit_fonts(); - init_fonts((win_width-window_border*2)/term->cols, - (win_height-window_border*2)/term->rows); - offset_width = (win_width-font_width*term->cols)/2; - offset_height = (win_height-font_height*term->rows)/2; + deinit_fonts(); + init_fonts((win_width-window_border*2)/term->cols, + (win_height-window_border*2)/term->rows); + offset_width = (win_width-font_width*term->cols)/2; + offset_height = (win_height-font_height*term->rows)/2; - extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2; - extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2; + extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2; + extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2; - InvalidateRect(hwnd, NULL, true); + InvalidateRect(hwnd, NULL, true); #ifdef RDB_DEBUG_PATCH - debug("reset_window() -> font resize to (%d,%d)\n", + debug("reset_window() -> font resize to (%d,%d)\n", font_width, font_height); #endif } @@ -2032,7 +2032,7 @@ static void set_input_locale(HKL kl) char lbuf[20]; GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE, - lbuf, sizeof(lbuf)); + lbuf, sizeof(lbuf)); kbd_codepage = atoi(lbuf); } @@ -2043,24 +2043,24 @@ static void click(Mouse_Button b, int x, int y, int thistime = GetMessageTime(); if (send_raw_mouse && - !(shift && conf_get_bool(conf, CONF_mouse_override))) { - lastbtn = MBT_NOTHING; - term_mouse(term, b, translate_button(b), MA_CLICK, - x, y, shift, ctrl, alt); - return; + !(shift && conf_get_bool(conf, CONF_mouse_override))) { + lastbtn = MBT_NOTHING; + term_mouse(term, b, translate_button(b), MA_CLICK, + x, y, shift, ctrl, alt); + return; } if (lastbtn == b && thistime - lasttime < dbltime) { - lastact = (lastact == MA_CLICK ? MA_2CLK : - lastact == MA_2CLK ? MA_3CLK : - lastact == MA_3CLK ? MA_CLICK : MA_NOTHING); + lastact = (lastact == MA_CLICK ? MA_2CLK : + lastact == MA_2CLK ? MA_3CLK : + lastact == MA_3CLK ? MA_CLICK : MA_NOTHING); } else { - lastbtn = b; - lastact = MA_CLICK; + lastbtn = b; + lastact = MA_CLICK; } if (lastact != MA_NOTHING) - term_mouse(term, b, translate_button(b), lastact, - x, y, shift, ctrl, alt); + term_mouse(term, b, translate_button(b), lastact, + x, y, shift, ctrl, alt); lasttime = thistime; } @@ -2071,14 +2071,14 @@ static void click(Mouse_Button b, int x, int y, static Mouse_Button translate_button(Mouse_Button button) { if (button == MBT_LEFT) - return MBT_SELECT; + return MBT_SELECT; if (button == MBT_MIDDLE) - return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ? - MBT_PASTE : MBT_EXTEND; + return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ? + MBT_PASTE : MBT_EXTEND; if (button == MBT_RIGHT) - return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ? - MBT_EXTEND : MBT_PASTE; - return 0; /* shouldn't happen */ + return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ? + MBT_EXTEND : MBT_PASTE; + return 0; /* shouldn't happen */ } static void show_mouseptr(bool show) @@ -2087,11 +2087,11 @@ static void show_mouseptr(bool show) * update_mouse_pointer() */ static bool cursor_visible = true; if (!conf_get_bool(conf, CONF_hide_mouseptr)) - show = true; /* override if this feature disabled */ + show = true; /* override if this feature disabled */ if (cursor_visible && !show) - ShowCursor(false); + ShowCursor(false); else if (!cursor_visible && show) - ShowCursor(true); + ShowCursor(true); cursor_visible = show; } @@ -2100,11 +2100,11 @@ static bool is_alt_pressed(void) BYTE keystate[256]; int r = GetKeyboardState(keystate); if (!r) - return false; + return false; if (keystate[VK_MENU] & 0x80) - return true; + return true; if (keystate[VK_RMENU] & 0x80) - return true; + return true; return false; } @@ -2116,22 +2116,22 @@ static void win_seat_notify_remote_exit(Seat *seat) if (!session_closed && (exitcode = backend_exitcode(backend)) >= 0) { - close_on_exit = conf_get_int(conf, CONF_close_on_exit); - /* Abnormal exits will already have set session_closed and taken - * appropriate action. */ - if (close_on_exit == FORCE_ON || - (close_on_exit == AUTO && exitcode != INT_MAX)) { - PostQuitMessage(0); - } else { + close_on_exit = conf_get_int(conf, CONF_close_on_exit); + /* Abnormal exits will already have set session_closed and taken + * appropriate action. */ + if (close_on_exit == FORCE_ON || + (close_on_exit == AUTO && exitcode != INT_MAX)) { + PostQuitMessage(0); + } else { queue_toplevel_callback(close_session, NULL); - session_closed = true; - /* exitcode == INT_MAX indicates that the connection was closed - * by a fatal error, so an error box will be coming our way and - * we should not generate this informational one. */ - if (exitcode != INT_MAX) - MessageBox(hwnd, "Connection closed by remote host", - appname, MB_OK | MB_ICONINFORMATION); - } + session_closed = true; + /* exitcode == INT_MAX indicates that the connection was closed + * by a fatal error, so an error box will be coming our way and + * we should not generate this informational one. */ + if (exitcode != INT_MAX) + MessageBox(hwnd, "Connection closed by remote host", + appname, MB_OK | MB_ICONINFORMATION); + } } } @@ -2140,9 +2140,9 @@ void timer_change_notify(unsigned long next) unsigned long now = GETTICKCOUNT(); long ticks; if (now - next < INT_MAX) - ticks = 0; + ticks = 0; else - ticks = next - now; + ticks = next - now; KillTimer(hwnd, TIMING_TIMER_ID); SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL); timing_next_time = next; @@ -2180,7 +2180,7 @@ static void free_hdc(HDC hdc) } static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { HDC hdc; static bool ignore_clip = false; @@ -2192,397 +2192,397 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, switch (message) { case WM_TIMER: - if ((UINT_PTR)wParam == TIMING_TIMER_ID) { - unsigned long next; + if ((UINT_PTR)wParam == TIMING_TIMER_ID) { + unsigned long next; - KillTimer(hwnd, TIMING_TIMER_ID); - if (run_timers(timing_next_time, &next)) { - timer_change_notify(next); - } else { - } - } - return 0; + KillTimer(hwnd, TIMING_TIMER_ID); + if (run_timers(timing_next_time, &next)) { + timer_change_notify(next); + } else { + } + } + return 0; case WM_CREATE: - break; + break; case WM_CLOSE: - { - char *str; - show_mouseptr(true); - str = dupprintf("%s Exit Confirmation", appname); - if (session_closed || !conf_get_bool(conf, CONF_warn_on_close) || - MessageBox(hwnd, - "Are you sure you want to close this session?", - str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1) - == IDOK) - DestroyWindow(hwnd); - sfree(str); - } - return 0; + { + char *str; + show_mouseptr(true); + str = dupprintf("%s Exit Confirmation", appname); + if (session_closed || !conf_get_bool(conf, CONF_warn_on_close) || + MessageBox(hwnd, + "Are you sure you want to close this session?", + str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1) + == IDOK) + DestroyWindow(hwnd); + sfree(str); + } + return 0; case WM_DESTROY: - show_mouseptr(true); - PostQuitMessage(0); - return 0; + show_mouseptr(true); + PostQuitMessage(0); + return 0; case WM_INITMENUPOPUP: - if ((HMENU)wParam == savedsess_menu) { - /* About to pop up Saved Sessions sub-menu. - * Refresh the session list. */ - get_sesslist(&sesslist, false); /* free */ - get_sesslist(&sesslist, true); - update_savedsess_menu(); - return 0; - } - break; + if ((HMENU)wParam == savedsess_menu) { + /* About to pop up Saved Sessions sub-menu. + * Refresh the session list. */ + get_sesslist(&sesslist, false); /* free */ + get_sesslist(&sesslist, true); + update_savedsess_menu(); + return 0; + } + break; case WM_COMMAND: case WM_SYSCOMMAND: - switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */ - case IDM_SHOWLOG: - showeventlog(hwnd); - break; - case IDM_NEWSESS: - case IDM_DUPSESS: - case IDM_SAVEDSESS: - { - char b[2048]; - char *cl; + switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */ + case IDM_SHOWLOG: + showeventlog(hwnd); + break; + case IDM_NEWSESS: + case IDM_DUPSESS: + case IDM_SAVEDSESS: + { + char b[2048]; + char *cl; const char *argprefix; - bool inherit_handles; - STARTUPINFO si; - PROCESS_INFORMATION pi; - HANDLE filemap = NULL; + bool inherit_handles; + STARTUPINFO si; + PROCESS_INFORMATION pi; + HANDLE filemap = NULL; if (restricted_acl) argprefix = "&R"; else argprefix = ""; - if (wParam == IDM_DUPSESS) { - /* - * Allocate a file-mapping memory chunk for the - * config structure. - */ - SECURITY_ATTRIBUTES sa; + if (wParam == IDM_DUPSESS) { + /* + * Allocate a file-mapping memory chunk for the + * config structure. + */ + SECURITY_ATTRIBUTES sa; strbuf *serbuf; - void *p; - int size; + void *p; + int size; serbuf = strbuf_new(); - conf_serialise(BinarySink_UPCAST(serbuf), conf); + conf_serialise(BinarySink_UPCAST(serbuf), conf); size = serbuf->len; - sa.nLength = sizeof(sa); - sa.lpSecurityDescriptor = NULL; - sa.bInheritHandle = true; - filemap = CreateFileMapping(INVALID_HANDLE_VALUE, - &sa, - PAGE_READWRITE, - 0, size, NULL); - if (filemap && filemap != INVALID_HANDLE_VALUE) { - p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size); - if (p) { - memcpy(p, serbuf->s, size); - UnmapViewOfFile(p); - } - } + sa.nLength = sizeof(sa); + sa.lpSecurityDescriptor = NULL; + sa.bInheritHandle = true; + filemap = CreateFileMapping(INVALID_HANDLE_VALUE, + &sa, + PAGE_READWRITE, + 0, size, NULL); + if (filemap && filemap != INVALID_HANDLE_VALUE) { + p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size); + if (p) { + memcpy(p, serbuf->s, size); + UnmapViewOfFile(p); + } + } strbuf_free(serbuf); - inherit_handles = true; - cl = dupprintf("putty %s&%p:%u", argprefix, + inherit_handles = true; + cl = dupprintf("putty %s&%p:%u", argprefix, filemap, (unsigned)size); - } else if (wParam == IDM_SAVEDSESS) { - unsigned int sessno = ((lParam - IDM_SAVED_MIN) - / MENU_SAVED_STEP) + 1; - if (sessno < (unsigned)sesslist.nsessions) { - const char *session = sesslist.sessions[sessno]; - cl = dupprintf("putty %s@%s", argprefix, session); - inherit_handles = false; - } else - break; - } else /* IDM_NEWSESS */ { + } else if (wParam == IDM_SAVEDSESS) { + unsigned int sessno = ((lParam - IDM_SAVED_MIN) + / MENU_SAVED_STEP) + 1; + if (sessno < (unsigned)sesslist.nsessions) { + const char *session = sesslist.sessions[sessno]; + cl = dupprintf("putty %s@%s", argprefix, session); + inherit_handles = false; + } else + break; + } else /* IDM_NEWSESS */ { cl = dupprintf("putty%s%s", *argprefix ? " " : "", argprefix); - inherit_handles = false; - } + inherit_handles = false; + } - GetModuleFileName(NULL, b, sizeof(b) - 1); - si.cb = sizeof(si); - si.lpReserved = NULL; - si.lpDesktop = NULL; - si.lpTitle = NULL; - si.dwFlags = 0; - si.cbReserved2 = 0; - si.lpReserved2 = NULL; - CreateProcess(b, cl, NULL, NULL, inherit_handles, - NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); + GetModuleFileName(NULL, b, sizeof(b) - 1); + si.cb = sizeof(si); + si.lpReserved = NULL; + si.lpDesktop = NULL; + si.lpTitle = NULL; + si.dwFlags = 0; + si.cbReserved2 = 0; + si.lpReserved2 = NULL; + CreateProcess(b, cl, NULL, NULL, inherit_handles, + NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); - if (filemap) - CloseHandle(filemap); + if (filemap) + CloseHandle(filemap); sfree(cl); - } - break; - case IDM_RESTART: + } + break; + case IDM_RESTART: if (!backend) { lp_eventlog(default_logpolicy, "----- Session restarted -----"); - term_pwron(term, false); - start_backend(); - } + term_pwron(term, false); + start_backend(); + } - break; - case IDM_RECONF: - { - Conf *prev_conf; - int init_lvl = 1; - bool reconfig_result; + break; + case IDM_RECONF: + { + Conf *prev_conf; + int init_lvl = 1; + bool reconfig_result; - if (reconfiguring) - break; - else - reconfiguring = true; + if (reconfiguring) + break; + else + reconfiguring = true; - /* - * Copy the current window title into the stored - * previous configuration, so that doing nothing to - * the window title field in the config box doesn't - * reset the title to its startup state. - */ - conf_set_str(conf, CONF_wintitle, window_name); + /* + * Copy the current window title into the stored + * previous configuration, so that doing nothing to + * the window title field in the config box doesn't + * reset the title to its startup state. + */ + conf_set_str(conf, CONF_wintitle, window_name); - prev_conf = conf_copy(conf); + prev_conf = conf_copy(conf); - reconfig_result = + reconfig_result = do_reconfig(hwnd, backend ? backend_cfg_info(backend) : 0); - reconfiguring = false; - if (!reconfig_result) { + reconfiguring = false; + if (!reconfig_result) { conf_free(prev_conf); - break; + break; } - conf_cache_data(); + conf_cache_data(); - resize_action = conf_get_int(conf, CONF_resize_action); - { - /* Disable full-screen if resizing forbidden */ - int i; - for (i = 0; i < lenof(popup_menus); i++) - EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, - MF_BYCOMMAND | - (resize_action == RESIZE_DISABLED) - ? MF_GRAYED : MF_ENABLED); - /* Gracefully unzoom if necessary */ - if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED)) - ShowWindow(hwnd, SW_RESTORE); - } + resize_action = conf_get_int(conf, CONF_resize_action); + { + /* Disable full-screen if resizing forbidden */ + int i; + for (i = 0; i < lenof(popup_menus); i++) + EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, + MF_BYCOMMAND | + (resize_action == RESIZE_DISABLED) + ? MF_GRAYED : MF_ENABLED); + /* Gracefully unzoom if necessary */ + if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED)) + ShowWindow(hwnd, SW_RESTORE); + } - /* Pass new config data to the logging module */ - log_reconfig(logctx, conf); + /* Pass new config data to the logging module */ + log_reconfig(logctx, conf); - sfree(logpal); - /* - * Flush the line discipline's edit buffer in the - * case where local editing has just been disabled. - */ - if (ldisc) { + sfree(logpal); + /* + * Flush the line discipline's edit buffer in the + * case where local editing has just been disabled. + */ + if (ldisc) { ldisc_configure(ldisc, conf); - ldisc_echoedit_update(ldisc); + ldisc_echoedit_update(ldisc); } - if (pal) - DeleteObject(pal); - logpal = NULL; - pal = NULL; - conftopalette(); - init_palette(); + if (pal) + DeleteObject(pal); + logpal = NULL; + pal = NULL; + conftopalette(); + init_palette(); - /* Pass new config data to the terminal */ - term_reconfig(term, conf); + /* Pass new config data to the terminal */ + term_reconfig(term, conf); setup_clipboards(term, conf); - /* Pass new config data to the back end */ + /* Pass new config data to the back end */ if (backend) backend_reconfig(backend, conf); - /* Screen size changed ? */ - if (conf_get_int(conf, CONF_height) != - conf_get_int(prev_conf, CONF_height) || - conf_get_int(conf, CONF_width) != - conf_get_int(prev_conf, CONF_width) || - conf_get_int(conf, CONF_savelines) != - conf_get_int(prev_conf, CONF_savelines) || - resize_action == RESIZE_FONT || - (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) || - resize_action == RESIZE_DISABLED) - term_size(term, conf_get_int(conf, CONF_height), - conf_get_int(conf, CONF_width), - conf_get_int(conf, CONF_savelines)); + /* Screen size changed ? */ + if (conf_get_int(conf, CONF_height) != + conf_get_int(prev_conf, CONF_height) || + conf_get_int(conf, CONF_width) != + conf_get_int(prev_conf, CONF_width) || + conf_get_int(conf, CONF_savelines) != + conf_get_int(prev_conf, CONF_savelines) || + resize_action == RESIZE_FONT || + (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) || + resize_action == RESIZE_DISABLED) + term_size(term, conf_get_int(conf, CONF_height), + conf_get_int(conf, CONF_width), + conf_get_int(conf, CONF_savelines)); - /* Enable or disable the scroll bar, etc */ - { - LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE); - LONG nexflag, exflag = - GetWindowLongPtr(hwnd, GWL_EXSTYLE); + /* Enable or disable the scroll bar, etc */ + { + LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE); + LONG nexflag, exflag = + GetWindowLongPtr(hwnd, GWL_EXSTYLE); - nexflag = exflag; - if (conf_get_bool(conf, CONF_alwaysontop) != - conf_get_bool(prev_conf, CONF_alwaysontop)) { - if (conf_get_bool(conf, CONF_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 (conf_get_bool(conf, CONF_sunken_edge)) - nexflag |= WS_EX_CLIENTEDGE; - else - nexflag &= ~(WS_EX_CLIENTEDGE); + nexflag = exflag; + if (conf_get_bool(conf, CONF_alwaysontop) != + conf_get_bool(prev_conf, CONF_alwaysontop)) { + if (conf_get_bool(conf, CONF_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 (conf_get_bool(conf, CONF_sunken_edge)) + nexflag |= WS_EX_CLIENTEDGE; + else + nexflag &= ~(WS_EX_CLIENTEDGE); - nflg = flag; - if (conf_get_bool(conf, is_full_screen() ? + nflg = flag; + if (conf_get_bool(conf, is_full_screen() ? CONF_scrollbar_in_fullscreen : CONF_scrollbar)) - nflg |= WS_VSCROLL; - else - nflg &= ~WS_VSCROLL; + nflg |= WS_VSCROLL; + else + nflg &= ~WS_VSCROLL; - if (resize_action == RESIZE_DISABLED || + if (resize_action == RESIZE_DISABLED || is_full_screen()) - nflg &= ~WS_THICKFRAME; - else - nflg |= WS_THICKFRAME; + nflg &= ~WS_THICKFRAME; + else + nflg |= WS_THICKFRAME; - if (resize_action == RESIZE_DISABLED) - nflg &= ~WS_MAXIMIZEBOX; - else - nflg |= WS_MAXIMIZEBOX; + if (resize_action == RESIZE_DISABLED) + nflg &= ~WS_MAXIMIZEBOX; + else + nflg |= WS_MAXIMIZEBOX; - if (nflg != flag || nexflag != exflag) { - if (nflg != flag) - SetWindowLongPtr(hwnd, GWL_STYLE, nflg); - if (nexflag != exflag) - SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag); + if (nflg != flag || nexflag != exflag) { + if (nflg != flag) + SetWindowLongPtr(hwnd, GWL_STYLE, nflg); + if (nexflag != exflag) + SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag); - SetWindowPos(hwnd, NULL, 0, 0, 0, 0, - SWP_NOACTIVATE | SWP_NOCOPYBITS | - SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | - SWP_FRAMECHANGED); + SetWindowPos(hwnd, NULL, 0, 0, 0, 0, + SWP_NOACTIVATE | SWP_NOCOPYBITS | + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | + SWP_FRAMECHANGED); - init_lvl = 2; - } - } + init_lvl = 2; + } + } - /* Oops */ - if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) { - force_normal(hwnd); - init_lvl = 2; - } + /* Oops */ + if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) { + force_normal(hwnd); + init_lvl = 2; + } - win_set_title(wintw, conf_get_str(conf, CONF_wintitle)); - if (IsIconic(hwnd)) { - SetWindowText(hwnd, - conf_get_bool(conf, CONF_win_name_always) ? - window_name : icon_name); - } + win_set_title(wintw, conf_get_str(conf, CONF_wintitle)); + if (IsIconic(hwnd)) { + SetWindowText(hwnd, + conf_get_bool(conf, CONF_win_name_always) ? + window_name : icon_name); + } - { - FontSpec *font = conf_get_fontspec(conf, CONF_font); - FontSpec *prev_font = conf_get_fontspec(prev_conf, + { + FontSpec *font = conf_get_fontspec(conf, CONF_font); + FontSpec *prev_font = conf_get_fontspec(prev_conf, CONF_font); - if (!strcmp(font->name, prev_font->name) || - !strcmp(conf_get_str(conf, CONF_line_codepage), - conf_get_str(prev_conf, CONF_line_codepage)) || - font->isbold != prev_font->isbold || - font->height != prev_font->height || - font->charset != prev_font->charset || - conf_get_int(conf, CONF_font_quality) != - conf_get_int(prev_conf, CONF_font_quality) || - conf_get_int(conf, CONF_vtmode) != - conf_get_int(prev_conf, CONF_vtmode) || - conf_get_int(conf, CONF_bold_style) != - conf_get_int(prev_conf, CONF_bold_style) || - resize_action == RESIZE_DISABLED || - resize_action == RESIZE_EITHER || - resize_action != conf_get_int(prev_conf, - CONF_resize_action)) - init_lvl = 2; - } + if (!strcmp(font->name, prev_font->name) || + !strcmp(conf_get_str(conf, CONF_line_codepage), + conf_get_str(prev_conf, CONF_line_codepage)) || + font->isbold != prev_font->isbold || + font->height != prev_font->height || + font->charset != prev_font->charset || + conf_get_int(conf, CONF_font_quality) != + conf_get_int(prev_conf, CONF_font_quality) || + conf_get_int(conf, CONF_vtmode) != + conf_get_int(prev_conf, CONF_vtmode) || + conf_get_int(conf, CONF_bold_style) != + conf_get_int(prev_conf, CONF_bold_style) || + resize_action == RESIZE_DISABLED || + resize_action == RESIZE_EITHER || + resize_action != conf_get_int(prev_conf, + CONF_resize_action)) + init_lvl = 2; + } - InvalidateRect(hwnd, NULL, true); - reset_window(init_lvl); + InvalidateRect(hwnd, NULL, true); + reset_window(init_lvl); - conf_free(prev_conf); - } - break; - case IDM_COPYALL: + conf_free(prev_conf); + } + break; + case IDM_COPYALL: term_copyall(term, clips_system, lenof(clips_system)); - break; - case IDM_COPY: + break; + case IDM_COPY: term_request_copy(term, clips_system, lenof(clips_system)); - break; - case IDM_PASTE: - term_request_paste(term, CLIP_SYSTEM); - break; - case IDM_CLRSB: - term_clrsb(term); - break; - case IDM_RESET: - term_pwron(term, true); - if (ldisc) - ldisc_echoedit_update(ldisc); - break; - case IDM_ABOUT: - showabout(hwnd); - break; - case IDM_HELP: - launch_help(hwnd, NULL); - break; - case SC_MOUSEMENU: - /* - * We get this if the System menu has been activated - * using the mouse. - */ - show_mouseptr(true); - break; + break; + case IDM_PASTE: + term_request_paste(term, CLIP_SYSTEM); + break; + case IDM_CLRSB: + term_clrsb(term); + break; + case IDM_RESET: + term_pwron(term, true); + if (ldisc) + ldisc_echoedit_update(ldisc); + break; + case IDM_ABOUT: + showabout(hwnd); + break; + case IDM_HELP: + launch_help(hwnd, NULL); + break; + case SC_MOUSEMENU: + /* + * We get this if the System menu has been activated + * using the mouse. + */ + show_mouseptr(true); + break; case SC_KEYMENU: - /* - * We get this if the System menu has been activated - * using the keyboard. This might happen from within - * TranslateKey, in which case it really wants to be - * followed by a `space' character to actually _bring - * the menu up_ rather than just sitting there in - * `ready to appear' state. - */ - show_mouseptr(true); /* make sure pointer is visible */ - if( lParam == 0 ) - PostMessage(hwnd, WM_CHAR, ' ', 0); - break; - case IDM_FULLSCREEN: - flip_full_screen(); - break; - default: - if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) { - SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam); - } - if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) { - int i = (wParam - IDM_SPECIAL_MIN) / 0x10; - /* - * Ensure we haven't been sent a bogus SYSCOMMAND - * which would cause us to reference invalid memory - * and crash. Perhaps I'm just too paranoid here. - */ - if (i >= n_specials) - break; + /* + * We get this if the System menu has been activated + * using the keyboard. This might happen from within + * TranslateKey, in which case it really wants to be + * followed by a `space' character to actually _bring + * the menu up_ rather than just sitting there in + * `ready to appear' state. + */ + show_mouseptr(true); /* make sure pointer is visible */ + if( lParam == 0 ) + PostMessage(hwnd, WM_CHAR, ' ', 0); + break; + case IDM_FULLSCREEN: + flip_full_screen(); + break; + default: + if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) { + SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam); + } + if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) { + int i = (wParam - IDM_SPECIAL_MIN) / 0x10; + /* + * Ensure we haven't been sent a bogus SYSCOMMAND + * which would cause us to reference invalid memory + * and crash. Perhaps I'm just too paranoid here. + */ + if (i >= n_specials) + break; if (backend) backend_special( backend, specials[i].code, specials[i].arg); - } - } - break; + } + } + break; #define X_POS(l) ((int)(short)LOWORD(l)) #define Y_POS(l) ((int)(short)HIWORD(l)) @@ -2595,274 +2595,274 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, case WM_LBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONUP: - if (message == WM_RBUTTONDOWN && - ((wParam & MK_CONTROL) || - (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) { - POINT cursorpos; + if (message == WM_RBUTTONDOWN && + ((wParam & MK_CONTROL) || + (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) { + POINT cursorpos; - show_mouseptr(true); /* make sure pointer is visible */ - GetCursorPos(&cursorpos); - TrackPopupMenu(popup_menus[CTXMENU].menu, - TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, - cursorpos.x, cursorpos.y, - 0, hwnd, NULL); - break; - } - { - int button; + show_mouseptr(true); /* make sure pointer is visible */ + GetCursorPos(&cursorpos); + TrackPopupMenu(popup_menus[CTXMENU].menu, + TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, + cursorpos.x, cursorpos.y, + 0, hwnd, NULL); + break; + } + { + int button; bool press; - switch (message) { - case WM_LBUTTONDOWN: - button = MBT_LEFT; - wParam |= MK_LBUTTON; - press = true; - break; - case WM_MBUTTONDOWN: - button = MBT_MIDDLE; - wParam |= MK_MBUTTON; - press = true; - break; - case WM_RBUTTONDOWN: - button = MBT_RIGHT; - wParam |= MK_RBUTTON; - press = true; - break; - case WM_LBUTTONUP: - button = MBT_LEFT; - wParam &= ~MK_LBUTTON; - press = false; - break; - case WM_MBUTTONUP: - button = MBT_MIDDLE; - wParam &= ~MK_MBUTTON; - press = false; - break; - case WM_RBUTTONUP: - button = MBT_RIGHT; - wParam &= ~MK_RBUTTON; - press = false; - break; - default: /* shouldn't happen */ - button = 0; + switch (message) { + case WM_LBUTTONDOWN: + button = MBT_LEFT; + wParam |= MK_LBUTTON; + press = true; + break; + case WM_MBUTTONDOWN: + button = MBT_MIDDLE; + wParam |= MK_MBUTTON; + press = true; + break; + case WM_RBUTTONDOWN: + button = MBT_RIGHT; + wParam |= MK_RBUTTON; + press = true; + break; + case WM_LBUTTONUP: + button = MBT_LEFT; + wParam &= ~MK_LBUTTON; press = false; - } - show_mouseptr(true); - /* - * Special case: in full-screen mode, if the left - * button is clicked in the very top left corner of the - * window, we put up the System menu instead of doing - * selection. - */ - { - bool mouse_on_hotspot = false; - POINT pt; + break; + case WM_MBUTTONUP: + button = MBT_MIDDLE; + wParam &= ~MK_MBUTTON; + press = false; + break; + case WM_RBUTTONUP: + button = MBT_RIGHT; + wParam &= ~MK_RBUTTON; + press = false; + break; + default: /* shouldn't happen */ + button = 0; + press = false; + } + show_mouseptr(true); + /* + * Special case: in full-screen mode, if the left + * button is clicked in the very top left corner of the + * window, we put up the System menu instead of doing + * selection. + */ + { + bool mouse_on_hotspot = false; + POINT pt; - GetCursorPos(&pt); + GetCursorPos(&pt); #ifndef NO_MULTIMON - { - HMONITOR mon; - MONITORINFO mi; + { + HMONITOR mon; + MONITORINFO mi; - mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL); + mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL); - if (mon != NULL) { - mi.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(mon, &mi); + if (mon != NULL) { + mi.cbSize = sizeof(MONITORINFO); + GetMonitorInfo(mon, &mi); - if (mi.rcMonitor.left == pt.x && - mi.rcMonitor.top == pt.y) { - mouse_on_hotspot = true; - } - } - } + if (mi.rcMonitor.left == pt.x && + mi.rcMonitor.top == pt.y) { + mouse_on_hotspot = true; + } + } + } #else - if (pt.x == 0 && pt.y == 0) { - mouse_on_hotspot = true; - } + if (pt.x == 0 && pt.y == 0) { + mouse_on_hotspot = true; + } #endif - if (is_full_screen() && press && - button == MBT_LEFT && mouse_on_hotspot) { - SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU, - MAKELPARAM(pt.x, pt.y)); - return 0; - } - } + if (is_full_screen() && press && + button == MBT_LEFT && mouse_on_hotspot) { + SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU, + MAKELPARAM(pt.x, pt.y)); + return 0; + } + } - if (press) { - click(button, - TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)), - wParam & MK_SHIFT, wParam & MK_CONTROL, - is_alt_pressed()); - SetCapture(hwnd); - } else { - term_mouse(term, button, translate_button(button), MA_RELEASE, - TO_CHR_X(X_POS(lParam)), - TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT, - wParam & MK_CONTROL, is_alt_pressed()); - if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON))) - ReleaseCapture(); - } - } - return 0; + if (press) { + click(button, + TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)), + wParam & MK_SHIFT, wParam & MK_CONTROL, + is_alt_pressed()); + SetCapture(hwnd); + } else { + term_mouse(term, button, translate_button(button), MA_RELEASE, + TO_CHR_X(X_POS(lParam)), + TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT, + wParam & MK_CONTROL, is_alt_pressed()); + if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON))) + ReleaseCapture(); + } + } + return 0; case WM_MOUSEMOVE: - { - /* - * Windows seems to like to occasionally send MOUSEMOVE - * events even if the mouse hasn't moved. Don't unhide - * the mouse pointer in this case. - */ - static WPARAM wp = 0; - static LPARAM lp = 0; - if (wParam != wp || lParam != lp || - last_mousemove != WM_MOUSEMOVE) { - show_mouseptr(true); - wp = wParam; lp = lParam; - last_mousemove = WM_MOUSEMOVE; - } - } - /* - * Add the mouse position and message time to the random - * number noise. - */ - noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam); + { + /* + * Windows seems to like to occasionally send MOUSEMOVE + * events even if the mouse hasn't moved. Don't unhide + * the mouse pointer in this case. + */ + static WPARAM wp = 0; + static LPARAM lp = 0; + if (wParam != wp || lParam != lp || + last_mousemove != WM_MOUSEMOVE) { + show_mouseptr(true); + wp = wParam; lp = lParam; + last_mousemove = WM_MOUSEMOVE; + } + } + /* + * Add the mouse position and message time to the random + * number noise. + */ + noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam); - if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) && - GetCapture() == hwnd) { - Mouse_Button b; - if (wParam & MK_LBUTTON) - b = MBT_LEFT; - else if (wParam & MK_MBUTTON) - b = MBT_MIDDLE; - else - b = MBT_RIGHT; - term_mouse(term, b, translate_button(b), MA_DRAG, - TO_CHR_X(X_POS(lParam)), - TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT, - wParam & MK_CONTROL, is_alt_pressed()); - } - return 0; + if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) && + GetCapture() == hwnd) { + Mouse_Button b; + if (wParam & MK_LBUTTON) + b = MBT_LEFT; + else if (wParam & MK_MBUTTON) + b = MBT_MIDDLE; + else + b = MBT_RIGHT; + term_mouse(term, b, translate_button(b), MA_DRAG, + TO_CHR_X(X_POS(lParam)), + TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT, + wParam & MK_CONTROL, is_alt_pressed()); + } + return 0; case WM_NCMOUSEMOVE: - { - static WPARAM wp = 0; - static LPARAM lp = 0; - if (wParam != wp || lParam != lp || - last_mousemove != WM_NCMOUSEMOVE) { - show_mouseptr(true); - wp = wParam; lp = lParam; - last_mousemove = WM_NCMOUSEMOVE; - } - } - noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam); - break; + { + static WPARAM wp = 0; + static LPARAM lp = 0; + if (wParam != wp || lParam != lp || + last_mousemove != WM_NCMOUSEMOVE) { + show_mouseptr(true); + wp = wParam; lp = lParam; + last_mousemove = WM_NCMOUSEMOVE; + } + } + noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam); + break; case WM_IGNORE_CLIP: - ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */ - break; + ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */ + break; case WM_DESTROYCLIPBOARD: - if (!ignore_clip) - term_lost_clipboard_ownership(term, CLIP_SYSTEM); - ignore_clip = false; - return 0; + if (!ignore_clip) + term_lost_clipboard_ownership(term, CLIP_SYSTEM); + ignore_clip = false; + return 0; case WM_PAINT: - { - PAINTSTRUCT p; + { + PAINTSTRUCT p; - HideCaret(hwnd); - hdc = BeginPaint(hwnd, &p); - if (pal) { - SelectPalette(hdc, pal, true); - RealizePalette(hdc); - } + HideCaret(hwnd); + hdc = BeginPaint(hwnd, &p); + if (pal) { + SelectPalette(hdc, pal, true); + RealizePalette(hdc); + } - /* - * We have to be careful about term_paint(). It will - * set a bunch of character cells to INVALID and then - * call do_paint(), which will redraw those cells and - * _then mark them as done_. This may not be accurate: - * when painting in WM_PAINT context we are restricted - * to the rectangle which has just been exposed - so if - * that only covers _part_ of a character cell and the - * rest of it was already visible, that remainder will - * not be redrawn at all. Accordingly, we must not - * paint any character cell in a WM_PAINT context which - * already has a pending update due to terminal output. - * The simplest solution to this - and many, many - * thanks to Hung-Te Lin for working all this out - is - * not to do any actual painting at _all_ if there's a - * pending terminal update: just mark the relevant - * character cells as INVALID and wait for the - * scheduled full update to sort it out. - * - * I have a suspicion this isn't the _right_ solution. - * An alternative approach would be to have terminal.c - * separately track what _should_ be on the terminal - * screen and what _is_ on the terminal screen, and - * have two completely different types of redraw (one - * for full updates, which syncs the former with the - * terminal itself, and one for WM_PAINT which syncs - * the latter with the former); yet another possibility - * would be to have the Windows front end do what the - * GTK one already does, and maintain a bitmap of the - * current terminal appearance so that WM_PAINT becomes - * completely trivial. However, this should do for now. - */ + /* + * We have to be careful about term_paint(). It will + * set a bunch of character cells to INVALID and then + * call do_paint(), which will redraw those cells and + * _then mark them as done_. This may not be accurate: + * when painting in WM_PAINT context we are restricted + * to the rectangle which has just been exposed - so if + * that only covers _part_ of a character cell and the + * rest of it was already visible, that remainder will + * not be redrawn at all. Accordingly, we must not + * paint any character cell in a WM_PAINT context which + * already has a pending update due to terminal output. + * The simplest solution to this - and many, many + * thanks to Hung-Te Lin for working all this out - is + * not to do any actual painting at _all_ if there's a + * pending terminal update: just mark the relevant + * character cells as INVALID and wait for the + * scheduled full update to sort it out. + * + * I have a suspicion this isn't the _right_ solution. + * An alternative approach would be to have terminal.c + * separately track what _should_ be on the terminal + * screen and what _is_ on the terminal screen, and + * have two completely different types of redraw (one + * for full updates, which syncs the former with the + * terminal itself, and one for WM_PAINT which syncs + * the latter with the former); yet another possibility + * would be to have the Windows front end do what the + * GTK one already does, and maintain a bitmap of the + * current terminal appearance so that WM_PAINT becomes + * completely trivial. However, this should do for now. + */ assert(!wintw_hdc); wintw_hdc = hdc; - term_paint(term, - (p.rcPaint.left-offset_width)/font_width, - (p.rcPaint.top-offset_height)/font_height, - (p.rcPaint.right-offset_width-1)/font_width, - (p.rcPaint.bottom-offset_height-1)/font_height, - !term->window_update_pending); + term_paint(term, + (p.rcPaint.left-offset_width)/font_width, + (p.rcPaint.top-offset_height)/font_height, + (p.rcPaint.right-offset_width-1)/font_width, + (p.rcPaint.bottom-offset_height-1)/font_height, + !term->window_update_pending); wintw_hdc = NULL; - if (p.fErase || - p.rcPaint.left < offset_width || - p.rcPaint.top < offset_height || - p.rcPaint.right >= offset_width + font_width*term->cols || - p.rcPaint.bottom>= offset_height + font_height*term->rows) - { - HBRUSH fillcolour, oldbrush; - HPEN edge, oldpen; - fillcolour = CreateSolidBrush ( - colours[ATTR_DEFBG>>ATTR_BGSHIFT]); - oldbrush = SelectObject(hdc, fillcolour); - edge = CreatePen(PS_SOLID, 0, - colours[ATTR_DEFBG>>ATTR_BGSHIFT]); - oldpen = SelectObject(hdc, edge); + if (p.fErase || + p.rcPaint.left < offset_width || + p.rcPaint.top < offset_height || + p.rcPaint.right >= offset_width + font_width*term->cols || + p.rcPaint.bottom>= offset_height + font_height*term->rows) + { + HBRUSH fillcolour, oldbrush; + HPEN edge, oldpen; + fillcolour = CreateSolidBrush ( + colours[ATTR_DEFBG>>ATTR_BGSHIFT]); + oldbrush = SelectObject(hdc, fillcolour); + edge = CreatePen(PS_SOLID, 0, + colours[ATTR_DEFBG>>ATTR_BGSHIFT]); + oldpen = SelectObject(hdc, edge); - /* - * Jordan Russell reports that this apparently - * ineffectual IntersectClipRect() call masks a - * Windows NT/2K bug causing strange display - * problems when the PuTTY window is taller than - * the primary monitor. It seems harmless enough... - */ - IntersectClipRect(hdc, - p.rcPaint.left, p.rcPaint.top, - p.rcPaint.right, p.rcPaint.bottom); + /* + * Jordan Russell reports that this apparently + * ineffectual IntersectClipRect() call masks a + * Windows NT/2K bug causing strange display + * problems when the PuTTY window is taller than + * the primary monitor. It seems harmless enough... + */ + IntersectClipRect(hdc, + p.rcPaint.left, p.rcPaint.top, + p.rcPaint.right, p.rcPaint.bottom); - ExcludeClipRect(hdc, - offset_width, offset_height, - offset_width+font_width*term->cols, - offset_height+font_height*term->rows); + ExcludeClipRect(hdc, + offset_width, offset_height, + offset_width+font_width*term->cols, + offset_height+font_height*term->rows); - Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, - p.rcPaint.right, p.rcPaint.bottom); + Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, + p.rcPaint.right, p.rcPaint.bottom); - /* SelectClipRgn(hdc, NULL); */ + /* SelectClipRgn(hdc, NULL); */ - SelectObject(hdc, oldbrush); - DeleteObject(fillcolour); - SelectObject(hdc, oldpen); - DeleteObject(edge); - } - SelectObject(hdc, GetStockObject(SYSTEM_FONT)); - SelectObject(hdc, GetStockObject(WHITE_PEN)); - EndPaint(hwnd, &p); - ShowCaret(hwnd); - } - return 0; + SelectObject(hdc, oldbrush); + DeleteObject(fillcolour); + SelectObject(hdc, oldpen); + DeleteObject(edge); + } + SelectObject(hdc, GetStockObject(SYSTEM_FONT)); + SelectObject(hdc, GetStockObject(WHITE_PEN)); + EndPaint(hwnd, &p); + ShowCaret(hwnd); + } + return 0; case WM_NETEVENT: { /* @@ -2878,146 +2878,146 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, params->lParam = lParam; queue_toplevel_callback(wm_netevent_callback, params); } - return 0; + return 0; case WM_SETFOCUS: - term_set_focus(term, true); - CreateCaret(hwnd, caretbm, font_width, font_height); - ShowCaret(hwnd); - flash_window(0); /* stop */ - compose_state = 0; - term_update(term); - break; + term_set_focus(term, true); + CreateCaret(hwnd, caretbm, font_width, font_height); + ShowCaret(hwnd); + flash_window(0); /* stop */ + compose_state = 0; + term_update(term); + break; case WM_KILLFOCUS: - show_mouseptr(true); - term_set_focus(term, false); - DestroyCaret(); - caret_x = caret_y = -1; /* ensure caret is replaced next time */ - term_update(term); - break; + show_mouseptr(true); + term_set_focus(term, false); + DestroyCaret(); + caret_x = caret_y = -1; /* ensure caret is replaced next time */ + term_update(term); + break; case WM_ENTERSIZEMOVE: #ifdef RDB_DEBUG_PATCH - debug("WM_ENTERSIZEMOVE\n"); + debug("WM_ENTERSIZEMOVE\n"); #endif - EnableSizeTip(true); - resizing = true; - need_backend_resize = false; - break; + EnableSizeTip(true); + resizing = true; + need_backend_resize = false; + break; case WM_EXITSIZEMOVE: - EnableSizeTip(false); - resizing = false; + EnableSizeTip(false); + resizing = false; #ifdef RDB_DEBUG_PATCH - debug("WM_EXITSIZEMOVE\n"); + debug("WM_EXITSIZEMOVE\n"); #endif - if (need_backend_resize) { - term_size(term, conf_get_int(conf, CONF_height), - conf_get_int(conf, CONF_width), - conf_get_int(conf, CONF_savelines)); - InvalidateRect(hwnd, NULL, true); - } - break; + if (need_backend_resize) { + term_size(term, conf_get_int(conf, CONF_height), + conf_get_int(conf, CONF_width), + conf_get_int(conf, CONF_savelines)); + InvalidateRect(hwnd, NULL, true); + } + break; case WM_SIZING: - /* - * This does two jobs: - * 1) Keep the sizetip uptodate - * 2) Make sure the window size is _stepped_ in units of the font size. - */ - resize_action = conf_get_int(conf, CONF_resize_action); - if (resize_action == RESIZE_TERM || + /* + * This does two jobs: + * 1) Keep the sizetip uptodate + * 2) Make sure the window size is _stepped_ in units of the font size. + */ + resize_action = conf_get_int(conf, CONF_resize_action); + if (resize_action == RESIZE_TERM || (resize_action == RESIZE_EITHER && !is_alt_pressed())) { - int width, height, w, h, ew, eh; - LPRECT r = (LPRECT) lParam; + int width, height, w, h, ew, eh; + LPRECT r = (LPRECT) lParam; - if (!need_backend_resize && resize_action == RESIZE_EITHER && - (conf_get_int(conf, CONF_height) != term->rows || - conf_get_int(conf, CONF_width) != term->cols)) { - /* - * Great! It seems that both the terminal size and the - * font size have been changed and the user is now dragging. - * - * It will now be difficult to get back to the configured - * font size! - * - * This would be easier but it seems to be too confusing. - */ - conf_set_int(conf, CONF_height, term->rows); - conf_set_int(conf, CONF_width, term->cols); + if (!need_backend_resize && resize_action == RESIZE_EITHER && + (conf_get_int(conf, CONF_height) != term->rows || + conf_get_int(conf, CONF_width) != term->cols)) { + /* + * Great! It seems that both the terminal size and the + * font size have been changed and the user is now dragging. + * + * It will now be difficult to get back to the configured + * font size! + * + * This would be easier but it seems to be too confusing. + */ + conf_set_int(conf, CONF_height, term->rows); + conf_set_int(conf, CONF_width, term->cols); - InvalidateRect(hwnd, NULL, true); - need_backend_resize = true; - } + InvalidateRect(hwnd, NULL, true); + need_backend_resize = true; + } - 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); - ew = width - w * font_width; - eh = height - h * font_height; - if (ew != 0) { - if (wParam == WMSZ_LEFT || - 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) - r->top += eh; - else - r->bottom -= eh; - } - if (ew || eh) - return 1; - else - return 0; - } else { - int width, height, w, h, rv = 0; - int window_border = conf_get_int(conf, CONF_window_border); - int ex_width = extra_width + (window_border - offset_width) * 2; - int ex_height = extra_height + (window_border - offset_height) * 2; - 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); + ew = width - w * font_width; + eh = height - h * font_height; + if (ew != 0) { + if (wParam == WMSZ_LEFT || + 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) + r->top += eh; + else + r->bottom -= eh; + } + if (ew || eh) + return 1; + else + return 0; + } else { + int width, height, w, h, rv = 0; + int window_border = conf_get_int(conf, CONF_window_border); + int ex_width = extra_width + (window_border - offset_width) * 2; + int ex_height = extra_height + (window_border - offset_height) * 2; + LPRECT r = (LPRECT) lParam; - width = r->right - r->left - ex_width; - height = r->bottom - r->top - ex_height; + width = r->right - r->left - ex_width; + height = r->bottom - r->top - ex_height; - w = (width + term->cols/2)/term->cols; - h = (height + term->rows/2)/term->rows; - if ( r->right != r->left + w*term->cols + ex_width) - rv = 1; + w = (width + term->cols/2)/term->cols; + h = (height + term->rows/2)/term->rows; + if ( r->right != r->left + w*term->cols + ex_width) + rv = 1; - if (wParam == WMSZ_LEFT || - wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT) - r->left = r->right - w*term->cols - ex_width; - else - r->right = r->left + w*term->cols + ex_width; + if (wParam == WMSZ_LEFT || + wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT) + r->left = r->right - w*term->cols - ex_width; + else + r->right = r->left + w*term->cols + ex_width; - if (r->bottom != r->top + h*term->rows + ex_height) - rv = 1; + if (r->bottom != r->top + h*term->rows + ex_height) + rv = 1; - if (wParam == WMSZ_TOP || - wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT) - r->top = r->bottom - h*term->rows - ex_height; - else - r->bottom = r->top + h*term->rows + ex_height; + if (wParam == WMSZ_TOP || + wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT) + r->top = r->bottom - h*term->rows - ex_height; + else + r->bottom = r->top + h*term->rows + ex_height; - return rv; - } - /* break; (never reached) */ + return rv; + } + /* break; (never reached) */ case WM_FULLSCR_ON_MAX: - fullscr_on_max = true; - break; + fullscr_on_max = true; + break; case WM_MOVE: - sys_cursor_update(); - break; + sys_cursor_update(); + break; case WM_SIZE: - resize_action = conf_get_int(conf, CONF_resize_action); + resize_action = conf_get_int(conf, CONF_resize_action); #ifdef RDB_DEBUG_PATCH - debug("WM_SIZE %s (%d,%d)\n", + debug("WM_SIZE %s (%d,%d)\n", (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED": (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED": (wParam == SIZE_RESTORED && resizing) ? "to": @@ -3025,12 +3025,12 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, "...", LOWORD(lParam), HIWORD(lParam)); #endif - if (wParam == SIZE_MINIMIZED) - SetWindowText(hwnd, - conf_get_bool(conf, CONF_win_name_always) ? - window_name : icon_name); - if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED) - SetWindowText(hwnd, window_name); + if (wParam == SIZE_MINIMIZED) + SetWindowText(hwnd, + conf_get_bool(conf, CONF_win_name_always) ? + window_name : icon_name); + if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED) + SetWindowText(hwnd, window_name); if (wParam == SIZE_RESTORED) { processed_resize = false; clear_full_screen(); @@ -3061,16 +3061,16 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, processed_resize = true; - if (resize_action == RESIZE_DISABLED) { - /* A resize, well it better be a minimize. */ - reset_window(-1); - } else { + if (resize_action == RESIZE_DISABLED) { + /* A resize, well it better be a minimize. */ + reset_window(-1); + } else { - int width, height, w, h; + int width, height, w, h; int window_border = conf_get_int(conf, CONF_window_border); - width = LOWORD(lParam); - height = HIWORD(lParam); + width = LOWORD(lParam); + height = HIWORD(lParam); if (wParam == SIZE_MAXIMIZED) { was_zoomed = true; @@ -3114,7 +3114,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, reset_window(0); } else if (wParam == SIZE_MINIMIZED) { /* do nothing */ - } else if (resize_action == RESIZE_TERM || + } else if (resize_action == RESIZE_TERM || (resize_action == RESIZE_EITHER && !is_alt_pressed())) { w = (width-window_border*2) / font_width; @@ -3129,214 +3129,214 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, * getting sent down the connection during an NT * opaque drag.) */ - need_backend_resize = true; - conf_set_int(conf, CONF_height, h); - conf_set_int(conf, CONF_width, w); + need_backend_resize = true; + conf_set_int(conf, CONF_height, h); + conf_set_int(conf, CONF_width, w); } else { term_size(term, h, w, conf_get_int(conf, CONF_savelines)); } } else { reset_window(0); - } - } - sys_cursor_update(); - return 0; + } + } + sys_cursor_update(); + return 0; case WM_VSCROLL: - switch (LOWORD(wParam)) { - case SB_BOTTOM: - term_scroll(term, -1, 0); - break; - case SB_TOP: - term_scroll(term, +1, 0); - break; - case SB_LINEDOWN: - term_scroll(term, 0, +1); - break; - case SB_LINEUP: - term_scroll(term, 0, -1); - break; - case SB_PAGEDOWN: - term_scroll(term, 0, +term->rows / 2); - break; - case SB_PAGEUP: - term_scroll(term, 0, -term->rows / 2); - break; - case SB_THUMBPOSITION: - case SB_THUMBTRACK: - /* - * Use GetScrollInfo instead of HIWORD(wParam) to get - * 32-bit scroll position. - */ - { - SCROLLINFO si; + switch (LOWORD(wParam)) { + case SB_BOTTOM: + term_scroll(term, -1, 0); + break; + case SB_TOP: + term_scroll(term, +1, 0); + break; + case SB_LINEDOWN: + term_scroll(term, 0, +1); + break; + case SB_LINEUP: + term_scroll(term, 0, -1); + break; + case SB_PAGEDOWN: + term_scroll(term, 0, +term->rows / 2); + break; + case SB_PAGEUP: + term_scroll(term, 0, -term->rows / 2); + break; + case SB_THUMBPOSITION: + case SB_THUMBTRACK: + /* + * Use GetScrollInfo instead of HIWORD(wParam) to get + * 32-bit scroll position. + */ + { + SCROLLINFO si; - si.cbSize = sizeof(si); - si.fMask = SIF_TRACKPOS; - if (GetScrollInfo(hwnd, SB_VERT, &si) == 0) - si.nTrackPos = HIWORD(wParam); - term_scroll(term, 1, si.nTrackPos); - } - break; - } - break; + si.cbSize = sizeof(si); + si.fMask = SIF_TRACKPOS; + if (GetScrollInfo(hwnd, SB_VERT, &si) == 0) + si.nTrackPos = HIWORD(wParam); + term_scroll(term, 1, si.nTrackPos); + } + break; + } + break; case WM_PALETTECHANGED: - if ((HWND) wParam != hwnd && pal != NULL) { - HDC hdc = make_hdc(); - if (hdc) { - if (RealizePalette(hdc) > 0) - UpdateColors(hdc); - free_hdc(hdc); - } - } - break; + if ((HWND) wParam != hwnd && pal != NULL) { + HDC hdc = make_hdc(); + if (hdc) { + if (RealizePalette(hdc) > 0) + UpdateColors(hdc); + free_hdc(hdc); + } + } + break; case WM_QUERYNEWPALETTE: - if (pal != NULL) { - HDC hdc = make_hdc(); - if (hdc) { - if (RealizePalette(hdc) > 0) - UpdateColors(hdc); - free_hdc(hdc); - return true; - } - } - return false; + if (pal != NULL) { + HDC hdc = make_hdc(); + if (hdc) { + if (RealizePalette(hdc) > 0) + UpdateColors(hdc); + free_hdc(hdc); + return true; + } + } + return false; case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: - /* - * Add the scan code and keypress timing to the random - * number noise. - */ - noise_ultralight(NOISE_SOURCE_KEY, lParam); + /* + * Add the scan code and keypress timing to the random + * number noise. + */ + noise_ultralight(NOISE_SOURCE_KEY, lParam); - /* - * We don't do TranslateMessage since it disassociates the - * resulting CHAR message from the KEYDOWN that sparked it, - * which we occasionally don't want. Instead, we process - * KEYDOWN, and call the Win32 translator functions so that - * we get the translations under _our_ control. - */ - { - unsigned char buf[20]; - int len; + /* + * We don't do TranslateMessage since it disassociates the + * resulting CHAR message from the KEYDOWN that sparked it, + * which we occasionally don't want. Instead, we process + * KEYDOWN, and call the Win32 translator functions so that + * we get the translations under _our_ control. + */ + { + unsigned char buf[20]; + int len; - if (wParam == VK_PROCESSKEY || /* IME PROCESS key */ + if (wParam == VK_PROCESSKEY || /* IME PROCESS key */ wParam == VK_PACKET) { /* 'this key is a Unicode char' */ - if (message == WM_KEYDOWN) { - MSG m; - m.hwnd = hwnd; - m.message = WM_KEYDOWN; - m.wParam = wParam; - m.lParam = lParam & 0xdfff; - TranslateMessage(&m); - } else break; /* pass to Windows for default processing */ - } else { - len = TranslateKey(message, wParam, lParam, buf); - if (len == -1) - return DefWindowProcW(hwnd, message, wParam, lParam); + if (message == WM_KEYDOWN) { + MSG m; + m.hwnd = hwnd; + m.message = WM_KEYDOWN; + m.wParam = wParam; + m.lParam = lParam & 0xdfff; + TranslateMessage(&m); + } else break; /* pass to Windows for default processing */ + } else { + len = TranslateKey(message, wParam, lParam, buf); + if (len == -1) + return DefWindowProcW(hwnd, message, wParam, lParam); - if (len != 0) { - /* - * We need not bother about stdin backlogs - * here, because in GUI PuTTY we can't do - * anything about it anyway; there's no means - * of asking Windows to hold off on KEYDOWN - * messages. We _have_ to buffer everything - * we're sent. - */ + if (len != 0) { + /* + * We need not bother about stdin backlogs + * here, because in GUI PuTTY we can't do + * anything about it anyway; there's no means + * of asking Windows to hold off on KEYDOWN + * messages. We _have_ to buffer everything + * we're sent. + */ term_keyinput(term, -1, buf, len); - show_mouseptr(false); - } - } - } - return 0; + show_mouseptr(false); + } + } + } + return 0; case WM_INPUTLANGCHANGE: - /* wParam == Font number */ - /* lParam == Locale */ - set_input_locale((HKL)lParam); - sys_cursor_update(); - break; + /* wParam == Font number */ + /* lParam == Locale */ + set_input_locale((HKL)lParam); + sys_cursor_update(); + break; case WM_IME_STARTCOMPOSITION: - { - HIMC hImc = ImmGetContext(hwnd); - ImmSetCompositionFont(hImc, &lfont); - ImmReleaseContext(hwnd, hImc); - } - break; + { + HIMC hImc = ImmGetContext(hwnd); + ImmSetCompositionFont(hImc, &lfont); + ImmReleaseContext(hwnd, hImc); + } + break; case WM_IME_COMPOSITION: - { - HIMC hIMC; - int n; - char *buff; + { + HIMC hIMC; + int n; + char *buff; - if (osPlatformId == VER_PLATFORM_WIN32_WINDOWS || - osPlatformId == VER_PLATFORM_WIN32s) + if (osPlatformId == VER_PLATFORM_WIN32_WINDOWS || + osPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */ - if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */ - break; /* fall back to DefWindowProc */ + if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */ + break; /* fall back to DefWindowProc */ - hIMC = ImmGetContext(hwnd); - n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0); + hIMC = ImmGetContext(hwnd); + n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0); - if (n > 0) { - int i; - buff = snewn(n, char); - ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n); - /* - * Jaeyoun Chung reports that Korean character - * input doesn't work correctly if we do a single - * term_keyinputw covering the whole of buff. So - * instead we send the characters one by one. - */ - /* don't divide SURROGATE PAIR */ - if (ldisc) { + if (n > 0) { + int i; + buff = snewn(n, char); + ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n); + /* + * Jaeyoun Chung reports that Korean character + * input doesn't work correctly if we do a single + * term_keyinputw covering the whole of buff. So + * instead we send the characters one by one. + */ + /* don't divide SURROGATE PAIR */ + if (ldisc) { for (i = 0; i < n; i += 2) { - WCHAR hs = *(unsigned short *)(buff+i); - if (IS_HIGH_SURROGATE(hs) && i+2 < n) { - WCHAR ls = *(unsigned short *)(buff+i+2); - if (IS_LOW_SURROGATE(ls)) { + WCHAR hs = *(unsigned short *)(buff+i); + if (IS_HIGH_SURROGATE(hs) && i+2 < n) { + WCHAR ls = *(unsigned short *)(buff+i+2); + if (IS_LOW_SURROGATE(ls)) { term_keyinputw( term, (unsigned short *)(buff+i), 2); - i += 2; - continue; - } - } + i += 2; + continue; + } + } term_keyinputw( term, (unsigned short *)(buff+i), 1); } - } - free(buff); - } - ImmReleaseContext(hwnd, hIMC); - return 1; - } + } + free(buff); + } + ImmReleaseContext(hwnd, hIMC); + return 1; + } case WM_IME_CHAR: - if (wParam & 0xFF00) { - char buf[2]; + if (wParam & 0xFF00) { + char buf[2]; - buf[1] = wParam; - buf[0] = wParam >> 8; + buf[1] = wParam; + buf[0] = wParam >> 8; term_keyinput(term, kbd_codepage, buf, 2); - } else { - char c = (unsigned char) wParam; - term_seen_key_event(term); + } else { + char c = (unsigned char) wParam; + term_seen_key_event(term); term_keyinput(term, kbd_codepage, &c, 1); - } - return (0); + } + return (0); case WM_CHAR: case WM_SYSCHAR: - /* - * Nevertheless, we are prepared to deal with WM_CHAR - * messages, should they crop up. So if someone wants to - * post the things to us as part of a macro manoeuvre, - * we're ready to cope. - */ - { + /* + * Nevertheless, we are prepared to deal with WM_CHAR + * messages, should they crop up. So if someone wants to + * post the things to us as part of a macro manoeuvre, + * we're ready to cope. + */ + { static wchar_t pending_surrogate = 0; - wchar_t c = wParam; + wchar_t c = wParam; if (IS_HIGH_SURROGATE(c)) { pending_surrogate = c; @@ -3348,83 +3348,83 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, } else if (!IS_SURROGATE(c)) { term_keyinputw(term, &c, 1); } - } - return 0; + } + return 0; case WM_SYSCOLORCHANGE: - if (conf_get_bool(conf, CONF_system_colour)) { - /* Refresh palette from system colours. */ - /* XXX actually this zaps the entire palette. */ - systopalette(); - init_palette(); - /* Force a repaint of the terminal window. */ - term_invalidate(term); - } - break; + if (conf_get_bool(conf, CONF_system_colour)) { + /* Refresh palette from system colours. */ + /* XXX actually this zaps the entire palette. */ + systopalette(); + init_palette(); + /* Force a repaint of the terminal window. */ + term_invalidate(term); + } + break; case WM_AGENT_CALLBACK: - { - struct agent_callback *c = (struct agent_callback *)lParam; - c->callback(c->callback_ctx, c->data, c->len); - sfree(c); - } - return 0; + { + struct agent_callback *c = (struct agent_callback *)lParam; + c->callback(c->callback_ctx, c->data, c->len); + sfree(c); + } + return 0; case WM_GOT_CLIPDATA: - process_clipdata((HGLOBAL)lParam, wParam); - return 0; + process_clipdata((HGLOBAL)lParam, wParam); + return 0; default: - if (message == wm_mousewheel || message == WM_MOUSEWHEEL) { - bool shift_pressed = false, control_pressed = false; + if (message == wm_mousewheel || message == WM_MOUSEWHEEL) { + bool shift_pressed = false, control_pressed = false; - if (message == WM_MOUSEWHEEL) { - wheel_accumulator += (short)HIWORD(wParam); - shift_pressed=LOWORD(wParam) & MK_SHIFT; - control_pressed=LOWORD(wParam) & MK_CONTROL; - } else { - BYTE keys[256]; - wheel_accumulator += (int)wParam; - if (GetKeyboardState(keys)!=0) { - shift_pressed=keys[VK_SHIFT]&0x80; - control_pressed=keys[VK_CONTROL]&0x80; - } - } + if (message == WM_MOUSEWHEEL) { + wheel_accumulator += (short)HIWORD(wParam); + shift_pressed=LOWORD(wParam) & MK_SHIFT; + control_pressed=LOWORD(wParam) & MK_CONTROL; + } else { + BYTE keys[256]; + wheel_accumulator += (int)wParam; + if (GetKeyboardState(keys)!=0) { + shift_pressed=keys[VK_SHIFT]&0x80; + control_pressed=keys[VK_CONTROL]&0x80; + } + } - /* process events when the threshold is reached */ - while (abs(wheel_accumulator) >= WHEEL_DELTA) { - int b; + /* process events when the threshold is reached */ + while (abs(wheel_accumulator) >= WHEEL_DELTA) { + int b; - /* reduce amount for next time */ - if (wheel_accumulator > 0) { - b = MBT_WHEEL_UP; - wheel_accumulator -= WHEEL_DELTA; - } else if (wheel_accumulator < 0) { - b = MBT_WHEEL_DOWN; - wheel_accumulator += WHEEL_DELTA; - } else - break; + /* reduce amount for next time */ + if (wheel_accumulator > 0) { + b = MBT_WHEEL_UP; + wheel_accumulator -= WHEEL_DELTA; + } else if (wheel_accumulator < 0) { + b = MBT_WHEEL_DOWN; + wheel_accumulator += WHEEL_DELTA; + } else + break; - if (send_raw_mouse && - !(conf_get_bool(conf, CONF_mouse_override) && + if (send_raw_mouse && + !(conf_get_bool(conf, CONF_mouse_override) && shift_pressed)) { - /* Mouse wheel position is in screen coordinates for - * some reason */ - POINT p; - p.x = X_POS(lParam); p.y = Y_POS(lParam); - if (ScreenToClient(hwnd, &p)) { - /* send a mouse-down followed by a mouse up */ - term_mouse(term, b, translate_button(b), - MA_CLICK, - TO_CHR_X(p.x), - TO_CHR_Y(p.y), shift_pressed, - control_pressed, is_alt_pressed()); - } /* else: not sure when this can fail */ - } else { - /* trigger a scroll */ - term_scroll(term, 0, - b == MBT_WHEEL_UP ? - -term->rows / 2 : term->rows / 2); - } - } - return 0; - } + /* Mouse wheel position is in screen coordinates for + * some reason */ + POINT p; + p.x = X_POS(lParam); p.y = Y_POS(lParam); + if (ScreenToClient(hwnd, &p)) { + /* send a mouse-down followed by a mouse up */ + term_mouse(term, b, translate_button(b), + MA_CLICK, + TO_CHR_X(p.x), + TO_CHR_Y(p.y), shift_pressed, + control_pressed, is_alt_pressed()); + } /* else: not sure when this can fail */ + } else { + /* trigger a scroll */ + term_scroll(term, 0, + b == MBT_WHEEL_UP ? + -term->rows / 2 : term->rows / 2); + } + } + return 0; + } } /* @@ -3453,7 +3453,7 @@ static void wintw_set_cursor_pos(TermWin *tw, int x, int y) cx = x * font_width + offset_width; cy = y * font_height + offset_height; if (cx == caret_x && cy == caret_y) - return; + return; caret_x = cx; caret_y = cy; @@ -3468,13 +3468,13 @@ static void sys_cursor_update(void) if (!term->has_focus) return; if (caret_x < 0 || caret_y < 0) - return; + return; SetCaretPos(caret_x, caret_y); /* IMM calls on Win98 and beyond only */ if (osPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */ - + if (osPlatformId == VER_PLATFORM_WIN32_WINDOWS && osMinorVersion == 0) return; /* 95 */ @@ -3518,11 +3518,11 @@ static void do_text_internal( char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM)); if (attr & ATTR_WIDE) - char_width *= 2; + char_width *= 2; /* Only want the left half of double width lines */ if (lattr != LATTR_NORM && x*2 >= term->cols) - return; + return; x *= fnt_width; y *= font_height; @@ -3531,114 +3531,114 @@ static void do_text_internal( if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) { truecolour.fg = truecolour.bg = optionalrgb_none; - attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS|ATTR_DIM); - /* cursor fg and bg */ - attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT); + attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS|ATTR_DIM); + /* cursor fg and bg */ + attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT); is_cursor = true; } nfont = 0; if (vtmode == VT_POORMAN && lattr != LATTR_NORM) { - /* Assume a poorman font is borken in other ways too. */ - lattr = LATTR_WIDE; + /* Assume a poorman font is borken in other ways too. */ + lattr = LATTR_WIDE; } else - switch (lattr) { - case LATTR_NORM: - break; - case LATTR_WIDE: - nfont |= FONT_WIDE; - break; - default: - nfont |= FONT_WIDE + FONT_HIGH; - break; - } + switch (lattr) { + case LATTR_NORM: + break; + case LATTR_WIDE: + nfont |= FONT_WIDE; + break; + default: + nfont |= FONT_WIDE + FONT_HIGH; + break; + } if (attr & ATTR_NARROW) - nfont |= FONT_NARROW; + nfont |= FONT_NARROW; #ifdef USES_VTLINE_HACK /* Special hack for the VT100 linedraw glyphs. */ if (text[0] >= 0x23BA && text[0] <= 0x23BD) { - switch ((unsigned char) (text[0])) { - case 0xBA: - text_adjust = -2 * font_height / 5; - break; - case 0xBB: - text_adjust = -1 * font_height / 5; - break; - case 0xBC: - text_adjust = font_height / 5; - break; - case 0xBD: - text_adjust = 2 * font_height / 5; - break; - } - if (lattr == LATTR_TOP || lattr == LATTR_BOT) - text_adjust *= 2; - text[0] = ucsdata.unitab_xterm['q']; - if (attr & ATTR_UNDER) { - attr &= ~ATTR_UNDER; - force_manual_underline = true; - } + switch ((unsigned char) (text[0])) { + case 0xBA: + text_adjust = -2 * font_height / 5; + break; + case 0xBB: + text_adjust = -1 * font_height / 5; + break; + case 0xBC: + text_adjust = font_height / 5; + break; + case 0xBD: + text_adjust = 2 * font_height / 5; + break; + } + if (lattr == LATTR_TOP || lattr == LATTR_BOT) + text_adjust *= 2; + text[0] = ucsdata.unitab_xterm['q']; + if (attr & ATTR_UNDER) { + attr &= ~ATTR_UNDER; + force_manual_underline = true; + } } #endif /* Anything left as an original character set is unprintable. */ if (DIRECT_CHAR(text[0]) && (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) { - int i; - for (i = 0; i < len; i++) - text[i] = 0xFFFD; + int i; + for (i = 0; i < len; i++) + text[i] = 0xFFFD; } /* OEM CP */ if ((text[0] & CSET_MASK) == CSET_OEMCP) - nfont |= FONT_OEM; + nfont |= FONT_OEM; nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT); nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT); if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD)) - nfont |= FONT_BOLD; + nfont |= FONT_BOLD; if (und_mode == UND_FONT && (attr & ATTR_UNDER)) - nfont |= FONT_UNDERLINE; + nfont |= FONT_UNDERLINE; another_font(nfont); if (!fonts[nfont]) { - if (nfont & FONT_UNDERLINE) - force_manual_underline = true; - /* Don't do the same for manual bold, it could be bad news. */ + if (nfont & FONT_UNDERLINE) + force_manual_underline = true; + /* Don't do the same for manual bold, it could be bad news. */ - nfont &= ~(FONT_BOLD | FONT_UNDERLINE); + nfont &= ~(FONT_BOLD | FONT_UNDERLINE); } another_font(nfont); if (!fonts[nfont]) - nfont = FONT_NORMAL; + nfont = FONT_NORMAL; if (attr & ATTR_REVERSE) { struct optionalrgb trgb; - t = nfg; - nfg = nbg; - nbg = t; + t = nfg; + nfg = nbg; + nbg = t; trgb = truecolour.fg; truecolour.fg = truecolour.bg; truecolour.bg = trgb; } if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) { - if (nfg < 16) nfg |= 8; - else if (nfg >= 256) nfg |= 1; + if (nfg < 16) nfg |= 8; + else if (nfg >= 256) nfg |= 1; } if (bold_colours && (attr & ATTR_BLINK)) { - if (nbg < 16) nbg |= 8; - else if (nbg >= 256) nbg |= 1; + if (nbg < 16) nbg |= 8; + else if (nbg >= 256) nbg |= 1; } if (!pal && truecolour.fg.enabled) - fg = RGB(truecolour.fg.r, truecolour.fg.g, truecolour.fg.b); + fg = RGB(truecolour.fg.r, truecolour.fg.g, truecolour.fg.b); else - fg = colours[nfg]; + fg = colours[nfg]; if (!pal && truecolour.bg.enabled) - bg = RGB(truecolour.bg.r, truecolour.bg.g, truecolour.bg.b); + bg = RGB(truecolour.bg.r, truecolour.bg.g, truecolour.bg.b); else - bg = colours[nbg]; + bg = colours[nbg]; if (!pal && (attr & ATTR_DIM)) { fg = RGB(GetRValue(fg) * 2 / 3, @@ -3650,35 +3650,35 @@ static void do_text_internal( SetTextColor(wintw_hdc, fg); SetBkColor(wintw_hdc, bg); if (attr & TATTR_COMBINING) - SetBkMode(wintw_hdc, TRANSPARENT); + SetBkMode(wintw_hdc, TRANSPARENT); else - SetBkMode(wintw_hdc, OPAQUE); + SetBkMode(wintw_hdc, OPAQUE); line_box.left = x; line_box.top = y; line_box.right = x + char_width * len; line_box.bottom = y + font_height; /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */ { - int i; - int rc_width = 0; - for (i = 0; i < len ; i++) { - if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) { - i++; - } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) { - rc_width += char_width; - i++; - } else if (IS_LOW_VARSEL(text[i])) { - /* do nothing */ + int i; + int rc_width = 0; + for (i = 0; i < len ; i++) { + if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) { + i++; + } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) { + rc_width += char_width; + i++; + } else if (IS_LOW_VARSEL(text[i])) { + /* do nothing */ } else { - rc_width += char_width; + rc_width += char_width; } - } - line_box.right = line_box.left + rc_width; + } + line_box.right = line_box.left + rc_width; } /* Only want the left half of double width lines */ if (line_box.right > font_width*term->cols+offset_width) - line_box.right = font_width*term->cols+offset_width; + line_box.right = font_width*term->cols+offset_width; if (font_varpitch) { /* @@ -3719,10 +3719,10 @@ static void do_text_internal( len += 2; } - if (len > lpDx_len) { + if (len > lpDx_len) { sgrowarray(lpDx, lpDx_len, len); - if (lpDx_maybe) lpDx_maybe = lpDx; - } + if (lpDx_maybe) lpDx_maybe = lpDx; + } { int i; @@ -3781,7 +3781,7 @@ static void do_text_internal( nlen++; } if (nlen <= 0) - return; /* Eeek! */ + return; /* Eeek! */ ExtTextOutW(wintw_hdc, x + xoffset, y - font_height * (lattr == LATTR_BOT) + text_adjust, @@ -3816,7 +3816,7 @@ static void do_text_internal( * 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... @@ -3865,18 +3865,18 @@ static void do_text_internal( opaque = false; } if (lattr != LATTR_TOP && (force_manual_underline || - (und_mode == UND_LINE - && (attr & ATTR_UNDER)))) { - HPEN oldpen; - int dec = descent; - if (lattr == LATTR_BOT) - dec = dec * 2 - font_height; + (und_mode == UND_LINE + && (attr & ATTR_UNDER)))) { + HPEN oldpen; + int dec = descent; + if (lattr == LATTR_BOT) + dec = dec * 2 - font_height; - oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, fg)); - MoveToEx(wintw_hdc, line_box.left, line_box.top + dec, NULL); - LineTo(wintw_hdc, line_box.right, line_box.top + dec); - oldpen = SelectObject(wintw_hdc, oldpen); - DeleteObject(oldpen); + oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, fg)); + MoveToEx(wintw_hdc, line_box.left, line_box.top + dec, NULL); + LineTo(wintw_hdc, line_box.right, line_box.top + dec); + oldpen = SelectObject(wintw_hdc, oldpen); + DeleteObject(oldpen); } } @@ -3888,40 +3888,40 @@ static void wintw_draw_text( unsigned long attr, int lattr, truecolour truecolour) { if (attr & TATTR_COMBINING) { - unsigned long a = 0; - int len0 = 1; + unsigned long a = 0; + int len0 = 1; /* don't divide SURROGATE PAIR and VARIATION SELECTOR */ - if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1])) - len0 = 2; - if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) { - attr &= ~TATTR_COMBINING; - do_text_internal(x, y, text, len0+1, attr, lattr, truecolour); - text += len0+1; - len -= len0+1; - a = TATTR_COMBINING; - } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) { - attr &= ~TATTR_COMBINING; - do_text_internal(x, y, text, len0+2, attr, lattr, truecolour); - text += len0+2; - len -= len0+2; - a = TATTR_COMBINING; - } else { + if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1])) + len0 = 2; + if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) { + attr &= ~TATTR_COMBINING; + do_text_internal(x, y, text, len0+1, attr, lattr, truecolour); + text += len0+1; + len -= len0+1; + a = TATTR_COMBINING; + } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) { + attr &= ~TATTR_COMBINING; + do_text_internal(x, y, text, len0+2, attr, lattr, truecolour); + text += len0+2; + len -= len0+2; + a = TATTR_COMBINING; + } else { attr &= ~TATTR_COMBINING; } - while (len--) { - if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) { - do_text_internal(x, y, text, 2, attr | a, lattr, truecolour); - len--; - text++; - } else + while (len--) { + if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) { + do_text_internal(x, y, text, 2, attr | a, lattr, truecolour); + len--; + text++; + } else do_text_internal(x, y, text, 1, attr | a, lattr, truecolour); - text++; - a = TATTR_COMBINING; - } + text++; + a = TATTR_COMBINING; + } } else - do_text_internal(x, y, text, len, attr, lattr, truecolour); + do_text_internal(x, y, text, len, attr, lattr, truecolour); } static void wintw_draw_cursor( @@ -3935,68 +3935,68 @@ static void wintw_draw_cursor( lattr &= LATTR_MODE; if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) { - if (*text != UCSWIDE) { - win_draw_text(tw, x, y, text, len, attr, lattr, truecolour); - return; - } - ctype = 2; - attr |= TATTR_RIGHTCURS; + if (*text != UCSWIDE) { + win_draw_text(tw, x, y, text, len, attr, lattr, truecolour); + return; + } + ctype = 2; + attr |= TATTR_RIGHTCURS; } fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM)); if (attr & ATTR_WIDE) - char_width *= 2; + char_width *= 2; x *= fnt_width; y *= font_height; x += offset_width; y += offset_height; if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) { - POINT pts[5]; - HPEN oldpen; - pts[0].x = pts[1].x = pts[4].x = x; - pts[2].x = pts[3].x = x + char_width - 1; - pts[0].y = pts[3].y = pts[4].y = y; - pts[1].y = pts[2].y = y + font_height - 1; - oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261])); - Polyline(wintw_hdc, pts, 5); - oldpen = SelectObject(wintw_hdc, oldpen); - DeleteObject(oldpen); + POINT pts[5]; + HPEN oldpen; + pts[0].x = pts[1].x = pts[4].x = x; + pts[2].x = pts[3].x = x + char_width - 1; + pts[0].y = pts[3].y = pts[4].y = y; + pts[1].y = pts[2].y = y + font_height - 1; + oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261])); + Polyline(wintw_hdc, pts, 5); + oldpen = SelectObject(wintw_hdc, oldpen); + DeleteObject(oldpen); } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) { - int startx, starty, dx, dy, length, i; - if (ctype == 1) { - startx = x; - starty = y + descent; - dx = 1; - dy = 0; - length = char_width; - } else { - int xadjust = 0; - if (attr & TATTR_RIGHTCURS) - xadjust = char_width - 1; - startx = x + xadjust; - starty = y; - dx = 0; - dy = 1; - length = font_height; - } - if (attr & TATTR_ACTCURS) { - HPEN oldpen; - oldpen = - SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261])); - MoveToEx(wintw_hdc, startx, starty, NULL); - LineTo(wintw_hdc, startx + dx * length, starty + dy * length); - oldpen = SelectObject(wintw_hdc, oldpen); - DeleteObject(oldpen); - } else { - for (i = 0; i < length; i++) { - if (i % 2 == 0) { - SetPixel(wintw_hdc, startx, starty, colours[261]); - } - startx += dx; - starty += dy; - } - } + int startx, starty, dx, dy, length, i; + if (ctype == 1) { + startx = x; + starty = y + descent; + dx = 1; + dy = 0; + length = char_width; + } else { + int xadjust = 0; + if (attr & TATTR_RIGHTCURS) + xadjust = char_width - 1; + startx = x + xadjust; + starty = y; + dx = 0; + dy = 1; + length = font_height; + } + if (attr & TATTR_ACTCURS) { + HPEN oldpen; + oldpen = + SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261])); + MoveToEx(wintw_hdc, startx, starty, NULL); + LineTo(wintw_hdc, startx + dx * length, starty + dy * length); + oldpen = SelectObject(wintw_hdc, oldpen); + DeleteObject(oldpen); + } else { + for (i = 0; i < length; i++) { + if (i % 2 == 0) { + SetPixel(wintw_hdc, startx, starty, colours[261]); + } + startx += dx; + starty += dy; + } + } } } @@ -4024,48 +4024,48 @@ static int wintw_char_width(TermWin *tw, int uc) switch (uc & CSET_MASK) { case CSET_ASCII: - uc = ucsdata.unitab_line[uc & 0xFF]; - break; + uc = ucsdata.unitab_line[uc & 0xFF]; + break; case CSET_LINEDRW: - uc = ucsdata.unitab_xterm[uc & 0xFF]; - break; + uc = ucsdata.unitab_xterm[uc & 0xFF]; + break; case CSET_SCOACS: - uc = ucsdata.unitab_scoacs[uc & 0xFF]; - break; + uc = ucsdata.unitab_scoacs[uc & 0xFF]; + break; } if (DIRECT_FONT(uc)) { - if (ucsdata.dbcs_screenfont) return 1; + if (ucsdata.dbcs_screenfont) return 1; - /* Speedup, I know of no font where ascii is the wrong width */ - if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~') - return 1; + /* Speedup, I know of no font where ascii is the wrong width */ + if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~') + return 1; - if ( (uc & CSET_MASK) == CSET_ACP ) { - SelectObject(wintw_hdc, fonts[FONT_NORMAL]); - } else if ( (uc & CSET_MASK) == CSET_OEMCP ) { - another_font(FONT_OEM); - if (!fonts[FONT_OEM]) return 0; + if ( (uc & CSET_MASK) == CSET_ACP ) { + SelectObject(wintw_hdc, fonts[FONT_NORMAL]); + } else if ( (uc & CSET_MASK) == CSET_OEMCP ) { + another_font(FONT_OEM); + if (!fonts[FONT_OEM]) return 0; - SelectObject(wintw_hdc, fonts[FONT_OEM]); - } else - return 0; + SelectObject(wintw_hdc, fonts[FONT_OEM]); + } else + return 0; - if (GetCharWidth32(wintw_hdc, uc & ~CSET_MASK, + if (GetCharWidth32(wintw_hdc, uc & ~CSET_MASK, uc & ~CSET_MASK, &ibuf) != 1 && - GetCharWidth(wintw_hdc, uc & ~CSET_MASK, + GetCharWidth(wintw_hdc, uc & ~CSET_MASK, uc & ~CSET_MASK, &ibuf) != 1) - return 0; + return 0; } else { - /* Speedup, I know of no font where ascii is the wrong width */ - if (uc >= ' ' && uc <= '~') return 1; + /* Speedup, I know of no font where ascii is the wrong width */ + if (uc >= ' ' && uc <= '~') return 1; - SelectObject(wintw_hdc, fonts[FONT_NORMAL]); - if (GetCharWidth32W(wintw_hdc, uc, uc, &ibuf) == 1) - /* Okay that one worked */ ; - else if (GetCharWidthW(wintw_hdc, uc, uc, &ibuf) == 1) - /* This should work on 9x too, but it's "less accurate" */ ; - else - return 0; + SelectObject(wintw_hdc, fonts[FONT_NORMAL]); + if (GetCharWidth32W(wintw_hdc, uc, uc, &ibuf) == 1) + /* Okay that one worked */ ; + else if (GetCharWidthW(wintw_hdc, uc, uc, &ibuf) == 1) + /* This should work on 9x too, but it's "less accurate" */ ; + else + return 0; } ibuf += font_width / 2 -1; @@ -4095,7 +4095,7 @@ static void init_winfuncs(void) * to indicate a NUL-terminated "special" string. */ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, - unsigned char *output) + unsigned char *output) { BYTE keystate[256]; int scan, shift_state; @@ -4117,214 +4117,214 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, r = GetKeyboardState(keystate); if (!r) - memset(keystate, 0, sizeof(keystate)); + memset(keystate, 0, sizeof(keystate)); else { #if 0 #define SHOW_TOASCII_RESULT - { /* 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; + { /* 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)); + 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); + ch = MapVirtualKeyEx(wParam, 2, kbd_layout); + if (ch >= ' ' && ch <= '~') + debug(", '%c'", ch); + else if (ch) + debug(", $%02x", ch); - if (keys_unicode[0]) - debug(", KB0=%04x", keys_unicode[0]); - if (keys_unicode[1]) - debug(", KB1=%04x", keys_unicode[1]); - if (keys_unicode[2]) - debug(", KB2=%04x", keys_unicode[2]); + if (keys_unicode[0]) + debug(", KB0=%04x", keys_unicode[0]); + if (keys_unicode[1]) + debug(", KB1=%04x", keys_unicode[1]); + if (keys_unicode[2]) + debug(", KB2=%04x", keys_unicode[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 ((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; + 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]); + for (ch = 0; ch < 256; ch++) + if (oldstate[ch] != keystate[ch]) + debug(", M%02x=%02x", ch, keystate[ch]); - memcpy(oldstate, keystate, sizeof(oldstate)); - } + memcpy(oldstate, keystate, sizeof(oldstate)); + } #endif - if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) { - keystate[VK_RMENU] = keystate[VK_MENU]; - } + if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) { + keystate[VK_RMENU] = keystate[VK_MENU]; + } - /* Nastyness with NUMLock - Shift-NUMLock is left alone though */ - if ((funky_type == FUNKY_VT400 || - (funky_type <= FUNKY_LINUX && term->app_keypad_keys && - !no_applic_k)) - && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) { + /* Nastyness with NUMLock - Shift-NUMLock is left alone though */ + if ((funky_type == FUNKY_VT400 || + (funky_type <= FUNKY_LINUX && term->app_keypad_keys && + !no_applic_k)) + && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) { - wParam = VK_EXECUTE; + wParam = VK_EXECUTE; - /* UnToggle NUMLock */ - if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) - keystate[VK_NUMLOCK] ^= 1; - } + /* UnToggle NUMLock */ + if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) + keystate[VK_NUMLOCK] ^= 1; + } - /* And write back the 'adjusted' state */ - SetKeyboardState(keystate); + /* And write back the 'adjusted' state */ + SetKeyboardState(keystate); } /* Disable Auto repeat if required */ if (term->repeat_off && - (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) - return 0; + (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) + return 0; if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0) - left_alt = true; + left_alt = true; 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 (ctrlaltkeys) - keystate[VK_MENU] = 0; - else { - keystate[VK_RMENU] = 0x80; - left_alt = false; - } + if (ctrlaltkeys) + keystate[VK_MENU] = 0; + else { + keystate[VK_RMENU] = 0x80; + left_alt = false; + } } scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF)); shift_state = ((keystate[VK_SHIFT] & 0x80) != 0) - + ((keystate[VK_CONTROL] & 0x80) != 0) * 2; + + ((keystate[VK_CONTROL] & 0x80) != 0) * 2; /* Note if AltGr was pressed and if it was used as a compose key */ if (!compose_state) { - compose_keycode = 0x100; - if (conf_get_bool(conf, CONF_compose_key)) { - if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) - compose_keycode = wParam; - } - if (wParam == VK_APPS) - compose_keycode = wParam; + compose_keycode = 0x100; + if (conf_get_bool(conf, CONF_compose_key)) { + if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) + compose_keycode = wParam; + } + if (wParam == VK_APPS) + compose_keycode = wParam; } if (wParam == compose_keycode) { - 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; + 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) - compose_state = 0; + compose_state = 0; if (compose_state > 1 && left_alt) - compose_state = 0; + compose_state = 0; /* Sanitize the number pad if not using a PC NumPad */ if (left_alt || (term->app_keypad_keys && !no_applic_k - && funky_type != FUNKY_XTERM) - || funky_type == FUNKY_VT400 || 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; - } - if (nParam) { - if (keystate[VK_NUMLOCK] & 1) - shift_state |= 1; - wParam = nParam; - } - } + && funky_type != FUNKY_XTERM) + || funky_type == FUNKY_VT400 || 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; + } + 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'; + /* 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; - } + /* 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; + } if (wParam == VK_PRIOR && shift_state == 3) { /* ctrl-shift-pageup */ SendMessage(hwnd, WM_VSCROLL, SB_TOP, 0); return 0; @@ -4334,23 +4334,23 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, return 0; } - if (wParam == VK_PRIOR && shift_state == 2) { - SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0); - return 0; - } - if (wParam == VK_NEXT && shift_state == 1) { - SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0); - return 0; - } - if (wParam == VK_NEXT && shift_state == 2) { - SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0); - return 0; - } - if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) { - term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1)); - return 0; - } - if (wParam == VK_INSERT && shift_state == 2) { + if (wParam == VK_PRIOR && shift_state == 2) { + SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0); + return 0; + } + if (wParam == VK_NEXT && shift_state == 1) { + SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0); + return 0; + } + if (wParam == VK_NEXT && shift_state == 2) { + SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0); + return 0; + } + if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) { + term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1)); + return 0; + } + if (wParam == VK_INSERT && shift_state == 2) { switch (conf_get_int(conf, CONF_ctrlshiftins)) { case CLIPUI_IMPLICIT: break; /* no need to re-copy to CLIP_LOCAL */ @@ -4360,9 +4360,9 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, default: break; } - return 0; - } - if (wParam == VK_INSERT && shift_state == 1) { + return 0; + } + if (wParam == VK_INSERT && shift_state == 1) { switch (conf_get_int(conf, CONF_ctrlshiftins)) { case CLIPUI_IMPLICIT: term_request_paste(term, CLIP_LOCAL); @@ -4373,9 +4373,9 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, default: break; } - return 0; - } - if (wParam == 'C' && shift_state == 3) { + return 0; + } + if (wParam == 'C' && shift_state == 3) { switch (conf_get_int(conf, CONF_ctrlshiftcv)) { case CLIPUI_IMPLICIT: break; /* no need to re-copy to CLIP_LOCAL */ @@ -4385,9 +4385,9 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, default: break; } - return 0; - } - if (wParam == 'V' && shift_state == 3) { + return 0; + } + if (wParam == 'V' && shift_state == 3) { switch (conf_get_int(conf, CONF_ctrlshiftcv)) { case CLIPUI_IMPLICIT: term_request_paste(term, CLIP_LOCAL); @@ -4398,83 +4398,83 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, default: break; } - return 0; - } - if (left_alt && wParam == VK_F4 && conf_get_bool(conf, CONF_alt_f4)) { - return -1; - } - if (left_alt && wParam == VK_SPACE && conf_get_bool(conf, + return 0; + } + if (left_alt && wParam == VK_F4 && conf_get_bool(conf, CONF_alt_f4)) { + return -1; + } + if (left_alt && wParam == VK_SPACE && conf_get_bool(conf, CONF_alt_space)) { - SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0); - return -1; - } - if (left_alt && wParam == VK_RETURN && - conf_get_bool(conf, CONF_fullscreenonaltenter) && - (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) { - if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT) - flip_full_screen(); - return -1; - } - /* Control-Numlock for app-keypad mode switch */ - if (wParam == VK_PAUSE && shift_state == 2) { - term->app_keypad_keys = !term->app_keypad_keys; - return 0; - } + SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0); + return -1; + } + if (left_alt && wParam == VK_RETURN && + conf_get_bool(conf, CONF_fullscreenonaltenter) && + (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) { + if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT) + flip_full_screen(); + return -1; + } + /* Control-Numlock for app-keypad mode switch */ + if (wParam == VK_PAUSE && shift_state == 2) { + term->app_keypad_keys = !term->app_keypad_keys; + return 0; + } - if (wParam == VK_BACK && shift_state == 0) { /* Backspace */ - *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x7F : 0x08); - *p++ = 0; - return -2; - } - if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */ - /* We do the opposite of what is configured */ - *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F); - *p++ = 0; - return -2; - } - 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 == 3) { /* Ctrl-Shift-Space */ - *p++ = 160; - return p - output; - } - if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */ + if (wParam == VK_BACK && shift_state == 0) { /* Backspace */ + *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x7F : 0x08); + *p++ = 0; + return -2; + } + if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */ + /* We do the opposite of what is configured */ + *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F); + *p++ = 0; + return -2; + } + 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 == 3) { /* Ctrl-Shift-Space */ + *p++ = 160; + return p - output; + } + if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */ if (backend) backend_special(backend, SS_BRK, 0); - return 0; - } - 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']; - return p - output; - } - if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) { - *p++ = 0x1F; - return p - output; - } - if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) { - *p++ = 0x1C; - return p - output; - } - if (shift_state == 3 && wParam == 0xDE) { - *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */ - return p - output; - } + return 0; + } + 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']; + return p - output; + } + if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) { + *p++ = 0x1F; + return p - output; + } + if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) { + *p++ = 0x1C; + return p - output; + } + if (shift_state == 3 && wParam == 0xDE) { + *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */ + return p - output; + } - switch (wParam) { + switch (wParam) { case VK_NUMPAD0: keypad_key = '0'; goto numeric_keypad; case VK_NUMPAD1: keypad_key = '1'; goto numeric_keypad; case VK_NUMPAD2: keypad_key = '2'; goto numeric_keypad; @@ -4535,38 +4535,38 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, } int fkey_number; - case VK_F1: fkey_number = 1; goto numbered_function_key; - case VK_F2: fkey_number = 2; goto numbered_function_key; - case VK_F3: fkey_number = 3; goto numbered_function_key; - case VK_F4: fkey_number = 4; goto numbered_function_key; - case VK_F5: fkey_number = 5; goto numbered_function_key; - case VK_F6: fkey_number = 6; goto numbered_function_key; - case VK_F7: fkey_number = 7; goto numbered_function_key; - case VK_F8: fkey_number = 8; goto numbered_function_key; - case VK_F9: fkey_number = 9; goto numbered_function_key; - case VK_F10: fkey_number = 10; goto numbered_function_key; - case VK_F11: fkey_number = 11; goto numbered_function_key; - case VK_F12: fkey_number = 12; goto numbered_function_key; - case VK_F13: fkey_number = 13; goto numbered_function_key; - case VK_F14: fkey_number = 14; goto numbered_function_key; - case VK_F15: fkey_number = 15; goto numbered_function_key; - case VK_F16: fkey_number = 16; goto numbered_function_key; - case VK_F17: fkey_number = 17; goto numbered_function_key; - case VK_F18: fkey_number = 18; goto numbered_function_key; - case VK_F19: fkey_number = 19; goto numbered_function_key; - case VK_F20: fkey_number = 20; goto numbered_function_key; + case VK_F1: fkey_number = 1; goto numbered_function_key; + case VK_F2: fkey_number = 2; goto numbered_function_key; + case VK_F3: fkey_number = 3; goto numbered_function_key; + case VK_F4: fkey_number = 4; goto numbered_function_key; + case VK_F5: fkey_number = 5; goto numbered_function_key; + case VK_F6: fkey_number = 6; goto numbered_function_key; + case VK_F7: fkey_number = 7; goto numbered_function_key; + case VK_F8: fkey_number = 8; goto numbered_function_key; + case VK_F9: fkey_number = 9; goto numbered_function_key; + case VK_F10: fkey_number = 10; goto numbered_function_key; + case VK_F11: fkey_number = 11; goto numbered_function_key; + case VK_F12: fkey_number = 12; goto numbered_function_key; + case VK_F13: fkey_number = 13; goto numbered_function_key; + case VK_F14: fkey_number = 14; goto numbered_function_key; + case VK_F15: fkey_number = 15; goto numbered_function_key; + case VK_F16: fkey_number = 16; goto numbered_function_key; + case VK_F17: fkey_number = 17; goto numbered_function_key; + case VK_F18: fkey_number = 18; goto numbered_function_key; + case VK_F19: fkey_number = 19; goto numbered_function_key; + case VK_F20: fkey_number = 20; goto numbered_function_key; numbered_function_key: p += format_function_key((char *)p, term, fkey_number, shift_state & 1, shift_state & 2); return p - output; SmallKeypadKey sk_key; - case VK_HOME: sk_key = SKK_HOME; goto small_keypad_key; - case VK_END: sk_key = SKK_END; goto small_keypad_key; - case VK_INSERT: sk_key = SKK_INSERT; goto small_keypad_key; - case VK_DELETE: sk_key = SKK_DELETE; goto small_keypad_key; - case VK_PRIOR: sk_key = SKK_PGUP; goto small_keypad_key; - case VK_NEXT: sk_key = SKK_PGDN; goto small_keypad_key; + case VK_HOME: sk_key = SKK_HOME; goto small_keypad_key; + case VK_END: sk_key = SKK_END; goto small_keypad_key; + case VK_INSERT: sk_key = SKK_INSERT; goto small_keypad_key; + case VK_DELETE: sk_key = SKK_DELETE; goto small_keypad_key; + case VK_PRIOR: sk_key = SKK_PGUP; goto small_keypad_key; + case VK_NEXT: sk_key = SKK_PGDN; goto small_keypad_key; small_keypad_key: /* These keys don't generate terminal input with Ctrl */ if (shift_state & 2) @@ -4575,7 +4575,7 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, p += format_small_keypad_key((char *)p, term, sk_key); return p - output; - char xkey; + char xkey; case VK_UP: xkey = 'A'; goto arrow_key; case VK_DOWN: xkey = 'B'; goto arrow_key; case VK_RIGHT: xkey = 'C'; goto arrow_key; @@ -4600,145 +4600,145 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, *p++ = 0; return -2; } - } + } } - /* Okay we've done everything interesting; let windows deal with + /* Okay we've done everything interesting; let windows deal with * the boring stuff */ { - bool capsOn = false; + bool capsOn = false; - /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */ - if(keystate[VK_CAPITAL] != 0 && - conf_get_bool(conf, CONF_xlat_capslockcyr)) { - capsOn= !left_alt; - keystate[VK_CAPITAL] = 0; - } + /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */ + if(keystate[VK_CAPITAL] != 0 && + conf_get_bool(conf, CONF_xlat_capslockcyr)) { + capsOn= !left_alt; + keystate[VK_CAPITAL] = 0; + } - /* XXX how do we know what the max size of the keys array should - * be is? There's indication on MS' website of an Inquire/InquireEx - * functioning returning a KBINFO structure which tells us. */ - if (osPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) { - r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode, + /* XXX how do we know what the max size of the keys array should + * be is? There's indication on MS' website of an Inquire/InquireEx + * functioning returning a KBINFO structure which tells us. */ + if (osPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) { + r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode, lenof(keys_unicode), 0, kbd_layout); - } else { - /* XXX 'keys' parameter is declared in MSDN documentation as - * 'LPWORD lpChar'. - * The experience of a French user indicates that on - * Win98, WORD[] should be passed in, but on Win2K, it should - * be BYTE[]. German WinXP and my Win2K with "US International" - * driver corroborate this. - * Experimentally I've conditionalised the behaviour on the - * Win9x/NT split, but I suspect it's worse than that. - * See wishlist item `win-dead-keys' for more horrible detail - * and speculations. */ - int i; - static WORD keys[3]; - static BYTE keysb[3]; - r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout); - if (r > 0) { - for (i = 0; i < r; i++) { - keysb[i] = (BYTE)keys[i]; - } - MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r, + } else { + /* XXX 'keys' parameter is declared in MSDN documentation as + * 'LPWORD lpChar'. + * The experience of a French user indicates that on + * Win98, WORD[] should be passed in, but on Win2K, it should + * be BYTE[]. German WinXP and my Win2K with "US International" + * driver corroborate this. + * Experimentally I've conditionalised the behaviour on the + * Win9x/NT split, but I suspect it's worse than that. + * See wishlist item `win-dead-keys' for more horrible detail + * and speculations. */ + int i; + static WORD keys[3]; + static BYTE keysb[3]; + r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout); + if (r > 0) { + for (i = 0; i < r; i++) { + keysb[i] = (BYTE)keys[i]; + } + MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r, keys_unicode, lenof(keys_unicode)); - } - } + } + } #ifdef SHOW_TOASCII_RESULT - if (r == 1 && !key_down) { - if (alt_sum) { - if (in_utf(term) || ucsdata.dbcs_screenfont) - debug(", (U+%04x)", alt_sum); - else - debug(", LCH(%d)", alt_sum); - } else { - debug(", ACH(%d)", keys_unicode[0]); - } - } else if (r > 0) { - int r1; - debug(", ASC("); - for (r1 = 0; r1 < r; r1++) { - debug("%s%d", r1 ? "," : "", keys_unicode[r1]); - } - debug(")"); - } + if (r == 1 && !key_down) { + if (alt_sum) { + if (in_utf(term) || ucsdata.dbcs_screenfont) + debug(", (U+%04x)", alt_sum); + else + debug(", LCH(%d)", alt_sum); + } else { + debug(", ACH(%d)", keys_unicode[0]); + } + } else if (r > 0) { + int r1; + debug(", ASC("); + for (r1 = 0; r1 < r; r1++) { + debug("%s%d", r1 ? "," : "", keys_unicode[r1]); + } + debug(")"); + } #endif - if (r > 0) { - WCHAR keybuf; + if (r > 0) { + WCHAR keybuf; - p = output; - for (i = 0; i < r; i++) { - wchar_t wch = keys_unicode[i]; + p = output; + for (i = 0; i < r; i++) { + wchar_t wch = keys_unicode[i]; - if (compose_state == 2 && wch >= ' ' && wch < 0x80) { - compose_char = wch; - compose_state++; - continue; - } - if (compose_state == 3 && wch >= ' ' && wch < 0x80) { - int nc; - compose_state = 0; + if (compose_state == 2 && wch >= ' ' && wch < 0x80) { + compose_char = wch; + compose_state++; + continue; + } + if (compose_state == 3 && wch >= ' ' && wch < 0x80) { + int nc; + compose_state = 0; - if ((nc = check_compose(compose_char, wch)) == -1) { - MessageBeep(MB_ICONHAND); - return 0; - } - keybuf = nc; + if ((nc = check_compose(compose_char, wch)) == -1) { + MessageBeep(MB_ICONHAND); + return 0; + } + keybuf = nc; term_keyinputw(term, &keybuf, 1); - continue; - } + continue; + } - compose_state = 0; + compose_state = 0; - if (!key_down) { - if (alt_sum) { - if (in_utf(term) || ucsdata.dbcs_screenfont) { - keybuf = alt_sum; + if (!key_down) { + if (alt_sum) { + if (in_utf(term) || ucsdata.dbcs_screenfont) { + keybuf = alt_sum; term_keyinputw(term, &keybuf, 1); - } else { - char ch = (char) alt_sum; - /* - * We need not bother about stdin - * backlogs here, because in GUI PuTTY - * we can't do anything about it - * anyway; there's no means of asking - * Windows to hold off on KEYDOWN - * messages. We _have_ to buffer - * everything we're sent. - */ - term_keyinput(term, -1, &ch, 1); - } - alt_sum = 0; - } else { - term_keyinputw(term, &wch, 1); - } - } else { - if(capsOn && wch < 0x80) { - WCHAR cbuf[2]; - cbuf[0] = 27; - cbuf[1] = xlat_uskbd2cyrllic(wch); - term_keyinputw(term, cbuf+!left_alt, 1+!!left_alt); - } else { - WCHAR cbuf[2]; - cbuf[0] = '\033'; - cbuf[1] = wch; - term_keyinputw(term, cbuf +!left_alt, 1+!!left_alt); - } - } - show_mouseptr(false); - } + } else { + char ch = (char) alt_sum; + /* + * We need not bother about stdin + * backlogs here, because in GUI PuTTY + * we can't do anything about it + * anyway; there's no means of asking + * Windows to hold off on KEYDOWN + * messages. We _have_ to buffer + * everything we're sent. + */ + term_keyinput(term, -1, &ch, 1); + } + alt_sum = 0; + } else { + term_keyinputw(term, &wch, 1); + } + } else { + if(capsOn && wch < 0x80) { + WCHAR cbuf[2]; + cbuf[0] = 27; + cbuf[1] = xlat_uskbd2cyrllic(wch); + term_keyinputw(term, cbuf+!left_alt, 1+!!left_alt); + } else { + WCHAR cbuf[2]; + cbuf[0] = '\033'; + cbuf[1] = wch; + term_keyinputw(term, cbuf +!left_alt, 1+!!left_alt); + } + } + show_mouseptr(false); + } - /* This is so the ALT-Numpad and dead keys work correctly. */ - keys_unicode[0] = 0; + /* This is so the ALT-Numpad and dead keys work correctly. */ + keys_unicode[0] = 0; - return p - output; - } - /* If we're definitely not building up an ALT-54321 then clear it */ - if (!left_alt) - keys_unicode[0] = 0; - /* If we will be using alt_sum fix the 256s */ - else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont)) - keys_unicode[0] = 10; + return p - output; + } + /* If we're definitely not building up an ALT-54321 then clear it */ + if (!left_alt) + keys_unicode[0] = 0; + /* If we will be using alt_sum fix the 256s */ + else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont)) + keys_unicode[0] = 10; } /* @@ -4749,7 +4749,7 @@ static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam, * its default handling (i.e. bring up the System menu). */ if (wParam == VK_MENU && !conf_get_bool(conf, CONF_alt_only)) - return 0; + return 0; return -1; } @@ -4760,7 +4760,7 @@ static void wintw_set_title(TermWin *tw, const char *title) window_name = snewn(1 + strlen(title), char); strcpy(window_name, title); if (conf_get_bool(conf, CONF_win_name_always) || !IsIconic(hwnd)) - SetWindowText(hwnd, title); + SetWindowText(hwnd, title); } static void wintw_set_icon_title(TermWin *tw, const char *title) @@ -4769,7 +4769,7 @@ static void wintw_set_icon_title(TermWin *tw, const char *title) icon_name = snewn(1 + strlen(title), char); strcpy(icon_name, title); if (!conf_get_bool(conf, CONF_win_name_always) && IsIconic(hwnd)) - SetWindowText(hwnd, title); + SetWindowText(hwnd, title); } static void wintw_set_scrollbar(TermWin *tw, int total, int start, int page) @@ -4778,7 +4778,7 @@ static void wintw_set_scrollbar(TermWin *tw, int total, int start, int page) if (!conf_get_bool(conf, is_full_screen() ? CONF_scrollbar_in_fullscreen : CONF_scrollbar)) - return; + return; si.cbSize = sizeof(si); si.fMask = SIF_ALL | SIF_DISABLENOSCROLL; @@ -4787,7 +4787,7 @@ static void wintw_set_scrollbar(TermWin *tw, 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); } static bool wintw_setup_draw_ctx(TermWin *tw) @@ -4808,18 +4808,18 @@ static void real_palette_set(int n, int r, int g, int b) { internal_set_colour(n, r, g, b); if (pal) { - logpal->palPalEntry[n].peRed = r; - logpal->palPalEntry[n].peGreen = g; - logpal->palPalEntry[n].peBlue = b; - logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE; - SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry); + logpal->palPalEntry[n].peRed = r; + logpal->palPalEntry[n].peGreen = g; + logpal->palPalEntry[n].peBlue = b; + logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE; + SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry); } } static bool wintw_palette_get(TermWin *tw, int n, int *r, int *g, int *b) { if (n < 0 || n >= NALLCOLOURS) - return false; + return false; *r = colours_rgb[n].r; *g = colours_rgb[n].g; *b = colours_rgb[n].b; @@ -4829,21 +4829,21 @@ static bool wintw_palette_get(TermWin *tw, int n, int *r, int *g, int *b) static void wintw_palette_set(TermWin *tw, int n, int r, int g, int b) { if (n >= 16) - n += 256 - 16; + n += 256 - 16; if (n >= NALLCOLOURS) - return; + return; real_palette_set(n, r, g, b); if (pal) { - HDC hdc = make_hdc(); - UnrealizeObject(pal); - RealizePalette(hdc); - free_hdc(hdc); + HDC hdc = make_hdc(); + UnrealizeObject(pal); + RealizePalette(hdc); + free_hdc(hdc); } else { - if (n == (ATTR_DEFBG>>ATTR_BGSHIFT)) - /* If Default Background changes, we need to ensure any - * space between the text area and the window border is - * redrawn. */ - InvalidateRect(hwnd, NULL, true); + if (n == (ATTR_DEFBG>>ATTR_BGSHIFT)) + /* If Default Background changes, we need to ensure any + * space between the text area and the window border is + * redrawn. */ + InvalidateRect(hwnd, NULL, true); } } @@ -4855,24 +4855,24 @@ static void wintw_palette_reset(TermWin *tw) for (i = 0; i < NALLCOLOURS; i++) { internal_set_colour(i, defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue); - if (pal) { - logpal->palPalEntry[i].peRed = defpal[i].rgbtRed; - logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen; - logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue; - logpal->palPalEntry[i].peFlags = 0; - } + if (pal) { + logpal->palPalEntry[i].peRed = defpal[i].rgbtRed; + logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen; + logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue; + logpal->palPalEntry[i].peFlags = 0; + } } if (pal) { - HDC hdc; - SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry); - hdc = make_hdc(); - RealizePalette(hdc); - free_hdc(hdc); + HDC hdc; + SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry); + hdc = make_hdc(); + RealizePalette(hdc); + free_hdc(hdc); } else { - /* Default Background may have changed. Ensure any space between - * text area and window border is redrawn. */ - InvalidateRect(hwnd, NULL, true); + /* Default Background may have changed. Ensure any space between + * text area and window border is redrawn. */ + InvalidateRect(hwnd, NULL, true); } } @@ -4886,26 +4886,26 @@ void write_aclip(int clipboard, char *data, int len, bool must_deselect) clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1); if (!clipdata) - return; + return; lock = GlobalLock(clipdata); if (!lock) - return; + return; 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)) { - EmptyClipboard(); - SetClipboardData(CF_TEXT, clipdata); - CloseClipboard(); + EmptyClipboard(); + 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); } typedef struct _rgbindex { @@ -4937,179 +4937,179 @@ static void wintw_clip_write( len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL); clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, - len * sizeof(wchar_t)); + len * sizeof(wchar_t)); clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2); if (!clipdata || !clipdata2) { - if (clipdata) - GlobalFree(clipdata); - if (clipdata2) - GlobalFree(clipdata2); - return; + if (clipdata) + GlobalFree(clipdata); + if (clipdata2) + GlobalFree(clipdata2); + return; } if (!(lock = GlobalLock(clipdata))) { GlobalFree(clipdata); GlobalFree(clipdata2); - return; + return; } if (!(lock2 = GlobalLock(clipdata2))) { GlobalUnlock(clipdata); GlobalFree(clipdata); GlobalFree(clipdata2); - return; + return; } memcpy(lock, data, len * sizeof(wchar_t)); WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL); if (conf_get_bool(conf, CONF_rtf_paste)) { - wchar_t unitab[256]; - strbuf *rtf = strbuf_new(); - unsigned char *tdata = (unsigned char *)lock2; - wchar_t *udata = (wchar_t *)lock; - int uindex = 0, tindex = 0; - int multilen, blen, alen, totallen, i; - char before[16], after[4]; - int fgcolour, lastfgcolour = -1; - int bgcolour, lastbgcolour = -1; - COLORREF fg, lastfg = -1; - COLORREF bg, lastbg = -1; - int attrBold, lastAttrBold = 0; - int attrUnder, lastAttrUnder = 0; - int palette[NALLCOLOURS]; - int numcolours; - tree234 *rgbtree = NULL; - FontSpec *font = conf_get_fontspec(conf, CONF_font); + wchar_t unitab[256]; + strbuf *rtf = strbuf_new(); + unsigned char *tdata = (unsigned char *)lock2; + wchar_t *udata = (wchar_t *)lock; + int uindex = 0, tindex = 0; + int multilen, blen, alen, totallen, i; + char before[16], after[4]; + int fgcolour, lastfgcolour = -1; + int bgcolour, lastbgcolour = -1; + COLORREF fg, lastfg = -1; + COLORREF bg, lastbg = -1; + int attrBold, lastAttrBold = 0; + int attrUnder, lastAttrUnder = 0; + int palette[NALLCOLOURS]; + int numcolours; + tree234 *rgbtree = NULL; + FontSpec *font = conf_get_fontspec(conf, CONF_font); - get_unitab(CP_ACP, unitab, 0); + get_unitab(CP_ACP, unitab, 0); - strbuf_catf( + strbuf_catf( rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d", font->name, font->height*2); - /* - * Add colour palette - * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;} - */ + /* + * Add colour palette + * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;} + */ - /* - * First - Determine all colours in use - * o Foregound and background colours share the same palette - */ - if (attr) { - memset(palette, 0, sizeof(palette)); - for (i = 0; i < (len-1); i++) { - fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT); - bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT); + /* + * First - Determine all colours in use + * o Foregound and background colours share the same palette + */ + if (attr) { + memset(palette, 0, sizeof(palette)); + for (i = 0; i < (len-1); i++) { + fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT); + bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT); - if (attr[i] & ATTR_REVERSE) { - int tmpcolour = fgcolour; /* Swap foreground and background */ - fgcolour = bgcolour; - bgcolour = tmpcolour; - } + if (attr[i] & ATTR_REVERSE) { + int tmpcolour = fgcolour; /* Swap foreground and background */ + fgcolour = bgcolour; + bgcolour = tmpcolour; + } - if (bold_colours && (attr[i] & ATTR_BOLD)) { - if (fgcolour < 8) /* ANSI colours */ - fgcolour += 8; - else if (fgcolour >= 256) /* Default colours */ - fgcolour ++; - } + if (bold_colours && (attr[i] & ATTR_BOLD)) { + if (fgcolour < 8) /* ANSI colours */ + fgcolour += 8; + else if (fgcolour >= 256) /* Default colours */ + fgcolour ++; + } - if ((attr[i] & ATTR_BLINK)) { - if (bgcolour < 8) /* ANSI colours */ - bgcolour += 8; - else if (bgcolour >= 256) /* Default colours */ - bgcolour ++; - } + if ((attr[i] & ATTR_BLINK)) { + if (bgcolour < 8) /* ANSI colours */ + bgcolour += 8; + else if (bgcolour >= 256) /* Default colours */ + bgcolour ++; + } - palette[fgcolour]++; - palette[bgcolour]++; - } + palette[fgcolour]++; + palette[bgcolour]++; + } - if (truecolour) { - rgbtree = newtree234(cmpCOLORREF); - for (i = 0; i < (len-1); i++) { - if (truecolour[i].fg.enabled) { - rgbindex *rgbp = snew(rgbindex); - rgbp->ref = RGB(truecolour[i].fg.r, - truecolour[i].fg.g, - truecolour[i].fg.b); - if (add234(rgbtree, rgbp) != rgbp) - sfree(rgbp); - } - if (truecolour[i].bg.enabled) { - rgbindex *rgbp = snew(rgbindex); - rgbp->ref = RGB(truecolour[i].bg.r, - truecolour[i].bg.g, - truecolour[i].bg.b); - if (add234(rgbtree, rgbp) != rgbp) - sfree(rgbp); - } - } - } + if (truecolour) { + rgbtree = newtree234(cmpCOLORREF); + for (i = 0; i < (len-1); i++) { + if (truecolour[i].fg.enabled) { + rgbindex *rgbp = snew(rgbindex); + rgbp->ref = RGB(truecolour[i].fg.r, + truecolour[i].fg.g, + truecolour[i].fg.b); + if (add234(rgbtree, rgbp) != rgbp) + sfree(rgbp); + } + if (truecolour[i].bg.enabled) { + rgbindex *rgbp = snew(rgbindex); + rgbp->ref = RGB(truecolour[i].bg.r, + truecolour[i].bg.g, + truecolour[i].bg.b); + if (add234(rgbtree, rgbp) != rgbp) + sfree(rgbp); + } + } + } - /* - * Next - Create a reduced palette - */ - numcolours = 0; - for (i = 0; i < NALLCOLOURS; i++) { - if (palette[i] != 0) - palette[i] = ++numcolours; - } + /* + * Next - Create a reduced palette + */ + numcolours = 0; + for (i = 0; i < NALLCOLOURS; i++) { + if (palette[i] != 0) + palette[i] = ++numcolours; + } - if (rgbtree) { - rgbindex *rgbp; - for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++) - rgbp->index = ++numcolours; - } + if (rgbtree) { + rgbindex *rgbp; + for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++) + rgbp->index = ++numcolours; + } - /* - * Finally - Write the colour table - */ - put_datapl(rtf, PTRLEN_LITERAL("{\\colortbl ;")); + /* + * Finally - Write the colour table + */ + put_datapl(rtf, PTRLEN_LITERAL("{\\colortbl ;")); - for (i = 0; i < NALLCOLOURS; i++) { - if (palette[i] != 0) { + for (i = 0; i < NALLCOLOURS; i++) { + if (palette[i] != 0) { strbuf_catf(rtf, "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue); - } - } - if (rgbtree) { - rgbindex *rgbp; - for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++) + } + } + if (rgbtree) { + rgbindex *rgbp; + for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++) strbuf_catf(rtf, "\\red%d\\green%d\\blue%d;", GetRValue(rgbp->ref), GetGValue(rgbp->ref), GetBValue(rgbp->ref)); - } - put_datapl(rtf, PTRLEN_LITERAL("}")); - } + } + put_datapl(rtf, PTRLEN_LITERAL("}")); + } - /* - * We want to construct a piece of RTF that specifies the - * same Unicode text. To do this we will read back in - * parallel from the Unicode data in `udata' and the - * non-Unicode data in `tdata'. For each character in - * `tdata' which becomes the right thing in `udata' when - * looked up in `unitab', we just copy straight over from - * tdata. For each one that doesn't, we must WCToMB it - * individually and produce a \u escape sequence. - * - * It would probably be more robust to just bite the bullet - * and WCToMB each individual Unicode character one by one, - * then MBToWC each one back to see if it was an accurate - * translation; but that strikes me as a horrifying number - * of Windows API calls so I want to see if this faster way - * will work. If it screws up badly we can always revert to - * the simple and slow way. - */ - while (tindex < len2 && uindex < len && - tdata[tindex] && udata[uindex]) { - if (tindex + 1 < len2 && - tdata[tindex] == '\r' && - tdata[tindex+1] == '\n') { - tindex++; - uindex++; + /* + * We want to construct a piece of RTF that specifies the + * same Unicode text. To do this we will read back in + * parallel from the Unicode data in `udata' and the + * non-Unicode data in `tdata'. For each character in + * `tdata' which becomes the right thing in `udata' when + * looked up in `unitab', we just copy straight over from + * tdata. For each one that doesn't, we must WCToMB it + * individually and produce a \u escape sequence. + * + * It would probably be more robust to just bite the bullet + * and WCToMB each individual Unicode character one by one, + * then MBToWC each one back to see if it was an accurate + * translation; but that strikes me as a horrifying number + * of Windows API calls so I want to see if this faster way + * will work. If it screws up badly we can always revert to + * the simple and slow way. + */ + while (tindex < len2 && uindex < len && + tdata[tindex] && udata[uindex]) { + if (tindex + 1 < len2 && + tdata[tindex] == '\r' && + tdata[tindex+1] == '\n') { + tindex++; + uindex++; } /* @@ -5119,216 +5119,216 @@ static void wintw_clip_write( /* * Determine foreground and background colours */ - if (truecolour && truecolour[tindex].fg.enabled) { - fgcolour = -1; - fg = RGB(truecolour[tindex].fg.r, - truecolour[tindex].fg.g, - truecolour[tindex].fg.b); - } else { - fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT); - fg = -1; - } - - if (truecolour && truecolour[tindex].bg.enabled) { - bgcolour = -1; - bg = RGB(truecolour[tindex].bg.r, - truecolour[tindex].bg.g, - truecolour[tindex].bg.b); - } else { - bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT); - bg = -1; - } - - if (attr[tindex] & ATTR_REVERSE) { - int tmpcolour = fgcolour; /* Swap foreground and background */ - fgcolour = bgcolour; - bgcolour = tmpcolour; - - COLORREF tmpref = fg; - fg = bg; - bg = tmpref; - } - - if (bold_colours && (attr[tindex] & ATTR_BOLD) && (fgcolour >= 0)) { - if (fgcolour < 8) /* ANSI colours */ - fgcolour += 8; - else if (fgcolour >= 256) /* Default colours */ - fgcolour ++; + if (truecolour && truecolour[tindex].fg.enabled) { + fgcolour = -1; + fg = RGB(truecolour[tindex].fg.r, + truecolour[tindex].fg.g, + truecolour[tindex].fg.b); + } else { + fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT); + fg = -1; } - if ((attr[tindex] & ATTR_BLINK) && (bgcolour >= 0)) { - if (bgcolour < 8) /* ANSI colours */ - bgcolour += 8; - else if (bgcolour >= 256) /* Default colours */ - bgcolour ++; + if (truecolour && truecolour[tindex].bg.enabled) { + bgcolour = -1; + bg = RGB(truecolour[tindex].bg.r, + truecolour[tindex].bg.g, + truecolour[tindex].bg.b); + } else { + bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT); + bg = -1; + } + + if (attr[tindex] & ATTR_REVERSE) { + int tmpcolour = fgcolour; /* Swap foreground and background */ + fgcolour = bgcolour; + bgcolour = tmpcolour; + + COLORREF tmpref = fg; + fg = bg; + bg = tmpref; + } + + if (bold_colours && (attr[tindex] & ATTR_BOLD) && (fgcolour >= 0)) { + if (fgcolour < 8) /* ANSI colours */ + fgcolour += 8; + else if (fgcolour >= 256) /* Default colours */ + fgcolour ++; + } + + if ((attr[tindex] & ATTR_BLINK) && (bgcolour >= 0)) { + if (bgcolour < 8) /* ANSI colours */ + bgcolour += 8; + else if (bgcolour >= 256) /* Default colours */ + bgcolour ++; } /* * Collect other attributes */ - if (bold_font_mode != BOLD_NONE) - attrBold = attr[tindex] & ATTR_BOLD; - else - attrBold = 0; - - attrUnder = attr[tindex] & ATTR_UNDER; + if (bold_font_mode != BOLD_NONE) + attrBold = attr[tindex] & ATTR_BOLD; + else + attrBold = 0; + + attrUnder = attr[tindex] & ATTR_UNDER; /* * Reverse video - * o If video isn't reversed, ignore colour attributes for default foregound - * or background. - * o Special case where bolded text is displayed using the default foregound - * and background colours - force to bolded RTF. + * o If video isn't reversed, ignore colour attributes for default foregound + * or background. + * o Special case where bolded text is displayed using the default foregound + * and background colours - force to bolded RTF. */ - if (!(attr[tindex] & ATTR_REVERSE)) { - if (bgcolour >= 256) /* Default color */ - bgcolour = -1; /* No coloring */ + if (!(attr[tindex] & ATTR_REVERSE)) { + if (bgcolour >= 256) /* Default color */ + bgcolour = -1; /* No coloring */ - if (fgcolour >= 256) { /* Default colour */ - if (bold_colours && (fgcolour & 1) && bgcolour == -1) - attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */ + if (fgcolour >= 256) { /* Default colour */ + if (bold_colours && (fgcolour & 1) && bgcolour == -1) + attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */ - fgcolour = -1; /* No coloring */ - } - } + fgcolour = -1; /* No coloring */ + } + } /* * Write RTF text attributes */ - if ((lastfgcolour != fgcolour) || (lastfg != fg)) { - lastfgcolour = fgcolour; - lastfg = fg; + if ((lastfgcolour != fgcolour) || (lastfg != fg)) { + lastfgcolour = fgcolour; + lastfg = fg; if (fg == -1) { strbuf_catf(rtf, "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0); } else { - rgbindex rgb, *rgbp; - rgb.ref = fg; - if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL) - strbuf_catf(rtf, "\\cf%d ", rgbp->index); - } - } + rgbindex rgb, *rgbp; + rgb.ref = fg; + if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL) + strbuf_catf(rtf, "\\cf%d ", rgbp->index); + } + } - if ((lastbgcolour != bgcolour) || (lastbg != bg)) { - lastbgcolour = bgcolour; - lastbg = bg; - if (bg == -1) - strbuf_catf(rtf, "\\highlight%d ", + if ((lastbgcolour != bgcolour) || (lastbg != bg)) { + lastbgcolour = bgcolour; + lastbg = bg; + if (bg == -1) + strbuf_catf(rtf, "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0); - else { - rgbindex rgb, *rgbp; - rgb.ref = bg; - if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL) - strbuf_catf(rtf, "\\highlight%d ", rgbp->index); - } - } + else { + rgbindex rgb, *rgbp; + rgb.ref = bg; + if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL) + strbuf_catf(rtf, "\\highlight%d ", rgbp->index); + } + } - if (lastAttrBold != attrBold) { - lastAttrBold = attrBold; - put_datapl(rtf, attrBold ? + if (lastAttrBold != attrBold) { + lastAttrBold = attrBold; + put_datapl(rtf, attrBold ? PTRLEN_LITERAL("\\b ") : PTRLEN_LITERAL("\\b0 ")); - } + } if (lastAttrUnder != attrUnder) { lastAttrUnder = attrUnder; - put_datapl(rtf, attrUnder ? + put_datapl(rtf, attrUnder ? PTRLEN_LITERAL("\\ul ") : PTRLEN_LITERAL("\\ulnone ")); } - } + } - if (unitab[tdata[tindex]] == udata[uindex]) { - multilen = 1; - before[0] = '\0'; - after[0] = '\0'; - blen = alen = 0; - } else { - multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1, - NULL, 0, NULL, NULL); - if (multilen != 1) { - blen = sprintf(before, "{\\uc%d\\u%d", (int)multilen, - (int)udata[uindex]); - alen = 1; strcpy(after, "}"); - } else { - blen = sprintf(before, "\\u%d", udata[uindex]); - alen = 0; after[0] = '\0'; - } - } - assert(tindex + multilen <= len2); - totallen = blen + alen; - for (i = 0; i < multilen; i++) { - if (tdata[tindex+i] == '\\' || - tdata[tindex+i] == '{' || - tdata[tindex+i] == '}') - totallen += 2; - else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) - totallen += 6; /* \par\r\n */ - else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) - totallen += 4; - else - totallen++; - } + if (unitab[tdata[tindex]] == udata[uindex]) { + multilen = 1; + before[0] = '\0'; + after[0] = '\0'; + blen = alen = 0; + } else { + multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1, + NULL, 0, NULL, NULL); + if (multilen != 1) { + blen = sprintf(before, "{\\uc%d\\u%d", (int)multilen, + (int)udata[uindex]); + alen = 1; strcpy(after, "}"); + } else { + blen = sprintf(before, "\\u%d", udata[uindex]); + alen = 0; after[0] = '\0'; + } + } + assert(tindex + multilen <= len2); + totallen = blen + alen; + for (i = 0; i < multilen; i++) { + if (tdata[tindex+i] == '\\' || + tdata[tindex+i] == '{' || + tdata[tindex+i] == '}') + totallen += 2; + else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) + totallen += 6; /* \par\r\n */ + else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) + totallen += 4; + else + totallen++; + } - put_data(rtf, before, blen); - for (i = 0; i < multilen; i++) { - if (tdata[tindex+i] == '\\' || - tdata[tindex+i] == '{' || - tdata[tindex+i] == '}') { + put_data(rtf, before, blen); + for (i = 0; i < multilen; i++) { + if (tdata[tindex+i] == '\\' || + tdata[tindex+i] == '{' || + tdata[tindex+i] == '}') { put_byte(rtf, '\\'); put_byte(rtf, tdata[tindex+i]); - } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) { + } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) { put_datapl(rtf, PTRLEN_LITERAL("\\par\r\n")); - } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) { + } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) { strbuf_catf(rtf, "\\'%02x", tdata[tindex+i]); - } else { + } else { put_byte(rtf, tdata[tindex+i]); - } - } - put_data(rtf, after, alen); + } + } + put_data(rtf, after, alen); - tindex += multilen; - uindex++; - } + tindex += multilen; + uindex++; + } put_datapl(rtf, PTRLEN_LITERAL("}\0\0")); /* Terminate RTF stream */ - clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtf->len); - if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) { - memcpy(lock3, rtf->u, rtf->len); - GlobalUnlock(clipdata3); - } - strbuf_free(rtf); + clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtf->len); + if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) { + memcpy(lock3, rtf->u, rtf->len); + GlobalUnlock(clipdata3); + } + strbuf_free(rtf); - if (rgbtree) { - rgbindex *rgbp; - while ((rgbp = delpos234(rgbtree, 0)) != NULL) - sfree(rgbp); - freetree234(rgbtree); - } + if (rgbtree) { + rgbindex *rgbp; + while ((rgbp = delpos234(rgbtree, 0)) != NULL) + sfree(rgbp); + freetree234(rgbtree); + } } else - clipdata3 = NULL; + clipdata3 = NULL; GlobalUnlock(clipdata); GlobalUnlock(clipdata2); if (!must_deselect) - SendMessage(hwnd, WM_IGNORE_CLIP, true, 0); + SendMessage(hwnd, WM_IGNORE_CLIP, true, 0); if (OpenClipboard(hwnd)) { - EmptyClipboard(); - SetClipboardData(CF_UNICODETEXT, clipdata); - SetClipboardData(CF_TEXT, clipdata2); - if (clipdata3) - SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3); - CloseClipboard(); + EmptyClipboard(); + SetClipboardData(CF_UNICODETEXT, clipdata); + SetClipboardData(CF_TEXT, clipdata2); + if (clipdata3) + SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3); + CloseClipboard(); } else { - GlobalFree(clipdata); - GlobalFree(clipdata2); + GlobalFree(clipdata); + GlobalFree(clipdata2); } if (!must_deselect) - SendMessage(hwnd, WM_IGNORE_CLIP, false, 0); + SendMessage(hwnd, WM_IGNORE_CLIP, false, 0); } static DWORD WINAPI clipboard_read_threadfunc(void *param) @@ -5337,14 +5337,14 @@ static DWORD WINAPI clipboard_read_threadfunc(void *param) HGLOBAL clipdata; if (OpenClipboard(NULL)) { - if ((clipdata = GetClipboardData(CF_UNICODETEXT))) { - SendMessage(hwnd, WM_GOT_CLIPDATA, + if ((clipdata = GetClipboardData(CF_UNICODETEXT))) { + SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)true, (LPARAM)clipdata); - } else if ((clipdata = GetClipboardData(CF_TEXT))) { - SendMessage(hwnd, WM_GOT_CLIPDATA, + } else if ((clipdata = GetClipboardData(CF_TEXT))) { + SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)false, (LPARAM)clipdata); - } - CloseClipboard(); + } + CloseClipboard(); } return 0; @@ -5356,31 +5356,31 @@ static void process_clipdata(HGLOBAL clipdata, bool unicode) size_t clipboard_length = 0; if (unicode) { - wchar_t *p = GlobalLock(clipdata); - wchar_t *p2; + wchar_t *p = GlobalLock(clipdata); + wchar_t *p2; - if (p) { - /* Unwilling to rely on Windows having wcslen() */ - for (p2 = p; *p2; p2++); - clipboard_length = p2 - p; - clipboard_contents = snewn(clipboard_length + 1, wchar_t); - memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t)); - clipboard_contents[clipboard_length] = L'\0'; - term_do_paste(term, clipboard_contents, clipboard_length); - } + if (p) { + /* Unwilling to rely on Windows having wcslen() */ + for (p2 = p; *p2; p2++); + clipboard_length = p2 - p; + clipboard_contents = snewn(clipboard_length + 1, wchar_t); + memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t)); + clipboard_contents[clipboard_length] = L'\0'; + term_do_paste(term, clipboard_contents, clipboard_length); + } } else { - char *s = GlobalLock(clipdata); - int i; + char *s = GlobalLock(clipdata); + int i; - if (s) { - i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0); - clipboard_contents = snewn(i, wchar_t); - MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, - clipboard_contents, i); - clipboard_length = i - 1; - clipboard_contents[clipboard_length] = L'\0'; - term_do_paste(term, clipboard_contents, clipboard_length); - } + if (s) { + i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0); + clipboard_contents = snewn(i, wchar_t); + MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, + clipboard_contents, i); + clipboard_length = i - 1; + clipboard_contents[clipboard_length] = L'\0'; + term_do_paste(term, clipboard_contents, clipboard_length); + } } sfree(clipboard_contents); @@ -5408,7 +5408,7 @@ static void wintw_clip_request_paste(TermWin *tw, int clipboard) */ DWORD in_threadid; /* required for Win9x */ CreateThread(NULL, 0, clipboard_read_threadfunc, - hwnd, 0, &in_threadid); + hwnd, 0, &in_threadid); } /* @@ -5449,16 +5449,16 @@ void nonfatal(const char *fmt, ...) static bool flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout) { if (p_FlashWindowEx) { - FLASHWINFO fi; - fi.cbSize = sizeof(fi); - fi.hwnd = hwnd; - fi.dwFlags = dwFlags; - fi.uCount = uCount; - fi.dwTimeout = dwTimeout; - return (*p_FlashWindowEx)(&fi); + FLASHWINFO fi; + fi.cbSize = sizeof(fi); + fi.hwnd = hwnd; + fi.dwFlags = dwFlags; + fi.uCount = uCount; + fi.dwTimeout = dwTimeout; + return (*p_FlashWindowEx)(&fi); } else - return false; /* shrug */ + return false; /* shrug */ } static void flash_window(int mode); @@ -5472,7 +5472,7 @@ static bool flashing = false; static void flash_window_timer(void *ctx, unsigned long now) { if (flashing && now == next_flash) { - flash_window(1); + flash_window(1); } } @@ -5484,42 +5484,42 @@ static void flash_window(int mode) { int beep_ind = conf_get_int(conf, CONF_beep_ind); if ((mode == 0) || (beep_ind == B_IND_DISABLED)) { - /* stop */ - if (flashing) { - flashing = false; - if (p_FlashWindowEx) - flash_window_ex(FLASHW_STOP, 0, 0); - else - FlashWindow(hwnd, false); - } + /* stop */ + if (flashing) { + flashing = false; + if (p_FlashWindowEx) + flash_window_ex(FLASHW_STOP, 0, 0); + else + FlashWindow(hwnd, false); + } } else if (mode == 2) { - /* start */ - if (!flashing) { - flashing = true; - if (p_FlashWindowEx) { - /* For so-called "steady" mode, we use uCount=2, which - * seems to be the traditional number of flashes used - * by user notifications (e.g., by Explorer). - * uCount=0 appears to enable continuous flashing, per - * "flashing" mode, although I haven't seen this - * documented. */ - flash_window_ex(FLASHW_ALL | FLASHW_TIMER, - (beep_ind == B_IND_FLASH ? 0 : 2), - 0 /* system cursor blink rate */); - /* No need to schedule timer */ - } else { - FlashWindow(hwnd, true); - next_flash = schedule_timer(450, flash_window_timer, hwnd); - } - } + /* start */ + if (!flashing) { + flashing = true; + if (p_FlashWindowEx) { + /* For so-called "steady" mode, we use uCount=2, which + * seems to be the traditional number of flashes used + * by user notifications (e.g., by Explorer). + * uCount=0 appears to enable continuous flashing, per + * "flashing" mode, although I haven't seen this + * documented. */ + flash_window_ex(FLASHW_ALL | FLASHW_TIMER, + (beep_ind == B_IND_FLASH ? 0 : 2), + 0 /* system cursor blink rate */); + /* No need to schedule timer */ + } else { + FlashWindow(hwnd, true); + next_flash = schedule_timer(450, flash_window_timer, hwnd); + } + } } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) { - /* maintain */ - if (flashing && !p_FlashWindowEx) { - FlashWindow(hwnd, true); /* toggle */ - next_flash = schedule_timer(450, flash_window_timer, hwnd); - } + /* maintain */ + if (flashing && !p_FlashWindowEx) { + FlashWindow(hwnd, true); /* toggle */ + next_flash = schedule_timer(450, flash_window_timer, hwnd); + } } } @@ -5529,27 +5529,27 @@ static void flash_window(int mode) static void wintw_bell(TermWin *tw, int mode) { if (mode == BELL_DEFAULT) { - /* - * For MessageBeep style bells, we want to be careful of - * timing, because they don't have the nice property of - * PlaySound bells that each one cancels the previous - * active one. So we limit the rate to one per 50ms or so. - */ - static long lastbeep = 0; - long beepdiff; + /* + * For MessageBeep style bells, we want to be careful of + * timing, because they don't have the nice property of + * PlaySound bells that each one cancels the previous + * active one. So we limit the rate to one per 50ms or so. + */ + static long lastbeep = 0; + long beepdiff; - beepdiff = GetTickCount() - lastbeep; - if (beepdiff >= 0 && beepdiff < 50) - return; - MessageBeep(MB_OK); - /* - * The above MessageBeep call takes time, so we record the - * time _after_ it finishes rather than before it starts. - */ - lastbeep = GetTickCount(); + beepdiff = GetTickCount() - lastbeep; + if (beepdiff >= 0 && beepdiff < 50) + return; + MessageBeep(MB_OK); + /* + * The above MessageBeep call takes time, so we record the + * time _after_ it finishes rather than before it starts. + */ + lastbeep = GetTickCount(); } else if (mode == BELL_WAVEFILE) { - Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile); - if (!p_PlaySound || !p_PlaySound(bell_wavefile->path, NULL, + Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile); + if (!p_PlaySound || !p_PlaySound(bell_wavefile->path, NULL, SND_ASYNC | SND_FILENAME)) { char *buf, *otherbuf; buf = dupprintf( @@ -5559,29 +5559,29 @@ static void wintw_bell(TermWin *tw, int mode) MessageBox(hwnd, buf, otherbuf, MB_OK | MB_ICONEXCLAMATION); sfree(buf); sfree(otherbuf); - conf_set_int(conf, CONF_beep, BELL_DEFAULT); - } + conf_set_int(conf, CONF_beep, BELL_DEFAULT); + } } else if (mode == BELL_PCSPEAKER) { - static long lastbeep = 0; - long beepdiff; + static long lastbeep = 0; + long beepdiff; - beepdiff = GetTickCount() - lastbeep; - if (beepdiff >= 0 && beepdiff < 50) - return; + beepdiff = GetTickCount() - lastbeep; + if (beepdiff >= 0 && beepdiff < 50) + return; - /* - * We must beep in different ways depending on whether this - * is a 95-series or NT-series OS. - */ - if (osPlatformId == VER_PLATFORM_WIN32_NT) - Beep(800, 100); - else - MessageBeep(-1); - lastbeep = GetTickCount(); + /* + * We must beep in different ways depending on whether this + * is a 95-series or NT-series OS. + */ + if (osPlatformId == VER_PLATFORM_WIN32_NT) + Beep(800, 100); + else + MessageBeep(-1); + lastbeep = GetTickCount(); } /* Otherwise, either visual bell or disabled; do nothing here */ if (!term->has_focus) { - flash_window(2); /* start */ + flash_window(2); /* start */ } } @@ -5592,11 +5592,11 @@ static void wintw_bell(TermWin *tw, int mode) static void wintw_set_minimised(TermWin *tw, bool minimised) { if (IsIconic(hwnd)) { - if (!minimised) - ShowWindow(hwnd, SW_RESTORE); + if (!minimised) + ShowWindow(hwnd, SW_RESTORE); } else { - if (minimised) - ShowWindow(hwnd, SW_MINIMIZE); + if (minimised) + ShowWindow(hwnd, SW_MINIMIZE); } } @@ -5606,9 +5606,9 @@ static void wintw_set_minimised(TermWin *tw, bool minimised) static void wintw_move(TermWin *tw, int x, int y) { int resize_action = conf_get_int(conf, CONF_resize_action); - if (resize_action == RESIZE_DISABLED || - resize_action == RESIZE_FONT || - IsZoomed(hwnd)) + if (resize_action == RESIZE_DISABLED || + resize_action == RESIZE_FONT || + IsZoomed(hwnd)) return; SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); @@ -5621,9 +5621,9 @@ static void wintw_move(TermWin *tw, int x, int y) static void wintw_set_zorder(TermWin *tw, bool top) { if (conf_get_bool(conf, CONF_alwaysontop)) - return; /* ignore */ + return; /* ignore */ SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE); + SWP_NOMOVE | SWP_NOSIZE); } /* @@ -5642,10 +5642,10 @@ static void wintw_set_maximised(TermWin *tw, bool maximised) { if (IsZoomed(hwnd)) { if (!maximised) - ShowWindow(hwnd, SW_RESTORE); + ShowWindow(hwnd, SW_RESTORE); } else { - if (maximised) - ShowWindow(hwnd, SW_MAXIMIZE); + if (maximised) + ShowWindow(hwnd, SW_MAXIMIZE); } } @@ -5693,9 +5693,9 @@ static const char *wintw_get_title(TermWin *tw, bool icon) static bool is_full_screen() { if (!IsZoomed(hwnd)) - return false; + return false; if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION) - return false; + return false; return true; } @@ -5705,22 +5705,22 @@ static bool is_full_screen() static bool get_fullscreen_rect(RECT * ss) { #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON) - HMONITOR mon; - MONITORINFO mi; - mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - mi.cbSize = sizeof(mi); - GetMonitorInfo(mon, &mi); + HMONITOR mon; + MONITORINFO mi; + mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + mi.cbSize = sizeof(mi); + GetMonitorInfo(mon, &mi); - /* structure copy */ - *ss = mi.rcMonitor; - return true; + /* structure copy */ + *ss = mi.rcMonitor; + return true; #else /* could also use code like this: - ss->left = ss->top = 0; - ss->right = GetSystemMetrics(SM_CXSCREEN); - ss->bottom = GetSystemMetrics(SM_CYSCREEN); -*/ - return GetClientRect(GetDesktopWindow(), ss); + ss->left = ss->top = 0; + ss->right = GetSystemMetrics(SM_CXSCREEN); + ss->bottom = GetSystemMetrics(SM_CYSCREEN); +*/ + return GetClientRect(GetDesktopWindow(), ss); #endif } @@ -5732,28 +5732,28 @@ static bool get_fullscreen_rect(RECT * ss) static void make_full_screen() { DWORD style; - RECT ss; + RECT ss; assert(IsZoomed(hwnd)); - if (is_full_screen()) - return; - + if (is_full_screen()) + return; + /* Remove the window furniture. */ style = GetWindowLongPtr(hwnd, GWL_STYLE); style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME); if (conf_get_bool(conf, CONF_scrollbar_in_fullscreen)) - style |= WS_VSCROLL; + style |= WS_VSCROLL; else - style &= ~WS_VSCROLL; + style &= ~WS_VSCROLL; SetWindowLongPtr(hwnd, GWL_STYLE, style); /* Resize ourselves to exactly cover the nearest monitor. */ - get_fullscreen_rect(&ss); + get_fullscreen_rect(&ss); SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top, - ss.right - ss.left, - ss.bottom - ss.top, - SWP_FRAMECHANGED); + ss.right - ss.left, + ss.bottom - ss.top, + SWP_FRAMECHANGED); /* We may have changed size as a result */ @@ -5761,9 +5761,9 @@ static void make_full_screen() /* Tick the menu item in the System and context menus. */ { - int i; - for (i = 0; i < lenof(popup_menus); i++) - CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED); + int i; + for (i = 0; i < lenof(popup_menus); i++) + CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED); } } @@ -5782,21 +5782,21 @@ static void clear_full_screen() else style |= WS_THICKFRAME; if (conf_get_bool(conf, CONF_scrollbar)) - style |= WS_VSCROLL; + style |= WS_VSCROLL; else - style &= ~WS_VSCROLL; + style &= ~WS_VSCROLL; if (style != oldstyle) { - SetWindowLongPtr(hwnd, GWL_STYLE, style); - SetWindowPos(hwnd, NULL, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | - SWP_FRAMECHANGED); + SetWindowLongPtr(hwnd, GWL_STYLE, style); + SetWindowPos(hwnd, NULL, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | + SWP_FRAMECHANGED); } /* Untick the menu item in the System and context menus. */ { - int i; - for (i = 0; i < lenof(popup_menus); i++) - CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED); + int i; + for (i = 0; i < lenof(popup_menus); i++) + CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED); } } @@ -5806,12 +5806,12 @@ static void clear_full_screen() static void flip_full_screen() { if (is_full_screen()) { - ShowWindow(hwnd, SW_RESTORE); + ShowWindow(hwnd, SW_RESTORE); } else if (IsZoomed(hwnd)) { - make_full_screen(); + make_full_screen(); } else { - SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0); - ShowWindow(hwnd, SW_MAXIMIZE); + SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0); + ShowWindow(hwnd, SW_MAXIMIZE); } } @@ -5832,12 +5832,12 @@ static int win_seat_get_userpass_input( int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = term_get_userpass_input(term, p, input); + ret = term_get_userpass_input(term, p, input); return ret; } void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len) + void *callback_ctx, void *data, int len) { struct agent_callback *c = snew(struct agent_callback); c->callback = callback; diff --git a/windows/wingss.c b/windows/wingss.c index d4d5d881..6744475b 100644 --- a/windows/wingss.c +++ b/windows/wingss.c @@ -12,8 +12,8 @@ #include "misc.h" -#define UNIX_EPOCH 11644473600ULL /* Seconds from Windows epoch */ -#define CNS_PERSEC 10000000ULL /* # 100ns per second */ +#define UNIX_EPOCH 11644473600ULL /* Seconds from Windows epoch */ +#define CNS_PERSEC 10000000ULL /* # 100ns per second */ /* * Note, as a special case, 0 relative to the Windows epoch (unspecified) maps @@ -49,29 +49,29 @@ const struct keyvalwhere gsslibkeywords[] = { }; DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - AcquireCredentialsHandleA, - (SEC_CHAR *, SEC_CHAR *, ULONG, PVOID, - PVOID, SEC_GET_KEY_FN, PVOID, PCredHandle, PTimeStamp)); + AcquireCredentialsHandleA, + (SEC_CHAR *, SEC_CHAR *, ULONG, PVOID, + PVOID, SEC_GET_KEY_FN, PVOID, PCredHandle, PTimeStamp)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - InitializeSecurityContextA, - (PCredHandle, PCtxtHandle, SEC_CHAR *, ULONG, ULONG, - ULONG, PSecBufferDesc, ULONG, PCtxtHandle, - PSecBufferDesc, PULONG, PTimeStamp)); + InitializeSecurityContextA, + (PCredHandle, PCtxtHandle, SEC_CHAR *, ULONG, ULONG, + ULONG, PSecBufferDesc, ULONG, PCtxtHandle, + PSecBufferDesc, PULONG, PTimeStamp)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - FreeContextBuffer, - (PVOID)); + FreeContextBuffer, + (PVOID)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - FreeCredentialsHandle, - (PCredHandle)); + FreeCredentialsHandle, + (PCredHandle)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - DeleteSecurityContext, - (PCtxtHandle)); + DeleteSecurityContext, + (PCtxtHandle)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - QueryContextAttributesA, - (PCtxtHandle, ULONG, PVOID)); + QueryContextAttributesA, + (PCtxtHandle, ULONG, PVOID)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, - MakeSignature, - (PCtxtHandle, ULONG, PSecBufferDesc, ULONG)); + MakeSignature, + (PCtxtHandle, ULONG, PSecBufferDesc, ULONG)); DECL_WINDOWS_FUNCTION(static, SECURITY_STATUS, VerifySignature, (PCtxtHandle, PSecBufferDesc, ULONG, PULONG)); @@ -118,19 +118,19 @@ struct ssh_gss_liblist *ssh_gss_setup(Conf *conf) /* MIT Kerberos GSSAPI implementation */ module = NULL; if (RegOpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\MIT\\Kerberos", ®key) - == ERROR_SUCCESS) { - DWORD type, size; - LONG ret; - char *buffer; + == ERROR_SUCCESS) { + DWORD type, size; + LONG ret; + char *buffer; - /* Find out the string length */ + /* Find out the string length */ ret = RegQueryValueEx(regkey, "InstallDir", NULL, &type, NULL, &size); - if (ret == ERROR_SUCCESS && type == REG_SZ) { - buffer = snewn(size + 20, char); - ret = RegQueryValueEx(regkey, "InstallDir", NULL, - &type, (LPBYTE)buffer, &size); - if (ret == ERROR_SUCCESS && type == REG_SZ) { + if (ret == ERROR_SUCCESS && type == REG_SZ) { + buffer = snewn(size + 20, char); + ret = RegQueryValueEx(regkey, "InstallDir", NULL, + &type, (LPBYTE)buffer, &size); + if (ret == ERROR_SUCCESS && type == REG_SZ) { strcat (buffer, "\\bin"); if(p_AddDllDirectory) { /* Add MIT Kerberos' path to the DLL search path, @@ -145,18 +145,18 @@ struct ssh_gss_liblist *ssh_gss_setup(Conf *conf) LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_USER_DIRS); - } - sfree(buffer); - } - RegCloseKey(regkey); + } + sfree(buffer); + } + RegCloseKey(regkey); } if (module) { - struct ssh_gss_library *lib = - &list->libraries[list->nlibraries++]; + struct ssh_gss_library *lib = + &list->libraries[list->nlibraries++]; - lib->id = 0; - lib->gsslogmsg = "Using GSSAPI from GSSAPI"MIT_KERB_SUFFIX".DLL"; - lib->handle = (void *)module; + lib->id = 0; + lib->gsslogmsg = "Using GSSAPI from GSSAPI"MIT_KERB_SUFFIX".DLL"; + lib->handle = (void *)module; #define BIND_GSS_FN(name) \ lib->u.gssapi.name = (t_gss_##name) GetProcAddress(module, "gss_" #name) @@ -181,23 +181,23 @@ struct ssh_gss_liblist *ssh_gss_setup(Conf *conf) /* Microsoft SSPI Implementation */ module = load_system32_dll("secur32.dll"); if (module) { - struct ssh_gss_library *lib = - &list->libraries[list->nlibraries++]; + struct ssh_gss_library *lib = + &list->libraries[list->nlibraries++]; - lib->id = 1; - lib->gsslogmsg = "Using SSPI from SECUR32.DLL"; - lib->handle = (void *)module; + lib->id = 1; + lib->gsslogmsg = "Using SSPI from SECUR32.DLL"; + lib->handle = (void *)module; - GET_WINDOWS_FUNCTION(module, AcquireCredentialsHandleA); - GET_WINDOWS_FUNCTION(module, InitializeSecurityContextA); - GET_WINDOWS_FUNCTION(module, FreeContextBuffer); - GET_WINDOWS_FUNCTION(module, FreeCredentialsHandle); - GET_WINDOWS_FUNCTION(module, DeleteSecurityContext); - GET_WINDOWS_FUNCTION(module, QueryContextAttributesA); - GET_WINDOWS_FUNCTION(module, MakeSignature); + GET_WINDOWS_FUNCTION(module, AcquireCredentialsHandleA); + GET_WINDOWS_FUNCTION(module, InitializeSecurityContextA); + GET_WINDOWS_FUNCTION(module, FreeContextBuffer); + GET_WINDOWS_FUNCTION(module, FreeCredentialsHandle); + GET_WINDOWS_FUNCTION(module, DeleteSecurityContext); + GET_WINDOWS_FUNCTION(module, QueryContextAttributesA); + GET_WINDOWS_FUNCTION(module, MakeSignature); GET_WINDOWS_FUNCTION(module, VerifySignature); - ssh_sspi_bind_fns(lib); + ssh_sspi_bind_fns(lib); } /* @@ -234,13 +234,13 @@ struct ssh_gss_liblist *ssh_gss_setup(Conf *conf) LOAD_LIBRARY_SEARCH_USER_DIRS); } if (module) { - struct ssh_gss_library *lib = - &list->libraries[list->nlibraries++]; + struct ssh_gss_library *lib = + &list->libraries[list->nlibraries++]; - lib->id = 2; - lib->gsslogmsg = dupprintf("Using GSSAPI from user-specified" - " library '%s'", path); - lib->handle = (void *)module; + lib->id = 2; + lib->gsslogmsg = dupprintf("Using GSSAPI from user-specified" + " library '%s'", path); + lib->handle = (void *)module; #define BIND_GSS_FN(name) \ lib->u.gssapi.name = (t_gss_##name) GetProcAddress(module, "gss_" #name) @@ -280,19 +280,19 @@ void ssh_gss_cleanup(struct ssh_gss_liblist *list) * another SSH instance still using it. */ for (i = 0; i < list->nlibraries; i++) { - FreeLibrary((HMODULE)list->libraries[i].handle); - if (list->libraries[i].id == 2) { - /* The 'custom' id involves a dynamically allocated message. - * Note that we must cast away the 'const' to free it. */ - sfree((char *)list->libraries[i].gsslogmsg); - } + FreeLibrary((HMODULE)list->libraries[i].handle); + if (list->libraries[i].id == 2) { + /* The 'custom' id involves a dynamically allocated message. + * Note that we must cast away the 'const' to free it. */ + sfree((char *)list->libraries[i].gsslogmsg); + } } sfree(list->libraries); sfree(list); } static Ssh_gss_stat ssh_sspi_indicate_mech(struct ssh_gss_library *lib, - Ssh_gss_buf *mech) + Ssh_gss_buf *mech) { *mech = gss_mech_krb5; return SSH_GSS_OK; @@ -300,13 +300,13 @@ static Ssh_gss_stat ssh_sspi_indicate_mech(struct ssh_gss_library *lib, static Ssh_gss_stat ssh_sspi_import_name(struct ssh_gss_library *lib, - char *host, Ssh_gss_name *srv_name) + char *host, Ssh_gss_name *srv_name) { char *pStr; /* Check hostname */ if (host == NULL) return SSH_GSS_FAILURE; - + /* copy it into form host/FQDN */ pStr = dupcat("host/", host, NULL); @@ -330,13 +330,13 @@ static Ssh_gss_stat ssh_sspi_acquire_cred(struct ssh_gss_library *lib, the current logged-in user */ winctx->maj_stat = p_AcquireCredentialsHandleA(NULL, - "Kerberos", - SECPKG_CRED_OUTBOUND, - NULL, - NULL, - NULL, - NULL, - &winctx->cred_handle, + "Kerberos", + SECPKG_CRED_OUTBOUND, + NULL, + NULL, + NULL, + NULL, + &winctx->cred_handle, NULL); if (winctx->maj_stat != SEC_E_OK) { @@ -407,10 +407,10 @@ static void localexp_to_exp_lifetime(TimeStamp *localexp, } static Ssh_gss_stat ssh_sspi_init_sec_context(struct ssh_gss_library *lib, - Ssh_gss_ctx *ctx, - Ssh_gss_name srv_name, - int to_deleg, - Ssh_gss_buf *recv_tok, + Ssh_gss_ctx *ctx, + Ssh_gss_name srv_name, + int to_deleg, + Ssh_gss_buf *recv_tok, Ssh_gss_buf *send_tok, time_t *expiry, unsigned long *lifetime) @@ -421,23 +421,23 @@ static Ssh_gss_stat ssh_sspi_init_sec_context(struct ssh_gss_library *lib, SecBufferDesc output_desc={SECBUFFER_VERSION,1,&wsend_tok}; SecBufferDesc input_desc ={SECBUFFER_VERSION,1,&wrecv_tok}; unsigned long flags=ISC_REQ_MUTUAL_AUTH|ISC_REQ_REPLAY_DETECT| - ISC_REQ_CONFIDENTIALITY|ISC_REQ_ALLOCATE_MEMORY; + ISC_REQ_CONFIDENTIALITY|ISC_REQ_ALLOCATE_MEMORY; unsigned long ret_flags=0; TimeStamp localexp; - + /* check if we have to delegate ... */ if (to_deleg) flags |= ISC_REQ_DELEGATE; winctx->maj_stat = p_InitializeSecurityContextA(&winctx->cred_handle, - winctx->context_handle, - (char*) srv_name, - flags, - 0, /* reserved */ - SECURITY_NATIVE_DREP, - &input_desc, - 0, /* reserved */ - &winctx->context, - &output_desc, - &ret_flags, + winctx->context_handle, + (char*) srv_name, + flags, + 0, /* reserved */ + SECURITY_NATIVE_DREP, + &input_desc, + 0, /* reserved */ + &winctx->context, + &output_desc, + &ret_flags, &localexp); localexp_to_exp_lifetime(&localexp, expiry, lifetime); @@ -446,16 +446,16 @@ static Ssh_gss_stat ssh_sspi_init_sec_context(struct ssh_gss_library *lib, winctx->context_handle = &winctx->context; send_tok->value = wsend_tok.pvBuffer; send_tok->length = wsend_tok.cbBuffer; - + /* check & return our status */ if (winctx->maj_stat==SEC_E_OK) return SSH_GSS_S_COMPLETE; if (winctx->maj_stat==SEC_I_CONTINUE_NEEDED) return SSH_GSS_S_CONTINUE_NEEDED; - + return SSH_GSS_FAILURE; } static Ssh_gss_stat ssh_sspi_free_tok(struct ssh_gss_library *lib, - Ssh_gss_buf *send_tok) + Ssh_gss_buf *send_tok) { /* check input */ if (send_tok == NULL) return SSH_GSS_FAILURE; @@ -463,12 +463,12 @@ static Ssh_gss_stat ssh_sspi_free_tok(struct ssh_gss_library *lib, /* free Windows buffer */ p_FreeContextBuffer(send_tok->value); SSH_GSS_CLEAR_BUF(send_tok); - + return SSH_GSS_OK; } static Ssh_gss_stat ssh_sspi_release_cred(struct ssh_gss_library *lib, - Ssh_gss_ctx *ctx) + Ssh_gss_ctx *ctx) { winSsh_gss_ctx *winctx= (winSsh_gss_ctx *) *ctx; @@ -488,7 +488,7 @@ static Ssh_gss_stat ssh_sspi_release_cred(struct ssh_gss_library *lib, static Ssh_gss_stat ssh_sspi_release_name(struct ssh_gss_library *lib, - Ssh_gss_name *srv_name) + Ssh_gss_name *srv_name) { char *pStr= (char *) *srv_name; @@ -500,7 +500,7 @@ static Ssh_gss_stat ssh_sspi_release_name(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_sspi_display_status(struct ssh_gss_library *lib, - Ssh_gss_ctx ctx, Ssh_gss_buf *buf) + Ssh_gss_ctx ctx, Ssh_gss_buf *buf) { winSsh_gss_ctx *winctx = (winSsh_gss_ctx *) ctx; const char *msg; @@ -511,48 +511,48 @@ static Ssh_gss_stat ssh_sspi_display_status(struct ssh_gss_library *lib, switch (winctx->maj_stat) { case SEC_E_OK: msg="SSPI status OK"; break; case SEC_E_INVALID_HANDLE: msg="The handle passed to the function" - " is invalid."; - break; + " is invalid."; + break; case SEC_E_TARGET_UNKNOWN: msg="The target was not recognized."; break; case SEC_E_LOGON_DENIED: msg="The logon failed."; break; case SEC_E_INTERNAL_ERROR: msg="The Local Security Authority cannot" - " be contacted."; - break; + " be contacted."; + break; case SEC_E_NO_CREDENTIALS: msg="No credentials are available in the" - " security package."; - break; + " security package."; + break; case SEC_E_NO_AUTHENTICATING_AUTHORITY: - msg="No authority could be contacted for authentication." - "The domain name of the authenticating party could be wrong," - " the domain could be unreachable, or there might have been" - " a trust relationship failure."; - break; + msg="No authority could be contacted for authentication." + "The domain name of the authenticating party could be wrong," + " the domain could be unreachable, or there might have been" + " a trust relationship failure."; + break; case SEC_E_INSUFFICIENT_MEMORY: - msg="One or more of the SecBufferDesc structures passed as" - " an OUT parameter has a buffer that is too small."; - break; + msg="One or more of the SecBufferDesc structures passed as" + " an OUT parameter has a buffer that is too small."; + break; case SEC_E_INVALID_TOKEN: - msg="The error is due to a malformed input token, such as a" - " token corrupted in transit, a token" - " of incorrect size, or a token passed into the wrong" - " security package. Passing a token to" - " the wrong package can happen if client and server did not" - " negotiate the proper security package."; - break; + msg="The error is due to a malformed input token, such as a" + " token corrupted in transit, a token" + " of incorrect size, or a token passed into the wrong" + " security package. Passing a token to" + " the wrong package can happen if client and server did not" + " negotiate the proper security package."; + break; default: - msg = "Internal SSPI error"; - break; + msg = "Internal SSPI error"; + break; } buf->value = dupstr(msg); buf->length = strlen(buf->value); - + return SSH_GSS_OK; } static Ssh_gss_stat ssh_sspi_get_mic(struct ssh_gss_library *lib, - Ssh_gss_ctx ctx, Ssh_gss_buf *buf, - Ssh_gss_buf *hash) + Ssh_gss_ctx ctx, Ssh_gss_buf *buf, + Ssh_gss_buf *hash) { winSsh_gss_ctx *winctx= (winSsh_gss_ctx *) ctx; SecPkgContext_Sizes ContextSizes; @@ -560,18 +560,18 @@ static Ssh_gss_stat ssh_sspi_get_mic(struct ssh_gss_library *lib, SecBuffer InputSecurityToken[2]; if (winctx == NULL) return SSH_GSS_FAILURE; - + winctx->maj_stat = 0; memset(&ContextSizes, 0, sizeof(ContextSizes)); winctx->maj_stat = p_QueryContextAttributesA(&winctx->context, - SECPKG_ATTR_SIZES, - &ContextSizes); - + SECPKG_ATTR_SIZES, + &ContextSizes); + if (winctx->maj_stat != SEC_E_OK || - ContextSizes.cbMaxSignature == 0) - return winctx->maj_stat; + ContextSizes.cbMaxSignature == 0) + return winctx->maj_stat; InputBufferDescriptor.cBuffers = 2; InputBufferDescriptor.pBuffers = InputSecurityToken; @@ -584,13 +584,13 @@ static Ssh_gss_stat ssh_sspi_get_mic(struct ssh_gss_library *lib, InputSecurityToken[1].pvBuffer = snewn(ContextSizes.cbMaxSignature, char); winctx->maj_stat = p_MakeSignature(&winctx->context, - 0, - &InputBufferDescriptor, - 0); + 0, + &InputBufferDescriptor, + 0); if (winctx->maj_stat == SEC_E_OK) { - hash->length = InputSecurityToken[1].cbBuffer; - hash->value = InputSecurityToken[1].pvBuffer; + hash->length = InputSecurityToken[1].cbBuffer; + hash->value = InputSecurityToken[1].pvBuffer; } return winctx->maj_stat; @@ -627,7 +627,7 @@ static Ssh_gss_stat ssh_sspi_verify_mic(struct ssh_gss_library *lib, } static Ssh_gss_stat ssh_sspi_free_mic(struct ssh_gss_library *lib, - Ssh_gss_buf *hash) + Ssh_gss_buf *hash) { sfree(hash->value); return SSH_GSS_OK; diff --git a/windows/winhandl.c b/windows/winhandl.c index 6e2c4be0..b41cac55 100644 --- a/windows/winhandl.c +++ b/windows/winhandl.c @@ -9,14 +9,14 @@ * data, the subthread sets an event object which is picked up by * the main thread, and the main thread then sets an event in * return to instruct the subthread to resume reading. - * + * * Output works precisely the other way round, in a second * subthread. The output subthread should not be attempting to * write all the time, because it hasn't always got data _to_ * write; so the output thread waits for an event object notifying * it to _attempt_ a write, and then it sets an event in return * when one completes. - * + * * (It's terribly annoying having to spawn a subthread for each * direction of each handle. Technically it isn't necessary for * serial ports, since we could use overlapped I/O within the main @@ -47,7 +47,7 @@ struct handle_generic { /* * Initial fields common to both handle_input and handle_output * structures. - * + * * The three HANDLEs are set up at initialisation time and are * thereafter read-only to both main thread and subthread. * `moribund' is only used by the main thread; `done' is @@ -55,14 +55,14 @@ struct handle_generic { * subthread. `defunct' and `busy' are used only by the main * thread. */ - HANDLE h; /* the handle itself */ - HANDLE ev_to_main; /* event used to signal main thread */ - HANDLE ev_from_main; /* event used to signal back to us */ + HANDLE h; /* the handle itself */ + HANDLE ev_to_main; /* event used to signal main thread */ + HANDLE ev_from_main; /* event used to signal back to us */ bool moribund; /* are we going to kill this soon? */ bool done; /* request subthread to terminate */ bool defunct; /* has the subthread already gone? */ bool busy; /* operation currently in progress? */ - void *privdata; /* for client to remember who they are */ + void *privdata; /* for client to remember who they are */ }; typedef enum { HT_INPUT, HT_OUTPUT, HT_FOREIGN } HandleType; @@ -78,14 +78,14 @@ struct handle_input { /* * Copy of the handle_generic structure. */ - HANDLE h; /* the handle itself */ - HANDLE ev_to_main; /* event used to signal main thread */ - HANDLE ev_from_main; /* event used to signal back to us */ + HANDLE h; /* the handle itself */ + HANDLE ev_to_main; /* event used to signal main thread */ + HANDLE ev_from_main; /* event used to signal back to us */ bool moribund; /* are we going to kill this soon? */ bool done; /* request subthread to terminate */ bool defunct; /* has the subthread already gone? */ bool busy; /* operation currently in progress? */ - void *privdata; /* for client to remember who they are */ + void *privdata; /* for client to remember who they are */ /* * Data set at initialisation and then read-only. @@ -96,9 +96,9 @@ struct handle_input { * Data set by the input thread before signalling ev_to_main, * and read by the main thread after receiving that signal. */ - char buffer[4096]; /* the data read from the handle */ - DWORD len; /* how much data that was */ - int readerr; /* lets us know about read errors */ + char buffer[4096]; /* the data read from the handle */ + DWORD len; /* how much data that was */ + int readerr; /* lets us know about read errors */ /* * Callback function called by this module when data arrives on @@ -119,52 +119,52 @@ static DWORD WINAPI handle_input_threadfunc(void *param) int readlen; if (ctx->flags & HANDLE_FLAG_OVERLAPPED) { - povl = &ovl; - oev = CreateEvent(NULL, true, false, NULL); + povl = &ovl; + oev = CreateEvent(NULL, true, false, NULL); } else { - povl = NULL; + povl = NULL; } if (ctx->flags & HANDLE_FLAG_UNITBUFFER) - readlen = 1; + readlen = 1; else - readlen = sizeof(ctx->buffer); + readlen = sizeof(ctx->buffer); while (1) { - if (povl) { - memset(povl, 0, sizeof(OVERLAPPED)); - povl->hEvent = oev; - } - readret = ReadFile(ctx->h, ctx->buffer,readlen, &ctx->len, povl); - if (!readret) - ctx->readerr = GetLastError(); - else - ctx->readerr = 0; - if (povl && !readret && ctx->readerr == ERROR_IO_PENDING) { - WaitForSingleObject(povl->hEvent, INFINITE); - readret = GetOverlappedResult(ctx->h, povl, &ctx->len, false); - if (!readret) - ctx->readerr = GetLastError(); - else - ctx->readerr = 0; - } + if (povl) { + memset(povl, 0, sizeof(OVERLAPPED)); + povl->hEvent = oev; + } + readret = ReadFile(ctx->h, ctx->buffer,readlen, &ctx->len, povl); + if (!readret) + ctx->readerr = GetLastError(); + else + ctx->readerr = 0; + if (povl && !readret && ctx->readerr == ERROR_IO_PENDING) { + WaitForSingleObject(povl->hEvent, INFINITE); + readret = GetOverlappedResult(ctx->h, povl, &ctx->len, false); + if (!readret) + ctx->readerr = GetLastError(); + else + ctx->readerr = 0; + } - if (!readret) { - /* - * Windows apparently sends ERROR_BROKEN_PIPE when a - * pipe we're reading from is closed normally from the - * writing end. This is ludicrous; if that situation - * isn't a natural EOF, _nothing_ is. So if we get that - * particular error, we pretend it's EOF. - */ - if (ctx->readerr == ERROR_BROKEN_PIPE) - ctx->readerr = 0; - ctx->len = 0; - } + if (!readret) { + /* + * Windows apparently sends ERROR_BROKEN_PIPE when a + * pipe we're reading from is closed normally from the + * writing end. This is ludicrous; if that situation + * isn't a natural EOF, _nothing_ is. So if we get that + * particular error, we pretend it's EOF. + */ + if (ctx->readerr == ERROR_BROKEN_PIPE) + ctx->readerr = 0; + ctx->len = 0; + } - if (readret && ctx->len == 0 && - (ctx->flags & HANDLE_FLAG_IGNOREEOF)) - continue; + if (readret && ctx->len == 0 && + (ctx->flags & HANDLE_FLAG_IGNOREEOF)) + continue; /* * If we just set ctx->len to 0, that means the read operation @@ -176,13 +176,13 @@ static DWORD WINAPI handle_input_threadfunc(void *param) */ finished = (ctx->len == 0); - SetEvent(ctx->ev_to_main); + SetEvent(ctx->ev_to_main); - if (finished) - break; + if (finished) + break; - WaitForSingleObject(ctx->ev_from_main, INFINITE); - if (ctx->done) { + WaitForSingleObject(ctx->ev_from_main, INFINITE); + if (ctx->done) { /* * The main thread has asked us to shut down. Send back an * event indicating that we've done so. Hereafter we must @@ -195,7 +195,7 @@ static DWORD WINAPI handle_input_threadfunc(void *param) } if (povl) - CloseHandle(oev); + CloseHandle(oev); return 0; } @@ -208,7 +208,7 @@ static DWORD WINAPI handle_input_threadfunc(void *param) static void handle_throttle(struct handle_input *ctx, int backlog) { if (ctx->defunct) - return; + return; /* * If there's a read operation already in progress, do nothing: @@ -216,15 +216,15 @@ static void handle_throttle(struct handle_input *ctx, int backlog) * position to make a better decision. */ if (ctx->busy) - return; + return; /* * Otherwise, we must decide whether to start a new read based * on the size of the backlog. */ if (backlog < MAX_BACKLOG) { - SetEvent(ctx->ev_from_main); - ctx->busy = true; + SetEvent(ctx->ev_from_main); + ctx->busy = true; } } @@ -239,14 +239,14 @@ struct handle_output { /* * Copy of the handle_generic structure. */ - HANDLE h; /* the handle itself */ - HANDLE ev_to_main; /* event used to signal main thread */ - HANDLE ev_from_main; /* event used to signal back to us */ + HANDLE h; /* the handle itself */ + HANDLE ev_to_main; /* event used to signal main thread */ + HANDLE ev_from_main; /* event used to signal back to us */ bool moribund; /* are we going to kill this soon? */ bool done; /* request subthread to terminate */ bool defunct; /* has the subthread already gone? */ bool busy; /* operation currently in progress? */ - void *privdata; /* for client to remember who they are */ + void *privdata; /* for client to remember who they are */ /* * Data set at initialisation and then read-only. @@ -258,19 +258,19 @@ struct handle_output { * and read by the input thread after receiving that signal. */ const char *buffer; /* the data to write */ - DWORD len; /* how much data there is */ + DWORD len; /* how much data there is */ /* * Data set by the input thread before signalling ev_to_main, * and read by the main thread after receiving that signal. */ - DWORD lenwritten; /* how much data we actually wrote */ - int writeerr; /* return value from WriteFile */ + DWORD lenwritten; /* how much data we actually wrote */ + int writeerr; /* return value from WriteFile */ /* * Data only ever read or written by the main thread. */ - bufchain queued_data; /* data still waiting to be written */ + bufchain queued_data; /* data still waiting to be written */ enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof; /* @@ -288,46 +288,46 @@ static DWORD WINAPI handle_output_threadfunc(void *param) bool writeret; if (ctx->flags & HANDLE_FLAG_OVERLAPPED) { - povl = &ovl; - oev = CreateEvent(NULL, true, false, NULL); + povl = &ovl; + oev = CreateEvent(NULL, true, false, NULL); } else { - povl = NULL; + povl = NULL; } while (1) { - WaitForSingleObject(ctx->ev_from_main, INFINITE); - if (ctx->done) { + WaitForSingleObject(ctx->ev_from_main, INFINITE); + if (ctx->done) { /* * The main thread has asked us to shut down. Send back an * event indicating that we've done so. Hereafter we must * not touch ctx at all, because the main thread might * have freed it. */ - SetEvent(ctx->ev_to_main); - break; - } - if (povl) { - memset(povl, 0, sizeof(OVERLAPPED)); - povl->hEvent = oev; - } + SetEvent(ctx->ev_to_main); + break; + } + if (povl) { + memset(povl, 0, sizeof(OVERLAPPED)); + povl->hEvent = oev; + } - writeret = WriteFile(ctx->h, ctx->buffer, ctx->len, - &ctx->lenwritten, povl); - if (!writeret) - ctx->writeerr = GetLastError(); - else - ctx->writeerr = 0; - if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) { - writeret = GetOverlappedResult(ctx->h, povl, - &ctx->lenwritten, true); - if (!writeret) - ctx->writeerr = GetLastError(); - else - ctx->writeerr = 0; - } + writeret = WriteFile(ctx->h, ctx->buffer, ctx->len, + &ctx->lenwritten, povl); + if (!writeret) + ctx->writeerr = GetLastError(); + else + ctx->writeerr = 0; + if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) { + writeret = GetOverlappedResult(ctx->h, povl, + &ctx->lenwritten, true); + if (!writeret) + ctx->writeerr = GetLastError(); + else + ctx->writeerr = 0; + } - SetEvent(ctx->ev_to_main); - if (!writeret) { + SetEvent(ctx->ev_to_main); + if (!writeret) { /* * The write operation has suffered an error. Telling that * to the main thread will cause it to set its 'defunct' @@ -335,12 +335,12 @@ static DWORD WINAPI handle_output_threadfunc(void *param) * opportunity, so we must not touch ctx at all after * this. */ - break; + break; } } if (povl) - CloseHandle(oev); + CloseHandle(oev); return 0; } @@ -348,11 +348,11 @@ static DWORD WINAPI handle_output_threadfunc(void *param) static void handle_try_output(struct handle_output *ctx) { if (!ctx->busy && bufchain_size(&ctx->queued_data)) { - ptrlen data = bufchain_prefix(&ctx->queued_data); - ctx->buffer = data.ptr; - ctx->len = min(data.len, ~(DWORD)0); - SetEvent(ctx->ev_from_main); - ctx->busy = true; + ptrlen data = bufchain_prefix(&ctx->queued_data); + ctx->buffer = data.ptr; + ctx->len = min(data.len, ~(DWORD)0); + SetEvent(ctx->ev_from_main); + ctx->busy = true; } else if (!ctx->busy && bufchain_size(&ctx->queued_data) == 0 && ctx->outgoingeof == EOF_PENDING) { CloseHandle(ctx->h); @@ -372,14 +372,14 @@ struct handle_foreign { /* * Copy of the handle_generic structure. */ - HANDLE h; /* the handle itself */ - HANDLE ev_to_main; /* event used to signal main thread */ - HANDLE ev_from_main; /* event used to signal back to us */ + HANDLE h; /* the handle itself */ + HANDLE ev_to_main; /* event used to signal main thread */ + HANDLE ev_from_main; /* event used to signal back to us */ bool moribund; /* are we going to kill this soon? */ bool done; /* request subthread to terminate */ bool defunct; /* has the subthread already gone? */ bool busy; /* operation currently in progress? */ - void *privdata; /* for client to remember who they are */ + void *privdata; /* for client to remember who they are */ /* * Our own data, just consisting of knowledge of who to call back. @@ -395,10 +395,10 @@ struct handle_foreign { struct handle { HandleType type; union { - struct handle_generic g; - struct handle_input i; - struct handle_output o; - struct handle_foreign f; + struct handle_generic g; + struct handle_input i; + struct handle_output o; + struct handle_foreign f; } u; }; @@ -410,11 +410,11 @@ static int handle_cmp_evtomain(void *av, void *bv) struct handle *b = (struct handle *)bv; if ((uintptr_t)a->u.g.ev_to_main < (uintptr_t)b->u.g.ev_to_main) - return -1; + return -1; else if ((uintptr_t)a->u.g.ev_to_main > (uintptr_t)b->u.g.ev_to_main) - return +1; + return +1; else - return 0; + return 0; } static int handle_find_evtomain(void *av, void *bv) @@ -423,15 +423,15 @@ static int handle_find_evtomain(void *av, void *bv) struct handle *b = (struct handle *)bv; if ((uintptr_t)*a < (uintptr_t)b->u.g.ev_to_main) - return -1; + return -1; else if ((uintptr_t)*a > (uintptr_t)b->u.g.ev_to_main) - return +1; + return +1; else - return 0; + return 0; } struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata, - void *privdata, int flags) + void *privdata, int flags) { struct handle *h = snew(struct handle); DWORD in_threadid; /* required for Win9x */ @@ -448,18 +448,18 @@ struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata, h->u.i.flags = flags; if (!handles_by_evtomain) - handles_by_evtomain = newtree234(handle_cmp_evtomain); + handles_by_evtomain = newtree234(handle_cmp_evtomain); add234(handles_by_evtomain, h); CreateThread(NULL, 0, handle_input_threadfunc, - &h->u.i, 0, &in_threadid); + &h->u.i, 0, &in_threadid); h->u.i.busy = true; return h; } struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata, - void *privdata, int flags) + void *privdata, int flags) { struct handle *h = snew(struct handle); DWORD out_threadid; /* required for Win9x */ @@ -479,11 +479,11 @@ struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata, h->u.o.flags = flags; if (!handles_by_evtomain) - handles_by_evtomain = newtree234(handle_cmp_evtomain); + handles_by_evtomain = newtree234(handle_cmp_evtomain); add234(handles_by_evtomain, h); CreateThread(NULL, 0, handle_output_threadfunc, - &h->u.o, 0, &out_threadid); + &h->u.o, 0, &out_threadid); return h; } @@ -506,7 +506,7 @@ struct handle *handle_add_foreign_event(HANDLE event, h->u.f.busy = true; if (!handles_by_evtomain) - handles_by_evtomain = newtree234(handle_cmp_evtomain); + handles_by_evtomain = newtree234(handle_cmp_evtomain); add234(handles_by_evtomain, h); return h; @@ -551,12 +551,12 @@ HANDLE *handle_get_events(int *nevents) ret = NULL; n = size = 0; if (handles_by_evtomain) { - for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) { - if (h->u.g.busy) { + for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) { + if (h->u.g.busy) { sgrowarray(ret, size, n); - ret[n++] = h->u.g.ev_to_main; - } - } + ret[n++] = h->u.g.ev_to_main; + } + } } *nevents = n; @@ -566,7 +566,7 @@ HANDLE *handle_get_events(int *nevents) static void handle_destroy(struct handle *h) { if (h->type == HT_OUTPUT) - bufchain_clear(&h->u.o.queued_data); + bufchain_clear(&h->u.o.queued_data); CloseHandle(h->u.g.ev_from_main); CloseHandle(h->u.g.ev_to_main); del234(handles_by_evtomain, h); @@ -587,24 +587,24 @@ void handle_free(struct handle *h) * invalid memory after we free its context from under it. So * we set the moribund flag, which will be noticed next time * an operation completes. - */ - h->u.g.moribund = true; + */ + h->u.g.moribund = true; } else if (h->u.g.defunct) { - /* - * There isn't even a subthread; we can go straight to - * handle_destroy. - */ - handle_destroy(h); + /* + * There isn't even a subthread; we can go straight to + * handle_destroy. + */ + handle_destroy(h); } else { - /* - * The subthread is alive but not busy, so we now signal it - * to die. Set the moribund flag to indicate that it will - * want destroying after that. - */ - h->u.g.moribund = true; - h->u.g.done = true; - h->u.g.busy = true; - SetEvent(h->u.g.ev_from_main); + /* + * The subthread is alive but not busy, so we now signal it + * to die. Set the moribund flag to indicate that it will + * want destroying after that. + */ + h->u.g.moribund = true; + h->u.g.done = true; + h->u.g.busy = true; + SetEvent(h->u.g.ev_from_main); } } @@ -615,79 +615,79 @@ void handle_got_event(HANDLE event) assert(handles_by_evtomain); h = find234(handles_by_evtomain, &event, handle_find_evtomain); if (!h) { - /* - * This isn't an error condition. If two or more event - * objects were signalled during the same select operation, - * and processing of the first caused the second handle to - * be closed, then it will sometimes happen that we receive - * an event notification here for a handle which is already - * deceased. In that situation we simply do nothing. - */ - return; + /* + * This isn't an error condition. If two or more event + * objects were signalled during the same select operation, + * and processing of the first caused the second handle to + * be closed, then it will sometimes happen that we receive + * an event notification here for a handle which is already + * deceased. In that situation we simply do nothing. + */ + return; } if (h->u.g.moribund) { - /* - * A moribund handle is one which we have either already - * signalled to die, or are waiting until its current I/O op - * completes to do so. Either way, it's treated as already - * dead from the external user's point of view, so we ignore - * the actual I/O result. We just signal the thread to die if - * we haven't yet done so, or destroy the handle if not. - */ - if (h->u.g.done) { - handle_destroy(h); - } else { - h->u.g.done = true; - h->u.g.busy = true; - SetEvent(h->u.g.ev_from_main); - } - return; + /* + * A moribund handle is one which we have either already + * signalled to die, or are waiting until its current I/O op + * completes to do so. Either way, it's treated as already + * dead from the external user's point of view, so we ignore + * the actual I/O result. We just signal the thread to die if + * we haven't yet done so, or destroy the handle if not. + */ + if (h->u.g.done) { + handle_destroy(h); + } else { + h->u.g.done = true; + h->u.g.busy = true; + SetEvent(h->u.g.ev_from_main); + } + return; } switch (h->type) { - int backlog; + int backlog; case HT_INPUT: - h->u.i.busy = false; + h->u.i.busy = false; - /* - * A signal on an input handle means data has arrived. - */ - if (h->u.i.len == 0) { - /* - * EOF, or (nearly equivalently) read error. - */ - h->u.i.defunct = true; - h->u.i.gotdata(h, NULL, 0, h->u.i.readerr); - } else { - backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len, 0); - handle_throttle(&h->u.i, backlog); - } + /* + * A signal on an input handle means data has arrived. + */ + if (h->u.i.len == 0) { + /* + * EOF, or (nearly equivalently) read error. + */ + h->u.i.defunct = true; + h->u.i.gotdata(h, NULL, 0, h->u.i.readerr); + } else { + backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len, 0); + handle_throttle(&h->u.i, backlog); + } break; case HT_OUTPUT: - h->u.o.busy = false; + h->u.o.busy = false; - /* - * A signal on an output handle means we have completed a - * write. Call the callback to indicate that the output - * buffer size has decreased, or to indicate an error. - */ - if (h->u.o.writeerr) { - /* - * Write error. Send a negative value to the callback, - * and mark the thread as defunct (because the output - * thread is terminating by now). - */ - h->u.o.defunct = true; - h->u.o.sentdata(h, 0, h->u.o.writeerr); - } else { - bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten); + /* + * A signal on an output handle means we have completed a + * write. Call the callback to indicate that the output + * buffer size has decreased, or to indicate an error. + */ + if (h->u.o.writeerr) { + /* + * Write error. Send a negative value to the callback, + * and mark the thread as defunct (because the output + * thread is terminating by now). + */ + h->u.o.defunct = true; + h->u.o.sentdata(h, 0, h->u.o.writeerr); + } else { + bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten); noise_ultralight(NOISE_SOURCE_IOLEN, h->u.o.lenwritten); - h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data), 0); - handle_try_output(&h->u.o); - } + h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data), 0); + handle_try_output(&h->u.o); + } break; case HT_FOREIGN: diff --git a/windows/winhsock.c b/windows/winhsock.c index aa3b5a9f..49529444 100644 --- a/windows/winhsock.c +++ b/windows/winhsock.c @@ -51,11 +51,11 @@ static size_t handle_gotdata( HandleSocket *hs = (HandleSocket *)handle_get_privdata(h); if (err) { - plug_closing(hs->plug, "Read error from handle", 0, 0); - return 0; + plug_closing(hs->plug, "Read error from handle", 0, 0); + return 0; } else if (len == 0) { - plug_closing(hs->plug, NULL, 0, 0); - return 0; + plug_closing(hs->plug, NULL, 0, 0); + return 0; } else { assert(hs->frozen != FROZEN && hs->frozen != THAWING); if (hs->frozen == FREEZING) { @@ -75,7 +75,7 @@ static size_t handle_gotdata( return INT_MAX; } else { plug_receive(hs->plug, 0, data, len); - return 0; + return 0; } } } @@ -108,7 +108,7 @@ static Plug *sk_handle_plug(Socket *s, Plug *p) HandleSocket *hs = container_of(s, HandleSocket, sock); Plug *ret = hs->plug; if (p) - hs->plug = p; + hs->plug = p; return ret; } diff --git a/windows/winjump.c b/windows/winjump.c index d33b5ce0..595bbe08 100644 --- a/windows/winjump.c +++ b/windows/winjump.c @@ -738,7 +738,7 @@ bool set_explicit_app_user_model_id(void) { if (p_SetCurrentProcessExplicitAppUserModelID(L"SimonTatham.PuTTY") == S_OK) { - return true; + return true; } return false; } diff --git a/windows/winmisc.c b/windows/winmisc.c index 00b2fcd2..9ccb65fd 100644 --- a/windows/winmisc.c +++ b/windows/winmisc.c @@ -73,62 +73,62 @@ char *get_username(void) char *user; bool got_username = false; DECL_WINDOWS_FUNCTION(static, BOOLEAN, GetUserNameExA, - (EXTENDED_NAME_FORMAT, LPSTR, PULONG)); + (EXTENDED_NAME_FORMAT, LPSTR, PULONG)); { - static bool tried_usernameex = false; - if (!tried_usernameex) { - /* Not available on Win9x, so load dynamically */ - HMODULE secur32 = load_system32_dll("secur32.dll"); - /* If MIT Kerberos is installed, the following call to - GET_WINDOWS_FUNCTION makes Windows implicitly load - sspicli.dll WITHOUT proper path sanitizing, so better - load it properly before */ - HMODULE sspicli = load_system32_dll("sspicli.dll"); + static bool tried_usernameex = false; + if (!tried_usernameex) { + /* Not available on Win9x, so load dynamically */ + HMODULE secur32 = load_system32_dll("secur32.dll"); + /* If MIT Kerberos is installed, the following call to + GET_WINDOWS_FUNCTION makes Windows implicitly load + sspicli.dll WITHOUT proper path sanitizing, so better + load it properly before */ + HMODULE sspicli = load_system32_dll("sspicli.dll"); (void)sspicli; /* squash compiler warning about unused variable */ - GET_WINDOWS_FUNCTION(secur32, GetUserNameExA); - tried_usernameex = true; - } + GET_WINDOWS_FUNCTION(secur32, GetUserNameExA); + tried_usernameex = true; + } } if (p_GetUserNameExA) { - /* - * If available, use the principal -- this avoids the problem - * that the local username is case-insensitive but Kerberos - * usernames are case-sensitive. - */ + /* + * If available, use the principal -- this avoids the problem + * that the local username is case-insensitive but Kerberos + * usernames are case-sensitive. + */ - /* Get the length */ - namelen = 0; - (void) p_GetUserNameExA(NameUserPrincipal, NULL, &namelen); + /* Get the length */ + namelen = 0; + (void) p_GetUserNameExA(NameUserPrincipal, NULL, &namelen); - user = snewn(namelen, char); - got_username = p_GetUserNameExA(NameUserPrincipal, user, &namelen); - if (got_username) { - char *p = strchr(user, '@'); - if (p) *p = 0; - } else { - sfree(user); - } + user = snewn(namelen, char); + got_username = p_GetUserNameExA(NameUserPrincipal, user, &namelen); + if (got_username) { + char *p = strchr(user, '@'); + if (p) *p = 0; + } else { + sfree(user); + } } if (!got_username) { - /* Fall back to local user name */ - namelen = 0; - if (!GetUserName(NULL, &namelen)) { - /* - * Apparently this doesn't work at least on Windows XP SP2. - * Thus assume a maximum of 256. It will fail again if it - * doesn't fit. - */ - namelen = 256; - } + /* Fall back to local user name */ + namelen = 0; + if (!GetUserName(NULL, &namelen)) { + /* + * Apparently this doesn't work at least on Windows XP SP2. + * Thus assume a maximum of 256. It will fail again if it + * doesn't fit. + */ + namelen = 256; + } - user = snewn(namelen, char); - got_username = GetUserName(user, &namelen); - if (!got_username) { - sfree(user); - } + user = snewn(namelen, char); + got_username = GetUserName(user, &namelen); + if (!got_username) { + sfree(user); + } } return got_username ? user : NULL; @@ -372,35 +372,35 @@ void escape_registry_key(const char *in, strbuf *out) static const char hex[16] = "0123456789ABCDEF"; while (*in) { - if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' || - *in == '%' || *in < ' ' || *in > '~' || (*in == '.' - && !candot)) { + if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' || + *in == '%' || *in < ' ' || *in > '~' || (*in == '.' + && !candot)) { put_byte(out, '%'); - put_byte(out, hex[((unsigned char) *in) >> 4]); - put_byte(out, hex[((unsigned char) *in) & 15]); - } else - put_byte(out, *in); - in++; - candot = true; + put_byte(out, hex[((unsigned char) *in) >> 4]); + put_byte(out, hex[((unsigned char) *in) & 15]); + } else + put_byte(out, *in); + in++; + candot = true; } } void unescape_registry_key(const char *in, strbuf *out) { while (*in) { - if (*in == '%' && in[1] && in[2]) { - int i, j; + 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); - put_byte(out, (i << 4) + j); - in += 3; - } else { + put_byte(out, (i << 4) + j); + in += 3; + } else { put_byte(out, *in++); - } + } } } @@ -414,17 +414,17 @@ void dputs(const char *buf) DWORD dw; if (!debug_got_console) { - if (AllocConsole()) { - debug_got_console = 1; - debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE); - } + if (AllocConsole()) { + debug_got_console = 1; + debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE); + } } if (!debug_fp) { - debug_fp = fopen("debug.log", "w"); + debug_fp = fopen("debug.log", "w"); } if (debug_hdl != INVALID_HANDLE_VALUE) { - WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL); + WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL); } fputs(buf, debug_fp); fflush(debug_fp); diff --git a/windows/winmiscs.c b/windows/winmiscs.c index d1662330..73e4f868 100644 --- a/windows/winmiscs.c +++ b/windows/winmiscs.c @@ -25,15 +25,15 @@ void smemclr(void *b, size_t n) { /* * Design: - * + * * We start by reserving as much virtual address space as Windows * will sensibly (or not sensibly) let us have. We flag it all as * invalid memory. - * + * * Any allocation attempt is satisfied by committing one or more * pages, with an uncommitted page on either side. The returned * memory region is jammed up against the _end_ of the pages. - * + * * Freeing anything causes instantaneous decommitment of the pages * involved, so stale pointers are caught as soon as possible. */ @@ -59,10 +59,10 @@ static void minefield_init(void) 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; + minefield_region = VirtualAlloc(NULL, size, + MEM_RESERVE, PAGE_NOACCESS); + if (minefield_region) + break; } minefield_size = size; @@ -80,13 +80,13 @@ static void minefield_init(void) * 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. @@ -119,27 +119,27 @@ 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; @@ -156,13 +156,13 @@ static void *minefield_alloc(int size) * 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[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); + MEM_COMMIT, PAGE_READWRITE); return (char *) minefield_pages + region_start; } @@ -175,10 +175,10 @@ static void minefield_free(void *ptr) 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); @@ -195,8 +195,8 @@ static int minefield_get_size(void *ptr) 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); @@ -207,14 +207,14 @@ static int minefield_get_size(void *ptr) void *minefield_c_malloc(size_t size) { if (!minefield_initialised) - minefield_init(); + minefield_init(); return minefield_alloc(size); } void minefield_c_free(void *p) { if (!minefield_initialised) - minefield_init(); + minefield_init(); minefield_free(p); } @@ -227,7 +227,7 @@ void *minefield_c_realloc(void *p, size_t size) size_t oldsize; void *q; if (!minefield_initialised) - minefield_init(); + minefield_init(); q = minefield_alloc(size); oldsize = minefield_get_size(p); memcpy(q, p, (oldsize < size ? oldsize : size)); @@ -235,7 +235,7 @@ void *minefield_c_realloc(void *p, size_t size) return q; } -#endif /* MINEFIELD */ +#endif /* MINEFIELD */ #if defined _MSC_VER && _MSC_VER < 1800 diff --git a/windows/winnet.c b/windows/winnet.c index 14513621..5a8b5d35 100644 --- a/windows/winnet.c +++ b/windows/winnet.c @@ -32,7 +32,7 @@ const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; #endif #define ipv4_is_loopback(addr) \ - ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L) + ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L) /* * Mutable state that goes with a SockAddr: stores information @@ -42,7 +42,7 @@ const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; typedef struct SockAddrStep_tag SockAddrStep; struct SockAddrStep_tag { #ifndef NO_IPV6 - struct addrinfo *ai; /* steps along addr->ais */ + struct addrinfo *ai; /* steps along addr->ais */ #endif int curraddr; }; @@ -85,11 +85,11 @@ struct SockAddr { bool namedpipe; /* indicates that this SockAddr is phony, holding a Windows * named pipe pathname instead of a network address */ #ifndef NO_IPV6 - struct addrinfo *ais; /* Addresses IPv6 style. */ + struct addrinfo *ais; /* Addresses IPv6 style. */ #endif - unsigned long *addresses; /* Addresses IPv4 style. */ + unsigned long *addresses; /* Addresses IPv4 style. */ int naddresses; - char hostname[512]; /* Store an unresolved host name. */ + char hostname[512]; /* Store an unresolved host name. */ }; /* @@ -126,13 +126,13 @@ static int cmpfortree(void *av, void *bv) NetSocket *a = (NetSocket *)av, *b = (NetSocket *)bv; uintptr_t as = (uintptr_t) a->s, bs = (uintptr_t) b->s; if (as < bs) - return -1; + return -1; if (as > bs) - return +1; + return +1; if (a < b) - return -1; + return -1; if (a > b) - return +1; + return +1; return 0; } @@ -141,9 +141,9 @@ static int cmpforsearch(void *av, void *bv) NetSocket *b = (NetSocket *)bv; uintptr_t as = (uintptr_t) av, bs = (uintptr_t) b->s; if (as < bs) - return -1; + return -1; if (as > bs) - return +1; + return +1; return 0; } @@ -156,47 +156,47 @@ DECL_WINDOWS_FUNCTION(static, u_short, htons, (u_short)); DECL_WINDOWS_FUNCTION(static, u_short, ntohs, (u_short)); DECL_WINDOWS_FUNCTION(static, int, gethostname, (char *, int)); DECL_WINDOWS_FUNCTION(static, struct hostent FAR *, gethostbyname, - (const char FAR *)); + (const char FAR *)); DECL_WINDOWS_FUNCTION(static, struct servent FAR *, getservbyname, - (const char FAR *, const char FAR *)); + (const char FAR *, const char FAR *)); DECL_WINDOWS_FUNCTION(static, unsigned long, inet_addr, (const char FAR *)); DECL_WINDOWS_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr)); DECL_WINDOWS_FUNCTION(static, const char FAR *, inet_ntop, (int, void FAR *, char *, size_t)); DECL_WINDOWS_FUNCTION(static, int, connect, - (SOCKET, const struct sockaddr FAR *, int)); + (SOCKET, const struct sockaddr FAR *, int)); DECL_WINDOWS_FUNCTION(static, int, bind, - (SOCKET, const struct sockaddr FAR *, int)); + (SOCKET, const struct sockaddr FAR *, int)); DECL_WINDOWS_FUNCTION(static, int, setsockopt, - (SOCKET, int, int, const char FAR *, int)); + (SOCKET, int, int, const char FAR *, int)); DECL_WINDOWS_FUNCTION(static, SOCKET, socket, (int, int, int)); DECL_WINDOWS_FUNCTION(static, int, listen, (SOCKET, int)); DECL_WINDOWS_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int)); DECL_WINDOWS_FUNCTION(static, int, shutdown, (SOCKET, int)); DECL_WINDOWS_FUNCTION(static, int, ioctlsocket, - (SOCKET, long, u_long FAR *)); + (SOCKET, long, u_long FAR *)); DECL_WINDOWS_FUNCTION(static, SOCKET, accept, - (SOCKET, struct sockaddr FAR *, int FAR *)); + (SOCKET, struct sockaddr FAR *, int FAR *)); DECL_WINDOWS_FUNCTION(static, int, getpeername, - (SOCKET, struct sockaddr FAR *, int FAR *)); + (SOCKET, struct sockaddr FAR *, int FAR *)); DECL_WINDOWS_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int)); DECL_WINDOWS_FUNCTION(static, int, WSAIoctl, - (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, - LPDWORD, LPWSAOVERLAPPED, - LPWSAOVERLAPPED_COMPLETION_ROUTINE)); + (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, + LPDWORD, LPWSAOVERLAPPED, + LPWSAOVERLAPPED_COMPLETION_ROUTINE)); #ifndef NO_IPV6 DECL_WINDOWS_FUNCTION(static, int, getaddrinfo, - (const char *nodename, const char *servname, - const struct addrinfo *hints, struct addrinfo **res)); + (const char *nodename, const char *servname, + const struct addrinfo *hints, struct addrinfo **res)); DECL_WINDOWS_FUNCTION(static, void, freeaddrinfo, (struct addrinfo *res)); DECL_WINDOWS_FUNCTION(static, int, getnameinfo, - (const struct sockaddr FAR * sa, socklen_t salen, - char FAR * host, DWORD hostlen, char FAR * serv, - DWORD servlen, int flags)); + (const struct sockaddr FAR * sa, socklen_t salen, + char FAR * host, DWORD hostlen, char FAR * serv, + DWORD servlen, int flags)); DECL_WINDOWS_FUNCTION(static, char *, gai_strerror, (int ecode)); DECL_WINDOWS_FUNCTION(static, int, WSAAddressToStringA, - (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO, - LPSTR, LPDWORD)); + (LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFO, + LPSTR, LPDWORD)); #endif static HMODULE winsock_module = NULL; @@ -213,11 +213,11 @@ static bool sk_startup(int hi, int lo) winsock_ver = MAKEWORD(hi, lo); if (p_WSAStartup(winsock_ver, &wsadata)) { - return false; + return false; } if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) { - return false; + return false; } return true; @@ -227,8 +227,8 @@ static bool sk_startup(int hi, int lo) * defined alongside all the others by PUTTY_DO_GLOBALS because of the * annoying winelib header-ordering issue. (See comment in winstuff.h.) */ DECL_WINDOWS_FUNCTION(/* empty */, int, select, - (int, fd_set FAR *, fd_set FAR *, - fd_set FAR *, const struct timeval FAR *)); + (int, fd_set FAR *, fd_set FAR *, + fd_set FAR *, const struct timeval FAR *)); void sk_init(void) { @@ -237,32 +237,32 @@ void sk_init(void) #endif winsock_module = load_system32_dll("ws2_32.dll"); if (!winsock_module) { - winsock_module = load_system32_dll("wsock32.dll"); + winsock_module = load_system32_dll("wsock32.dll"); } if (!winsock_module) - modalfatalbox("Unable to load any WinSock library"); + modalfatalbox("Unable to load any WinSock library"); #ifndef NO_IPV6 /* Check if we have getaddrinfo in Winsock */ if (GetProcAddress(winsock_module, "getaddrinfo") != NULL) { - GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo); - GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo); - GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, getnameinfo); + GET_WINDOWS_FUNCTION(winsock_module, getaddrinfo); + GET_WINDOWS_FUNCTION(winsock_module, freeaddrinfo); + GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, getnameinfo); /* This function would fail its type-check if we did one, * because the VS header file provides an inline definition * which is __cdecl instead of WINAPI. */ GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, gai_strerror); } else { - /* Fall back to wship6.dll for Windows 2000 */ - wship6_module = load_system32_dll("wship6.dll"); - if (wship6_module) { - GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo); - GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo); + /* Fall back to wship6.dll for Windows 2000 */ + wship6_module = load_system32_dll("wship6.dll"); + if (wship6_module) { + GET_WINDOWS_FUNCTION(wship6_module, getaddrinfo); + GET_WINDOWS_FUNCTION(wship6_module, freeaddrinfo); /* See comment above about type check */ - GET_WINDOWS_FUNCTION_NO_TYPECHECK(wship6_module, getnameinfo); + GET_WINDOWS_FUNCTION_NO_TYPECHECK(wship6_module, getnameinfo); GET_WINDOWS_FUNCTION_NO_TYPECHECK(winsock_module, gai_strerror); - } else { - } + } else { + } } GET_WINDOWS_FUNCTION(winsock2_module, WSAAddressToStringA); #endif @@ -320,9 +320,9 @@ void sk_init(void) /* Try to get the best WinSock version we can get */ if (!sk_startup(2,2) && - !sk_startup(2,0) && - !sk_startup(1,1)) { - modalfatalbox("Unable to initialise WinSock"); + !sk_startup(2,0) && + !sk_startup(1,1)) { + modalfatalbox("Unable to initialise WinSock"); } sktree = newtree234(cmpfortree); @@ -334,20 +334,20 @@ void sk_cleanup(void) int i; if (sktree) { - for (i = 0; (s = index234(sktree, i)) != NULL; i++) { - p_closesocket(s->s); - } - freetree234(sktree); - sktree = NULL; + for (i = 0; (s = index234(sktree, i)) != NULL; i++) { + p_closesocket(s->s); + } + freetree234(sktree); + sktree = NULL; } if (p_WSACleanup) - p_WSACleanup(); + p_WSACleanup(); if (winsock_module) - FreeLibrary(winsock_module); + FreeLibrary(winsock_module); #ifndef NO_IPV6 if (wship6_module) - FreeLibrary(wship6_module); + FreeLibrary(wship6_module); #endif } @@ -359,76 +359,76 @@ const char *winsock_error_string(int error) */ switch (error) { case WSAEACCES: - return "Network error: Permission denied"; + return "Network error: Permission denied"; case WSAEADDRINUSE: - return "Network error: Address already in use"; + return "Network error: Address already in use"; case WSAEADDRNOTAVAIL: - return "Network error: Cannot assign requested address"; + return "Network error: Cannot assign requested address"; case WSAEAFNOSUPPORT: - return - "Network error: Address family not supported by protocol family"; + return + "Network error: Address family not supported by protocol family"; case WSAEALREADY: - return "Network error: Operation already in progress"; + return "Network error: Operation already in progress"; case WSAECONNABORTED: - return "Network error: Software caused connection abort"; + return "Network error: Software caused connection abort"; case WSAECONNREFUSED: - return "Network error: Connection refused"; + return "Network error: Connection refused"; case WSAECONNRESET: - return "Network error: Connection reset by peer"; + return "Network error: Connection reset by peer"; case WSAEDESTADDRREQ: - return "Network error: Destination address required"; + return "Network error: Destination address required"; case WSAEFAULT: - return "Network error: Bad address"; + return "Network error: Bad address"; case WSAEHOSTDOWN: - return "Network error: Host is down"; + return "Network error: Host is down"; case WSAEHOSTUNREACH: - return "Network error: No route to host"; + return "Network error: No route to host"; case WSAEINPROGRESS: - return "Network error: Operation now in progress"; + return "Network error: Operation now in progress"; case WSAEINTR: - return "Network error: Interrupted function call"; + return "Network error: Interrupted function call"; case WSAEINVAL: - return "Network error: Invalid argument"; + return "Network error: Invalid argument"; case WSAEISCONN: - return "Network error: Socket is already connected"; + return "Network error: Socket is already connected"; case WSAEMFILE: - return "Network error: Too many open files"; + return "Network error: Too many open files"; case WSAEMSGSIZE: - return "Network error: Message too long"; + return "Network error: Message too long"; case WSAENETDOWN: - return "Network error: Network is down"; + return "Network error: Network is down"; case WSAENETRESET: - return "Network error: Network dropped connection on reset"; + return "Network error: Network dropped connection on reset"; case WSAENETUNREACH: - return "Network error: Network is unreachable"; + return "Network error: Network is unreachable"; case WSAENOBUFS: - return "Network error: No buffer space available"; + return "Network error: No buffer space available"; case WSAENOPROTOOPT: - return "Network error: Bad protocol option"; + return "Network error: Bad protocol option"; case WSAENOTCONN: - return "Network error: Socket is not connected"; + return "Network error: Socket is not connected"; case WSAENOTSOCK: - return "Network error: Socket operation on non-socket"; + return "Network error: Socket operation on non-socket"; case WSAEOPNOTSUPP: - return "Network error: Operation not supported"; + return "Network error: Operation not supported"; case WSAEPFNOSUPPORT: - return "Network error: Protocol family not supported"; + return "Network error: Protocol family not supported"; case WSAEPROCLIM: - return "Network error: Too many processes"; + return "Network error: Too many processes"; case WSAEPROTONOSUPPORT: - return "Network error: Protocol not supported"; + return "Network error: Protocol not supported"; case WSAEPROTOTYPE: - return "Network error: Protocol wrong type for socket"; + return "Network error: Protocol wrong type for socket"; case WSAESHUTDOWN: - return "Network error: Cannot send after socket shutdown"; + return "Network error: Cannot send after socket shutdown"; case WSAESOCKTNOSUPPORT: - return "Network error: Socket type not supported"; + return "Network error: Socket type not supported"; case WSAETIMEDOUT: - return "Network error: Connection timed out"; + return "Network error: Connection timed out"; case WSAEWOULDBLOCK: - return "Network error: Resource temporarily unavailable"; + return "Network error: Resource temporarily unavailable"; case WSAEDISCON: - return "Network error: Graceful shutdown in progress"; + return "Network error: Graceful shutdown in progress"; } /* @@ -448,9 +448,9 @@ SockAddr *sk_namelookup(const char *host, char **canonicalname, /* Default to IPv4. */ hint_family = (address_family == ADDRTYPE_IPV4 ? AF_INET : #ifndef NO_IPV6 - address_family == ADDRTYPE_IPV6 ? AF_INET6 : + address_family == ADDRTYPE_IPV6 ? AF_INET6 : #endif - AF_UNSPEC); + AF_UNSPEC); /* Clear the structure and default to IPv4. */ memset(ret, 0, sizeof(SockAddr)); @@ -464,91 +464,91 @@ SockAddr *sk_namelookup(const char *host, char **canonicalname, *realhost = '\0'; if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) { - struct hostent *h = NULL; - int err = 0; + struct hostent *h = NULL; + int err = 0; #ifndef NO_IPV6 - /* - * Use getaddrinfo when it's available - */ - if (p_getaddrinfo) { - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = hint_family; - hints.ai_flags = AI_CANONNAME; + /* + * Use getaddrinfo when it's available + */ + if (p_getaddrinfo) { + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = hint_family; + hints.ai_flags = AI_CANONNAME; { /* strip [] on IPv6 address literals */ char *trimmed_host = host_strduptrim(host); err = p_getaddrinfo(trimmed_host, NULL, &hints, &ret->ais); sfree(trimmed_host); } - if (err == 0) - ret->resolved = true; - } else + if (err == 0) + ret->resolved = true; + } else #endif - { - /* - * Otherwise use the IPv4-only gethostbyname... - * (NOTE: we don't use gethostbyname as a fallback!) - */ - if ( (h = p_gethostbyname(host)) ) - ret->resolved = true; - else - err = p_WSAGetLastError(); - } + { + /* + * Otherwise use the IPv4-only gethostbyname... + * (NOTE: we don't use gethostbyname as a fallback!) + */ + if ( (h = p_gethostbyname(host)) ) + ret->resolved = true; + else + err = p_WSAGetLastError(); + } - if (!ret->resolved) { - ret->error = (err == WSAENETDOWN ? "Network is down" : - err == WSAHOST_NOT_FOUND ? "Host does not exist" : - err == WSATRY_AGAIN ? "Host not found" : + if (!ret->resolved) { + ret->error = (err == WSAENETDOWN ? "Network is down" : + err == WSAHOST_NOT_FOUND ? "Host does not exist" : + err == WSATRY_AGAIN ? "Host not found" : #ifndef NO_IPV6 - p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) : + p_getaddrinfo&&p_gai_strerror ? p_gai_strerror(err) : #endif - "gethostbyname: unknown error"); - } else { - ret->error = NULL; + "gethostbyname: unknown error"); + } else { + ret->error = NULL; #ifndef NO_IPV6 - /* If we got an address info use that... */ - if (ret->ais) { - /* 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->ais->ai_family == AF_INET) - memcpy(&a, - (char *) &((SOCKADDR_IN *) ret->ais-> - ai_addr)->sin_addr, sizeof(a)); + /* If we got an address info use that... */ + if (ret->ais) { + /* 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->ais->ai_family == AF_INET) + memcpy(&a, + (char *) &((SOCKADDR_IN *) ret->ais-> + ai_addr)->sin_addr, sizeof(a)); - if (ret->ais->ai_canonname) - strncpy(realhost, ret->ais->ai_canonname, lenof(realhost)); - else - strncpy(realhost, host, lenof(realhost)); - } - /* We used the IPv4-only gethostbyname()... */ - else + if (ret->ais->ai_canonname) + strncpy(realhost, ret->ais->ai_canonname, lenof(realhost)); + else + strncpy(realhost, host, lenof(realhost)); + } + /* We used the IPv4-only gethostbyname()... */ + else #endif - { - int n; - for (n = 0; h->h_addr_list[n]; n++); - ret->addresses = snewn(n, unsigned long); - ret->naddresses = n; - for (n = 0; n < ret->naddresses; n++) { - memcpy(&a, h->h_addr_list[n], sizeof(a)); - ret->addresses[n] = p_ntohl(a); - } - memcpy(&a, h->h_addr, sizeof(a)); - /* This way we are always sure the h->h_name is valid :) */ - strncpy(realhost, h->h_name, sizeof(realhost)); - } - } + { + int n; + for (n = 0; h->h_addr_list[n]; n++); + ret->addresses = snewn(n, unsigned long); + ret->naddresses = n; + for (n = 0; n < ret->naddresses; n++) { + memcpy(&a, h->h_addr_list[n], sizeof(a)); + ret->addresses[n] = p_ntohl(a); + } + memcpy(&a, h->h_addr, sizeof(a)); + /* This way we are always sure the h->h_name is valid :) */ + strncpy(realhost, h->h_name, sizeof(realhost)); + } + } } else { - /* - * This must be a numeric IPv4 address because it caused a - * success return from inet_addr. - */ - ret->addresses = snewn(1, unsigned long); - ret->naddresses = 1; - ret->addresses[0] = p_ntohl(a); - ret->resolved = true; - strncpy(realhost, host, sizeof(realhost)); + /* + * This must be a numeric IPv4 address because it caused a + * success return from inet_addr. + */ + ret->addresses = snewn(1, unsigned long); + ret->naddresses = 1; + ret->addresses[0] = p_ntohl(a); + ret->resolved = true; + strncpy(realhost, host, sizeof(realhost)); } realhost[lenof(realhost)-1] = '\0'; *canonicalname = snewn(1+strlen(realhost), char); @@ -594,18 +594,18 @@ static bool sk_nextaddr(SockAddr *addr, SockAddrStep *step) { #ifndef NO_IPV6 if (step->ai) { - if (step->ai->ai_next) { - step->ai = step->ai->ai_next; - return true; - } else - return false; + if (step->ai->ai_next) { + step->ai = step->ai->ai_next; + return true; + } else + return false; } #endif if (step->curraddr+1 < addr->naddresses) { - step->curraddr++; - return true; + step->curraddr++; + return true; } else { - return false; + return false; } } @@ -616,30 +616,30 @@ void sk_getaddr(SockAddr *addr, char *buf, int buflen) #ifndef NO_IPV6 if (step.ai) { - int err = 0; - if (p_WSAAddressToStringA) { - DWORD dwbuflen = buflen; - err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen, - NULL, buf, &dwbuflen); - } else - err = -1; - if (err) { - strncpy(buf, addr->hostname, buflen); - if (!buf[0]) - strncpy(buf, "", buflen); - buf[buflen-1] = '\0'; - } + int err = 0; + if (p_WSAAddressToStringA) { + DWORD dwbuflen = buflen; + err = p_WSAAddressToStringA(step.ai->ai_addr, step.ai->ai_addrlen, + NULL, buf, &dwbuflen); + } else + err = -1; + if (err) { + strncpy(buf, addr->hostname, buflen); + if (!buf[0]) + strncpy(buf, "", buflen); + buf[buflen-1] = '\0'; + } } else #endif if (SOCKADDR_FAMILY(addr, step) == AF_INET) { - struct in_addr a; - assert(addr->addresses && step.curraddr < addr->naddresses); - a.s_addr = p_htonl(addr->addresses[step.curraddr]); - strncpy(buf, p_inet_ntoa(a), buflen); - buf[buflen-1] = '\0'; + struct in_addr a; + assert(addr->addresses && step.curraddr < addr->naddresses); + a.s_addr = p_htonl(addr->addresses[step.curraddr]); + strncpy(buf, p_inet_ntoa(a), buflen); + buf[buflen-1] = '\0'; } else { - strncpy(buf, addr->hostname, buflen); - buf[buflen-1] = '\0'; + strncpy(buf, addr->hostname, buflen); + buf[buflen-1] = '\0'; } } @@ -680,8 +680,8 @@ bool sk_addr_needs_port(SockAddr *addr) bool sk_hostname_is_local(const char *name) { return !strcmp(name, "localhost") || - !strcmp(name, "::1") || - !strncmp(name, "127.", 4); + !strcmp(name, "::1") || + !strncmp(name, "127.", 4); } static INTERFACE_INFO local_interfaces[16]; @@ -690,29 +690,29 @@ static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */ static bool ipv4_is_local_addr(struct in_addr addr) { if (ipv4_is_loopback(addr)) - return true; /* loopback addresses are local */ + return true; /* loopback addresses are local */ if (!n_local_interfaces) { - SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0); - DWORD retbytes; + SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0); + DWORD retbytes; - SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); - if (p_WSAIoctl && - p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0, - local_interfaces, sizeof(local_interfaces), - &retbytes, NULL, NULL) == 0) - n_local_interfaces = retbytes / sizeof(INTERFACE_INFO); - else + if (p_WSAIoctl && + p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0, + local_interfaces, sizeof(local_interfaces), + &retbytes, NULL, NULL) == 0) + n_local_interfaces = retbytes / sizeof(INTERFACE_INFO); + else n_local_interfaces = -1; } if (n_local_interfaces > 0) { - int i; - for (i = 0; i < n_local_interfaces; i++) { - SOCKADDR_IN *address = - (SOCKADDR_IN *)&local_interfaces[i].iiAddress; - if (address->sin_addr.s_addr == addr.s_addr) - return true; /* this address is local */ - } + int i; + for (i = 0; i < n_local_interfaces; i++) { + SOCKADDR_IN *address = + (SOCKADDR_IN *)&local_interfaces[i].iiAddress; + if (address->sin_addr.s_addr == addr.s_addr) + return true; /* this address is local */ + } } return false; /* this address is not local */ } @@ -726,25 +726,25 @@ bool sk_address_is_local(SockAddr *addr) #ifndef NO_IPV6 if (family == AF_INET6) { - return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr); + return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr); } else #endif if (family == AF_INET) { #ifndef NO_IPV6 - if (step.ai) { - return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr) - ->sin_addr); - } else + if (step.ai) { + return ipv4_is_local_addr(((struct sockaddr_in *)step.ai->ai_addr) + ->sin_addr); + } else #endif - { - struct in_addr a; - assert(addr->addresses && step.curraddr < addr->naddresses); - a.s_addr = p_htonl(addr->addresses[step.curraddr]); - return ipv4_is_local_addr(a); - } + { + struct in_addr a; + assert(addr->addresses && step.curraddr < addr->naddresses); + a.s_addr = p_htonl(addr->addresses[step.curraddr]); + return ipv4_is_local_addr(a); + } } else { - assert(family == AF_UNSPEC); - return false; /* we don't know; assume not */ + assert(family == AF_UNSPEC); + return false; /* we don't know; assume not */ } } @@ -762,9 +762,9 @@ int sk_addrtype(SockAddr *addr) return (family == AF_INET ? ADDRTYPE_IPV4 : #ifndef NO_IPV6 - family == AF_INET6 ? ADDRTYPE_IPV6 : + family == AF_INET6 ? ADDRTYPE_IPV6 : #endif - ADDRTYPE_NAME); + ADDRTYPE_NAME); } void sk_addrcopy(SockAddr *addr, char *buf) @@ -777,34 +777,34 @@ void sk_addrcopy(SockAddr *addr, char *buf) assert(family != AF_UNSPEC); #ifndef NO_IPV6 if (step.ai) { - if (family == AF_INET) - memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr, - sizeof(struct in_addr)); - else if (family == AF_INET6) - memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr, - sizeof(struct in6_addr)); - else - unreachable("bad address family in sk_addrcopy"); + if (family == AF_INET) + memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr, + sizeof(struct in_addr)); + else if (family == AF_INET6) + memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr, + sizeof(struct in6_addr)); + else + unreachable("bad address family in sk_addrcopy"); } else #endif if (family == AF_INET) { - struct in_addr a; - assert(addr->addresses && step.curraddr < addr->naddresses); - a.s_addr = p_htonl(addr->addresses[step.curraddr]); - memcpy(buf, (char*) &a.s_addr, 4); + struct in_addr a; + assert(addr->addresses && step.curraddr < addr->naddresses); + a.s_addr = p_htonl(addr->addresses[step.curraddr]); + memcpy(buf, (char*) &a.s_addr, 4); } } void sk_addr_free(SockAddr *addr) { if (--addr->refcount > 0) - return; + return; #ifndef NO_IPV6 if (addr->ais && p_freeaddrinfo) - p_freeaddrinfo(addr->ais); + p_freeaddrinfo(addr->ais); #endif if (addr->addresses) - sfree(addr->addresses); + sfree(addr->addresses); sfree(addr); } @@ -819,7 +819,7 @@ static Plug *sk_net_plug(Socket *sock, Plug *p) NetSocket *s = container_of(sock, NetSocket, sock); Plug *ret = s->plug; if (p) - s->plug = p; + s->plug = p; return ret; } @@ -869,9 +869,9 @@ static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug) ret->s = (SOCKET)ctx.p; if (ret->s == INVALID_SOCKET) { - err = p_WSAGetLastError(); - ret->error = winsock_error_string(err); - return &ret->sock; + err = p_WSAGetLastError(); + ret->error = winsock_error_string(err); + return &ret->sock; } ret->oobinline = false; @@ -880,8 +880,8 @@ static Socket *sk_net_accept(accept_ctx_t ctx, Plug *plug) * window, or an EventSelect on an event object. */ errstr = do_select(ret->s, true); if (errstr) { - ret->error = errstr; - return &ret->sock; + ret->error = errstr; + return &ret->sock; } add234(sktree, ret); @@ -902,7 +902,7 @@ static DWORD try_connect(NetSocket *sock) int family; if (sock->s != INVALID_SOCKET) { - do_select(sock->s, false); + do_select(sock->s, false); p_closesocket(sock->s); } @@ -929,80 +929,80 @@ static DWORD try_connect(NetSocket *sock) sock->s = s; if (s == INVALID_SOCKET) { - err = p_WSAGetLastError(); - sock->error = winsock_error_string(err); - goto ret; + err = p_WSAGetLastError(); + sock->error = winsock_error_string(err); + goto ret; } - SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); if (sock->oobinline) { - BOOL b = true; - p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b)); + BOOL b = true; + p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b)); } if (sock->nodelay) { - BOOL b = true; - p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b)); + BOOL b = true; + p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b)); } if (sock->keepalive) { - BOOL b = true; - p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b)); + BOOL b = true; + p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b)); } /* * Bind to local address. */ if (sock->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 sockcode; + int sockcode; #ifndef NO_IPV6 - if (family == AF_INET6) { - memset(&a6, 0, sizeof(a6)); - a6.sin6_family = AF_INET6; + if (family == AF_INET6) { + memset(&a6, 0, sizeof(a6)); + a6.sin6_family = AF_INET6; /*a6.sin6_addr = in6addr_any; */ /* == 0 done by memset() */ - a6.sin6_port = p_htons(localport); - } else + a6.sin6_port = p_htons(localport); + } else #endif - { - a.sin_family = AF_INET; - a.sin_addr.s_addr = p_htonl(INADDR_ANY); - a.sin_port = p_htons(localport); - } + { + a.sin_family = AF_INET; + a.sin_addr.s_addr = p_htonl(INADDR_ANY); + a.sin_port = p_htons(localport); + } #ifndef NO_IPV6 - sockcode = p_bind(s, (family == AF_INET6 ? - (struct sockaddr *) &a6 : - (struct sockaddr *) &a), - (family == AF_INET6 ? sizeof(a6) : sizeof(a))); + sockcode = p_bind(s, (family == AF_INET6 ? + (struct sockaddr *) &a6 : + (struct sockaddr *) &a), + (family == AF_INET6 ? sizeof(a6) : sizeof(a))); #else - sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a)); + sockcode = p_bind(s, (struct sockaddr *) &a, sizeof(a)); #endif - if (sockcode != SOCKET_ERROR) { - err = 0; - break; /* done */ - } else { - err = p_WSAGetLastError(); - if (err != WSAEADDRINUSE) /* failed, for a bad reason */ - break; - } + if (sockcode != SOCKET_ERROR) { + err = 0; + break; /* done */ + } else { + err = p_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 (localport == 0) + break; /* we're only looping once */ + localport--; + if (localport == 0) + break; /* we might have got to the end */ } if (err) { - sock->error = winsock_error_string(err); - goto ret; + sock->error = winsock_error_string(err); + goto ret; } /* @@ -1010,64 +1010,64 @@ static DWORD try_connect(NetSocket *sock) */ #ifndef NO_IPV6 if (sock->step.ai) { - if (family == AF_INET6) { - a6.sin6_family = AF_INET6; - a6.sin6_port = p_htons((short) sock->port); - a6.sin6_addr = - ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr; - a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo; - a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id; - } else { - a.sin_family = AF_INET; - a.sin_addr = - ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr; - a.sin_port = p_htons((short) sock->port); - } + if (family == AF_INET6) { + a6.sin6_family = AF_INET6; + a6.sin6_port = p_htons((short) sock->port); + a6.sin6_addr = + ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_addr; + a6.sin6_flowinfo = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_flowinfo; + a6.sin6_scope_id = ((struct sockaddr_in6 *) sock->step.ai->ai_addr)->sin6_scope_id; + } else { + a.sin_family = AF_INET; + a.sin_addr = + ((struct sockaddr_in *) sock->step.ai->ai_addr)->sin_addr; + a.sin_port = p_htons((short) sock->port); + } } else #endif { - assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses); - a.sin_family = AF_INET; - a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]); - a.sin_port = p_htons((short) sock->port); + assert(sock->addr->addresses && sock->step.curraddr < sock->addr->naddresses); + a.sin_family = AF_INET; + a.sin_addr.s_addr = p_htonl(sock->addr->addresses[sock->step.curraddr]); + a.sin_port = p_htons((short) sock->port); } /* Set up a select mechanism. This could be an AsyncSelect on a * window, or an EventSelect on an event object. */ errstr = do_select(s, true); if (errstr) { - sock->error = errstr; - err = 1; - goto ret; + sock->error = errstr; + err = 1; + goto ret; } if (( #ifndef NO_IPV6 - p_connect(s, - ((family == AF_INET6) ? (struct sockaddr *) &a6 : - (struct sockaddr *) &a), - (family == AF_INET6) ? sizeof(a6) : sizeof(a)) + p_connect(s, + ((family == AF_INET6) ? (struct sockaddr *) &a6 : + (struct sockaddr *) &a), + (family == AF_INET6) ? sizeof(a6) : sizeof(a)) #else - p_connect(s, (struct sockaddr *) &a, sizeof(a)) + p_connect(s, (struct sockaddr *) &a, sizeof(a)) #endif - ) == SOCKET_ERROR) { - err = p_WSAGetLastError(); - /* - * We expect a potential EWOULDBLOCK here, because the - * chances are the front end has done a select for - * FD_CONNECT, so that connect() will complete - * asynchronously. - */ - if ( err != WSAEWOULDBLOCK ) { - sock->error = winsock_error_string(err); - goto ret; - } + ) == SOCKET_ERROR) { + err = p_WSAGetLastError(); + /* + * We expect a potential EWOULDBLOCK here, because the + * chances are the front end has done a select for + * FD_CONNECT, so that connect() will complete + * asynchronously. + */ + if ( err != WSAEWOULDBLOCK ) { + sock->error = winsock_error_string(err); + goto ret; + } } else { - /* - * If we _don't_ get EWOULDBLOCK, the connect has completed - * and we should set the socket as writable. - */ - sock->writable = true; + /* + * If we _don't_ get EWOULDBLOCK, the connect has completed + * and we should set the socket as writable. + */ + sock->writable = true; } err = 0; @@ -1082,7 +1082,7 @@ static DWORD try_connect(NetSocket *sock) if (err) { SockAddr thisaddr = sk_extractaddr_tmp( sock->addr, &sock->step); - plug_log(sock->plug, 1, &thisaddr, sock->port, sock->error, err); + plug_log(sock->plug, 1, &thisaddr, sock->port, sock->error, err); } return err; } @@ -1168,9 +1168,9 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, */ address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET : #ifndef NO_IPV6 - orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 : + orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 : #endif - AF_UNSPEC); + AF_UNSPEC); /* * Our default, if passed the `don't care' value @@ -1188,9 +1188,9 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, ret->s = s; if (s == INVALID_SOCKET) { - err = p_WSAGetLastError(); - ret->error = winsock_error_string(err); - return &ret->sock; + err = p_WSAGetLastError(); + ret->error = winsock_error_string(err); + return &ret->sock; } SetHandleInformation((HANDLE)s, HANDLE_FLAG_INHERIT, 0); @@ -1200,13 +1200,13 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on)); #ifndef NO_IPV6 - if (address_family == AF_INET6) { - memset(&a6, 0, sizeof(a6)); - a6.sin6_family = AF_INET6; - if (local_host_only) - a6.sin6_addr = in6addr_loopback; - else - a6.sin6_addr = in6addr_any; + if (address_family == AF_INET6) { + memset(&a6, 0, sizeof(a6)); + a6.sin6_family = AF_INET6; + if (local_host_only) + a6.sin6_addr = in6addr_loopback; + else + a6.sin6_addr = in6addr_any; if (srcaddr != NULL && p_getaddrinfo) { struct addrinfo hints; struct addrinfo *ai; @@ -1226,73 +1226,73 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr; } } - a6.sin6_port = p_htons(port); - } else + a6.sin6_port = p_htons(port); + } else #endif - { + { bool got_addr = false; - a.sin_family = AF_INET; + a.sin_family = AF_INET; - /* - * Bind to source address. First try an explicitly - * specified one... - */ - if (srcaddr) { - a.sin_addr.s_addr = p_inet_addr(srcaddr); - if (a.sin_addr.s_addr != INADDR_NONE) { - /* Override localhost_only with specified listen addr. */ - ret->localhost_only = ipv4_is_loopback(a.sin_addr); - got_addr = true; - } - } + /* + * Bind to source address. First try an explicitly + * specified one... + */ + if (srcaddr) { + a.sin_addr.s_addr = p_inet_addr(srcaddr); + if (a.sin_addr.s_addr != INADDR_NONE) { + /* Override localhost_only with specified listen addr. */ + ret->localhost_only = ipv4_is_loopback(a.sin_addr); + got_addr = true; + } + } - /* - * ... and failing that, go with one of the standard ones. - */ - if (!got_addr) { - if (local_host_only) - a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK); - else - a.sin_addr.s_addr = p_htonl(INADDR_ANY); - } + /* + * ... and failing that, go with one of the standard ones. + */ + if (!got_addr) { + if (local_host_only) + a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK); + else + a.sin_addr.s_addr = p_htonl(INADDR_ANY); + } - a.sin_port = p_htons((short)port); - } + a.sin_port = p_htons((short)port); + } #ifndef NO_IPV6 - retcode = p_bind(s, (address_family == AF_INET6 ? - (struct sockaddr *) &a6 : - (struct sockaddr *) &a), - (address_family == - AF_INET6 ? sizeof(a6) : sizeof(a))); + retcode = p_bind(s, (address_family == AF_INET6 ? + (struct sockaddr *) &a6 : + (struct sockaddr *) &a), + (address_family == + AF_INET6 ? sizeof(a6) : sizeof(a))); #else - retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a)); + retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a)); #endif - if (retcode != SOCKET_ERROR) { - err = 0; - } else { - err = p_WSAGetLastError(); - } + if (retcode != SOCKET_ERROR) { + err = 0; + } else { + err = p_WSAGetLastError(); + } if (err) { - p_closesocket(s); - ret->error = winsock_error_string(err); - return &ret->sock; + p_closesocket(s); + ret->error = winsock_error_string(err); + return &ret->sock; } if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) { p_closesocket(s); - ret->error = winsock_error_string(p_WSAGetLastError()); - return &ret->sock; + ret->error = winsock_error_string(p_WSAGetLastError()); + return &ret->sock; } /* Set up a select mechanism. This could be an AsyncSelect on a * window, or an EventSelect on an event object. */ errstr = do_select(s, true); if (errstr) { - p_closesocket(s); - ret->error = errstr; - return &ret->sock; + p_closesocket(s); + ret->error = errstr; + return &ret->sock; } add234(sktree, ret); @@ -1303,18 +1303,18 @@ Socket *sk_newlistener(const char *srcaddr, int port, Plug *plug, * IPv6 listening socket and link it to this one. */ if (address_family == AF_INET && orig_address_family == ADDRTYPE_UNSPEC) { - Socket *other = sk_newlistener(srcaddr, port, plug, + Socket *other = sk_newlistener(srcaddr, port, plug, local_host_only, ADDRTYPE_IPV6); - if (other) { + if (other) { NetSocket *ns = container_of(other, NetSocket, sock); - if (!ns->error) { - ns->parent = ret; - ret->child = ns; - } else { - sfree(ns); - } - } + if (!ns->error) { + ns->parent = ret; + ret->child = ns; + } else { + sfree(ns); + } + } } #endif @@ -1326,7 +1326,7 @@ static void sk_net_close(Socket *sock) NetSocket *s = container_of(sock, NetSocket, sock); if (s->child) - sk_net_close(&s->child->sock); + sk_net_close(&s->child->sock); bufchain_clear(&s->output_data); @@ -1334,7 +1334,7 @@ static void sk_net_close(Socket *sock) do_select(s->s, false); p_closesocket(s->s); if (s->addr) - sk_addr_free(s->addr); + sk_addr_free(s->addr); delete_callbacks_for_context(s); sfree(s); } @@ -1367,66 +1367,66 @@ static void socket_error_callback(void *vs) void try_send(NetSocket *s) { while (s->sending_oob || bufchain_size(&s->output_data) > 0) { - int nsent; - DWORD err; - const void *data; - size_t len; + int nsent; + DWORD err; + const void *data; + size_t len; int urgentflag; - if (s->sending_oob) { - urgentflag = MSG_OOB; - len = s->sending_oob; - data = &s->oobdata; - } else { - urgentflag = 0; + if (s->sending_oob) { + urgentflag = MSG_OOB; + len = s->sending_oob; + data = &s->oobdata; + } else { + urgentflag = 0; ptrlen bufdata = bufchain_prefix(&s->output_data); data = bufdata.ptr; len = bufdata.len; - } + } len = min(len, INT_MAX); /* WinSock send() takes an int */ - nsent = p_send(s->s, data, len, urgentflag); - noise_ultralight(NOISE_SOURCE_IOLEN, nsent); - if (nsent <= 0) { - err = (nsent < 0 ? p_WSAGetLastError() : 0); - if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) { - /* - * Perfectly normal: we've sent all we can for the moment. - * - * (Some WinSock send() implementations can return - * <0 but leave no sensible error indication - - * WSAGetLastError() is called but returns zero or - * a small number - so we check that case and treat - * it just like WSAEWOULDBLOCK.) - */ - s->writable = false; - return; - } else { - /* - * If send() returns a socket error, we unfortunately - * can't just call plug_closing(), because it's quite - * likely that we're currently _in_ a call from the - * code we'd be calling back to, so we'd have to make - * half the SSH code reentrant. Instead we flag a - * pending error on the socket, to be dealt with (by - * calling plug_closing()) at some suitable future - * moment. - */ - s->pending_error = err; + nsent = p_send(s->s, data, len, urgentflag); + noise_ultralight(NOISE_SOURCE_IOLEN, nsent); + if (nsent <= 0) { + err = (nsent < 0 ? p_WSAGetLastError() : 0); + if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) { + /* + * Perfectly normal: we've sent all we can for the moment. + * + * (Some WinSock send() implementations can return + * <0 but leave no sensible error indication - + * WSAGetLastError() is called but returns zero or + * a small number - so we check that case and treat + * it just like WSAEWOULDBLOCK.) + */ + s->writable = false; + return; + } else { + /* + * If send() returns a socket error, we unfortunately + * can't just call plug_closing(), because it's quite + * likely that we're currently _in_ a call from the + * code we'd be calling back to, so we'd have to make + * half the SSH code reentrant. Instead we flag a + * pending error on the socket, to be dealt with (by + * calling plug_closing()) at some suitable future + * moment. + */ + s->pending_error = err; queue_toplevel_callback(socket_error_callback, s); - return; - } - } else { - if (s->sending_oob) { - if (nsent < len) { - memmove(s->oobdata, s->oobdata+nsent, len-nsent); - s->sending_oob = len - nsent; - } else { - s->sending_oob = 0; - } - } else { - bufchain_consume(&s->output_data, nsent); - } - } + return; + } + } else { + if (s->sending_oob) { + if (nsent < len) { + memmove(s->oobdata, s->oobdata+nsent, len-nsent); + s->sending_oob = len - nsent; + } else { + s->sending_oob = 0; + } + } else { + bufchain_consume(&s->output_data, nsent); + } + } } /* @@ -1454,7 +1454,7 @@ static size_t sk_net_write(Socket *sock, const void *buf, size_t len) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); return bufchain_size(&s->output_data); } @@ -1477,7 +1477,7 @@ static size_t sk_net_write_oob(Socket *sock, const void *buf, size_t len) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); return s->sending_oob; } @@ -1497,168 +1497,168 @@ static void sk_net_write_eof(Socket *sock) * Now try sending from the start of the buffer list. */ if (s->writable) - try_send(s); + try_send(s); } void select_result(WPARAM wParam, LPARAM lParam) { int ret; DWORD err; - char buf[20480]; /* nice big buffer for plenty of speed */ + char buf[20480]; /* nice big buffer for plenty of speed */ NetSocket *s; bool atmark; /* wParam is the socket itself */ if (wParam == 0) - return; /* boggle */ + return; /* boggle */ s = find234(sktree, (void *) wParam, cmpforsearch); if (!s) - return; /* boggle */ + return; /* boggle */ if ((err = WSAGETSELECTERROR(lParam)) != 0) { - /* - * An error has occurred on this socket. Pass it to the - * plug. - */ - if (s->addr) { + /* + * An error has occurred on this socket. Pass it to the + * plug. + */ + if (s->addr) { SockAddr thisaddr = sk_extractaddr_tmp( s->addr, &s->step); - plug_log(s->plug, 1, &thisaddr, s->port, - winsock_error_string(err), err); - while (err && s->addr && sk_nextaddr(s->addr, &s->step)) { - err = try_connect(s); - } - } - if (err != 0) - plug_closing(s->plug, winsock_error_string(err), err, 0); - return; + plug_log(s->plug, 1, &thisaddr, s->port, + winsock_error_string(err), err); + while (err && s->addr && sk_nextaddr(s->addr, &s->step)) { + err = try_connect(s); + } + } + if (err != 0) + plug_closing(s->plug, winsock_error_string(err), err, 0); + return; } noise_ultralight(NOISE_SOURCE_IOID, wParam); switch (WSAGETSELECTEVENT(lParam)) { case FD_CONNECT: - s->connected = true; + s->connected = true; s->writable = true; - /* - * Once a socket is connected, we can stop falling - * back through the candidate addresses to connect - * to. - */ - if (s->addr) { - sk_addr_free(s->addr); - s->addr = NULL; - } - break; + /* + * Once a socket is connected, we can stop falling + * back through the candidate addresses to connect + * to. + */ + if (s->addr) { + sk_addr_free(s->addr); + s->addr = NULL; + } + break; case FD_READ: - /* In the case the socket is still frozen, we don't even bother */ - if (s->frozen) { - s->frozen_readable = true; - break; - } + /* In the case the socket is still frozen, we don't even bother */ + if (s->frozen) { + s->frozen_readable = true; + break; + } - /* - * 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) { + /* + * 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) { u_long atmark_from_ioctl = 1; - p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl); - /* - * 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. - */ + p_ioctlsocket(s->s, SIOCATMARK, &atmark_from_ioctl); + /* + * 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. + */ atmark = atmark_from_ioctl; - } else - atmark = true; + } else + atmark = true; - ret = p_recv(s->s, buf, sizeof(buf), 0); - noise_ultralight(NOISE_SOURCE_IOLEN, ret); - if (ret < 0) { - err = p_WSAGetLastError(); - if (err == WSAEWOULDBLOCK) { - break; - } - } - if (ret < 0) { - plug_closing(s->plug, winsock_error_string(err), err, 0); - } else if (0 == ret) { - plug_closing(s->plug, NULL, 0, 0); - } else { - plug_receive(s->plug, atmark ? 0 : 1, buf, ret); - } - break; + ret = p_recv(s->s, buf, sizeof(buf), 0); + noise_ultralight(NOISE_SOURCE_IOLEN, ret); + if (ret < 0) { + err = p_WSAGetLastError(); + if (err == WSAEWOULDBLOCK) { + break; + } + } + if (ret < 0) { + plug_closing(s->plug, winsock_error_string(err), err, 0); + } else if (0 == ret) { + plug_closing(s->plug, NULL, 0, 0); + } else { + 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 = p_recv(s->s, buf, sizeof(buf), MSG_OOB); - noise_ultralight(NOISE_SOURCE_IOLEN, ret); - if (ret <= 0) { + /* + * 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 = p_recv(s->s, buf, sizeof(buf), MSG_OOB); + noise_ultralight(NOISE_SOURCE_IOLEN, ret); + if (ret <= 0) { int err = p_WSAGetLastError(); - plug_closing(s->plug, winsock_error_string(err), err, 0); - } else { - plug_receive(s->plug, 2, buf, ret); - } - break; + plug_closing(s->plug, winsock_error_string(err), err, 0); + } else { + plug_receive(s->plug, 2, buf, ret); + } + break; case FD_WRITE: - { - int bufsize_before, bufsize_after; - s->writable = true; - bufsize_before = s->sending_oob + bufchain_size(&s->output_data); - try_send(s); - bufsize_after = s->sending_oob + bufchain_size(&s->output_data); - if (bufsize_after < bufsize_before) - plug_sent(s->plug, bufsize_after); - } - break; + { + int bufsize_before, bufsize_after; + s->writable = true; + bufsize_before = s->sending_oob + bufchain_size(&s->output_data); + try_send(s); + bufsize_after = s->sending_oob + bufchain_size(&s->output_data); + if (bufsize_after < bufsize_before) + plug_sent(s->plug, bufsize_after); + } + break; case FD_CLOSE: - /* Signal a close on the socket. First read any outstanding data. */ - do { - ret = p_recv(s->s, buf, sizeof(buf), 0); - if (ret < 0) { - err = p_WSAGetLastError(); - if (err == WSAEWOULDBLOCK) - break; - plug_closing(s->plug, winsock_error_string(err), err, 0); - } else { - if (ret) - plug_receive(s->plug, 0, buf, ret); - else - plug_closing(s->plug, NULL, 0, 0); - } - } while (ret > 0); - return; + /* Signal a close on the socket. First read any outstanding data. */ + do { + ret = p_recv(s->s, buf, sizeof(buf), 0); + if (ret < 0) { + err = p_WSAGetLastError(); + if (err == WSAEWOULDBLOCK) + break; + plug_closing(s->plug, winsock_error_string(err), err, 0); + } else { + if (ret) + plug_receive(s->plug, 0, buf, ret); + else + plug_closing(s->plug, NULL, 0, 0); + } + } while (ret > 0); + return; case FD_ACCEPT: - { + { #ifdef NO_IPV6 - struct sockaddr_in isa; + struct sockaddr_in isa; #else struct sockaddr_storage isa; #endif - int addrlen = sizeof(isa); - SOCKET t; /* socket of connection */ + int addrlen = sizeof(isa); + SOCKET t; /* socket of connection */ accept_ctx_t actx; - memset(&isa, 0, sizeof(isa)); - err = 0; - t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen); - if (t == INVALID_SOCKET) - { - err = p_WSAGetLastError(); - if (err == WSATRY_AGAIN) - break; - } + memset(&isa, 0, sizeof(isa)); + err = 0; + t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen); + if (t == INVALID_SOCKET) + { + err = p_WSAGetLastError(); + if (err == WSATRY_AGAIN) + break; + } actx.p = (void *)t; @@ -1667,14 +1667,14 @@ void select_result(WPARAM wParam, LPARAM lParam) s->localhost_only && !ipv4_is_local_addr(((struct sockaddr_in *)&isa)->sin_addr)) #else - if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) + if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) #endif - { - p_closesocket(t); /* dodgy WinSock let nonlocal through */ - } else if (plug_accepting(s->plug, sk_net_accept, actx)) { - p_closesocket(t); /* denied or error */ - } - } + { + p_closesocket(t); /* dodgy WinSock let nonlocal through */ + } else if (plug_accepting(s->plug, sk_net_accept, actx)) { + p_closesocket(t); /* denied or error */ + } + } } } @@ -1746,14 +1746,14 @@ static void sk_net_set_frozen(Socket *sock, bool is_frozen) { NetSocket *s = container_of(sock, NetSocket, sock); if (s->frozen == is_frozen) - return; + return; s->frozen = is_frozen; if (!is_frozen) { - do_select(s->s, true); - if (s->frozen_readable) { - char c; - p_recv(s->s, &c, 1, MSG_PEEK); - } + do_select(s->s, true); + if (s->frozen_readable) { + char c; + p_recv(s->s, &c, 1, MSG_PEEK); + } } s->frozen_readable = false; } @@ -1764,8 +1764,8 @@ void socket_reselect_all(void) int i; for (i = 0; (s = index234(sktree, i)) != NULL; i++) { - if (!s->frozen) - do_select(s->s, true); + if (!s->frozen) + do_select(s->s, true); } } @@ -1791,9 +1791,9 @@ bool socket_writable(SOCKET skt) NetSocket *s = find234(sktree, (void *)skt, cmpforsearch); if (s) - return bufchain_size(&s->output_data) > 0; + return bufchain_size(&s->output_data) > 0; else - return false; + return false; } int net_service_lookup(char *service) @@ -1801,9 +1801,9 @@ int net_service_lookup(char *service) struct servent *se; se = p_getservbyname(service, NULL); if (se != NULL) - return p_ntohs(se->s_port); + return p_ntohs(se->s_port); else - return 0; + return 0; } char *get_hostname(void) @@ -1815,7 +1815,7 @@ char *get_hostname(void) } SockAddr *platform_get_x11_unix_address(const char *display, int displaynum, - char **canonicalname) + char **canonicalname) { SockAddr *ret = snew(SockAddr); memset(ret, 0, sizeof(SockAddr)); diff --git a/windows/winnoise.c b/windows/winnoise.c index 842a69b0..65c4c92d 100644 --- a/windows/winnoise.c +++ b/windows/winnoise.c @@ -58,10 +58,10 @@ void noise_get_heavy(void (*func) (void *, int)) strcat(winpath, "\\*"); srch = FindFirstFile(winpath, &finddata); if (srch != INVALID_HANDLE_VALUE) { - do { - func(&finddata, sizeof(finddata)); - } while (FindNextFile(srch, &finddata)); - FindClose(srch); + do { + func(&finddata, sizeof(finddata)); + } while (FindNextFile(srch, &finddata)); + FindClose(srch); } pid = GetCurrentProcessId(); @@ -105,10 +105,10 @@ void noise_regular(void) random_add_noise(NOISE_SOURCE_MEMINFO, &memstat, sizeof(memstat)); GetThreadTimes(GetCurrentThread(), times, times + 1, times + 2, - times + 3); + times + 3); random_add_noise(NOISE_SOURCE_THREADTIME, ×, sizeof(times)); GetProcessTimes(GetCurrentProcess(), times, times + 1, times + 2, - times + 3); + times + 3); random_add_noise(NOISE_SOURCE_PROCTIME, ×, sizeof(times)); } @@ -129,7 +129,7 @@ void noise_ultralight(NoiseSourceId id, unsigned long data) random_add_noise(NOISE_SOURCE_TIME, &wintime, sizeof(DWORD)); if (QueryPerformanceCounter(&perftime)) - random_add_noise(NOISE_SOURCE_PERFCOUNT, &perftime, sizeof(perftime)); + random_add_noise(NOISE_SOURCE_PERFCOUNT, &perftime, sizeof(perftime)); } uint64_t prng_reseed_time_ms(void) diff --git a/windows/winnps.c b/windows/winnps.c index 5c201641..36e24d2c 100644 --- a/windows/winnps.c +++ b/windows/winnps.c @@ -38,7 +38,7 @@ static Plug *sk_namedpipeserver_plug(Socket *s, Plug *p) NamedPipeServerSocket *ps = container_of(s, NamedPipeServerSocket, sock); Plug *ret = ps->plug; if (p) - ps->plug = p; + ps->plug = p; return ret; } diff --git a/windows/winpgen.c b/windows/winpgen.c index 9076c3ef..353caa02 100644 --- a/windows/winpgen.c +++ b/windows/winpgen.c @@ -39,7 +39,7 @@ void modalfatalbox(const char *fmt, ...) stuff = dupvprintf(fmt, ap); va_end(ap); MessageBox(NULL, stuff, "PuTTYgen Fatal Error", - MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); + MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); sfree(stuff); exit(1); } @@ -56,7 +56,7 @@ void nonfatal(const char *fmt, ...) stuff = dupvprintf(fmt, ap); va_end(ap); MessageBox(NULL, stuff, "PuTTYgen Error", - MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); + MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); sfree(stuff); } @@ -68,10 +68,10 @@ void nonfatal(const char *fmt, ...) struct progress { int nphases; struct { - bool exponential; - unsigned startpoint, total; - unsigned param, current, n; /* if exponential */ - unsigned mult; /* if linear */ + bool exponential; + unsigned startpoint, total; + unsigned param, current, n; /* if exponential */ + unsigned mult; /* if linear */ } phases[MAXPHASE]; unsigned total, divisor, range; HWND progbar; @@ -84,53 +84,53 @@ static void progress_update(void *param, int action, int phase, int iprogress) int position; if (action < PROGFN_READY && p->nphases < phase) - p->nphases = phase; + p->nphases = phase; switch (action) { case PROGFN_INITIALISE: - p->nphases = 0; - break; + p->nphases = 0; + break; case PROGFN_LIN_PHASE: - p->phases[phase-1].exponential = false; - p->phases[phase-1].mult = p->phases[phase].total / progress; - break; + p->phases[phase-1].exponential = false; + p->phases[phase-1].mult = p->phases[phase].total / progress; + break; case PROGFN_EXP_PHASE: - p->phases[phase-1].exponential = true; - p->phases[phase-1].param = 0x10000 + progress; - p->phases[phase-1].current = p->phases[phase-1].total; - p->phases[phase-1].n = 0; - break; + p->phases[phase-1].exponential = true; + p->phases[phase-1].param = 0x10000 + progress; + p->phases[phase-1].current = p->phases[phase-1].total; + p->phases[phase-1].n = 0; + break; case PROGFN_PHASE_EXTENT: - p->phases[phase-1].total = progress; - break; + p->phases[phase-1].total = progress; + break; case PROGFN_READY: - { - unsigned total = 0; - int i; - for (i = 0; i < p->nphases; i++) { - p->phases[i].startpoint = total; - total += p->phases[i].total; - } - p->total = total; - p->divisor = ((p->total + PROGRESSRANGE - 1) / PROGRESSRANGE); - p->range = p->total / p->divisor; - SendMessage(p->progbar, PBM_SETRANGE, 0, MAKELPARAM(0, p->range)); - } - break; + { + unsigned total = 0; + int i; + for (i = 0; i < p->nphases; i++) { + p->phases[i].startpoint = total; + total += p->phases[i].total; + } + p->total = total; + p->divisor = ((p->total + PROGRESSRANGE - 1) / PROGRESSRANGE); + p->range = p->total / p->divisor; + SendMessage(p->progbar, PBM_SETRANGE, 0, MAKELPARAM(0, p->range)); + } + break; case PROGFN_PROGRESS: - if (p->phases[phase-1].exponential) { - while (p->phases[phase-1].n < progress) { - p->phases[phase-1].n++; - p->phases[phase-1].current *= p->phases[phase-1].param; - p->phases[phase-1].current /= 0x10000; - } - position = (p->phases[phase-1].startpoint + - p->phases[phase-1].total - p->phases[phase-1].current); - } else { - position = (p->phases[phase-1].startpoint + - progress * p->phases[phase-1].mult); - } - SendMessage(p->progbar, PBM_SETPOS, position / p->divisor, 0); - break; + if (p->phases[phase-1].exponential) { + while (p->phases[phase-1].n < progress) { + p->phases[phase-1].n++; + p->phases[phase-1].current *= p->phases[phase-1].param; + p->phases[phase-1].current /= 0x10000; + } + position = (p->phases[phase-1].startpoint + + p->phases[phase-1].total - p->phases[phase-1].current); + } else { + position = (p->phases[phase-1].startpoint + + progress * p->phases[phase-1].mult); + } + SendMessage(p->progbar, PBM_SETPOS, position / p->divisor, 0); + break; } } @@ -143,62 +143,62 @@ struct PassphraseProcStruct { * Dialog-box function for the passphrase box. */ static INT_PTR 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. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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); + } - p = (struct PassphraseProcStruct *) lParam; - passphrase = p->passphrase; - if (p->comment) - SetDlgItemText(hwnd, 101, p->comment); + p = (struct PassphraseProcStruct *) lParam; + passphrase = p->passphrase; + if (p->comment) + SetDlgItemText(hwnd, 101, p->comment); burnstr(*passphrase); *passphrase = dupstr(""); - SetDlgItemText(hwnd, 102, *passphrase); - return 0; + SetDlgItemText(hwnd, 102, *passphrase); + return 0; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - if (*passphrase) - EndDialog(hwnd, 1); - else - MessageBeep(0); - return 0; - case IDCANCEL: - EndDialog(hwnd, 0); - return 0; - case 102: /* edit box */ - if ((HIWORD(wParam) == EN_CHANGE) && passphrase) { + switch (LOWORD(wParam)) { + case IDOK: + if (*passphrase) + EndDialog(hwnd, 1); + else + MessageBeep(0); + return 0; + case IDCANCEL: + EndDialog(hwnd, 0); + return 0; + case 102: /* edit box */ + if ((HIWORD(wParam) == EN_CHANGE) && passphrase) { burnstr(*passphrase); *passphrase = GetDlgItemText_alloc(hwnd, 102); - } - return 0; - } - return 0; + } + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 0); - return 0; + EndDialog(hwnd, 0); + return 0; } return 0; } @@ -214,11 +214,11 @@ static bool prompt_keyfile(HWND hwnd, char *dlgtitle, memset(&of, 0, sizeof(of)); of.hwndOwner = hwnd; if (ppk) { - of.lpstrFilter = "PuTTY Private Key Files (*.ppk)\0*.ppk\0" - "All Files (*.*)\0*\0\0\0"; - of.lpstrDefExt = ".ppk"; + of.lpstrFilter = "PuTTY Private Key Files (*.ppk)\0*.ppk\0" + "All Files (*.*)\0*\0\0\0"; + of.lpstrDefExt = ".ppk"; } else { - of.lpstrFilter = "All Files (*.*)\0*\0\0\0"; + of.lpstrFilter = "All Files (*.*)\0*\0\0\0"; } of.lpstrCustomFilter = NULL; of.nFilterIndex = 1; @@ -235,38 +235,38 @@ static bool prompt_keyfile(HWND hwnd, char *dlgtitle, * Dialog-box function for the Licence box. */ static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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); + } SetDlgItemText(hwnd, 1000, LICENCE_TEXT("\r\n\r\n")); - return 1; + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - EndDialog(hwnd, 1); - return 0; - } - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + EndDialog(hwnd, 1); + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 1); - return 0; + EndDialog(hwnd, 1); + return 0; } return 0; } @@ -275,24 +275,24 @@ static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg, * Dialog-box function for the About box. */ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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); + } { char *buildinfo_text = buildinfo("\r\n"); @@ -304,30 +304,30 @@ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, SetDlgItemText(hwnd, 1000, text); sfree(text); } - return 1; + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - EndDialog(hwnd, 1); - return 0; - case 101: - EnableWindow(hwnd, 0); - DialogBox(hinst, MAKEINTRESOURCE(214), hwnd, LicenceProc); - EnableWindow(hwnd, 1); - SetActiveWindow(hwnd); - return 0; - case 102: - /* Load web browser */ - ShellExecute(hwnd, "open", - "https://www.chiark.greenend.org.uk/~sgtatham/putty/", - 0, 0, SW_SHOWDEFAULT); - return 0; - } - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + EndDialog(hwnd, 1); + return 0; + case 101: + EnableWindow(hwnd, 0); + DialogBox(hinst, MAKEINTRESOURCE(214), hwnd, LicenceProc); + EnableWindow(hwnd, 1); + SetActiveWindow(hwnd); + return 0; + case 102: + /* Load web browser */ + ShellExecute(hwnd, "open", + "https://www.chiark.greenend.org.uk/~sgtatham/putty/", + 0, 0, SW_SHOWDEFAULT); + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 1); - return 0; + EndDialog(hwnd, 1); + return 0; } return 0; } @@ -338,9 +338,9 @@ typedef enum {RSA, DSA, ECDSA, ED25519} keytype; * Thread to generate a key. */ struct rsa_key_thread_params { - HWND progressbar; /* notify this with progress */ - HWND dialog; /* notify this on completion */ - int key_bits; /* bits in key modulus (RSA, DSA) */ + HWND progressbar; /* notify this with progress */ + HWND dialog; /* notify this on completion */ + int key_bits; /* bits in key modulus (RSA, DSA) */ int curve_bits; /* bits in elliptic curve (ECDSA) */ keytype keytype; union { @@ -353,21 +353,21 @@ struct rsa_key_thread_params { static DWORD WINAPI generate_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; progress_update(&prog, PROGFN_INITIALISE, 0, 0); if (params->keytype == DSA) - dsa_generate(params->dsskey, params->key_bits, progress_update, &prog); + dsa_generate(params->dsskey, params->key_bits, progress_update, &prog); else if (params->keytype == ECDSA) ecdsa_generate(params->eckey, params->curve_bits, progress_update, &prog); else if (params->keytype == ED25519) eddsa_generate(params->edkey, 256, progress_update, &prog); else - rsa_generate(params->key, params->key_bits, progress_update, &prog); + rsa_generate(params->key, params->key_bits, progress_update, &prog); PostMessage(params->dialog, WM_DONEKEY, 0, 0); @@ -383,7 +383,7 @@ struct MainDlgState { int key_bits, curve_bits; bool ssh2; keytype keytype; - char **commentptr; /* points to key.comment or ssh2key.comment */ + char **commentptr; /* points to key.comment or ssh2key.comment */ ssh2_userkey ssh2key; unsigned *entropy; union { @@ -398,7 +398,7 @@ struct MainDlgState { static void hidemany(HWND hwnd, const int *ids, bool hideit) { while (*ids) { - ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW)); + ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW)); } } @@ -407,17 +407,17 @@ static void setupbigedit1(HWND hwnd, int id, int idstatic, RSAKey *key) char *buffer = ssh1_pubkey_str(key); SetDlgItemText(hwnd, id, buffer); SetDlgItemText(hwnd, idstatic, - "&Public key for pasting into authorized_keys file:"); + "&Public key for pasting into authorized_keys file:"); sfree(buffer); } static void setupbigedit2(HWND hwnd, int id, int idstatic, - ssh2_userkey *key) + ssh2_userkey *key) { char *buffer = ssh2_pubkey_openssh_str(key); SetDlgItemText(hwnd, id, buffer); SetDlgItemText(hwnd, idstatic, "&Public key for pasting into " - "OpenSSH authorized_keys file:"); + "OpenSSH authorized_keys file:"); sfree(buffer); } @@ -428,15 +428,15 @@ void old_keyfile_warning(void) { static const char mbtitle[] = "PuTTY Key File Warning"; static const char message[] = - "You are loading an SSH-2 private key which has an\n" - "old version of the file format. This means your key\n" - "file is not fully tamperproof. Future versions of\n" - "PuTTY may stop supporting this private key format,\n" - "so we recommend you convert your key to the new\n" - "format.\n" - "\n" - "Once the key is loaded into PuTTYgen, you can perform\n" - "this conversion simply by saving it again."; + "You are loading an SSH-2 private key which has an\n" + "old version of the file format. This means your key\n" + "file is not fully tamperproof. Future versions of\n" + "PuTTY may stop supporting this private key format,\n" + "so we recommend you convert your key to the new\n" + "format.\n" + "\n" + "Once the key is loaded into PuTTYgen, you can perform\n" + "this conversion simply by saving it again."; MessageBox(NULL, message, mbtitle, MB_OK); } @@ -490,111 +490,111 @@ void ui_set_state(HWND hwnd, struct MainDlgState *state, int status) int type; switch (status) { - case 0: /* no key */ - hidemany(hwnd, nokey_ids, false); - hidemany(hwnd, generating_ids, true); - hidemany(hwnd, gotkey_ids, true); - EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1); - EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1); - EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0); - EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1); + case 0: /* no key */ + hidemany(hwnd, nokey_ids, false); + hidemany(hwnd, generating_ids, true); + hidemany(hwnd, gotkey_ids, true); + EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1); + EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1); + EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0); + EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ECDSA), 1); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ED25519), 1); - EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1); - EnableMenuItem(state->filemenu, IDC_LOAD, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVE, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_GENERATE, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA, MF_ENABLED|MF_BYCOMMAND); + EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1); + EnableMenuItem(state->filemenu, IDC_LOAD, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVE, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_GENERATE, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA, MF_ENABLED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ECDSA, MF_ENABLED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ED25519, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_AUTO, - MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_NEW, - MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_SSHCOM, - MF_GRAYED|MF_BYCOMMAND); - break; - case 1: /* generating key */ - 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); - EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 0); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 0); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 0); + EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_AUTO, + MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_NEW, + MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_SSHCOM, + MF_GRAYED|MF_BYCOMMAND); + break; + case 1: /* generating key */ + 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); + EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 0); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 0); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 0); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 0); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ECDSA), 0); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ED25519), 0); - EnableWindow(GetDlgItem(hwnd, IDC_BITS), 0); - EnableMenuItem(state->filemenu, IDC_LOAD, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVE, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_GENERATE, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA, MF_GRAYED|MF_BYCOMMAND); + EnableWindow(GetDlgItem(hwnd, IDC_BITS), 0); + EnableMenuItem(state->filemenu, IDC_LOAD, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVE, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_GENERATE, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA, MF_GRAYED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ECDSA, MF_GRAYED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ED25519, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_AUTO, - MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_NEW, - MF_GRAYED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_EXPORT_SSHCOM, - MF_GRAYED|MF_BYCOMMAND); - break; + EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_AUTO, + MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_OPENSSH_NEW, + MF_GRAYED|MF_BYCOMMAND); + EnableMenuItem(state->cvtmenu, IDC_EXPORT_SSHCOM, + MF_GRAYED|MF_BYCOMMAND); + break; case 2: - hidemany(hwnd, nokey_ids, true); - hidemany(hwnd, generating_ids, true); - hidemany(hwnd, gotkey_ids, false); - EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1); - EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1); - EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1); - EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 1); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1); - EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1); + hidemany(hwnd, nokey_ids, true); + hidemany(hwnd, generating_ids, true); + hidemany(hwnd, gotkey_ids, false); + EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1); + EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1); + EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1); + EnableWindow(GetDlgItem(hwnd, IDC_SAVEPUB), 1); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH1), 1); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2RSA), 1); + EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2DSA), 1); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ECDSA), 1); EnableWindow(GetDlgItem(hwnd, IDC_KEYSSH2ED25519), 1); - EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1); - EnableMenuItem(state->filemenu, IDC_LOAD, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVE, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_GENERATE, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA,MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA,MF_ENABLED|MF_BYCOMMAND); + EnableWindow(GetDlgItem(hwnd, IDC_BITS), 1); + EnableMenuItem(state->filemenu, IDC_LOAD, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVE, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->filemenu, IDC_SAVEPUB, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_GENERATE, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH1, MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2RSA,MF_ENABLED|MF_BYCOMMAND); + EnableMenuItem(state->keymenu, IDC_KEYSSH2DSA,MF_ENABLED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ECDSA, MF_ENABLED|MF_BYCOMMAND); EnableMenuItem(state->keymenu, IDC_KEYSSH2ED25519, MF_ENABLED|MF_BYCOMMAND); - EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_ENABLED|MF_BYCOMMAND); - /* - * Enable export menu items if and only if the key type - * supports this kind of export. - */ - type = state->ssh2 ? SSH_KEYTYPE_SSH2 : SSH_KEYTYPE_SSH1; + EnableMenuItem(state->cvtmenu, IDC_IMPORT, MF_ENABLED|MF_BYCOMMAND); + /* + * Enable export menu items if and only if the key type + * supports this kind of export. + */ + type = state->ssh2 ? SSH_KEYTYPE_SSH2 : SSH_KEYTYPE_SSH1; #define do_export_menuitem(x,y) \ EnableMenuItem(state->cvtmenu, x, MF_BYCOMMAND | \ - (import_target_type(y)==type?MF_ENABLED:MF_GRAYED)) - do_export_menuitem(IDC_EXPORT_OPENSSH_AUTO, SSH_KEYTYPE_OPENSSH_AUTO); - do_export_menuitem(IDC_EXPORT_OPENSSH_NEW, SSH_KEYTYPE_OPENSSH_NEW); - do_export_menuitem(IDC_EXPORT_SSHCOM, SSH_KEYTYPE_SSHCOM); + (import_target_type(y)==type?MF_ENABLED:MF_GRAYED)) + do_export_menuitem(IDC_EXPORT_OPENSSH_AUTO, SSH_KEYTYPE_OPENSSH_AUTO); + do_export_menuitem(IDC_EXPORT_OPENSSH_NEW, SSH_KEYTYPE_OPENSSH_NEW); + do_export_menuitem(IDC_EXPORT_SSHCOM, SSH_KEYTYPE_SSHCOM); #undef do_export_menuitem - break; + break; } } @@ -640,7 +640,7 @@ void ui_set_key_type(HWND hwnd, struct MainDlgState *state, int button) } void load_key_file(HWND hwnd, struct MainDlgState *state, - Filename *filename, bool was_import_cmd) + Filename *filename, bool was_import_cmd) { char *passphrase; bool needs_pass; @@ -653,159 +653,159 @@ void load_key_file(HWND hwnd, struct MainDlgState *state, type = realtype = key_type(filename); if (type != SSH_KEYTYPE_SSH1 && - type != SSH_KEYTYPE_SSH2 && - !import_possible(type)) { - char *msg = dupprintf("Couldn't load private key (%s)", - key_type_to_str(type)); - message_box(msg, "PuTTYgen Error", MB_OK | MB_ICONERROR, - HELPCTXID(errors_cantloadkey)); - sfree(msg); - return; + type != SSH_KEYTYPE_SSH2 && + !import_possible(type)) { + char *msg = dupprintf("Couldn't load private key (%s)", + key_type_to_str(type)); + message_box(msg, "PuTTYgen Error", MB_OK | MB_ICONERROR, + HELPCTXID(errors_cantloadkey)); + sfree(msg); + return; } if (type != SSH_KEYTYPE_SSH1 && - type != SSH_KEYTYPE_SSH2) { - realtype = type; - type = import_target_type(type); + type != SSH_KEYTYPE_SSH2) { + realtype = type; + type = import_target_type(type); } comment = NULL; passphrase = NULL; if (realtype == SSH_KEYTYPE_SSH1) - needs_pass = rsa_ssh1_encrypted(filename, &comment); + needs_pass = rsa_ssh1_encrypted(filename, &comment); else if (realtype == SSH_KEYTYPE_SSH2) - needs_pass = ssh2_userkey_encrypted(filename, &comment); + needs_pass = ssh2_userkey_encrypted(filename, &comment); else - needs_pass = import_encrypted(filename, realtype, &comment); + needs_pass = import_encrypted(filename, realtype, &comment); do { burnstr(passphrase); passphrase = NULL; - if (needs_pass) { - int dlgret; + if (needs_pass) { + int dlgret; struct PassphraseProcStruct pps; pps.passphrase = &passphrase; pps.comment = comment; - dlgret = DialogBoxParam(hinst, - MAKEINTRESOURCE(210), - NULL, PassphraseProc, - (LPARAM) &pps); - if (!dlgret) { - ret = -2; - break; - } + dlgret = DialogBoxParam(hinst, + MAKEINTRESOURCE(210), + NULL, PassphraseProc, + (LPARAM) &pps); + if (!dlgret) { + ret = -2; + break; + } assert(passphrase != NULL); - } else - passphrase = dupstr(""); - if (type == SSH_KEYTYPE_SSH1) { - if (realtype == type) - ret = rsa_ssh1_loadkey( + } else + passphrase = dupstr(""); + if (type == SSH_KEYTYPE_SSH1) { + if (realtype == type) + ret = rsa_ssh1_loadkey( filename, &newkey1, passphrase, &errmsg); - else - ret = import_ssh1(filename, realtype, &newkey1, + else + ret = import_ssh1(filename, realtype, &newkey1, passphrase, &errmsg); - } else { - if (realtype == type) - newkey2 = ssh2_load_userkey(filename, passphrase, &errmsg); - else - newkey2 = import_ssh2(filename, realtype, passphrase, &errmsg); - if (newkey2 == SSH2_WRONG_PASSPHRASE) - ret = -1; - else if (!newkey2) - ret = 0; - else - ret = 1; - } + } else { + if (realtype == type) + newkey2 = ssh2_load_userkey(filename, passphrase, &errmsg); + else + newkey2 = import_ssh2(filename, realtype, passphrase, &errmsg); + if (newkey2 == SSH2_WRONG_PASSPHRASE) + ret = -1; + else if (!newkey2) + ret = 0; + else + ret = 1; + } } while (ret == -1); if (comment) - sfree(comment); + sfree(comment); if (ret == 0) { - char *msg = dupprintf("Couldn't load private key (%s)", errmsg); - message_box(msg, "PuTTYgen Error", MB_OK | MB_ICONERROR, - HELPCTXID(errors_cantloadkey)); - sfree(msg); + char *msg = dupprintf("Couldn't load private key (%s)", errmsg); + message_box(msg, "PuTTYgen Error", MB_OK | MB_ICONERROR, + HELPCTXID(errors_cantloadkey)); + sfree(msg); } else if (ret == 1) { - /* - * Now update the key controls with all the - * key data. - */ - { - SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, - passphrase); - SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, - passphrase); - if (type == SSH_KEYTYPE_SSH1) { - char *fingerprint, *savecomment; + /* + * Now update the key controls with all the + * key data. + */ + { + SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, + passphrase); + SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, + passphrase); + if (type == SSH_KEYTYPE_SSH1) { + char *fingerprint, *savecomment; - state->ssh2 = false; - state->commentptr = &state->key.comment; - state->key = newkey1; + state->ssh2 = false; + state->commentptr = &state->key.comment; + state->key = newkey1; - /* - * Set the key fingerprint. - */ - savecomment = state->key.comment; - state->key.comment = NULL; - fingerprint = rsa_ssh1_fingerprint(&state->key); - state->key.comment = savecomment; - SetDlgItemText(hwnd, IDC_FINGERPRINT, fingerprint); + /* + * Set the key fingerprint. + */ + savecomment = state->key.comment; + state->key.comment = NULL; + fingerprint = rsa_ssh1_fingerprint(&state->key); + state->key.comment = savecomment; + SetDlgItemText(hwnd, IDC_FINGERPRINT, fingerprint); sfree(fingerprint); - /* - * Construct a decimal representation - * of the key, for pasting into - * .ssh/authorized_keys on a Unix box. - */ - setupbigedit1(hwnd, IDC_KEYDISPLAY, - IDC_PKSTATIC, &state->key); - } else { - char *fp; - char *savecomment; + /* + * Construct a decimal representation + * of the key, for pasting into + * .ssh/authorized_keys on a Unix box. + */ + setupbigedit1(hwnd, IDC_KEYDISPLAY, + IDC_PKSTATIC, &state->key); + } else { + char *fp; + char *savecomment; - state->ssh2 = true; - state->commentptr = - &state->ssh2key.comment; - state->ssh2key = *newkey2; /* structure copy */ - sfree(newkey2); + state->ssh2 = true; + state->commentptr = + &state->ssh2key.comment; + state->ssh2key = *newkey2; /* structure copy */ + sfree(newkey2); - savecomment = state->ssh2key.comment; - state->ssh2key.comment = NULL; - fp = ssh2_fingerprint(state->ssh2key.key); - state->ssh2key.comment = savecomment; + savecomment = state->ssh2key.comment; + state->ssh2key.comment = NULL; + fp = ssh2_fingerprint(state->ssh2key.key); + state->ssh2key.comment = savecomment; - SetDlgItemText(hwnd, IDC_FINGERPRINT, fp); - sfree(fp); + SetDlgItemText(hwnd, IDC_FINGERPRINT, fp); + sfree(fp); - setupbigedit2(hwnd, IDC_KEYDISPLAY, - IDC_PKSTATIC, &state->ssh2key); - } - SetDlgItemText(hwnd, IDC_COMMENTEDIT, - *state->commentptr); - } - /* - * Finally, hide the progress bar and show - * the key data. - */ - ui_set_state(hwnd, state, 2); - state->key_exists = true; + setupbigedit2(hwnd, IDC_KEYDISPLAY, + IDC_PKSTATIC, &state->ssh2key); + } + SetDlgItemText(hwnd, IDC_COMMENTEDIT, + *state->commentptr); + } + /* + * Finally, hide the progress bar and show + * the key data. + */ + ui_set_state(hwnd, state, 2); + state->key_exists = true; - /* - * If the user has imported a foreign key - * using the Load command, let them know. - * If they've used the Import command, be - * silent. - */ - if (realtype != type && !was_import_cmd) { - char msg[512]; - sprintf(msg, "Successfully imported foreign key\n" - "(%s).\n" - "To use this key with PuTTY, you need to\n" - "use the \"Save private key\" command to\n" - "save it in PuTTY's own format.", - key_type_to_str(realtype)); - MessageBox(NULL, msg, "PuTTYgen Notice", - MB_OK | MB_ICONINFORMATION); - } + /* + * If the user has imported a foreign key + * using the Load command, let them know. + * If they've used the Import command, be + * silent. + */ + if (realtype != type && !was_import_cmd) { + char msg[512]; + sprintf(msg, "Successfully imported foreign key\n" + "(%s).\n" + "To use this key with PuTTY, you need to\n" + "use the \"Save private key\" command to\n" + "save it in PuTTY's own format.", + key_type_to_str(realtype)); + MessageBox(NULL, msg, "PuTTYgen Notice", + MB_OK | MB_ICONINFORMATION); + } } burnstr(passphrase); } @@ -813,7 +813,7 @@ void load_key_file(HWND hwnd, struct MainDlgState *state, static void start_generating_key(HWND hwnd, struct MainDlgState *state) { static const char generating_msg[] = - "Please wait while a key is generated..."; + "Please wait while a key is generated..."; struct rsa_key_thread_params *params; DWORD threadid; @@ -847,146 +847,146 @@ static void start_generating_key(HWND hwnd, struct MainDlgState *state) * Dialog-box function for the main PuTTYgen dialog box. */ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { 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) { case WM_INITDIALOG: if (has_help()) SetWindowLongPtr(hwnd, GWL_EXSTYLE, - GetWindowLongPtr(hwnd, GWL_EXSTYLE) | - WS_EX_CONTEXTHELP); + GetWindowLongPtr(hwnd, GWL_EXSTYLE) | + WS_EX_CONTEXTHELP); else { /* * If we add a Help button, this is where we destroy it * if the help file isn't present. */ } - SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, - (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(200))); + SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, + (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(200))); - state = snew(struct MainDlgState); - state->generation_thread_exists = false; - state->collecting_entropy = false; - state->entropy = NULL; - state->key_exists = false; - SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) state); - { - HMENU menu, menu1; + state = snew(struct MainDlgState); + state->generation_thread_exists = false; + state->collecting_entropy = false; + state->entropy = NULL; + state->key_exists = false; + SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) state); + { + HMENU menu, menu1; - menu = CreateMenu(); + menu = CreateMenu(); - menu1 = CreateMenu(); - AppendMenu(menu1, MF_ENABLED, IDC_LOAD, "&Load private key"); - AppendMenu(menu1, MF_ENABLED, IDC_SAVEPUB, "Save p&ublic key"); - AppendMenu(menu1, MF_ENABLED, IDC_SAVE, "&Save private key"); - AppendMenu(menu1, MF_SEPARATOR, 0, 0); - AppendMenu(menu1, MF_ENABLED, IDC_QUIT, "E&xit"); - AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&File"); - state->filemenu = menu1; + menu1 = CreateMenu(); + AppendMenu(menu1, MF_ENABLED, IDC_LOAD, "&Load private key"); + AppendMenu(menu1, MF_ENABLED, IDC_SAVEPUB, "Save p&ublic key"); + AppendMenu(menu1, MF_ENABLED, IDC_SAVE, "&Save private key"); + AppendMenu(menu1, MF_SEPARATOR, 0, 0); + AppendMenu(menu1, MF_ENABLED, IDC_QUIT, "E&xit"); + AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&File"); + state->filemenu = menu1; - menu1 = CreateMenu(); - AppendMenu(menu1, MF_ENABLED, IDC_GENERATE, "&Generate key pair"); - AppendMenu(menu1, MF_SEPARATOR, 0, 0); - AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH1, "SSH-&1 key (RSA)"); - AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2RSA, "SSH-2 &RSA key"); - AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2DSA, "SSH-2 &DSA key"); + menu1 = CreateMenu(); + AppendMenu(menu1, MF_ENABLED, IDC_GENERATE, "&Generate key pair"); + AppendMenu(menu1, MF_SEPARATOR, 0, 0); + AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH1, "SSH-&1 key (RSA)"); + AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2RSA, "SSH-2 &RSA key"); + AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2DSA, "SSH-2 &DSA key"); AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2ECDSA, "SSH-2 &ECDSA key"); AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2ED25519, "SSH-2 Ed&25519 key"); - AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&Key"); - state->keymenu = menu1; + AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&Key"); + state->keymenu = menu1; - menu1 = CreateMenu(); - AppendMenu(menu1, MF_ENABLED, IDC_IMPORT, "&Import key"); - AppendMenu(menu1, MF_SEPARATOR, 0, 0); - AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH_AUTO, - "Export &OpenSSH key"); - AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH_NEW, - "Export &OpenSSH key (force new file format)"); - AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_SSHCOM, - "Export &ssh.com key"); - AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, - "Con&versions"); - state->cvtmenu = menu1; + menu1 = CreateMenu(); + AppendMenu(menu1, MF_ENABLED, IDC_IMPORT, "&Import key"); + AppendMenu(menu1, MF_SEPARATOR, 0, 0); + AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH_AUTO, + "Export &OpenSSH key"); + AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH_NEW, + "Export &OpenSSH key (force new file format)"); + AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_SSHCOM, + "Export &ssh.com key"); + AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, + "Con&versions"); + state->cvtmenu = menu1; - menu1 = CreateMenu(); - AppendMenu(menu1, MF_ENABLED, IDC_ABOUT, "&About"); - if (has_help()) - AppendMenu(menu1, MF_ENABLED, IDC_GIVEHELP, "&Help"); - AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&Help"); + menu1 = CreateMenu(); + AppendMenu(menu1, MF_ENABLED, IDC_ABOUT, "&About"); + if (has_help()) + AppendMenu(menu1, MF_ENABLED, IDC_GIVEHELP, "&Help"); + AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT_PTR) menu1, "&Help"); - SetMenu(hwnd, menu); - } + SetMenu(hwnd, menu); + } - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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); + } - { - struct ctlpos cp, cp2; + { + struct ctlpos cp, cp2; int ymax; - /* Accelerators used: acglops1rbvde */ + /* Accelerators used: acglops1rbvde */ - ctlposinit(&cp, hwnd, 4, 4, 4); - beginbox(&cp, "Key", IDC_BOX_KEY); - cp2 = cp; - statictext(&cp2, "No key.", 1, IDC_NOKEY); - cp2 = cp; - statictext(&cp2, "", 1, IDC_GENERATING); - progressbar(&cp2, IDC_PROGRESS); - bigeditctrl(&cp, - "&Public key for pasting into authorized_keys file:", - IDC_PKSTATIC, IDC_KEYDISPLAY, 5); - SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0); - staticedit(&cp, "Key f&ingerprint:", 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); - static2btn(&cp, "Save the generated key", IDC_SAVESTATIC, - "Save p&ublic key", IDC_SAVEPUB, - "&Save private key", IDC_SAVE); - endbox(&cp); - beginbox(&cp, "Parameters", IDC_BOX_PARAMS); - radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 5, - "&RSA", IDC_KEYSSH2RSA, + ctlposinit(&cp, hwnd, 4, 4, 4); + beginbox(&cp, "Key", IDC_BOX_KEY); + cp2 = cp; + statictext(&cp2, "No key.", 1, IDC_NOKEY); + cp2 = cp; + statictext(&cp2, "", 1, IDC_GENERATING); + progressbar(&cp2, IDC_PROGRESS); + bigeditctrl(&cp, + "&Public key for pasting into authorized_keys file:", + IDC_PKSTATIC, IDC_KEYDISPLAY, 5); + SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0); + staticedit(&cp, "Key f&ingerprint:", 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); + static2btn(&cp, "Save the generated key", IDC_SAVESTATIC, + "Save p&ublic key", IDC_SAVEPUB, + "&Save private key", IDC_SAVE); + endbox(&cp); + beginbox(&cp, "Parameters", IDC_BOX_PARAMS); + radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 5, + "&RSA", IDC_KEYSSH2RSA, "&DSA", IDC_KEYSSH2DSA, "&ECDSA", IDC_KEYSSH2ECDSA, "Ed&25519", IDC_KEYSSH2ED25519, - "SSH-&1 (RSA)", IDC_KEYSSH1, + "SSH-&1 (RSA)", IDC_KEYSSH1, NULL); cp2 = cp; - staticedit(&cp2, "Number of &bits in a generated key:", - IDC_BITSSTATIC, IDC_BITS, 20); + staticedit(&cp2, "Number of &bits in a generated key:", + IDC_BITSSTATIC, IDC_BITS, 20); ymax = cp2.ypos; cp2 = cp; - staticddl(&cp2, "Cur&ve to use for generating this key:", + staticddl(&cp2, "Cur&ve to use for generating this key:", IDC_CURVESTATIC, IDC_CURVE, 20); SendDlgItemMessage(hwnd, IDC_CURVE, CB_RESETCONTENT, 0, 0); { @@ -1003,119 +1003,119 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, } ymax = ymax > cp2.ypos ? ymax : cp2.ypos; cp2 = cp; - statictext(&cp2, "(nothing to configure for this key type)", - 1, IDC_NOTHINGSTATIC); + statictext(&cp2, "(nothing to configure for this key type)", + 1, IDC_NOTHINGSTATIC); ymax = ymax > cp2.ypos ? ymax : cp2.ypos; cp.ypos = ymax; - endbox(&cp); - } + endbox(&cp); + } ui_set_key_type(hwnd, state, IDC_KEYSSH2RSA); - SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEY_BITS, false); - SendDlgItemMessage(hwnd, IDC_CURVE, CB_SETCURSEL, + SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEY_BITS, false); + SendDlgItemMessage(hwnd, IDC_CURVE, CB_SETCURSEL, DEFAULT_CURVE_INDEX, 0); - /* - * Initially, hide the progress bar and the key display, - * and show the no-key display. Also disable the Save - * buttons, because with no key we obviously can't save - * anything. - */ - ui_set_state(hwnd, state, 0); + /* + * Initially, hide the progress bar and the key display, + * and show the no-key display. Also disable the Save + * buttons, because with no key we obviously can't save + * anything. + */ + ui_set_state(hwnd, state, 0); - /* - * Load a key file if one was provided on the command line. - */ - if (cmdline_keyfile) { + /* + * Load a key file if one was provided on the command line. + */ + if (cmdline_keyfile) { Filename *fn = filename_from_str(cmdline_keyfile); - load_key_file(hwnd, state, fn, false); + load_key_file(hwnd, state, fn, false); filename_free(fn); } - return 1; + return 1; case WM_MOUSEMOVE: - state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_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) { - /* - * Seed the entropy pool - */ + state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_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) { + /* + * Seed the entropy pool + */ random_reseed( make_ptrlen(state->entropy, state->entropy_size)); - smemclr(state->entropy, state->entropy_size); - sfree(state->entropy); - state->collecting_entropy = false; + smemclr(state->entropy, state->entropy_size); + sfree(state->entropy); + state->collecting_entropy = false; start_generating_key(hwnd, state); - } - } - break; + } + } + break; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDC_KEYSSH1: - case IDC_KEYSSH2RSA: - case IDC_KEYSSH2DSA: + switch (LOWORD(wParam)) { + case IDC_KEYSSH1: + case IDC_KEYSSH2RSA: + case IDC_KEYSSH2DSA: case IDC_KEYSSH2ECDSA: case IDC_KEYSSH2ED25519: - { - state = (struct MainDlgState *) - GetWindowLongPtr(hwnd, GWLP_USERDATA); + { + state = (struct MainDlgState *) + GetWindowLongPtr(hwnd, GWLP_USERDATA); ui_set_key_type(hwnd, state, LOWORD(wParam)); - } - break; - case IDC_QUIT: - PostMessage(hwnd, WM_CLOSE, 0, 0); - break; - case IDC_COMMENTEDIT: - if (HIWORD(wParam) == EN_CHANGE) { - state = (struct MainDlgState *) - GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (state->key_exists) { - HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT); - int len = GetWindowTextLength(editctl); - if (*state->commentptr) - sfree(*state->commentptr); - *state->commentptr = snewn(len + 1, char); - GetWindowText(editctl, *state->commentptr, len + 1); - if (state->ssh2) { - setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, - &state->ssh2key); - } else { - setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, - &state->key); - } - } - } - break; - case IDC_ABOUT: - EnableWindow(hwnd, 0); - DialogBox(hinst, MAKEINTRESOURCE(213), hwnd, AboutProc); - EnableWindow(hwnd, 1); - SetActiveWindow(hwnd); - return 0; - case IDC_GIVEHELP: + } + break; + case IDC_QUIT: + PostMessage(hwnd, WM_CLOSE, 0, 0); + break; + case IDC_COMMENTEDIT: + if (HIWORD(wParam) == EN_CHANGE) { + state = (struct MainDlgState *) + GetWindowLongPtr(hwnd, GWLP_USERDATA); + if (state->key_exists) { + HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT); + int len = GetWindowTextLength(editctl); + if (*state->commentptr) + sfree(*state->commentptr); + *state->commentptr = snewn(len + 1, char); + GetWindowText(editctl, *state->commentptr, len + 1); + if (state->ssh2) { + setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, + &state->ssh2key); + } else { + setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, + &state->key); + } + } + } + break; + case IDC_ABOUT: + EnableWindow(hwnd, 0); + DialogBox(hinst, MAKEINTRESOURCE(213), hwnd, AboutProc); + EnableWindow(hwnd, 1); + SetActiveWindow(hwnd); + return 0; + case IDC_GIVEHELP: if (HIWORD(wParam) == BN_CLICKED || HIWORD(wParam) == BN_DOUBLECLICKED) { - launch_help(hwnd, WINHELP_CTX_puttygen_general); + launch_help(hwnd, WINHELP_CTX_puttygen_general); } - return 0; - case IDC_GENERATE: + return 0; + case IDC_GENERATE: if (HIWORD(wParam) != BN_CLICKED && HIWORD(wParam) != BN_DOUBLECLICKED) - break; - state = - (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (!state->generation_thread_exists) { + break; + state = + (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + if (!state->generation_thread_exists) { unsigned raw_entropy_required; unsigned char *raw_entropy_buf; - BOOL ok; - state->key_bits = GetDlgItemInt(hwnd, IDC_BITS, &ok, false); - if (!ok) - state->key_bits = DEFAULT_KEY_BITS; + BOOL ok; + state->key_bits = GetDlgItemInt(hwnd, IDC_BITS, &ok, false); + if (!ok) + state->key_bits = DEFAULT_KEY_BITS; { int curveindex = SendDlgItemMessage(hwnd, IDC_CURVE, CB_GETCURSEL, 0, 0); @@ -1123,8 +1123,8 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, assert(curveindex < n_ec_nist_curve_lengths); state->curve_bits = ec_nist_curve_lengths[curveindex]; } - /* If we ever introduce a new key type, check it here! */ - state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1); + /* If we ever introduce a new key type, check it here! */ + state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1); state->keytype = RSA; if (IsDlgButtonChecked(hwnd, IDC_KEYSSH2DSA)) { state->keytype = DSA; @@ -1134,34 +1134,34 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, state->keytype = ED25519; } - if ((state->keytype == RSA || state->keytype == DSA) && + if ((state->keytype == RSA || state->keytype == DSA) && state->key_bits < 256) { char *message = dupprintf ("PuTTYgen will not generate a key smaller than 256" " bits.\nKey length reset to default %d. Continue?", DEFAULT_KEY_BITS); - int ret = MessageBox(hwnd, message, "PuTTYgen Warning", - MB_ICONWARNING | MB_OKCANCEL); + int ret = MessageBox(hwnd, message, "PuTTYgen Warning", + MB_ICONWARNING | MB_OKCANCEL); sfree(message); - if (ret != IDOK) - break; - state->key_bits = DEFAULT_KEY_BITS; - SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEY_BITS, false); - } else if ((state->keytype == RSA || state->keytype == DSA) && + if (ret != IDOK) + break; + state->key_bits = DEFAULT_KEY_BITS; + SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEY_BITS, false); + } else if ((state->keytype == RSA || state->keytype == DSA) && state->key_bits < DEFAULT_KEY_BITS) { char *message = dupprintf ("Keys shorter than %d bits are not recommended. " "Really generate this key?", DEFAULT_KEY_BITS); - int ret = MessageBox(hwnd, message, "PuTTYgen Warning", - MB_ICONWARNING | MB_OKCANCEL); + int ret = MessageBox(hwnd, message, "PuTTYgen Warning", + MB_ICONWARNING | MB_OKCANCEL); sfree(message); - if (ret != IDOK) - break; + if (ret != IDOK) + break; } - if (state->keytype == RSA || state->keytype == DSA) + if (state->keytype == RSA || state->keytype == DSA) raw_entropy_required = (state->key_bits / 2) * 2; - else if (state->keytype == ECDSA) + else if (state->keytype == ECDSA) raw_entropy_required = (state->curve_bits / 2) * 2; else raw_entropy_required = 256; @@ -1222,19 +1222,19 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, smemclr(raw_entropy_buf, raw_entropy_required); sfree(raw_entropy_buf); - } - break; - case IDC_SAVE: + } + break; + case IDC_SAVE: case IDC_EXPORT_OPENSSH_AUTO: case IDC_EXPORT_OPENSSH_NEW: case IDC_EXPORT_SSHCOM: - if (HIWORD(wParam) != BN_CLICKED) - break; - state = - (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (state->key_exists) { - char filename[FILENAME_MAX]; - char *passphrase, *passphrase2; + if (HIWORD(wParam) != BN_CLICKED) + break; + state = + (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + if (state->key_exists) { + char filename[FILENAME_MAX]; + char *passphrase, *passphrase2; int type, realtype; if (state->ssh2) @@ -1257,54 +1257,54 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, sprintf(msg, "Cannot export an SSH-%d key in an SSH-%d" " format", (state->ssh2 ? 2 : 1), (state->ssh2 ? 1 : 2)); - MessageBox(hwnd, msg, + MessageBox(hwnd, msg, "PuTTYgen Error", MB_OK | MB_ICONERROR); - break; + break; } - passphrase = GetDlgItemText_alloc(hwnd, IDC_PASSPHRASE1EDIT); - passphrase2 = GetDlgItemText_alloc(hwnd, IDC_PASSPHRASE2EDIT); - if (strcmp(passphrase, passphrase2)) { - MessageBox(hwnd, - "The two passphrases given do not match.", - "PuTTYgen Error", MB_OK | MB_ICONERROR); + passphrase = GetDlgItemText_alloc(hwnd, IDC_PASSPHRASE1EDIT); + passphrase2 = GetDlgItemText_alloc(hwnd, IDC_PASSPHRASE2EDIT); + if (strcmp(passphrase, passphrase2)) { + MessageBox(hwnd, + "The two passphrases given do not match.", + "PuTTYgen Error", MB_OK | MB_ICONERROR); burnstr(passphrase); burnstr(passphrase2); - break; - } + break; + } burnstr(passphrase2); - 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) { + 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) { burnstr(passphrase); break; } - } - if (prompt_keyfile(hwnd, "Save private key as:", - filename, true, (type == realtype))) { - int ret; - FILE *fp = fopen(filename, "r"); - if (fp) { - char *buffer; - fclose(fp); - buffer = dupprintf("Overwrite existing file\n%s?", - filename); - ret = MessageBox(hwnd, buffer, "PuTTYgen Warning", - MB_YESNO | MB_ICONWARNING); - sfree(buffer); - if (ret != IDYES) { + } + if (prompt_keyfile(hwnd, "Save private key as:", + filename, true, (type == realtype))) { + int ret; + FILE *fp = fopen(filename, "r"); + if (fp) { + char *buffer; + fclose(fp); + buffer = dupprintf("Overwrite existing file\n%s?", + filename); + ret = MessageBox(hwnd, buffer, "PuTTYgen Warning", + MB_YESNO | MB_ICONWARNING); + sfree(buffer); + if (ret != IDYES) { burnstr(passphrase); - break; + break; } - } + } - if (state->ssh2) { - Filename *fn = filename_from_str(filename); + if (state->ssh2) { + Filename *fn = filename_from_str(filename); if (type != realtype) ret = export_ssh2(fn, type, &state->ssh2key, *passphrase ? passphrase : NULL); @@ -1313,8 +1313,8 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, *passphrase ? passphrase : NULL); filename_free(fn); - } else { - Filename *fn = filename_from_str(filename); + } else { + Filename *fn = filename_from_str(filename); if (type != realtype) ret = export_ssh1(fn, type, &state->key, *passphrase ? passphrase : NULL); @@ -1323,37 +1323,37 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, fn, &state->key, *passphrase ? passphrase : NULL); filename_free(fn); - } - if (ret <= 0) { - MessageBox(hwnd, "Unable to save key file", - "PuTTYgen Error", MB_OK | MB_ICONERROR); - } - } + } + if (ret <= 0) { + MessageBox(hwnd, "Unable to save key file", + "PuTTYgen Error", MB_OK | MB_ICONERROR); + } + } burnstr(passphrase); - } - break; - case IDC_SAVEPUB: - if (HIWORD(wParam) != BN_CLICKED) - break; - state = - (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (state->key_exists) { - char filename[FILENAME_MAX]; - if (prompt_keyfile(hwnd, "Save public key as:", - filename, true, false)) { - int ret; - FILE *fp = fopen(filename, "r"); - if (fp) { - char *buffer; - fclose(fp); - buffer = dupprintf("Overwrite existing file\n%s?", - filename); - ret = MessageBox(hwnd, buffer, "PuTTYgen Warning", - MB_YESNO | MB_ICONWARNING); - sfree(buffer); - if (ret != IDYES) - break; - } + } + break; + case IDC_SAVEPUB: + if (HIWORD(wParam) != BN_CLICKED) + break; + state = + (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + if (state->key_exists) { + char filename[FILENAME_MAX]; + if (prompt_keyfile(hwnd, "Save public key as:", + filename, true, false)) { + int ret; + FILE *fp = fopen(filename, "r"); + if (fp) { + char *buffer; + fclose(fp); + buffer = dupprintf("Overwrite existing file\n%s?", + filename); + ret = MessageBox(hwnd, buffer, "PuTTYgen Warning", + MB_YESNO | MB_ICONWARNING); + sfree(buffer); + if (ret != IDYES) + break; + } fp = fopen(filename, "w"); if (!fp) { MessageBox(hwnd, "Unable to open key file", @@ -1375,114 +1375,114 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, "PuTTYgen Error", MB_OK | MB_ICONERROR); } } - } - } - break; - case IDC_LOAD: - case IDC_IMPORT: - if (HIWORD(wParam) != BN_CLICKED) - break; - state = - (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (!state->generation_thread_exists) { - char filename[FILENAME_MAX]; - if (prompt_keyfile(hwnd, "Load private key:", filename, false, + } + } + break; + case IDC_LOAD: + case IDC_IMPORT: + if (HIWORD(wParam) != BN_CLICKED) + break; + state = + (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + if (!state->generation_thread_exists) { + char filename[FILENAME_MAX]; + if (prompt_keyfile(hwnd, "Load private key:", filename, false, LOWORD(wParam) == IDC_LOAD)) { Filename *fn = filename_from_str(filename); - load_key_file(hwnd, state, fn, LOWORD(wParam) != IDC_LOAD); + load_key_file(hwnd, state, fn, LOWORD(wParam) != IDC_LOAD); filename_free(fn); } - } - break; - } - return 0; + } + break; + } + return 0; case WM_DONEKEY: - state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - state->generation_thread_exists = false; - state->key_exists = true; - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, - MAKELPARAM(0, PROGRESSRANGE)); - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0); - if (state->ssh2) { + state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + state->generation_thread_exists = false; + state->key_exists = true; + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, + MAKELPARAM(0, PROGRESSRANGE)); + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0); + if (state->ssh2) { if (state->keytype == DSA) { - state->ssh2key.key = &state->dsskey.sshk; + state->ssh2key.key = &state->dsskey.sshk; } else if (state->keytype == ECDSA) { state->ssh2key.key = &state->eckey.sshk; } else if (state->keytype == ED25519) { state->ssh2key.key = &state->edkey.sshk; - } else { - state->ssh2key.key = &state->key.sshk; - } - state->commentptr = &state->ssh2key.comment; - } 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 = snewn(30, char); - { - struct tm tm; - tm = ltime(); + } else { + state->ssh2key.key = &state->key.sshk; + } + state->commentptr = &state->ssh2key.comment; + } 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 = snewn(30, char); + { + struct tm tm; + tm = ltime(); if (state->keytype == DSA) - strftime(*state->commentptr, 30, "dsa-key-%Y%m%d", &tm); + strftime(*state->commentptr, 30, "dsa-key-%Y%m%d", &tm); else if (state->keytype == ECDSA) strftime(*state->commentptr, 30, "ecdsa-key-%Y%m%d", &tm); else if (state->keytype == ED25519) strftime(*state->commentptr, 30, "ed25519-key-%Y%m%d", &tm); - else - strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", &tm); - } + else + strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", &tm); + } - /* - * Now update the key controls with all the key data. - */ - { - char *fp, *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. - */ - savecomment = *state->commentptr; - *state->commentptr = NULL; - if (state->ssh2) - fp = ssh2_fingerprint(state->ssh2key.key); + /* + * Now update the key controls with all the key data. + */ + { + char *fp, *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. + */ + savecomment = *state->commentptr; + *state->commentptr = NULL; + if (state->ssh2) + fp = ssh2_fingerprint(state->ssh2key.key); else fp = rsa_ssh1_fingerprint(&state->key); SetDlgItemText(hwnd, IDC_FINGERPRINT, fp); sfree(fp); - *state->commentptr = savecomment; - /* - * Construct a decimal representation of the key, for - * pasting into .ssh/authorized_keys or - * .ssh/authorized_keys2 on a Unix box. - */ - if (state->ssh2) { - setupbigedit2(hwnd, IDC_KEYDISPLAY, - IDC_PKSTATIC, &state->ssh2key); - } else { - setupbigedit1(hwnd, IDC_KEYDISPLAY, - IDC_PKSTATIC, &state->key); - } - } - /* - * Finally, hide the progress bar and show the key data. - */ - ui_set_state(hwnd, state, 2); - break; + *state->commentptr = savecomment; + /* + * Construct a decimal representation of the key, for + * pasting into .ssh/authorized_keys or + * .ssh/authorized_keys2 on a Unix box. + */ + if (state->ssh2) { + setupbigedit2(hwnd, IDC_KEYDISPLAY, + IDC_PKSTATIC, &state->ssh2key); + } else { + setupbigedit1(hwnd, IDC_KEYDISPLAY, + IDC_PKSTATIC, &state->key); + } + } + /* + * Finally, hide the progress bar and show the key data. + */ + ui_set_state(hwnd, state, 2); + break; case WM_HELP: { int id = ((LPHELPINFO)lParam)->iCtrlId; @@ -1539,11 +1539,11 @@ static INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT msg, } break; case WM_CLOSE: - state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); - sfree(state); - quit_help(hwnd); - EndDialog(hwnd, 1); - return 0; + state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); + sfree(state); + quit_help(hwnd); + EndDialog(hwnd, 1); + return 0; } return 0; } @@ -1574,26 +1574,26 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) split_into_argv(cmdline, &argc, &argv, NULL); for (i = 0; i < argc; i++) { - if (!strcmp(argv[i], "-pgpfp")) { - pgp_fingerprints(); - return 1; + if (!strcmp(argv[i], "-pgpfp")) { + pgp_fingerprints(); + return 1; } else if (!strcmp(argv[i], "-restrict-acl") || !strcmp(argv[i], "-restrict_acl") || !strcmp(argv[i], "-restrictacl")) { restrict_process_acl(); - } else { - /* - * Assume the first argument to be a private key file, and - * attempt to load it. - */ - cmdline_keyfile = argv[i]; + } else { + /* + * Assume the first argument to be a private key file, and + * attempt to load it. + */ + cmdline_keyfile = argv[i]; break; - } + } } random_setup_special(); ret = DialogBox(hinst, MAKEINTRESOURCE(201), NULL, MainDlgProc) != IDOK; cleanup_exit(ret); - return ret; /* just in case optimiser complains */ + return ret; /* just in case optimiser complains */ } diff --git a/windows/winpgnt.c b/windows/winpgnt.c index b777fca5..83c516c2 100644 --- a/windows/winpgnt.c +++ b/windows/winpgnt.c @@ -80,7 +80,7 @@ void modalfatalbox(const char *fmt, ...) buf = dupvprintf(fmt, ap); va_end(ap); MessageBox(hwnd, buf, "Pageant Fatal Error", - MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); + MB_SYSTEMMODAL | MB_ICONERROR | MB_OK); sfree(buf); exit(1); } @@ -96,23 +96,23 @@ struct PassphraseProcStruct { * Dialog-box function for the Licence box. */ static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: SetDlgItemText(hwnd, 1000, LICENCE_TEXT("\r\n\r\n")); - return 1; + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - EndDialog(hwnd, 1); - return 0; - } - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + EndDialog(hwnd, 1); + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 1); - return 0; + EndDialog(hwnd, 1); + return 0; } return 0; } @@ -121,7 +121,7 @@ static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg, * Dialog-box function for the About box. */ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: @@ -135,32 +135,32 @@ static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg, SetDlgItemText(hwnd, 1000, text); sfree(text); } - return 1; + return 1; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - aboutbox = NULL; - DestroyWindow(hwnd); - return 0; - case 101: - EnableWindow(hwnd, 0); - DialogBox(hinst, MAKEINTRESOURCE(214), hwnd, LicenceProc); - EnableWindow(hwnd, 1); - SetActiveWindow(hwnd); - return 0; - case 102: - /* Load web browser */ - ShellExecute(hwnd, "open", - "https://www.chiark.greenend.org.uk/~sgtatham/putty/", - 0, 0, SW_SHOWDEFAULT); - return 0; - } - return 0; + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + aboutbox = NULL; + DestroyWindow(hwnd); + return 0; + case 101: + EnableWindow(hwnd, 0); + DialogBox(hinst, MAKEINTRESOURCE(214), hwnd, LicenceProc); + EnableWindow(hwnd, 1); + SetActiveWindow(hwnd); + return 0; + case 102: + /* Load web browser */ + ShellExecute(hwnd, "open", + "https://www.chiark.greenend.org.uk/~sgtatham/putty/", + 0, 0, SW_SHOWDEFAULT); + return 0; + } + return 0; case WM_CLOSE: - aboutbox = NULL; - DestroyWindow(hwnd); - return 0; + aboutbox = NULL; + DestroyWindow(hwnd); + return 0; } return 0; } @@ -171,62 +171,62 @@ static HWND passphrase_box; * Dialog-box function for the passphrase box. */ static INT_PTR 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: - passphrase_box = hwnd; - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + passphrase_box = hwnd; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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); + } - 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); + 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); burnstr(*passphrase); *passphrase = dupstr(""); - SetDlgItemText(hwnd, 102, *passphrase); - return 0; + SetDlgItemText(hwnd, 102, *passphrase); + return 0; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - if (*passphrase) - EndDialog(hwnd, 1); - else - MessageBeep(0); - return 0; - case IDCANCEL: - EndDialog(hwnd, 0); - return 0; - case 102: /* edit box */ - if ((HIWORD(wParam) == EN_CHANGE) && passphrase) { + switch (LOWORD(wParam)) { + case IDOK: + if (*passphrase) + EndDialog(hwnd, 1); + else + MessageBeep(0); + return 0; + case IDCANCEL: + EndDialog(hwnd, 0); + return 0; + case 102: /* edit box */ + if ((HIWORD(wParam) == EN_CHANGE) && passphrase) { burnstr(*passphrase); *passphrase = GetDlgItemText_alloc(hwnd, 102); - } - return 0; - } - return 0; + } + return 0; + } + return 0; case WM_CLOSE: - EndDialog(hwnd, 0); - return 0; + EndDialog(hwnd, 0); + return 0; } return 0; } @@ -238,15 +238,15 @@ void old_keyfile_warning(void) { static const char mbtitle[] = "PuTTY Key File Warning"; static const char message[] = - "You are loading an SSH-2 private key which has an\n" - "old version of the file format. This means your key\n" - "file is not fully tamperproof. Future versions of\n" - "PuTTY may stop supporting this private key format,\n" - "so we recommend you convert your key to the new\n" - "format.\n" - "\n" - "You can perform this conversion by loading the key\n" - "into PuTTYgen and then saving it again."; + "You are loading an SSH-2 private key which has an\n" + "old version of the file format. This means your key\n" + "file is not fully tamperproof. Future versions of\n" + "PuTTY may stop supporting this private key format,\n" + "so we recommend you convert your key to the new\n" + "format.\n" + "\n" + "You can perform this conversion by loading the key\n" + "into PuTTYgen and then saving it again."; MessageBox(NULL, message, mbtitle, MB_OK); } @@ -261,31 +261,31 @@ void keylist_update(void) int i; if (keylist) { - SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0); - for (i = 0; NULL != (rkey = pageant_nth_ssh1_key(i)); i++) { - char *listentry, *fp, *p; + SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0); + for (i = 0; NULL != (rkey = pageant_nth_ssh1_key(i)); i++) { + char *listentry, *fp, *p; - fp = rsa_ssh1_fingerprint(rkey); - listentry = dupprintf("ssh1\t%s", fp); + fp = rsa_ssh1_fingerprint(rkey); + listentry = dupprintf("ssh1\t%s", fp); sfree(fp); - /* - * Replace two spaces in the fingerprint with tabs, for - * nice alignment in the box. - */ - p = strchr(listentry, ' '); - if (p) - *p = '\t'; - p = strchr(listentry, ' '); - if (p) - *p = '\t'; - SendDlgItemMessage(keylist, 100, LB_ADDSTRING, - 0, (LPARAM) listentry); + /* + * Replace two spaces in the fingerprint with tabs, for + * nice alignment in the box. + */ + p = strchr(listentry, ' '); + if (p) + *p = '\t'; + p = strchr(listentry, ' '); + if (p) + *p = '\t'; + SendDlgItemMessage(keylist, 100, LB_ADDSTRING, + 0, (LPARAM) listentry); sfree(listentry); - } - for (i = 0; NULL != (skey = pageant_nth_ssh2_key(i)); i++) { - char *listentry, *p; - int pos; + } + for (i = 0; NULL != (skey = pageant_nth_ssh2_key(i)); i++) { + char *listentry, *p; + int pos; /* * For nice alignment in the list box, we would ideally @@ -312,7 +312,7 @@ void keylist_update(void) * stop and leave out a tab character. Urgh. */ - p = ssh2_fingerprint(skey->key); + p = ssh2_fingerprint(skey->key); listentry = dupprintf("%s\t%s", p, skey->comment); sfree(p); @@ -345,11 +345,11 @@ void keylist_update(void) } } - SendDlgItemMessage(keylist, 100, LB_ADDSTRING, 0, - (LPARAM) listentry); + SendDlgItemMessage(keylist, 100, LB_ADDSTRING, 0, + (LPARAM) listentry); sfree(listentry); - } - SendDlgItemMessage(keylist, 100, LB_SETCURSEL, (WPARAM) - 1, 0); + } + SendDlgItemMessage(keylist, 100, LB_SETCURSEL, (WPARAM) - 1, 0); } } @@ -386,7 +386,7 @@ static void win_add_keyfile(Filename *filename) passphrase_box = NULL; if (!dlgret) - goto done; /* operation cancelled */ + goto done; /* operation cancelled */ sfree(err); @@ -423,7 +423,7 @@ static void prompt_add_keyfile(void) { OPENFILENAME of; char *filelist = snewn(8192, char); - + if (!keypath) keypath = filereq_new(); memset(&of, 0, sizeof(of)); of.hwndOwner = hwnd; @@ -437,31 +437,31 @@ static void prompt_add_keyfile(void) of.lpstrTitle = "Select Private Key File"; of.Flags = OFN_ALLOWMULTISELECT | OFN_EXPLORER; if (request_file(keypath, &of, true, false)) { - if(strlen(filelist) > of.nFileOffset) { - /* Only one filename returned? */ + if(strlen(filelist) > of.nFileOffset) { + /* Only one filename returned? */ Filename *fn = filename_from_str(filelist); - win_add_keyfile(fn); + win_add_keyfile(fn); filename_free(fn); } else { - /* we are returned a bunch of strings, end to - * end. first string is the directory, the - * rest the filenames. terminated with an - * empty string. - */ - char *dir = filelist; - char *filewalker = filelist + strlen(dir) + 1; - while (*filewalker != '\0') { - char *filename = dupcat(dir, "\\", filewalker, NULL); + /* we are returned a bunch of strings, end to + * end. first string is the directory, the + * rest the filenames. terminated with an + * empty string. + */ + char *dir = filelist; + char *filewalker = filelist + strlen(dir) + 1; + while (*filewalker != '\0') { + char *filename = dupcat(dir, "\\", filewalker, NULL); Filename *fn = filename_from_str(filename); - win_add_keyfile(fn); + win_add_keyfile(fn); filename_free(fn); - sfree(filename); - filewalker += strlen(filewalker) + 1; - } - } + sfree(filename); + filewalker += strlen(filewalker) + 1; + } + } - keylist_update(); - pageant_forget_passphrases(); + keylist_update(); + pageant_forget_passphrases(); } sfree(filelist); } @@ -470,112 +470,112 @@ static void prompt_add_keyfile(void) * Dialog-box function for the key list box. */ static INT_PTR CALLBACK KeyListProc(HWND hwnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { RSAKey *rkey; ssh2_userkey *skey; switch (msg) { case WM_INITDIALOG: - /* - * Centre the window. - */ - { /* centre the window */ - RECT rs, rd; - HWND hw; + /* + * Centre the window. + */ + { /* centre the window */ + RECT rs, rd; + 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); - } + 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 (has_help()) SetWindowLongPtr(hwnd, GWL_EXSTYLE, - GetWindowLongPtr(hwnd, GWL_EXSTYLE) | - WS_EX_CONTEXTHELP); + GetWindowLongPtr(hwnd, GWL_EXSTYLE) | + WS_EX_CONTEXTHELP); else { HWND item = GetDlgItem(hwnd, 103); /* the Help button */ if (item) DestroyWindow(item); } - keylist = hwnd; - { - static int tabs[] = { 35, 75, 250 }; - SendDlgItemMessage(hwnd, 100, LB_SETTABSTOPS, - sizeof(tabs) / sizeof(*tabs), - (LPARAM) tabs); - } - keylist_update(); - return 0; + keylist = hwnd; + { + static int tabs[] = { 35, 75, 250 }; + SendDlgItemMessage(hwnd, 100, LB_SETTABSTOPS, + sizeof(tabs) / sizeof(*tabs), + (LPARAM) tabs); + } + keylist_update(); + return 0; case WM_COMMAND: - switch (LOWORD(wParam)) { - case IDOK: - case IDCANCEL: - keylist = NULL; - DestroyWindow(hwnd); - return 0; - case 101: /* add key */ - if (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED) { - if (passphrase_box) { - MessageBeep(MB_ICONERROR); - SetForegroundWindow(passphrase_box); - break; - } - prompt_add_keyfile(); - } - return 0; - case 102: /* remove key */ - if (HIWORD(wParam) == BN_CLICKED || - HIWORD(wParam) == BN_DOUBLECLICKED) { - int i; - int rCount, sCount; - int *selectedArray; - - /* our counter within the array of selected items */ - int itemNum; - - /* get the number of items selected in the list */ - int numSelected = - SendDlgItemMessage(hwnd, 100, LB_GETSELCOUNT, 0, 0); - - /* none selected? that was silly */ - if (numSelected == 0) { - MessageBeep(0); - break; - } + switch (LOWORD(wParam)) { + case IDOK: + case IDCANCEL: + keylist = NULL; + DestroyWindow(hwnd); + return 0; + case 101: /* add key */ + if (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED) { + if (passphrase_box) { + MessageBeep(MB_ICONERROR); + SetForegroundWindow(passphrase_box); + break; + } + prompt_add_keyfile(); + } + return 0; + case 102: /* remove key */ + if (HIWORD(wParam) == BN_CLICKED || + HIWORD(wParam) == BN_DOUBLECLICKED) { + int i; + int rCount, sCount; + int *selectedArray; - /* get item indices in an array */ - selectedArray = snewn(numSelected, int); - SendDlgItemMessage(hwnd, 100, LB_GETSELITEMS, - numSelected, (WPARAM)selectedArray); - - itemNum = numSelected - 1; - rCount = pageant_count_ssh1_keys(); - sCount = pageant_count_ssh2_keys(); - - /* go through the non-rsakeys until we've covered them all, - * and/or we're out of selected items to check. note that - * we go *backwards*, to avoid complications from deleting - * things hence altering the offset of subsequent items - */ + /* our counter within the array of selected items */ + int itemNum; + + /* get the number of items selected in the list */ + int numSelected = + SendDlgItemMessage(hwnd, 100, LB_GETSELCOUNT, 0, 0); + + /* none selected? that was silly */ + if (numSelected == 0) { + MessageBeep(0); + break; + } + + /* get item indices in an array */ + selectedArray = snewn(numSelected, int); + SendDlgItemMessage(hwnd, 100, LB_GETSELITEMS, + numSelected, (WPARAM)selectedArray); + + itemNum = numSelected - 1; + rCount = pageant_count_ssh1_keys(); + sCount = pageant_count_ssh2_keys(); + + /* go through the non-rsakeys until we've covered them all, + * and/or we're out of selected items to check. note that + * we go *backwards*, to avoid complications from deleting + * things hence altering the offset of subsequent items + */ for (i = sCount - 1; (itemNum >= 0) && (i >= 0); i--) { skey = pageant_nth_ssh2_key(i); - + if (selectedArray[itemNum] == rCount + i) { pageant_delete_ssh2_key(skey); ssh_key_free(skey->key); sfree(skey); itemNum--; } - } - - /* do the same for the rsa keys */ - for (i = rCount - 1; (itemNum >= 0) && (i >= 0); i--) { + } + + /* do the same for the rsa keys */ + for (i = rCount - 1; (itemNum >= 0) && (i >= 0); i--) { rkey = pageant_nth_ssh1_key(i); if(selectedArray[itemNum] == i) { @@ -584,20 +584,20 @@ static INT_PTR CALLBACK KeyListProc(HWND hwnd, UINT msg, sfree(rkey); itemNum--; } - } + } - sfree(selectedArray); - keylist_update(); - } - return 0; - case 103: /* help */ + sfree(selectedArray); + keylist_update(); + } + return 0; + case 103: /* help */ if (HIWORD(wParam) == BN_CLICKED || HIWORD(wParam) == BN_DOUBLECLICKED) { - launch_help(hwnd, WINHELP_CTX_pageant_general); + launch_help(hwnd, WINHELP_CTX_pageant_general); } - return 0; - } - return 0; + return 0; + } + return 0; case WM_HELP: { int id = ((LPHELPINFO)lParam)->iCtrlId; @@ -608,16 +608,16 @@ static INT_PTR CALLBACK KeyListProc(HWND hwnd, UINT msg, case 102: topic = WINHELP_CTX_pageant_remkey; break; } if (topic) { - launch_help(hwnd, topic); + launch_help(hwnd, topic); } else { MessageBeep(0); } } break; case WM_CLOSE: - keylist = NULL; - DestroyWindow(hwnd); - return 0; + keylist = NULL; + DestroyWindow(hwnd); + return 0; } return 0; } @@ -636,7 +636,7 @@ static BOOL AddTrayIcon(HWND hwnd) 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(hinst, MAKEINTRESOURCE(201)); @@ -645,7 +645,7 @@ static BOOL AddTrayIcon(HWND hwnd) res = Shell_NotifyIcon(NIM_ADD, &tnid); if (hicon) DestroyIcon(hicon); - + return res; } @@ -661,48 +661,48 @@ static void update_sessions(void) int index_key, index_menu; if (!putty_path) - return; + return; if(ERROR_SUCCESS != RegOpenKey(HKEY_CURRENT_USER, PUTTY_REGKEY, &hkey)) - return; + return; for(num_entries = GetMenuItemCount(session_menu); - num_entries > initial_menuitems_count; - num_entries--) - RemoveMenu(session_menu, 0, MF_BYPOSITION); + num_entries > initial_menuitems_count; + num_entries--) + RemoveMenu(session_menu, 0, MF_BYPOSITION); index_key = 0; index_menu = 0; sb = strbuf_new(); while(ERROR_SUCCESS == RegEnumKey(hkey, index_key, buf, MAX_PATH)) { - if(strcmp(buf, PUTTY_DEFAULT) != 0) { + if(strcmp(buf, PUTTY_DEFAULT) != 0) { sb->len = 0; unescape_registry_key(buf, sb); - memset(&mii, 0, sizeof(mii)); - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID; - mii.fType = MFT_STRING; - mii.fState = MFS_ENABLED; - mii.wID = (index_menu * 16) + IDM_SESSIONS_BASE; - mii.dwTypeData = sb->s; - InsertMenuItem(session_menu, index_menu, true, &mii); - index_menu++; - } - index_key++; + memset(&mii, 0, sizeof(mii)); + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID; + mii.fType = MFT_STRING; + mii.fState = MFS_ENABLED; + mii.wID = (index_menu * 16) + IDM_SESSIONS_BASE; + mii.dwTypeData = sb->s; + InsertMenuItem(session_menu, index_menu, true, &mii); + index_menu++; + } + index_key++; } strbuf_free(sb); RegCloseKey(hkey); if(index_menu == 0) { - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_TYPE | MIIM_STATE; - mii.fType = MFT_STRING; - mii.fState = MFS_GRAYED; - mii.dwTypeData = _T("(No sessions)"); - InsertMenuItem(session_menu, index_menu, true, &mii); + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_TYPE | MIIM_STATE; + mii.fType = MFT_STRING; + mii.fState = MFS_GRAYED; + mii.dwTypeData = _T("(No sessions)"); + InsertMenuItem(session_menu, index_menu, true, &mii); } } @@ -940,7 +940,7 @@ static char *answer_filemapping_message(const char *mapname) } static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { static bool menuinprogress; static UINT msgTaskbarCreated = 0; @@ -952,41 +952,41 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, default: if (message==msgTaskbarCreated) { /* - * Explorer has been restarted, so the tray icon will - * have been lost. - */ - AddTrayIcon(hwnd); + * Explorer has been restarted, so the tray icon will + * have been lost. + */ + AddTrayIcon(hwnd); } break; - + case WM_SYSTRAY: - if (lParam == WM_RBUTTONUP) { - POINT cursorpos; - GetCursorPos(&cursorpos); - PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y); - } else if (lParam == WM_LBUTTONDBLCLK) { - /* Run the default menu item. */ - UINT menuitem = GetMenuDefaultItem(systray_menu, false, 0); - if (menuitem != -1) - PostMessage(hwnd, WM_COMMAND, menuitem, 0); - } - break; + if (lParam == WM_RBUTTONUP) { + POINT cursorpos; + GetCursorPos(&cursorpos); + PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y); + } else if (lParam == WM_LBUTTONDBLCLK) { + /* Run the default menu item. */ + UINT menuitem = GetMenuDefaultItem(systray_menu, false, 0); + if (menuitem != -1) + PostMessage(hwnd, WM_COMMAND, menuitem, 0); + } + break; case WM_SYSTRAY2: - if (!menuinprogress) { - menuinprogress = true; - update_sessions(); - SetForegroundWindow(hwnd); - TrackPopupMenu(systray_menu, - TPM_RIGHTALIGN | TPM_BOTTOMALIGN | - TPM_RIGHTBUTTON, - wParam, lParam, 0, hwnd, NULL); - menuinprogress = false; - } - break; + if (!menuinprogress) { + menuinprogress = true; + update_sessions(); + SetForegroundWindow(hwnd); + TrackPopupMenu(systray_menu, + TPM_RIGHTALIGN | TPM_BOTTOMALIGN | + TPM_RIGHTBUTTON, + wParam, lParam, 0, hwnd, NULL); + menuinprogress = false; + } + break; case WM_COMMAND: case WM_SYSCOMMAND: - switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */ - case IDM_PUTTY: + switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */ + case IDM_PUTTY: { TCHAR cmdline[10]; cmdline[0] = '\0'; @@ -999,96 +999,96 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, "Error", MB_OK | MB_ICONERROR); } } - break; - case IDM_CLOSE: - if (passphrase_box) - SendMessage(passphrase_box, WM_CLOSE, 0, 0); - SendMessage(hwnd, WM_CLOSE, 0, 0); - break; - case IDM_VIEWKEYS: - if (!keylist) { - keylist = CreateDialog(hinst, MAKEINTRESOURCE(211), - NULL, KeyListProc); - ShowWindow(keylist, SW_SHOWNORMAL); - } - /* - * Sometimes the window comes up minimised / hidden for - * no obvious reason. Prevent this. This also brings it - * to the front if it's already present (the user - * selected View Keys because they wanted to _see_ the - * thing). - */ - SetForegroundWindow(keylist); - SetWindowPos(keylist, HWND_TOP, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); - break; - case IDM_ADDKEY: - if (passphrase_box) { - MessageBeep(MB_ICONERROR); - SetForegroundWindow(passphrase_box); - break; - } - prompt_add_keyfile(); - break; - case IDM_ABOUT: - if (!aboutbox) { - aboutbox = CreateDialog(hinst, 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; - case IDM_HELP: - launch_help(hwnd, WINHELP_CTX_pageant_general); - break; - default: - { - if(wParam >= IDM_SESSIONS_BASE && wParam <= IDM_SESSIONS_MAX) { - MENUITEMINFO mii; - TCHAR buf[MAX_PATH + 1]; - TCHAR param[MAX_PATH + 1]; - memset(&mii, 0, sizeof(mii)); - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_TYPE; - mii.cch = MAX_PATH; - mii.dwTypeData = buf; - GetMenuItemInfo(session_menu, wParam, false, &mii); + break; + case IDM_CLOSE: + if (passphrase_box) + SendMessage(passphrase_box, WM_CLOSE, 0, 0); + SendMessage(hwnd, WM_CLOSE, 0, 0); + break; + case IDM_VIEWKEYS: + if (!keylist) { + keylist = CreateDialog(hinst, MAKEINTRESOURCE(211), + NULL, KeyListProc); + ShowWindow(keylist, SW_SHOWNORMAL); + } + /* + * Sometimes the window comes up minimised / hidden for + * no obvious reason. Prevent this. This also brings it + * to the front if it's already present (the user + * selected View Keys because they wanted to _see_ the + * thing). + */ + SetForegroundWindow(keylist); + SetWindowPos(keylist, HWND_TOP, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); + break; + case IDM_ADDKEY: + if (passphrase_box) { + MessageBeep(MB_ICONERROR); + SetForegroundWindow(passphrase_box); + break; + } + prompt_add_keyfile(); + break; + case IDM_ABOUT: + if (!aboutbox) { + aboutbox = CreateDialog(hinst, 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; + case IDM_HELP: + launch_help(hwnd, WINHELP_CTX_pageant_general); + break; + default: + { + if(wParam >= IDM_SESSIONS_BASE && wParam <= IDM_SESSIONS_MAX) { + MENUITEMINFO mii; + TCHAR buf[MAX_PATH + 1]; + TCHAR param[MAX_PATH + 1]; + memset(&mii, 0, sizeof(mii)); + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_TYPE; + mii.cch = MAX_PATH; + mii.dwTypeData = buf; + GetMenuItemInfo(session_menu, wParam, false, &mii); param[0] = '\0'; if (restrict_putty_acl) strcat(param, "&R"); - strcat(param, "@"); - strcat(param, mii.dwTypeData); - if((INT_PTR)ShellExecute(hwnd, NULL, putty_path, param, - _T(""), SW_SHOW) <= 32) { - MessageBox(NULL, "Unable to execute PuTTY!", "Error", - MB_OK | MB_ICONERROR); - } - } - } - break; - } - break; + strcat(param, "@"); + strcat(param, mii.dwTypeData); + if((INT_PTR)ShellExecute(hwnd, NULL, putty_path, param, + _T(""), SW_SHOW) <= 32) { + MessageBox(NULL, "Unable to execute PuTTY!", "Error", + MB_OK | MB_ICONERROR); + } + } + } + break; + } + break; case WM_DESTROY: - quit_help(hwnd); - PostQuitMessage(0); - return 0; + quit_help(hwnd); + PostQuitMessage(0); + return 0; case WM_COPYDATA: - { - COPYDATASTRUCT *cds; - char *mapname, *err; + { + COPYDATASTRUCT *cds; + char *mapname, *err; - 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! */ + 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! */ err = answer_filemapping_message(mapname); if (err) { #ifdef DEBUG_IPC @@ -1097,8 +1097,8 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, sfree(err); return 0; } - return 1; - } + return 1; + } } return DefWindowProc(hwnd, message, wParam, lParam); @@ -1110,12 +1110,12 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, void spawn_cmd(const char *cmdline, const char *args, int show) { if (ShellExecute(NULL, _T("open"), cmdline, - args, NULL, show) <= (HINSTANCE) 32) { - char *msg; - msg = dupprintf("Failed to run \"%s\": %s", cmdline, - win_strerror(GetLastError())); - MessageBox(NULL, msg, APPNAME, MB_OK | MB_ICONEXCLAMATION); - sfree(msg); + args, NULL, show) <= (HINSTANCE) 32) { + char *msg; + msg = dupprintf("Failed to run \"%s\": %s", cmdline, + win_strerror(GetLastError())); + MessageBox(NULL, msg, APPNAME, MB_OK | MB_ICONEXCLAMATION); + sfree(msg); } } @@ -1124,7 +1124,7 @@ void spawn_cmd(const char *cmdline, const char *args, int show) * asynchronous agent requests. */ void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len) + void *callback_ctx, void *data, int len) { assert(!"We shouldn't get here"); } @@ -1160,22 +1160,22 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) if (has_security) { #ifndef NO_SECURITY - /* - * Attempt to get the security API we need. - */ + /* + * Attempt to get the security API we need. + */ if (!got_advapi()) { - 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; - } + 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" - "not run on NT, in case it causes a security breach.", - "Pageant Fatal Error", MB_ICONERROR | MB_OK); - return 1; + MessageBox(NULL, + "This program has been compiled for Win9X and will\n" + "not run on NT, in case it causes a security breach.", + "Pageant Fatal Error", MB_ICONERROR | MB_OK); + return 1; #endif } @@ -1222,9 +1222,9 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) */ split_into_argv(cmdline, &argc, &argv, &argstart); for (i = 0; i < argc; i++) { - if (!strcmp(argv[i], "-pgpfp")) { - pgp_fingerprints(); - return 1; + if (!strcmp(argv[i], "-pgpfp")) { + pgp_fingerprints(); + return 1; } else if (!strcmp(argv[i], "-restrict-acl") || !strcmp(argv[i], "-restrict_acl") || !strcmp(argv[i], "-restrictacl")) { @@ -1232,23 +1232,23 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) } else if (!strcmp(argv[i], "-restrict-putty-acl") || !strcmp(argv[i], "-restrict_putty_acl")) { restrict_putty_acl = true; - } else if (!strcmp(argv[i], "-c")) { - /* - * If we see `-c', then the rest of the - * command line should be treated as a - * command to be spawned. - */ - if (i < argc-1) - command = argstart[i+1]; - else - command = ""; - break; - } else { + } else if (!strcmp(argv[i], "-c")) { + /* + * If we see `-c', then the rest of the + * command line should be treated as a + * command to be spawned. + */ + if (i < argc-1) + command = argstart[i+1]; + else + command = ""; + break; + } else { Filename *fn = filename_from_str(argv[i]); - win_add_keyfile(fn); + win_add_keyfile(fn); filename_free(fn); - added_keys = true; - } + added_keys = true; + } } /* @@ -1258,16 +1258,16 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) pageant_forget_passphrases(); if (command) { - char *args; - if (command[0] == '"') - args = strchr(++command, '"'); - else - args = strchr(command, ' '); - if (args) { - *args++ = 0; - while(*args && isspace(*args)) args++; - } - spawn_cmd(command, args, show); + char *args; + if (command[0] == '"') + args = strchr(++command, '"'); + else + args = strchr(command, ' '); + if (args) { + *args++ = 0; + while(*args && isspace(*args)) args++; + } + spawn_cmd(command, args, show); } /* @@ -1276,34 +1276,34 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * keys), complain. */ if (already_running) { - if (!command && !added_keys) { - MessageBox(NULL, "Pageant is already running", "Pageant Error", - MB_ICONERROR | MB_OK); - } - return 0; + if (!command && !added_keys) { + MessageBox(NULL, "Pageant is already running", "Pageant Error", + MB_ICONERROR | MB_OK); + } + return 0; } 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.lpszClassName = APPNAME; + 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); } keylist = NULL; hwnd = CreateWindow(APPNAME, APPNAME, - WS_OVERLAPPEDWINDOW | WS_VSCROLL, - CW_USEDEFAULT, CW_USEDEFAULT, - 100, 100, NULL, NULL, inst, NULL); + WS_OVERLAPPEDWINDOW | WS_VSCROLL, + CW_USEDEFAULT, CW_USEDEFAULT, + 100, 100, NULL, NULL, inst, NULL); /* Set up a system tray icon */ AddTrayIcon(hwnd); @@ -1311,18 +1311,18 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) /* Accelerators used: nsvkxa */ systray_menu = CreatePopupMenu(); if (putty_path) { - session_menu = CreateMenu(); - AppendMenu(systray_menu, MF_ENABLED, IDM_PUTTY, "&New Session"); - AppendMenu(systray_menu, MF_POPUP | MF_ENABLED, - (UINT_PTR) session_menu, "&Saved Sessions"); - AppendMenu(systray_menu, MF_SEPARATOR, 0, 0); + session_menu = CreateMenu(); + AppendMenu(systray_menu, MF_ENABLED, IDM_PUTTY, "&New Session"); + AppendMenu(systray_menu, MF_POPUP | MF_ENABLED, + (UINT_PTR) session_menu, "&Saved Sessions"); + AppendMenu(systray_menu, MF_SEPARATOR, 0, 0); } AppendMenu(systray_menu, MF_ENABLED, IDM_VIEWKEYS, - "&View Keys"); + "&View Keys"); AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key"); AppendMenu(systray_menu, MF_SEPARATOR, 0, 0); if (has_help()) - AppendMenu(systray_menu, MF_ENABLED, IDM_HELP, "&Help"); + AppendMenu(systray_menu, MF_ENABLED, IDM_HELP, "&Help"); AppendMenu(systray_menu, MF_ENABLED, IDM_ABOUT, "&About"); AppendMenu(systray_menu, MF_SEPARATOR, 0, 0); AppendMenu(systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit"); @@ -1337,28 +1337,28 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) * Main message loop. */ while (GetMessage(&msg, NULL, 0, 0) == 1) { - if (!(IsWindow(keylist) && IsDialogMessage(keylist, &msg)) && - !(IsWindow(aboutbox) && IsDialogMessage(aboutbox, &msg))) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + if (!(IsWindow(keylist) && IsDialogMessage(keylist, &msg)) && + !(IsWindow(aboutbox) && IsDialogMessage(aboutbox, &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 (keypath) filereq_free(keypath); cleanup_exit(msg.wParam); - return msg.wParam; /* just in case optimiser complains */ + return msg.wParam; /* just in case optimiser complains */ } diff --git a/windows/winpgntc.c b/windows/winpgntc.c index 05608831..7166585b 100644 --- a/windows/winpgntc.c +++ b/windows/winpgntc.c @@ -20,9 +20,9 @@ bool agent_exists(void) HWND hwnd; hwnd = FindWindow("Pageant", "Pageant"); if (!hwnd) - return false; + return false; else - return true; + return true; } void agent_cancel_query(agent_pending_query *q) @@ -52,7 +52,7 @@ agent_pending_query *agent_query( hwnd = FindWindow("Pageant", "Pageant"); if (!hwnd) - return NULL; /* *out == NULL, so failure */ + return NULL; /* *out == NULL, so failure */ mapname = dupprintf("PageantRequest%08x", (unsigned)GetCurrentThreadId()); psa = NULL; @@ -90,10 +90,10 @@ agent_pending_query *agent_query( #endif /* NO_SECURITY */ filemap = CreateFileMapping(INVALID_HANDLE_VALUE, psa, PAGE_READWRITE, - 0, AGENT_MAX_MSGLEN, mapname); + 0, AGENT_MAX_MSGLEN, mapname); if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) { sfree(mapname); - return NULL; /* *out == NULL, so failure */ + return NULL; /* *out == NULL, so failure */ } p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0); strbuf_finalise_agent_query(query); @@ -113,7 +113,7 @@ agent_pending_query *agent_query( if (length_field > 0 && length_field <= AGENT_MAX_MSGLEN - 4) { retlen = length_field + 4; ret = snewn(retlen, unsigned char); - memcpy(ret, p, retlen); + memcpy(ret, p, retlen); *out = ret; *outlen = retlen; } else { diff --git a/windows/winplink.c b/windows/winplink.c index 46c19c69..55aa088c 100644 --- a/windows/winplink.c +++ b/windows/winplink.c @@ -7,7 +7,7 @@ #include #include -#define PUTTY_DO_GLOBALS /* actually _define_ globals */ +#define PUTTY_DO_GLOBALS /* actually _define_ globals */ #include "putty.h" #include "storage.h" #include "tree234.h" @@ -50,13 +50,13 @@ static void plink_echoedit_update(Seat *seat, bool echo, bool edit) 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); } @@ -80,7 +80,7 @@ static int plink_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = console_get_userpass_input(p); + ret = console_get_userpass_input(p); return ret; } @@ -109,7 +109,7 @@ static Seat plink_seat[1] = {{ &plink_seat_vt }}; static DWORD main_thread_id; void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len) + void *callback_ctx, void *data, int len) { struct agent_callback *c = snew(struct agent_callback); c->callback = callback; @@ -194,18 +194,18 @@ char *do_select(SOCKET skt, bool startup) { int events; if (startup) { - events = (FD_CONNECT | FD_READ | FD_WRITE | - FD_OOB | FD_CLOSE | FD_ACCEPT); + events = (FD_CONNECT | FD_READ | FD_WRITE | + FD_OOB | FD_CLOSE | FD_ACCEPT); } else { - events = 0; + events = 0; } if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) { - switch (p_WSAGetLastError()) { - case WSAENETDOWN: - return "Network is down"; - default: - return "WSAEventSelect(): unknown error"; - } + switch (p_WSAGetLastError()) { + case WSAENETDOWN: + return "Network is down"; + default: + return "WSAEventSelect(): unknown error"; + } } return NULL; } @@ -213,40 +213,40 @@ char *do_select(SOCKET skt, bool startup) size_t stdin_gotdata(struct handle *h, const void *data, size_t len, int err) { if (err) { - char buf[4096]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, - buf, lenof(buf), NULL); - buf[lenof(buf)-1] = '\0'; - if (buf[strlen(buf)-1] == '\n') - buf[strlen(buf)-1] = '\0'; - fprintf(stderr, "Unable to read from standard input: %s\n", buf); - cleanup_exit(0); + char buf[4096]; + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, + buf, lenof(buf), NULL); + buf[lenof(buf)-1] = '\0'; + if (buf[strlen(buf)-1] == '\n') + buf[strlen(buf)-1] = '\0'; + fprintf(stderr, "Unable to read from standard input: %s\n", buf); + cleanup_exit(0); } noise_ultralight(NOISE_SOURCE_IOLEN, len); if (backend_connected(backend)) { - if (len > 0) { + if (len > 0) { return backend_send(backend, data, len); - } else { + } else { backend_special(backend, SS_EOF, 0); - return 0; - } + return 0; + } } else - return 0; + return 0; } void stdouterr_sent(struct handle *h, size_t new_backlog, int err) { if (err) { - char buf[4096]; - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, - buf, lenof(buf), NULL); - buf[lenof(buf)-1] = '\0'; - if (buf[strlen(buf)-1] == '\n') - buf[strlen(buf)-1] = '\0'; - fprintf(stderr, "Unable to write to standard %s: %s\n", - (h == stdout_handle ? "output" : "error"), buf); - cleanup_exit(0); + char buf[4096]; + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, + buf, lenof(buf), NULL); + buf[lenof(buf)-1] = '\0'; + if (buf[strlen(buf)-1] == '\n') + buf[strlen(buf)-1] = '\0'; + fprintf(stderr, "Unable to write to standard %s: %s\n", + (h == stdout_handle ? "output" : "error"), buf); + cleanup_exit(0); } if (backend_connected(backend)) { @@ -299,22 +299,22 @@ int main(int argc, char **argv) default_port = conf_get_int(conf, CONF_port); errors = false; { - /* - * Override the default protocol if PLINK_PROTOCOL is set. - */ - char *p = getenv("PLINK_PROTOCOL"); - if (p) { + /* + * Override the default protocol if PLINK_PROTOCOL is set. + */ + char *p = getenv("PLINK_PROTOCOL"); + if (p) { const struct BackendVtable *vt = backend_vt_from_name(p); if (vt) { default_protocol = vt->protocol; default_port = vt->default_port; - conf_set_int(conf, CONF_protocol, default_protocol); - conf_set_int(conf, CONF_port, default_port); - } - } + conf_set_int(conf, CONF_protocol, default_protocol); + conf_set_int(conf, CONF_port, default_port); + } + } } while (--argc) { - char *p = *++argv; + char *p = *++argv; int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL), 1, conf); if (ret == -2) { @@ -353,7 +353,7 @@ int main(int argc, char **argv) sanitise_stderr = FORCE_OFF; } else if (!strcmp(p, "-no-antispoof")) { console_antispoof_prompt = false; - } else if (*p != '-') { + } else if (*p != '-') { strbuf *cmdbuf = strbuf_new(); while (argc > 0) { @@ -369,7 +369,7 @@ int main(int argc, char **argv) conf_set_bool(conf, CONF_nopty, true); /* command => no tty */ strbuf_free(cmdbuf); - break; /* done with cmdline */ + break; /* done with cmdline */ } else { fprintf(stderr, "plink: unknown option \"%s\"\n", p); errors = true; @@ -377,10 +377,10 @@ int main(int argc, char **argv) } if (errors) - return 1; + return 1; if (!cmdline_host_ok(conf)) { - usage(); + usage(); } prepare_session(conf); @@ -397,9 +397,9 @@ int main(int argc, char **argv) conf_set_bool(conf, CONF_ssh_subsys, true); if (!*conf_get_str(conf, CONF_remote_cmd) && - !*conf_get_str(conf, CONF_remote_cmd2) && - !*conf_get_str(conf, CONF_ssh_nc_host)) - flags |= FLAG_INTERACTIVE; + !*conf_get_str(conf, CONF_remote_cmd2) && + !*conf_get_str(conf, CONF_ssh_nc_host)) + flags |= FLAG_INTERACTIVE; /* * Select protocol. This is farmed out into a table in a @@ -407,15 +407,15 @@ int main(int argc, char **argv) */ vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol)); if (vt == NULL) { - fprintf(stderr, - "Internal fault: Unsupported protocol found\n"); - return 1; + fprintf(stderr, + "Internal fault: Unsupported protocol found\n"); + return 1; } sk_init(); if (p_WSAEventSelect == NULL) { - fprintf(stderr, "Plink requires WinSock 2\n"); - return 1; + fprintf(stderr, "Plink requires WinSock 2\n"); + return 1; } /* @@ -424,10 +424,10 @@ int main(int argc, char **argv) * the "simple" flag. */ if (conf_get_int(conf, CONF_protocol) == PROT_SSH && - !conf_get_bool(conf, CONF_x11_forward) && - !conf_get_bool(conf, CONF_agentfwd) && - !conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) - conf_set_bool(conf, CONF_ssh_simple, true); + !conf_get_bool(conf, CONF_x11_forward) && + !conf_get_bool(conf, CONF_agentfwd) && + !conf_get_str_nthstrkey(conf, CONF_portfwd, 0)) + conf_set_bool(conf, CONF_ssh_simple, true); logctx = log_init(default_logpolicy, conf); @@ -453,22 +453,22 @@ int main(int argc, char **argv) */ netevent = CreateEvent(NULL, false, false, NULL); { - const char *error; - char *realhost; - /* nodelay is only useful if stdin is a character device (console) */ - bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && - (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR); + const char *error; + char *realhost; + /* nodelay is only useful if stdin is a character device (console) */ + bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) && + (GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR); error = backend_init(vt, plink_seat, &backend, logctx, conf, conf_get_str(conf, CONF_host), conf_get_int(conf, CONF_port), &realhost, nodelay, conf_get_bool(conf, CONF_tcp_keepalives)); - if (error) { - fprintf(stderr, "Unable to open connection:\n%s", error); - return 1; - } - sfree(realhost); + if (error) { + fprintf(stderr, "Unable to open connection:\n%s", error); + return 1; + } + sfree(realhost); } inhandle = GetStdHandle(STD_INPUT_HANDLE); @@ -529,74 +529,74 @@ int main(int argc, char **argv) now = GETTICKCOUNT(); while (1) { - int nhandles; - HANDLE *handles; - int n; - DWORD ticks; + int nhandles; + HANDLE *handles; + int n; + DWORD ticks; if (!sending && backend_sendok(backend)) { - stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL, - 0); - sending = true; - } + stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL, + 0); + sending = true; + } if (toplevel_callback_pending()) { ticks = 0; next = now; } else if (run_timers(now, &next)) { - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; - } else { - ticks = INFINITE; + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; + } else { + ticks = INFINITE; /* no need to initialise next here because we can never * get WAIT_TIMEOUT */ - } + } - handles = handle_get_events(&nhandles); - handles = sresize(handles, nhandles+1, HANDLE); - handles[nhandles] = netevent; - n = MsgWaitForMultipleObjects(nhandles+1, handles, false, ticks, - QS_POSTMESSAGE); - if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) { - handle_got_event(handles[n - WAIT_OBJECT_0]); - } else if (n == WAIT_OBJECT_0 + nhandles) { - WSANETWORKEVENTS things; - SOCKET socket; - int i, socketstate; + handles = handle_get_events(&nhandles); + handles = sresize(handles, nhandles+1, HANDLE); + handles[nhandles] = netevent; + n = MsgWaitForMultipleObjects(nhandles+1, handles, false, ticks, + QS_POSTMESSAGE); + if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) { + handle_got_event(handles[n - WAIT_OBJECT_0]); + } else if (n == WAIT_OBJECT_0 + nhandles) { + WSANETWORKEVENTS things; + SOCKET 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++; + /* + * 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. */ + /* Expand the buffer if necessary. */ sgrowarray(sklist, sksize, i); - /* Retrieve the sockets into sklist. */ - skcount = 0; - for (socket = first_socket(&socketstate); - socket != INVALID_SOCKET; - socket = next_socket(&socketstate)) { - sklist[skcount++] = socket; - } + /* 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; - if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) { + /* Now we're done enumerating; go through the list. */ + for (i = 0; i < skcount; i++) { + WPARAM wp; + socket = sklist[i]; + wp = (WPARAM) socket; + if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) { static const struct { int bit, mask; } eventtypes[] = { {FD_CONNECT_BIT, FD_CONNECT}, {FD_READ_BIT, FD_READ}, @@ -607,7 +607,7 @@ int main(int argc, char **argv) }; int e; - noise_ultralight(NOISE_SOURCE_IOID, socket); + noise_ultralight(NOISE_SOURCE_IOID, socket); for (e = 0; e < lenof(eventtypes); e++) if (things.lNetworkEvents & eventtypes[e].mask) { @@ -616,41 +616,41 @@ int main(int argc, char **argv) lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err); select_result(wp, lp); } - } - } - } else if (n == WAIT_OBJECT_0 + nhandles + 1) { - MSG msg; - while (PeekMessage(&msg, INVALID_HANDLE_VALUE, - WM_AGENT_CALLBACK, WM_AGENT_CALLBACK, - PM_REMOVE)) { - struct agent_callback *c = (struct agent_callback *)msg.lParam; - c->callback(c->callback_ctx, c->data, c->len); - sfree(c); - } - } + } + } + } else if (n == WAIT_OBJECT_0 + nhandles + 1) { + MSG msg; + while (PeekMessage(&msg, INVALID_HANDLE_VALUE, + WM_AGENT_CALLBACK, WM_AGENT_CALLBACK, + PM_REMOVE)) { + struct agent_callback *c = (struct agent_callback *)msg.lParam; + c->callback(c->callback_ctx, c->data, c->len); + sfree(c); + } + } run_toplevel_callbacks(); - if (n == WAIT_TIMEOUT) { - now = next; - } else { - now = GETTICKCOUNT(); - } + if (n == WAIT_TIMEOUT) { + now = next; + } else { + now = GETTICKCOUNT(); + } - sfree(handles); + sfree(handles); - if (sending) + if (sending) handle_unthrottle(stdin_handle, backend_sendbuffer(backend)); if (!backend_connected(backend) && - handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0) - break; /* we closed the connection */ + handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0) + break; /* we closed the connection */ } exitcode = backend_exitcode(backend); if (exitcode < 0) { - fprintf(stderr, "Remote process exit code unavailable\n"); - exitcode = 1; /* this is an error condition */ + fprintf(stderr, "Remote process exit code unavailable\n"); + exitcode = 1; /* this is an error condition */ } cleanup_exit(exitcode); - return 0; /* placate compiler warning */ + return 0; /* placate compiler warning */ } diff --git a/windows/winprint.c b/windows/winprint.c index 36699f05..e6b3531d 100644 --- a/windows/winprint.c +++ b/windows/winprint.c @@ -9,8 +9,8 @@ struct printer_enum_tag { int nprinters; DWORD enum_level; union { - LPPRINTER_INFO_4 i4; - LPPRINTER_INFO_5 i5; + LPPRINTER_INFO_4 i4; + LPPRINTER_INFO_5 i5; } info; }; @@ -92,7 +92,7 @@ printer_enum *printer_start_enum(int *nprinters_ptr) printer_enum *ret = snew(printer_enum); char *buffer = NULL; - *nprinters_ptr = 0; /* default return value */ + *nprinters_ptr = 0; /* default return value */ buffer = snewn(512, char); /* @@ -106,9 +106,9 @@ printer_enum *printer_start_enum(int *nprinters_ptr) * Bletch. */ if (osPlatformId != VER_PLATFORM_WIN32_NT) { - ret->enum_level = 5; + ret->enum_level = 5; } else { - ret->enum_level = 4; + ret->enum_level = 4; } if (!printer_add_enum(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, @@ -117,14 +117,14 @@ printer_enum *printer_start_enum(int *nprinters_ptr) switch (ret->enum_level) { case 4: - ret->info.i4 = (LPPRINTER_INFO_4)buffer; - break; + ret->info.i4 = (LPPRINTER_INFO_4)buffer; + break; case 5: - ret->info.i5 = (LPPRINTER_INFO_5)buffer; - break; + ret->info.i5 = (LPPRINTER_INFO_5)buffer; + break; } ret->nprinters = *nprinters_ptr; - + return ret; error: @@ -137,30 +137,30 @@ printer_enum *printer_start_enum(int *nprinters_ptr) char *printer_get_name(printer_enum *pe, int i) { if (!pe) - return NULL; + return NULL; if (i < 0 || i >= pe->nprinters) - return NULL; + return NULL; switch (pe->enum_level) { case 4: - return pe->info.i4[i].pPrinterName; + return pe->info.i4[i].pPrinterName; case 5: - return pe->info.i5[i].pPrinterName; + return pe->info.i5[i].pPrinterName; default: - return NULL; + return NULL; } } void printer_finish_enum(printer_enum *pe) { if (!pe) - return; + return; switch (pe->enum_level) { case 4: - sfree(pe->info.i4); - break; + sfree(pe->info.i4); + break; case 5: - sfree(pe->info.i5); - break; + sfree(pe->info.i5); + break; } sfree(pe); } @@ -175,29 +175,29 @@ printer_job *printer_start_job(char *printer) ret->hprinter = NULL; if (!p_OpenPrinter(printer, &ret->hprinter, NULL)) - goto error; + goto error; docinfo.pDocName = "PuTTY remote printer output"; docinfo.pOutputFile = NULL; docinfo.pDatatype = "RAW"; if (!p_StartDocPrinter(ret->hprinter, 1, (LPBYTE)&docinfo)) - goto error; + goto error; jobstarted = true; if (!p_StartPagePrinter(ret->hprinter)) - goto error; + goto error; pagestarted = true; return ret; error: if (pagestarted) - p_EndPagePrinter(ret->hprinter); + p_EndPagePrinter(ret->hprinter); if (jobstarted) - p_EndDocPrinter(ret->hprinter); + p_EndDocPrinter(ret->hprinter); if (ret->hprinter) - p_ClosePrinter(ret->hprinter); + p_ClosePrinter(ret->hprinter); sfree(ret); return NULL; } @@ -207,7 +207,7 @@ void printer_job_data(printer_job *pj, const void *data, size_t len) DWORD written; if (!pj) - return; + return; p_WritePrinter(pj->hprinter, (void *)data, len, &written); } @@ -215,7 +215,7 @@ void printer_job_data(printer_job *pj, const void *data, size_t len) void printer_finish_job(printer_job *pj) { if (!pj) - return; + return; p_EndPagePrinter(pj->hprinter); p_EndDocPrinter(pj->hprinter); diff --git a/windows/winproxy.c b/windows/winproxy.c index 909af2f1..24ca261c 100644 --- a/windows/winproxy.c +++ b/windows/winproxy.c @@ -26,7 +26,7 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, PROCESS_INFORMATION pi; if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD) - return NULL; + return NULL; cmd = format_telnet_command(addr, port, conf); @@ -34,9 +34,9 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, sk_addr_free(addr); { - char *msg = dupprintf("Starting local proxy command: %s", cmd); - plug_log(plug, 2, NULL, 0, msg, 0); - sfree(msg); + char *msg = dupprintf("Starting local proxy command: %s", cmd); + plug_log(plug, 2, NULL, 0, msg, 0); + sfree(msg); } /* @@ -48,16 +48,16 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, sa.bInheritHandle = true; if (!CreatePipe(&us_from_cmd, &cmd_to_us, &sa, 0)) { sfree(cmd); - return new_error_socket_fmt( + return new_error_socket_fmt( plug, "Unable to create pipes for proxy command: %s", win_strerror(GetLastError())); } if (!CreatePipe(&cmd_from_us, &us_to_cmd, &sa, 0)) { sfree(cmd); - CloseHandle(us_from_cmd); - CloseHandle(cmd_to_us); - return new_error_socket_fmt( + CloseHandle(us_from_cmd); + CloseHandle(cmd_to_us); + return new_error_socket_fmt( plug, "Unable to create pipes for proxy command: %s", win_strerror(GetLastError())); } @@ -89,8 +89,8 @@ Socket *platform_new_connection(SockAddr *addr, const char *hostname, si.hStdOutput = cmd_to_us; si.hStdError = cmd_err_to_us; CreateProcess(NULL, cmd, NULL, NULL, true, - CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS, - NULL, NULL, &si, &pi); + CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS, + NULL, NULL, &si, &pi); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); diff --git a/windows/winsecur.c b/windows/winsecur.c index 3096d26e..3926e33a 100644 --- a/windows/winsecur.c +++ b/windows/winsecur.c @@ -140,7 +140,7 @@ bool getsids(char **error) cleanup: return ret; } - + bool make_private_security_descriptor(DWORD permissions, PSECURITY_DESCRIPTOR *psd, @@ -236,14 +236,14 @@ static bool really_restrict_process_acl(char **error) PACL acl = NULL; static const DWORD nastyace=WRITE_DAC | WRITE_OWNER | - PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | - PROCESS_DUP_HANDLE | - PROCESS_SET_QUOTA | PROCESS_SET_INFORMATION | - PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | - PROCESS_SUSPEND_RESUME; + PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | + PROCESS_DUP_HANDLE | + PROCESS_SET_QUOTA | PROCESS_SET_INFORMATION | + PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | + PROCESS_SUSPEND_RESUME; if (!getsids(error)) - goto cleanup; + goto cleanup; memset(ea, 0, sizeof(ea)); @@ -264,7 +264,7 @@ static bool really_restrict_process_acl(char **error) acl_err = p_SetEntriesInAclA(2, ea, NULL, &acl); if (acl_err != ERROR_SUCCESS || acl == NULL) { - *error = dupprintf("unable to construct ACL: %s", + *error = dupprintf("unable to construct ACL: %s", win_strerror(acl_err)); goto cleanup; } @@ -273,14 +273,14 @@ static bool really_restrict_process_acl(char **error) (GetCurrentProcess(), SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, usersid, NULL, acl, NULL)) { - *error = dupprintf("Unable to set process ACL: %s", + *error = dupprintf("Unable to set process ACL: %s", win_strerror(GetLastError())); - goto cleanup; + goto cleanup; } - + ret=true; - + cleanup: if (!ret) { if (acl) { diff --git a/windows/winsecur.h b/windows/winsecur.h index 50c696db..d5d4cfb1 100644 --- a/windows/winsecur.h +++ b/windows/winsecur.h @@ -16,23 +16,23 @@ * Functions loaded from advapi32.dll. */ DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, BOOL, OpenProcessToken, - (HANDLE, DWORD, PHANDLE)); + (HANDLE, DWORD, PHANDLE)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, BOOL, GetTokenInformation, - (HANDLE, TOKEN_INFORMATION_CLASS, + (HANDLE, TOKEN_INFORMATION_CLASS, LPVOID, DWORD, PDWORD)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, BOOL, InitializeSecurityDescriptor, - (PSECURITY_DESCRIPTOR, DWORD)); + (PSECURITY_DESCRIPTOR, DWORD)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, BOOL, SetSecurityDescriptorOwner, - (PSECURITY_DESCRIPTOR, PSID, BOOL)); + (PSECURITY_DESCRIPTOR, PSID, BOOL)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, DWORD, GetSecurityInfo, - (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION, - PSID *, PSID *, PACL *, PACL *, - PSECURITY_DESCRIPTOR *)); + (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION, + PSID *, PSID *, PACL *, PACL *, + PSECURITY_DESCRIPTOR *)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, DWORD, SetSecurityInfo, - (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION, - PSID, PSID, PACL, PACL)); + (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION, + PSID, PSID, PACL, PACL)); DECL_WINDOWS_FUNCTION(WINSECUR_GLOBAL, DWORD, SetEntriesInAclA, - (ULONG, PEXPLICIT_ACCESS, PACL, PACL *)); + (ULONG, PEXPLICIT_ACCESS, PACL, PACL *)); bool got_advapi(void); /* diff --git a/windows/winser.c b/windows/winser.c index fd412e38..d87ca6c9 100644 --- a/windows/winser.c +++ b/windows/winser.c @@ -25,18 +25,18 @@ struct Serial { static void serial_terminate(Serial *serial) { if (serial->out) { - handle_free(serial->out); - serial->out = NULL; + handle_free(serial->out); + serial->out = NULL; } if (serial->in) { - handle_free(serial->in); - serial->in = NULL; + handle_free(serial->in); + serial->in = NULL; } if (serial->port != INVALID_HANDLE_VALUE) { - if (serial->break_in_progress) - ClearCommBreak(serial->port); - CloseHandle(serial->port); - serial->port = INVALID_HANDLE_VALUE; + if (serial->break_in_progress) + ClearCommBreak(serial->port); + CloseHandle(serial->port); + serial->port = INVALID_HANDLE_VALUE; } } @@ -45,31 +45,31 @@ static size_t serial_gotdata( { Serial *serial = (Serial *)handle_get_privdata(h); if (err || len == 0) { - const char *error_msg; + const char *error_msg; - /* - * Currently, len==0 should never happen because we're - * ignoring EOFs. However, it seems not totally impossible - * that this same back end might be usable to talk to named - * pipes or some other non-serial device, in which case EOF - * may become meaningful here. - */ + /* + * Currently, len==0 should never happen because we're + * ignoring EOFs. However, it seems not totally impossible + * that this same back end might be usable to talk to named + * pipes or some other non-serial device, in which case EOF + * may become meaningful here. + */ if (!err) - error_msg = "End of file reading from serial device"; - else - error_msg = "Error reading from serial device"; + error_msg = "End of file reading from serial device"; + else + error_msg = "Error reading from serial device"; - serial_terminate(serial); + serial_terminate(serial); - seat_notify_remote_exit(serial->seat); + seat_notify_remote_exit(serial->seat); logevent(serial->logctx, error_msg); - seat_connection_fatal(serial->seat, "%s", error_msg); + seat_connection_fatal(serial->seat, "%s", error_msg); - return 0; + return 0; } else { - return seat_stdout(serial->seat, data, len); + return seat_stdout(serial->seat, data, len); } } @@ -77,17 +77,17 @@ static void serial_sentdata(struct handle *h, size_t new_backlog, int err) { Serial *serial = (Serial *)handle_get_privdata(h); if (err) { - const char *error_msg = "Error writing to serial device"; + const char *error_msg = "Error writing to serial device"; - serial_terminate(serial); + serial_terminate(serial); - seat_notify_remote_exit(serial->seat); + seat_notify_remote_exit(serial->seat); logevent(serial->logctx, error_msg); - seat_connection_fatal(serial->seat, "%s", error_msg); + seat_connection_fatal(serial->seat, "%s", error_msg); } else { - serial->bufsize = new_backlog; + serial->bufsize = new_backlog; } } @@ -103,81 +103,81 @@ static const char *serial_configure(Serial *serial, HANDLE serport, Conf *conf) * device instead of a serial port. */ if (GetCommState(serport, &dcb)) { - const char *str; + const char *str; - /* - * Boilerplate. - */ - dcb.fBinary = true; - dcb.fDtrControl = DTR_CONTROL_ENABLE; - dcb.fDsrSensitivity = false; - dcb.fTXContinueOnXoff = false; - dcb.fOutX = false; - dcb.fInX = false; - dcb.fErrorChar = false; - dcb.fNull = false; - dcb.fRtsControl = RTS_CONTROL_ENABLE; - dcb.fAbortOnError = false; - dcb.fOutxCtsFlow = false; - dcb.fOutxDsrFlow = false; + /* + * Boilerplate. + */ + dcb.fBinary = true; + dcb.fDtrControl = DTR_CONTROL_ENABLE; + dcb.fDsrSensitivity = false; + dcb.fTXContinueOnXoff = false; + dcb.fOutX = false; + dcb.fInX = false; + dcb.fErrorChar = false; + dcb.fNull = false; + dcb.fRtsControl = RTS_CONTROL_ENABLE; + dcb.fAbortOnError = false; + dcb.fOutxCtsFlow = false; + dcb.fOutxDsrFlow = false; - /* - * Configurable parameters. - */ - dcb.BaudRate = conf_get_int(conf, CONF_serspeed); + /* + * Configurable parameters. + */ + dcb.BaudRate = conf_get_int(conf, CONF_serspeed); logeventf(serial->logctx, "Configuring baud rate %lu", dcb.BaudRate); - dcb.ByteSize = conf_get_int(conf, CONF_serdatabits); + dcb.ByteSize = conf_get_int(conf, CONF_serdatabits); logeventf(serial->logctx, "Configuring %u data bits", dcb.ByteSize); - switch (conf_get_int(conf, CONF_serstopbits)) { - case 2: dcb.StopBits = ONESTOPBIT; str = "1"; break; - case 3: dcb.StopBits = ONE5STOPBITS; str = "1.5"; break; - case 4: dcb.StopBits = TWOSTOPBITS; str = "2"; break; - default: return "Invalid number of stop bits (need 1, 1.5 or 2)"; - } + switch (conf_get_int(conf, CONF_serstopbits)) { + case 2: dcb.StopBits = ONESTOPBIT; str = "1"; break; + case 3: dcb.StopBits = ONE5STOPBITS; str = "1.5"; break; + case 4: dcb.StopBits = TWOSTOPBITS; str = "2"; break; + default: return "Invalid number of stop bits (need 1, 1.5 or 2)"; + } logeventf(serial->logctx, "Configuring %s data bits", str); - switch (conf_get_int(conf, CONF_serparity)) { - case SER_PAR_NONE: dcb.Parity = NOPARITY; str = "no"; break; - case SER_PAR_ODD: dcb.Parity = ODDPARITY; str = "odd"; break; - case SER_PAR_EVEN: dcb.Parity = EVENPARITY; str = "even"; break; - case SER_PAR_MARK: dcb.Parity = MARKPARITY; str = "mark"; break; - case SER_PAR_SPACE: dcb.Parity = SPACEPARITY; str = "space"; break; - } + switch (conf_get_int(conf, CONF_serparity)) { + case SER_PAR_NONE: dcb.Parity = NOPARITY; str = "no"; break; + case SER_PAR_ODD: dcb.Parity = ODDPARITY; str = "odd"; break; + case SER_PAR_EVEN: dcb.Parity = EVENPARITY; str = "even"; break; + case SER_PAR_MARK: dcb.Parity = MARKPARITY; str = "mark"; break; + case SER_PAR_SPACE: dcb.Parity = SPACEPARITY; str = "space"; break; + } logeventf(serial->logctx, "Configuring %s parity", str); - switch (conf_get_int(conf, CONF_serflow)) { - case SER_FLOW_NONE: - str = "no"; - break; - case SER_FLOW_XONXOFF: - dcb.fOutX = dcb.fInX = true; - str = "XON/XOFF"; - break; - case SER_FLOW_RTSCTS: - dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; - dcb.fOutxCtsFlow = true; - str = "RTS/CTS"; - break; - case SER_FLOW_DSRDTR: - dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; - dcb.fOutxDsrFlow = true; - str = "DSR/DTR"; - break; - } + switch (conf_get_int(conf, CONF_serflow)) { + case SER_FLOW_NONE: + str = "no"; + break; + case SER_FLOW_XONXOFF: + dcb.fOutX = dcb.fInX = true; + str = "XON/XOFF"; + break; + case SER_FLOW_RTSCTS: + dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; + dcb.fOutxCtsFlow = true; + str = "RTS/CTS"; + break; + case SER_FLOW_DSRDTR: + dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; + dcb.fOutxDsrFlow = true; + str = "DSR/DTR"; + break; + } logeventf(serial->logctx, "Configuring %s flow control", str); - if (!SetCommState(serport, &dcb)) - return "Unable to configure serial port"; + if (!SetCommState(serport, &dcb)) + return "Unable to configure serial port"; - timeouts.ReadIntervalTimeout = 1; - timeouts.ReadTotalTimeoutMultiplier = 0; - timeouts.ReadTotalTimeoutConstant = 0; - timeouts.WriteTotalTimeoutMultiplier = 0; - timeouts.WriteTotalTimeoutConstant = 0; - if (!SetCommTimeouts(serport, &timeouts)) - return "Unable to configure serial timeouts"; + timeouts.ReadIntervalTimeout = 1; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 0; + timeouts.WriteTotalTimeoutMultiplier = 0; + timeouts.WriteTotalTimeoutConstant = 0; + if (!SetCommTimeouts(serport, &timeouts)) + return "Unable to configure serial timeouts"; } return NULL; @@ -185,7 +185,7 @@ static const char *serial_configure(Serial *serial, HANDLE serport, Conf *conf) /* * Called to set up the serial connection. - * + * * Returns an error message, or NULL on success. * * Also places the canonical host name into `realhost'. It must be @@ -194,7 +194,7 @@ static const char *serial_configure(Serial *serial, HANDLE serport, Conf *conf) static const char *serial_init(Seat *seat, Backend **backend_handle, LogContext *logctx, Conf *conf, const char *host, int port, - char **realhost, bool nodelay, bool keepalive) + char **realhost, bool nodelay, bool keepalive) { Serial *serial; HANDLE serport; @@ -219,50 +219,50 @@ static const char *serial_init(Seat *seat, Backend **backend_handle, logeventf(serial->logctx, "Opening serial device %s", serline); { - /* - * Munge the string supplied by the user into a Windows filename. - * - * Windows supports opening a few "legacy" devices (including - * COM1-9) by specifying their names verbatim as a filename to - * open. (Thus, no files can ever have these names. See - * - * ("Naming a File") for the complete list of reserved names.) - * - * However, this doesn't let you get at devices COM10 and above. - * For that, you need to specify a filename like "\\.\COM10". - * This is also necessary for special serial and serial-like - * devices such as \\.\WCEUSBSH001. It also works for the "legacy" - * names, so you can do \\.\COM1 (verified as far back as Win95). - * See - * (CreateFile() docs). - * - * So, we believe that prepending "\\.\" should always be the - * Right Thing. However, just in case someone finds something to - * talk to that doesn't exist under there, if the serial line - * contains a backslash, we use it verbatim. (This also lets - * existing configurations using \\.\ continue working.) - */ - char *serfilename = - dupprintf("%s%s", strchr(serline, '\\') ? "" : "\\\\.\\", serline); - serport = CreateFile(serfilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); - sfree(serfilename); + /* + * Munge the string supplied by the user into a Windows filename. + * + * Windows supports opening a few "legacy" devices (including + * COM1-9) by specifying their names verbatim as a filename to + * open. (Thus, no files can ever have these names. See + * + * ("Naming a File") for the complete list of reserved names.) + * + * However, this doesn't let you get at devices COM10 and above. + * For that, you need to specify a filename like "\\.\COM10". + * This is also necessary for special serial and serial-like + * devices such as \\.\WCEUSBSH001. It also works for the "legacy" + * names, so you can do \\.\COM1 (verified as far back as Win95). + * See + * (CreateFile() docs). + * + * So, we believe that prepending "\\.\" should always be the + * Right Thing. However, just in case someone finds something to + * talk to that doesn't exist under there, if the serial line + * contains a backslash, we use it verbatim. (This also lets + * existing configurations using \\.\ continue working.) + */ + char *serfilename = + dupprintf("%s%s", strchr(serline, '\\') ? "" : "\\\\.\\", serline); + serport = CreateFile(serfilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + sfree(serfilename); } if (serport == INVALID_HANDLE_VALUE) - return "Unable to open serial port"; + return "Unable to open serial port"; err = serial_configure(serial, serport, conf); if (err) - return err; + return err; serial->port = serport; serial->out = handle_output_new(serport, serial_sentdata, serial, - HANDLE_FLAG_OVERLAPPED); + HANDLE_FLAG_OVERLAPPED); serial->in = handle_input_new(serport, serial_gotdata, serial, - HANDLE_FLAG_OVERLAPPED | - HANDLE_FLAG_IGNOREEOF | - HANDLE_FLAG_UNITBUFFER); + HANDLE_FLAG_OVERLAPPED | + HANDLE_FLAG_IGNOREEOF | + HANDLE_FLAG_UNITBUFFER); *realhost = dupstr(serline); @@ -303,7 +303,7 @@ static size_t serial_send(Backend *be, const char *buf, size_t len) Serial *serial = container_of(be, Serial, backend); if (serial->out == NULL) - return 0; + return 0; serial->bufsize = handle_write(serial->out, buf, len); return serial->bufsize; @@ -332,8 +332,8 @@ static void serbreak_timer(void *ctx, unsigned long now) Serial *serial = (Serial *)ctx; if (now == serial->clearbreak_time && serial->port) { - ClearCommBreak(serial->port); - serial->break_in_progress = false; + ClearCommBreak(serial->port); + serial->break_in_progress = false; logevent(serial->logctx, "Finished serial break"); } } @@ -347,20 +347,20 @@ static void serial_special(Backend *be, SessionSpecialCode code, int arg) if (serial->port && code == SS_BRK) { logevent(serial->logctx, "Starting serial break at user request"); - SetCommBreak(serial->port); - /* - * To send a serial break on Windows, we call SetCommBreak - * to begin the break, then wait a bit, and then call - * ClearCommBreak to finish it. Hence, I must use timing.c - * to arrange a callback when it's time to do the latter. - * - * SUS says that a default break length must be between 1/4 - * and 1/2 second. FreeBSD apparently goes with 2/5 second, - * and so will I. - */ - serial->clearbreak_time = - schedule_timer(TICKSPERSEC * 2 / 5, serbreak_timer, serial); - serial->break_in_progress = true; + SetCommBreak(serial->port); + /* + * To send a serial break on Windows, we call SetCommBreak + * to begin the break, then wait a bit, and then call + * ClearCommBreak to finish it. Hence, I must use timing.c + * to arrange a callback when it's time to do the latter. + * + * SUS says that a default break length must be between 1/4 + * and 1/2 second. FreeBSD apparently goes with 2/5 second, + * and so will I. + */ + serial->clearbreak_time = + schedule_timer(TICKSPERSEC * 2 / 5, serbreak_timer, serial); + serial->break_in_progress = true; } return; @@ -373,8 +373,8 @@ static void serial_special(Backend *be, SessionSpecialCode code, int arg) static const SessionSpecial *serial_get_specials(Backend *be) { static const SessionSpecial specials[] = { - {"Break", SS_BRK}, - {NULL, SS_EXITMENU} + {"Break", SS_BRK}, + {NULL, SS_EXITMENU} }; return specials; } @@ -393,7 +393,7 @@ static void serial_unthrottle(Backend *be, size_t backlog) { Serial *serial = container_of(be, Serial, backend); if (serial->in) - handle_unthrottle(serial->in, backlog); + handle_unthrottle(serial->in, backlog); } static bool serial_ldisc(Backend *be, int option) diff --git a/windows/winsftp.c b/windows/winsftp.c index adea38c8..ab323404 100644 --- a/windows/winsftp.c +++ b/windows/winsftp.c @@ -17,7 +17,7 @@ int filexfer_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input) int ret; ret = cmdline_get_passwd_input(p); if (ret == -1) - ret = console_get_userpass_input(p); + ret = console_get_userpass_input(p); return ret; } @@ -40,17 +40,17 @@ char *psftp_lcd(char *dir) char *ret = NULL; if (!SetCurrentDirectory(dir)) { - LPVOID message; - int i; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)&message, 0, NULL); - i = strcspn((char *)message, "\n"); - ret = dupprintf("%.*s", i, (LPCTSTR)message); - LocalFree(message); + LPVOID message; + int i; + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR)&message, 0, NULL); + i = strcspn((char *)message, "\n"); + ret = dupprintf("%.*s", i, (LPCTSTR)message); + LocalFree(message); } return ret; @@ -65,7 +65,7 @@ char *psftp_getcwd(void) char *ret = snewn(256, char); size_t len = GetCurrentDirectory(256, ret); if (len > 256) - ret = sresize(ret, len, char); + ret = sresize(ret, len, char); GetCurrentDirectory(len, ret); return ret; } @@ -94,16 +94,16 @@ struct RFile { }; RFile *open_existing_file(const char *name, uint64_t *size, - unsigned long *mtime, unsigned long *atime, + unsigned long *mtime, unsigned long *atime, long *perms) { HANDLE h; RFile *ret; h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, 0, 0); + OPEN_EXISTING, 0, 0); if (h == INVALID_HANDLE_VALUE) - return NULL; + return NULL; ret = snew(RFile); ret->h = h; @@ -115,12 +115,12 @@ RFile *open_existing_file(const char *name, uint64_t *size, } if (mtime || atime) { - FILETIME actime, wrtime; - GetFileTime(h, NULL, &actime, &wrtime); - if (atime) - TIME_WIN_TO_POSIX(actime, *atime); - if (mtime) - TIME_WIN_TO_POSIX(wrtime, *mtime); + FILETIME actime, wrtime; + GetFileTime(h, NULL, &actime, &wrtime); + if (atime) + TIME_WIN_TO_POSIX(actime, *atime); + if (mtime) + TIME_WIN_TO_POSIX(wrtime, *mtime); } if (perms) @@ -133,9 +133,9 @@ int read_from_file(RFile *f, void *buffer, int length) { DWORD read; if (!ReadFile(f->h, buffer, length, &read, NULL)) - return -1; /* error */ + return -1; /* error */ else - return read; + return read; } void close_rfile(RFile *f) @@ -154,9 +154,9 @@ WFile *open_new_file(const char *name, long perms) WFile *ret; h = CreateFile(name, GENERIC_WRITE, 0, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (h == INVALID_HANDLE_VALUE) - return NULL; + return NULL; ret = snew(WFile); ret->h = h; @@ -170,9 +170,9 @@ WFile *open_existing_wfile(const char *name, uint64_t *size) WFile *ret; h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL, - OPEN_EXISTING, 0, 0); + OPEN_EXISTING, 0, 0); if (h == INVALID_HANDLE_VALUE) - return NULL; + return NULL; ret = snew(WFile); ret->h = h; @@ -190,9 +190,9 @@ int write_to_file(WFile *f, void *buffer, int length) { DWORD written; if (!WriteFile(f->h, buffer, length, &written, NULL)) - return -1; /* error */ + return -1; /* error */ else - return written; + return written; } void set_file_times(WFile *f, unsigned long mtime, unsigned long atime) @@ -217,27 +217,27 @@ int seek_file(WFile *f, uint64_t offset, int whence) switch (whence) { case FROM_START: - movemethod = FILE_BEGIN; - break; + movemethod = FILE_BEGIN; + break; case FROM_CURRENT: - movemethod = FILE_CURRENT; - break; + movemethod = FILE_CURRENT; + break; case FROM_END: - movemethod = FILE_END; - break; + movemethod = FILE_END; + break; default: - return -1; + return -1; } { LONG lo = offset & 0xFFFFFFFFU, hi = offset >> 32; SetFilePointer(f->h, lo, &hi, movemethod); } - + if (GetLastError() != NO_ERROR) - return -1; - else - return 0; + return -1; + else + return 0; } uint64_t get_file_posn(WFile *f) @@ -254,11 +254,11 @@ int file_type(const char *name) attr = GetFileAttributes(name); /* We know of no `weird' files under Windows. */ if (attr == (DWORD)-1) - return FILE_TYPE_NONEXISTENT; + return FILE_TYPE_NONEXISTENT; else if (attr & FILE_ATTRIBUTE_DIRECTORY) - return FILE_TYPE_DIRECTORY; + return FILE_TYPE_DIRECTORY; else - return FILE_TYPE_FILE; + return FILE_TYPE_FILE; } struct DirHandle { @@ -278,7 +278,7 @@ DirHandle *open_directory(const char *name, const char **errmsg) h = FindFirstFile(findfile, &fdat); if (h == INVALID_HANDLE_VALUE) { *errmsg = win_strerror(GetLastError()); - return NULL; + return NULL; } sfree(findfile); @@ -292,37 +292,37 @@ char *read_filename(DirHandle *dir) { do { - if (!dir->name) { - WIN32_FIND_DATA fdat; - if (!FindNextFile(dir->h, &fdat)) - return NULL; - else - dir->name = dupstr(fdat.cFileName); - } + if (!dir->name) { + WIN32_FIND_DATA fdat; + if (!FindNextFile(dir->h, &fdat)) + return NULL; + else + dir->name = dupstr(fdat.cFileName); + } - assert(dir->name); - if (dir->name[0] == '.' && - (dir->name[1] == '\0' || - (dir->name[1] == '.' && dir->name[2] == '\0'))) { - sfree(dir->name); - dir->name = NULL; - } + assert(dir->name); + if (dir->name[0] == '.' && + (dir->name[1] == '\0' || + (dir->name[1] == '.' && dir->name[2] == '\0'))) { + sfree(dir->name); + dir->name = NULL; + } } while (!dir->name); if (dir->name) { - char *ret = dir->name; - dir->name = NULL; - return ret; + char *ret = dir->name; + dir->name = NULL; + return ret; } else - return NULL; + return NULL; } void close_directory(DirHandle *dir) { FindClose(dir->h); if (dir->name) - sfree(dir->name); + sfree(dir->name); sfree(dir); } @@ -333,12 +333,12 @@ int test_wildcard(const char *name, bool cmdline) /* First see if the exact name exists. */ if (GetFileAttributes(name) != (DWORD)-1) - return WCTYPE_FILENAME; + return WCTYPE_FILENAME; /* Otherwise see if a wildcard match finds anything. */ fh = FindFirstFile(name, &fdat); if (fh == INVALID_HANDLE_VALUE) - return WCTYPE_NONEXISTENT; + return WCTYPE_NONEXISTENT; FindClose(fh); return WCTYPE_WILDCARD; @@ -367,8 +367,8 @@ char *stripslashes(const char *str, bool local) if (p) str = p+1; if (local) { - p = strrchr(str, '\\'); - if (p) str = p+1; + p = strrchr(str, '\\'); + if (p) str = p+1; } return (char *)str; @@ -383,7 +383,7 @@ WildcardMatcher *begin_wildcard_matching(const char *name) h = FindFirstFile(name, &fdat); if (h == INVALID_HANDLE_VALUE) - return NULL; + return NULL; ret = snew(WildcardMatcher); ret->h = h; @@ -391,11 +391,11 @@ WildcardMatcher *begin_wildcard_matching(const char *name) last = stripslashes(ret->srcpath, true); *last = '\0'; if (fdat.cFileName[0] == '.' && - (fdat.cFileName[1] == '\0' || - (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0'))) - ret->name = NULL; + (fdat.cFileName[1] == '\0' || + (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0'))) + ret->name = NULL; else - ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL); + ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL); return ret; } @@ -403,32 +403,32 @@ WildcardMatcher *begin_wildcard_matching(const char *name) char *wildcard_get_filename(WildcardMatcher *dir) { while (!dir->name) { - WIN32_FIND_DATA fdat; + WIN32_FIND_DATA fdat; - if (!FindNextFile(dir->h, &fdat)) - return NULL; + if (!FindNextFile(dir->h, &fdat)) + return NULL; - if (fdat.cFileName[0] == '.' && - (fdat.cFileName[1] == '\0' || - (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0'))) - dir->name = NULL; - else - dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL); + if (fdat.cFileName[0] == '.' && + (fdat.cFileName[1] == '\0' || + (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0'))) + dir->name = NULL; + else + dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL); } if (dir->name) { - char *ret = dir->name; - dir->name = NULL; - return ret; + char *ret = dir->name; + dir->name = NULL; + return ret; } else - return NULL; + return NULL; } void finish_wildcard_matching(WildcardMatcher *dir) { FindClose(dir->h); if (dir->name) - sfree(dir->name); + sfree(dir->name); sfree(dir->srcpath); sfree(dir); } @@ -436,10 +436,10 @@ void finish_wildcard_matching(WildcardMatcher *dir) bool vet_filename(const char *name) { if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':')) - return false; + return false; if (!name[strspn(name, ".")]) /* entirely composed of dots */ - return false; + return false; return true; } @@ -471,26 +471,26 @@ char *do_select(SOCKET skt, bool startup) { int events; if (startup) - sftp_ssh_socket = skt; + sftp_ssh_socket = skt; else - sftp_ssh_socket = INVALID_SOCKET; + sftp_ssh_socket = INVALID_SOCKET; if (p_WSAEventSelect) { - if (startup) { - events = (FD_CONNECT | FD_READ | FD_WRITE | - FD_OOB | FD_CLOSE | FD_ACCEPT); - netevent = CreateEvent(NULL, false, false, NULL); - } else { - events = 0; - } - if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) { - switch (p_WSAGetLastError()) { - case WSAENETDOWN: - return "Network is down"; - default: - return "WSAEventSelect(): unknown error"; - } - } + if (startup) { + events = (FD_CONNECT | FD_READ | FD_WRITE | + FD_OOB | FD_CLOSE | FD_ACCEPT); + netevent = CreateEvent(NULL, false, false, NULL); + } else { + events = 0; + } + if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) { + switch (p_WSAGetLastError()) { + case WSAENETDOWN: + return "Network is down"; + default: + return "WSAEventSelect(): unknown error"; + } + } } return NULL; } @@ -509,14 +509,14 @@ int do_eventsel_loop(HANDLE other_event) ticks = 0; next = now; } else if (run_timers(now, &next)) { - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; } else { - ticks = INFINITE; + ticks = INFINITE; /* no need to initialise next here because we can never get * WAIT_TIMEOUT */ } @@ -526,75 +526,75 @@ int do_eventsel_loop(HANDLE other_event) nallhandles = nhandles; if (netevent != INVALID_HANDLE_VALUE) - handles[netindex = nallhandles++] = netevent; + handles[netindex = nallhandles++] = netevent; else - netindex = -1; + netindex = -1; if (other_event != INVALID_HANDLE_VALUE) - handles[otherindex = nallhandles++] = other_event; + handles[otherindex = nallhandles++] = other_event; else - otherindex = -1; + otherindex = -1; n = WaitForMultipleObjects(nallhandles, handles, false, ticks); if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) { - handle_got_event(handles[n - WAIT_OBJECT_0]); + handle_got_event(handles[n - WAIT_OBJECT_0]); } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) { - WSANETWORKEVENTS things; - SOCKET socket; - int i, socketstate; + WSANETWORKEVENTS things; + SOCKET 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++; + /* + * 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. */ - sklist = snewn(i, SOCKET); + /* Expand the buffer if necessary. */ + sklist = snewn(i, SOCKET); - /* Retrieve the sockets into sklist. */ - skcount = 0; - for (socket = first_socket(&socketstate); - socket != INVALID_SOCKET; - socket = next_socket(&socketstate)) { - sklist[skcount++] = socket; - } + /* 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; - if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) { - static const struct { int bit, mask; } eventtypes[] = { - {FD_CONNECT_BIT, FD_CONNECT}, - {FD_READ_BIT, FD_READ}, - {FD_CLOSE_BIT, FD_CLOSE}, - {FD_OOB_BIT, FD_OOB}, - {FD_WRITE_BIT, FD_WRITE}, - {FD_ACCEPT_BIT, FD_ACCEPT}, - }; - int e; + /* Now we're done enumerating; go through the list. */ + for (i = 0; i < skcount; i++) { + WPARAM wp; + socket = sklist[i]; + wp = (WPARAM) socket; + if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) { + static const struct { int bit, mask; } eventtypes[] = { + {FD_CONNECT_BIT, FD_CONNECT}, + {FD_READ_BIT, FD_READ}, + {FD_CLOSE_BIT, FD_CLOSE}, + {FD_OOB_BIT, FD_OOB}, + {FD_WRITE_BIT, FD_WRITE}, + {FD_ACCEPT_BIT, FD_ACCEPT}, + }; + int e; - noise_ultralight(NOISE_SOURCE_IOID, socket); + noise_ultralight(NOISE_SOURCE_IOID, socket); - for (e = 0; e < lenof(eventtypes); e++) - if (things.lNetworkEvents & eventtypes[e].mask) { - LPARAM lp; - int err = things.iErrorCode[eventtypes[e].bit]; - lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err); - select_result(wp, lp); - } - } - } + for (e = 0; e < lenof(eventtypes); e++) + if (things.lNetworkEvents & eventtypes[e].mask) { + LPARAM lp; + int err = things.iErrorCode[eventtypes[e].bit]; + lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err); + select_result(wp, lp); + } + } + } - sfree(sklist); + sfree(sklist); } sfree(handles); @@ -602,13 +602,13 @@ int do_eventsel_loop(HANDLE other_event) run_toplevel_callbacks(); if (n == WAIT_TIMEOUT) { - now = next; + now = next; } else { - now = GETTICKCOUNT(); + now = GETTICKCOUNT(); } if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex) - return 1; + return 1; return 0; } @@ -625,59 +625,59 @@ int do_eventsel_loop(HANDLE other_event) int ssh_sftp_loop_iteration(void) { if (p_WSAEventSelect == NULL) { - fd_set readfds; - int ret; - unsigned long now = GETTICKCOUNT(), then; + fd_set readfds; + int ret; + unsigned long now = GETTICKCOUNT(), then; - if (sftp_ssh_socket == INVALID_SOCKET) - return -1; /* doom */ + if (sftp_ssh_socket == INVALID_SOCKET) + return -1; /* doom */ - if (socket_writable(sftp_ssh_socket)) - select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE); + if (socket_writable(sftp_ssh_socket)) + select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE); - do { - unsigned long next; - long ticks; - struct timeval tv, *ptv; + do { + unsigned long next; + long ticks; + struct timeval tv, *ptv; - if (run_timers(now, &next)) { - then = now; - now = GETTICKCOUNT(); - if (now - then > next - then) - ticks = 0; - else - ticks = next - now; - tv.tv_sec = ticks / 1000; - tv.tv_usec = ticks % 1000 * 1000; - ptv = &tv; - } else { - ptv = NULL; - } + if (run_timers(now, &next)) { + then = now; + now = GETTICKCOUNT(); + if (now - then > next - then) + ticks = 0; + else + ticks = next - now; + tv.tv_sec = ticks / 1000; + tv.tv_usec = ticks % 1000 * 1000; + ptv = &tv; + } else { + ptv = NULL; + } - FD_ZERO(&readfds); - FD_SET(sftp_ssh_socket, &readfds); - ret = p_select(1, &readfds, NULL, NULL, ptv); + FD_ZERO(&readfds); + FD_SET(sftp_ssh_socket, &readfds); + ret = p_select(1, &readfds, NULL, NULL, ptv); - if (ret < 0) - return -1; /* doom */ - else if (ret == 0) - now = next; - else - now = GETTICKCOUNT(); + if (ret < 0) + return -1; /* doom */ + else if (ret == 0) + now = next; + else + now = GETTICKCOUNT(); - } while (ret == 0); + } while (ret == 0); - select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ); + select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ); - return 0; + return 0; } else { - return do_eventsel_loop(INVALID_HANDLE_VALUE); + return do_eventsel_loop(INVALID_HANDLE_VALUE); } } /* * Read a command line from standard input. - * + * * In the presence of WinSock 2, we can use WSAEventSelect to * mediate between the socket and stdin, meaning we can send * keepalives and respond to server events even while waiting at @@ -711,8 +711,8 @@ char *ssh_sftp_get_cmdline(const char *prompt, bool no_fds_ok) fflush(stdout); if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) || - p_WSAEventSelect == NULL) { - return fgetline(stdin); /* very simple */ + p_WSAEventSelect == NULL) { + return fgetline(stdin); /* very simple */ } /* @@ -724,16 +724,16 @@ char *ssh_sftp_get_cmdline(const char *prompt, bool no_fds_ok) hThread = CreateThread(NULL, 0, command_read_thread, ctx, 0, &threadid); if (!hThread) { - CloseHandle(ctx->event); - fprintf(stderr, "Unable to create command input thread\n"); - cleanup_exit(1); + CloseHandle(ctx->event); + fprintf(stderr, "Unable to create command input thread\n"); + cleanup_exit(1); } do { - ret = do_eventsel_loop(ctx->event); + ret = do_eventsel_loop(ctx->event); - /* Error return can only occur if netevent==NULL, and it ain't. */ - assert(ret >= 0); + /* Error return can only occur if netevent==NULL, and it ain't. */ + assert(ret >= 0); } while (ret == 0); CloseHandle(hThread); diff --git a/windows/winstore.c b/windows/winstore.c index 260fa20f..1fba6ddb 100644 --- a/windows/winstore.c +++ b/windows/winstore.c @@ -24,8 +24,8 @@ static const char *const puttystr = PUTTY_REG_POS "\\Sessions"; static bool tried_shgetfolderpath = false; static HMODULE shell32_module = NULL; -DECL_WINDOWS_FUNCTION(static, HRESULT, SHGetFolderPathA, - (HWND, int, HANDLE, DWORD, LPSTR)); +DECL_WINDOWS_FUNCTION(static, HRESULT, SHGetFolderPathA, + (HWND, int, HANDLE, DWORD, LPSTR)); struct settings_w { HKEY sesskey; @@ -40,25 +40,25 @@ settings_w *open_settings_w(const char *sessionname, char **errmsg) *errmsg = NULL; if (!sessionname || !*sessionname) - sessionname = "Default Settings"; + sessionname = "Default Settings"; sb = strbuf_new(); escape_registry_key(sessionname, sb); ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1); if (ret != ERROR_SUCCESS) { - strbuf_free(sb); + strbuf_free(sb); *errmsg = dupprintf("Unable to create registry key\n" "HKEY_CURRENT_USER\\%s", puttystr); - return NULL; + return NULL; } ret = RegCreateKey(subkey1, sb->s, &sesskey); RegCloseKey(subkey1); if (ret != ERROR_SUCCESS) { *errmsg = dupprintf("Unable to create registry key\n" "HKEY_CURRENT_USER\\%s\\%s", puttystr, sb->s); - strbuf_free(sb); - return NULL; + strbuf_free(sb); + return NULL; } strbuf_free(sb); @@ -71,14 +71,14 @@ void write_setting_s(settings_w *handle, const char *key, const char *value) { if (handle) RegSetValueEx(handle->sesskey, key, 0, REG_SZ, (CONST BYTE *)value, - 1 + strlen(value)); + 1 + strlen(value)); } void write_setting_i(settings_w *handle, const char *key, int value) { if (handle) RegSetValueEx(handle->sesskey, key, 0, REG_DWORD, - (CONST BYTE *) &value, sizeof(value)); + (CONST BYTE *) &value, sizeof(value)); } void close_settings_w(settings_w *handle) @@ -97,18 +97,18 @@ settings_r *open_settings_r(const char *sessionname) strbuf *sb; if (!sessionname || !*sessionname) - sessionname = "Default Settings"; + sessionname = "Default Settings"; sb = strbuf_new(); escape_registry_key(sessionname, sb); if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) { - sesskey = NULL; + sesskey = NULL; } else { - if (RegOpenKey(subkey1, sb->s, &sesskey) != ERROR_SUCCESS) { - sesskey = NULL; - } - RegCloseKey(subkey1); + if (RegOpenKey(subkey1, sb->s, &sesskey) != ERROR_SUCCESS) { + sesskey = NULL; + } + RegCloseKey(subkey1); } strbuf_free(sb); @@ -127,19 +127,19 @@ char *read_setting_s(settings_r *handle, const char *key) char *ret; if (!handle) - return NULL; + return NULL; /* Find out the type and size of the data. */ if (RegQueryValueEx(handle->sesskey, key, 0, - &type, NULL, &size) != ERROR_SUCCESS || - type != REG_SZ) - return NULL; + &type, NULL, &size) != ERROR_SUCCESS || + type != REG_SZ) + return NULL; allocsize = size+1; /* allow for an extra NUL if needed */ ret = snewn(allocsize, char); if (RegQueryValueEx(handle->sesskey, key, 0, - &type, (BYTE *)ret, &size) != ERROR_SUCCESS || - type != REG_SZ) { + &type, (BYTE *)ret, &size) != ERROR_SUCCESS || + type != REG_SZ) { sfree(ret); return NULL; } @@ -157,11 +157,11 @@ int read_setting_i(settings_r *handle, const char *key, int defvalue) if (!handle || RegQueryValueEx(handle->sesskey, key, 0, &type, - (BYTE *) &val, &size) != ERROR_SUCCESS || - size != sizeof(val) || type != REG_DWORD) - return defvalue; + (BYTE *) &val, &size) != ERROR_SUCCESS || + size != sizeof(val) || type != REG_DWORD) + return defvalue; else - return val; + return val; } FontSpec *read_setting_fontspec(settings_r *handle, const char *name) @@ -173,7 +173,7 @@ FontSpec *read_setting_fontspec(settings_r *handle, const char *name) fontname = read_setting_s(handle, name); if (!fontname) - return NULL; + return NULL; settingname = dupcat(name, "IsBold", NULL); isbold = read_setting_i(handle, settingname, -1); @@ -226,10 +226,10 @@ Filename *read_setting_filename(settings_r *handle, const char *name) char *tmp = read_setting_s(handle, name); if (tmp) { Filename *ret = filename_from_str(tmp); - sfree(tmp); - return ret; + sfree(tmp); + return ret; } else - return NULL; + return NULL; } void write_setting_filename(settings_w *handle, @@ -252,7 +252,7 @@ void del_settings(const char *sessionname) strbuf *sb; if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) - return; + return; sb = strbuf_new(); escape_registry_key(sessionname, sb); @@ -275,12 +275,12 @@ settings_e *enum_settings_start(void) HKEY key; if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS) - return NULL; + return NULL; ret = snew(settings_e); if (ret) { - ret->key = key; - ret->i = 0; + ret->key = key; + ret->i = 0; } return ret; @@ -316,14 +316,14 @@ void enum_settings_finish(settings_e *e) } static void hostkey_regname(strbuf *sb, const char *hostname, - int port, const char *keytype) + int port, const char *keytype) { strbuf_catf(sb, "%s@%d:", keytype, port); escape_registry_key(hostname, sb); } int verify_host_key(const char *hostname, int port, - const char *keytype, const char *key) + const char *keytype, const char *key) { char *otherstr; strbuf *regname; @@ -343,9 +343,9 @@ int verify_host_key(const char *hostname, int port, hostkey_regname(regname, hostname, port, keytype); if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys", - &rkey) != ERROR_SUCCESS) { + &rkey) != ERROR_SUCCESS) { strbuf_free(regname); - return 1; /* key does not exist in registry */ + return 1; /* key does not exist in registry */ } readlen = len; @@ -354,65 +354,65 @@ int verify_host_key(const char *hostname, int port, &type, (BYTE *)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->s + 1 + strcspn(regname->s, ":"); - char *oldstyle = snewn(len + 10, char); /* safety margin */ - readlen = len; - ret = RegQueryValueEx(rkey, justhost, NULL, &type, - (BYTE *)oldstyle, &readlen); + !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->s + 1 + strcspn(regname->s, ":"); + char *oldstyle = snewn(len + 10, char); /* safety margin */ + readlen = len; + ret = RegQueryValueEx(rkey, justhost, NULL, &type, + (BYTE *)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; + 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 */ - } + 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->s, 0, REG_SZ, (BYTE *)otherstr, - strlen(otherstr) + 1); - } + /* + * 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->s, 0, REG_SZ, (BYTE *)otherstr, + strlen(otherstr) + 1); + } sfree(oldstyle); } @@ -425,16 +425,16 @@ int verify_host_key(const char *hostname, int port, strbuf_free(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 */ } bool have_ssh_host_key(const char *hostname, int port, - const char *keytype) + const char *keytype) { /* * If we have a host key, verify_host_key will return 0 or 2. @@ -444,7 +444,7 @@ bool have_ssh_host_key(const char *hostname, int port, } void store_host_key(const char *hostname, int port, - const char *keytype, const char *key) + const char *keytype, const char *key) { strbuf *regname; HKEY rkey; @@ -453,10 +453,10 @@ void store_host_key(const char *hostname, int port, hostkey_regname(regname, hostname, port, keytype); if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys", - &rkey) == ERROR_SUCCESS) { - RegSetValueEx(rkey, regname->s, 0, REG_SZ, + &rkey) == ERROR_SUCCESS) { + RegSetValueEx(rkey, regname->s, 0, REG_SZ, (BYTE *)key, strlen(key) + 1); - RegCloseKey(rkey); + RegCloseKey(rkey); } /* else key does not exist in registry */ strbuf_free(regname); @@ -473,18 +473,18 @@ static bool try_random_seed(char const *path, int action, HANDLE *ret) nonfatal("Unable to delete '%s': %s", path, win_strerror(GetLastError())); } - *ret = INVALID_HANDLE_VALUE; - return false; /* so we'll do the next ones too */ + *ret = INVALID_HANDLE_VALUE; + return false; /* so we'll do the next ones too */ } *ret = CreateFile(path, - action == OPEN_W ? GENERIC_WRITE : GENERIC_READ, - action == OPEN_W ? 0 : (FILE_SHARE_READ | - FILE_SHARE_WRITE), - NULL, - action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING, - action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0, - NULL); + action == OPEN_W ? GENERIC_WRITE : GENERIC_READ, + action == OPEN_W ? 0 : (FILE_SHARE_READ | + FILE_SHARE_WRITE), + NULL, + action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING, + action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0, + NULL); return (*ret != INVALID_HANDLE_VALUE); } @@ -504,7 +504,7 @@ static HANDLE access_random_seed(int action) /* * Iterate over a selection of possible random seed paths until * we find one that works. - * + * * We do this iteration separately for reading and writing, * meaning that we will automatically migrate random seed files * if a better location becomes available (by reading from the @@ -537,27 +537,27 @@ static HANDLE access_random_seed(int action) * versions of Windows. */ if (!tried_shgetfolderpath) { - /* This is likely only to bear fruit on systems with IE5+ - * installed, or WinMe/2K+. There is some faffing with - * SHFOLDER.DLL we could do to try to find an equivalent - * on older versions of Windows if we cared enough. - * However, the invocation below requires IE5+ anyway, - * so stuff that. */ - shell32_module = load_system32_dll("shell32.dll"); - GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA); - tried_shgetfolderpath = true; + /* This is likely only to bear fruit on systems with IE5+ + * installed, or WinMe/2K+. There is some faffing with + * SHFOLDER.DLL we could do to try to find an equivalent + * on older versions of Windows if we cared enough. + * However, the invocation below requires IE5+ anyway, + * so stuff that. */ + shell32_module = load_system32_dll("shell32.dll"); + GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA); + tried_shgetfolderpath = true; } if (p_SHGetFolderPathA) { char profile[MAX_PATH + 1]; - if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, - NULL, SHGFP_TYPE_CURRENT, profile)) && + if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, + NULL, SHGFP_TYPE_CURRENT, profile)) && try_random_seed_and_free(dupcat(profile, "\\PUTTY.RND", (const char *)NULL), action, &rethandle)) return rethandle; - if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA, - NULL, SHGFP_TYPE_CURRENT, profile)) && + if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA, + NULL, SHGFP_TYPE_CURRENT, profile)) && try_random_seed_and_free(dupcat(profile, "\\PUTTY.RND", (const char *)NULL), action, &rethandle)) @@ -569,7 +569,7 @@ static HANDLE access_random_seed(int action) * user's home directory. */ { - char drv[MAX_PATH], path[MAX_PATH]; + char drv[MAX_PATH], path[MAX_PATH]; DWORD drvlen = GetEnvironmentVariable("HOMEDRIVE", drv, sizeof(drv)); DWORD pathlen = GetEnvironmentVariable("HOMEPATH", path, sizeof(path)); @@ -611,16 +611,16 @@ void read_random_seed(noise_consumer_t consumer) HANDLE seedf = access_random_seed(OPEN_R); if (seedf != INVALID_HANDLE_VALUE) { - while (1) { - char buf[1024]; - DWORD len; + while (1) { + char buf[1024]; + DWORD len; - if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len) - consumer(buf, len); - else - break; - } - CloseHandle(seedf); + if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len) + consumer(buf, len); + else + break; + } + CloseHandle(seedf); } } @@ -629,10 +629,10 @@ void write_random_seed(void *data, int len) HANDLE seedf = access_random_seed(OPEN_W); if (seedf != INVALID_HANDLE_VALUE) { - DWORD lenwritten; + DWORD lenwritten; - WriteFile(seedf, data, len, &lenwritten, NULL); - CloseHandle(seedf); + WriteFile(seedf, data, len, &lenwritten, NULL); + CloseHandle(seedf); } } @@ -659,7 +659,7 @@ static int transform_jumplist_registry REG_OPTION_NON_VOLATILE, (KEY_READ | KEY_WRITE), NULL, &pjumplist_key, NULL); if (ret != ERROR_SUCCESS) { - return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE; + return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE; } /* Get current list of saved sessions in the registry. */ @@ -792,7 +792,7 @@ char *get_jumplist_registry_entries (void) char *list_value; if (transform_jumplist_registry(NULL,NULL,&list_value) != JUMPLISTREG_OK) { - list_value = snewn(2, char); + list_value = snewn(2, char); *list_value = '\0'; *(list_value + 1) = '\0'; } @@ -810,11 +810,11 @@ static void registry_recursive_remove(HKEY key) 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); } } @@ -844,9 +844,9 @@ 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); + ERROR_SUCCESS) { + registry_recursive_remove(key); + RegCloseKey(key); } /* * Now open the parent key and remove the PuTTY main key. Once @@ -854,22 +854,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. diff --git a/windows/winstuff.h b/windows/winstuff.h index 48bd4d43..0b191d54 100644 --- a/windows/winstuff.h +++ b/windows/winstuff.h @@ -9,7 +9,7 @@ #include #endif #include -#include /* for FILENAME_MAX */ +#include /* for FILENAME_MAX */ /* We use uintptr_t for Win32/Win64 portability, so we should in * principle include stdint.h, which defines it according to the C @@ -66,7 +66,7 @@ struct FontSpec *fontspec_new( CLEARTYPE_QUALITY) #define PLATFORM_IS_UTF16 /* enable UTF-16 processing when exchanging - * wchar_t strings with environment */ + * wchar_t strings with environment */ #define PLATFORM_CLIPBOARDS(X) \ X(CLIP_SYSTEM, "system clipboard") \ @@ -185,7 +185,7 @@ struct FontSpec *fontspec_new( #define GETTICKCOUNT GetTickCount #define CURSORBLINK GetCaretBlinkTime() -#define TICKSPERSEC 1000 /* GetTickCount returns milliseconds */ +#define TICKSPERSEC 1000 /* GetTickCount returns milliseconds */ #define DEFAULT_CODEPAGE CP_ACP #define USES_VTLINE_HACK @@ -210,7 +210,7 @@ typedef void *Ssh_gss_name; * Window handles for the windows that can be running during a * PuTTY session. */ -GLOBAL HWND hwnd; /* the main terminal window */ +GLOBAL HWND hwnd; /* the main terminal window */ GLOBAL HWND logbox; /* @@ -299,11 +299,11 @@ void write_aclip(int clipboard, char *, int, bool); * `lpstrFilter' in an OPENFILENAME structure. */ #define FILTER_KEY_FILES ("PuTTY Private Key Files (*.ppk)\0*.ppk\0" \ - "All Files (*.*)\0*\0\0\0") + "All Files (*.*)\0*\0\0\0") #define FILTER_WAVE_FILES ("Wave Files (*.wav)\0*.WAV\0" \ - "All Files (*.*)\0*\0\0\0") + "All Files (*.*)\0*\0\0\0") #define FILTER_DYNLIB_FILES ("Dynamic Library Files (*.dll)\0*.dll\0" \ - "All Files (*.*)\0*\0\0\0") + "All Files (*.*)\0*\0\0\0") /* * Exports from winnet.c. @@ -327,12 +327,12 @@ SockAddr *sk_namedpipe_addr(const char *pipename); * here they are. */ DECL_WINDOWS_FUNCTION(GLOBAL, int, WSAAsyncSelect, - (SOCKET, HWND, u_int, long)); + (SOCKET, HWND, u_int, long)); DECL_WINDOWS_FUNCTION(GLOBAL, int, WSAEventSelect, - (SOCKET, WSAEVENT, long)); + (SOCKET, WSAEVENT, long)); DECL_WINDOWS_FUNCTION(GLOBAL, int, WSAGetLastError, (void)); DECL_WINDOWS_FUNCTION(GLOBAL, int, WSAEnumNetworkEvents, - (SOCKET, WSAEVENT, LPWSANETWORKEVENTS)); + (SOCKET, WSAEVENT, LPWSANETWORKEVENTS)); #ifdef NEED_DECLARATION_OF_SELECT /* This declaration is protected by an ifdef for the sake of building * against winelib, in which you have to include winsock2.h before @@ -342,8 +342,8 @@ DECL_WINDOWS_FUNCTION(GLOBAL, int, WSAEnumNetworkEvents, * this function pointer will see its declaration, and _those_ modules * - which will be Windows-specific anyway - can take more care. */ DECL_WINDOWS_FUNCTION(GLOBAL, int, select, - (int, fd_set FAR *, fd_set FAR *, - fd_set FAR *, const struct timeval FAR *)); + (int, fd_set FAR *, fd_set FAR *, + fd_set FAR *, const struct timeval FAR *)); #endif /* @@ -402,21 +402,21 @@ struct prefslist { * parameter, and hence is passed back to winctrls access functions. */ struct dlgparam { - HWND hwnd; /* the hwnd of the dialog box */ + HWND hwnd; /* the hwnd of the dialog box */ struct winctrls *controltrees[8]; /* can have several of these */ int nctrltrees; - char *wintitle; /* title of actual window */ - char *errtitle; /* title of error sub-messageboxes */ - void *data; /* data to pass in refresh events */ + char *wintitle; /* title of actual window */ + char *errtitle; /* title of error sub-messageboxes */ + void *data; /* data to pass in refresh events */ union control *focused, *lastfocused; /* which ctrl has focus now/before */ bool shortcuts[128]; /* track which shortcuts in use */ bool coloursel_wanted; /* has an event handler asked for - * a colour selector? */ + * a colour selector? */ struct { unsigned char r, g, b; /* 0-255 */ bool ok; } coloursel_result; - tree234 *privdata; /* stores per-control private data */ + tree234 *privdata; /* stores per-control private data */ bool ended; /* has the dialog been ended? */ int endresult; /* and if so, what was the result? */ bool fixed_pitch_fonts; /* are we constrained to fixed fonts? */ @@ -426,57 +426,57 @@ struct dlgparam { * Exports from winctrls.c. */ void ctlposinit(struct ctlpos *cp, HWND hwnd, - int leftborder, int rightborder, int topborder); + int leftborder, int rightborder, int topborder); HWND 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 editboxfw(struct ctlpos *cp, bool password, char *text, - int staticid, int editid); + int staticid, int editid); void radioline(struct ctlpos *cp, char *text, int id, int nacross, ...); void bareradioline(struct ctlpos *cp, 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 lines, int id); void staticbtn(struct ctlpos *cp, char *stext, int sid, - char *btext, int bid); + char *btext, int bid); void static2btn(struct ctlpos *cp, char *stext, int sid, - char *btext1, int bid1, char *btext2, int bid2); + char *btext1, int bid1, char *btext2, int bid2); void staticedit(struct ctlpos *cp, char *stext, - int sid, int eid, int percentedit); + int sid, int eid, int percentedit); void staticddl(struct ctlpos *cp, char *stext, - int sid, int lid, int percentlist); + int sid, int lid, int percentlist); void combobox(struct ctlpos *cp, char *text, int staticid, int listid); 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); + 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 prefslist(struct prefslist *hdl, struct ctlpos *cp, int lines, - char *stext, int sid, int listid, int upbid, int dnbid); + char *stext, int sid, int listid, int upbid, int dnbid); int handle_prefslist(struct prefslist *hdl, - int *array, int maxmemb, - bool is_dlmsg, HWND hwnd, - WPARAM wParam, LPARAM lParam); + int *array, int maxmemb, + bool is_dlmsg, HWND hwnd, + WPARAM wParam, LPARAM lParam); void progressbar(struct ctlpos *cp, int id); void fwdsetter(struct ctlpos *cp, int listid, char *stext, int sid, - char *e1stext, int e1sid, int e1id, - char *e2stext, int e2sid, int e2id, - char *btext, int bid, - char *r1text, int r1id, char *r2text, int r2id); + char *e1stext, int e1sid, int e1id, + char *e2stext, int e2sid, int e2id, + char *btext, int bid, + char *r1text, int r1id, char *r2text, int r2id); void dlg_auto_set_fixed_pitch_flag(dlgparam *dlg); bool dlg_get_fixed_pitch_flag(dlgparam *dlg); @@ -531,7 +531,7 @@ struct winctrl *winctrl_findbyctrl(struct winctrls *, union control *); struct winctrl *winctrl_findbyid(struct winctrls *, int); struct winctrl *winctrl_findbyindex(struct winctrls *, int); void winctrl_layout(struct dlgparam *dp, struct winctrls *wc, - struct ctlpos *cp, struct controlset *s, int *id); + struct ctlpos *cp, struct controlset *s, int *id); bool winctrl_handle_command(struct dlgparam *dp, UINT msg, WPARAM wParam, LPARAM lParam); void winctrl_rem_shortcuts(struct dlgparam *dp, struct winctrl *c); @@ -545,7 +545,7 @@ void dp_cleanup(struct dlgparam *dp); * Exports from wincfg.c. */ void win_setup_config_box(struct controlbox *b, HWND *hwndp, bool has_help, - bool midsession, int protocol); + bool midsession, int protocol); /* * Exports from windlg.c. @@ -614,9 +614,9 @@ typedef size_t (*handle_inputfn_t)( typedef void (*handle_outputfn_t)( struct handle *h, size_t new_backlog, int err); struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata, - void *privdata, int flags); + void *privdata, int flags); struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata, - void *privdata, int flags); + void *privdata, int flags); size_t handle_write(struct handle *h, const void *data, size_t len); void handle_write_eof(struct handle *h); HANDLE *handle_get_events(int *nevents); @@ -638,12 +638,12 @@ void handle_sink_init(handle_sink *sink, struct handle *h); * winpgntc.c needs to schedule callbacks for asynchronous agent * requests. This has to be done differently in GUI and console, so * there's an exported function used for the purpose. - * + * * Also, we supply FLAG_SYNCAGENT to force agent requests to be * synchronous in pscp and psftp. */ void agent_schedule_callback(void (*callback)(void *, void *, int), - void *callback_ctx, void *data, int len); + void *callback_ctx, void *data, int len); #define FLAG_SYNCAGENT 0x1000 /* diff --git a/windows/winucs.c b/windows/winucs.c index f5fbffe6..9ffff5e9 100644 --- a/windows/winucs.c +++ b/windows/winucs.c @@ -25,7 +25,7 @@ static const WCHAR unitab_xterm_std[32] = { * duplicate definitions. */ -/* +/* * Tables for ISO-8859-{1-10,13-16} derived from those downloaded * 2001-10-02 from -- jtn * Table for ISO-8859-11 derived from same on 2002-11-18. -- bjh21 @@ -445,62 +445,62 @@ void init_ucs(Conf *conf, struct unicode_data *ucsdata) /* Decide on the Line and Font codepages */ ucsdata->line_codepage = decode_codepage(conf_get_str(conf, - CONF_line_codepage)); + CONF_line_codepage)); - if (ucsdata->font_codepage <= 0) { - ucsdata->font_codepage=0; - ucsdata->dbcs_screenfont=false; + if (ucsdata->font_codepage <= 0) { + ucsdata->font_codepage=0; + ucsdata->dbcs_screenfont=false; } vtmode = conf_get_int(conf, CONF_vtmode); if (vtmode == VT_OEMONLY) { - ucsdata->font_codepage = 437; - ucsdata->dbcs_screenfont = false; - if (ucsdata->line_codepage <= 0) - ucsdata->line_codepage = GetACP(); + ucsdata->font_codepage = 437; + ucsdata->dbcs_screenfont = false; + if (ucsdata->line_codepage <= 0) + ucsdata->line_codepage = GetACP(); } else if (ucsdata->line_codepage <= 0) - ucsdata->line_codepage = ucsdata->font_codepage; + ucsdata->line_codepage = ucsdata->font_codepage; /* Collect screen font ucs table */ if (ucsdata->dbcs_screenfont || ucsdata->font_codepage == 0) { - get_unitab(ucsdata->font_codepage, ucsdata->unitab_font, 2); - for (i = 128; i < 256; i++) - ucsdata->unitab_font[i] = (WCHAR) (CSET_ACP + i); + get_unitab(ucsdata->font_codepage, ucsdata->unitab_font, 2); + for (i = 128; i < 256; i++) + ucsdata->unitab_font[i] = (WCHAR) (CSET_ACP + i); } else { - get_unitab(ucsdata->font_codepage, ucsdata->unitab_font, 1); + get_unitab(ucsdata->font_codepage, ucsdata->unitab_font, 1); - /* CP437 fonts are often broken ... */ - if (ucsdata->font_codepage == 437) - ucsdata->unitab_font[0] = ucsdata->unitab_font[255] = 0xFFFF; + /* CP437 fonts are often broken ... */ + if (ucsdata->font_codepage == 437) + ucsdata->unitab_font[0] = ucsdata->unitab_font[255] = 0xFFFF; } if (vtmode == VT_XWINDOWS) - memcpy(ucsdata->unitab_font + 1, unitab_xterm_std, - sizeof(unitab_xterm_std)); + memcpy(ucsdata->unitab_font + 1, unitab_xterm_std, + sizeof(unitab_xterm_std)); /* Collect OEMCP ucs table */ get_unitab(CP_OEMCP, ucsdata->unitab_oemcp, 1); /* Collect CP437 ucs table for SCO acs */ if (vtmode == VT_OEMANSI || vtmode == VT_XWINDOWS) - memcpy(ucsdata->unitab_scoacs, ucsdata->unitab_oemcp, - sizeof(ucsdata->unitab_scoacs)); + memcpy(ucsdata->unitab_scoacs, ucsdata->unitab_oemcp, + sizeof(ucsdata->unitab_scoacs)); else - get_unitab(437, ucsdata->unitab_scoacs, 1); + get_unitab(437, ucsdata->unitab_scoacs, 1); /* Collect line set ucs table */ if (ucsdata->line_codepage == ucsdata->font_codepage && - (ucsdata->dbcs_screenfont || - vtmode == VT_POORMAN || ucsdata->font_codepage==0)) { + (ucsdata->dbcs_screenfont || + vtmode == VT_POORMAN || ucsdata->font_codepage==0)) { - /* For DBCS and POOR fonts force direct to font */ - used_dtf = true; - for (i = 0; i < 32; i++) - ucsdata->unitab_line[i] = (WCHAR) i; - for (i = 32; i < 256; i++) - ucsdata->unitab_line[i] = (WCHAR) (CSET_ACP + i); - ucsdata->unitab_line[127] = (WCHAR) 127; + /* For DBCS and POOR fonts force direct to font */ + used_dtf = true; + for (i = 0; i < 32; i++) + ucsdata->unitab_line[i] = (WCHAR) i; + for (i = 32; i < 256; i++) + ucsdata->unitab_line[i] = (WCHAR) (CSET_ACP + i); + ucsdata->unitab_line[127] = (WCHAR) 127; } else { - get_unitab(ucsdata->line_codepage, ucsdata->unitab_line, 0); + get_unitab(ucsdata->line_codepage, ucsdata->unitab_line, 0); } #if 0 @@ -508,101 +508,101 @@ void init_ucs(Conf *conf, struct unicode_data *ucsdata) ucsdata->font_codepage, ucsdata->dbcs_screenfont ? " DBCS" : ""); for (i = 0; i < 256; i += 16) { - for (j = 0; j < 16; j++) { - debug("%04x%s", ucsdata->unitab_line[i + j], j == 15 ? "" : ","); - } - debug("\n"); + for (j = 0; j < 16; j++) { + debug("%04x%s", ucsdata->unitab_line[i + j], j == 15 ? "" : ","); + } + debug("\n"); } #endif /* VT100 graphics - NB: Broken for non-ascii CP's */ memcpy(ucsdata->unitab_xterm, ucsdata->unitab_line, - sizeof(ucsdata->unitab_xterm)); + sizeof(ucsdata->unitab_xterm)); memcpy(ucsdata->unitab_xterm + '`', unitab_xterm_std, - sizeof(unitab_xterm_std)); + sizeof(unitab_xterm_std)); ucsdata->unitab_xterm['_'] = ' '; /* Generate UCS ->line page table. */ if (ucsdata->uni_tbl) { - for (i = 0; i < 256; i++) - if (ucsdata->uni_tbl[i]) - sfree(ucsdata->uni_tbl[i]); - sfree(ucsdata->uni_tbl); - ucsdata->uni_tbl = 0; + for (i = 0; i < 256; i++) + if (ucsdata->uni_tbl[i]) + sfree(ucsdata->uni_tbl[i]); + sfree(ucsdata->uni_tbl); + ucsdata->uni_tbl = 0; } if (!used_dtf) { - for (i = 0; i < 256; i++) { - if (DIRECT_CHAR(ucsdata->unitab_line[i])) - continue; - if (DIRECT_FONT(ucsdata->unitab_line[i])) - continue; - if (!ucsdata->uni_tbl) { - ucsdata->uni_tbl = snewn(256, char *); - memset(ucsdata->uni_tbl, 0, 256 * sizeof(char *)); - } - j = ((ucsdata->unitab_line[i] >> 8) & 0xFF); - if (!ucsdata->uni_tbl[j]) { - ucsdata->uni_tbl[j] = snewn(256, char); - memset(ucsdata->uni_tbl[j], 0, 256 * sizeof(char)); - } - ucsdata->uni_tbl[j][ucsdata->unitab_line[i] & 0xFF] = i; - } + for (i = 0; i < 256; i++) { + if (DIRECT_CHAR(ucsdata->unitab_line[i])) + continue; + if (DIRECT_FONT(ucsdata->unitab_line[i])) + continue; + if (!ucsdata->uni_tbl) { + ucsdata->uni_tbl = snewn(256, char *); + memset(ucsdata->uni_tbl, 0, 256 * sizeof(char *)); + } + j = ((ucsdata->unitab_line[i] >> 8) & 0xFF); + if (!ucsdata->uni_tbl[j]) { + ucsdata->uni_tbl[j] = snewn(256, char); + memset(ucsdata->uni_tbl[j], 0, 256 * sizeof(char)); + } + ucsdata->uni_tbl[j][ucsdata->unitab_line[i] & 0xFF] = i; + } } /* Find the line control characters. */ for (i = 0; i < 256; i++) - if (ucsdata->unitab_line[i] < ' ' - || (ucsdata->unitab_line[i] >= 0x7F && - ucsdata->unitab_line[i] < 0xA0)) - ucsdata->unitab_ctrl[i] = i; - else - ucsdata->unitab_ctrl[i] = 0xFF; + if (ucsdata->unitab_line[i] < ' ' + || (ucsdata->unitab_line[i] >= 0x7F && + ucsdata->unitab_line[i] < 0xA0)) + ucsdata->unitab_ctrl[i] = i; + else + ucsdata->unitab_ctrl[i] = 0xFF; /* Generate line->screen direct conversion links. */ if (vtmode == VT_OEMANSI || vtmode == VT_XWINDOWS) - link_font(ucsdata->unitab_scoacs, ucsdata->unitab_oemcp, CSET_OEMCP); + link_font(ucsdata->unitab_scoacs, ucsdata->unitab_oemcp, CSET_OEMCP); link_font(ucsdata->unitab_line, ucsdata->unitab_font, CSET_ACP); link_font(ucsdata->unitab_scoacs, ucsdata->unitab_font, CSET_ACP); link_font(ucsdata->unitab_xterm, ucsdata->unitab_font, CSET_ACP); if (vtmode == VT_OEMANSI || vtmode == VT_XWINDOWS) { - link_font(ucsdata->unitab_line, ucsdata->unitab_oemcp, CSET_OEMCP); - link_font(ucsdata->unitab_xterm, ucsdata->unitab_oemcp, CSET_OEMCP); + link_font(ucsdata->unitab_line, ucsdata->unitab_oemcp, CSET_OEMCP); + link_font(ucsdata->unitab_xterm, ucsdata->unitab_oemcp, CSET_OEMCP); } if (ucsdata->dbcs_screenfont && - ucsdata->font_codepage != ucsdata->line_codepage) { - /* F***ing Microsoft fonts, Japanese and Korean codepage fonts - * have a currency symbol at 0x5C but their unicode value is - * still given as U+005C not the correct U+00A5. */ - ucsdata->unitab_line['\\'] = CSET_OEMCP + '\\'; + ucsdata->font_codepage != ucsdata->line_codepage) { + /* F***ing Microsoft fonts, Japanese and Korean codepage fonts + * have a currency symbol at 0x5C but their unicode value is + * still given as U+005C not the correct U+00A5. */ + ucsdata->unitab_line['\\'] = CSET_OEMCP + '\\'; } /* Last chance, if !unicode then try poorman links. */ if (vtmode != VT_UNICODE) { - static const char poorman_scoacs[] = - "CueaaaaceeeiiiAAE**ooouuyOUc$YPsaiounNao?++**!<>###||||++||++++++--|-+||++--|-+----++++++++##||#aBTPEsyt******EN=+><++-=... n2* "; - static const char poorman_latin1[] = - " !cL.Y|S\"Ca<--R~o+23'u|.,1o>///?AAAAAAACEEEEIIIIDNOOOOOxOUUUUYPBaaaaaaaceeeeiiiionooooo/ouuuuypy"; - static const char poorman_vt100[] = "*#****o~**+++++-----++++|****L."; + static const char poorman_scoacs[] = + "CueaaaaceeeiiiAAE**ooouuyOUc$YPsaiounNao?++**!<>###||||++||++++++--|-+||++--|-+----++++++++##||#aBTPEsyt******EN=+><++-=... n2* "; + static const char poorman_latin1[] = + " !cL.Y|S\"Ca<--R~o+23'u|.,1o>///?AAAAAAACEEEEIIIIDNOOOOOxOUUUUYPBaaaaaaaceeeeiiiionooooo/ouuuuypy"; + static const char poorman_vt100[] = "*#****o~**+++++-----++++|****L."; - for (i = 160; i < 256; i++) - if (!DIRECT_FONT(ucsdata->unitab_line[i]) && - ucsdata->unitab_line[i] >= 160 && - ucsdata->unitab_line[i] < 256) { - ucsdata->unitab_line[i] = - (WCHAR) (CSET_ACP + - poorman_latin1[ucsdata->unitab_line[i] - 160]); - } - for (i = 96; i < 127; i++) - if (!DIRECT_FONT(ucsdata->unitab_xterm[i])) - ucsdata->unitab_xterm[i] = - (WCHAR) (CSET_ACP + poorman_vt100[i - 96]); - for(i=128;i<256;i++) - if (!DIRECT_FONT(ucsdata->unitab_scoacs[i])) - ucsdata->unitab_scoacs[i] = - (WCHAR) (CSET_ACP + poorman_scoacs[i - 128]); + for (i = 160; i < 256; i++) + if (!DIRECT_FONT(ucsdata->unitab_line[i]) && + ucsdata->unitab_line[i] >= 160 && + ucsdata->unitab_line[i] < 256) { + ucsdata->unitab_line[i] = + (WCHAR) (CSET_ACP + + poorman_latin1[ucsdata->unitab_line[i] - 160]); + } + for (i = 96; i < 127; i++) + if (!DIRECT_FONT(ucsdata->unitab_xterm[i])) + ucsdata->unitab_xterm[i] = + (WCHAR) (CSET_ACP + poorman_vt100[i - 96]); + for(i=128;i<256;i++) + if (!DIRECT_FONT(ucsdata->unitab_scoacs[i])) + ucsdata->unitab_scoacs[i] = + (WCHAR) (CSET_ACP + poorman_scoacs[i - 128]); } } @@ -610,15 +610,15 @@ static void link_font(WCHAR * line_tbl, WCHAR * font_tbl, WCHAR attr) { int font_index, line_index, i; for (line_index = 0; line_index < 256; line_index++) { - if (DIRECT_FONT(line_tbl[line_index])) - continue; - for(i = 0; i < 256; i++) { - font_index = ((32 + i) & 0xFF); - if (line_tbl[line_index] == font_tbl[font_index]) { - line_tbl[line_index] = (WCHAR) (attr + font_index); - break; - } - } + if (DIRECT_FONT(line_tbl[line_index])) + continue; + for(i = 0; i < 256; i++) { + font_index = ((32 + i) & 0xFF); + if (line_tbl[line_index] == font_tbl[font_index]) { + line_tbl[line_index] = (WCHAR) (attr + font_index); + break; + } + } } } @@ -649,7 +649,7 @@ int check_compose_internal(int first, int second, int recurse) { static const struct { - char first, second; + char first, second; wchar_t composed; } composetbl[] = { {0x2b, 0x2b, 0x0023}, @@ -981,16 +981,16 @@ int check_compose_internal(int first, int second, int recurse) int nc = -1; for (c = composetbl; c->first; c++) { - if (c->first == first && c->second == second) - return c->composed; + if (c->first == first && c->second == second) + return c->composed; } if (recurse == 0) { - nc = check_compose_internal(second, first, 1); - if (nc == -1) - nc = check_compose_internal(toupper(first), toupper(second), 1); - if (nc == -1) - nc = check_compose_internal(toupper(second), toupper(first), 1); + nc = check_compose_internal(second, first, 1); + if (nc == -1) + nc = check_compose_internal(toupper(first), toupper(second), 1); + if (nc == -1) + nc = check_compose_internal(toupper(second), toupper(first), 1); } return nc; } @@ -1047,7 +1047,7 @@ int decode_codepage(char *cp_name) d += 3; for (s = d; *s >= '0' && *s <= '9'; s++); if (*s == 0 && s != d) - codepage = atoi(d); /* CP999 or IBM999 */ + codepage = atoi(d); /* CP999 or IBM999 */ if (codepage == CP_ACP) codepage = GetACP(); @@ -1058,15 +1058,15 @@ int decode_codepage(char *cp_name) break_break:; if (codepage != -1) { - if (codepage != CP_UTF8 && codepage < 65536) { - if (GetCPInfo(codepage, &cpinfo) == 0) { - codepage = -2; - } else if (cpinfo.MaxCharSize > 1) - codepage = -3; - } + if (codepage != CP_UTF8 && codepage < 65536) { + if (GetCPInfo(codepage, &cpinfo) == 0) { + codepage = -2; + } else if (cpinfo.MaxCharSize > 1) + codepage = -3; + } } if (codepage == -1 && *cp_name) - codepage = -2; + codepage = -2; return codepage; } @@ -1076,32 +1076,32 @@ const char *cp_name(int codepage) static char buf[32]; if (codepage == -1) { - sprintf(buf, "Use font encoding"); - return buf; + sprintf(buf, "Use font encoding"); + return buf; } if (codepage > 0 && codepage < 65536) - sprintf(buf, "CP%03d", codepage); + sprintf(buf, "CP%03d", codepage); else - *buf = 0; + *buf = 0; if (codepage >= 65536) { - cpno = 0; - for (cpi = cp_list; cpi->name; cpi++) - if (cpi == cp_list + (codepage - 65536)) { - cpno = cpi; - break; - } - if (cpno) - for (cpi = cp_list; cpi->name; cpi++) { - if (cpno->cp_table == cpi->cp_table) - return cpi->name; - } + cpno = 0; + for (cpi = cp_list; cpi->name; cpi++) + if (cpi == cp_list + (codepage - 65536)) { + cpno = cpi; + break; + } + if (cpno) + for (cpi = cp_list; cpi->name; cpi++) { + if (cpno->cp_table == cpi->cp_table) + return cpi->name; + } } else { - for (cpi = cp_list; cpi->name; cpi++) { - if (codepage == cpi->codepage) - return cpi->name; - } + for (cpi = cp_list; cpi->name; cpi++) { + if (codepage == cpi->codepage) + return cpi->name; + } } return buf; } @@ -1113,7 +1113,7 @@ const char *cp_name(int codepage) const char *cp_enumerate(int index) { if (index < 0 || index >= lenof(cp_list)) - return NULL; + return NULL; return cp_list[index].name; } @@ -1123,53 +1123,53 @@ void get_unitab(int codepage, wchar_t * unitab, int ftype) int i, max = 256, flg = MB_ERR_INVALID_CHARS; if (ftype) - flg |= MB_USEGLYPHCHARS; + flg |= MB_USEGLYPHCHARS; if (ftype == 2) - max = 128; + max = 128; if (codepage == CP_UTF8) { - for (i = 0; i < max; i++) - unitab[i] = i; - return; + for (i = 0; i < max; i++) + unitab[i] = i; + return; } if (codepage == CP_ACP) - codepage = GetACP(); + codepage = GetACP(); else if (codepage == CP_OEMCP) - codepage = GetOEMCP(); + codepage = GetOEMCP(); if (codepage > 0 && codepage < 65536) { - for (i = 0; i < max; i++) { - tbuf[0] = i; + for (i = 0; i < max; i++) { + tbuf[0] = i; - if (mb_to_wc(codepage, flg, tbuf, 1, unitab + i, 1) - != 1) - unitab[i] = 0xFFFD; - } + if (mb_to_wc(codepage, flg, tbuf, 1, unitab + i, 1) + != 1) + unitab[i] = 0xFFFD; + } } else { - int j = 256 - cp_list[codepage & 0xFFFF].cp_size; - for (i = 0; i < max; i++) - unitab[i] = i; - for (i = j; i < max; i++) - unitab[i] = cp_list[codepage & 0xFFFF].cp_table[i - j]; + int j = 256 - cp_list[codepage & 0xFFFF].cp_size; + for (i = 0; i < max; i++) + unitab[i] = i; + for (i = j; i < max; i++) + unitab[i] = cp_list[codepage & 0xFFFF].cp_table[i - j]; } } int wc_to_mb(int codepage, int flags, const wchar_t *wcstr, int wclen, - char *mbstr, int mblen, const char *defchr, - struct unicode_data *ucsdata) + char *mbstr, int mblen, const char *defchr, + struct unicode_data *ucsdata) { char *p; int i; if (ucsdata && codepage == ucsdata->line_codepage && ucsdata->uni_tbl) { - /* Do this by array lookup if we can. */ - if (wclen < 0) { - for (wclen = 0; wcstr[wclen++] ;); /* will include the NUL */ - } - for (p = mbstr, i = 0; i < wclen; i++) { - wchar_t ch = wcstr[i]; - int by; - char *p1; + /* Do this by array lookup if we can. */ + if (wclen < 0) { + for (wclen = 0; wcstr[wclen++] ;); /* will include the NUL */ + } + for (p = mbstr, i = 0; i < wclen; i++) { + wchar_t ch = wcstr[i]; + int by; + char *p1; #define WRITECH(chr) do \ { \ @@ -1179,30 +1179,30 @@ int wc_to_mb(int codepage, int flags, const wchar_t *wcstr, int wclen, if (ucsdata->uni_tbl && (p1 = ucsdata->uni_tbl[(ch >> 8) & 0xFF]) != NULL && - (by = p1[ch & 0xFF]) != '\0') + (by = p1[ch & 0xFF]) != '\0') WRITECH(by); - else if (ch < 0x80) + else if (ch < 0x80) WRITECH(ch); else if (defchr) for (const char *q = defchr; *q; q++) WRITECH(*q); #if 1 - else - WRITECH('.'); + else + WRITECH('.'); #endif #undef WRITECH - } - return p - mbstr; + } + return p - mbstr; } else { int defused; - return WideCharToMultiByte(codepage, flags, wcstr, wclen, - mbstr, mblen, defchr, &defused); + return WideCharToMultiByte(codepage, flags, wcstr, wclen, + mbstr, mblen, defchr, &defused); } } int mb_to_wc(int codepage, int flags, const char *mbstr, int mblen, - wchar_t *wcstr, int wclen) + wchar_t *wcstr, int wclen) { return MultiByteToWideChar(codepage, flags, mbstr, mblen, wcstr, wclen); } diff --git a/windows/winutils.c b/windows/winutils.c index 2f4c8f59..404e11a2 100644 --- a/windows/winutils.c +++ b/windows/winutils.c @@ -41,36 +41,36 @@ bool request_file(filereq *state, OPENFILENAME *of, bool preserve, bool save) /* Get process CWD */ if (preserve) { - DWORD r = GetCurrentDirectory(lenof(cwd), cwd); - if (r == 0 || r >= lenof(cwd)) - /* Didn't work, oh well. Stop trying to be clever. */ - preserve = false; + DWORD r = GetCurrentDirectory(lenof(cwd), cwd); + if (r == 0 || r >= lenof(cwd)) + /* Didn't work, oh well. Stop trying to be clever. */ + preserve = false; } /* Open the file requester, maybe setting lpstrInitialDir */ { #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->lpstrInitialDir = (state && state->cwd[0]) ? state->cwd : NULL; - /* Actually put up the requester. */ - ret = save ? GetSaveFileName(of) : GetOpenFileName(of); + of->lpstrInitialDir = (state && state->cwd[0]) ? state->cwd : NULL; + /* Actually put up the requester. */ + ret = save ? GetSaveFileName(of) : GetOpenFileName(of); } /* Get CWD left by requester */ if (state) { - DWORD r = GetCurrentDirectory(lenof(state->cwd), state->cwd); - if (r == 0 || r >= lenof(state->cwd)) - /* Didn't work, oh well. */ - state->cwd[0] = '\0'; + DWORD r = GetCurrentDirectory(lenof(state->cwd), state->cwd); + if (r == 0 || r >= lenof(state->cwd)) + /* Didn't work, oh well. */ + state->cwd[0] = '\0'; } - + /* Restore process CWD */ if (preserve) - /* If it fails, there's not much we can do. */ - (void) SetCurrentDirectory(cwd); + /* If it fails, there's not much we can do. */ + (void) SetCurrentDirectory(cwd); return ret; } @@ -97,8 +97,8 @@ static VOID CALLBACK message_box_help_callback(LPHELPINFO lpHelpInfo) const char *context = NULL; #define CHECK_CTX(name) \ do { \ - if (lpHelpInfo->dwContextId == WINHELP_CTXID_ ## name) \ - context = WINHELP_CTX_ ## name; \ + if (lpHelpInfo->dwContextId == WINHELP_CTXID_ ## name) \ + context = WINHELP_CTX_ ## name; \ } while (0) CHECK_CTX(errors_hostkey_absent); CHECK_CTX(errors_hostkey_changed); @@ -107,13 +107,13 @@ static VOID CALLBACK message_box_help_callback(LPHELPINFO lpHelpInfo) CHECK_CTX(pgp_fingerprints); #undef CHECK_CTX if (context) - launch_help(hwnd, context); + launch_help(hwnd, context); } int message_box(LPCTSTR text, LPCTSTR caption, DWORD style, DWORD helpctxid) { MSGBOXPARAMS mbox; - + /* * We use MessageBoxIndirect() because it allows us to specify a * callback function for the Help button. @@ -138,18 +138,18 @@ int message_box(LPCTSTR text, LPCTSTR caption, DWORD style, DWORD helpctxid) void pgp_fingerprints(void) { message_box("These are the fingerprints of the PuTTY PGP Master Keys. They can\n" - "be used to establish a trust path from this executable to another\n" - "one. See the manual for more information.\n" - "(Note: these fingerprints have nothing to do with SSH!)\n" - "\n" + "be used to establish a trust path from this executable to another\n" + "one. See the manual for more information.\n" + "(Note: these fingerprints have nothing to do with SSH!)\n" + "\n" "PuTTY Master Key as of " PGP_MASTER_KEY_YEAR " (" PGP_MASTER_KEY_DETAILS "):\n" " " PGP_MASTER_KEY_FP "\n\n" "Previous Master Key (" PGP_PREV_MASTER_KEY_YEAR ", " PGP_PREV_MASTER_KEY_DETAILS "):\n" " " PGP_PREV_MASTER_KEY_FP, - "PGP fingerprints", MB_ICONINFORMATION | MB_OK, - HELPCTXID(pgp_fingerprints)); + "PGP fingerprints", MB_ICONINFORMATION | MB_OK, + HELPCTXID(pgp_fingerprints)); } /* @@ -164,7 +164,7 @@ char *GetDlgItemText_alloc(HWND hwnd, int id) do { sgrowarray_nm(ret, size, size); - GetDlgItemText(hwnd, id, ret, size); + GetDlgItemText(hwnd, id, ret, size); } while (!memchr(ret, '\0', size-1)); return ret; @@ -177,9 +177,9 @@ char *GetDlgItemText_alloc(HWND hwnd, int id) * broken apart by the C library, will have their command lines * processed in the same way as the GUI utilities which get a whole * command line and must call this function). - * + * * Does not modify the input command line. - * + * * The final parameter (argstart) is used to return a second array * of char * pointers, the same length as argv, each one pointing * at the start of the corresponding element of argv in the @@ -189,7 +189,7 @@ char *GetDlgItemText_alloc(HWND hwnd, int id) * `argstart' can be safely left NULL. */ void split_into_argv(char *cmdline, int *argc, char ***argv, - char ***argstart) + char ***argstart) { char *p; char *outputline, *q; @@ -237,11 +237,11 @@ void split_into_argv(char *cmdline, int *argc, char ***argv, * quotes (down the left), and indicate how many backslashes * are output, how many quotes are output, and whether a * quoted segment is open at the end of the sequence: - * + * * backslashes - * + * * 0 1 2 3 4 - * + * * 0 0,0,y | 1,0,y 2,0,y 3,0,y 4,0,y * --------+----------------------------- * 1 0,0,n | 0,1,y 1,0,n 1,1,y 2,0,n @@ -255,18 +255,18 @@ void split_into_argv(char *cmdline, int *argc, char ***argv, * 9 0,3,y | 0,4,n 1,3,y 1,4,n 2,3,y * 10 0,3,n | 0,4,y 1,3,n 1,4,y 2,3,n * 11 0,4,n | 0,4,n 1,4,n 1,4,n 2,4,n - * - * + * + * * [Test fragment was of the form "a\\\"""b c" d.] - * + * * There is very weird mod-3 behaviour going on here in the * number of quotes, and it even applies when there aren't any * backslashes! How ghastly. - * + * * With a bit of thought, this extremely odd diagram suddenly * coalesced itself into a coherent, if still ghastly, model of * how things work: - * + * * - As before, backslashes are only special when one or more * of them appear contiguously before at least one double * quote. In this situation the backslashes do exactly what @@ -275,17 +275,17 @@ void split_into_argv(char *cmdline, int *argc, char ***argv, * even) or (n-1)/2 literal backslashes and a literal quote * (if n is odd). In the latter case the double quote * character right after the backslashes is used up. - * + * * - After that, any remaining double quotes are processed. A * string of contiguous unescaped double quotes has a mod-3 * behaviour: - * + * * * inside a quoted segment, a quote ends the segment. * * _immediately_ after ending a quoted segment, a quote * simply produces a literal quote. * * otherwise, outside a quoted segment, a quote begins a * quoted segment. - * + * * So, for example, if we started inside a quoted segment * then two contiguous quotes would close the segment and * produce a literal quote; three would close the segment, @@ -303,10 +303,10 @@ void split_into_argv(char *cmdline, int *argc, char ***argv, */ while (*cmdline && isspace(*cmdline)) cmdline++; if (!*cmdline) { - if (argc) *argc = 0; - if (argv) *argv = NULL; - if (argstart) *argstart = NULL; - return; + if (argc) *argc = 0; + if (argv) *argv = NULL; + if (argstart) *argstart = NULL; + return; } /* @@ -320,66 +320,66 @@ void split_into_argv(char *cmdline, int *argc, char ***argv, p = cmdline; q = outputline; outputargc = 0; while (*p) { - bool quote; + bool quote; - /* Skip whitespace searching for start of argument. */ - while (*p && isspace(*p)) p++; - if (!*p) break; + /* Skip whitespace searching for start of argument. */ + while (*p && isspace(*p)) p++; + if (!*p) break; - /* We have an argument; start it. */ - outputargv[outputargc] = q; - outputargstart[outputargc] = p; - outputargc++; - quote = false; + /* We have an argument; start it. */ + outputargv[outputargc] = q; + outputargstart[outputargc] = p; + outputargc++; + quote = false; - /* Copy data into the argument until it's finished. */ - while (*p) { - if (!quote && isspace(*p)) - break; /* argument is finished */ + /* Copy data into the argument until it's finished. */ + while (*p) { + if (!quote && isspace(*p)) + break; /* argument is finished */ - if (*p == '"' || *p == '\\') { - /* - * We have a sequence of zero or more backslashes - * followed by a sequence of zero or more quotes. - * Count up how many of each, and then deal with - * them as appropriate. - */ - int i, slashes = 0, quotes = 0; - while (*p == '\\') slashes++, p++; - while (*p == '"') quotes++, p++; + if (*p == '"' || *p == '\\') { + /* + * We have a sequence of zero or more backslashes + * followed by a sequence of zero or more quotes. + * Count up how many of each, and then deal with + * them as appropriate. + */ + int i, slashes = 0, quotes = 0; + while (*p == '\\') slashes++, p++; + while (*p == '"') quotes++, p++; - if (!quotes) { - /* - * Special case: if there are no quotes, - * slashes are not special at all, so just copy - * n slashes to the output string. - */ - while (slashes--) *q++ = '\\'; - } else { - /* Slashes annihilate in pairs. */ - while (slashes >= 2) slashes -= 2, *q++ = '\\'; + if (!quotes) { + /* + * Special case: if there are no quotes, + * slashes are not special at all, so just copy + * n slashes to the output string. + */ + while (slashes--) *q++ = '\\'; + } else { + /* Slashes annihilate in pairs. */ + while (slashes >= 2) slashes -= 2, *q++ = '\\'; - /* One remaining slash takes out the first quote. */ - if (slashes) quotes--, *q++ = '"'; + /* One remaining slash takes out the first quote. */ + if (slashes) quotes--, *q++ = '"'; - if (quotes > 0) { - /* Outside a quote segment, a quote starts one. */ - if (!quote) quotes--; + if (quotes > 0) { + /* Outside a quote segment, a quote starts one. */ + if (!quote) quotes--; - /* Now we produce (n+1)/3 literal quotes... */ - for (i = 3; i <= quotes+1; i += 3) *q++ = '"'; + /* Now we produce (n+1)/3 literal quotes... */ + for (i = 3; i <= quotes+1; i += 3) *q++ = '"'; - /* ... and end in a quote segment iff 3 divides n. */ - quote = (quotes % 3 == 0); - } - } - } else { - *q++ = *p++; - } - } + /* ... and end in a quote segment iff 3 divides n. */ + quote = (quotes % 3 == 0); + } + } + } else { + *q++ = *p++; + } + } - /* At the end of an argument, just append a trailing NUL. */ - *q++ = '\0'; + /* At the end of an argument, just append a trailing NUL. */ + *q++ = '\0'; } outputargv = sresize(outputargv, outputargc, char *); @@ -497,96 +497,96 @@ int main(int argc, char **argv) int i, j; if (argc > 1) { - /* - * Generation of tests. - * - * Given `-splat ', we print out a C-style - * representation of each argument (in the form "a", "b", - * NULL), backslash-escaping each backslash and double - * quote. - * - * Given `-split ', we first doctor `string' by - * turning forward slashes into backslashes, single quotes - * into double quotes and underscores into spaces; and then - * we feed the resulting string to ourself with `-splat'. - * - * Given `-generate', we concoct a variety of fun test - * cases, encode them in quote-safe form (mapping \, " and - * space to /, ' and _ respectively) and feed each one to - * `-split'. - */ - if (!strcmp(argv[1], "-splat")) { - int i; - char *p; - for (i = 2; i < argc; i++) { - putchar('"'); - for (p = argv[i]; *p; p++) { - if (*p == '\\' || *p == '"') - putchar('\\'); - putchar(*p); - } - printf("\", "); - } - printf("NULL"); - return 0; - } + /* + * Generation of tests. + * + * Given `-splat ', we print out a C-style + * representation of each argument (in the form "a", "b", + * NULL), backslash-escaping each backslash and double + * quote. + * + * Given `-split ', we first doctor `string' by + * turning forward slashes into backslashes, single quotes + * into double quotes and underscores into spaces; and then + * we feed the resulting string to ourself with `-splat'. + * + * Given `-generate', we concoct a variety of fun test + * cases, encode them in quote-safe form (mapping \, " and + * space to /, ' and _ respectively) and feed each one to + * `-split'. + */ + if (!strcmp(argv[1], "-splat")) { + int i; + char *p; + for (i = 2; i < argc; i++) { + putchar('"'); + for (p = argv[i]; *p; p++) { + if (*p == '\\' || *p == '"') + putchar('\\'); + putchar(*p); + } + printf("\", "); + } + printf("NULL"); + return 0; + } - if (!strcmp(argv[1], "-split") && argc > 2) { - char *str = malloc(20 + strlen(argv[0]) + strlen(argv[2])); - char *p, *q; + if (!strcmp(argv[1], "-split") && argc > 2) { + char *str = malloc(20 + strlen(argv[0]) + strlen(argv[2])); + char *p, *q; - q = str + sprintf(str, "%s -splat ", argv[0]); - printf(" {\""); - for (p = argv[2]; *p; p++, q++) { - switch (*p) { - case '/': printf("\\\\"); *q = '\\'; break; - case '\'': printf("\\\""); *q = '"'; break; - case '_': printf(" "); *q = ' '; break; - default: putchar(*p); *q = *p; break; - } - } - *p = '\0'; - printf("\", {"); - fflush(stdout); + q = str + sprintf(str, "%s -splat ", argv[0]); + printf(" {\""); + for (p = argv[2]; *p; p++, q++) { + switch (*p) { + case '/': printf("\\\\"); *q = '\\'; break; + case '\'': printf("\\\""); *q = '"'; break; + case '_': printf(" "); *q = ' '; break; + default: putchar(*p); *q = *p; break; + } + } + *p = '\0'; + printf("\", {"); + fflush(stdout); - system(str); + system(str); - printf("}},\n"); + printf("}},\n"); - return 0; - } + return 0; + } - if (!strcmp(argv[1], "-generate")) { - char *teststr, *p; - int i, initialquote, backslashes, quotes; + if (!strcmp(argv[1], "-generate")) { + char *teststr, *p; + int i, initialquote, backslashes, quotes; - teststr = malloc(200 + strlen(argv[0])); + teststr = malloc(200 + strlen(argv[0])); - for (initialquote = 0; initialquote <= 1; initialquote++) { - for (backslashes = 0; backslashes < 5; backslashes++) { - for (quotes = 0; quotes < 9; quotes++) { - p = teststr + sprintf(teststr, "%s -split ", argv[0]); - if (initialquote) *p++ = '\''; - *p++ = 'a'; - for (i = 0; i < backslashes; i++) *p++ = '/'; - for (i = 0; i < quotes; i++) *p++ = '\''; - *p++ = 'b'; - *p++ = '_'; - *p++ = 'c'; - *p++ = '\''; - *p++ = '_'; - *p++ = 'd'; - *p = '\0'; + for (initialquote = 0; initialquote <= 1; initialquote++) { + for (backslashes = 0; backslashes < 5; backslashes++) { + for (quotes = 0; quotes < 9; quotes++) { + p = teststr + sprintf(teststr, "%s -split ", argv[0]); + if (initialquote) *p++ = '\''; + *p++ = 'a'; + for (i = 0; i < backslashes; i++) *p++ = '/'; + for (i = 0; i < quotes; i++) *p++ = '\''; + *p++ = 'b'; + *p++ = '_'; + *p++ = 'c'; + *p++ = '\''; + *p++ = '_'; + *p++ = 'd'; + *p = '\0'; - system(teststr); - } - } - } - return 0; - } + system(teststr); + } + } + } + return 0; + } - fprintf(stderr, "unrecognised option: \"%s\"\n", argv[1]); - return 1; + fprintf(stderr, "unrecognised option: \"%s\"\n", argv[1]); + return 1; } /* @@ -595,31 +595,31 @@ int main(int argc, char **argv) */ for (i = 0; i < lenof(argv_tests); i++) { - int ac; - char **av; + int ac; + char **av; - split_into_argv(argv_tests[i].cmdline, &ac, &av); + split_into_argv(argv_tests[i].cmdline, &ac, &av); - for (j = 0; j < ac && argv_tests[i].argv[j]; j++) { - if (strcmp(av[j], argv_tests[i].argv[j])) { - printf("failed test %d (|%s|) arg %d: |%s| should be |%s|\n", - i, argv_tests[i].cmdline, - j, av[j], argv_tests[i].argv[j]); - } + for (j = 0; j < ac && argv_tests[i].argv[j]; j++) { + if (strcmp(av[j], argv_tests[i].argv[j])) { + printf("failed test %d (|%s|) arg %d: |%s| should be |%s|\n", + i, argv_tests[i].cmdline, + j, av[j], argv_tests[i].argv[j]); + } #ifdef VERBOSE - else { - printf("test %d (|%s|) arg %d: |%s| == |%s|\n", - i, argv_tests[i].cmdline, - j, av[j], argv_tests[i].argv[j]); - } + else { + printf("test %d (|%s|) arg %d: |%s| == |%s|\n", + i, argv_tests[i].cmdline, + j, av[j], argv_tests[i].argv[j]); + } #endif - } - if (j < ac) - printf("failed test %d (|%s|): %d args returned, should be %d\n", - i, argv_tests[i].cmdline, ac, j); - if (argv_tests[i].argv[j]) - printf("failed test %d (|%s|): %d args returned, should be more\n", - i, argv_tests[i].cmdline, ac); + } + if (j < ac) + printf("failed test %d (|%s|): %d args returned, should be %d\n", + i, argv_tests[i].cmdline, ac, j); + if (argv_tests[i].argv[j]) + printf("failed test %d (|%s|): %d args returned, should be more\n", + i, argv_tests[i].cmdline, ac); } return 0; diff --git a/windows/winx11.c b/windows/winx11.c index e85fe4fb..800d8509 100644 --- a/windows/winx11.c +++ b/windows/winx11.c @@ -13,7 +13,7 @@ void platform_get_x11_auth(struct X11Display *disp, Conf *conf) { char *xauthpath = conf_get_filename(conf, CONF_xauthfile)->path; if (xauthpath[0]) - x11_get_auth_from_authfile(disp, xauthpath); + x11_get_auth_from_authfile(disp, xauthpath); } const bool platform_uses_x11_unix_by_default = false; diff --git a/x11fwd.c b/x11fwd.c index 91a5da75..faca7862 100644 --- a/x11fwd.c +++ b/x11fwd.c @@ -35,7 +35,7 @@ struct XDMSeen { }; typedef struct X11Connection { - unsigned char firstpkt[12]; /* first X data packet */ + unsigned char firstpkt[12]; /* first X data packet */ tree234 *authtree; struct X11Display *disp; char *auth_protocol; @@ -57,7 +57,7 @@ static int xdmseen_cmp(void *a, void *b) { struct XDMSeen *sa = a, *sb = b; return sa->time > sb->time ? 1 : - sa->time < sb->time ? -1 : + sa->time < sb->time ? -1 : memcmp(sa->clientid, sb->clientid, sizeof(sa->clientid)); } @@ -92,11 +92,11 @@ struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype) */ if (authtype == X11_MIT) { - auth->proto = X11_MIT; + auth->proto = X11_MIT; - /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */ + /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */ auth->datalen = 16; - auth->data = snewn(auth->datalen, unsigned char); + auth->data = snewn(auth->datalen, unsigned char); auth->xa1_firstblock = NULL; while (1) { @@ -105,14 +105,14 @@ struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype) break; } - auth->xdmseen = NULL; + auth->xdmseen = NULL; } else { - assert(authtype == X11_XDM); - auth->proto = X11_XDM; + assert(authtype == X11_XDM); + auth->proto = X11_XDM; - /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */ - auth->datalen = 16; - auth->data = snewn(auth->datalen, unsigned char); + /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */ + auth->datalen = 16; + auth->data = snewn(auth->datalen, unsigned char); auth->xa1_firstblock = snewn(8, unsigned char); memset(auth->xa1_firstblock, 0, 8); @@ -132,8 +132,8 @@ struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype) auth->protoname = dupstr(x11_authnames[auth->proto]); auth->datastring = snewn(auth->datalen * 2 + 1, char); for (i = 0; i < auth->datalen; i++) - sprintf(auth->datastring + i*2, "%02x", - auth->data[i]); + sprintf(auth->datastring + i*2, "%02x", + auth->data[i]); auth->disp = NULL; auth->share_cs = NULL; @@ -145,16 +145,16 @@ struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype) void x11_free_fake_auth(struct X11FakeAuth *auth) { if (auth->data) - smemclr(auth->data, auth->datalen); + smemclr(auth->data, auth->datalen); sfree(auth->data); sfree(auth->protoname); sfree(auth->datastring); sfree(auth->xa1_firstblock); if (auth->xdmseen != NULL) { - struct XDMSeen *seen; - while ((seen = delpos234(auth->xdmseen, 0)) != NULL) - sfree(seen); - freetree234(auth->xdmseen); + struct XDMSeen *seen; + while ((seen = delpos234(auth->xdmseen, 0)) != NULL) + sfree(seen); + freetree234(auth->xdmseen); } sfree(auth); } @@ -192,112 +192,112 @@ struct X11Display *x11_setup_display(const char *display, Conf *conf, *error_msg = NULL; if (!display || !*display) { - localcopy = platform_get_x_display(); - if (!localcopy || !*localcopy) { - sfree(localcopy); - localcopy = dupstr(":0"); /* plausible default for any platform */ - } + localcopy = platform_get_x_display(); + if (!localcopy || !*localcopy) { + sfree(localcopy); + localcopy = dupstr(":0"); /* plausible default for any platform */ + } } else - localcopy = dupstr(display); + localcopy = dupstr(display); /* * Parse the display name. * * We expect this to have one of the following forms: - * + * * - the standard X format which looks like * [ [ protocol '/' ] host ] ':' displaynumber [ '.' screennumber ] * (X11 also permits a double colon to indicate DECnet, but * that's not our problem, thankfully!) * - * - only seen in the wild on MacOS (so far): a pathname to a - * Unix-domain socket, which will typically and confusingly - * end in ":0", and which I'm currently distinguishing from - * the standard scheme by noting that it starts with '/'. + * - only seen in the wild on MacOS (so far): a pathname to a + * Unix-domain socket, which will typically and confusingly + * end in ":0", and which I'm currently distinguishing from + * the standard scheme by noting that it starts with '/'. */ if (localcopy[0] == '/') { - disp->unixsocketpath = localcopy; - disp->unixdomain = true; - disp->hostname = NULL; - disp->displaynum = -1; - disp->screennum = 0; - disp->addr = NULL; + disp->unixsocketpath = localcopy; + disp->unixdomain = true; + disp->hostname = NULL; + disp->displaynum = -1; + disp->screennum = 0; + disp->addr = NULL; } else { - char *colon, *dot, *slash; - char *protocol, *hostname; + char *colon, *dot, *slash; + char *protocol, *hostname; - colon = host_strrchr(localcopy, ':'); - if (!colon) { + colon = host_strrchr(localcopy, ':'); + if (!colon) { *error_msg = dupprintf("display name '%s' has no ':number'" " suffix", localcopy); - sfree(disp); - sfree(localcopy); - return NULL; - } + sfree(disp); + sfree(localcopy); + return NULL; + } - *colon++ = '\0'; - dot = strchr(colon, '.'); - if (dot) - *dot++ = '\0'; + *colon++ = '\0'; + dot = strchr(colon, '.'); + if (dot) + *dot++ = '\0'; - disp->displaynum = atoi(colon); - if (dot) - disp->screennum = atoi(dot); - else - disp->screennum = 0; + disp->displaynum = atoi(colon); + if (dot) + disp->screennum = atoi(dot); + else + disp->screennum = 0; - protocol = NULL; - hostname = localcopy; - if (colon > localcopy) { - slash = strchr(localcopy, '/'); - if (slash) { - *slash++ = '\0'; - protocol = localcopy; - hostname = slash; - } - } + protocol = NULL; + hostname = localcopy; + if (colon > localcopy) { + slash = strchr(localcopy, '/'); + if (slash) { + *slash++ = '\0'; + protocol = localcopy; + hostname = slash; + } + } - disp->hostname = *hostname ? dupstr(hostname) : NULL; + disp->hostname = *hostname ? dupstr(hostname) : NULL; - if (protocol) - disp->unixdomain = (!strcmp(protocol, "local") || - !strcmp(protocol, "unix")); - else if (!*hostname || !strcmp(hostname, "unix")) - disp->unixdomain = platform_uses_x11_unix_by_default; - else - disp->unixdomain = false; + if (protocol) + disp->unixdomain = (!strcmp(protocol, "local") || + !strcmp(protocol, "unix")); + else if (!*hostname || !strcmp(hostname, "unix")) + disp->unixdomain = platform_uses_x11_unix_by_default; + else + disp->unixdomain = false; - if (!disp->hostname && !disp->unixdomain) - disp->hostname = dupstr("localhost"); + if (!disp->hostname && !disp->unixdomain) + disp->hostname = dupstr("localhost"); - disp->unixsocketpath = NULL; - disp->addr = NULL; + disp->unixsocketpath = NULL; + disp->addr = NULL; - sfree(localcopy); + sfree(localcopy); } /* * Look up the display hostname, if we need to. */ if (!disp->unixdomain) { - const char *err; + const char *err; - disp->port = 6000 + disp->displaynum; - disp->addr = name_lookup(disp->hostname, disp->port, - &disp->realhost, conf, ADDRTYPE_UNSPEC, + disp->port = 6000 + disp->displaynum; + disp->addr = name_lookup(disp->hostname, disp->port, + &disp->realhost, conf, ADDRTYPE_UNSPEC, NULL, NULL); - - if ((err = sk_addr_error(disp->addr)) != NULL) { + + if ((err = sk_addr_error(disp->addr)) != NULL) { *error_msg = dupprintf("unable to resolve host name '%s' in " "display name", disp->hostname); - sk_addr_free(disp->addr); - sfree(disp->hostname); - sfree(disp->unixsocketpath); - sfree(disp); - return NULL; - } + sk_addr_free(disp->addr); + sfree(disp->hostname); + sfree(disp->unixsocketpath); + sfree(disp); + return NULL; + } } /* @@ -305,35 +305,35 @@ struct X11Display *x11_setup_display(const char *display, Conf *conf, * display (as the standard X connection libraries do). */ if (!disp->unixdomain && sk_address_is_local(disp->addr)) { - SockAddr *ux = platform_get_x11_unix_address(NULL, disp->displaynum); - const char *err = sk_addr_error(ux); - if (!err) { - /* Create trial connection to see if there is a useful Unix-domain - * socket */ - Socket *s = sk_new(sk_addr_dup(ux), 0, false, false, + SockAddr *ux = platform_get_x11_unix_address(NULL, disp->displaynum); + const char *err = sk_addr_error(ux); + if (!err) { + /* Create trial connection to see if there is a useful Unix-domain + * socket */ + Socket *s = sk_new(sk_addr_dup(ux), 0, false, false, false, false, nullplug); - err = sk_socket_error(s); - sk_close(s); - } - if (err) { - sk_addr_free(ux); - } else { - sk_addr_free(disp->addr); - disp->unixdomain = true; - disp->addr = ux; - /* Fill in the rest in a moment */ - } + err = sk_socket_error(s); + sk_close(s); + } + if (err) { + sk_addr_free(ux); + } else { + sk_addr_free(disp->addr); + disp->unixdomain = true; + disp->addr = ux; + /* Fill in the rest in a moment */ + } } if (disp->unixdomain) { - if (!disp->addr) - disp->addr = platform_get_x11_unix_address(disp->unixsocketpath, - disp->displaynum); - if (disp->unixsocketpath) - disp->realhost = dupstr(disp->unixsocketpath); - else - disp->realhost = dupprintf("unix:%d", disp->displaynum); - disp->port = 0; + if (!disp->addr) + disp->addr = platform_get_x11_unix_address(disp->unixsocketpath, + disp->displaynum); + if (disp->unixsocketpath) + disp->realhost = dupstr(disp->unixsocketpath); + else + disp->realhost = dupprintf("unix:%d", disp->displaynum); + disp->port = 0; } /* @@ -352,7 +352,7 @@ void x11_free_display(struct X11Display *disp) sfree(disp->hostname); sfree(disp->unixsocketpath); if (disp->localauthdata) - smemclr(disp->localauthdata, disp->localauthdatalen); + smemclr(disp->localauthdata, disp->localauthdatalen); sfree(disp->localauthdata); sk_addr_free(disp->addr); sfree(disp); @@ -402,47 +402,47 @@ static const char *x11_verify(unsigned long peer_ip, int peer_port, * rest of the auth data. */ if (auth->proto == X11_XDM) { - unsigned long t; - time_t tim; - int i; - struct XDMSeen *seen, *ret; + unsigned long t; + time_t tim; + int i; + struct XDMSeen *seen, *ret; if (dlen != 24) return "XDM-AUTHORIZATION-1 data was wrong length"; - if (peer_port == -1) + if (peer_port == -1) return "cannot do XDM-AUTHORIZATION-1 without remote address data"; - des_decrypt_xdmauth(auth->data+9, data, 24); + des_decrypt_xdmauth(auth->data+9, data, 24); if (memcmp(auth->data, data, 8) != 0) return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */ - if (GET_32BIT_MSB_FIRST(data+8) != peer_ip) + if (GET_32BIT_MSB_FIRST(data+8) != peer_ip) return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */ - if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port) + if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port) return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */ - t = GET_32BIT_MSB_FIRST(data+14); - for (i = 18; i < 24; i++) - if (data[i] != 0) /* zero padding wrong */ - return "XDM-AUTHORIZATION-1 data failed check"; - tim = time(NULL); - if (((unsigned long)t - (unsigned long)tim + t = GET_32BIT_MSB_FIRST(data+14); + for (i = 18; i < 24; i++) + if (data[i] != 0) /* zero padding wrong */ + return "XDM-AUTHORIZATION-1 data failed check"; + tim = time(NULL); + if (((unsigned long)t - (unsigned long)tim + XDM_MAXSKEW) > 2*XDM_MAXSKEW) - return "XDM-AUTHORIZATION-1 time stamp was too far out"; - seen = snew(struct XDMSeen); - seen->time = t; - memcpy(seen->clientid, data+8, 6); - assert(auth->xdmseen != NULL); - ret = add234(auth->xdmseen, seen); - if (ret != seen) { - sfree(seen); - return "XDM-AUTHORIZATION-1 data replayed"; - } - /* While we're here, purge entries too old to be replayed. */ - for (;;) { - seen = index234(auth->xdmseen, 0); - assert(seen != NULL); - if (t - seen->time <= XDM_MAXSKEW) - break; - sfree(delpos234(auth->xdmseen, 0)); - } + return "XDM-AUTHORIZATION-1 time stamp was too far out"; + seen = snew(struct XDMSeen); + seen->time = t; + memcpy(seen->clientid, data+8, 6); + assert(auth->xdmseen != NULL); + ret = add234(auth->xdmseen, seen); + if (ret != seen) { + sfree(seen); + return "XDM-AUTHORIZATION-1 data replayed"; + } + /* While we're here, purge entries too old to be replayed. */ + for (;;) { + seen = index234(auth->xdmseen, 0); + assert(seen != NULL); + if (t - seen->time <= XDM_MAXSKEW) + break; + sfree(delpos234(auth->xdmseen, 0)); + } } /* implement other protocols here if ever required */ @@ -468,7 +468,7 @@ void BinarySink_put_stringpl_xauth(BinarySink *bs, ptrlen pl) BinarySink_put_stringpl_xauth(BinarySink_UPCAST(bs),ptrlen) void x11_get_auth_from_authfile(struct X11Display *disp, - const char *authfilename) + const char *authfilename) { FILE *authfp; char *buf; @@ -515,7 +515,7 @@ void x11_get_auth_from_authfile(struct X11Display *disp, authfp = fopen(authfilename, "rb"); if (!authfp) - return; + return; ourhostname = get_hostname(); @@ -555,94 +555,94 @@ void x11_get_auth_from_authfile(struct X11Display *disp, if (get_err(src)) break; - /* - * Now we have a full X authority record in memory. See - * whether it matches the display we're trying to - * authenticate to. - * - * The details we've just read should be interpreted as - * follows: - * - * - 'family' is the network address family used to - * connect to the display. 0 means IPv4; 6 means IPv6; - * 256 means Unix-domain sockets. - * - * - 'addr' is the network address itself. For IPv4 and - * IPv6, this is a string of binary data of the - * appropriate length (respectively 4 and 16 bytes) - * representing the address in big-endian format, e.g. - * 7F 00 00 01 means IPv4 localhost. For Unix-domain - * sockets, this is the host name of the machine on - * which the Unix-domain display resides (so that an - * .Xauthority file on a shared file system can contain - * authority entries for Unix-domain displays on - * several machines without them clashing). - * - * - 'displaynum' is the display number. An empty display - * number is a wildcard for any display number. - * - * - 'protoname' is the authorisation protocol, encoded as - * its canonical string name (i.e. "MIT-MAGIC-COOKIE-1", - * "XDM-AUTHORIZATION-1" or something we don't recognise). - * - * - 'data' is the actual authorisation data, stored in - * binary form. - */ + /* + * Now we have a full X authority record in memory. See + * whether it matches the display we're trying to + * authenticate to. + * + * The details we've just read should be interpreted as + * follows: + * + * - 'family' is the network address family used to + * connect to the display. 0 means IPv4; 6 means IPv6; + * 256 means Unix-domain sockets. + * + * - 'addr' is the network address itself. For IPv4 and + * IPv6, this is a string of binary data of the + * appropriate length (respectively 4 and 16 bytes) + * representing the address in big-endian format, e.g. + * 7F 00 00 01 means IPv4 localhost. For Unix-domain + * sockets, this is the host name of the machine on + * which the Unix-domain display resides (so that an + * .Xauthority file on a shared file system can contain + * authority entries for Unix-domain displays on + * several machines without them clashing). + * + * - 'displaynum' is the display number. An empty display + * number is a wildcard for any display number. + * + * - 'protoname' is the authorisation protocol, encoded as + * its canonical string name (i.e. "MIT-MAGIC-COOKIE-1", + * "XDM-AUTHORIZATION-1" or something we don't recognise). + * + * - 'data' is the actual authorisation data, stored in + * binary form. + */ - if (disp->displaynum < 0 || - (displaynum >= 0 && disp->displaynum != displaynum)) - continue; /* not the one */ + if (disp->displaynum < 0 || + (displaynum >= 0 && disp->displaynum != displaynum)) + continue; /* not the one */ - for (protocol = 1; protocol < lenof(x11_authnames); protocol++) - if (ptrlen_eq_string(protoname, x11_authnames[protocol])) - break; - if (protocol == lenof(x11_authnames)) - continue; /* don't recognise this protocol, look for another */ + for (protocol = 1; protocol < lenof(x11_authnames); protocol++) + if (ptrlen_eq_string(protoname, x11_authnames[protocol])) + break; + if (protocol == lenof(x11_authnames)) + continue; /* don't recognise this protocol, look for another */ - switch (family) { - case 0: /* IPv4 */ - if (!disp->unixdomain && - sk_addrtype(disp->addr) == ADDRTYPE_IPV4) { - char buf[4]; - sk_addrcopy(disp->addr, buf); - if (addr.len == 4 && !memcmp(addr.ptr, buf, 4)) { - match = true; - /* If this is a "localhost" entry, note it down - * but carry on looking for a Unix-domain entry. */ - ideal_match = !localhost; - } - } - break; - case 6: /* IPv6 */ - if (!disp->unixdomain && - sk_addrtype(disp->addr) == ADDRTYPE_IPV6) { - char buf[16]; - sk_addrcopy(disp->addr, buf); - if (addr.len == 16 && !memcmp(addr.ptr, buf, 16)) { - match = true; - ideal_match = !localhost; - } - } - break; - case 256: /* Unix-domain / localhost */ - if ((disp->unixdomain || localhost) + switch (family) { + case 0: /* IPv4 */ + if (!disp->unixdomain && + sk_addrtype(disp->addr) == ADDRTYPE_IPV4) { + char buf[4]; + sk_addrcopy(disp->addr, buf); + if (addr.len == 4 && !memcmp(addr.ptr, buf, 4)) { + match = true; + /* If this is a "localhost" entry, note it down + * but carry on looking for a Unix-domain entry. */ + ideal_match = !localhost; + } + } + break; + case 6: /* IPv6 */ + if (!disp->unixdomain && + sk_addrtype(disp->addr) == ADDRTYPE_IPV6) { + char buf[16]; + sk_addrcopy(disp->addr, buf); + if (addr.len == 16 && !memcmp(addr.ptr, buf, 16)) { + match = true; + ideal_match = !localhost; + } + } + break; + case 256: /* Unix-domain / localhost */ + if ((disp->unixdomain || localhost) && ourhostname && ptrlen_eq_string(addr, ourhostname)) { - /* A matching Unix-domain socket is always the best - * match. */ - match = true; + /* A matching Unix-domain socket is always the best + * match. */ + match = true; ideal_match = true; } - break; - } + break; + } - if (match) { - /* Current best guess -- may be overridden if !ideal_match */ - disp->localauthproto = protocol; - sfree(disp->localauthdata); /* free previous guess, if any */ - disp->localauthdata = snewn(data.len, unsigned char); - memcpy(disp->localauthdata, data.ptr, data.len); - disp->localauthdatalen = data.len; - } + if (match) { + /* Current best guess -- may be overridden if !ideal_match */ + disp->localauthproto = protocol; + sfree(disp->localauthdata); /* free previous guess, if any */ + disp->localauthdata = snewn(data.len, unsigned char); + memcpy(disp->localauthdata, data.ptr, data.len); + disp->localauthdatalen = data.len; + } } fclose(authfp); @@ -685,7 +685,7 @@ void x11_format_auth_for_authfile( } static void x11_log(Plug *p, int type, SockAddr *addr, int port, - const char *error_msg, int error_code) + const char *error_msg, int error_code) { /* We have no interface to the logging module here, so we drop these. */ } @@ -694,7 +694,7 @@ static void x11_send_init_error(struct X11Connection *conn, const char *err_message); static void x11_closing(Plug *plug, const char *error_msg, int error_code, - bool calling_back) + bool calling_back) { struct X11Connection *xconn = container_of( plug, struct X11Connection, plug); @@ -754,10 +754,10 @@ int x11_get_screen_number(char *display) n = host_strcspn(display, ":"); if (!display[n]) - return 0; + return 0; n = strcspn(display, "."); if (!display[n]) - return 0; + return 0; return atoi(display + n + 1); } @@ -853,8 +853,8 @@ static void x11_chan_free(Channel *chan) X11Connection *xconn = container_of(chan, X11Connection, chan); if (xconn->auth_protocol) { - sfree(xconn->auth_protocol); - sfree(xconn->auth_data); + sfree(xconn->auth_protocol); + sfree(xconn->auth_data); } if (xconn->s) @@ -886,9 +886,9 @@ static void x11_send_init_error(struct X11Connection *xconn, msglen = strlen(full_message); reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */ msgsize = (msglen + 3) & ~3; - reply[0] = 0; /* failure */ - reply[1] = msglen; /* length of reason string */ - memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */ + reply[0] = 0; /* failure */ + reply[1] = msglen; /* length of reason string */ + memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */ PUT_16BIT_X11(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */ memset(reply + 8, 0, msgsize); memcpy(reply + 8, full_message, msglen); @@ -930,9 +930,9 @@ static size_t x11_send( * Read the first packet. */ while (len > 0 && xconn->data_read < 12) - xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++); + xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++); if (xconn->data_read < 12) - return 0; + return 0; /* * If we have not allocated the auth_protocol and auth_data @@ -940,13 +940,13 @@ static size_t x11_send( */ if (!xconn->auth_protocol) { char endian = xconn->firstpkt[0]; - xconn->auth_plen = GET_16BIT_X11(endian, xconn->firstpkt + 6); - xconn->auth_dlen = GET_16BIT_X11(endian, xconn->firstpkt + 8); - xconn->auth_psize = (xconn->auth_plen + 3) & ~3; - xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3; - /* Leave room for a terminating zero, to make our lives easier. */ - xconn->auth_protocol = snewn(xconn->auth_psize + 1, char); - xconn->auth_data = snewn(xconn->auth_dsize, unsigned char); + xconn->auth_plen = GET_16BIT_X11(endian, xconn->firstpkt + 6); + xconn->auth_dlen = GET_16BIT_X11(endian, xconn->firstpkt + 8); + xconn->auth_psize = (xconn->auth_plen + 3) & ~3; + xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3; + /* Leave room for a terminating zero, to make our lives easier. */ + xconn->auth_protocol = snewn(xconn->auth_psize + 1, char); + xconn->auth_data = snewn(xconn->auth_dsize, unsigned char); } /* @@ -954,19 +954,19 @@ static size_t x11_send( */ while (len > 0 && xconn->data_read < 12 + xconn->auth_psize) - xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++); + xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++); while (len > 0 && xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize) - xconn->auth_data[xconn->data_read++ - 12 - - xconn->auth_psize] = (unsigned char) (len--, *data++); + xconn->auth_data[xconn->data_read++ - 12 - + xconn->auth_psize] = (unsigned char) (len--, *data++); if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize) - return 0; + return 0; /* * If we haven't verified the authorisation, do so now. */ if (!xconn->verified) { - const char *err; + const char *err; struct X11FakeAuth *auth_matched = NULL; unsigned long peer_ip; int peer_port; @@ -984,7 +984,7 @@ static size_t x11_send( assert(!xconn->s); - xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */ + xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */ peer_ip = 0; /* placate optimiser */ if (x11_parse_ip(xconn->peer_addr, &peer_ip)) @@ -992,10 +992,10 @@ static size_t x11_send( else peer_port = -1; /* signal no peer address data available */ - err = x11_verify(peer_ip, peer_port, - xconn->authtree, xconn->auth_protocol, - xconn->auth_data, xconn->auth_dlen, &auth_matched); - if (err) { + err = x11_verify(peer_ip, peer_port, + xconn->authtree, xconn->auth_protocol, + xconn->auth_data, xconn->auth_dlen, &auth_matched); + if (err) { x11_send_init_error(xconn, err); return 0; } @@ -1024,7 +1024,7 @@ static size_t x11_send( sshfwd_window_override_removed(xconn->c); xconn->disp = auth_matched->disp; xconn->s = new_connection(sk_addr_dup(xconn->disp->addr), - xconn->disp->realhost, xconn->disp->port, + xconn->disp->realhost, xconn->disp->port, false, true, false, false, &xconn->plug, sshfwd_get_conf(xconn->c)); if ((err = sk_socket_error(xconn->s)) != NULL) { @@ -1038,7 +1038,7 @@ static size_t x11_send( /* * Write a new connection header containing our replacement * auth data. - */ + */ socketdatalen = 0; /* placate compiler warning */ socketdata = sk_getxdmdata(xconn->s, &socketdatalen); if (socketdata && socketdatalen==6) { @@ -1057,7 +1057,7 @@ static size_t x11_send( xconn->disp->localauthdatalen, new_peer_addr, new_peer_port, &greeting_len); - + sk_write(xconn->s, greeting, greeting_len); smemclr(greeting, greeting_len); @@ -1066,7 +1066,7 @@ static size_t x11_send( /* * Now we're done. */ - xconn->verified = true; + xconn->verified = true; } /*