home *** CD-ROM | disk | FTP | other *** search
/ PC-Online 1996 May / PCOnline_05_1996.bin / linux / source / a / bin / fileutil.12 / fileutil / fileutils-3.12 / src / dd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-10-01  |  29.2 KB  |  1,126 lines

  1. /* dd -- convert a file while copying it.
  2.    Copyright (C) 1985, 1990, 1991 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 2, 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, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Paul Rubin, David MacKenzie, and Stuart Kemp. */
  19.  
  20. /* Options:
  21.  
  22.    Numbers can be followed by a multiplier:
  23.    b=512, c=1, k=1024, w=2, xm=number m
  24.  
  25.    if=FILE            Read from FILE instead of stdin.
  26.    of=FILE            Write to FILE instead of stdout; don't
  27.                 truncate FILE.
  28.    ibs=BYTES            Read BYTES bytes at a time.
  29.    obs=BYTES            Write BYTES bytes at a time.
  30.    bs=BYTES            Override ibs and obs.
  31.    cbs=BYTES            Convert BYTES bytes at a time.
  32.    skip=BLOCKS            Skip BLOCKS ibs-sized blocks at
  33.                 start of input.
  34.    seek=BLOCKS            Skip BLOCKS obs-sized blocks at
  35.                 start of output.
  36.    count=BLOCKS            Copy only BLOCKS input blocks.
  37.    conv=CONVERSION[,CONVERSION...]
  38.  
  39.    Conversions:
  40.    ascii            Convert EBCDIC to ASCII.
  41.    ebcdic            Convert ASCII to EBCDIC.
  42.    ibm                Convert ASCII to alternate EBCDIC.
  43.    block            Pad newline-terminated records to size of
  44.                 cbs, replacing newline with trailing spaces.
  45.    unblock            Replace trailing spaces in cbs-sized block
  46.                 with newline.
  47.    lcase            Change upper case characters to lower case.
  48.    ucase            Change lower case characters to upper case.
  49.    swab                Swap every pair of input bytes.
  50.                 Unlike the Unix dd, this works when an odd
  51.                 number of bytes are read.
  52.    noerror            Continue after read errors.
  53.    sync                Pad every input block to size of ibs with
  54.                 trailing NULs. */
  55.  
  56. #include <config.h>
  57. #include <stdio.h>
  58. #include <ctype.h>
  59.  
  60. #if !defined (isascii) || defined (STDC_HEADERS)
  61. #undef isascii
  62. #define isascii(c) 1
  63. #endif
  64.  
  65. #define ISLOWER(c) (isascii (c) && islower (c))
  66. #define ISUPPER(c) (isascii (c) && isupper (c))
  67. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  68.  
  69. #define SWAB_ALIGN_OFFSET 2
  70.  
  71. #include <sys/types.h>
  72. #include <signal.h>
  73. #include <getopt.h>
  74.  
  75. #include "system.h"
  76. #include "version.h"
  77.  
  78. #define equal(p, q) (strcmp ((p),(q)) == 0)
  79. #define max(a, b) ((a) > (b) ? (a) : (b))
  80. #define output_char(c) \
  81.   do { \
  82.   obuf[oc++] = (c); if (oc >= output_blocksize) write_output (); \
  83.   } while (0)
  84.  
  85. /* Default input and output blocksize. */
  86. #define DEFAULT_BLOCKSIZE 512
  87.  
  88. /* Conversions bit masks. */
  89. #define C_ASCII 01
  90. #define C_EBCDIC 02
  91. #define C_IBM 04
  92. #define C_BLOCK 010
  93. #define C_UNBLOCK 020
  94. #define C_LCASE 040
  95. #define C_UCASE 0100
  96. #define C_SWAB 0200
  97. #define C_NOERROR 0400
  98. #define C_NOTRUNC 01000
  99. #define C_SYNC 02000
  100. /* Use separate input and output buffers, and combine partial input blocks. */
  101. #define C_TWOBUFS 04000
  102.  
  103. char *xmalloc ();
  104. void error ();
  105. int safe_read ();
  106.  
  107. static RETSIGTYPE interrupt_handler ();
  108. static int bit_count ();
  109. static int parse_integer ();
  110. static void apply_translations ();
  111. static void copy ();
  112. static void copy_simple ();
  113. static void copy_with_block ();
  114. static void copy_with_unblock ();
  115. static void parse_conversion ();
  116. static void print_stats ();
  117. static void translate_charset ();
  118. static void quit ();
  119. static void scanargs ();
  120. static void skip ();
  121. static void usage ();
  122. static void write_output ();
  123.  
  124. /* The name this program was run with. */
  125. char *program_name;
  126.  
  127. /* The name of the input file, or NULL for the standard input. */
  128. static char *input_file = NULL;
  129.  
  130. /* The input file descriptor. */
  131. static int input_fd = 0;
  132.  
  133. /* The name of the output file, or NULL for the standard output. */
  134. static char *output_file = NULL;
  135.  
  136. /* The output file descriptor. */
  137. static int output_fd = 1;
  138.  
  139. /* The number of bytes in which atomic reads are done. */
  140. static long input_blocksize = -1;
  141.  
  142. /* The number of bytes in which atomic writes are done. */
  143. static long output_blocksize = -1;
  144.  
  145. /* Conversion buffer size, in bytes.  0 prevents conversions. */
  146. static long conversion_blocksize = 0;
  147.  
  148. /* Skip this many records of `input_blocksize' bytes before input. */
  149. static long skip_records = 0;
  150.  
  151. /* Skip this many records of `output_blocksize' bytes before output. */
  152. static long seek_record = 0;
  153.  
  154. /* Copy only this many records.  <0 means no limit. */
  155. static int max_records = -1;
  156.  
  157. /* Bit vector of conversions to apply. */
  158. static int conversions_mask = 0;
  159.  
  160. /* If nonzero, filter characters through the translation table.  */
  161. static int translation_needed = 0;
  162.  
  163. /* Number of partial blocks written. */
  164. static unsigned w_partial = 0;
  165.  
  166. /* Number of full blocks written. */
  167. static unsigned w_full = 0;
  168.  
  169. /* Number of partial blocks read. */
  170. static unsigned r_partial = 0;
  171.  
  172. /* Number of full blocks read. */
  173. static unsigned r_full = 0;
  174.  
  175. /* Records truncated by conv=block. */
  176. static unsigned r_truncate = 0;
  177.  
  178. /* Output representation of newline and space characters.
  179.    They change if we're converting to EBCDIC.  */
  180. static unsigned char newline_character = '\n';
  181. static unsigned char space_character = ' ';
  182.  
  183. struct conversion
  184. {
  185.   char *convname;
  186.   int conversion;
  187. };
  188.  
  189. static struct conversion conversions[] =
  190. {
  191.   {"ascii", C_ASCII | C_TWOBUFS},    /* EBCDIC to ASCII. */
  192.   {"ebcdic", C_EBCDIC | C_TWOBUFS},    /* ASCII to EBCDIC. */
  193.   {"ibm", C_IBM | C_TWOBUFS},    /* Slightly different ASCII to EBCDIC. */
  194.   {"block", C_BLOCK | C_TWOBUFS},    /* Variable to fixed length records. */
  195.   {"unblock", C_UNBLOCK | C_TWOBUFS},    /* Fixed to variable length records. */
  196.   {"lcase", C_LCASE | C_TWOBUFS},    /* Translate upper to lower case. */
  197.   {"ucase", C_UCASE | C_TWOBUFS},    /* Translate lower to upper case. */
  198.   {"swab", C_SWAB | C_TWOBUFS},    /* Swap bytes of input. */
  199.   {"noerror", C_NOERROR},    /* Ignore i/o errors. */
  200.   {"notrunc", C_NOTRUNC},    /* Do not truncate output file. */
  201.   {"sync", C_SYNC},        /* Pad input records to ibs with NULs. */
  202.   {NULL, 0}
  203. };
  204.  
  205. /* Translation table formed by applying successive transformations. */
  206. static unsigned char trans_table[256];
  207.  
  208. static unsigned char const ascii_to_ebcdic[] =
  209. {
  210.   0, 01, 02, 03, 067, 055, 056, 057,
  211.   026, 05, 045, 013, 014, 015, 016, 017,
  212.   020, 021, 022, 023, 074, 075, 062, 046,
  213.   030, 031, 077, 047, 034, 035, 036, 037,
  214.   0100, 0117, 0177, 0173, 0133, 0154, 0120, 0175,
  215.   0115, 0135, 0134, 0116, 0153, 0140, 0113, 0141,
  216.   0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  217.   0370, 0371, 0172, 0136, 0114, 0176, 0156, 0157,
  218.   0174, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  219.   0310, 0311, 0321, 0322, 0323, 0324, 0325, 0326,
  220.   0327, 0330, 0331, 0342, 0343, 0344, 0345, 0346,
  221.   0347, 0350, 0351, 0112, 0340, 0132, 0137, 0155,
  222.   0171, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  223.   0210, 0211, 0221, 0222, 0223, 0224, 0225, 0226,
  224.   0227, 0230, 0231, 0242, 0243, 0244, 0245, 0246,
  225.   0247, 0250, 0251, 0300, 0152, 0320, 0241, 07,
  226.   040, 041, 042, 043, 044, 025, 06, 027,
  227.   050, 051, 052, 053, 054, 011, 012, 033,
  228.   060, 061, 032, 063, 064, 065, 066, 010,
  229.   070, 071, 072, 073, 04, 024, 076, 0341,
  230.   0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110,
  231.   0111, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  232.   0130, 0131, 0142, 0143, 0144, 0145, 0146, 0147,
  233.   0150, 0151, 0160, 0161, 0162, 0163, 0164, 0165,
  234.   0166, 0167, 0170, 0200, 0212, 0213, 0214, 0215,
  235.   0216, 0217, 0220, 0232, 0233, 0234, 0235, 0236,
  236.   0237, 0240, 0252, 0253, 0254, 0255, 0256, 0257,
  237.   0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  238.   0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  239.   0312, 0313, 0314, 0315, 0316, 0317, 0332, 0333,
  240.   0334, 0335, 0336, 0337, 0352, 0353, 0354, 0355,
  241.   0356, 0357, 0372, 0373, 0374, 0375, 0376, 0377
  242. };
  243.  
  244. static unsigned char const ascii_to_ibm[] =
  245. {
  246.   0, 01, 02, 03, 067, 055, 056, 057,
  247.   026, 05, 045, 013, 014, 015, 016, 017,
  248.   020, 021, 022, 023, 074, 075, 062, 046,
  249.   030, 031, 077, 047, 034, 035, 036, 037,
  250.   0100, 0132, 0177, 0173, 0133, 0154, 0120, 0175,
  251.   0115, 0135, 0134, 0116, 0153, 0140, 0113, 0141,
  252.   0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  253.   0370, 0371, 0172, 0136, 0114, 0176, 0156, 0157,
  254.   0174, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  255.   0310, 0311, 0321, 0322, 0323, 0324, 0325, 0326,
  256.   0327, 0330, 0331, 0342, 0343, 0344, 0345, 0346,
  257.   0347, 0350, 0351, 0255, 0340, 0275, 0137, 0155,
  258.   0171, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  259.   0210, 0211, 0221, 0222, 0223, 0224, 0225, 0226,
  260.   0227, 0230, 0231, 0242, 0243, 0244, 0245, 0246,
  261.   0247, 0250, 0251, 0300, 0117, 0320, 0241, 07,
  262.   040, 041, 042, 043, 044, 025, 06, 027,
  263.   050, 051, 052, 053, 054, 011, 012, 033,
  264.   060, 061, 032, 063, 064, 065, 066, 010,
  265.   070, 071, 072, 073, 04, 024, 076, 0341,
  266.   0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110,
  267.   0111, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  268.   0130, 0131, 0142, 0143, 0144, 0145, 0146, 0147,
  269.   0150, 0151, 0160, 0161, 0162, 0163, 0164, 0165,
  270.   0166, 0167, 0170, 0200, 0212, 0213, 0214, 0215,
  271.   0216, 0217, 0220, 0232, 0233, 0234, 0235, 0236,
  272.   0237, 0240, 0252, 0253, 0254, 0255, 0256, 0257,
  273.   0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  274.   0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  275.   0312, 0313, 0314, 0315, 0316, 0317, 0332, 0333,
  276.   0334, 0335, 0336, 0337, 0352, 0353, 0354, 0355,
  277.   0356, 0357, 0372, 0373, 0374, 0375, 0376, 0377
  278. };
  279.  
  280. static unsigned char const ebcdic_to_ascii[] =
  281. {
  282.   0, 01, 02, 03, 0234, 011, 0206, 0177,
  283.   0227, 0215, 0216, 013, 014, 015, 016, 017,
  284.   020, 021, 022, 023, 0235, 0205, 010, 0207,
  285.   030, 031, 0222, 0217, 034, 035, 036, 037,
  286.   0200, 0201, 0202, 0203, 0204, 012, 027, 033,
  287.   0210, 0211, 0212, 0213, 0214, 05, 06, 07,
  288.   0220, 0221, 026, 0223, 0224, 0225, 0226, 04,
  289.   0230, 0231, 0232, 0233, 024, 025, 0236, 032,
  290.   040, 0240, 0241, 0242, 0243, 0244, 0245, 0246,
  291.   0247, 0250, 0133, 056, 074, 050, 053, 041,
  292.   046, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  293.   0260, 0261, 0135, 044, 052, 051, 073, 0136,
  294.   055, 057, 0262, 0263, 0264, 0265, 0266, 0267,
  295.   0270, 0271, 0174, 054, 045, 0137, 076, 077,
  296.   0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301,
  297.   0302, 0140, 072, 043, 0100, 047, 075, 042,
  298.   0303, 0141, 0142, 0143, 0144, 0145, 0146, 0147,
  299.   0150, 0151, 0304, 0305, 0306, 0307, 0310, 0311,
  300.   0312, 0152, 0153, 0154, 0155, 0156, 0157, 0160,
  301.   0161, 0162, 0313, 0314, 0315, 0316, 0317, 0320,
  302.   0321, 0176, 0163, 0164, 0165, 0166, 0167, 0170,
  303.   0171, 0172, 0322, 0323, 0324, 0325, 0326, 0327,
  304.   0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  305.   0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  306.   0173, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  307.   0110, 0111, 0350, 0351, 0352, 0353, 0354, 0355,
  308.   0175, 0112, 0113, 0114, 0115, 0116, 0117, 0120,
  309.   0121, 0122, 0356, 0357, 0360, 0361, 0362, 0363,
  310.   0134, 0237, 0123, 0124, 0125, 0126, 0127, 0130,
  311.   0131, 0132, 0364, 0365, 0366, 0367, 0370, 0371,
  312.   060, 061, 062, 063, 064, 065, 066, 067,
  313.   070, 071, 0372, 0373, 0374, 0375, 0376, 0377
  314. };
  315.  
  316. /* If non-zero, display usage information and exit.  */
  317. static int show_help;
  318.  
  319. /* If non-zero, print the version on standard output and exit.  */
  320. static int show_version;
  321.  
  322. static struct option const long_options[] =
  323. {
  324.   {"help", no_argument, &show_help, 1},
  325.   {"version", no_argument, &show_version, 1},
  326.   {0, 0, 0, 0}
  327. };
  328.  
  329. void
  330. main (argc, argv)
  331.      int argc;
  332.      char **argv;
  333. {
  334. #ifdef _POSIX_VERSION
  335.   struct sigaction sigact;
  336. #endif /* _POSIX_VERSION */
  337.   int i;
  338.  
  339.   program_name = argv[0];
  340.  
  341.   /* Initialize translation table to identity translation. */
  342.   for (i = 0; i < 256; i++)
  343.     trans_table[i] = i;
  344.  
  345.   /* Decode arguments. */
  346.   scanargs (argc, argv);
  347.  
  348.   if (show_version)
  349.     {
  350.       printf ("%s\n", version_string);
  351.       exit (0);
  352.     }
  353.  
  354.   if (show_help)
  355.     usage (0);
  356.  
  357.   apply_translations ();
  358.  
  359.   if (input_file != NULL)
  360.     {
  361.       input_fd = open (input_file, O_RDONLY);
  362.       if (input_fd < 0)
  363.     error (1, errno, "%s", input_file);
  364.     }
  365.   else
  366.     input_file = "standard input";
  367.  
  368.   if (input_fd == output_fd)
  369.     error (1, 0, "standard %s is closed", input_fd == 0 ? "input" : "output");
  370.  
  371.   if (output_file != NULL)
  372.     {
  373.       int omode = O_RDWR | O_CREAT;
  374.  
  375.       if (seek_record == 0 && !(conversions_mask & C_NOTRUNC))
  376.     omode |= O_TRUNC;
  377.       output_fd = open (output_file, omode, 0666);
  378.       if (output_fd < 0)
  379.     error (1, errno, "%s", output_file);
  380. #ifdef HAVE_FTRUNCATE
  381.       if (seek_record > 0 && !(conversions_mask & C_NOTRUNC))
  382.     {
  383.       if (ftruncate (output_fd, seek_record * output_blocksize) < 0)
  384.         error (0, errno, "%s", output_file);
  385.     }
  386. #endif
  387.     }
  388.   else
  389.     output_file = "standard output";
  390.  
  391. #ifdef _POSIX_VERSION
  392.   sigaction (SIGINT, NULL, &sigact);
  393.   if (sigact.sa_handler != SIG_IGN)
  394.     {
  395.       sigact.sa_handler = interrupt_handler;
  396.       sigemptyset (&sigact.sa_mask);
  397.       sigact.sa_flags = 0;
  398.       sigaction (SIGINT, &sigact, NULL);
  399.     }
  400.   sigaction (SIGPIPE, NULL, &sigact);
  401.   if (sigact.sa_handler != SIG_IGN)
  402.     {
  403.       sigact.sa_handler = interrupt_handler;
  404.       sigemptyset (&sigact.sa_mask);
  405.       sigact.sa_flags = 0;
  406.       sigaction (SIGPIPE, &sigact, NULL);
  407.     }
  408. #else                /* !_POSIX_VERSION */
  409.   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
  410.     signal (SIGINT, interrupt_handler);
  411.   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
  412.     signal (SIGPIPE, interrupt_handler); 
  413. #endif                /* !_POSIX_VERSION */
  414.   copy ();
  415. }
  416.  
  417. /* Throw away RECORDS blocks of BLOCKSIZE bytes on file descriptor FDESC,
  418.    which is open with read permission for FILE.  Store up to BLOCKSIZE
  419.    bytes of the data at a time in BUF, if necessary. */
  420.  
  421. static void
  422. skip (fdesc, file, records, blocksize, buf)
  423.      int fdesc;
  424.      char *file;
  425.      long records;
  426.      long blocksize;
  427.      char *buf;
  428. {
  429.   struct stat stats;
  430.  
  431.   /* Use fstat instead of checking for errno == ESPIPE because
  432.      lseek doesn't work on some special files but doesn't return an
  433.      error, either. */
  434.   if (fstat (fdesc, &stats))
  435.     {
  436.       error (0, errno, "%s", file);
  437.       quit (1);
  438.     }
  439.  
  440.   if (S_ISREG (stats.st_mode))
  441.     {
  442.       if (lseek (fdesc, records * blocksize, SEEK_SET) < 0)
  443.     {
  444.       error (0, errno, "%s", file);
  445.       quit (1);
  446.     }
  447.     }
  448.   else
  449.     {
  450.       while (records-- > 0)
  451.     {
  452.       if (read (fdesc, buf, blocksize) < 0
  453. #ifdef EINTR
  454.           && errno != EINTR
  455. #endif
  456.           )
  457.         {
  458.           error (0, errno, "%s", file);
  459.           quit (1);
  460.         }
  461.       /* FIXME If fewer bytes were read than requested, meaning that
  462.          EOF was reached, POSIX wants the output file padded with NULs. */
  463.     }
  464.     }
  465. }
  466.  
  467. /* Apply the character-set translations specified by the user
  468.    to the NREAD bytes in BUF.  */
  469.  
  470. static void
  471. translate_buffer (buf, nread)
  472.      unsigned char *buf;
  473.      int nread;
  474. {
  475.   register unsigned char *cp;
  476.   register int i;
  477.  
  478.   for (i = nread, cp = buf; i; i--, cp++)
  479.     *cp = trans_table[*cp];
  480. }
  481.  
  482. /* If nonnzero, the last char from the previous call to `swab_buffer'
  483.    is saved in `saved_char'.  */
  484. static int char_is_saved = 0;
  485.  
  486. /* Odd char from previous call.  */
  487. static unsigned char saved_char;
  488.  
  489. /* Swap NREAD bytes in BUF, plus possibly an initial char from the
  490.    previous call.  If NREAD is odd, save the last char for the
  491.    next call.   Return the new start of the BUF buffer.  */
  492.  
  493. static unsigned char *
  494. swab_buffer (buf, nread)
  495.      unsigned char *buf;
  496.      int *nread;
  497. {
  498.   unsigned char *bufstart = buf;
  499.   register unsigned char *cp;
  500.   register int i;
  501.  
  502.   /* Is a char left from last time?  */
  503.   if (char_is_saved)
  504.     {
  505.       *--bufstart = saved_char;
  506.       (*nread)++;
  507.       char_is_saved = 0;
  508.     }
  509.  
  510.   if (*nread & 1)
  511.     {
  512.       /* An odd number of chars are in the buffer.  */
  513.       saved_char = bufstart[--*nread];
  514.       char_is_saved = 1;
  515.     }
  516.  
  517.   /* Do the byte-swapping by moving every second character two
  518.      positions toward the end, working from the end of the buffer
  519.      toward the beginning.  This way we only move half of the data.  */
  520.  
  521.   cp = bufstart + *nread;    /* Start one char past the last.  */
  522.   for (i = *nread / 2; i; i--, cp -= 2)
  523.     *cp = *(cp - 2);
  524.  
  525.   return ++bufstart;
  526. }
  527.  
  528. /* Output buffer. */
  529. static unsigned char *obuf;
  530.  
  531. /* Current index into `obuf'. */
  532. static int oc = 0;
  533.  
  534. /* Index into current line, for `conv=block' and `conv=unblock'.  */
  535. static int col = 0;
  536.  
  537. /* The main loop.  */
  538.  
  539. static void
  540. copy ()
  541. {
  542.   unsigned char *ibuf, *bufstart; /* Input buffer. */
  543.   int nread;            /* Bytes read in the current block. */
  544.   int exit_status = 0;
  545.  
  546.   /* Leave at least one extra byte at the beginning and end of `ibuf'
  547.      for conv=swab, but keep the buffer address even.  But some peculiar
  548.      device drivers work only with word-aligned buffers, so leave an
  549.      extra two bytes.  */
  550.  
  551.   ibuf = (unsigned char *) xmalloc (input_blocksize + 2 * SWAB_ALIGN_OFFSET);
  552.   ibuf += SWAB_ALIGN_OFFSET;
  553.  
  554.   if (conversions_mask & C_TWOBUFS)
  555.     obuf = (unsigned char *) xmalloc (output_blocksize);
  556.   else
  557.     obuf = ibuf;
  558.  
  559.   if (skip_records > 0)
  560.     skip (input_fd, input_file, skip_records, input_blocksize, ibuf);
  561.  
  562.   if (seek_record > 0)
  563.     skip (output_fd, output_file, seek_record, output_blocksize, obuf);
  564.  
  565.   if (max_records == 0)
  566.     quit (exit_status);
  567.  
  568.   while (1)
  569.     {
  570.       if (max_records >= 0 && r_partial + r_full >= max_records)
  571.     break;
  572.  
  573.       /* Zero the buffer before reading, so that if we get a read error,
  574.      whatever data we are able to read is followed by zeros.
  575.      This minimizes data loss. */
  576.       if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR))
  577.     bzero (ibuf, input_blocksize);
  578.  
  579.       nread = safe_read (input_fd, ibuf, input_blocksize);
  580.  
  581.       if (nread == 0)
  582.     break;            /* EOF.  */
  583.  
  584.       if (nread < 0)
  585.     {
  586.       error (0, errno, "%s", input_file);
  587.       if (conversions_mask & C_NOERROR)
  588.         {
  589.           print_stats ();
  590.           /* Seek past the bad block if possible. */
  591.           lseek (input_fd, input_blocksize, SEEK_CUR);
  592.           if (conversions_mask & C_SYNC)
  593.         /* Replace the missing input with null bytes and
  594.            proceed normally.  */
  595.         nread = 0;
  596.           else
  597.         continue;
  598.         }
  599.       else
  600.         {
  601.           /* Write any partial block. */
  602.           exit_status = 2;
  603.           break;
  604.         }
  605.     }
  606.  
  607.       if (nread < input_blocksize)
  608.     {
  609.       r_partial++;
  610.       if (conversions_mask & C_SYNC)
  611.         {
  612.           if (!(conversions_mask & C_NOERROR))
  613.         /* If C_NOERROR, we zeroed the block before reading. */
  614.         bzero (ibuf + nread, input_blocksize - nread);
  615.           nread = input_blocksize;
  616.         }
  617.     }
  618.       else
  619.     r_full++;
  620.  
  621.       if (ibuf == obuf)        /* If not C_TWOBUFS. */
  622.     {
  623.       int nwritten = write (output_fd, obuf, nread);
  624.       if (nwritten != nread)
  625.         {
  626.           error (0, errno, "%s", output_file);
  627.           if (nwritten > 0)
  628.         w_partial++;
  629.           quit (1);
  630.         }
  631.       else if (nread == input_blocksize)
  632.         w_full++;
  633.       else
  634.         w_partial++;
  635.       continue;
  636.     }
  637.  
  638.       /* Do any translations on the whole buffer at once.  */
  639.  
  640.       if (translation_needed)
  641.     translate_buffer (ibuf, nread);
  642.  
  643.       if (conversions_mask & C_SWAB)
  644.     bufstart = swab_buffer (ibuf, &nread);
  645.       else
  646.     bufstart = ibuf;
  647.  
  648.       if (conversions_mask & C_BLOCK)
  649.         copy_with_block (bufstart, nread);
  650.       else if (conversions_mask & C_UNBLOCK)
  651.     copy_with_unblock (bufstart, nread);
  652.       else
  653.     copy_simple (bufstart, nread);
  654.     }
  655.  
  656.   /* If we have a char left as a result of conv=swab, output it.  */
  657.   if (char_is_saved)
  658.     {
  659.       if (conversions_mask & C_BLOCK)
  660.         copy_with_block (&saved_char, 1);
  661.       else if (conversions_mask & C_UNBLOCK)
  662.     copy_with_unblock (&saved_char, 1);
  663.       else
  664.     output_char (saved_char);
  665.     }
  666.  
  667.   if ((conversions_mask & C_BLOCK) && col > 0)
  668.     {
  669.       /* If the final input line didn't end with a '\n', pad
  670.      the output block to `conversion_blocksize' chars.  */
  671.       int pending_spaces = max (0, conversion_blocksize - col);
  672.       while (pending_spaces)
  673.     {
  674.       output_char (space_character);
  675.       --pending_spaces;
  676.     }
  677.     }
  678.  
  679.   if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize)
  680.     /* Add a final '\n' if there are exactly `conversion_blocksize'
  681.        characters in the final record. */
  682.     output_char (newline_character);
  683.  
  684.   /* Write out the last block. */
  685.   if (oc > 0)
  686.     {
  687.       int nwritten = write (output_fd, obuf, oc);
  688.       if (nwritten > 0)
  689.     w_partial++;
  690.       if (nwritten != oc)
  691.     {
  692.       error (0, errno, "%s", output_file);
  693.       quit (1);
  694.     }
  695.     }
  696.  
  697.   free (ibuf - SWAB_ALIGN_OFFSET);
  698.   if (obuf != ibuf)
  699.     free (obuf);
  700.  
  701.   quit (exit_status);
  702. }
  703.  
  704. /* Copy NREAD bytes of BUF, with no conversions.  */
  705.  
  706. static void
  707. copy_simple (buf, nread)
  708.      unsigned char *buf;
  709.      int nread;
  710. {
  711.   int nfree;            /* Number of unused bytes in `obuf'.  */
  712.   unsigned char *start = buf; /* First uncopied char in BUF.  */
  713.  
  714.   do
  715.     {
  716.       nfree = output_blocksize - oc;
  717.       if (nfree > nread)
  718.     nfree = nread;
  719.  
  720.       bcopy (start, obuf + oc, nfree);
  721.  
  722.       nread -= nfree;        /* Update the number of bytes left to copy. */
  723.       start += nfree;
  724.       oc += nfree;
  725.       if (oc >= output_blocksize)
  726.     write_output ();
  727.     }
  728.   while (nread > 0);
  729. }
  730.  
  731. /* Copy NREAD bytes of BUF, doing conv=block
  732.    (pad newline-terminated records to `conversion_blocksize',
  733.    replacing the newline with trailing spaces).  */
  734.  
  735. static void
  736. copy_with_block (buf, nread)
  737.      unsigned char *buf;
  738.      int nread;
  739. {
  740.   register int i;
  741.  
  742.   for (i = nread; i; i--, buf++)
  743.     {
  744.       if (*buf == newline_character)
  745.     {
  746.       int pending_spaces = max (0, conversion_blocksize - col);
  747.       while (pending_spaces)
  748.         {
  749.           output_char (space_character);
  750.           --pending_spaces;
  751.         }
  752.       col = 0;
  753.     }
  754.       else
  755.     {
  756.       if (col == conversion_blocksize)
  757.         r_truncate++;
  758.       else if (col < conversion_blocksize)
  759.         output_char (*buf);
  760.       col++;
  761.     }
  762.     }
  763. }
  764.  
  765. /* Copy NREAD bytes of BUF, doing conv=unblock
  766.    (replace trailing spaces in `conversion_blocksize'-sized records
  767.    with a newline).  */
  768.  
  769. static void
  770. copy_with_unblock (buf, nread)
  771.      unsigned char *buf;
  772.      int nread;
  773. {
  774.   register int i;
  775.   register unsigned char c;
  776.   static int pending_spaces = 0;
  777.  
  778.   for (i = 0; i < nread; i++)
  779.     {
  780.       c = buf[i];
  781.  
  782.       if (col++ >= conversion_blocksize)
  783.     {
  784.       col = pending_spaces = 0; /* Wipe out any pending spaces.  */
  785.       i--;            /* Push the char back; get it later. */
  786.       output_char (newline_character);
  787.     }
  788.       else if (c == space_character)
  789.     pending_spaces++;
  790.       else
  791.     {
  792.       /* `c' is the character after a run of spaces that were not
  793.          at the end of the conversion buffer.  Output them.  */
  794.       while (pending_spaces)
  795.         {
  796.           output_char (space_character);
  797.           --pending_spaces;
  798.         }
  799.       output_char (c);
  800.     }
  801.     }
  802. }
  803.  
  804. /* Write, then empty, the output buffer `obuf'. */
  805.  
  806. static void
  807. write_output ()
  808. {
  809.   int nwritten = write (output_fd, obuf, output_blocksize);
  810.   if (nwritten != output_blocksize)
  811.     {
  812.       error (0, errno, "%s", output_file);
  813.       if (nwritten > 0)
  814.     w_partial++;
  815.       quit (1);
  816.     }
  817.   else
  818.     w_full++;
  819.   oc = 0;
  820. }
  821.  
  822. static void
  823. scanargs (argc, argv)
  824.      int argc;
  825.      char **argv;
  826. {
  827.   int i, n;
  828.   int c;
  829.  
  830.   while ((c = getopt_long (argc, argv, "", long_options, (int *) 0)) != EOF)
  831.     {
  832.       switch (c)
  833.     {
  834.     case 0:
  835.       break;
  836.  
  837.     default:
  838.       usage (1);
  839.     }
  840.     }
  841.  
  842.   for (i = optind; i < argc; i++)
  843.     {
  844.       char *name, *val;
  845.  
  846.       name = argv[i];
  847.       val = index (name, '=');
  848.       if (val == NULL)
  849.     {
  850.       error (0, 0, "unrecognized option `%s'", name);
  851.       usage (1);
  852.     }
  853.       *val++ = '\0';
  854.  
  855.       if (equal (name, "if"))
  856.     input_file = val;
  857.       else if (equal (name, "of"))
  858.     output_file = val;
  859.       else if (equal (name, "conv"))
  860.     parse_conversion (val);
  861.       else
  862.     {
  863.       n = parse_integer (val);
  864.       if (n < 0)
  865.         error (1, 0, "invalid number `%s'", val);
  866.  
  867.       if (equal (name, "ibs"))
  868.         {
  869.           input_blocksize = n;
  870.           conversions_mask |= C_TWOBUFS;
  871.         }
  872.       else if (equal (name, "obs"))
  873.         {
  874.           output_blocksize = n;
  875.           conversions_mask |= C_TWOBUFS;
  876.         }
  877.       else if (equal (name, "bs"))
  878.         output_blocksize = input_blocksize = n;
  879.       else if (equal (name, "cbs"))
  880.         conversion_blocksize = n;
  881.       else if (equal (name, "skip"))
  882.         skip_records = n;
  883.       else if (equal (name, "seek"))
  884.         seek_record = n;
  885.       else if (equal (name, "count"))
  886.         max_records = n;
  887.       else
  888.         {
  889.           error (0, 0, "unrecognized option `%s=%s'", name, val);
  890.           usage (1);
  891.         }
  892.     }
  893.     }
  894.  
  895.   /* If bs= was given, both `input_blocksize' and `output_blocksize' will
  896.      have been set to non-negative values.  If either has not been set,
  897.      bs= was not given, so make sure two buffers are used. */
  898.   if (input_blocksize == -1 || output_blocksize == -1)
  899.     conversions_mask |= C_TWOBUFS;
  900.   if (input_blocksize == -1)
  901.     input_blocksize = DEFAULT_BLOCKSIZE;
  902.   if (output_blocksize == -1)
  903.     output_blocksize = DEFAULT_BLOCKSIZE;
  904.   if (conversion_blocksize == 0)
  905.     conversions_mask &= ~(C_BLOCK | C_UNBLOCK);
  906. }
  907.  
  908. /* Return the value of STR, interpreted as a non-negative decimal integer,
  909.    optionally multiplied by various values.
  910.    Return -1 if STR does not represent a number in this format. */
  911.  
  912. static int
  913. parse_integer (str)
  914.      char *str;
  915. {
  916.   register int n = 0;
  917.   register int temp;
  918.   register char *p = str;
  919.  
  920.   while (ISDIGIT (*p))
  921.     {
  922.       n = n * 10 + *p - '0';
  923.       p++;
  924.     }
  925. loop:
  926.   switch (*p++)
  927.     {
  928.     case '\0':
  929.       return n;
  930.     case 'b':
  931.       n *= 512;
  932.       goto loop;
  933.     case 'c':
  934.       goto loop;
  935.     case 'k':
  936.       n *= 1024;
  937.       goto loop;
  938.     case 'w':
  939.       n *= 2;
  940.       goto loop;
  941.     case 'x':
  942.       temp = parse_integer (p);
  943.       if (temp == -1)
  944.     return -1;
  945.       n *= temp;
  946.       break;
  947.     default:
  948.       return -1;
  949.     }
  950.   return n;
  951. }
  952.  
  953. /* Interpret one "conv=..." option. */
  954.  
  955. static void
  956. parse_conversion (str)
  957.      char *str;
  958. {
  959.   char *new;
  960.   int i;
  961.  
  962.   do
  963.     {
  964.       new = index (str, ',');
  965.       if (new != NULL)
  966.     *new++ = '\0';
  967.       for (i = 0; conversions[i].convname != NULL; i++)
  968.     if (equal (conversions[i].convname, str))
  969.       {
  970.         conversions_mask |= conversions[i].conversion;
  971.         break;
  972.       }
  973.       if (conversions[i].convname == NULL)
  974.     {
  975.       error (0, 0, "%s: invalid conversion", str);
  976.       usage (1);
  977.     }
  978.       str = new;
  979.   } while (new != NULL);
  980. }
  981.  
  982. /* Fix up translation table. */
  983.  
  984. static void
  985. apply_translations ()
  986. {
  987.   int i;
  988.  
  989. #define MX(a) (bit_count (conversions_mask & (a)))
  990.   if ((MX (C_ASCII | C_EBCDIC | C_IBM) > 1)
  991.       || (MX (C_BLOCK | C_UNBLOCK) > 1)
  992.       || (MX (C_LCASE | C_UCASE) > 1)
  993.       || (MX (C_UNBLOCK | C_SYNC) > 1))
  994.     {
  995.       error (1, 0, "\
  996. only one conv in {ascii,ebcdic,ibm}, {lcase,ucase}, {block,unblock}, {unblock,sync}");
  997.     }
  998. #undef MX
  999.  
  1000.   if (conversions_mask & C_ASCII)
  1001.     translate_charset (ebcdic_to_ascii);
  1002.  
  1003.   if (conversions_mask & C_UCASE)
  1004.     {
  1005.       for (i = 0; i < 256; i++)
  1006.     if (ISLOWER (trans_table[i]))
  1007.       trans_table[i] = toupper (trans_table[i]);
  1008.       translation_needed = 1;
  1009.     }
  1010.   else if (conversions_mask & C_LCASE)
  1011.     {
  1012.       for (i = 0; i < 256; i++)
  1013.     if (ISUPPER (trans_table[i]))
  1014.       trans_table[i] = tolower (trans_table[i]);
  1015.       translation_needed = 1;
  1016.     }
  1017.  
  1018.   if (conversions_mask & C_EBCDIC)
  1019.     {
  1020.       translate_charset (ascii_to_ebcdic);
  1021.       newline_character = ascii_to_ebcdic['\n'];
  1022.       space_character = ascii_to_ebcdic[' '];
  1023.     }
  1024.   else if (conversions_mask & C_IBM)
  1025.     {
  1026.       translate_charset (ascii_to_ibm);
  1027.       newline_character = ascii_to_ibm['\n'];
  1028.       space_character = ascii_to_ibm[' '];
  1029.     }
  1030. }
  1031.  
  1032. static void
  1033. translate_charset (new_trans)
  1034.      unsigned char *new_trans;
  1035. {
  1036.   int i;
  1037.  
  1038.   for (i = 0; i < 256; i++)
  1039.     trans_table[i] = new_trans[trans_table[i]];
  1040.   translation_needed = 1;
  1041. }
  1042.  
  1043. /* Return the number of 1 bits in `i'. */
  1044.  
  1045. static int
  1046. bit_count (i)
  1047.      register unsigned int i;
  1048. {
  1049.   register int set_bits;
  1050.  
  1051.   for (set_bits = 0; i != 0; set_bits++)
  1052.     i &= i - 1;
  1053.   return set_bits;
  1054. }
  1055.  
  1056. static void
  1057. print_stats ()
  1058. {
  1059.   fprintf (stderr, "%u+%u records in\n", r_full, r_partial);
  1060.   fprintf (stderr, "%u+%u records out\n", w_full, w_partial);
  1061.   if (r_truncate > 0)
  1062.     fprintf (stderr, "%u truncated record%s\n", r_truncate,
  1063.          r_truncate == 1 ? "" : "s");
  1064. }
  1065.  
  1066. static void
  1067. quit (code)
  1068.      int code;
  1069. {
  1070.   int errcode = code ? code : 1;
  1071.   print_stats ();
  1072.   if (close (input_fd) < 0)
  1073.     error (errcode, errno, "%s", input_file);
  1074.   if (close (output_fd) < 0)
  1075.     error (errcode, errno, "%s", output_file);
  1076.   exit (code);
  1077. }
  1078.  
  1079. static RETSIGTYPE
  1080. interrupt_handler ()
  1081. {
  1082.   quit (1);
  1083. }
  1084.  
  1085. static void
  1086. usage (status)
  1087.      int status;
  1088. {
  1089.   if (status != 0)
  1090.     fprintf (stderr, "Try `%s --help' for more information.\n",
  1091.          program_name);
  1092.   else
  1093.     {
  1094.       printf ("Usage: %s [OPTION]...\n", program_name);
  1095.       printf ("\
  1096. \n\
  1097.   bs=BYTES        force ibs=BYTES and obs=BYTES\n\
  1098.   cbs=BYTES       convert BYTES bytes at a time\n\
  1099.   conv=KEYWORDS   convert the file as per the comma separated keyword list\n\
  1100.   count=BLOCKS    copy only BLOCKS input blocks\n\
  1101.   ibs=BYTES       read BYTES bytes at a time\n\
  1102.   if=FILE         read from FILE instead of stdin\n\
  1103.   obs=BYTES       write BYTES bytes at a time\n\
  1104.   of=FILE         write to FILE instead of stdout, don't truncate file\n\
  1105.   seek=BLOCKS     skip BLOCKS obs-sized blocks at start of output\n\
  1106.   skip=BLOCKS     skip BLOCKS ibs-sized blocks at start of input\n\
  1107.       --help      display this help and exit\n\
  1108.       --version   output version information and exit\n\
  1109. \n\
  1110. BYTES may be suffixed: by xM for multiplication by M, by c for x1,\n\
  1111. by w for x2, by b for x512, by k for x1024.  Each KEYWORD may be:\n\
  1112. \n\
  1113.   ascii     from EBCDIC to ASCII\n\
  1114.   ebcdic    from ASCII to EBCDIC\n\
  1115.   ibm       from ASCII to alternated EBCDIC\n\
  1116.   block     pad newline-terminated records with spaces to cbs-size \n\
  1117.   unblock   replace trailing spaces in cbs-size records with newline\n\
  1118.   lcase     change upper case to lower case\n\
  1119.   ucase     change lower case to upper case\n\
  1120.   swab      swap every pair of input bytes\n\
  1121.   noerror   continue after read errors\n\
  1122.   sync      pad every input block with NULs to ibs-size\n");
  1123.     }
  1124.   exit (status);
  1125. }
  1126.