2 * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
12 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
14 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
17 ret = cmdline_get_passwd_input(p, in, inlen);
19 ret = console_get_userpass_input(p, in, inlen);
23 void platform_get_x11_auth(struct X11Display *display, Conf *conf)
25 /* Do nothing, therefore no auth. */
27 const int platform_uses_x11_unix_by_default = TRUE;
29 /* ----------------------------------------------------------------------
30 * File access abstraction.
34 * Set local current directory. Returns NULL on success, or else an
35 * error message which must be freed after printing.
37 char *psftp_lcd(char *dir)
41 if (!SetCurrentDirectory(dir)) {
44 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
45 FORMAT_MESSAGE_FROM_SYSTEM |
46 FORMAT_MESSAGE_IGNORE_INSERTS,
48 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
49 (LPTSTR)&message, 0, NULL);
50 i = strcspn((char *)message, "\n");
51 ret = dupprintf("%.*s", i, (LPCTSTR)message);
59 * Get local current directory. Returns a string which must be
62 char *psftp_getcwd(void)
64 char *ret = snewn(256, char);
65 int len = GetCurrentDirectory(256, ret);
67 ret = sresize(ret, len, char);
68 GetCurrentDirectory(len, ret);
72 #define TIME_POSIX_TO_WIN(t, ft) do { \
74 uli.QuadPart = ((ULONGLONG)(t) + 11644473600ull) * 10000000ull; \
75 (ft).dwLowDateTime = uli.LowPart; \
76 (ft).dwHighDateTime = uli.HighPart; \
78 #define TIME_WIN_TO_POSIX(ft, t) do { \
80 uli.LowPart = (ft).dwLowDateTime; \
81 uli.HighPart = (ft).dwHighDateTime; \
82 uli.QuadPart = uli.QuadPart / 10000000ull - 11644473600ull; \
83 (t) = (unsigned long) uli.QuadPart; \
90 RFile *open_existing_file(const char *name, uint64 *size,
91 unsigned long *mtime, unsigned long *atime,
97 h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
99 if (h == INVALID_HANDLE_VALUE)
107 lo = GetFileSize(h, &hi);
112 if (mtime || atime) {
113 FILETIME actime, wrtime;
114 GetFileTime(h, NULL, &actime, &wrtime);
116 TIME_WIN_TO_POSIX(actime, *atime);
118 TIME_WIN_TO_POSIX(wrtime, *mtime);
127 int read_from_file(RFile *f, void *buffer, int length)
131 ret = ReadFile(f->h, buffer, length, &read, NULL);
133 return -1; /* error */
138 void close_rfile(RFile *f)
148 WFile *open_new_file(const char *name, long perms)
153 h = CreateFile(name, GENERIC_WRITE, 0, NULL,
154 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
155 if (h == INVALID_HANDLE_VALUE)
164 WFile *open_existing_wfile(const char *name, uint64 *size)
169 h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
170 OPEN_EXISTING, 0, 0);
171 if (h == INVALID_HANDLE_VALUE)
179 lo = GetFileSize(h, &hi);
187 int write_to_file(WFile *f, void *buffer, int length)
191 ret = WriteFile(f->h, buffer, length, &written, NULL);
193 return -1; /* error */
198 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
200 FILETIME actime, wrtime;
201 TIME_POSIX_TO_WIN(atime, actime);
202 TIME_POSIX_TO_WIN(mtime, wrtime);
203 SetFileTime(f->h, NULL, &actime, &wrtime);
206 void close_wfile(WFile *f)
212 /* Seek offset bytes through file, from whence, where whence is
213 FROM_START, FROM_CURRENT, or FROM_END */
214 int seek_file(WFile *f, uint64 offset, int whence)
220 movemethod = FILE_BEGIN;
223 movemethod = FILE_CURRENT;
226 movemethod = FILE_END;
233 LONG lo = offset.lo, hi = offset.hi;
234 SetFilePointer(f->h, lo, &hi, movemethod);
237 if (GetLastError() != NO_ERROR)
243 uint64 get_file_posn(WFile *f)
248 lo = SetFilePointer(f->h, 0L, &hi, FILE_CURRENT);
255 int file_type(const char *name)
258 attr = GetFileAttributes(name);
259 /* We know of no `weird' files under Windows. */
260 if (attr == (DWORD)-1)
261 return FILE_TYPE_NONEXISTENT;
262 else if (attr & FILE_ATTRIBUTE_DIRECTORY)
263 return FILE_TYPE_DIRECTORY;
265 return FILE_TYPE_FILE;
273 DirHandle *open_directory(const char *name)
276 WIN32_FIND_DATA fdat;
280 /* Enumerate files in dir `foo'. */
281 findfile = dupcat(name, "/*", NULL);
282 h = FindFirstFile(findfile, &fdat);
283 if (h == INVALID_HANDLE_VALUE)
287 ret = snew(DirHandle);
289 ret->name = dupstr(fdat.cFileName);
293 char *read_filename(DirHandle *dir)
298 WIN32_FIND_DATA fdat;
299 int ok = FindNextFile(dir->h, &fdat);
303 dir->name = dupstr(fdat.cFileName);
307 if (dir->name[0] == '.' &&
308 (dir->name[1] == '\0' ||
309 (dir->name[1] == '.' && dir->name[2] == '\0'))) {
314 } while (!dir->name);
317 char *ret = dir->name;
324 void close_directory(DirHandle *dir)
332 int test_wildcard(const char *name, int cmdline)
335 WIN32_FIND_DATA fdat;
337 /* First see if the exact name exists. */
338 if (GetFileAttributes(name) != (DWORD)-1)
339 return WCTYPE_FILENAME;
341 /* Otherwise see if a wildcard match finds anything. */
342 fh = FindFirstFile(name, &fdat);
343 if (fh == INVALID_HANDLE_VALUE)
344 return WCTYPE_NONEXISTENT;
347 return WCTYPE_WILDCARD;
350 struct WildcardMatcher {
356 char *stripslashes(const char *str, int local)
361 * On Windows, \ / : are all path component separators.
365 p = strchr(str, ':');
369 p = strrchr(str, '/');
373 p = strrchr(str, '\\');
380 WildcardMatcher *begin_wildcard_matching(const char *name)
383 WIN32_FIND_DATA fdat;
384 WildcardMatcher *ret;
387 h = FindFirstFile(name, &fdat);
388 if (h == INVALID_HANDLE_VALUE)
391 ret = snew(WildcardMatcher);
393 ret->srcpath = dupstr(name);
394 last = stripslashes(ret->srcpath, 1);
396 if (fdat.cFileName[0] == '.' &&
397 (fdat.cFileName[1] == '\0' ||
398 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
401 ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
406 char *wildcard_get_filename(WildcardMatcher *dir)
409 WIN32_FIND_DATA fdat;
410 int ok = FindNextFile(dir->h, &fdat);
415 if (fdat.cFileName[0] == '.' &&
416 (fdat.cFileName[1] == '\0' ||
417 (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
420 dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
424 char *ret = dir->name;
431 void finish_wildcard_matching(WildcardMatcher *dir)
440 int vet_filename(const char *name)
442 if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
445 if (!name[strspn(name, ".")]) /* entirely composed of dots */
451 int create_directory(const char *name)
453 return CreateDirectory(name, NULL) != 0;
456 char *dir_file_cat(const char *dir, const char *file)
458 return dupcat(dir, "\\", file, NULL);
461 /* ----------------------------------------------------------------------
462 * Platform-specific network handling.
466 * Be told what socket we're supposed to be using.
468 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
469 static HANDLE netevent = INVALID_HANDLE_VALUE;
470 char *do_select(SOCKET skt, int startup)
474 sftp_ssh_socket = skt;
476 sftp_ssh_socket = INVALID_SOCKET;
478 if (p_WSAEventSelect) {
480 events = (FD_CONNECT | FD_READ | FD_WRITE |
481 FD_OOB | FD_CLOSE | FD_ACCEPT);
482 netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
486 if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
487 switch (p_WSAGetLastError()) {
489 return "Network is down";
491 return "WSAEventSelect(): unknown error";
497 extern int select_result(WPARAM, LPARAM);
499 int do_eventsel_loop(HANDLE other_event)
501 int n, nhandles, nallhandles, netindex, otherindex;
502 unsigned long next, then;
507 unsigned long now = GETTICKCOUNT();
509 if (toplevel_callback_pending()) {
512 } else if (run_timers(now, &next)) {
514 now = GETTICKCOUNT();
515 if (now - then > next - then)
521 /* no need to initialise next here because we can never get
525 handles = handle_get_events(&nhandles);
526 handles = sresize(handles, nhandles+2, HANDLE);
527 nallhandles = nhandles;
529 if (netevent != INVALID_HANDLE_VALUE)
530 handles[netindex = nallhandles++] = netevent;
533 if (other_event != INVALID_HANDLE_VALUE)
534 handles[otherindex = nallhandles++] = other_event;
538 n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
540 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
541 handle_got_event(handles[n - WAIT_OBJECT_0]);
542 } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) {
543 WSANETWORKEVENTS things;
545 extern SOCKET first_socket(int *), next_socket(int *);
546 extern int select_result(WPARAM, LPARAM);
550 * We must not call select_result() for any socket
551 * until we have finished enumerating within the
552 * tree. This is because select_result() may close
553 * the socket and modify the tree.
555 /* Count the active sockets. */
557 for (socket = first_socket(&socketstate);
558 socket != INVALID_SOCKET;
559 socket = next_socket(&socketstate)) i++;
561 /* Expand the buffer if necessary. */
562 sklist = snewn(i, SOCKET);
564 /* Retrieve the sockets into sklist. */
566 for (socket = first_socket(&socketstate);
567 socket != INVALID_SOCKET;
568 socket = next_socket(&socketstate)) {
569 sklist[skcount++] = socket;
572 /* Now we're done enumerating; go through the list. */
573 for (i = 0; i < skcount; i++) {
576 wp = (WPARAM) socket;
577 if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
578 static const struct { int bit, mask; } eventtypes[] = {
579 {FD_CONNECT_BIT, FD_CONNECT},
580 {FD_READ_BIT, FD_READ},
581 {FD_CLOSE_BIT, FD_CLOSE},
582 {FD_OOB_BIT, FD_OOB},
583 {FD_WRITE_BIT, FD_WRITE},
584 {FD_ACCEPT_BIT, FD_ACCEPT},
588 noise_ultralight(socket);
589 noise_ultralight(things.lNetworkEvents);
591 for (e = 0; e < lenof(eventtypes); e++)
592 if (things.lNetworkEvents & eventtypes[e].mask) {
594 int err = things.iErrorCode[eventtypes[e].bit];
595 lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
596 select_result(wp, lp);
606 run_toplevel_callbacks();
608 if (n == WAIT_TIMEOUT) {
611 now = GETTICKCOUNT();
614 if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
621 * Wait for some network data and process it.
623 * We have two variants of this function. One uses select() so that
624 * it's compatible with WinSock 1. The other uses WSAEventSelect
625 * and MsgWaitForMultipleObjects, so that we can consistently use
626 * WSAEventSelect throughout; this enables us to also implement
627 * ssh_sftp_get_cmdline() using a parallel mechanism.
629 int ssh_sftp_loop_iteration(void)
631 if (p_WSAEventSelect == NULL) {
634 unsigned long now = GETTICKCOUNT(), then;
636 if (sftp_ssh_socket == INVALID_SOCKET)
637 return -1; /* doom */
639 if (socket_writable(sftp_ssh_socket))
640 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
645 struct timeval tv, *ptv;
647 if (run_timers(now, &next)) {
649 now = GETTICKCOUNT();
650 if (now - then > next - then)
654 tv.tv_sec = ticks / 1000;
655 tv.tv_usec = ticks % 1000 * 1000;
662 FD_SET(sftp_ssh_socket, &readfds);
663 ret = p_select(1, &readfds, NULL, NULL, ptv);
666 return -1; /* doom */
670 now = GETTICKCOUNT();
674 select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
678 return do_eventsel_loop(INVALID_HANDLE_VALUE);
683 * Read a command line from standard input.
685 * In the presence of WinSock 2, we can use WSAEventSelect to
686 * mediate between the socket and stdin, meaning we can send
687 * keepalives and respond to server events even while waiting at
688 * the PSFTP command prompt. Without WS2, we fall back to a simple
691 struct command_read_ctx {
696 static DWORD WINAPI command_read_thread(void *param)
698 struct command_read_ctx *ctx = (struct command_read_ctx *) param;
700 ctx->line = fgetline(stdin);
702 SetEvent(ctx->event);
707 char *ssh_sftp_get_cmdline(const char *prompt, int no_fds_ok)
710 struct command_read_ctx actx, *ctx = &actx;
714 fputs(prompt, stdout);
717 if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
718 p_WSAEventSelect == NULL) {
719 return fgetline(stdin); /* very simple */
723 * Create a second thread to read from stdin. Process network
724 * and timing events until it terminates.
726 ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
729 hThread = CreateThread(NULL, 0, command_read_thread, ctx, 0, &threadid);
731 CloseHandle(ctx->event);
732 fprintf(stderr, "Unable to create command input thread\n");
737 ret = do_eventsel_loop(ctx->event);
739 /* Error return can only occur if netevent==NULL, and it ain't. */
743 CloseHandle(hThread);
744 CloseHandle(ctx->event);
749 void platform_psftp_post_option_setup(void)
751 #if !defined UNPROTECT && !defined NO_SECURITY
753 * Protect our process.
757 if (!setprocessacl(error)) {
758 char *message = dupprintf("Could not restrict process ACL: %s",
760 logevent(NULL, message);
768 /* ----------------------------------------------------------------------
769 * Main program. Parse arguments etc.
771 int main(int argc, char *argv[])
775 ret = psftp_main(argc, argv);