]> andersk Git - openssh.git/blob - sftp-int.c
- mouring@cvs.openbsd.org 2003/05/15 03:39:07
[openssh.git] / sftp-int.c
1 /*
2  * Copyright (c) 2001,2002 Damien Miller.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24
25 /* XXX: recursive operations */
26
27 #include "includes.h"
28 RCSID("$OpenBSD: sftp-int.c,v 1.59 2003/05/15 03:39:07 mouring Exp $");
29
30 #include "buffer.h"
31 #include "xmalloc.h"
32 #include "log.h"
33 #include "pathnames.h"
34
35 #include "sftp.h"
36 #include "sftp-common.h"
37 #include "sftp-glob.h"
38 #include "sftp-client.h"
39 #include "sftp-int.h"
40
41 /* File to read commands from */
42 extern FILE *infile;
43
44 /* Size of buffer used when copying files */
45 extern size_t copy_buffer_len;
46
47 /* Number of concurrent outstanding requests */
48 extern int num_requests;
49
50 /* This is set to 0 if the progressmeter is not desired. */
51 int showprogress = 1;
52
53 /* Seperators for interactive commands */
54 #define WHITESPACE " \t\r\n"
55
56 /* Commands for interactive mode */
57 #define I_CHDIR         1
58 #define I_CHGRP         2
59 #define I_CHMOD         3
60 #define I_CHOWN         4
61 #define I_GET           5
62 #define I_HELP          6
63 #define I_LCHDIR        7
64 #define I_LLS           8
65 #define I_LMKDIR        9
66 #define I_LPWD          10
67 #define I_LS            11
68 #define I_LUMASK        12
69 #define I_MKDIR         13
70 #define I_PUT           14
71 #define I_PWD           15
72 #define I_QUIT          16
73 #define I_RENAME        17
74 #define I_RM            18
75 #define I_RMDIR         19
76 #define I_SHELL         20
77 #define I_SYMLINK       21
78 #define I_VERSION       22
79 #define I_PROGRESS      23
80
81 struct CMD {
82         const char *c;
83         const int n;
84 };
85
86 static const struct CMD cmds[] = {
87         { "bye",        I_QUIT },
88         { "cd",         I_CHDIR },
89         { "chdir",      I_CHDIR },
90         { "chgrp",      I_CHGRP },
91         { "chmod",      I_CHMOD },
92         { "chown",      I_CHOWN },
93         { "dir",        I_LS },
94         { "exit",       I_QUIT },
95         { "get",        I_GET },
96         { "mget",       I_GET },
97         { "help",       I_HELP },
98         { "lcd",        I_LCHDIR },
99         { "lchdir",     I_LCHDIR },
100         { "lls",        I_LLS },
101         { "lmkdir",     I_LMKDIR },
102         { "ln",         I_SYMLINK },
103         { "lpwd",       I_LPWD },
104         { "ls",         I_LS },
105         { "lumask",     I_LUMASK },
106         { "mkdir",      I_MKDIR },
107         { "progress",   I_PROGRESS },
108         { "put",        I_PUT },
109         { "mput",       I_PUT },
110         { "pwd",        I_PWD },
111         { "quit",       I_QUIT },
112         { "rename",     I_RENAME },
113         { "rm",         I_RM },
114         { "rmdir",      I_RMDIR },
115         { "symlink",    I_SYMLINK },
116         { "version",    I_VERSION },
117         { "!",          I_SHELL },
118         { "?",          I_HELP },
119         { NULL,                 -1}
120 };
121
122 static void
123 help(void)
124 {
125         printf("Available commands:\n");
126         printf("cd path                       Change remote directory to 'path'\n");
127         printf("lcd path                      Change local directory to 'path'\n");
128         printf("chgrp grp path                Change group of file 'path' to 'grp'\n");
129         printf("chmod mode path               Change permissions of file 'path' to 'mode'\n");
130         printf("chown own path                Change owner of file 'path' to 'own'\n");
131         printf("help                          Display this help text\n");
132         printf("get remote-path [local-path]  Download file\n");
133         printf("lls [ls-options [path]]       Display local directory listing\n");
134         printf("ln oldpath newpath            Symlink remote file\n");
135         printf("lmkdir path                   Create local directory\n");
136         printf("lpwd                          Print local working directory\n");
137         printf("ls [path]                     Display remote directory listing\n");
138         printf("lumask umask                  Set local umask to 'umask'\n");
139         printf("mkdir path                    Create remote directory\n");
140         printf("progress                      Toggle display of progress meter\n");
141         printf("put local-path [remote-path]  Upload file\n");
142         printf("pwd                           Display remote working directory\n");
143         printf("exit                          Quit sftp\n");
144         printf("quit                          Quit sftp\n");
145         printf("rename oldpath newpath        Rename remote file\n");
146         printf("rmdir path                    Remove remote directory\n");
147         printf("rm path                       Delete remote file\n");
148         printf("symlink oldpath newpath       Symlink remote file\n");
149         printf("version                       Show SFTP version\n");
150         printf("!command                      Execute 'command' in local shell\n");
151         printf("!                             Escape to local shell\n");
152         printf("?                             Synonym for help\n");
153 }
154
155 static void
156 local_do_shell(const char *args)
157 {
158         int status;
159         char *shell;
160         pid_t pid;
161
162         if (!*args)
163                 args = NULL;
164
165         if ((shell = getenv("SHELL")) == NULL)
166                 shell = _PATH_BSHELL;
167
168         if ((pid = fork()) == -1)
169                 fatal("Couldn't fork: %s", strerror(errno));
170
171         if (pid == 0) {
172                 /* XXX: child has pipe fds to ssh subproc open - issue? */
173                 if (args) {
174                         debug3("Executing %s -c \"%s\"", shell, args);
175                         execl(shell, shell, "-c", args, (char *)NULL);
176                 } else {
177                         debug3("Executing %s", shell);
178                         execl(shell, shell, (char *)NULL);
179                 }
180                 fprintf(stderr, "Couldn't execute \"%s\": %s\n", shell,
181                     strerror(errno));
182                 _exit(1);
183         }
184         while (waitpid(pid, &status, 0) == -1)
185                 if (errno != EINTR)
186                         fatal("Couldn't wait for child: %s", strerror(errno));
187         if (!WIFEXITED(status))
188                 error("Shell exited abormally");
189         else if (WEXITSTATUS(status))
190                 error("Shell exited with status %d", WEXITSTATUS(status));
191 }
192
193 static void
194 local_do_ls(const char *args)
195 {
196         if (!args || !*args)
197                 local_do_shell(_PATH_LS);
198         else {
199                 int len = strlen(_PATH_LS " ") + strlen(args) + 1;
200                 char *buf = xmalloc(len);
201
202                 /* XXX: quoting - rip quoting code from ftp? */
203                 snprintf(buf, len, _PATH_LS " %s", args);
204                 local_do_shell(buf);
205                 xfree(buf);
206         }
207 }
208
209 /* Strip one path (usually the pwd) from the start of another */
210 static char *
211 path_strip(char *path, char *strip)
212 {
213         size_t len;
214
215         if (strip == NULL)
216                 return (xstrdup(path));
217
218         len = strlen(strip);
219         if (strip != NULL && strncmp(path, strip, len) == 0) {
220                 if (strip[len - 1] != '/' && path[len] == '/')
221                         len++;
222                 return (xstrdup(path + len));
223         }
224
225         return (xstrdup(path));
226 }
227
228 static char *
229 path_append(char *p1, char *p2)
230 {
231         char *ret;
232         int len = strlen(p1) + strlen(p2) + 2;
233
234         ret = xmalloc(len);
235         strlcpy(ret, p1, len);
236         if (p1[strlen(p1) - 1] != '/')
237                 strlcat(ret, "/", len);
238         strlcat(ret, p2, len);
239
240         return(ret);
241 }
242
243 static char *
244 make_absolute(char *p, char *pwd)
245 {
246         char *abs;
247
248         /* Derelativise */
249         if (p && p[0] != '/') {
250                 abs = path_append(pwd, p);
251                 xfree(p);
252                 return(abs);
253         } else
254                 return(p);
255 }
256
257 static int
258 infer_path(const char *p, char **ifp)
259 {
260         char *cp;
261
262         cp = strrchr(p, '/');
263         if (cp == NULL) {
264                 *ifp = xstrdup(p);
265                 return(0);
266         }
267
268         if (!cp[1]) {
269                 error("Invalid path");
270                 return(-1);
271         }
272
273         *ifp = xstrdup(cp + 1);
274         return(0);
275 }
276
277 static int
278 parse_getput_flags(const char **cpp, int *pflag)
279 {
280         const char *cp = *cpp;
281
282         /* Check for flags */
283         if (cp[0] == '-' && cp[1] && strchr(WHITESPACE, cp[2])) {
284                 switch (cp[1]) {
285                 case 'p':
286                 case 'P':
287                         *pflag = 1;
288                         break;
289                 default:
290                         error("Invalid flag -%c", cp[1]);
291                         return(-1);
292                 }
293                 cp += 2;
294                 *cpp = cp + strspn(cp, WHITESPACE);
295         }
296
297         return(0);
298 }
299
300 static int
301 parse_ls_flags(const char **cpp, int *lflag)
302 {
303         const char *cp = *cpp;
304
305         /* Check for flags */
306         if (cp++[0] == '-') {
307                 for(; strchr(WHITESPACE, *cp) == NULL; cp++) {
308                         switch (*cp) {
309                         case 'l':
310                                 *lflag = 1;
311                                 break;
312                         default:
313                                 error("Invalid flag -%c", *cp);
314                                 return(-1);
315                         }
316                 }
317                 *cpp = cp + strspn(cp, WHITESPACE);
318         }
319
320         return(0);
321 }
322
323 static int
324 get_pathname(const char **cpp, char **path)
325 {
326         const char *cp = *cpp, *end;
327         char quot;
328         int i;
329
330         cp += strspn(cp, WHITESPACE);
331         if (!*cp) {
332                 *cpp = cp;
333                 *path = NULL;
334                 return (0);
335         }
336
337         /* Check for quoted filenames */
338         if (*cp == '\"' || *cp == '\'') {
339                 quot = *cp++;
340
341                 end = strchr(cp, quot);
342                 if (end == NULL) {
343                         error("Unterminated quote");
344                         goto fail;
345                 }
346                 if (cp == end) {
347                         error("Empty quotes");
348                         goto fail;
349                 }
350                 *cpp = end + 1 + strspn(end + 1, WHITESPACE);
351         } else {
352                 /* Read to end of filename */
353                 end = strpbrk(cp, WHITESPACE);
354                 if (end == NULL)
355                         end = strchr(cp, '\0');
356                 *cpp = end + strspn(end, WHITESPACE);
357         }
358
359         i = end - cp;
360
361         *path = xmalloc(i + 1);
362         memcpy(*path, cp, i);
363         (*path)[i] = '\0';
364         return(0);
365
366  fail:
367         *path = NULL;
368         return (-1);
369 }
370
371 static int
372 is_dir(char *path)
373 {
374         struct stat sb;
375
376         /* XXX: report errors? */
377         if (stat(path, &sb) == -1)
378                 return(0);
379
380         return(sb.st_mode & S_IFDIR);
381 }
382
383 static int
384 is_reg(char *path)
385 {
386         struct stat sb;
387
388         if (stat(path, &sb) == -1)
389                 fatal("stat %s: %s", path, strerror(errno));
390
391         return(S_ISREG(sb.st_mode));
392 }
393
394 static int
395 remote_is_dir(struct sftp_conn *conn, char *path)
396 {
397         Attrib *a;
398
399         /* XXX: report errors? */
400         if ((a = do_stat(conn, path, 1)) == NULL)
401                 return(0);
402         if (!(a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS))
403                 return(0);
404         return(a->perm & S_IFDIR);
405 }
406
407 static int
408 process_get(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
409 {
410         char *abs_src = NULL;
411         char *abs_dst = NULL;
412         char *tmp;
413         glob_t g;
414         int err = 0;
415         int i;
416
417         abs_src = xstrdup(src);
418         abs_src = make_absolute(abs_src, pwd);
419
420         memset(&g, 0, sizeof(g));
421         debug3("Looking up %s", abs_src);
422         if (remote_glob(conn, abs_src, 0, NULL, &g)) {
423                 error("File \"%s\" not found.", abs_src);
424                 err = -1;
425                 goto out;
426         }
427
428         /* If multiple matches, dst must be a directory or unspecified */
429         if (g.gl_matchc > 1 && dst && !is_dir(dst)) {
430                 error("Multiple files match, but \"%s\" is not a directory",
431                     dst);
432                 err = -1;
433                 goto out;
434         }
435
436         for (i = 0; g.gl_pathv[i]; i++) {
437                 if (infer_path(g.gl_pathv[i], &tmp)) {
438                         err = -1;
439                         goto out;
440                 }
441
442                 if (g.gl_matchc == 1 && dst) {
443                         /* If directory specified, append filename */
444                         if (is_dir(dst)) {
445                                 if (infer_path(g.gl_pathv[0], &tmp)) {
446                                         err = 1;
447                                         goto out;
448                                 }
449                                 abs_dst = path_append(dst, tmp);
450                                 xfree(tmp);
451                         } else
452                                 abs_dst = xstrdup(dst);
453                 } else if (dst) {
454                         abs_dst = path_append(dst, tmp);
455                         xfree(tmp);
456                 } else
457                         abs_dst = tmp;
458
459                 printf("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
460                 if (do_download(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
461                         err = -1;
462                 xfree(abs_dst);
463                 abs_dst = NULL;
464         }
465
466 out:
467         xfree(abs_src);
468         if (abs_dst)
469                 xfree(abs_dst);
470         globfree(&g);
471         return(err);
472 }
473
474 static int
475 process_put(struct sftp_conn *conn, char *src, char *dst, char *pwd, int pflag)
476 {
477         char *tmp_dst = NULL;
478         char *abs_dst = NULL;
479         char *tmp;
480         glob_t g;
481         int err = 0;
482         int i;
483
484         if (dst) {
485                 tmp_dst = xstrdup(dst);
486                 tmp_dst = make_absolute(tmp_dst, pwd);
487         }
488
489         memset(&g, 0, sizeof(g));
490         debug3("Looking up %s", src);
491         if (glob(src, 0, NULL, &g)) {
492                 error("File \"%s\" not found.", src);
493                 err = -1;
494                 goto out;
495         }
496
497         /* If multiple matches, dst may be directory or unspecified */
498         if (g.gl_matchc > 1 && tmp_dst && !remote_is_dir(conn, tmp_dst)) {
499                 error("Multiple files match, but \"%s\" is not a directory",
500                     tmp_dst);
501                 err = -1;
502                 goto out;
503         }
504
505         for (i = 0; g.gl_pathv[i]; i++) {
506                 if (!is_reg(g.gl_pathv[i])) {
507                         error("skipping non-regular file %s", 
508                             g.gl_pathv[i]);
509                         continue;
510                 }
511                 if (infer_path(g.gl_pathv[i], &tmp)) {
512                         err = -1;
513                         goto out;
514                 }
515
516                 if (g.gl_matchc == 1 && tmp_dst) {
517                         /* If directory specified, append filename */
518                         if (remote_is_dir(conn, tmp_dst)) {
519                                 if (infer_path(g.gl_pathv[0], &tmp)) {
520                                         err = 1;
521                                         goto out;
522                                 }
523                                 abs_dst = path_append(tmp_dst, tmp);
524                                 xfree(tmp);
525                         } else
526                                 abs_dst = xstrdup(tmp_dst);
527
528                 } else if (tmp_dst) {
529                         abs_dst = path_append(tmp_dst, tmp);
530                         xfree(tmp);
531                 } else
532                         abs_dst = make_absolute(tmp, pwd);
533
534                 printf("Uploading %s to %s\n", g.gl_pathv[i], abs_dst);
535                 if (do_upload(conn, g.gl_pathv[i], abs_dst, pflag) == -1)
536                         err = -1;
537         }
538
539 out:
540         if (abs_dst)
541                 xfree(abs_dst);
542         if (tmp_dst)
543                 xfree(tmp_dst);
544         globfree(&g);
545         return(err);
546 }
547
548 static int
549 sdirent_comp(const void *aa, const void *bb)
550 {
551         SFTP_DIRENT *a = *(SFTP_DIRENT **)aa;
552         SFTP_DIRENT *b = *(SFTP_DIRENT **)bb;
553
554         return (strcmp(a->filename, b->filename));
555 }
556
557 /* sftp ls.1 replacement for directories */
558 static int
559 do_ls_dir(struct sftp_conn *conn, char *path, char *strip_path, int lflag)
560 {
561         int n;
562         SFTP_DIRENT **d;
563
564         if ((n = do_readdir(conn, path, &d)) != 0)
565                 return (n);
566
567         /* Count entries for sort */
568         for (n = 0; d[n] != NULL; n++)
569                 ;
570
571         qsort(d, n, sizeof(*d), sdirent_comp);
572
573         for (n = 0; d[n] != NULL; n++) {
574                 char *tmp, *fname;
575
576                 tmp = path_append(path, d[n]->filename);
577                 fname = path_strip(tmp, strip_path);
578                 xfree(tmp);
579
580                 if (lflag) {
581                         char *lname;
582                         struct stat sb;
583
584                         memset(&sb, 0, sizeof(sb));
585                         attrib_to_stat(&d[n]->a, &sb);
586                         lname = ls_file(fname, &sb, 1);
587                         printf("%s\n", lname);
588                         xfree(lname);
589                 } else {
590                         /* XXX - multicolumn display would be nice here */
591                         printf("%s\n", fname);
592                 }
593
594                 xfree(fname);
595         }
596
597         free_sftp_dirents(d);
598         return (0);
599 }
600
601 /* sftp ls.1 replacement which handles path globs */
602 static int
603 do_globbed_ls(struct sftp_conn *conn, char *path, char *strip_path,
604     int lflag)
605 {
606         glob_t g;
607         int i;
608         Attrib *a;
609         struct stat sb;
610
611         memset(&g, 0, sizeof(g));
612
613         if (remote_glob(conn, path, GLOB_MARK|GLOB_NOCHECK|GLOB_BRACE,
614             NULL, &g)) {
615                 error("Can't ls: \"%s\" not found", path);
616                 return (-1);
617         }
618
619         /*
620          * If the glob returns a single match, which is the same as the
621          * input glob, and it is a directory, then just list its contents
622          */
623         if (g.gl_pathc == 1 &&
624             strncmp(path, g.gl_pathv[0], strlen(g.gl_pathv[0]) - 1) == 0) {
625                 if ((a = do_lstat(conn, path, 1)) == NULL) {
626                         globfree(&g);
627                         return (-1);
628                 }
629                 if ((a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) &&
630                     S_ISDIR(a->perm)) {
631                         globfree(&g);
632                         return (do_ls_dir(conn, path, strip_path, lflag));
633                 }
634         }
635
636         for (i = 0; g.gl_pathv[i]; i++) {
637                 char *fname, *lname;
638
639                 fname = path_strip(g.gl_pathv[i], strip_path);
640
641                 if (lflag) {
642                         /*
643                          * XXX: this is slow - 1 roundtrip per path
644                          * A solution to this is to fork glob() and
645                          * build a sftp specific version which keeps the
646                          * attribs (which currently get thrown away)
647                          * that the server returns as well as the filenames.
648                          */
649                         memset(&sb, 0, sizeof(sb));
650                         a = do_lstat(conn, g.gl_pathv[i], 1);
651                         if (a != NULL)
652                                 attrib_to_stat(a, &sb);
653                         lname = ls_file(fname, &sb, 1);
654                         printf("%s\n", lname);
655                         xfree(lname);
656                 } else {
657                         /* XXX - multicolumn display would be nice here */
658                         printf("%s\n", fname);
659                 }
660                 xfree(fname);
661         }
662
663         if (g.gl_pathc)
664                 globfree(&g);
665
666         return (0);
667 }
668
669 static int
670 parse_args(const char **cpp, int *pflag, int *lflag, int *iflag,
671     unsigned long *n_arg, char **path1, char **path2)
672 {
673         const char *cmd, *cp = *cpp;
674         char *cp2;
675         int base = 0;
676         long l;
677         int i, cmdnum;
678
679         /* Skip leading whitespace */
680         cp = cp + strspn(cp, WHITESPACE);
681
682         /* Ignore blank lines and lines which begin with comment '#' char */
683         if (*cp == '\0' || *cp == '#')
684                 return (0);
685
686         /* Check for leading '-' (disable error processing) */
687         *iflag = 0;
688         if (*cp == '-') {
689                 *iflag = 1;
690                 cp++;
691         }
692                 
693         /* Figure out which command we have */
694         for (i = 0; cmds[i].c; i++) {
695                 int cmdlen = strlen(cmds[i].c);
696
697                 /* Check for command followed by whitespace */
698                 if (!strncasecmp(cp, cmds[i].c, cmdlen) &&
699                     strchr(WHITESPACE, cp[cmdlen])) {
700                         cp += cmdlen;
701                         cp = cp + strspn(cp, WHITESPACE);
702                         break;
703                 }
704         }
705         cmdnum = cmds[i].n;
706         cmd = cmds[i].c;
707
708         /* Special case */
709         if (*cp == '!') {
710                 cp++;
711                 cmdnum = I_SHELL;
712         } else if (cmdnum == -1) {
713                 error("Invalid command.");
714                 return (-1);
715         }
716
717         /* Get arguments and parse flags */
718         *lflag = *pflag = *n_arg = 0;
719         *path1 = *path2 = NULL;
720         switch (cmdnum) {
721         case I_GET:
722         case I_PUT:
723                 if (parse_getput_flags(&cp, pflag))
724                         return(-1);
725                 /* Get first pathname (mandatory) */
726                 if (get_pathname(&cp, path1))
727                         return(-1);
728                 if (*path1 == NULL) {
729                         error("You must specify at least one path after a "
730                             "%s command.", cmd);
731                         return(-1);
732                 }
733                 /* Try to get second pathname (optional) */
734                 if (get_pathname(&cp, path2))
735                         return(-1);
736                 break;
737         case I_RENAME:
738         case I_SYMLINK:
739                 if (get_pathname(&cp, path1))
740                         return(-1);
741                 if (get_pathname(&cp, path2))
742                         return(-1);
743                 if (!*path1 || !*path2) {
744                         error("You must specify two paths after a %s "
745                             "command.", cmd);
746                         return(-1);
747                 }
748                 break;
749         case I_RM:
750         case I_MKDIR:
751         case I_RMDIR:
752         case I_CHDIR:
753         case I_LCHDIR:
754         case I_LMKDIR:
755                 /* Get pathname (mandatory) */
756                 if (get_pathname(&cp, path1))
757                         return(-1);
758                 if (*path1 == NULL) {
759                         error("You must specify a path after a %s command.",
760                             cmd);
761                         return(-1);
762                 }
763                 break;
764         case I_LS:
765                 if (parse_ls_flags(&cp, lflag))
766                         return(-1);
767                 /* Path is optional */
768                 if (get_pathname(&cp, path1))
769                         return(-1);
770                 break;
771         case I_LLS:
772         case I_SHELL:
773                 /* Uses the rest of the line */
774                 break;
775         case I_LUMASK:
776                 base = 8;
777         case I_CHMOD:
778                 base = 8;
779         case I_CHOWN:
780         case I_CHGRP:
781                 /* Get numeric arg (mandatory) */
782                 l = strtol(cp, &cp2, base);
783                 if (cp2 == cp || ((l == LONG_MIN || l == LONG_MAX) &&
784                     errno == ERANGE) || l < 0) {
785                         error("You must supply a numeric argument "
786                             "to the %s command.", cmd);
787                         return(-1);
788                 }
789                 cp = cp2;
790                 *n_arg = l;
791                 if (cmdnum == I_LUMASK && strchr(WHITESPACE, *cp))
792                         break;
793                 if (cmdnum == I_LUMASK || !strchr(WHITESPACE, *cp)) {
794                         error("You must supply a numeric argument "
795                             "to the %s command.", cmd);
796                         return(-1);
797                 }
798                 cp += strspn(cp, WHITESPACE);
799
800                 /* Get pathname (mandatory) */
801                 if (get_pathname(&cp, path1))
802                         return(-1);
803                 if (*path1 == NULL) {
804                         error("You must specify a path after a %s command.",
805                             cmd);
806                         return(-1);
807                 }
808                 break;
809         case I_QUIT:
810         case I_PWD:
811         case I_LPWD:
812         case I_HELP:
813         case I_VERSION:
814         case I_PROGRESS:
815                 break;
816         default:
817                 fatal("Command not implemented");
818         }
819
820         *cpp = cp;
821         return(cmdnum);
822 }
823
824 static int
825 parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd,
826     int err_abort)
827 {
828         char *path1, *path2, *tmp;
829         int pflag, lflag, iflag, cmdnum, i;
830         unsigned long n_arg;
831         Attrib a, *aa;
832         char path_buf[MAXPATHLEN];
833         int err = 0;
834         glob_t g;
835
836         path1 = path2 = NULL;
837         cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg,
838             &path1, &path2);
839
840         if (iflag != 0)
841                 err_abort = 0;
842
843         memset(&g, 0, sizeof(g));
844
845         /* Perform command */
846         switch (cmdnum) {
847         case 0:
848                 /* Blank line */
849                 break;
850         case -1:
851                 /* Unrecognized command */
852                 err = -1;
853                 break;
854         case I_GET:
855                 err = process_get(conn, path1, path2, *pwd, pflag);
856                 break;
857         case I_PUT:
858                 err = process_put(conn, path1, path2, *pwd, pflag);
859                 break;
860         case I_RENAME:
861                 path1 = make_absolute(path1, *pwd);
862                 path2 = make_absolute(path2, *pwd);
863                 err = do_rename(conn, path1, path2);
864                 break;
865         case I_SYMLINK:
866                 path2 = make_absolute(path2, *pwd);
867                 err = do_symlink(conn, path1, path2);
868                 break;
869         case I_RM:
870                 path1 = make_absolute(path1, *pwd);
871                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
872                 for (i = 0; g.gl_pathv[i]; i++) {
873                         printf("Removing %s\n", g.gl_pathv[i]);
874                         err = do_rm(conn, g.gl_pathv[i]);
875                         if (err != 0 && err_abort)
876                                 break;
877                 }
878                 break;
879         case I_MKDIR:
880                 path1 = make_absolute(path1, *pwd);
881                 attrib_clear(&a);
882                 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
883                 a.perm = 0777;
884                 err = do_mkdir(conn, path1, &a);
885                 break;
886         case I_RMDIR:
887                 path1 = make_absolute(path1, *pwd);
888                 err = do_rmdir(conn, path1);
889                 break;
890         case I_CHDIR:
891                 path1 = make_absolute(path1, *pwd);
892                 if ((tmp = do_realpath(conn, path1)) == NULL) {
893                         err = 1;
894                         break;
895                 }
896                 if ((aa = do_stat(conn, tmp, 0)) == NULL) {
897                         xfree(tmp);
898                         err = 1;
899                         break;
900                 }
901                 if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) {
902                         error("Can't change directory: Can't check target");
903                         xfree(tmp);
904                         err = 1;
905                         break;
906                 }
907                 if (!S_ISDIR(aa->perm)) {
908                         error("Can't change directory: \"%s\" is not "
909                             "a directory", tmp);
910                         xfree(tmp);
911                         err = 1;
912                         break;
913                 }
914                 xfree(*pwd);
915                 *pwd = tmp;
916                 break;
917         case I_LS:
918                 if (!path1) {
919                         do_globbed_ls(conn, *pwd, *pwd, lflag);
920                         break;
921                 }
922
923                 /* Strip pwd off beginning of non-absolute paths */
924                 tmp = NULL;
925                 if (*path1 != '/')
926                         tmp = *pwd;
927
928                 path1 = make_absolute(path1, *pwd);
929                 err = do_globbed_ls(conn, path1, tmp, lflag);
930                 break;
931         case I_LCHDIR:
932                 if (chdir(path1) == -1) {
933                         error("Couldn't change local directory to "
934                             "\"%s\": %s", path1, strerror(errno));
935                         err = 1;
936                 }
937                 break;
938         case I_LMKDIR:
939                 if (mkdir(path1, 0777) == -1) {
940                         error("Couldn't create local directory "
941                             "\"%s\": %s", path1, strerror(errno));
942                         err = 1;
943                 }
944                 break;
945         case I_LLS:
946                 local_do_ls(cmd);
947                 break;
948         case I_SHELL:
949                 local_do_shell(cmd);
950                 break;
951         case I_LUMASK:
952                 umask(n_arg);
953                 printf("Local umask: %03lo\n", n_arg);
954                 break;
955         case I_CHMOD:
956                 path1 = make_absolute(path1, *pwd);
957                 attrib_clear(&a);
958                 a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS;
959                 a.perm = n_arg;
960                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
961                 for (i = 0; g.gl_pathv[i]; i++) {
962                         printf("Changing mode on %s\n", g.gl_pathv[i]);
963                         err = do_setstat(conn, g.gl_pathv[i], &a);
964                         if (err != 0 && err_abort)
965                                 break;
966                 }
967                 break;
968         case I_CHOWN:
969         case I_CHGRP:
970                 path1 = make_absolute(path1, *pwd);
971                 remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g);
972                 for (i = 0; g.gl_pathv[i]; i++) {
973                         if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) {
974                                 if (err != 0 && err_abort)
975                                         break;
976                                 else
977                                         continue;
978                         }
979                         if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) {
980                                 error("Can't get current ownership of "
981                                     "remote file \"%s\"", g.gl_pathv[i]);
982                                 if (err != 0 && err_abort)
983                                         break;
984                                 else
985                                         continue;
986                         }
987                         aa->flags &= SSH2_FILEXFER_ATTR_UIDGID;
988                         if (cmdnum == I_CHOWN) {
989                                 printf("Changing owner on %s\n", g.gl_pathv[i]);
990                                 aa->uid = n_arg;
991                         } else {
992                                 printf("Changing group on %s\n", g.gl_pathv[i]);
993                                 aa->gid = n_arg;
994                         }
995                         err = do_setstat(conn, g.gl_pathv[i], aa);
996                         if (err != 0 && err_abort)
997                                 break;
998                 }
999                 break;
1000         case I_PWD:
1001                 printf("Remote working directory: %s\n", *pwd);
1002                 break;
1003         case I_LPWD:
1004                 if (!getcwd(path_buf, sizeof(path_buf))) {
1005                         error("Couldn't get local cwd: %s", strerror(errno));
1006                         err = -1;
1007                         break;
1008                 }
1009                 printf("Local working directory: %s\n", path_buf);
1010                 break;
1011         case I_QUIT:
1012                 /* Processed below */
1013                 break;
1014         case I_HELP:
1015                 help();
1016                 break;
1017         case I_VERSION:
1018                 printf("SFTP protocol version %u\n", sftp_proto_version(conn));
1019                 break;
1020         case I_PROGRESS:
1021                 showprogress = !showprogress;
1022                 if (showprogress)
1023                         printf("Progress meter enabled\n");
1024                 else
1025                         printf("Progress meter disabled\n");
1026                 break;
1027         default:
1028                 fatal("%d is not implemented", cmdnum);
1029         }
1030
1031         if (g.gl_pathc)
1032                 globfree(&g);
1033         if (path1)
1034                 xfree(path1);
1035         if (path2)
1036                 xfree(path2);
1037
1038         /* If an unignored error occurs in batch mode we should abort. */
1039         if (err_abort && err != 0)
1040                 return (-1);
1041         else if (cmdnum == I_QUIT)
1042                 return (1);
1043
1044         return (0);
1045 }
1046
1047 int
1048 interactive_loop(int fd_in, int fd_out, char *file1, char *file2)
1049 {
1050         char *pwd;
1051         char *dir = NULL;
1052         char cmd[2048];
1053         struct sftp_conn *conn;
1054         int err;
1055
1056         conn = do_init(fd_in, fd_out, copy_buffer_len, num_requests);
1057         if (conn == NULL)
1058                 fatal("Couldn't initialise connection to server");
1059
1060         pwd = do_realpath(conn, ".");
1061         if (pwd == NULL)
1062                 fatal("Need cwd");
1063
1064         if (file1 != NULL) {
1065                 dir = xstrdup(file1);
1066                 dir = make_absolute(dir, pwd);
1067
1068                 if (remote_is_dir(conn, dir) && file2 == NULL) {
1069                         printf("Changing to: %s\n", dir);
1070                         snprintf(cmd, sizeof cmd, "cd \"%s\"", dir);
1071                         if (parse_dispatch_command(conn, cmd, &pwd, 1) != 0)
1072                                 return (-1);
1073                 } else {
1074                         if (file2 == NULL)
1075                                 snprintf(cmd, sizeof cmd, "get %s", dir);
1076                         else
1077                                 snprintf(cmd, sizeof cmd, "get %s %s", dir,
1078                                     file2);
1079
1080                         err = parse_dispatch_command(conn, cmd, &pwd, 1);
1081                         xfree(dir);
1082                         xfree(pwd);
1083                         return (err);
1084                 }
1085                 xfree(dir);
1086         }
1087
1088 #if HAVE_SETVBUF
1089         setvbuf(stdout, NULL, _IOLBF, 0);
1090         setvbuf(infile, NULL, _IOLBF, 0);
1091 #else
1092         setlinebuf(stdout);
1093         setlinebuf(infile);
1094 #endif
1095
1096         err = 0;
1097         for (;;) {
1098                 char *cp;
1099
1100                 printf("sftp> ");
1101
1102                 /* XXX: use libedit */
1103                 if (fgets(cmd, sizeof(cmd), infile) == NULL) {
1104                         printf("\n");
1105                         break;
1106                 } else if (infile != stdin) /* Bluff typing */
1107                         printf("%s", cmd);
1108
1109                 cp = strrchr(cmd, '\n');
1110                 if (cp)
1111                         *cp = '\0';
1112
1113                 err = parse_dispatch_command(conn, cmd, &pwd, infile != stdin);
1114                 if (err != 0)
1115                         break;
1116         }
1117         xfree(pwd);
1118
1119         /* err == 1 signifies normal "quit" exit */
1120         return (err >= 0 ? 0 : -1);
1121 }
1122
This page took 0.430206 seconds and 5 git commands to generate.