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