Merge branch '1858_segfault_in_search'
[midnight-commander.git] / vfs / fish.c
blobc256cd1580a601a56c66fd01186de61fdcea0fe2
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"
57 #include "../src/tty/tty.h" /* enable/disable interrupt key */
59 #include "../src/wtools.h" /* message() */
60 #include "../src/main.h" /* print_vfs_message */
61 #include "../src/util.h"
62 #include "../src/strescape.h"
63 #include "../src/unixcompat.h"
64 #include "../src/fs.h"
65 #include "utilvfs.h"
66 #include "xdirentry.h"
67 #include "vfs.h"
68 #include "vfs-impl.h"
69 #include "gc.h" /* vfs_stamp_create */
70 #include "tcputil.h"
71 #include "fish.h"
73 int fish_directory_timeout = 900;
75 #define DO_RESOLVE_SYMLINK 1
76 #define DO_OPEN 2
77 #define DO_FREE_RESOURCE 4
79 #define FISH_FLAG_COMPRESSED 1
80 #define FISH_FLAG_RSH 2
82 #define OPT_FLUSH 1
83 #define OPT_IGNORE_ERROR 2
86 * Reply codes.
88 #define PRELIM 1 /* positive preliminary */
89 #define COMPLETE 2 /* positive completion */
90 #define CONTINUE 3 /* positive intermediate */
91 #define TRANSIENT 4 /* transient negative completion */
92 #define ERROR 5 /* permanent negative completion */
94 /* command wait_flag: */
95 #define NONE 0x00
96 #define WAIT_REPLY 0x01
97 #define WANT_STRING 0x02
98 static char reply_str [80];
100 static struct vfs_class vfs_fish_ops;
102 static int
103 fish_command (struct vfs_class *me, struct vfs_s_super *super,
104 int wait_reply, const char *fmt, ...)
105 __attribute__ ((format (__printf__, 4, 5)));
107 static int fish_decode_reply (char *s, int was_garbage)
109 int code;
110 if (!sscanf(s, "%d", &code)) {
111 code = 500;
112 return 5;
114 if (code<100) return was_garbage ? ERROR : (!code ? COMPLETE : PRELIM);
115 return code / 100;
118 /* Returns a reply code, check /usr/include/arpa/ftp.h for possible values */
119 static int fish_get_reply (struct vfs_class *me, int sock, char *string_buf, int string_len)
121 char answer[1024];
122 int was_garbage = 0;
124 for (;;) {
125 if (!vfs_s_get_line(me, sock, answer, sizeof(answer), '\n')) {
126 if (string_buf)
127 *string_buf = 0;
128 return 4;
131 if (strncmp(answer, "### ", 4)) {
132 was_garbage = 1;
133 if (string_buf)
134 g_strlcpy(string_buf, answer, string_len);
135 } else return fish_decode_reply(answer+4, was_garbage);
139 #define SUP super->u.fish
141 static int
142 fish_command (struct vfs_class *me, struct vfs_s_super *super,
143 int wait_reply, const char *fmt, ...)
145 va_list ap;
146 char *str;
147 int status;
148 FILE *logfile = MEDATA->logfile;
150 va_start (ap, fmt);
152 str = g_strdup_vprintf (fmt, ap);
153 va_end (ap);
155 if (logfile) {
156 fwrite (str, strlen (str), 1, logfile);
157 fflush (logfile);
160 tty_enable_interrupt_key ();
162 status = write (SUP.sockw, str, strlen (str));
163 g_free (str);
165 tty_disable_interrupt_key ();
166 if (status < 0)
167 return TRANSIENT;
169 if (wait_reply)
170 return fish_get_reply (me, SUP.sockr,
171 (wait_reply & WANT_STRING) ? reply_str :
172 NULL, sizeof (reply_str) - 1);
173 return COMPLETE;
176 static void
177 fish_free_archive (struct vfs_class *me, struct vfs_s_super *super)
179 if ((SUP.sockw != -1) || (SUP.sockr != -1)) {
180 print_vfs_message (_("fish: Disconnecting from %s"),
181 super->name ? super->name : "???");
182 fish_command (me, super, NONE, "#BYE\nexit\n");
183 close (SUP.sockw);
184 close (SUP.sockr);
185 SUP.sockw = SUP.sockr = -1;
187 g_free (SUP.host);
188 g_free (SUP.user);
189 g_free (SUP.cwdir);
190 g_free (SUP.password);
193 static void
194 fish_pipeopen(struct vfs_s_super *super, const char *path, const char *argv[])
196 int fileset1[2], fileset2[2];
197 int res;
199 if ((pipe(fileset1)<0) || (pipe(fileset2)<0))
200 vfs_die("Cannot pipe(): %m.");
202 if ((res = fork())) {
203 if (res<0) vfs_die("Cannot fork(): %m.");
204 /* We are the parent */
205 close(fileset1[0]);
206 SUP.sockw = fileset1[1];
207 close(fileset2[1]);
208 SUP.sockr = fileset2[0];
209 } else {
210 close(0);
211 dup(fileset1[0]);
212 close(fileset1[0]); close(fileset1[1]);
213 close(1); close(2);
214 dup(fileset2[1]);
215 /* stderr to /dev/null */
216 open ("/dev/null", O_WRONLY);
217 close(fileset2[0]); close(fileset2[1]);
218 execvp(path, const_cast(char **, argv));
219 _exit(3);
223 /* The returned directory should always contain a trailing slash */
224 static char *fish_getcwd(struct vfs_class *me, struct vfs_s_super *super)
226 if (fish_command (me, super, WANT_STRING, "#PWD\npwd; echo '### 200'\n") == COMPLETE)
227 return g_strconcat (reply_str, "/", (char *) NULL);
228 ERRNOR (EIO, NULL);
231 static int
232 fish_open_archive_int (struct vfs_class *me, struct vfs_s_super *super)
235 char gbuf[10];
236 const char *argv[10]; /* All of 10 is used now */
237 const char *xsh = (SUP.flags == FISH_FLAG_RSH ? "rsh" : "ssh");
238 int i = 0;
240 argv[i++] = xsh;
241 if (SUP.flags == FISH_FLAG_COMPRESSED)
242 argv[i++] = "-C";
244 if (SUP.flags > FISH_FLAG_RSH)
246 argv[i++] = "-p";
247 g_snprintf (gbuf, sizeof (gbuf), "%d", SUP.flags);
248 argv[i++] = gbuf;
251 argv[i++] = "-l";
252 argv[i++] = SUP.user;
253 argv[i++] = SUP.host;
254 argv[i++] = "echo FISH:; /bin/sh";
255 argv[i++] = NULL;
257 fish_pipeopen (super, xsh, argv);
260 char answer[2048];
261 print_vfs_message (_("fish: Waiting for initial line..."));
262 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
263 ERRNOR (E_PROTO, -1);
264 print_vfs_message ("%s", answer);
265 if (strstr (answer, "assword")) {
267 /* Currently, this does not work. ssh reads passwords from
268 /dev/tty, not from stdin :-(. */
270 message (D_ERROR, MSG_ERROR,
272 ("Sorry, we cannot do password authenticated connections for now."));
273 ERRNOR (EPERM, -1);
274 if (!SUP.password) {
275 char *p, *op;
276 p = g_strconcat (_(" fish: Password required for "),
277 SUP.user, " ", (char *) NULL);
278 op = vfs_get_password (p);
279 g_free (p);
280 if (op == NULL)
281 ERRNOR (EPERM, -1);
282 SUP.password = op;
284 print_vfs_message (_("fish: Sending password..."));
285 write (SUP.sockw, SUP.password, strlen (SUP.password));
286 write (SUP.sockw, "\n", 1);
290 print_vfs_message (_("fish: Sending initial line..."));
292 * Run `start_fish_server'. If it doesn't exist - no problem,
293 * we'll talk directly to the shell.
295 if (fish_command
296 (me, super, WAIT_REPLY,
297 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
298 COMPLETE)
299 ERRNOR (E_PROTO, -1);
301 print_vfs_message (_("fish: Handshaking version..."));
302 if (fish_command
303 (me, super, WAIT_REPLY,
304 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
305 ERRNOR (E_PROTO, -1);
307 /* Set up remote locale to C, otherwise dates cannot be recognized */
308 if (fish_command
309 (me, super, WAIT_REPLY,
310 "LANG=C; LC_ALL=C; LC_TIME=C\n"
311 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
312 != COMPLETE)
313 ERRNOR (E_PROTO, -1);
315 print_vfs_message (_("fish: Setting up current directory..."));
316 SUP.cwdir = fish_getcwd (me, super);
317 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
318 #if 0
319 super->name =
320 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
321 #endif
322 super->name = g_strdup (PATH_SEP_STR);
324 super->root =
325 vfs_s_new_inode (me, super,
326 vfs_s_default_stat (me, S_IFDIR | 0755));
327 return 0;
330 static int
331 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
332 const char *archive_name, char *op)
334 char *host, *user, *password, *p;
335 int flags;
337 (void) archive_name;
339 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
340 &password, 0, URL_NOSLASH);
342 g_free (p);
344 SUP.host = host;
345 SUP.user = user;
346 SUP.flags = flags;
347 if (!strncmp (op, "rsh:", 4))
348 SUP.flags = FISH_FLAG_RSH;
349 SUP.cwdir = NULL;
350 if (password)
351 SUP.password = password;
352 return fish_open_archive_int (me, super);
355 static int
356 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
357 const char *archive_name, char *op, void *cookie)
359 char *host, *user;
360 int flags;
362 (void) me;
363 (void) archive_name;
364 (void) cookie;
366 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
367 URL_NOSLASH);
369 g_free (op);
371 flags = ((strcmp (host, SUP.host) == 0)
372 && (strcmp (user, SUP.user) == 0) && (flags == SUP.flags));
373 g_free (host);
374 g_free (user);
376 return flags;
379 static int
380 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
382 struct vfs_s_super *super = dir->super;
383 char buffer[8192];
384 struct vfs_s_entry *ent = NULL;
385 FILE *logfile;
386 char *quoted_path;
387 int reply_code;
388 gchar *shell_commands;
390 #if 0
392 * Simple FISH debug interface :]
394 if (!(MEDATA->logfile))
396 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
398 #endif /* 0 */
400 logfile = MEDATA->logfile;
402 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
404 gettimeofday(&dir->timestamp, NULL);
405 dir->timestamp.tv_sec += fish_directory_timeout;
406 quoted_path = strutils_shell_escape (remote_path);
407 shell_commands = g_strconcat(
408 "#LIST /%s\n"
409 "if `perl -v > /dev/null 2>&1` ; then\n"
410 "perl -e '\n"
411 "use strict;\n"
412 "use POSIX;\n"
413 "use Fcntl;\n"
414 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
415 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
416 "my $dirname = $ARGV[0];\n"
417 "if (opendir ( DIR, $dirname )) {\n"
418 "while( (my $filename = readdir(DIR))){\n"
419 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
420 "my $mloctime= strftime(\"%%m-%%d-%%Y %%H:%%M\", localtime $mtime);\n"
422 "my $strutils_shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
423 "my $e_filename = $filename;\n"
424 "$e_filename =~ $strutils_shell_escape_regex;\n"
425 "if (S_ISLNK($mode) ) {\n"
426 "my $linkname = readlink (\"$dirname/$filename\");\n"
427 "$linkname =~ $strutils_shell_escape_regex;\n"
428 "\n"
429 "printf(\"R%%o %%o $uid.$gid\\n"
430 "S$size\\n"
431 "d$mloctime\\n"
432 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
433 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
434 "} else {\n"
435 "printf(\"R%%o %%o $uid.$gid\\n"
436 "S$size\\n"
437 "d$mloctime\\n"
438 ":\\\"$e_filename\\\"\\n"
439 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
440 "}}\n"
442 "printf(\"### 200\\n\");\n"
443 "closedir(DIR);\n"
444 "} else {\n"
445 "printf(\"### 500\\n\");\n"
446 "}\n"
447 "exit 0\n"
448 "' /%s ||\n" /* ARGV[0] - path to browse */
449 " echo '### 500'\n" /* do not hang if perl is to eval it */
450 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
451 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
452 "LSOPT=\"-Qlan\";\n"
453 "ADD=0;\n"
454 "else\n"
455 "LSOPT=\"-lan\";\n"
456 "ADD=1;\n"
457 "fi\n"
458 "ls $LSOPT /%s 2>/dev/null | grep '^[^cbt]' | (\n"
459 "while read p l u g s m d y n n2 n3; do\n"
460 "if test \"$m\" = \"0\" ; then \n"
461 "s=$d; m=$y; d=$n y=$n2; n=$n3\n"
462 "else\n"
463 "n=$n\" \"$n2\" \"n3\n"
464 "fi\n"
465 "if [ $ADD = 0 ]; then\n"
466 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
467 "elif `sed --version >/dev/null 2>&1` ; then\n"
468 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
470 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
471 "else\n"
472 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
473 "fi\n"
474 "done )\n"
475 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
476 "while read p l u g a i m d y n n2 n3; do\n"
477 "if test \"$a\" = \"0\" ; then \n"
478 "a=$m; i=$d; m=$y; d=$n y=$n2; n=$n3\n"
479 "else\n"
480 "n=$n\" \"$n2\" \"n3\n"
481 "fi\n"
482 "if [ $ADD = 0 ]; then\n"
483 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
484 "elif `sed --version >/dev/null 2>&1` ; then\n"
485 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
486 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
487 "else\n"
488 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
489 "fi\n"
490 "done)\n"
491 "echo '### 200'\n"
492 "else\n"
493 "echo '### 500'\n"
494 "fi\n"
496 NULL
499 fish_command (me, super, NONE, shell_commands,
500 quoted_path, quoted_path, quoted_path, quoted_path, quoted_path, quoted_path);
502 g_free(shell_commands);
503 g_free (quoted_path);
504 ent = vfs_s_generate_entry(me, NULL, dir, 0);
505 while (1) {
506 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
507 if ((!res) || (res == EINTR)) {
508 vfs_s_free_entry(me, ent);
509 me->verrno = ECONNRESET;
510 goto error;
512 if (logfile) {
513 fputs (buffer, logfile);
514 fputs ("\n", logfile);
515 fflush (logfile);
517 if (!strncmp(buffer, "### ", 4))
518 break;
519 if ((!buffer[0])) {
520 if (ent->name) {
521 vfs_s_insert_entry(me, dir, ent);
522 ent = vfs_s_generate_entry(me, NULL, dir, 0);
524 continue;
527 #define ST ent->ino->st
529 switch(buffer[0]) {
530 case ':': {
531 char *temp;
532 char *data_start = buffer+1;
533 char *filename = data_start;
534 char *linkname = data_start;
535 char *filename_bound = filename + strlen(filename);
536 char *linkname_bound = filename_bound;
537 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
538 break; /* We'll do "." and ".." ourselves */
540 if (S_ISLNK(ST.st_mode)) {
541 /* we expect: "escaped-name" -> "escaped-name"
542 // -> cannot occur in filenames,
543 // because it will be escaped to -\> */
545 if (*filename == '"')
546 ++filename;
548 linkname = strstr(filename, "\" -> \"");
549 if (!linkname)
551 /* broken client, or smth goes wrong */
552 linkname = filename_bound;
553 if (filename_bound > filename
554 && *(filename_bound - 1) == '"')
555 --filename_bound; /* skip trailing " */
557 else
559 filename_bound = linkname;
560 linkname += 6; /* strlen ("\" -> \"") */
561 if (*(linkname_bound - 1) == '"')
562 --linkname_bound; /* skip trailing " */
565 ent->name = str_dup_range(filename, filename_bound);
566 temp = ent->name;
567 ent->name = strutils_shell_unescape(ent->name);
568 g_free(temp);
570 ent->ino->linkname = str_dup_range(linkname, linkname_bound);
571 temp = ent->ino->linkname;
572 ent->ino->linkname = strutils_shell_unescape(ent->ino->linkname);
573 g_free(temp);
574 } else {
575 /* we expect: "escaped-name" */
576 if (filename_bound - filename > 2)
579 there is at least 2 "
580 and we skip them
582 if (*filename == '"')
583 ++filename;
584 if (*(filename_bound - 1) == '"')
585 --filename_bound;
587 ent->name = str_dup_range(filename, filename_bound);
588 temp = ent->name;
589 ent->name = strutils_shell_unescape(ent->name);
590 g_free(temp);
592 break;
594 case 'S':
595 #ifdef HAVE_ATOLL
596 ST.st_size = (off_t) atoll (buffer+1);
597 #else
598 ST.st_size = (off_t) atof (buffer+1);
599 #endif
600 break;
601 case 'P': {
602 size_t skipped;
603 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
604 break;
606 case 'R': {
608 raw filemode:
609 we expect: Roctal-filemode octal-filetype uid.gid
611 size_t skipped;
612 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
613 break;
615 case 'd': {
616 vfs_split_text(buffer+1);
617 if (!vfs_parse_filedate(0, &ST.st_ctime))
618 break;
619 ST.st_atime = ST.st_mtime = ST.st_ctime;
621 break;
622 case 'D': {
623 struct tm tim;
624 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
625 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
626 break;
627 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
629 break;
630 case 'E': {
631 int maj, min;
632 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
633 break;
634 #ifdef HAVE_STRUCT_STAT_ST_RDEV
635 ST.st_rdev = makedev (maj, min);
636 #endif
641 vfs_s_free_entry (me, ent);
642 reply_code = fish_decode_reply(buffer + 4, 0);
643 if (reply_code == COMPLETE) {
644 g_free (SUP.cwdir);
645 SUP.cwdir = g_strdup (remote_path);
646 print_vfs_message (_("%s: done."), me->name);
647 return 0;
648 } else if (reply_code == ERROR) {
649 me->verrno = EACCES;
650 } else {
651 me->verrno = E_REMOTE;
654 error:
655 print_vfs_message (_("%s: failure"), me->name);
656 return -1;
659 static int
660 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
662 struct vfs_s_super *super = FH_SUPER;
663 int n, total;
664 char buffer[8192];
665 struct stat s;
666 int was_error = 0;
667 int h;
668 char *quoted_name;
670 h = open (localname, O_RDONLY);
672 if (h == -1)
673 ERRNOR (EIO, -1);
674 if (fstat(h, &s)<0) {
675 close (h);
676 ERRNOR (EIO, -1);
679 /* First, try this as stor:
681 * ( head -c number ) | ( cat > file; cat >/dev/null )
683 * If `head' is not present on the remote system, `dd' will be used.
684 * Unfortunately, we cannot trust most non-GNU `head' implementations
685 * even if `-c' options is supported. Therefore, we separate GNU head
686 * (and other modern heads?) using `-q' and `-' . This causes another
687 * implementations to fail (because of "incorrect options").
689 * Fallback is:
691 * rest=<number>
692 * while [ $rest -gt 0 ]
693 * do
694 * cnt=`expr \( $rest + 255 \) / 256`
695 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
696 * rest=`expr $rest - $n`
697 * done
699 * `dd' was not designed for full filling of input buffers,
700 * and does not report exact number of bytes (not blocks).
701 * Therefore a more complex shell script is needed.
703 * On some systems non-GNU head writes "Usage:" error report to stdout
704 * instead of stderr. It makes impossible the use of "head || dd"
705 * algorithm for file appending case, therefore just "dd" is used for it.
708 quoted_name = strutils_shell_escape(name);
709 print_vfs_message(_("fish: store %s: sending command..."), quoted_name );
711 /* FIXME: File size is limited to ULONG_MAX */
712 if (!fh->u.fish.append)
713 n = fish_command (me, super, WAIT_REPLY,
714 "#STOR %lu /%s\n"
715 "echo '### 001'\n"
716 "file=/%s\n"
717 "res=`exec 3>&1\n"
718 "(\n"
719 "head -c %lu -q - || echo DD >&3\n"
720 ") 2>/dev/null | (\n"
721 "cat > $file\n"
722 "cat > /dev/null\n"
723 ")`; [ \"$res\" = DD ] && {\n"
724 "> \"$file\"\n"
725 "rest=%lu\n"
726 "while [ $rest -gt 0 ]\n"
727 "do\n"
728 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
729 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
730 " rest=`expr $rest - $n`\n"
731 "done\n"
732 "}; echo '### 200'\n",
733 (unsigned long) s.st_size, quoted_name,
734 quoted_name, (unsigned long) s.st_size,
735 (unsigned long) s.st_size);
736 else
737 n = fish_command (me, super, WAIT_REPLY,
738 "#STOR %lu /%s\n"
739 "echo '### 001'\n"
740 "{\n"
741 "file=/%s\n"
742 "rest=%lu\n"
743 "while [ $rest -gt 0 ]\n"
744 "do\n"
745 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
746 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
747 " rest=`expr $rest - $n`\n"
748 "done\n"
749 "}; echo '### 200'\n",
750 (unsigned long) s.st_size, quoted_name,
751 quoted_name, (unsigned long) s.st_size);
753 if (n != PRELIM) {
754 close (h);
755 ERRNOR(E_REMOTE, -1);
757 total = 0;
759 while (1) {
760 int t;
761 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
762 if ((errno == EINTR) && tty_got_interrupt ())
763 continue;
764 print_vfs_message(_("fish: Local read failed, sending zeros") );
765 close(h);
766 h = open( "/dev/zero", O_RDONLY );
768 if (n == 0)
769 break;
770 if ((t = write (SUP.sockw, buffer, n)) != n) {
771 if (t == -1) {
772 me->verrno = errno;
773 } else {
774 me->verrno = EIO;
776 goto error_return;
778 tty_disable_interrupt_key ();
779 total += n;
780 print_vfs_message(_("fish: storing %s %d (%lu)"),
781 was_error ? _("zeros") : _("file"), total,
782 (unsigned long) s.st_size);
784 close(h);
785 g_free(quoted_name);
786 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
787 ERRNOR (E_REMOTE, -1);
788 return 0;
789 error_return:
790 close(h);
791 fish_get_reply(me, SUP.sockr, NULL, 0);
792 g_free(quoted_name);
793 return -1;
796 static int
797 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
799 char *name;
800 char *quoted_name;
801 if (offset)
802 ERRNOR (E_NOTSUPP, 0);
803 name = vfs_s_fullpath (me, fh->ino);
804 if (!name)
805 return 0;
806 quoted_name = strutils_shell_escape(name);
807 fh->u.fish.append = 0;
810 * Check whether the remote file is readable by using `dd' to copy
811 * a single byte from the remote file to /dev/null. If `dd' completes
812 * with exit status of 0 use `cat' to send the file contents to the
813 * standard output (i.e. over the network).
815 offset = fish_command (me, FH_SUPER, WANT_STRING,
816 "#RETR /%s\n"
817 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
818 "then\n"
819 "ls -ln /%s 2>/dev/null | (\n"
820 "read p l u g s r\n"
821 "echo $s\n"
822 ")\n"
823 "echo '### 100'\n"
824 "cat /%s\n"
825 "echo '### 200'\n"
826 "else\n"
827 "echo '### 500'\n"
828 "fi\n",
829 quoted_name, quoted_name, quoted_name, quoted_name );
830 g_free (quoted_name);
831 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
832 fh->linear = LS_LINEAR_OPEN;
833 fh->u.fish.got = 0;
834 errno = 0;
835 #if SIZEOF_OFF_T == SIZEOF_LONG
836 fh->u.fish.total = strtol (reply_str, NULL, 10);
837 #else
838 fh->u.fish.total = strtoll (reply_str, NULL, 10);
839 #endif
840 if (errno != 0)
841 ERRNOR (E_REMOTE, 0);
842 return 1;
845 static void
846 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
848 struct vfs_s_super *super = FH_SUPER;
849 char buffer[8192];
850 int n;
852 print_vfs_message( _("Aborting transfer...") );
853 do {
854 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
855 if (n) {
856 if ((n = read(SUP.sockr, buffer, n)) < 0)
857 return;
858 fh->u.fish.got += n;
860 } while (n);
862 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
863 print_vfs_message( _("Error reported after abort.") );
864 else
865 print_vfs_message( _("Aborted transfer would be successful.") );
868 static int
869 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
871 struct vfs_s_super *super = FH_SUPER;
872 int n = 0;
873 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
874 tty_disable_interrupt_key ();
875 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
876 if ((errno == EINTR) && !tty_got_interrupt ())
877 continue;
878 break;
880 tty_enable_interrupt_key();
882 if (n>0) fh->u.fish.got += n;
883 if (n<0) fish_linear_abort(me, fh);
884 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
885 ERRNOR (E_REMOTE, -1);
886 ERRNOR (errno, n);
889 static void
890 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
892 if (fh->u.fish.total != fh->u.fish.got)
893 fish_linear_abort(me, fh);
896 static int
897 fish_ctl (void *fh, int ctlop, void *arg)
899 (void) arg;
900 (void) fh;
901 (void) ctlop;
902 return 0;
903 #if 0
904 switch (ctlop) {
905 case VFS_CTL_IS_NOTREADY:
907 int v;
909 if (!FH->linear)
910 vfs_die ("You may not do this");
911 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
912 return 0;
914 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
915 if (((v < 0) && (errno == EINTR)) || v == 0)
916 return 1;
917 return 0;
919 default:
920 return 0;
922 #endif
925 static int
926 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
928 int r;
930 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
931 vfs_stamp_create (&vfs_fish_ops, super);
932 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
933 if (flags & OPT_FLUSH)
934 vfs_s_invalidate(me, super);
935 return 0;
938 #define PREFIX \
939 char buf[BUF_LARGE]; \
940 const char *crpath; \
941 char *rpath, *mpath = g_strdup (path); \
942 struct vfs_s_super *super; \
943 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
944 g_free (mpath); \
945 return -1; \
947 rpath = strutils_shell_escape(crpath); \
948 g_free (mpath);
950 #define POSTFIX(flags) \
951 g_free (rpath); \
952 return fish_send_command(me, super, buf, flags);
954 static int
955 fish_chmod (struct vfs_class *me, const char *path, int mode)
957 PREFIX
958 g_snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
959 "if chmod %4.4o /%s 2>/dev/null; then\n"
960 "echo '### 000'\n"
961 "else\n"
962 "echo '### 500'\n"
963 "fi\n",
964 mode & 07777, rpath,
965 mode & 07777, rpath);
966 POSTFIX(OPT_FLUSH);
969 #define FISH_OP(name, string) \
970 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
972 char buf[BUF_LARGE]; \
973 const char *crpath1, *crpath2; \
974 char *rpath1, *rpath2, *mpath1, *mpath2; \
975 struct vfs_s_super *super1, *super2; \
976 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = g_strdup(path1), &super1, 0))) { \
977 g_free (mpath1); \
978 return -1; \
980 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = g_strdup(path2), &super2, 0))) { \
981 g_free (mpath1); \
982 g_free (mpath2); \
983 return -1; \
985 rpath1 = strutils_shell_escape (crpath1); \
986 g_free (mpath1); \
987 rpath2 = strutils_shell_escape (crpath2); \
988 g_free (mpath2); \
989 g_snprintf(buf, sizeof(buf), string "\n", rpath1, rpath2, rpath1, rpath2); \
990 g_free (rpath1); \
991 g_free (rpath2); \
992 return fish_send_command(me, super2, buf, OPT_FLUSH); \
995 FISH_OP(rename, "#RENAME /%s /%s\n"
996 "if mv /%s /%s 2>/dev/null; then\n"
997 "echo '### 000'\n"
998 "else\n"
999 "echo '### 500'\n"
1000 "fi\n")
1001 FISH_OP(link, "#LINK /%s /%s\n"
1002 "if ln /%s /%s 2>/dev/null; then\n"
1003 "echo '### 000'\n"
1004 "else\n"
1005 "echo '### 500'\n"
1006 "fi\n")
1008 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
1010 char *qsetto;
1011 PREFIX
1012 qsetto = strutils_shell_escape (setto);
1013 g_snprintf(buf, sizeof(buf),
1014 "#SYMLINK %s /%s\n"
1015 "if ln -s %s /%s 2>/dev/null; then\n"
1016 "echo '### 000'\n"
1017 "else\n"
1018 "echo '### 500'\n"
1019 "fi\n",
1020 qsetto, rpath, qsetto, rpath);
1021 g_free (qsetto);
1022 POSTFIX(OPT_FLUSH);
1025 static int
1026 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
1028 char *sowner, *sgroup;
1029 struct passwd *pw;
1030 struct group *gr;
1032 if ((pw = getpwuid (owner)) == NULL)
1033 return 0;
1035 if ((gr = getgrgid (group)) == NULL)
1036 return 0;
1038 sowner = pw->pw_name;
1039 sgroup = gr->gr_name;
1041 PREFIX
1042 g_snprintf (buf, sizeof(buf),
1043 "#CHOWN %s:%s /%s\n"
1044 "if chown %s:%s /%s 2>/dev/null; then\n"
1045 "echo '### 000'\n"
1046 "else\n"
1047 "echo '### 500'\n"
1048 "fi\n",
1049 sowner, sgroup, rpath,
1050 sowner, sgroup, rpath);
1051 fish_send_command (me, super, buf, OPT_FLUSH);
1052 /* FIXME: what should we report if chgrp succeeds but chown fails? */
1053 /* fish_send_command(me, super, buf, OPT_FLUSH); */
1054 POSTFIX (OPT_FLUSH)
1058 static int fish_unlink (struct vfs_class *me, const char *path)
1060 PREFIX
1061 g_snprintf(buf, sizeof(buf),
1062 "#DELE /%s\n"
1063 "if rm -f /%s 2>/dev/null; then\n"
1064 "echo '### 000'\n"
1065 "else\n"
1066 "echo '### 500'\n"
1067 "fi\n",
1068 rpath, rpath);
1069 POSTFIX(OPT_FLUSH);
1072 static int fish_exists (struct vfs_class *me, const char *path)
1074 PREFIX
1076 g_snprintf(buf, sizeof(buf),
1077 "#ISEXISTS /%s\n"
1078 "ls -l /%s >/dev/null 2>/dev/null\n"
1079 "echo '### '$?\n",
1080 rpath, rpath);
1082 g_free (rpath);
1084 if ( fish_send_command(me, super, buf, OPT_FLUSH) == 0 )
1085 return 1;
1087 return 0;
1091 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1093 int ret_code;
1095 PREFIX
1097 (void) mode;
1099 g_snprintf(buf, sizeof(buf),
1100 "#MKD /%s\n"
1101 "if mkdir /%s 2>/dev/null; then\n"
1102 "echo '### 000'\n"
1103 "else\n"
1104 "echo '### 500'\n"
1105 "fi\n",
1106 rpath, rpath);
1108 g_free (rpath);
1109 ret_code = fish_send_command(me, super, buf, OPT_FLUSH);
1111 if ( ret_code != 0 )
1112 return ret_code;
1114 if ( ! fish_exists (me, path) ){
1115 ERRNOR (EACCES, -1);
1117 return 0;
1120 static int fish_rmdir (struct vfs_class *me, const char *path)
1122 PREFIX
1123 g_snprintf(buf, sizeof(buf),
1124 "#RMD /%s\n"
1125 "if rmdir /%s 2>/dev/null; then\n"
1126 "echo '### 000'\n"
1127 "else\n"
1128 "echo '### 500'\n"
1129 "fi\n",
1130 rpath, rpath);
1131 POSTFIX(OPT_FLUSH);
1134 static int
1135 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1136 int mode)
1138 (void) mode;
1140 fh->u.fish.append = 0;
1141 /* File will be written only, so no need to retrieve it */
1142 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1143 fh->u.fish.append = flags & O_APPEND;
1144 if (!fh->ino->localname) {
1145 int tmp_handle =
1146 vfs_mkstemps (&fh->ino->localname, me->name,
1147 fh->ino->ent->name);
1148 if (tmp_handle == -1)
1149 return -1;
1150 close (tmp_handle);
1152 return 0;
1154 if (!fh->ino->localname)
1155 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1156 return -1;
1157 if (!fh->ino->localname)
1158 vfs_die ("retrieve_file failed to fill in localname");
1159 return 0;
1162 static void
1163 fish_fill_names (struct vfs_class *me, fill_names_f func)
1165 struct vfs_s_super *super = MEDATA->supers;
1166 char *name;
1168 char gbuf[10];
1170 while (super)
1172 const char *flags = "";
1173 switch (SUP.flags)
1175 case FISH_FLAG_RSH:
1176 flags = ":r";
1177 break;
1178 case FISH_FLAG_COMPRESSED:
1179 flags = ":C";
1180 break;
1181 default:
1182 if (SUP.flags > FISH_FLAG_RSH)
1184 break;
1185 g_snprintf (gbuf, sizeof (gbuf), ":%d", SUP.flags);
1186 flags = gbuf;
1188 break;
1191 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1192 "/", SUP.cwdir, (char *) NULL);
1193 (*func)(name);
1194 g_free (name);
1195 super = super->next;
1199 static void *
1200 fish_open (struct vfs_class *me, const char *file, int flags, int mode)
1203 sorry, i've places hack here
1204 cause fish don't able to open files with O_EXCL flag
1206 flags &= ~O_EXCL;
1207 return vfs_s_open (me, file, flags, mode);
1211 void
1212 init_fish (void)
1214 static struct vfs_s_subclass fish_subclass;
1216 fish_subclass.flags = VFS_S_REMOTE;
1217 fish_subclass.archive_same = fish_archive_same;
1218 fish_subclass.open_archive = fish_open_archive;
1219 fish_subclass.free_archive = fish_free_archive;
1220 fish_subclass.fh_open = fish_fh_open;
1221 fish_subclass.dir_load = fish_dir_load;
1222 fish_subclass.file_store = fish_file_store;
1223 fish_subclass.linear_start = fish_linear_start;
1224 fish_subclass.linear_read = fish_linear_read;
1225 fish_subclass.linear_close = fish_linear_close;
1227 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1228 vfs_fish_ops.name = "fish";
1229 vfs_fish_ops.prefix = "sh:";
1230 vfs_fish_ops.fill_names = fish_fill_names;
1231 vfs_fish_ops.chmod = fish_chmod;
1232 vfs_fish_ops.chown = fish_chown;
1233 vfs_fish_ops.open = fish_open;
1234 vfs_fish_ops.symlink = fish_symlink;
1235 vfs_fish_ops.link = fish_link;
1236 vfs_fish_ops.unlink = fish_unlink;
1237 vfs_fish_ops.rename = fish_rename;
1238 vfs_fish_ops.mkdir = fish_mkdir;
1239 vfs_fish_ops.rmdir = fish_rmdir;
1240 vfs_fish_ops.ctl = fish_ctl;
1241 vfs_register_class (&vfs_fish_ops);