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