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