blob: 4e170ee60afaeb97ba648926cc84a9af3df76c03 [file] [log] [blame]
Damien Miller33804262001-02-04 23:20:18 +11001/*
Damien Miller4e60ed72004-02-17 17:07:59 +11002 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
Damien Miller33804262001-02-04 23:20:18 +11003 *
Damien Miller4e60ed72004-02-17 17:07:59 +11004 * 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.
Damien Miller33804262001-02-04 23:20:18 +11007 *
Damien Miller4e60ed72004-02-17 17:07:59 +11008 * 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.
Damien Miller33804262001-02-04 23:20:18 +110015 */
16
17#include "includes.h"
Damien Miller9cf6d072006-03-15 11:29:24 +110018RCSID("$OpenBSD: sftp.c,v 1.73 2006/02/10 01:44:27 stevesk Exp $");
Damien Miller33804262001-02-04 23:20:18 +110019
Damien Miller17e91c02006-03-15 11:28:34 +110020#include <sys/ioctl.h>
Damien Miller9cf6d072006-03-15 11:29:24 +110021#include <sys/types.h>
22#include <sys/wait.h>
Darren Tucker2d963d82004-11-07 20:04:10 +110023
Damien Miller03e20032006-03-15 11:16:59 +110024#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110025# include <paths.h>
Damien Miller03e20032006-03-15 11:16:59 +110026#endif
Darren Tucker2d963d82004-11-07 20:04:10 +110027#ifdef USE_LIBEDIT
28#include <histedit.h>
29#else
30typedef void EditLine;
31#endif
Damien Miller33804262001-02-04 23:20:18 +110032
33#include "buffer.h"
34#include "xmalloc.h"
35#include "log.h"
36#include "pathnames.h"
Ben Lindstrom4529b702001-05-03 23:39:53 +000037#include "misc.h"
Damien Miller33804262001-02-04 23:20:18 +110038
39#include "sftp.h"
40#include "sftp-common.h"
41#include "sftp-client.h"
Damien Millerd7d46bb2004-02-18 14:11:13 +110042
Damien Miller20e1fab2004-02-18 14:30:55 +110043/* File to read commands from */
44FILE* infile;
45
46/* Are we in batchfile mode? */
47int batchmode = 0;
48
49/* Size of buffer used when copying files */
50size_t copy_buffer_len = 32768;
51
52/* Number of concurrent outstanding requests */
53size_t num_requests = 16;
54
55/* PID of ssh transport process */
56static pid_t sshpid = -1;
57
58/* This is set to 0 if the progressmeter is not desired. */
Damien Millerc0f27d82004-03-08 23:12:19 +110059int showprogress = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +110060
Darren Tuckercdf547a2004-05-24 10:12:19 +100061/* SIGINT received during command processing */
62volatile sig_atomic_t interrupted = 0;
63
Darren Tuckerb9123452004-06-22 13:06:45 +100064/* I wish qsort() took a separate ctx for the comparison function...*/
65int sort_flag;
66
Damien Miller20e1fab2004-02-18 14:30:55 +110067int remote_glob(struct sftp_conn *, const char *, int,
68 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
Damien Miller33804262001-02-04 23:20:18 +110069
Kevin Steves12888d12001-03-05 19:50:57 +000070extern char *__progname;
Kevin Steves12888d12001-03-05 19:50:57 +000071
Damien Miller20e1fab2004-02-18 14:30:55 +110072/* Separators for interactive commands */
73#define WHITESPACE " \t\r\n"
Damien Millerd7686fd2001-02-10 00:40:03 +110074
Darren Tuckerb9123452004-06-22 13:06:45 +100075/* ls flags */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100076#define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
77#define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
78#define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
79#define LS_NAME_SORT 0x08 /* Sort by name (default) */
80#define LS_TIME_SORT 0x10 /* Sort by mtime */
81#define LS_SIZE_SORT 0x20 /* Sort by file size */
82#define LS_REVERSE_SORT 0x40 /* Reverse sort order */
Darren Tucker9a526452004-06-22 13:09:55 +100083#define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
Darren Tuckerb9123452004-06-22 13:06:45 +100084
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100085#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
86#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
Damien Miller20e1fab2004-02-18 14:30:55 +110087
88/* Commands for interactive mode */
89#define I_CHDIR 1
90#define I_CHGRP 2
91#define I_CHMOD 3
92#define I_CHOWN 4
93#define I_GET 5
94#define I_HELP 6
95#define I_LCHDIR 7
96#define I_LLS 8
97#define I_LMKDIR 9
98#define I_LPWD 10
99#define I_LS 11
100#define I_LUMASK 12
101#define I_MKDIR 13
102#define I_PUT 14
103#define I_PWD 15
104#define I_QUIT 16
105#define I_RENAME 17
106#define I_RM 18
107#define I_RMDIR 19
108#define I_SHELL 20
109#define I_SYMLINK 21
110#define I_VERSION 22
111#define I_PROGRESS 23
112
113struct CMD {
114 const char *c;
115 const int n;
116};
117
118static const struct CMD cmds[] = {
119 { "bye", I_QUIT },
120 { "cd", I_CHDIR },
121 { "chdir", I_CHDIR },
122 { "chgrp", I_CHGRP },
123 { "chmod", I_CHMOD },
124 { "chown", I_CHOWN },
125 { "dir", I_LS },
126 { "exit", I_QUIT },
127 { "get", I_GET },
128 { "mget", I_GET },
129 { "help", I_HELP },
130 { "lcd", I_LCHDIR },
131 { "lchdir", I_LCHDIR },
132 { "lls", I_LLS },
133 { "lmkdir", I_LMKDIR },
134 { "ln", I_SYMLINK },
135 { "lpwd", I_LPWD },
136 { "ls", I_LS },
137 { "lumask", I_LUMASK },
138 { "mkdir", I_MKDIR },
139 { "progress", I_PROGRESS },
140 { "put", I_PUT },
141 { "mput", I_PUT },
142 { "pwd", I_PWD },
143 { "quit", I_QUIT },
144 { "rename", I_RENAME },
145 { "rm", I_RM },
146 { "rmdir", I_RMDIR },
147 { "symlink", I_SYMLINK },
148 { "version", I_VERSION },
149 { "!", I_SHELL },
150 { "?", I_HELP },
151 { NULL, -1}
152};
153
154int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
155
156static void
Darren Tuckercdf547a2004-05-24 10:12:19 +1000157killchild(int signo)
158{
Darren Tuckerba66df82005-01-24 21:57:40 +1100159 if (sshpid > 1) {
Darren Tuckercdf547a2004-05-24 10:12:19 +1000160 kill(sshpid, SIGTERM);
Darren Tuckerba66df82005-01-24 21:57:40 +1100161 waitpid(sshpid, NULL, 0);
162 }
Darren Tuckercdf547a2004-05-24 10:12:19 +1000163
164 _exit(1);
165}
166
167static void
168cmd_interrupt(int signo)
169{
170 const char msg[] = "\rInterrupt \n";
Darren Tuckere2f189a2004-12-06 22:45:53 +1100171 int olderrno = errno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000172
173 write(STDERR_FILENO, msg, sizeof(msg) - 1);
174 interrupted = 1;
Darren Tuckere2f189a2004-12-06 22:45:53 +1100175 errno = olderrno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000176}
177
178static void
Damien Miller20e1fab2004-02-18 14:30:55 +1100179help(void)
180{
181 printf("Available commands:\n");
182 printf("cd path Change remote directory to 'path'\n");
183 printf("lcd path Change local directory to 'path'\n");
184 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
185 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
186 printf("chown own path Change owner of file 'path' to 'own'\n");
187 printf("help Display this help text\n");
188 printf("get remote-path [local-path] Download file\n");
189 printf("lls [ls-options [path]] Display local directory listing\n");
190 printf("ln oldpath newpath Symlink remote file\n");
191 printf("lmkdir path Create local directory\n");
192 printf("lpwd Print local working directory\n");
193 printf("ls [path] Display remote directory listing\n");
194 printf("lumask umask Set local umask to 'umask'\n");
195 printf("mkdir path Create remote directory\n");
196 printf("progress Toggle display of progress meter\n");
197 printf("put local-path [remote-path] Upload file\n");
198 printf("pwd Display remote working directory\n");
199 printf("exit Quit sftp\n");
200 printf("quit Quit sftp\n");
201 printf("rename oldpath newpath Rename remote file\n");
202 printf("rmdir path Remove remote directory\n");
203 printf("rm path Delete remote file\n");
204 printf("symlink oldpath newpath Symlink remote file\n");
205 printf("version Show SFTP version\n");
206 printf("!command Execute 'command' in local shell\n");
207 printf("! Escape to local shell\n");
208 printf("? Synonym for help\n");
209}
210
211static void
212local_do_shell(const char *args)
213{
214 int status;
215 char *shell;
216 pid_t pid;
217
218 if (!*args)
219 args = NULL;
220
221 if ((shell = getenv("SHELL")) == NULL)
222 shell = _PATH_BSHELL;
223
224 if ((pid = fork()) == -1)
225 fatal("Couldn't fork: %s", strerror(errno));
226
227 if (pid == 0) {
228 /* XXX: child has pipe fds to ssh subproc open - issue? */
229 if (args) {
230 debug3("Executing %s -c \"%s\"", shell, args);
231 execl(shell, shell, "-c", args, (char *)NULL);
232 } else {
233 debug3("Executing %s", shell);
234 execl(shell, shell, (char *)NULL);
235 }
236 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
237 strerror(errno));
238 _exit(1);
239 }
240 while (waitpid(pid, &status, 0) == -1)
241 if (errno != EINTR)
242 fatal("Couldn't wait for child: %s", strerror(errno));
243 if (!WIFEXITED(status))
244 error("Shell exited abormally");
245 else if (WEXITSTATUS(status))
246 error("Shell exited with status %d", WEXITSTATUS(status));
247}
248
249static void
250local_do_ls(const char *args)
251{
252 if (!args || !*args)
253 local_do_shell(_PATH_LS);
254 else {
255 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
256 char *buf = xmalloc(len);
257
258 /* XXX: quoting - rip quoting code from ftp? */
259 snprintf(buf, len, _PATH_LS " %s", args);
260 local_do_shell(buf);
261 xfree(buf);
262 }
263}
264
265/* Strip one path (usually the pwd) from the start of another */
266static char *
267path_strip(char *path, char *strip)
268{
269 size_t len;
270
271 if (strip == NULL)
272 return (xstrdup(path));
273
274 len = strlen(strip);
Darren Tuckere2f189a2004-12-06 22:45:53 +1100275 if (strncmp(path, strip, len) == 0) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100276 if (strip[len - 1] != '/' && path[len] == '/')
277 len++;
278 return (xstrdup(path + len));
279 }
280
281 return (xstrdup(path));
282}
283
284static char *
285path_append(char *p1, char *p2)
286{
287 char *ret;
288 int len = strlen(p1) + strlen(p2) + 2;
289
290 ret = xmalloc(len);
291 strlcpy(ret, p1, len);
292 if (p1[strlen(p1) - 1] != '/')
293 strlcat(ret, "/", len);
294 strlcat(ret, p2, len);
295
296 return(ret);
297}
298
299static char *
300make_absolute(char *p, char *pwd)
301{
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000302 char *abs_str;
Damien Miller20e1fab2004-02-18 14:30:55 +1100303
304 /* Derelativise */
305 if (p && p[0] != '/') {
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000306 abs_str = path_append(pwd, p);
Damien Miller20e1fab2004-02-18 14:30:55 +1100307 xfree(p);
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000308 return(abs_str);
Damien Miller20e1fab2004-02-18 14:30:55 +1100309 } else
310 return(p);
311}
312
313static int
314infer_path(const char *p, char **ifp)
315{
316 char *cp;
317
318 cp = strrchr(p, '/');
319 if (cp == NULL) {
320 *ifp = xstrdup(p);
321 return(0);
322 }
323
324 if (!cp[1]) {
325 error("Invalid path");
326 return(-1);
327 }
328
329 *ifp = xstrdup(cp + 1);
330 return(0);
331}
332
333static int
334parse_getput_flags(const char **cpp, int *pflag)
335{
336 const char *cp = *cpp;
337
338 /* Check for flags */
339 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
340 switch (cp[1]) {
341 case 'p':
342 case 'P':
343 *pflag = 1;
344 break;
345 default:
346 error("Invalid flag -%c", cp[1]);
347 return(-1);
348 }
349 cp += 2;
350 *cpp = cp + strspn(cp, WHITESPACE);
351 }
352
353 return(0);
354}
355
356static int
357parse_ls_flags(const char **cpp, int *lflag)
358{
359 const char *cp = *cpp;
360
Darren Tuckerb9123452004-06-22 13:06:45 +1000361 /* Defaults */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000362 *lflag = LS_NAME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000363
Damien Miller20e1fab2004-02-18 14:30:55 +1100364 /* Check for flags */
365 if (cp++[0] == '-') {
Darren Tucker47eede72005-03-14 23:08:12 +1100366 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100367 switch (*cp) {
368 case 'l':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000369 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000370 *lflag |= LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100371 break;
372 case '1':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000373 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000374 *lflag |= LS_SHORT_VIEW;
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000375 break;
376 case 'n':
377 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000378 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100379 break;
Darren Tuckerb9123452004-06-22 13:06:45 +1000380 case 'S':
381 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000382 *lflag |= LS_SIZE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000383 break;
384 case 't':
385 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000386 *lflag |= LS_TIME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000387 break;
388 case 'r':
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000389 *lflag |= LS_REVERSE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000390 break;
391 case 'f':
392 *lflag &= ~SORT_FLAGS;
393 break;
Darren Tucker9a526452004-06-22 13:09:55 +1000394 case 'a':
395 *lflag |= LS_SHOW_ALL;
396 break;
Damien Miller20e1fab2004-02-18 14:30:55 +1100397 default:
398 error("Invalid flag -%c", *cp);
399 return(-1);
400 }
401 }
402 *cpp = cp + strspn(cp, WHITESPACE);
403 }
404
405 return(0);
406}
407
408static int
409get_pathname(const char **cpp, char **path)
410{
411 const char *cp = *cpp, *end;
412 char quot;
Damien Millereccb9de2005-06-17 12:59:34 +1000413 u_int i, j;
Damien Miller20e1fab2004-02-18 14:30:55 +1100414
415 cp += strspn(cp, WHITESPACE);
416 if (!*cp) {
417 *cpp = cp;
418 *path = NULL;
419 return (0);
420 }
421
422 *path = xmalloc(strlen(cp) + 1);
423
424 /* Check for quoted filenames */
425 if (*cp == '\"' || *cp == '\'') {
426 quot = *cp++;
427
428 /* Search for terminating quote, unescape some chars */
429 for (i = j = 0; i <= strlen(cp); i++) {
430 if (cp[i] == quot) { /* Found quote */
431 i++;
432 (*path)[j] = '\0';
433 break;
434 }
435 if (cp[i] == '\0') { /* End of string */
436 error("Unterminated quote");
437 goto fail;
438 }
439 if (cp[i] == '\\') { /* Escaped characters */
440 i++;
441 if (cp[i] != '\'' && cp[i] != '\"' &&
442 cp[i] != '\\') {
Damien Miller96d6d7d2004-06-26 09:21:06 +1000443 error("Bad escaped character '\\%c'",
Damien Miller20e1fab2004-02-18 14:30:55 +1100444 cp[i]);
445 goto fail;
446 }
447 }
448 (*path)[j++] = cp[i];
449 }
450
451 if (j == 0) {
452 error("Empty quotes");
453 goto fail;
454 }
455 *cpp = cp + i + strspn(cp + i, WHITESPACE);
456 } else {
457 /* Read to end of filename */
458 end = strpbrk(cp, WHITESPACE);
459 if (end == NULL)
460 end = strchr(cp, '\0');
461 *cpp = end + strspn(end, WHITESPACE);
462
463 memcpy(*path, cp, end - cp);
464 (*path)[end - cp] = '\0';
465 }
466 return (0);
467
468 fail:
469 xfree(*path);
470 *path = NULL;
471 return (-1);
472}
473
474static int
475is_dir(char *path)
476{
477 struct stat sb;
478
479 /* XXX: report errors? */
480 if (stat(path, &sb) == -1)
481 return(0);
482
483 return(sb.st_mode & S_IFDIR);
484}
485
486static int
487is_reg(char *path)
488{
489 struct stat sb;
490
491 if (stat(path, &sb) == -1)
492 fatal("stat %s: %s", path, strerror(errno));
493
494 return(S_ISREG(sb.st_mode));
495}
496
497static int
498remote_is_dir(struct sftp_conn *conn, char *path)
499{
500 Attrib *a;
501
502 /* XXX: report errors? */
503 if ((a = do_stat(conn, path, 1)) == NULL)
504 return(0);
505 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
506 return(0);
507 return(a->perm & S_IFDIR);
508}
509
510static int
511process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
512{
513 char *abs_src = NULL;
514 char *abs_dst = NULL;
515 char *tmp;
516 glob_t g;
517 int err = 0;
518 int i;
519
520 abs_src = xstrdup(src);
521 abs_src = make_absolute(abs_src, pwd);
522
523 memset(&g, 0, sizeof(g));
524 debug3("Looking up %s", abs_src);
525 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
526 error("File \"%s\" not found.", abs_src);
527 err = -1;
528 goto out;
529 }
530
531 /* If multiple matches, dst must be a directory or unspecified */
532 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
533 error("Multiple files match, but \"%s\" is not a directory",
534 dst);
535 err = -1;
536 goto out;
537 }
538
Darren Tuckercdf547a2004-05-24 10:12:19 +1000539 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100540 if (infer_path(g.gl_pathv[i], &tmp)) {
541 err = -1;
542 goto out;
543 }
544
545 if (g.gl_matchc == 1 && dst) {
546 /* If directory specified, append filename */
547 if (is_dir(dst)) {
548 if (infer_path(g.gl_pathv[0], &tmp)) {
549 err = 1;
550 goto out;
551 }
552 abs_dst = path_append(dst, tmp);
553 xfree(tmp);
554 } else
555 abs_dst = xstrdup(dst);
556 } else if (dst) {
557 abs_dst = path_append(dst, tmp);
558 xfree(tmp);
559 } else
560 abs_dst = tmp;
561
562 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
563 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
564 err = -1;
565 xfree(abs_dst);
566 abs_dst = NULL;
567 }
568
569out:
570 xfree(abs_src);
571 if (abs_dst)
572 xfree(abs_dst);
573 globfree(&g);
574 return(err);
575}
576
577static int
578process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
579{
580 char *tmp_dst = NULL;
581 char *abs_dst = NULL;
582 char *tmp;
583 glob_t g;
584 int err = 0;
585 int i;
586
587 if (dst) {
588 tmp_dst = xstrdup(dst);
589 tmp_dst = make_absolute(tmp_dst, pwd);
590 }
591
592 memset(&g, 0, sizeof(g));
593 debug3("Looking up %s", src);
594 if (glob(src, 0, NULL, &g)) {
595 error("File \"%s\" not found.", src);
596 err = -1;
597 goto out;
598 }
599
600 /* If multiple matches, dst may be directory or unspecified */
601 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
602 error("Multiple files match, but \"%s\" is not a directory",
603 tmp_dst);
604 err = -1;
605 goto out;
606 }
607
Darren Tuckercdf547a2004-05-24 10:12:19 +1000608 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100609 if (!is_reg(g.gl_pathv[i])) {
610 error("skipping non-regular file %s",
611 g.gl_pathv[i]);
612 continue;
613 }
614 if (infer_path(g.gl_pathv[i], &tmp)) {
615 err = -1;
616 goto out;
617 }
618
619 if (g.gl_matchc == 1 && tmp_dst) {
620 /* If directory specified, append filename */
621 if (remote_is_dir(conn, tmp_dst)) {
622 if (infer_path(g.gl_pathv[0], &tmp)) {
623 err = 1;
624 goto out;
625 }
626 abs_dst = path_append(tmp_dst, tmp);
627 xfree(tmp);
628 } else
629 abs_dst = xstrdup(tmp_dst);
630
631 } else if (tmp_dst) {
632 abs_dst = path_append(tmp_dst, tmp);
633 xfree(tmp);
634 } else
635 abs_dst = make_absolute(tmp, pwd);
636
637 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
638 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
639 err = -1;
640 }
641
642out:
643 if (abs_dst)
644 xfree(abs_dst);
645 if (tmp_dst)
646 xfree(tmp_dst);
647 globfree(&g);
648 return(err);
649}
650
651static int
652sdirent_comp(const void *aa, const void *bb)
653{
654 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
655 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000656 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100657
Darren Tuckerb9123452004-06-22 13:06:45 +1000658#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000659 if (sort_flag & LS_NAME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000660 return (rmul * strcmp(a->filename, b->filename));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000661 else if (sort_flag & LS_TIME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000662 return (rmul * NCMP(a->a.mtime, b->a.mtime));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000663 else if (sort_flag & LS_SIZE_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000664 return (rmul * NCMP(a->a.size, b->a.size));
665
666 fatal("Unknown ls sort type");
Damien Miller20e1fab2004-02-18 14:30:55 +1100667}
668
669/* sftp ls.1 replacement for directories */
670static int
671do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
672{
Damien Millereccb9de2005-06-17 12:59:34 +1000673 int n;
674 u_int c = 1, colspace = 0, columns = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100675 SFTP_DIRENT **d;
676
677 if ((n = do_readdir(conn, path, &d)) != 0)
678 return (n);
679
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000680 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000681 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100682 struct winsize ws;
683 char *tmp;
684
685 /* Count entries for sort and find longest filename */
Darren Tucker9a526452004-06-22 13:09:55 +1000686 for (n = 0; d[n] != NULL; n++) {
687 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
688 m = MAX(m, strlen(d[n]->filename));
689 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100690
691 /* Add any subpath that also needs to be counted */
692 tmp = path_strip(path, strip_path);
693 m += strlen(tmp);
694 xfree(tmp);
695
696 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
697 width = ws.ws_col;
698
699 columns = width / (m + 2);
700 columns = MAX(columns, 1);
701 colspace = width / columns;
702 colspace = MIN(colspace, width);
703 }
704
Darren Tuckerb9123452004-06-22 13:06:45 +1000705 if (lflag & SORT_FLAGS) {
Damien Miller653b93b2005-11-05 15:15:23 +1100706 for (n = 0; d[n] != NULL; n++)
707 ; /* count entries */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000708 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
Darren Tuckerb9123452004-06-22 13:06:45 +1000709 qsort(d, n, sizeof(*d), sdirent_comp);
710 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100711
Darren Tuckercdf547a2004-05-24 10:12:19 +1000712 for (n = 0; d[n] != NULL && !interrupted; n++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100713 char *tmp, *fname;
714
Darren Tucker9a526452004-06-22 13:09:55 +1000715 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
716 continue;
717
Damien Miller20e1fab2004-02-18 14:30:55 +1100718 tmp = path_append(path, d[n]->filename);
719 fname = path_strip(tmp, strip_path);
720 xfree(tmp);
721
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000722 if (lflag & LS_LONG_VIEW) {
723 if (lflag & LS_NUMERIC_VIEW) {
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000724 char *lname;
725 struct stat sb;
Damien Miller20e1fab2004-02-18 14:30:55 +1100726
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000727 memset(&sb, 0, sizeof(sb));
728 attrib_to_stat(&d[n]->a, &sb);
729 lname = ls_file(fname, &sb, 1);
730 printf("%s\n", lname);
731 xfree(lname);
732 } else
733 printf("%s\n", d[n]->longname);
Damien Miller20e1fab2004-02-18 14:30:55 +1100734 } else {
735 printf("%-*s", colspace, fname);
736 if (c >= columns) {
737 printf("\n");
738 c = 1;
739 } else
740 c++;
741 }
742
743 xfree(fname);
744 }
745
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000746 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100747 printf("\n");
748
749 free_sftp_dirents(d);
750 return (0);
751}
752
753/* sftp ls.1 replacement which handles path globs */
754static int
755do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
756 int lflag)
757{
758 glob_t g;
Damien Millereccb9de2005-06-17 12:59:34 +1000759 u_int i, c = 1, colspace = 0, columns = 1;
Darren Tucker596dcfa2004-12-11 13:37:22 +1100760 Attrib *a = NULL;
Damien Miller20e1fab2004-02-18 14:30:55 +1100761
762 memset(&g, 0, sizeof(g));
763
764 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
Darren Tucker596dcfa2004-12-11 13:37:22 +1100765 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
766 if (g.gl_pathc)
767 globfree(&g);
Damien Miller20e1fab2004-02-18 14:30:55 +1100768 error("Can't ls: \"%s\" not found", path);
769 return (-1);
770 }
771
Darren Tuckercdf547a2004-05-24 10:12:19 +1000772 if (interrupted)
773 goto out;
774
Damien Miller20e1fab2004-02-18 14:30:55 +1100775 /*
Darren Tucker596dcfa2004-12-11 13:37:22 +1100776 * If the glob returns a single match and it is a directory,
777 * then just list its contents.
Damien Miller20e1fab2004-02-18 14:30:55 +1100778 */
Darren Tucker596dcfa2004-12-11 13:37:22 +1100779 if (g.gl_matchc == 1) {
780 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100781 globfree(&g);
782 return (-1);
783 }
784 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
785 S_ISDIR(a->perm)) {
Darren Tucker596dcfa2004-12-11 13:37:22 +1100786 int err;
787
788 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
Damien Miller20e1fab2004-02-18 14:30:55 +1100789 globfree(&g);
Darren Tucker596dcfa2004-12-11 13:37:22 +1100790 return (err);
Damien Miller20e1fab2004-02-18 14:30:55 +1100791 }
792 }
793
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000794 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000795 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100796 struct winsize ws;
797
798 /* Count entries for sort and find longest filename */
799 for (i = 0; g.gl_pathv[i]; i++)
800 m = MAX(m, strlen(g.gl_pathv[i]));
801
802 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
803 width = ws.ws_col;
804
805 columns = width / (m + 2);
806 columns = MAX(columns, 1);
807 colspace = width / columns;
808 }
809
Darren Tucker596dcfa2004-12-11 13:37:22 +1100810 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100811 char *fname;
812
813 fname = path_strip(g.gl_pathv[i], strip_path);
814
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000815 if (lflag & LS_LONG_VIEW) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100816 char *lname;
817 struct stat sb;
818
819 /*
820 * XXX: this is slow - 1 roundtrip per path
821 * A solution to this is to fork glob() and
822 * build a sftp specific version which keeps the
823 * attribs (which currently get thrown away)
824 * that the server returns as well as the filenames.
825 */
826 memset(&sb, 0, sizeof(sb));
Darren Tucker596dcfa2004-12-11 13:37:22 +1100827 if (a == NULL)
828 a = do_lstat(conn, g.gl_pathv[i], 1);
Damien Miller20e1fab2004-02-18 14:30:55 +1100829 if (a != NULL)
830 attrib_to_stat(a, &sb);
831 lname = ls_file(fname, &sb, 1);
832 printf("%s\n", lname);
833 xfree(lname);
834 } else {
835 printf("%-*s", colspace, fname);
836 if (c >= columns) {
837 printf("\n");
838 c = 1;
839 } else
840 c++;
841 }
842 xfree(fname);
843 }
844
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000845 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100846 printf("\n");
847
Darren Tuckercdf547a2004-05-24 10:12:19 +1000848 out:
Damien Miller20e1fab2004-02-18 14:30:55 +1100849 if (g.gl_pathc)
850 globfree(&g);
851
852 return (0);
853}
854
855static int
856parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
857 unsigned long *n_arg, char **path1, char **path2)
858{
859 const char *cmd, *cp = *cpp;
860 char *cp2;
861 int base = 0;
862 long l;
863 int i, cmdnum;
864
865 /* Skip leading whitespace */
866 cp = cp + strspn(cp, WHITESPACE);
867
868 /* Ignore blank lines and lines which begin with comment '#' char */
869 if (*cp == '\0' || *cp == '#')
870 return (0);
871
872 /* Check for leading '-' (disable error processing) */
873 *iflag = 0;
874 if (*cp == '-') {
875 *iflag = 1;
876 cp++;
877 }
878
879 /* Figure out which command we have */
880 for (i = 0; cmds[i].c; i++) {
881 int cmdlen = strlen(cmds[i].c);
882
883 /* Check for command followed by whitespace */
884 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
885 strchr(WHITESPACE, cp[cmdlen])) {
886 cp += cmdlen;
887 cp = cp + strspn(cp, WHITESPACE);
888 break;
889 }
890 }
891 cmdnum = cmds[i].n;
892 cmd = cmds[i].c;
893
894 /* Special case */
895 if (*cp == '!') {
896 cp++;
897 cmdnum = I_SHELL;
898 } else if (cmdnum == -1) {
899 error("Invalid command.");
900 return (-1);
901 }
902
903 /* Get arguments and parse flags */
904 *lflag = *pflag = *n_arg = 0;
905 *path1 = *path2 = NULL;
906 switch (cmdnum) {
907 case I_GET:
908 case I_PUT:
909 if (parse_getput_flags(&cp, pflag))
910 return(-1);
911 /* Get first pathname (mandatory) */
912 if (get_pathname(&cp, path1))
913 return(-1);
914 if (*path1 == NULL) {
915 error("You must specify at least one path after a "
916 "%s command.", cmd);
917 return(-1);
918 }
919 /* Try to get second pathname (optional) */
920 if (get_pathname(&cp, path2))
921 return(-1);
922 break;
923 case I_RENAME:
924 case I_SYMLINK:
925 if (get_pathname(&cp, path1))
926 return(-1);
927 if (get_pathname(&cp, path2))
928 return(-1);
929 if (!*path1 || !*path2) {
930 error("You must specify two paths after a %s "
931 "command.", cmd);
932 return(-1);
933 }
934 break;
935 case I_RM:
936 case I_MKDIR:
937 case I_RMDIR:
938 case I_CHDIR:
939 case I_LCHDIR:
940 case I_LMKDIR:
941 /* Get pathname (mandatory) */
942 if (get_pathname(&cp, path1))
943 return(-1);
944 if (*path1 == NULL) {
945 error("You must specify a path after a %s command.",
946 cmd);
947 return(-1);
948 }
949 break;
950 case I_LS:
951 if (parse_ls_flags(&cp, lflag))
952 return(-1);
953 /* Path is optional */
954 if (get_pathname(&cp, path1))
955 return(-1);
956 break;
957 case I_LLS:
958 case I_SHELL:
959 /* Uses the rest of the line */
960 break;
961 case I_LUMASK:
962 base = 8;
963 case I_CHMOD:
964 base = 8;
965 case I_CHOWN:
966 case I_CHGRP:
967 /* Get numeric arg (mandatory) */
968 l = strtol(cp, &cp2, base);
969 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
970 errno == ERANGE) || l < 0) {
971 error("You must supply a numeric argument "
972 "to the %s command.", cmd);
973 return(-1);
974 }
975 cp = cp2;
976 *n_arg = l;
977 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
978 break;
979 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
980 error("You must supply a numeric argument "
981 "to the %s command.", cmd);
982 return(-1);
983 }
984 cp += strspn(cp, WHITESPACE);
985
986 /* Get pathname (mandatory) */
987 if (get_pathname(&cp, path1))
988 return(-1);
989 if (*path1 == NULL) {
990 error("You must specify a path after a %s command.",
991 cmd);
992 return(-1);
993 }
994 break;
995 case I_QUIT:
996 case I_PWD:
997 case I_LPWD:
998 case I_HELP:
999 case I_VERSION:
1000 case I_PROGRESS:
1001 break;
1002 default:
1003 fatal("Command not implemented");
1004 }
1005
1006 *cpp = cp;
1007 return(cmdnum);
1008}
1009
1010static int
1011parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1012 int err_abort)
1013{
1014 char *path1, *path2, *tmp;
1015 int pflag, lflag, iflag, cmdnum, i;
1016 unsigned long n_arg;
1017 Attrib a, *aa;
1018 char path_buf[MAXPATHLEN];
1019 int err = 0;
1020 glob_t g;
1021
1022 path1 = path2 = NULL;
1023 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1024 &path1, &path2);
1025
1026 if (iflag != 0)
1027 err_abort = 0;
1028
1029 memset(&g, 0, sizeof(g));
1030
1031 /* Perform command */
1032 switch (cmdnum) {
1033 case 0:
1034 /* Blank line */
1035 break;
1036 case -1:
1037 /* Unrecognized command */
1038 err = -1;
1039 break;
1040 case I_GET:
1041 err = process_get(conn, path1, path2, *pwd, pflag);
1042 break;
1043 case I_PUT:
1044 err = process_put(conn, path1, path2, *pwd, pflag);
1045 break;
1046 case I_RENAME:
1047 path1 = make_absolute(path1, *pwd);
1048 path2 = make_absolute(path2, *pwd);
1049 err = do_rename(conn, path1, path2);
1050 break;
1051 case I_SYMLINK:
1052 path2 = make_absolute(path2, *pwd);
1053 err = do_symlink(conn, path1, path2);
1054 break;
1055 case I_RM:
1056 path1 = make_absolute(path1, *pwd);
1057 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001058 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001059 printf("Removing %s\n", g.gl_pathv[i]);
1060 err = do_rm(conn, g.gl_pathv[i]);
1061 if (err != 0 && err_abort)
1062 break;
1063 }
1064 break;
1065 case I_MKDIR:
1066 path1 = make_absolute(path1, *pwd);
1067 attrib_clear(&a);
1068 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1069 a.perm = 0777;
1070 err = do_mkdir(conn, path1, &a);
1071 break;
1072 case I_RMDIR:
1073 path1 = make_absolute(path1, *pwd);
1074 err = do_rmdir(conn, path1);
1075 break;
1076 case I_CHDIR:
1077 path1 = make_absolute(path1, *pwd);
1078 if ((tmp = do_realpath(conn, path1)) == NULL) {
1079 err = 1;
1080 break;
1081 }
1082 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1083 xfree(tmp);
1084 err = 1;
1085 break;
1086 }
1087 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1088 error("Can't change directory: Can't check target");
1089 xfree(tmp);
1090 err = 1;
1091 break;
1092 }
1093 if (!S_ISDIR(aa->perm)) {
1094 error("Can't change directory: \"%s\" is not "
1095 "a directory", tmp);
1096 xfree(tmp);
1097 err = 1;
1098 break;
1099 }
1100 xfree(*pwd);
1101 *pwd = tmp;
1102 break;
1103 case I_LS:
1104 if (!path1) {
1105 do_globbed_ls(conn, *pwd, *pwd, lflag);
1106 break;
1107 }
1108
1109 /* Strip pwd off beginning of non-absolute paths */
1110 tmp = NULL;
1111 if (*path1 != '/')
1112 tmp = *pwd;
1113
1114 path1 = make_absolute(path1, *pwd);
1115 err = do_globbed_ls(conn, path1, tmp, lflag);
1116 break;
1117 case I_LCHDIR:
1118 if (chdir(path1) == -1) {
1119 error("Couldn't change local directory to "
1120 "\"%s\": %s", path1, strerror(errno));
1121 err = 1;
1122 }
1123 break;
1124 case I_LMKDIR:
1125 if (mkdir(path1, 0777) == -1) {
1126 error("Couldn't create local directory "
1127 "\"%s\": %s", path1, strerror(errno));
1128 err = 1;
1129 }
1130 break;
1131 case I_LLS:
1132 local_do_ls(cmd);
1133 break;
1134 case I_SHELL:
1135 local_do_shell(cmd);
1136 break;
1137 case I_LUMASK:
1138 umask(n_arg);
1139 printf("Local umask: %03lo\n", n_arg);
1140 break;
1141 case I_CHMOD:
1142 path1 = make_absolute(path1, *pwd);
1143 attrib_clear(&a);
1144 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1145 a.perm = n_arg;
1146 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001147 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001148 printf("Changing mode on %s\n", g.gl_pathv[i]);
1149 err = do_setstat(conn, g.gl_pathv[i], &a);
1150 if (err != 0 && err_abort)
1151 break;
1152 }
1153 break;
1154 case I_CHOWN:
1155 case I_CHGRP:
1156 path1 = make_absolute(path1, *pwd);
1157 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001158 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001159 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1160 if (err != 0 && err_abort)
1161 break;
1162 else
1163 continue;
1164 }
1165 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1166 error("Can't get current ownership of "
1167 "remote file \"%s\"", g.gl_pathv[i]);
1168 if (err != 0 && err_abort)
1169 break;
1170 else
1171 continue;
1172 }
1173 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1174 if (cmdnum == I_CHOWN) {
1175 printf("Changing owner on %s\n", g.gl_pathv[i]);
1176 aa->uid = n_arg;
1177 } else {
1178 printf("Changing group on %s\n", g.gl_pathv[i]);
1179 aa->gid = n_arg;
1180 }
1181 err = do_setstat(conn, g.gl_pathv[i], aa);
1182 if (err != 0 && err_abort)
1183 break;
1184 }
1185 break;
1186 case I_PWD:
1187 printf("Remote working directory: %s\n", *pwd);
1188 break;
1189 case I_LPWD:
1190 if (!getcwd(path_buf, sizeof(path_buf))) {
1191 error("Couldn't get local cwd: %s", strerror(errno));
1192 err = -1;
1193 break;
1194 }
1195 printf("Local working directory: %s\n", path_buf);
1196 break;
1197 case I_QUIT:
1198 /* Processed below */
1199 break;
1200 case I_HELP:
1201 help();
1202 break;
1203 case I_VERSION:
1204 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1205 break;
1206 case I_PROGRESS:
1207 showprogress = !showprogress;
1208 if (showprogress)
1209 printf("Progress meter enabled\n");
1210 else
1211 printf("Progress meter disabled\n");
1212 break;
1213 default:
1214 fatal("%d is not implemented", cmdnum);
1215 }
1216
1217 if (g.gl_pathc)
1218 globfree(&g);
1219 if (path1)
1220 xfree(path1);
1221 if (path2)
1222 xfree(path2);
1223
1224 /* If an unignored error occurs in batch mode we should abort. */
1225 if (err_abort && err != 0)
1226 return (-1);
1227 else if (cmdnum == I_QUIT)
1228 return (1);
1229
1230 return (0);
1231}
1232
Darren Tucker2d963d82004-11-07 20:04:10 +11001233#ifdef USE_LIBEDIT
1234static char *
1235prompt(EditLine *el)
1236{
1237 return ("sftp> ");
1238}
1239#endif
1240
Damien Miller20e1fab2004-02-18 14:30:55 +11001241int
1242interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1243{
1244 char *pwd;
1245 char *dir = NULL;
1246 char cmd[2048];
1247 struct sftp_conn *conn;
Damien Miller0e2c1022005-08-12 22:16:22 +10001248 int err, interactive;
Darren Tucker2d963d82004-11-07 20:04:10 +11001249 EditLine *el = NULL;
1250#ifdef USE_LIBEDIT
1251 History *hl = NULL;
1252 HistEvent hev;
1253 extern char *__progname;
1254
1255 if (!batchmode && isatty(STDIN_FILENO)) {
1256 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1257 fatal("Couldn't initialise editline");
1258 if ((hl = history_init()) == NULL)
1259 fatal("Couldn't initialise editline history");
1260 history(hl, &hev, H_SETSIZE, 100);
1261 el_set(el, EL_HIST, history, hl);
1262
1263 el_set(el, EL_PROMPT, prompt);
1264 el_set(el, EL_EDITOR, "emacs");
1265 el_set(el, EL_TERMINAL, NULL);
1266 el_set(el, EL_SIGNAL, 1);
1267 el_source(el, NULL);
1268 }
1269#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001270
1271 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1272 if (conn == NULL)
1273 fatal("Couldn't initialise connection to server");
1274
1275 pwd = do_realpath(conn, ".");
1276 if (pwd == NULL)
1277 fatal("Need cwd");
1278
1279 if (file1 != NULL) {
1280 dir = xstrdup(file1);
1281 dir = make_absolute(dir, pwd);
1282
1283 if (remote_is_dir(conn, dir) && file2 == NULL) {
1284 printf("Changing to: %s\n", dir);
1285 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001286 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1287 xfree(dir);
1288 xfree(pwd);
Damien Miller20e1fab2004-02-18 14:30:55 +11001289 return (-1);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001290 }
Damien Miller20e1fab2004-02-18 14:30:55 +11001291 } else {
1292 if (file2 == NULL)
1293 snprintf(cmd, sizeof cmd, "get %s", dir);
1294 else
1295 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1296 file2);
1297
1298 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1299 xfree(dir);
1300 xfree(pwd);
1301 return (err);
1302 }
1303 xfree(dir);
1304 }
1305
Darren Tucker93e7e8f2005-08-23 08:06:55 +10001306#if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
Damien Miller20e1fab2004-02-18 14:30:55 +11001307 setvbuf(stdout, NULL, _IOLBF, 0);
1308 setvbuf(infile, NULL, _IOLBF, 0);
1309#else
Damien Miller37294fb2005-07-17 17:18:49 +10001310 setlinebuf(stdout);
1311 setlinebuf(infile);
Damien Miller20e1fab2004-02-18 14:30:55 +11001312#endif
1313
Damien Miller0e2c1022005-08-12 22:16:22 +10001314 interactive = !batchmode && isatty(STDIN_FILENO);
Damien Miller20e1fab2004-02-18 14:30:55 +11001315 err = 0;
1316 for (;;) {
1317 char *cp;
1318
Darren Tuckercdf547a2004-05-24 10:12:19 +10001319 signal(SIGINT, SIG_IGN);
1320
Darren Tucker2d963d82004-11-07 20:04:10 +11001321 if (el == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001322 if (interactive)
1323 printf("sftp> ");
Darren Tucker2d963d82004-11-07 20:04:10 +11001324 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001325 if (interactive)
1326 printf("\n");
Darren Tucker2d963d82004-11-07 20:04:10 +11001327 break;
1328 }
Damien Miller0e2c1022005-08-12 22:16:22 +10001329 if (!interactive) { /* Echo command */
1330 printf("sftp> %s", cmd);
1331 if (strlen(cmd) > 0 &&
1332 cmd[strlen(cmd) - 1] != '\n')
1333 printf("\n");
1334 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001335 } else {
1336#ifdef USE_LIBEDIT
1337 const char *line;
1338 int count = 0;
Damien Miller20e1fab2004-02-18 14:30:55 +11001339
Damien Miller0e2c1022005-08-12 22:16:22 +10001340 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1341 printf("\n");
1342 break;
1343 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001344 history(hl, &hev, H_ENTER, line);
1345 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1346 fprintf(stderr, "Error: input line too long\n");
1347 continue;
1348 }
1349#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001350 }
1351
Damien Miller20e1fab2004-02-18 14:30:55 +11001352 cp = strrchr(cmd, '\n');
1353 if (cp)
1354 *cp = '\0';
1355
Darren Tuckercdf547a2004-05-24 10:12:19 +10001356 /* Handle user interrupts gracefully during commands */
1357 interrupted = 0;
1358 signal(SIGINT, cmd_interrupt);
1359
Damien Miller20e1fab2004-02-18 14:30:55 +11001360 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1361 if (err != 0)
1362 break;
1363 }
1364 xfree(pwd);
1365
Tim Rice027e8b12005-08-15 14:52:50 -07001366#ifdef USE_LIBEDIT
Damien Miller0e2c1022005-08-12 22:16:22 +10001367 if (el != NULL)
1368 el_end(el);
Tim Rice027e8b12005-08-15 14:52:50 -07001369#endif /* USE_LIBEDIT */
Damien Miller0e2c1022005-08-12 22:16:22 +10001370
Damien Miller20e1fab2004-02-18 14:30:55 +11001371 /* err == 1 signifies normal "quit" exit */
1372 return (err >= 0 ? 0 : -1);
1373}
Damien Miller62d57f62003-01-10 21:43:24 +11001374
Ben Lindstrombba81212001-06-25 05:01:22 +00001375static void
Damien Millercc685c12003-06-04 22:51:38 +10001376connect_to_server(char *path, char **args, int *in, int *out)
Damien Miller33804262001-02-04 23:20:18 +11001377{
1378 int c_in, c_out;
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001379
Damien Miller33804262001-02-04 23:20:18 +11001380#ifdef USE_PIPES
1381 int pin[2], pout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001382
Damien Miller33804262001-02-04 23:20:18 +11001383 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1384 fatal("pipe: %s", strerror(errno));
1385 *in = pin[0];
1386 *out = pout[1];
1387 c_in = pout[0];
1388 c_out = pin[1];
1389#else /* USE_PIPES */
1390 int inout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001391
Damien Miller33804262001-02-04 23:20:18 +11001392 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1393 fatal("socketpair: %s", strerror(errno));
1394 *in = *out = inout[0];
1395 c_in = c_out = inout[1];
1396#endif /* USE_PIPES */
1397
Damien Millercc685c12003-06-04 22:51:38 +10001398 if ((sshpid = fork()) == -1)
Damien Miller33804262001-02-04 23:20:18 +11001399 fatal("fork: %s", strerror(errno));
Damien Millercc685c12003-06-04 22:51:38 +10001400 else if (sshpid == 0) {
Damien Miller33804262001-02-04 23:20:18 +11001401 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1402 (dup2(c_out, STDOUT_FILENO) == -1)) {
1403 fprintf(stderr, "dup2: %s\n", strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001404 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001405 }
1406 close(*in);
1407 close(*out);
1408 close(c_in);
1409 close(c_out);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001410
1411 /*
1412 * The underlying ssh is in the same process group, so we must
Darren Tuckerfc959702004-07-17 16:12:08 +10001413 * ignore SIGINT if we want to gracefully abort commands,
1414 * otherwise the signal will make it to the ssh process and
Darren Tuckercdf547a2004-05-24 10:12:19 +10001415 * kill it too
1416 */
1417 signal(SIGINT, SIG_IGN);
Darren Tuckerbd12f172004-06-18 16:23:43 +10001418 execvp(path, args);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001419 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001420 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001421 }
1422
Damien Millercc685c12003-06-04 22:51:38 +10001423 signal(SIGTERM, killchild);
1424 signal(SIGINT, killchild);
1425 signal(SIGHUP, killchild);
Damien Miller33804262001-02-04 23:20:18 +11001426 close(c_in);
1427 close(c_out);
1428}
1429
Ben Lindstrombba81212001-06-25 05:01:22 +00001430static void
Damien Miller33804262001-02-04 23:20:18 +11001431usage(void)
1432{
Damien Miller025e01c2002-02-08 22:06:29 +11001433 extern char *__progname;
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001434
Ben Lindstrom1e243242001-09-18 05:38:44 +00001435 fprintf(stderr,
Darren Tucker1f203942003-10-15 15:50:42 +10001436 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1437 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1438 " [-S program] [-s subsystem | sftp_server] host\n"
1439 " %s [[user@]host[:file [file]]]\n"
1440 " %s [[user@]host[:dir[/]]]\n"
1441 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
Damien Miller33804262001-02-04 23:20:18 +11001442 exit(1);
1443}
1444
Kevin Stevesef4eea92001-02-05 12:42:17 +00001445int
Damien Miller33804262001-02-04 23:20:18 +11001446main(int argc, char **argv)
1447{
Damien Miller956f3fb2003-01-10 21:40:00 +11001448 int in, out, ch, err;
Damien Miller7cf17eb2004-06-15 10:28:56 +10001449 char *host, *userhost, *cp, *file2 = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001450 int debug_level = 0, sshver = 2;
1451 char *file1 = NULL, *sftp_server = NULL;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001452 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001453 LogLevel ll = SYSLOG_LEVEL_INFO;
1454 arglist args;
Damien Millerd7686fd2001-02-10 00:40:03 +11001455 extern int optind;
1456 extern char *optarg;
Damien Miller33804262001-02-04 23:20:18 +11001457
Darren Tuckerce321d82005-10-03 18:11:24 +10001458 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1459 sanitise_stdfd();
1460
Damien Miller59d3d5b2003-08-22 09:34:41 +10001461 __progname = ssh_get_progname(argv[0]);
Damien Miller3eec6b72006-01-31 21:49:27 +11001462 memset(&args, '\0', sizeof(args));
Ben Lindstrom387c4722001-05-08 20:27:25 +00001463 args.list = NULL;
Damien Miller3eec6b72006-01-31 21:49:27 +11001464 addargs(&args, ssh_program);
Ben Lindstrom387c4722001-05-08 20:27:25 +00001465 addargs(&args, "-oForwardX11 no");
1466 addargs(&args, "-oForwardAgent no");
Damien Millerd27b9472005-12-13 19:29:02 +11001467 addargs(&args, "-oPermitLocalCommand no");
Ben Lindstrom2b7a0e92001-09-20 00:57:55 +00001468 addargs(&args, "-oClearAllForwardings yes");
Damien Millere4f5a822004-01-21 14:11:05 +11001469
Ben Lindstrom387c4722001-05-08 20:27:25 +00001470 ll = SYSLOG_LEVEL_INFO;
Damien Millere4f5a822004-01-21 14:11:05 +11001471 infile = stdin;
Damien Millerd7686fd2001-02-10 00:40:03 +11001472
Damien Miller16a13332002-02-13 14:03:56 +11001473 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
Damien Millerd7686fd2001-02-10 00:40:03 +11001474 switch (ch) {
1475 case 'C':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001476 addargs(&args, "-C");
Damien Millerd7686fd2001-02-10 00:40:03 +11001477 break;
1478 case 'v':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001479 if (debug_level < 3) {
1480 addargs(&args, "-v");
1481 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1482 }
1483 debug_level++;
Damien Millerd7686fd2001-02-10 00:40:03 +11001484 break;
Ben Lindstrom1e243242001-09-18 05:38:44 +00001485 case 'F':
Damien Millerd7686fd2001-02-10 00:40:03 +11001486 case 'o':
Ben Lindstrom1e243242001-09-18 05:38:44 +00001487 addargs(&args, "-%c%s", ch, optarg);
Damien Millerd7686fd2001-02-10 00:40:03 +11001488 break;
1489 case '1':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001490 sshver = 1;
Damien Millerd7686fd2001-02-10 00:40:03 +11001491 if (sftp_server == NULL)
1492 sftp_server = _PATH_SFTP_SERVER;
1493 break;
1494 case 's':
1495 sftp_server = optarg;
1496 break;
1497 case 'S':
1498 ssh_program = optarg;
Damien Miller3eec6b72006-01-31 21:49:27 +11001499 replacearg(&args, 0, "%s", ssh_program);
Damien Millerd7686fd2001-02-10 00:40:03 +11001500 break;
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001501 case 'b':
Damien Miller44f75c12004-01-21 10:58:47 +11001502 if (batchmode)
1503 fatal("Batch file already specified.");
1504
1505 /* Allow "-" as stdin */
Darren Tuckerfc959702004-07-17 16:12:08 +10001506 if (strcmp(optarg, "-") != 0 &&
Damien Miller0dc1bef2005-07-17 17:22:45 +10001507 (infile = fopen(optarg, "r")) == NULL)
Damien Miller44f75c12004-01-21 10:58:47 +11001508 fatal("%s (%s).", strerror(errno), optarg);
Damien Miller62d57f62003-01-10 21:43:24 +11001509 showprogress = 0;
Damien Miller44f75c12004-01-21 10:58:47 +11001510 batchmode = 1;
Damien Miller64e8d442005-03-01 21:16:47 +11001511 addargs(&args, "-obatchmode yes");
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001512 break;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001513 case 'P':
1514 sftp_direct = optarg;
1515 break;
Damien Miller8829d362002-02-08 22:04:05 +11001516 case 'B':
1517 copy_buffer_len = strtol(optarg, &cp, 10);
1518 if (copy_buffer_len == 0 || *cp != '\0')
1519 fatal("Invalid buffer size \"%s\"", optarg);
1520 break;
Damien Miller16a13332002-02-13 14:03:56 +11001521 case 'R':
1522 num_requests = strtol(optarg, &cp, 10);
1523 if (num_requests == 0 || *cp != '\0')
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001524 fatal("Invalid number of requests \"%s\"",
Damien Miller16a13332002-02-13 14:03:56 +11001525 optarg);
1526 break;
Damien Millerd7686fd2001-02-10 00:40:03 +11001527 case 'h':
1528 default:
Damien Miller33804262001-02-04 23:20:18 +11001529 usage();
1530 }
1531 }
1532
Damien Millerc0f27d82004-03-08 23:12:19 +11001533 if (!isatty(STDERR_FILENO))
1534 showprogress = 0;
1535
Ben Lindstrom2f3d52a2002-04-02 21:06:18 +00001536 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1537
Damien Millerd14ee1e2002-02-05 12:27:31 +11001538 if (sftp_direct == NULL) {
1539 if (optind == argc || argc > (optind + 2))
1540 usage();
Damien Miller33804262001-02-04 23:20:18 +11001541
Damien Millerd14ee1e2002-02-05 12:27:31 +11001542 userhost = xstrdup(argv[optind]);
1543 file2 = argv[optind+1];
Ben Lindstrom63667f62001-04-13 00:00:14 +00001544
Ben Lindstromc276c122002-12-23 02:14:51 +00001545 if ((host = strrchr(userhost, '@')) == NULL)
Damien Millerd14ee1e2002-02-05 12:27:31 +11001546 host = userhost;
1547 else {
1548 *host++ = '\0';
1549 if (!userhost[0]) {
1550 fprintf(stderr, "Missing username\n");
1551 usage();
1552 }
1553 addargs(&args, "-l%s",userhost);
1554 }
1555
Damien Millerec692032004-01-27 21:22:00 +11001556 if ((cp = colon(host)) != NULL) {
1557 *cp++ = '\0';
1558 file1 = cp;
1559 }
1560
Damien Millerd14ee1e2002-02-05 12:27:31 +11001561 host = cleanhostname(host);
1562 if (!*host) {
1563 fprintf(stderr, "Missing hostname\n");
Damien Miller33804262001-02-04 23:20:18 +11001564 usage();
1565 }
Damien Millerd14ee1e2002-02-05 12:27:31 +11001566
Damien Millerd14ee1e2002-02-05 12:27:31 +11001567 addargs(&args, "-oProtocol %d", sshver);
1568
1569 /* no subsystem if the server-spec contains a '/' */
1570 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1571 addargs(&args, "-s");
1572
1573 addargs(&args, "%s", host);
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001574 addargs(&args, "%s", (sftp_server != NULL ?
Damien Millerd14ee1e2002-02-05 12:27:31 +11001575 sftp_server : "sftp"));
Damien Millerd14ee1e2002-02-05 12:27:31 +11001576
Damien Miller44f75c12004-01-21 10:58:47 +11001577 if (!batchmode)
1578 fprintf(stderr, "Connecting to %s...\n", host);
Damien Millercc685c12003-06-04 22:51:38 +10001579 connect_to_server(ssh_program, args.list, &in, &out);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001580 } else {
1581 args.list = NULL;
1582 addargs(&args, "sftp-server");
1583
Damien Miller44f75c12004-01-21 10:58:47 +11001584 if (!batchmode)
1585 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
Damien Millercc685c12003-06-04 22:51:38 +10001586 connect_to_server(sftp_direct, args.list, &in, &out);
Damien Miller33804262001-02-04 23:20:18 +11001587 }
Damien Miller3eec6b72006-01-31 21:49:27 +11001588 freeargs(&args);
Damien Miller33804262001-02-04 23:20:18 +11001589
Damien Miller956f3fb2003-01-10 21:40:00 +11001590 err = interactive_loop(in, out, file1, file2);
Damien Miller33804262001-02-04 23:20:18 +11001591
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001592#if !defined(USE_PIPES)
Damien Miller37294fb2005-07-17 17:18:49 +10001593 shutdown(in, SHUT_RDWR);
1594 shutdown(out, SHUT_RDWR);
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001595#endif
1596
Damien Miller33804262001-02-04 23:20:18 +11001597 close(in);
1598 close(out);
Damien Miller44f75c12004-01-21 10:58:47 +11001599 if (batchmode)
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001600 fclose(infile);
Damien Miller33804262001-02-04 23:20:18 +11001601
Ben Lindstrom47fd8112002-04-02 20:48:19 +00001602 while (waitpid(sshpid, NULL, 0) == -1)
1603 if (errno != EINTR)
1604 fatal("Couldn't wait for ssh process: %s",
1605 strerror(errno));
Damien Miller33804262001-02-04 23:20:18 +11001606
Damien Miller956f3fb2003-01-10 21:40:00 +11001607 exit(err == 0 ? 0 : 1);
Damien Miller33804262001-02-04 23:20:18 +11001608}