]> git.cworth.org Git - tar/blob - rmt/rmt.c
fix for syntax error induced when resolving merge conflicts
[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     }
279   else
280     mode = numeric_mode;
281   *pmode = mode;
282   return 0;
283 }
284
285 \f
286 /* Syntax
287    ------
288    O<device>\n<flags>\n
289
290    Function
291    --------
292    Opens the <device> with given <flags>. If a device had already been opened,
293    it is closed before opening the new one.
294
295    Arguments
296    ---------
297    <device> - name of the device to open.
298    <flags>  - flags for open(2): a decimal number, or any valid O_* constant
299    from fcntl.h (the initial O_ may be omitted), or a bitwise or (using '|')
300    of any number of these, e.g.:
301
302       576
303       64|512
304       CREAT|TRUNC
305
306    In addition, a compined form is also allowed, i.e. a decimal mode followed
307    by its symbolic representation.  In this case the symbolic representation
308    is given preference.
309       
310    Reply
311    -----
312    A0\n on success, E0\n<msg>\n on error.
313
314    Extensions
315    ----------
316    BSD version allows only decimal number as <flags>
317 */
318
319 static void
320 open_device (char *str)
321 {
322   char *device = xstrdup (str);
323   char *flag_str;
324   int flag;
325
326   flag_str = rmt_read ();
327   if (!flag_str)
328     {
329       DEBUG (1, "unexpected EOF");
330       exit (EXIT_FAILURE);
331     }
332   if (decode_open_flag (flag_str, &flag) == 0)
333     {
334       if (device_fd >= 0)
335         close (device_fd);
336
337       device_fd = open (device, flag, MODE_RW);
338       if (device_fd < 0)
339         rmt_error (errno);
340       else
341         rmt_reply (0);
342     }
343   free (device);
344 }
345 \f
346 /* Syntax
347    ------
348    C[<device>]\n
349
350    Function
351    --------
352    Close the currently open device.
353
354    Arguments
355    ---------
356    Any arguments are silently ignored.
357
358    Reply
359    -----
360    A0\n on success, E0\n<msg>\n on error.
361 */
362 static void
363 close_device (void)
364 {
365   if (close (device_fd) < 0)
366     rmt_error (errno);
367   else
368     {
369       device_fd = -1;
370       rmt_reply (0);
371     }
372 }
373 \f
374 /* Syntax
375    ------
376    L<whence>\n<offset>\n
377
378    Function
379    --------
380    Perform an lseek(2) on the currently open device with the specified
381    parameters.
382
383    Arguments
384    ---------
385    <whence>  -  Where to measure offset from. Valid values are:
386                 0, SET, SEEK_SET to seek from the file beginning,
387                 1, CUR, SEEK_CUR to seek from the current location in file,
388                 2, END, SEEK_END to seek from the file end.
389    Reply
390    -----
391    A<offset>\n on success. The <offset> is the new offset in file.
392    E0\n<msg>\n on error.
393
394    Extensions
395    ----------
396    BSD version allows only 0,1,2 as <whence>.
397 */
398
399 static struct rmt_kw const seek_whence_kw[] =
400   {
401     RMT_KW(SET, SEEK_SET),
402     RMT_KW(CUR, SEEK_CUR),
403     RMT_KW(END, SEEK_END),
404     { NULL }
405   };
406
407 static void
408 lseek_device (const char *str)
409 {
410   char *p;
411   int whence;
412   off_t off;
413   uintmax_t n;
414
415   if (str[0] && str[1] == 0)
416     {
417       switch (str[0])
418         {
419         case '0':
420           whence = SEEK_SET;
421           break;
422
423         case '1':
424           whence = SEEK_CUR;
425           break;
426
427         case '2':
428           whence = SEEK_END;
429           break;
430
431         default:
432           rmt_error_message (EINVAL, N_("Seek direction out of range"));
433           return;
434         }
435     }
436   else if (xlat_kw (str, "SEEK_", seek_whence_kw, &whence, (const char **) &p))
437     {
438       rmt_error_message (EINVAL, N_("Invalid seek direction"));
439       return;
440     }
441
442   str = rmt_read ();
443   n = off = strtoumax (str, &p, 10);
444   if (*p)
445     {
446       rmt_error_message (EINVAL, N_("Invalid seek offset"));
447       return;
448     }
449
450   if (n != off || errno == ERANGE)
451     {
452       rmt_error_message (EINVAL, N_("Seek offset out of range"));
453       return;
454     }
455
456   off = lseek (device_fd, off, whence);
457   if (off < 0)
458     rmt_error (errno);
459   else
460     rmt_reply (off);
461 }
462 \f
463 /* Syntax
464    ------
465    R<count>\n
466
467    Function
468    --------
469    Read <count> bytes of data from the current device.
470
471    Arguments
472    ---------
473    <count>  -  number of bytes to read.
474
475    Reply
476    -----
477    On success: A<rdcount>\n, followed by <rdcount> bytes of data read from
478    the device.
479    On error: E0\n<msg>\n
480 */
481
482 static void
483 read_device (const char *str)
484 {
485   char *p;
486   size_t size;
487   uintmax_t n;
488   size_t status;
489
490   n = size = strtoumax (str, &p, 10);
491   if (*p)
492     {
493       rmt_error_message (EINVAL, N_("Invalid byte count"));
494       return;
495     }
496
497   if (n != size || errno == ERANGE)
498     {
499       rmt_error_message (EINVAL, N_("Byte count out of range"));
500       return;
501     }
502
503   prepare_record_buffer (size);
504   status = safe_read (device_fd, record_buffer_ptr, size);
505   if (status == SAFE_READ_ERROR)
506     rmt_error (errno);
507   else
508     {
509       rmt_reply (status);
510       full_write (STDOUT_FILENO, record_buffer_ptr, status);
511     }
512 }
513 \f
514 /* Syntax
515    ------
516    W<count>\n followed by <count> bytes of input data.
517
518    Function
519    --------
520    Write data onto the current device.
521
522    Arguments
523    ---------
524    <count>  - number of bytes.
525
526    Reply
527    -----
528    On success: A<wrcount>\n, where <wrcount> is number of bytes actually
529    written.
530    On error: E0\n<msg>\n
531 */
532
533 static void
534 write_device (const char *str)
535 {
536   char *p;
537   size_t size;
538   uintmax_t n;
539   size_t status;
540
541   n = size = strtoumax (str, &p, 10);
542   if (*p)
543     {
544       rmt_error_message (EINVAL, N_("Invalid byte count"));
545       return;
546     }
547
548   if (n != size || errno == ERANGE)
549     {
550       rmt_error_message (EINVAL, N_("Byte count out of range"));
551       return;
552     }
553
554   prepare_record_buffer (size);
555   if (fread (record_buffer_ptr, size, 1, stdin) != 1)
556     {
557       if (feof (stdin))
558         rmt_error_message (EIO, N_("Premature eof"));
559       else
560         rmt_error (errno);
561       return;
562     }
563
564   status = full_write (device_fd, record_buffer_ptr, size);
565   if (status != size)
566     rmt_error (errno);
567   else
568     rmt_reply (status);
569 }
570 \f
571 /* Syntax
572    ------
573    I<opcode>\n<count>\n
574
575    Function
576    --------
577    Perform a MTIOCOP ioctl(2) command using the specified paramedters.
578
579    Arguments
580    ---------
581    <opcode>   -  MTIOCOP operation code.
582    <count>    -  mt_count.
583
584    Reply
585    -----
586    On success: A0\n
587    On error: E0\n<msg>\n
588 */
589
590 static void
591 iocop_device (const char *str)
592 {
593   char *p;
594   long opcode;
595   off_t count;
596   uintmax_t n;
597
598   opcode = strtol (str, &p, 10);
599   if (*p)
600     {
601       rmt_error_message (EINVAL, N_("Invalid operation code"));
602       return;
603     }
604   str = rmt_read ();
605   n = count = strtoumax (str, &p, 10);
606   if (*p)
607     {
608       rmt_error_message (EINVAL, N_("Invalid byte count"));
609       return;
610     }
611
612   if (n != count || errno == ERANGE)
613     {
614       rmt_error_message (EINVAL, N_("Byte count out of range"));
615       return;
616     }
617
618 #ifdef MTIOCTOP
619   {
620     struct mtop mtop;
621
622     mtop.mt_count = count;
623     if (mtop.mt_count != count)
624       {
625         rmt_error_message (EINVAL, N_("Byte count out of range"));
626         return;
627       }
628
629     mtop.mt_op = opcode;
630     if (ioctl (device_fd, MTIOCTOP, (char *) &mtop) < 0)
631       rmt_error (errno);
632     else
633       rmt_reply (0);
634   }
635 #else
636   rmt_error_message (ENOSYS, N_("Operation not supported"));
637 #endif
638 }
639 \f
640 /* Syntax
641    ------
642    S\n
643
644    Function
645    --------
646    Return the status of the open device, as obtained with a MTIOCGET
647    ioctl call.
648
649    Arguments
650    ---------
651    None
652
653    Reply
654    -----
655    On success: A<count>\n followed by <count> bytes of data.
656    On error: E0\n<msg>\n
657 */
658
659 static void
660 status_device (const char *str)
661 {
662   if (*str)
663     {
664       rmt_error_message (EINVAL, N_("Unexpected arguments"));
665       return;
666     }
667 #ifdef MTIOCGET
668   {
669     struct mtget mtget;
670
671     if (ioctl (device_fd, MTIOCGET, (char *) &mtget) < 0)
672       rmt_error (errno);
673     else
674       {
675         rmt_reply (sizeof (mtget));
676         full_write (STDOUT_FILENO, (char *) &mtget, sizeof (mtget));
677       }
678   }
679 #else
680   rmt_error_message (ENOSYS, N_("Operation not supported"));
681 #endif
682 }
683
684
685 \f
686 const char *argp_program_version = "rmt (" PACKAGE_NAME ") " VERSION;
687 const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
688
689 static char const doc[] = N_("Manipulate a tape drive, accepting commands from a remote process");
690
691 enum {
692   DEBUG_FILE_OPTION = 256
693 };
694
695 static struct argp_option options[] = {
696   { "debug", 'd', N_("NUMBER"), 0,
697     N_("set debug level"), 0 },
698   { "debug-file", DEBUG_FILE_OPTION, N_("FILE"), 0,
699     N_("set debug output file name"), 0 },
700   { NULL }
701 };
702
703 static error_t
704 parse_opt (int key, char *arg, struct argp_state *state)
705 {
706   switch (key)
707     {
708     case 'd':
709       dbglev = strtol (arg, NULL, 0);
710       break;
711
712     case DEBUG_FILE_OPTION:
713       dbgout = fopen (arg, "w");
714       if (!dbgout)
715         error (EXIT_FAILURE, errno, _("cannot open %s"), arg);
716       break;
717
718     case ARGP_KEY_FINI:
719       if (dbglev)
720         {
721           if (!dbgout)
722             dbgout = stderr;
723         }
724       else if (dbgout)
725         dbglev = 1;
726       break;
727
728     default:
729       return ARGP_ERR_UNKNOWN;
730     }
731   return 0;
732 }
733
734 static struct argp argp = {
735   options,
736   parse_opt,
737   NULL,
738   doc,
739   NULL,
740   NULL,
741   NULL
742 };
743
744 static const char *rmt_authors[] = {
745   "Sergey Poznyakoff",
746   NULL
747 };
748
749 \f
750 void
751 xalloc_die (void)
752 {
753   rmt_error (ENOMEM);
754   exit (EXIT_FAILURE);
755 }
756
757 \f
758 int
759 main (int argc, char **argv)
760 {
761   char *buf;
762   int idx;
763   int stop = 0;
764
765   set_program_name (argv[0]);
766   argp_version_setup ("rmt", rmt_authors);
767
768   if (isatty (STDOUT_FILENO))
769     {
770       setlocale (LC_ALL, "");
771       bindtextdomain (PACKAGE, LOCALEDIR);
772       textdomain (PACKAGE);
773     }
774
775   if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, NULL))
776     exit (EXIT_FAILURE);
777   if (idx != argc)
778     {
779       if (idx != argc - 1)
780         error (EXIT_FAILURE, 0, _("too many arguments"));
781       dbgout = fopen (argv[idx], "w");
782       if (!dbgout)
783         error (EXIT_FAILURE, errno, _("cannot open %s"), argv[idx]);
784       dbglev = 1;
785     }
786
787   while (!stop && (buf = rmt_read ()) != NULL)
788     {
789       switch (buf[0])
790         {
791         case 'C':
792           close_device ();
793           stop = 1;
794           break;
795
796         case 'I':
797           iocop_device (buf + 1);
798           break;
799
800         case 'L':
801           lseek_device (buf + 1);
802           break;
803
804         case 'O':
805           open_device (buf + 1);
806           break;
807
808         case 'R':
809           read_device (buf + 1);
810           break;
811
812         case 'S':
813           status_device (buf + 1);
814           break;
815
816         case 'W':
817           write_device (buf + 1);
818           break;
819
820         default:
821           DEBUG1 (1, "garbage input %s\n", buf);
822           rmt_error_message (EINVAL, N_("Garbage command"));
823           return EXIT_FAILURE;  /* exit status used to be 3 */
824         }
825     }
826   if (device_fd >= 0)
827     close_device ();
828   free (input_buf_ptr);
829   free (record_buffer_ptr);
830   return EXIT_SUCCESS;
831 }