Ticket #1867: fish: omit '-l' parameter for userless URLs.
[midnight-commander.git] / vfs / fish.c
blob04c85273f8fdba6c63c828555eeeda539a555bbb
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: \verbatim /#sh:user@host[:Cr]/path \endverbatim
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;
252 * Add the user name to the ssh command line only if it was explicitly
253 * set in vfs URL. rsh/ssh will get current user by default
254 * plus we can set convenient overrides in ~/.ssh/config (explicit -l
255 * option breaks it for some)
258 if (SUP.user) {
259 argv[i++] = "-l";
260 argv[i++] = SUP.user;
262 else
264 /* The rest of the code assumes it to be a valid username */
265 SUP.user = vfs_get_local_username();
268 argv[i++] = SUP.host;
269 argv[i++] = "echo FISH:; /bin/sh";
270 argv[i++] = NULL;
272 fish_pipeopen (super, xsh, argv);
275 char answer[2048];
276 print_vfs_message (_("fish: Waiting for initial line..."));
277 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
278 ERRNOR (E_PROTO, -1);
279 print_vfs_message ("%s", answer);
280 if (strstr (answer, "assword")) {
282 /* Currently, this does not work. ssh reads passwords from
283 /dev/tty, not from stdin :-(. */
285 message (D_ERROR, MSG_ERROR,
287 ("Sorry, we cannot do password authenticated connections for now."));
288 ERRNOR (EPERM, -1);
289 if (!SUP.password) {
290 char *p, *op;
291 p = g_strconcat (_(" fish: Password required for "),
292 SUP.user, " ", (char *) NULL);
293 op = vfs_get_password (p);
294 g_free (p);
295 if (op == NULL)
296 ERRNOR (EPERM, -1);
297 SUP.password = op;
299 print_vfs_message (_("fish: Sending password..."));
300 write (SUP.sockw, SUP.password, strlen (SUP.password));
301 write (SUP.sockw, "\n", 1);
305 print_vfs_message (_("fish: Sending initial line..."));
307 * Run `start_fish_server'. If it doesn't exist - no problem,
308 * we'll talk directly to the shell.
310 if (fish_command
311 (me, super, WAIT_REPLY,
312 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
313 COMPLETE)
314 ERRNOR (E_PROTO, -1);
316 print_vfs_message (_("fish: Handshaking version..."));
317 if (fish_command
318 (me, super, WAIT_REPLY,
319 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
320 ERRNOR (E_PROTO, -1);
322 /* Set up remote locale to C, otherwise dates cannot be recognized */
323 if (fish_command
324 (me, super, WAIT_REPLY,
325 "LANG=C; LC_ALL=C; LC_TIME=C\n"
326 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
327 != COMPLETE)
328 ERRNOR (E_PROTO, -1);
330 print_vfs_message (_("fish: Setting up current directory..."));
331 SUP.cwdir = fish_getcwd (me, super);
332 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
333 #if 0
334 super->name =
335 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
336 #endif
337 super->name = g_strdup (PATH_SEP_STR);
339 super->root =
340 vfs_s_new_inode (me, super,
341 vfs_s_default_stat (me, S_IFDIR | 0755));
342 return 0;
345 static int
346 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
347 const char *archive_name, char *op)
349 char *host, *user, *password, *p;
350 int flags;
352 (void) archive_name;
354 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
355 &password, 0, URL_NOSLASH | URL_USE_ANONYMOUS);
357 g_free (p);
359 SUP.host = host;
360 SUP.user = user;
361 SUP.flags = flags;
362 if (!strncmp (op, "rsh:", 4))
363 SUP.flags = FISH_FLAG_RSH;
364 SUP.cwdir = NULL;
365 if (password)
366 SUP.password = password;
367 return fish_open_archive_int (me, super);
370 static int
371 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
372 const char *archive_name, char *op, void *cookie)
374 char *host, *user;
375 int flags;
376 int result;
378 (void) me;
379 (void) archive_name;
380 (void) cookie;
382 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
383 URL_NOSLASH | URL_USE_ANONYMOUS);
385 g_free (op);
387 if (user == NULL)
388 user = vfs_get_local_username();
390 result = ((strcmp (host, SUP.host) == 0)
391 && (strcmp (user, SUP.user) == 0)
392 && (flags == SUP.flags));
394 g_free (host);
395 g_free (user);
397 return result;
400 static int
401 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
403 struct vfs_s_super *super = dir->super;
404 char buffer[8192];
405 struct vfs_s_entry *ent = NULL;
406 FILE *logfile;
407 char *quoted_path;
408 int reply_code;
409 gchar *shell_commands;
411 #if 0
413 * Simple FISH debug interface :]
415 if (!(MEDATA->logfile))
417 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
419 #endif /* 0 */
421 logfile = MEDATA->logfile;
423 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
425 gettimeofday(&dir->timestamp, NULL);
426 dir->timestamp.tv_sec += fish_directory_timeout;
427 quoted_path = strutils_shell_escape (remote_path);
428 shell_commands = g_strconcat(
429 "#LIST /%s\n"
430 "if `perl -v > /dev/null 2>&1` ; then\n"
431 "perl -e '\n"
432 "use strict;\n"
433 "use POSIX;\n"
434 "use Fcntl;\n"
435 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
436 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
437 "my $dirname = $ARGV[0];\n"
438 "if (opendir ( DIR, $dirname )) {\n"
439 "while( (my $filename = readdir(DIR))){\n"
440 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
441 "my $mloctime= strftime(\"%%m-%%d-%%Y %%H:%%M\", localtime $mtime);\n"
443 "my $strutils_shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
444 "my $e_filename = $filename;\n"
445 "$e_filename =~ $strutils_shell_escape_regex;\n"
446 "if (S_ISLNK($mode) ) {\n"
447 "my $linkname = readlink (\"$dirname/$filename\");\n"
448 "$linkname =~ $strutils_shell_escape_regex;\n"
449 "\n"
450 "printf(\"R%%o %%o $uid.$gid\\n"
451 "S$size\\n"
452 "d$mloctime\\n"
453 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
454 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
455 "} else {\n"
456 "printf(\"R%%o %%o $uid.$gid\\n"
457 "S$size\\n"
458 "d$mloctime\\n"
459 ":\\\"$e_filename\\\"\\n"
460 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
461 "}}\n"
463 "printf(\"### 200\\n\");\n"
464 "closedir(DIR);\n"
465 "} else {\n"
466 "printf(\"### 500\\n\");\n"
467 "}\n"
468 "exit 0\n"
469 "' /%s ||\n" /* ARGV[0] - path to browse */
470 " echo '### 500'\n" /* do not hang if perl is to eval it */
471 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
472 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
473 "LSOPT=\"-Qlan\";\n"
474 "ADD=0;\n"
475 "else\n"
476 "LSOPT=\"-lan\";\n"
477 "ADD=1;\n"
478 "fi\n"
479 "ls $LSOPT /%s 2>/dev/null | grep '^[^cbt]' | (\n"
480 "while read p l u g s m d y n n2 n3; do\n"
481 "if test \"$m\" = \"0\" ; then \n"
482 "s=$d; m=$y; d=$n y=$n2; n=$n3\n"
483 "else\n"
484 "n=$n\" \"$n2\" \"$n3\n"
485 "fi\n"
486 "if [ $ADD = 0 ]; then\n"
487 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
488 "elif `sed --version >/dev/null 2>&1` ; then\n"
489 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
491 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
492 "else\n"
493 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
494 "fi\n"
495 "done )\n"
496 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
497 "while read p l u g a i m d y n n2 n3; do\n"
498 "if test \"$a\" = \"0\" ; then \n"
499 "a=$m; i=$d; m=$y; d=$n y=$n2; n=$n3\n"
500 "else\n"
501 "n=$n\" \"$n2\" \"$n3\n"
502 "fi\n"
503 "if [ $ADD = 0 ]; then\n"
504 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
505 "elif `sed --version >/dev/null 2>&1` ; then\n"
506 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
507 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
508 "else\n"
509 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
510 "fi\n"
511 "done)\n"
512 "echo '### 200'\n"
513 "else\n"
514 "echo '### 500'\n"
515 "fi\n"
516 , (char *) NULL
519 fish_command (me, super, NONE, shell_commands,
520 quoted_path, quoted_path, quoted_path, quoted_path, quoted_path, quoted_path);
522 g_free(shell_commands);
523 g_free (quoted_path);
524 ent = vfs_s_generate_entry(me, NULL, dir, 0);
525 while (1) {
526 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
527 if ((!res) || (res == EINTR)) {
528 vfs_s_free_entry(me, ent);
529 me->verrno = ECONNRESET;
530 goto error;
532 if (logfile) {
533 fputs (buffer, logfile);
534 fputs ("\n", logfile);
535 fflush (logfile);
537 if (!strncmp(buffer, "### ", 4))
538 break;
539 if ((!buffer[0])) {
540 if (ent->name) {
541 vfs_s_insert_entry(me, dir, ent);
542 ent = vfs_s_generate_entry(me, NULL, dir, 0);
544 continue;
547 #define ST ent->ino->st
549 switch(buffer[0]) {
550 case ':': {
551 char *temp;
552 char *data_start = buffer+1;
553 char *filename = data_start;
554 char *linkname = data_start;
555 char *filename_bound = filename + strlen(filename);
556 char *linkname_bound = filename_bound;
557 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
558 break; /* We'll do "." and ".." ourselves */
560 if (S_ISLNK(ST.st_mode)) {
561 /* we expect: "escaped-name" -> "escaped-name"
562 // -> cannot occur in filenames,
563 // because it will be escaped to -\> */
565 if (*filename == '"')
566 ++filename;
568 linkname = strstr(filename, "\" -> \"");
569 if (!linkname)
571 /* broken client, or smth goes wrong */
572 linkname = filename_bound;
573 if (filename_bound > filename
574 && *(filename_bound - 1) == '"')
575 --filename_bound; /* skip trailing " */
577 else
579 filename_bound = linkname;
580 linkname += 6; /* strlen ("\" -> \"") */
581 if (*(linkname_bound - 1) == '"')
582 --linkname_bound; /* skip trailing " */
585 ent->name = str_dup_range(filename, filename_bound);
586 temp = ent->name;
587 ent->name = strutils_shell_unescape(ent->name);
588 g_free(temp);
590 ent->ino->linkname = str_dup_range(linkname, linkname_bound);
591 temp = ent->ino->linkname;
592 ent->ino->linkname = strutils_shell_unescape(ent->ino->linkname);
593 g_free(temp);
594 } else {
595 /* we expect: "escaped-name" */
596 if (filename_bound - filename > 2)
599 there is at least 2 "
600 and we skip them
602 if (*filename == '"')
603 ++filename;
604 if (*(filename_bound - 1) == '"')
605 --filename_bound;
607 ent->name = str_dup_range(filename, filename_bound);
608 temp = ent->name;
609 ent->name = strutils_shell_unescape(ent->name);
610 g_free(temp);
612 break;
614 case 'S':
615 #ifdef HAVE_ATOLL
616 ST.st_size = (off_t) atoll (buffer+1);
617 #else
618 ST.st_size = (off_t) atof (buffer+1);
619 #endif
620 break;
621 case 'P': {
622 size_t skipped;
623 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
624 break;
626 case 'R': {
628 raw filemode:
629 we expect: Roctal-filemode octal-filetype uid.gid
631 size_t skipped;
632 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
633 break;
635 case 'd': {
636 vfs_split_text(buffer+1);
637 if (!vfs_parse_filedate(0, &ST.st_ctime))
638 break;
639 ST.st_atime = ST.st_mtime = ST.st_ctime;
641 break;
642 case 'D': {
643 struct tm tim;
644 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
645 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
646 break;
647 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
649 break;
650 case 'E': {
651 int maj, min;
652 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
653 break;
654 #ifdef HAVE_STRUCT_STAT_ST_RDEV
655 ST.st_rdev = makedev (maj, min);
656 #endif
661 vfs_s_free_entry (me, ent);
662 reply_code = fish_decode_reply(buffer + 4, 0);
663 if (reply_code == COMPLETE) {
664 g_free (SUP.cwdir);
665 SUP.cwdir = g_strdup (remote_path);
666 print_vfs_message (_("%s: done."), me->name);
667 return 0;
668 } else if (reply_code == ERROR) {
669 me->verrno = EACCES;
670 } else {
671 me->verrno = E_REMOTE;
674 error:
675 print_vfs_message (_("%s: failure"), me->name);
676 return -1;
679 static int
680 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
682 struct vfs_s_super *super = FH_SUPER;
683 int n, total;
684 char buffer[8192];
685 struct stat s;
686 int was_error = 0;
687 int h;
688 char *quoted_name;
690 h = open (localname, O_RDONLY);
692 if (h == -1)
693 ERRNOR (EIO, -1);
694 if (fstat(h, &s)<0) {
695 close (h);
696 ERRNOR (EIO, -1);
699 /* First, try this as stor:
701 * ( head -c number ) | ( cat > file; cat >/dev/null )
703 * If `head' is not present on the remote system, `dd' will be used.
704 * Unfortunately, we cannot trust most non-GNU `head' implementations
705 * even if `-c' options is supported. Therefore, we separate GNU head
706 * (and other modern heads?) using `-q' and `-' . This causes another
707 * implementations to fail (because of "incorrect options").
709 * Fallback is:
711 * rest=<number>
712 * while [ $rest -gt 0 ]
713 * do
714 * cnt=`expr \( $rest + 255 \) / 256`
715 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
716 * rest=`expr $rest - $n`
717 * done
719 * `dd' was not designed for full filling of input buffers,
720 * and does not report exact number of bytes (not blocks).
721 * Therefore a more complex shell script is needed.
723 * On some systems non-GNU head writes "Usage:" error report to stdout
724 * instead of stderr. It makes impossible the use of "head || dd"
725 * algorithm for file appending case, therefore just "dd" is used for it.
728 quoted_name = strutils_shell_escape(name);
729 print_vfs_message(_("fish: store %s: sending command..."), quoted_name );
731 /* FIXME: File size is limited to ULONG_MAX */
732 if (!fh->u.fish.append)
733 n = fish_command (me, super, WAIT_REPLY,
734 "#STOR %lu /%s\n"
735 "echo '### 001'\n"
736 "file=/%s\n"
737 "res=`exec 3>&1\n"
738 "(\n"
739 "head -c %lu -q - || echo DD >&3\n"
740 ") 2>/dev/null | (\n"
741 "cat > $file\n"
742 "cat > /dev/null\n"
743 ")`; [ \"$res\" = DD ] && {\n"
744 "> \"$file\"\n"
745 "rest=%lu\n"
746 "while [ $rest -gt 0 ]\n"
747 "do\n"
748 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
749 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
750 " rest=`expr $rest - $n`\n"
751 "done\n"
752 "}; echo '### 200'\n",
753 (unsigned long) s.st_size, quoted_name,
754 quoted_name, (unsigned long) s.st_size,
755 (unsigned long) s.st_size);
756 else
757 n = fish_command (me, super, WAIT_REPLY,
758 "#STOR %lu /%s\n"
759 "echo '### 001'\n"
760 "{\n"
761 "file=/%s\n"
762 "rest=%lu\n"
763 "while [ $rest -gt 0 ]\n"
764 "do\n"
765 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
766 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
767 " rest=`expr $rest - $n`\n"
768 "done\n"
769 "}; echo '### 200'\n",
770 (unsigned long) s.st_size, quoted_name,
771 quoted_name, (unsigned long) s.st_size);
773 if (n != PRELIM) {
774 close (h);
775 ERRNOR(E_REMOTE, -1);
777 total = 0;
779 while (1) {
780 int t;
781 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
782 if ((errno == EINTR) && tty_got_interrupt ())
783 continue;
784 print_vfs_message(_("fish: Local read failed, sending zeros") );
785 close(h);
786 h = open( "/dev/zero", O_RDONLY );
788 if (n == 0)
789 break;
790 if ((t = write (SUP.sockw, buffer, n)) != n) {
791 if (t == -1) {
792 me->verrno = errno;
793 } else {
794 me->verrno = EIO;
796 goto error_return;
798 tty_disable_interrupt_key ();
799 total += n;
800 print_vfs_message(_("fish: storing %s %d (%lu)"),
801 was_error ? _("zeros") : _("file"), total,
802 (unsigned long) s.st_size);
804 close(h);
805 g_free(quoted_name);
806 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
807 ERRNOR (E_REMOTE, -1);
808 return 0;
809 error_return:
810 close(h);
811 fish_get_reply(me, SUP.sockr, NULL, 0);
812 g_free(quoted_name);
813 return -1;
816 static int
817 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
819 char *name;
820 char *quoted_name;
821 if (offset)
822 ERRNOR (E_NOTSUPP, 0);
823 name = vfs_s_fullpath (me, fh->ino);
824 if (!name)
825 return 0;
826 quoted_name = strutils_shell_escape(name);
827 fh->u.fish.append = 0;
830 * Check whether the remote file is readable by using `dd' to copy
831 * a single byte from the remote file to /dev/null. If `dd' completes
832 * with exit status of 0 use `cat' to send the file contents to the
833 * standard output (i.e. over the network).
835 offset = fish_command (me, FH_SUPER, WANT_STRING,
836 "#RETR /%s\n"
837 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
838 "then\n"
839 "ls -ln /%s 2>/dev/null | (\n"
840 "read p l u g s r\n"
841 "echo $s\n"
842 ")\n"
843 "echo '### 100'\n"
844 "cat /%s\n"
845 "echo '### 200'\n"
846 "else\n"
847 "echo '### 500'\n"
848 "fi\n",
849 quoted_name, quoted_name, quoted_name, quoted_name );
850 g_free (quoted_name);
851 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
852 fh->linear = LS_LINEAR_OPEN;
853 fh->u.fish.got = 0;
854 errno = 0;
855 #if SIZEOF_OFF_T == SIZEOF_LONG
856 fh->u.fish.total = strtol (reply_str, NULL, 10);
857 #else
858 fh->u.fish.total = strtoll (reply_str, NULL, 10);
859 #endif
860 if (errno != 0)
861 ERRNOR (E_REMOTE, 0);
862 return 1;
865 static void
866 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
868 struct vfs_s_super *super = FH_SUPER;
869 char buffer[8192];
870 int n;
872 print_vfs_message( _("Aborting transfer...") );
873 do {
874 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
875 if (n) {
876 if ((n = read(SUP.sockr, buffer, n)) < 0)
877 return;
878 fh->u.fish.got += n;
880 } while (n);
882 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
883 print_vfs_message( _("Error reported after abort.") );
884 else
885 print_vfs_message( _("Aborted transfer would be successful.") );
888 static int
889 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
891 struct vfs_s_super *super = FH_SUPER;
892 int n = 0;
893 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
894 tty_disable_interrupt_key ();
895 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
896 if ((errno == EINTR) && !tty_got_interrupt ())
897 continue;
898 break;
900 tty_enable_interrupt_key();
902 if (n>0) fh->u.fish.got += n;
903 if (n<0) fish_linear_abort(me, fh);
904 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
905 ERRNOR (E_REMOTE, -1);
906 ERRNOR (errno, n);
909 static void
910 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
912 if (fh->u.fish.total != fh->u.fish.got)
913 fish_linear_abort(me, fh);
916 static int
917 fish_ctl (void *fh, int ctlop, void *arg)
919 (void) arg;
920 (void) fh;
921 (void) ctlop;
922 return 0;
923 #if 0
924 switch (ctlop) {
925 case VFS_CTL_IS_NOTREADY:
927 int v;
929 if (!FH->linear)
930 vfs_die ("You may not do this");
931 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
932 return 0;
934 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
935 if (((v < 0) && (errno == EINTR)) || v == 0)
936 return 1;
937 return 0;
939 default:
940 return 0;
942 #endif
945 static int
946 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
948 int r;
950 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
951 vfs_stamp_create (&vfs_fish_ops, super);
952 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
953 if (flags & OPT_FLUSH)
954 vfs_s_invalidate(me, super);
955 return 0;
958 #define PREFIX \
959 char buf[BUF_LARGE]; \
960 const char *crpath; \
961 char *rpath, *mpath = g_strdup (path); \
962 struct vfs_s_super *super; \
963 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
964 g_free (mpath); \
965 return -1; \
967 rpath = strutils_shell_escape(crpath); \
968 g_free (mpath);
970 #define POSTFIX(flags) \
971 g_free (rpath); \
972 return fish_send_command(me, super, buf, flags);
974 static int
975 fish_chmod (struct vfs_class *me, const char *path, int mode)
977 PREFIX
978 g_snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
979 "if chmod %4.4o /%s 2>/dev/null; then\n"
980 "echo '### 000'\n"
981 "else\n"
982 "echo '### 500'\n"
983 "fi\n",
984 mode & 07777, rpath,
985 mode & 07777, rpath);
986 POSTFIX(OPT_FLUSH);
989 #define FISH_OP(name, string) \
990 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
992 char buf[BUF_LARGE]; \
993 const char *crpath1, *crpath2; \
994 char *rpath1, *rpath2, *mpath1, *mpath2; \
995 struct vfs_s_super *super1, *super2; \
996 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = g_strdup(path1), &super1, 0))) { \
997 g_free (mpath1); \
998 return -1; \
1000 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = g_strdup(path2), &super2, 0))) { \
1001 g_free (mpath1); \
1002 g_free (mpath2); \
1003 return -1; \
1005 rpath1 = strutils_shell_escape (crpath1); \
1006 g_free (mpath1); \
1007 rpath2 = strutils_shell_escape (crpath2); \
1008 g_free (mpath2); \
1009 g_snprintf(buf, sizeof(buf), string "\n", rpath1, rpath2, rpath1, rpath2); \
1010 g_free (rpath1); \
1011 g_free (rpath2); \
1012 return fish_send_command(me, super2, buf, OPT_FLUSH); \
1015 FISH_OP(rename, "#RENAME /%s /%s\n"
1016 "if mv /%s /%s 2>/dev/null; then\n"
1017 "echo '### 000'\n"
1018 "else\n"
1019 "echo '### 500'\n"
1020 "fi\n")
1021 FISH_OP(link, "#LINK /%s /%s\n"
1022 "if ln /%s /%s 2>/dev/null; then\n"
1023 "echo '### 000'\n"
1024 "else\n"
1025 "echo '### 500'\n"
1026 "fi\n")
1028 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
1030 char *qsetto;
1031 PREFIX
1032 qsetto = strutils_shell_escape (setto);
1033 g_snprintf(buf, sizeof(buf),
1034 "#SYMLINK %s /%s\n"
1035 "if ln -s %s /%s 2>/dev/null; then\n"
1036 "echo '### 000'\n"
1037 "else\n"
1038 "echo '### 500'\n"
1039 "fi\n",
1040 qsetto, rpath, qsetto, rpath);
1041 g_free (qsetto);
1042 POSTFIX(OPT_FLUSH);
1045 static int
1046 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
1048 char *sowner, *sgroup;
1049 struct passwd *pw;
1050 struct group *gr;
1052 if ((pw = getpwuid (owner)) == NULL)
1053 return 0;
1055 if ((gr = getgrgid (group)) == NULL)
1056 return 0;
1058 sowner = pw->pw_name;
1059 sgroup = gr->gr_name;
1061 PREFIX
1062 g_snprintf (buf, sizeof(buf),
1063 "#CHOWN %s:%s /%s\n"
1064 "if chown %s:%s /%s 2>/dev/null; then\n"
1065 "echo '### 000'\n"
1066 "else\n"
1067 "echo '### 500'\n"
1068 "fi\n",
1069 sowner, sgroup, rpath,
1070 sowner, sgroup, rpath);
1071 fish_send_command (me, super, buf, OPT_FLUSH);
1072 /* FIXME: what should we report if chgrp succeeds but chown fails? */
1073 /* fish_send_command(me, super, buf, OPT_FLUSH); */
1074 POSTFIX (OPT_FLUSH)
1078 static int fish_unlink (struct vfs_class *me, const char *path)
1080 PREFIX
1081 g_snprintf(buf, sizeof(buf),
1082 "#DELE /%s\n"
1083 "if rm -f /%s 2>/dev/null; then\n"
1084 "echo '### 000'\n"
1085 "else\n"
1086 "echo '### 500'\n"
1087 "fi\n",
1088 rpath, rpath);
1089 POSTFIX(OPT_FLUSH);
1092 static int fish_exists (struct vfs_class *me, const char *path)
1094 PREFIX
1096 g_snprintf(buf, sizeof(buf),
1097 "#ISEXISTS /%s\n"
1098 "ls -l /%s >/dev/null 2>/dev/null\n"
1099 "echo '### '$?\n",
1100 rpath, rpath);
1102 g_free (rpath);
1104 if ( fish_send_command(me, super, buf, OPT_FLUSH) == 0 )
1105 return 1;
1107 return 0;
1111 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1113 int ret_code;
1115 PREFIX
1117 (void) mode;
1119 g_snprintf(buf, sizeof(buf),
1120 "#MKD /%s\n"
1121 "if mkdir /%s 2>/dev/null; then\n"
1122 "echo '### 000'\n"
1123 "else\n"
1124 "echo '### 500'\n"
1125 "fi\n",
1126 rpath, rpath);
1128 g_free (rpath);
1129 ret_code = fish_send_command(me, super, buf, OPT_FLUSH);
1131 if ( ret_code != 0 )
1132 return ret_code;
1134 if ( ! fish_exists (me, path) ){
1135 ERRNOR (EACCES, -1);
1137 return 0;
1140 static int fish_rmdir (struct vfs_class *me, const char *path)
1142 PREFIX
1143 g_snprintf(buf, sizeof(buf),
1144 "#RMD /%s\n"
1145 "if rmdir /%s 2>/dev/null; then\n"
1146 "echo '### 000'\n"
1147 "else\n"
1148 "echo '### 500'\n"
1149 "fi\n",
1150 rpath, rpath);
1151 POSTFIX(OPT_FLUSH);
1154 static int
1155 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1156 int mode)
1158 (void) mode;
1160 fh->u.fish.append = 0;
1161 /* File will be written only, so no need to retrieve it */
1162 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1163 fh->u.fish.append = flags & O_APPEND;
1164 if (!fh->ino->localname) {
1165 int tmp_handle =
1166 vfs_mkstemps (&fh->ino->localname, me->name,
1167 fh->ino->ent->name);
1168 if (tmp_handle == -1)
1169 return -1;
1170 close (tmp_handle);
1172 return 0;
1174 if (!fh->ino->localname)
1175 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1176 return -1;
1177 if (!fh->ino->localname)
1178 vfs_die ("retrieve_file failed to fill in localname");
1179 return 0;
1182 static void
1183 fish_fill_names (struct vfs_class *me, fill_names_f func)
1185 struct vfs_s_super *super = MEDATA->supers;
1186 char *name;
1188 char gbuf[10];
1190 while (super)
1192 const char *flags = "";
1193 switch (SUP.flags)
1195 case FISH_FLAG_RSH:
1196 flags = ":r";
1197 break;
1198 case FISH_FLAG_COMPRESSED:
1199 flags = ":C";
1200 break;
1201 default:
1202 if (SUP.flags > FISH_FLAG_RSH)
1204 break;
1205 g_snprintf (gbuf, sizeof (gbuf), ":%d", SUP.flags);
1206 flags = gbuf;
1208 break;
1211 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1212 "/", SUP.cwdir, (char *) NULL);
1213 (*func)(name);
1214 g_free (name);
1215 super = super->next;
1219 static void *
1220 fish_open (struct vfs_class *me, const char *file, int flags, int mode)
1223 sorry, i've places hack here
1224 cause fish don't able to open files with O_EXCL flag
1226 flags &= ~O_EXCL;
1227 return vfs_s_open (me, file, flags, mode);
1231 void
1232 init_fish (void)
1234 static struct vfs_s_subclass fish_subclass;
1236 fish_subclass.flags = VFS_S_REMOTE;
1237 fish_subclass.archive_same = fish_archive_same;
1238 fish_subclass.open_archive = fish_open_archive;
1239 fish_subclass.free_archive = fish_free_archive;
1240 fish_subclass.fh_open = fish_fh_open;
1241 fish_subclass.dir_load = fish_dir_load;
1242 fish_subclass.file_store = fish_file_store;
1243 fish_subclass.linear_start = fish_linear_start;
1244 fish_subclass.linear_read = fish_linear_read;
1245 fish_subclass.linear_close = fish_linear_close;
1247 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1248 vfs_fish_ops.name = "fish";
1249 vfs_fish_ops.prefix = "sh:";
1250 vfs_fish_ops.fill_names = fish_fill_names;
1251 vfs_fish_ops.chmod = fish_chmod;
1252 vfs_fish_ops.chown = fish_chown;
1253 vfs_fish_ops.open = fish_open;
1254 vfs_fish_ops.symlink = fish_symlink;
1255 vfs_fish_ops.link = fish_link;
1256 vfs_fish_ops.unlink = fish_unlink;
1257 vfs_fish_ops.rename = fish_rename;
1258 vfs_fish_ops.mkdir = fish_mkdir;
1259 vfs_fish_ops.rmdir = fish_rmdir;
1260 vfs_fish_ops.ctl = fish_ctl;
1261 vfs_register_class (&vfs_fish_ops);