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