blob: 2da6c722f575cd179df64701ce083f676e1f4bb7 [file] [log] [blame]
Damien Millere3476ed2006-07-24 14:13:33 +10001/* $OpenBSD: sftp.c,v 1.87 2006/07/22 20:48:23 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 Millere3476ed2006-07-24 14:13:33 +100039#include <string.h>
Damien Millere6b3b612006-07-24 14:01:23 +100040#include <unistd.h>
Damien Miller33804262001-02-04 23:20:18 +110041
Damien Miller33804262001-02-04 23:20:18 +110042#include "xmalloc.h"
43#include "log.h"
44#include "pathnames.h"
Ben Lindstrom4529b702001-05-03 23:39:53 +000045#include "misc.h"
Damien Miller33804262001-02-04 23:20:18 +110046
47#include "sftp.h"
48#include "sftp-common.h"
49#include "sftp-client.h"
Damien Millerd7d46bb2004-02-18 14:11:13 +110050
Damien Miller20e1fab2004-02-18 14:30:55 +110051/* File to read commands from */
52FILE* infile;
53
54/* Are we in batchfile mode? */
55int batchmode = 0;
56
57/* Size of buffer used when copying files */
58size_t copy_buffer_len = 32768;
59
60/* Number of concurrent outstanding requests */
61size_t num_requests = 16;
62
63/* PID of ssh transport process */
64static pid_t sshpid = -1;
65
66/* This is set to 0 if the progressmeter is not desired. */
Damien Millerc0f27d82004-03-08 23:12:19 +110067int showprogress = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +110068
Darren Tuckercdf547a2004-05-24 10:12:19 +100069/* SIGINT received during command processing */
70volatile sig_atomic_t interrupted = 0;
71
Darren Tuckerb9123452004-06-22 13:06:45 +100072/* I wish qsort() took a separate ctx for the comparison function...*/
73int sort_flag;
74
Damien Miller20e1fab2004-02-18 14:30:55 +110075int remote_glob(struct sftp_conn *, const char *, int,
76 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
Damien Miller33804262001-02-04 23:20:18 +110077
Kevin Steves12888d12001-03-05 19:50:57 +000078extern char *__progname;
Kevin Steves12888d12001-03-05 19:50:57 +000079
Damien Miller20e1fab2004-02-18 14:30:55 +110080/* Separators for interactive commands */
81#define WHITESPACE " \t\r\n"
Damien Millerd7686fd2001-02-10 00:40:03 +110082
Darren Tuckerb9123452004-06-22 13:06:45 +100083/* ls flags */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100084#define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
85#define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
86#define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
87#define LS_NAME_SORT 0x08 /* Sort by name (default) */
88#define LS_TIME_SORT 0x10 /* Sort by mtime */
89#define LS_SIZE_SORT 0x20 /* Sort by file size */
90#define LS_REVERSE_SORT 0x40 /* Reverse sort order */
Darren Tucker9a526452004-06-22 13:09:55 +100091#define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
Darren Tuckerb9123452004-06-22 13:06:45 +100092
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100093#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
94#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
Damien Miller20e1fab2004-02-18 14:30:55 +110095
96/* Commands for interactive mode */
97#define I_CHDIR 1
98#define I_CHGRP 2
99#define I_CHMOD 3
100#define I_CHOWN 4
101#define I_GET 5
102#define I_HELP 6
103#define I_LCHDIR 7
104#define I_LLS 8
105#define I_LMKDIR 9
106#define I_LPWD 10
107#define I_LS 11
108#define I_LUMASK 12
109#define I_MKDIR 13
110#define I_PUT 14
111#define I_PWD 15
112#define I_QUIT 16
113#define I_RENAME 17
114#define I_RM 18
115#define I_RMDIR 19
116#define I_SHELL 20
117#define I_SYMLINK 21
118#define I_VERSION 22
119#define I_PROGRESS 23
120
121struct CMD {
122 const char *c;
123 const int n;
124};
125
126static const struct CMD cmds[] = {
127 { "bye", I_QUIT },
128 { "cd", I_CHDIR },
129 { "chdir", I_CHDIR },
130 { "chgrp", I_CHGRP },
131 { "chmod", I_CHMOD },
132 { "chown", I_CHOWN },
133 { "dir", I_LS },
134 { "exit", I_QUIT },
135 { "get", I_GET },
136 { "mget", I_GET },
137 { "help", I_HELP },
138 { "lcd", I_LCHDIR },
139 { "lchdir", I_LCHDIR },
140 { "lls", I_LLS },
141 { "lmkdir", I_LMKDIR },
142 { "ln", I_SYMLINK },
143 { "lpwd", I_LPWD },
144 { "ls", I_LS },
145 { "lumask", I_LUMASK },
146 { "mkdir", I_MKDIR },
147 { "progress", I_PROGRESS },
148 { "put", I_PUT },
149 { "mput", I_PUT },
150 { "pwd", I_PWD },
151 { "quit", I_QUIT },
152 { "rename", I_RENAME },
153 { "rm", I_RM },
154 { "rmdir", I_RMDIR },
155 { "symlink", I_SYMLINK },
156 { "version", I_VERSION },
157 { "!", I_SHELL },
158 { "?", I_HELP },
159 { NULL, -1}
160};
161
162int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
163
164static void
Darren Tuckercdf547a2004-05-24 10:12:19 +1000165killchild(int signo)
166{
Darren Tuckerba66df82005-01-24 21:57:40 +1100167 if (sshpid > 1) {
Darren Tuckercdf547a2004-05-24 10:12:19 +1000168 kill(sshpid, SIGTERM);
Darren Tuckerba66df82005-01-24 21:57:40 +1100169 waitpid(sshpid, NULL, 0);
170 }
Darren Tuckercdf547a2004-05-24 10:12:19 +1000171
172 _exit(1);
173}
174
175static void
176cmd_interrupt(int signo)
177{
178 const char msg[] = "\rInterrupt \n";
Darren Tuckere2f189a2004-12-06 22:45:53 +1100179 int olderrno = errno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000180
181 write(STDERR_FILENO, msg, sizeof(msg) - 1);
182 interrupted = 1;
Darren Tuckere2f189a2004-12-06 22:45:53 +1100183 errno = olderrno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000184}
185
186static void
Damien Miller20e1fab2004-02-18 14:30:55 +1100187help(void)
188{
189 printf("Available commands:\n");
190 printf("cd path Change remote directory to 'path'\n");
191 printf("lcd path Change local directory to 'path'\n");
192 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
193 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
194 printf("chown own path Change owner of file 'path' to 'own'\n");
195 printf("help Display this help text\n");
196 printf("get remote-path [local-path] Download file\n");
197 printf("lls [ls-options [path]] Display local directory listing\n");
198 printf("ln oldpath newpath Symlink remote file\n");
199 printf("lmkdir path Create local directory\n");
200 printf("lpwd Print local working directory\n");
201 printf("ls [path] Display remote directory listing\n");
202 printf("lumask umask Set local umask to 'umask'\n");
203 printf("mkdir path Create remote directory\n");
204 printf("progress Toggle display of progress meter\n");
205 printf("put local-path [remote-path] Upload file\n");
206 printf("pwd Display remote working directory\n");
207 printf("exit Quit sftp\n");
208 printf("quit Quit sftp\n");
209 printf("rename oldpath newpath Rename remote file\n");
210 printf("rmdir path Remove remote directory\n");
211 printf("rm path Delete remote file\n");
212 printf("symlink oldpath newpath Symlink remote file\n");
213 printf("version Show SFTP version\n");
214 printf("!command Execute 'command' in local shell\n");
215 printf("! Escape to local shell\n");
216 printf("? Synonym for help\n");
217}
218
219static void
220local_do_shell(const char *args)
221{
222 int status;
223 char *shell;
224 pid_t pid;
225
226 if (!*args)
227 args = NULL;
228
229 if ((shell = getenv("SHELL")) == NULL)
230 shell = _PATH_BSHELL;
231
232 if ((pid = fork()) == -1)
233 fatal("Couldn't fork: %s", strerror(errno));
234
235 if (pid == 0) {
236 /* XXX: child has pipe fds to ssh subproc open - issue? */
237 if (args) {
238 debug3("Executing %s -c \"%s\"", shell, args);
239 execl(shell, shell, "-c", args, (char *)NULL);
240 } else {
241 debug3("Executing %s", shell);
242 execl(shell, shell, (char *)NULL);
243 }
244 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
245 strerror(errno));
246 _exit(1);
247 }
248 while (waitpid(pid, &status, 0) == -1)
249 if (errno != EINTR)
250 fatal("Couldn't wait for child: %s", strerror(errno));
251 if (!WIFEXITED(status))
Damien Miller55b04f12006-03-26 14:23:17 +1100252 error("Shell exited abnormally");
Damien Miller20e1fab2004-02-18 14:30:55 +1100253 else if (WEXITSTATUS(status))
254 error("Shell exited with status %d", WEXITSTATUS(status));
255}
256
257static void
258local_do_ls(const char *args)
259{
260 if (!args || !*args)
261 local_do_shell(_PATH_LS);
262 else {
263 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
264 char *buf = xmalloc(len);
265
266 /* XXX: quoting - rip quoting code from ftp? */
267 snprintf(buf, len, _PATH_LS " %s", args);
268 local_do_shell(buf);
269 xfree(buf);
270 }
271}
272
273/* Strip one path (usually the pwd) from the start of another */
274static char *
275path_strip(char *path, char *strip)
276{
277 size_t len;
278
279 if (strip == NULL)
280 return (xstrdup(path));
281
282 len = strlen(strip);
Darren Tuckere2f189a2004-12-06 22:45:53 +1100283 if (strncmp(path, strip, len) == 0) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100284 if (strip[len - 1] != '/' && path[len] == '/')
285 len++;
286 return (xstrdup(path + len));
287 }
288
289 return (xstrdup(path));
290}
291
292static char *
293path_append(char *p1, char *p2)
294{
295 char *ret;
296 int len = strlen(p1) + strlen(p2) + 2;
297
298 ret = xmalloc(len);
299 strlcpy(ret, p1, len);
300 if (p1[strlen(p1) - 1] != '/')
301 strlcat(ret, "/", len);
302 strlcat(ret, p2, len);
303
304 return(ret);
305}
306
307static char *
308make_absolute(char *p, char *pwd)
309{
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000310 char *abs_str;
Damien Miller20e1fab2004-02-18 14:30:55 +1100311
312 /* Derelativise */
313 if (p && p[0] != '/') {
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000314 abs_str = path_append(pwd, p);
Damien Miller20e1fab2004-02-18 14:30:55 +1100315 xfree(p);
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000316 return(abs_str);
Damien Miller20e1fab2004-02-18 14:30:55 +1100317 } else
318 return(p);
319}
320
321static int
322infer_path(const char *p, char **ifp)
323{
324 char *cp;
325
326 cp = strrchr(p, '/');
327 if (cp == NULL) {
328 *ifp = xstrdup(p);
329 return(0);
330 }
331
332 if (!cp[1]) {
333 error("Invalid path");
334 return(-1);
335 }
336
337 *ifp = xstrdup(cp + 1);
338 return(0);
339}
340
341static int
342parse_getput_flags(const char **cpp, int *pflag)
343{
344 const char *cp = *cpp;
345
346 /* Check for flags */
347 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
348 switch (cp[1]) {
349 case 'p':
350 case 'P':
351 *pflag = 1;
352 break;
353 default:
354 error("Invalid flag -%c", cp[1]);
355 return(-1);
356 }
357 cp += 2;
358 *cpp = cp + strspn(cp, WHITESPACE);
359 }
360
361 return(0);
362}
363
364static int
365parse_ls_flags(const char **cpp, int *lflag)
366{
367 const char *cp = *cpp;
368
Darren Tuckerb9123452004-06-22 13:06:45 +1000369 /* Defaults */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000370 *lflag = LS_NAME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000371
Damien Miller20e1fab2004-02-18 14:30:55 +1100372 /* Check for flags */
373 if (cp++[0] == '-') {
Darren Tucker47eede72005-03-14 23:08:12 +1100374 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100375 switch (*cp) {
376 case 'l':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000377 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000378 *lflag |= LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100379 break;
380 case '1':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000381 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000382 *lflag |= LS_SHORT_VIEW;
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000383 break;
384 case 'n':
385 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000386 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100387 break;
Darren Tuckerb9123452004-06-22 13:06:45 +1000388 case 'S':
389 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000390 *lflag |= LS_SIZE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000391 break;
392 case 't':
393 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000394 *lflag |= LS_TIME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000395 break;
396 case 'r':
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000397 *lflag |= LS_REVERSE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000398 break;
399 case 'f':
400 *lflag &= ~SORT_FLAGS;
401 break;
Darren Tucker9a526452004-06-22 13:09:55 +1000402 case 'a':
403 *lflag |= LS_SHOW_ALL;
404 break;
Damien Miller20e1fab2004-02-18 14:30:55 +1100405 default:
406 error("Invalid flag -%c", *cp);
407 return(-1);
408 }
409 }
410 *cpp = cp + strspn(cp, WHITESPACE);
411 }
412
413 return(0);
414}
415
416static int
417get_pathname(const char **cpp, char **path)
418{
419 const char *cp = *cpp, *end;
420 char quot;
Damien Millereccb9de2005-06-17 12:59:34 +1000421 u_int i, j;
Damien Miller20e1fab2004-02-18 14:30:55 +1100422
423 cp += strspn(cp, WHITESPACE);
424 if (!*cp) {
425 *cpp = cp;
426 *path = NULL;
427 return (0);
428 }
429
430 *path = xmalloc(strlen(cp) + 1);
431
432 /* Check for quoted filenames */
433 if (*cp == '\"' || *cp == '\'') {
434 quot = *cp++;
435
436 /* Search for terminating quote, unescape some chars */
437 for (i = j = 0; i <= strlen(cp); i++) {
438 if (cp[i] == quot) { /* Found quote */
439 i++;
440 (*path)[j] = '\0';
441 break;
442 }
443 if (cp[i] == '\0') { /* End of string */
444 error("Unterminated quote");
445 goto fail;
446 }
447 if (cp[i] == '\\') { /* Escaped characters */
448 i++;
449 if (cp[i] != '\'' && cp[i] != '\"' &&
450 cp[i] != '\\') {
Damien Miller96d6d7d2004-06-26 09:21:06 +1000451 error("Bad escaped character '\\%c'",
Damien Miller20e1fab2004-02-18 14:30:55 +1100452 cp[i]);
453 goto fail;
454 }
455 }
456 (*path)[j++] = cp[i];
457 }
458
459 if (j == 0) {
460 error("Empty quotes");
461 goto fail;
462 }
463 *cpp = cp + i + strspn(cp + i, WHITESPACE);
464 } else {
465 /* Read to end of filename */
466 end = strpbrk(cp, WHITESPACE);
467 if (end == NULL)
468 end = strchr(cp, '\0');
469 *cpp = end + strspn(end, WHITESPACE);
470
471 memcpy(*path, cp, end - cp);
472 (*path)[end - cp] = '\0';
473 }
474 return (0);
475
476 fail:
477 xfree(*path);
478 *path = NULL;
479 return (-1);
480}
481
482static int
483is_dir(char *path)
484{
485 struct stat sb;
486
487 /* XXX: report errors? */
488 if (stat(path, &sb) == -1)
489 return(0);
490
491 return(sb.st_mode & S_IFDIR);
492}
493
494static int
495is_reg(char *path)
496{
497 struct stat sb;
498
499 if (stat(path, &sb) == -1)
500 fatal("stat %s: %s", path, strerror(errno));
501
502 return(S_ISREG(sb.st_mode));
503}
504
505static int
506remote_is_dir(struct sftp_conn *conn, char *path)
507{
508 Attrib *a;
509
510 /* XXX: report errors? */
511 if ((a = do_stat(conn, path, 1)) == NULL)
512 return(0);
513 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
514 return(0);
515 return(a->perm & S_IFDIR);
516}
517
518static int
519process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
520{
521 char *abs_src = NULL;
522 char *abs_dst = NULL;
523 char *tmp;
524 glob_t g;
525 int err = 0;
526 int i;
527
528 abs_src = xstrdup(src);
529 abs_src = make_absolute(abs_src, pwd);
530
531 memset(&g, 0, sizeof(g));
532 debug3("Looking up %s", abs_src);
533 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
534 error("File \"%s\" not found.", abs_src);
535 err = -1;
536 goto out;
537 }
538
539 /* If multiple matches, dst must be a directory or unspecified */
540 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
541 error("Multiple files match, but \"%s\" is not a directory",
542 dst);
543 err = -1;
544 goto out;
545 }
546
Darren Tuckercdf547a2004-05-24 10:12:19 +1000547 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100548 if (infer_path(g.gl_pathv[i], &tmp)) {
549 err = -1;
550 goto out;
551 }
552
553 if (g.gl_matchc == 1 && dst) {
554 /* If directory specified, append filename */
Damien Miller40b59852006-06-13 13:00:25 +1000555 xfree(tmp);
Damien Miller20e1fab2004-02-18 14:30:55 +1100556 if (is_dir(dst)) {
557 if (infer_path(g.gl_pathv[0], &tmp)) {
558 err = 1;
559 goto out;
560 }
561 abs_dst = path_append(dst, tmp);
562 xfree(tmp);
563 } else
564 abs_dst = xstrdup(dst);
565 } else if (dst) {
566 abs_dst = path_append(dst, tmp);
567 xfree(tmp);
568 } else
569 abs_dst = tmp;
570
571 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
572 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
573 err = -1;
574 xfree(abs_dst);
575 abs_dst = NULL;
576 }
577
578out:
579 xfree(abs_src);
Damien Miller20e1fab2004-02-18 14:30:55 +1100580 globfree(&g);
581 return(err);
582}
583
584static int
585process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
586{
587 char *tmp_dst = NULL;
588 char *abs_dst = NULL;
589 char *tmp;
590 glob_t g;
591 int err = 0;
592 int i;
593
594 if (dst) {
595 tmp_dst = xstrdup(dst);
596 tmp_dst = make_absolute(tmp_dst, pwd);
597 }
598
599 memset(&g, 0, sizeof(g));
600 debug3("Looking up %s", src);
601 if (glob(src, 0, NULL, &g)) {
602 error("File \"%s\" not found.", src);
603 err = -1;
604 goto out;
605 }
606
607 /* If multiple matches, dst may be directory or unspecified */
608 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
609 error("Multiple files match, but \"%s\" is not a directory",
610 tmp_dst);
611 err = -1;
612 goto out;
613 }
614
Darren Tuckercdf547a2004-05-24 10:12:19 +1000615 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100616 if (!is_reg(g.gl_pathv[i])) {
617 error("skipping non-regular file %s",
618 g.gl_pathv[i]);
619 continue;
620 }
621 if (infer_path(g.gl_pathv[i], &tmp)) {
622 err = -1;
623 goto out;
624 }
625
626 if (g.gl_matchc == 1 && tmp_dst) {
627 /* If directory specified, append filename */
628 if (remote_is_dir(conn, tmp_dst)) {
629 if (infer_path(g.gl_pathv[0], &tmp)) {
630 err = 1;
631 goto out;
632 }
633 abs_dst = path_append(tmp_dst, tmp);
634 xfree(tmp);
635 } else
636 abs_dst = xstrdup(tmp_dst);
637
638 } else if (tmp_dst) {
639 abs_dst = path_append(tmp_dst, tmp);
640 xfree(tmp);
641 } else
642 abs_dst = make_absolute(tmp, pwd);
643
644 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
645 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
646 err = -1;
647 }
648
649out:
650 if (abs_dst)
651 xfree(abs_dst);
652 if (tmp_dst)
653 xfree(tmp_dst);
654 globfree(&g);
655 return(err);
656}
657
658static int
659sdirent_comp(const void *aa, const void *bb)
660{
661 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
662 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000663 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100664
Darren Tuckerb9123452004-06-22 13:06:45 +1000665#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000666 if (sort_flag & LS_NAME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000667 return (rmul * strcmp(a->filename, b->filename));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000668 else if (sort_flag & LS_TIME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000669 return (rmul * NCMP(a->a.mtime, b->a.mtime));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000670 else if (sort_flag & LS_SIZE_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000671 return (rmul * NCMP(a->a.size, b->a.size));
672
673 fatal("Unknown ls sort type");
Damien Miller20e1fab2004-02-18 14:30:55 +1100674}
675
676/* sftp ls.1 replacement for directories */
677static int
678do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
679{
Damien Millereccb9de2005-06-17 12:59:34 +1000680 int n;
681 u_int c = 1, colspace = 0, columns = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100682 SFTP_DIRENT **d;
683
684 if ((n = do_readdir(conn, path, &d)) != 0)
685 return (n);
686
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000687 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000688 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100689 struct winsize ws;
690 char *tmp;
691
692 /* Count entries for sort and find longest filename */
Darren Tucker9a526452004-06-22 13:09:55 +1000693 for (n = 0; d[n] != NULL; n++) {
694 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
695 m = MAX(m, strlen(d[n]->filename));
696 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100697
698 /* Add any subpath that also needs to be counted */
699 tmp = path_strip(path, strip_path);
700 m += strlen(tmp);
701 xfree(tmp);
702
703 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
704 width = ws.ws_col;
705
706 columns = width / (m + 2);
707 columns = MAX(columns, 1);
708 colspace = width / columns;
709 colspace = MIN(colspace, width);
710 }
711
Darren Tuckerb9123452004-06-22 13:06:45 +1000712 if (lflag & SORT_FLAGS) {
Damien Miller653b93b2005-11-05 15:15:23 +1100713 for (n = 0; d[n] != NULL; n++)
714 ; /* count entries */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000715 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
Darren Tuckerb9123452004-06-22 13:06:45 +1000716 qsort(d, n, sizeof(*d), sdirent_comp);
717 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100718
Darren Tuckercdf547a2004-05-24 10:12:19 +1000719 for (n = 0; d[n] != NULL && !interrupted; n++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100720 char *tmp, *fname;
721
Darren Tucker9a526452004-06-22 13:09:55 +1000722 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
723 continue;
724
Damien Miller20e1fab2004-02-18 14:30:55 +1100725 tmp = path_append(path, d[n]->filename);
726 fname = path_strip(tmp, strip_path);
727 xfree(tmp);
728
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000729 if (lflag & LS_LONG_VIEW) {
730 if (lflag & LS_NUMERIC_VIEW) {
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000731 char *lname;
732 struct stat sb;
Damien Miller20e1fab2004-02-18 14:30:55 +1100733
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000734 memset(&sb, 0, sizeof(sb));
735 attrib_to_stat(&d[n]->a, &sb);
736 lname = ls_file(fname, &sb, 1);
737 printf("%s\n", lname);
738 xfree(lname);
739 } else
740 printf("%s\n", d[n]->longname);
Damien Miller20e1fab2004-02-18 14:30:55 +1100741 } else {
742 printf("%-*s", colspace, fname);
743 if (c >= columns) {
744 printf("\n");
745 c = 1;
746 } else
747 c++;
748 }
749
750 xfree(fname);
751 }
752
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000753 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100754 printf("\n");
755
756 free_sftp_dirents(d);
757 return (0);
758}
759
760/* sftp ls.1 replacement which handles path globs */
761static int
762do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
763 int lflag)
764{
765 glob_t g;
Damien Millereccb9de2005-06-17 12:59:34 +1000766 u_int i, c = 1, colspace = 0, columns = 1;
Darren Tucker596dcfa2004-12-11 13:37:22 +1100767 Attrib *a = NULL;
Damien Miller20e1fab2004-02-18 14:30:55 +1100768
769 memset(&g, 0, sizeof(g));
770
771 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
Darren Tucker596dcfa2004-12-11 13:37:22 +1100772 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
773 if (g.gl_pathc)
774 globfree(&g);
Damien Miller20e1fab2004-02-18 14:30:55 +1100775 error("Can't ls: \"%s\" not found", path);
776 return (-1);
777 }
778
Darren Tuckercdf547a2004-05-24 10:12:19 +1000779 if (interrupted)
780 goto out;
781
Damien Miller20e1fab2004-02-18 14:30:55 +1100782 /*
Darren Tucker596dcfa2004-12-11 13:37:22 +1100783 * If the glob returns a single match and it is a directory,
784 * then just list its contents.
Damien Miller20e1fab2004-02-18 14:30:55 +1100785 */
Darren Tucker596dcfa2004-12-11 13:37:22 +1100786 if (g.gl_matchc == 1) {
787 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100788 globfree(&g);
789 return (-1);
790 }
791 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
792 S_ISDIR(a->perm)) {
Darren Tucker596dcfa2004-12-11 13:37:22 +1100793 int err;
794
795 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
Damien Miller20e1fab2004-02-18 14:30:55 +1100796 globfree(&g);
Darren Tucker596dcfa2004-12-11 13:37:22 +1100797 return (err);
Damien Miller20e1fab2004-02-18 14:30:55 +1100798 }
799 }
800
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000801 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000802 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100803 struct winsize ws;
804
805 /* Count entries for sort and find longest filename */
806 for (i = 0; g.gl_pathv[i]; i++)
807 m = MAX(m, strlen(g.gl_pathv[i]));
808
809 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
810 width = ws.ws_col;
811
812 columns = width / (m + 2);
813 columns = MAX(columns, 1);
814 colspace = width / columns;
815 }
816
Darren Tucker596dcfa2004-12-11 13:37:22 +1100817 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100818 char *fname;
819
820 fname = path_strip(g.gl_pathv[i], strip_path);
821
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000822 if (lflag & LS_LONG_VIEW) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100823 char *lname;
824 struct stat sb;
825
826 /*
827 * XXX: this is slow - 1 roundtrip per path
828 * A solution to this is to fork glob() and
829 * build a sftp specific version which keeps the
830 * attribs (which currently get thrown away)
831 * that the server returns as well as the filenames.
832 */
833 memset(&sb, 0, sizeof(sb));
Darren Tucker596dcfa2004-12-11 13:37:22 +1100834 if (a == NULL)
835 a = do_lstat(conn, g.gl_pathv[i], 1);
Damien Miller20e1fab2004-02-18 14:30:55 +1100836 if (a != NULL)
837 attrib_to_stat(a, &sb);
838 lname = ls_file(fname, &sb, 1);
839 printf("%s\n", lname);
840 xfree(lname);
841 } else {
842 printf("%-*s", colspace, fname);
843 if (c >= columns) {
844 printf("\n");
845 c = 1;
846 } else
847 c++;
848 }
849 xfree(fname);
850 }
851
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000852 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100853 printf("\n");
854
Darren Tuckercdf547a2004-05-24 10:12:19 +1000855 out:
Damien Miller20e1fab2004-02-18 14:30:55 +1100856 if (g.gl_pathc)
857 globfree(&g);
858
859 return (0);
860}
861
862static int
863parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
864 unsigned long *n_arg, char **path1, char **path2)
865{
866 const char *cmd, *cp = *cpp;
867 char *cp2;
868 int base = 0;
869 long l;
870 int i, cmdnum;
871
872 /* Skip leading whitespace */
873 cp = cp + strspn(cp, WHITESPACE);
874
875 /* Ignore blank lines and lines which begin with comment '#' char */
876 if (*cp == '\0' || *cp == '#')
877 return (0);
878
879 /* Check for leading '-' (disable error processing) */
880 *iflag = 0;
881 if (*cp == '-') {
882 *iflag = 1;
883 cp++;
884 }
885
886 /* Figure out which command we have */
887 for (i = 0; cmds[i].c; i++) {
888 int cmdlen = strlen(cmds[i].c);
889
890 /* Check for command followed by whitespace */
891 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
892 strchr(WHITESPACE, cp[cmdlen])) {
893 cp += cmdlen;
894 cp = cp + strspn(cp, WHITESPACE);
895 break;
896 }
897 }
898 cmdnum = cmds[i].n;
899 cmd = cmds[i].c;
900
901 /* Special case */
902 if (*cp == '!') {
903 cp++;
904 cmdnum = I_SHELL;
905 } else if (cmdnum == -1) {
906 error("Invalid command.");
907 return (-1);
908 }
909
910 /* Get arguments and parse flags */
911 *lflag = *pflag = *n_arg = 0;
912 *path1 = *path2 = NULL;
913 switch (cmdnum) {
914 case I_GET:
915 case I_PUT:
916 if (parse_getput_flags(&cp, pflag))
917 return(-1);
918 /* Get first pathname (mandatory) */
919 if (get_pathname(&cp, path1))
920 return(-1);
921 if (*path1 == NULL) {
922 error("You must specify at least one path after a "
923 "%s command.", cmd);
924 return(-1);
925 }
926 /* Try to get second pathname (optional) */
927 if (get_pathname(&cp, path2))
928 return(-1);
929 break;
930 case I_RENAME:
931 case I_SYMLINK:
932 if (get_pathname(&cp, path1))
933 return(-1);
934 if (get_pathname(&cp, path2))
935 return(-1);
936 if (!*path1 || !*path2) {
937 error("You must specify two paths after a %s "
938 "command.", cmd);
939 return(-1);
940 }
941 break;
942 case I_RM:
943 case I_MKDIR:
944 case I_RMDIR:
945 case I_CHDIR:
946 case I_LCHDIR:
947 case I_LMKDIR:
948 /* Get pathname (mandatory) */
949 if (get_pathname(&cp, path1))
950 return(-1);
951 if (*path1 == NULL) {
952 error("You must specify a path after a %s command.",
953 cmd);
954 return(-1);
955 }
956 break;
957 case I_LS:
958 if (parse_ls_flags(&cp, lflag))
959 return(-1);
960 /* Path is optional */
961 if (get_pathname(&cp, path1))
962 return(-1);
963 break;
964 case I_LLS:
965 case I_SHELL:
966 /* Uses the rest of the line */
967 break;
968 case I_LUMASK:
969 base = 8;
970 case I_CHMOD:
971 base = 8;
972 case I_CHOWN:
973 case I_CHGRP:
974 /* Get numeric arg (mandatory) */
975 l = strtol(cp, &cp2, base);
976 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
977 errno == ERANGE) || l < 0) {
978 error("You must supply a numeric argument "
979 "to the %s command.", cmd);
980 return(-1);
981 }
982 cp = cp2;
983 *n_arg = l;
984 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
985 break;
986 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
987 error("You must supply a numeric argument "
988 "to the %s command.", cmd);
989 return(-1);
990 }
991 cp += strspn(cp, WHITESPACE);
992
993 /* Get pathname (mandatory) */
994 if (get_pathname(&cp, path1))
995 return(-1);
996 if (*path1 == NULL) {
997 error("You must specify a path after a %s command.",
998 cmd);
999 return(-1);
1000 }
1001 break;
1002 case I_QUIT:
1003 case I_PWD:
1004 case I_LPWD:
1005 case I_HELP:
1006 case I_VERSION:
1007 case I_PROGRESS:
1008 break;
1009 default:
1010 fatal("Command not implemented");
1011 }
1012
1013 *cpp = cp;
1014 return(cmdnum);
1015}
1016
1017static int
1018parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1019 int err_abort)
1020{
1021 char *path1, *path2, *tmp;
1022 int pflag, lflag, iflag, cmdnum, i;
1023 unsigned long n_arg;
1024 Attrib a, *aa;
1025 char path_buf[MAXPATHLEN];
1026 int err = 0;
1027 glob_t g;
1028
1029 path1 = path2 = NULL;
1030 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1031 &path1, &path2);
1032
1033 if (iflag != 0)
1034 err_abort = 0;
1035
1036 memset(&g, 0, sizeof(g));
1037
1038 /* Perform command */
1039 switch (cmdnum) {
1040 case 0:
1041 /* Blank line */
1042 break;
1043 case -1:
1044 /* Unrecognized command */
1045 err = -1;
1046 break;
1047 case I_GET:
1048 err = process_get(conn, path1, path2, *pwd, pflag);
1049 break;
1050 case I_PUT:
1051 err = process_put(conn, path1, path2, *pwd, pflag);
1052 break;
1053 case I_RENAME:
1054 path1 = make_absolute(path1, *pwd);
1055 path2 = make_absolute(path2, *pwd);
1056 err = do_rename(conn, path1, path2);
1057 break;
1058 case I_SYMLINK:
1059 path2 = make_absolute(path2, *pwd);
1060 err = do_symlink(conn, path1, path2);
1061 break;
1062 case I_RM:
1063 path1 = make_absolute(path1, *pwd);
1064 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001065 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001066 printf("Removing %s\n", g.gl_pathv[i]);
1067 err = do_rm(conn, g.gl_pathv[i]);
1068 if (err != 0 && err_abort)
1069 break;
1070 }
1071 break;
1072 case I_MKDIR:
1073 path1 = make_absolute(path1, *pwd);
1074 attrib_clear(&a);
1075 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1076 a.perm = 0777;
1077 err = do_mkdir(conn, path1, &a);
1078 break;
1079 case I_RMDIR:
1080 path1 = make_absolute(path1, *pwd);
1081 err = do_rmdir(conn, path1);
1082 break;
1083 case I_CHDIR:
1084 path1 = make_absolute(path1, *pwd);
1085 if ((tmp = do_realpath(conn, path1)) == NULL) {
1086 err = 1;
1087 break;
1088 }
1089 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1090 xfree(tmp);
1091 err = 1;
1092 break;
1093 }
1094 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1095 error("Can't change directory: Can't check target");
1096 xfree(tmp);
1097 err = 1;
1098 break;
1099 }
1100 if (!S_ISDIR(aa->perm)) {
1101 error("Can't change directory: \"%s\" is not "
1102 "a directory", tmp);
1103 xfree(tmp);
1104 err = 1;
1105 break;
1106 }
1107 xfree(*pwd);
1108 *pwd = tmp;
1109 break;
1110 case I_LS:
1111 if (!path1) {
1112 do_globbed_ls(conn, *pwd, *pwd, lflag);
1113 break;
1114 }
1115
1116 /* Strip pwd off beginning of non-absolute paths */
1117 tmp = NULL;
1118 if (*path1 != '/')
1119 tmp = *pwd;
1120
1121 path1 = make_absolute(path1, *pwd);
1122 err = do_globbed_ls(conn, path1, tmp, lflag);
1123 break;
1124 case I_LCHDIR:
1125 if (chdir(path1) == -1) {
1126 error("Couldn't change local directory to "
1127 "\"%s\": %s", path1, strerror(errno));
1128 err = 1;
1129 }
1130 break;
1131 case I_LMKDIR:
1132 if (mkdir(path1, 0777) == -1) {
1133 error("Couldn't create local directory "
1134 "\"%s\": %s", path1, strerror(errno));
1135 err = 1;
1136 }
1137 break;
1138 case I_LLS:
1139 local_do_ls(cmd);
1140 break;
1141 case I_SHELL:
1142 local_do_shell(cmd);
1143 break;
1144 case I_LUMASK:
1145 umask(n_arg);
1146 printf("Local umask: %03lo\n", n_arg);
1147 break;
1148 case I_CHMOD:
1149 path1 = make_absolute(path1, *pwd);
1150 attrib_clear(&a);
1151 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1152 a.perm = n_arg;
1153 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001154 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001155 printf("Changing mode on %s\n", g.gl_pathv[i]);
1156 err = do_setstat(conn, g.gl_pathv[i], &a);
1157 if (err != 0 && err_abort)
1158 break;
1159 }
1160 break;
1161 case I_CHOWN:
1162 case I_CHGRP:
1163 path1 = make_absolute(path1, *pwd);
1164 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001165 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001166 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1167 if (err != 0 && err_abort)
1168 break;
1169 else
1170 continue;
1171 }
1172 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1173 error("Can't get current ownership of "
1174 "remote file \"%s\"", g.gl_pathv[i]);
1175 if (err != 0 && err_abort)
1176 break;
1177 else
1178 continue;
1179 }
1180 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1181 if (cmdnum == I_CHOWN) {
1182 printf("Changing owner on %s\n", g.gl_pathv[i]);
1183 aa->uid = n_arg;
1184 } else {
1185 printf("Changing group on %s\n", g.gl_pathv[i]);
1186 aa->gid = n_arg;
1187 }
1188 err = do_setstat(conn, g.gl_pathv[i], aa);
1189 if (err != 0 && err_abort)
1190 break;
1191 }
1192 break;
1193 case I_PWD:
1194 printf("Remote working directory: %s\n", *pwd);
1195 break;
1196 case I_LPWD:
1197 if (!getcwd(path_buf, sizeof(path_buf))) {
1198 error("Couldn't get local cwd: %s", strerror(errno));
1199 err = -1;
1200 break;
1201 }
1202 printf("Local working directory: %s\n", path_buf);
1203 break;
1204 case I_QUIT:
1205 /* Processed below */
1206 break;
1207 case I_HELP:
1208 help();
1209 break;
1210 case I_VERSION:
1211 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1212 break;
1213 case I_PROGRESS:
1214 showprogress = !showprogress;
1215 if (showprogress)
1216 printf("Progress meter enabled\n");
1217 else
1218 printf("Progress meter disabled\n");
1219 break;
1220 default:
1221 fatal("%d is not implemented", cmdnum);
1222 }
1223
1224 if (g.gl_pathc)
1225 globfree(&g);
1226 if (path1)
1227 xfree(path1);
1228 if (path2)
1229 xfree(path2);
1230
1231 /* If an unignored error occurs in batch mode we should abort. */
1232 if (err_abort && err != 0)
1233 return (-1);
1234 else if (cmdnum == I_QUIT)
1235 return (1);
1236
1237 return (0);
1238}
1239
Darren Tucker2d963d82004-11-07 20:04:10 +11001240#ifdef USE_LIBEDIT
1241static char *
1242prompt(EditLine *el)
1243{
1244 return ("sftp> ");
1245}
1246#endif
1247
Damien Miller20e1fab2004-02-18 14:30:55 +11001248int
1249interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1250{
1251 char *pwd;
1252 char *dir = NULL;
1253 char cmd[2048];
1254 struct sftp_conn *conn;
Damien Miller0e2c1022005-08-12 22:16:22 +10001255 int err, interactive;
Darren Tucker2d963d82004-11-07 20:04:10 +11001256 EditLine *el = NULL;
1257#ifdef USE_LIBEDIT
1258 History *hl = NULL;
1259 HistEvent hev;
1260 extern char *__progname;
1261
1262 if (!batchmode && isatty(STDIN_FILENO)) {
1263 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1264 fatal("Couldn't initialise editline");
1265 if ((hl = history_init()) == NULL)
1266 fatal("Couldn't initialise editline history");
1267 history(hl, &hev, H_SETSIZE, 100);
1268 el_set(el, EL_HIST, history, hl);
1269
1270 el_set(el, EL_PROMPT, prompt);
1271 el_set(el, EL_EDITOR, "emacs");
1272 el_set(el, EL_TERMINAL, NULL);
1273 el_set(el, EL_SIGNAL, 1);
1274 el_source(el, NULL);
1275 }
1276#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001277
1278 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1279 if (conn == NULL)
1280 fatal("Couldn't initialise connection to server");
1281
1282 pwd = do_realpath(conn, ".");
1283 if (pwd == NULL)
1284 fatal("Need cwd");
1285
1286 if (file1 != NULL) {
1287 dir = xstrdup(file1);
1288 dir = make_absolute(dir, pwd);
1289
1290 if (remote_is_dir(conn, dir) && file2 == NULL) {
1291 printf("Changing to: %s\n", dir);
1292 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001293 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1294 xfree(dir);
1295 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001296 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001297 return (-1);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001298 }
Damien Miller20e1fab2004-02-18 14:30:55 +11001299 } else {
1300 if (file2 == NULL)
1301 snprintf(cmd, sizeof cmd, "get %s", dir);
1302 else
1303 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1304 file2);
1305
1306 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1307 xfree(dir);
1308 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001309 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001310 return (err);
1311 }
1312 xfree(dir);
1313 }
1314
Darren Tucker93e7e8f2005-08-23 08:06:55 +10001315#if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
Damien Miller20e1fab2004-02-18 14:30:55 +11001316 setvbuf(stdout, NULL, _IOLBF, 0);
1317 setvbuf(infile, NULL, _IOLBF, 0);
1318#else
Damien Miller37294fb2005-07-17 17:18:49 +10001319 setlinebuf(stdout);
1320 setlinebuf(infile);
Damien Miller20e1fab2004-02-18 14:30:55 +11001321#endif
1322
Damien Miller0e2c1022005-08-12 22:16:22 +10001323 interactive = !batchmode && isatty(STDIN_FILENO);
Damien Miller20e1fab2004-02-18 14:30:55 +11001324 err = 0;
1325 for (;;) {
1326 char *cp;
1327
Darren Tuckercdf547a2004-05-24 10:12:19 +10001328 signal(SIGINT, SIG_IGN);
1329
Darren Tucker2d963d82004-11-07 20:04:10 +11001330 if (el == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001331 if (interactive)
1332 printf("sftp> ");
Darren Tucker2d963d82004-11-07 20:04:10 +11001333 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001334 if (interactive)
1335 printf("\n");
Darren Tucker2d963d82004-11-07 20:04:10 +11001336 break;
1337 }
Damien Miller0e2c1022005-08-12 22:16:22 +10001338 if (!interactive) { /* Echo command */
1339 printf("sftp> %s", cmd);
1340 if (strlen(cmd) > 0 &&
1341 cmd[strlen(cmd) - 1] != '\n')
1342 printf("\n");
1343 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001344 } else {
1345#ifdef USE_LIBEDIT
1346 const char *line;
1347 int count = 0;
Damien Miller20e1fab2004-02-18 14:30:55 +11001348
Damien Miller0e2c1022005-08-12 22:16:22 +10001349 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1350 printf("\n");
1351 break;
1352 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001353 history(hl, &hev, H_ENTER, line);
1354 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1355 fprintf(stderr, "Error: input line too long\n");
1356 continue;
1357 }
1358#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001359 }
1360
Damien Miller20e1fab2004-02-18 14:30:55 +11001361 cp = strrchr(cmd, '\n');
1362 if (cp)
1363 *cp = '\0';
1364
Darren Tuckercdf547a2004-05-24 10:12:19 +10001365 /* Handle user interrupts gracefully during commands */
1366 interrupted = 0;
1367 signal(SIGINT, cmd_interrupt);
1368
Damien Miller20e1fab2004-02-18 14:30:55 +11001369 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1370 if (err != 0)
1371 break;
1372 }
1373 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001374 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001375
Tim Rice027e8b12005-08-15 14:52:50 -07001376#ifdef USE_LIBEDIT
Damien Miller0e2c1022005-08-12 22:16:22 +10001377 if (el != NULL)
1378 el_end(el);
Tim Rice027e8b12005-08-15 14:52:50 -07001379#endif /* USE_LIBEDIT */
Damien Miller0e2c1022005-08-12 22:16:22 +10001380
Damien Miller20e1fab2004-02-18 14:30:55 +11001381 /* err == 1 signifies normal "quit" exit */
1382 return (err >= 0 ? 0 : -1);
1383}
Damien Miller62d57f62003-01-10 21:43:24 +11001384
Ben Lindstrombba81212001-06-25 05:01:22 +00001385static void
Damien Millercc685c12003-06-04 22:51:38 +10001386connect_to_server(char *path, char **args, int *in, int *out)
Damien Miller33804262001-02-04 23:20:18 +11001387{
1388 int c_in, c_out;
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001389
Damien Miller33804262001-02-04 23:20:18 +11001390#ifdef USE_PIPES
1391 int pin[2], pout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001392
Damien Miller33804262001-02-04 23:20:18 +11001393 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1394 fatal("pipe: %s", strerror(errno));
1395 *in = pin[0];
1396 *out = pout[1];
1397 c_in = pout[0];
1398 c_out = pin[1];
1399#else /* USE_PIPES */
1400 int inout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001401
Damien Miller33804262001-02-04 23:20:18 +11001402 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1403 fatal("socketpair: %s", strerror(errno));
1404 *in = *out = inout[0];
1405 c_in = c_out = inout[1];
1406#endif /* USE_PIPES */
1407
Damien Millercc685c12003-06-04 22:51:38 +10001408 if ((sshpid = fork()) == -1)
Damien Miller33804262001-02-04 23:20:18 +11001409 fatal("fork: %s", strerror(errno));
Damien Millercc685c12003-06-04 22:51:38 +10001410 else if (sshpid == 0) {
Damien Miller33804262001-02-04 23:20:18 +11001411 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1412 (dup2(c_out, STDOUT_FILENO) == -1)) {
1413 fprintf(stderr, "dup2: %s\n", strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001414 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001415 }
1416 close(*in);
1417 close(*out);
1418 close(c_in);
1419 close(c_out);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001420
1421 /*
1422 * The underlying ssh is in the same process group, so we must
Darren Tuckerfc959702004-07-17 16:12:08 +10001423 * ignore SIGINT if we want to gracefully abort commands,
1424 * otherwise the signal will make it to the ssh process and
Darren Tuckercdf547a2004-05-24 10:12:19 +10001425 * kill it too
1426 */
1427 signal(SIGINT, SIG_IGN);
Darren Tuckerbd12f172004-06-18 16:23:43 +10001428 execvp(path, args);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001429 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001430 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001431 }
1432
Damien Millercc685c12003-06-04 22:51:38 +10001433 signal(SIGTERM, killchild);
1434 signal(SIGINT, killchild);
1435 signal(SIGHUP, killchild);
Damien Miller33804262001-02-04 23:20:18 +11001436 close(c_in);
1437 close(c_out);
1438}
1439
Ben Lindstrombba81212001-06-25 05:01:22 +00001440static void
Damien Miller33804262001-02-04 23:20:18 +11001441usage(void)
1442{
Damien Miller025e01c2002-02-08 22:06:29 +11001443 extern char *__progname;
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001444
Ben Lindstrom1e243242001-09-18 05:38:44 +00001445 fprintf(stderr,
Darren Tucker1f203942003-10-15 15:50:42 +10001446 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1447 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1448 " [-S program] [-s subsystem | sftp_server] host\n"
1449 " %s [[user@]host[:file [file]]]\n"
1450 " %s [[user@]host[:dir[/]]]\n"
1451 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
Damien Miller33804262001-02-04 23:20:18 +11001452 exit(1);
1453}
1454
Kevin Stevesef4eea92001-02-05 12:42:17 +00001455int
Damien Miller33804262001-02-04 23:20:18 +11001456main(int argc, char **argv)
1457{
Damien Miller956f3fb2003-01-10 21:40:00 +11001458 int in, out, ch, err;
Damien Miller7cf17eb2004-06-15 10:28:56 +10001459 char *host, *userhost, *cp, *file2 = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001460 int debug_level = 0, sshver = 2;
1461 char *file1 = NULL, *sftp_server = NULL;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001462 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001463 LogLevel ll = SYSLOG_LEVEL_INFO;
1464 arglist args;
Damien Millerd7686fd2001-02-10 00:40:03 +11001465 extern int optind;
1466 extern char *optarg;
Damien Miller33804262001-02-04 23:20:18 +11001467
Darren Tuckerce321d82005-10-03 18:11:24 +10001468 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1469 sanitise_stdfd();
1470
Damien Miller59d3d5b2003-08-22 09:34:41 +10001471 __progname = ssh_get_progname(argv[0]);
Damien Miller3eec6b72006-01-31 21:49:27 +11001472 memset(&args, '\0', sizeof(args));
Ben Lindstrom387c4722001-05-08 20:27:25 +00001473 args.list = NULL;
Damien Miller2b5a0de2006-03-31 23:10:31 +11001474 addargs(&args, "%s", ssh_program);
Ben Lindstrom387c4722001-05-08 20:27:25 +00001475 addargs(&args, "-oForwardX11 no");
1476 addargs(&args, "-oForwardAgent no");
Damien Millerd27b9472005-12-13 19:29:02 +11001477 addargs(&args, "-oPermitLocalCommand no");
Ben Lindstrom2b7a0e92001-09-20 00:57:55 +00001478 addargs(&args, "-oClearAllForwardings yes");
Damien Millere4f5a822004-01-21 14:11:05 +11001479
Ben Lindstrom387c4722001-05-08 20:27:25 +00001480 ll = SYSLOG_LEVEL_INFO;
Damien Millere4f5a822004-01-21 14:11:05 +11001481 infile = stdin;
Damien Millerd7686fd2001-02-10 00:40:03 +11001482
Damien Miller16a13332002-02-13 14:03:56 +11001483 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
Damien Millerd7686fd2001-02-10 00:40:03 +11001484 switch (ch) {
1485 case 'C':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001486 addargs(&args, "-C");
Damien Millerd7686fd2001-02-10 00:40:03 +11001487 break;
1488 case 'v':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001489 if (debug_level < 3) {
1490 addargs(&args, "-v");
1491 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1492 }
1493 debug_level++;
Damien Millerd7686fd2001-02-10 00:40:03 +11001494 break;
Ben Lindstrom1e243242001-09-18 05:38:44 +00001495 case 'F':
Damien Millerd7686fd2001-02-10 00:40:03 +11001496 case 'o':
Ben Lindstrom1e243242001-09-18 05:38:44 +00001497 addargs(&args, "-%c%s", ch, optarg);
Damien Millerd7686fd2001-02-10 00:40:03 +11001498 break;
1499 case '1':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001500 sshver = 1;
Damien Millerd7686fd2001-02-10 00:40:03 +11001501 if (sftp_server == NULL)
1502 sftp_server = _PATH_SFTP_SERVER;
1503 break;
1504 case 's':
1505 sftp_server = optarg;
1506 break;
1507 case 'S':
1508 ssh_program = optarg;
Damien Miller3eec6b72006-01-31 21:49:27 +11001509 replacearg(&args, 0, "%s", ssh_program);
Damien Millerd7686fd2001-02-10 00:40:03 +11001510 break;
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001511 case 'b':
Damien Miller44f75c12004-01-21 10:58:47 +11001512 if (batchmode)
1513 fatal("Batch file already specified.");
1514
1515 /* Allow "-" as stdin */
Darren Tuckerfc959702004-07-17 16:12:08 +10001516 if (strcmp(optarg, "-") != 0 &&
Damien Miller0dc1bef2005-07-17 17:22:45 +10001517 (infile = fopen(optarg, "r")) == NULL)
Damien Miller44f75c12004-01-21 10:58:47 +11001518 fatal("%s (%s).", strerror(errno), optarg);
Damien Miller62d57f62003-01-10 21:43:24 +11001519 showprogress = 0;
Damien Miller44f75c12004-01-21 10:58:47 +11001520 batchmode = 1;
Damien Miller64e8d442005-03-01 21:16:47 +11001521 addargs(&args, "-obatchmode yes");
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001522 break;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001523 case 'P':
1524 sftp_direct = optarg;
1525 break;
Damien Miller8829d362002-02-08 22:04:05 +11001526 case 'B':
1527 copy_buffer_len = strtol(optarg, &cp, 10);
1528 if (copy_buffer_len == 0 || *cp != '\0')
1529 fatal("Invalid buffer size \"%s\"", optarg);
1530 break;
Damien Miller16a13332002-02-13 14:03:56 +11001531 case 'R':
1532 num_requests = strtol(optarg, &cp, 10);
1533 if (num_requests == 0 || *cp != '\0')
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001534 fatal("Invalid number of requests \"%s\"",
Damien Miller16a13332002-02-13 14:03:56 +11001535 optarg);
1536 break;
Damien Millerd7686fd2001-02-10 00:40:03 +11001537 case 'h':
1538 default:
Damien Miller33804262001-02-04 23:20:18 +11001539 usage();
1540 }
1541 }
1542
Damien Millerc0f27d82004-03-08 23:12:19 +11001543 if (!isatty(STDERR_FILENO))
1544 showprogress = 0;
1545
Ben Lindstrom2f3d52a2002-04-02 21:06:18 +00001546 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1547
Damien Millerd14ee1e2002-02-05 12:27:31 +11001548 if (sftp_direct == NULL) {
1549 if (optind == argc || argc > (optind + 2))
1550 usage();
Damien Miller33804262001-02-04 23:20:18 +11001551
Damien Millerd14ee1e2002-02-05 12:27:31 +11001552 userhost = xstrdup(argv[optind]);
1553 file2 = argv[optind+1];
Ben Lindstrom63667f62001-04-13 00:00:14 +00001554
Ben Lindstromc276c122002-12-23 02:14:51 +00001555 if ((host = strrchr(userhost, '@')) == NULL)
Damien Millerd14ee1e2002-02-05 12:27:31 +11001556 host = userhost;
1557 else {
1558 *host++ = '\0';
1559 if (!userhost[0]) {
1560 fprintf(stderr, "Missing username\n");
1561 usage();
1562 }
1563 addargs(&args, "-l%s",userhost);
1564 }
1565
Damien Millerec692032004-01-27 21:22:00 +11001566 if ((cp = colon(host)) != NULL) {
1567 *cp++ = '\0';
1568 file1 = cp;
1569 }
1570
Damien Millerd14ee1e2002-02-05 12:27:31 +11001571 host = cleanhostname(host);
1572 if (!*host) {
1573 fprintf(stderr, "Missing hostname\n");
Damien Miller33804262001-02-04 23:20:18 +11001574 usage();
1575 }
Damien Millerd14ee1e2002-02-05 12:27:31 +11001576
Damien Millerd14ee1e2002-02-05 12:27:31 +11001577 addargs(&args, "-oProtocol %d", sshver);
1578
1579 /* no subsystem if the server-spec contains a '/' */
1580 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1581 addargs(&args, "-s");
1582
1583 addargs(&args, "%s", host);
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001584 addargs(&args, "%s", (sftp_server != NULL ?
Damien Millerd14ee1e2002-02-05 12:27:31 +11001585 sftp_server : "sftp"));
Damien Millerd14ee1e2002-02-05 12:27:31 +11001586
Damien Miller44f75c12004-01-21 10:58:47 +11001587 if (!batchmode)
1588 fprintf(stderr, "Connecting to %s...\n", host);
Damien Millercc685c12003-06-04 22:51:38 +10001589 connect_to_server(ssh_program, args.list, &in, &out);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001590 } else {
1591 args.list = NULL;
1592 addargs(&args, "sftp-server");
1593
Damien Miller44f75c12004-01-21 10:58:47 +11001594 if (!batchmode)
1595 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
Damien Millercc685c12003-06-04 22:51:38 +10001596 connect_to_server(sftp_direct, args.list, &in, &out);
Damien Miller33804262001-02-04 23:20:18 +11001597 }
Damien Miller3eec6b72006-01-31 21:49:27 +11001598 freeargs(&args);
Damien Miller33804262001-02-04 23:20:18 +11001599
Damien Miller956f3fb2003-01-10 21:40:00 +11001600 err = interactive_loop(in, out, file1, file2);
Damien Miller33804262001-02-04 23:20:18 +11001601
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001602#if !defined(USE_PIPES)
Damien Miller37294fb2005-07-17 17:18:49 +10001603 shutdown(in, SHUT_RDWR);
1604 shutdown(out, SHUT_RDWR);
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001605#endif
1606
Damien Miller33804262001-02-04 23:20:18 +11001607 close(in);
1608 close(out);
Damien Miller44f75c12004-01-21 10:58:47 +11001609 if (batchmode)
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001610 fclose(infile);
Damien Miller33804262001-02-04 23:20:18 +11001611
Ben Lindstrom47fd8112002-04-02 20:48:19 +00001612 while (waitpid(sshpid, NULL, 0) == -1)
1613 if (errno != EINTR)
1614 fatal("Couldn't wait for ssh process: %s",
1615 strerror(errno));
Damien Miller33804262001-02-04 23:20:18 +11001616
Damien Miller956f3fb2003-01-10 21:40:00 +11001617 exit(err == 0 ? 0 : 1);
Damien Miller33804262001-02-04 23:20:18 +11001618}