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