1
0
mirror of https://git.tartarus.org/simon/putty.git synced 2025-01-10 01:48:00 +00:00
putty-source/unix/uxsftp.c
Simon Tatham 3214563d8e 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-03 13:45:00 +00:00

627 lines
12 KiB
C

/*
* uxsftp.c: the Unix-specific parts of PSFTP and PSCP.
*/
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <utime.h>
#include <errno.h>
#include <assert.h>
#include <glob.h>
#ifndef HAVE_NO_SYS_SELECT_H
#include <sys/select.h>
#endif
#include "putty.h"
#include "ssh.h"
#include "psftp.h"
/*
* In PSFTP our selects are synchronous, so these functions are
* empty stubs.
*/
uxsel_id *uxsel_input_add(int fd, int rwx) { return NULL; }
void uxsel_input_remove(uxsel_id *id) { }
char *x_get_default(const char *key)
{
return NULL; /* this is a stub */
}
void platform_get_x11_auth(struct X11Display *display, Conf *conf)
{
/* Do nothing, therefore no auth. */
}
const bool platform_uses_x11_unix_by_default = true;
/*
* Default settings that are specific to PSFTP.
*/
char *platform_default_s(const char *name)
{
return NULL;
}
bool platform_default_b(const char *name, bool def)
{
return def;
}
int platform_default_i(const char *name, int def)
{
return def;
}
FontSpec *platform_default_fontspec(const char *name)
{
return fontspec_new("");
}
Filename *platform_default_filename(const char *name)
{
if (!strcmp(name, "LogFileName"))
return filename_from_str("putty.log");
else
return filename_from_str("");
}
int filexfer_get_userpass_input(Seat *seat, prompts_t *p, bufchain *input)
{
int ret;
ret = cmdline_get_passwd_input(p);
if (ret == -1)
ret = console_get_userpass_input(p);
return ret;
}
/*
* Set local current directory. Returns NULL on success, or else an
* error message which must be freed after printing.
*/
char *psftp_lcd(char *dir)
{
if (chdir(dir) < 0)
return dupprintf("%s: chdir: %s", dir, strerror(errno));
else
return NULL;
}
/*
* Get local current directory. Returns a string which must be
* freed.
*/
char *psftp_getcwd(void)
{
char *buffer, *ret;
int size = 256;
buffer = snewn(size, char);
while (1) {
ret = getcwd(buffer, size);
if (ret != NULL)
return ret;
if (errno != ERANGE) {
sfree(buffer);
return dupprintf("[cwd unavailable: %s]", strerror(errno));
}
/*
* Otherwise, ERANGE was returned, meaning the buffer
* wasn't big enough.
*/
size = size * 3 / 2;
buffer = sresize(buffer, size, char);
}
}
struct RFile {
int fd;
};
RFile *open_existing_file(const char *name, uint64_t *size,
unsigned long *mtime, unsigned long *atime,
long *perms)
{
int fd;
RFile *ret;
fd = open(name, O_RDONLY);
if (fd < 0)
return NULL;
ret = snew(RFile);
ret->fd = fd;
if (size || mtime || atime || perms) {
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
fprintf(stderr, "%s: stat: %s\n", name, strerror(errno));
memset(&statbuf, 0, sizeof(statbuf));
}
if (size)
*size = statbuf.st_size;
if (mtime)
*mtime = statbuf.st_mtime;
if (atime)
*atime = statbuf.st_atime;
if (perms)
*perms = statbuf.st_mode;
}
return ret;
}
int read_from_file(RFile *f, void *buffer, int length)
{
return read(f->fd, buffer, length);
}
void close_rfile(RFile *f)
{
close(f->fd);
sfree(f);
}
struct WFile {
int fd;
char *name;
};
WFile *open_new_file(const char *name, long perms)
{
int fd;
WFile *ret;
fd = open(name, O_CREAT | O_TRUNC | O_WRONLY,
(mode_t)(perms ? perms : 0666));
if (fd < 0)
return NULL;
ret = snew(WFile);
ret->fd = fd;
ret->name = dupstr(name);
return ret;
}
WFile *open_existing_wfile(const char *name, uint64_t *size)
{
int fd;
WFile *ret;
fd = open(name, O_APPEND | O_WRONLY);
if (fd < 0)
return NULL;
ret = snew(WFile);
ret->fd = fd;
ret->name = dupstr(name);
if (size) {
struct stat statbuf;
if (fstat(fd, &statbuf) < 0) {
fprintf(stderr, "%s: stat: %s\n", name, strerror(errno));
memset(&statbuf, 0, sizeof(statbuf));
}
*size = statbuf.st_size;
}
return ret;
}
int write_to_file(WFile *f, void *buffer, int length)
{
char *p = (char *)buffer;
int so_far = 0;
/* Keep trying until we've really written as much as we can. */
while (length > 0) {
int ret = write(f->fd, p, length);
if (ret < 0)
return ret;
if (ret == 0)
break;
p += ret;
length -= ret;
so_far += ret;
}
return so_far;
}
void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
{
struct utimbuf ut;
ut.actime = atime;
ut.modtime = mtime;
utime(f->name, &ut);
}
/* Closes and frees the WFile */
void close_wfile(WFile *f)
{
close(f->fd);
sfree(f->name);
sfree(f);
}
/* Seek offset bytes through file, from whence, where whence is
FROM_START, FROM_CURRENT, or FROM_END */
int seek_file(WFile *f, uint64_t offset, int whence)
{
int lseek_whence;
switch (whence) {
case FROM_START:
lseek_whence = SEEK_SET;
break;
case FROM_CURRENT:
lseek_whence = SEEK_CUR;
break;
case FROM_END:
lseek_whence = SEEK_END;
break;
default:
return -1;
}
return lseek(f->fd, offset, lseek_whence) >= 0 ? 0 : -1;
}
uint64_t get_file_posn(WFile *f)
{
return lseek(f->fd, (off_t) 0, SEEK_CUR);
}
int file_type(const char *name)
{
struct stat statbuf;
if (stat(name, &statbuf) < 0) {
if (errno != ENOENT)
fprintf(stderr, "%s: stat: %s\n", name, strerror(errno));
return FILE_TYPE_NONEXISTENT;
}
if (S_ISREG(statbuf.st_mode))
return FILE_TYPE_FILE;
if (S_ISDIR(statbuf.st_mode))
return FILE_TYPE_DIRECTORY;
return FILE_TYPE_WEIRD;
}
struct DirHandle {
DIR *dir;
};
DirHandle *open_directory(const char *name)
{
DIR *dir;
DirHandle *ret;
dir = opendir(name);
if (!dir)
return NULL;
ret = snew(DirHandle);
ret->dir = dir;
return ret;
}
char *read_filename(DirHandle *dir)
{
struct dirent *de;
do {
de = readdir(dir->dir);
if (de == NULL)
return NULL;
} while ((de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0'))));
return dupstr(de->d_name);
}
void close_directory(DirHandle *dir)
{
closedir(dir->dir);
sfree(dir);
}
int test_wildcard(const char *name, bool cmdline)
{
struct stat statbuf;
if (stat(name, &statbuf) == 0) {
return WCTYPE_FILENAME;
} else if (cmdline) {
/*
* On Unix, we never need to parse wildcards coming from
* the command line, because the shell will have expanded
* them into a filename list already.
*/
return WCTYPE_NONEXISTENT;
} else {
glob_t globbed;
int ret = WCTYPE_NONEXISTENT;
if (glob(name, GLOB_ERR, NULL, &globbed) == 0) {
if (globbed.gl_pathc > 0)
ret = WCTYPE_WILDCARD;
globfree(&globbed);
}
return ret;
}
}
/*
* Actually return matching file names for a local wildcard.
*/
struct WildcardMatcher {
glob_t globbed;
int i;
};
WildcardMatcher *begin_wildcard_matching(const char *name) {
WildcardMatcher *ret = snew(WildcardMatcher);
if (glob(name, 0, NULL, &ret->globbed) < 0) {
sfree(ret);
return NULL;
}
ret->i = 0;
return ret;
}
char *wildcard_get_filename(WildcardMatcher *dir) {
if (dir->i < dir->globbed.gl_pathc) {
return dupstr(dir->globbed.gl_pathv[dir->i++]);
} else
return NULL;
}
void finish_wildcard_matching(WildcardMatcher *dir) {
globfree(&dir->globbed);
sfree(dir);
}
char *stripslashes(const char *str, bool local)
{
char *p;
/*
* On Unix, we do the same thing regardless of the 'local'
* parameter.
*/
p = strrchr(str, '/');
if (p) str = p+1;
return (char *)str;
}
bool vet_filename(const char *name)
{
if (strchr(name, '/'))
return false;
if (name[0] == '.' && (!name[1] || (name[1] == '.' && !name[2])))
return false;
return true;
}
bool create_directory(const char *name)
{
return mkdir(name, 0777) == 0;
}
char *dir_file_cat(const char *dir, const char *file)
{
return dupcat(dir, "/", file, NULL);
}
/*
* Do a select() between all currently active network fds and
* optionally stdin.
*/
static int ssh_sftp_do_select(bool include_stdin, bool no_fds_ok)
{
fd_set rset, wset, xset;
int i, fdcount, fdsize, *fdlist;
int fd, fdstate, rwx, ret, maxfd;
unsigned long now = GETTICKCOUNT();
unsigned long next;
bool done_something = false;
fdlist = NULL;
fdcount = fdsize = 0;
do {
/* Count the currently active fds. */
i = 0;
for (fd = first_fd(&fdstate, &rwx); fd >= 0;
fd = next_fd(&fdstate, &rwx)) i++;
if (i < 1 && !no_fds_ok)
return -1; /* doom */
/* Expand the fdlist buffer if necessary. */
if (i > fdsize) {
fdsize = i + 16;
fdlist = sresize(fdlist, fdsize, int);
}
FD_ZERO(&rset);
FD_ZERO(&wset);
FD_ZERO(&xset);
maxfd = 0;
/*
* Add all currently open fds to the select sets, and store
* them in fdlist as well.
*/
fdcount = 0;
for (fd = first_fd(&fdstate, &rwx); fd >= 0;
fd = next_fd(&fdstate, &rwx)) {
fdlist[fdcount++] = fd;
if (rwx & 1)
FD_SET_MAX(fd, maxfd, rset);
if (rwx & 2)
FD_SET_MAX(fd, maxfd, wset);
if (rwx & 4)
FD_SET_MAX(fd, maxfd, xset);
}
if (include_stdin)
FD_SET_MAX(0, maxfd, rset);
if (toplevel_callback_pending()) {
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
ret = select(maxfd, &rset, &wset, &xset, &tv);
if (ret == 0)
done_something |= run_toplevel_callbacks();
} else if (run_timers(now, &next)) {
do {
unsigned long then;
long ticks;
struct timeval tv;
then = now;
now = GETTICKCOUNT();
if (now - then > next - then)
ticks = 0;
else
ticks = next - now;
tv.tv_sec = ticks / 1000;
tv.tv_usec = ticks % 1000 * 1000;
ret = select(maxfd, &rset, &wset, &xset, &tv);
if (ret == 0)
now = next;
else
now = GETTICKCOUNT();
} while (ret < 0 && errno == EINTR);
} else {
do {
ret = select(maxfd, &rset, &wset, &xset, NULL);
} while (ret < 0 && errno == EINTR);
}
} while (ret == 0 && !done_something);
if (ret < 0) {
perror("select");
exit(1);
}
for (i = 0; i < fdcount; i++) {
fd = fdlist[i];
/*
* We must process exceptional notifications before
* ordinary readability ones, or we may go straight
* past the urgent marker.
*/
if (FD_ISSET(fd, &xset))
select_result(fd, 4);
if (FD_ISSET(fd, &rset))
select_result(fd, 1);
if (FD_ISSET(fd, &wset))
select_result(fd, 2);
}
sfree(fdlist);
run_toplevel_callbacks();
return FD_ISSET(0, &rset) ? 1 : 0;
}
/*
* Wait for some network data and process it.
*/
int ssh_sftp_loop_iteration(void)
{
return ssh_sftp_do_select(false, false);
}
/*
* Read a PSFTP command line from stdin.
*/
char *ssh_sftp_get_cmdline(const char *prompt, bool no_fds_ok)
{
char *buf;
int buflen, bufsize, ret;
fputs(prompt, stdout);
fflush(stdout);
buf = NULL;
buflen = bufsize = 0;
while (1) {
ret = ssh_sftp_do_select(true, no_fds_ok);
if (ret < 0) {
printf("connection died\n");
sfree(buf);
return NULL; /* woop woop */
}
if (ret > 0) {
if (buflen >= bufsize) {
bufsize = buflen + 512;
buf = sresize(buf, bufsize, char);
}
ret = read(0, buf+buflen, 1);
if (ret < 0) {
perror("read");
sfree(buf);
return NULL;
}
if (ret == 0) {
/* eof on stdin; no error, but no answer either */
sfree(buf);
return NULL;
}
if (buf[buflen++] == '\n') {
/* we have a full line */
return buf;
}
}
}
}
void frontend_net_error_pending(void) {}
void platform_psftp_pre_conn_setup(void) {}
const bool buildinfo_gtk_relevant = false;
/*
* Main program: do platform-specific initialisation and then call
* psftp_main().
*/
int main(int argc, char *argv[])
{
uxsel_init();
return psftp_main(argc, argv);
}