Ticket #2108: Fixed memory leak in fish_linear_start() function.
[midnight-commander.git] / lib / vfs / mc-vfs / fish.c
blob1f20c95dffcfab7e46a415f25b182267d0783234
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 "lib/global.h"
56 #include "lib/fs.h"
57 #include "lib/tty/tty.h" /* enable/disable interrupt key */
58 #include "lib/strescape.h"
59 #include "lib/unixcompat.h"
61 #include "src/wtools.h" /* message() */
62 #include "src/main.h" /* print_vfs_message */
63 #include "utilvfs.h"
64 #include "xdirentry.h"
65 #include "vfs.h"
66 #include "vfs-impl.h"
67 #include "gc.h" /* vfs_stamp_create */
68 #include "netutil.h"
69 #include "fish.h"
71 int fish_directory_timeout = 900;
73 #define DO_RESOLVE_SYMLINK 1
74 #define DO_OPEN 2
75 #define DO_FREE_RESOURCE 4
77 #define FISH_FLAG_COMPRESSED 1
78 #define FISH_FLAG_RSH 2
80 #define OPT_FLUSH 1
81 #define OPT_IGNORE_ERROR 2
84 * Reply codes.
86 #define PRELIM 1 /* positive preliminary */
87 #define COMPLETE 2 /* positive completion */
88 #define CONTINUE 3 /* positive intermediate */
89 #define TRANSIENT 4 /* transient negative completion */
90 #define ERROR 5 /* permanent negative completion */
92 /* command wait_flag: */
93 #define NONE 0x00
94 #define WAIT_REPLY 0x01
95 #define WANT_STRING 0x02
96 static char reply_str [80];
98 static struct vfs_class vfs_fish_ops;
100 static int
101 fish_command (struct vfs_class *me, struct vfs_s_super *super,
102 int wait_reply, const char *fmt, ...)
103 __attribute__ ((format (__printf__, 4, 5)));
105 static int fish_decode_reply (char *s, int was_garbage)
107 int code;
108 if (!sscanf(s, "%d", &code)) {
109 code = 500;
110 return 5;
112 if (code<100) return was_garbage ? ERROR : (!code ? COMPLETE : PRELIM);
113 return code / 100;
116 /* Returns a reply code, check /usr/include/arpa/ftp.h for possible values */
117 static int fish_get_reply (struct vfs_class *me, int sock, char *string_buf, int string_len)
119 char answer[1024];
120 int was_garbage = 0;
122 for (;;) {
123 if (!vfs_s_get_line(me, sock, answer, sizeof(answer), '\n')) {
124 if (string_buf)
125 *string_buf = 0;
126 return 4;
129 if (strncmp(answer, "### ", 4)) {
130 was_garbage = 1;
131 if (string_buf)
132 g_strlcpy(string_buf, answer, string_len);
133 } else return fish_decode_reply(answer+4, was_garbage);
137 #define SUP super->u.fish
139 static int
140 fish_command (struct vfs_class *me, struct vfs_s_super *super,
141 int wait_reply, const char *fmt, ...)
143 va_list ap;
144 char *str;
145 int status;
146 FILE *logfile = MEDATA->logfile;
148 va_start (ap, fmt);
150 str = g_strdup_vprintf (fmt, ap);
151 va_end (ap);
153 if (logfile) {
154 fwrite (str, strlen (str), 1, logfile);
155 fflush (logfile);
158 tty_enable_interrupt_key ();
160 status = write (SUP.sockw, str, strlen (str));
161 g_free (str);
163 tty_disable_interrupt_key ();
164 if (status < 0)
165 return TRANSIENT;
167 if (wait_reply)
168 return fish_get_reply (me, SUP.sockr,
169 (wait_reply & WANT_STRING) ? reply_str :
170 NULL, sizeof (reply_str) - 1);
171 return COMPLETE;
174 static void
175 fish_free_archive (struct vfs_class *me, struct vfs_s_super *super)
177 if ((SUP.sockw != -1) || (SUP.sockr != -1)) {
178 print_vfs_message (_("fish: Disconnecting from %s"),
179 super->name ? super->name : "???");
180 fish_command (me, super, NONE, "#BYE\nexit\n");
181 close (SUP.sockw);
182 close (SUP.sockr);
183 SUP.sockw = SUP.sockr = -1;
185 g_free (SUP.host);
186 g_free (SUP.user);
187 g_free (SUP.cwdir);
188 g_free (SUP.password);
191 static void
192 fish_pipeopen(struct vfs_s_super *super, const char *path, const char *argv[])
194 int fileset1[2], fileset2[2];
195 int res;
197 if ((pipe(fileset1)<0) || (pipe(fileset2)<0))
198 vfs_die("Cannot pipe(): %m.");
200 if ((res = fork())) {
201 if (res<0) vfs_die("Cannot fork(): %m.");
202 /* We are the parent */
203 close(fileset1[0]);
204 SUP.sockw = fileset1[1];
205 close(fileset2[1]);
206 SUP.sockr = fileset2[0];
207 } else {
208 close(0);
209 dup(fileset1[0]);
210 close(fileset1[0]); close(fileset1[1]);
211 close(1); close(2);
212 dup(fileset2[1]);
213 /* stderr to /dev/null */
214 open ("/dev/null", O_WRONLY);
215 close(fileset2[0]); close(fileset2[1]);
216 execvp(path, const_cast(char **, argv));
217 _exit(3);
221 /* The returned directory should always contain a trailing slash */
222 static char *fish_getcwd(struct vfs_class *me, struct vfs_s_super *super)
224 if (fish_command (me, super, WANT_STRING, "#PWD\npwd; echo '### 200'\n") == COMPLETE)
225 return g_strconcat (reply_str, "/", (char *) NULL);
226 ERRNOR (EIO, NULL);
229 static int
230 fish_open_archive_int (struct vfs_class *me, struct vfs_s_super *super)
233 char gbuf[10];
234 const char *argv[10]; /* All of 10 is used now */
235 const char *xsh = (SUP.flags == FISH_FLAG_RSH ? "rsh" : "ssh");
236 int i = 0;
238 argv[i++] = xsh;
239 if (SUP.flags == FISH_FLAG_COMPRESSED)
240 argv[i++] = "-C";
242 if (SUP.flags > FISH_FLAG_RSH)
244 argv[i++] = "-p";
245 g_snprintf (gbuf, sizeof (gbuf), "%d", SUP.flags);
246 argv[i++] = gbuf;
250 * Add the user name to the ssh command line only if it was explicitly
251 * set in vfs URL. rsh/ssh will get current user by default
252 * plus we can set convenient overrides in ~/.ssh/config (explicit -l
253 * option breaks it for some)
256 if (SUP.user) {
257 argv[i++] = "-l";
258 argv[i++] = SUP.user;
260 else
262 /* The rest of the code assumes it to be a valid username */
263 SUP.user = vfs_get_local_username();
266 argv[i++] = SUP.host;
267 argv[i++] = "echo FISH:; /bin/sh";
268 argv[i++] = NULL;
270 fish_pipeopen (super, xsh, argv);
273 char answer[2048];
274 print_vfs_message (_("fish: Waiting for initial line..."));
275 if (!vfs_s_get_line (me, SUP.sockr, answer, sizeof (answer), ':'))
276 ERRNOR (E_PROTO, -1);
277 print_vfs_message ("%s", answer);
278 if (strstr (answer, "assword")) {
280 /* Currently, this does not work. ssh reads passwords from
281 /dev/tty, not from stdin :-(. */
283 message (D_ERROR, MSG_ERROR,
285 ("Sorry, we cannot do password authenticated connections for now."));
286 ERRNOR (EPERM, -1);
287 if (!SUP.password) {
288 char *p, *op;
289 p = g_strconcat (_(" fish: Password required for "),
290 SUP.user, " ", (char *) NULL);
291 op = vfs_get_password (p);
292 g_free (p);
293 if (op == NULL)
294 ERRNOR (EPERM, -1);
295 SUP.password = op;
297 print_vfs_message (_("fish: Sending password..."));
298 write (SUP.sockw, SUP.password, strlen (SUP.password));
299 write (SUP.sockw, "\n", 1);
303 print_vfs_message (_("fish: Sending initial line..."));
305 * Run `start_fish_server'. If it doesn't exist - no problem,
306 * we'll talk directly to the shell.
308 if (fish_command
309 (me, super, WAIT_REPLY,
310 "#FISH\necho; start_fish_server 2>&1; echo '### 200'\n") !=
311 COMPLETE)
312 ERRNOR (E_PROTO, -1);
314 print_vfs_message (_("fish: Handshaking version..."));
315 if (fish_command
316 (me, super, WAIT_REPLY,
317 "#VER 0.0.0\necho '### 000'\n") != COMPLETE)
318 ERRNOR (E_PROTO, -1);
320 /* Set up remote locale to C, otherwise dates cannot be recognized */
321 if (fish_command
322 (me, super, WAIT_REPLY,
323 "LANG=C; LC_ALL=C; LC_TIME=C\n"
324 "export LANG; export LC_ALL; export LC_TIME\n" "echo '### 200'\n")
325 != COMPLETE)
326 ERRNOR (E_PROTO, -1);
328 print_vfs_message (_("fish: Setting up current directory..."));
329 SUP.cwdir = fish_getcwd (me, super);
330 print_vfs_message (_("fish: Connected, home %s."), SUP.cwdir);
331 #if 0
332 super->name =
333 g_strconcat ("/#sh:", SUP.user, "@", SUP.host, "/", (char *) NULL);
334 #endif
335 super->name = g_strdup (PATH_SEP_STR);
337 super->root =
338 vfs_s_new_inode (me, super,
339 vfs_s_default_stat (me, S_IFDIR | 0755));
340 return 0;
343 static int
344 fish_open_archive (struct vfs_class *me, struct vfs_s_super *super,
345 const char *archive_name, char *op)
347 char *host, *user, *password, *p;
348 int flags;
350 (void) archive_name;
352 p = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags,
353 &password, 0, URL_NOSLASH | URL_USE_ANONYMOUS);
355 g_free (p);
357 SUP.host = host;
358 SUP.user = user;
359 SUP.flags = flags;
360 if (!strncmp (op, "rsh:", 4))
361 SUP.flags = FISH_FLAG_RSH;
362 SUP.cwdir = NULL;
363 if (password)
364 SUP.password = password;
365 return fish_open_archive_int (me, super);
368 static int
369 fish_archive_same (struct vfs_class *me, struct vfs_s_super *super,
370 const char *archive_name, char *op, void *cookie)
372 char *host, *user;
373 int flags;
374 int result;
376 (void) me;
377 (void) archive_name;
378 (void) cookie;
380 op = vfs_split_url (strchr (op, ':') + 1, &host, &user, &flags, 0, 0,
381 URL_NOSLASH | URL_USE_ANONYMOUS);
383 g_free (op);
385 if (user == NULL)
386 user = vfs_get_local_username();
388 result = ((strcmp (host, SUP.host) == 0)
389 && (strcmp (user, SUP.user) == 0)
390 && (flags == SUP.flags));
392 g_free (host);
393 g_free (user);
395 return result;
398 static int
399 fish_dir_load(struct vfs_class *me, struct vfs_s_inode *dir, char *remote_path)
401 struct vfs_s_super *super = dir->super;
402 char buffer[8192];
403 struct vfs_s_entry *ent = NULL;
404 FILE *logfile;
405 char *quoted_path;
406 int reply_code;
407 gchar *shell_commands;
409 #if 0
411 * Simple FISH debug interface :]
413 if (!(MEDATA->logfile))
415 MEDATA->logfile = fopen("/tmp/mc-FISH.sh", "w");
417 #endif /* 0 */
419 logfile = MEDATA->logfile;
421 print_vfs_message(_("fish: Reading directory %s..."), remote_path);
423 gettimeofday(&dir->timestamp, NULL);
424 dir->timestamp.tv_sec += fish_directory_timeout;
425 quoted_path = strutils_shell_escape (remote_path);
426 shell_commands = g_strconcat(
427 "#LIST /%s\n"
428 "if `perl -v > /dev/null 2>&1` ; then\n"
429 "perl -e '\n"
430 "use strict;\n"
431 "use POSIX;\n"
432 "use Fcntl;\n"
433 "use POSIX \":fcntl_h\"; #S_ISLNK was here until 5.6\n"
434 "import Fcntl \":mode\" unless defined &S_ISLNK; #and is now here\n"
435 "my $dirname = $ARGV[0];\n"
436 "if (opendir ( DIR, $dirname )) {\n"
437 "while( (my $filename = readdir(DIR))){\n"
438 "my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = lstat(\"$dirname/$filename\");\n"
439 "my $mloctime= strftime(\"%%m-%%d-%%Y %%H:%%M\", localtime $mtime);\n"
441 "my $strutils_shell_escape_regex= s/([;<>\\*\\|`&\\$!#\\(\\)\\[\\]\\{\\}:'\\''\"\\ \\\\])/\\\\$1/g;\n"
442 "my $e_filename = $filename;\n"
443 "$e_filename =~ $strutils_shell_escape_regex;\n"
444 "if (S_ISLNK($mode) ) {\n"
445 "my $linkname = readlink (\"$dirname/$filename\");\n"
446 "$linkname =~ $strutils_shell_escape_regex;\n"
447 "\n"
448 "printf(\"R%%o %%o $uid.$gid\\n"
449 "S$size\\n"
450 "d$mloctime\\n"
451 ":\\\"$e_filename\\\" -> \\\"$linkname\\\"\\n"
452 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
453 "} else {\n"
454 "printf(\"R%%o %%o $uid.$gid\\n"
455 "S$size\\n"
456 "d$mloctime\\n"
457 ":\\\"$e_filename\\\"\\n"
458 "\\n\", S_IMODE($mode), S_IFMT($mode));\n"
459 "}}\n"
461 "printf(\"### 200\\n\");\n"
462 "closedir(DIR);\n"
463 "} else {\n"
464 "printf(\"### 500\\n\");\n"
465 "}\n"
466 "exit 0\n"
467 "' /%s ||\n" /* ARGV[0] - path to browse */
468 " echo '### 500'\n" /* do not hang if perl is to eval it */
469 "elif `ls -1 /%s >/dev/null 2>&1` ; then\n"
470 "if `ls -Q /%s >/dev/null 2>&1`; then\n"
471 "LSOPT=\"-Qlan\";\n"
472 "ADD=0;\n"
473 "else\n"
474 "LSOPT=\"-lan\";\n"
475 "ADD=1;\n"
476 "fi\n"
477 "ls $LSOPT /%s 2>/dev/null | grep '^[^cbt]' | (\n"
478 "while read p l u g s m d y n n2 n3; do\n"
479 "if test \"$m\" = \"0\" ; then \n"
480 "s=$d; m=$y; d=$n y=$n2; n=$n3\n"
481 "else\n"
482 "n=$n\" \"$n2\" \"$n3\n"
483 "fi\n"
484 "if [ $ADD = 0 ]; then\n"
485 "echo \"P$p $u.$g\nS$s\nd$m $d $y\n:$n\n\"\n"
486 "elif `sed --version >/dev/null 2>&1` ; then\n"
487 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
489 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
490 "else\n"
491 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
492 "fi\n"
493 "done )\n"
494 "ls $LSOPT /%s 2>/dev/null | grep '^[cb]' | (\n"
495 "while read p l u g a i m d y n n2 n3; do\n"
496 "if test \"$a\" = \"0\" ; then \n"
497 "a=$m; i=$d; m=$y; d=$n y=$n2; n=$n3\n"
498 "else\n"
499 "n=$n\" \"$n2\" \"$n3\n"
500 "fi\n"
501 "if [ $ADD = 0 ]; then\n"
502 "echo \"P$p $u.$g\nE$a$i\nd$m $d $y\n:$n\n\"\n"
503 "elif `sed --version >/dev/null 2>&1` ; then\n"
504 "file=`echo $n | sed -e 's#^\\(.*\\) -> \\(.*\\)#\\1\" -> \"\\2#'`\n"
505 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$file\"\n\"\n"
506 "else\n"
507 "echo \"P$p $u $g\nS$s\nd$m $d $y\n:\"$n\"\n\"\n"
508 "fi\n"
509 "done)\n"
510 "echo '### 200'\n"
511 "else\n"
512 "echo '### 500'\n"
513 "fi\n"
514 , (char *) NULL
517 fish_command (me, super, NONE, shell_commands,
518 quoted_path, quoted_path, quoted_path, quoted_path, quoted_path, quoted_path);
520 g_free(shell_commands);
521 g_free (quoted_path);
522 ent = vfs_s_generate_entry(me, NULL, dir, 0);
523 while (1) {
524 int res = vfs_s_get_line_interruptible (me, buffer, sizeof (buffer), SUP.sockr);
525 if ((!res) || (res == EINTR)) {
526 vfs_s_free_entry(me, ent);
527 me->verrno = ECONNRESET;
528 goto error;
530 if (logfile) {
531 fputs (buffer, logfile);
532 fputs ("\n", logfile);
533 fflush (logfile);
535 if (!strncmp(buffer, "### ", 4))
536 break;
537 if ((!buffer[0])) {
538 if (ent->name) {
539 vfs_s_insert_entry(me, dir, ent);
540 ent = vfs_s_generate_entry(me, NULL, dir, 0);
542 continue;
545 #define ST ent->ino->st
547 switch(buffer[0]) {
548 case ':': {
549 char *temp;
550 char *data_start = buffer+1;
551 char *filename = data_start;
552 char *linkname = data_start;
553 char *filename_bound = filename + strlen(filename);
554 char *linkname_bound = filename_bound;
555 if (!strcmp(data_start, "\".\"") || !strcmp(data_start, "\"..\""))
556 break; /* We'll do "." and ".." ourselves */
558 if (S_ISLNK(ST.st_mode)) {
559 /* we expect: "escaped-name" -> "escaped-name"
560 // -> cannot occur in filenames,
561 // because it will be escaped to -\> */
563 if (*filename == '"')
564 ++filename;
566 linkname = strstr(filename, "\" -> \"");
567 if (!linkname)
569 /* broken client, or smth goes wrong */
570 linkname = filename_bound;
571 if (filename_bound > filename
572 && *(filename_bound - 1) == '"')
573 --filename_bound; /* skip trailing " */
575 else
577 filename_bound = linkname;
578 linkname += 6; /* strlen ("\" -> \"") */
579 if (*(linkname_bound - 1) == '"')
580 --linkname_bound; /* skip trailing " */
583 ent->name = str_dup_range(filename, filename_bound);
584 temp = ent->name;
585 ent->name = strutils_shell_unescape(ent->name);
586 g_free(temp);
588 ent->ino->linkname = str_dup_range(linkname, linkname_bound);
589 temp = ent->ino->linkname;
590 ent->ino->linkname = strutils_shell_unescape(ent->ino->linkname);
591 g_free(temp);
592 } else {
593 /* we expect: "escaped-name" */
594 if (filename_bound - filename > 2)
597 there is at least 2 "
598 and we skip them
600 if (*filename == '"')
601 ++filename;
602 if (*(filename_bound - 1) == '"')
603 --filename_bound;
605 ent->name = str_dup_range(filename, filename_bound);
606 temp = ent->name;
607 ent->name = strutils_shell_unescape(ent->name);
608 g_free(temp);
610 break;
612 case 'S':
613 #ifdef HAVE_ATOLL
614 ST.st_size = (off_t) atoll (buffer+1);
615 #else
616 ST.st_size = (off_t) atof (buffer+1);
617 #endif
618 break;
619 case 'P': {
620 size_t skipped;
621 vfs_parse_filemode (buffer + 1, &skipped, &ST.st_mode);
622 break;
624 case 'R': {
626 raw filemode:
627 we expect: Roctal-filemode octal-filetype uid.gid
629 size_t skipped;
630 vfs_parse_raw_filemode (buffer + 1, &skipped, &ST.st_mode);
631 break;
633 case 'd': {
634 vfs_split_text(buffer+1);
635 if (!vfs_parse_filedate(0, &ST.st_ctime))
636 break;
637 ST.st_atime = ST.st_mtime = ST.st_ctime;
639 break;
640 case 'D': {
641 struct tm tim;
642 if (sscanf(buffer+1, "%d %d %d %d %d %d", &tim.tm_year, &tim.tm_mon,
643 &tim.tm_mday, &tim.tm_hour, &tim.tm_min, &tim.tm_sec) != 6)
644 break;
645 ST.st_atime = ST.st_mtime = ST.st_ctime = mktime(&tim);
647 break;
648 case 'E': {
649 int maj, min;
650 if (sscanf(buffer+1, "%d,%d", &maj, &min) != 2)
651 break;
652 #ifdef HAVE_STRUCT_STAT_ST_RDEV
653 ST.st_rdev = makedev (maj, min);
654 #endif
659 vfs_s_free_entry (me, ent);
660 reply_code = fish_decode_reply(buffer + 4, 0);
661 if (reply_code == COMPLETE) {
662 g_free (SUP.cwdir);
663 SUP.cwdir = g_strdup (remote_path);
664 print_vfs_message (_("%s: done."), me->name);
665 return 0;
666 } else if (reply_code == ERROR) {
667 me->verrno = EACCES;
668 } else {
669 me->verrno = E_REMOTE;
672 error:
673 print_vfs_message (_("%s: failure"), me->name);
674 return -1;
677 static int
678 fish_file_store(struct vfs_class *me, struct vfs_s_fh *fh, char *name, char *localname)
680 struct vfs_s_super *super = FH_SUPER;
681 int n, total;
682 char buffer[8192];
683 struct stat s;
684 int was_error = 0;
685 int h;
686 char *quoted_name;
688 h = open (localname, O_RDONLY);
690 if (h == -1)
691 ERRNOR (EIO, -1);
692 if (fstat(h, &s)<0) {
693 close (h);
694 ERRNOR (EIO, -1);
697 /* First, try this as stor:
699 * ( head -c number ) | ( cat > file; cat >/dev/null )
701 * If `head' is not present on the remote system, `dd' will be used.
702 * Unfortunately, we cannot trust most non-GNU `head' implementations
703 * even if `-c' options is supported. Therefore, we separate GNU head
704 * (and other modern heads?) using `-q' and `-' . This causes another
705 * implementations to fail (because of "incorrect options").
707 * Fallback is:
709 * rest=<number>
710 * while [ $rest -gt 0 ]
711 * do
712 * cnt=`expr \( $rest + 255 \) / 256`
713 * n=`dd bs=256 count=$cnt | tee -a <target_file> | wc -c`
714 * rest=`expr $rest - $n`
715 * done
717 * `dd' was not designed for full filling of input buffers,
718 * and does not report exact number of bytes (not blocks).
719 * Therefore a more complex shell script is needed.
721 * On some systems non-GNU head writes "Usage:" error report to stdout
722 * instead of stderr. It makes impossible the use of "head || dd"
723 * algorithm for file appending case, therefore just "dd" is used for it.
726 quoted_name = strutils_shell_escape(name);
727 print_vfs_message(_("fish: store %s: sending command..."), quoted_name );
729 /* FIXME: File size is limited to ULONG_MAX */
730 if (!fh->u.fish.append)
731 n = fish_command (me, super, WAIT_REPLY,
732 "#STOR %lu /%s\n"
733 "echo '### 001'\n"
734 "file=/%s\n"
735 "res=`exec 3>&1\n"
736 "(\n"
737 "head -c %lu -q - || echo DD >&3\n"
738 ") 2>/dev/null | (\n"
739 "cat > $file\n"
740 "cat > /dev/null\n"
741 ")`; [ \"$res\" = DD ] && {\n"
742 "> \"$file\"\n"
743 "rest=%lu\n"
744 "while [ $rest -gt 0 ]\n"
745 "do\n"
746 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
747 " n=`dd bs=256 count=$cnt | tee -a \"$file\" | wc -c`\n"
748 " rest=`expr $rest - $n`\n"
749 "done\n"
750 "}; echo '### 200'\n",
751 (unsigned long) s.st_size, quoted_name,
752 quoted_name, (unsigned long) s.st_size,
753 (unsigned long) s.st_size);
754 else
755 n = fish_command (me, super, WAIT_REPLY,
756 "#STOR %lu /%s\n"
757 "echo '### 001'\n"
758 "{\n"
759 "file=/%s\n"
760 "rest=%lu\n"
761 "while [ $rest -gt 0 ]\n"
762 "do\n"
763 " cnt=`expr \\( $rest + 255 \\) / 256`\n"
764 " n=`dd bs=256 count=$cnt | tee -a $file | wc -c`\n"
765 " rest=`expr $rest - $n`\n"
766 "done\n"
767 "}; echo '### 200'\n",
768 (unsigned long) s.st_size, quoted_name,
769 quoted_name, (unsigned long) s.st_size);
771 if (n != PRELIM) {
772 close (h);
773 ERRNOR(E_REMOTE, -1);
775 total = 0;
777 while (1) {
778 int t;
779 while ((n = read(h, buffer, sizeof(buffer))) < 0) {
780 if ((errno == EINTR) && tty_got_interrupt ())
781 continue;
782 print_vfs_message(_("fish: Local read failed, sending zeros") );
783 close(h);
784 h = open( "/dev/zero", O_RDONLY );
786 if (n == 0)
787 break;
788 if ((t = write (SUP.sockw, buffer, n)) != n) {
789 if (t == -1) {
790 me->verrno = errno;
791 } else {
792 me->verrno = EIO;
794 goto error_return;
796 tty_disable_interrupt_key ();
797 total += n;
798 print_vfs_message(_("fish: storing %s %d (%lu)"),
799 was_error ? _("zeros") : _("file"), total,
800 (unsigned long) s.st_size);
802 close(h);
803 g_free(quoted_name);
804 if ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE) || was_error)
805 ERRNOR (E_REMOTE, -1);
806 return 0;
807 error_return:
808 close(h);
809 fish_get_reply(me, SUP.sockr, NULL, 0);
810 g_free(quoted_name);
811 return -1;
814 static int
815 fish_linear_start (struct vfs_class *me, struct vfs_s_fh *fh, off_t offset)
817 char *name;
818 char *quoted_name;
819 if (offset)
820 ERRNOR (E_NOTSUPP, 0);
821 name = vfs_s_fullpath (me, fh->ino);
822 if (name == NULL)
823 return 0;
824 quoted_name = strutils_shell_escape (name);
825 g_free (name);
826 fh->u.fish.append = 0;
829 * Check whether the remote file is readable by using `dd' to copy
830 * a single byte from the remote file to /dev/null. If `dd' completes
831 * with exit status of 0 use `cat' to send the file contents to the
832 * standard output (i.e. over the network).
834 offset = fish_command (me, FH_SUPER, WANT_STRING,
835 "#RETR /%s\n"
836 "if dd if=/%s of=/dev/null bs=1 count=1 2>/dev/null ;\n"
837 "then\n"
838 "ls -ln /%s 2>/dev/null | (\n"
839 "read p l u g s r\n"
840 "echo $s\n"
841 ")\n"
842 "echo '### 100'\n"
843 "cat /%s\n"
844 "echo '### 200'\n"
845 "else\n"
846 "echo '### 500'\n"
847 "fi\n",
848 quoted_name, quoted_name, quoted_name, quoted_name );
849 g_free (quoted_name);
850 if (offset != PRELIM) ERRNOR (E_REMOTE, 0);
851 fh->linear = LS_LINEAR_OPEN;
852 fh->u.fish.got = 0;
853 errno = 0;
854 #if SIZEOF_OFF_T == SIZEOF_LONG
855 fh->u.fish.total = strtol (reply_str, NULL, 10);
856 #else
857 fh->u.fish.total = strtoll (reply_str, NULL, 10);
858 #endif
859 if (errno != 0)
860 ERRNOR (E_REMOTE, 0);
861 return 1;
864 static void
865 fish_linear_abort (struct vfs_class *me, struct vfs_s_fh *fh)
867 struct vfs_s_super *super = FH_SUPER;
868 char buffer[8192];
869 int n;
871 print_vfs_message( _("Aborting transfer...") );
872 do {
873 n = MIN(8192, fh->u.fish.total - fh->u.fish.got);
874 if (n) {
875 if ((n = read(SUP.sockr, buffer, n)) < 0)
876 return;
877 fh->u.fish.got += n;
879 } while (n);
881 if (fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)
882 print_vfs_message( _("Error reported after abort.") );
883 else
884 print_vfs_message( _("Aborted transfer would be successful.") );
887 static int
888 fish_linear_read (struct vfs_class *me, struct vfs_s_fh *fh, void *buf, int len)
890 struct vfs_s_super *super = FH_SUPER;
891 int n = 0;
892 len = MIN( fh->u.fish.total - fh->u.fish.got, len );
893 tty_disable_interrupt_key ();
894 while (len && ((n = read (SUP.sockr, buf, len))<0)) {
895 if ((errno == EINTR) && !tty_got_interrupt ())
896 continue;
897 break;
899 tty_enable_interrupt_key();
901 if (n>0) fh->u.fish.got += n;
902 if (n<0) fish_linear_abort(me, fh);
903 if ((!n) && ((fish_get_reply (me, SUP.sockr, NULL, 0) != COMPLETE)))
904 ERRNOR (E_REMOTE, -1);
905 ERRNOR (errno, n);
908 static void
909 fish_linear_close (struct vfs_class *me, struct vfs_s_fh *fh)
911 if (fh->u.fish.total != fh->u.fish.got)
912 fish_linear_abort(me, fh);
915 static int
916 fish_ctl (void *fh, int ctlop, void *arg)
918 (void) arg;
919 (void) fh;
920 (void) ctlop;
921 return 0;
922 #if 0
923 switch (ctlop) {
924 case VFS_CTL_IS_NOTREADY:
926 int v;
928 if (!FH->linear)
929 vfs_die ("You may not do this");
930 if (FH->linear == LS_LINEAR_CLOSED || FH->linear == LS_LINEAR_PREOPEN)
931 return 0;
933 v = vfs_s_select_on_two (FH_SUPER->u.fish.sockr, 0);
934 if (((v < 0) && (errno == EINTR)) || v == 0)
935 return 1;
936 return 0;
938 default:
939 return 0;
941 #endif
944 static int
945 fish_send_command(struct vfs_class *me, struct vfs_s_super *super, const char *cmd, int flags)
947 int r;
949 r = fish_command (me, super, WAIT_REPLY, "%s", cmd);
950 vfs_stamp_create (&vfs_fish_ops, super);
951 if (r != COMPLETE) ERRNOR (E_REMOTE, -1);
952 if (flags & OPT_FLUSH)
953 vfs_s_invalidate(me, super);
954 return 0;
957 #define PREFIX \
958 char buf[BUF_LARGE]; \
959 const char *crpath; \
960 char *rpath, *mpath = g_strdup (path); \
961 struct vfs_s_super *super; \
962 if (!(crpath = vfs_s_get_path_mangle (me, mpath, &super, 0))) { \
963 g_free (mpath); \
964 return -1; \
966 rpath = strutils_shell_escape(crpath); \
967 g_free (mpath);
969 #define POSTFIX(flags) \
970 g_free (rpath); \
971 return fish_send_command(me, super, buf, flags);
973 static int
974 fish_chmod (struct vfs_class *me, const char *path, int mode)
976 PREFIX
977 g_snprintf(buf, sizeof(buf), "#CHMOD %4.4o /%s\n"
978 "if chmod %4.4o /%s 2>/dev/null; then\n"
979 "echo '### 000'\n"
980 "else\n"
981 "echo '### 500'\n"
982 "fi\n",
983 mode & 07777, rpath,
984 mode & 07777, rpath);
985 POSTFIX(OPT_FLUSH);
988 #define FISH_OP(name, string) \
989 static int fish_##name (struct vfs_class *me, const char *path1, const char *path2) \
991 char buf[BUF_LARGE]; \
992 const char *crpath1, *crpath2; \
993 char *rpath1, *rpath2, *mpath1, *mpath2; \
994 struct vfs_s_super *super1, *super2; \
995 if (!(crpath1 = vfs_s_get_path_mangle (me, mpath1 = g_strdup(path1), &super1, 0))) { \
996 g_free (mpath1); \
997 return -1; \
999 if (!(crpath2 = vfs_s_get_path_mangle (me, mpath2 = g_strdup(path2), &super2, 0))) { \
1000 g_free (mpath1); \
1001 g_free (mpath2); \
1002 return -1; \
1004 rpath1 = strutils_shell_escape (crpath1); \
1005 g_free (mpath1); \
1006 rpath2 = strutils_shell_escape (crpath2); \
1007 g_free (mpath2); \
1008 g_snprintf(buf, sizeof(buf), string "\n", rpath1, rpath2, rpath1, rpath2); \
1009 g_free (rpath1); \
1010 g_free (rpath2); \
1011 return fish_send_command(me, super2, buf, OPT_FLUSH); \
1014 FISH_OP(rename, "#RENAME /%s /%s\n"
1015 "if mv /%s /%s 2>/dev/null; then\n"
1016 "echo '### 000'\n"
1017 "else\n"
1018 "echo '### 500'\n"
1019 "fi\n")
1020 FISH_OP(link, "#LINK /%s /%s\n"
1021 "if ln /%s /%s 2>/dev/null; then\n"
1022 "echo '### 000'\n"
1023 "else\n"
1024 "echo '### 500'\n"
1025 "fi\n")
1027 static int fish_symlink (struct vfs_class *me, const char *setto, const char *path)
1029 char *qsetto;
1030 PREFIX
1031 qsetto = strutils_shell_escape (setto);
1032 g_snprintf(buf, sizeof(buf),
1033 "#SYMLINK %s /%s\n"
1034 "if ln -s %s /%s 2>/dev/null; then\n"
1035 "echo '### 000'\n"
1036 "else\n"
1037 "echo '### 500'\n"
1038 "fi\n",
1039 qsetto, rpath, qsetto, rpath);
1040 g_free (qsetto);
1041 POSTFIX(OPT_FLUSH);
1044 static int
1045 fish_chown (struct vfs_class *me, const char *path, int owner, int group)
1047 char *sowner, *sgroup;
1048 struct passwd *pw;
1049 struct group *gr;
1051 if ((pw = getpwuid (owner)) == NULL)
1052 return 0;
1054 if ((gr = getgrgid (group)) == NULL)
1055 return 0;
1057 sowner = pw->pw_name;
1058 sgroup = gr->gr_name;
1060 PREFIX
1061 g_snprintf (buf, sizeof(buf),
1062 "#CHOWN %s:%s /%s\n"
1063 "if chown %s:%s /%s 2>/dev/null; then\n"
1064 "echo '### 000'\n"
1065 "else\n"
1066 "echo '### 500'\n"
1067 "fi\n",
1068 sowner, sgroup, rpath,
1069 sowner, sgroup, rpath);
1070 fish_send_command (me, super, buf, OPT_FLUSH);
1071 /* FIXME: what should we report if chgrp succeeds but chown fails? */
1072 /* fish_send_command(me, super, buf, OPT_FLUSH); */
1073 POSTFIX (OPT_FLUSH)
1077 static int fish_unlink (struct vfs_class *me, const char *path)
1079 PREFIX
1080 g_snprintf(buf, sizeof(buf),
1081 "#DELE /%s\n"
1082 "if rm -f /%s 2>/dev/null; then\n"
1083 "echo '### 000'\n"
1084 "else\n"
1085 "echo '### 500'\n"
1086 "fi\n",
1087 rpath, rpath);
1088 POSTFIX(OPT_FLUSH);
1091 static int fish_exists (struct vfs_class *me, const char *path)
1093 PREFIX
1095 g_snprintf(buf, sizeof(buf),
1096 "#ISEXISTS /%s\n"
1097 "ls -l /%s >/dev/null 2>/dev/null\n"
1098 "echo '### '$?\n",
1099 rpath, rpath);
1101 g_free (rpath);
1103 if ( fish_send_command(me, super, buf, OPT_FLUSH) == 0 )
1104 return 1;
1106 return 0;
1110 static int fish_mkdir (struct vfs_class *me, const char *path, mode_t mode)
1112 int ret_code;
1114 PREFIX
1116 (void) mode;
1118 g_snprintf(buf, sizeof(buf),
1119 "#MKD /%s\n"
1120 "if mkdir /%s 2>/dev/null; then\n"
1121 "echo '### 000'\n"
1122 "else\n"
1123 "echo '### 500'\n"
1124 "fi\n",
1125 rpath, rpath);
1127 g_free (rpath);
1128 ret_code = fish_send_command(me, super, buf, OPT_FLUSH);
1130 if ( ret_code != 0 )
1131 return ret_code;
1133 if ( ! fish_exists (me, path) ){
1134 ERRNOR (EACCES, -1);
1136 return 0;
1139 static int fish_rmdir (struct vfs_class *me, const char *path)
1141 PREFIX
1142 g_snprintf(buf, sizeof(buf),
1143 "#RMD /%s\n"
1144 "if rmdir /%s 2>/dev/null; then\n"
1145 "echo '### 000'\n"
1146 "else\n"
1147 "echo '### 500'\n"
1148 "fi\n",
1149 rpath, rpath);
1150 POSTFIX(OPT_FLUSH);
1153 static int
1154 fish_fh_open (struct vfs_class *me, struct vfs_s_fh *fh, int flags,
1155 int mode)
1157 (void) mode;
1159 fh->u.fish.append = 0;
1160 /* File will be written only, so no need to retrieve it */
1161 if (((flags & O_WRONLY) == O_WRONLY) && !(flags & (O_RDONLY | O_RDWR))) {
1162 fh->u.fish.append = flags & O_APPEND;
1163 if (!fh->ino->localname) {
1164 int tmp_handle =
1165 vfs_mkstemps (&fh->ino->localname, me->name,
1166 fh->ino->ent->name);
1167 if (tmp_handle == -1)
1168 return -1;
1169 close (tmp_handle);
1171 return 0;
1173 if (!fh->ino->localname)
1174 if (vfs_s_retrieve_file (me, fh->ino) == -1)
1175 return -1;
1176 if (!fh->ino->localname)
1177 vfs_die ("retrieve_file failed to fill in localname");
1178 return 0;
1181 static void
1182 fish_fill_names (struct vfs_class *me, fill_names_f func)
1184 struct vfs_s_super *super = MEDATA->supers;
1185 char *name;
1187 char gbuf[10];
1189 while (super)
1191 const char *flags = "";
1192 switch (SUP.flags)
1194 case FISH_FLAG_RSH:
1195 flags = ":r";
1196 break;
1197 case FISH_FLAG_COMPRESSED:
1198 flags = ":C";
1199 break;
1200 default:
1201 if (SUP.flags > FISH_FLAG_RSH)
1203 break;
1204 g_snprintf (gbuf, sizeof (gbuf), ":%d", SUP.flags);
1205 flags = gbuf;
1207 break;
1210 name = g_strconcat ("/#sh:", SUP.user, "@", SUP.host, flags,
1211 "/", SUP.cwdir, (char *) NULL);
1212 (*func)(name);
1213 g_free (name);
1214 super = super->next;
1218 static void *
1219 fish_open (struct vfs_class *me, const char *file, int flags, int mode)
1222 sorry, i've places hack here
1223 cause fish don't able to open files with O_EXCL flag
1225 flags &= ~O_EXCL;
1226 return vfs_s_open (me, file, flags, mode);
1230 void
1231 init_fish (void)
1233 static struct vfs_s_subclass fish_subclass;
1235 tcp_init();
1237 fish_subclass.flags = VFS_S_REMOTE;
1238 fish_subclass.archive_same = fish_archive_same;
1239 fish_subclass.open_archive = fish_open_archive;
1240 fish_subclass.free_archive = fish_free_archive;
1241 fish_subclass.fh_open = fish_fh_open;
1242 fish_subclass.dir_load = fish_dir_load;
1243 fish_subclass.file_store = fish_file_store;
1244 fish_subclass.linear_start = fish_linear_start;
1245 fish_subclass.linear_read = fish_linear_read;
1246 fish_subclass.linear_close = fish_linear_close;
1248 vfs_s_init_class (&vfs_fish_ops, &fish_subclass);
1249 vfs_fish_ops.name = "fish";
1250 vfs_fish_ops.prefix = "sh:";
1251 vfs_fish_ops.fill_names = fish_fill_names;
1252 vfs_fish_ops.chmod = fish_chmod;
1253 vfs_fish_ops.chown = fish_chown;
1254 vfs_fish_ops.open = fish_open;
1255 vfs_fish_ops.symlink = fish_symlink;
1256 vfs_fish_ops.link = fish_link;
1257 vfs_fish_ops.unlink = fish_unlink;
1258 vfs_fish_ops.rename = fish_rename;
1259 vfs_fish_ops.mkdir = fish_mkdir;
1260 vfs_fish_ops.rmdir = fish_rmdir;
1261 vfs_fish_ops.ctl = fish_ctl;
1262 vfs_register_class (&vfs_fish_ops);