2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
11 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
13 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
16 ret = cmdline_get_passwd_input(p, in, inlen);
18 ret = console_get_userpass_input(p, in, inlen);
22 void platform_get_x11_auth(struct X11Display *display, const Config *cfg)
24 /* Do nothing, therefore no auth. */
26 const int platform_uses_x11_unix_by_default = TRUE;
28 /* ----------------------------------------------------------------------
29 * File access abstraction.
33 * Set local current directory. Returns NULL on success, or else an
34 * error message which must be freed after printing.
36 char *psftp_lcd(char *dir)
40 if (!SetCurrentDirectory(dir)) {
43 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
44 FORMAT_MESSAGE_FROM_SYSTEM |
45 FORMAT_MESSAGE_IGNORE_INSERTS,
47 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
48 (LPTSTR)&message, 0, NULL);
49 i = strcspn((char *)message, "\n");
50 ret = dupprintf("%.*s", i, (LPCTSTR)message);
58 * Get local current directory. Returns a string which must be
61 char *psftp_getcwd(void)
63 char *ret = snewn(256, char);
64 int len = GetCurrentDirectory(256, ret);
66 ret = sresize(ret, len, char);
67 GetCurrentDirectory(len, ret);
71 #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
72 ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
73 #define TIME_WIN_TO_POSIX(ft, t) ((t) = (unsigned long) \
74 ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
80 RFile *open_existing_file(char *name, uint64 *size,
81 unsigned long *mtime, unsigned long *atime)
86 h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
88 if (h == INVALID_HANDLE_VALUE)
95 size->lo=GetFileSize(h, &(size->hi));
98 FILETIME actime, wrtime;
99 GetFileTime(h, NULL, &actime, &wrtime);
101 TIME_WIN_TO_POSIX(actime, *atime);
103 TIME_WIN_TO_POSIX(wrtime, *mtime);
109 int read_from_file(RFile *f, void *buffer, int length)
112 ret = ReadFile(f->h, buffer, length, &read, NULL);
114 return -1; /* error */
119 void close_rfile(RFile *f)
129 WFile *open_new_file(char *name)
134 h = CreateFile(name, GENERIC_WRITE, 0, NULL,
135 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
136 if (h == INVALID_HANDLE_VALUE)
145 WFile *open_existing_wfile(char *name, uint64 *size)
150 h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
151 OPEN_EXISTING, 0, 0);
152 if (h == INVALID_HANDLE_VALUE)
159 size->lo=GetFileSize(h, &(size->hi));
164 int write_to_file(WFile *f, void *buffer, int length)
167 ret = WriteFile(f->h, buffer, length, &written, NULL);
169 return -1; /* error */
174 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
176 FILETIME actime, wrtime;
177 TIME_POSIX_TO_WIN(atime, actime);
178 TIME_POSIX_TO_WIN(mtime, wrtime);
179 SetFileTime(f->h, NULL, &actime, &wrtime);
182 void close_wfile(WFile *f)
188 /* Seek offset bytes through file, from whence, where whence is
189 FROM_START, FROM_CURRENT, or FROM_END */
190 int seek_file(WFile *f, uint64 offset, int whence)
196 movemethod = FILE_BEGIN;
199 movemethod = FILE_CURRENT;
202 movemethod = FILE_END;
208 SetFilePointer(f->h, offset.lo, &(offset.hi), movemethod);
210 if (GetLastError() != NO_ERROR)
216 uint64 get_file_posn(WFile *f)
221 ret.lo = SetFilePointer(f->h, 0L, &(ret.hi), FILE_CURRENT);
226 int file_type(char *name)
229 attr = GetFileAttributes(name);
230 /* We know of no `weird' files under Windows. */
231 if (attr == (DWORD)-1)
232 return FILE_TYPE_NONEXISTENT;
233 else if (attr & FILE_ATTRIBUTE_DIRECTORY)
234 return FILE_TYPE_DIRECTORY;
236 return FILE_TYPE_FILE;
244 DirHandle *open_directory(char *name)
247 WIN32_FIND_DATA fdat;
251 /* Enumerate files in dir `foo'. */
252 findfile = dupcat(name, "/*", NULL);
253 h = FindFirstFile(findfile, &fdat);
254 if (h == INVALID_HANDLE_VALUE)
258 ret = snew(DirHandle);
260 ret->name = dupstr(fdat.cFileName);
264 char *read_filename(DirHandle *dir)
269 WIN32_FIND_DATA fdat;
270 int ok = FindNextFile(dir->h, &fdat);
274 dir->name = dupstr(fdat.cFileName);
278 if (dir->name[0] == '.' &&
279 (dir->name[1] == '\0' ||
280 (dir->name[1] == '.' && dir->name[2] == '\0'))) {
285 } while (!dir->name);
288 char *ret = dir->name;
295 void close_directory(DirHandle *dir)
303 int test_wildcard(char *name, int cmdline)
306 WIN32_FIND_DATA fdat;
308 /* First see if the exact name exists. */
309 if (GetFileAttributes(name) != (DWORD)-1)
310 return WCTYPE_FILENAME;
312 /* Otherwise see if a wildcard match finds anything. */
313 fh = FindFirstFile(name, &fdat);
314 if (fh == INVALID_HANDLE_VALUE)
315 return WCTYPE_NONEXISTENT;
318 return WCTYPE_WILDCARD;
321 struct WildcardMatcher {
328 * Return a pointer to the portion of str that comes after the last
329 * slash (or backslash or colon, if `local' is TRUE).
331 static char *stripslashes(char *str, int local)
336 p = strchr(str, ':');
340 p = strrchr(str, '/');
344 p = strrchr(str, '\\');
351 WildcardMatcher *begin_wildcard_matching(char *name)
354 WIN32_FIND_DATA fdat;
355 WildcardMatcher *ret;
358 h = FindFirstFile(name, &fdat);
359 if (h == INVALID_HANDLE_VALUE)
362 ret = snew(WildcardMatcher);
364 ret->srcpath = dupstr(name);
365 last = stripslashes(ret->srcpath, 1);
367 if (fdat.cFileName[0] == '.' &&
368 (fdat.cFileName[1] == '\0' ||
369 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
372 ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
377 char *wildcard_get_filename(WildcardMatcher *dir)
380 WIN32_FIND_DATA fdat;
381 int ok = FindNextFile(dir->h, &fdat);
386 if (fdat.cFileName[0] == '.' &&
387 (fdat.cFileName[1] == '\0' ||
388 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
391 dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
395 char *ret = dir->name;
402 void finish_wildcard_matching(WildcardMatcher *dir)
411 int vet_filename(char *name)
413 if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
416 if (!name[strspn(name, ".")]) /* entirely composed of dots */
422 int create_directory(char *name)
424 return CreateDirectory(name, NULL) != 0;
427 char *dir_file_cat(char *dir, char *file)
429 return dupcat(dir, "\\", file, NULL);
432 /* ----------------------------------------------------------------------
433 * Platform-specific network handling.
437 * Be told what socket we're supposed to be using.
439 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
440 static HANDLE netevent = INVALID_HANDLE_VALUE;
441 char *do_select(SOCKET skt, int startup)
445 sftp_ssh_socket = skt;
447 sftp_ssh_socket = INVALID_SOCKET;
449 if (p_WSAEventSelect) {
451 events = (FD_CONNECT | FD_READ | FD_WRITE |
452 FD_OOB | FD_CLOSE | FD_ACCEPT);
453 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
457 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
458 switch (p_WSAGetLastError()) {
460 return "Network is down";
462 return "WSAEventSelect(): unknown error";
468 extern int select_result(WPARAM, LPARAM);
470 int do_eventsel_loop(HANDLE other_event)
472 int n, nhandles, nallhandles, netindex, otherindex;
477 long now = GETTICKCOUNT();
479 if (run_timers(now, &next)) {
480 ticks = next - GETTICKCOUNT();
481 if (ticks < 0) ticks = 0; /* just in case */
486 handles = handle_get_events(&nhandles);
487 handles = sresize(handles, nhandles+2, HANDLE);
488 nallhandles = nhandles;
490 if (netevent != INVALID_HANDLE_VALUE)
491 handles[netindex = nallhandles++] = netevent;
494 if (other_event != INVALID_HANDLE_VALUE)
495 handles[otherindex = nallhandles++] = other_event;
499 n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
501 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
502 handle_got_event(handles[n - WAIT_OBJECT_0]);
503 } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) {
504 WSANETWORKEVENTS things;
506 extern SOCKET first_socket(int *), next_socket(int *);
507 extern int select_result(WPARAM, LPARAM);
511 * We must not call select_result() for any socket
512 * until we have finished enumerating within the
513 * tree. This is because select_result() may close
514 * the socket and modify the tree.
516 /* Count the active sockets. */
518 for (socket = first_socket(&socketstate);
519 socket != INVALID_SOCKET;
520 socket = next_socket(&socketstate)) i++;
522 /* Expand the buffer if necessary. */
523 sklist = snewn(i, SOCKET);
525 /* Retrieve the sockets into sklist. */
527 for (socket = first_socket(&socketstate);
528 socket != INVALID_SOCKET;
529 socket = next_socket(&socketstate)) {
530 sklist[skcount++] = socket;
533 /* Now we're done enumerating; go through the list. */
534 for (i = 0; i < skcount; i++) {
537 wp = (WPARAM) socket;
538 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
539 static const struct { int bit, mask; } eventtypes[] = {
540 {FD_CONNECT_BIT, FD_CONNECT},
541 {FD_READ_BIT, FD_READ},
542 {FD_CLOSE_BIT, FD_CLOSE},
543 {FD_OOB_BIT, FD_OOB},
544 {FD_WRITE_BIT, FD_WRITE},
545 {FD_ACCEPT_BIT, FD_ACCEPT},
549 noise_ultralight(socket);
550 noise_ultralight(things.lNetworkEvents);
552 for (e = 0; e < lenof(eventtypes); e++)
553 if (things.lNetworkEvents & eventtypes[e].mask) {
555 int err = things.iErrorCode[eventtypes[e].bit];
556 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
557 select_result(wp, lp);
567 if (n == WAIT_TIMEOUT) {
570 now = GETTICKCOUNT();
573 if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
580 * Wait for some network data and process it.
582 * We have two variants of this function. One uses select() so that
583 * it's compatible with WinSock 1. The other uses WSAEventSelect
584 * and MsgWaitForMultipleObjects, so that we can consistently use
585 * WSAEventSelect throughout; this enables us to also implement
586 * ssh_sftp_get_cmdline() using a parallel mechanism.
588 int ssh_sftp_loop_iteration(void)
590 if (p_WSAEventSelect == NULL) {
593 long now = GETTICKCOUNT();
595 if (sftp_ssh_socket == INVALID_SOCKET)
596 return -1; /* doom */
598 if (socket_writable(sftp_ssh_socket))
599 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
603 struct timeval tv, *ptv;
605 if (run_timers(now, &next)) {
606 ticks = next - GETTICKCOUNT();
608 ticks = 1; /* just in case */
609 tv.tv_sec = ticks / 1000;
610 tv.tv_usec = ticks % 1000 * 1000;
617 FD_SET(sftp_ssh_socket, &readfds);
618 ret = p_select(1, &readfds, NULL, NULL, ptv);
621 return -1; /* doom */
625 now = GETTICKCOUNT();
629 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
633 return do_eventsel_loop(INVALID_HANDLE_VALUE);
638 * Read a command line from standard input.
640 * In the presence of WinSock 2, we can use WSAEventSelect to
641 * mediate between the socket and stdin, meaning we can send
642 * keepalives and respond to server events even while waiting at
643 * the PSFTP command prompt. Without WS2, we fall back to a simple
646 struct command_read_ctx {
651 static DWORD WINAPI command_read_thread(void *param)
653 struct command_read_ctx *ctx = (struct command_read_ctx *) param;
655 ctx->line = fgetline(stdin);
657 SetEvent(ctx->event);
662 char *ssh_sftp_get_cmdline(char *prompt, int no_fds_ok)
665 struct command_read_ctx actx, *ctx = &actx;
668 fputs(prompt, stdout);
671 if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
672 p_WSAEventSelect == NULL) {
673 return fgetline(stdin); /* very simple */
677 * Create a second thread to read from stdin. Process network
678 * and timing events until it terminates.
680 ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
683 if (!CreateThread(NULL, 0, command_read_thread,
684 ctx, 0, &threadid)) {
685 fprintf(stderr, "Unable to create command input thread\n");
690 ret = do_eventsel_loop(ctx->event);
692 /* Error return can only occur if netevent==NULL, and it ain't. */
699 /* ----------------------------------------------------------------------
700 * Main program. Parse arguments etc.
702 int main(int argc, char *argv[])
706 ret = psftp_main(argc, argv);