2 ** m_getfld.c -- read/parse a message
4 ** This code is Copyright (c) 2002, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
15 ** This module has a long and checkered history.
17 ** [ Here had been some history of delimiter problems in MMDF maildrops ... ]
19 ** Unfortunately the speed issue finally caught up with us since this
20 ** routine is at the very heart of MH. To speed things up considerably, the
21 ** routine Eom() was made an auxilary function called by the macro eom().
22 ** Unless we are bursting a maildrop, the eom() macro returns FALSE saying
23 ** we aren't at the end of the message.
25 ** [ ... and here had been some more of it. ]
28 ** ------------------------
29 ** (Written by Van Jacobson for the mh6 m_getfld, January, 1986):
31 ** This routine was accounting for 60% of the cpu time used by most mh
32 ** programs. I spent a bit of time tuning and it now accounts for <10%
33 ** of the time used. Like any heavily tuned routine, it's a bit
34 ** complex and you want to be sure you understand everything that it's
35 ** doing before you start hacking on it. Let me try to emphasize
36 ** that: every line in this atrocity depends on every other line,
37 ** sometimes in subtle ways. You should understand it all, in detail,
38 ** before trying to change any part. If you do change it, test the
39 ** result thoroughly (I use a hand-constructed test file that exercises
40 ** all the ways a header name, header body, header continuation,
41 ** header-body separator, body line and body eom can align themselves
42 ** with respect to a buffer boundary). "Minor" bugs in this routine
43 ** result in garbaged or lost mail.
45 ** If you hack on this and slow it down, I, my children and my
46 ** children's children will curse you.
48 ** This routine gets used on two different types of files: normal,
49 ** single msg files and "packed" unix mailboxs (when used by inc).
50 ** The biggest impact of different file types is in "eom" testing. The
51 ** code has been carefully organized to test for eom at appropriate
52 ** times and at no other times (since the check is quite expensive).
53 ** I have tried to arrange things so that the eom check need only be
54 ** done on entry to this routine. Since an eom can only occur after a
55 ** newline, this is easy to manage for header fields. For the msg
56 ** body, we try to efficiently search the input buffer to see if
57 ** contains the eom delimiter. If it does, we take up to the
58 ** delimiter, otherwise we take everything in the buffer. (The change
59 ** to the body eom/copy processing produced the most noticeable
60 ** performance difference, particularly for "inc" and "show".)
62 ** There are three qualitatively different things this routine busts
63 ** out of a message: field names, field text and msg bodies. Field
64 ** names are typically short (~8 char) and the loop that extracts them
65 ** might terminate on a colon, newline or max width. I considered
66 ** using a Vax "scanc" to locate the end of the field followed by a
67 ** "bcopy" but the routine call overhead on a Vax is too large for this
68 ** to work on short names. If Berkeley ever makes "inline" part of the
69 ** C optimiser (so things like "scanc" turn into inline instructions) a
70 ** change here would be worthwhile.
72 ** Field text is typically 60 - 100 characters so there's (barely)
73 ** a win in doing a routine call to something that does a "locc"
74 ** followed by a "bmove". About 30% of the fields have continuations
75 ** (usually the 822 "received:" lines) and each continuation generates
76 ** another routine call. "Inline" would be a big win here, as well.
78 ** Messages, as of this writing, seem to come in two flavors: small
79 ** (~1K) and long (>2K). Most messages have 400 - 600 bytes of headers
80 ** so message bodies average at least a few hundred characters.
81 ** Assuming your system uses reasonably sized stdio buffers (1K or
82 ** more), this routine should be able to remove the body in large
83 ** (>500 byte) chunks. The makes the cost of a call to "bcopy"
84 ** small but there is a premium on checking for the eom in packed
85 ** maildrops. The eom pattern is always a simple string so we can
86 ** construct an efficient pattern matcher for it (e.g., a Vax "matchc"
87 ** instruction). Some thought went into recognizing the start of
88 ** an eom that has been split across two buffers.
90 ** This routine wants to deal with large chunks of data so, rather
91 ** than "getc" into a local buffer, it uses stdio's buffer. If
92 ** you try to use it on a non-buffered file, you'll get what you
93 ** deserve. This routine "knows" that struct FILEs have a _ptr
94 ** and a _cnt to describe the current state of the buffer and
95 ** it knows that _filbuf ignores the _ptr & _cnt and simply fills
96 ** the buffer. If stdio on your system doesn't work this way, you
97 ** may have to make small changes in this routine.
99 ** This routine also "knows" that an EOF indication on a stream is
100 ** "sticky" (i.e., you will keep getting EOF until you reposition the
101 ** stream). If your system doesn't work this way it is broken and you
102 ** should complain to the vendor. As a consequence of the sticky
103 ** EOF, this routine will never return any kind of EOF status when
104 ** there is data in "name" or "buf").
111 static int m_Eom(int, FILE *);
112 static unsigned char *matchc(int, char *, int, char *);
113 static unsigned char *locc(int, unsigned char *, unsigned char);
115 #define eom(c,iob) (ismbox && \
116 (((c) == *msg_delim && m_Eom(c,iob)) ||\
117 (eom_action && (*eom_action)(c))))
119 static unsigned char **pat_map;
122 ** This is a disgusting hack for "inc" so it can know how many
123 ** characters were stuffed in the buffer on the last call
124 ** (see comments in uip/scansbr.c).
131 ** The "full" delimiter string for a packed maildrop consists
132 ** of a newline followed by the actual delimiter. E.g., the
133 ** full string for a Unix maildrop would be: "\n\nFrom ".
134 ** "Fdelim" points to the start of the full string and is used
135 ** in the BODY case of the main routine to search the buffer for
136 ** a possible eom. Msg_delim points to the first character of
137 ** the actual delim. string (i.e., fdelim+1). Edelim
138 ** points to the 2nd character of actual delimiter string. It
139 ** is used in m_Eom because the first character of the string
140 ** has been read and matched before m_Eom is called.
142 static char *msg_delim = "";
144 static unsigned char *fdelim;
145 static unsigned char *delimend;
146 static int fdelimlen;
147 static unsigned char *edelim;
148 static int edelimlen;
150 static int (*eom_action)(int) = NULL;
153 ** This replaces the old approach, which included direct access to
154 ** stdio internals. It uses one fread() to load a buffer that we
157 #define MSG_INPUT_SIZE 8192
158 static struct m_getfld_buffer {
159 unsigned char msg_buf[2 * MSG_INPUT_SIZE];
160 unsigned char *readpos;
161 unsigned char *end; /* One past the last character read in. */
165 setup_buffer(FILE *iob, struct m_getfld_buffer *m)
168 ** Rely on Restrictions that m_getfld() calls on different file
169 ** streams are not interleaved, and no other file stream read
170 ** methods are used. And, the first call to m_getfld (), etc., on
171 ** a stream always reads at least 1 byte.
172 ** I don't think it's necessary to use ftello() because we just
173 ** need to determine whether the current offset is 0 or not.
175 if (ftell(iob) == 0) {
176 /* A new file stream, so reset the buffer state. */
177 m->readpos = m->end = m->msg_buf;
182 read_more(struct m_getfld_buffer *m, FILE *iob)
186 /* Move any leftover at the end of buf to the beginning. */
187 if (m->end > m->readpos) {
188 memmove(m->msg_buf, m->readpos, m->end - m->readpos);
190 m->readpos = m->msg_buf + (m->end - m->readpos);
191 num_read = fread(m->readpos, 1, MSG_INPUT_SIZE, iob);
192 m->end = m->readpos + num_read;
200 if (m.end - m.readpos < 1) {
201 if (read_more(&m, iob) == 0) {
203 ** Pretend that we read a character.
204 ** That's what stdio does.
210 return (m.readpos < m.end) ? *m.readpos++ : EOF;
214 Ungetc(int c, FILE *iob)
216 return (m.readpos == m.msg_buf) ? EOF : (*--m.readpos = c);
222 m_getfld(int state, unsigned char *name, unsigned char *buf,
223 int bufsz, FILE *iob)
225 unsigned char *bp, *cp, *ep, *sp;
228 setup_buffer(iob, &m);
230 if ((c = Getc(iob)) < 0) {
237 /* flush null messages */
238 while ((c = Getc(iob)) >= 0 && eom(c, iob))
252 if (c == '\n' || c == '-') {
253 /* we hit the header/body separator */
254 while (c != '\n' && (c = Getc(iob)) >= 0)
257 if (c < 0 || (c = Getc(iob)) < 0 || eom(c, iob)) {
259 /* flush null messages */
260 while ((c = Getc(iob)) >= 0 && eom(c, iob))
273 ** get the name of this component. take characters up
274 ** to a ':', a newline or NAMESZ-1 characters,
275 ** whichever comes first.
280 /* Store current pos, ungetting the last char. */
281 bp = sp = (unsigned char *) m.readpos - 1;
282 j = ((cnt = m.end - m.readpos + 1) < i) ? cnt : i;
284 while (--j >= 0 && (c = *bp++) != ':' && c != '\n')
288 if ((cnt -= j) <= 0) {
290 ** Used to explicitly force refill of the
291 ** buffer here, but Getc() will do that
294 if (Getc (iob) == EOF) {
296 advise(NULL, "eof encountered in field \"%s\"", name);
300 /* Restore the current offset. */
307 ** something went wrong. possibilities are:
308 ** . hit a newline (error)
309 ** . got more than namesz chars. (error)
310 ** . hit the end of the buffer. (loop)
314 ** We hit the end of the line without
315 ** seeing ':' to terminate the field name.
316 ** This is usually (always?) spam. But,
317 ** blowing up is lame, especially when
318 ** scan(1)ing a folder with such messages.
319 ** Pretend such lines are the first of
320 ** the body (at least mutt also handles
325 ** See if buf can hold this line, since we
326 ** were assuming we had a buffer of NAMESZ,
329 /* + 1 for the newline */
332 ** No, it can't. Oh well,
333 ** guess we'll blow up.
336 advise(NULL, "eol encountered in field \"%s\"", name);
340 memcpy(buf, name, j - 1);
344 ** mhparse.c:get_content wants to find
345 ** the position of the body start, but
346 ** it thinks there's a blank line between
347 ** the header and the body (naturally!),
348 ** so seek back so that things line up
349 ** even though we don't have that blank
350 ** line in this case. Simpler parsers
351 ** (e.g. mhl) get extra newlines, but
352 ** that should be harmless enough, right?
353 ** This is a corrupt message anyway.
355 /* emulates: fseek(iob, ftell(iob) -(-2 + cnt + 1), SEEK_SET) */
356 m.readpos += cnt - 1;
358 ** Reset file stream position so caller,
359 ** e.g., get_content, can use ftell(), etc.
361 fseek(iob, -cnt - 1, SEEK_CUR);
366 advise(NULL, "field name \"%s\" exceeds %d bytes", name, NAMESZ - 2);
372 while (isspace(*--cp) && cp >= name)
379 ** get (more of) the text of a field. take
380 ** characters up to the end of this field (newline
381 ** followed by non-blank) or bufsz-1 characters.
383 cp = buf; i = bufsz-1;
385 /* Set and save the current pos and update cnt. */
386 cnt = m.end - m.readpos;
388 c = cnt < i ? cnt : i;
389 while ((ep = locc( c, bp, '\n' ))) {
391 ** if we hit the end of this field,
394 if ((j = *++ep) != ' ' && j != '\t') {
396 ** Save the text and update the
400 memcpy (cp, m.readpos, j);
410 ** end of input or dest buffer - copy what
414 for (k = 0; k < c; ++k, --i) {
418 /* the dest buffer is full */
423 ** There's one character left in the input
424 ** buffer. Copy it & fill the buffer (that
425 ** fill used to be explicit, but now Getc()
426 ** does it). If the last char was a newline
427 ** and the next char is not whitespace, this
428 ** is the end of the field. Otherwise loop.
431 *cp++ = j = Getc(iob);
433 if (c == EOF || ((j == '\0' || j == '\n')
434 && c != ' ' && c != '\t')) {
437 ** Put the character back for
451 ** get the message body up to bufsz characters or
452 ** the end of the message. Sleazy hack: if bufsz
453 ** is negative we assume that we were called to
454 ** copy directly into the output buffer and we
457 i = (bufsz < 0) ? -bufsz : bufsz-1;
458 /* Back up and store the current position and update cnt. */
460 cnt = m.end - m.readpos;
461 c = (cnt < i) ? cnt : i;
462 if (ismbox && c > 1) {
464 ** packed maildrop - only take up to the (possible)
465 ** start of the next message. This "matchc" should
466 ** probably be a Boyer-Moore matcher for non-vaxen,
467 ** particularly since we have the alignment table
468 ** all built for the end-of-buffer test (next).
469 ** But our vax timings indicate that the "matchc"
470 ** instruction is 50% faster than a carefully coded
471 ** B.M. matcher for most strings. (So much for
472 ** elegant algorithms vs. brute force.) Since I
473 ** (currently) run MH on a vax, we use the matchc
476 if ((ep = matchc( fdelimlen, fdelim, c, bp )))
480 ** There's no delim in the buffer but
481 ** there may be a partial one at the end.
482 ** If so, we want to leave it so the "eom"
483 ** check on the next call picks it up. Use a
484 ** modified Boyer-Moore matcher to make this
485 ** check relatively cheap. The first "if"
486 ** figures out what position in the pattern
487 ** matches the last character in the buffer.
488 ** The inner "while" matches the pattern
489 ** against the buffer, backwards starting
490 ** at that position. Note that unless the
491 ** buffer ends with one of the characters
492 ** in the pattern (excluding the first
493 ** and last), we do only one test.
496 if ((sp = pat_map[*ep])) {
499 ** This if() is true unless
500 ** (a) the buffer is too
501 ** small to contain this
503 ** or (b) it contains
504 ** exactly enough chars for
505 ** the delimiter prefix.
506 ** For case (a) obviously we
507 ** aren't going to match.
508 ** For case (b), if the
509 ** buffer really contained
510 ** exactly a delim prefix,
511 ** then the m_eom call
512 ** at entry should have
513 ** found it. Thus it's
514 ** not a delim and we know
515 ** we won't get a match.
517 if (((sp - fdelim) + 2) <= c) {
520 ** Unfortunately although fdelim has a preceding NUL
521 ** we can't use this as a sentinel in case the buffer
522 ** contains a NUL in exactly the wrong place (this
523 ** would cause us to run off the front of fdelim).
525 while (*--ep == *--cp)
529 /* we matched the entire delim prefix,
530 ** so only take the buffer up to there.
531 ** we know ep >= bp -- check above prevents underrun
537 /* try matching one less char of delim string */
539 } while (--sp > fdelim);
543 memcpy( buf, bp, c );
544 /* Advance the current position to reflect the copy out. */
554 adios(EX_SOFTWARE, NULL, "m_getfld() called with bogus state of %d", state);
558 msg_count = cp - buf;
564 thisisanmbox(FILE *iob)
571 setup_buffer(iob, &m);
580 ** Figure out what the message delimitter string is for this
581 ** maildrop. (This used to be part of m_Eom but I didn't like
582 ** the idea of an "if" statement that could only succeed on the
583 ** first call to m_Eom getting executed on each call, i.e., at
584 ** every newline in the message).
586 ** If the first line of the maildrop is a Unix "From " line, we
587 ** say the style is MBOX and eat the rest of the line. Otherwise
590 for (c=0, cp=text; c<5; ++c, ++cp) {
591 if ((*cp = Getc(iob)) == EOF) {
596 adios(EX_IOERR, NULL, "Read error");
598 if (strncmp(text, "From ", 5)!=0) {
599 adios(EX_USAGE, NULL, "No Unix style (mbox) maildrop.");
602 delimstr = "\nFrom ";
603 while ((c = Getc(iob)) != '\n' && c >= 0) {
606 c = strlen(delimstr);
607 fdelim = (unsigned char *) mh_xmalloc((size_t) (c + 3));
610 msg_delim = (char *)fdelim+1;
611 edelim = (unsigned char *)msg_delim+1;
614 strcpy(msg_delim, delimstr);
615 delimend = (unsigned char *)msg_delim + edelimlen;
616 if (edelimlen <= 1) {
617 adios(EX_DATAERR, NULL, "maildrop delimiter must be at least 2 bytes");
620 ** build a Boyer-Moore end-position map for the matcher in m_getfld.
621 ** N.B. - we don't match just the first char (since it's the newline
622 ** separator) or the last char (since the matchc would have found it
623 ** if it was a real delim).
625 pat_map = (unsigned char **) calloc(256, sizeof(unsigned char *));
627 for (cp = (char *) fdelim + 1; cp < (char *) delimend; cp++) {
628 pat_map[(unsigned char)*cp] = (unsigned char *) cp;
634 ** test for msg delimiter string
638 m_Eom(int c, FILE *iob)
645 pos = m.readpos; /* ftell */
646 for (i=0, cp=text; i<edelimlen; ++i, ++cp) {
647 if ((*cp = Getc(iob)) == EOF) {
651 if (i != edelimlen ||
652 (strncmp(text, (char *)edelim, edelimlen)!=0)) {
653 if (i == 0 && ismbox) {
655 ** the final newline in the (brain damaged) unix-format
656 ** maildrop is part of the delimitter - delete it.
660 m.readpos = pos - 1; /* fseek(iob, pos - 1, SEEK_SET) */
661 Getc(iob); /* should be OK */
666 while ((c = Getc(iob)) != '\n' && c >= 0) {
675 static unsigned char *
676 matchc(int patln, char *pat, int strln, char *str)
678 char *es = str + strln - patln;
681 char *ep = pat + patln;
691 while (pp < ep && *sp++ == *pp)
694 return ((unsigned char *)--str);
700 ** Locate character "term" in the next "cnt" characters of "src".
701 ** If found, return its address, otherwise return 0.
704 static unsigned char *
705 locc(int cnt, unsigned char *src, unsigned char term)
707 while (*src++ != term && --cnt > 0)
710 return (cnt > 0 ? --src : (unsigned char *)0);