1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-01-10 01:48:00 +00:00
putty-source/windows/winser.c
Simon Tatham ad0c502cef Refactor the LogContext type.
LogContext is now the owner of the logevent() function that back ends
and so forth are constantly calling. Previously, logevent was owned by
the Frontend, which would store the message into its list for the GUI
Event Log dialog (or print it to standard error, or whatever) and then
pass it _back_ to LogContext to write to the currently open log file.
Now it's the other way round: LogContext gets the message from the
back end first, writes it to its log file if it feels so inclined, and
communicates it back to the front end.

This means that lots of parts of the back end system no longer need to
have a pointer to a full-on Frontend; the only thing they needed it
for was logging, so now they just have a LogContext (which many of
them had to have anyway, e.g. for logging SSH packets or session
traffic).

LogContext itself also doesn't get a full Frontend pointer any more:
it now talks back to the front end via a little vtable of its own
called LogPolicy, which contains the method that passes Event Log
entries through, the old askappend() function that decides whether to
truncate a pre-existing log file, and an emergency function for
printing an especially prominent message if the log file can't be
created. One minor nice effect of this is that console and GUI apps
can implement that last function subtly differently, so that Unix
console apps can write it with a plain \n instead of the \r\n
(harmless but inelegant) that the old centralised implementation
generated.

One other consequence of this is that the LogContext has to be
provided to backend_init() so that it's available to backends from the
instant of creation, rather than being provided via a separate API
call a couple of function calls later, because backends have typically
started doing things that need logging (like making network
connections) before the call to backend_provide_logctx. Fortunately,
there's no case in the whole code base where we don't already have
logctx by the time we make a backend (so I don't actually remember why
I ever delayed providing one). So that shortens the backend API by one
function, which is always nice.

While I'm tidying up, I've also moved the printf-style logeventf() and
the handy logevent_and_free() into logging.c, instead of having copies
of them scattered around other places. This has also let me remove
some stub functions from a couple of outlying applications like
Pageant. Finally, I've removed the pointless "_tag" at the end of
LogContext's official struct name.
2018-10-10 21:50:50 +01:00

447 lines
12 KiB
C

/*
* Serial back end (Windows-specific).
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "putty.h"
#define SERIAL_MAX_BACKLOG 4096
typedef struct Serial Serial;
struct Serial {
HANDLE port;
struct handle *out, *in;
Frontend *frontend;
LogContext *logctx;
int bufsize;
long clearbreak_time;
int break_in_progress;
Backend backend;
};
static void serial_terminate(Serial *serial)
{
if (serial->out) {
handle_free(serial->out);
serial->out = NULL;
}
if (serial->in) {
handle_free(serial->in);
serial->in = NULL;
}
if (serial->port != INVALID_HANDLE_VALUE) {
if (serial->break_in_progress)
ClearCommBreak(serial->port);
CloseHandle(serial->port);
serial->port = INVALID_HANDLE_VALUE;
}
}
static int serial_gotdata(struct handle *h, void *data, int len)
{
Serial *serial = (Serial *)handle_get_privdata(h);
if (len <= 0) {
const char *error_msg;
/*
* Currently, len==0 should never happen because we're
* ignoring EOFs. However, it seems not totally impossible
* that this same back end might be usable to talk to named
* pipes or some other non-serial device, in which case EOF
* may become meaningful here.
*/
if (len == 0)
error_msg = "End of file reading from serial device";
else
error_msg = "Error reading from serial device";
serial_terminate(serial);
notify_remote_exit(serial->frontend);
logevent(serial->logctx, error_msg);
connection_fatal(serial->frontend, "%s", error_msg);
return 0; /* placate optimiser */
} else {
return from_backend(serial->frontend, 0, data, len);
}
}
static void serial_sentdata(struct handle *h, int new_backlog)
{
Serial *serial = (Serial *)handle_get_privdata(h);
if (new_backlog < 0) {
const char *error_msg = "Error writing to serial device";
serial_terminate(serial);
notify_remote_exit(serial->frontend);
logevent(serial->logctx, error_msg);
connection_fatal(serial->frontend, "%s", error_msg);
} else {
serial->bufsize = new_backlog;
}
}
static const char *serial_configure(Serial *serial, HANDLE serport, Conf *conf)
{
DCB dcb;
COMMTIMEOUTS timeouts;
/*
* Set up the serial port parameters. If we can't even
* GetCommState, we ignore the problem on the grounds that the
* user might have pointed us at some other type of two-way
* device instead of a serial port.
*/
if (GetCommState(serport, &dcb)) {
const char *str;
/*
* Boilerplate.
*/
dcb.fBinary = TRUE;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fDsrSensitivity = FALSE;
dcb.fTXContinueOnXoff = FALSE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
dcb.fErrorChar = FALSE;
dcb.fNull = FALSE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fAbortOnError = FALSE;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
/*
* Configurable parameters.
*/
dcb.BaudRate = conf_get_int(conf, CONF_serspeed);
logeventf(serial->logctx, "Configuring baud rate %lu", dcb.BaudRate);
dcb.ByteSize = conf_get_int(conf, CONF_serdatabits);
logeventf(serial->logctx, "Configuring %u data bits", dcb.ByteSize);
switch (conf_get_int(conf, CONF_serstopbits)) {
case 2: dcb.StopBits = ONESTOPBIT; str = "1"; break;
case 3: dcb.StopBits = ONE5STOPBITS; str = "1.5"; break;
case 4: dcb.StopBits = TWOSTOPBITS; str = "2"; break;
default: return "Invalid number of stop bits (need 1, 1.5 or 2)";
}
logeventf(serial->logctx, "Configuring %s data bits", str);
switch (conf_get_int(conf, CONF_serparity)) {
case SER_PAR_NONE: dcb.Parity = NOPARITY; str = "no"; break;
case SER_PAR_ODD: dcb.Parity = ODDPARITY; str = "odd"; break;
case SER_PAR_EVEN: dcb.Parity = EVENPARITY; str = "even"; break;
case SER_PAR_MARK: dcb.Parity = MARKPARITY; str = "mark"; break;
case SER_PAR_SPACE: dcb.Parity = SPACEPARITY; str = "space"; break;
}
logeventf(serial->logctx, "Configuring %s parity", str);
switch (conf_get_int(conf, CONF_serflow)) {
case SER_FLOW_NONE:
str = "no";
break;
case SER_FLOW_XONXOFF:
dcb.fOutX = dcb.fInX = TRUE;
str = "XON/XOFF";
break;
case SER_FLOW_RTSCTS:
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fOutxCtsFlow = TRUE;
str = "RTS/CTS";
break;
case SER_FLOW_DSRDTR:
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fOutxDsrFlow = TRUE;
str = "DSR/DTR";
break;
}
logeventf(serial->logctx, "Configuring %s flow control", str);
if (!SetCommState(serport, &dcb))
return "Unable to configure serial port";
timeouts.ReadIntervalTimeout = 1;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts(serport, &timeouts))
return "Unable to configure serial timeouts";
}
return NULL;
}
/*
* Called to set up the serial connection.
*
* Returns an error message, or NULL on success.
*
* Also places the canonical host name into `realhost'. It must be
* freed by the caller.
*/
static const char *serial_init(Frontend *frontend, Backend **backend_handle,
LogContext *logctx, Conf *conf,
const char *host, int port,
char **realhost, int nodelay, int keepalive)
{
Serial *serial;
HANDLE serport;
const char *err;
char *serline;
serial = snew(Serial);
serial->port = INVALID_HANDLE_VALUE;
serial->out = serial->in = NULL;
serial->bufsize = 0;
serial->break_in_progress = FALSE;
serial->backend.vt = &serial_backend;
*backend_handle = &serial->backend;
serial->frontend = frontend;
serial->logctx = logctx;
serline = conf_get_str(conf, CONF_serline);
logeventf(serial->logctx, "Opening serial device %s", serline);
{
/*
* Munge the string supplied by the user into a Windows filename.
*
* Windows supports opening a few "legacy" devices (including
* COM1-9) by specifying their names verbatim as a filename to
* open. (Thus, no files can ever have these names. See
* <http://msdn2.microsoft.com/en-us/library/aa365247.aspx>
* ("Naming a File") for the complete list of reserved names.)
*
* However, this doesn't let you get at devices COM10 and above.
* For that, you need to specify a filename like "\\.\COM10".
* This is also necessary for special serial and serial-like
* devices such as \\.\WCEUSBSH001. It also works for the "legacy"
* names, so you can do \\.\COM1 (verified as far back as Win95).
* See <http://msdn2.microsoft.com/en-us/library/aa363858.aspx>
* (CreateFile() docs).
*
* So, we believe that prepending "\\.\" should always be the
* Right Thing. However, just in case someone finds something to
* talk to that doesn't exist under there, if the serial line
* contains a backslash, we use it verbatim. (This also lets
* existing configurations using \\.\ continue working.)
*/
char *serfilename =
dupprintf("%s%s", strchr(serline, '\\') ? "" : "\\\\.\\", serline);
serport = CreateFile(serfilename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
sfree(serfilename);
}
if (serport == INVALID_HANDLE_VALUE)
return "Unable to open serial port";
err = serial_configure(serial, serport, conf);
if (err)
return err;
serial->port = serport;
serial->out = handle_output_new(serport, serial_sentdata, serial,
HANDLE_FLAG_OVERLAPPED);
serial->in = handle_input_new(serport, serial_gotdata, serial,
HANDLE_FLAG_OVERLAPPED |
HANDLE_FLAG_IGNOREEOF |
HANDLE_FLAG_UNITBUFFER);
*realhost = dupstr(serline);
/*
* Specials are always available.
*/
update_specials_menu(serial->frontend);
return NULL;
}
static void serial_free(Backend *be)
{
Serial *serial = container_of(be, Serial, backend);
serial_terminate(serial);
expire_timer_context(serial);
sfree(serial);
}
static void serial_reconfig(Backend *be, Conf *conf)
{
Serial *serial = container_of(be, Serial, backend);
serial_configure(serial, serial->port, conf);
/*
* FIXME: what should we do if that call returned a non-NULL error
* message?
*/
}
/*
* Called to send data down the serial connection.
*/
static int serial_send(Backend *be, const char *buf, int len)
{
Serial *serial = container_of(be, Serial, backend);
if (serial->out == NULL)
return 0;
serial->bufsize = handle_write(serial->out, buf, len);
return serial->bufsize;
}
/*
* Called to query the current sendability status.
*/
static int serial_sendbuffer(Backend *be)
{
Serial *serial = container_of(be, Serial, backend);
return serial->bufsize;
}
/*
* Called to set the size of the window
*/
static void serial_size(Backend *be, int width, int height)
{
/* Do nothing! */
return;
}
static void serbreak_timer(void *ctx, unsigned long now)
{
Serial *serial = (Serial *)ctx;
if (now == serial->clearbreak_time && serial->port) {
ClearCommBreak(serial->port);
serial->break_in_progress = FALSE;
logevent(serial->logctx, "Finished serial break");
}
}
/*
* Send serial special codes.
*/
static void serial_special(Backend *be, SessionSpecialCode code, int arg)
{
Serial *serial = container_of(be, Serial, backend);
if (serial->port && code == SS_BRK) {
logevent(serial->logctx, "Starting serial break at user request");
SetCommBreak(serial->port);
/*
* To send a serial break on Windows, we call SetCommBreak
* to begin the break, then wait a bit, and then call
* ClearCommBreak to finish it. Hence, I must use timing.c
* to arrange a callback when it's time to do the latter.
*
* SUS says that a default break length must be between 1/4
* and 1/2 second. FreeBSD apparently goes with 2/5 second,
* and so will I.
*/
serial->clearbreak_time =
schedule_timer(TICKSPERSEC * 2 / 5, serbreak_timer, serial);
serial->break_in_progress = TRUE;
}
return;
}
/*
* Return a list of the special codes that make sense in this
* protocol.
*/
static const SessionSpecial *serial_get_specials(Backend *be)
{
static const SessionSpecial specials[] = {
{"Break", SS_BRK},
{NULL, SS_EXITMENU}
};
return specials;
}
static int serial_connected(Backend *be)
{
return 1; /* always connected */
}
static int serial_sendok(Backend *be)
{
return 1;
}
static void serial_unthrottle(Backend *be, int backlog)
{
Serial *serial = container_of(be, Serial, backend);
if (serial->in)
handle_unthrottle(serial->in, backlog);
}
static int serial_ldisc(Backend *be, int option)
{
/*
* Local editing and local echo are off by default.
*/
return 0;
}
static void serial_provide_ldisc(Backend *be, Ldisc *ldisc)
{
/* This is a stub. */
}
static int serial_exitcode(Backend *be)
{
Serial *serial = container_of(be, Serial, backend);
if (serial->port != INVALID_HANDLE_VALUE)
return -1; /* still connected */
else
/* Exit codes are a meaningless concept with serial ports */
return INT_MAX;
}
/*
* cfg_info for Serial does nothing at all.
*/
static int serial_cfg_info(Backend *be)
{
return 0;
}
const struct BackendVtable serial_backend = {
serial_init,
serial_free,
serial_reconfig,
serial_send,
serial_sendbuffer,
serial_size,
serial_special,
serial_get_specials,
serial_connected,
serial_exitcode,
serial_sendok,
serial_ldisc,
serial_provide_ldisc,
serial_unthrottle,
serial_cfg_info,
NULL /* test_for_upstream */,
"serial",
PROT_SERIAL,
0
};