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