1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-01-09 17:38:00 +00:00
putty-source/windows/dialog.c

1166 lines
36 KiB
C
Raw Normal View History

/*
* windlg.c - dialogs for PuTTY(tel), including the configuration dialog.
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
#include <ctype.h>
#include <time.h>
#include "putty.h"
#include "ssh.h"
#include "putty-rc.h"
#include "win-gui-seat.h"
#include "storage.h"
#include "dialog.h"
#include "licence.h"
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#ifdef MSVC4
#define TVINSERTSTRUCT TV_INSERTSTRUCT
#define TVITEM TV_ITEM
#define ICON_BIG 1
#endif
/*
* These are the various bits of data required to handle the
* portable-dialog stuff in the config box. Having them at file
* scope in here isn't too bad a place to put them; if we were ever
* to need more than one config box per process we could always
* shift them to a per-config-box structure stored in GWL_USERDATA.
*/
static struct controlbox *ctrlbox;
/*
* ctrls_base holds the OK and Cancel buttons: the controls which
* are present in all dialog panels. ctrls_panel holds the ones
* which change from panel to panel.
*/
static struct winctrls ctrls_base, ctrls_panel;
static struct dlgparam dp;
#define LOGEVENT_INITIAL_MAX 128
#define LOGEVENT_CIRCULAR_MAX 128
static char *events_initial[LOGEVENT_INITIAL_MAX];
static char *events_circular[LOGEVENT_CIRCULAR_MAX];
static int ninitial = 0, ncircular = 0, circular_first = 0;
#define PRINTER_DISABLED_STRING "None (printing disabled)"
void force_normal(HWND hwnd)
{
Convert a lot of 'int' variables to 'bool'. My normal habit these days, in new code, is to treat int and bool as _almost_ completely separate types. I'm still willing to use C's implicit test for zero on an integer (e.g. 'if (!blob.len)' is fine, no need to spell it out as blob.len != 0), but generally, if a variable is going to be conceptually a boolean, I like to declare it bool and assign to it using 'true' or 'false' rather than 0 or 1. PuTTY is an exception, because it predates the C99 bool, and I've stuck to its existing coding style even when adding new code to it. But it's been annoying me more and more, so now that I've decided C99 bool is an acceptable thing to require from our toolchain in the first place, here's a quite thorough trawl through the source doing 'boolification'. Many variables and function parameters are now typed as bool rather than int; many assignments of 0 or 1 to those variables are now spelled 'true' or 'false'. I managed this thorough conversion with the help of a custom clang plugin that I wrote to trawl the AST and apply heuristics to point out where things might want changing. So I've even managed to do a decent job on parts of the code I haven't looked at in years! To make the plugin's work easier, I pushed platform front ends generally in the direction of using standard 'bool' in preference to platform-specific boolean types like Windows BOOL or GTK's gboolean; I've left the platform booleans in places they _have_ to be for the platform APIs to work right, but variables only used by my own code have been converted wherever I found them. In a few places there are int values that look very like booleans in _most_ of the places they're used, but have a rarely-used third value, or a distinction between different nonzero values that most users don't care about. In these cases, I've _removed_ uses of 'true' and 'false' for the return values, to emphasise that there's something more subtle going on than a simple boolean answer: - the 'multisel' field in dialog.h's list box structure, for which the GTK front end in particular recognises a difference between 1 and 2 but nearly everything else treats as boolean - the 'urgent' parameter to plug_receive, where 1 vs 2 tells you something about the specific location of the urgent pointer, but most clients only care about 0 vs 'something nonzero' - the return value of wc_match, where -1 indicates a syntax error in the wildcard. - the return values from SSH-1 RSA-key loading functions, which use -1 for 'wrong passphrase' and 0 for all other failures (so any caller which already knows it's not loading an _encrypted private_ key can treat them as boolean) - term->esc_query, and the 'query' parameter in toggle_mode in terminal.c, which _usually_ hold 0 for ESC[123h or 1 for ESC[?123h, but can also hold -1 for some other intervening character that we don't support. In a few places there's an integer that I haven't turned into a bool even though it really _can_ only take values 0 or 1 (and, as above, tried to make the call sites consistent in not calling those values true and false), on the grounds that I thought it would make it more confusing to imply that the 0 value was in some sense 'negative' or bad and the 1 positive or good: - the return value of plug_accepting uses the POSIXish convention of 0=success and nonzero=error; I think if I made it bool then I'd also want to reverse its sense, and that's a job for a separate piece of work. - the 'screen' parameter to lineptr() in terminal.c, where 0 and 1 represent the default and alternate screens. There's no obvious reason why one of those should be considered 'true' or 'positive' or 'success' - they're just indices - so I've left it as int. ssh_scp_recv had particularly confusing semantics for its previous int return value: its call sites used '<= 0' to check for error, but it never actually returned a negative number, just 0 or 1. Now the function and its call sites agree that it's a bool. In a couple of places I've renamed variables called 'ret', because I don't like that name any more - it's unclear whether it means the return value (in preparation) for the _containing_ function or the return value received from a subroutine call, and occasionally I've accidentally used the same variable for both and introduced a bug. So where one of those got in my way, I've renamed it to 'toret' or 'retd' (the latter short for 'returned') in line with my usual modern practice, but I haven't done a thorough job of finding all of them. Finally, one amusing side effect of doing this is that I've had to separate quite a few chained assignments. It used to be perfectly fine to write 'a = b = c = TRUE' when a,b,c were int and TRUE was just a the 'true' defined by stdbool.h, that idiom provokes a warning from gcc: 'suggest parentheses around assignment used as truth value'!
2018-11-02 19:23:19 +00:00
static bool recurse = false;
WINDOWPLACEMENT wp;
if (recurse)
return;
Convert a lot of 'int' variables to 'bool'. My normal habit these days, in new code, is to treat int and bool as _almost_ completely separate types. I'm still willing to use C's implicit test for zero on an integer (e.g. 'if (!blob.len)' is fine, no need to spell it out as blob.len != 0), but generally, if a variable is going to be conceptually a boolean, I like to declare it bool and assign to it using 'true' or 'false' rather than 0 or 1. PuTTY is an exception, because it predates the C99 bool, and I've stuck to its existing coding style even when adding new code to it. But it's been annoying me more and more, so now that I've decided C99 bool is an acceptable thing to require from our toolchain in the first place, here's a quite thorough trawl through the source doing 'boolification'. Many variables and function parameters are now typed as bool rather than int; many assignments of 0 or 1 to those variables are now spelled 'true' or 'false'. I managed this thorough conversion with the help of a custom clang plugin that I wrote to trawl the AST and apply heuristics to point out where things might want changing. So I've even managed to do a decent job on parts of the code I haven't looked at in years! To make the plugin's work easier, I pushed platform front ends generally in the direction of using standard 'bool' in preference to platform-specific boolean types like Windows BOOL or GTK's gboolean; I've left the platform booleans in places they _have_ to be for the platform APIs to work right, but variables only used by my own code have been converted wherever I found them. In a few places there are int values that look very like booleans in _most_ of the places they're used, but have a rarely-used third value, or a distinction between different nonzero values that most users don't care about. In these cases, I've _removed_ uses of 'true' and 'false' for the return values, to emphasise that there's something more subtle going on than a simple boolean answer: - the 'multisel' field in dialog.h's list box structure, for which the GTK front end in particular recognises a difference between 1 and 2 but nearly everything else treats as boolean - the 'urgent' parameter to plug_receive, where 1 vs 2 tells you something about the specific location of the urgent pointer, but most clients only care about 0 vs 'something nonzero' - the return value of wc_match, where -1 indicates a syntax error in the wildcard. - the return values from SSH-1 RSA-key loading functions, which use -1 for 'wrong passphrase' and 0 for all other failures (so any caller which already knows it's not loading an _encrypted private_ key can treat them as boolean) - term->esc_query, and the 'query' parameter in toggle_mode in terminal.c, which _usually_ hold 0 for ESC[123h or 1 for ESC[?123h, but can also hold -1 for some other intervening character that we don't support. In a few places there's an integer that I haven't turned into a bool even though it really _can_ only take values 0 or 1 (and, as above, tried to make the call sites consistent in not calling those values true and false), on the grounds that I thought it would make it more confusing to imply that the 0 value was in some sense 'negative' or bad and the 1 positive or good: - the return value of plug_accepting uses the POSIXish convention of 0=success and nonzero=error; I think if I made it bool then I'd also want to reverse its sense, and that's a job for a separate piece of work. - the 'screen' parameter to lineptr() in terminal.c, where 0 and 1 represent the default and alternate screens. There's no obvious reason why one of those should be considered 'true' or 'positive' or 'success' - they're just indices - so I've left it as int. ssh_scp_recv had particularly confusing semantics for its previous int return value: its call sites used '<= 0' to check for error, but it never actually returned a negative number, just 0 or 1. Now the function and its call sites agree that it's a bool. In a couple of places I've renamed variables called 'ret', because I don't like that name any more - it's unclear whether it means the return value (in preparation) for the _containing_ function or the return value received from a subroutine call, and occasionally I've accidentally used the same variable for both and introduced a bug. So where one of those got in my way, I've renamed it to 'toret' or 'retd' (the latter short for 'returned') in line with my usual modern practice, but I haven't done a thorough job of finding all of them. Finally, one amusing side effect of doing this is that I've had to separate quite a few chained assignments. It used to be perfectly fine to write 'a = b = c = TRUE' when a,b,c were int and TRUE was just a the 'true' defined by stdbool.h, that idiom provokes a warning from gcc: 'suggest parentheses around assignment used as truth value'!
2018-11-02 19:23:19 +00:00
recurse = true;
wp.length = sizeof(wp);
if (GetWindowPlacement(hwnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED) {
wp.showCmd = SW_SHOWNORMAL;
SetWindowPlacement(hwnd, &wp);
}
Convert a lot of 'int' variables to 'bool'. My normal habit these days, in new code, is to treat int and bool as _almost_ completely separate types. I'm still willing to use C's implicit test for zero on an integer (e.g. 'if (!blob.len)' is fine, no need to spell it out as blob.len != 0), but generally, if a variable is going to be conceptually a boolean, I like to declare it bool and assign to it using 'true' or 'false' rather than 0 or 1. PuTTY is an exception, because it predates the C99 bool, and I've stuck to its existing coding style even when adding new code to it. But it's been annoying me more and more, so now that I've decided C99 bool is an acceptable thing to require from our toolchain in the first place, here's a quite thorough trawl through the source doing 'boolification'. Many variables and function parameters are now typed as bool rather than int; many assignments of 0 or 1 to those variables are now spelled 'true' or 'false'. I managed this thorough conversion with the help of a custom clang plugin that I wrote to trawl the AST and apply heuristics to point out where things might want changing. So I've even managed to do a decent job on parts of the code I haven't looked at in years! To make the plugin's work easier, I pushed platform front ends generally in the direction of using standard 'bool' in preference to platform-specific boolean types like Windows BOOL or GTK's gboolean; I've left the platform booleans in places they _have_ to be for the platform APIs to work right, but variables only used by my own code have been converted wherever I found them. In a few places there are int values that look very like booleans in _most_ of the places they're used, but have a rarely-used third value, or a distinction between different nonzero values that most users don't care about. In these cases, I've _removed_ uses of 'true' and 'false' for the return values, to emphasise that there's something more subtle going on than a simple boolean answer: - the 'multisel' field in dialog.h's list box structure, for which the GTK front end in particular recognises a difference between 1 and 2 but nearly everything else treats as boolean - the 'urgent' parameter to plug_receive, where 1 vs 2 tells you something about the specific location of the urgent pointer, but most clients only care about 0 vs 'something nonzero' - the return value of wc_match, where -1 indicates a syntax error in the wildcard. - the return values from SSH-1 RSA-key loading functions, which use -1 for 'wrong passphrase' and 0 for all other failures (so any caller which already knows it's not loading an _encrypted private_ key can treat them as boolean) - term->esc_query, and the 'query' parameter in toggle_mode in terminal.c, which _usually_ hold 0 for ESC[123h or 1 for ESC[?123h, but can also hold -1 for some other intervening character that we don't support. In a few places there's an integer that I haven't turned into a bool even though it really _can_ only take values 0 or 1 (and, as above, tried to make the call sites consistent in not calling those values true and false), on the grounds that I thought it would make it more confusing to imply that the 0 value was in some sense 'negative' or bad and the 1 positive or good: - the return value of plug_accepting uses the POSIXish convention of 0=success and nonzero=error; I think if I made it bool then I'd also want to reverse its sense, and that's a job for a separate piece of work. - the 'screen' parameter to lineptr() in terminal.c, where 0 and 1 represent the default and alternate screens. There's no obvious reason why one of those should be considered 'true' or 'positive' or 'success' - they're just indices - so I've left it as int. ssh_scp_recv had particularly confusing semantics for its previous int return value: its call sites used '<= 0' to check for error, but it never actually returned a negative number, just 0 or 1. Now the function and its call sites agree that it's a bool. In a couple of places I've renamed variables called 'ret', because I don't like that name any more - it's unclear whether it means the return value (in preparation) for the _containing_ function or the return value received from a subroutine call, and occasionally I've accidentally used the same variable for both and introduced a bug. So where one of those got in my way, I've renamed it to 'toret' or 'retd' (the latter short for 'returned') in line with my usual modern practice, but I haven't done a thorough job of finding all of them. Finally, one amusing side effect of doing this is that I've had to separate quite a few chained assignments. It used to be perfectly fine to write 'a = b = c = TRUE' when a,b,c were int and TRUE was just a the 'true' defined by stdbool.h, that idiom provokes a warning from gcc: 'suggest parentheses around assignment used as truth value'!
2018-11-02 19:23:19 +00:00
recurse = false;
}
static char *getevent(int i)
{
if (i < ninitial)
return events_initial[i];
if ((i -= ninitial) < ncircular)
return events_circular[(circular_first + i) % LOGEVENT_CIRCULAR_MAX];
return NULL;
}
static HWND logbox;
HWND event_log_window(void) { return logbox; }
static INT_PTR CALLBACK LogProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
int i;
switch (msg) {
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
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;
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
}
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;
}
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;
}
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);
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;
}
return 0;
}
static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch (msg) {
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
case WM_INITDIALOG: {
char *str = dupprintf("%s Licence", appname);
SetWindowText(hwnd, str);
sfree(str);
SetDlgItemText(hwnd, IDA_TEXT, LICENCE_TEXT("\r\n\r\n"));
return 1;
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
EndDialog(hwnd, 1);
return 0;
}
return 0;
case WM_CLOSE:
EndDialog(hwnd, 1);
return 0;
}
return 0;
}
static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
char *str;
switch (msg) {
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
case WM_INITDIALOG: {
str = dupprintf("About %s", appname);
SetWindowText(hwnd, str);
sfree(str);
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
char *buildinfo_text = buildinfo("\r\n");
char *text = dupprintf
("%s\r\n\r\n%s\r\n\r\n%s\r\n\r\n%s",
appname, ver, buildinfo_text,
"\251 " SHORT_COPYRIGHT_DETAILS ". All rights reserved.");
sfree(buildinfo_text);
SetDlgItemText(hwnd, IDA_TEXT, text);
MakeDlgItemBorderless(hwnd, IDA_TEXT);
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
sfree(text);
return 1;
Formatting change to braces around one case of a switch. Sometimes, within a switch statement, you want to declare local variables specific to the handler for one particular case. Until now I've mostly been writing this in the form switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; } break; } which is ugly because the two pieces of essentially similar code appear at different indent levels, and also inconvenient because you have less horizontal space available to write the complicated case handler in - particuarly undesirable because _complicated_ case handlers are the ones most likely to need all the space they can get! After encountering a rather nicer idiom in the LLVM source code, and after a bit of hackery this morning figuring out how to persuade Emacs's auto-indent to do what I wanted with it, I've decided to move to an idiom in which the open brace comes right after the case statement, and the code within it is indented the same as it would have been without the brace. Then the whole case handler (including the break) lives inside those braces, and you get something that looks more like this: switch (discriminant) { case SIMPLE: do stuff; break; case COMPLICATED: { declare variables; do stuff; break; } } This commit is a big-bang change that reformats all the complicated case handlers I could find into the new layout. This is particularly nice in the Pageant main function, in which almost _every_ case handler had a bundle of variables and was long and complicated. (In fact that's what motivated me to get round to this.) Some of the innermost parts of the terminal escape-sequence handling are also breathing a bit easier now the horizontal pressure on them is relieved. (Also, in a few cases, I was able to remove the extra braces completely, because the only variable local to the case handler was a loop variable which our new C99 policy allows me to move into the initialiser clause of its for statement.) Viewed with whitespace ignored, this is not too disruptive a change. Downstream patches that conflict with it may need to be reapplied using --ignore-whitespace or similar.
2020-02-16 07:49:52 +00:00
}
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;
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;
}
return 0;
}
static int SaneDialogBox(HINSTANCE hinst,
LPCTSTR tmpl,
HWND hwndparent,
DLGPROC lpDialogFunc)
{
WNDCLASS wc;
HWND hwnd;
MSG msg;
int flags;
int ret;
int gm;
wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW;
wc.lpfnWndProc = DefDlgProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = DLGWINDOWEXTRA + 2*sizeof(LONG_PTR);
wc.hInstance = hinst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) (COLOR_BACKGROUND +1);
wc.lpszMenuName = NULL;
wc.lpszClassName = "PuTTYConfigBox";
RegisterClass(&wc);
hwnd = CreateDialog(hinst, tmpl, hwndparent, lpDialogFunc);
SetWindowLongPtr(hwnd, BOXFLAGS, 0); /* flags */
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;
}
if (gm == 0)
PostQuitMessage(msg.wParam); /* We got a WM_QUIT, pass it on */
ret=GetWindowLongPtr(hwnd, BOXRESULT);
DestroyWindow(hwnd);
return ret;
}
static void SaneEndDialog(HWND hwnd, int ret)
{
SetWindowLongPtr(hwnd, BOXRESULT, ret);
SetWindowLongPtr(hwnd, BOXFLAGS, DF_END);
}
/*
* Null dialog procedure.
*/
static INT_PTR CALLBACK NullDlgProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
return 0;
}
enum {
IDCX_ABOUT = IDC_ABOUT,
IDCX_TVSTATIC,
IDCX_TREEVIEW,
IDCX_STDBASE,
IDCX_PANELBASE = IDCX_STDBASE + 32
};
struct treeview_faff {
HWND treeview;
HTREEITEM lastat[4];
};
static HTREEITEM treeview_insert(struct treeview_faff *faff,
int level, char *text, char *path)
{
TVINSERTSTRUCT ins;
int i;
HTREEITEM newitem;
ins.hParent = (level > 0 ? faff->lastat[level - 1] : TVI_ROOT);
ins.hInsertAfter = faff->lastat[level];
#if _WIN32_IE >= 0x0400 && defined NONAMELESSUNION
#define INSITEM DUMMYUNIONNAME.item
#else
#define INSITEM item
#endif
ins.INSITEM.mask = TVIF_TEXT | TVIF_PARAM;
ins.INSITEM.pszText = text;
ins.INSITEM.cchTextMax = strlen(text)+1;
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));
faff->lastat[level] = newitem;
for (i = level + 1; i < 4; i++)
faff->lastat[i] = NULL;
return newitem;
}
/*
* Create the panelfuls of controls in the configuration box.
*/
static void create_controls(HWND hwnd, char *path)
{
struct ctlpos cp;
int index;
int base_id;
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;
} else {
/*
* 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);
}
}
/*
* This function is the configuration box.
* (Being a dialog procedure, in general it returns 0 if the default
* dialog processing should be performed, and 1 if it should not.)
*/
static INT_PTR CALLBACK GenericMainDlgProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
HWND hw, treeview;
struct treeview_faff tvfaff;
int ret;
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);
if (has_help())
SetWindowLongPtr(hwnd, GWL_EXSTYLE,
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;
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;
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));
}
/*
* Set up the tree view contents.
*/
{
HTREEITEM hfirst = NULL;
int i;
char *path = NULL;
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
char *firstpath = NULL;
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 */
/*
* 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++;
item = treeview_insert(&tvfaff, j, c, s->pathname);
if (!hfirst) {
hfirst = item;
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
firstpath = s->pathname;
}
path = s->pathname;
}
/*
* Put the treeview selection on to the first panel in the
* ctrlbox.
*/
TreeView_SelectItem(treeview, hfirst);
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
/*
* And create the actual control set for that panel, to
* match the initial treeview selection.
*/
assert(firstpath); /* config.c must have given us _something_ */
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
create_controls(hwnd, firstpath);
dlg_refresh(NULL, &dp); /* and set up control values */
}
/*
* 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;
}
}
}
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
/*
* Now we've finished creating our initial set of controls,
* it's safe to actually show the window without risking setup
* flicker.
*/
ShowWindow(hwnd, SW_SHOWNORMAL);
/*
* Set the flag that activates a couple of the other message
* handlers below, which were disabled until now to avoid
* spurious firing during the above setup procedure.
*/
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;
case WM_NOTIFY:
if (LOWORD(wParam) == IDCX_TREEVIEW &&
((LPNMHDR) lParam)->code == TVN_SELCHANGED) {
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
/*
* Selection-change events on the treeview cause us to do
* a flurry of control deletion and creation - but only
* after WM_INITDIALOG has finished. The initial
* selection-change event(s) during treeview setup are
* ignored.
*/
HTREEITEM i;
TVITEM item;
char buffer[64];
Fix accidental dependence on Windows API quirk in config box. Our config boxes are constructed using the CreateDialog() API function, rather than the modal DialogBox(). CreateDialog() is not that different from CreateWindow(), so windows created with it don't appear on the screen automatically; MSDN says that they must be shown via ShowWindow(), just like non-dialog windows have to be. But we weren't doing that at any point! So how was our config box ever getting displayed at all? Apparently by sheer chance, it turns out. The handler for a selection change in the tree view, which has to delete a whole panel of controls and creates a different set, surrounds that procedure with some WM_SETREDRAW calls and an InvalidateRect(), to prevent flicker while lots of changes were being made. And the creation of the _first_ panelful of controls, at dialog box setup, was done by simply selecting an item in the treeview and expecting that handler to be recursively called. And it appears that calling WM_SETREDRAW(TRUE) and then InvalidateRect was undocumentedly having an effect equivalent to the ShowWindow() we should have called, so that we never noticed the latter was missing. But a recent Vista update (all reports implicate KB3057839) has caused that not to work any more: on an updated Vista machine, in some desktop configurations, it seems that any attempt to fiddle with WM_SETREDRAW during dialog setup can leave the dialog box in a really unhelpful invisible state - the window is _physically there_ (you can see its taskbar entry, and the mouse pointer changes as you move over where its edit boxes are), but 100% transparent. So now we're doing something a bit more sensible. The first panelful of controls is created directly by the WM_INITDIALOG handler, rather than recursing into code that wasn't really designed to run at setup time. To be on the safe side, that handler for treeview selection change is also disabled until the WM_INITDIALOG handler has finished (like we already did with the WM_COMMAND handler), so that we can be sure of not accidentally messing about with WM_SETREDRAW at all during setup. And at the end of setup, we show the window in the sensible way, by a docs-approved call to ShowWindow(). This appears (on the one machine I've so far tested it on) to fix the Vista invisible-window issue, and also it should be more API-compliant and hence safer in future.
2015-06-18 06:05:19 +00:00
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);
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;
case WM_HELP:
if (!winctrl_context_help(&dp, hwnd,
((LPHELPINFO)lParam)->iCtrlId))
MessageBeep(0);
break;
case WM_CLOSE:
quit_help(hwnd);
SaneEndDialog(hwnd, 0);
return 0;
/* Grrr Explorer will maximize Dialogs! */
case WM_SIZE:
if (wParam == SIZE_MAXIMIZED)
force_normal(hwnd);
return 0;
}
return 0;
}
void modal_about_box(HWND hwnd)
{
EnableWindow(hwnd, 0);
DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, AboutProc);
EnableWindow(hwnd, 1);
SetActiveWindow(hwnd);
}
void show_help(HWND hwnd)
{
launch_help(hwnd, NULL);
}
void defuse_showwindow(void)
{
/*
* Work around the fact that the app's first call to ShowWindow
* will ignore the default in favour of the shell-provided
* setting.
*/
{
HWND hwnd;
hwnd = CreateDialog(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX),
NULL, NullDlgProc);
ShowWindow(hwnd, SW_HIDE);
SetActiveWindow(hwnd);
DestroyWindow(hwnd);
}
}
bool do_config(Conf *conf)
{
Convert a lot of 'int' variables to 'bool'. My normal habit these days, in new code, is to treat int and bool as _almost_ completely separate types. I'm still willing to use C's implicit test for zero on an integer (e.g. 'if (!blob.len)' is fine, no need to spell it out as blob.len != 0), but generally, if a variable is going to be conceptually a boolean, I like to declare it bool and assign to it using 'true' or 'false' rather than 0 or 1. PuTTY is an exception, because it predates the C99 bool, and I've stuck to its existing coding style even when adding new code to it. But it's been annoying me more and more, so now that I've decided C99 bool is an acceptable thing to require from our toolchain in the first place, here's a quite thorough trawl through the source doing 'boolification'. Many variables and function parameters are now typed as bool rather than int; many assignments of 0 or 1 to those variables are now spelled 'true' or 'false'. I managed this thorough conversion with the help of a custom clang plugin that I wrote to trawl the AST and apply heuristics to point out where things might want changing. So I've even managed to do a decent job on parts of the code I haven't looked at in years! To make the plugin's work easier, I pushed platform front ends generally in the direction of using standard 'bool' in preference to platform-specific boolean types like Windows BOOL or GTK's gboolean; I've left the platform booleans in places they _have_ to be for the platform APIs to work right, but variables only used by my own code have been converted wherever I found them. In a few places there are int values that look very like booleans in _most_ of the places they're used, but have a rarely-used third value, or a distinction between different nonzero values that most users don't care about. In these cases, I've _removed_ uses of 'true' and 'false' for the return values, to emphasise that there's something more subtle going on than a simple boolean answer: - the 'multisel' field in dialog.h's list box structure, for which the GTK front end in particular recognises a difference between 1 and 2 but nearly everything else treats as boolean - the 'urgent' parameter to plug_receive, where 1 vs 2 tells you something about the specific location of the urgent pointer, but most clients only care about 0 vs 'something nonzero' - the return value of wc_match, where -1 indicates a syntax error in the wildcard. - the return values from SSH-1 RSA-key loading functions, which use -1 for 'wrong passphrase' and 0 for all other failures (so any caller which already knows it's not loading an _encrypted private_ key can treat them as boolean) - term->esc_query, and the 'query' parameter in toggle_mode in terminal.c, which _usually_ hold 0 for ESC[123h or 1 for ESC[?123h, but can also hold -1 for some other intervening character that we don't support. In a few places there's an integer that I haven't turned into a bool even though it really _can_ only take values 0 or 1 (and, as above, tried to make the call sites consistent in not calling those values true and false), on the grounds that I thought it would make it more confusing to imply that the 0 value was in some sense 'negative' or bad and the 1 positive or good: - the return value of plug_accepting uses the POSIXish convention of 0=success and nonzero=error; I think if I made it bool then I'd also want to reverse its sense, and that's a job for a separate piece of work. - the 'screen' parameter to lineptr() in terminal.c, where 0 and 1 represent the default and alternate screens. There's no obvious reason why one of those should be considered 'true' or 'positive' or 'success' - they're just indices - so I've left it as int. ssh_scp_recv had particularly confusing semantics for its previous int return value: its call sites used '<= 0' to check for error, but it never actually returned a negative number, just 0 or 1. Now the function and its call sites agree that it's a bool. In a couple of places I've renamed variables called 'ret', because I don't like that name any more - it's unclear whether it means the return value (in preparation) for the _containing_ function or the return value received from a subroutine call, and occasionally I've accidentally used the same variable for both and introduced a bug. So where one of those got in my way, I've renamed it to 'toret' or 'retd' (the latter short for 'returned') in line with my usual modern practice, but I haven't done a thorough job of finding all of them. Finally, one amusing side effect of doing this is that I've had to separate quite a few chained assignments. It used to be perfectly fine to write 'a = b = c = TRUE' when a,b,c were int and TRUE was just a the 'true' defined by stdbool.h, that idiom provokes a warning from gcc: 'suggest parentheses around assignment used as truth value'!
2018-11-02 19:23:19 +00:00
bool ret;
ctrlbox = ctrl_new_box();
setup_config_box(ctrlbox, false, 0, 0);
win_setup_config_box(ctrlbox, &dp.hwnd, has_help(), false, 0);
dp_init(&dp);
winctrl_init(&ctrls_base);
winctrl_init(&ctrls_panel);
dp_add_tree(&dp, &ctrls_base);
dp_add_tree(&dp, &ctrls_panel);
dp.wintitle = dupprintf("%s Configuration", appname);
dp.errtitle = dupprintf("%s Error", appname);
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
dp.data = conf;
dlg_auto_set_fixed_pitch_flag(&dp);
dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */
ret =
SaneDialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL,
GenericMainDlgProc);
ctrl_free_box(ctrlbox);
winctrl_cleanup(&ctrls_panel);
winctrl_cleanup(&ctrls_base);
dp_cleanup(&dp);
return ret;
}
bool do_reconfig(HWND hwnd, Conf *conf, int protcfginfo)
{
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
Conf *backup_conf;
Convert a lot of 'int' variables to 'bool'. My normal habit these days, in new code, is to treat int and bool as _almost_ completely separate types. I'm still willing to use C's implicit test for zero on an integer (e.g. 'if (!blob.len)' is fine, no need to spell it out as blob.len != 0), but generally, if a variable is going to be conceptually a boolean, I like to declare it bool and assign to it using 'true' or 'false' rather than 0 or 1. PuTTY is an exception, because it predates the C99 bool, and I've stuck to its existing coding style even when adding new code to it. But it's been annoying me more and more, so now that I've decided C99 bool is an acceptable thing to require from our toolchain in the first place, here's a quite thorough trawl through the source doing 'boolification'. Many variables and function parameters are now typed as bool rather than int; many assignments of 0 or 1 to those variables are now spelled 'true' or 'false'. I managed this thorough conversion with the help of a custom clang plugin that I wrote to trawl the AST and apply heuristics to point out where things might want changing. So I've even managed to do a decent job on parts of the code I haven't looked at in years! To make the plugin's work easier, I pushed platform front ends generally in the direction of using standard 'bool' in preference to platform-specific boolean types like Windows BOOL or GTK's gboolean; I've left the platform booleans in places they _have_ to be for the platform APIs to work right, but variables only used by my own code have been converted wherever I found them. In a few places there are int values that look very like booleans in _most_ of the places they're used, but have a rarely-used third value, or a distinction between different nonzero values that most users don't care about. In these cases, I've _removed_ uses of 'true' and 'false' for the return values, to emphasise that there's something more subtle going on than a simple boolean answer: - the 'multisel' field in dialog.h's list box structure, for which the GTK front end in particular recognises a difference between 1 and 2 but nearly everything else treats as boolean - the 'urgent' parameter to plug_receive, where 1 vs 2 tells you something about the specific location of the urgent pointer, but most clients only care about 0 vs 'something nonzero' - the return value of wc_match, where -1 indicates a syntax error in the wildcard. - the return values from SSH-1 RSA-key loading functions, which use -1 for 'wrong passphrase' and 0 for all other failures (so any caller which already knows it's not loading an _encrypted private_ key can treat them as boolean) - term->esc_query, and the 'query' parameter in toggle_mode in terminal.c, which _usually_ hold 0 for ESC[123h or 1 for ESC[?123h, but can also hold -1 for some other intervening character that we don't support. In a few places there's an integer that I haven't turned into a bool even though it really _can_ only take values 0 or 1 (and, as above, tried to make the call sites consistent in not calling those values true and false), on the grounds that I thought it would make it more confusing to imply that the 0 value was in some sense 'negative' or bad and the 1 positive or good: - the return value of plug_accepting uses the POSIXish convention of 0=success and nonzero=error; I think if I made it bool then I'd also want to reverse its sense, and that's a job for a separate piece of work. - the 'screen' parameter to lineptr() in terminal.c, where 0 and 1 represent the default and alternate screens. There's no obvious reason why one of those should be considered 'true' or 'positive' or 'success' - they're just indices - so I've left it as int. ssh_scp_recv had particularly confusing semantics for its previous int return value: its call sites used '<= 0' to check for error, but it never actually returned a negative number, just 0 or 1. Now the function and its call sites agree that it's a bool. In a couple of places I've renamed variables called 'ret', because I don't like that name any more - it's unclear whether it means the return value (in preparation) for the _containing_ function or the return value received from a subroutine call, and occasionally I've accidentally used the same variable for both and introduced a bug. So where one of those got in my way, I've renamed it to 'toret' or 'retd' (the latter short for 'returned') in line with my usual modern practice, but I haven't done a thorough job of finding all of them. Finally, one amusing side effect of doing this is that I've had to separate quite a few chained assignments. It used to be perfectly fine to write 'a = b = c = TRUE' when a,b,c were int and TRUE was just a the 'true' defined by stdbool.h, that idiom provokes a warning from gcc: 'suggest parentheses around assignment used as truth value'!
2018-11-02 19:23:19 +00:00
bool ret;
int protocol;
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
backup_conf = conf_copy(conf);
ctrlbox = ctrl_new_box();
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
protocol = conf_get_int(conf, CONF_protocol);
setup_config_box(ctrlbox, true, protocol, protcfginfo);
win_setup_config_box(ctrlbox, &dp.hwnd, has_help(), true, protocol);
dp_init(&dp);
winctrl_init(&ctrls_base);
winctrl_init(&ctrls_panel);
dp_add_tree(&dp, &ctrls_base);
dp_add_tree(&dp, &ctrls_panel);
dp.wintitle = dupprintf("%s Reconfiguration", appname);
dp.errtitle = dupprintf("%s Error", appname);
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
dp.data = conf;
dlg_auto_set_fixed_pitch_flag(&dp);
dp.shortcuts['g'] = true; /* the treeview: `Cate&gory' */
ret = SaneDialogBox(hinst, MAKEINTRESOURCE(IDD_MAINBOX), NULL,
GenericMainDlgProc);
ctrl_free_box(ctrlbox);
winctrl_cleanup(&ctrls_base);
winctrl_cleanup(&ctrls_panel);
dp_cleanup(&dp);
if (!ret)
conf_copy_into(conf, backup_conf);
Post-release destabilisation! Completely remove the struct type 'Config' in putty.h, which stores all PuTTY's settings and includes an arbitrary length limit on every single one of those settings which is stored in string form. In place of it is 'Conf', an opaque data type everywhere outside the new file conf.c, which stores a list of (key, value) pairs in which every key contains an integer identifying a configuration setting, and for some of those integers the key also contains extra parts (so that, for instance, CONF_environmt is a string-to-string mapping). Everywhere that a Config was previously used, a Conf is now; everywhere there was a Config structure copy, conf_copy() is called; every lookup, adjustment, load and save operation on a Config has been rewritten; and there's a mechanism for serialising a Conf into a binary blob and back for use with Duplicate Session. User-visible effects of this change _should_ be minimal, though I don't doubt I've introduced one or two bugs here and there which will eventually be found. The _intended_ visible effects of this change are that all arbitrary limits on configuration strings and lists (e.g. limit on number of port forwardings) should now disappear; that list boxes in the configuration will now be displayed in a sorted order rather than the arbitrary order in which they were added to the list (since the underlying data structure is now a sorted tree234 rather than an ad-hoc comma-separated string); and one more specific change, which is that local and dynamic port forwardings on the same port number are now mutually exclusive in the configuration (putting 'D' in the key rather than the value was a mistake in the first place). One other reorganisation as a result of this is that I've moved all the dialog.c standard handlers (dlg_stdeditbox_handler and friends) out into config.c, because I can't really justify calling them generic any more. When they took a pointer to an arbitrary structure type and the offset of a field within that structure, they were independent of whether that structure was a Config or something completely different, but now they really do expect to talk to a Conf, which can _only_ be used for PuTTY configuration, so I've renamed them all things like conf_editbox_handler and moved them out of the nominally independent dialog-box management module into the PuTTY-specific config.c. [originally from svn r9214]
2011-07-14 18:52:21 +00:00
conf_free(backup_conf);
return ret;
}
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
static void win_gui_eventlog(LogPolicy *lp, const char *string)
{
char timebuf[40];
char **location;
struct tm tm;
tm=ltime();
strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S\t", &tm);
if (ninitial < LOGEVENT_INITIAL_MAX)
location = &events_initial[ninitial];
else
location = &events_circular[(circular_first + ncircular) % LOGEVENT_CIRCULAR_MAX];
if (*location)
sfree(*location);
*location = dupcat(timebuf, string);
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);
}
if (ninitial < LOGEVENT_INITIAL_MAX) {
ninitial++;
} else if (ncircular < LOGEVENT_CIRCULAR_MAX) {
ncircular++;
} else if (ncircular == LOGEVENT_CIRCULAR_MAX) {
circular_first = (circular_first + 1) % LOGEVENT_CIRCULAR_MAX;
sfree(events_circular[circular_first]);
events_circular[circular_first] = dupstr("..");
}
}
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
static void win_gui_logging_error(LogPolicy *lp, const char *event)
{
GUI PuTTY: stop using the global 'hwnd'. This was the difficult part of cleaning up that global variable. The main Windows PuTTY GUI is split between source files, so that _does_ actually need to refer to the main window from multiple places. But all the places where windlg.c needed to use 'hwnd' are seat methods, so they were already receiving a Seat pointer as a parameter. In other words, the methods of the Windows GUI Seat were already split between source files. So it seems only fair that they should be able to share knowledge of the seat's data as well. Hence, I've created a small 'WinGuiSeat' structure which both window.c and windlg.c can see the layout of, and put the main terminal window handle in there. Then the seat methods implemented in windlg.c, like win_seat_verify_ssh_host_key, can use container_of to turn the Seat pointer parameter back into the address of that structure, just as the methods in window.c can do (even though they currently don't need to). (Who knows: now that it _exists_, perhaps that structure can be gradually expanded in future to turn it into a proper encapsulation of all the Windows frontend's state, like we should have had all along...) I've also moved the Windows GUI LogPolicy implementation into the same object (i.e. WinGuiSeat implements both traits at once). That allows win_gui_logging_error to recover the same WinGuiSeat from its input LogPolicy pointer, which means it can get from there to the Seat facet of the same object, so that I don't need the extern variable 'win_seat' any more either.
2020-02-02 10:00:43 +00:00
WinGuiSeat *wgs = container_of(lp, WinGuiSeat, logpolicy);
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
/* Send 'can't open log file' errors to the terminal window.
* (Marked as stderr, although terminal.c won't care.) */
GUI PuTTY: stop using the global 'hwnd'. This was the difficult part of cleaning up that global variable. The main Windows PuTTY GUI is split between source files, so that _does_ actually need to refer to the main window from multiple places. But all the places where windlg.c needed to use 'hwnd' are seat methods, so they were already receiving a Seat pointer as a parameter. In other words, the methods of the Windows GUI Seat were already split between source files. So it seems only fair that they should be able to share knowledge of the seat's data as well. Hence, I've created a small 'WinGuiSeat' structure which both window.c and windlg.c can see the layout of, and put the main terminal window handle in there. Then the seat methods implemented in windlg.c, like win_seat_verify_ssh_host_key, can use container_of to turn the Seat pointer parameter back into the address of that structure, just as the methods in window.c can do (even though they currently don't need to). (Who knows: now that it _exists_, perhaps that structure can be gradually expanded in future to turn it into a proper encapsulation of all the Windows frontend's state, like we should have had all along...) I've also moved the Windows GUI LogPolicy implementation into the same object (i.e. WinGuiSeat implements both traits at once). That allows win_gui_logging_error to recover the same WinGuiSeat from its input LogPolicy pointer, which means it can get from there to the Seat facet of the same object, so that I don't need the extern variable 'win_seat' any more either.
2020-02-02 10:00:43 +00:00
seat_stderr_pl(&wgs->seat, ptrlen_from_asciz(event));
seat_stderr_pl(&wgs->seat, PTRLEN_LITERAL("\r\n"));
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
}
void showeventlog(HWND hwnd)
{
if (!logbox) {
logbox = CreateDialog(hinst, MAKEINTRESOURCE(IDD_LOGBOX),
hwnd, LogProc);
ShowWindow(logbox, SW_SHOWNORMAL);
}
SetActiveWindow(logbox);
}
void showabout(HWND hwnd)
{
DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, AboutProc);
}
struct hostkey_dialog_ctx {
const char *const *keywords;
const char *const *values;
const char *host;
int port;
FingerprintType fptype_default;
char **fingerprints;
const char *keydisp;
LPCTSTR iconid;
const char *helpctx;
};
static INT_PTR CALLBACK HostKeyMoreInfoProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
const struct hostkey_dialog_ctx *ctx =
(const struct hostkey_dialog_ctx *)lParam;
SetWindowLongPtr(hwnd, GWLP_USERDATA, (INT_PTR)ctx);
if (ctx->fingerprints[SSH_FPTYPE_SHA256])
SetDlgItemText(hwnd, IDC_HKI_SHA256,
ctx->fingerprints[SSH_FPTYPE_SHA256]);
if (ctx->fingerprints[SSH_FPTYPE_MD5])
SetDlgItemText(hwnd, IDC_HKI_MD5,
ctx->fingerprints[SSH_FPTYPE_MD5]);
SetDlgItemText(hwnd, IDA_TEXT, ctx->keydisp);
return 1;
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
EndDialog(hwnd, 0);
return 0;
}
return 0;
case WM_CLOSE:
EndDialog(hwnd, 0);
return 0;
}
return 0;
}
static INT_PTR CALLBACK HostKeyDialogProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
strbuf *sb = strbuf_new();
const struct hostkey_dialog_ctx *ctx =
(const struct hostkey_dialog_ctx *)lParam;
SetWindowLongPtr(hwnd, GWLP_USERDATA, (INT_PTR)ctx);
for (int id = 100;; id++) {
char buf[256];
if (!GetDlgItemText(hwnd, id, buf, (int)lenof(buf)))
break;
strbuf_clear(sb);
for (const char *p = buf; *p ;) {
if (*p == '{') {
for (size_t i = 0; ctx->keywords[i]; i++) {
if (strstartswith(p, ctx->keywords[i])) {
p += strlen(ctx->keywords[i]);
put_datapl(sb, ptrlen_from_asciz(ctx->values[i]));
goto matched;
}
}
} else {
put_byte(sb, *p++);
}
matched:;
}
SetDlgItemText(hwnd, id, sb->s);
}
strbuf_free(sb);
char *hostport = dupprintf("%s (port %d)", ctx->host, ctx->port);
SetDlgItemText(hwnd, IDC_HK_HOST, hostport);
sfree(hostport);
MakeDlgItemBorderless(hwnd, IDC_HK_HOST);
SetDlgItemText(hwnd, IDC_HK_FINGERPRINT,
ctx->fingerprints[ctx->fptype_default]);
MakeDlgItemBorderless(hwnd, IDC_HK_FINGERPRINT);
HANDLE icon = LoadImage(
NULL, ctx->iconid, IMAGE_ICON,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON),
LR_SHARED);
SendDlgItemMessage(hwnd, IDC_HK_ICON, STM_SETICON, (WPARAM)icon, 0);
if (!has_help()) {
HWND item = GetDlgItem(hwnd, IDHELP);
if (item)
DestroyWindow(item);
}
return 1;
}
case WM_CTLCOLORSTATIC: {
HDC hdc = (HDC)wParam;
HWND control = (HWND)lParam;
if (GetWindowLongPtr(control, GWLP_ID) == IDC_HK_TITLE) {
SetBkMode(hdc, TRANSPARENT);
HFONT prev_font = (HFONT)SelectObject(
hdc, (HFONT)GetStockObject(SYSTEM_FONT));
LOGFONT lf;
if (GetObject(prev_font, sizeof(lf), &lf)) {
lf.lfWeight = FW_BOLD;
lf.lfHeight = lf.lfHeight * 3 / 2;
HFONT bold_font = CreateFontIndirect(&lf);
if (bold_font)
SelectObject(hdc, bold_font);
}
return (INT_PTR)GetSysColorBrush(COLOR_BTNFACE);
}
return 0;
}
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_HK_ACCEPT:
case IDC_HK_ONCE:
case IDCANCEL:
EndDialog(hwnd, LOWORD(wParam));
return 0;
case IDHELP: {
const struct hostkey_dialog_ctx *ctx =
(const struct hostkey_dialog_ctx *)
GetWindowLongPtr(hwnd, GWLP_USERDATA);
launch_help(hwnd, ctx->helpctx);
return 0;
}
case IDC_HK_MOREINFO: {
const struct hostkey_dialog_ctx *ctx =
(const struct hostkey_dialog_ctx *)
GetWindowLongPtr(hwnd, GWLP_USERDATA);
DialogBoxParam(hinst, MAKEINTRESOURCE(IDD_HK_MOREINFO),
hwnd, HostKeyMoreInfoProc, (LPARAM)ctx);
}
}
return 0;
case WM_CLOSE:
EndDialog(hwnd, IDCANCEL);
return 0;
}
return 0;
}
New abstraction 'Seat', to pass to backends. This is a new vtable-based abstraction which is passed to a backend in place of Frontend, and it implements only the subset of the Frontend functions needed by a backend. (Many other Frontend functions still exist, notably the wide range of things called by terminal.c providing platform-independent operations on the GUI terminal window.) The purpose of making it a vtable is that this opens up the possibility of creating a backend as an internal implementation detail of some other activity, by providing just that one backend with a custom Seat that implements the methods differently. For example, this refactoring should make it feasible to directly implement an SSH proxy type, aka the 'jump host' feature supported by OpenSSH, aka 'open a secondary SSH session in MAINCHAN_DIRECT_TCP mode, and then expose the main channel of that as the Socket for the primary connection'. (Which of course you can already do by spawning 'plink -nc' as a separate proxy process, but this would permit it in the _same_ process without anything getting confused.) I've centralised a full set of stub methods in misc.c for the new abstraction, which allows me to get rid of several annoying stubs in the previous code. Also, while I'm here, I've moved a lot of duplicated modalfatalbox() type functions from application main program files into wincons.c / uxcons.c, which I think saves duplication overall. (A minor visible effect is that the prefixes on those console-based fatal error messages will now be more consistent between applications.)
2018-10-11 18:58:42 +00:00
int win_seat_verify_ssh_host_key(
Seat *seat, const char *host, int port, const char *keytype,
char *keystr, const char *keydisp, char **fingerprints,
New abstraction 'Seat', to pass to backends. This is a new vtable-based abstraction which is passed to a backend in place of Frontend, and it implements only the subset of the Frontend functions needed by a backend. (Many other Frontend functions still exist, notably the wide range of things called by terminal.c providing platform-independent operations on the GUI terminal window.) The purpose of making it a vtable is that this opens up the possibility of creating a backend as an internal implementation detail of some other activity, by providing just that one backend with a custom Seat that implements the methods differently. For example, this refactoring should make it feasible to directly implement an SSH proxy type, aka the 'jump host' feature supported by OpenSSH, aka 'open a secondary SSH session in MAINCHAN_DIRECT_TCP mode, and then expose the main channel of that as the Socket for the primary connection'. (Which of course you can already do by spawning 'plink -nc' as a separate proxy process, but this would permit it in the _same_ process without anything getting confused.) I've centralised a full set of stub methods in misc.c for the new abstraction, which allows me to get rid of several annoying stubs in the previous code. Also, while I'm here, I've moved a lot of duplicated modalfatalbox() type functions from application main program files into wincons.c / uxcons.c, which I think saves duplication overall. (A minor visible effect is that the prefixes on those console-based fatal error messages will now be more consistent between applications.)
2018-10-11 18:58:42 +00:00
void (*callback)(void *ctx, int result), void *ctx)
{
int ret;
GUI PuTTY: stop using the global 'hwnd'. This was the difficult part of cleaning up that global variable. The main Windows PuTTY GUI is split between source files, so that _does_ actually need to refer to the main window from multiple places. But all the places where windlg.c needed to use 'hwnd' are seat methods, so they were already receiving a Seat pointer as a parameter. In other words, the methods of the Windows GUI Seat were already split between source files. So it seems only fair that they should be able to share knowledge of the seat's data as well. Hence, I've created a small 'WinGuiSeat' structure which both window.c and windlg.c can see the layout of, and put the main terminal window handle in there. Then the seat methods implemented in windlg.c, like win_seat_verify_ssh_host_key, can use container_of to turn the Seat pointer parameter back into the address of that structure, just as the methods in window.c can do (even though they currently don't need to). (Who knows: now that it _exists_, perhaps that structure can be gradually expanded in future to turn it into a proper encapsulation of all the Windows frontend's state, like we should have had all along...) I've also moved the Windows GUI LogPolicy implementation into the same object (i.e. WinGuiSeat implements both traits at once). That allows win_gui_logging_error to recover the same WinGuiSeat from its input LogPolicy pointer, which means it can get from there to the Seat facet of the same object, so that I don't need the extern variable 'win_seat' any more either.
2020-02-02 10:00:43 +00:00
WinGuiSeat *wgs = container_of(seat, WinGuiSeat, seat);
/*
* Verify the key against the registry.
*/
ret = verify_host_key(host, port, keytype, keystr);
if (ret == 0) /* success - key matched OK */
return 1;
else {
static const char *const keywords[] =
{ "{KEYTYPE}", "{APPNAME}", NULL };
const char *values[2];
values[0] = keytype;
values[1] = appname;
struct hostkey_dialog_ctx ctx[1];
ctx->keywords = keywords;
ctx->values = values;
ctx->fingerprints = fingerprints;
ctx->fptype_default = ssh2_pick_default_fingerprint(fingerprints);
ctx->keydisp = keydisp;
ctx->iconid = (ret == 2 ? IDI_WARNING : IDI_QUESTION);
ctx->helpctx = (ret == 2 ? WINHELP_CTX_errors_hostkey_changed :
WINHELP_CTX_errors_hostkey_absent);
ctx->host = host;
ctx->port = port;
int dlgid = (ret == 2 ? IDD_HK_WRONG : IDD_HK_ABSENT);
int mbret = DialogBoxParam(
hinst, MAKEINTRESOURCE(dlgid), wgs->term_hwnd,
HostKeyDialogProc, (LPARAM)ctx);
assert(mbret==IDC_HK_ACCEPT || mbret==IDC_HK_ONCE || mbret==IDCANCEL);
if (mbret == IDC_HK_ACCEPT) {
store_host_key(host, port, keytype, keystr);
return 1;
} else if (mbret == IDC_HK_ONCE)
return 1;
}
return 0; /* abandon the connection */
}
/*
* Ask whether the selected algorithm is acceptable (since it was
* below the configured 'warn' threshold).
*/
New abstraction 'Seat', to pass to backends. This is a new vtable-based abstraction which is passed to a backend in place of Frontend, and it implements only the subset of the Frontend functions needed by a backend. (Many other Frontend functions still exist, notably the wide range of things called by terminal.c providing platform-independent operations on the GUI terminal window.) The purpose of making it a vtable is that this opens up the possibility of creating a backend as an internal implementation detail of some other activity, by providing just that one backend with a custom Seat that implements the methods differently. For example, this refactoring should make it feasible to directly implement an SSH proxy type, aka the 'jump host' feature supported by OpenSSH, aka 'open a secondary SSH session in MAINCHAN_DIRECT_TCP mode, and then expose the main channel of that as the Socket for the primary connection'. (Which of course you can already do by spawning 'plink -nc' as a separate proxy process, but this would permit it in the _same_ process without anything getting confused.) I've centralised a full set of stub methods in misc.c for the new abstraction, which allows me to get rid of several annoying stubs in the previous code. Also, while I'm here, I've moved a lot of duplicated modalfatalbox() type functions from application main program files into wincons.c / uxcons.c, which I think saves duplication overall. (A minor visible effect is that the prefixes on those console-based fatal error messages will now be more consistent between applications.)
2018-10-11 18:58:42 +00:00
int win_seat_confirm_weak_crypto_primitive(
Seat *seat, const char *algtype, const char *algname,
void (*callback)(void *ctx, int result), void *ctx)
{
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";
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);
socket_reselect_all();
sfree(message);
sfree(title);
if (mbret == IDYES)
return 1;
else
return 0;
}
New abstraction 'Seat', to pass to backends. This is a new vtable-based abstraction which is passed to a backend in place of Frontend, and it implements only the subset of the Frontend functions needed by a backend. (Many other Frontend functions still exist, notably the wide range of things called by terminal.c providing platform-independent operations on the GUI terminal window.) The purpose of making it a vtable is that this opens up the possibility of creating a backend as an internal implementation detail of some other activity, by providing just that one backend with a custom Seat that implements the methods differently. For example, this refactoring should make it feasible to directly implement an SSH proxy type, aka the 'jump host' feature supported by OpenSSH, aka 'open a secondary SSH session in MAINCHAN_DIRECT_TCP mode, and then expose the main channel of that as the Socket for the primary connection'. (Which of course you can already do by spawning 'plink -nc' as a separate proxy process, but this would permit it in the _same_ process without anything getting confused.) I've centralised a full set of stub methods in misc.c for the new abstraction, which allows me to get rid of several annoying stubs in the previous code. Also, while I'm here, I've moved a lot of duplicated modalfatalbox() type functions from application main program files into wincons.c / uxcons.c, which I think saves duplication overall. (A minor visible effect is that the prefixes on those console-based fatal error messages will now be more consistent between applications.)
2018-10-11 18:58:42 +00:00
int win_seat_confirm_weak_cached_hostkey(
Seat *seat, const char *algname, const char *betteralgs,
void (*callback)(void *ctx, int result), void *ctx)
{
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"
"above the threshold, which we do not have stored:\n"
"%s\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);
socket_reselect_all();
sfree(message);
sfree(title);
if (mbret == IDYES)
return 1;
else
return 0;
}
/*
* Ask whether to wipe a session log file before writing to it.
* Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
*/
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
static int win_gui_askappend(LogPolicy *lp, Filename *filename,
void (*callback)(void *ctx, int result),
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.";
char *message;
char *mbtitle;
int mbret;
message = dupprintf(msgtemplate, FILENAME_MAX, filename->path);
mbtitle = dupprintf("%s Log to File", appname);
mbret = MessageBox(NULL, message, mbtitle,
MB_ICONQUESTION | MB_YESNOCANCEL | MB_DEFBUTTON3);
socket_reselect_all();
sfree(message);
sfree(mbtitle);
if (mbret == IDYES)
return 2;
else if (mbret == IDNO)
return 1;
else
return 0;
}
GUI PuTTY: stop using the global 'hwnd'. This was the difficult part of cleaning up that global variable. The main Windows PuTTY GUI is split between source files, so that _does_ actually need to refer to the main window from multiple places. But all the places where windlg.c needed to use 'hwnd' are seat methods, so they were already receiving a Seat pointer as a parameter. In other words, the methods of the Windows GUI Seat were already split between source files. So it seems only fair that they should be able to share knowledge of the seat's data as well. Hence, I've created a small 'WinGuiSeat' structure which both window.c and windlg.c can see the layout of, and put the main terminal window handle in there. Then the seat methods implemented in windlg.c, like win_seat_verify_ssh_host_key, can use container_of to turn the Seat pointer parameter back into the address of that structure, just as the methods in window.c can do (even though they currently don't need to). (Who knows: now that it _exists_, perhaps that structure can be gradually expanded in future to turn it into a proper encapsulation of all the Windows frontend's state, like we should have had all along...) I've also moved the Windows GUI LogPolicy implementation into the same object (i.e. WinGuiSeat implements both traits at once). That allows win_gui_logging_error to recover the same WinGuiSeat from its input LogPolicy pointer, which means it can get from there to the Seat facet of the same object, so that I don't need the extern variable 'win_seat' any more either.
2020-02-02 10:00:43 +00:00
const LogPolicyVtable win_gui_logpolicy_vt = {
.eventlog = win_gui_eventlog,
.askappend = win_gui_askappend,
.logging_error = win_gui_logging_error,
.verbose = null_lp_verbose_yes,
Refactor the LogContext type. LogContext is now the owner of the logevent() function that back ends and so forth are constantly calling. Previously, logevent was owned by the Frontend, which would store the message into its list for the GUI Event Log dialog (or print it to standard error, or whatever) and then pass it _back_ to LogContext to write to the currently open log file. Now it's the other way round: LogContext gets the message from the back end first, writes it to its log file if it feels so inclined, and communicates it back to the front end. This means that lots of parts of the back end system no longer need to have a pointer to a full-on Frontend; the only thing they needed it for was logging, so now they just have a LogContext (which many of them had to have anyway, e.g. for logging SSH packets or session traffic). LogContext itself also doesn't get a full Frontend pointer any more: it now talks back to the front end via a little vtable of its own called LogPolicy, which contains the method that passes Event Log entries through, the old askappend() function that decides whether to truncate a pre-existing log file, and an emergency function for printing an especially prominent message if the log file can't be created. One minor nice effect of this is that console and GUI apps can implement that last function subtly differently, so that Unix console apps can write it with a plain \n instead of the \r\n (harmless but inelegant) that the old centralised implementation generated. One other consequence of this is that the LogContext has to be provided to backend_init() so that it's available to backends from the instant of creation, rather than being provided via a separate API call a couple of function calls later, because backends have typically started doing things that need logging (like making network connections) before the call to backend_provide_logctx. Fortunately, there's no case in the whole code base where we don't already have logctx by the time we make a backend (so I don't actually remember why I ever delayed providing one). So that shortens the backend API by one function, which is always nice. While I'm tidying up, I've also moved the printf-style logeventf() and the handy logevent_and_free() into logging.c, instead of having copies of them scattered around other places. This has also let me remove some stub functions from a couple of outlying applications like Pageant. Finally, I've removed the pointless "_tag" at the end of LogContext's official struct name.
2018-10-10 18:26:18 +00:00
};
/*
* 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
* an anomaly. Fortunately, the problem it addresses will not have
* been present on that platform, so it can plausibly be
* implemented as an empty function.
*/
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.";
char *msg, *title;
msg = dupprintf(message, appname);
title = dupprintf(mbtitle, appname);
MessageBox(NULL, msg, title, MB_OK);
socket_reselect_all();
sfree(msg);
sfree(title);
}