blob: 649f08e5dffd90eca831332c7c2904132c4b3753 [file] [log] [blame]
Darren Tucker39972492006-07-12 22:22:46 +10001/* $OpenBSD: sftp.c,v 1.85 2006/07/11 20:07:25 stevesk Exp $ */
Damien Miller33804262001-02-04 23:20:18 +11002/*
Damien Miller4e60ed72004-02-17 17:07:59 +11003 * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
Damien Miller33804262001-02-04 23:20:18 +11004 *
Damien Miller4e60ed72004-02-17 17:07:59 +11005 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
Damien Miller33804262001-02-04 23:20:18 +11008 *
Damien Miller4e60ed72004-02-17 17:07:59 +11009 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Damien Miller33804262001-02-04 23:20:18 +110016 */
17
18#include "includes.h"
19
Damien Miller9cf6d072006-03-15 11:29:24 +110020#include <sys/types.h>
Damien Millerf17883e2006-03-15 11:45:54 +110021#ifdef HAVE_SYS_STAT_H
22# include <sys/stat.h>
23#endif
24#include <sys/ioctl.h>
Damien Millere3b60b52006-07-10 21:08:03 +100025#include <sys/socket.h>
Damien Miller9cf6d072006-03-15 11:29:24 +110026#include <sys/wait.h>
Darren Tucker2d963d82004-11-07 20:04:10 +110027
Darren Tucker39972492006-07-12 22:22:46 +100028#include <errno.h>
29
Damien Miller03e20032006-03-15 11:16:59 +110030#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110031# include <paths.h>
Damien Miller03e20032006-03-15 11:16:59 +110032#endif
Darren Tucker2d963d82004-11-07 20:04:10 +110033#ifdef USE_LIBEDIT
34#include <histedit.h>
35#else
36typedef void EditLine;
37#endif
Damien Miller6ff3cad2006-03-15 11:52:09 +110038#include <signal.h>
Damien Miller33804262001-02-04 23:20:18 +110039
Damien Miller33804262001-02-04 23:20:18 +110040#include "xmalloc.h"
41#include "log.h"
42#include "pathnames.h"
Ben Lindstrom4529b702001-05-03 23:39:53 +000043#include "misc.h"
Damien Miller33804262001-02-04 23:20:18 +110044
45#include "sftp.h"
46#include "sftp-common.h"
47#include "sftp-client.h"
Damien Millerd7d46bb2004-02-18 14:11:13 +110048
Damien Miller20e1fab2004-02-18 14:30:55 +110049/* File to read commands from */
50FILE* infile;
51
52/* Are we in batchfile mode? */
53int batchmode = 0;
54
55/* Size of buffer used when copying files */
56size_t copy_buffer_len = 32768;
57
58/* Number of concurrent outstanding requests */
59size_t num_requests = 16;
60
61/* PID of ssh transport process */
62static pid_t sshpid = -1;
63
64/* This is set to 0 if the progressmeter is not desired. */
Damien Millerc0f27d82004-03-08 23:12:19 +110065int showprogress = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +110066
Darren Tuckercdf547a2004-05-24 10:12:19 +100067/* SIGINT received during command processing */
68volatile sig_atomic_t interrupted = 0;
69
Darren Tuckerb9123452004-06-22 13:06:45 +100070/* I wish qsort() took a separate ctx for the comparison function...*/
71int sort_flag;
72
Damien Miller20e1fab2004-02-18 14:30:55 +110073int remote_glob(struct sftp_conn *, const char *, int,
74 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
Damien Miller33804262001-02-04 23:20:18 +110075
Kevin Steves12888d12001-03-05 19:50:57 +000076extern char *__progname;
Kevin Steves12888d12001-03-05 19:50:57 +000077
Damien Miller20e1fab2004-02-18 14:30:55 +110078/* Separators for interactive commands */
79#define WHITESPACE " \t\r\n"
Damien Millerd7686fd2001-02-10 00:40:03 +110080
Darren Tuckerb9123452004-06-22 13:06:45 +100081/* ls flags */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100082#define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
83#define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
84#define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
85#define LS_NAME_SORT 0x08 /* Sort by name (default) */
86#define LS_TIME_SORT 0x10 /* Sort by mtime */
87#define LS_SIZE_SORT 0x20 /* Sort by file size */
88#define LS_REVERSE_SORT 0x40 /* Reverse sort order */
Darren Tucker9a526452004-06-22 13:09:55 +100089#define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
Darren Tuckerb9123452004-06-22 13:06:45 +100090
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100091#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
92#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
Damien Miller20e1fab2004-02-18 14:30:55 +110093
94/* Commands for interactive mode */
95#define I_CHDIR 1
96#define I_CHGRP 2
97#define I_CHMOD 3
98#define I_CHOWN 4
99#define I_GET 5
100#define I_HELP 6
101#define I_LCHDIR 7
102#define I_LLS 8
103#define I_LMKDIR 9
104#define I_LPWD 10
105#define I_LS 11
106#define I_LUMASK 12
107#define I_MKDIR 13
108#define I_PUT 14
109#define I_PWD 15
110#define I_QUIT 16
111#define I_RENAME 17
112#define I_RM 18
113#define I_RMDIR 19
114#define I_SHELL 20
115#define I_SYMLINK 21
116#define I_VERSION 22
117#define I_PROGRESS 23
118
119struct CMD {
120 const char *c;
121 const int n;
122};
123
124static const struct CMD cmds[] = {
125 { "bye", I_QUIT },
126 { "cd", I_CHDIR },
127 { "chdir", I_CHDIR },
128 { "chgrp", I_CHGRP },
129 { "chmod", I_CHMOD },
130 { "chown", I_CHOWN },
131 { "dir", I_LS },
132 { "exit", I_QUIT },
133 { "get", I_GET },
134 { "mget", I_GET },
135 { "help", I_HELP },
136 { "lcd", I_LCHDIR },
137 { "lchdir", I_LCHDIR },
138 { "lls", I_LLS },
139 { "lmkdir", I_LMKDIR },
140 { "ln", I_SYMLINK },
141 { "lpwd", I_LPWD },
142 { "ls", I_LS },
143 { "lumask", I_LUMASK },
144 { "mkdir", I_MKDIR },
145 { "progress", I_PROGRESS },
146 { "put", I_PUT },
147 { "mput", I_PUT },
148 { "pwd", I_PWD },
149 { "quit", I_QUIT },
150 { "rename", I_RENAME },
151 { "rm", I_RM },
152 { "rmdir", I_RMDIR },
153 { "symlink", I_SYMLINK },
154 { "version", I_VERSION },
155 { "!", I_SHELL },
156 { "?", I_HELP },
157 { NULL, -1}
158};
159
160int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
161
162static void
Darren Tuckercdf547a2004-05-24 10:12:19 +1000163killchild(int signo)
164{
Darren Tuckerba66df82005-01-24 21:57:40 +1100165 if (sshpid > 1) {
Darren Tuckercdf547a2004-05-24 10:12:19 +1000166 kill(sshpid, SIGTERM);
Darren Tuckerba66df82005-01-24 21:57:40 +1100167 waitpid(sshpid, NULL, 0);
168 }
Darren Tuckercdf547a2004-05-24 10:12:19 +1000169
170 _exit(1);
171}
172
173static void
174cmd_interrupt(int signo)
175{
176 const char msg[] = "\rInterrupt \n";
Darren Tuckere2f189a2004-12-06 22:45:53 +1100177 int olderrno = errno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000178
179 write(STDERR_FILENO, msg, sizeof(msg) - 1);
180 interrupted = 1;
Darren Tuckere2f189a2004-12-06 22:45:53 +1100181 errno = olderrno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000182}
183
184static void
Damien Miller20e1fab2004-02-18 14:30:55 +1100185help(void)
186{
187 printf("Available commands:\n");
188 printf("cd path Change remote directory to 'path'\n");
189 printf("lcd path Change local directory to 'path'\n");
190 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
191 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
192 printf("chown own path Change owner of file 'path' to 'own'\n");
193 printf("help Display this help text\n");
194 printf("get remote-path [local-path] Download file\n");
195 printf("lls [ls-options [path]] Display local directory listing\n");
196 printf("ln oldpath newpath Symlink remote file\n");
197 printf("lmkdir path Create local directory\n");
198 printf("lpwd Print local working directory\n");
199 printf("ls [path] Display remote directory listing\n");
200 printf("lumask umask Set local umask to 'umask'\n");
201 printf("mkdir path Create remote directory\n");
202 printf("progress Toggle display of progress meter\n");
203 printf("put local-path [remote-path] Upload file\n");
204 printf("pwd Display remote working directory\n");
205 printf("exit Quit sftp\n");
206 printf("quit Quit sftp\n");
207 printf("rename oldpath newpath Rename remote file\n");
208 printf("rmdir path Remove remote directory\n");
209 printf("rm path Delete remote file\n");
210 printf("symlink oldpath newpath Symlink remote file\n");
211 printf("version Show SFTP version\n");
212 printf("!command Execute 'command' in local shell\n");
213 printf("! Escape to local shell\n");
214 printf("? Synonym for help\n");
215}
216
217static void
218local_do_shell(const char *args)
219{
220 int status;
221 char *shell;
222 pid_t pid;
223
224 if (!*args)
225 args = NULL;
226
227 if ((shell = getenv("SHELL")) == NULL)
228 shell = _PATH_BSHELL;
229
230 if ((pid = fork()) == -1)
231 fatal("Couldn't fork: %s", strerror(errno));
232
233 if (pid == 0) {
234 /* XXX: child has pipe fds to ssh subproc open - issue? */
235 if (args) {
236 debug3("Executing %s -c \"%s\"", shell, args);
237 execl(shell, shell, "-c", args, (char *)NULL);
238 } else {
239 debug3("Executing %s", shell);
240 execl(shell, shell, (char *)NULL);
241 }
242 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
243 strerror(errno));
244 _exit(1);
245 }
246 while (waitpid(pid, &status, 0) == -1)
247 if (errno != EINTR)
248 fatal("Couldn't wait for child: %s", strerror(errno));
249 if (!WIFEXITED(status))
Damien Miller55b04f12006-03-26 14:23:17 +1100250 error("Shell exited abnormally");
Damien Miller20e1fab2004-02-18 14:30:55 +1100251 else if (WEXITSTATUS(status))
252 error("Shell exited with status %d", WEXITSTATUS(status));
253}
254
255static void
256local_do_ls(const char *args)
257{
258 if (!args || !*args)
259 local_do_shell(_PATH_LS);
260 else {
261 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
262 char *buf = xmalloc(len);
263
264 /* XXX: quoting - rip quoting code from ftp? */
265 snprintf(buf, len, _PATH_LS " %s", args);
266 local_do_shell(buf);
267 xfree(buf);
268 }
269}
270
271/* Strip one path (usually the pwd) from the start of another */
272static char *
273path_strip(char *path, char *strip)
274{
275 size_t len;
276
277 if (strip == NULL)
278 return (xstrdup(path));
279
280 len = strlen(strip);
Darren Tuckere2f189a2004-12-06 22:45:53 +1100281 if (strncmp(path, strip, len) == 0) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100282 if (strip[len - 1] != '/' && path[len] == '/')
283 len++;
284 return (xstrdup(path + len));
285 }
286
287 return (xstrdup(path));
288}
289
290static char *
291path_append(char *p1, char *p2)
292{
293 char *ret;
294 int len = strlen(p1) + strlen(p2) + 2;
295
296 ret = xmalloc(len);
297 strlcpy(ret, p1, len);
298 if (p1[strlen(p1) - 1] != '/')
299 strlcat(ret, "/", len);
300 strlcat(ret, p2, len);
301
302 return(ret);
303}
304
305static char *
306make_absolute(char *p, char *pwd)
307{
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000308 char *abs_str;
Damien Miller20e1fab2004-02-18 14:30:55 +1100309
310 /* Derelativise */
311 if (p && p[0] != '/') {
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000312 abs_str = path_append(pwd, p);
Damien Miller20e1fab2004-02-18 14:30:55 +1100313 xfree(p);
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000314 return(abs_str);
Damien Miller20e1fab2004-02-18 14:30:55 +1100315 } else
316 return(p);
317}
318
319static int
320infer_path(const char *p, char **ifp)
321{
322 char *cp;
323
324 cp = strrchr(p, '/');
325 if (cp == NULL) {
326 *ifp = xstrdup(p);
327 return(0);
328 }
329
330 if (!cp[1]) {
331 error("Invalid path");
332 return(-1);
333 }
334
335 *ifp = xstrdup(cp + 1);
336 return(0);
337}
338
339static int
340parse_getput_flags(const char **cpp, int *pflag)
341{
342 const char *cp = *cpp;
343
344 /* Check for flags */
345 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
346 switch (cp[1]) {
347 case 'p':
348 case 'P':
349 *pflag = 1;
350 break;
351 default:
352 error("Invalid flag -%c", cp[1]);
353 return(-1);
354 }
355 cp += 2;
356 *cpp = cp + strspn(cp, WHITESPACE);
357 }
358
359 return(0);
360}
361
362static int
363parse_ls_flags(const char **cpp, int *lflag)
364{
365 const char *cp = *cpp;
366
Darren Tuckerb9123452004-06-22 13:06:45 +1000367 /* Defaults */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000368 *lflag = LS_NAME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000369
Damien Miller20e1fab2004-02-18 14:30:55 +1100370 /* Check for flags */
371 if (cp++[0] == '-') {
Darren Tucker47eede72005-03-14 23:08:12 +1100372 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100373 switch (*cp) {
374 case 'l':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000375 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000376 *lflag |= LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100377 break;
378 case '1':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000379 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000380 *lflag |= LS_SHORT_VIEW;
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000381 break;
382 case 'n':
383 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000384 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100385 break;
Darren Tuckerb9123452004-06-22 13:06:45 +1000386 case 'S':
387 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000388 *lflag |= LS_SIZE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000389 break;
390 case 't':
391 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000392 *lflag |= LS_TIME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000393 break;
394 case 'r':
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000395 *lflag |= LS_REVERSE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000396 break;
397 case 'f':
398 *lflag &= ~SORT_FLAGS;
399 break;
Darren Tucker9a526452004-06-22 13:09:55 +1000400 case 'a':
401 *lflag |= LS_SHOW_ALL;
402 break;
Damien Miller20e1fab2004-02-18 14:30:55 +1100403 default:
404 error("Invalid flag -%c", *cp);
405 return(-1);
406 }
407 }
408 *cpp = cp + strspn(cp, WHITESPACE);
409 }
410
411 return(0);
412}
413
414static int
415get_pathname(const char **cpp, char **path)
416{
417 const char *cp = *cpp, *end;
418 char quot;
Damien Millereccb9de2005-06-17 12:59:34 +1000419 u_int i, j;
Damien Miller20e1fab2004-02-18 14:30:55 +1100420
421 cp += strspn(cp, WHITESPACE);
422 if (!*cp) {
423 *cpp = cp;
424 *path = NULL;
425 return (0);
426 }
427
428 *path = xmalloc(strlen(cp) + 1);
429
430 /* Check for quoted filenames */
431 if (*cp == '\"' || *cp == '\'') {
432 quot = *cp++;
433
434 /* Search for terminating quote, unescape some chars */
435 for (i = j = 0; i <= strlen(cp); i++) {
436 if (cp[i] == quot) { /* Found quote */
437 i++;
438 (*path)[j] = '\0';
439 break;
440 }
441 if (cp[i] == '\0') { /* End of string */
442 error("Unterminated quote");
443 goto fail;
444 }
445 if (cp[i] == '\\') { /* Escaped characters */
446 i++;
447 if (cp[i] != '\'' && cp[i] != '\"' &&
448 cp[i] != '\\') {
Damien Miller96d6d7d2004-06-26 09:21:06 +1000449 error("Bad escaped character '\\%c'",
Damien Miller20e1fab2004-02-18 14:30:55 +1100450 cp[i]);
451 goto fail;
452 }
453 }
454 (*path)[j++] = cp[i];
455 }
456
457 if (j == 0) {
458 error("Empty quotes");
459 goto fail;
460 }
461 *cpp = cp + i + strspn(cp + i, WHITESPACE);
462 } else {
463 /* Read to end of filename */
464 end = strpbrk(cp, WHITESPACE);
465 if (end == NULL)
466 end = strchr(cp, '\0');
467 *cpp = end + strspn(end, WHITESPACE);
468
469 memcpy(*path, cp, end - cp);
470 (*path)[end - cp] = '\0';
471 }
472 return (0);
473
474 fail:
475 xfree(*path);
476 *path = NULL;
477 return (-1);
478}
479
480static int
481is_dir(char *path)
482{
483 struct stat sb;
484
485 /* XXX: report errors? */
486 if (stat(path, &sb) == -1)
487 return(0);
488
489 return(sb.st_mode & S_IFDIR);
490}
491
492static int
493is_reg(char *path)
494{
495 struct stat sb;
496
497 if (stat(path, &sb) == -1)
498 fatal("stat %s: %s", path, strerror(errno));
499
500 return(S_ISREG(sb.st_mode));
501}
502
503static int
504remote_is_dir(struct sftp_conn *conn, char *path)
505{
506 Attrib *a;
507
508 /* XXX: report errors? */
509 if ((a = do_stat(conn, path, 1)) == NULL)
510 return(0);
511 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
512 return(0);
513 return(a->perm & S_IFDIR);
514}
515
516static int
517process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
518{
519 char *abs_src = NULL;
520 char *abs_dst = NULL;
521 char *tmp;
522 glob_t g;
523 int err = 0;
524 int i;
525
526 abs_src = xstrdup(src);
527 abs_src = make_absolute(abs_src, pwd);
528
529 memset(&g, 0, sizeof(g));
530 debug3("Looking up %s", abs_src);
531 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
532 error("File \"%s\" not found.", abs_src);
533 err = -1;
534 goto out;
535 }
536
537 /* If multiple matches, dst must be a directory or unspecified */
538 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
539 error("Multiple files match, but \"%s\" is not a directory",
540 dst);
541 err = -1;
542 goto out;
543 }
544
Darren Tuckercdf547a2004-05-24 10:12:19 +1000545 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100546 if (infer_path(g.gl_pathv[i], &tmp)) {
547 err = -1;
548 goto out;
549 }
550
551 if (g.gl_matchc == 1 && dst) {
552 /* If directory specified, append filename */
Damien Miller40b59852006-06-13 13:00:25 +1000553 xfree(tmp);
Damien Miller20e1fab2004-02-18 14:30:55 +1100554 if (is_dir(dst)) {
555 if (infer_path(g.gl_pathv[0], &tmp)) {
556 err = 1;
557 goto out;
558 }
559 abs_dst = path_append(dst, tmp);
560 xfree(tmp);
561 } else
562 abs_dst = xstrdup(dst);
563 } else if (dst) {
564 abs_dst = path_append(dst, tmp);
565 xfree(tmp);
566 } else
567 abs_dst = tmp;
568
569 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
570 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
571 err = -1;
572 xfree(abs_dst);
573 abs_dst = NULL;
574 }
575
576out:
577 xfree(abs_src);
Damien Miller20e1fab2004-02-18 14:30:55 +1100578 globfree(&g);
579 return(err);
580}
581
582static int
583process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
584{
585 char *tmp_dst = NULL;
586 char *abs_dst = NULL;
587 char *tmp;
588 glob_t g;
589 int err = 0;
590 int i;
591
592 if (dst) {
593 tmp_dst = xstrdup(dst);
594 tmp_dst = make_absolute(tmp_dst, pwd);
595 }
596
597 memset(&g, 0, sizeof(g));
598 debug3("Looking up %s", src);
599 if (glob(src, 0, NULL, &g)) {
600 error("File \"%s\" not found.", src);
601 err = -1;
602 goto out;
603 }
604
605 /* If multiple matches, dst may be directory or unspecified */
606 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
607 error("Multiple files match, but \"%s\" is not a directory",
608 tmp_dst);
609 err = -1;
610 goto out;
611 }
612
Darren Tuckercdf547a2004-05-24 10:12:19 +1000613 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100614 if (!is_reg(g.gl_pathv[i])) {
615 error("skipping non-regular file %s",
616 g.gl_pathv[i]);
617 continue;
618 }
619 if (infer_path(g.gl_pathv[i], &tmp)) {
620 err = -1;
621 goto out;
622 }
623
624 if (g.gl_matchc == 1 && tmp_dst) {
625 /* If directory specified, append filename */
626 if (remote_is_dir(conn, tmp_dst)) {
627 if (infer_path(g.gl_pathv[0], &tmp)) {
628 err = 1;
629 goto out;
630 }
631 abs_dst = path_append(tmp_dst, tmp);
632 xfree(tmp);
633 } else
634 abs_dst = xstrdup(tmp_dst);
635
636 } else if (tmp_dst) {
637 abs_dst = path_append(tmp_dst, tmp);
638 xfree(tmp);
639 } else
640 abs_dst = make_absolute(tmp, pwd);
641
642 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
643 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
644 err = -1;
645 }
646
647out:
648 if (abs_dst)
649 xfree(abs_dst);
650 if (tmp_dst)
651 xfree(tmp_dst);
652 globfree(&g);
653 return(err);
654}
655
656static int
657sdirent_comp(const void *aa, const void *bb)
658{
659 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
660 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000661 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100662
Darren Tuckerb9123452004-06-22 13:06:45 +1000663#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000664 if (sort_flag & LS_NAME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000665 return (rmul * strcmp(a->filename, b->filename));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000666 else if (sort_flag & LS_TIME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000667 return (rmul * NCMP(a->a.mtime, b->a.mtime));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000668 else if (sort_flag & LS_SIZE_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000669 return (rmul * NCMP(a->a.size, b->a.size));
670
671 fatal("Unknown ls sort type");
Damien Miller20e1fab2004-02-18 14:30:55 +1100672}
673
674/* sftp ls.1 replacement for directories */
675static int
676do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
677{
Damien Millereccb9de2005-06-17 12:59:34 +1000678 int n;
679 u_int c = 1, colspace = 0, columns = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100680 SFTP_DIRENT **d;
681
682 if ((n = do_readdir(conn, path, &d)) != 0)
683 return (n);
684
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000685 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000686 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100687 struct winsize ws;
688 char *tmp;
689
690 /* Count entries for sort and find longest filename */
Darren Tucker9a526452004-06-22 13:09:55 +1000691 for (n = 0; d[n] != NULL; n++) {
692 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
693 m = MAX(m, strlen(d[n]->filename));
694 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100695
696 /* Add any subpath that also needs to be counted */
697 tmp = path_strip(path, strip_path);
698 m += strlen(tmp);
699 xfree(tmp);
700
701 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
702 width = ws.ws_col;
703
704 columns = width / (m + 2);
705 columns = MAX(columns, 1);
706 colspace = width / columns;
707 colspace = MIN(colspace, width);
708 }
709
Darren Tuckerb9123452004-06-22 13:06:45 +1000710 if (lflag & SORT_FLAGS) {
Damien Miller653b93b2005-11-05 15:15:23 +1100711 for (n = 0; d[n] != NULL; n++)
712 ; /* count entries */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000713 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
Darren Tuckerb9123452004-06-22 13:06:45 +1000714 qsort(d, n, sizeof(*d), sdirent_comp);
715 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100716
Darren Tuckercdf547a2004-05-24 10:12:19 +1000717 for (n = 0; d[n] != NULL && !interrupted; n++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100718 char *tmp, *fname;
719
Darren Tucker9a526452004-06-22 13:09:55 +1000720 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
721 continue;
722
Damien Miller20e1fab2004-02-18 14:30:55 +1100723 tmp = path_append(path, d[n]->filename);
724 fname = path_strip(tmp, strip_path);
725 xfree(tmp);
726
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000727 if (lflag & LS_LONG_VIEW) {
728 if (lflag & LS_NUMERIC_VIEW) {
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000729 char *lname;
730 struct stat sb;
Damien Miller20e1fab2004-02-18 14:30:55 +1100731
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000732 memset(&sb, 0, sizeof(sb));
733 attrib_to_stat(&d[n]->a, &sb);
734 lname = ls_file(fname, &sb, 1);
735 printf("%s\n", lname);
736 xfree(lname);
737 } else
738 printf("%s\n", d[n]->longname);
Damien Miller20e1fab2004-02-18 14:30:55 +1100739 } else {
740 printf("%-*s", colspace, fname);
741 if (c >= columns) {
742 printf("\n");
743 c = 1;
744 } else
745 c++;
746 }
747
748 xfree(fname);
749 }
750
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000751 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100752 printf("\n");
753
754 free_sftp_dirents(d);
755 return (0);
756}
757
758/* sftp ls.1 replacement which handles path globs */
759static int
760do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
761 int lflag)
762{
763 glob_t g;
Damien Millereccb9de2005-06-17 12:59:34 +1000764 u_int i, c = 1, colspace = 0, columns = 1;
Darren Tucker596dcfa2004-12-11 13:37:22 +1100765 Attrib *a = NULL;
Damien Miller20e1fab2004-02-18 14:30:55 +1100766
767 memset(&g, 0, sizeof(g));
768
769 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
Darren Tucker596dcfa2004-12-11 13:37:22 +1100770 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
771 if (g.gl_pathc)
772 globfree(&g);
Damien Miller20e1fab2004-02-18 14:30:55 +1100773 error("Can't ls: \"%s\" not found", path);
774 return (-1);
775 }
776
Darren Tuckercdf547a2004-05-24 10:12:19 +1000777 if (interrupted)
778 goto out;
779
Damien Miller20e1fab2004-02-18 14:30:55 +1100780 /*
Darren Tucker596dcfa2004-12-11 13:37:22 +1100781 * If the glob returns a single match and it is a directory,
782 * then just list its contents.
Damien Miller20e1fab2004-02-18 14:30:55 +1100783 */
Darren Tucker596dcfa2004-12-11 13:37:22 +1100784 if (g.gl_matchc == 1) {
785 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100786 globfree(&g);
787 return (-1);
788 }
789 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
790 S_ISDIR(a->perm)) {
Darren Tucker596dcfa2004-12-11 13:37:22 +1100791 int err;
792
793 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
Damien Miller20e1fab2004-02-18 14:30:55 +1100794 globfree(&g);
Darren Tucker596dcfa2004-12-11 13:37:22 +1100795 return (err);
Damien Miller20e1fab2004-02-18 14:30:55 +1100796 }
797 }
798
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000799 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000800 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100801 struct winsize ws;
802
803 /* Count entries for sort and find longest filename */
804 for (i = 0; g.gl_pathv[i]; i++)
805 m = MAX(m, strlen(g.gl_pathv[i]));
806
807 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
808 width = ws.ws_col;
809
810 columns = width / (m + 2);
811 columns = MAX(columns, 1);
812 colspace = width / columns;
813 }
814
Darren Tucker596dcfa2004-12-11 13:37:22 +1100815 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100816 char *fname;
817
818 fname = path_strip(g.gl_pathv[i], strip_path);
819
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000820 if (lflag & LS_LONG_VIEW) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100821 char *lname;
822 struct stat sb;
823
824 /*
825 * XXX: this is slow - 1 roundtrip per path
826 * A solution to this is to fork glob() and
827 * build a sftp specific version which keeps the
828 * attribs (which currently get thrown away)
829 * that the server returns as well as the filenames.
830 */
831 memset(&sb, 0, sizeof(sb));
Darren Tucker596dcfa2004-12-11 13:37:22 +1100832 if (a == NULL)
833 a = do_lstat(conn, g.gl_pathv[i], 1);
Damien Miller20e1fab2004-02-18 14:30:55 +1100834 if (a != NULL)
835 attrib_to_stat(a, &sb);
836 lname = ls_file(fname, &sb, 1);
837 printf("%s\n", lname);
838 xfree(lname);
839 } else {
840 printf("%-*s", colspace, fname);
841 if (c >= columns) {
842 printf("\n");
843 c = 1;
844 } else
845 c++;
846 }
847 xfree(fname);
848 }
849
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000850 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100851 printf("\n");
852
Darren Tuckercdf547a2004-05-24 10:12:19 +1000853 out:
Damien Miller20e1fab2004-02-18 14:30:55 +1100854 if (g.gl_pathc)
855 globfree(&g);
856
857 return (0);
858}
859
860static int
861parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
862 unsigned long *n_arg, char **path1, char **path2)
863{
864 const char *cmd, *cp = *cpp;
865 char *cp2;
866 int base = 0;
867 long l;
868 int i, cmdnum;
869
870 /* Skip leading whitespace */
871 cp = cp + strspn(cp, WHITESPACE);
872
873 /* Ignore blank lines and lines which begin with comment '#' char */
874 if (*cp == '\0' || *cp == '#')
875 return (0);
876
877 /* Check for leading '-' (disable error processing) */
878 *iflag = 0;
879 if (*cp == '-') {
880 *iflag = 1;
881 cp++;
882 }
883
884 /* Figure out which command we have */
885 for (i = 0; cmds[i].c; i++) {
886 int cmdlen = strlen(cmds[i].c);
887
888 /* Check for command followed by whitespace */
889 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
890 strchr(WHITESPACE, cp[cmdlen])) {
891 cp += cmdlen;
892 cp = cp + strspn(cp, WHITESPACE);
893 break;
894 }
895 }
896 cmdnum = cmds[i].n;
897 cmd = cmds[i].c;
898
899 /* Special case */
900 if (*cp == '!') {
901 cp++;
902 cmdnum = I_SHELL;
903 } else if (cmdnum == -1) {
904 error("Invalid command.");
905 return (-1);
906 }
907
908 /* Get arguments and parse flags */
909 *lflag = *pflag = *n_arg = 0;
910 *path1 = *path2 = NULL;
911 switch (cmdnum) {
912 case I_GET:
913 case I_PUT:
914 if (parse_getput_flags(&cp, pflag))
915 return(-1);
916 /* Get first pathname (mandatory) */
917 if (get_pathname(&cp, path1))
918 return(-1);
919 if (*path1 == NULL) {
920 error("You must specify at least one path after a "
921 "%s command.", cmd);
922 return(-1);
923 }
924 /* Try to get second pathname (optional) */
925 if (get_pathname(&cp, path2))
926 return(-1);
927 break;
928 case I_RENAME:
929 case I_SYMLINK:
930 if (get_pathname(&cp, path1))
931 return(-1);
932 if (get_pathname(&cp, path2))
933 return(-1);
934 if (!*path1 || !*path2) {
935 error("You must specify two paths after a %s "
936 "command.", cmd);
937 return(-1);
938 }
939 break;
940 case I_RM:
941 case I_MKDIR:
942 case I_RMDIR:
943 case I_CHDIR:
944 case I_LCHDIR:
945 case I_LMKDIR:
946 /* Get pathname (mandatory) */
947 if (get_pathname(&cp, path1))
948 return(-1);
949 if (*path1 == NULL) {
950 error("You must specify a path after a %s command.",
951 cmd);
952 return(-1);
953 }
954 break;
955 case I_LS:
956 if (parse_ls_flags(&cp, lflag))
957 return(-1);
958 /* Path is optional */
959 if (get_pathname(&cp, path1))
960 return(-1);
961 break;
962 case I_LLS:
963 case I_SHELL:
964 /* Uses the rest of the line */
965 break;
966 case I_LUMASK:
967 base = 8;
968 case I_CHMOD:
969 base = 8;
970 case I_CHOWN:
971 case I_CHGRP:
972 /* Get numeric arg (mandatory) */
973 l = strtol(cp, &cp2, base);
974 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
975 errno == ERANGE) || l < 0) {
976 error("You must supply a numeric argument "
977 "to the %s command.", cmd);
978 return(-1);
979 }
980 cp = cp2;
981 *n_arg = l;
982 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
983 break;
984 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
985 error("You must supply a numeric argument "
986 "to the %s command.", cmd);
987 return(-1);
988 }
989 cp += strspn(cp, WHITESPACE);
990
991 /* Get pathname (mandatory) */
992 if (get_pathname(&cp, path1))
993 return(-1);
994 if (*path1 == NULL) {
995 error("You must specify a path after a %s command.",
996 cmd);
997 return(-1);
998 }
999 break;
1000 case I_QUIT:
1001 case I_PWD:
1002 case I_LPWD:
1003 case I_HELP:
1004 case I_VERSION:
1005 case I_PROGRESS:
1006 break;
1007 default:
1008 fatal("Command not implemented");
1009 }
1010
1011 *cpp = cp;
1012 return(cmdnum);
1013}
1014
1015static int
1016parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1017 int err_abort)
1018{
1019 char *path1, *path2, *tmp;
1020 int pflag, lflag, iflag, cmdnum, i;
1021 unsigned long n_arg;
1022 Attrib a, *aa;
1023 char path_buf[MAXPATHLEN];
1024 int err = 0;
1025 glob_t g;
1026
1027 path1 = path2 = NULL;
1028 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1029 &path1, &path2);
1030
1031 if (iflag != 0)
1032 err_abort = 0;
1033
1034 memset(&g, 0, sizeof(g));
1035
1036 /* Perform command */
1037 switch (cmdnum) {
1038 case 0:
1039 /* Blank line */
1040 break;
1041 case -1:
1042 /* Unrecognized command */
1043 err = -1;
1044 break;
1045 case I_GET:
1046 err = process_get(conn, path1, path2, *pwd, pflag);
1047 break;
1048 case I_PUT:
1049 err = process_put(conn, path1, path2, *pwd, pflag);
1050 break;
1051 case I_RENAME:
1052 path1 = make_absolute(path1, *pwd);
1053 path2 = make_absolute(path2, *pwd);
1054 err = do_rename(conn, path1, path2);
1055 break;
1056 case I_SYMLINK:
1057 path2 = make_absolute(path2, *pwd);
1058 err = do_symlink(conn, path1, path2);
1059 break;
1060 case I_RM:
1061 path1 = make_absolute(path1, *pwd);
1062 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001063 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001064 printf("Removing %s\n", g.gl_pathv[i]);
1065 err = do_rm(conn, g.gl_pathv[i]);
1066 if (err != 0 && err_abort)
1067 break;
1068 }
1069 break;
1070 case I_MKDIR:
1071 path1 = make_absolute(path1, *pwd);
1072 attrib_clear(&a);
1073 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1074 a.perm = 0777;
1075 err = do_mkdir(conn, path1, &a);
1076 break;
1077 case I_RMDIR:
1078 path1 = make_absolute(path1, *pwd);
1079 err = do_rmdir(conn, path1);
1080 break;
1081 case I_CHDIR:
1082 path1 = make_absolute(path1, *pwd);
1083 if ((tmp = do_realpath(conn, path1)) == NULL) {
1084 err = 1;
1085 break;
1086 }
1087 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1088 xfree(tmp);
1089 err = 1;
1090 break;
1091 }
1092 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1093 error("Can't change directory: Can't check target");
1094 xfree(tmp);
1095 err = 1;
1096 break;
1097 }
1098 if (!S_ISDIR(aa->perm)) {
1099 error("Can't change directory: \"%s\" is not "
1100 "a directory", tmp);
1101 xfree(tmp);
1102 err = 1;
1103 break;
1104 }
1105 xfree(*pwd);
1106 *pwd = tmp;
1107 break;
1108 case I_LS:
1109 if (!path1) {
1110 do_globbed_ls(conn, *pwd, *pwd, lflag);
1111 break;
1112 }
1113
1114 /* Strip pwd off beginning of non-absolute paths */
1115 tmp = NULL;
1116 if (*path1 != '/')
1117 tmp = *pwd;
1118
1119 path1 = make_absolute(path1, *pwd);
1120 err = do_globbed_ls(conn, path1, tmp, lflag);
1121 break;
1122 case I_LCHDIR:
1123 if (chdir(path1) == -1) {
1124 error("Couldn't change local directory to "
1125 "\"%s\": %s", path1, strerror(errno));
1126 err = 1;
1127 }
1128 break;
1129 case I_LMKDIR:
1130 if (mkdir(path1, 0777) == -1) {
1131 error("Couldn't create local directory "
1132 "\"%s\": %s", path1, strerror(errno));
1133 err = 1;
1134 }
1135 break;
1136 case I_LLS:
1137 local_do_ls(cmd);
1138 break;
1139 case I_SHELL:
1140 local_do_shell(cmd);
1141 break;
1142 case I_LUMASK:
1143 umask(n_arg);
1144 printf("Local umask: %03lo\n", n_arg);
1145 break;
1146 case I_CHMOD:
1147 path1 = make_absolute(path1, *pwd);
1148 attrib_clear(&a);
1149 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1150 a.perm = n_arg;
1151 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001152 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001153 printf("Changing mode on %s\n", g.gl_pathv[i]);
1154 err = do_setstat(conn, g.gl_pathv[i], &a);
1155 if (err != 0 && err_abort)
1156 break;
1157 }
1158 break;
1159 case I_CHOWN:
1160 case I_CHGRP:
1161 path1 = make_absolute(path1, *pwd);
1162 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001163 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001164 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1165 if (err != 0 && err_abort)
1166 break;
1167 else
1168 continue;
1169 }
1170 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1171 error("Can't get current ownership of "
1172 "remote file \"%s\"", g.gl_pathv[i]);
1173 if (err != 0 && err_abort)
1174 break;
1175 else
1176 continue;
1177 }
1178 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1179 if (cmdnum == I_CHOWN) {
1180 printf("Changing owner on %s\n", g.gl_pathv[i]);
1181 aa->uid = n_arg;
1182 } else {
1183 printf("Changing group on %s\n", g.gl_pathv[i]);
1184 aa->gid = n_arg;
1185 }
1186 err = do_setstat(conn, g.gl_pathv[i], aa);
1187 if (err != 0 && err_abort)
1188 break;
1189 }
1190 break;
1191 case I_PWD:
1192 printf("Remote working directory: %s\n", *pwd);
1193 break;
1194 case I_LPWD:
1195 if (!getcwd(path_buf, sizeof(path_buf))) {
1196 error("Couldn't get local cwd: %s", strerror(errno));
1197 err = -1;
1198 break;
1199 }
1200 printf("Local working directory: %s\n", path_buf);
1201 break;
1202 case I_QUIT:
1203 /* Processed below */
1204 break;
1205 case I_HELP:
1206 help();
1207 break;
1208 case I_VERSION:
1209 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1210 break;
1211 case I_PROGRESS:
1212 showprogress = !showprogress;
1213 if (showprogress)
1214 printf("Progress meter enabled\n");
1215 else
1216 printf("Progress meter disabled\n");
1217 break;
1218 default:
1219 fatal("%d is not implemented", cmdnum);
1220 }
1221
1222 if (g.gl_pathc)
1223 globfree(&g);
1224 if (path1)
1225 xfree(path1);
1226 if (path2)
1227 xfree(path2);
1228
1229 /* If an unignored error occurs in batch mode we should abort. */
1230 if (err_abort && err != 0)
1231 return (-1);
1232 else if (cmdnum == I_QUIT)
1233 return (1);
1234
1235 return (0);
1236}
1237
Darren Tucker2d963d82004-11-07 20:04:10 +11001238#ifdef USE_LIBEDIT
1239static char *
1240prompt(EditLine *el)
1241{
1242 return ("sftp> ");
1243}
1244#endif
1245
Damien Miller20e1fab2004-02-18 14:30:55 +11001246int
1247interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1248{
1249 char *pwd;
1250 char *dir = NULL;
1251 char cmd[2048];
1252 struct sftp_conn *conn;
Damien Miller0e2c1022005-08-12 22:16:22 +10001253 int err, interactive;
Darren Tucker2d963d82004-11-07 20:04:10 +11001254 EditLine *el = NULL;
1255#ifdef USE_LIBEDIT
1256 History *hl = NULL;
1257 HistEvent hev;
1258 extern char *__progname;
1259
1260 if (!batchmode && isatty(STDIN_FILENO)) {
1261 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1262 fatal("Couldn't initialise editline");
1263 if ((hl = history_init()) == NULL)
1264 fatal("Couldn't initialise editline history");
1265 history(hl, &hev, H_SETSIZE, 100);
1266 el_set(el, EL_HIST, history, hl);
1267
1268 el_set(el, EL_PROMPT, prompt);
1269 el_set(el, EL_EDITOR, "emacs");
1270 el_set(el, EL_TERMINAL, NULL);
1271 el_set(el, EL_SIGNAL, 1);
1272 el_source(el, NULL);
1273 }
1274#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001275
1276 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1277 if (conn == NULL)
1278 fatal("Couldn't initialise connection to server");
1279
1280 pwd = do_realpath(conn, ".");
1281 if (pwd == NULL)
1282 fatal("Need cwd");
1283
1284 if (file1 != NULL) {
1285 dir = xstrdup(file1);
1286 dir = make_absolute(dir, pwd);
1287
1288 if (remote_is_dir(conn, dir) && file2 == NULL) {
1289 printf("Changing to: %s\n", dir);
1290 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001291 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1292 xfree(dir);
1293 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001294 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001295 return (-1);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001296 }
Damien Miller20e1fab2004-02-18 14:30:55 +11001297 } else {
1298 if (file2 == NULL)
1299 snprintf(cmd, sizeof cmd, "get %s", dir);
1300 else
1301 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1302 file2);
1303
1304 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1305 xfree(dir);
1306 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001307 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001308 return (err);
1309 }
1310 xfree(dir);
1311 }
1312
Darren Tucker93e7e8f2005-08-23 08:06:55 +10001313#if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
Damien Miller20e1fab2004-02-18 14:30:55 +11001314 setvbuf(stdout, NULL, _IOLBF, 0);
1315 setvbuf(infile, NULL, _IOLBF, 0);
1316#else
Damien Miller37294fb2005-07-17 17:18:49 +10001317 setlinebuf(stdout);
1318 setlinebuf(infile);
Damien Miller20e1fab2004-02-18 14:30:55 +11001319#endif
1320
Damien Miller0e2c1022005-08-12 22:16:22 +10001321 interactive = !batchmode && isatty(STDIN_FILENO);
Damien Miller20e1fab2004-02-18 14:30:55 +11001322 err = 0;
1323 for (;;) {
1324 char *cp;
1325
Darren Tuckercdf547a2004-05-24 10:12:19 +10001326 signal(SIGINT, SIG_IGN);
1327
Darren Tucker2d963d82004-11-07 20:04:10 +11001328 if (el == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001329 if (interactive)
1330 printf("sftp> ");
Darren Tucker2d963d82004-11-07 20:04:10 +11001331 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001332 if (interactive)
1333 printf("\n");
Darren Tucker2d963d82004-11-07 20:04:10 +11001334 break;
1335 }
Damien Miller0e2c1022005-08-12 22:16:22 +10001336 if (!interactive) { /* Echo command */
1337 printf("sftp> %s", cmd);
1338 if (strlen(cmd) > 0 &&
1339 cmd[strlen(cmd) - 1] != '\n')
1340 printf("\n");
1341 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001342 } else {
1343#ifdef USE_LIBEDIT
1344 const char *line;
1345 int count = 0;
Damien Miller20e1fab2004-02-18 14:30:55 +11001346
Damien Miller0e2c1022005-08-12 22:16:22 +10001347 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1348 printf("\n");
1349 break;
1350 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001351 history(hl, &hev, H_ENTER, line);
1352 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1353 fprintf(stderr, "Error: input line too long\n");
1354 continue;
1355 }
1356#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001357 }
1358
Damien Miller20e1fab2004-02-18 14:30:55 +11001359 cp = strrchr(cmd, '\n');
1360 if (cp)
1361 *cp = '\0';
1362
Darren Tuckercdf547a2004-05-24 10:12:19 +10001363 /* Handle user interrupts gracefully during commands */
1364 interrupted = 0;
1365 signal(SIGINT, cmd_interrupt);
1366
Damien Miller20e1fab2004-02-18 14:30:55 +11001367 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1368 if (err != 0)
1369 break;
1370 }
1371 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001372 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001373
Tim Rice027e8b12005-08-15 14:52:50 -07001374#ifdef USE_LIBEDIT
Damien Miller0e2c1022005-08-12 22:16:22 +10001375 if (el != NULL)
1376 el_end(el);
Tim Rice027e8b12005-08-15 14:52:50 -07001377#endif /* USE_LIBEDIT */
Damien Miller0e2c1022005-08-12 22:16:22 +10001378
Damien Miller20e1fab2004-02-18 14:30:55 +11001379 /* err == 1 signifies normal "quit" exit */
1380 return (err >= 0 ? 0 : -1);
1381}
Damien Miller62d57f62003-01-10 21:43:24 +11001382
Ben Lindstrombba81212001-06-25 05:01:22 +00001383static void
Damien Millercc685c12003-06-04 22:51:38 +10001384connect_to_server(char *path, char **args, int *in, int *out)
Damien Miller33804262001-02-04 23:20:18 +11001385{
1386 int c_in, c_out;
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001387
Damien Miller33804262001-02-04 23:20:18 +11001388#ifdef USE_PIPES
1389 int pin[2], pout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001390
Damien Miller33804262001-02-04 23:20:18 +11001391 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1392 fatal("pipe: %s", strerror(errno));
1393 *in = pin[0];
1394 *out = pout[1];
1395 c_in = pout[0];
1396 c_out = pin[1];
1397#else /* USE_PIPES */
1398 int inout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001399
Damien Miller33804262001-02-04 23:20:18 +11001400 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1401 fatal("socketpair: %s", strerror(errno));
1402 *in = *out = inout[0];
1403 c_in = c_out = inout[1];
1404#endif /* USE_PIPES */
1405
Damien Millercc685c12003-06-04 22:51:38 +10001406 if ((sshpid = fork()) == -1)
Damien Miller33804262001-02-04 23:20:18 +11001407 fatal("fork: %s", strerror(errno));
Damien Millercc685c12003-06-04 22:51:38 +10001408 else if (sshpid == 0) {
Damien Miller33804262001-02-04 23:20:18 +11001409 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1410 (dup2(c_out, STDOUT_FILENO) == -1)) {
1411 fprintf(stderr, "dup2: %s\n", strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001412 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001413 }
1414 close(*in);
1415 close(*out);
1416 close(c_in);
1417 close(c_out);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001418
1419 /*
1420 * The underlying ssh is in the same process group, so we must
Darren Tuckerfc959702004-07-17 16:12:08 +10001421 * ignore SIGINT if we want to gracefully abort commands,
1422 * otherwise the signal will make it to the ssh process and
Darren Tuckercdf547a2004-05-24 10:12:19 +10001423 * kill it too
1424 */
1425 signal(SIGINT, SIG_IGN);
Darren Tuckerbd12f172004-06-18 16:23:43 +10001426 execvp(path, args);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001427 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001428 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001429 }
1430
Damien Millercc685c12003-06-04 22:51:38 +10001431 signal(SIGTERM, killchild);
1432 signal(SIGINT, killchild);
1433 signal(SIGHUP, killchild);
Damien Miller33804262001-02-04 23:20:18 +11001434 close(c_in);
1435 close(c_out);
1436}
1437
Ben Lindstrombba81212001-06-25 05:01:22 +00001438static void
Damien Miller33804262001-02-04 23:20:18 +11001439usage(void)
1440{
Damien Miller025e01c2002-02-08 22:06:29 +11001441 extern char *__progname;
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001442
Ben Lindstrom1e243242001-09-18 05:38:44 +00001443 fprintf(stderr,
Darren Tucker1f203942003-10-15 15:50:42 +10001444 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1445 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1446 " [-S program] [-s subsystem | sftp_server] host\n"
1447 " %s [[user@]host[:file [file]]]\n"
1448 " %s [[user@]host[:dir[/]]]\n"
1449 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
Damien Miller33804262001-02-04 23:20:18 +11001450 exit(1);
1451}
1452
Kevin Stevesef4eea92001-02-05 12:42:17 +00001453int
Damien Miller33804262001-02-04 23:20:18 +11001454main(int argc, char **argv)
1455{
Damien Miller956f3fb2003-01-10 21:40:00 +11001456 int in, out, ch, err;
Damien Miller7cf17eb2004-06-15 10:28:56 +10001457 char *host, *userhost, *cp, *file2 = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001458 int debug_level = 0, sshver = 2;
1459 char *file1 = NULL, *sftp_server = NULL;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001460 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001461 LogLevel ll = SYSLOG_LEVEL_INFO;
1462 arglist args;
Damien Millerd7686fd2001-02-10 00:40:03 +11001463 extern int optind;
1464 extern char *optarg;
Damien Miller33804262001-02-04 23:20:18 +11001465
Darren Tuckerce321d82005-10-03 18:11:24 +10001466 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1467 sanitise_stdfd();
1468
Damien Miller59d3d5b2003-08-22 09:34:41 +10001469 __progname = ssh_get_progname(argv[0]);
Damien Miller3eec6b72006-01-31 21:49:27 +11001470 memset(&args, '\0', sizeof(args));
Ben Lindstrom387c4722001-05-08 20:27:25 +00001471 args.list = NULL;
Damien Miller2b5a0de2006-03-31 23:10:31 +11001472 addargs(&args, "%s", ssh_program);
Ben Lindstrom387c4722001-05-08 20:27:25 +00001473 addargs(&args, "-oForwardX11 no");
1474 addargs(&args, "-oForwardAgent no");
Damien Millerd27b9472005-12-13 19:29:02 +11001475 addargs(&args, "-oPermitLocalCommand no");
Ben Lindstrom2b7a0e92001-09-20 00:57:55 +00001476 addargs(&args, "-oClearAllForwardings yes");
Damien Millere4f5a822004-01-21 14:11:05 +11001477
Ben Lindstrom387c4722001-05-08 20:27:25 +00001478 ll = SYSLOG_LEVEL_INFO;
Damien Millere4f5a822004-01-21 14:11:05 +11001479 infile = stdin;
Damien Millerd7686fd2001-02-10 00:40:03 +11001480
Damien Miller16a13332002-02-13 14:03:56 +11001481 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
Damien Millerd7686fd2001-02-10 00:40:03 +11001482 switch (ch) {
1483 case 'C':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001484 addargs(&args, "-C");
Damien Millerd7686fd2001-02-10 00:40:03 +11001485 break;
1486 case 'v':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001487 if (debug_level < 3) {
1488 addargs(&args, "-v");
1489 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1490 }
1491 debug_level++;
Damien Millerd7686fd2001-02-10 00:40:03 +11001492 break;
Ben Lindstrom1e243242001-09-18 05:38:44 +00001493 case 'F':
Damien Millerd7686fd2001-02-10 00:40:03 +11001494 case 'o':
Ben Lindstrom1e243242001-09-18 05:38:44 +00001495 addargs(&args, "-%c%s", ch, optarg);
Damien Millerd7686fd2001-02-10 00:40:03 +11001496 break;
1497 case '1':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001498 sshver = 1;
Damien Millerd7686fd2001-02-10 00:40:03 +11001499 if (sftp_server == NULL)
1500 sftp_server = _PATH_SFTP_SERVER;
1501 break;
1502 case 's':
1503 sftp_server = optarg;
1504 break;
1505 case 'S':
1506 ssh_program = optarg;
Damien Miller3eec6b72006-01-31 21:49:27 +11001507 replacearg(&args, 0, "%s", ssh_program);
Damien Millerd7686fd2001-02-10 00:40:03 +11001508 break;
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001509 case 'b':
Damien Miller44f75c12004-01-21 10:58:47 +11001510 if (batchmode)
1511 fatal("Batch file already specified.");
1512
1513 /* Allow "-" as stdin */
Darren Tuckerfc959702004-07-17 16:12:08 +10001514 if (strcmp(optarg, "-") != 0 &&
Damien Miller0dc1bef2005-07-17 17:22:45 +10001515 (infile = fopen(optarg, "r")) == NULL)
Damien Miller44f75c12004-01-21 10:58:47 +11001516 fatal("%s (%s).", strerror(errno), optarg);
Damien Miller62d57f62003-01-10 21:43:24 +11001517 showprogress = 0;
Damien Miller44f75c12004-01-21 10:58:47 +11001518 batchmode = 1;
Damien Miller64e8d442005-03-01 21:16:47 +11001519 addargs(&args, "-obatchmode yes");
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001520 break;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001521 case 'P':
1522 sftp_direct = optarg;
1523 break;
Damien Miller8829d362002-02-08 22:04:05 +11001524 case 'B':
1525 copy_buffer_len = strtol(optarg, &cp, 10);
1526 if (copy_buffer_len == 0 || *cp != '\0')
1527 fatal("Invalid buffer size \"%s\"", optarg);
1528 break;
Damien Miller16a13332002-02-13 14:03:56 +11001529 case 'R':
1530 num_requests = strtol(optarg, &cp, 10);
1531 if (num_requests == 0 || *cp != '\0')
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001532 fatal("Invalid number of requests \"%s\"",
Damien Miller16a13332002-02-13 14:03:56 +11001533 optarg);
1534 break;
Damien Millerd7686fd2001-02-10 00:40:03 +11001535 case 'h':
1536 default:
Damien Miller33804262001-02-04 23:20:18 +11001537 usage();
1538 }
1539 }
1540
Damien Millerc0f27d82004-03-08 23:12:19 +11001541 if (!isatty(STDERR_FILENO))
1542 showprogress = 0;
1543
Ben Lindstrom2f3d52a2002-04-02 21:06:18 +00001544 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1545
Damien Millerd14ee1e2002-02-05 12:27:31 +11001546 if (sftp_direct == NULL) {
1547 if (optind == argc || argc > (optind + 2))
1548 usage();
Damien Miller33804262001-02-04 23:20:18 +11001549
Damien Millerd14ee1e2002-02-05 12:27:31 +11001550 userhost = xstrdup(argv[optind]);
1551 file2 = argv[optind+1];
Ben Lindstrom63667f62001-04-13 00:00:14 +00001552
Ben Lindstromc276c122002-12-23 02:14:51 +00001553 if ((host = strrchr(userhost, '@')) == NULL)
Damien Millerd14ee1e2002-02-05 12:27:31 +11001554 host = userhost;
1555 else {
1556 *host++ = '\0';
1557 if (!userhost[0]) {
1558 fprintf(stderr, "Missing username\n");
1559 usage();
1560 }
1561 addargs(&args, "-l%s",userhost);
1562 }
1563
Damien Millerec692032004-01-27 21:22:00 +11001564 if ((cp = colon(host)) != NULL) {
1565 *cp++ = '\0';
1566 file1 = cp;
1567 }
1568
Damien Millerd14ee1e2002-02-05 12:27:31 +11001569 host = cleanhostname(host);
1570 if (!*host) {
1571 fprintf(stderr, "Missing hostname\n");
Damien Miller33804262001-02-04 23:20:18 +11001572 usage();
1573 }
Damien Millerd14ee1e2002-02-05 12:27:31 +11001574
Damien Millerd14ee1e2002-02-05 12:27:31 +11001575 addargs(&args, "-oProtocol %d", sshver);
1576
1577 /* no subsystem if the server-spec contains a '/' */
1578 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1579 addargs(&args, "-s");
1580
1581 addargs(&args, "%s", host);
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001582 addargs(&args, "%s", (sftp_server != NULL ?
Damien Millerd14ee1e2002-02-05 12:27:31 +11001583 sftp_server : "sftp"));
Damien Millerd14ee1e2002-02-05 12:27:31 +11001584
Damien Miller44f75c12004-01-21 10:58:47 +11001585 if (!batchmode)
1586 fprintf(stderr, "Connecting to %s...\n", host);
Damien Millercc685c12003-06-04 22:51:38 +10001587 connect_to_server(ssh_program, args.list, &in, &out);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001588 } else {
1589 args.list = NULL;
1590 addargs(&args, "sftp-server");
1591
Damien Miller44f75c12004-01-21 10:58:47 +11001592 if (!batchmode)
1593 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
Damien Millercc685c12003-06-04 22:51:38 +10001594 connect_to_server(sftp_direct, args.list, &in, &out);
Damien Miller33804262001-02-04 23:20:18 +11001595 }
Damien Miller3eec6b72006-01-31 21:49:27 +11001596 freeargs(&args);
Damien Miller33804262001-02-04 23:20:18 +11001597
Damien Miller956f3fb2003-01-10 21:40:00 +11001598 err = interactive_loop(in, out, file1, file2);
Damien Miller33804262001-02-04 23:20:18 +11001599
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001600#if !defined(USE_PIPES)
Damien Miller37294fb2005-07-17 17:18:49 +10001601 shutdown(in, SHUT_RDWR);
1602 shutdown(out, SHUT_RDWR);
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001603#endif
1604
Damien Miller33804262001-02-04 23:20:18 +11001605 close(in);
1606 close(out);
Damien Miller44f75c12004-01-21 10:58:47 +11001607 if (batchmode)
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001608 fclose(infile);
Damien Miller33804262001-02-04 23:20:18 +11001609
Ben Lindstrom47fd8112002-04-02 20:48:19 +00001610 while (waitpid(sshpid, NULL, 0) == -1)
1611 if (errno != EINTR)
1612 fatal("Couldn't wait for ssh process: %s",
1613 strerror(errno));
Damien Miller33804262001-02-04 23:20:18 +11001614
Damien Miller956f3fb2003-01-10 21:40:00 +11001615 exit(err == 0 ? 0 : 1);
Damien Miller33804262001-02-04 23:20:18 +11001616}