]> git.cworth.org Git - tar/blob - rmt/rmt.c
Merge branch 'dfsg-orig' into dfsg-debian
[tar] / rmt / rmt.c
1 /* This file is part of GNU Paxutils.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include "system.h"
18 #include "system-ioctl.h"
19 #include <configmake.h>
20 #include <argp.h>
21 #include <argp-version-etc.h>
22 #include <getopt.h>
23 #include <full-write.h>
24 #include <configmake.h>
25 #include <inttostr.h>
26 #include <error.h>
27 #include <progname.h>
28 #include <c-ctype.h>
29 #include <safe-read.h>
30
31 #ifndef EXIT_FAILURE
32 # define EXIT_FAILURE 1
33 #endif
34 #ifndef EXIT_SUCCESS
35 # define EXIT_SUCCESS 0
36 #endif
37
38 \f
39 int dbglev;
40 FILE *dbgout;
41
42 #define DEBUG(lev,msg)                                          \
43   do { if (dbgout && (lev) <= dbglev) fprintf (dbgout, "%s", msg); } while (0)
44 #define DEBUG1(lev, fmt, x)                                             \
45   do { if (dbgout && (lev) <= dbglev) fprintf (dbgout, fmt, x); } while (0)
46 #define DEBUG2(lev, fmt, x1, x2)                                        \
47   do                                                                    \
48     {                                                                   \
49       if (dbgout && (lev) <= dbglev)                                    \
50         fprintf (dbgout, fmt, x1, x2);                                  \
51     }                                                                   \
52   while (0)
53
54 #define VDEBUG(lev, pfx, fmt, ap)               \
55   do                                            \
56     {                                           \
57       if (dbgout && (lev) <= dbglev)            \
58         {                                       \
59           fprintf (dbgout, "%s", pfx);          \
60           vfprintf (dbgout, fmt, ap);           \
61         }                                       \
62     }                                           \
63   while (0)
64
65
66 \f
67 static void
68 trimnl (char *str)
69 {
70   if (str)
71     {
72       size_t len = strlen (str);
73       if (len > 1 && str[len-1] == '\n')
74         str[len-1] = 0;
75     }
76 }
77
78
79 \f
80 char *input_buf_ptr = NULL;
81 size_t input_buf_size = 0;
82
83 static char *
84 rmt_read (void)
85 {
86   ssize_t rc = getline (&input_buf_ptr, &input_buf_size, stdin);
87   if (rc > 0)
88     {
89       DEBUG1 (10, "C: %s", input_buf_ptr);
90       trimnl (input_buf_ptr);
91       return input_buf_ptr;
92     }
93   DEBUG (10, "reached EOF");
94   return NULL;
95 }
96
97 static void
98 rmt_write (const char *fmt, ...)
99 {
100   va_list ap;
101   va_start (ap, fmt);
102   vfprintf (stdout, fmt, ap);
103   fflush (stdout);
104   VDEBUG (10, "S: ", fmt, ap);
105 }
106
107 static void
108 rmt_reply (uintmax_t code)
109 {
110   char buf[UINTMAX_STRSIZE_BOUND];
111   rmt_write ("A%s\n", umaxtostr (code, buf));
112 }
113
114 static void
115 rmt_error_message (int code, const char *msg)
116 {
117   DEBUG1 (10, "S: E%d\n", code);
118   DEBUG1 (10, "S: %s\n", msg);
119   DEBUG1 (1, "error: %s\n", msg);
120   fprintf (stdout, "E%d\n%s\n", code, msg);
121   fflush (stdout);
122 }
123
124 static void
125 rmt_error (int code)
126 {
127   rmt_error_message (code, strerror (code));
128 }
129
130 \f
131 char *record_buffer_ptr;
132 size_t record_buffer_size;
133
134 static void
135 prepare_record_buffer (size_t size)
136 {
137   if (size > record_buffer_size)
138     {
139       record_buffer_ptr = xrealloc (record_buffer_ptr, size);
140       record_buffer_size = size;
141     }
142 }
143
144
145 \f
146 int device_fd = -1;
147
148 struct rmt_kw
149 {
150   char const *name;
151   size_t len;
152   int value;
153 };
154
155 #define RMT_KW(s,v) { #s, sizeof (#s) - 1, v }
156
157 static int
158 xlat_kw (const char *s, const char *pfx,
159          struct rmt_kw const *kw, int *valp, const char **endp)
160 {
161   size_t slen = strlen (s);
162
163   if (pfx)
164     {
165       size_t pfxlen = strlen (pfx);
166       if (slen > pfxlen && memcmp (s, pfx, pfxlen) == 0)
167         {
168           s += pfxlen;
169           slen -= pfxlen;
170         }
171     }
172
173   for (; kw->name; kw++)
174     {
175       if (slen >= kw->len
176           && memcmp (kw->name, s, kw->len) == 0
177           && !(s[kw->len] && c_isalnum (s[kw->len])))
178         {
179           *valp = kw->value;
180           *endp = s + kw->len;
181           return 0;
182         }
183     }
184   return 1;
185 }
186
187 static const char *
188 skip_ws (const char *s)
189 {
190   while (*s && c_isblank (*s))
191     s++;
192   return s;
193 }
194
195 static struct rmt_kw const open_flag_kw[] =
196   {
197 #ifdef O_APPEND
198     RMT_KW(APPEND, O_APPEND),
199 #endif
200     RMT_KW(CREAT, O_CREAT),
201 #ifdef O_DSYNC
202     RMT_KW(DSYNC, O_DSYNC),
203 #endif
204     RMT_KW(EXCL, O_EXCL),
205 #ifdef O_LARGEFILE
206     RMT_KW(LARGEFILE, O_LARGEFILE),
207 #endif
208 #ifdef O_NOCTTY
209     RMT_KW(NOCTTY, O_NOCTTY),
210 #endif
211 #if O_NONBLOCK
212     RMT_KW(NONBLOCK, O_NONBLOCK),
213 #endif
214     RMT_KW(RDONLY, O_RDONLY),
215     RMT_KW(RDWR, O_RDWR),
216 #ifdef O_RSYNC
217     RMT_KW(RSYNC, O_RSYNC),
218 #endif
219 #ifdef O_SYNC
220     RMT_KW(SYNC, O_SYNC),
221 #endif
222     RMT_KW(TRUNC, O_TRUNC),
223     RMT_KW(WRONLY, O_WRONLY),
224     { NULL }
225   };
226
227 static int
228 decode_open_flag (const char *mstr, int *pmode)
229 {
230   int numeric_mode = 0;
231   int mode = 0;
232   const char *p;
233
234   mstr = skip_ws (mstr);
235   if (c_isdigit (*mstr))
236     {
237       numeric_mode = strtol (mstr, (char**) &p, 10);
238       mstr = skip_ws (p);
239     }
240
241   if (*mstr)
242     {
243       while (mstr)
244         {
245           int v;
246           
247           mstr = skip_ws (mstr);
248           if (*mstr == 0)
249             break;
250           else if (c_isdigit (*mstr))
251             v = strtol (mstr, (char**) &p, 10);
252           else if (xlat_kw (mstr, "O_", open_flag_kw, &v, &p))
253             {
254               rmt_error_message (EINVAL, "invalid open mode");
255               return 1;
256             }
257
258           mode |= v;
259           
260           if (*p && c_isblank (*p))
261             p = skip_ws (p);
262           if (*p == 0)
263             break;
264           else if (*p == '|')
265             {
266               /* FIXMEL
267                  if (p[1] == 0)
268                  rmt_error_message (EINVAL, "invalid open mode");
269               */
270               mstr = p + 1;
271             }
272           else
273             {
274               rmt_error_message (EINVAL, "invalid open mode");
275               return 1;
276             }
277     }
278   else
279     mode = numeric_mode;
280   *pmode = mode;
281   return 0;
282 }
283
284 \f
285 /* Syntax
286    ------
287    O<device>\n<flags>\n
288
289    Function
290    --------
291    Opens the <device> with given <flags>. If a device had already been opened,
292    it is closed before opening the new one.
293
294    Arguments
295    ---------
296    <device> - name of the device to open.
297    <flags>  - flags for open(2): a decimal number, or any valid O_* constant
298    from fcntl.h (the initial O_ may be omitted), or a bitwise or (using '|')
299    of any number of these, e.g.:
300
301       576
302       64|512
303       CREAT|TRUNC
304
305    In addition, a compined form is also allowed, i.e. a decimal mode followed
306    by its symbolic representation.  In this case the symbolic representation
307    is given preference.
308       
309    Reply
310    -----
311    A0\n on success, E0\n<msg>\n on error.
312
313    Extensions
314    ----------
315    BSD version allows only decimal number as <flags>
316 */
317
318 static void
319 open_device (char *str)
320 {
321   char *device = xstrdup (str);
322   char *flag_str;
323   int flag;
324
325   flag_str = rmt_read ();
326   if (!flag_str)
327     {
328       DEBUG (1, "unexpected EOF");
329       exit (EXIT_FAILURE);
330     }
331   if (decode_open_flag (flag_str, &flag) == 0)
332     {
333       if (device_fd >= 0)
334         close (device_fd);
335
336       device_fd = open (device, flag, MODE_RW);
337       if (device_fd < 0)
338         rmt_error (errno);
339       else
340         rmt_reply (0);
341     }
342   free (device);
343 }
344 \f
345 /* Syntax
346    ------
347    C[<device>]\n
348
349    Function
350    --------
351    Close the currently open device.
352
353    Arguments
354    ---------
355    Any arguments are silently ignored.
356
357    Reply
358    -----
359    A0\n on success, E0\n<msg>\n on error.
360 */
361 static void
362 close_device (void)
363 {
364   if (close (device_fd) < 0)
365     rmt_error (errno);
366   else
367     {
368       device_fd = -1;
369       rmt_reply (0);
370     }
371 }
372 \f
373 /* Syntax
374    ------
375    L<whence>\n<offset>\n
376
377    Function
378    --------
379    Perform an lseek(2) on the currently open device with the specified
380    parameters.
381
382    Arguments
383    ---------
384    <whence>  -  Where to measure offset from. Valid values are:
385                 0, SET, SEEK_SET to seek from the file beginning,
386                 1, CUR, SEEK_CUR to seek from the current location in file,
387                 2, END, SEEK_END to seek from the file end.
388    Reply
389    -----
390    A<offset>\n on success. The <offset> is the new offset in file.
391    E0\n<msg>\n on error.
392
393    Extensions
394    ----------
395    BSD version allows only 0,1,2 as <whence>.
396 */
397
398 static struct rmt_kw const seek_whence_kw[] =
399   {
400     RMT_KW(SET, SEEK_SET),
401     RMT_KW(CUR, SEEK_CUR),
402     RMT_KW(END, SEEK_END),
403     { NULL }
404   };
405
406 static void
407 lseek_device (const char *str)
408 {
409   char *p;
410   int whence;
411   off_t off;
412   uintmax_t n;
413
414   if (str[0] && str[1] == 0)
415     {
416       switch (str[0])
417         {
418         case '0':
419           whence = SEEK_SET;
420           break;
421
422         case '1':
423           whence = SEEK_CUR;
424           break;
425
426         case '2':
427           whence = SEEK_END;
428           break;
429
430         default:
431           rmt_error_message (EINVAL, N_("Seek direction out of range"));
432           return;
433         }
434     }
435   else if (xlat_kw (str, "SEEK_", seek_whence_kw, &whence, (const char **) &p))
436     {
437       rmt_error_message (EINVAL, N_("Invalid seek direction"));
438       return;
439     }
440
441   str = rmt_read ();
442   n = off = strtoumax (str, &p, 10);
443   if (*p)
444     {
445       rmt_error_message (EINVAL, N_("Invalid seek offset"));
446       return;
447     }
448
449   if (n != off || errno == ERANGE)
450     {
451       rmt_error_message (EINVAL, N_("Seek offset out of range"));
452       return;
453     }
454
455   off = lseek (device_fd, off, whence);
456   if (off < 0)
457     rmt_error (errno);
458   else
459     rmt_reply (off);
460 }
461 \f
462 /* Syntax
463    ------
464    R<count>\n
465
466    Function
467    --------
468    Read <count> bytes of data from the current device.
469
470    Arguments
471    ---------
472    <count>  -  number of bytes to read.
473
474    Reply
475    -----
476    On success: A<rdcount>\n, followed by <rdcount> bytes of data read from
477    the device.
478    On error: E0\n<msg>\n
479 */
480
481 static void
482 read_device (const char *str)
483 {
484   char *p;
485   size_t size;
486   uintmax_t n;
487   size_t status;
488
489   n = size = strtoumax (str, &p, 10);
490   if (*p)
491     {
492       rmt_error_message (EINVAL, N_("Invalid byte count"));
493       return;
494     }
495
496   if (n != size || errno == ERANGE)
497     {
498       rmt_error_message (EINVAL, N_("Byte count out of range"));
499       return;
500     }
501
502   prepare_record_buffer (size);
503   status = safe_read (device_fd, record_buffer_ptr, size);
504   if (status == SAFE_READ_ERROR)
505     rmt_error (errno);
506   else
507     {
508       rmt_reply (status);
509       full_write (STDOUT_FILENO, record_buffer_ptr, status);
510     }
511 }
512 \f
513 /* Syntax
514    ------
515    W<count>\n followed by <count> bytes of input data.
516
517    Function
518    --------
519    Write data onto the current device.
520
521    Arguments
522    ---------
523    <count>  - number of bytes.
524
525    Reply
526    -----
527    On success: A<wrcount>\n, where <wrcount> is number of bytes actually
528    written.
529    On error: E0\n<msg>\n
530 */
531
532 static void
533 write_device (const char *str)
534 {
535   char *p;
536   size_t size;
537   uintmax_t n;
538   size_t status;
539
540   n = size = strtoumax (str, &p, 10);
541   if (*p)
542     {
543       rmt_error_message (EINVAL, N_("Invalid byte count"));
544       return;
545     }
546
547   if (n != size || errno == ERANGE)
548     {
549       rmt_error_message (EINVAL, N_("Byte count out of range"));
550       return;
551     }
552
553   prepare_record_buffer (size);
554   if (fread (record_buffer_ptr, size, 1, stdin) != 1)
555     {
556       if (feof (stdin))
557         rmt_error_message (EIO, N_("Premature eof"));
558       else
559         rmt_error (errno);
560       return;
561     }
562
563   status = full_write (device_fd, record_buffer_ptr, size);
564   if (status != size)
565     rmt_error (errno);
566   else
567     rmt_reply (status);
568 }
569 \f
570 /* Syntax
571    ------
572    I<opcode>\n<count>\n
573
574    Function
575    --------
576    Perform a MTIOCOP ioctl(2) command using the specified paramedters.
577
578    Arguments
579    ---------
580    <opcode>   -  MTIOCOP operation code.
581    <count>    -  mt_count.
582
583    Reply
584    -----
585    On success: A0\n
586    On error: E0\n<msg>\n
587 */
588
589 static void
590 iocop_device (const char *str)
591 {
592   char *p;
593   long opcode;
594   off_t count;
595   uintmax_t n;
596
597   opcode = strtol (str, &p, 10);
598   if (*p)
599     {
600       rmt_error_message (EINVAL, N_("Invalid operation code"));
601       return;
602     }
603   str = rmt_read ();
604   n = count = strtoumax (str, &p, 10);
605   if (*p)
606     {
607       rmt_error_message (EINVAL, N_("Invalid byte count"));
608       return;
609     }
610
611   if (n != count || errno == ERANGE)
612     {
613       rmt_error_message (EINVAL, N_("Byte count out of range"));
614       return;
615     }
616
617 #ifdef MTIOCTOP
618   {
619     struct mtop mtop;
620
621     mtop.mt_count = count;
622     if (mtop.mt_count != count)
623       {
624         rmt_error_message (EINVAL, N_("Byte count out of range"));
625         return;
626       }
627
628     mtop.mt_op = opcode;
629     if (ioctl (device_fd, MTIOCTOP, (char *) &mtop) < 0)
630       rmt_error (errno);
631     else
632       rmt_reply (0);
633   }
634 #else
635   rmt_error_message (ENOSYS, N_("Operation not supported"));
636 #endif
637 }
638 \f
639 /* Syntax
640    ------
641    S\n
642
643    Function
644    --------
645    Return the status of the open device, as obtained with a MTIOCGET
646    ioctl call.
647
648    Arguments
649    ---------
650    None
651
652    Reply
653    -----
654    On success: A<count>\n followed by <count> bytes of data.
655    On error: E0\n<msg>\n
656 */
657
658 static void
659 status_device (const char *str)
660 {
661   if (*str)
662     {
663       rmt_error_message (EINVAL, N_("Unexpected arguments"));
664       return;
665     }
666 #ifdef MTIOCGET
667   {
668     struct mtget mtget;
669
670     if (ioctl (device_fd, MTIOCGET, (char *) &mtget) < 0)
671       rmt_error (errno);
672     else
673       {
674         rmt_reply (sizeof (mtget));
675         full_write (STDOUT_FILENO, (char *) &mtget, sizeof (mtget));
676       }
677   }
678 #else
679   rmt_error_message (ENOSYS, N_("Operation not supported"));
680 #endif
681 }
682
683
684 \f
685 const char *argp_program_version = "rmt (" PACKAGE_NAME ") " VERSION;
686 const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
687
688 static char const doc[] = N_("Manipulate a tape drive, accepting commands from a remote process");
689
690 enum {
691   DEBUG_FILE_OPTION = 256
692 };
693
694 static struct argp_option options[] = {
695   { "debug", 'd', N_("NUMBER"), 0,
696     N_("set debug level"), 0 },
697   { "debug-file", DEBUG_FILE_OPTION, N_("FILE"), 0,
698     N_("set debug output file name"), 0 },
699   { NULL }
700 };
701
702 static error_t
703 parse_opt (int key, char *arg, struct argp_state *state)
704 {
705   switch (key)
706     {
707     case 'd':
708       dbglev = strtol (arg, NULL, 0);
709       break;
710
711     case DEBUG_FILE_OPTION:
712       dbgout = fopen (arg, "w");
713       if (!dbgout)
714         error (EXIT_FAILURE, errno, _("cannot open %s"), arg);
715       break;
716
717     case ARGP_KEY_FINI:
718       if (dbglev)
719         {
720           if (!dbgout)
721             dbgout = stderr;
722         }
723       else if (dbgout)
724         dbglev = 1;
725       break;
726
727     default:
728       return ARGP_ERR_UNKNOWN;
729     }
730   return 0;
731 }
732
733 static struct argp argp = {
734   options,
735   parse_opt,
736   NULL,
737   doc,
738   NULL,
739   NULL,
740   NULL
741 };
742
743 static const char *rmt_authors[] = {
744   "Sergey Poznyakoff",
745   NULL
746 };
747
748 \f
749 void
750 xalloc_die (void)
751 {
752   rmt_error (ENOMEM);
753   exit (EXIT_FAILURE);
754 }
755
756 \f
757 int
758 main (int argc, char **argv)
759 {
760   char *buf;
761   int idx;
762   int stop = 0;
763
764   set_program_name (argv[0]);
765   argp_version_setup ("rmt", rmt_authors);
766
767   if (isatty (STDOUT_FILENO))
768     {
769       setlocale (LC_ALL, "");
770       bindtextdomain (PACKAGE, LOCALEDIR);
771       textdomain (PACKAGE);
772     }
773
774   if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, NULL))
775     exit (EXIT_FAILURE);
776   if (idx != argc)
777     {
778       if (idx != argc - 1)
779         error (EXIT_FAILURE, 0, _("too many arguments"));
780       dbgout = fopen (argv[idx], "w");
781       if (!dbgout)
782         error (EXIT_FAILURE, errno, _("cannot open %s"), argv[idx]);
783       dbglev = 1;
784     }
785
786   while (!stop && (buf = rmt_read ()) != NULL)
787     {
788       switch (buf[0])
789         {
790         case 'C':
791           close_device ();
792           stop = 1;
793           break;
794
795         case 'I':
796           iocop_device (buf + 1);
797           break;
798
799         case 'L':
800           lseek_device (buf + 1);
801           break;
802
803         case 'O':
804           open_device (buf + 1);
805           break;
806
807         case 'R':
808           read_device (buf + 1);
809           break;
810
811         case 'S':
812           status_device (buf + 1);
813           break;
814
815         case 'W':
816           write_device (buf + 1);
817           break;
818
819         default:
820           DEBUG1 (1, "garbage input %s\n", buf);
821           rmt_error_message (EINVAL, N_("Garbage command"));
822           return EXIT_FAILURE;  /* exit status used to be 3 */
823         }
824     }
825   if (device_fd >= 0)
826     close_device ();
827   free (input_buf_ptr);
828   free (record_buffer_ptr);
829   return EXIT_SUCCESS;
830 }