]> andersk Git - openssh.git/blame - sftp.c
- stevesk@cvs.openbsd.org 2006/02/10 00:27:13
[openssh.git] / sftp.c
CommitLineData
61e96248 1/*
ab3932ab 2 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
61e96248 3 *
ab3932ab 4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
61e96248 7 *
ab3932ab 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
61e96248 15 */
16
17#include "includes.h"
bd7c69ea 18RCSID("$OpenBSD: sftp.c,v 1.72 2006/02/10 00:27:13 stevesk Exp $");
61e96248 19
bd7c69ea 20#include <sys/ioctl.h>
5132eac0 21
a75f5360 22#ifdef HAVE_PATHS_H
6f61e0ec 23# include <paths.h>
a75f5360 24#endif
5132eac0 25#ifdef USE_LIBEDIT
26#include <histedit.h>
27#else
28typedef void EditLine;
29#endif
61e96248 30
31#include "buffer.h"
32#include "xmalloc.h"
33#include "log.h"
34#include "pathnames.h"
1fcde3fe 35#include "misc.h"
61e96248 36
37#include "sftp.h"
38#include "sftp-common.h"
39#include "sftp-client.h"
caf1e9f0 40
2cda7d6b 41/* File to read commands from */
42FILE* infile;
43
44/* Are we in batchfile mode? */
45int batchmode = 0;
46
47/* Size of buffer used when copying files */
48size_t copy_buffer_len = 32768;
49
50/* Number of concurrent outstanding requests */
51size_t num_requests = 16;
52
53/* PID of ssh transport process */
54static pid_t sshpid = -1;
55
56/* This is set to 0 if the progressmeter is not desired. */
06abcf97 57int showprogress = 1;
2cda7d6b 58
0e5de6f8 59/* SIGINT received during command processing */
60volatile sig_atomic_t interrupted = 0;
61
95cbd340 62/* I wish qsort() took a separate ctx for the comparison function...*/
63int sort_flag;
64
2cda7d6b 65int remote_glob(struct sftp_conn *, const char *, int,
66 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
61e96248 67
5152d46f 68extern char *__progname;
5152d46f 69
2cda7d6b 70/* Separators for interactive commands */
71#define WHITESPACE " \t\r\n"
72
95cbd340 73/* ls flags */
ae7daec3 74#define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
75#define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
76#define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
77#define LS_NAME_SORT 0x08 /* Sort by name (default) */
78#define LS_TIME_SORT 0x10 /* Sort by mtime */
79#define LS_SIZE_SORT 0x20 /* Sort by file size */
80#define LS_REVERSE_SORT 0x40 /* Reverse sort order */
cc4ff6c4 81#define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
95cbd340 82
ae7daec3 83#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
84#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
2cda7d6b 85
86/* Commands for interactive mode */
87#define I_CHDIR 1
88#define I_CHGRP 2
89#define I_CHMOD 3
90#define I_CHOWN 4
91#define I_GET 5
92#define I_HELP 6
93#define I_LCHDIR 7
94#define I_LLS 8
95#define I_LMKDIR 9
96#define I_LPWD 10
97#define I_LS 11
98#define I_LUMASK 12
99#define I_MKDIR 13
100#define I_PUT 14
101#define I_PWD 15
102#define I_QUIT 16
103#define I_RENAME 17
104#define I_RM 18
105#define I_RMDIR 19
106#define I_SHELL 20
107#define I_SYMLINK 21
108#define I_VERSION 22
109#define I_PROGRESS 23
110
111struct CMD {
112 const char *c;
113 const int n;
114};
115
116static const struct CMD cmds[] = {
117 { "bye", I_QUIT },
118 { "cd", I_CHDIR },
119 { "chdir", I_CHDIR },
120 { "chgrp", I_CHGRP },
121 { "chmod", I_CHMOD },
122 { "chown", I_CHOWN },
123 { "dir", I_LS },
124 { "exit", I_QUIT },
125 { "get", I_GET },
126 { "mget", I_GET },
127 { "help", I_HELP },
128 { "lcd", I_LCHDIR },
129 { "lchdir", I_LCHDIR },
130 { "lls", I_LLS },
131 { "lmkdir", I_LMKDIR },
132 { "ln", I_SYMLINK },
133 { "lpwd", I_LPWD },
134 { "ls", I_LS },
135 { "lumask", I_LUMASK },
136 { "mkdir", I_MKDIR },
137 { "progress", I_PROGRESS },
138 { "put", I_PUT },
139 { "mput", I_PUT },
140 { "pwd", I_PWD },
141 { "quit", I_QUIT },
142 { "rename", I_RENAME },
143 { "rm", I_RM },
144 { "rmdir", I_RMDIR },
145 { "symlink", I_SYMLINK },
146 { "version", I_VERSION },
147 { "!", I_SHELL },
148 { "?", I_HELP },
149 { NULL, -1}
150};
151
152int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
153
0e5de6f8 154static void
155killchild(int signo)
156{
3c03ad3f 157 if (sshpid > 1) {
0e5de6f8 158 kill(sshpid, SIGTERM);
3c03ad3f 159 waitpid(sshpid, NULL, 0);
160 }
0e5de6f8 161
162 _exit(1);
163}
164
165static void
166cmd_interrupt(int signo)
167{
168 const char msg[] = "\rInterrupt \n";
47460206 169 int olderrno = errno;
0e5de6f8 170
171 write(STDERR_FILENO, msg, sizeof(msg) - 1);
172 interrupted = 1;
47460206 173 errno = olderrno;
0e5de6f8 174}
175
2cda7d6b 176static void
177help(void)
178{
179 printf("Available commands:\n");
180 printf("cd path Change remote directory to 'path'\n");
181 printf("lcd path Change local directory to 'path'\n");
182 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
183 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
184 printf("chown own path Change owner of file 'path' to 'own'\n");
185 printf("help Display this help text\n");
186 printf("get remote-path [local-path] Download file\n");
187 printf("lls [ls-options [path]] Display local directory listing\n");
188 printf("ln oldpath newpath Symlink remote file\n");
189 printf("lmkdir path Create local directory\n");
190 printf("lpwd Print local working directory\n");
191 printf("ls [path] Display remote directory listing\n");
192 printf("lumask umask Set local umask to 'umask'\n");
193 printf("mkdir path Create remote directory\n");
194 printf("progress Toggle display of progress meter\n");
195 printf("put local-path [remote-path] Upload file\n");
196 printf("pwd Display remote working directory\n");
197 printf("exit Quit sftp\n");
198 printf("quit Quit sftp\n");
199 printf("rename oldpath newpath Rename remote file\n");
200 printf("rmdir path Remove remote directory\n");
201 printf("rm path Delete remote file\n");
202 printf("symlink oldpath newpath Symlink remote file\n");
203 printf("version Show SFTP version\n");
204 printf("!command Execute 'command' in local shell\n");
205 printf("! Escape to local shell\n");
206 printf("? Synonym for help\n");
207}
208
209static void
210local_do_shell(const char *args)
211{
212 int status;
213 char *shell;
214 pid_t pid;
215
216 if (!*args)
217 args = NULL;
218
219 if ((shell = getenv("SHELL")) == NULL)
220 shell = _PATH_BSHELL;
221
222 if ((pid = fork()) == -1)
223 fatal("Couldn't fork: %s", strerror(errno));
224
225 if (pid == 0) {
226 /* XXX: child has pipe fds to ssh subproc open - issue? */
227 if (args) {
228 debug3("Executing %s -c \"%s\"", shell, args);
229 execl(shell, shell, "-c", args, (char *)NULL);
230 } else {
231 debug3("Executing %s", shell);
232 execl(shell, shell, (char *)NULL);
233 }
234 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
235 strerror(errno));
236 _exit(1);
237 }
238 while (waitpid(pid, &status, 0) == -1)
239 if (errno != EINTR)
240 fatal("Couldn't wait for child: %s", strerror(errno));
241 if (!WIFEXITED(status))
242 error("Shell exited abormally");
243 else if (WEXITSTATUS(status))
244 error("Shell exited with status %d", WEXITSTATUS(status));
245}
246
247static void
248local_do_ls(const char *args)
249{
250 if (!args || !*args)
251 local_do_shell(_PATH_LS);
252 else {
253 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
254 char *buf = xmalloc(len);
255
256 /* XXX: quoting - rip quoting code from ftp? */
257 snprintf(buf, len, _PATH_LS " %s", args);
258 local_do_shell(buf);
259 xfree(buf);
260 }
261}
262
263/* Strip one path (usually the pwd) from the start of another */
264static char *
265path_strip(char *path, char *strip)
266{
267 size_t len;
0426a3b4 268
2cda7d6b 269 if (strip == NULL)
270 return (xstrdup(path));
271
272 len = strlen(strip);
47460206 273 if (strncmp(path, strip, len) == 0) {
2cda7d6b 274 if (strip[len - 1] != '/' && path[len] == '/')
275 len++;
276 return (xstrdup(path + len));
277 }
278
279 return (xstrdup(path));
280}
281
282static char *
283path_append(char *p1, char *p2)
284{
285 char *ret;
286 int len = strlen(p1) + strlen(p2) + 2;
287
288 ret = xmalloc(len);
289 strlcpy(ret, p1, len);
290 if (p1[strlen(p1) - 1] != '/')
291 strlcat(ret, "/", len);
292 strlcat(ret, p2, len);
293
294 return(ret);
295}
296
297static char *
298make_absolute(char *p, char *pwd)
299{
ca75d7de 300 char *abs_str;
2cda7d6b 301
302 /* Derelativise */
303 if (p && p[0] != '/') {
ca75d7de 304 abs_str = path_append(pwd, p);
2cda7d6b 305 xfree(p);
ca75d7de 306 return(abs_str);
2cda7d6b 307 } else
308 return(p);
309}
310
311static int
312infer_path(const char *p, char **ifp)
313{
314 char *cp;
315
316 cp = strrchr(p, '/');
317 if (cp == NULL) {
318 *ifp = xstrdup(p);
319 return(0);
320 }
321
322 if (!cp[1]) {
323 error("Invalid path");
324 return(-1);
325 }
326
327 *ifp = xstrdup(cp + 1);
328 return(0);
329}
330
331static int
332parse_getput_flags(const char **cpp, int *pflag)
333{
334 const char *cp = *cpp;
335
336 /* Check for flags */
337 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
338 switch (cp[1]) {
339 case 'p':
340 case 'P':
341 *pflag = 1;
342 break;
343 default:
344 error("Invalid flag -%c", cp[1]);
345 return(-1);
346 }
347 cp += 2;
348 *cpp = cp + strspn(cp, WHITESPACE);
349 }
350
351 return(0);
352}
353
354static int
355parse_ls_flags(const char **cpp, int *lflag)
356{
357 const char *cp = *cpp;
358
95cbd340 359 /* Defaults */
ae7daec3 360 *lflag = LS_NAME_SORT;
95cbd340 361
2cda7d6b 362 /* Check for flags */
363 if (cp++[0] == '-') {
f8cc7664 364 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
2cda7d6b 365 switch (*cp) {
366 case 'l':
48925711 367 *lflag &= ~VIEW_FLAGS;
ae7daec3 368 *lflag |= LS_LONG_VIEW;
2cda7d6b 369 break;
370 case '1':
48925711 371 *lflag &= ~VIEW_FLAGS;
ae7daec3 372 *lflag |= LS_SHORT_VIEW;
48925711 373 break;
374 case 'n':
375 *lflag &= ~VIEW_FLAGS;
ae7daec3 376 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
2cda7d6b 377 break;
95cbd340 378 case 'S':
379 *lflag &= ~SORT_FLAGS;
ae7daec3 380 *lflag |= LS_SIZE_SORT;
95cbd340 381 break;
382 case 't':
383 *lflag &= ~SORT_FLAGS;
ae7daec3 384 *lflag |= LS_TIME_SORT;
95cbd340 385 break;
386 case 'r':
ae7daec3 387 *lflag |= LS_REVERSE_SORT;
95cbd340 388 break;
389 case 'f':
390 *lflag &= ~SORT_FLAGS;
391 break;
cc4ff6c4 392 case 'a':
393 *lflag |= LS_SHOW_ALL;
394 break;
2cda7d6b 395 default:
396 error("Invalid flag -%c", *cp);
397 return(-1);
398 }
399 }
400 *cpp = cp + strspn(cp, WHITESPACE);
401 }
402
403 return(0);
404}
405
406static int
407get_pathname(const char **cpp, char **path)
408{
409 const char *cp = *cpp, *end;
410 char quot;
2ceb8101 411 u_int i, j;
2cda7d6b 412
413 cp += strspn(cp, WHITESPACE);
414 if (!*cp) {
415 *cpp = cp;
416 *path = NULL;
417 return (0);
418 }
419
420 *path = xmalloc(strlen(cp) + 1);
421
422 /* Check for quoted filenames */
423 if (*cp == '\"' || *cp == '\'') {
424 quot = *cp++;
425
426 /* Search for terminating quote, unescape some chars */
427 for (i = j = 0; i <= strlen(cp); i++) {
428 if (cp[i] == quot) { /* Found quote */
429 i++;
430 (*path)[j] = '\0';
431 break;
432 }
433 if (cp[i] == '\0') { /* End of string */
434 error("Unterminated quote");
435 goto fail;
436 }
437 if (cp[i] == '\\') { /* Escaped characters */
438 i++;
439 if (cp[i] != '\'' && cp[i] != '\"' &&
440 cp[i] != '\\') {
7f09f717 441 error("Bad escaped character '\\%c'",
2cda7d6b 442 cp[i]);
443 goto fail;
444 }
445 }
446 (*path)[j++] = cp[i];
447 }
448
449 if (j == 0) {
450 error("Empty quotes");
451 goto fail;
452 }
453 *cpp = cp + i + strspn(cp + i, WHITESPACE);
454 } else {
455 /* Read to end of filename */
456 end = strpbrk(cp, WHITESPACE);
457 if (end == NULL)
458 end = strchr(cp, '\0');
459 *cpp = end + strspn(end, WHITESPACE);
460
461 memcpy(*path, cp, end - cp);
462 (*path)[end - cp] = '\0';
463 }
464 return (0);
465
466 fail:
467 xfree(*path);
468 *path = NULL;
469 return (-1);
470}
471
472static int
473is_dir(char *path)
474{
475 struct stat sb;
476
477 /* XXX: report errors? */
478 if (stat(path, &sb) == -1)
479 return(0);
480
481 return(sb.st_mode & S_IFDIR);
482}
483
484static int
485is_reg(char *path)
486{
487 struct stat sb;
488
489 if (stat(path, &sb) == -1)
490 fatal("stat %s: %s", path, strerror(errno));
491
492 return(S_ISREG(sb.st_mode));
493}
494
495static int
496remote_is_dir(struct sftp_conn *conn, char *path)
497{
498 Attrib *a;
499
500 /* XXX: report errors? */
501 if ((a = do_stat(conn, path, 1)) == NULL)
502 return(0);
503 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
504 return(0);
505 return(a->perm & S_IFDIR);
506}
507
508static int
509process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
510{
511 char *abs_src = NULL;
512 char *abs_dst = NULL;
513 char *tmp;
514 glob_t g;
515 int err = 0;
516 int i;
517
518 abs_src = xstrdup(src);
519 abs_src = make_absolute(abs_src, pwd);
520
521 memset(&g, 0, sizeof(g));
522 debug3("Looking up %s", abs_src);
523 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
524 error("File \"%s\" not found.", abs_src);
525 err = -1;
526 goto out;
527 }
528
529 /* If multiple matches, dst must be a directory or unspecified */
530 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
531 error("Multiple files match, but \"%s\" is not a directory",
532 dst);
533 err = -1;
534 goto out;
535 }
536
0e5de6f8 537 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2cda7d6b 538 if (infer_path(g.gl_pathv[i], &tmp)) {
539 err = -1;
540 goto out;
541 }
542
543 if (g.gl_matchc == 1 && dst) {
544 /* If directory specified, append filename */
545 if (is_dir(dst)) {
546 if (infer_path(g.gl_pathv[0], &tmp)) {
547 err = 1;
548 goto out;
549 }
550 abs_dst = path_append(dst, tmp);
551 xfree(tmp);
552 } else
553 abs_dst = xstrdup(dst);
554 } else if (dst) {
555 abs_dst = path_append(dst, tmp);
556 xfree(tmp);
557 } else
558 abs_dst = tmp;
559
560 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
561 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
562 err = -1;
563 xfree(abs_dst);
564 abs_dst = NULL;
565 }
566
567out:
568 xfree(abs_src);
569 if (abs_dst)
570 xfree(abs_dst);
571 globfree(&g);
572 return(err);
573}
574
575static int
576process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
577{
578 char *tmp_dst = NULL;
579 char *abs_dst = NULL;
580 char *tmp;
581 glob_t g;
582 int err = 0;
583 int i;
584
585 if (dst) {
586 tmp_dst = xstrdup(dst);
587 tmp_dst = make_absolute(tmp_dst, pwd);
588 }
589
590 memset(&g, 0, sizeof(g));
591 debug3("Looking up %s", src);
592 if (glob(src, 0, NULL, &g)) {
593 error("File \"%s\" not found.", src);
594 err = -1;
595 goto out;
596 }
597
598 /* If multiple matches, dst may be directory or unspecified */
599 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
600 error("Multiple files match, but \"%s\" is not a directory",
601 tmp_dst);
602 err = -1;
603 goto out;
604 }
605
0e5de6f8 606 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2cda7d6b 607 if (!is_reg(g.gl_pathv[i])) {
608 error("skipping non-regular file %s",
609 g.gl_pathv[i]);
610 continue;
611 }
612 if (infer_path(g.gl_pathv[i], &tmp)) {
613 err = -1;
614 goto out;
615 }
616
617 if (g.gl_matchc == 1 && tmp_dst) {
618 /* If directory specified, append filename */
619 if (remote_is_dir(conn, tmp_dst)) {
620 if (infer_path(g.gl_pathv[0], &tmp)) {
621 err = 1;
622 goto out;
623 }
624 abs_dst = path_append(tmp_dst, tmp);
625 xfree(tmp);
626 } else
627 abs_dst = xstrdup(tmp_dst);
628
629 } else if (tmp_dst) {
630 abs_dst = path_append(tmp_dst, tmp);
631 xfree(tmp);
632 } else
633 abs_dst = make_absolute(tmp, pwd);
634
635 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
636 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
637 err = -1;
638 }
639
640out:
641 if (abs_dst)
642 xfree(abs_dst);
643 if (tmp_dst)
644 xfree(tmp_dst);
645 globfree(&g);
646 return(err);
647}
648
649static int
650sdirent_comp(const void *aa, const void *bb)
651{
652 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
653 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
ae7daec3 654 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
2cda7d6b 655
95cbd340 656#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
ae7daec3 657 if (sort_flag & LS_NAME_SORT)
95cbd340 658 return (rmul * strcmp(a->filename, b->filename));
ae7daec3 659 else if (sort_flag & LS_TIME_SORT)
95cbd340 660 return (rmul * NCMP(a->a.mtime, b->a.mtime));
ae7daec3 661 else if (sort_flag & LS_SIZE_SORT)
95cbd340 662 return (rmul * NCMP(a->a.size, b->a.size));
663
664 fatal("Unknown ls sort type");
2cda7d6b 665}
666
667/* sftp ls.1 replacement for directories */
668static int
669do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
670{
2ceb8101 671 int n;
672 u_int c = 1, colspace = 0, columns = 1;
2cda7d6b 673 SFTP_DIRENT **d;
674
675 if ((n = do_readdir(conn, path, &d)) != 0)
676 return (n);
677
ae7daec3 678 if (!(lflag & LS_SHORT_VIEW)) {
2ceb8101 679 u_int m = 0, width = 80;
2cda7d6b 680 struct winsize ws;
681 char *tmp;
682
683 /* Count entries for sort and find longest filename */
cc4ff6c4 684 for (n = 0; d[n] != NULL; n++) {
685 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
686 m = MAX(m, strlen(d[n]->filename));
687 }
2cda7d6b 688
689 /* Add any subpath that also needs to be counted */
690 tmp = path_strip(path, strip_path);
691 m += strlen(tmp);
692 xfree(tmp);
693
694 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
695 width = ws.ws_col;
696
697 columns = width / (m + 2);
698 columns = MAX(columns, 1);
699 colspace = width / columns;
700 colspace = MIN(colspace, width);
701 }
702
95cbd340 703 if (lflag & SORT_FLAGS) {
bdd3b323 704 for (n = 0; d[n] != NULL; n++)
705 ; /* count entries */
ae7daec3 706 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
95cbd340 707 qsort(d, n, sizeof(*d), sdirent_comp);
708 }
2cda7d6b 709
0e5de6f8 710 for (n = 0; d[n] != NULL && !interrupted; n++) {
2cda7d6b 711 char *tmp, *fname;
712
cc4ff6c4 713 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
714 continue;
715
2cda7d6b 716 tmp = path_append(path, d[n]->filename);
717 fname = path_strip(tmp, strip_path);
718 xfree(tmp);
719
ae7daec3 720 if (lflag & LS_LONG_VIEW) {
721 if (lflag & LS_NUMERIC_VIEW) {
48925711 722 char *lname;
723 struct stat sb;
724
725 memset(&sb, 0, sizeof(sb));
726 attrib_to_stat(&d[n]->a, &sb);
727 lname = ls_file(fname, &sb, 1);
728 printf("%s\n", lname);
729 xfree(lname);
730 } else
731 printf("%s\n", d[n]->longname);
2cda7d6b 732 } else {
733 printf("%-*s", colspace, fname);
734 if (c >= columns) {
735 printf("\n");
736 c = 1;
737 } else
738 c++;
739 }
740
741 xfree(fname);
742 }
743
ae7daec3 744 if (!(lflag & LS_LONG_VIEW) && (c != 1))
2cda7d6b 745 printf("\n");
746
747 free_sftp_dirents(d);
748 return (0);
749}
750
751/* sftp ls.1 replacement which handles path globs */
752static int
753do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
754 int lflag)
755{
756 glob_t g;
2ceb8101 757 u_int i, c = 1, colspace = 0, columns = 1;
2bd204e5 758 Attrib *a = NULL;
2cda7d6b 759
760 memset(&g, 0, sizeof(g));
761
762 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
2bd204e5 763 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
764 if (g.gl_pathc)
765 globfree(&g);
2cda7d6b 766 error("Can't ls: \"%s\" not found", path);
767 return (-1);
768 }
769
0e5de6f8 770 if (interrupted)
771 goto out;
772
2cda7d6b 773 /*
2bd204e5 774 * If the glob returns a single match and it is a directory,
775 * then just list its contents.
2cda7d6b 776 */
2bd204e5 777 if (g.gl_matchc == 1) {
778 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
2cda7d6b 779 globfree(&g);
780 return (-1);
781 }
782 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
783 S_ISDIR(a->perm)) {
2bd204e5 784 int err;
785
786 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
2cda7d6b 787 globfree(&g);
2bd204e5 788 return (err);
2cda7d6b 789 }
790 }
791
ae7daec3 792 if (!(lflag & LS_SHORT_VIEW)) {
2ceb8101 793 u_int m = 0, width = 80;
2cda7d6b 794 struct winsize ws;
795
796 /* Count entries for sort and find longest filename */
797 for (i = 0; g.gl_pathv[i]; i++)
798 m = MAX(m, strlen(g.gl_pathv[i]));
799
800 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
801 width = ws.ws_col;
802
803 columns = width / (m + 2);
804 columns = MAX(columns, 1);
805 colspace = width / columns;
806 }
807
2bd204e5 808 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
2cda7d6b 809 char *fname;
810
811 fname = path_strip(g.gl_pathv[i], strip_path);
812
ae7daec3 813 if (lflag & LS_LONG_VIEW) {
2cda7d6b 814 char *lname;
815 struct stat sb;
816
817 /*
818 * XXX: this is slow - 1 roundtrip per path
819 * A solution to this is to fork glob() and
820 * build a sftp specific version which keeps the
821 * attribs (which currently get thrown away)
822 * that the server returns as well as the filenames.
823 */
824 memset(&sb, 0, sizeof(sb));
2bd204e5 825 if (a == NULL)
826 a = do_lstat(conn, g.gl_pathv[i], 1);
2cda7d6b 827 if (a != NULL)
828 attrib_to_stat(a, &sb);
829 lname = ls_file(fname, &sb, 1);
830 printf("%s\n", lname);
831 xfree(lname);
832 } else {
833 printf("%-*s", colspace, fname);
834 if (c >= columns) {
835 printf("\n");
836 c = 1;
837 } else
838 c++;
839 }
840 xfree(fname);
841 }
842
ae7daec3 843 if (!(lflag & LS_LONG_VIEW) && (c != 1))
2cda7d6b 844 printf("\n");
845
0e5de6f8 846 out:
2cda7d6b 847 if (g.gl_pathc)
848 globfree(&g);
849
850 return (0);
851}
852
853static int
854parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
855 unsigned long *n_arg, char **path1, char **path2)
856{
857 const char *cmd, *cp = *cpp;
858 char *cp2;
859 int base = 0;
860 long l;
861 int i, cmdnum;
862
863 /* Skip leading whitespace */
864 cp = cp + strspn(cp, WHITESPACE);
865
866 /* Ignore blank lines and lines which begin with comment '#' char */
867 if (*cp == '\0' || *cp == '#')
868 return (0);
869
870 /* Check for leading '-' (disable error processing) */
871 *iflag = 0;
872 if (*cp == '-') {
873 *iflag = 1;
874 cp++;
875 }
876
877 /* Figure out which command we have */
878 for (i = 0; cmds[i].c; i++) {
879 int cmdlen = strlen(cmds[i].c);
880
881 /* Check for command followed by whitespace */
882 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
883 strchr(WHITESPACE, cp[cmdlen])) {
884 cp += cmdlen;
885 cp = cp + strspn(cp, WHITESPACE);
886 break;
887 }
888 }
889 cmdnum = cmds[i].n;
890 cmd = cmds[i].c;
891
892 /* Special case */
893 if (*cp == '!') {
894 cp++;
895 cmdnum = I_SHELL;
896 } else if (cmdnum == -1) {
897 error("Invalid command.");
898 return (-1);
899 }
900
901 /* Get arguments and parse flags */
902 *lflag = *pflag = *n_arg = 0;
903 *path1 = *path2 = NULL;
904 switch (cmdnum) {
905 case I_GET:
906 case I_PUT:
907 if (parse_getput_flags(&cp, pflag))
908 return(-1);
909 /* Get first pathname (mandatory) */
910 if (get_pathname(&cp, path1))
911 return(-1);
912 if (*path1 == NULL) {
913 error("You must specify at least one path after a "
914 "%s command.", cmd);
915 return(-1);
916 }
917 /* Try to get second pathname (optional) */
918 if (get_pathname(&cp, path2))
919 return(-1);
920 break;
921 case I_RENAME:
922 case I_SYMLINK:
923 if (get_pathname(&cp, path1))
924 return(-1);
925 if (get_pathname(&cp, path2))
926 return(-1);
927 if (!*path1 || !*path2) {
928 error("You must specify two paths after a %s "
929 "command.", cmd);
930 return(-1);
931 }
932 break;
933 case I_RM:
934 case I_MKDIR:
935 case I_RMDIR:
936 case I_CHDIR:
937 case I_LCHDIR:
938 case I_LMKDIR:
939 /* Get pathname (mandatory) */
940 if (get_pathname(&cp, path1))
941 return(-1);
942 if (*path1 == NULL) {
943 error("You must specify a path after a %s command.",
944 cmd);
945 return(-1);
946 }
947 break;
948 case I_LS:
949 if (parse_ls_flags(&cp, lflag))
950 return(-1);
951 /* Path is optional */
952 if (get_pathname(&cp, path1))
953 return(-1);
954 break;
955 case I_LLS:
956 case I_SHELL:
957 /* Uses the rest of the line */
958 break;
959 case I_LUMASK:
960 base = 8;
961 case I_CHMOD:
962 base = 8;
963 case I_CHOWN:
964 case I_CHGRP:
965 /* Get numeric arg (mandatory) */
966 l = strtol(cp, &cp2, base);
967 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
968 errno == ERANGE) || l < 0) {
969 error("You must supply a numeric argument "
970 "to the %s command.", cmd);
971 return(-1);
972 }
973 cp = cp2;
974 *n_arg = l;
975 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
976 break;
977 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
978 error("You must supply a numeric argument "
979 "to the %s command.", cmd);
980 return(-1);
981 }
982 cp += strspn(cp, WHITESPACE);
983
984 /* Get pathname (mandatory) */
985 if (get_pathname(&cp, path1))
986 return(-1);
987 if (*path1 == NULL) {
988 error("You must specify a path after a %s command.",
989 cmd);
990 return(-1);
991 }
992 break;
993 case I_QUIT:
994 case I_PWD:
995 case I_LPWD:
996 case I_HELP:
997 case I_VERSION:
998 case I_PROGRESS:
999 break;
1000 default:
1001 fatal("Command not implemented");
1002 }
1003
1004 *cpp = cp;
1005 return(cmdnum);
1006}
1007
1008static int
1009parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1010 int err_abort)
1011{
1012 char *path1, *path2, *tmp;
1013 int pflag, lflag, iflag, cmdnum, i;
1014 unsigned long n_arg;
1015 Attrib a, *aa;
1016 char path_buf[MAXPATHLEN];
1017 int err = 0;
1018 glob_t g;
1019
1020 path1 = path2 = NULL;
1021 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1022 &path1, &path2);
1023
1024 if (iflag != 0)
1025 err_abort = 0;
1026
1027 memset(&g, 0, sizeof(g));
1028
1029 /* Perform command */
1030 switch (cmdnum) {
1031 case 0:
1032 /* Blank line */
1033 break;
1034 case -1:
1035 /* Unrecognized command */
1036 err = -1;
1037 break;
1038 case I_GET:
1039 err = process_get(conn, path1, path2, *pwd, pflag);
1040 break;
1041 case I_PUT:
1042 err = process_put(conn, path1, path2, *pwd, pflag);
1043 break;
1044 case I_RENAME:
1045 path1 = make_absolute(path1, *pwd);
1046 path2 = make_absolute(path2, *pwd);
1047 err = do_rename(conn, path1, path2);
1048 break;
1049 case I_SYMLINK:
1050 path2 = make_absolute(path2, *pwd);
1051 err = do_symlink(conn, path1, path2);
1052 break;
1053 case I_RM:
1054 path1 = make_absolute(path1, *pwd);
1055 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
0e5de6f8 1056 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2cda7d6b 1057 printf("Removing %s\n", g.gl_pathv[i]);
1058 err = do_rm(conn, g.gl_pathv[i]);
1059 if (err != 0 && err_abort)
1060 break;
1061 }
1062 break;
1063 case I_MKDIR:
1064 path1 = make_absolute(path1, *pwd);
1065 attrib_clear(&a);
1066 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1067 a.perm = 0777;
1068 err = do_mkdir(conn, path1, &a);
1069 break;
1070 case I_RMDIR:
1071 path1 = make_absolute(path1, *pwd);
1072 err = do_rmdir(conn, path1);
1073 break;
1074 case I_CHDIR:
1075 path1 = make_absolute(path1, *pwd);
1076 if ((tmp = do_realpath(conn, path1)) == NULL) {
1077 err = 1;
1078 break;
1079 }
1080 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1081 xfree(tmp);
1082 err = 1;
1083 break;
1084 }
1085 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1086 error("Can't change directory: Can't check target");
1087 xfree(tmp);
1088 err = 1;
1089 break;
1090 }
1091 if (!S_ISDIR(aa->perm)) {
1092 error("Can't change directory: \"%s\" is not "
1093 "a directory", tmp);
1094 xfree(tmp);
1095 err = 1;
1096 break;
1097 }
1098 xfree(*pwd);
1099 *pwd = tmp;
1100 break;
1101 case I_LS:
1102 if (!path1) {
1103 do_globbed_ls(conn, *pwd, *pwd, lflag);
1104 break;
1105 }
1106
1107 /* Strip pwd off beginning of non-absolute paths */
1108 tmp = NULL;
1109 if (*path1 != '/')
1110 tmp = *pwd;
1111
1112 path1 = make_absolute(path1, *pwd);
1113 err = do_globbed_ls(conn, path1, tmp, lflag);
1114 break;
1115 case I_LCHDIR:
1116 if (chdir(path1) == -1) {
1117 error("Couldn't change local directory to "
1118 "\"%s\": %s", path1, strerror(errno));
1119 err = 1;
1120 }
1121 break;
1122 case I_LMKDIR:
1123 if (mkdir(path1, 0777) == -1) {
1124 error("Couldn't create local directory "
1125 "\"%s\": %s", path1, strerror(errno));
1126 err = 1;
1127 }
1128 break;
1129 case I_LLS:
1130 local_do_ls(cmd);
1131 break;
1132 case I_SHELL:
1133 local_do_shell(cmd);
1134 break;
1135 case I_LUMASK:
1136 umask(n_arg);
1137 printf("Local umask: %03lo\n", n_arg);
1138 break;
1139 case I_CHMOD:
1140 path1 = make_absolute(path1, *pwd);
1141 attrib_clear(&a);
1142 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1143 a.perm = n_arg;
1144 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
0e5de6f8 1145 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2cda7d6b 1146 printf("Changing mode on %s\n", g.gl_pathv[i]);
1147 err = do_setstat(conn, g.gl_pathv[i], &a);
1148 if (err != 0 && err_abort)
1149 break;
1150 }
1151 break;
1152 case I_CHOWN:
1153 case I_CHGRP:
1154 path1 = make_absolute(path1, *pwd);
1155 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
0e5de6f8 1156 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2cda7d6b 1157 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1158 if (err != 0 && err_abort)
1159 break;
1160 else
1161 continue;
1162 }
1163 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1164 error("Can't get current ownership of "
1165 "remote file \"%s\"", g.gl_pathv[i]);
1166 if (err != 0 && err_abort)
1167 break;
1168 else
1169 continue;
1170 }
1171 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1172 if (cmdnum == I_CHOWN) {
1173 printf("Changing owner on %s\n", g.gl_pathv[i]);
1174 aa->uid = n_arg;
1175 } else {
1176 printf("Changing group on %s\n", g.gl_pathv[i]);
1177 aa->gid = n_arg;
1178 }
1179 err = do_setstat(conn, g.gl_pathv[i], aa);
1180 if (err != 0 && err_abort)
1181 break;
1182 }
1183 break;
1184 case I_PWD:
1185 printf("Remote working directory: %s\n", *pwd);
1186 break;
1187 case I_LPWD:
1188 if (!getcwd(path_buf, sizeof(path_buf))) {
1189 error("Couldn't get local cwd: %s", strerror(errno));
1190 err = -1;
1191 break;
1192 }
1193 printf("Local working directory: %s\n", path_buf);
1194 break;
1195 case I_QUIT:
1196 /* Processed below */
1197 break;
1198 case I_HELP:
1199 help();
1200 break;
1201 case I_VERSION:
1202 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1203 break;
1204 case I_PROGRESS:
1205 showprogress = !showprogress;
1206 if (showprogress)
1207 printf("Progress meter enabled\n");
1208 else
1209 printf("Progress meter disabled\n");
1210 break;
1211 default:
1212 fatal("%d is not implemented", cmdnum);
1213 }
1214
1215 if (g.gl_pathc)
1216 globfree(&g);
1217 if (path1)
1218 xfree(path1);
1219 if (path2)
1220 xfree(path2);
1221
1222 /* If an unignored error occurs in batch mode we should abort. */
1223 if (err_abort && err != 0)
1224 return (-1);
1225 else if (cmdnum == I_QUIT)
1226 return (1);
1227
1228 return (0);
1229}
1230
5132eac0 1231#ifdef USE_LIBEDIT
1232static char *
1233prompt(EditLine *el)
1234{
1235 return ("sftp> ");
1236}
1237#endif
1238
2cda7d6b 1239int
1240interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1241{
1242 char *pwd;
1243 char *dir = NULL;
1244 char cmd[2048];
1245 struct sftp_conn *conn;
0aa1cc4b 1246 int err, interactive;
5132eac0 1247 EditLine *el = NULL;
1248#ifdef USE_LIBEDIT
1249 History *hl = NULL;
1250 HistEvent hev;
1251 extern char *__progname;
1252
1253 if (!batchmode && isatty(STDIN_FILENO)) {
1254 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1255 fatal("Couldn't initialise editline");
1256 if ((hl = history_init()) == NULL)
1257 fatal("Couldn't initialise editline history");
1258 history(hl, &hev, H_SETSIZE, 100);
1259 el_set(el, EL_HIST, history, hl);
1260
1261 el_set(el, EL_PROMPT, prompt);
1262 el_set(el, EL_EDITOR, "emacs");
1263 el_set(el, EL_TERMINAL, NULL);
1264 el_set(el, EL_SIGNAL, 1);
1265 el_source(el, NULL);
1266 }
1267#endif /* USE_LIBEDIT */
2cda7d6b 1268
1269 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1270 if (conn == NULL)
1271 fatal("Couldn't initialise connection to server");
1272
1273 pwd = do_realpath(conn, ".");
1274 if (pwd == NULL)
1275 fatal("Need cwd");
1276
1277 if (file1 != NULL) {
1278 dir = xstrdup(file1);
1279 dir = make_absolute(dir, pwd);
1280
1281 if (remote_is_dir(conn, dir) && file2 == NULL) {
1282 printf("Changing to: %s\n", dir);
1283 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
aa41be57 1284 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1285 xfree(dir);
1286 xfree(pwd);
2cda7d6b 1287 return (-1);
aa41be57 1288 }
2cda7d6b 1289 } else {
1290 if (file2 == NULL)
1291 snprintf(cmd, sizeof cmd, "get %s", dir);
1292 else
1293 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1294 file2);
1295
1296 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1297 xfree(dir);
1298 xfree(pwd);
1299 return (err);
1300 }
1301 xfree(dir);
1302 }
1303
157b6700 1304#if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
2cda7d6b 1305 setvbuf(stdout, NULL, _IOLBF, 0);
1306 setvbuf(infile, NULL, _IOLBF, 0);
1307#else
ed9e8be3 1308 setlinebuf(stdout);
1309 setlinebuf(infile);
2cda7d6b 1310#endif
1311
0aa1cc4b 1312 interactive = !batchmode && isatty(STDIN_FILENO);
2cda7d6b 1313 err = 0;
1314 for (;;) {
1315 char *cp;
1316
0e5de6f8 1317 signal(SIGINT, SIG_IGN);
1318
5132eac0 1319 if (el == NULL) {
0aa1cc4b 1320 if (interactive)
1321 printf("sftp> ");
5132eac0 1322 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
0aa1cc4b 1323 if (interactive)
1324 printf("\n");
5132eac0 1325 break;
1326 }
0aa1cc4b 1327 if (!interactive) { /* Echo command */
1328 printf("sftp> %s", cmd);
1329 if (strlen(cmd) > 0 &&
1330 cmd[strlen(cmd) - 1] != '\n')
1331 printf("\n");
1332 }
5132eac0 1333 } else {
1334#ifdef USE_LIBEDIT
1335 const char *line;
1336 int count = 0;
2cda7d6b 1337
0aa1cc4b 1338 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1339 printf("\n");
1340 break;
1341 }
5132eac0 1342 history(hl, &hev, H_ENTER, line);
1343 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1344 fprintf(stderr, "Error: input line too long\n");
1345 continue;
1346 }
1347#endif /* USE_LIBEDIT */
2cda7d6b 1348 }
1349
2cda7d6b 1350 cp = strrchr(cmd, '\n');
1351 if (cp)
1352 *cp = '\0';
1353
0e5de6f8 1354 /* Handle user interrupts gracefully during commands */
1355 interrupted = 0;
1356 signal(SIGINT, cmd_interrupt);
1357
2cda7d6b 1358 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1359 if (err != 0)
1360 break;
1361 }
1362 xfree(pwd);
1363
a345f787 1364#ifdef USE_LIBEDIT
0aa1cc4b 1365 if (el != NULL)
1366 el_end(el);
a345f787 1367#endif /* USE_LIBEDIT */
0aa1cc4b 1368
2cda7d6b 1369 /* err == 1 signifies normal "quit" exit */
1370 return (err >= 0 ? 0 : -1);
1371}
b65c3807 1372
1b558925 1373static void
1374connect_to_server(char *path, char **args, int *in, int *out)
61e96248 1375{
1376 int c_in, c_out;
9906a836 1377
61e96248 1378#ifdef USE_PIPES
1379 int pin[2], pout[2];
9906a836 1380
61e96248 1381 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1382 fatal("pipe: %s", strerror(errno));
1383 *in = pin[0];
1384 *out = pout[1];
1385 c_in = pout[0];
1386 c_out = pin[1];
1387#else /* USE_PIPES */
1388 int inout[2];
9906a836 1389
61e96248 1390 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1391 fatal("socketpair: %s", strerror(errno));
1392 *in = *out = inout[0];
1393 c_in = c_out = inout[1];
1394#endif /* USE_PIPES */
1395
1b558925 1396 if ((sshpid = fork()) == -1)
61e96248 1397 fatal("fork: %s", strerror(errno));
1b558925 1398 else if (sshpid == 0) {
61e96248 1399 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1400 (dup2(c_out, STDOUT_FILENO) == -1)) {
1401 fprintf(stderr, "dup2: %s\n", strerror(errno));
8dbffee9 1402 _exit(1);
61e96248 1403 }
1404 close(*in);
1405 close(*out);
1406 close(c_in);
1407 close(c_out);
0e5de6f8 1408
1409 /*
1410 * The underlying ssh is in the same process group, so we must
f2107e97 1411 * ignore SIGINT if we want to gracefully abort commands,
1412 * otherwise the signal will make it to the ssh process and
0e5de6f8 1413 * kill it too
1414 */
1415 signal(SIGINT, SIG_IGN);
35e49915 1416 execvp(path, args);
a96fd7c2 1417 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
8dbffee9 1418 _exit(1);
61e96248 1419 }
1420
1b558925 1421 signal(SIGTERM, killchild);
1422 signal(SIGINT, killchild);
1423 signal(SIGHUP, killchild);
61e96248 1424 close(c_in);
1425 close(c_out);
1426}
1427
396c147e 1428static void
61e96248 1429usage(void)
1430{
22be05a5 1431 extern char *__progname;
762715ce 1432
f1278af7 1433 fprintf(stderr,
433e60ac 1434 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1435 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1436 " [-S program] [-s subsystem | sftp_server] host\n"
1437 " %s [[user@]host[:file [file]]]\n"
1438 " %s [[user@]host[:dir[/]]]\n"
1439 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
61e96248 1440 exit(1);
1441}
1442
2b87da3b 1443int
61e96248 1444main(int argc, char **argv)
1445{
9a36208d 1446 int in, out, ch, err;
6e007f08 1447 char *host, *userhost, *cp, *file2 = NULL;
8a624ebf 1448 int debug_level = 0, sshver = 2;
1449 char *file1 = NULL, *sftp_server = NULL;
a96fd7c2 1450 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
8a624ebf 1451 LogLevel ll = SYSLOG_LEVEL_INFO;
1452 arglist args;
0426a3b4 1453 extern int optind;
1454 extern char *optarg;
61e96248 1455
fd6168c1 1456 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1457 sanitise_stdfd();
1458
fda04d7d 1459 __progname = ssh_get_progname(argv[0]);
4116f5c0 1460 memset(&args, '\0', sizeof(args));
8a624ebf 1461 args.list = NULL;
4116f5c0 1462 addargs(&args, ssh_program);
8a624ebf 1463 addargs(&args, "-oForwardX11 no");
1464 addargs(&args, "-oForwardAgent no");
d20f3c9e 1465 addargs(&args, "-oPermitLocalCommand no");
e1c5bfaf 1466 addargs(&args, "-oClearAllForwardings yes");
ac414e17 1467
8a624ebf 1468 ll = SYSLOG_LEVEL_INFO;
ac414e17 1469 infile = stdin;
0426a3b4 1470
c25d3df7 1471 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
0426a3b4 1472 switch (ch) {
1473 case 'C':
8a624ebf 1474 addargs(&args, "-C");
0426a3b4 1475 break;
1476 case 'v':
8a624ebf 1477 if (debug_level < 3) {
1478 addargs(&args, "-v");
1479 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1480 }
1481 debug_level++;
0426a3b4 1482 break;
f1278af7 1483 case 'F':
0426a3b4 1484 case 'o':
f1278af7 1485 addargs(&args, "-%c%s", ch, optarg);
0426a3b4 1486 break;
1487 case '1':
8a624ebf 1488 sshver = 1;
0426a3b4 1489 if (sftp_server == NULL)
1490 sftp_server = _PATH_SFTP_SERVER;
1491 break;
1492 case 's':
1493 sftp_server = optarg;
1494 break;
1495 case 'S':
1496 ssh_program = optarg;
4116f5c0 1497 replacearg(&args, 0, "%s", ssh_program);
0426a3b4 1498 break;
a5ec8a3d 1499 case 'b':
a8b64bb8 1500 if (batchmode)
1501 fatal("Batch file already specified.");
1502
1503 /* Allow "-" as stdin */
f2107e97 1504 if (strcmp(optarg, "-") != 0 &&
4e2e5cfd 1505 (infile = fopen(optarg, "r")) == NULL)
a8b64bb8 1506 fatal("%s (%s).", strerror(errno), optarg);
b65c3807 1507 showprogress = 0;
a8b64bb8 1508 batchmode = 1;
0b73a454 1509 addargs(&args, "-obatchmode yes");
a5ec8a3d 1510 break;
a96fd7c2 1511 case 'P':
1512 sftp_direct = optarg;
1513 break;
375f867e 1514 case 'B':
1515 copy_buffer_len = strtol(optarg, &cp, 10);
1516 if (copy_buffer_len == 0 || *cp != '\0')
1517 fatal("Invalid buffer size \"%s\"", optarg);
1518 break;
c25d3df7 1519 case 'R':
1520 num_requests = strtol(optarg, &cp, 10);
1521 if (num_requests == 0 || *cp != '\0')
762715ce 1522 fatal("Invalid number of requests \"%s\"",
c25d3df7 1523 optarg);
1524 break;
0426a3b4 1525 case 'h':
1526 default:
61e96248 1527 usage();
1528 }
1529 }
1530
06abcf97 1531 if (!isatty(STDERR_FILENO))
1532 showprogress = 0;
1533
b69145c2 1534 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1535
a96fd7c2 1536 if (sftp_direct == NULL) {
1537 if (optind == argc || argc > (optind + 2))
1538 usage();
61e96248 1539
a96fd7c2 1540 userhost = xstrdup(argv[optind]);
1541 file2 = argv[optind+1];
edeeab1e 1542
15748b4d 1543 if ((host = strrchr(userhost, '@')) == NULL)
a96fd7c2 1544 host = userhost;
1545 else {
1546 *host++ = '\0';
1547 if (!userhost[0]) {
1548 fprintf(stderr, "Missing username\n");
1549 usage();
1550 }
1551 addargs(&args, "-l%s",userhost);
61e96248 1552 }
61e96248 1553
02de7c6e 1554 if ((cp = colon(host)) != NULL) {
1555 *cp++ = '\0';
1556 file1 = cp;
1557 }
1558
a96fd7c2 1559 host = cleanhostname(host);
1560 if (!*host) {
1561 fprintf(stderr, "Missing hostname\n");
1562 usage();
1563 }
61e96248 1564
a96fd7c2 1565 addargs(&args, "-oProtocol %d", sshver);
8a624ebf 1566
a96fd7c2 1567 /* no subsystem if the server-spec contains a '/' */
1568 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1569 addargs(&args, "-s");
61e96248 1570
a96fd7c2 1571 addargs(&args, "%s", host);
762715ce 1572 addargs(&args, "%s", (sftp_server != NULL ?
a96fd7c2 1573 sftp_server : "sftp"));
61e96248 1574
a8b64bb8 1575 if (!batchmode)
1576 fprintf(stderr, "Connecting to %s...\n", host);
1b558925 1577 connect_to_server(ssh_program, args.list, &in, &out);
a96fd7c2 1578 } else {
1579 args.list = NULL;
1580 addargs(&args, "sftp-server");
61e96248 1581
a8b64bb8 1582 if (!batchmode)
1583 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
1b558925 1584 connect_to_server(sftp_direct, args.list, &in, &out);
a96fd7c2 1585 }
4116f5c0 1586 freeargs(&args);
61e96248 1587
9a36208d 1588 err = interactive_loop(in, out, file1, file2);
61e96248 1589
51fb577a 1590#if !defined(USE_PIPES)
ed9e8be3 1591 shutdown(in, SHUT_RDWR);
1592 shutdown(out, SHUT_RDWR);
51fb577a 1593#endif
1594
61e96248 1595 close(in);
1596 close(out);
a8b64bb8 1597 if (batchmode)
a5ec8a3d 1598 fclose(infile);
61e96248 1599
8c38e88b 1600 while (waitpid(sshpid, NULL, 0) == -1)
1601 if (errno != EINTR)
1602 fatal("Couldn't wait for ssh process: %s",
1603 strerror(errno));
61e96248 1604
9a36208d 1605 exit(err == 0 ? 0 : 1);
61e96248 1606}
This page took 0.462487 seconds and 5 git commands to generate.