blob: 82ef58019497479352dfefd7e2009aef13471d51 [file] [log] [blame]
Damien Millera7a73ee2006-08-05 11:37:59 +10001/* $OpenBSD: sftp.c,v 1.90 2006/08/01 23:22:47 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 Miller8dbffe72006-08-05 11:02:17 +100025#include <sys/param.h>
Damien Millere3b60b52006-07-10 21:08:03 +100026#include <sys/socket.h>
Damien Miller9cf6d072006-03-15 11:29:24 +110027#include <sys/wait.h>
Darren Tucker2d963d82004-11-07 20:04:10 +110028
Darren Tucker39972492006-07-12 22:22:46 +100029#include <errno.h>
30
Damien Miller03e20032006-03-15 11:16:59 +110031#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110032# include <paths.h>
Damien Miller03e20032006-03-15 11:16:59 +110033#endif
Darren Tucker2d963d82004-11-07 20:04:10 +110034#ifdef USE_LIBEDIT
35#include <histedit.h>
36#else
37typedef void EditLine;
38#endif
Damien Miller6ff3cad2006-03-15 11:52:09 +110039#include <signal.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100040#include <stdlib.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100041#include <stdio.h>
Damien Millere3476ed2006-07-24 14:13:33 +100042#include <string.h>
Damien Millere6b3b612006-07-24 14:01:23 +100043#include <unistd.h>
Damien Miller33804262001-02-04 23:20:18 +110044
Damien Miller33804262001-02-04 23:20:18 +110045#include "xmalloc.h"
46#include "log.h"
47#include "pathnames.h"
Ben Lindstrom4529b702001-05-03 23:39:53 +000048#include "misc.h"
Damien Miller33804262001-02-04 23:20:18 +110049
50#include "sftp.h"
51#include "sftp-common.h"
52#include "sftp-client.h"
Damien Millerd7d46bb2004-02-18 14:11:13 +110053
Damien Miller20e1fab2004-02-18 14:30:55 +110054/* File to read commands from */
55FILE* infile;
56
57/* Are we in batchfile mode? */
58int batchmode = 0;
59
60/* Size of buffer used when copying files */
61size_t copy_buffer_len = 32768;
62
63/* Number of concurrent outstanding requests */
64size_t num_requests = 16;
65
66/* PID of ssh transport process */
67static pid_t sshpid = -1;
68
69/* This is set to 0 if the progressmeter is not desired. */
Damien Millerc0f27d82004-03-08 23:12:19 +110070int showprogress = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +110071
Darren Tuckercdf547a2004-05-24 10:12:19 +100072/* SIGINT received during command processing */
73volatile sig_atomic_t interrupted = 0;
74
Darren Tuckerb9123452004-06-22 13:06:45 +100075/* I wish qsort() took a separate ctx for the comparison function...*/
76int sort_flag;
77
Damien Miller20e1fab2004-02-18 14:30:55 +110078int remote_glob(struct sftp_conn *, const char *, int,
79 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
Damien Miller33804262001-02-04 23:20:18 +110080
Kevin Steves12888d12001-03-05 19:50:57 +000081extern char *__progname;
Kevin Steves12888d12001-03-05 19:50:57 +000082
Damien Miller20e1fab2004-02-18 14:30:55 +110083/* Separators for interactive commands */
84#define WHITESPACE " \t\r\n"
Damien Millerd7686fd2001-02-10 00:40:03 +110085
Darren Tuckerb9123452004-06-22 13:06:45 +100086/* ls flags */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100087#define LS_LONG_VIEW 0x01 /* Full view ala ls -l */
88#define LS_SHORT_VIEW 0x02 /* Single row view ala ls -1 */
89#define LS_NUMERIC_VIEW 0x04 /* Long view with numeric uid/gid */
90#define LS_NAME_SORT 0x08 /* Sort by name (default) */
91#define LS_TIME_SORT 0x10 /* Sort by mtime */
92#define LS_SIZE_SORT 0x20 /* Sort by file size */
93#define LS_REVERSE_SORT 0x40 /* Reverse sort order */
Darren Tucker9a526452004-06-22 13:09:55 +100094#define LS_SHOW_ALL 0x80 /* Don't skip filenames starting with '.' */
Darren Tuckerb9123452004-06-22 13:06:45 +100095
Darren Tuckera4e9ffa2004-06-22 13:07:58 +100096#define VIEW_FLAGS (LS_LONG_VIEW|LS_SHORT_VIEW|LS_NUMERIC_VIEW)
97#define SORT_FLAGS (LS_NAME_SORT|LS_TIME_SORT|LS_SIZE_SORT)
Damien Miller20e1fab2004-02-18 14:30:55 +110098
99/* Commands for interactive mode */
100#define I_CHDIR 1
101#define I_CHGRP 2
102#define I_CHMOD 3
103#define I_CHOWN 4
104#define I_GET 5
105#define I_HELP 6
106#define I_LCHDIR 7
107#define I_LLS 8
108#define I_LMKDIR 9
109#define I_LPWD 10
110#define I_LS 11
111#define I_LUMASK 12
112#define I_MKDIR 13
113#define I_PUT 14
114#define I_PWD 15
115#define I_QUIT 16
116#define I_RENAME 17
117#define I_RM 18
118#define I_RMDIR 19
119#define I_SHELL 20
120#define I_SYMLINK 21
121#define I_VERSION 22
122#define I_PROGRESS 23
123
124struct CMD {
125 const char *c;
126 const int n;
127};
128
129static const struct CMD cmds[] = {
130 { "bye", I_QUIT },
131 { "cd", I_CHDIR },
132 { "chdir", I_CHDIR },
133 { "chgrp", I_CHGRP },
134 { "chmod", I_CHMOD },
135 { "chown", I_CHOWN },
136 { "dir", I_LS },
137 { "exit", I_QUIT },
138 { "get", I_GET },
139 { "mget", I_GET },
140 { "help", I_HELP },
141 { "lcd", I_LCHDIR },
142 { "lchdir", I_LCHDIR },
143 { "lls", I_LLS },
144 { "lmkdir", I_LMKDIR },
145 { "ln", I_SYMLINK },
146 { "lpwd", I_LPWD },
147 { "ls", I_LS },
148 { "lumask", I_LUMASK },
149 { "mkdir", I_MKDIR },
150 { "progress", I_PROGRESS },
151 { "put", I_PUT },
152 { "mput", I_PUT },
153 { "pwd", I_PWD },
154 { "quit", I_QUIT },
155 { "rename", I_RENAME },
156 { "rm", I_RM },
157 { "rmdir", I_RMDIR },
158 { "symlink", I_SYMLINK },
159 { "version", I_VERSION },
160 { "!", I_SHELL },
161 { "?", I_HELP },
162 { NULL, -1}
163};
164
165int interactive_loop(int fd_in, int fd_out, char *file1, char *file2);
166
167static void
Darren Tuckercdf547a2004-05-24 10:12:19 +1000168killchild(int signo)
169{
Darren Tuckerba66df82005-01-24 21:57:40 +1100170 if (sshpid > 1) {
Darren Tuckercdf547a2004-05-24 10:12:19 +1000171 kill(sshpid, SIGTERM);
Darren Tuckerba66df82005-01-24 21:57:40 +1100172 waitpid(sshpid, NULL, 0);
173 }
Darren Tuckercdf547a2004-05-24 10:12:19 +1000174
175 _exit(1);
176}
177
178static void
179cmd_interrupt(int signo)
180{
181 const char msg[] = "\rInterrupt \n";
Darren Tuckere2f189a2004-12-06 22:45:53 +1100182 int olderrno = errno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000183
184 write(STDERR_FILENO, msg, sizeof(msg) - 1);
185 interrupted = 1;
Darren Tuckere2f189a2004-12-06 22:45:53 +1100186 errno = olderrno;
Darren Tuckercdf547a2004-05-24 10:12:19 +1000187}
188
189static void
Damien Miller20e1fab2004-02-18 14:30:55 +1100190help(void)
191{
192 printf("Available commands:\n");
193 printf("cd path Change remote directory to 'path'\n");
194 printf("lcd path Change local directory to 'path'\n");
195 printf("chgrp grp path Change group of file 'path' to 'grp'\n");
196 printf("chmod mode path Change permissions of file 'path' to 'mode'\n");
197 printf("chown own path Change owner of file 'path' to 'own'\n");
198 printf("help Display this help text\n");
199 printf("get remote-path [local-path] Download file\n");
200 printf("lls [ls-options [path]] Display local directory listing\n");
201 printf("ln oldpath newpath Symlink remote file\n");
202 printf("lmkdir path Create local directory\n");
203 printf("lpwd Print local working directory\n");
204 printf("ls [path] Display remote directory listing\n");
205 printf("lumask umask Set local umask to 'umask'\n");
206 printf("mkdir path Create remote directory\n");
207 printf("progress Toggle display of progress meter\n");
208 printf("put local-path [remote-path] Upload file\n");
209 printf("pwd Display remote working directory\n");
210 printf("exit Quit sftp\n");
211 printf("quit Quit sftp\n");
212 printf("rename oldpath newpath Rename remote file\n");
213 printf("rmdir path Remove remote directory\n");
214 printf("rm path Delete remote file\n");
215 printf("symlink oldpath newpath Symlink remote file\n");
216 printf("version Show SFTP version\n");
217 printf("!command Execute 'command' in local shell\n");
218 printf("! Escape to local shell\n");
219 printf("? Synonym for help\n");
220}
221
222static void
223local_do_shell(const char *args)
224{
225 int status;
226 char *shell;
227 pid_t pid;
228
229 if (!*args)
230 args = NULL;
231
232 if ((shell = getenv("SHELL")) == NULL)
233 shell = _PATH_BSHELL;
234
235 if ((pid = fork()) == -1)
236 fatal("Couldn't fork: %s", strerror(errno));
237
238 if (pid == 0) {
239 /* XXX: child has pipe fds to ssh subproc open - issue? */
240 if (args) {
241 debug3("Executing %s -c \"%s\"", shell, args);
242 execl(shell, shell, "-c", args, (char *)NULL);
243 } else {
244 debug3("Executing %s", shell);
245 execl(shell, shell, (char *)NULL);
246 }
247 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
248 strerror(errno));
249 _exit(1);
250 }
251 while (waitpid(pid, &status, 0) == -1)
252 if (errno != EINTR)
253 fatal("Couldn't wait for child: %s", strerror(errno));
254 if (!WIFEXITED(status))
Damien Miller55b04f12006-03-26 14:23:17 +1100255 error("Shell exited abnormally");
Damien Miller20e1fab2004-02-18 14:30:55 +1100256 else if (WEXITSTATUS(status))
257 error("Shell exited with status %d", WEXITSTATUS(status));
258}
259
260static void
261local_do_ls(const char *args)
262{
263 if (!args || !*args)
264 local_do_shell(_PATH_LS);
265 else {
266 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
267 char *buf = xmalloc(len);
268
269 /* XXX: quoting - rip quoting code from ftp? */
270 snprintf(buf, len, _PATH_LS " %s", args);
271 local_do_shell(buf);
272 xfree(buf);
273 }
274}
275
276/* Strip one path (usually the pwd) from the start of another */
277static char *
278path_strip(char *path, char *strip)
279{
280 size_t len;
281
282 if (strip == NULL)
283 return (xstrdup(path));
284
285 len = strlen(strip);
Darren Tuckere2f189a2004-12-06 22:45:53 +1100286 if (strncmp(path, strip, len) == 0) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100287 if (strip[len - 1] != '/' && path[len] == '/')
288 len++;
289 return (xstrdup(path + len));
290 }
291
292 return (xstrdup(path));
293}
294
295static char *
296path_append(char *p1, char *p2)
297{
298 char *ret;
299 int len = strlen(p1) + strlen(p2) + 2;
300
301 ret = xmalloc(len);
302 strlcpy(ret, p1, len);
303 if (p1[strlen(p1) - 1] != '/')
304 strlcat(ret, "/", len);
305 strlcat(ret, p2, len);
306
307 return(ret);
308}
309
310static char *
311make_absolute(char *p, char *pwd)
312{
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000313 char *abs_str;
Damien Miller20e1fab2004-02-18 14:30:55 +1100314
315 /* Derelativise */
316 if (p && p[0] != '/') {
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000317 abs_str = path_append(pwd, p);
Damien Miller20e1fab2004-02-18 14:30:55 +1100318 xfree(p);
Darren Tucker3f9fdc72004-06-22 12:56:01 +1000319 return(abs_str);
Damien Miller20e1fab2004-02-18 14:30:55 +1100320 } else
321 return(p);
322}
323
324static int
325infer_path(const char *p, char **ifp)
326{
327 char *cp;
328
329 cp = strrchr(p, '/');
330 if (cp == NULL) {
331 *ifp = xstrdup(p);
332 return(0);
333 }
334
335 if (!cp[1]) {
336 error("Invalid path");
337 return(-1);
338 }
339
340 *ifp = xstrdup(cp + 1);
341 return(0);
342}
343
344static int
345parse_getput_flags(const char **cpp, int *pflag)
346{
347 const char *cp = *cpp;
348
349 /* Check for flags */
350 if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
351 switch (cp[1]) {
352 case 'p':
353 case 'P':
354 *pflag = 1;
355 break;
356 default:
357 error("Invalid flag -%c", cp[1]);
358 return(-1);
359 }
360 cp += 2;
361 *cpp = cp + strspn(cp, WHITESPACE);
362 }
363
364 return(0);
365}
366
367static int
368parse_ls_flags(const char **cpp, int *lflag)
369{
370 const char *cp = *cpp;
371
Darren Tuckerb9123452004-06-22 13:06:45 +1000372 /* Defaults */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000373 *lflag = LS_NAME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000374
Damien Miller20e1fab2004-02-18 14:30:55 +1100375 /* Check for flags */
376 if (cp++[0] == '-') {
Darren Tucker47eede72005-03-14 23:08:12 +1100377 for (; strchr(WHITESPACE, *cp) == NULL; cp++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100378 switch (*cp) {
379 case 'l':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000380 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000381 *lflag |= LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100382 break;
383 case '1':
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000384 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000385 *lflag |= LS_SHORT_VIEW;
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000386 break;
387 case 'n':
388 *lflag &= ~VIEW_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000389 *lflag |= LS_NUMERIC_VIEW|LS_LONG_VIEW;
Damien Miller20e1fab2004-02-18 14:30:55 +1100390 break;
Darren Tuckerb9123452004-06-22 13:06:45 +1000391 case 'S':
392 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000393 *lflag |= LS_SIZE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000394 break;
395 case 't':
396 *lflag &= ~SORT_FLAGS;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000397 *lflag |= LS_TIME_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000398 break;
399 case 'r':
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000400 *lflag |= LS_REVERSE_SORT;
Darren Tuckerb9123452004-06-22 13:06:45 +1000401 break;
402 case 'f':
403 *lflag &= ~SORT_FLAGS;
404 break;
Darren Tucker9a526452004-06-22 13:09:55 +1000405 case 'a':
406 *lflag |= LS_SHOW_ALL;
407 break;
Damien Miller20e1fab2004-02-18 14:30:55 +1100408 default:
409 error("Invalid flag -%c", *cp);
410 return(-1);
411 }
412 }
413 *cpp = cp + strspn(cp, WHITESPACE);
414 }
415
416 return(0);
417}
418
419static int
420get_pathname(const char **cpp, char **path)
421{
422 const char *cp = *cpp, *end;
423 char quot;
Damien Millereccb9de2005-06-17 12:59:34 +1000424 u_int i, j;
Damien Miller20e1fab2004-02-18 14:30:55 +1100425
426 cp += strspn(cp, WHITESPACE);
427 if (!*cp) {
428 *cpp = cp;
429 *path = NULL;
430 return (0);
431 }
432
433 *path = xmalloc(strlen(cp) + 1);
434
435 /* Check for quoted filenames */
436 if (*cp == '\"' || *cp == '\'') {
437 quot = *cp++;
438
439 /* Search for terminating quote, unescape some chars */
440 for (i = j = 0; i <= strlen(cp); i++) {
441 if (cp[i] == quot) { /* Found quote */
442 i++;
443 (*path)[j] = '\0';
444 break;
445 }
446 if (cp[i] == '\0') { /* End of string */
447 error("Unterminated quote");
448 goto fail;
449 }
450 if (cp[i] == '\\') { /* Escaped characters */
451 i++;
452 if (cp[i] != '\'' && cp[i] != '\"' &&
453 cp[i] != '\\') {
Damien Miller96d6d7d2004-06-26 09:21:06 +1000454 error("Bad escaped character '\\%c'",
Damien Miller20e1fab2004-02-18 14:30:55 +1100455 cp[i]);
456 goto fail;
457 }
458 }
459 (*path)[j++] = cp[i];
460 }
461
462 if (j == 0) {
463 error("Empty quotes");
464 goto fail;
465 }
466 *cpp = cp + i + strspn(cp + i, WHITESPACE);
467 } else {
468 /* Read to end of filename */
469 end = strpbrk(cp, WHITESPACE);
470 if (end == NULL)
471 end = strchr(cp, '\0');
472 *cpp = end + strspn(end, WHITESPACE);
473
474 memcpy(*path, cp, end - cp);
475 (*path)[end - cp] = '\0';
476 }
477 return (0);
478
479 fail:
480 xfree(*path);
481 *path = NULL;
482 return (-1);
483}
484
485static int
486is_dir(char *path)
487{
488 struct stat sb;
489
490 /* XXX: report errors? */
491 if (stat(path, &sb) == -1)
492 return(0);
493
494 return(sb.st_mode & S_IFDIR);
495}
496
497static int
498is_reg(char *path)
499{
500 struct stat sb;
501
502 if (stat(path, &sb) == -1)
503 fatal("stat %s: %s", path, strerror(errno));
504
505 return(S_ISREG(sb.st_mode));
506}
507
508static int
509remote_is_dir(struct sftp_conn *conn, char *path)
510{
511 Attrib *a;
512
513 /* XXX: report errors? */
514 if ((a = do_stat(conn, path, 1)) == NULL)
515 return(0);
516 if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
517 return(0);
518 return(a->perm & S_IFDIR);
519}
520
521static int
522process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
523{
524 char *abs_src = NULL;
525 char *abs_dst = NULL;
526 char *tmp;
527 glob_t g;
528 int err = 0;
529 int i;
530
531 abs_src = xstrdup(src);
532 abs_src = make_absolute(abs_src, pwd);
533
534 memset(&g, 0, sizeof(g));
535 debug3("Looking up %s", abs_src);
536 if (remote_glob(conn, abs_src, 0, NULL, &g)) {
537 error("File \"%s\" not found.", abs_src);
538 err = -1;
539 goto out;
540 }
541
542 /* If multiple matches, dst must be a directory or unspecified */
543 if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
544 error("Multiple files match, but \"%s\" is not a directory",
545 dst);
546 err = -1;
547 goto out;
548 }
549
Darren Tuckercdf547a2004-05-24 10:12:19 +1000550 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100551 if (infer_path(g.gl_pathv[i], &tmp)) {
552 err = -1;
553 goto out;
554 }
555
556 if (g.gl_matchc == 1 && dst) {
557 /* If directory specified, append filename */
Damien Miller40b59852006-06-13 13:00:25 +1000558 xfree(tmp);
Damien Miller20e1fab2004-02-18 14:30:55 +1100559 if (is_dir(dst)) {
560 if (infer_path(g.gl_pathv[0], &tmp)) {
561 err = 1;
562 goto out;
563 }
564 abs_dst = path_append(dst, tmp);
565 xfree(tmp);
566 } else
567 abs_dst = xstrdup(dst);
568 } else if (dst) {
569 abs_dst = path_append(dst, tmp);
570 xfree(tmp);
571 } else
572 abs_dst = tmp;
573
574 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
575 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
576 err = -1;
577 xfree(abs_dst);
578 abs_dst = NULL;
579 }
580
581out:
582 xfree(abs_src);
Damien Miller20e1fab2004-02-18 14:30:55 +1100583 globfree(&g);
584 return(err);
585}
586
587static int
588process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
589{
590 char *tmp_dst = NULL;
591 char *abs_dst = NULL;
592 char *tmp;
593 glob_t g;
594 int err = 0;
595 int i;
596
597 if (dst) {
598 tmp_dst = xstrdup(dst);
599 tmp_dst = make_absolute(tmp_dst, pwd);
600 }
601
602 memset(&g, 0, sizeof(g));
603 debug3("Looking up %s", src);
604 if (glob(src, 0, NULL, &g)) {
605 error("File \"%s\" not found.", src);
606 err = -1;
607 goto out;
608 }
609
610 /* If multiple matches, dst may be directory or unspecified */
611 if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
612 error("Multiple files match, but \"%s\" is not a directory",
613 tmp_dst);
614 err = -1;
615 goto out;
616 }
617
Darren Tuckercdf547a2004-05-24 10:12:19 +1000618 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100619 if (!is_reg(g.gl_pathv[i])) {
620 error("skipping non-regular file %s",
621 g.gl_pathv[i]);
622 continue;
623 }
624 if (infer_path(g.gl_pathv[i], &tmp)) {
625 err = -1;
626 goto out;
627 }
628
629 if (g.gl_matchc == 1 && tmp_dst) {
630 /* If directory specified, append filename */
631 if (remote_is_dir(conn, tmp_dst)) {
632 if (infer_path(g.gl_pathv[0], &tmp)) {
633 err = 1;
634 goto out;
635 }
636 abs_dst = path_append(tmp_dst, tmp);
637 xfree(tmp);
638 } else
639 abs_dst = xstrdup(tmp_dst);
640
641 } else if (tmp_dst) {
642 abs_dst = path_append(tmp_dst, tmp);
643 xfree(tmp);
644 } else
645 abs_dst = make_absolute(tmp, pwd);
646
647 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
648 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
649 err = -1;
650 }
651
652out:
653 if (abs_dst)
654 xfree(abs_dst);
655 if (tmp_dst)
656 xfree(tmp_dst);
657 globfree(&g);
658 return(err);
659}
660
661static int
662sdirent_comp(const void *aa, const void *bb)
663{
664 SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
665 SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000666 int rmul = sort_flag & LS_REVERSE_SORT ? -1 : 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100667
Darren Tuckerb9123452004-06-22 13:06:45 +1000668#define NCMP(a,b) (a == b ? 0 : (a < b ? 1 : -1))
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000669 if (sort_flag & LS_NAME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000670 return (rmul * strcmp(a->filename, b->filename));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000671 else if (sort_flag & LS_TIME_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000672 return (rmul * NCMP(a->a.mtime, b->a.mtime));
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000673 else if (sort_flag & LS_SIZE_SORT)
Darren Tuckerb9123452004-06-22 13:06:45 +1000674 return (rmul * NCMP(a->a.size, b->a.size));
675
676 fatal("Unknown ls sort type");
Damien Miller20e1fab2004-02-18 14:30:55 +1100677}
678
679/* sftp ls.1 replacement for directories */
680static int
681do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
682{
Damien Millereccb9de2005-06-17 12:59:34 +1000683 int n;
684 u_int c = 1, colspace = 0, columns = 1;
Damien Miller20e1fab2004-02-18 14:30:55 +1100685 SFTP_DIRENT **d;
686
687 if ((n = do_readdir(conn, path, &d)) != 0)
688 return (n);
689
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000690 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000691 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100692 struct winsize ws;
693 char *tmp;
694
695 /* Count entries for sort and find longest filename */
Darren Tucker9a526452004-06-22 13:09:55 +1000696 for (n = 0; d[n] != NULL; n++) {
697 if (d[n]->filename[0] != '.' || (lflag & LS_SHOW_ALL))
698 m = MAX(m, strlen(d[n]->filename));
699 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100700
701 /* Add any subpath that also needs to be counted */
702 tmp = path_strip(path, strip_path);
703 m += strlen(tmp);
704 xfree(tmp);
705
706 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
707 width = ws.ws_col;
708
709 columns = width / (m + 2);
710 columns = MAX(columns, 1);
711 colspace = width / columns;
712 colspace = MIN(colspace, width);
713 }
714
Darren Tuckerb9123452004-06-22 13:06:45 +1000715 if (lflag & SORT_FLAGS) {
Damien Miller653b93b2005-11-05 15:15:23 +1100716 for (n = 0; d[n] != NULL; n++)
717 ; /* count entries */
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000718 sort_flag = lflag & (SORT_FLAGS|LS_REVERSE_SORT);
Darren Tuckerb9123452004-06-22 13:06:45 +1000719 qsort(d, n, sizeof(*d), sdirent_comp);
720 }
Damien Miller20e1fab2004-02-18 14:30:55 +1100721
Darren Tuckercdf547a2004-05-24 10:12:19 +1000722 for (n = 0; d[n] != NULL && !interrupted; n++) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100723 char *tmp, *fname;
724
Darren Tucker9a526452004-06-22 13:09:55 +1000725 if (d[n]->filename[0] == '.' && !(lflag & LS_SHOW_ALL))
726 continue;
727
Damien Miller20e1fab2004-02-18 14:30:55 +1100728 tmp = path_append(path, d[n]->filename);
729 fname = path_strip(tmp, strip_path);
730 xfree(tmp);
731
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000732 if (lflag & LS_LONG_VIEW) {
733 if (lflag & LS_NUMERIC_VIEW) {
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000734 char *lname;
735 struct stat sb;
Damien Miller20e1fab2004-02-18 14:30:55 +1100736
Darren Tuckerb215c5d2004-06-22 12:30:53 +1000737 memset(&sb, 0, sizeof(sb));
738 attrib_to_stat(&d[n]->a, &sb);
739 lname = ls_file(fname, &sb, 1);
740 printf("%s\n", lname);
741 xfree(lname);
742 } else
743 printf("%s\n", d[n]->longname);
Damien Miller20e1fab2004-02-18 14:30:55 +1100744 } else {
745 printf("%-*s", colspace, fname);
746 if (c >= columns) {
747 printf("\n");
748 c = 1;
749 } else
750 c++;
751 }
752
753 xfree(fname);
754 }
755
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000756 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100757 printf("\n");
758
759 free_sftp_dirents(d);
760 return (0);
761}
762
763/* sftp ls.1 replacement which handles path globs */
764static int
765do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
766 int lflag)
767{
768 glob_t g;
Damien Millereccb9de2005-06-17 12:59:34 +1000769 u_int i, c = 1, colspace = 0, columns = 1;
Darren Tucker596dcfa2004-12-11 13:37:22 +1100770 Attrib *a = NULL;
Damien Miller20e1fab2004-02-18 14:30:55 +1100771
772 memset(&g, 0, sizeof(g));
773
774 if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
Darren Tucker596dcfa2004-12-11 13:37:22 +1100775 NULL, &g) || (g.gl_pathc && !g.gl_matchc)) {
776 if (g.gl_pathc)
777 globfree(&g);
Damien Miller20e1fab2004-02-18 14:30:55 +1100778 error("Can't ls: \"%s\" not found", path);
779 return (-1);
780 }
781
Darren Tuckercdf547a2004-05-24 10:12:19 +1000782 if (interrupted)
783 goto out;
784
Damien Miller20e1fab2004-02-18 14:30:55 +1100785 /*
Darren Tucker596dcfa2004-12-11 13:37:22 +1100786 * If the glob returns a single match and it is a directory,
787 * then just list its contents.
Damien Miller20e1fab2004-02-18 14:30:55 +1100788 */
Darren Tucker596dcfa2004-12-11 13:37:22 +1100789 if (g.gl_matchc == 1) {
790 if ((a = do_lstat(conn, g.gl_pathv[0], 1)) == NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100791 globfree(&g);
792 return (-1);
793 }
794 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
795 S_ISDIR(a->perm)) {
Darren Tucker596dcfa2004-12-11 13:37:22 +1100796 int err;
797
798 err = do_ls_dir(conn, g.gl_pathv[0], strip_path, lflag);
Damien Miller20e1fab2004-02-18 14:30:55 +1100799 globfree(&g);
Darren Tucker596dcfa2004-12-11 13:37:22 +1100800 return (err);
Damien Miller20e1fab2004-02-18 14:30:55 +1100801 }
802 }
803
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000804 if (!(lflag & LS_SHORT_VIEW)) {
Damien Millereccb9de2005-06-17 12:59:34 +1000805 u_int m = 0, width = 80;
Damien Miller20e1fab2004-02-18 14:30:55 +1100806 struct winsize ws;
807
808 /* Count entries for sort and find longest filename */
809 for (i = 0; g.gl_pathv[i]; i++)
810 m = MAX(m, strlen(g.gl_pathv[i]));
811
812 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1)
813 width = ws.ws_col;
814
815 columns = width / (m + 2);
816 columns = MAX(columns, 1);
817 colspace = width / columns;
818 }
819
Darren Tucker596dcfa2004-12-11 13:37:22 +1100820 for (i = 0; g.gl_pathv[i] && !interrupted; i++, a = NULL) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100821 char *fname;
822
823 fname = path_strip(g.gl_pathv[i], strip_path);
824
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000825 if (lflag & LS_LONG_VIEW) {
Damien Miller20e1fab2004-02-18 14:30:55 +1100826 char *lname;
827 struct stat sb;
828
829 /*
830 * XXX: this is slow - 1 roundtrip per path
831 * A solution to this is to fork glob() and
832 * build a sftp specific version which keeps the
833 * attribs (which currently get thrown away)
834 * that the server returns as well as the filenames.
835 */
836 memset(&sb, 0, sizeof(sb));
Darren Tucker596dcfa2004-12-11 13:37:22 +1100837 if (a == NULL)
838 a = do_lstat(conn, g.gl_pathv[i], 1);
Damien Miller20e1fab2004-02-18 14:30:55 +1100839 if (a != NULL)
840 attrib_to_stat(a, &sb);
841 lname = ls_file(fname, &sb, 1);
842 printf("%s\n", lname);
843 xfree(lname);
844 } else {
845 printf("%-*s", colspace, fname);
846 if (c >= columns) {
847 printf("\n");
848 c = 1;
849 } else
850 c++;
851 }
852 xfree(fname);
853 }
854
Darren Tuckera4e9ffa2004-06-22 13:07:58 +1000855 if (!(lflag & LS_LONG_VIEW) && (c != 1))
Damien Miller20e1fab2004-02-18 14:30:55 +1100856 printf("\n");
857
Darren Tuckercdf547a2004-05-24 10:12:19 +1000858 out:
Damien Miller20e1fab2004-02-18 14:30:55 +1100859 if (g.gl_pathc)
860 globfree(&g);
861
862 return (0);
863}
864
865static int
866parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
867 unsigned long *n_arg, char **path1, char **path2)
868{
869 const char *cmd, *cp = *cpp;
870 char *cp2;
871 int base = 0;
872 long l;
873 int i, cmdnum;
874
875 /* Skip leading whitespace */
876 cp = cp + strspn(cp, WHITESPACE);
877
878 /* Ignore blank lines and lines which begin with comment '#' char */
879 if (*cp == '\0' || *cp == '#')
880 return (0);
881
882 /* Check for leading '-' (disable error processing) */
883 *iflag = 0;
884 if (*cp == '-') {
885 *iflag = 1;
886 cp++;
887 }
888
889 /* Figure out which command we have */
890 for (i = 0; cmds[i].c; i++) {
891 int cmdlen = strlen(cmds[i].c);
892
893 /* Check for command followed by whitespace */
894 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
895 strchr(WHITESPACE, cp[cmdlen])) {
896 cp += cmdlen;
897 cp = cp + strspn(cp, WHITESPACE);
898 break;
899 }
900 }
901 cmdnum = cmds[i].n;
902 cmd = cmds[i].c;
903
904 /* Special case */
905 if (*cp == '!') {
906 cp++;
907 cmdnum = I_SHELL;
908 } else if (cmdnum == -1) {
909 error("Invalid command.");
910 return (-1);
911 }
912
913 /* Get arguments and parse flags */
914 *lflag = *pflag = *n_arg = 0;
915 *path1 = *path2 = NULL;
916 switch (cmdnum) {
917 case I_GET:
918 case I_PUT:
919 if (parse_getput_flags(&cp, pflag))
920 return(-1);
921 /* Get first pathname (mandatory) */
922 if (get_pathname(&cp, path1))
923 return(-1);
924 if (*path1 == NULL) {
925 error("You must specify at least one path after a "
926 "%s command.", cmd);
927 return(-1);
928 }
929 /* Try to get second pathname (optional) */
930 if (get_pathname(&cp, path2))
931 return(-1);
932 break;
933 case I_RENAME:
934 case I_SYMLINK:
935 if (get_pathname(&cp, path1))
936 return(-1);
937 if (get_pathname(&cp, path2))
938 return(-1);
939 if (!*path1 || !*path2) {
940 error("You must specify two paths after a %s "
941 "command.", cmd);
942 return(-1);
943 }
944 break;
945 case I_RM:
946 case I_MKDIR:
947 case I_RMDIR:
948 case I_CHDIR:
949 case I_LCHDIR:
950 case I_LMKDIR:
951 /* Get pathname (mandatory) */
952 if (get_pathname(&cp, path1))
953 return(-1);
954 if (*path1 == NULL) {
955 error("You must specify a path after a %s command.",
956 cmd);
957 return(-1);
958 }
959 break;
960 case I_LS:
961 if (parse_ls_flags(&cp, lflag))
962 return(-1);
963 /* Path is optional */
964 if (get_pathname(&cp, path1))
965 return(-1);
966 break;
967 case I_LLS:
968 case I_SHELL:
969 /* Uses the rest of the line */
970 break;
971 case I_LUMASK:
972 base = 8;
973 case I_CHMOD:
974 base = 8;
975 case I_CHOWN:
976 case I_CHGRP:
977 /* Get numeric arg (mandatory) */
978 l = strtol(cp, &cp2, base);
979 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
980 errno == ERANGE) || l < 0) {
981 error("You must supply a numeric argument "
982 "to the %s command.", cmd);
983 return(-1);
984 }
985 cp = cp2;
986 *n_arg = l;
987 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
988 break;
989 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
990 error("You must supply a numeric argument "
991 "to the %s command.", cmd);
992 return(-1);
993 }
994 cp += strspn(cp, WHITESPACE);
995
996 /* Get pathname (mandatory) */
997 if (get_pathname(&cp, path1))
998 return(-1);
999 if (*path1 == NULL) {
1000 error("You must specify a path after a %s command.",
1001 cmd);
1002 return(-1);
1003 }
1004 break;
1005 case I_QUIT:
1006 case I_PWD:
1007 case I_LPWD:
1008 case I_HELP:
1009 case I_VERSION:
1010 case I_PROGRESS:
1011 break;
1012 default:
1013 fatal("Command not implemented");
1014 }
1015
1016 *cpp = cp;
1017 return(cmdnum);
1018}
1019
1020static int
1021parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
1022 int err_abort)
1023{
1024 char *path1, *path2, *tmp;
1025 int pflag, lflag, iflag, cmdnum, i;
1026 unsigned long n_arg;
1027 Attrib a, *aa;
1028 char path_buf[MAXPATHLEN];
1029 int err = 0;
1030 glob_t g;
1031
1032 path1 = path2 = NULL;
1033 cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
1034 &path1, &path2);
1035
1036 if (iflag != 0)
1037 err_abort = 0;
1038
1039 memset(&g, 0, sizeof(g));
1040
1041 /* Perform command */
1042 switch (cmdnum) {
1043 case 0:
1044 /* Blank line */
1045 break;
1046 case -1:
1047 /* Unrecognized command */
1048 err = -1;
1049 break;
1050 case I_GET:
1051 err = process_get(conn, path1, path2, *pwd, pflag);
1052 break;
1053 case I_PUT:
1054 err = process_put(conn, path1, path2, *pwd, pflag);
1055 break;
1056 case I_RENAME:
1057 path1 = make_absolute(path1, *pwd);
1058 path2 = make_absolute(path2, *pwd);
1059 err = do_rename(conn, path1, path2);
1060 break;
1061 case I_SYMLINK:
1062 path2 = make_absolute(path2, *pwd);
1063 err = do_symlink(conn, path1, path2);
1064 break;
1065 case I_RM:
1066 path1 = make_absolute(path1, *pwd);
1067 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001068 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001069 printf("Removing %s\n", g.gl_pathv[i]);
1070 err = do_rm(conn, g.gl_pathv[i]);
1071 if (err != 0 && err_abort)
1072 break;
1073 }
1074 break;
1075 case I_MKDIR:
1076 path1 = make_absolute(path1, *pwd);
1077 attrib_clear(&a);
1078 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1079 a.perm = 0777;
1080 err = do_mkdir(conn, path1, &a);
1081 break;
1082 case I_RMDIR:
1083 path1 = make_absolute(path1, *pwd);
1084 err = do_rmdir(conn, path1);
1085 break;
1086 case I_CHDIR:
1087 path1 = make_absolute(path1, *pwd);
1088 if ((tmp = do_realpath(conn, path1)) == NULL) {
1089 err = 1;
1090 break;
1091 }
1092 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
1093 xfree(tmp);
1094 err = 1;
1095 break;
1096 }
1097 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
1098 error("Can't change directory: Can't check target");
1099 xfree(tmp);
1100 err = 1;
1101 break;
1102 }
1103 if (!S_ISDIR(aa->perm)) {
1104 error("Can't change directory: \"%s\" is not "
1105 "a directory", tmp);
1106 xfree(tmp);
1107 err = 1;
1108 break;
1109 }
1110 xfree(*pwd);
1111 *pwd = tmp;
1112 break;
1113 case I_LS:
1114 if (!path1) {
1115 do_globbed_ls(conn, *pwd, *pwd, lflag);
1116 break;
1117 }
1118
1119 /* Strip pwd off beginning of non-absolute paths */
1120 tmp = NULL;
1121 if (*path1 != '/')
1122 tmp = *pwd;
1123
1124 path1 = make_absolute(path1, *pwd);
1125 err = do_globbed_ls(conn, path1, tmp, lflag);
1126 break;
1127 case I_LCHDIR:
1128 if (chdir(path1) == -1) {
1129 error("Couldn't change local directory to "
1130 "\"%s\": %s", path1, strerror(errno));
1131 err = 1;
1132 }
1133 break;
1134 case I_LMKDIR:
1135 if (mkdir(path1, 0777) == -1) {
1136 error("Couldn't create local directory "
1137 "\"%s\": %s", path1, strerror(errno));
1138 err = 1;
1139 }
1140 break;
1141 case I_LLS:
1142 local_do_ls(cmd);
1143 break;
1144 case I_SHELL:
1145 local_do_shell(cmd);
1146 break;
1147 case I_LUMASK:
1148 umask(n_arg);
1149 printf("Local umask: %03lo\n", n_arg);
1150 break;
1151 case I_CHMOD:
1152 path1 = make_absolute(path1, *pwd);
1153 attrib_clear(&a);
1154 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
1155 a.perm = n_arg;
1156 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001157 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001158 printf("Changing mode on %s\n", g.gl_pathv[i]);
1159 err = do_setstat(conn, g.gl_pathv[i], &a);
1160 if (err != 0 && err_abort)
1161 break;
1162 }
1163 break;
1164 case I_CHOWN:
1165 case I_CHGRP:
1166 path1 = make_absolute(path1, *pwd);
1167 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001168 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
Damien Miller20e1fab2004-02-18 14:30:55 +11001169 if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
1170 if (err != 0 && err_abort)
1171 break;
1172 else
1173 continue;
1174 }
1175 if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
1176 error("Can't get current ownership of "
1177 "remote file \"%s\"", g.gl_pathv[i]);
1178 if (err != 0 && err_abort)
1179 break;
1180 else
1181 continue;
1182 }
1183 aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
1184 if (cmdnum == I_CHOWN) {
1185 printf("Changing owner on %s\n", g.gl_pathv[i]);
1186 aa->uid = n_arg;
1187 } else {
1188 printf("Changing group on %s\n", g.gl_pathv[i]);
1189 aa->gid = n_arg;
1190 }
1191 err = do_setstat(conn, g.gl_pathv[i], aa);
1192 if (err != 0 && err_abort)
1193 break;
1194 }
1195 break;
1196 case I_PWD:
1197 printf("Remote working directory: %s\n", *pwd);
1198 break;
1199 case I_LPWD:
1200 if (!getcwd(path_buf, sizeof(path_buf))) {
1201 error("Couldn't get local cwd: %s", strerror(errno));
1202 err = -1;
1203 break;
1204 }
1205 printf("Local working directory: %s\n", path_buf);
1206 break;
1207 case I_QUIT:
1208 /* Processed below */
1209 break;
1210 case I_HELP:
1211 help();
1212 break;
1213 case I_VERSION:
1214 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1215 break;
1216 case I_PROGRESS:
1217 showprogress = !showprogress;
1218 if (showprogress)
1219 printf("Progress meter enabled\n");
1220 else
1221 printf("Progress meter disabled\n");
1222 break;
1223 default:
1224 fatal("%d is not implemented", cmdnum);
1225 }
1226
1227 if (g.gl_pathc)
1228 globfree(&g);
1229 if (path1)
1230 xfree(path1);
1231 if (path2)
1232 xfree(path2);
1233
1234 /* If an unignored error occurs in batch mode we should abort. */
1235 if (err_abort && err != 0)
1236 return (-1);
1237 else if (cmdnum == I_QUIT)
1238 return (1);
1239
1240 return (0);
1241}
1242
Darren Tucker2d963d82004-11-07 20:04:10 +11001243#ifdef USE_LIBEDIT
1244static char *
1245prompt(EditLine *el)
1246{
1247 return ("sftp> ");
1248}
1249#endif
1250
Damien Miller20e1fab2004-02-18 14:30:55 +11001251int
1252interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1253{
1254 char *pwd;
1255 char *dir = NULL;
1256 char cmd[2048];
1257 struct sftp_conn *conn;
Damien Miller0e2c1022005-08-12 22:16:22 +10001258 int err, interactive;
Darren Tucker2d963d82004-11-07 20:04:10 +11001259 EditLine *el = NULL;
1260#ifdef USE_LIBEDIT
1261 History *hl = NULL;
1262 HistEvent hev;
1263 extern char *__progname;
1264
1265 if (!batchmode && isatty(STDIN_FILENO)) {
1266 if ((el = el_init(__progname, stdin, stdout, stderr)) == NULL)
1267 fatal("Couldn't initialise editline");
1268 if ((hl = history_init()) == NULL)
1269 fatal("Couldn't initialise editline history");
1270 history(hl, &hev, H_SETSIZE, 100);
1271 el_set(el, EL_HIST, history, hl);
1272
1273 el_set(el, EL_PROMPT, prompt);
1274 el_set(el, EL_EDITOR, "emacs");
1275 el_set(el, EL_TERMINAL, NULL);
1276 el_set(el, EL_SIGNAL, 1);
1277 el_source(el, NULL);
1278 }
1279#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001280
1281 conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1282 if (conn == NULL)
1283 fatal("Couldn't initialise connection to server");
1284
1285 pwd = do_realpath(conn, ".");
1286 if (pwd == NULL)
1287 fatal("Need cwd");
1288
1289 if (file1 != NULL) {
1290 dir = xstrdup(file1);
1291 dir = make_absolute(dir, pwd);
1292
1293 if (remote_is_dir(conn, dir) && file2 == NULL) {
1294 printf("Changing to: %s\n", dir);
1295 snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001296 if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0) {
1297 xfree(dir);
1298 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001299 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001300 return (-1);
Darren Tuckercd516ef2004-12-06 22:43:43 +11001301 }
Damien Miller20e1fab2004-02-18 14:30:55 +11001302 } else {
1303 if (file2 == NULL)
1304 snprintf(cmd, sizeof cmd, "get %s", dir);
1305 else
1306 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1307 file2);
1308
1309 err = parse_dispatch_command(conn, cmd, &pwd, 1);
1310 xfree(dir);
1311 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001312 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001313 return (err);
1314 }
1315 xfree(dir);
1316 }
1317
Darren Tucker93e7e8f2005-08-23 08:06:55 +10001318#if defined(HAVE_SETVBUF) && !defined(BROKEN_SETVBUF)
Damien Miller20e1fab2004-02-18 14:30:55 +11001319 setvbuf(stdout, NULL, _IOLBF, 0);
1320 setvbuf(infile, NULL, _IOLBF, 0);
1321#else
Damien Miller37294fb2005-07-17 17:18:49 +10001322 setlinebuf(stdout);
1323 setlinebuf(infile);
Damien Miller20e1fab2004-02-18 14:30:55 +11001324#endif
1325
Damien Miller0e2c1022005-08-12 22:16:22 +10001326 interactive = !batchmode && isatty(STDIN_FILENO);
Damien Miller20e1fab2004-02-18 14:30:55 +11001327 err = 0;
1328 for (;;) {
1329 char *cp;
1330
Darren Tuckercdf547a2004-05-24 10:12:19 +10001331 signal(SIGINT, SIG_IGN);
1332
Darren Tucker2d963d82004-11-07 20:04:10 +11001333 if (el == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001334 if (interactive)
1335 printf("sftp> ");
Darren Tucker2d963d82004-11-07 20:04:10 +11001336 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
Damien Miller0e2c1022005-08-12 22:16:22 +10001337 if (interactive)
1338 printf("\n");
Darren Tucker2d963d82004-11-07 20:04:10 +11001339 break;
1340 }
Damien Miller0e2c1022005-08-12 22:16:22 +10001341 if (!interactive) { /* Echo command */
1342 printf("sftp> %s", cmd);
1343 if (strlen(cmd) > 0 &&
1344 cmd[strlen(cmd) - 1] != '\n')
1345 printf("\n");
1346 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001347 } else {
1348#ifdef USE_LIBEDIT
1349 const char *line;
1350 int count = 0;
Damien Miller20e1fab2004-02-18 14:30:55 +11001351
Damien Miller0e2c1022005-08-12 22:16:22 +10001352 if ((line = el_gets(el, &count)) == NULL || count <= 0) {
1353 printf("\n");
1354 break;
1355 }
Darren Tucker2d963d82004-11-07 20:04:10 +11001356 history(hl, &hev, H_ENTER, line);
1357 if (strlcpy(cmd, line, sizeof(cmd)) >= sizeof(cmd)) {
1358 fprintf(stderr, "Error: input line too long\n");
1359 continue;
1360 }
1361#endif /* USE_LIBEDIT */
Damien Miller20e1fab2004-02-18 14:30:55 +11001362 }
1363
Damien Miller20e1fab2004-02-18 14:30:55 +11001364 cp = strrchr(cmd, '\n');
1365 if (cp)
1366 *cp = '\0';
1367
Darren Tuckercdf547a2004-05-24 10:12:19 +10001368 /* Handle user interrupts gracefully during commands */
1369 interrupted = 0;
1370 signal(SIGINT, cmd_interrupt);
1371
Damien Miller20e1fab2004-02-18 14:30:55 +11001372 err = parse_dispatch_command(conn, cmd, &pwd, batchmode);
1373 if (err != 0)
1374 break;
1375 }
1376 xfree(pwd);
Damien Millere0b90a62006-03-26 13:51:44 +11001377 xfree(conn);
Damien Miller20e1fab2004-02-18 14:30:55 +11001378
Tim Rice027e8b12005-08-15 14:52:50 -07001379#ifdef USE_LIBEDIT
Damien Miller0e2c1022005-08-12 22:16:22 +10001380 if (el != NULL)
1381 el_end(el);
Tim Rice027e8b12005-08-15 14:52:50 -07001382#endif /* USE_LIBEDIT */
Damien Miller0e2c1022005-08-12 22:16:22 +10001383
Damien Miller20e1fab2004-02-18 14:30:55 +11001384 /* err == 1 signifies normal "quit" exit */
1385 return (err >= 0 ? 0 : -1);
1386}
Damien Miller62d57f62003-01-10 21:43:24 +11001387
Ben Lindstrombba81212001-06-25 05:01:22 +00001388static void
Damien Millercc685c12003-06-04 22:51:38 +10001389connect_to_server(char *path, char **args, int *in, int *out)
Damien Miller33804262001-02-04 23:20:18 +11001390{
1391 int c_in, c_out;
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001392
Damien Miller33804262001-02-04 23:20:18 +11001393#ifdef USE_PIPES
1394 int pin[2], pout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001395
Damien Miller33804262001-02-04 23:20:18 +11001396 if ((pipe(pin) == -1) || (pipe(pout) == -1))
1397 fatal("pipe: %s", strerror(errno));
1398 *in = pin[0];
1399 *out = pout[1];
1400 c_in = pout[0];
1401 c_out = pin[1];
1402#else /* USE_PIPES */
1403 int inout[2];
Ben Lindstromb1f483f2002-06-23 21:27:18 +00001404
Damien Miller33804262001-02-04 23:20:18 +11001405 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1)
1406 fatal("socketpair: %s", strerror(errno));
1407 *in = *out = inout[0];
1408 c_in = c_out = inout[1];
1409#endif /* USE_PIPES */
1410
Damien Millercc685c12003-06-04 22:51:38 +10001411 if ((sshpid = fork()) == -1)
Damien Miller33804262001-02-04 23:20:18 +11001412 fatal("fork: %s", strerror(errno));
Damien Millercc685c12003-06-04 22:51:38 +10001413 else if (sshpid == 0) {
Damien Miller33804262001-02-04 23:20:18 +11001414 if ((dup2(c_in, STDIN_FILENO) == -1) ||
1415 (dup2(c_out, STDOUT_FILENO) == -1)) {
1416 fprintf(stderr, "dup2: %s\n", strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001417 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001418 }
1419 close(*in);
1420 close(*out);
1421 close(c_in);
1422 close(c_out);
Darren Tuckercdf547a2004-05-24 10:12:19 +10001423
1424 /*
1425 * The underlying ssh is in the same process group, so we must
Darren Tuckerfc959702004-07-17 16:12:08 +10001426 * ignore SIGINT if we want to gracefully abort commands,
1427 * otherwise the signal will make it to the ssh process and
Darren Tuckercdf547a2004-05-24 10:12:19 +10001428 * kill it too
1429 */
1430 signal(SIGINT, SIG_IGN);
Darren Tuckerbd12f172004-06-18 16:23:43 +10001431 execvp(path, args);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001432 fprintf(stderr, "exec: %s: %s\n", path, strerror(errno));
Damien Miller350327c2004-06-15 10:24:13 +10001433 _exit(1);
Damien Miller33804262001-02-04 23:20:18 +11001434 }
1435
Damien Millercc685c12003-06-04 22:51:38 +10001436 signal(SIGTERM, killchild);
1437 signal(SIGINT, killchild);
1438 signal(SIGHUP, killchild);
Damien Miller33804262001-02-04 23:20:18 +11001439 close(c_in);
1440 close(c_out);
1441}
1442
Ben Lindstrombba81212001-06-25 05:01:22 +00001443static void
Damien Miller33804262001-02-04 23:20:18 +11001444usage(void)
1445{
Damien Miller025e01c2002-02-08 22:06:29 +11001446 extern char *__progname;
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001447
Ben Lindstrom1e243242001-09-18 05:38:44 +00001448 fprintf(stderr,
Darren Tucker1f203942003-10-15 15:50:42 +10001449 "usage: %s [-1Cv] [-B buffer_size] [-b batchfile] [-F ssh_config]\n"
1450 " [-o ssh_option] [-P sftp_server_path] [-R num_requests]\n"
1451 " [-S program] [-s subsystem | sftp_server] host\n"
1452 " %s [[user@]host[:file [file]]]\n"
1453 " %s [[user@]host[:dir[/]]]\n"
1454 " %s -b batchfile [user@]host\n", __progname, __progname, __progname, __progname);
Damien Miller33804262001-02-04 23:20:18 +11001455 exit(1);
1456}
1457
Kevin Stevesef4eea92001-02-05 12:42:17 +00001458int
Damien Miller33804262001-02-04 23:20:18 +11001459main(int argc, char **argv)
1460{
Damien Miller956f3fb2003-01-10 21:40:00 +11001461 int in, out, ch, err;
Damien Miller7cf17eb2004-06-15 10:28:56 +10001462 char *host, *userhost, *cp, *file2 = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001463 int debug_level = 0, sshver = 2;
1464 char *file1 = NULL, *sftp_server = NULL;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001465 char *ssh_program = _PATH_SSH_PROGRAM, *sftp_direct = NULL;
Ben Lindstrom387c4722001-05-08 20:27:25 +00001466 LogLevel ll = SYSLOG_LEVEL_INFO;
1467 arglist args;
Damien Millerd7686fd2001-02-10 00:40:03 +11001468 extern int optind;
1469 extern char *optarg;
Damien Miller33804262001-02-04 23:20:18 +11001470
Darren Tuckerce321d82005-10-03 18:11:24 +10001471 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1472 sanitise_stdfd();
1473
Damien Miller59d3d5b2003-08-22 09:34:41 +10001474 __progname = ssh_get_progname(argv[0]);
Damien Miller3eec6b72006-01-31 21:49:27 +11001475 memset(&args, '\0', sizeof(args));
Ben Lindstrom387c4722001-05-08 20:27:25 +00001476 args.list = NULL;
Damien Miller2b5a0de2006-03-31 23:10:31 +11001477 addargs(&args, "%s", ssh_program);
Ben Lindstrom387c4722001-05-08 20:27:25 +00001478 addargs(&args, "-oForwardX11 no");
1479 addargs(&args, "-oForwardAgent no");
Damien Millerd27b9472005-12-13 19:29:02 +11001480 addargs(&args, "-oPermitLocalCommand no");
Ben Lindstrom2b7a0e92001-09-20 00:57:55 +00001481 addargs(&args, "-oClearAllForwardings yes");
Damien Millere4f5a822004-01-21 14:11:05 +11001482
Ben Lindstrom387c4722001-05-08 20:27:25 +00001483 ll = SYSLOG_LEVEL_INFO;
Damien Millere4f5a822004-01-21 14:11:05 +11001484 infile = stdin;
Damien Millerd7686fd2001-02-10 00:40:03 +11001485
Damien Miller16a13332002-02-13 14:03:56 +11001486 while ((ch = getopt(argc, argv, "1hvCo:s:S:b:B:F:P:R:")) != -1) {
Damien Millerd7686fd2001-02-10 00:40:03 +11001487 switch (ch) {
1488 case 'C':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001489 addargs(&args, "-C");
Damien Millerd7686fd2001-02-10 00:40:03 +11001490 break;
1491 case 'v':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001492 if (debug_level < 3) {
1493 addargs(&args, "-v");
1494 ll = SYSLOG_LEVEL_DEBUG1 + debug_level;
1495 }
1496 debug_level++;
Damien Millerd7686fd2001-02-10 00:40:03 +11001497 break;
Ben Lindstrom1e243242001-09-18 05:38:44 +00001498 case 'F':
Damien Millerd7686fd2001-02-10 00:40:03 +11001499 case 'o':
Ben Lindstrom1e243242001-09-18 05:38:44 +00001500 addargs(&args, "-%c%s", ch, optarg);
Damien Millerd7686fd2001-02-10 00:40:03 +11001501 break;
1502 case '1':
Ben Lindstrom387c4722001-05-08 20:27:25 +00001503 sshver = 1;
Damien Millerd7686fd2001-02-10 00:40:03 +11001504 if (sftp_server == NULL)
1505 sftp_server = _PATH_SFTP_SERVER;
1506 break;
1507 case 's':
1508 sftp_server = optarg;
1509 break;
1510 case 'S':
1511 ssh_program = optarg;
Damien Miller3eec6b72006-01-31 21:49:27 +11001512 replacearg(&args, 0, "%s", ssh_program);
Damien Millerd7686fd2001-02-10 00:40:03 +11001513 break;
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001514 case 'b':
Damien Miller44f75c12004-01-21 10:58:47 +11001515 if (batchmode)
1516 fatal("Batch file already specified.");
1517
1518 /* Allow "-" as stdin */
Darren Tuckerfc959702004-07-17 16:12:08 +10001519 if (strcmp(optarg, "-") != 0 &&
Damien Miller0dc1bef2005-07-17 17:22:45 +10001520 (infile = fopen(optarg, "r")) == NULL)
Damien Miller44f75c12004-01-21 10:58:47 +11001521 fatal("%s (%s).", strerror(errno), optarg);
Damien Miller62d57f62003-01-10 21:43:24 +11001522 showprogress = 0;
Damien Miller44f75c12004-01-21 10:58:47 +11001523 batchmode = 1;
Damien Miller64e8d442005-03-01 21:16:47 +11001524 addargs(&args, "-obatchmode yes");
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001525 break;
Damien Millerd14ee1e2002-02-05 12:27:31 +11001526 case 'P':
1527 sftp_direct = optarg;
1528 break;
Damien Miller8829d362002-02-08 22:04:05 +11001529 case 'B':
1530 copy_buffer_len = strtol(optarg, &cp, 10);
1531 if (copy_buffer_len == 0 || *cp != '\0')
1532 fatal("Invalid buffer size \"%s\"", optarg);
1533 break;
Damien Miller16a13332002-02-13 14:03:56 +11001534 case 'R':
1535 num_requests = strtol(optarg, &cp, 10);
1536 if (num_requests == 0 || *cp != '\0')
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001537 fatal("Invalid number of requests \"%s\"",
Damien Miller16a13332002-02-13 14:03:56 +11001538 optarg);
1539 break;
Damien Millerd7686fd2001-02-10 00:40:03 +11001540 case 'h':
1541 default:
Damien Miller33804262001-02-04 23:20:18 +11001542 usage();
1543 }
1544 }
1545
Damien Millerc0f27d82004-03-08 23:12:19 +11001546 if (!isatty(STDERR_FILENO))
1547 showprogress = 0;
1548
Ben Lindstrom2f3d52a2002-04-02 21:06:18 +00001549 log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1);
1550
Damien Millerd14ee1e2002-02-05 12:27:31 +11001551 if (sftp_direct == NULL) {
1552 if (optind == argc || argc > (optind + 2))
1553 usage();
Damien Miller33804262001-02-04 23:20:18 +11001554
Damien Millerd14ee1e2002-02-05 12:27:31 +11001555 userhost = xstrdup(argv[optind]);
1556 file2 = argv[optind+1];
Ben Lindstrom63667f62001-04-13 00:00:14 +00001557
Ben Lindstromc276c122002-12-23 02:14:51 +00001558 if ((host = strrchr(userhost, '@')) == NULL)
Damien Millerd14ee1e2002-02-05 12:27:31 +11001559 host = userhost;
1560 else {
1561 *host++ = '\0';
1562 if (!userhost[0]) {
1563 fprintf(stderr, "Missing username\n");
1564 usage();
1565 }
1566 addargs(&args, "-l%s",userhost);
1567 }
1568
Damien Millerec692032004-01-27 21:22:00 +11001569 if ((cp = colon(host)) != NULL) {
1570 *cp++ = '\0';
1571 file1 = cp;
1572 }
1573
Damien Millerd14ee1e2002-02-05 12:27:31 +11001574 host = cleanhostname(host);
1575 if (!*host) {
1576 fprintf(stderr, "Missing hostname\n");
Damien Miller33804262001-02-04 23:20:18 +11001577 usage();
1578 }
Damien Millerd14ee1e2002-02-05 12:27:31 +11001579
Damien Millerd14ee1e2002-02-05 12:27:31 +11001580 addargs(&args, "-oProtocol %d", sshver);
1581
1582 /* no subsystem if the server-spec contains a '/' */
1583 if (sftp_server == NULL || strchr(sftp_server, '/') == NULL)
1584 addargs(&args, "-s");
1585
1586 addargs(&args, "%s", host);
Ben Lindstrom6328ab32002-03-22 02:54:23 +00001587 addargs(&args, "%s", (sftp_server != NULL ?
Damien Millerd14ee1e2002-02-05 12:27:31 +11001588 sftp_server : "sftp"));
Damien Millerd14ee1e2002-02-05 12:27:31 +11001589
Damien Miller44f75c12004-01-21 10:58:47 +11001590 if (!batchmode)
1591 fprintf(stderr, "Connecting to %s...\n", host);
Damien Millercc685c12003-06-04 22:51:38 +10001592 connect_to_server(ssh_program, args.list, &in, &out);
Damien Millerd14ee1e2002-02-05 12:27:31 +11001593 } else {
1594 args.list = NULL;
1595 addargs(&args, "sftp-server");
1596
Damien Miller44f75c12004-01-21 10:58:47 +11001597 if (!batchmode)
1598 fprintf(stderr, "Attaching to %s...\n", sftp_direct);
Damien Millercc685c12003-06-04 22:51:38 +10001599 connect_to_server(sftp_direct, args.list, &in, &out);
Damien Miller33804262001-02-04 23:20:18 +11001600 }
Damien Miller3eec6b72006-01-31 21:49:27 +11001601 freeargs(&args);
Damien Miller33804262001-02-04 23:20:18 +11001602
Damien Miller956f3fb2003-01-10 21:40:00 +11001603 err = interactive_loop(in, out, file1, file2);
Damien Miller33804262001-02-04 23:20:18 +11001604
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001605#if !defined(USE_PIPES)
Damien Miller37294fb2005-07-17 17:18:49 +10001606 shutdown(in, SHUT_RDWR);
1607 shutdown(out, SHUT_RDWR);
Ben Lindstrom10b9bf92001-02-26 20:04:45 +00001608#endif
1609
Damien Miller33804262001-02-04 23:20:18 +11001610 close(in);
1611 close(out);
Damien Miller44f75c12004-01-21 10:58:47 +11001612 if (batchmode)
Ben Lindstrom562c26b2001-03-07 01:26:48 +00001613 fclose(infile);
Damien Miller33804262001-02-04 23:20:18 +11001614
Ben Lindstrom47fd8112002-04-02 20:48:19 +00001615 while (waitpid(sshpid, NULL, 0) == -1)
1616 if (errno != EINTR)
1617 fatal("Couldn't wait for ssh process: %s",
1618 strerror(errno));
Damien Miller33804262001-02-04 23:20:18 +11001619
Damien Miller956f3fb2003-01-10 21:40:00 +11001620 exit(err == 0 ? 0 : 1);
Damien Miller33804262001-02-04 23:20:18 +11001621}