Ticket #1413 (overly quoted escaped pathnames)
[midnight-commander.git] / vfs / fish.c
blob1e1ccbecbb113fa1e70ed593e06b406eb58bf8b4
1 /* Virtual File System: FISH implementation for transfering files over
2 shell connections.
4 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
5 2007 Free Software Foundation, Inc.
7 Written by: 1998 Pavel Machek
8 Spaces fix: 2000 Michal Svec
10 Derived from ftpfs.c.
12 This program is free software; you can redistribute it and/or
13 modify it under the terms of the GNU Library General Public License
14 as published by the Free Software Foundation; either version 2 of
15 the License, or (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU Library General Public License for more details.
22 You should have received a copy of the GNU Library General Public
23 License along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
26 /**
27 * \file
28 * \brief Source: Virtual File System: FISH implementation for transfering files over
29 * shell connections
30 * \author Pavel Machek
31 * \author Michal Svec
32 * \date 1998, 2000
34 * Derived from ftpfs.c
35 * Read README.fish for protocol specification.
37 * Syntax of path is: /#sh:user@host[:Cr]/path
38 * where C means you want compressed connection,
39 * and r means you want to use rsh
41 * Namespace: fish_vfs_ops exported.
44 /* Define this if your ssh can take -I option */
46 #include <config.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <pwd.h>
50 #include <grp.h>
51 #include <sys/time.h> /* gettimeofday() */
52 #include <stdlib.h>
53 #include <string.h>
55 #include "../src/global.h"
56 #include "../src/tty.h" /* enable/disable interrupt key */
57 #include "../src/wtools.h" /* message() */
58 #include "../src/main.h" /* print_vfs_message */
59 #include "../src/util.h"
60 #include "../src/strescape.h"
61 #include "../src/unixcompat.h"
62 #include "../src/fs.h"
63 #include "utilvfs.h"
64 #include "xdirentry.h"
65 #include "vfs.h"
66 #include "vfs-impl.h"
67 #include "gc.h" /* vfs_stamp_create */
68 #include "tcputil.h"
69 #include "fish.h"
71 int fish_directory_timeout = 900;
73 #define DO_RESOLVE_SYMLINK 1
74 #define DO_OPEN 2
75 #define DO_FREE_RESOURCE 4
77 #define FISH_FLAG_COMPRESSED 1
78 #define FISH_FLAG_RSH 2
80 #define OPT_FLUSH 1
81 #define OPT_IGNORE_ERROR 2
84 * Reply codes.
86 #define PRELIM 1 /* positive preliminary */
87 #define COMPLETE 2 /* positive completion */
88 #define CONTINUE 3 /* positive intermediate */
89 #define TRANSIENT 4 /* transient negative completion */
90 #define ERROR 5 /* permanent negative completion */
92 /* command wait_flag: */
93 #define NONE 0x00
94 #define WAIT_REPLY 0x01
95 #define WANT_STRING 0x02
96 static char reply_str [80];
98 static struct vfs_class vfs_fish_ops;
100 static int
101 fish_command (struct vfs_class *me, struct vfs_s_super *super,
102 int wait_reply, const char *fmt, ...)
103 __attribute__ ((format (__printf__, 4, 5)));
105 static int fish_decode_reply (char *s, int was_garbage)
107 int code;
108 if (!sscanf(s, "%d", &code)) {
109 code = 500;
110 return 5;
112 if (code<100) return was_garbage ? ERROR : (!code ? COMPLETE : PRELIM);
113 return code / 100;
116 /* Returns a reply code, check /usr/include/arpa/ftp.h for possible values */
117 static int fish_get_reply (struct vfs_class *me, int sock, char *string_buf, int string_len)
119 char answer[1024];
120 int was_garbage = 0;
122 for (;;) {
123 if (!vfs_s_get_line(me, sock, answer, sizeof(answer), '\n')) {
124 if (string_buf)
125 *string_buf = 0;
126 return 4;
129 if (strncmp(answer, "### ", 4)) {
130 was_garbage = 1;
131 if (string_buf)
132 g_strlcpy(string_buf, answer, string_len);
133 } else return fish_decode_reply(answer+4, was_garbage);
137 #define SUP super->u.fish
139 static int
140 fish_command (struct vfs_class *me, struct vfs_s_super *super,
141 int wait_reply, const char *fmt, ...)
143 va_list ap;
144 char *str;
145 int status;
146 FILE *logfile = MEDATA->logfile;
148 va_start (ap, fmt);
150 str = g_strdup_vprintf (fmt, ap);
151 va_end (ap);
153 if (logfile) {
154 fwrite (str, strlen (str), 1, logfile);
155 fflush (logfile);
158 enable_interrupt_key ();
160 status = write (SUP.sockw, str, strlen (str));
161 g_free (str);
163 disable_interrupt_key ();
164 if (status < 0)
165 return TRANSIENT;
167 if (wait_reply)
168 return fish_get_reply (me, SUP.sockr,
169 (wait_reply & WANT_STRING) ? reply_str :
170 NULL, sizeof (reply_str) - 1);
171 return COMPLETE;
174 static void
175 fish_free_archive (struct vfs_class *me, struct vfs_s_super *super)
177 if ((SUP.sockw != -1) || (SUP.sockr != -1)) {
178 print_vfs_message (_("fish: Disconnecting from %s"),
179 super->name ? super->name : "???");
180 fish_command (me, super, NONE, "#BYE\nexit\n");
181 close (SUP.sockw);
182 close (SUP.sockr);
183 SUP.sockw = SUP.sockr = -1;
185 g_free (SUP.host);
186 g_free (SUP.user);
187 g_free (SUP.cwdir);
188 g_free (SUP.password);
191 static void
192 fish_pipeopen(struct vfs_s_super *super, const char *path, const char *argv[])
194 int fileset1[2], fileset2[2];
195 int res;
197 if ((pipe(fileset1)<0) || (pipe(fileset2)<0))
198 vfs_die("Cannot pipe(): %m.");
200 if ((res = fork())) {
201 if (res<0) vfs_die("Cannot fork(): %m.");
202 /* We are the parent */
203 close(fileset1[0]);
204 SUP.sockw = fileset1[1];
205 close(fileset2[1]);
206 SUP.sockr = fileset2[0];
207 } else {
208 close(0);
209 dup(fileset1[0]);
210 close(fileset1[0]); close(fileset1[1]);
211 close(1); close(2);
212 dup(fileset2[1]);
213 /* stderr to /dev/null */
214 open ("/dev/null", O_WRONLY);
215 close(fileset2[0]); close(fileset2[1]);
216 execvp(path, const_cast(char **, argv));
217 _exit(3);
221 /* The returned directory should always contain a trailing slash */
222 static char *fish_getcwd(struct vfs_class *me, struct vfs_s_super *super)
224 if (fish_command (me, super, WANT_STRING, "#PWD\npwd; echo '### 200'\n") == COMPLETE)
225 return g_strconcat (reply_str, "/", (char *) NULL);
226 ERRNOR (EIO, NULL);
229 static int
230 fish_open_archive_int (struct vfs_class *me, struct vfs_s_super *super)
233 char gbuf[10];
234 const char *argv[10]; /* All of 10 is used now */
235 const char *xsh = (SUP.flags == FISH_FLAG_RSH ? "rsh" : "ssh");
236 int i = 0;
238 argv[i++] = xsh;
239 if (SUP.flags == FISH_FLAG_COMPRESSED)
240 argv[i++] = "-C";
242 if (SUP.flags > FISH_FLAG_RSH)
244 argv[i++] = "-p";
245 g_snprintf (gbuf, sizeof (gbuf), "%d", SUP.flags);
246 argv[i++] = gbuf;
249 argv[i++] = "-l";
250 argv[i++] = SUP.user;
251 argv[i++] = SUP.host;
252 argv[i++] = "echo FISH:; /bin/sh";
253 argv[i++] = NULL;
255 fish_pipeopen (super, xsh, argv);
258 char answer[2048];
259 print_vfs_message (_("fish: Waiting for initial line..."));
260 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
261 ERRNOR (E_PROTO, -1);
262 print_vfs_message ("%s", answer);
263 if (strstr (answer, "assword")) {
265 /* Currently, this does not work. ssh reads passwords from
266 /dev/tty, not from stdin :-(. */
268 message (D_ERROR, MSG_ERROR,
270 ("Sorry, we cannot do password authenticated connections for now."));
271 ERRNOR (EPERM, -1);
272 if (!SUP.password) {
273 char *p, *op;
274 p = g_strconcat (_(" fish: Password required for "),
275 SUP.user, " ", (char *) NULL);
276 op = vfs_get_password (p);
277 g_free (p);
278 if (op == NULL)
279 ERRNOR (EPERM, -1);
280 SUP.password = op;
282 print_vfs_message (_("fish: Sending password..."));
283 write (SUP.sockw, SUP.password, strlen (SUP.password));
284 write (SUP.sockw, "\n", 1);
288 print_vfs_message (_("fish: Sending initial line..."));
290 * Run `start_fish_server'. If it doesn't exist - no problem,
291 * we'll talk directly to the shell.
293 if (fish_command
294 (me, super, WAIT_REPLY,
295 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
296 COMPLETE)
297 ERRNOR (E_PROTO, -1);
299 print_vfs_message (_("fish: Handshaking version..."));
300 if (fish_command
301 (me, super, WAIT_REPLY,
302 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
303 ERRNOR (E_PROTO, -1);
305 /* Set up remote locale to C, otherwise dates cannot be recognized */
306 if (fish_command
307 (me, super, WAIT_REPLY,
308 "LANG=C; LC_ALL=C; LC_TIME=C\n"
309 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
310 != COMPLETE)
311 ERRNOR (E_PROTO, -1);
313 print_vfs_message (_("fish: Setting up current directory..."));
314 SUP.cwdir = fish_getcwd (me, super);
315 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
316 #if 0
317 super->name =
318 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
319 #endif
320 super->name = g_strdup (PATH_SEP_STR);
322 super->root =
323 vfs_s_new_inode (me, super,
324 vfs_s_default_stat (me, S_IFDIR | 0755));
325 return 0;
328 static int
329 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
330 const char *archive_name, char *op)
332 char *host, *user, *password, *p;
333 int flags;
335 (void) archive_name;
337 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
338 &password, 0, URL_NOSLASH);
340 g_free (p);
342 SUP.host = host;
343 SUP.user = user;
344 SUP.flags = flags;
345 if (!strncmp (op, "rsh:", 4))
346 SUP.flags = FISH_FLAG_RSH;
347 SUP.cwdir = NULL;
348 if (password)
349 SUP.password = password;
350 return fish_open_archive_int (me, super);
353 static int
354 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
355 const char *archive_name, char *op, void *cookie)
357 char *host, *user;
358 int flags;
360 (void) me;
361 (void) archive_name;
362 (void) cookie;
364 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
365 URL_NOSLASH);
367 g_free (op);
369 flags = ((strcmp (host, SUP.host) == 0)
370 && (strcmp (user, SUP.user) == 0) && (flags == SUP.flags));
371 g_free (host);
372 g_free (user);
374 return flags;
377 static int
378 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
380 struct vfs_s_super *super = dir->super;
381 char buffer[8192];
382 struct vfs_s_entry *ent = NULL;
383 FILE *logfile;
384 char *quoted_path;
385 int reply_code;
386 gchar *shell_commands;
388 #if 0
390 * Simple FISH debug interface :]
392 if (!(MEDATA->logfile))
394 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
396 #endif /* 0 */
398 logfile = MEDATA->logfile;
400 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
402 gettimeofday(&dir->timestamp, NULL);
403 dir->timestamp.tv_sec += fish_directory_timeout;
404 quoted_path = strutils_shell_escape (remote_path);
405 shell_commands = g_strconcat(
406 "#LIST /%s\n"
407 "if `perl -v > /dev/null 2>&1` ; then\n"
408 "perl -e '\n"
409 "use strict;\n"
410 "use POSIX;\n"
411 "use Fcntl;\n"
412 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
413 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
414 "my $dirname = $ARGV[0];\n"
415 "if (opendir ( DIR, $dirname )) {\n"
416 "while( (my $filename = readdir(DIR))){\n"
417 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
418 "my $mloctime= scalar localtime $mtime;\n"
420 "my $strutils_shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
421 "my $e_filename = $filename;\n"
422 "$e_filename =~ $strutils_shell_escape_regex;\n"
423 "if (S_ISLNK($mode) ) {\n"
424 "my $linkname = readlink (\"$dirname/$filename\");\n"
425 "$linkname =~ $strutils_shell_escape_regex;\n"
426 "\n"
427 "printf(\"R%%o %%o $uid.$gid\\n"
428 "S$size\\n"
429 "d$mloctime\\n"
430 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
431 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
432 "} else {\n"
433 "printf(\"R%%o %%o $uid.$gid\\n"
434 "S$size\\n"
435 "d$mloctime\\n"
436 ":\\\"$e_filename\\\"\\n"
437 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
438 "}}\n"
440 "printf(\"### 200\\n\");\n"
441 "closedir(DIR);\n"
442 "} else {\n"
443 "printf(\"### 500\\n\");\n"
444 "}\n"
445 "exit 0\n"
446 "' /%s ||\n" /* ARGV[0] - path to browse */
447 " echo '### 500'\n" /* do not hang if perl is to eval it */
448 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
449 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
450 "LSOPT=\"-Qlan\";\n"
451 "ADD=0;\n"
452 "else\n"
453 "LSOPT=\"-lan\";\n"
454 "ADD=1;\n"
455 "fi\n"
456 "ls $LSOPT /%s 2>/dev/null | grep '^[^cbt]' | (\n"
457 "while read p l u g s m d y n; do\n"
458 "if [ $ADD = 0 ]; then\n"
459 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
460 "elif `sed --version >/dev/null 2>&1` ; then\n"
461 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
463 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
464 "else\n"
465 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
466 "fi\n"
467 "done )\n"
468 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
469 "while read p l u g a i m d y n; do\n"
470 "if [ $ADD = 0 ]; then\n"
471 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
472 "elif `sed --version >/dev/null 2>&1` ; then\n"
473 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
474 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
475 "else\n"
476 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
477 "fi\n"
478 "done)\n"
479 "echo '### 200'\n"
480 "else\n"
481 "echo '### 500'\n"
482 "fi\n"
484 NULL
487 fish_command (me, super, NONE, shell_commands,
488 quoted_path, quoted_path, quoted_path, quoted_path, quoted_path, quoted_path);
490 g_free(shell_commands);
491 g_free (quoted_path);
492 ent = vfs_s_generate_entry(me, NULL, dir, 0);
493 while (1) {
494 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
495 if ((!res) || (res == EINTR)) {
496 vfs_s_free_entry(me, ent);
497 me->verrno = ECONNRESET;
498 goto error;
500 if (logfile) {
501 fputs (buffer, logfile);
502 fputs ("\n", logfile);
503 fflush (logfile);
505 if (!strncmp(buffer, "### ", 4))
506 break;
507 if ((!buffer[0])) {
508 if (ent->name) {
509 vfs_s_insert_entry(me, dir, ent);
510 ent = vfs_s_generate_entry(me, NULL, dir, 0);
512 continue;
515 #define ST ent->ino->st
517 switch(buffer[0]) {
518 case ':': {
519 char *temp;
520 char *data_start = buffer+1;
521 char *filename = data_start;
522 char *linkname = data_start;
523 char *filename_bound = filename + strlen(filename);
524 char *linkname_bound = filename_bound;
525 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
526 break; /* We'll do "." and ".." ourselves */
528 if (S_ISLNK(ST.st_mode)) {
529 /* we expect: "escaped-name" -> "escaped-name"
530 // -> cannot occur in filenames,
531 // because it will be escaped to -\> */
533 if (*filename == '"')
534 ++filename;
536 linkname = strstr(filename, "\" -> \"");
537 if (!linkname)
539 /* broken client, or smth goes wrong */
540 linkname = filename_bound;
541 if (filename_bound > filename
542 && *(filename_bound - 1) == '"')
543 --filename_bound; /* skip trailing " */
545 else
547 filename_bound = linkname;
548 linkname += 6; /* strlen ("\" -> \"") */
549 if (*(linkname_bound - 1) == '"')
550 --linkname_bound; /* skip trailing " */
553 ent->name = str_dup_range(filename, filename_bound);
554 temp = ent->name;
555 ent->name = strutils_shell_unescape(ent->name);
556 g_free(temp);
558 ent->ino->linkname = str_dup_range(linkname, linkname_bound);
559 temp = ent->ino->linkname;
560 ent->ino->linkname = strutils_shell_unescape(ent->ino->linkname);
561 g_free(temp);
562 } else {
563 /* we expect: "escaped-name" */
564 if (filename_bound - filename > 2)
567 there is at least 2 "
568 and we skip them
570 if (*filename == '"')
571 ++filename;
572 if (*(filename_bound - 1) == '"')
573 --filename_bound;
575 ent->name = str_dup_range(filename, filename_bound);
576 temp = ent->name;
577 ent->name = strutils_shell_unescape(ent->name);
578 g_free(temp);
580 break;
582 case 'S':
583 #ifdef HAVE_ATOLL
584 ST.st_size = (off_t) atoll (buffer+1);
585 #else
586 ST.st_size = (off_t) atof (buffer+1);
587 #endif
588 break;
589 case 'P': {
590 size_t skipped;
591 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
592 break;
594 case 'R': {
596 raw filemode:
597 we expect: Roctal-filemode octal-filetype uid.gid
599 size_t skipped;
600 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
601 break;
603 case 'd': {
604 vfs_split_text(buffer+1);
605 if (!vfs_parse_filedate(0, &ST.st_ctime))
606 break;
607 ST.st_atime = ST.st_mtime = ST.st_ctime;
609 break;
610 case 'D': {
611 struct tm tim;
612 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
613 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
614 break;
615 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
617 break;
618 case 'E': {
619 int maj, min;
620 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
621 break;
622 #ifdef HAVE_STRUCT_STAT_ST_RDEV
623 ST.st_rdev = makedev (maj, min);
624 #endif
629 vfs_s_free_entry (me, ent);
630 reply_code = fish_decode_reply(buffer + 4, 0);
631 if (reply_code == COMPLETE) {
632 g_free (SUP.cwdir);
633 SUP.cwdir = g_strdup (remote_path);
634 print_vfs_message (_("%s: done."), me->name);
635 return 0;
636 } else if (reply_code == ERROR) {
637 me->verrno = EACCES;
638 } else {
639 me->verrno = E_REMOTE;
642 error:
643 print_vfs_message (_("%s: failure"), me->name);
644 return -1;
647 static int
648 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
650 struct vfs_s_super *super = FH_SUPER;
651 int n, total;
652 char buffer[8192];
653 struct stat s;
654 int was_error = 0;
655 int h;
656 char *quoted_name;
658 h = open (localname, O_RDONLY);
660 if (h == -1)
661 ERRNOR (EIO, -1);
662 if (fstat(h, &s)<0) {
663 close (h);
664 ERRNOR (EIO, -1);
667 /* First, try this as stor:
669 * ( head -c number ) | ( cat > file; cat >/dev/null )
671 * If `head' is not present on the remote system, `dd' will be used.
672 * Unfortunately, we cannot trust most non-GNU `head' implementations
673 * even if `-c' options is supported. Therefore, we separate GNU head
674 * (and other modern heads?) using `-q' and `-' . This causes another
675 * implementations to fail (because of "incorrect options").
677 * Fallback is:
679 * rest=<number>
680 * while [ $rest -gt 0 ]
681 * do
682 * cnt=`expr \( $rest + 255 \) / 256`
683 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
684 * rest=`expr $rest - $n`
685 * done
687 * `dd' was not designed for full filling of input buffers,
688 * and does not report exact number of bytes (not blocks).
689 * Therefore a more complex shell script is needed.
691 * On some systems non-GNU head writes "Usage:" error report to stdout
692 * instead of stderr. It makes impossible the use of "head || dd"
693 * algorithm for file appending case, therefore just "dd" is used for it.
696 quoted_name = strutils_shell_escape(name);
697 print_vfs_message(_("fish: store %s: sending command..."), quoted_name );
699 /* FIXME: File size is limited to ULONG_MAX */
700 if (!fh->u.fish.append)
701 n = fish_command (me, super, WAIT_REPLY,
702 "#STOR %lu /%s\n"
703 "echo '### 001'\n"
704 "file=/%s\n"
705 "res=`exec 3>&1\n"
706 "(\n"
707 "head -c %lu -q - || echo DD >&3\n"
708 ") 2>/dev/null | (\n"
709 "cat > $file\n"
710 "cat > /dev/null\n"
711 ")`; [ \"$res\" = DD ] && {\n"
712 "> \"$file\"\n"
713 "rest=%lu\n"
714 "while [ $rest -gt 0 ]\n"
715 "do\n"
716 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
717 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
718 " rest=`expr $rest - $n`\n"
719 "done\n"
720 "}; echo '### 200'\n",
721 (unsigned long) s.st_size, quoted_name,
722 quoted_name, (unsigned long) s.st_size,
723 (unsigned long) s.st_size);
724 else
725 n = fish_command (me, super, WAIT_REPLY,
726 "#STOR %lu /%s\n"
727 "echo '### 001'\n"
728 "{\n"
729 "file=/%s\n"
730 "rest=%lu\n"
731 "while [ $rest -gt 0 ]\n"
732 "do\n"
733 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
734 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
735 " rest=`expr $rest - $n`\n"
736 "done\n"
737 "}; echo '### 200'\n",
738 (unsigned long) s.st_size, quoted_name,
739 quoted_name, (unsigned long) s.st_size);
741 if (n != PRELIM) {
742 close (h);
743 ERRNOR(E_REMOTE, -1);
745 total = 0;
747 while (1) {
748 int t;
749 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
750 if ((errno == EINTR) && got_interrupt())
751 continue;
752 print_vfs_message(_("fish: Local read failed, sending zeros") );
753 close(h);
754 h = open( "/dev/zero", O_RDONLY );
756 if (n == 0)
757 break;
758 if ((t = write (SUP.sockw, buffer, n)) != n) {
759 if (t == -1) {
760 me->verrno = errno;
761 } else {
762 me->verrno = EIO;
764 goto error_return;
766 disable_interrupt_key();
767 total += n;
768 print_vfs_message(_("fish: storing %s %d (%lu)"),
769 was_error ? _("zeros") : _("file"), total,
770 (unsigned long) s.st_size);
772 close(h);
773 g_free(quoted_name);
774 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
775 ERRNOR (E_REMOTE, -1);
776 return 0;
777 error_return:
778 close(h);
779 fish_get_reply(me, SUP.sockr, NULL, 0);
780 g_free(quoted_name);
781 return -1;
784 static int
785 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
787 char *name;
788 char *quoted_name;
789 if (offset)
790 ERRNOR (E_NOTSUPP, 0);
791 name = vfs_s_fullpath (me, fh->ino);
792 if (!name)
793 return 0;
794 quoted_name = strutils_shell_escape(name);
795 fh->u.fish.append = 0;
798 * Check whether the remote file is readable by using `dd' to copy
799 * a single byte from the remote file to /dev/null. If `dd' completes
800 * with exit status of 0 use `cat' to send the file contents to the
801 * standard output (i.e. over the network).
803 offset = fish_command (me, FH_SUPER, WANT_STRING,
804 "#RETR /%s\n"
805 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
806 "then\n"
807 "ls -ln /%s 2>/dev/null | (\n"
808 "read p l u g s r\n"
809 "echo $s\n"
810 ")\n"
811 "echo '### 100'\n"
812 "cat /%s\n"
813 "echo '### 200'\n"
814 "else\n"
815 "echo '### 500'\n"
816 "fi\n",
817 quoted_name, quoted_name, quoted_name, quoted_name );
818 g_free (quoted_name);
819 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
820 fh->linear = LS_LINEAR_OPEN;
821 fh->u.fish.got = 0;
822 errno = 0;
823 #if SIZEOF_OFF_T == SIZEOF_LONG
824 fh->u.fish.total = strtol (reply_str, NULL, 10);
825 #else
826 fh->u.fish.total = strtoll (reply_str, NULL, 10);
827 #endif
828 if (errno != 0)
829 ERRNOR (E_REMOTE, 0);
830 return 1;
833 static void
834 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
836 struct vfs_s_super *super = FH_SUPER;
837 char buffer[8192];
838 int n;
840 print_vfs_message( _("Aborting transfer...") );
841 do {
842 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
843 if (n) {
844 if ((n = read(SUP.sockr, buffer, n)) < 0)
845 return;
846 fh->u.fish.got += n;
848 } while (n);
850 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
851 print_vfs_message( _("Error reported after abort.") );
852 else
853 print_vfs_message( _("Aborted transfer would be successful.") );
856 static int
857 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
859 struct vfs_s_super *super = FH_SUPER;
860 int n = 0;
861 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
862 disable_interrupt_key();
863 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
864 if ((errno == EINTR) && !got_interrupt())
865 continue;
866 break;
868 enable_interrupt_key();
870 if (n>0) fh->u.fish.got += n;
871 if (n<0) fish_linear_abort(me, fh);
872 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
873 ERRNOR (E_REMOTE, -1);
874 ERRNOR (errno, n);
877 static void
878 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
880 if (fh->u.fish.total != fh->u.fish.got)
881 fish_linear_abort(me, fh);
884 static int
885 fish_ctl (void *fh, int ctlop, void *arg)
887 (void) arg;
888 (void) fh;
889 (void) ctlop;
890 return 0;
891 #if 0
892 switch (ctlop) {
893 case VFS_CTL_IS_NOTREADY:
895 int v;
897 if (!FH->linear)
898 vfs_die ("You may not do this");
899 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
900 return 0;
902 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
903 if (((v < 0) && (errno == EINTR)) || v == 0)
904 return 1;
905 return 0;
907 default:
908 return 0;
910 #endif
913 static int
914 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
916 int r;
918 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
919 vfs_stamp_create (&vfs_fish_ops, super);
920 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
921 if (flags & OPT_FLUSH)
922 vfs_s_invalidate(me, super);
923 return 0;
926 #define PREFIX \
927 char buf[BUF_LARGE]; \
928 const char *crpath; \
929 char *rpath, *mpath = g_strdup (path); \
930 struct vfs_s_super *super; \
931 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
932 g_free (mpath); \
933 return -1; \
935 rpath = strutils_shell_escape(crpath); \
936 g_free (mpath);
938 #define POSTFIX(flags) \
939 g_free (rpath); \
940 return fish_send_command(me, super, buf, flags);
942 static int
943 fish_chmod (struct vfs_class *me, const char *path, int mode)
945 PREFIX
946 g_snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
947 "chmod %4.4o /%s 2>/dev/null\n"
948 "echo '### 000'\n",
949 mode & 07777, rpath,
950 mode & 07777, rpath);
951 POSTFIX(OPT_FLUSH);
954 #define FISH_OP(name, string) \
955 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
957 char buf[BUF_LARGE]; \
958 const char *crpath1, *crpath2; \
959 char *rpath1, *rpath2, *mpath1, *mpath2; \
960 struct vfs_s_super *super1, *super2; \
961 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = g_strdup(path1), &super1, 0))) { \
962 g_free (mpath1); \
963 return -1; \
965 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = g_strdup(path2), &super2, 0))) { \
966 g_free (mpath1); \
967 g_free (mpath2); \
968 return -1; \
970 rpath1 = strutils_shell_escape (crpath1); \
971 g_free (mpath1); \
972 rpath2 = strutils_shell_escape (crpath2); \
973 g_free (mpath2); \
974 g_snprintf(buf, sizeof(buf), string "\n", rpath1, rpath2, rpath1, rpath2); \
975 g_free (rpath1); \
976 g_free (rpath2); \
977 return fish_send_command(me, super2, buf, OPT_FLUSH); \
980 FISH_OP(rename, "#RENAME /%s /%s\n"
981 "mv /%s /%s 2>/dev/null\n"
982 "echo '### 000'" )
983 FISH_OP(link, "#LINK /%s /%s\n"
984 "ln /%s /%s 2>/dev/null\n"
985 "echo '### 000'" )
987 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
989 char *qsetto;
990 PREFIX
991 qsetto = strutils_shell_escape (setto);
992 g_snprintf(buf, sizeof(buf),
993 "#SYMLINK %s /%s\n"
994 "ln -s %s /%s 2>/dev/null\n"
995 "echo '### 000'\n",
996 qsetto, rpath, qsetto, rpath);
997 g_free (qsetto);
998 POSTFIX(OPT_FLUSH);
1001 static int
1002 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
1004 char *sowner, *sgroup;
1005 struct passwd *pw;
1006 struct group *gr;
1008 if ((pw = getpwuid (owner)) == NULL)
1009 return 0;
1011 if ((gr = getgrgid (group)) == NULL)
1012 return 0;
1014 sowner = pw->pw_name;
1015 sgroup = gr->gr_name;
1017 PREFIX
1018 g_snprintf (buf, sizeof(buf),
1019 "#CHOWN %s /%s\n"
1020 "chown %s /%s 2>/dev/null\n"
1021 "echo '### 000'\n",
1022 sowner, rpath,
1023 sowner, rpath);
1024 fish_send_command (me, super, buf, OPT_FLUSH);
1025 /* FIXME: what should we report if chgrp succeeds but chown fails? */
1026 g_snprintf (buf, sizeof(buf),
1027 "#CHGRP /%s /%s\n"
1028 "chgrp %s /%s 2>/dev/null\n"
1029 "echo '### 000'\n",
1030 sgroup, rpath,
1031 sgroup, rpath);
1032 /* fish_send_command(me, super, buf, OPT_FLUSH); */
1033 POSTFIX (OPT_FLUSH)
1037 static int fish_unlink (struct vfs_class *me, const char *path)
1039 PREFIX
1040 g_snprintf(buf, sizeof(buf),
1041 "#DELE /%s\n"
1042 "rm -f /%s 2>/dev/null\n"
1043 "echo '### 000'\n",
1044 rpath, rpath);
1045 POSTFIX(OPT_FLUSH);
1048 static int fish_exists (struct vfs_class *me, const char *path)
1050 int ret_code;
1052 PREFIX
1054 g_snprintf(buf, sizeof(buf),
1055 "#ISEXISTS /%s\n"
1056 "ls -l /%s >/dev/null 2>/dev/null\n"
1057 "echo '### '$?\n",
1058 rpath, rpath);
1060 g_free (rpath);
1062 if ( fish_send_command(me, super, buf, OPT_FLUSH) == 0 )
1063 return 1;
1065 return 0;
1069 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1071 int ret_code;
1073 PREFIX
1075 (void) mode;
1077 g_snprintf(buf, sizeof(buf),
1078 "#MKD /%s\n"
1079 "mkdir /%s 2>/dev/null\n"
1080 "echo '### 000'\n",
1081 rpath, rpath);
1083 g_free (rpath);
1084 ret_code = fish_send_command(me, super, buf, OPT_FLUSH);
1086 if ( ret_code != 0 )
1087 return ret_code;
1089 if ( ! fish_exists (me, path) ){
1090 ERRNOR (EACCES, -1);
1092 return 0;
1095 static int fish_rmdir (struct vfs_class *me, const char *path)
1097 PREFIX
1098 g_snprintf(buf, sizeof(buf),
1099 "#RMD /%s\n"
1100 "rmdir /%s 2>/dev/null\n"
1101 "echo '### 000'\n",
1102 rpath, rpath);
1103 POSTFIX(OPT_FLUSH);
1106 static int
1107 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1108 int mode)
1110 (void) mode;
1112 fh->u.fish.append = 0;
1113 /* File will be written only, so no need to retrieve it */
1114 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1115 fh->u.fish.append = flags & O_APPEND;
1116 if (!fh->ino->localname) {
1117 int tmp_handle =
1118 vfs_mkstemps (&fh->ino->localname, me->name,
1119 fh->ino->ent->name);
1120 if (tmp_handle == -1)
1121 return -1;
1122 close (tmp_handle);
1124 return 0;
1126 if (!fh->ino->localname)
1127 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1128 return -1;
1129 if (!fh->ino->localname)
1130 vfs_die ("retrieve_file failed to fill in localname");
1131 return 0;
1134 static void
1135 fish_fill_names (struct vfs_class *me, fill_names_f func)
1137 struct vfs_s_super *super = MEDATA->supers;
1138 char *name;
1140 char gbuf[10];
1142 while (super)
1144 const char *flags = "";
1145 switch (SUP.flags)
1147 case FISH_FLAG_RSH:
1148 flags = ":r";
1149 break;
1150 case FISH_FLAG_COMPRESSED:
1151 flags = ":C";
1152 break;
1153 default:
1154 if (SUP.flags > FISH_FLAG_RSH)
1156 break;
1157 g_snprintf (gbuf, sizeof (gbuf), ":%d", SUP.flags);
1158 flags = gbuf;
1160 break;
1163 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1164 "/", SUP.cwdir, (char *) NULL);
1165 (*func)(name);
1166 g_free (name);
1167 super = super->next;
1171 static void *
1172 fish_open (struct vfs_class *me, const char *file, int flags, int mode)
1175 sorry, i've places hack here
1176 cause fish don't able to open files with O_EXCL flag
1178 flags &= ~O_EXCL;
1179 return vfs_s_open (me, file, flags, mode);
1183 void
1184 init_fish (void)
1186 static struct vfs_s_subclass fish_subclass;
1188 fish_subclass.flags = VFS_S_REMOTE;
1189 fish_subclass.archive_same = fish_archive_same;
1190 fish_subclass.open_archive = fish_open_archive;
1191 fish_subclass.free_archive = fish_free_archive;
1192 fish_subclass.fh_open = fish_fh_open;
1193 fish_subclass.dir_load = fish_dir_load;
1194 fish_subclass.file_store = fish_file_store;
1195 fish_subclass.linear_start = fish_linear_start;
1196 fish_subclass.linear_read = fish_linear_read;
1197 fish_subclass.linear_close = fish_linear_close;
1199 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1200 vfs_fish_ops.name = "fish";
1201 vfs_fish_ops.prefix = "sh:";
1202 vfs_fish_ops.fill_names = fish_fill_names;
1203 vfs_fish_ops.chmod = fish_chmod;
1204 vfs_fish_ops.chown = fish_chown;
1205 vfs_fish_ops.open = fish_open;
1206 vfs_fish_ops.symlink = fish_symlink;
1207 vfs_fish_ops.link = fish_link;
1208 vfs_fish_ops.unlink = fish_unlink;
1209 vfs_fish_ops.rename = fish_rename;
1210 vfs_fish_ops.mkdir = fish_mkdir;
1211 vfs_fish_ops.rmdir = fish_rmdir;
1212 vfs_fish_ops.ctl = fish_ctl;
1213 vfs_register_class (&vfs_fish_ops);