]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winsftp.c
c5555d53f9aa159dcbdb2185c9aadfdd9edb5a16
[PuTTY.git] / windows / winsftp.c
1 /*
2  * winsftp.c: the Windows-specific parts of PSFTP and PSCP.
3  */
4
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "psftp.h"
9 #include "ssh.h"
10 #include "int64.h"
11
12 char *get_ttymode(void *frontend, const char *mode) { return NULL; }
13
14 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
15 {
16     int ret;
17     ret = cmdline_get_passwd_input(p, in, inlen);
18     if (ret == -1)
19         ret = console_get_userpass_input(p, in, inlen);
20     return ret;
21 }
22
23 void platform_get_x11_auth(struct X11Display *display, const Config *cfg)
24 {
25     /* Do nothing, therefore no auth. */
26 }
27 const int platform_uses_x11_unix_by_default = TRUE;
28
29 /* ----------------------------------------------------------------------
30  * File access abstraction.
31  */
32
33 /*
34  * Set local current directory. Returns NULL on success, or else an
35  * error message which must be freed after printing.
36  */
37 char *psftp_lcd(char *dir)
38 {
39     char *ret = NULL;
40
41     if (!SetCurrentDirectory(dir)) {
42         LPVOID message;
43         int i;
44         FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
45                       FORMAT_MESSAGE_FROM_SYSTEM |
46                       FORMAT_MESSAGE_IGNORE_INSERTS,
47                       NULL, GetLastError(),
48                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
49                       (LPTSTR)&message, 0, NULL);
50         i = strcspn((char *)message, "\n");
51         ret = dupprintf("%.*s", i, (LPCTSTR)message);
52         LocalFree(message);
53     }
54
55     return ret;
56 }
57
58 /*
59  * Get local current directory. Returns a string which must be
60  * freed.
61  */
62 char *psftp_getcwd(void)
63 {
64     char *ret = snewn(256, char);
65     int len = GetCurrentDirectory(256, ret);
66     if (len > 256)
67         ret = sresize(ret, len, char);
68     GetCurrentDirectory(len, ret);
69     return ret;
70 }
71
72 #define TIME_POSIX_TO_WIN(t, ft) do { \
73     ULARGE_INTEGER uli; \
74     uli.QuadPart = ((ULONGLONG)(t) + 11644473600ull) * 10000000ull; \
75     (ft).dwLowDateTime  = uli.LowPart; \
76     (ft).dwHighDateTime = uli.HighPart; \
77 } while(0)
78 #define TIME_WIN_TO_POSIX(ft, t) do { \
79     ULARGE_INTEGER uli; \
80     uli.LowPart  = (ft).dwLowDateTime; \
81     uli.HighPart = (ft).dwHighDateTime; \
82     uli.QuadPart = uli.QuadPart / 10000000ull - 11644473600ull; \
83     (t) = (unsigned long) uli.QuadPart; \
84 } while(0)
85
86 struct RFile {
87     HANDLE h;
88 };
89
90 RFile *open_existing_file(char *name, uint64 *size,
91                           unsigned long *mtime, unsigned long *atime)
92 {
93     HANDLE h;
94     RFile *ret;
95
96     h = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,
97                    OPEN_EXISTING, 0, 0);
98     if (h == INVALID_HANDLE_VALUE)
99         return NULL;
100
101     ret = snew(RFile);
102     ret->h = h;
103
104     if (size)
105         size->lo=GetFileSize(h, &(size->hi));
106
107     if (mtime || atime) {
108         FILETIME actime, wrtime;
109         GetFileTime(h, NULL, &actime, &wrtime);
110         if (atime)
111             TIME_WIN_TO_POSIX(actime, *atime);
112         if (mtime)
113             TIME_WIN_TO_POSIX(wrtime, *mtime);
114     }
115
116     return ret;
117 }
118
119 int read_from_file(RFile *f, void *buffer, int length)
120 {
121     int ret;
122     DWORD read;
123     ret = ReadFile(f->h, buffer, length, &read, NULL);
124     if (!ret)
125         return -1;                     /* error */
126     else
127         return read;
128 }
129
130 void close_rfile(RFile *f)
131 {
132     CloseHandle(f->h);
133     sfree(f);
134 }
135
136 struct WFile {
137     HANDLE h;
138 };
139
140 WFile *open_new_file(char *name)
141 {
142     HANDLE h;
143     WFile *ret;
144
145     h = CreateFile(name, GENERIC_WRITE, 0, NULL,
146                    CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
147     if (h == INVALID_HANDLE_VALUE)
148         return NULL;
149
150     ret = snew(WFile);
151     ret->h = h;
152
153     return ret;
154 }
155
156 WFile *open_existing_wfile(char *name, uint64 *size)
157 {
158     HANDLE h;
159     WFile *ret;
160
161     h = CreateFile(name, GENERIC_WRITE, FILE_SHARE_READ, NULL,
162                    OPEN_EXISTING, 0, 0);
163     if (h == INVALID_HANDLE_VALUE)
164         return NULL;
165
166     ret = snew(WFile);
167     ret->h = h;
168
169     if (size)
170         size->lo=GetFileSize(h, &(size->hi));
171
172     return ret;
173 }
174
175 int write_to_file(WFile *f, void *buffer, int length)
176 {
177     int ret;
178     DWORD written;
179     ret = WriteFile(f->h, buffer, length, &written, NULL);
180     if (!ret)
181         return -1;                     /* error */
182     else
183         return written;
184 }
185
186 void set_file_times(WFile *f, unsigned long mtime, unsigned long atime)
187 {
188     FILETIME actime, wrtime;
189     TIME_POSIX_TO_WIN(atime, actime);
190     TIME_POSIX_TO_WIN(mtime, wrtime);
191     SetFileTime(f->h, NULL, &actime, &wrtime);
192 }
193
194 void close_wfile(WFile *f)
195 {
196     CloseHandle(f->h);
197     sfree(f);
198 }
199
200 /* Seek offset bytes through file, from whence, where whence is
201    FROM_START, FROM_CURRENT, or FROM_END */
202 int seek_file(WFile *f, uint64 offset, int whence)
203 {
204     DWORD movemethod;
205
206     switch (whence) {
207     case FROM_START:
208         movemethod = FILE_BEGIN;
209         break;
210     case FROM_CURRENT:
211         movemethod = FILE_CURRENT;
212         break;
213     case FROM_END:
214         movemethod = FILE_END;
215         break;
216     default:
217         return -1;
218     }
219
220     SetFilePointer(f->h, offset.lo, &(offset.hi), movemethod);
221     
222     if (GetLastError() != NO_ERROR)
223         return -1;
224     else 
225         return 0;
226 }
227
228 uint64 get_file_posn(WFile *f)
229 {
230     uint64 ret;
231
232     ret.hi = 0L;
233     ret.lo = SetFilePointer(f->h, 0L, &(ret.hi), FILE_CURRENT);
234
235     return ret;
236 }
237
238 int file_type(char *name)
239 {
240     DWORD attr;
241     attr = GetFileAttributes(name);
242     /* We know of no `weird' files under Windows. */
243     if (attr == (DWORD)-1)
244         return FILE_TYPE_NONEXISTENT;
245     else if (attr & FILE_ATTRIBUTE_DIRECTORY)
246         return FILE_TYPE_DIRECTORY;
247     else
248         return FILE_TYPE_FILE;
249 }
250
251 struct DirHandle {
252     HANDLE h;
253     char *name;
254 };
255
256 DirHandle *open_directory(char *name)
257 {
258     HANDLE h;
259     WIN32_FIND_DATA fdat;
260     char *findfile;
261     DirHandle *ret;
262
263     /* Enumerate files in dir `foo'. */
264     findfile = dupcat(name, "/*", NULL);
265     h = FindFirstFile(findfile, &fdat);
266     if (h == INVALID_HANDLE_VALUE)
267         return NULL;
268     sfree(findfile);
269
270     ret = snew(DirHandle);
271     ret->h = h;
272     ret->name = dupstr(fdat.cFileName);
273     return ret;
274 }
275
276 char *read_filename(DirHandle *dir)
277 {
278     do {
279
280         if (!dir->name) {
281             WIN32_FIND_DATA fdat;
282             int ok = FindNextFile(dir->h, &fdat);
283             if (!ok)
284                 return NULL;
285             else
286                 dir->name = dupstr(fdat.cFileName);
287         }
288
289         assert(dir->name);
290         if (dir->name[0] == '.' &&
291             (dir->name[1] == '\0' ||
292              (dir->name[1] == '.' && dir->name[2] == '\0'))) {
293             sfree(dir->name);
294             dir->name = NULL;
295         }
296
297     } while (!dir->name);
298
299     if (dir->name) {
300         char *ret = dir->name;
301         dir->name = NULL;
302         return ret;
303     } else
304         return NULL;
305 }
306
307 void close_directory(DirHandle *dir)
308 {
309     FindClose(dir->h);
310     if (dir->name)
311         sfree(dir->name);
312     sfree(dir);
313 }
314
315 int test_wildcard(char *name, int cmdline)
316 {
317     HANDLE fh;
318     WIN32_FIND_DATA fdat;
319
320     /* First see if the exact name exists. */
321     if (GetFileAttributes(name) != (DWORD)-1)
322         return WCTYPE_FILENAME;
323
324     /* Otherwise see if a wildcard match finds anything. */
325     fh = FindFirstFile(name, &fdat);
326     if (fh == INVALID_HANDLE_VALUE)
327         return WCTYPE_NONEXISTENT;
328
329     FindClose(fh);
330     return WCTYPE_WILDCARD;
331 }
332
333 struct WildcardMatcher {
334     HANDLE h;
335     char *name;
336     char *srcpath;
337 };
338
339 /*
340  * Return a pointer to the portion of str that comes after the last
341  * slash (or backslash or colon, if `local' is TRUE).
342  */
343 static char *stripslashes(char *str, int local)
344 {
345     char *p;
346
347     if (local) {
348         p = strchr(str, ':');
349         if (p) str = p+1;
350     }
351
352     p = strrchr(str, '/');
353     if (p) str = p+1;
354
355     if (local) {
356         p = strrchr(str, '\\');
357         if (p) str = p+1;
358     }
359
360     return str;
361 }
362
363 WildcardMatcher *begin_wildcard_matching(char *name)
364 {
365     HANDLE h;
366     WIN32_FIND_DATA fdat;
367     WildcardMatcher *ret;
368     char *last;
369
370     h = FindFirstFile(name, &fdat);
371     if (h == INVALID_HANDLE_VALUE)
372         return NULL;
373
374     ret = snew(WildcardMatcher);
375     ret->h = h;
376     ret->srcpath = dupstr(name);
377     last = stripslashes(ret->srcpath, 1);
378     *last = '\0';
379     if (fdat.cFileName[0] == '.' &&
380         (fdat.cFileName[1] == '\0' ||
381          (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
382         ret->name = NULL;
383     else
384         ret->name = dupcat(ret->srcpath, fdat.cFileName, NULL);
385
386     return ret;
387 }
388
389 char *wildcard_get_filename(WildcardMatcher *dir)
390 {
391     while (!dir->name) {
392         WIN32_FIND_DATA fdat;
393         int ok = FindNextFile(dir->h, &fdat);
394
395         if (!ok)
396             return NULL;
397
398         if (fdat.cFileName[0] == '.' &&
399             (fdat.cFileName[1] == '\0' ||
400              (fdat.cFileName[1] == '.' && fdat.cFileName[2] == '\0')))
401             dir->name = NULL;
402         else
403             dir->name = dupcat(dir->srcpath, fdat.cFileName, NULL);
404     }
405
406     if (dir->name) {
407         char *ret = dir->name;
408         dir->name = NULL;
409         return ret;
410     } else
411         return NULL;
412 }
413
414 void finish_wildcard_matching(WildcardMatcher *dir)
415 {
416     FindClose(dir->h);
417     if (dir->name)
418         sfree(dir->name);
419     sfree(dir->srcpath);
420     sfree(dir);
421 }
422
423 int vet_filename(char *name)
424 {
425     if (strchr(name, '/') || strchr(name, '\\') || strchr(name, ':'))
426         return FALSE;
427
428     if (!name[strspn(name, ".")])      /* entirely composed of dots */
429         return FALSE;
430
431     return TRUE;
432 }
433
434 int create_directory(char *name)
435 {
436     return CreateDirectory(name, NULL) != 0;
437 }
438
439 char *dir_file_cat(char *dir, char *file)
440 {
441     return dupcat(dir, "\\", file, NULL);
442 }
443
444 /* ----------------------------------------------------------------------
445  * Platform-specific network handling.
446  */
447
448 /*
449  * Be told what socket we're supposed to be using.
450  */
451 static SOCKET sftp_ssh_socket = INVALID_SOCKET;
452 static HANDLE netevent = INVALID_HANDLE_VALUE;
453 char *do_select(SOCKET skt, int startup)
454 {
455     int events;
456     if (startup)
457         sftp_ssh_socket = skt;
458     else
459         sftp_ssh_socket = INVALID_SOCKET;
460
461     if (p_WSAEventSelect) {
462         if (startup) {
463             events = (FD_CONNECT | FD_READ | FD_WRITE |
464                       FD_OOB | FD_CLOSE | FD_ACCEPT);
465             netevent = CreateEvent(NULL, FALSE, FALSE, NULL);
466         } else {
467             events = 0;
468         }
469         if (p_WSAEventSelect(skt, netevent, events) == SOCKET_ERROR) {
470             switch (p_WSAGetLastError()) {
471               case WSAENETDOWN:
472                 return "Network is down";
473               default:
474                 return "WSAEventSelect(): unknown error";
475             }
476         }
477     }
478     return NULL;
479 }
480 extern int select_result(WPARAM, LPARAM);
481
482 int do_eventsel_loop(HANDLE other_event)
483 {
484     int n, nhandles, nallhandles, netindex, otherindex;
485     long next, ticks;
486     HANDLE *handles;
487     SOCKET *sklist;
488     int skcount;
489     long now = GETTICKCOUNT();
490
491     if (run_timers(now, &next)) {
492         ticks = next - GETTICKCOUNT();
493         if (ticks < 0) ticks = 0;  /* just in case */
494     } else {
495         ticks = INFINITE;
496     }
497
498     handles = handle_get_events(&nhandles);
499     handles = sresize(handles, nhandles+2, HANDLE);
500     nallhandles = nhandles;
501
502     if (netevent != INVALID_HANDLE_VALUE)
503         handles[netindex = nallhandles++] = netevent;
504     else
505         netindex = -1;
506     if (other_event != INVALID_HANDLE_VALUE)
507         handles[otherindex = nallhandles++] = other_event;
508     else
509         otherindex = -1;
510
511     n = WaitForMultipleObjects(nallhandles, handles, FALSE, ticks);
512
513     if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
514         handle_got_event(handles[n - WAIT_OBJECT_0]);
515     } else if (netindex >= 0 && n == WAIT_OBJECT_0 + netindex) {
516         WSANETWORKEVENTS things;
517         SOCKET socket;
518         extern SOCKET first_socket(int *), next_socket(int *);
519         extern int select_result(WPARAM, LPARAM);
520         int i, socketstate;
521
522         /*
523          * We must not call select_result() for any socket
524          * until we have finished enumerating within the
525          * tree. This is because select_result() may close
526          * the socket and modify the tree.
527          */
528         /* Count the active sockets. */
529         i = 0;
530         for (socket = first_socket(&socketstate);
531              socket != INVALID_SOCKET;
532              socket = next_socket(&socketstate)) i++;
533
534         /* Expand the buffer if necessary. */
535         sklist = snewn(i, SOCKET);
536
537         /* Retrieve the sockets into sklist. */
538         skcount = 0;
539         for (socket = first_socket(&socketstate);
540              socket != INVALID_SOCKET;
541              socket = next_socket(&socketstate)) {
542             sklist[skcount++] = socket;
543         }
544
545         /* Now we're done enumerating; go through the list. */
546         for (i = 0; i < skcount; i++) {
547             WPARAM wp;
548             socket = sklist[i];
549             wp = (WPARAM) socket;
550             if (!p_WSAEnumNetworkEvents(socket, NULL, &things)) {
551                 static const struct { int bit, mask; } eventtypes[] = {
552                     {FD_CONNECT_BIT, FD_CONNECT},
553                     {FD_READ_BIT, FD_READ},
554                     {FD_CLOSE_BIT, FD_CLOSE},
555                     {FD_OOB_BIT, FD_OOB},
556                     {FD_WRITE_BIT, FD_WRITE},
557                     {FD_ACCEPT_BIT, FD_ACCEPT},
558                 };
559                 int e;
560
561                 noise_ultralight(socket);
562                 noise_ultralight(things.lNetworkEvents);
563
564                 for (e = 0; e < lenof(eventtypes); e++)
565                     if (things.lNetworkEvents & eventtypes[e].mask) {
566                         LPARAM lp;
567                         int err = things.iErrorCode[eventtypes[e].bit];
568                         lp = WSAMAKESELECTREPLY(eventtypes[e].mask, err);
569                         select_result(wp, lp);
570                     }
571             }
572         }
573
574         sfree(sklist);
575     }
576
577     sfree(handles);
578
579     if (n == WAIT_TIMEOUT) {
580         now = next;
581     } else {
582         now = GETTICKCOUNT();
583     }
584
585     if (otherindex >= 0 && n == WAIT_OBJECT_0 + otherindex)
586         return 1;
587
588     return 0;
589 }
590
591 /*
592  * Wait for some network data and process it.
593  *
594  * We have two variants of this function. One uses select() so that
595  * it's compatible with WinSock 1. The other uses WSAEventSelect
596  * and MsgWaitForMultipleObjects, so that we can consistently use
597  * WSAEventSelect throughout; this enables us to also implement
598  * ssh_sftp_get_cmdline() using a parallel mechanism.
599  */
600 int ssh_sftp_loop_iteration(void)
601 {
602     if (p_WSAEventSelect == NULL) {
603         fd_set readfds;
604         int ret;
605         long now = GETTICKCOUNT();
606
607         if (sftp_ssh_socket == INVALID_SOCKET)
608             return -1;                 /* doom */
609
610         if (socket_writable(sftp_ssh_socket))
611             select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_WRITE);
612
613         do {
614             long next, ticks;
615             struct timeval tv, *ptv;
616
617             if (run_timers(now, &next)) {
618                 ticks = next - GETTICKCOUNT();
619                 if (ticks <= 0)
620                     ticks = 1;         /* just in case */
621                 tv.tv_sec = ticks / 1000;
622                 tv.tv_usec = ticks % 1000 * 1000;
623                 ptv = &tv;
624             } else {
625                 ptv = NULL;
626             }
627
628             FD_ZERO(&readfds);
629             FD_SET(sftp_ssh_socket, &readfds);
630             ret = p_select(1, &readfds, NULL, NULL, ptv);
631
632             if (ret < 0)
633                 return -1;                     /* doom */
634             else if (ret == 0)
635                 now = next;
636             else
637                 now = GETTICKCOUNT();
638
639         } while (ret == 0);
640
641         select_result((WPARAM) sftp_ssh_socket, (LPARAM) FD_READ);
642
643         return 0;
644     } else {
645         return do_eventsel_loop(INVALID_HANDLE_VALUE);
646     }
647 }
648
649 /*
650  * Read a command line from standard input.
651  * 
652  * In the presence of WinSock 2, we can use WSAEventSelect to
653  * mediate between the socket and stdin, meaning we can send
654  * keepalives and respond to server events even while waiting at
655  * the PSFTP command prompt. Without WS2, we fall back to a simple
656  * fgets.
657  */
658 struct command_read_ctx {
659     HANDLE event;
660     char *line;
661 };
662
663 static DWORD WINAPI command_read_thread(void *param)
664 {
665     struct command_read_ctx *ctx = (struct command_read_ctx *) param;
666
667     ctx->line = fgetline(stdin);
668
669     SetEvent(ctx->event);
670
671     return 0;
672 }
673
674 char *ssh_sftp_get_cmdline(char *prompt, int no_fds_ok)
675 {
676     int ret;
677     struct command_read_ctx actx, *ctx = &actx;
678     DWORD threadid;
679
680     fputs(prompt, stdout);
681     fflush(stdout);
682
683     if ((sftp_ssh_socket == INVALID_SOCKET && no_fds_ok) ||
684         p_WSAEventSelect == NULL) {
685         return fgetline(stdin);        /* very simple */
686     }
687
688     /*
689      * Create a second thread to read from stdin. Process network
690      * and timing events until it terminates.
691      */
692     ctx->event = CreateEvent(NULL, FALSE, FALSE, NULL);
693     ctx->line = NULL;
694
695     if (!CreateThread(NULL, 0, command_read_thread,
696                       ctx, 0, &threadid)) {
697         fprintf(stderr, "Unable to create command input thread\n");
698         cleanup_exit(1);
699     }
700
701     do {
702         ret = do_eventsel_loop(ctx->event);
703
704         /* Error return can only occur if netevent==NULL, and it ain't. */
705         assert(ret >= 0);
706     } while (ret == 0);
707
708     return ctx->line;
709 }
710
711 /* ----------------------------------------------------------------------
712  * Main program. Parse arguments etc.
713  */
714 int main(int argc, char *argv[])
715 {
716     int ret;
717
718     ret = psftp_main(argc, argv);
719
720     return ret;
721 }