Article View: news.software.readers
Article #11851TIN: Uudecoding multiple files (source)
From: Michael Bergman
Date: Tue, 11 Oct 1994 14:58
Date: Tue, 11 Oct 1994 14:58
1394 lines
44626 bytes
44626 bytes
Pete Jones (pmj@tardis.jyu.fi) wrote:
> It would be nice if it searched for a 'begin' and 'end' through the entire
>catted list and plopped each file out at a time, like as shar file does.
>It's just a pain to tag each set of files seperately and uudecode each set
>of files together.
> Does anyone know how to do this convenient thing ? I'm sure I installed it
>OK. I'm using tin 1.2 PL2 [UNIX] (Solaris 2.3), and reading via a NNTP
>server.
Yes, use the program I've included in this post.
Tag all the articles and pipe them through uuexplode. It will extract
all the files for you to any directory you wich directly from the
NNTP server. No intermediate storage of huge uucode files.
As been said, there are many programs that can do this job (uud, uushred,
unpost...) but this one is the fastest and most secure.
Enjoy,
M
--
Michael Bergman Email: euambn@eua.ericsson.se
EUA/XO Phone: +46 8 7275709
Ellemtel Telecom Systems Labs, Armborstv 14, S-125 25 Alvsjo, Sweden
--
"Of a' their foreign tricks n' pliskies, I maist abominate their whiskies"
- Robert Louis Stevenson
----- cut here ----- cut here ----- cut here ----- cut here ----- cut here
I have now completed version 1.6 of uuexplode, bug fixes and some
small changes to printouts. It's now a bit faster, but not much.
uuexplode is YASMU (Yet Another Smart Multipart Uudecoder).
So, you say, do we really need another one of these? Yes, that's why
I wrote it. It behaves much like unpost in sorted mode, if you're
familiar with that utility.
Anyway, this compiles with any K & R compiler or GCC or any other
you might prefer.
It is written for BSD-ish UNIX but is easy to port since only 4 system
specific calls are used: chmod, mkdir, stat, unlink.
I also use some library functions, see the source code at the end of
the large initial comment.
Basically it assumes that there are an arbitary number of uuencoded
files in its input stream, uudecodes all the lines that really are
uucode and writes the appropriate output (target) files.
Naturally all parts of a file must be there and they must be *in order*.
Ideally you should tag articles in order (using a newsreader that can do
that, e.g. tin) and then pipe everything through uuexplode and that's it.
I CANNOT PORT THIS TO MS-DOS OR ANY OTHER NON-BSD UNIX SYSTEM.
YOU'LL HAVE TO DO THAT YOURSELF. IT IS NOT DIFFICULT AND HAS BEEN
DONE BEFORE.
Please use as much as you can and report any problems to me! If you find
something uuexplode can't decode correctly no matter what options you try,
*but* uudecode can after you've removed garbage by hand, mail it to me!
Features (in no specific order):
1. Fast (~ 600000 lines/min on a Sun SPARC 2 from disk to disk).
This uuexplode was compiled with gcc -O3.
2. Small (well, fairly small anyway :-)
3. Quite verbose, warns when it suspects it may have produced corrupt
output. Warning/errors always give accurate line numbers.
4. Takes multiple input files or stdin (you can pipe through it).
5. Quiet option stops *all* errors/warnings.
6. Overwrite option. By default already existing target files will
not be overwritten but give an error.
7. Can write a target file to stdout for further piping. All warnings
and errors are printed on stderr so there is no need to use -q with -s.
8. Target directory option. Writes target files in specified directory
instead of in ./ The directory will be created if it doesn't exist.
9. Return codes for use from scripts. A bitmask is used:
1=at least 1 warning was issued
2=an error occurred, possibly causing a target file not to be created
4=a target file already existed (only if -w was not given)
10. Handles garbage between all the last 3 lines of a uucode block
11. Handles bogus space/` lines between parts (and at the end) of the
same block. This would otherwise cause truncation of the target
file since this line normally marks the end of a uucode block.
12. Handles bogus short data lines in the middle of a uucode block
13. Does not assume *anything* about headers or other garbage
14. Handles short or even empty uucode blocks correctly
15. Tolerates optional checksum/"guard" character(s) at the end of data
lines that would be transparent to a "dumb" uudecode.
16. Can decode files encoded with character range ASCII [>..}]. This type
of uucode is transparent to a "dumb" uudecode. Use -f -c to do this.
17. Tolerates SPACE or ` as zero-code. The empty-line can be SPACE,
` or `` which are those that normally occur.
18. Option to accept non standard length of short data lines
Sophisticated strategies are used to ensure lowest possible probability
if erroneous output. It is optimal in the sense that it does not produce
corrupt output wihtout issuing at least one warning (unless of course the
error in the input is theoretically undedectable without violating
item 13 above).
All in all this program is about as "intelligent" as it can be without
assuming anything at all about the format of the garbage in the input.
The strategies used are fully documented in the source code for anyone
who is interested :-)
---- cut here ---- cut here ---- cut here ---- cut here ---- cut here ----
.TH UUEXPLODE 1L "14 January 1994"
.IX uuexplode
.SH NAME
uuexplode - decode multiple and/or multipart uuencoded files to their
target files
.SH SYNOPSIS
\fBuuexplode\fR [-hqslcfw] [-t dirname] [filename, filename...]
.SH DESCRIPTION
\fBuuexplode\fR is a "smart", fast uudecoder that will decode one or
more files consisting of complete uuencoded files. The target files can be
written in any user specified directory. It is upward compatible with
uudecode(1) provided that the encoder program used to create the input
to \fBuuexplode\fR has more or less followed the format described in
uuencode(5). See Technical Notes below.
.PP
If no filename(s) is supplied, input is read from stdin. It can also write to
stdout and hence act as a proper filter. Target files are normally written
in current directory.
.PP
\fBuuexplode \fR automatically ignores lines that do not appear to be part of
the uuencoded file. This is particularly useful in uudecoding files that have
been concatenated from several email or news articles \fIwithout\fR stripping
off the headers or otherwise editing extraneous content. A lot of effort was
put into ensuring that erroneous target files are not written, several error
and warning messages are written to stdout when \fBuuexplode\fR finds
something in the input it doesn't accept or just finds strange. The messages
are meant to be self explanatory and contain line numbers in the input file.
Note that when warnings are issued, the output is still most likely correct.
.SH OPTIONS
.TP 8
\fB-h\fR
Print usage message on stdout.
.TP
\fB-q\fR
Quiet. Do not print any diagnostics, errors or warning messages, no matter
what goes wrong.
.TP
\fB-s\fR
Write data to stdout instead of to the target file. Only the very first
target file found in the input will be decoded, then \fBuuexplode\fR exits.
By the "first file" is meant the first one actually containing any decodable
uucode at all. This file may not be in the first input file if there are more
than one. All warning/error messages go to stderr so there is no need to use
-q with -s.
.TP
\fB-l\fR
Lenient mode. This allows for the short data line, the one not beginning with
an "M" at the end of a uucode block, to have a non-standard length.
Use this as a second attempt if a target file seems to come out corrupted
even if no warnings were printed during decoding. Note: -l causes the security
of uucode recognition to drop quite considerably, do not use casually.
.TP
\fB-c\fR
Careless mode. This stops the checks for illegal characters in the short
data line. Its main use is in conjunction with -f when it allows decoding
of uucode in the character range [>..}] that some non-standard encoders
produce. This kind of code is transparent to a "dumb" uudecode program.
Never use this option unless you know you have non-standard uucode.
.TP
\fB-f\fR
Fast mode. This stops the checks for illegal characters in the normal uucode
data lines. It makes the decoding go faster, but not significantly (in fact
probably not even noticably). Normally this would only be used with -c
if you know you have uucode with the non-standard character range. The
sequrity of uucode recognition with -f -c is \fImuch\fR lower than normal.
.TP
\fB-w\fR
Overwrite. Without this, \fBuuexplode\fR will refuse to overwrite a target
file that already exists.
.TP
\fB-t dirname\fR
Target directory. The named directory does not have to exist, it will be
created. Should this fail, \fBuuexplode\fR exits and no target files will be
written.
.SH TECHNICAL NOTES
This is for advanced users who know the uucode format well and want to
know more about what \fBuuexplode\fR accepts as valid uucode.
A number of constraints are put on it:
.TP 3
1
The first line after the 'begin'-line is a uucode line. All characters must
be valid, it must begin with [SPC..M,'] and the length is not totally
absurd with respect to what the first char was. If this is not fulfilled,
\fBuuexplode\fR gives up on that target file.
.TP 3
2
There is at least a \\n behind each uucode line. There may be a \\r also.
.TP 3
3
If there are extra chars at the end of the data lines it is present in
all lines, even the last `-line. And always the same number of chars.
.TP 3
4
There are no extra chars behind the 'end'-line in addition to \\n or \\r\\n
.TP 3
5
The normal uucode lines are always 45 bytes (60 chars) and have 'M'
as length indicator. A "standard" uudecode program does not care about
this at all.
.TP 3
6
No valid uucode contains ASCII > 'a'. Note that one can also use
the range [>..}] since bit 6 of the chars are unused. Again a "standard"
uudecode program will happily decode such data, uuexplode will only do
this with -f -c. There are uuencoders (e.g. on the Macintosh) that produce
such uucode.
.TP 3
7
The end of a uucode block resides in the same input file (or stdin)
as the corresponding 'begin'-line.
.TP 3
8
All parts belonging to the same target file(s) are in correct order in the
input.
.TP 3
9
A uucode line contains no characters with ASCII code < 32.
.PP
A small list of capabilities concerning garbage lines:
.br
No assumptions whatsoever are made about the format of a garbage line.
.br
Tolerates optional checksum/"guard" character(s) at the end of data lines.
.br
Tolerates SPACE or ` as zero-code. The empty-line can be SPACE, ` or ``.
.br
Handles garbage between all the last three lines of a uucode block.
.br
Handles bogus SPACE/` lines between parts (and at the end) of the same block.
.br
Handles bogus short data lines in the middle of a uucode block.
.br
Handles short or even empty uucode blocks correctly.
.SH RETURNS
If all decoding went well, the returncode is 0. Otherwise it is the
logical OR of the following values:
.br
1 \ \ At least one warning was issued
.br
2 \ \ At least one error occurred, possibly causing a target file not to be
created
.br
4 \ \ A target file already existed (only if -w was not active)
.SH BUGS
Some of the warnings and errors are not quite as self explanatory as one would
wish. A user that does not know the uucode format and does not want to know,
may not be able to understand why the file he tried to decode failed.
.PP
The options -c and -l require at least rudimentary knowledge of the uucode
format to be really useful.
.PP
There is no proper standard (except some very new ISO/IEEE paper from
92/93) formally specifying the format of uucode or what a uudecode
algorithm shall accept as valid input. This program tries to be
lenient enough to accept all the common variants while still being as
pedantic as possible.
There are variants of uuencoders out there producing (at least capable of
producing) uucode that uuexplode does not accept. A present no such
\fIcommonly\fR used uuencoders are known to me.
.PP
The algorithms used to recognise valid uucode are not based on proper
statistical analysis of uuencoded data with garbage lines in it. Instead,
some fairly rigid theoretical analysis, partly based on what kind of garbage
normally occur in Email and News postings (but not limited to those) was done.
It \fImay\fR not work as well with totally random garbage interleaved with the
uucode.
.PP
Parts of the uucode recognition algorithm probably cost too much in lower
speed since the cases they test for are very unlikely to occur.
.SH SEE ALSO
uuencode(5), uuencode(1), uudecode(1)
.SH AUTHOR
Michael Bergman (euambn@eua.ericsson.se)
Uuexplode was originally based on a program called "kiss", written by
Kevin Young. This program was part of a collection of uucode tools called
\fBuuxfer\fR. The actual decoding function that decodes one line of
uucode is also written by Kevin and altough almost all the other code has
been almost completely rewritten this remains unaltered.
----- cut here ----- cut here ----- cut here ----- cut here ----- cut here
/*
* File: uuexplode.c (for UNIX)
*
* Description: Smart, fast multiple file uudecoder. Takes any number of
* input files with any number of uucoded files (optionally split
* in parts in correct order) and decodes them creating the
* target files as they appear in the input. Any garbage between
* uucode lines are ignored (e.g. news article/mail headers and
* footers). Sophisticated methods are used to detect garbage
* lines and warnings/errors are printed when faults or potential
* faults are seen.
*
*
* Released to the Public Domain, no warranty whatsoever implied.
*
* Rev: 1.6
* Date: 1994-01-07
*
* Author:
* Michael Bergman
* mail: euambn@eua.ericsson.se
*
* Revisions:
* 1.0
* Created. Used code from a program called kiss 1.0, author
* Kevin Young. Used the decoding function that decoded one line of
* uucode as is.
* 1.1 & 1.2
* Bug fixes. Implemented handling of very short uuencoded files.
* Now quite verbose as opposed to e.g. uuconvert. More warnings/error
* messages. Handles garbage between the `/SPC line and the end line and
* warns if it suspects there is garbage between the last short data line
* and the empty-line.
* 1.3
* Better format of warning messages, e.g. line numbers provided.
* Bogus space lines in data and at end of a uucode block is handled.
* See details below in ExplodeFile() if you're interested in exactly how
* this is done. Released to USENET.
* 1.4
* Secure option is now implemented. It does not noticably slow down
* the decoding :-)
* 1.5
* Changed string and I/O buffer size. 128 char string buffers
* is not enough for long path names in news headers. This made
* the line numbers in warning messages be wrong.
* 1.6
* Changed comments (this text). Included version number in usage.
* Code cleanup and reformatting, improved checks for valid uucode.
* Improved line number accuracy in warnings at end of uucode block.
* Corrected bug in handling missing short-line at premature EOF.
* Wrote the function display_msg. No need to flush the printstream
* since stderr is always unbuffered - removed all fflush().
* Changed -s option to -f and reversed default behaviour.
* New options: -s -w -t -l -c
* With -f -c can now also handle uucode in range [>..}].
* New return codes for use from scripts. Now using getopt(3) to scan
* options. New man page in troff format.
*
*
* TECHNICAL NOTES
* If there is garbage between the short data line (if any) and the
* empty-line, the target file *might* be corrupted, but with the default
* strict checks on the short-lines and empty-lines this is so
* unlikely that no warning is issued. If -l or -c is active, the strict
* checking on the short-lines is disabled so garbage warning is then issued.
*
* The format of the uucode is assumed to be more or less as described
* in uuencode(5) in the online UNIX manual with some exceptions:
* An M-line can be longer than necessary. Some coders put an extra
* checksum (character) after each line, this is ignored by uuexplode.
* It is assumed though that all lines have the same number of extra
* chars after them.
* The last data line before end-line can be either SPC, ` or ``
* since SPC is equivalent to ` when decoding (both give 0).
*
* Any char in the range [a-~] is normally illegal uucode to this program
* until someone has shown that there are COMMONLY used uuencode
* programs that produce correct uucode with small letters in it.
* There are such uuencode, e.g. for the Macintosh(?), which use the
* the range [>-}] by adding 96 to [0-29] and 32 to [30-63].
* Note that this code is transparent to the standard uudecode.
* From version 1.6 this kind of code can be decoded with -f -c.
*
* The end line of a uucode-block must be in the same input file as the
* corresponding begin and that the parts must be in correct order (of course).
*
* Some diagnostics mean that the current output file is removed.
* Others leave the output file, but check the input to be sure!
*
* To speed up the file handling, the file I/O buffers are re-set.
* I chose 32 KB because it is 8 whole pages in a Solaris 1.x system.
* The file I/O is by default buffered. If it is not in your system,
* change to setvbuf() instead. This is also the appropriate action
* to take if you don't have setbuffer().
* Other system specific calls used: stat, unlink, mkdir.
*
* To compile: "cc -O -o uuexplode uuexplode-1.x.c".
*
*/
#include <stdio.h>
#include <ctype.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <varargs.h>
#include <errno.h>
/*
* Some garbage lines such as paths in news headers are very long,
* almost 200 chars. LEN is the max length of a line in the input.
*/
#define LEN 256
#define BUFFER_SIZE 32768
#define VERSION "1.6"
#define D(x) x
/*
* Many variables are declared globally, in order to
* speed up function calls.
*/
extern int errno;
static char input_buf[LEN],
b[LEN] = " "; /* Empty marker. If b is decoded when it is empty,
nothing will happen since length is 0 */
static char out_buf[LEN], dest[LEN], dummy[LEN];
static char *ibuf = input_buf, *bp = b, *obuf = out_buf;
/* Pointers to file buffers */
static char *filebuf1 = NULL, *filebuf2 = NULL;
static int line, len, mlen;
static int retcode = 0;
static char *targetdir = NULL;
static int verbose = 1, fast = 0, clobber = 0;
static int filter = 0, lenient=0, careless = 0;
static int i;
static int max_len = LEN;
static FILE *ofp;
/*
* Forward declarations.
*/
void ExplodeFile();
void ExplodeLine();
int ExplodeLineCheck();
/*
* This function returns 1 if the string s only has
* chars which are valid in uuencoded data, 0 otherwise.
* It is assumed that there are no ASCII < 32.
* *Only* chars that actually contain encoded data is checked,
* no pad-chars (if any).
*/
int uuchk(s)
char *s;
{
int i, top;
i = *s-32;
top = i/3*4 + (i%3 ? i%3+1:0) + 1;
for (i=1; i<top; i++) /* Check only those chars that are data */
{
if (*s++ >= 'a') return 0; /* This string is normally not valid */
}
return 1;
}
/*
* This function prints messages to stderr but only if the verbose flag
* is true. To port this function to DOS or whatever, you must know how to
* handle variable arguments in your OS.
*/
int display_msg(va_alist)
va_dcl
{
va_list ap;
char* format;
char line[100]; /* To store the printstring */
if (verbose)
{
va_start(ap);
format = va_arg(ap, char*);
vsprintf(line, format, ap);
va_end(ap);
return fprintf(stderr, "%s", line);
}
return 0;
}
/*
* The main program. Scan options, test for directories, open files.
* I use the system calls to read file statistics (stat) and to create a new
* directory, so to port to your system you must know how to do that.
*/
void main(argc, argv)
int argc;
char *argv[];
{
FILE *ifp;
int c;
struct stat stat_buf;
extern char *optarg;
extern int optind;
/*
* Get the options and their arguments using getopt(3).
* -hqswfcl have no argument, -t has one.
* After all options and their arguments have been processed,
* argv[optind] is assumed to be the name of the first file
* containing uucode.
*/
c = 0;
while ((c = getopt(argc, argv, "hqswflct:")) != -1)
{
switch (c)
{
case 't':
if (*optarg == '-')
{
printf("uuexplode: inappropriate argument for option -- t\n");
return;
}
targetdir = optarg; /* optarg -> argument to -t */
break;
case 'c':
careless = 1;
break;
case 'l':
lenient = 1;
break;
case 'f':
fast = 1; /* Indicates fast = non-secure */
break;
case 'w':
clobber = 1; /* Overwrite existing target files */
break;
case 's':
filter = 1; /* Act as filter, write to stdout */
break;
case 'q': /* Quiet, print no warnings or errors */
verbose = 0;
break;
case 'h':
printf("Usage: uuexplode [-hqslcfw] [-t dirname] [file1, file2...]\n");
printf("-q quiet\n-h usage\n");
printf("-s write target data to stdout\n-t target directory\n");
printf("-w overwrite existing target files\n");
printf("-f fast, disable check on data lines for illegal chars\n");
printf("-l lenient, accept non-standard length of short-line\n");
printf("-c careless, disable character checks on short-line\n");
printf("When you get warnings check the input.\n");
printf("With -f -c you can decode uucode in [>..}] range, but with much lower\nlevel of security.\n");
printf("Use -l as 2nd attempt if a target file seems to get corrupted.\n");
printf("Version: %s\n", VERSION);
return;
case '?':
return;
}
}
argv = &argv[optind-1];
argc -= optind-1;
D(fprintf(stderr, "verbose=%d, fast=%d, clobber=%d\n", verbose, fast, clobber));
D(fprintf(stderr, "filter=%d, lenient=%d, careless=%d\n", filter, lenient, careless));
D(fprintf(stderr, "argc=%d, *argv=%s\n", argc, *argv));
/*
* Check the target directory if -t was given.
* Stat it and if it doesn't exist, try to create.
*/
if (targetdir != NULL)
{
len = strlen(targetdir);
if (targetdir[len-1] == '/') targetdir[len-1] = 0;
if (stat(targetdir, &stat_buf) == -1)
{
if (errno == ENOENT) /* File does not exist */
{
if (mkdir(targetdir, 0777) == -1)
{
if (verbose) perror(targetdir);
exit(2);
}
}
else
{
if (verbose) perror(targetdir);
exit(2);
}
}
else if (! S_ISDIR(stat_buf.st_mode)) /* It is not a directory */
{
display_msg("%s: not a directory\n", targetdir);
exit(2);
}
D(fprintf(stderr, "targetdir=%s\n", targetdir));
}
if (argc < 2)
{
line = 0; /* Not that one has much use of linenumbers in stdin... */
ExplodeFile(stdin, "stdin");
}
else
{
if ((filebuf1 = malloc(BUFFER_SIZE)) == NULL
|| (filebuf2 = malloc(BUFFER_SIZE)) == NULL)
{
display_msg("uuexplode: buffer allocation failed\n");
}
for (; --argc && ++argv; )
{
if ((ifp = fopen(*argv,"r")) == NULL)
{
if (verbose) perror(*argv);
continue;
}
if (filebuf1 != NULL)
{
setbuffer(ifp, filebuf1, BUFFER_SIZE);
}
line = 0; /* Reset line number */
ExplodeFile(ifp, *argv); /* Uudecodes the data in this input file */
/*
* Uncomment the next line to save some disk space.
* It simply deletes the input file
*/
/* unlink(*argv); */
fclose(ifp);
}
}
exit(retcode);
}
/*
* This function scans the input file until all parts are decoded.
* If the filter flag is set however, only the very first uuencoded file in
* the input will be decoded and then the function will exit.
* By "the very first file" is meant the first file that contains any
* decodable data at all. This file may not be in the first input file
* if there are several.
*/
void ExplodeFile(ifp, fname)
FILE *ifp;
char *fname;
{
char *bufptr, *tmp;
int bquote, garbage, shortdata;
int bquoteline, garbageline, shortdataline;
int mode, end, hasdata, newdata, truncation = 0;
int dlen, t;
hasdata = mlen = 0;
/*
* On EOF, fgets returns NULL, not its first argument
*/
while (fgets(ibuf, max_len, ifp) != NULL)
{
for (;;)
{
line++;
if (! strncmp(ibuf, "begin ", 6)
&& isdigit(ibuf[6])
&& isdigit(ibuf[7])
&& isdigit(ibuf[8]))
{
break; /* Found a potentially valid begin line */
}
if (fgets(ibuf, max_len, ifp) == NULL) /* EOF was reached */
{
if (! hasdata)
{
display_msg("%s: no begin line\n", fname);
}
return;
}
}
/*
* Extract filename and file mode
*/
if ((sscanf(ibuf, "begin %o%[ ]%s", &mode, dummy, dummy)) != 3)
{
len = strlen(ibuf);
while (ibuf[len] == '\n' || ibuf[len] == '\r') ibuf[len--] = 0;
display_msg("%s: %s: invalid mode or filename\n", fname, ibuf);
retcode |= 2;
continue; /* Search for next begin line */
}
hasdata = 1; /* Found a valid begin line */
display_msg("Extracting <%s>\t", dummy);
/*
* By default stderr is unbuffered so there is no longer any
* need to flush the stream. (display_msg always prints to stderr.)
*/
/* fflush(stdout); */
if (filter)
{
ofp = stdout;
}
else
{
/*
* Prepare the output file. Try to open it, if it exists abort
* unless the clobber flag set.
*/
if (targetdir != NULL)
{
strcat(strcat(strcpy(dest, targetdir), "/"), dummy);
}
else
{
strcpy(dest, dummy);
}
if ((ofp = fopen(dest, "r")) != NULL)
{
fclose(ofp);
if (! clobber)
{
display_msg("-- file exists\n");
retcode |= 4;
continue;
}
}
if ((ofp = fopen(dest, "w")) == NULL)
{
if (verbose) perror(dest);
retcode |= 2;
continue;
}
if (chmod(dest, mode) == -1) /* Set file mode */
{
if (verbose) perror(dest);
}
if (filebuf2 != NULL)
{
setbuffer(ofp, filebuf2, BUFFER_SIZE);
}
}
/*
* The line after the begin is assumed to be a valid data line.
* If it is an M-line, the length is saved unless it is < 62, which
* is considered a fatal error (the line must have 60 chars plus the
* M plus at least a linefeed).
* If it begins with [!-L], it is decoded as the short-line,
* if the next line is not an empty-line, a warning is issued.
* If it is, the outputfile is simply closed.
* (The code below was added to handle very small uuencoded files.)
*/
if (fgets(ibuf, max_len, ifp) == NULL) /* EOF encountered */
{
display_msg("\nEOF after begin\n");
retcode |= 2;
if (! filter)
{
fclose(ofp);
unlink(dest); /* Remove the output file and... */
}
return; /* ..proceed with next input file */
}
line++;
len = strlen(ibuf);
if (*ibuf == 'M')
{
if ((mlen = len) < 62)
{
display_msg("\ninvalid first data line %d\n", line);
retcode |= 2;
if (! filter)
{
fclose(ofp);
unlink(dest);
}
continue; /* Search for next begin line */
}
if (mlen > 64)
{
display_msg("\nwarning: very long data lines ");
retcode |= 1;
}
if (fast)
{
ExplodeLine(ibuf);
}
else if (! ExplodeLineCheck(ibuf))
{
display_msg("\nillegal chars in first data line %d\n", line);
retcode |= 2;
if (! filter)
{
fclose(ofp);
unlink(dest);
}
continue; /* Search for next begin line */
}
}
else if (*ibuf <= 'L' && *ibuf > ' ') /* No length check here! */
{
if (fast)
{
ExplodeLine(ibuf);
}
else if (! ExplodeLineCheck(ibuf))
{
display_msg("\nillegal chars in first data line %d\n", line);
retcode |= 2;
if (! filter) fclose(ofp);
continue; /* Search for next begin line */
}
/*
* Now read in line after short data line
*/
if (fgets(ibuf, max_len, ifp) == NULL)
{
display_msg("\nEOF after data line\n");
retcode |= 2;
if (! filter)
{
fclose(ofp);
return; /* Proceed with next input file */
}
else
{
exit(retcode); /* One file has been decoded to stdout */
}
}
len = strlen(ibuf);
/*
* The next line depends on lazy evaluation
*/
if (len > 5 || *ibuf != ' ' && *ibuf != '`')
{
display_msg("\nwarning: garbage at end %d\n", line+1);
retcode |= 1;
/*
* Back up, it may have been a new begin line.
* If writing to stdout just exit.
*/
if (! filter)
{
fseek(ifp, (long)-strlen(ibuf), 1);
fclose(ofp);
}
else
{
exit(retcode);
}
}
else
{
line++;
display_msg("-- done\n");
if (! filter)
{
fclose(ofp);
}
else
{
exit(retcode);
}
}
continue; /* Search for next begin line */
}
else if ((*ibuf == ' ' || *ibuf == '`') && len <= 5)
/* uuencoded empty file */
{
display_msg("-- done\n");
if (! filter) fclose(ofp);
continue; /* Search for next begin line */
}
else
{
display_msg("\ngarbage at first line %d\n", line);
retcode |= 2;
if (! filter)
{
fclose(ofp);
unlink(dest);
}
continue; /* Search for next begin line */
}
/*
* When a [!-L] line is found, a length and char check is made to
* validate it as the short data line. If the next valid uucode line is:
* 1. empty-line - the saved line is decoded and target is finished
* 2. short-line - this replaces the previous one and a warning
* about ambiguous data is later issued..
* 3. M-line - the short-line is assumed bogus and ignored,
* issue warning if lenient or careless is true.
* 4. other - error/warning is printed and the saved line is
* decoded (most likely correctly).
*
* When an empty-line is found, one of two things are done:
* 1. If a short line has been seen, this empty-line is assumed valid
* and I never bother about the end line.
* 2. If not, look for the end-line. If next valid uucode line is
* end-line - finish output file, no warnings
* M-line - empty-line was bogus, continue & issue warning.
* empty-line - continue & issue warning
* EOF or begin - finish output file with "end line not found"
* short data line - empty-line was bogus, continue & issue warning
*
* The reason for 2. is that P(no short data line) ~= 2% (see below)
* and P(bogus short line) is very small. So if a valid short-line
* is seen after an empty-line, it is more likely that it is valid
* and the empty-line was bogus (as long as not -c and -l).
* A problem here is how to know if the file has ` or SPC as its
* empty-line. It is one or the other and if it is SPC, I can
* always just ignore spurious '-lines and vice versa. I decided not
* to distinguish between them. This is a bit vaulnerable, but saves
* overhead.
*
* The above empty-line checking is new in v 1.3 and was added to handle
* cases like this (which do occur sometimes):
* M-lines
* [garbage]
* bogus empty-line
* [garbage]
* M-lines (belonging to the same file)
*
* As a bonus, it now also handles (I've never seen this happen):
* M-lines
* [garbage]
* bogus empty-line
* [garbage]
* short-line
* empty-line
*
* Even this is correctly decoded:
* M-line
* bogus empty-line
* [garbage]
* bogus short-line
* [garbage]
* M-line (belonging to the same file)
* The chance that this would happen is rather small.
*
* There is still only *one* pathological case where this algorithm
* would issue no warning at all and still produce corrupted output:
* M-lines
* bogus short-line (exactly one, falling through the checks)
* empty-line
* [garbage]
* M-lines (belonging to the same file)
* This case is obviously theoretically undetectable, so then there's
* no point in looking for the end-line.
*
* X = original filesize % 45
* Assumption: X is uniform(0..44) (seems reasonable)
* P(no short-line) = P(X=0) = 1/45 ~= 2%
* Even if no short line is found in a block, no warning about this
* is printed. This was changed because in this case I always look for
* the end line. If it is found, the output is very likely correct.
* If not, a warning "no end line" is given, so the previuos warning
* is now obsolete.
*
* If there is a garbage line beginning with M, of correct length
* and all characters valid the output will be corrupted.
* Option -f turns of the character check which looks for chars
* that cannot normally belong to a valid M-line.
* This check is done in ExplodeLineCheck() writing to an array
* instead of directly to the file. If all goes well, the array is
* written to the file.
* This approach costs less if the M-line is valid (which is probable)
* than checking the line first and then decoding it.
*/
/*
* Reset the buffer for short data lines to empty
* Reset a couple of indicators
*/
*bp = ' ';
garbage = shortdata = truncation = 0;
bquote = bquoteline = 0;
garbageline = shortdataline = 0;
end = 0;
while ((bufptr = fgets(ibuf, max_len, ifp)) != NULL)
{
if ((newdata = ! strncmp(ibuf, "begin ", 6)
&& isdigit(ibuf[6])
&& isdigit(ibuf[7])
&& isdigit(ibuf[8])) ) /* No SPC line in this block, or
no end line */
{
/*
* Return the begin line to input stream
*/
fseek(ifp, (long)-strlen(ibuf), 1);
ExplodeLine(bp);
break; /* Get out of inner while loop */
}
line++;
len = strlen(ibuf);
if (*ibuf <= 'L' && *ibuf > ' ') /* It may be a short data line */
{
dlen = *ibuf-32; /* No of encoded bytes */
if (lenient) t = dlen/3*4 + (dlen%3 ? dlen%3+1:0);
else t = (dlen/3 + (dlen%3 ? 1:0))*4;
/*
* Check the length of the short-line.
* I still allow for extra chars, but if lenient is true
* (-l option) I allow even more extra chars or *less* chars
* than reuqired to obey the multiple-by-4 rule. Some non-
* standard uuencoders may put more chars here than on the other
* lines - or they won't pad to a multiple of 4 at all!
*/
if (len == t+(mlen-60) ||
lenient && len > t+(mlen-60) && len < mlen)
/*
* This line depends on lazy evaluation. If the careless
* flag is true, the uuchk is never done.
*/
if (careless || uuchk(ibuf))
{
tmp = bp; /* Keep this line in b[] */
bp = ibuf;
ibuf = tmp;
if (bquote) /* There is a bogus SPC line above */
{
display_msg("\nwarning: bogus empty-line %d ", bquoteline);
retcode |= 1;
bquote = bquoteline = 0;
/*
* I must also reset the truncation flag in
* case a "truncated" message has been displayed.
*/
truncation = 0;
}
shortdata++; /* No of seen valid short-lines between */
/* last M-line and first empty-line */
shortdataline = line;
continue; /* Get next input line */
}
/*
* If this code is reached, it must be a garbage line.
* Have I already seen a potentially valid short-line?
*/
if (*bp != ' ')
{
garbage++;
garbageline = line; /* Save the line number */
}
}
/*
* I allow for the empty-line to be `` even if the M-lines
* do not contain any extra char at the end.
*/
else if (
(*ibuf == ' ' || *ibuf == '`' ) && len == 0+(mlen-60)
||
*ibuf == '`' && *(ibuf+1) == '`' && (len == 0+(mlen-60)+1)
)
{
bquote = 1; /* Mark that an empty-line has been seen */
if (bquoteline) /* There was a previous empty-line */
{
display_msg("\nwarning: bogus empty-line %d ", bquoteline);
retcode |= 1;
truncation = 0;
}
bquoteline = line; /* Save the line number */
if (shortdata) /* At least one short line has been seen */
{
/*
* Have I seen garbage line(s) between the latest short-line
* and this empty-line? If I'm sloppy about checking
* the short-lines print a warning, otherwise keep silent.
*/
if (garbage && (lenient || careless))
{
display_msg("\nwarning: garbage at end %d ", garbageline);
retcode |= 1;
}
if (shortdata > 1)
{
display_msg("\nambiguous data at end %d ", shortdataline);
retcode |= 2;
}
ExplodeLine(bp);
break; /* Exit inner while, ignore the end line */
}
}
else if (! shortdata &&
bquote &&
len < 6 &&
((end = !strncmp(ibuf, "end\n", 4)) ||
(end = !strncmp(ibuf, "end\r", 4))))
{
/* Mark that the end line has been seen, end = 1 */
break; /* Finished, get out of inner while loop */
}
else if (*ibuf == 'M') /* This is probably a valid data line */
{
if (len != mlen)
{
if (uuchk(ibuf)) /* All chars are valid */
{
if (! truncation)
{
display_msg("\nwarning: truncated data line %d ", line);
retcode |= 1;
/* fflush(stdout); */
truncation = 1;
}
else
{
display_msg("%d ", line);
/* fflush(stdout); */
}
}
}
else
{
mode = 1; /* Used temporary as a flag */
if (fast)
{
ExplodeLine(ibuf);
}
else
{
mode = ExplodeLineCheck(ibuf);
D(if (! mode) fprintf(stderr, "\nIllegal char %d", line));
}
if (mode)
{
if (shortdata && (lenient || careless))
{
display_msg("\nwarning: possible bogus data %d ", shortdataline);
retcode |=1;
}
/* Reset the garbage and shortdata indicators */
garbage = shortdata = 0;
if (bquote) /* There is a bogus SPC line above */
{
display_msg("\nwarning: bogus empty-line %d ", bquoteline);
retcode |= 1;
bquoteline = bquote = 0;
/*
* I must also reset the truncation flag in case
* the "truncated" message has been displayed. It
* would otherwise be "broken off" by this message.
*/
truncation = 0;
}
}
}
}
} /*while*/
if (bufptr == NULL) /* EOF encountered before empty-line */
{
if (shortdata > 1)
{
display_msg("\nambiguous data at end");
retcode |= 2;
}
ExplodeLine(bp); /* If b[] is empty, nothing happens */
}
if (! shortdata && ! end && bquote)
{
display_msg("\nwarning: no end line ");
retcode |= 1;
}
if (! bquote)
{
display_msg("\nend of uucode not found\n");
retcode |= 2;
}
else
{
display_msg("-- done\n");
}
if (! filter)
{
fclose(ofp);
}
else
{
exit(retcode); /* One target file has been decoded to stdout */
}
} /*while*/
}
/*
* This function decodes one line of information, written by Kevin Yang.
* The code is slightly different from that of uuconvert.c
* or uudecode.c. I use pointers instead of array indices
* to avoid time consuming address multiplications. The
* condition tests are modified and eliminates 2 tests
* for every 4 bytes. Characters are decoded only when
* one of the three conditions matches, in which complicated
* mathematical computation are eliminated for the last few
* bytes.
* I hope this can speed up the decoding!
*/
#define DECODE(C) (((C) - ' ') & 077)
static int x, y, z;
static char *p;
void ExplodeLine(str)
char *str;
{
i = DECODE(*str); /* Always 0 for a line beginning with SPC or ` */
p = ++str;
while (i > 0)
{
if (i >= 3)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
y = (DECODE(*p) << 4); p++;
y |= (DECODE(*p) >> 2);
z = (DECODE(*p) << 6); p++;
z |= (DECODE(*p));
putc(x, ofp);
putc(y, ofp);
putc(z, ofp);
}
else if (i >= 2)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
y = (DECODE(*p) << 4); p++;
y |= (DECODE(*p) >> 2);
putc(x, ofp);
putc(y, ofp);
}
else if (i >= 1)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
putc(x, ofp);
}
str += 4;
p = str;
i -= 3;
} /*while*/
}
/*
* This array is used to hold decoded data. The entire buffer is
* written to the output file when the line is decoded.
* It is assumed that a full data line is 45 bytes.
*/
unsigned char data[50];
/*
* Returns:
* 1 -- OK, wrote to file
* 0 -- this is no data line, illegal chars found
*/
int ExplodeLineCheck(str)
char *str;
{
unsigned char *d;
i = DECODE(*str); /* Always 0 for a line beginning with SPC or ` */
p = ++str;
d = data;
while (i > 0)
{
if (i >= 3)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
y = (DECODE(*p) << 4); p++;
y |= (DECODE(*p) >> 2);
z = (DECODE(*p) << 6); p++;
z |= (DECODE(*p));
*d++ = x; *d++ = y; *d++ = z;
/*
* Check if these chars were valid uucode
*/
if (*p >= 'a' || *(p-1) >= 'a' || *(p-2) >= 'a' || *(p-3) >= 'a')
{
return 0;
}
}
else if (i >= 2)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
y = (DECODE(*p) << 4); p++;
y |= (DECODE(*p) >> 2);
*d++ = x; *d++ = y;
/*
* Check if these chars were valid uucode
*/
if (*p >= 'a' || *(p-1) >= 'a' || *(p-2) >= 'a')
{
return 0;
}
}
else if (i >= 1)
{
x = (DECODE(*p) << 2); p++;
x |= (DECODE(*p) >> 4);
*d++ = x;
if (*p >= 'a' || *(p-1) >= 'a')
{
return 0;
}
}
str += 4;
p = str;
i -= 3;
} /*while*/
*d = 0; /* End the string */
fwrite(data, 1, d-data, ofp);
return 1;
}
Technical Details
Message-ID:
<37e95p$prn@euas20.eua.ericsson.se>Path:
mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!archive.pugleaf.net!archive.newsdeef.eu!archive!mbox2nntp-news.software.readers.mbox.zip!bga.com!news.sprintlink.net!hookup!swrinde!pipex!sunic!erinews.ericsson.se!eua.ericsson.se!euambnReferences:
<Cx9p37.7vB@liverpool.ac.uk>Show Full Headers
Complete Article Headers
Message-ID: <37e95p$prn@euas20.eua.ericsson.se> Subject: TIN: Uudecoding multiple files (source) Date: Tue, 11 Oct 1994 14:58:01 +0000 From: euambn@eua.ericsson.se (Michael Bergman) References: <Cx9p37.7vB@liverpool.ac.uk> Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!illumos!news.pugleaf.net!.TX!archive.pugleaf.net!archive.newsdeef.eu!archive!mbox2nntp-news.software.readers.mbox.zip!bga.com!news.sprintlink.net!hookup!swrinde!pipex!sunic!erinews.ericsson.se!eua.ericsson.se!euambn Newsgroups: news.software.readers Organization: Ellemtel Telecom Systems Labs, Stockholm, Sweden Lines: 1394 NNTP-Posting-Host: euas45c12.eua.ericsson.se X-Newsreader: TIN [version 1.2 PL2]