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