merged mc-4.6
[midnight-commander.git] / vfs / fish.c
blob1d53230d6fdfe4da20ecbffacfd72661de14d4b7
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. */
27 * Read README.fish for protocol specification.
29 * Syntax of path is: /#sh:user@host[:Cr]/path
30 * where C means you want compressed connection,
31 * and r means you want to use rsh
33 * Namespace: fish_vfs_ops exported.
36 /* Define this if your ssh can take -I option */
38 #include <config.h>
40 #include <errno.h>
42 #include <mhl/string.h>
44 #include "../src/global.h"
45 #include "../src/tty.h" /* enable/disable interrupt key */
46 #include "../src/wtools.h" /* message() */
47 #include "../src/main.h" /* print_vfs_message */
48 #include "utilvfs.h"
49 #include "xdirentry.h"
50 #include "vfs.h"
51 #include "vfs-impl.h"
52 #include "gc.h" /* vfs_stamp_create */
53 #include "tcputil.h"
54 #include "../src/unixcompat.h"
55 #include "fish.h"
56 #include "../mhl/memory.h"
57 #include "../mhl/string.h"
58 #include "../mhl/escape.h"
60 int fish_directory_timeout = 900;
62 #define DO_RESOLVE_SYMLINK 1
63 #define DO_OPEN 2
64 #define DO_FREE_RESOURCE 4
66 #define FISH_FLAG_COMPRESSED 1
67 #define FISH_FLAG_RSH 2
69 #define OPT_FLUSH 1
70 #define OPT_IGNORE_ERROR 2
73 * Reply codes.
75 #define PRELIM 1 /* positive preliminary */
76 #define COMPLETE 2 /* positive completion */
77 #define CONTINUE 3 /* positive intermediate */
78 #define TRANSIENT 4 /* transient negative completion */
79 #define ERROR 5 /* permanent negative completion */
81 /* command wait_flag: */
82 #define NONE 0x00
83 #define WAIT_REPLY 0x01
84 #define WANT_STRING 0x02
85 static char reply_str [80];
87 static struct vfs_class vfs_fish_ops;
89 static int
90 fish_command (struct vfs_class *me, struct vfs_s_super *super,
91 int wait_reply, const char *fmt, ...)
92 __attribute__ ((format (__printf__, 4, 5)));
94 static int fish_decode_reply (char *s, int was_garbage)
96 int code;
97 if (!sscanf(s, "%d", &code)) {
98 code = 500;
99 return 5;
101 if (code<100) return was_garbage ? ERROR : (!code ? COMPLETE : PRELIM);
102 return code / 100;
105 /* Returns a reply code, check /usr/include/arpa/ftp.h for possible values */
106 static int fish_get_reply (struct vfs_class *me, int sock, char *string_buf, int string_len)
108 char answer[1024];
109 int was_garbage = 0;
111 for (;;) {
112 if (!vfs_s_get_line(me, sock, answer, sizeof(answer), '\n')) {
113 if (string_buf)
114 *string_buf = 0;
115 return 4;
118 if (strncmp(answer, "### ", 4)) {
119 was_garbage = 1;
120 if (string_buf)
121 g_strlcpy(string_buf, answer, string_len);
122 } else return fish_decode_reply(answer+4, was_garbage);
126 #define SUP super->u.fish
128 static int
129 fish_command (struct vfs_class *me, struct vfs_s_super *super,
130 int wait_reply, const char *fmt, ...)
132 va_list ap;
133 char *str;
134 int status;
135 FILE *logfile = MEDATA->logfile;
137 va_start (ap, fmt);
139 str = g_strdup_vprintf (fmt, ap);
140 va_end (ap);
142 if (logfile) {
143 fwrite (str, strlen (str), 1, logfile);
144 fflush (logfile);
147 enable_interrupt_key ();
149 status = write (SUP.sockw, str, strlen (str));
150 mhl_mem_free (str);
152 disable_interrupt_key ();
153 if (status < 0)
154 return TRANSIENT;
156 if (wait_reply)
157 return fish_get_reply (me, SUP.sockr,
158 (wait_reply & WANT_STRING) ? reply_str :
159 NULL, sizeof (reply_str) - 1);
160 return COMPLETE;
163 static void
164 fish_free_archive (struct vfs_class *me, struct vfs_s_super *super)
166 if ((SUP.sockw != -1) || (SUP.sockr != -1)) {
167 print_vfs_message (_("fish: Disconnecting from %s"),
168 super->name ? super->name : "???");
169 fish_command (me, super, NONE, "#BYE\nexit\n");
170 close (SUP.sockw);
171 close (SUP.sockr);
172 SUP.sockw = SUP.sockr = -1;
174 mhl_mem_free (SUP.host);
175 mhl_mem_free (SUP.user);
176 mhl_mem_free (SUP.cwdir);
177 mhl_mem_free (SUP.password);
180 static void
181 fish_pipeopen(struct vfs_s_super *super, const char *path, const char *argv[])
183 int fileset1[2], fileset2[2];
184 int res;
186 if ((pipe(fileset1)<0) || (pipe(fileset2)<0))
187 vfs_die("Cannot pipe(): %m.");
189 if ((res = fork())) {
190 if (res<0) vfs_die("Cannot fork(): %m.");
191 /* We are the parent */
192 close(fileset1[0]);
193 SUP.sockw = fileset1[1];
194 close(fileset2[1]);
195 SUP.sockr = fileset2[0];
196 } else {
197 close(0);
198 dup(fileset1[0]);
199 close(fileset1[0]); close(fileset1[1]);
200 close(1); close(2);
201 dup(fileset2[1]);
202 /* stderr to /dev/null */
203 open ("/dev/null", O_WRONLY);
204 close(fileset2[0]); close(fileset2[1]);
205 execvp(path, const_cast(char **, argv));
206 _exit(3);
210 /* The returned directory should always contain a trailing slash */
211 static char *fish_getcwd(struct vfs_class *me, struct vfs_s_super *super)
213 if (fish_command (me, super, WANT_STRING, "#PWD\npwd; echo '### 200'\n") == COMPLETE)
214 return g_strconcat (reply_str, "/", (char *) NULL);
215 ERRNOR (EIO, NULL);
218 static int
219 fish_open_archive_int (struct vfs_class *me, struct vfs_s_super *super)
222 char gbuf[10];
223 const char *argv[10]; /* All of 10 is used now */
224 const char *xsh = (SUP.flags == FISH_FLAG_RSH ? "rsh" : "ssh");
225 int i = 0;
227 argv[i++] = xsh;
228 if (SUP.flags == FISH_FLAG_COMPRESSED)
229 argv[i++] = "-C";
231 if (SUP.flags > FISH_FLAG_RSH)
233 argv[i++] = "-p";
234 snprintf (gbuf, sizeof (gbuf), "%d", SUP.flags);
235 argv[i++] = gbuf;
238 argv[i++] = "-l";
239 argv[i++] = SUP.user;
240 argv[i++] = SUP.host;
241 argv[i++] = "echo FISH:; /bin/sh";
242 argv[i++] = NULL;
244 fish_pipeopen (super, xsh, argv);
247 char answer[2048];
248 print_vfs_message (_("fish: Waiting for initial line..."));
249 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
250 ERRNOR (E_PROTO, -1);
251 print_vfs_message ("%s", answer);
252 if (strstr (answer, "assword")) {
254 /* Currently, this does not work. ssh reads passwords from
255 /dev/tty, not from stdin :-(. */
257 message (D_ERROR, MSG_ERROR,
259 ("Sorry, we cannot do password authenticated connections for now."));
260 ERRNOR (EPERM, -1);
261 if (!SUP.password) {
262 char *p, *op;
263 p = g_strconcat (_(" fish: Password required for "),
264 SUP.user, " ", (char *) NULL);
265 op = vfs_get_password (p);
266 mhl_mem_free (p);
267 if (op == NULL)
268 ERRNOR (EPERM, -1);
269 SUP.password = op;
271 print_vfs_message (_("fish: Sending password..."));
272 write (SUP.sockw, SUP.password, strlen (SUP.password));
273 write (SUP.sockw, "\n", 1);
277 print_vfs_message (_("fish: Sending initial line..."));
279 * Run `start_fish_server'. If it doesn't exist - no problem,
280 * we'll talk directly to the shell.
282 if (fish_command
283 (me, super, WAIT_REPLY,
284 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
285 COMPLETE)
286 ERRNOR (E_PROTO, -1);
288 print_vfs_message (_("fish: Handshaking version..."));
289 if (fish_command
290 (me, super, WAIT_REPLY,
291 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
292 ERRNOR (E_PROTO, -1);
294 /* Set up remote locale to C, otherwise dates cannot be recognized */
295 if (fish_command
296 (me, super, WAIT_REPLY,
297 "LANG=C; LC_ALL=C; LC_TIME=C\n"
298 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
299 != COMPLETE)
300 ERRNOR (E_PROTO, -1);
302 print_vfs_message (_("fish: Setting up current directory..."));
303 SUP.cwdir = fish_getcwd (me, super);
304 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
305 #if 0
306 super->name =
307 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
308 #endif
309 super->name = mhl_str_dup (PATH_SEP_STR);
311 super->root =
312 vfs_s_new_inode (me, super,
313 vfs_s_default_stat (me, S_IFDIR | 0755));
314 return 0;
317 static int
318 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
319 const char *archive_name, char *op)
321 char *host, *user, *password, *p;
322 int flags;
324 (void) archive_name;
326 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
327 &password, 0, URL_NOSLASH);
329 mhl_mem_free (p);
331 SUP.host = host;
332 SUP.user = user;
333 SUP.flags = flags;
334 if (!strncmp (op, "rsh:", 4))
335 SUP.flags = FISH_FLAG_RSH;
336 SUP.cwdir = NULL;
337 if (password)
338 SUP.password = password;
339 return fish_open_archive_int (me, super);
342 static int
343 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
344 const char *archive_name, char *op, void *cookie)
346 char *host, *user;
347 int flags;
349 (void) me;
350 (void) archive_name;
351 (void) cookie;
353 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
354 URL_NOSLASH);
356 mhl_mem_free (op);
358 flags = ((strcmp (host, SUP.host) == 0)
359 && (strcmp (user, SUP.user) == 0) && (flags == SUP.flags));
360 mhl_mem_free (host);
361 mhl_mem_free (user);
363 return flags;
366 static int
367 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
369 struct vfs_s_super *super = dir->super;
370 char buffer[8192];
371 struct vfs_s_entry *ent = NULL;
372 FILE *logfile;
373 SHELL_ESCAPED_STR quoted_path;
374 int reply_code;
376 #if 0
378 * Simple FISH debug interface :]
380 if (!(MEDATA->logfile))
382 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
384 #endif // 0
386 logfile = MEDATA->logfile;
388 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
390 gettimeofday(&dir->timestamp, NULL);
391 dir->timestamp.tv_sec += fish_directory_timeout;
392 quoted_path = mhl_shell_escape_dup (remote_path);
393 fish_command (me, super, NONE,
394 "#LIST /%s\n"
395 "if `perl -v > /dev/null 2>&1` ; then\n"
396 "perl -e '\n"
397 "use strict;\n"
398 "use POSIX;\n"
399 "use Fcntl;\n"
400 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
401 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
402 "my $dirname = $ARGV[0];\n"
403 "if (opendir ( DIR, $dirname )) {\n"
404 "while( (my $filename = readdir(DIR))){\n"
405 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
406 "my $mloctime= scalar localtime $mtime;\n"
407 "my $shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
408 "my $e_filename = $filename;\n"
409 "$e_filename =~ $shell_escape_regex;\n"
410 "if (S_ISLNK($mode) ) {\n"
411 "my $linkname = readlink (\"$dirname/$filename\");\n"
412 "$linkname =~ $shell_escape_regex;\n"
413 "\n"
414 "printf(\"R%%o %%o $uid.$gid\\n"
415 "S$size\\n"
416 "d$mloctime\\n"
417 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
418 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
419 "} else {\n"
420 "printf(\"R%%o %%o $uid.$gid\\n"
421 "S$size\\n"
422 "d$mloctime\\n"
423 ":\\\"$e_filename\\\"\\n"
424 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
425 "}}\n"
426 "printf(\"### 200\\n\");\n"
427 "closedir(DIR);\n"
428 "} else {\n"
429 "printf(\"### 500\\n\");\n"
430 "}\n"
431 "exit 0\n"
432 "' /%s ||\n" /* ARGV[0] - path to browse */
433 " echo '### 500'\n" /* do not hang if perl is to eval it */
434 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
435 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
436 "LSOPT=\"-Qlan\";\n"
437 "ADD=0;\n"
438 "else\n"
439 "LSOPT=\"-lan\";\n"
440 "ADD=1;\n"
441 "fi\n"
442 "ls $LSOPT \"/%s\" 2>/dev/null | grep '^[^cbt]' | (\n"
443 "while read p l u g s m d y n; do\n"
444 "if [ $ADD = 0 ]; then\n"
445 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
446 "elif `sed --version >/dev/null 2>&1` ; then\n"
447 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
448 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
449 "else\n"
450 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
451 "fi\n"
452 "done )\n"
453 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
454 "while read p l u g a i m d y n; do\n"
455 "if [ $ADD = 0 ]; then\n"
456 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
457 "elif `sed --version >/dev/null 2>&1` ; then\n"
458 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
459 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
460 "else\n"
461 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
462 "fi\n"
463 "done)\n"
464 "echo '### 200'\n"
465 "else\n"
466 "echo '### 500'\n"
467 "fi\n",
468 quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s);
469 mhl_mem_free (quoted_path.s);
470 ent = vfs_s_generate_entry(me, NULL, dir, 0);
471 while (1) {
472 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
473 if ((!res) || (res == EINTR)) {
474 vfs_s_free_entry(me, ent);
475 me->verrno = ECONNRESET;
476 goto error;
478 if (logfile) {
479 fputs (buffer, logfile);
480 fputs ("\n", logfile);
481 fflush (logfile);
483 if (!strncmp(buffer, "### ", 4))
484 break;
485 if ((!buffer[0])) {
486 if (ent->name) {
487 vfs_s_insert_entry(me, dir, ent);
488 ent = vfs_s_generate_entry(me, NULL, dir, 0);
490 continue;
493 #define ST ent->ino->st
495 switch(buffer[0]) {
496 case ':': {
497 char *data_start = buffer+1;
498 char *filename = data_start;
499 char *linkname = data_start;
500 char *filename_bound = filename + strlen(filename);
501 char *linkname_bound = filename_bound;
502 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
503 break; /* We'll do "." and ".." ourselves */
505 if (S_ISLNK(ST.st_mode)) {
506 // we expect: "escaped-name" -> "escaped-name"
507 // -> cannot occur in filenames,
508 // because it will be escaped to -\>
510 if (*filename == '"')
511 ++filename;
513 linkname = strstr(filename, "\" -> \"");
514 if (!linkname)
516 /* broken client, or smth goes wrong */
517 linkname = filename_bound;
518 if (filename_bound > filename
519 && *(filename_bound - 1) == '"')
520 --filename_bound; // skip trailing "
522 else
524 filename_bound = linkname;
525 linkname += 6; // strlen ("\" -> \"")
526 if (*(linkname_bound - 1) == '"')
527 --linkname_bound; // skip trailing "
530 ent->name = mhl_str_dup_range(filename, filename_bound);
531 mhl_shell_unescape_buf(ent->name);
533 ent->ino->linkname = mhl_str_dup_range(linkname, linkname_bound);
534 mhl_shell_unescape_buf(ent->ino->linkname);
535 } else {
536 // we expect: "escaped-name"
537 if (filename_bound - filename > 2)
539 // there is at least 2 "
540 // and we skip them
541 if (*filename == '"')
542 ++filename;
543 if (*(filename_bound - 1) == '"')
544 --filename_bound;
547 ent->name = mhl_str_dup_range(filename, filename_bound);
548 mhl_shell_unescape_buf(ent->name);
550 break;
552 case 'S':
553 #ifdef HAVE_ATOLL
554 ST.st_size = (off_t) atoll (buffer+1);
555 #else
556 ST.st_size = (off_t) atof (buffer+1);
557 #endif
558 break;
559 case 'P': {
560 size_t skipped;
561 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
562 break;
564 case 'R': {
565 // raw filemode:
566 // we expect: Roctal-filemode octal-filetype uid.gid
567 size_t skipped;
568 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
569 break;
571 case 'd': {
572 vfs_split_text(buffer+1);
573 if (!vfs_parse_filedate(0, &ST.st_ctime))
574 break;
575 ST.st_atime = ST.st_mtime = ST.st_ctime;
577 break;
578 case 'D': {
579 struct tm tim;
580 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
581 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
582 break;
583 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
585 break;
586 case 'E': {
587 int maj, min;
588 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
589 break;
590 #ifdef HAVE_STRUCT_STAT_ST_RDEV
591 ST.st_rdev = makedev (maj, min);
592 #endif
597 vfs_s_free_entry (me, ent);
598 reply_code = fish_decode_reply(buffer + 4, 0);
599 if (reply_code == COMPLETE) {
600 mhl_mem_free (SUP.cwdir);
601 SUP.cwdir = mhl_str_dup (remote_path);
602 print_vfs_message (_("%s: done."), me->name);
603 return 0;
604 } else if (reply_code == ERROR) {
605 me->verrno = EACCES;
606 } else {
607 me->verrno = E_REMOTE;
610 error:
611 print_vfs_message (_("%s: failure"), me->name);
612 return -1;
615 static int
616 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
618 struct vfs_s_super *super = FH_SUPER;
619 int n, total;
620 char buffer[8192];
621 struct stat s;
622 int was_error = 0;
623 int h;
624 SHELL_ESCAPED_STR quoted_name;
626 h = open (localname, O_RDONLY);
628 if (h == -1)
629 ERRNOR (EIO, -1);
630 if (fstat(h, &s)<0) {
631 close (h);
632 ERRNOR (EIO, -1);
635 /* First, try this as stor:
637 * ( head -c number ) | ( cat > file; cat >/dev/null )
639 * If `head' is not present on the remote system, `dd' will be used.
640 * Unfortunately, we cannot trust most non-GNU `head' implementations
641 * even if `-c' options is supported. Therefore, we separate GNU head
642 * (and other modern heads?) using `-q' and `-' . This causes another
643 * implementations to fail (because of "incorrect options").
645 * Fallback is:
647 * rest=<number>
648 * while [ $rest -gt 0 ]
649 * do
650 * cnt=`expr \( $rest + 255 \) / 256`
651 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
652 * rest=`expr $rest - $n`
653 * done
655 * `dd' was not designed for full filling of input buffers,
656 * and does not report exact number of bytes (not blocks).
657 * Therefore a more complex shell script is needed.
659 * On some systems non-GNU head writes "Usage:" error report to stdout
660 * instead of stderr. It makes impossible the use of "head || dd"
661 * algorithm for file appending case, therefore just "dd" is used for it.
664 quoted_name = mhl_shell_escape_dup(name);
665 print_vfs_message(_("fish: store %s: sending command..."), quoted_name.s );
667 /* FIXME: File size is limited to ULONG_MAX */
668 if (!fh->u.fish.append)
669 n = fish_command (me, super, WAIT_REPLY,
670 "#STOR %lu /%s\n"
671 "echo '### 001'\n"
672 "file=/%s\n"
673 "res=`exec 3>&1\n"
674 "(\n"
675 "head -c %lu -q - || echo DD >&3\n"
676 ") 2>/dev/null | (\n"
677 "cat > $file\n"
678 "cat > /dev/null\n"
679 ")`; [ \"$res\" = DD ] && {\n"
680 "> \"$file\"\n"
681 "rest=%lu\n"
682 "while [ $rest -gt 0 ]\n"
683 "do\n"
684 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
685 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
686 " rest=`expr $rest - $n`\n"
687 "done\n"
688 "}; echo '### 200'\n",
689 (unsigned long) s.st_size, quoted_name.s,
690 quoted_name.s, (unsigned long) s.st_size,
691 (unsigned long) s.st_size);
692 else
693 n = fish_command (me, super, WAIT_REPLY,
694 "#STOR %lu /%s\n"
695 "echo '### 001'\n"
696 "{\n"
697 "file=/%s\n"
698 "rest=%lu\n"
699 "while [ $rest -gt 0 ]\n"
700 "do\n"
701 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
702 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
703 " rest=`expr $rest - $n`\n"
704 "done\n"
705 "}; echo '### 200'\n",
706 (unsigned long) s.st_size, quoted_name.s,
707 quoted_name.s, (unsigned long) s.st_size);
709 if (n != PRELIM) {
710 close (h);
711 ERRNOR(E_REMOTE, -1);
713 total = 0;
715 while (1) {
716 int t;
717 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
718 if ((errno == EINTR) && got_interrupt())
719 continue;
720 print_vfs_message(_("fish: Local read failed, sending zeros") );
721 close(h);
722 h = open( "/dev/zero", O_RDONLY );
724 if (n == 0)
725 break;
726 if ((t = write (SUP.sockw, buffer, n)) != n) {
727 if (t == -1) {
728 me->verrno = errno;
729 } else {
730 me->verrno = EIO;
732 goto error_return;
734 disable_interrupt_key();
735 total += n;
736 print_vfs_message(_("fish: storing %s %d (%lu)"),
737 was_error ? _("zeros") : _("file"), total,
738 (unsigned long) s.st_size);
740 close(h);
741 mhl_mem_free(quoted_name.s);
742 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
743 ERRNOR (E_REMOTE, -1);
744 return 0;
745 error_return:
746 close(h);
747 fish_get_reply(me, SUP.sockr, NULL, 0);
748 mhl_mem_free(quoted_name.s);
749 return -1;
752 static int
753 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
755 char *name;
756 SHELL_ESCAPED_STR quoted_name;
757 if (offset)
758 ERRNOR (E_NOTSUPP, 0);
759 name = vfs_s_fullpath (me, fh->ino);
760 if (!name)
761 return 0;
762 quoted_name = mhl_shell_escape_dup(name);
763 fh->u.fish.append = 0;
766 * Check whether the remote file is readable by using `dd' to copy
767 * a single byte from the remote file to /dev/null. If `dd' completes
768 * with exit status of 0 use `cat' to send the file contents to the
769 * standard output (i.e. over the network).
771 offset = fish_command (me, FH_SUPER, WANT_STRING,
772 "#RETR /%s\n"
773 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
774 "then\n"
775 "ls -ln /%s 2>/dev/null | (\n"
776 "read p l u g s r\n"
777 "echo $s\n"
778 ")\n"
779 "echo '### 100'\n"
780 "cat /%s\n"
781 "echo '### 200'\n"
782 "else\n"
783 "echo '### 500'\n"
784 "fi\n",
785 quoted_name.s, quoted_name.s, quoted_name.s, quoted_name.s );
786 mhl_mem_free (quoted_name.s);
787 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
788 fh->linear = LS_LINEAR_OPEN;
789 fh->u.fish.got = 0;
790 errno = 0;
791 #if SIZEOF_OFF_T == SIZEOF_LONG
792 fh->u.fish.total = strtol (reply_str, NULL, 10);
793 #else
794 fh->u.fish.total = strtoll (reply_str, NULL, 10);
795 #endif
796 if (errno != 0)
797 ERRNOR (E_REMOTE, 0);
798 return 1;
801 static void
802 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
804 struct vfs_s_super *super = FH_SUPER;
805 char buffer[8192];
806 int n;
808 print_vfs_message( _("Aborting transfer...") );
809 do {
810 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
811 if (n) {
812 if ((n = read(SUP.sockr, buffer, n)) < 0)
813 return;
814 fh->u.fish.got += n;
816 } while (n);
818 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
819 print_vfs_message( _("Error reported after abort.") );
820 else
821 print_vfs_message( _("Aborted transfer would be successful.") );
824 static int
825 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
827 struct vfs_s_super *super = FH_SUPER;
828 int n = 0;
829 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
830 disable_interrupt_key();
831 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
832 if ((errno == EINTR) && !got_interrupt())
833 continue;
834 break;
836 enable_interrupt_key();
838 if (n>0) fh->u.fish.got += n;
839 if (n<0) fish_linear_abort(me, fh);
840 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
841 ERRNOR (E_REMOTE, -1);
842 ERRNOR (errno, n);
845 static void
846 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
848 if (fh->u.fish.total != fh->u.fish.got)
849 fish_linear_abort(me, fh);
852 static int
853 fish_ctl (void *fh, int ctlop, void *arg)
855 (void) arg;
856 return 0;
857 #if 0
858 switch (ctlop) {
859 case VFS_CTL_IS_NOTREADY:
861 int v;
863 if (!FH->linear)
864 vfs_die ("You may not do this");
865 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
866 return 0;
868 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
869 if (((v < 0) && (errno == EINTR)) || v == 0)
870 return 1;
871 return 0;
873 default:
874 return 0;
876 #endif
879 static int
880 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
882 int r;
884 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
885 vfs_stamp_create (&vfs_fish_ops, super);
886 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
887 if (flags & OPT_FLUSH)
888 vfs_s_invalidate(me, super);
889 return 0;
892 #define PREFIX \
893 char buf[BUF_LARGE]; \
894 const char *crpath; \
895 char *mpath = mhl_str_dup (path); \
896 SHELL_ESCAPED_STR rpath; \
897 struct vfs_s_super *super; \
898 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
899 mhl_mem_free (mpath); \
900 return -1; \
902 rpath = mhl_shell_escape_dup(crpath); \
903 mhl_mem_free (mpath);
905 #define POSTFIX(flags) \
906 mhl_mem_free (rpath.s); \
907 return fish_send_command(me, super, buf, flags);
909 static int
910 fish_chmod (struct vfs_class *me, const char *path, int mode)
912 PREFIX
913 snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
914 "chmod %4.4o /%s 2>/dev/null\n"
915 "echo '### 000'\n",
916 mode & 07777, rpath.s,
917 mode & 07777, rpath.s);
918 POSTFIX(OPT_FLUSH);
921 #define FISH_OP(name, string) \
922 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
924 char buf[BUF_LARGE]; \
925 const char *crpath1, *crpath2; \
926 char *mpath1, *mpath2; \
927 struct vfs_s_super *super1, *super2; \
928 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = mhl_str_dup(path1), &super1, 0))) { \
929 mhl_mem_free (mpath1); \
930 return -1; \
932 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = mhl_str_dup(path2), &super2, 0))) { \
933 mhl_mem_free (mpath1); \
934 mhl_mem_free (mpath2); \
936 SHELL_ESCAPED_STR rpath1 = mhl_shell_escape_dup (crpath1); \
937 mhl_mem_free (mpath1); \
938 SHELL_ESCAPED_STR rpath2 = mhl_shell_escape_dup (crpath2); \
939 mhl_mem_free (mpath2); \
940 snprintf(buf, sizeof(buf), string "\n", rpath1.s, rpath2.s, rpath1.s, rpath2.s); \
941 mhl_mem_free (rpath1.s); \
942 mhl_mem_free (rpath2.s); \
943 return fish_send_command(me, super2, buf, OPT_FLUSH); \
946 FISH_OP(rename, "#RENAME /%s /%s\n"
947 "mv /%s /%s 2>/dev/null\n"
948 "echo '### 000'" )
949 FISH_OP(link, "#LINK /%s /%s\n"
950 "ln /%s /%s 2>/dev/null\n"
951 "echo '### 000'" )
953 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
955 SHELL_ESCAPED_STR qsetto;
956 PREFIX
957 qsetto = mhl_shell_escape_dup (setto);
958 snprintf(buf, sizeof(buf),
959 "#SYMLINK %s /%s\n"
960 "ln -s %s /%s 2>/dev/null\n"
961 "echo '### 000'\n",
962 qsetto.s, rpath.s, qsetto.s, rpath.s);
963 mhl_mem_free (qsetto.s);
964 POSTFIX(OPT_FLUSH);
967 static int
968 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
970 char *sowner, *sgroup;
971 struct passwd *pw;
972 struct group *gr;
974 if ((pw = getpwuid (owner)) == NULL)
975 return 0;
977 if ((gr = getgrgid (group)) == NULL)
978 return 0;
980 sowner = pw->pw_name;
981 sgroup = gr->gr_name;
983 PREFIX
984 snprintf (buf, sizeof(buf),
985 "#CHOWN %s /%s\n"
986 "chown %s /%s 2>/dev/null\n"
987 "echo '### 000'\n",
988 sowner, rpath.s,
989 sowner, rpath.s);
990 fish_send_command (me, super, buf, OPT_FLUSH);
991 /* FIXME: what should we report if chgrp succeeds but chown fails? */
992 snprintf (buf, sizeof(buf),
993 "#CHGRP /%s \"/%s\"\n"
994 "chgrp %s \"/%s\" 2>/dev/null\n"
995 "echo '### 000'\n",
996 sgroup, rpath.s,
997 sgroup, rpath.s);
998 /* fish_send_command(me, super, buf, OPT_FLUSH); */
999 POSTFIX (OPT_FLUSH)
1003 static int fish_unlink (struct vfs_class *me, const char *path)
1005 PREFIX
1006 snprintf(buf, sizeof(buf),
1007 "#DELE /%s\n"
1008 "rm -f /%s 2>/dev/null\n"
1009 "echo '### 000'\n",
1010 rpath.s, rpath.s);
1011 POSTFIX(OPT_FLUSH);
1014 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1016 PREFIX
1018 (void) mode;
1020 snprintf(buf, sizeof(buf),
1021 "#MKD /%s\n"
1022 "mkdir /%s 2>/dev/null\n"
1023 "echo '### 000'\n",
1024 rpath.s, rpath.s);
1025 POSTFIX(OPT_FLUSH);
1028 static int fish_rmdir (struct vfs_class *me, const char *path)
1030 PREFIX
1031 snprintf(buf, sizeof(buf),
1032 "#RMD /%s\n"
1033 "rmdir /%s 2>/dev/null\n"
1034 "echo '### 000'\n",
1035 rpath.s, rpath.s);
1036 POSTFIX(OPT_FLUSH);
1039 static int
1040 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1041 int mode)
1043 (void) mode;
1045 fh->u.fish.append = 0;
1046 /* File will be written only, so no need to retrieve it */
1047 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1048 fh->u.fish.append = flags & O_APPEND;
1049 if (!fh->ino->localname) {
1050 int tmp_handle =
1051 vfs_mkstemps (&fh->ino->localname, me->name,
1052 fh->ino->ent->name);
1053 if (tmp_handle == -1)
1054 return -1;
1055 close (tmp_handle);
1057 return 0;
1059 if (!fh->ino->localname)
1060 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1061 return -1;
1062 if (!fh->ino->localname)
1063 vfs_die ("retrieve_file failed to fill in localname");
1064 return 0;
1067 static void
1068 fish_fill_names (struct vfs_class *me, fill_names_f func)
1070 struct vfs_s_super *super = MEDATA->supers;
1071 char *name;
1073 char gbuf[10];
1075 while (super)
1077 const char *flags = "";
1078 switch (SUP.flags)
1080 case FISH_FLAG_RSH:
1081 flags = ":r";
1082 break;
1083 case FISH_FLAG_COMPRESSED:
1084 flags = ":C";
1085 break;
1086 default:
1087 if (SUP.flags > FISH_FLAG_RSH)
1089 break;
1090 snprintf (gbuf, sizeof (gbuf), ":%d", SUP.flags);
1091 flags = gbuf;
1093 break;
1096 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1097 "/", SUP.cwdir, (char *) NULL);
1098 (*func)(name);
1099 mhl_mem_free (name);
1100 super = super->next;
1104 void
1105 init_fish (void)
1107 static struct vfs_s_subclass fish_subclass;
1109 fish_subclass.flags = VFS_S_REMOTE;
1110 fish_subclass.archive_same = fish_archive_same;
1111 fish_subclass.open_archive = fish_open_archive;
1112 fish_subclass.free_archive = fish_free_archive;
1113 fish_subclass.fh_open = fish_fh_open;
1114 fish_subclass.dir_load = fish_dir_load;
1115 fish_subclass.file_store = fish_file_store;
1116 fish_subclass.linear_start = fish_linear_start;
1117 fish_subclass.linear_read = fish_linear_read;
1118 fish_subclass.linear_close = fish_linear_close;
1120 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1121 vfs_fish_ops.name = "fish";
1122 vfs_fish_ops.prefix = "sh:";
1123 vfs_fish_ops.fill_names = fish_fill_names;
1124 vfs_fish_ops.chmod = fish_chmod;
1125 vfs_fish_ops.chown = fish_chown;
1126 vfs_fish_ops.symlink = fish_symlink;
1127 vfs_fish_ops.link = fish_link;
1128 vfs_fish_ops.unlink = fish_unlink;
1129 vfs_fish_ops.rename = fish_rename;
1130 vfs_fish_ops.mkdir = fish_mkdir;
1131 vfs_fish_ops.rmdir = fish_rmdir;
1132 vfs_fish_ops.ctl = fish_ctl;
1133 vfs_register_class (&vfs_fish_ops);