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.
14 ** This module has a long and checkered history.
16 ** [ Here had been some history of delimiter problems in MMDF maildrops ... ]
18 ** Unfortunately the speed issue finally caught up with us since this
19 ** routine is at the very heart of MH. To speed things up considerably, the
20 ** routine Eom() was made an auxilary function called by the macro eom().
21 ** Unless we are bursting a maildrop, the eom() macro returns FALSE saying
22 ** we aren't at the end of the message.
24 ** [ ... and here had been some more of it. ]
27 ** ------------------------
28 ** (Written by Van Jacobson for the mh6 m_getfld, January, 1986):
30 ** This routine was accounting for 60% of the cpu time used by most mh
31 ** programs. I spent a bit of time tuning and it now accounts for <10%
32 ** of the time used. Like any heavily tuned routine, it's a bit
33 ** complex and you want to be sure you understand everything that it's
34 ** doing before you start hacking on it. Let me try to emphasize
35 ** that: every line in this atrocity depends on every other line,
36 ** sometimes in subtle ways. You should understand it all, in detail,
37 ** before trying to change any part. If you do change it, test the
38 ** result thoroughly (I use a hand-constructed test file that exercises
39 ** all the ways a header name, header body, header continuation,
40 ** header-body separator, body line and body eom can align themselves
41 ** with respect to a buffer boundary). "Minor" bugs in this routine
42 ** result in garbaged or lost mail.
44 ** If you hack on this and slow it down, I, my children and my
45 ** children's children will curse you.
47 ** This routine gets used on two different types of files: normal,
48 ** single msg files and "packed" unix mailboxs (when used by inc).
49 ** The biggest impact of different file types is in "eom" testing. The
50 ** code has been carefully organized to test for eom at appropriate
51 ** times and at no other times (since the check is quite expensive).
52 ** I have tried to arrange things so that the eom check need only be
53 ** done on entry to this routine. Since an eom can only occur after a
54 ** newline, this is easy to manage for header fields. For the msg
55 ** body, we try to efficiently search the input buffer to see if
56 ** contains the eom delimiter. If it does, we take up to the
57 ** delimiter, otherwise we take everything in the buffer. (The change
58 ** to the body eom/copy processing produced the most noticeable
59 ** performance difference, particularly for "inc" and "show".)
61 ** There are three qualitatively different things this routine busts
62 ** out of a message: field names, field text and msg bodies. Field
63 ** names are typically short (~8 char) and the loop that extracts them
64 ** might terminate on a colon, newline or max width. I considered
65 ** using a Vax "scanc" to locate the end of the field followed by a
66 ** "bcopy" but the routine call overhead on a Vax is too large for this
67 ** to work on short names. If Berkeley ever makes "inline" part of the
68 ** C optimiser (so things like "scanc" turn into inline instructions) a
69 ** change here would be worthwhile.
71 ** Field text is typically 60 - 100 characters so there's (barely)
72 ** a win in doing a routine call to something that does a "locc"
73 ** followed by a "bmove". About 30% of the fields have continuations
74 ** (usually the 822 "received:" lines) and each continuation generates
75 ** another routine call. "Inline" would be a big win here, as well.
77 ** Messages, as of this writing, seem to come in two flavors: small
78 ** (~1K) and long (>2K). Most messages have 400 - 600 bytes of headers
79 ** so message bodies average at least a few hundred characters.
80 ** Assuming your system uses reasonably sized stdio buffers (1K or
81 ** more), this routine should be able to remove the body in large
82 ** (>500 byte) chunks. The makes the cost of a call to "bcopy"
83 ** small but there is a premium on checking for the eom in packed
84 ** maildrops. The eom pattern is always a simple string so we can
85 ** construct an efficient pattern matcher for it (e.g., a Vax "matchc"
86 ** instruction). Some thought went into recognizing the start of
87 ** an eom that has been split across two buffers.
89 ** This routine wants to deal with large chunks of data so, rather
90 ** than "getc" into a local buffer, it uses stdio's buffer. If
91 ** you try to use it on a non-buffered file, you'll get what you
92 ** deserve. This routine "knows" that struct FILEs have a _ptr
93 ** and a _cnt to describe the current state of the buffer and
94 ** it knows that _filbuf ignores the _ptr & _cnt and simply fills
95 ** the buffer. If stdio on your system doesn't work this way, you
96 ** may have to make small changes in this routine.
98 ** This routine also "knows" that an EOF indication on a stream is
99 ** "sticky" (i.e., you will keep getting EOF until you reposition the
100 ** stream). If your system doesn't work this way it is broken and you
101 ** should complain to the vendor. As a consequence of the sticky
102 ** EOF, this routine will never return any kind of EOF status when
103 ** there is data in "name" or "buf").
110 static int m_Eom(int, FILE *);
111 static unsigned char *matchc(int, char *, int, char *);
112 static unsigned char *locc(int, unsigned char *, unsigned char);
114 #define eom(c,iob) (ismbox && \
115 (((c) == *msg_delim && m_Eom(c,iob)) ||\
116 (eom_action && (*eom_action)(c))))
118 static unsigned char **pat_map;
121 ** This is a disgusting hack for "inc" so it can know how many
122 ** characters were stuffed in the buffer on the last call
123 ** (see comments in uip/scansbr.c).
130 ** The "full" delimiter string for a packed maildrop consists
131 ** of a newline followed by the actual delimiter. E.g., the
132 ** full string for a Unix maildrop would be: "\n\nFrom ".
133 ** "Fdelim" points to the start of the full string and is used
134 ** in the BODY case of the main routine to search the buffer for
135 ** a possible eom. Msg_delim points to the first character of
136 ** the actual delim. string (i.e., fdelim+1). Edelim
137 ** points to the 2nd character of actual delimiter string. It
138 ** is used in m_Eom because the first character of the string
139 ** has been read and matched before m_Eom is called.
141 char *msg_delim = "";
143 static unsigned char *fdelim;
144 static unsigned char *delimend;
145 static int fdelimlen;
146 static unsigned char *edelim;
147 static int edelimlen;
149 static int (*eom_action)(int) = NULL;
152 # define _ptr _p /* Gag */
153 # define _cnt _r /* Retch */
154 # define _filbuf __srget /* Puke */
155 # define DEFINED__FILBUF_TO_SOMETHING_SPECIFIC
158 #ifndef DEFINED__FILBUF_TO_SOMETHING_SPECIFIC
159 extern int _filbuf(FILE*);
164 m_getfld(int state, unsigned char *name, unsigned char *buf,
165 int bufsz, FILE *iob)
167 register unsigned char *bp, *cp, *ep, *sp;
168 register int cnt, c, i, j;
170 if ((c = getc(iob)) < 0) {
177 /* flush null messages */
178 while ((c = getc(iob)) >= 0 && eom(c, iob))
192 if (c == '\n' || c == '-') {
193 /* we hit the header/body separator */
194 while (c != '\n' && (c = getc(iob)) >= 0)
197 if (c < 0 || (c = getc(iob)) < 0 || eom(c, iob)) {
199 /* flush null messages */
200 while ((c = getc(iob)) >= 0 && eom(c, iob))
213 ** get the name of this component. take characters up
214 ** to a ':', a newline or NAMESZ-1 characters,
215 ** whichever comes first.
221 bp = sp = (unsigned char *) iob->_IO_read_ptr - 1;
222 j = (cnt = ((long) iob->_IO_read_end -
223 (long) iob->_IO_read_ptr) + 1) < i ? cnt : i;
224 #elif defined(__DragonFly__)
225 bp = sp = (unsigned char *) ((struct __FILE_public *)iob)->_p - 1;
226 j = (cnt = ((struct __FILE_public *)iob)->_r+1) < i ? cnt : i;
228 bp = sp = (unsigned char *) iob->_ptr - 1;
229 j = (cnt = iob->_cnt+1) < i ? cnt : i;
231 while (--j >= 0 && (c = *bp++) != ':' && c != '\n')
235 if ((cnt -= j) <= 0) {
237 iob->_IO_read_ptr = iob->_IO_read_end;
238 if (__underflow(iob) == EOF) {
239 #elif defined(__DragonFly__)
240 if (__srget(iob) == EOF) {
242 if (_filbuf(iob) == EOF) {
245 advise(NULL, "eof encountered in field \"%s\"", name);
249 iob->_IO_read_ptr++; /* NOT automatic in __underflow()! */
253 iob->_IO_read_ptr = bp + 1;
254 #elif defined(__DragonFly__)
255 ((struct __FILE_public *)iob)->_p = bp + 1;
256 ((struct __FILE_public *)iob)->_r = cnt - 1;
266 ** something went wrong. possibilities are:
267 ** . hit a newline (error)
268 ** . got more than namesz chars. (error)
269 ** . hit the end of the buffer. (loop)
273 ** We hit the end of the line without
274 ** seeing ':' to terminate the field name.
275 ** This is usually (always?) spam. But,
276 ** blowing up is lame, especially when
277 ** scan(1)ing a folder with such messages.
278 ** Pretend such lines are the first of
279 ** the body (at least mutt also handles
284 ** See if buf can hold this line, since we
285 ** were assuming we had a buffer of NAMESZ,
288 /* + 1 for the newline */
291 ** No, it can't. Oh well,
292 ** guess we'll blow up.
295 advise(NULL, "eol encountered in field \"%s\"", name);
299 memcpy(buf, name, j - 1);
303 ** mhparse.c:get_content wants to find
304 ** the position of the body start, but
305 ** it thinks there's a blank line between
306 ** the header and the body (naturally!),
307 ** so seek back so that things line up
308 ** even though we don't have that blank
309 ** line in this case. Simpler parsers
310 ** (e.g. mhl) get extra newlines, but
311 ** that should be harmless enough, right?
312 ** This is a corrupt message anyway.
314 fseek(iob, ftell(iob) - 2, SEEK_SET);
319 advise(NULL, "field name \"%s\" exceeds %d bytes", name, NAMESZ - 2);
325 while (isspace(*--cp) && cp >= name)
332 ** get (more of) the text of a field. take
333 ** characters up to the end of this field (newline
334 ** followed by non-blank) or bufsz-1 characters.
336 cp = buf; i = bufsz-1;
339 cnt = (long) iob->_IO_read_end - (long) iob->_IO_read_ptr;
340 bp = (unsigned char *) --iob->_IO_read_ptr;
341 #elif defined(__DragonFly__)
342 cnt = ((struct __FILE_public *)iob)->_r++;
343 bp = (unsigned char *) --((struct __FILE_public *)iob)->_p;
346 bp = (unsigned char *) --iob->_ptr;
348 c = cnt < i ? cnt : i;
349 while ((ep = locc( c, bp, '\n' ))) {
351 ** if we hit the end of this field,
354 if ((j = *++ep) != ' ' && j != '\t') {
356 j = ep - (unsigned char *) iob->_IO_read_ptr;
357 memcpy(cp, iob->_IO_read_ptr, j);
358 iob->_IO_read_ptr = ep;
359 #elif defined(__DragonFly__)
360 j = ep - (unsigned char *) ((struct __FILE_public *)iob)->_p;
361 memcpy(cp, ((struct __FILE_public *)iob)->_p, j);
362 ((struct __FILE_public *)iob)->_p = ep;
363 ((struct __FILE_public *)iob)->_r -= j;
365 j = ep - (unsigned char *) iob->_ptr;
366 memcpy(cp, iob->_ptr, j);
378 ** end of input or dest buffer - copy what
382 c += bp - (unsigned char *) iob->_IO_read_ptr;
383 memcpy(cp, iob->_IO_read_ptr, c);
384 #elif defined(__DragonFly__)
385 c += bp - (unsigned char *) ((struct __FILE_public *)iob)->_p;
386 memcpy(cp, ((struct __FILE_public *)iob)->_p, c);
388 c += bp - (unsigned char *) iob->_ptr;
389 memcpy(cp, iob->_ptr, c);
394 /* the dest buffer is full */
396 iob->_IO_read_ptr += c;
397 #elif defined(__DragonFly__)
398 ((struct __FILE_public *)iob)->_r -= c;
399 ((struct __FILE_public *)iob)->_p += c;
408 ** There's one character left in the input
409 ** buffer. Copy it & fill the buffer.
410 ** If the last char was a newline and the
411 ** next char is not whitespace, this is
412 ** the end of the field. Otherwise loop.
416 *cp++ = j = *(iob->_IO_read_ptr + c);
417 iob->_IO_read_ptr = iob->_IO_read_end;
418 c = __underflow(iob);
419 iob->_IO_read_ptr++; /* NOT automatic! */
420 #elif defined(__DragonFly__)
421 *cp++ =j = *(((struct __FILE_public *)iob)->_p + c);
424 *cp++ = j = *(iob->_ptr + c);
427 if (c == EOF || ((j == '\0' || j == '\n')
428 && c != ' ' && c != '\t')) {
432 #elif defined(__DragonFly__)
433 --((struct __FILE_public *)iob)->_p;
434 ++((struct __FILE_public *)iob)->_r;
449 ** get the message body up to bufsz characters or
450 ** the end of the message. Sleazy hack: if bufsz
451 ** is negative we assume that we were called to
452 ** copy directly into the output buffer and we
455 i = (bufsz < 0) ? -bufsz : bufsz-1;
457 bp = (unsigned char *) --iob->_IO_read_ptr;
458 cnt = (long) iob->_IO_read_end - (long) iob->_IO_read_ptr;
459 #elif defined(__DragonFly__)
460 bp = (unsigned char *) --((struct __FILE_public *)iob)->_p;
461 cnt = ++((struct __FILE_public *)iob)->_r;
463 bp = (unsigned char *) --iob->_ptr;
466 c = (cnt < i ? cnt : i);
467 if (ismbox && c > 1) {
469 ** packed maildrop - only take up to the (possible)
470 ** start of the next message. This "matchc" should
471 ** probably be a Boyer-Moore matcher for non-vaxen,
472 ** particularly since we have the alignment table
473 ** all built for the end-of-buffer test (next).
474 ** But our vax timings indicate that the "matchc"
475 ** instruction is 50% faster than a carefully coded
476 ** B.M. matcher for most strings. (So much for
477 ** elegant algorithms vs. brute force.) Since I
478 ** (currently) run MH on a vax, we use the matchc
481 if ((ep = matchc( fdelimlen, fdelim, c, bp )))
485 ** There's no delim in the buffer but
486 ** there may be a partial one at the end.
487 ** If so, we want to leave it so the "eom"
488 ** check on the next call picks it up. Use a
489 ** modified Boyer-Moore matcher to make this
490 ** check relatively cheap. The first "if"
491 ** figures out what position in the pattern
492 ** matches the last character in the buffer.
493 ** The inner "while" matches the pattern
494 ** against the buffer, backwards starting
495 ** at that position. Note that unless the
496 ** buffer ends with one of the characters
497 ** in the pattern (excluding the first
498 ** and last), we do only one test.
501 if ((sp = pat_map[*ep])) {
504 ** This if() is true unless
505 ** (a) the buffer is too
506 ** small to contain this
508 ** or (b) it contains
509 ** exactly enough chars for
510 ** the delimiter prefix.
511 ** For case (a) obviously we
512 ** aren't going to match.
513 ** For case (b), if the
514 ** buffer really contained
515 ** exactly a delim prefix,
516 ** then the m_eom call
517 ** at entry should have
518 ** found it. Thus it's
519 ** not a delim and we know
520 ** we won't get a match.
522 if (((sp - fdelim) + 2) <= c) {
525 ** Unfortunately although fdelim has a preceding NUL
526 ** we can't use this as a sentinel in case the buffer
527 ** contains a NUL in exactly the wrong place (this
528 ** would cause us to run off the front of fdelim).
530 while (*--ep == *--cp)
534 /* we matched the entire delim prefix,
535 ** so only take the buffer up to there.
536 ** we know ep >= bp -- check above prevents underrun
542 /* try matching one less char of delim string */
544 } while (--sp > fdelim);
548 memcpy( buf, bp, c );
550 iob->_IO_read_ptr += c;
551 #elif defined(__DragonFly__)
552 ((struct __FILE_public *)iob)->_r -= c;
553 ((struct __FILE_public *)iob)->_p += c;
566 adios(NULL, "m_getfld() called with bogus state of %d", state);
570 msg_count = cp - buf;
576 thisisanmbox(FILE *iob)
581 register char *delimstr;
590 ** Figure out what the message delimitter string is for this
591 ** maildrop. (This used to be part of m_Eom but I didn't like
592 ** the idea of an "if" statement that could only succeed on the
593 ** first call to m_Eom getting executed on each call, i.e., at
594 ** every newline in the message).
596 ** If the first line of the maildrop is a Unix "From " line, we
597 ** say the style is MBOX and eat the rest of the line. Otherwise
601 if (fread(text, sizeof(*text), 5, iob) != 5) {
602 adios(NULL, "Read error");
604 if (strncmp(text, "From ", 5)!=0) {
605 adios(NULL, "No Unix style (mbox) maildrop.");
608 delimstr = "\nFrom ";
609 while ((c = getc(iob)) != '\n' && c >= 0) {
612 c = strlen(delimstr);
613 fdelim = (unsigned char *) mh_xmalloc((size_t) (c + 3));
616 msg_delim = (char *)fdelim+1;
617 edelim = (unsigned char *)msg_delim+1;
620 strcpy(msg_delim, delimstr);
621 delimend = (unsigned char *)msg_delim + edelimlen;
623 adios(NULL, "maildrop delimiter must be at least 2 bytes");
625 ** build a Boyer-Moore end-position map for the matcher in m_getfld.
626 ** N.B. - we don't match just the first char (since it's the newline
627 ** separator) or the last char (since the matchc would have found it
628 ** if it was a real delim).
630 pat_map = (unsigned char **) calloc(256, sizeof(unsigned char *));
632 for (cp = (char *) fdelim + 1; cp < (char *) delimend; cp++ )
633 pat_map[(unsigned char)*cp] = (unsigned char *) cp;
638 ** test for msg delimiter string
642 m_Eom(int c, FILE *iob)
644 register long pos = 0L;
649 if ((i = fread(text, sizeof *text, edelimlen, iob)) != edelimlen ||
650 (strncmp(text, (char *)edelim, edelimlen)!=0)) {
651 if (i == 0 && ismbox)
653 ** the final newline in the (brain damaged) unix-format
654 ** maildrop is part of the delimitter - delete it.
658 fseek(iob, (long)(pos-1), SEEK_SET);
659 getc(iob); /* should be OK */
664 while ((c = getc(iob)) != '\n' && c >= 0) {
673 static unsigned char *
674 matchc(int patln, char *pat, int strln, char *str)
676 register char *es = str + strln - patln;
679 register char *ep = pat + patln;
680 register char pc = *pat++;
689 while (pp < ep && *sp++ == *pp)
692 return ((unsigned char *)--str);
698 ** Locate character "term" in the next "cnt" characters of "src".
699 ** If found, return its address, otherwise return 0.
702 static unsigned char *
703 locc(int cnt, unsigned char *src, unsigned char term)
705 while (*src++ != term && --cnt > 0)
708 return (cnt > 0 ? --src : (unsigned char *)0);