Merge from vendor branch GCC:
[dragonfly.git] / contrib / tar / src / rtapelib.c
1 /* Functions for communicating with a remote tape drive.
2
3    Copyright 1988, 1992, 1994, 1996, 1997, 1999, 2000, 2001 Free Software
4    Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* The man page rmt(8) for /etc/rmt documents the remote mag tape protocol
21    which rdump and rrestore use.  Unfortunately, the man page is *WRONG*.
22    The author of the routines I'm including originally wrote his code just
23    based on the man page, and it didn't work, so he went to the rdump source
24    to figure out why.  The only thing he had to change was to check for the
25    'F' return code in addition to the 'E', and to separate the various
26    arguments with \n instead of a space.  I personally don't think that this
27    is much of a problem, but I wanted to point it out. -- Arnold Robbins
28
29    Originally written by Jeff Lee, modified some by Arnold Robbins.  Redone
30    as a library that can replace open, read, write, etc., by Fred Fish, with
31    some additional work by Arnold Robbins.  Modified to make all rmt* calls
32    into macros for speed by Jay Fenlason.  Use -DWITH_REXEC for rexec
33    code, courtesy of Dan Kegel.  */
34
35 /* $FreeBSD: src/contrib/tar/src/rtapelib.c,v 1.2.2.1 2002/07/14 13:19:44 sobomax Exp $ */
36 /* $DragonFly: src/contrib/tar/src/Attic/rtapelib.c,v 1.2 2003/06/17 04:24:06 dillon Exp $ */
37
38 #include "system.h"
39
40 #include <safe-read.h>
41 #include <full-write.h>
42
43 /* Try hard to get EOPNOTSUPP defined.  486/ISC has it in net/errno.h,
44    3B2/SVR3 has it in sys/inet.h.  Otherwise, like on MSDOS, use EINVAL.  */
45
46 #ifndef EOPNOTSUPP
47 # if HAVE_NET_ERRNO_H
48 #  include <net/errno.h>
49 # endif
50 # if HAVE_SYS_INET_H
51 #  include <sys/inet.h>
52 # endif
53 # ifndef EOPNOTSUPP
54 #  define EOPNOTSUPP EINVAL
55 # endif
56 #endif
57
58 #include <signal.h>
59
60 #if HAVE_NETDB_H
61 # include <netdb.h>
62 #endif
63
64 #include "rmt.h"
65
66 /* Exit status if exec errors.  */
67 #define EXIT_ON_EXEC_ERROR 128
68
69 /* FIXME: Size of buffers for reading and writing commands to rmt.  */
70 #define COMMAND_BUFFER_SIZE 64
71
72 #ifndef RETSIGTYPE
73 # define RETSIGTYPE void
74 #endif
75
76 /* FIXME: Maximum number of simultaneous remote tape connections.  */
77 #define MAXUNIT 4
78
79 #define PREAD 0                 /* read  file descriptor from pipe() */
80 #define PWRITE 1                /* write file descriptor from pipe() */
81
82 /* Return the parent's read side of remote tape connection Fd.  */
83 #define READ_SIDE(Fd) (from_remote[Fd][PREAD])
84
85 /* Return the parent's write side of remote tape connection Fd.  */
86 #define WRITE_SIDE(Fd) (to_remote[Fd][PWRITE])
87
88 /* The pipes for receiving data from remote tape drives.  */
89 static int from_remote[MAXUNIT][2] = {{-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}};
90
91 /* The pipes for sending data to remote tape drives.  */
92 static int to_remote[MAXUNIT][2] = {{-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}};
93
94 /* Temporary variable used by macros in rmt.h.  */
95 char *rmt_path__;
96 \f
97
98 /* Close remote tape connection HANDLE, and reset errno to ERRNO_VALUE.  */
99 static void
100 _rmt_shutdown (int handle, int errno_value)
101 {
102   close (READ_SIDE (handle));
103   close (WRITE_SIDE (handle));
104   READ_SIDE (handle) = -1;
105   WRITE_SIDE (handle) = -1;
106   errno = errno_value;
107 }
108
109 /* Attempt to perform the remote tape command specified in BUFFER on
110    remote tape connection HANDLE.  Return 0 if successful, -1 on
111    error.  */
112 static int
113 do_command (int handle, const char *buffer)
114 {
115   /* Save the current pipe handler and try to make the request.  */
116
117   size_t length = strlen (buffer);
118   RETSIGTYPE (*pipe_handler) () = signal (SIGPIPE, SIG_IGN);
119   ssize_t written = full_write (WRITE_SIDE (handle), buffer, length);
120   signal (SIGPIPE, pipe_handler);
121
122   if (written == length)
123     return 0;
124
125   /* Something went wrong.  Close down and go home.  */
126
127   _rmt_shutdown (handle, EIO);
128   return -1;
129 }
130
131 static char *
132 get_status_string (int handle, char *command_buffer)
133 {
134   char *cursor;
135   int counter;
136
137   /* Read the reply command line.  */
138
139   for (counter = 0, cursor = command_buffer;
140        counter < COMMAND_BUFFER_SIZE;
141        counter++, cursor++)
142     {
143       if (safe_read (READ_SIDE (handle), cursor, 1) != 1)
144         {
145           _rmt_shutdown (handle, EIO);
146           return 0;
147         }
148       if (*cursor == '\n')
149         {
150           *cursor = '\0';
151           break;
152         }
153     }
154
155   if (counter == COMMAND_BUFFER_SIZE)
156     {
157       _rmt_shutdown (handle, EIO);
158       return 0;
159     }
160
161   /* Check the return status.  */
162
163   for (cursor = command_buffer; *cursor; cursor++)
164     if (*cursor != ' ')
165       break;
166
167   if (*cursor == 'E' || *cursor == 'F')
168     {
169       errno = atoi (cursor + 1);
170
171       /* Skip the error message line.  */
172
173       /* FIXME: there is better to do than merely ignoring error messages
174          coming from the remote end.  Translate them, too...  */
175
176       {
177         char character;
178
179         while (safe_read (READ_SIDE (handle), &character, 1) == 1)
180           if (character == '\n')
181             break;
182       }
183
184       if (*cursor == 'F')
185         _rmt_shutdown (handle, errno);
186
187       return 0;
188     }
189
190   /* Check for mis-synced pipes.  */
191
192   if (*cursor != 'A')
193     {
194       _rmt_shutdown (handle, EIO);
195       return 0;
196     }
197
198   /* Got an `A' (success) response.  */
199
200   return cursor + 1;
201 }
202
203 /* Read and return the status from remote tape connection HANDLE.  If
204    an error occurred, return -1 and set errno.  */
205 static long
206 get_status (int handle)
207 {
208   char command_buffer[COMMAND_BUFFER_SIZE];
209   const char *status = get_status_string (handle, command_buffer);
210   return status ? atol (status) : -1L;
211 }
212
213 static off_t
214 get_status_off (int handle)
215 {
216   char command_buffer[COMMAND_BUFFER_SIZE];
217   const char *status = get_status_string (handle, command_buffer);
218
219   if (! status)
220     return -1;
221   else
222     {
223       /* Parse status, taking care to check for overflow.
224          We can't use standard functions,
225          since off_t might be longer than long.  */
226
227       off_t count = 0;
228       int negative;
229
230       for (;  *status == ' ' || *status == '\t';  status++)
231         continue;
232       
233       negative = *status == '-';
234       status += negative || *status == '+';
235       
236       for (;;)
237         {
238           int digit = *status++ - '0';
239           if (9 < (unsigned) digit)
240             break;
241           else
242             {
243               off_t c10 = 10 * count;
244               off_t nc = negative ? c10 - digit : c10 + digit;
245               if (c10 / 10 != count || (negative ? c10 < nc : nc < c10))
246                 return -1;
247               count = nc;
248             }
249         }
250
251       return count;
252     }
253 }
254
255 #if WITH_REXEC
256
257 /* Execute /etc/rmt as user USER on remote system HOST using rexec.
258    Return a file descriptor of a bidirectional socket for stdin and
259    stdout.  If USER is zero, use the current username.
260
261    By default, this code is not used, since it requires that the user
262    have a .netrc file in his/her home directory, or that the
263    application designer be willing to have rexec prompt for login and
264    password info.  This may be unacceptable, and .rhosts files for use
265    with rsh are much more common on BSD systems.  */
266 static int
267 _rmt_rexec (char *host, char *user)
268 {
269   int saved_stdin = dup (STDIN_FILENO);
270   int saved_stdout = dup (STDOUT_FILENO);
271   struct servent *rexecserv;
272   int result;
273
274   /* When using cpio -o < filename, stdin is no longer the tty.  But the
275      rexec subroutine reads the login and the passwd on stdin, to allow
276      remote execution of the command.  So, reopen stdin and stdout on
277      /dev/tty before the rexec and give them back their original value
278      after.  */
279
280   if (! freopen ("/dev/tty", "r", stdin))
281     freopen ("/dev/null", "r", stdin);
282   if (! freopen ("/dev/tty", "w", stdout))
283     freopen ("/dev/null", "w", stdout);
284
285   if (rexecserv = getservbyname ("exec", "tcp"), !rexecserv)
286     error (EXIT_ON_EXEC_ERROR, 0, _("exec/tcp: Service not available"));
287
288   result = rexec (&host, rexecserv->s_port, user, 0, "/etc/rmt", 0);
289   if (fclose (stdin) == EOF)
290     error (0, errno, _("stdin"));
291   fdopen (saved_stdin, "r");
292   if (fclose (stdout) == EOF)
293     error (0, errno, _("stdout"));
294   fdopen (saved_stdout, "w");
295
296   return result;
297 }
298
299 #endif /* WITH_REXEC */
300
301 /* Place into BUF a string representing OFLAG, which must be suitable
302    as argument 2 of `open'.  BUF must be large enough to hold the
303    result.  This function should generate a string that decode_oflag
304    can parse.  */
305 static void
306 encode_oflag (char *buf, int oflag)
307 {
308   sprintf (buf, "%d ", oflag);
309
310   switch (oflag & O_ACCMODE)
311     {
312     case O_RDONLY: strcat (buf, "O_RDONLY"); break;
313     case O_RDWR: strcat (buf, "O_RDWR"); break;
314     case O_WRONLY: strcat (buf, "O_WRONLY"); break;
315     default: abort ();
316     }
317
318 #ifdef O_APPEND
319   if (oflag & O_APPEND) strcat (buf, "|O_APPEND");
320 #endif
321   if (oflag & O_CREAT) strcat (buf, "|O_CREAT");
322 #ifdef O_DSYNC
323   if (oflag & O_DSYNC) strcat (buf, "|O_DSYNC");
324 #endif
325   if (oflag & O_EXCL) strcat (buf, "|O_EXCL");
326 #ifdef O_LARGEFILE
327   if (oflag & O_LARGEFILE) strcat (buf, "|O_LARGEFILE");
328 #endif
329 #ifdef O_NOCTTY
330   if (oflag & O_NOCTTY) strcat (buf, "|O_NOCTTY");
331 #endif
332 #ifdef O_NONBLOCK
333   if (oflag & O_NONBLOCK) strcat (buf, "|O_NONBLOCK");
334 #endif
335 #ifdef O_RSYNC
336   if (oflag & O_RSYNC) strcat (buf, "|O_RSYNC");
337 #endif
338 #ifdef O_SYNC
339   if (oflag & O_SYNC) strcat (buf, "|O_SYNC");
340 #endif
341   if (oflag & O_TRUNC) strcat (buf, "|O_TRUNC");
342 }
343
344 /* Open a file (a magnetic tape device?) on the system specified in
345    PATH, as the given user.  PATH has the form `[USER@]HOST:FILE'.
346    OPEN_MODE is O_RDONLY, O_WRONLY, etc.  If successful, return the
347    remote pipe number plus BIAS.  REMOTE_SHELL may be overridden.  On
348    error, return -1.  */
349 int
350 rmt_open__ (const char *path, int open_mode, int bias, const char *remote_shell)
351 {
352   int remote_pipe_number;       /* pseudo, biased file descriptor */
353   char *path_copy ;             /* copy of path string */
354   char *remote_host;            /* remote host name */
355   char *remote_file;            /* remote file name (often a device) */
356   char *remote_user;            /* remote user name */
357
358   /* Find an unused pair of file descriptors.  */
359
360   for (remote_pipe_number = 0;
361        remote_pipe_number < MAXUNIT;
362        remote_pipe_number++)
363     if (READ_SIDE (remote_pipe_number) == -1
364         && WRITE_SIDE (remote_pipe_number) == -1)
365       break;
366
367   if (remote_pipe_number == MAXUNIT)
368     {
369       errno = EMFILE;
370       return -1;
371     }
372
373   /* Pull apart the system and device, and optional user.  */
374
375   {
376     char *cursor;
377
378     path_copy = xstrdup (path);
379     remote_host = path_copy;
380     remote_user = 0;
381     remote_file = 0;
382
383     for (cursor = path_copy; *cursor; cursor++)
384       switch (*cursor)
385         {
386         default:
387           break;
388
389         case '\n':
390           /* Do not allow newlines in the path, since the protocol
391              uses newline delimiters.  */
392           free (path_copy);
393           errno = ENOENT;
394           return -1;
395
396         case '@':
397           if (!remote_user)
398             {
399               remote_user = remote_host;
400               *cursor = '\0';
401               remote_host = cursor + 1;
402             }
403           break;
404
405         case ':':
406           if (!remote_file)
407             {
408               *cursor = '\0';
409               remote_file = cursor + 1;
410             }
411           break;
412         }
413   }
414
415   /* FIXME: Should somewhat validate the decoding, here.  */
416
417   if (remote_user && *remote_user == '\0')
418     remote_user = 0;
419
420 #if WITH_REXEC
421
422   /* Execute the remote command using rexec.  */
423
424   READ_SIDE (remote_pipe_number) = _rmt_rexec (remote_host, remote_user);
425   if (READ_SIDE (remote_pipe_number) < 0)
426     {
427       int e = errno;
428       free (path_copy);
429       errno = e;
430       return -1;
431     }
432
433   WRITE_SIDE (remote_pipe_number) = READ_SIDE (remote_pipe_number);
434
435 #else /* not WITH_REXEC */
436   {
437     const char *remote_shell_basename;
438     pid_t status;
439
440     /* Identify the remote command to be executed.  */
441
442     if (!remote_shell)
443       remote_shell = getenv("TAR_RSH");
444
445     if (!remote_shell)
446       {
447 #ifdef REMOTE_SHELL
448         remote_shell = REMOTE_SHELL;
449 #else
450         free (path_copy);
451         errno = EIO;
452         return -1;
453 #endif
454       }
455     remote_shell_basename = base_name (remote_shell);
456
457     /* Set up the pipes for the `rsh' command, and fork.  */
458
459     if (pipe (to_remote[remote_pipe_number]) == -1
460         || pipe (from_remote[remote_pipe_number]) == -1)
461       {
462         int e = errno;
463         free (path_copy);
464         errno = e;
465         return -1;
466       }
467
468     status = fork ();
469     if (status == -1)
470       {
471         int e = errno;
472         free (path_copy);
473         errno = e;
474         return -1;
475       }
476
477     if (status == 0)
478       {
479         /* Child.  */
480
481         close (STDIN_FILENO);
482         dup (to_remote[remote_pipe_number][PREAD]);
483         close (to_remote[remote_pipe_number][PREAD]);
484         close (to_remote[remote_pipe_number][PWRITE]);
485
486         close (STDOUT_FILENO);
487         dup (from_remote[remote_pipe_number][PWRITE]);
488         close (from_remote[remote_pipe_number][PREAD]);
489         close (from_remote[remote_pipe_number][PWRITE]);
490
491 #if !MSDOS
492         setuid (getuid ());
493         setgid (getgid ());
494 #endif
495
496         if (remote_user)
497           execlp (remote_shell, remote_shell_basename, "-l", remote_user,
498                 remote_host, "/etc/rmt", (char *) 0);
499         else
500           execlp (remote_shell, remote_shell_basename, remote_host,
501                  "/etc/rmt", (char *) 0);
502
503         /* Bad problems if we get here.  */
504
505         /* In a previous version, _exit was used here instead of exit.  */
506         error (EXIT_ON_EXEC_ERROR, errno, _("Cannot execute remote shell"));
507       }
508
509     /* Parent.  */
510
511     close (from_remote[remote_pipe_number][PWRITE]);
512     close (to_remote[remote_pipe_number][PREAD]);
513   }
514 #endif /* not WITH_REXEC */
515
516   /* Attempt to open the tape device.  */
517
518   {
519     size_t remote_file_len = strlen (remote_file);
520     char *command_buffer = xmalloc (remote_file_len + 1000);
521     sprintf (command_buffer, "O%s\n", remote_file);
522     encode_oflag (command_buffer + remote_file_len + 2, open_mode);
523     strcat (command_buffer, "\n");
524     if (do_command (remote_pipe_number, command_buffer) == -1
525         || get_status (remote_pipe_number) == -1)
526       {
527         int e = errno;
528         free (command_buffer);
529         free (path_copy);
530         _rmt_shutdown (remote_pipe_number, e);
531         return -1;
532       }
533     free (command_buffer);
534   }
535
536   free (path_copy);
537   return remote_pipe_number + bias;
538 }
539
540 /* Close remote tape connection HANDLE and shut down.  Return 0 if
541    successful, -1 on error.  */
542 int
543 rmt_close__ (int handle)
544 {
545   int status;
546
547   if (do_command (handle, "C\n") == -1)
548     return -1;
549
550   status = get_status (handle);
551   _rmt_shutdown (handle, errno);
552   return status;
553 }
554
555 /* Read up to LENGTH bytes into BUFFER from remote tape connection HANDLE.
556    Return the number of bytes read on success, -1 on error.  */
557 ssize_t
558 rmt_read__ (int handle, char *buffer, size_t length)
559 {
560   char command_buffer[COMMAND_BUFFER_SIZE];
561   ssize_t status, rlen;
562   size_t counter;
563
564   sprintf (command_buffer, "R%lu\n", (unsigned long) length);
565   if (do_command (handle, command_buffer) == -1
566       || (status = get_status (handle)) == -1)
567     return -1;
568
569   for (counter = 0; counter < status; counter += rlen, buffer += rlen)
570     {
571       rlen = safe_read (READ_SIDE (handle), buffer, status - counter);
572       if (rlen <= 0)
573         {
574           _rmt_shutdown (handle, EIO);
575           return -1;
576         }
577     }
578
579   return status;
580 }
581
582 /* Write LENGTH bytes from BUFFER to remote tape connection HANDLE.
583    Return the number of bytes written on success, -1 on error.  */
584 ssize_t
585 rmt_write__ (int handle, char *buffer, size_t length)
586 {
587   char command_buffer[COMMAND_BUFFER_SIZE];
588   RETSIGTYPE (*pipe_handler) ();
589   size_t written;
590
591   sprintf (command_buffer, "W%lu\n", (unsigned long) length);
592   if (do_command (handle, command_buffer) == -1)
593     return -1;
594
595   pipe_handler = signal (SIGPIPE, SIG_IGN);
596   written = full_write (WRITE_SIDE (handle), buffer, length);
597   signal (SIGPIPE, pipe_handler);
598   if (written == length)
599     return get_status (handle);
600
601   /* Write error.  */
602
603   _rmt_shutdown (handle, EIO);
604   return -1;
605 }
606
607 /* Perform an imitation lseek operation on remote tape connection
608    HANDLE.  Return the new file offset if successful, -1 if on error.  */
609 off_t
610 rmt_lseek__ (int handle, off_t offset, int whence)
611 {
612   char command_buffer[COMMAND_BUFFER_SIZE];
613   char operand_buffer[UINTMAX_STRSIZE_BOUND];
614   uintmax_t u = offset < 0 ? - (uintmax_t) offset : (uintmax_t) offset;
615   char *p = operand_buffer + sizeof operand_buffer;
616
617   do
618     *--p = '0' + (int) (u % 10);
619   while ((u /= 10) != 0);
620   if (offset < 0)
621     *--p = '-';
622
623   switch (whence)
624     {
625     case SEEK_SET: whence = 0; break;
626     case SEEK_CUR: whence = 1; break;
627     case SEEK_END: whence = 2; break;
628     default: abort ();
629     }
630
631   sprintf (command_buffer, "L%s\n%d\n", p, whence);
632
633   if (do_command (handle, command_buffer) == -1)
634     return -1;
635
636   return get_status_off (handle);
637 }
638
639 /* Perform a raw tape operation on remote tape connection HANDLE.
640    Return the results of the ioctl, or -1 on error.  */
641 int
642 rmt_ioctl__ (int handle, int operation, char *argument)
643 {
644   switch (operation)
645     {
646     default:
647       errno = EOPNOTSUPP;
648       return -1;
649
650 #ifdef MTIOCTOP
651     case MTIOCTOP:
652       {
653         char command_buffer[COMMAND_BUFFER_SIZE];
654         char operand_buffer[UINTMAX_STRSIZE_BOUND];
655         uintmax_t u = (((struct mtop *) argument)->mt_count < 0
656                        ? - (uintmax_t) ((struct mtop *) argument)->mt_count
657                        : (uintmax_t) ((struct mtop *) argument)->mt_count);
658         char *p = operand_buffer + sizeof operand_buffer;
659         
660         do
661           *--p = '0' + (int) (u % 10);
662         while ((u /= 10) != 0);
663         if (((struct mtop *) argument)->mt_count < 0)
664           *--p = '-';
665
666         /* MTIOCTOP is the easy one.  Nothing is transferred in binary.  */
667
668         sprintf (command_buffer, "I%d\n%s\n",
669                  ((struct mtop *) argument)->mt_op, p);
670         if (do_command (handle, command_buffer) == -1)
671           return -1;
672
673         return get_status (handle);
674       }
675 #endif /* MTIOCTOP */
676
677 #ifdef MTIOCGET
678     case MTIOCGET:
679       {
680         ssize_t status;
681         ssize_t counter;
682
683         /* Grab the status and read it directly into the structure.  This
684            assumes that the status buffer is not padded and that 2 shorts
685            fit in a long without any word alignment problems; i.e., the
686            whole struct is contiguous.  NOTE - this is probably NOT a good
687            assumption.  */
688
689         if (do_command (handle, "S") == -1
690             || (status = get_status (handle), status == -1))
691           return -1;
692
693         for (; status > 0; status -= counter, argument += counter)
694           {
695             counter = safe_read (READ_SIDE (handle), argument, status);
696             if (counter <= 0)
697               {
698                 _rmt_shutdown (handle, EIO);
699                 return -1;
700               }
701           }
702
703         /* Check for byte position.  mt_type (or mt_model) is a small integer
704            field (normally) so we will check its magnitude.  If it is larger
705            than 256, we will assume that the bytes are swapped and go through
706            and reverse all the bytes.  */
707
708         if (((struct mtget *) argument)->MTIO_CHECK_FIELD < 256)
709           return 0;
710
711         for (counter = 0; counter < status; counter += 2)
712           {
713             char copy = argument[counter];
714
715             argument[counter] = argument[counter + 1];
716             argument[counter + 1] = copy;
717           }
718
719         return 0;
720       }
721 #endif /* MTIOCGET */
722
723     }
724 }