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