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

561 lines
20 KiB
C
Raw Normal View History

/*
* PLink - a Windows command-line (stdin/stdout) variant of PuTTY.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include "putty.h"
#include "ssh.h"
#include "storage.h"
#include "tree234.h"
#include "security-api.h"
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 cmdline_error(const char *fmt, ...)
{
va_list ap;
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
va_start(ap, fmt);
console_print_error_msg_fmt_v("plink", fmt, ap);
va_end(ap);
exit(1);
}
static HANDLE inhandle, outhandle, errhandle;
static struct handle *stdin_handle, *stdout_handle, *stderr_handle;
static handle_sink stdout_hs, stderr_hs;
static StripCtrlChars *stdout_scc, *stderr_scc;
static BinarySink *stdout_bs, *stderr_bs;
static DWORD orig_console_mode;
static Backend *backend;
static LogContext *logctx;
static 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
static void plink_echoedit_update(Seat *seat, bool echo, bool edit)
{
/* Update stdin read mode to reflect changes in line discipline. */
DWORD mode;
mode = ENABLE_PROCESSED_INPUT;
if (echo)
mode = mode | ENABLE_ECHO_INPUT;
else
mode = mode & ~ENABLE_ECHO_INPUT;
if (edit)
mode = mode | ENABLE_LINE_INPUT;
else
mode = mode & ~ENABLE_LINE_INPUT;
SetConsoleMode(inhandle, mode);
}
static size_t plink_output(
Seat *seat, SeatOutputType type, const void *data, size_t len)
{
bool is_stderr = type != SEAT_OUTPUT_STDOUT;
Plink: default to sanitising non-tty console output. If Plink's standard output and/or standard error points at a Windows console or a Unix tty device, and if Plink was not configured to request a remote pty (and hence to send a terminal-type string), then we apply the new control-character stripping facility. The idea is to be a mild defence against malicious remote processes sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like git: it's OK to have actual sensible error messages come back from the server, but when you run a git command, you didn't really intend to give the remote server the implicit licence to write _all over_ your local terminal display. At the same time, in that scenario, the standard _output_ of Plink is left completely alone, on the grounds that git will be expecting it to be 8-bit clean. (And Plink can tell that because it's redirected away from the console.) For interactive login sessions using Plink, this behaviour is disabled, on the grounds that once you've sent a terminal-type string it's assumed that you were _expecting_ the server to use it to know what escape sequences to send to you. So it should be transparent for all the use cases I've so far thought of. But in case it's not, there's a family of new command-line options like -no-sanitise-stdout and -sanitise-stderr that you can use to forcibly override the autodetection of whether to do it. This all applies the same way to both Unix and Windows Plink.
2019-02-20 07:03:57 +00:00
BinarySink *bs = is_stderr ? stderr_bs : stdout_bs;
put_data(bs, data, len);
return handle_backlog(stdout_handle) + handle_backlog(stderr_handle);
}
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 plink_eof(Seat *seat)
{
handle_write_eof(stdout_handle);
return false; /* do not respond to incoming EOF with outgoing */
}
Richer data type for interactive prompt results. All the seat functions that request an interactive prompt of some kind to the user - both the main seat_get_userpass_input and the various confirmation dialogs for things like host keys - were using a simple int return value, with the general semantics of 0 = "fail", 1 = "proceed" (and in the case of seat_get_userpass_input, answers to the prompts were provided), and -1 = "request in progress, wait for a callback". In this commit I change all those functions' return types to a new struct called SeatPromptResult, whose primary field is an enum replacing those simple integer values. The main purpose is that the enum has not three but _four_ values: the "fail" result has been split into 'user abort' and 'software abort'. The distinction is that a user abort occurs as a result of an interactive UI action, such as the user clicking 'cancel' in a dialog box or hitting ^D or ^C at a terminal password prompt - and therefore, there's no need to display an error message telling the user that the interactive operation has failed, because the user already knows, because they _did_ it. 'Software abort' is from any other cause, where PuTTY is the first to know there was a problem, and has to tell the user. We already had this 'user abort' vs 'software abort' distinction in other parts of the code - the SSH backend has separate termination functions which protocol layers can call. But we assumed that any failure from an interactive prompt request fell into the 'user abort' category, which is not true. A couple of examples: if you configure a host key fingerprint in your saved session via the SSH > Host keys pane, and the server presents a host key that doesn't match it, then verify_ssh_host_key would report that the user had aborted the connection, and feel no need to tell the user what had gone wrong! Similarly, if a password provided on the command line was not accepted, then (after I fixed the semantics of that in the previous commit) the same wrong handling would occur. So now, those Seat prompt functions too can communicate whether the user or the software originated a connection abort. And in the latter case, we also provide an error message to present to the user. Result: in those two example cases (and others), error messages should no longer go missing. Implementation note: to avoid the hassle of having the error message in a SeatPromptResult being a dynamically allocated string (and hence, every recipient of one must always check whether it's non-NULL and free it on every exit path, plus being careful about copying the struct around), I've instead arranged that the structure contains a function pointer and a couple of parameters, so that the string form of the message can be constructed on demand. That way, the only users who need to free it are the ones who actually _asked_ for it in the first place, which is a much smaller set. (This is one of the rare occasions that I regret not having C++'s extra features available in this code base - a unique_ptr or shared_ptr to a string would have been just the thing here, and the compiler would have done all the hard work for me of remembering where to insert the frees!)
2021-12-28 17:52:00 +00:00
static SeatPromptResult plink_get_userpass_input(Seat *seat, prompts_t *p)
{
Fix command-line password handling in Restart Session. When the user provides a password on the PuTTY command line, via -pw or -pwfile, the flag 'tried_once' inside cmdline_get_passwd_input() is intended to arrange that we only try sending that password once, and after we've sent it, we don't try again. But this plays badly with the 'Restart Session' operation. If the connection is lost and then restarted at user request, we _do_ want to send that password again! So this commit moves that static variable out into a small state structure held by the client of cmdline_get_passwd_input. Each client can decide how to manage that state itself. Clients that support 'Restart Session' - i.e. just GUI PuTTY itself - will initialise the state at the same time as instantiating the backend, so that every time the session is restarted, we return to (correctly) believing that we _haven't_ yet tried the password provided on the command line. But clients that don't support 'Restart Session' - i.e. Plink and file transfer tools - can do the same thing that cmdline.c was doing before: just keep the state in a static variable. This also means that the GUI login tools will now retain the command-line password in memory, whereas previously they'd have wiped it out once it was used. But the other tools will still wipe and free the password, because I've also added a 'bool restartable' flag to cmdline_get_passwd_input to let it know when it _is_ allowed to do that. In the GUI tools, I don't see any way to get round that, because if the session is restarted you _have_ to still have the password to use again. (And you can't infer that that will never happen from the CONF_close_on_exit setting, because that too could be changed in mid-session.) On the other hand, I think it's not all that worrying, because the use of either -pw or -pwfile means that a persistent copy of your password is *already* stored somewhere, so another one isn't too big a stretch. (Due to the change of -pw policy in 0.77, the effect of this bug was that an attempt to reconnect in a session set up this way would lead to "Configured password was not accepted". In 0.76, the failure mode was different: PuTTY would interactively prompt for the password, having wiped it out of memory after it was used the first time round.)
2022-05-18 12:04:56 +00:00
/* Plink doesn't support Restart Session, so we can just have a
* single static cmdline_get_passwd_input_state that's never reset */
static cmdline_get_passwd_input_state cmdline_state =
CMDLINE_GET_PASSWD_INPUT_STATE_INIT;
Richer data type for interactive prompt results. All the seat functions that request an interactive prompt of some kind to the user - both the main seat_get_userpass_input and the various confirmation dialogs for things like host keys - were using a simple int return value, with the general semantics of 0 = "fail", 1 = "proceed" (and in the case of seat_get_userpass_input, answers to the prompts were provided), and -1 = "request in progress, wait for a callback". In this commit I change all those functions' return types to a new struct called SeatPromptResult, whose primary field is an enum replacing those simple integer values. The main purpose is that the enum has not three but _four_ values: the "fail" result has been split into 'user abort' and 'software abort'. The distinction is that a user abort occurs as a result of an interactive UI action, such as the user clicking 'cancel' in a dialog box or hitting ^D or ^C at a terminal password prompt - and therefore, there's no need to display an error message telling the user that the interactive operation has failed, because the user already knows, because they _did_ it. 'Software abort' is from any other cause, where PuTTY is the first to know there was a problem, and has to tell the user. We already had this 'user abort' vs 'software abort' distinction in other parts of the code - the SSH backend has separate termination functions which protocol layers can call. But we assumed that any failure from an interactive prompt request fell into the 'user abort' category, which is not true. A couple of examples: if you configure a host key fingerprint in your saved session via the SSH > Host keys pane, and the server presents a host key that doesn't match it, then verify_ssh_host_key would report that the user had aborted the connection, and feel no need to tell the user what had gone wrong! Similarly, if a password provided on the command line was not accepted, then (after I fixed the semantics of that in the previous commit) the same wrong handling would occur. So now, those Seat prompt functions too can communicate whether the user or the software originated a connection abort. And in the latter case, we also provide an error message to present to the user. Result: in those two example cases (and others), error messages should no longer go missing. Implementation note: to avoid the hassle of having the error message in a SeatPromptResult being a dynamically allocated string (and hence, every recipient of one must always check whether it's non-NULL and free it on every exit path, plus being careful about copying the struct around), I've instead arranged that the structure contains a function pointer and a couple of parameters, so that the string form of the message can be constructed on demand. That way, the only users who need to free it are the ones who actually _asked_ for it in the first place, which is a much smaller set. (This is one of the rare occasions that I regret not having C++'s extra features available in this code base - a unique_ptr or shared_ptr to a string would have been just the thing here, and the compiler would have done all the hard work for me of remembering where to insert the frees!)
2021-12-28 17:52:00 +00:00
SeatPromptResult spr;
Fix command-line password handling in Restart Session. When the user provides a password on the PuTTY command line, via -pw or -pwfile, the flag 'tried_once' inside cmdline_get_passwd_input() is intended to arrange that we only try sending that password once, and after we've sent it, we don't try again. But this plays badly with the 'Restart Session' operation. If the connection is lost and then restarted at user request, we _do_ want to send that password again! So this commit moves that static variable out into a small state structure held by the client of cmdline_get_passwd_input. Each client can decide how to manage that state itself. Clients that support 'Restart Session' - i.e. just GUI PuTTY itself - will initialise the state at the same time as instantiating the backend, so that every time the session is restarted, we return to (correctly) believing that we _haven't_ yet tried the password provided on the command line. But clients that don't support 'Restart Session' - i.e. Plink and file transfer tools - can do the same thing that cmdline.c was doing before: just keep the state in a static variable. This also means that the GUI login tools will now retain the command-line password in memory, whereas previously they'd have wiped it out once it was used. But the other tools will still wipe and free the password, because I've also added a 'bool restartable' flag to cmdline_get_passwd_input to let it know when it _is_ allowed to do that. In the GUI tools, I don't see any way to get round that, because if the session is restarted you _have_ to still have the password to use again. (And you can't infer that that will never happen from the CONF_close_on_exit setting, because that too could be changed in mid-session.) On the other hand, I think it's not all that worrying, because the use of either -pw or -pwfile means that a persistent copy of your password is *already* stored somewhere, so another one isn't too big a stretch. (Due to the change of -pw policy in 0.77, the effect of this bug was that an attempt to reconnect in a session set up this way would lead to "Configured password was not accepted". In 0.76, the failure mode was different: PuTTY would interactively prompt for the password, having wiped it out of memory after it was used the first time round.)
2022-05-18 12:04:56 +00:00
spr = cmdline_get_passwd_input(p, &cmdline_state, false);
Richer data type for interactive prompt results. All the seat functions that request an interactive prompt of some kind to the user - both the main seat_get_userpass_input and the various confirmation dialogs for things like host keys - were using a simple int return value, with the general semantics of 0 = "fail", 1 = "proceed" (and in the case of seat_get_userpass_input, answers to the prompts were provided), and -1 = "request in progress, wait for a callback". In this commit I change all those functions' return types to a new struct called SeatPromptResult, whose primary field is an enum replacing those simple integer values. The main purpose is that the enum has not three but _four_ values: the "fail" result has been split into 'user abort' and 'software abort'. The distinction is that a user abort occurs as a result of an interactive UI action, such as the user clicking 'cancel' in a dialog box or hitting ^D or ^C at a terminal password prompt - and therefore, there's no need to display an error message telling the user that the interactive operation has failed, because the user already knows, because they _did_ it. 'Software abort' is from any other cause, where PuTTY is the first to know there was a problem, and has to tell the user. We already had this 'user abort' vs 'software abort' distinction in other parts of the code - the SSH backend has separate termination functions which protocol layers can call. But we assumed that any failure from an interactive prompt request fell into the 'user abort' category, which is not true. A couple of examples: if you configure a host key fingerprint in your saved session via the SSH > Host keys pane, and the server presents a host key that doesn't match it, then verify_ssh_host_key would report that the user had aborted the connection, and feel no need to tell the user what had gone wrong! Similarly, if a password provided on the command line was not accepted, then (after I fixed the semantics of that in the previous commit) the same wrong handling would occur. So now, those Seat prompt functions too can communicate whether the user or the software originated a connection abort. And in the latter case, we also provide an error message to present to the user. Result: in those two example cases (and others), error messages should no longer go missing. Implementation note: to avoid the hassle of having the error message in a SeatPromptResult being a dynamically allocated string (and hence, every recipient of one must always check whether it's non-NULL and free it on every exit path, plus being careful about copying the struct around), I've instead arranged that the structure contains a function pointer and a couple of parameters, so that the string form of the message can be constructed on demand. That way, the only users who need to free it are the ones who actually _asked_ for it in the first place, which is a much smaller set. (This is one of the rare occasions that I regret not having C++'s extra features available in this code base - a unique_ptr or shared_ptr to a string would have been just the thing here, and the compiler would have done all the hard work for me of remembering where to insert the frees!)
2021-12-28 17:52:00 +00:00
if (spr.kind == SPRK_INCOMPLETE)
spr = console_get_userpass_input(p);
return spr;
}
static bool plink_seat_interactive(Seat *seat)
{
return (!*conf_get_str_ambi(conf, CONF_remote_cmd, NULL) &&
!*conf_get_str_ambi(conf, CONF_remote_cmd2, NULL) &&
!*conf_get_str(conf, CONF_ssh_nc_host));
}
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
static const SeatVtable plink_seat_vt = {
.output = plink_output,
.eof = plink_eof,
New Seat callback, seat_sent(). This is used to notify the Seat that some data has been cleared from the backend's outgoing data buffer. In other words, it notifies the Seat that it might be worth calling backend_sendbuffer() again. We've never needed this before, because until now, Seats have always been the 'main program' part of the application, meaning they were also in control of the event loop. So they've been able to call backend_sendbuffer() proactively, every time they go round the event loop, instead of having to wait for a callback. But now, the SSH proxy is the first example of a Seat without privileged access to the event loop, so it has no way to find out that the backend's sendbuffer has got smaller. And without that, it can't pass that notification on to plug_sent, to unblock in turn whatever the proxied connection might have been waiting to send. In fact, before this commit, sshproxy.c never called plug_sent at all. As a result, large data uploads over an SSH jump host would hang forever as soon as the outgoing buffer filled up for the first time: the main backend (to which sshproxy.c was acting as a Socket) would carefully stop filling up the buffer, and then never receive the call to plug_sent that would cause it to start again. The new callback is ignored everywhere except in sshproxy.c. It might be a good idea to remove backend_sendbuffer() entirely and convert all previous uses of it into non-empty implementations of this callback, so that we've only got one system; but for the moment, I haven't done that.
2021-06-27 12:52:48 +00:00
.sent = nullseat_sent,
.banner = nullseat_banner_to_stderr,
.get_userpass_input = plink_get_userpass_input,
.notify_session_started = nullseat_notify_session_started,
.notify_remote_exit = nullseat_notify_remote_exit,
.notify_remote_disconnect = nullseat_notify_remote_disconnect,
.connection_fatal = console_connection_fatal,
.nonfatal = console_nonfatal,
.update_specials_menu = nullseat_update_specials_menu,
.get_ttymode = nullseat_get_ttymode,
.set_busy_status = nullseat_set_busy_status,
Reorganise host key checking and confirmation. Previously, checking the host key against the persistent cache managed by the storage.h API was done as part of the seat_verify_ssh_host_key method, i.e. separately by each Seat. Now that check is done by verify_ssh_host_key(), which is a new function in ssh/common.c that centralises all the parts of host key checking that don't need an interactive prompt. It subsumes the previous verify_ssh_manual_host_key() that checked against the Conf, and it does the check against the storage API that each Seat was previously doing separately. If it can't confirm or definitively reject the host key by itself, _then_ it calls out to the Seat, once an interactive prompt is definitely needed. The main point of doing this is so that when SshProxy forwards a Seat call from the proxy SSH connection to the primary Seat, it won't print an announcement of which connection is involved unless it's actually going to do something interactive. (Not that we're printing those announcements _yet_ anyway, but this is a piece of groundwork that works towards doing so.) But while I'm at it, I've also taken the opportunity to clean things up a bit by renaming functions sensibly. Previously we had three very similarly named functions verify_ssh_manual_host_key(), SeatVtable's 'verify_ssh_host_key' method, and verify_host_key() in storage.h. Now the Seat method is called 'confirm' rather than 'verify' (since its job is now always to print an interactive prompt, so it looks more like the other confirm_foo methods), and the storage.h function is called check_stored_host_key(), which goes better with store_host_key and avoids having too many functions with similar names. And the 'manual' function is subsumed into the new centralised code, so there's now just *one* host key function with 'verify' in the name. Several functions are reindented in this commit. Best viewed with whitespace changes ignored.
2021-10-25 17:12:17 +00:00
.confirm_ssh_host_key = console_confirm_ssh_host_key,
.confirm_weak_crypto_primitive = console_confirm_weak_crypto_primitive,
.confirm_weak_cached_hostkey = console_confirm_weak_cached_hostkey,
Centralise most details of host-key prompting. The text of the host key warnings was replicated in three places: the Windows rc file, the GTK dialog setup function, and the console.c shared between both platforms' CLI tools. Now it lives in just one place, namely ssh/common.c where the rest of the centralised host-key checking is done, so it'll be easier to adjust the wording in future. This comes with some extra automation. Paragraph wrapping is no longer done by hand in any version of these prompts. (Previously we let GTK do the wrapping on GTK, but on Windows the resource file contained a bunch of pre-wrapped LTEXT lines, and console.c had pre-wrapped terminal messages.) And the dialog heights in Windows are determined automatically based on the amount of stuff in the window. The main idea of all this is that it'll be easier to set up more elaborate kinds of host key prompt that deal with certificates (if, e.g., a server sends us a certified host key which we don't trust the CA for). But there are side benefits of this refactoring too: each tool now reliably inserts its own appname in the prompts, and also, on Windows the entire prompt text is copy-pastable. Details of implementation: there's a new type SeatDialogText which holds a set of (type, string) pairs describing the contents of a prompt. Type codes distinguish ordinary text paragraphs, paragraphs to be displayed prominently (like key fingerprints), the extra-bold scary title at the top of the 'host key changed' version of the dialog, and the various information that lives in the subsidiary 'more info' box. ssh/common.c constructs this, and passes it to the Seat to present the actual prompt. In order to deal with the different UI for answering the prompt, I've added an extra Seat method 'prompt_descriptions' which returns some snippets of text to interpolate into the messages. ssh/common.c calls that while it's still constructing the text, and incorporates the resulting snippets into the SeatDialogText. For the moment, this refactoring only affects the host key prompts. The warnings about outmoded crypto are still done the old-fashioned way; they probably ought to be similarly refactored to use this new SeatDialogText system, but it's not immediately critical for the purpose I have right now.
2022-07-07 16:25:15 +00:00
.prompt_descriptions = console_prompt_descriptions,
.is_utf8 = nullseat_is_never_utf8,
.echoedit_update = plink_echoedit_update,
.get_x_display = nullseat_get_x_display,
.get_windowid = nullseat_get_windowid,
.get_window_pixel_size = nullseat_get_window_pixel_size,
.stripctrl_new = console_stripctrl_new,
.set_trust_status = console_set_trust_status,
.can_set_trust_status = console_can_set_trust_status,
New Seat query, has_mixed_input_stream(). (TL;DR: to suppress redundant 'Press Return to begin session' prompts in between hops of a jump-host configuration, in Plink.) This new query method directly asks the Seat the question: is the same stream of input used to provide responses to interactive login prompts, and the session input provided after login concludes? It's used to suppress the last-ditch anti-spoofing defence in Plink of interactively asking 'Access granted. Press Return to begin session', on the basis that any such spoofing attack works by confusing the user about what's a legit login prompt before the session begins and what's sent by the server after the main session begins - so if those two things take input from different places, the user can't be confused. This doesn't change the existing behaviour of Plink, which was already suppressing the antispoof prompt in cases where its standard input was redirected from something other than a terminal. But previously it was doing it within the can_set_trust_status() seat query, and I've now moved it out into a separate query function. The reason why these need to be separate is for SshProxy, which needs to give an unusual combination of answers when run inside Plink. For can_set_trust_status(), it needs to return whatever the parent Seat returns, so that all the login prompts for a string of proxy connections in session will be antispoofed the same way. But you only want that final 'Access granted' prompt to happen _once_, after all the proxy connection setup phases are done, because up until then you're still in the safe hands of PuTTY itself presenting an unbroken sequence of legit login prompts (even if they come from a succession of different servers). Hence, SshProxy unconditionally returns 'no' to the query of whether it has a single mixed input stream, because indeed, it never does - for purposes of session input it behaves like an always-redirected Plink, no matter what kind of real Seat it ends up sending its pre-session login prompts to.
2021-11-06 14:33:03 +00:00
.has_mixed_input_stream = console_has_mixed_input_stream,
.verbose = cmdline_seat_verbose,
.interactive = plink_seat_interactive,
.get_cursor_position = nullseat_get_cursor_position,
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
};
static Seat plink_seat[1] = {{ &plink_seat_vt }};
static DWORD main_thread_id;
/*
* Short description of parameters.
*/
static void usage(void)
{
printf("Plink: command-line connection utility\n");
printf("%s\n", ver);
printf("Usage: plink [options] [user@]host [command]\n");
printf(" (\"host\" can also be a PuTTY saved session name)\n");
printf("Options:\n");
printf(" -V print version information and exit\n");
printf(" -pgpfp print PGP key fingerprints and exit\n");
printf(" -v show verbose messages\n");
printf(" -load sessname Load settings from saved session\n");
printf(" -ssh -telnet -rlogin -raw -serial\n");
printf(" force use of a particular protocol\n");
printf(" -ssh-connection\n");
printf(" force use of the bare ssh-connection protocol\n");
printf(" -P port connect to specified port\n");
printf(" -l user connect with specified username\n");
printf(" -batch disable all interactive prompts\n");
printf(" -proxycmd command\n");
printf(" use 'command' as local proxy\n");
printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
printf(" Specify the serial configuration (serial only)\n");
printf("The following options only apply to SSH connections:\n");
printf(" -pwfile file login with password read from specified file\n");
printf(" -D [listen-IP:]listen-port\n");
printf(" Dynamic SOCKS-based port forwarding\n");
printf(" -L [listen-IP:]listen-port:host:port\n");
printf(" Forward local port to remote address\n");
printf(" -R [listen-IP:]listen-port:host:port\n");
printf(" Forward remote port to local address\n");
printf(" -X -x enable / disable X11 forwarding\n");
printf(" -A -a enable / disable agent forwarding\n");
printf(" -t -T enable / disable pty allocation\n");
printf(" -1 -2 force use of particular SSH protocol version\n");
printf(" -4 -6 force use of IPv4 or IPv6\n");
printf(" -C enable compression\n");
printf(" -i key private key file for user authentication\n");
printf(" -noagent disable use of Pageant\n");
printf(" -agent enable use of Pageant\n");
New option to reject 'trivial' success of userauth. Suggested by Manfred Kaiser, who also wrote most of this patch (although outlying parts, like documentation and SSH-1 support, are by me). This is a second line of defence against the kind of spoofing attacks in which a malicious or compromised SSH server rushes the client through the userauth phase of SSH without actually requiring any auth inputs (passwords or signatures or whatever), and then at the start of the connection phase it presents something like a spoof prompt, intended to be taken for part of userauth by the user but in fact with some more sinister purpose. Our existing line of defence against this is the trust sigil system, and as far as I know, that's still working. This option allows a bit of extra defence in depth: if you don't expect your SSH server to trivially accept authentication in the first place, then enabling this option will cause PuTTY to disconnect if it unexpectedly does so, without the user having to spot the presence or absence of a fiddly little sigil anywhere. Several types of authentication count as 'trivial'. The obvious one is the SSH-2 "none" method, which clients always try first so that the failure message will tell them what else they can try, and which a server can instead accept in order to authenticate you unconditionally. But there are two other ways to do it that we know of: one is to run keyboard-interactive authentication and send an empty INFO_REQUEST packet containing no actual prompts for the user, and another even weirder one is to send USERAUTH_SUCCESS in response to the user's preliminary *offer* of a public key (instead of sending the usual PK_OK to request an actual signature from the key). This new option detects all of those, by clearing the 'is_trivial_auth' flag only when we send some kind of substantive authentication response (be it a password, a k-i prompt response, a signature, or a GSSAPI token). So even if there's a further path through the userauth maze we haven't spotted, that somehow avoids sending anything substantive, this strategy should still pick it up.
2021-06-19 14:39:15 +00:00
printf(" -no-trivial-auth\n");
printf(" disconnect if SSH authentication succeeds trivially\n");
printf(" -noshare disable use of connection sharing\n");
printf(" -share enable use of connection sharing\n");
printf(" -hostkey keyid\n");
printf(" manually specify a host key (may be repeated)\n");
Plink: default to sanitising non-tty console output. If Plink's standard output and/or standard error points at a Windows console or a Unix tty device, and if Plink was not configured to request a remote pty (and hence to send a terminal-type string), then we apply the new control-character stripping facility. The idea is to be a mild defence against malicious remote processes sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like git: it's OK to have actual sensible error messages come back from the server, but when you run a git command, you didn't really intend to give the remote server the implicit licence to write _all over_ your local terminal display. At the same time, in that scenario, the standard _output_ of Plink is left completely alone, on the grounds that git will be expecting it to be 8-bit clean. (And Plink can tell that because it's redirected away from the console.) For interactive login sessions using Plink, this behaviour is disabled, on the grounds that once you've sent a terminal-type string it's assumed that you were _expecting_ the server to use it to know what escape sequences to send to you. So it should be transparent for all the use cases I've so far thought of. But in case it's not, there's a family of new command-line options like -no-sanitise-stdout and -sanitise-stderr that you can use to forcibly override the autodetection of whether to do it. This all applies the same way to both Unix and Windows Plink.
2019-02-20 07:03:57 +00:00
printf(" -sanitise-stderr, -sanitise-stdout, "
"-no-sanitise-stderr, -no-sanitise-stdout\n");
printf(" do/don't strip control chars from standard "
"output/error\n");
printf(" -no-antispoof omit anti-spoofing prompt after "
"authentication\n");
printf(" -m file read remote command(s) from file\n");
printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
printf(" -N don't start a shell/command (SSH-2 only)\n");
printf(" -nc host:port\n");
printf(" open tunnel in place of session (SSH-2 only)\n");
printf(" -sshlog file\n");
printf(" -sshrawlog file\n");
printf(" log protocol details to a file\n");
2020-11-25 15:12:56 +00:00
printf(" -logoverwrite\n");
printf(" -logappend\n");
printf(" control what happens when a log file already exists\n");
printf(" -shareexists\n");
printf(" test whether a connection-sharing upstream exists\n");
}
static void version(void)
{
char *buildinfo_text = buildinfo("\n");
printf("plink: %s\n%s\n", ver, buildinfo_text);
sfree(buildinfo_text);
exit(0);
}
size_t stdin_gotdata(struct handle *h, const void *data, size_t len, int err)
{
if (err) {
char buf[4096];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
buf, lenof(buf), NULL);
buf[lenof(buf)-1] = '\0';
if (buf[strlen(buf)-1] == '\n')
buf[strlen(buf)-1] = '\0';
fprintf(stderr, "Unable to read from standard input: %s\n", buf);
cleanup_exit(0);
}
noise_ultralight(NOISE_SOURCE_IOLEN, len);
if (backend_connected(backend)) {
if (len > 0) {
backend_send(backend, data, len);
return backend_sendbuffer(backend);
} else {
backend_special(backend, SS_EOF, 0);
return 0;
}
} else
return 0;
}
handle_write_eof: delegate CloseHandle back to the client. When a writable HANDLE is managed by the handle-io.c system, you ask to send EOF on the handle by calling handle_write_eof. That waits until all buffered data has been written, and then sends an EOF event by simply closing the handle. That is, of course, the only way to send an EOF signal on a handle at all. And yet, it's a bug, because the handle_output system does not take ownership of the handle you give it: the client of handle_output retains ownership, keeps its own copy of the handle, and will expect to close it itself. In most cases, the extra close will harmlessly fail, and return ERROR_INVALID_HANDLE (which the caller didn't notice anyway). But if you're unlucky, in conditions of frantic handle opening and closing (e.g. with a lot of separate named-pipe-style agent forwarding connections being constantly set up and torn down), the handle value might have been reused between the two closes, so that the second CloseHandle closes an unrelated handle belonging to some other part of the program. We can't fix this by giving handle_output permanent ownership of the handle, because it really _is_ necessary for copies of it to survive elsewhere: in particular, for a bidirectional file such as a serial port or named pipe, the reading side also needs a copy of the same handle! And yet, we can't replace the handle_write_eof call in the client with a direct CloseHandle, because that won't wait until buffered output has been drained. The solution is that the client still calls handle_write_eof to register that it _wants_ an EOF sent; the handle_output system will wait until it's ready, but then, instead of calling CloseHandle, it will ask its _client_ to close the handle, by calling the provided 'sentdata' callback with the new 'close' flag set to true. And then the client can not only close the handle, but do whatever else it needs to do to record that that has been done.
2021-09-30 18:16:20 +00:00
void stdouterr_sent(struct handle *h, size_t new_backlog, int err, bool close)
{
handle_write_eof: delegate CloseHandle back to the client. When a writable HANDLE is managed by the handle-io.c system, you ask to send EOF on the handle by calling handle_write_eof. That waits until all buffered data has been written, and then sends an EOF event by simply closing the handle. That is, of course, the only way to send an EOF signal on a handle at all. And yet, it's a bug, because the handle_output system does not take ownership of the handle you give it: the client of handle_output retains ownership, keeps its own copy of the handle, and will expect to close it itself. In most cases, the extra close will harmlessly fail, and return ERROR_INVALID_HANDLE (which the caller didn't notice anyway). But if you're unlucky, in conditions of frantic handle opening and closing (e.g. with a lot of separate named-pipe-style agent forwarding connections being constantly set up and torn down), the handle value might have been reused between the two closes, so that the second CloseHandle closes an unrelated handle belonging to some other part of the program. We can't fix this by giving handle_output permanent ownership of the handle, because it really _is_ necessary for copies of it to survive elsewhere: in particular, for a bidirectional file such as a serial port or named pipe, the reading side also needs a copy of the same handle! And yet, we can't replace the handle_write_eof call in the client with a direct CloseHandle, because that won't wait until buffered output has been drained. The solution is that the client still calls handle_write_eof to register that it _wants_ an EOF sent; the handle_output system will wait until it's ready, but then, instead of calling CloseHandle, it will ask its _client_ to close the handle, by calling the provided 'sentdata' callback with the new 'close' flag set to true. And then the client can not only close the handle, but do whatever else it needs to do to record that that has been done.
2021-09-30 18:16:20 +00:00
if (close) {
CloseHandle(outhandle);
CloseHandle(errhandle);
outhandle = errhandle = INVALID_HANDLE_VALUE;
}
if (err) {
char buf[4096];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
buf, lenof(buf), NULL);
buf[lenof(buf)-1] = '\0';
if (buf[strlen(buf)-1] == '\n')
buf[strlen(buf)-1] = '\0';
fprintf(stderr, "Unable to write to standard %s: %s\n",
(h == stdout_handle ? "output" : "error"), buf);
cleanup_exit(0);
}
if (backend_connected(backend)) {
backend_unthrottle(backend, (handle_backlog(stdout_handle) +
handle_backlog(stderr_handle)));
}
}
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
const bool share_can_be_downstream = true;
const bool share_can_be_upstream = true;
const unsigned cmdline_tooltype =
TOOLTYPE_HOST_ARG |
TOOLTYPE_HOST_ARG_CAN_BE_SESSION |
TOOLTYPE_HOST_ARG_PROTOCOL_PREFIX |
TOOLTYPE_HOST_ARG_FROM_LAUNCHABLE_LOAD;
static bool sending;
static bool plink_mainloop_pre(void *vctx, const HANDLE **extra_handles,
size_t *n_extra_handles)
{
if (!sending && backend_sendok(backend)) {
stdin_handle = handle_input_new(inhandle, stdin_gotdata, NULL,
0);
sending = true;
}
return true;
}
static bool plink_mainloop_post(void *vctx, size_t extra_handle_index)
{
if (sending)
handle_unthrottle(stdin_handle, backend_sendbuffer(backend));
if (!backend_connected(backend) &&
handle_backlog(stdout_handle) + handle_backlog(stderr_handle) == 0)
return false; /* we closed the connection */
return true;
}
int main(int argc, char **argv)
{
int exitcode;
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 errors;
bool use_subsystem = false;
bool just_test_share_exists = false;
Plink: default to sanitising non-tty console output. If Plink's standard output and/or standard error points at a Windows console or a Unix tty device, and if Plink was not configured to request a remote pty (and hence to send a terminal-type string), then we apply the new control-character stripping facility. The idea is to be a mild defence against malicious remote processes sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like git: it's OK to have actual sensible error messages come back from the server, but when you run a git command, you didn't really intend to give the remote server the implicit licence to write _all over_ your local terminal display. At the same time, in that scenario, the standard _output_ of Plink is left completely alone, on the grounds that git will be expecting it to be 8-bit clean. (And Plink can tell that because it's redirected away from the console.) For interactive login sessions using Plink, this behaviour is disabled, on the grounds that once you've sent a terminal-type string it's assumed that you were _expecting_ the server to use it to know what escape sequences to send to you. So it should be transparent for all the use cases I've so far thought of. But in case it's not, there's a family of new command-line options like -no-sanitise-stdout and -sanitise-stderr that you can use to forcibly override the autodetection of whether to do it. This all applies the same way to both Unix and Windows Plink.
2019-02-20 07:03:57 +00:00
enum TriState sanitise_stdout = AUTO, sanitise_stderr = AUTO;
const struct BackendVtable *vt;
dll_hijacking_protection();
/*
* Initialise port and protocol to sensible defaults. (These
* will be overridden by more or less anything.)
*/
settings_set_default_protocol(PROT_SSH);
settings_set_default_port(22);
/*
* Process the command line.
*/
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 = conf_new();
do_defaults(NULL, conf);
settings_set_default_protocol(conf_get_int(conf, CONF_protocol));
settings_set_default_port(conf_get_int(conf, CONF_port));
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
errors = false;
{
/*
* Override the default protocol if PLINK_PROTOCOL is set.
*/
char *p = getenv("PLINK_PROTOCOL");
if (p) {
const struct BackendVtable *vt = backend_vt_from_name(p);
if (vt) {
settings_set_default_protocol(vt->protocol);
settings_set_default_port(vt->default_port);
conf_set_int(conf, CONF_protocol, vt->protocol);
conf_set_int(conf, CONF_port, vt->default_port);
}
}
}
New abstraction for command-line arguments. This begins the process of enabling our Windows applications to handle Unicode characters on their command lines which don't fit in the system code page. Instead of passing plain strings to cmdline_process_param, we now pass a partially opaque and platform-specific thing called a CmdlineArg. This has a method that extracts the argument word as a default-encoded string, and another one that tries to extract it as UTF-8 (though it may fail if the UTF-8 isn't available). On Windows, the command line is now constructed by calling split_into_argv_w on the Unicode command line returned by GetCommandLineW(), and the UTF-8 method returns text converted directly from that wide-character form, not going via the system code page. So it _can_ include UTF-8 characters that wouldn't have round-tripped via CP_ACP. This commit introduces the abstraction and switches over the cross-platform and Windows argv-handling code to use it, with minimal functional change. Nothing yet tries to call cmdline_arg_get_utf8(). I say 'cross-platform and Windows' because on the Unix side there's still a lot of use of plain old argv which I haven't converted. That would be a much larger project, and isn't currently needed: the _current_ aim of this abstraction is to get the right things to happen relating to Unicode on Windows, so for code that doesn't run on Windows anyway, it's not adding value. (Also there's a tension with GTK, which wants to talk to standard argv and extract arguments _it_ knows about, so at the very least we'd have to let it munge argv before importing it into this new system.)
2024-09-25 09:18:38 +00:00
CmdlineArgList *arglist = cmdline_arg_list_from_GetCommandLineW();
size_t arglistpos = 0;
while (arglist->args[arglistpos]) {
CmdlineArg *arg = arglist->args[arglistpos++];
CmdlineArg *nextarg = arglist->args[arglistpos];
const char *p = cmdline_arg_to_str(arg);
int ret = cmdline_process_param(arg, nextarg, 1, conf);
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
if (ret == -2) {
fprintf(stderr,
"plink: option \"%s\" requires an argument\n", p);
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
errors = true;
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else if (ret == 2) {
New abstraction for command-line arguments. This begins the process of enabling our Windows applications to handle Unicode characters on their command lines which don't fit in the system code page. Instead of passing plain strings to cmdline_process_param, we now pass a partially opaque and platform-specific thing called a CmdlineArg. This has a method that extracts the argument word as a default-encoded string, and another one that tries to extract it as UTF-8 (though it may fail if the UTF-8 isn't available). On Windows, the command line is now constructed by calling split_into_argv_w on the Unicode command line returned by GetCommandLineW(), and the UTF-8 method returns text converted directly from that wide-character form, not going via the system code page. So it _can_ include UTF-8 characters that wouldn't have round-tripped via CP_ACP. This commit introduces the abstraction and switches over the cross-platform and Windows argv-handling code to use it, with minimal functional change. Nothing yet tries to call cmdline_arg_get_utf8(). I say 'cross-platform and Windows' because on the Unix side there's still a lot of use of plain old argv which I haven't converted. That would be a much larger project, and isn't currently needed: the _current_ aim of this abstraction is to get the right things to happen relating to Unicode on Windows, so for code that doesn't run on Windows anyway, it's not adding value. (Also there's a tension with GTK, which wants to talk to standard argv and extract arguments _it_ knows about, so at the very least we'd have to let it munge argv before importing it into this new system.)
2024-09-25 09:18:38 +00:00
arglistpos++;
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else if (ret == 1) {
continue;
} else if (!strcmp(p, "-s")) {
/* Save status to write to conf later. */
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
use_subsystem = true;
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
version();
} else if (!strcmp(p, "--help")) {
usage();
exit(0);
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else if (!strcmp(p, "-pgpfp")) {
pgp_fingerprints();
exit(0);
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else if (!strcmp(p, "-shareexists")) {
just_test_share_exists = true;
Plink: default to sanitising non-tty console output. If Plink's standard output and/or standard error points at a Windows console or a Unix tty device, and if Plink was not configured to request a remote pty (and hence to send a terminal-type string), then we apply the new control-character stripping facility. The idea is to be a mild defence against malicious remote processes sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like git: it's OK to have actual sensible error messages come back from the server, but when you run a git command, you didn't really intend to give the remote server the implicit licence to write _all over_ your local terminal display. At the same time, in that scenario, the standard _output_ of Plink is left completely alone, on the grounds that git will be expecting it to be 8-bit clean. (And Plink can tell that because it's redirected away from the console.) For interactive login sessions using Plink, this behaviour is disabled, on the grounds that once you've sent a terminal-type string it's assumed that you were _expecting_ the server to use it to know what escape sequences to send to you. So it should be transparent for all the use cases I've so far thought of. But in case it's not, there's a family of new command-line options like -no-sanitise-stdout and -sanitise-stderr that you can use to forcibly override the autodetection of whether to do it. This all applies the same way to both Unix and Windows Plink.
2019-02-20 07:03:57 +00:00
} else if (!strcmp(p, "-sanitise-stdout") ||
!strcmp(p, "-sanitize-stdout")) {
sanitise_stdout = FORCE_ON;
} else if (!strcmp(p, "-no-sanitise-stdout") ||
!strcmp(p, "-no-sanitize-stdout")) {
sanitise_stdout = FORCE_OFF;
} else if (!strcmp(p, "-sanitise-stderr") ||
!strcmp(p, "-sanitize-stderr")) {
sanitise_stderr = FORCE_ON;
} else if (!strcmp(p, "-no-sanitise-stderr") ||
!strcmp(p, "-no-sanitize-stderr")) {
sanitise_stderr = FORCE_OFF;
} else if (!strcmp(p, "-no-antispoof")) {
console_antispoof_prompt = false;
} else if (*p != '-') {
strbuf *cmdbuf = strbuf_new();
New abstraction for command-line arguments. This begins the process of enabling our Windows applications to handle Unicode characters on their command lines which don't fit in the system code page. Instead of passing plain strings to cmdline_process_param, we now pass a partially opaque and platform-specific thing called a CmdlineArg. This has a method that extracts the argument word as a default-encoded string, and another one that tries to extract it as UTF-8 (though it may fail if the UTF-8 isn't available). On Windows, the command line is now constructed by calling split_into_argv_w on the Unicode command line returned by GetCommandLineW(), and the UTF-8 method returns text converted directly from that wide-character form, not going via the system code page. So it _can_ include UTF-8 characters that wouldn't have round-tripped via CP_ACP. This commit introduces the abstraction and switches over the cross-platform and Windows argv-handling code to use it, with minimal functional change. Nothing yet tries to call cmdline_arg_get_utf8(). I say 'cross-platform and Windows' because on the Unix side there's still a lot of use of plain old argv which I haven't converted. That would be a much larger project, and isn't currently needed: the _current_ aim of this abstraction is to get the right things to happen relating to Unicode on Windows, so for code that doesn't run on Windows anyway, it's not adding value. (Also there's a tension with GTK, which wants to talk to standard argv and extract arguments _it_ knows about, so at the very least we'd have to let it munge argv before importing it into this new system.)
2024-09-25 09:18:38 +00:00
while (arg) {
if (cmdbuf->len > 0)
put_byte(cmdbuf, ' '); /* add space separator */
put_dataz(cmdbuf, cmdline_arg_to_utf8(arg));
New abstraction for command-line arguments. This begins the process of enabling our Windows applications to handle Unicode characters on their command lines which don't fit in the system code page. Instead of passing plain strings to cmdline_process_param, we now pass a partially opaque and platform-specific thing called a CmdlineArg. This has a method that extracts the argument word as a default-encoded string, and another one that tries to extract it as UTF-8 (though it may fail if the UTF-8 isn't available). On Windows, the command line is now constructed by calling split_into_argv_w on the Unicode command line returned by GetCommandLineW(), and the UTF-8 method returns text converted directly from that wide-character form, not going via the system code page. So it _can_ include UTF-8 characters that wouldn't have round-tripped via CP_ACP. This commit introduces the abstraction and switches over the cross-platform and Windows argv-handling code to use it, with minimal functional change. Nothing yet tries to call cmdline_arg_get_utf8(). I say 'cross-platform and Windows' because on the Unix side there's still a lot of use of plain old argv which I haven't converted. That would be a much larger project, and isn't currently needed: the _current_ aim of this abstraction is to get the right things to happen relating to Unicode on Windows, so for code that doesn't run on Windows anyway, it's not adding value. (Also there's a tension with GTK, which wants to talk to standard argv and extract arguments _it_ knows about, so at the very least we'd have to let it munge argv before importing it into this new system.)
2024-09-25 09:18:38 +00:00
arg = arglist->args[arglistpos++];
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
}
conf_set_str(conf, CONF_remote_cmd, cmdbuf->s);
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
conf_set_str(conf, CONF_remote_cmd2, "");
conf_set_bool(conf, CONF_nopty, true); /* command => no tty */
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
strbuf_free(cmdbuf);
break; /* done with cmdline */
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
} else {
fprintf(stderr, "plink: unknown option \"%s\"\n", p);
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
errors = true;
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
}
}
if (errors)
return 1;
Centralise PuTTY and Plink's non-option argument handling. This is another piece of long-overdue refactoring similar to the recent commit e3796cb77. But where that one dealt with normalisation of stuff already stored _in_ a Conf by whatever means (including, in particular, handling a user typing 'username@host.name' into the Hostname box of the GUI session dialog box), this one deals with handling argv entries and putting them into the Conf. This isn't exactly a pure no-functional-change-at-all refactoring. On the other hand, it isn't a full-on cleanup that completely rationalises all the user-visible behaviour as well as the code structure. It's somewhere in between: I've preserved all the behaviour quirks that I could imagine a reason for having intended, but taken the opportunity to _not_ faithfully replicate anything I thought was clearly just a bug. So, for example, the following inconsistency is carefully preserved: the command 'plink -load session nextword' treats 'nextword' as a host name if the loaded session hasn't provided a hostname already, and otherwise treats 'nextword' as the remote command to execute on the already-specified remote host, but the same combination of arguments to GUI PuTTY will _always_ treat 'nextword' as a hostname, overriding a hostname (if any) in the saved session. That makes some sense to me because of the different shapes of the overall command lines. On the other hand, there are two behaviour changes I know of as a result of this commit: a third argument to GUI PuTTY (after a hostname and port) now provokes an error message instead of being silently ignored, and in Plink, if you combine a -P option (specifying a port number) with the historical comma-separated protocol selection prefix on the hostname argument (which I'd completely forgotten even existed until this piece of work), then the -P will now override the selected protocol's default port number, whereas previously the default port would win. For example, 'plink -P 12345 telnet,hostname' will now connect via Telnet to port 12345 instead of to port 23. There may be scope for removing or rethinking some of the command- line syntax quirks in the wake of this change. If we do decide to do anything like that, then hopefully having it all in one place will make it easier to remove or change things consistently across the tools.
2017-12-07 19:59:43 +00:00
if (!cmdline_host_ok(conf)) {
fprintf(stderr, "plink: no valid host name provided\n"
"try \"plink --help\" for help\n");
cmdline_arg_list_free(arglist);
return 1;
}
prepare_session(conf);
/*
* Perform command-line overrides on session configuration.
*/
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
cmdline_run_saved(conf);
/*
* Apply subsystem status.
*/
if (use_subsystem)
conf_set_bool(conf, CONF_ssh_subsys, true);
/*
* Select protocol. This is farmed out into a table in a
* separate file to enable an ssh-free variant.
*/
vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
if (vt == NULL) {
fprintf(stderr,
"Internal fault: Unsupported protocol found\n");
return 1;
}
if (vt->flags & BACKEND_NEEDS_TERMINAL) {
fprintf(stderr,
"Plink doesn't support %s, which needs terminal emulation\n",
vt->displayname_lc);
return 1;
}
sk_init();
if (p_WSAEventSelect == NULL) {
fprintf(stderr, "Plink requires WinSock 2\n");
return 1;
}
/*
* Plink doesn't provide any way to add forwardings after the
* connection is set up, so if there are none now, we can safely set
* the "simple" flag.
*/
if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
!conf_get_bool(conf, CONF_x11_forward) &&
!conf_get_bool(conf, CONF_agentfwd) &&
!conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
conf_set_bool(conf, CONF_ssh_simple, true);
Remove FLAG_VERBOSE. The global 'int flags' has always been an ugly feature of this code base, and I suddenly thought that perhaps it's time to start throwing it out, one flag at a time, until it's totally unused. My first target is FLAG_VERBOSE. This was usually set by cmdline.c when it saw a -v option on the program's command line, except that GUI PuTTY itself sets it unconditionally on startup. And then various bits of the code would check it in order to decide whether to print a given message. In the current system of front-end abstraction traits, there's no _one_ place that I can move it to. But there are two: every place that checked FLAG_VERBOSE has access to either a Seat or a LogPolicy. So now each of those traits has a query method for 'do I want verbose messages?'. A good effect of this is that subsidiary Seats, like the ones used in Uppity for the main SSH server module itself and the server end of shell channels, now get to have their own verbosity setting instead of inheriting the one global one. In fact I don't expect any code using those Seats to be generating any messages at all, but if that changes later, we'll have a way to control it. (Who knows, perhaps logging in Uppity might become a thing.) As part of this cleanup, I've added a new flag to cmdline_tooltype, called TOOLTYPE_NO_VERBOSE_OPTION. The unconditionally-verbose tools now set that, and it has the effect of making cmdline.c disallow -v completely. So where 'putty -v' would previously have been silently ignored ("I was already verbose"), it's now an error, reminding you that that option doesn't actually do anything. Finally, the 'default_logpolicy' provided by uxcons.c and wincons.c (with identical definitions) has had to move into a new file of its own, because now it has to ask cmdline.c for the verbosity setting as well as asking console.c for the rest of its methods. So there's a new file clicons.c which can only be included by programs that link against both cmdline.c _and_ one of the *cons.c, and I've renamed the logpolicy to reflect that.
2020-01-30 06:40:21 +00:00
logctx = log_init(console_cli_logpolicy, conf);
if (just_test_share_exists) {
if (!vt->test_for_upstream) {
fprintf(stderr, "Connection sharing not supported for this "
"connection type (%s)'\n", vt->displayname_lc);
return 1;
}
if (vt->test_for_upstream(conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port), conf))
return 0;
else
return 1;
}
if (restricted_acl()) {
Remove FLAG_VERBOSE. The global 'int flags' has always been an ugly feature of this code base, and I suddenly thought that perhaps it's time to start throwing it out, one flag at a time, until it's totally unused. My first target is FLAG_VERBOSE. This was usually set by cmdline.c when it saw a -v option on the program's command line, except that GUI PuTTY itself sets it unconditionally on startup. And then various bits of the code would check it in order to decide whether to print a given message. In the current system of front-end abstraction traits, there's no _one_ place that I can move it to. But there are two: every place that checked FLAG_VERBOSE has access to either a Seat or a LogPolicy. So now each of those traits has a query method for 'do I want verbose messages?'. A good effect of this is that subsidiary Seats, like the ones used in Uppity for the main SSH server module itself and the server end of shell channels, now get to have their own verbosity setting instead of inheriting the one global one. In fact I don't expect any code using those Seats to be generating any messages at all, but if that changes later, we'll have a way to control it. (Who knows, perhaps logging in Uppity might become a thing.) As part of this cleanup, I've added a new flag to cmdline_tooltype, called TOOLTYPE_NO_VERBOSE_OPTION. The unconditionally-verbose tools now set that, and it has the effect of making cmdline.c disallow -v completely. So where 'putty -v' would previously have been silently ignored ("I was already verbose"), it's now an error, reminding you that that option doesn't actually do anything. Finally, the 'default_logpolicy' provided by uxcons.c and wincons.c (with identical definitions) has had to move into a new file of its own, because now it has to ask cmdline.c for the verbosity setting as well as asking console.c for the rest of its methods. So there's a new file clicons.c which can only be included by programs that link against both cmdline.c _and_ one of the *cons.c, and I've renamed the logpolicy to reflect that.
2020-01-30 06:40:21 +00:00
lp_eventlog(console_cli_logpolicy,
"Running with restricted process ACL");
}
inhandle = GetStdHandle(STD_INPUT_HANDLE);
outhandle = GetStdHandle(STD_OUTPUT_HANDLE);
errhandle = GetStdHandle(STD_ERROR_HANDLE);
/*
* Turn off ECHO and LINE input modes. We don't care if this
* call fails, because we know we aren't necessarily running in
* a console.
*/
GetConsoleMode(inhandle, &orig_console_mode);
SetConsoleMode(inhandle, ENABLE_PROCESSED_INPUT);
/*
* Pass the output handles to the handle-handling subsystem.
* (The input one we leave until we're through the
* authentication process.)
*/
stdout_handle = handle_output_new(outhandle, stdouterr_sent, NULL, 0);
stderr_handle = handle_output_new(errhandle, stdouterr_sent, NULL, 0);
Plink: default to sanitising non-tty console output. If Plink's standard output and/or standard error points at a Windows console or a Unix tty device, and if Plink was not configured to request a remote pty (and hence to send a terminal-type string), then we apply the new control-character stripping facility. The idea is to be a mild defence against malicious remote processes sending confusing escape sequences through the standard error channel when Plink is being used as a transport for something like git: it's OK to have actual sensible error messages come back from the server, but when you run a git command, you didn't really intend to give the remote server the implicit licence to write _all over_ your local terminal display. At the same time, in that scenario, the standard _output_ of Plink is left completely alone, on the grounds that git will be expecting it to be 8-bit clean. (And Plink can tell that because it's redirected away from the console.) For interactive login sessions using Plink, this behaviour is disabled, on the grounds that once you've sent a terminal-type string it's assumed that you were _expecting_ the server to use it to know what escape sequences to send to you. So it should be transparent for all the use cases I've so far thought of. But in case it's not, there's a family of new command-line options like -no-sanitise-stdout and -sanitise-stderr that you can use to forcibly override the autodetection of whether to do it. This all applies the same way to both Unix and Windows Plink.
2019-02-20 07:03:57 +00:00
handle_sink_init(&stdout_hs, stdout_handle);
handle_sink_init(&stderr_hs, stderr_handle);
stdout_bs = BinarySink_UPCAST(&stdout_hs);
stderr_bs = BinarySink_UPCAST(&stderr_hs);
/*
* Decide whether to sanitise control sequences out of standard
* output and standard error.
*
* If we weren't given a command-line override, we do this if (a)
* the fd in question is pointing at a console, and (b) we aren't
* trying to allocate a terminal as part of the session.
*
* (Rationale: the risk of control sequences is that they cause
* confusion when sent to a local console, so if there isn't one,
* no problem. Also, if we allocate a remote terminal, then we
* sent a terminal type, i.e. we told it what kind of escape
* sequences we _like_, i.e. we were expecting to receive some.)
*/
if (sanitise_stdout == FORCE_ON ||
(sanitise_stdout == AUTO && is_console_handle(outhandle) &&
conf_get_bool(conf, CONF_nopty))) {
stdout_scc = stripctrl_new(stdout_bs, true, L'\0');
stdout_bs = BinarySink_UPCAST(stdout_scc);
}
if (sanitise_stderr == FORCE_ON ||
(sanitise_stderr == AUTO && is_console_handle(errhandle) &&
conf_get_bool(conf, CONF_nopty))) {
stderr_scc = stripctrl_new(stderr_bs, true, L'\0');
stderr_bs = BinarySink_UPCAST(stderr_scc);
}
/*
* Start up the connection.
*/
winselcli_setup(); /* ensure event object exists */
{
char *error, *realhost;
/* nodelay is only useful if stdin is a character device (console) */
bool nodelay = conf_get_bool(conf, CONF_tcp_nodelay) &&
(GetFileType(GetStdHandle(STD_INPUT_HANDLE)) == FILE_TYPE_CHAR);
error = backend_init(vt, plink_seat, &backend, logctx, conf,
conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port),
&realhost, nodelay,
conf_get_bool(conf, CONF_tcp_keepalives));
if (error) {
fprintf(stderr, "Unable to open connection:\n%s", error);
sfree(error);
return 1;
}
ldisc_create(conf, NULL, backend, plink_seat);
sfree(realhost);
}
main_thread_id = GetCurrentThreadId();
sending = false;
cli_main_loop(plink_mainloop_pre, plink_mainloop_post, NULL);
exitcode = backend_exitcode(backend);
if (exitcode < 0) {
fprintf(stderr, "Remote process exit code unavailable\n");
exitcode = 1; /* this is an error condition */
}
cleanup_exit(exitcode);
return 0; /* placate compiler warning */
}