manually merged 232_fix_init_chown_advanced
[midnight-commander.git] / vfs / fish.c
blob7df2e1e6a992e6003891fdae729ac98b08f66cf4
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>
39 #include <errno.h>
41 #include "../src/global.h"
42 #include "../src/tty.h" /* enable/disable interrupt key */
43 #include "../src/wtools.h" /* message() */
44 #include "../src/main.h" /* print_vfs_message */
45 #include "utilvfs.h"
46 #include "xdirentry.h"
47 #include "vfs.h"
48 #include "vfs-impl.h"
49 #include "gc.h" /* vfs_stamp_create */
50 #include "tcputil.h"
51 #include "../src/unixcompat.h"
52 #include "fish.h"
53 #include "../mhl/memory.h"
54 #include "../mhl/string.h"
55 #include "../mhl/escape.h"
57 int fish_directory_timeout = 900;
59 #define DO_RESOLVE_SYMLINK 1
60 #define DO_OPEN 2
61 #define DO_FREE_RESOURCE 4
63 #define FISH_FLAG_COMPRESSED 1
64 #define FISH_FLAG_RSH 2
66 #define OPT_FLUSH 1
67 #define OPT_IGNORE_ERROR 2
70 * Reply codes.
72 #define PRELIM 1 /* positive preliminary */
73 #define COMPLETE 2 /* positive completion */
74 #define CONTINUE 3 /* positive intermediate */
75 #define TRANSIENT 4 /* transient negative completion */
76 #define ERROR 5 /* permanent negative completion */
78 /* command wait_flag: */
79 #define NONE 0x00
80 #define WAIT_REPLY 0x01
81 #define WANT_STRING 0x02
82 static char reply_str [80];
84 static struct vfs_class vfs_fish_ops;
86 static int
87 fish_command (struct vfs_class *me, struct vfs_s_super *super,
88 int wait_reply, const char *fmt, ...)
89 __attribute__ ((format (__printf__, 4, 5)));
91 static int fish_decode_reply (char *s, int was_garbage)
93 int code;
94 if (!sscanf(s, "%d", &code)) {
95 code = 500;
96 return 5;
98 if (code<100) return was_garbage ? ERROR : (!code ? COMPLETE : PRELIM);
99 return code / 100;
102 /* Returns a reply code, check /usr/include/arpa/ftp.h for possible values */
103 static int fish_get_reply (struct vfs_class *me, int sock, char *string_buf, int string_len)
105 char answer[1024];
106 int was_garbage = 0;
108 for (;;) {
109 if (!vfs_s_get_line(me, sock, answer, sizeof(answer), '\n')) {
110 if (string_buf)
111 *string_buf = 0;
112 return 4;
115 if (strncmp(answer, "### ", 4)) {
116 was_garbage = 1;
117 if (string_buf)
118 g_strlcpy(string_buf, answer, string_len);
119 } else return fish_decode_reply(answer+4, was_garbage);
123 #define SUP super->u.fish
125 static int
126 fish_command (struct vfs_class *me, struct vfs_s_super *super,
127 int wait_reply, const char *fmt, ...)
129 va_list ap;
130 char *str;
131 int status;
132 FILE *logfile = MEDATA->logfile;
134 va_start (ap, fmt);
136 str = g_strdup_vprintf (fmt, ap);
137 va_end (ap);
139 if (logfile) {
140 fwrite (str, strlen (str), 1, logfile);
141 fflush (logfile);
144 enable_interrupt_key ();
146 status = write (SUP.sockw, str, strlen (str));
147 mhl_mem_free (str);
149 disable_interrupt_key ();
150 if (status < 0)
151 return TRANSIENT;
153 if (wait_reply)
154 return fish_get_reply (me, SUP.sockr,
155 (wait_reply & WANT_STRING) ? reply_str :
156 NULL, sizeof (reply_str) - 1);
157 return COMPLETE;
160 static void
161 fish_free_archive (struct vfs_class *me, struct vfs_s_super *super)
163 if ((SUP.sockw != -1) || (SUP.sockr != -1)) {
164 print_vfs_message (_("fish: Disconnecting from %s"),
165 super->name ? super->name : "???");
166 fish_command (me, super, NONE, "#BYE\nexit\n");
167 close (SUP.sockw);
168 close (SUP.sockr);
169 SUP.sockw = SUP.sockr = -1;
171 mhl_mem_free (SUP.host);
172 mhl_mem_free (SUP.user);
173 mhl_mem_free (SUP.cwdir);
174 mhl_mem_free (SUP.password);
177 static void
178 fish_pipeopen(struct vfs_s_super *super, const char *path, const char *argv[])
180 int fileset1[2], fileset2[2];
181 int res;
183 if ((pipe(fileset1)<0) || (pipe(fileset2)<0))
184 vfs_die("Cannot pipe(): %m.");
186 if ((res = fork())) {
187 if (res<0) vfs_die("Cannot fork(): %m.");
188 /* We are the parent */
189 close(fileset1[0]);
190 SUP.sockw = fileset1[1];
191 close(fileset2[1]);
192 SUP.sockr = fileset2[0];
193 } else {
194 close(0);
195 dup(fileset1[0]);
196 close(fileset1[0]); close(fileset1[1]);
197 close(1); close(2);
198 dup(fileset2[1]);
199 /* stderr to /dev/null */
200 open ("/dev/null", O_WRONLY);
201 close(fileset2[0]); close(fileset2[1]);
202 execvp(path, const_cast(char **, argv));
203 _exit(3);
207 /* The returned directory should always contain a trailing slash */
208 static char *fish_getcwd(struct vfs_class *me, struct vfs_s_super *super)
210 if (fish_command (me, super, WANT_STRING, "#PWD\npwd; echo '### 200'\n") == COMPLETE)
211 return g_strconcat (reply_str, "/", (char *) NULL);
212 ERRNOR (EIO, NULL);
215 static int
216 fish_open_archive_int (struct vfs_class *me, struct vfs_s_super *super)
219 const char *argv[10];
220 const char *xsh = (SUP.flags == FISH_FLAG_RSH ? "rsh" : "ssh");
221 int i = 0;
223 argv[i++] = xsh;
224 if (SUP.flags == FISH_FLAG_COMPRESSED)
225 argv[i++] = "-C";
226 argv[i++] = "-l";
227 argv[i++] = SUP.user;
228 argv[i++] = SUP.host;
229 argv[i++] = "echo FISH:; /bin/sh";
230 argv[i++] = NULL;
232 fish_pipeopen (super, xsh, argv);
235 char answer[2048];
236 print_vfs_message (_("fish: Waiting for initial line..."));
237 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
238 ERRNOR (E_PROTO, -1);
239 print_vfs_message ("%s", answer);
240 if (strstr (answer, "assword")) {
242 /* Currently, this does not work. ssh reads passwords from
243 /dev/tty, not from stdin :-(. */
245 message (1, MSG_ERROR,
247 ("Sorry, we cannot do password authenticated connections for now."));
248 ERRNOR (EPERM, -1);
249 if (!SUP.password) {
250 char *p, *op;
251 p = g_strconcat (_(" fish: Password required for "),
252 SUP.user, " ", (char *) NULL);
253 op = vfs_get_password (p);
254 mhl_mem_free (p);
255 if (op == NULL)
256 ERRNOR (EPERM, -1);
257 SUP.password = op;
259 print_vfs_message (_("fish: Sending password..."));
260 write (SUP.sockw, SUP.password, strlen (SUP.password));
261 write (SUP.sockw, "\n", 1);
265 print_vfs_message (_("fish: Sending initial line..."));
267 * Run `start_fish_server'. If it doesn't exist - no problem,
268 * we'll talk directly to the shell.
270 if (fish_command
271 (me, super, WAIT_REPLY,
272 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
273 COMPLETE)
274 ERRNOR (E_PROTO, -1);
276 print_vfs_message (_("fish: Handshaking version..."));
277 if (fish_command
278 (me, super, WAIT_REPLY,
279 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
280 ERRNOR (E_PROTO, -1);
282 /* Set up remote locale to C, otherwise dates cannot be recognized */
283 if (fish_command
284 (me, super, WAIT_REPLY,
285 "LANG=C; LC_ALL=C; LC_TIME=C\n"
286 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
287 != COMPLETE)
288 ERRNOR (E_PROTO, -1);
290 print_vfs_message (_("fish: Setting up current directory..."));
291 SUP.cwdir = fish_getcwd (me, super);
292 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
293 #if 0
294 super->name =
295 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
296 #endif
297 super->name = g_strdup (PATH_SEP_STR);
299 super->root =
300 vfs_s_new_inode (me, super,
301 vfs_s_default_stat (me, S_IFDIR | 0755));
302 return 0;
305 static int
306 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
307 const char *archive_name, char *op)
309 char *host, *user, *password, *p;
310 int flags;
312 (void) archive_name;
314 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
315 &password, 0, URL_NOSLASH);
317 mhl_mem_free (p);
319 SUP.host = host;
320 SUP.user = user;
321 SUP.flags = flags;
322 if (!strncmp (op, "rsh:", 4))
323 SUP.flags |= FISH_FLAG_RSH;
324 SUP.cwdir = NULL;
325 if (password)
326 SUP.password = password;
327 return fish_open_archive_int (me, super);
330 static int
331 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
332 const char *archive_name, char *op, void *cookie)
334 char *host, *user;
335 int flags;
337 (void) me;
338 (void) archive_name;
339 (void) cookie;
341 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
342 URL_NOSLASH);
344 mhl_mem_free (op);
346 flags = ((strcmp (host, SUP.host) == 0)
347 && (strcmp (user, SUP.user) == 0) && (flags == SUP.flags));
348 mhl_mem_free (host);
349 mhl_mem_free (user);
351 return flags;
354 static int
355 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
357 struct vfs_s_super *super = dir->super;
358 char buffer[8192];
359 struct vfs_s_entry *ent = NULL;
360 FILE *logfile;
361 SHELL_ESCAPED_STR quoted_path;
362 int reply_code;
364 #if 0
366 * Simple FISH debug interface :]
368 if (!(MEDATA->logfile))
370 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
372 #endif // 0
374 logfile = MEDATA->logfile;
376 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
378 gettimeofday(&dir->timestamp, NULL);
379 dir->timestamp.tv_sec += fish_directory_timeout;
380 quoted_path = mhl_shell_escape_dup (remote_path);
381 fish_command (me, super, NONE,
382 "#LIST /%s\n"
383 "if `perl -v > /dev/null 2>&1` ; then\n"
384 "perl -e '\n"
385 "use strict;\n"
386 "use POSIX;\n"
387 "use Fcntl;\n"
388 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
389 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
390 "my $dirname = $ARGV[0];\n"
391 "if (opendir ( DIR, $dirname )) {\n"
392 "while( (my $filename = readdir(DIR))){\n"
393 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
394 "my $mloctime= scalar localtime $mtime;\n"
395 "my $shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
396 "my $e_filename = $filename;\n"
397 "$e_filename =~ $shell_escape_regex;\n"
398 "if (S_ISLNK($mode) ) {\n"
399 "my $linkname = readlink (\"$dirname/$filename\");\n"
400 "$linkname =~ $shell_escape_regex;\n"
401 "\n"
402 "printf(\"R%%o %%o $uid.$gid\\n"
403 "S$size\\n"
404 "d$mloctime\\n"
405 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
406 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
407 "} else {\n"
408 "printf(\"R%%o %%o $uid.$gid\\n"
409 "S$size\\n"
410 "d$mloctime\\n"
411 ":\\\"$e_filename\\\"\\n"
412 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
413 "}}\n"
414 "printf(\"### 200\\n\");\n"
415 "closedir(DIR);\n"
416 "} else {\n"
417 "printf(\"### 500\\n\");\n"
418 "}\n"
419 "exit 0\n"
420 "' /%s ||\n" /* ARGV[0] - path to browse */
421 " echo '### 500'\n" /* do not hang if perl is to eval it */
422 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
423 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
424 "LSOPT=\"-Qlan\";\n"
425 "ADD=0;\n"
426 "else\n"
427 "LSOPT=\"-lan\";\n"
428 "ADD=1;\n"
429 "fi\n"
430 "ls $LSOPT \"/%s\" 2>/dev/null | grep '^[^cbt]' | (\n"
431 "while read p l u g s m d y n; do\n"
432 "if [ $ADD = 0 ]; then\n"
433 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
434 "elif `sed --version >/dev/null 2>&1` ; then\n"
435 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
436 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
437 "else\n"
438 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
439 "fi\n"
440 "done )\n"
441 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
442 "while read p l u g a i m d y n; do\n"
443 "if [ $ADD = 0 ]; then\n"
444 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
445 "elif `sed --version >/dev/null 2>&1` ; then\n"
446 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
447 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
448 "else\n"
449 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
450 "fi\n"
451 "done)\n"
452 "echo '### 200'\n"
453 "else\n"
454 "echo '### 500'\n"
455 "fi\n",
456 quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s, quoted_path.s);
457 mhl_mem_free (quoted_path.s);
458 ent = vfs_s_generate_entry(me, NULL, dir, 0);
459 while (1) {
460 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
461 if ((!res) || (res == EINTR)) {
462 vfs_s_free_entry(me, ent);
463 me->verrno = ECONNRESET;
464 goto error;
466 if (logfile) {
467 fputs (buffer, logfile);
468 fputs ("\n", logfile);
469 fflush (logfile);
471 if (!strncmp(buffer, "### ", 4))
472 break;
473 if ((!buffer[0])) {
474 if (ent->name) {
475 vfs_s_insert_entry(me, dir, ent);
476 ent = vfs_s_generate_entry(me, NULL, dir, 0);
478 continue;
481 #define ST ent->ino->st
483 switch(buffer[0]) {
484 case ':': {
485 char *data_start = buffer+1;
486 char *filename = data_start;
487 char *linkname = data_start;
488 char *filename_bound = filename + strlen(filename);
489 char *linkname_bound = filename_bound;
490 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
491 break; /* We'll do "." and ".." ourselves */
493 if (S_ISLNK(ST.st_mode)) {
494 // we expect: "escaped-name" -> "escaped-name"
495 // -> cannot occur in filenames,
496 // because it will be escaped to -\>
498 if (*filename == '"')
499 ++filename;
501 linkname = strstr(filename, "\" -> \"");
502 if (!linkname)
504 /* broken client, or smth goes wrong */
505 linkname = filename_bound;
506 if (filename_bound > filename
507 && *(filename_bound - 1) == '"')
508 --filename_bound; // skip trailing "
510 else
512 filename_bound = linkname;
513 linkname += 6; // strlen ("\" -> \"")
514 if (*(linkname_bound - 1) == '"')
515 --linkname_bound; // skip trailing "
518 ent->name = mhl_str_dup_range(filename, filename_bound);
519 mhl_shell_unescape_buf(ent->name);
521 ent->ino->linkname = mhl_str_dup_range(linkname, linkname_bound);
522 mhl_shell_unescape_buf(ent->ino->linkname);
523 } else {
524 // we expect: "escaped-name"
525 if (filename_bound - filename > 2)
527 // there is at least 2 "
528 // and we skip them
529 if (*filename == '"')
530 ++filename;
531 if (*(filename_bound - 1) == '"')
532 --filename_bound;
535 ent->name = mhl_str_dup_range(filename, filename_bound);
536 mhl_shell_unescape_buf(ent->name);
538 break;
540 case 'S':
541 #ifdef HAVE_ATOLL
542 ST.st_size = (off_t) atoll (buffer+1);
543 #else
544 ST.st_size = (off_t) atof (buffer+1);
545 #endif
546 break;
547 case 'P': {
548 size_t skipped;
549 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
550 break;
552 case 'R': {
553 // raw filemode:
554 // we expect: Roctal-filemode octal-filetype uid.gid
555 size_t skipped;
556 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
557 break;
559 case 'd': {
560 vfs_split_text(buffer+1);
561 if (!vfs_parse_filedate(0, &ST.st_ctime))
562 break;
563 ST.st_atime = ST.st_mtime = ST.st_ctime;
565 break;
566 case 'D': {
567 struct tm tim;
568 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
569 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
570 break;
571 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
573 break;
574 case 'E': {
575 int maj, min;
576 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
577 break;
578 #ifdef HAVE_STRUCT_STAT_ST_RDEV
579 ST.st_rdev = makedev (maj, min);
580 #endif
585 vfs_s_free_entry (me, ent);
586 reply_code = fish_decode_reply(buffer + 4, 0);
587 if (reply_code == COMPLETE) {
588 mhl_mem_free (SUP.cwdir);
589 SUP.cwdir = g_strdup (remote_path);
590 print_vfs_message (_("%s: done."), me->name);
591 return 0;
592 } else if (reply_code == ERROR) {
593 me->verrno = EACCES;
594 } else {
595 me->verrno = E_REMOTE;
598 error:
599 print_vfs_message (_("%s: failure"), me->name);
600 return -1;
603 static int
604 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
606 struct vfs_s_super *super = FH_SUPER;
607 int n, total;
608 char buffer[8192];
609 struct stat s;
610 int was_error = 0;
611 int h;
612 SHELL_ESCAPED_STR quoted_name;
614 h = open (localname, O_RDONLY);
616 if (h == -1)
617 ERRNOR (EIO, -1);
618 if (fstat(h, &s)<0) {
619 close (h);
620 ERRNOR (EIO, -1);
623 /* First, try this as stor:
625 * ( head -c number ) | ( cat > file; cat >/dev/null )
627 * If `head' is not present on the remote system, `dd' will be used.
628 * Unfortunately, we cannot trust most non-GNU `head' implementations
629 * even if `-c' options is supported. Therefore, we separate GNU head
630 * (and other modern heads?) using `-q' and `-' . This causes another
631 * implementations to fail (because of "incorrect options").
633 * Fallback is:
635 * rest=<number>
636 * while [ $rest -gt 0 ]
637 * do
638 * cnt=`expr \( $rest + 255 \) / 256`
639 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
640 * rest=`expr $rest - $n`
641 * done
643 * `dd' was not designed for full filling of input buffers,
644 * and does not report exact number of bytes (not blocks).
645 * Therefore a more complex shell script is needed.
647 * On some systems non-GNU head writes "Usage:" error report to stdout
648 * instead of stderr. It makes impossible the use of "head || dd"
649 * algorithm for file appending case, therefore just "dd" is used for it.
652 quoted_name = mhl_shell_escape_dup(name);
653 print_vfs_message(_("fish: store %s: sending command..."), quoted_name.s );
655 /* FIXME: File size is limited to ULONG_MAX */
656 if (!fh->u.fish.append)
657 n = fish_command (me, super, WAIT_REPLY,
658 "#STOR %lu /%s\n"
659 "echo '### 001'\n"
660 "file=/%s\n"
661 "res=`exec 3>&1\n"
662 "(\n"
663 "head -c %lu -q - || echo DD >&3\n"
664 ") 2>/dev/null | (\n"
665 "cat > $file\n"
666 "cat > /dev/null\n"
667 ")`; [ \"$res\" = DD ] && {\n"
668 "> \"$file\"\n"
669 "rest=%lu\n"
670 "while [ $rest -gt 0 ]\n"
671 "do\n"
672 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
673 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
674 " rest=`expr $rest - $n`\n"
675 "done\n"
676 "}; echo '### 200'\n",
677 (unsigned long) s.st_size, quoted_name.s,
678 quoted_name.s, (unsigned long) s.st_size,
679 (unsigned long) s.st_size);
680 else
681 n = fish_command (me, super, WAIT_REPLY,
682 "#STOR %lu /%s\n"
683 "echo '### 001'\n"
684 "{\n"
685 "file=/%s\n"
686 "rest=%lu\n"
687 "while [ $rest -gt 0 ]\n"
688 "do\n"
689 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
690 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
691 " rest=`expr $rest - $n`\n"
692 "done\n"
693 "}; echo '### 200'\n",
694 (unsigned long) s.st_size, quoted_name.s,
695 quoted_name.s, (unsigned long) s.st_size);
697 if (n != PRELIM) {
698 close (h);
699 ERRNOR(E_REMOTE, -1);
701 total = 0;
703 while (1) {
704 int t;
705 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
706 if ((errno == EINTR) && got_interrupt())
707 continue;
708 print_vfs_message(_("fish: Local read failed, sending zeros") );
709 close(h);
710 h = open( "/dev/zero", O_RDONLY );
712 if (n == 0)
713 break;
714 if ((t = write (SUP.sockw, buffer, n)) != n) {
715 if (t == -1) {
716 me->verrno = errno;
717 } else {
718 me->verrno = EIO;
720 goto error_return;
722 disable_interrupt_key();
723 total += n;
724 print_vfs_message(_("fish: storing %s %d (%lu)"),
725 was_error ? _("zeros") : _("file"), total,
726 (unsigned long) s.st_size);
728 close(h);
729 mhl_mem_free(quoted_name.s);
730 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
731 ERRNOR (E_REMOTE, -1);
732 return 0;
733 error_return:
734 close(h);
735 fish_get_reply(me, SUP.sockr, NULL, 0);
736 mhl_mem_free(quoted_name.s);
737 return -1;
740 static int
741 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
743 char *name;
744 SHELL_ESCAPED_STR quoted_name;
745 if (offset)
746 ERRNOR (E_NOTSUPP, 0);
747 name = vfs_s_fullpath (me, fh->ino);
748 if (!name)
749 return 0;
750 quoted_name = mhl_shell_escape_dup(name);
751 fh->u.fish.append = 0;
754 * Check whether the remote file is readable by using `dd' to copy
755 * a single byte from the remote file to /dev/null. If `dd' completes
756 * with exit status of 0 use `cat' to send the file contents to the
757 * standard output (i.e. over the network).
759 offset = fish_command (me, FH_SUPER, WANT_STRING,
760 "#RETR /%s\n"
761 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
762 "then\n"
763 "ls -ln /%s 2>/dev/null | (\n"
764 "read p l u g s r\n"
765 "echo $s\n"
766 ")\n"
767 "echo '### 100'\n"
768 "cat /%s\n"
769 "echo '### 200'\n"
770 "else\n"
771 "echo '### 500'\n"
772 "fi\n",
773 quoted_name.s, quoted_name.s, quoted_name.s, quoted_name.s );
774 mhl_mem_free (quoted_name.s);
775 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
776 fh->linear = LS_LINEAR_OPEN;
777 fh->u.fish.got = 0;
778 errno = 0;
779 #if SIZEOF_OFF_T == SIZEOF_LONG
780 fh->u.fish.total = strtol (reply_str, NULL, 10);
781 #else
782 fh->u.fish.total = strtoll (reply_str, NULL, 10);
783 #endif
784 if (errno != 0)
785 ERRNOR (E_REMOTE, 0);
786 return 1;
789 static void
790 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
792 struct vfs_s_super *super = FH_SUPER;
793 char buffer[8192];
794 int n;
796 print_vfs_message( _("Aborting transfer...") );
797 do {
798 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
799 if (n) {
800 if ((n = read(SUP.sockr, buffer, n)) < 0)
801 return;
802 fh->u.fish.got += n;
804 } while (n);
806 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
807 print_vfs_message( _("Error reported after abort.") );
808 else
809 print_vfs_message( _("Aborted transfer would be successful.") );
812 static int
813 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
815 struct vfs_s_super *super = FH_SUPER;
816 int n = 0;
817 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
818 disable_interrupt_key();
819 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
820 if ((errno == EINTR) && !got_interrupt())
821 continue;
822 break;
824 enable_interrupt_key();
826 if (n>0) fh->u.fish.got += n;
827 if (n<0) fish_linear_abort(me, fh);
828 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
829 ERRNOR (E_REMOTE, -1);
830 ERRNOR (errno, n);
833 static void
834 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
836 if (fh->u.fish.total != fh->u.fish.got)
837 fish_linear_abort(me, fh);
840 static int
841 fish_ctl (void *fh, int ctlop, void *arg)
843 (void) arg;
844 return 0;
845 #if 0
846 switch (ctlop) {
847 case VFS_CTL_IS_NOTREADY:
849 int v;
851 if (!FH->linear)
852 vfs_die ("You may not do this");
853 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
854 return 0;
856 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
857 if (((v < 0) && (errno == EINTR)) || v == 0)
858 return 1;
859 return 0;
861 default:
862 return 0;
864 #endif
867 static int
868 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
870 int r;
872 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
873 vfs_stamp_create (&vfs_fish_ops, super);
874 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
875 if (flags & OPT_FLUSH)
876 vfs_s_invalidate(me, super);
877 return 0;
880 #define PREFIX \
881 char buf[BUF_LARGE]; \
882 const char *crpath; \
883 char *mpath = mhl_str_dup (path); \
884 SHELL_ESCAPED_STR rpath; \
885 struct vfs_s_super *super; \
886 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
887 mhl_mem_free (mpath); \
888 return -1; \
890 rpath = mhl_shell_escape_dup(crpath); \
891 mhl_mem_free (mpath);
893 #define POSTFIX(flags) \
894 mhl_mem_free (rpath.s); \
895 return fish_send_command(me, super, buf, flags);
897 static int
898 fish_chmod (struct vfs_class *me, const char *path, int mode)
900 PREFIX
901 g_snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
902 "chmod %4.4o /%s 2>/dev/null\n"
903 "echo '### 000'\n",
904 mode & 07777, rpath.s,
905 mode & 07777, rpath.s);
906 POSTFIX(OPT_FLUSH);
909 #define FISH_OP(name, string) \
910 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
912 char buf[BUF_LARGE]; \
913 const char *crpath1, *crpath2; \
914 char *mpath1, *mpath2; \
915 struct vfs_s_super *super1, *super2; \
916 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = g_strdup(path1), &super1, 0))) { \
917 mhl_mem_free (mpath1); \
918 return -1; \
920 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = g_strdup(path2), &super2, 0))) { \
921 mhl_mem_free (mpath1); \
922 mhl_mem_free (mpath2); \
923 return -1; \
925 SHELL_ESCAPED_STR rpath1 = mhl_shell_escape_dup (crpath1); \
926 mhl_mem_free (mpath1); \
927 SHELL_ESCAPED_STR rpath2 = mhl_shell_escape_dup (crpath2); \
928 mhl_mem_free (mpath2); \
929 g_snprintf(buf, sizeof(buf), string "\n", rpath1.s, rpath2.s, rpath1.s, rpath2.s); \
930 mhl_mem_free (rpath1.s); \
931 mhl_mem_free (rpath2.s); \
932 return fish_send_command(me, super2, buf, OPT_FLUSH); \
935 FISH_OP(rename, "#RENAME /%s /%s\n"
936 "mv /%s /%s 2>/dev/null\n"
937 "echo '### 000'" )
938 FISH_OP(link, "#LINK /%s /%s\n"
939 "ln /%s /%s 2>/dev/null\n"
940 "echo '### 000'" )
942 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
944 SHELL_ESCAPED_STR qsetto;
945 PREFIX
946 qsetto = mhl_shell_escape_dup (setto);
947 g_snprintf(buf, sizeof(buf),
948 "#SYMLINK %s /%s\n"
949 "ln -s %s /%s 2>/dev/null\n"
950 "echo '### 000'\n",
951 qsetto.s, rpath.s, qsetto.s, rpath.s);
952 mhl_mem_free (qsetto.s);
953 POSTFIX(OPT_FLUSH);
956 static int
957 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
959 char *sowner, *sgroup;
960 struct passwd *pw;
961 struct group *gr;
963 if ((pw = getpwuid (owner)) == NULL)
964 return 0;
966 if ((gr = getgrgid (group)) == NULL)
967 return 0;
969 sowner = pw->pw_name;
970 sgroup = gr->gr_name;
972 PREFIX
973 g_snprintf (buf, sizeof(buf),
974 "#CHOWN %s /%s\n"
975 "chown %s /%s 2>/dev/null\n"
976 "echo '### 000'\n",
977 sowner, rpath.s,
978 sowner, rpath.s);
979 fish_send_command (me, super, buf, OPT_FLUSH);
980 /* FIXME: what should we report if chgrp succeeds but chown fails? */
981 g_snprintf (buf, sizeof(buf),
982 "#CHGRP /%s \"/%s\"\n"
983 "chgrp %s \"/%s\" 2>/dev/null\n"
984 "echo '### 000'\n",
985 sgroup, rpath.s,
986 sgroup, rpath.s);
987 /* fish_send_command(me, super, buf, OPT_FLUSH); */
988 POSTFIX (OPT_FLUSH)
992 static int fish_unlink (struct vfs_class *me, const char *path)
994 PREFIX
995 g_snprintf(buf, sizeof(buf),
996 "#DELE /%s\n"
997 "rm -f /%s 2>/dev/null\n"
998 "echo '### 000'\n",
999 rpath.s, rpath.s);
1000 POSTFIX(OPT_FLUSH);
1003 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1005 PREFIX
1007 (void) mode;
1009 g_snprintf(buf, sizeof(buf),
1010 "#MKD /%s\n"
1011 "mkdir /%s 2>/dev/null\n"
1012 "echo '### 000'\n",
1013 rpath.s, rpath.s);
1014 POSTFIX(OPT_FLUSH);
1017 static int fish_rmdir (struct vfs_class *me, const char *path)
1019 PREFIX
1020 g_snprintf(buf, sizeof(buf),
1021 "#RMD /%s\n"
1022 "rmdir /%s 2>/dev/null\n"
1023 "echo '### 000'\n",
1024 rpath.s, rpath.s);
1025 POSTFIX(OPT_FLUSH);
1028 static int
1029 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1030 int mode)
1032 (void) mode;
1034 fh->u.fish.append = 0;
1035 /* File will be written only, so no need to retrieve it */
1036 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1037 fh->u.fish.append = flags & O_APPEND;
1038 if (!fh->ino->localname) {
1039 int tmp_handle =
1040 vfs_mkstemps (&fh->ino->localname, me->name,
1041 fh->ino->ent->name);
1042 if (tmp_handle == -1)
1043 return -1;
1044 close (tmp_handle);
1046 return 0;
1048 if (!fh->ino->localname)
1049 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1050 return -1;
1051 if (!fh->ino->localname)
1052 vfs_die ("retrieve_file failed to fill in localname");
1053 return 0;
1056 static void
1057 fish_fill_names (struct vfs_class *me, fill_names_f func)
1059 struct vfs_s_super *super = MEDATA->supers;
1060 const char *flags;
1061 char *name;
1063 while (super){
1064 switch (SUP.flags & (FISH_FLAG_RSH | FISH_FLAG_COMPRESSED)) {
1065 case FISH_FLAG_RSH:
1066 flags = ":r";
1067 break;
1068 case FISH_FLAG_COMPRESSED:
1069 flags = ":C";
1070 break;
1071 case FISH_FLAG_RSH | FISH_FLAG_COMPRESSED:
1072 flags = "";
1073 break;
1074 default:
1075 flags = "";
1076 break;
1079 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1080 "/", SUP.cwdir, (char *) NULL);
1081 (*func)(name);
1082 mhl_mem_free (name);
1083 super = super->next;
1087 void
1088 init_fish (void)
1090 static struct vfs_s_subclass fish_subclass;
1092 fish_subclass.flags = VFS_S_REMOTE;
1093 fish_subclass.archive_same = fish_archive_same;
1094 fish_subclass.open_archive = fish_open_archive;
1095 fish_subclass.free_archive = fish_free_archive;
1096 fish_subclass.fh_open = fish_fh_open;
1097 fish_subclass.dir_load = fish_dir_load;
1098 fish_subclass.file_store = fish_file_store;
1099 fish_subclass.linear_start = fish_linear_start;
1100 fish_subclass.linear_read = fish_linear_read;
1101 fish_subclass.linear_close = fish_linear_close;
1103 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1104 vfs_fish_ops.name = "fish";
1105 vfs_fish_ops.prefix = "sh:";
1106 vfs_fish_ops.fill_names = fish_fill_names;
1107 vfs_fish_ops.chmod = fish_chmod;
1108 vfs_fish_ops.chown = fish_chown;
1109 vfs_fish_ops.symlink = fish_symlink;
1110 vfs_fish_ops.link = fish_link;
1111 vfs_fish_ops.unlink = fish_unlink;
1112 vfs_fish_ops.rename = fish_rename;
1113 vfs_fish_ops.mkdir = fish_mkdir;
1114 vfs_fish_ops.rmdir = fish_rmdir;
1115 vfs_fish_ops.ctl = fish_ctl;
1116 vfs_register_class (&vfs_fish_ops);