]> diplodocus.org Git - nmh/blob - sbr/m_getfld.c
f674792e448539d80c27e8b6db5ff6d13dd7227b
[nmh] / sbr / m_getfld.c
1 /* m_getfld.c -- read/parse a message
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <h/mh.h>
9 #include <h/mts.h>
10 #include <h/utils.h>
11 #include <inttypes.h>
12
13 /*
14 Purpose
15 =======
16 Reads an Internet message (RFC 5322), or one or more messages
17 stored in a maildrop in mbox (RFC 4155) or MMDF format, from a file
18 stream. Each call to m_getfld() reads one header field, or a
19 portion of the body, in sequence.
20
21 Inputs
22 ======
23 gstate: opaque parse state
24 bufsz: maximum number of characters to load into buf
25 iob: input file stream
26
27 Outputs
28 =======
29 name: header field name (array of size NAMESZ=999)
30 buf: either a header field body or message body
31 bufsz: number of characters loaded into buf
32 (return value): message parse state on return from function
33
34 Functions
35 =========
36 void m_getfld_state_destroy (m_getfld_state_t *gstate): destroys
37 the parse state pointed to by the gstate argument.
38
39 m_getfld_state_reset (m_getfld_state_t *gstate): resets the parse
40 state to FLD.
41
42 void m_unknown(FILE *iob): Determines the message delimiter string
43 for the maildrop. Called by inc and scan when reading from a
44 maildrop file.
45
46 State variables
47 ===============
48 m_getfld() retains state internally between calls in the
49 m_getfld_state_t variable. These are used for detecting the end of
50 each message when reading maildrops:
51
52 char **pat_map
53 char *fdelim
54 char *delimend
55 int fdelimlen
56 char *edelim
57 int edelimlen
58 char *msg_delim
59 int msg_style
60
61 Usage
62 =====
63 m_getfld_state_t gstate = 0;
64 ...
65 int state = m_getfld (&gstate, ...);
66 ...
67 m_getfld_state_destroy (&gstate);
68
69 The state is retained internally by gstate. To reset its state to FLD:
70 m_getfld_state_reset (&gstate);
71 */
72
73 /* The following described the old implementation. The high-level
74 structure hasn't changed, but some of the details have. I'm
75 leaving this as-is, though, for posterity.
76 */
77
78 /* This module has a long and checkered history. First, it didn't burst
79 maildrops correctly because it considered two CTRL-A:s in a row to be
80 an inter-message delimiter. It really is four CTRL-A:s followed by a
81 newline. Unfortunately, MMDF will convert this delimiter *inside* a
82 message to a CTRL-B followed by three CTRL-A:s and a newline. This
83 caused the old version of m_getfld() to declare eom prematurely. The
84 fix was a lot slower than
85
86 c == '\001' && peekc (iob) == '\001'
87
88 but it worked, and to increase generality, MBOX style maildrops could
89 be parsed as well. Unfortunately the speed issue finally caught up with
90 us since this routine is at the very heart of MH.
91
92 To speed things up considerably, the routine Eom() was made an auxiliary
93 function called by the macro eom(). Unless we are bursting a maildrop,
94 the eom() macro returns FALSE saying we aren't at the end of the
95 message.
96
97 The next thing to do is to read the mts.conf file and initialize
98 delimiter[] and delimlen accordingly...
99
100 After mhl was made a built-in in msh, m_getfld() worked just fine
101 (using m_unknown() at startup). Until one day: a message which was
102 the result of a bursting was shown. Then, since the burst boundaries
103 aren't CTRL-A:s, m_getfld() would blinding plunge on past the boundary.
104 Very sad. The solution: introduce m_eomsbr(). This hook gets called
105 after the end of each line (since testing for eom involves an fseek()).
106 This worked fine, until one day: a message with no body portion arrived.
107 Then the
108
109 while (eom (c = Getc (iob), iob))
110 continue;
111
112 loop caused m_getfld() to return FMTERR. So, that logic was changed to
113 check for (*eom_action) and act accordingly.
114
115 This worked fine, until one day: someone didn't use four CTRL:A's as
116 their delimiters. So, the bullet got bit and we read mts.h and
117 continue to struggle on. It's not that bad though, since the only time
118 the code gets executed is when inc (or msh) calls it, and both of these
119 have already called mts_init().
120
121 ------------------------
122 (Written by Van Jacobson for the mh6 m_getfld, January, 1986):
123
124 This routine was accounting for 60% of the cpu time used by most mh
125 programs. I spent a bit of time tuning and it now accounts for <10%
126 of the time used. Like any heavily tuned routine, it's a bit
127 complex and you want to be sure you understand everything that it's
128 doing before you start hacking on it. Let me try to emphasize
129 that: every line in this atrocity depends on every other line,
130 sometimes in subtle ways. You should understand it all, in detail,
131 before trying to change any part. If you do change it, test the
132 result thoroughly (I use a hand-constructed test file that exercises
133 all the ways a header name, header body, header continuation,
134 header-body separator, body line and body eom can align themselves
135 with respect to a buffer boundary). "Minor" bugs in this routine
136 result in garbaged or lost mail.
137
138 If you hack on this and slow it down, I, my children and my
139 children's children will curse you.
140
141 This routine gets used on three different types of files: normal,
142 single msg files, "packed" unix or mmdf mailboxs (when used by inc)
143 and packed, directoried bulletin board files (when used by msh).
144 The biggest impact of different file types is in "eom" testing. The
145 code has been carefully organized to test for eom at appropriate
146 times and at no other times (since the check is quite expensive).
147 I have tried to arrange things so that the eom check need only be
148 done on entry to this routine. Since an eom can only occur after a
149 newline, this is easy to manage for header fields. For the msg
150 body, we try to efficiently search the input buffer to see if
151 contains the eom delimiter. If it does, we take up to the
152 delimiter, otherwise we take everything in the buffer. (The change
153 to the body eom/copy processing produced the most noticeable
154 performance difference, particularly for "inc" and "show".)
155
156 There are three qualitatively different things this routine busts
157 out of a message: field names, field text and msg bodies. Field
158 names are typically short (~8 char) and the loop that extracts them
159 might terminate on a colon, newline or max width. I considered
160 using a Vax "scanc" to locate the end of the field followed by a
161 "memmove" but the routine call overhead on a Vax is too large for this
162 to work on short names. If Berkeley ever makes "inline" part of the
163 C optimiser (so things like "scanc" turn into inline instructions) a
164 change here would be worthwhile.
165
166 Field text is typically 60 - 100 characters so there's (barely)
167 a win in doing a routine call to something that does a "locc"
168 followed by a "bmove". About 30% of the fields have continuations
169 (usually the 822 "received:" lines) and each continuation generates
170 another routine call. "Inline" would be a big win here, as well.
171
172 Messages, as of this writing, seem to come in two flavors: small
173 (~1K) and long (>2K). Most messages have 400 - 600 bytes of headers
174 so message bodies average at least a few hundred characters.
175 Assuming your system uses reasonably sized stdio buffers (1K or
176 more), this routine should be able to remove the body in large
177 (>500 byte) chunks. The makes the cost of a call to "memmove"
178 small but there is a premium on checking for the eom in packed
179 maildrops. The eom pattern is always a simple string so we can
180 construct an efficient pattern matcher for it (e.g., a Vax "matchc"
181 instruction). Some thought went into recognizing the start of
182 an eom that has been split across two buffers.
183
184 This routine wants to deal with large chunks of data so, rather
185 than "getc" into a local buffer, it uses stdio's buffer. If
186 you try to use it on a non-buffered file, you'll get what you
187 deserve. This routine "knows" that struct FILEs have a _ptr
188 and a _cnt to describe the current state of the buffer and
189 it knows that _filbuf ignores the _ptr & _cnt and simply fills
190 the buffer. If stdio on your system doesn't work this way, you
191 may have to make small changes in this routine.
192
193 This routine also "knows" that an EOF indication on a stream is
194 "sticky" (i.e., you will keep getting EOF until you reposition the
195 stream). If your system doesn't work this way it is broken and you
196 should complain to the vendor. As a consequence of the sticky
197 EOF, this routine will never return any kind of EOF status when
198 there is data in "name" or "buf").
199 */
200
201 /*
202 * static prototypes
203 */
204 static void Ungetc(m_getfld_state_t s);
205 static int m_Eom (m_getfld_state_t);
206
207 #define eom(c,s) (s->msg_style != MS_DEFAULT && \
208 ((c) == *s->msg_delim && m_Eom(s)))
209
210 /*
211 * Maildrop styles
212 */
213 #define MS_DEFAULT 0 /* default (one msg per file) */
214 #define MS_UNKNOWN 1 /* type not known yet */
215 #define MS_MBOX 2 /* Unix-style "from" lines */
216 #define MS_MMDF 3 /* string MMDF_DELIM */
217
218 /* This replaces the old approach, with its direct access to stdio
219 * internals. It uses one fread() to load a buffer that we manage.
220 *
221 * MSG_INPUT_SIZE is the size of the buffer.
222 * MAX_DELIMITER_SIZE is the maximum size of the delimiter used to
223 * separate messages in a maildrop, such as mbox "From ".
224 *
225 * Some of the tests in the test suite assume a MSG_INPUT_SIZE
226 * of 8192.
227 */
228 #define MSG_INPUT_SIZE NMH_BUFSIZ
229 #define MAX_DELIMITER_SIZE 5
230
231 struct m_getfld_state {
232 /* The file to read from; I/O block. Caller keeps passing it after
233 * initialisation due to historic interface so it keeps getting
234 * updated, presumably to the same value. */
235 FILE *iob;
236
237 /* Holds content of iob. */
238 char msg_buf[2 * MSG_INPUT_SIZE + MAX_DELIMITER_SIZE];
239 /* Points to the next byte to read from msg_buf. */
240 char *readpos;
241 /* Points to just after the last valid byte in msg_buf. If readpos
242 * equals end then msg_buf is empty. */
243 char *end;
244
245 /* Whether the caller intends to ftell(3)/fseek(3) iob's position,
246 * and thus whether m_getfld() needs to detect that and compensate. */
247 int track_filepos;
248 /* Position in iob given what's been consumed ready for returning to
249 * the caller. Further than this may have been read into msg_buf. */
250 off_t total_bytes_read;
251 /* Bytes of iob consumed during this call. */
252 off_t bytes_read;
253 /* What fseeko(3) tells us iob's position is having just explicitly
254 * set it to total_bytes_read. Surely always the same? */
255 off_t last_caller_pos;
256 /* Saved position in iob from filling msg_buf, prior to returning. */
257 off_t last_internal_pos;
258
259 /* One of the MS_* macros tracking the type of iob's content and
260 * thus if it's a single email, or several with delimeters. Default
261 * is MS_DEFAULT. */
262 int msg_style;
263
264 /* The message delimeter if iob has multiple emails, else NULL. For
265 * MS_MBOX it's the string that separates two emails, "\nFrom ",
266 * i.e. the terminating blank line of the previous email, and the
267 * starting From_ line of the next, but for MS_MMDF it's
268 * "\001\001\001\001\n" that may start or terminate an email. */
269 char *msg_delim;
270 /* The last non-NUL char of msg_delim. */
271 char *delimend;
272 /* When searching for msg_delim after an email, it's only of
273 * interest at the start of the line, i.e. when preceded by a
274 * linefeed. fdelim points to msg_delim[-1] that contains '\n' so
275 * it can be used as the needle. */
276 char *fdelim;
277 /* strlen(fdelim). */
278 int fdelimlen;
279 /* The second char of msg_delim. Used when the first char has
280 * already been matched to test the rest. */
281 char *edelim;
282 /* strlen(edelim). */
283 int edelimlen;
284 /* The relationship between all of these pointers and lengths for
285 * the two possible msg_delim values.
286 *
287 * "\0\n\nFrom \0" 9 "\0\n\001\001\001\001\n\0" 8
288 * | || | | | | |
289 * | || s->delimend | | | s->delimend
290 * | || | | |
291 * | |s->edelim s->edelimlen=5 | | s->edelim s->edelimlen=4
292 * | | | |
293 * | s->msg_delim | s->msg_delim
294 * | |
295 * s->fdelim s->fdelimlen=7 s->fdelim s->fdelimlen=6
296 */
297
298 /* Maps all the bytes of msg_delim, apart from the last two,
299 * including the NUL, onto the last position in msg_delim where they
300 * occur. Bytes not present are NULL. */
301 char **pat_map;
302
303 /* The parser's current state. Also returned to the caller, amongst
304 * other possible values, to indicate the token consumed. One of
305 * FLD, FLDPLUS, BODY, or FILEEOF. */
306 int state;
307 };
308
309 m_getfld_state_t m_getfld_state_init(FILE *iob)
310 {
311 m_getfld_state_t s;
312
313 NEW(s);
314 s->readpos = s->end = s->msg_buf;
315 s->bytes_read = s->total_bytes_read = 0;
316 s->last_caller_pos = s->last_internal_pos = 0;
317 s->iob = iob;
318 s->pat_map = NULL;
319 s->msg_style = MS_DEFAULT;
320 s->msg_delim = "";
321 s->fdelim = s->delimend = s->edelim = NULL;
322 s->fdelimlen = s->edelimlen = 0;
323 s->state = FLD;
324 s->track_filepos = 0;
325
326 return s;
327 }
328
329 /* scan() needs to force an initial state of FLD for each message. */
330 void
331 m_getfld_state_reset (m_getfld_state_t *gstate) {
332 if (*gstate) {
333 (*gstate)->state = FLD;
334 }
335 }
336
337 /* If the caller interleaves ftell*()/fseek*() calls with m_getfld()
338 calls, m_getfld() must keep track of the file position. The caller
339 must use this function to inform m_getfld(). */
340 void
341 m_getfld_track_filepos (m_getfld_state_t *gstate, FILE *iob) {
342 if (! *gstate) {
343 *gstate = m_getfld_state_init(iob);
344 }
345
346 (*gstate)->track_filepos = 1;
347 }
348
349 /* m_getfld_track_filepos() with the existing iob. */
350 void m_getfld_track_filepos2(m_getfld_state_t *gstate)
351 {
352 if (!*gstate)
353 adios(NULL, "m_getfld_track_filepos2 without gstate");
354
355 m_getfld_track_filepos(gstate, (*gstate)->iob);
356 }
357
358 void m_getfld_state_destroy (m_getfld_state_t *gstate) {
359 m_getfld_state_t s = *gstate;
360
361 if (s) {
362 if (s->fdelim) {
363 free (s->fdelim-1);
364 free (s->pat_map);
365 }
366 free (s);
367 *gstate = 0;
368 }
369 }
370
371 /*
372 Summary of file and message input buffer positions:
373
374 input file -------------------------------------------EOF
375 | |
376 last_caller_pos last_internal_pos
377
378
379 msg_buf --------------------EOF
380 | | |
381 msg_buf readpos end
382
383 |<>|=retained characters, difference
384 between last_internal_pos and
385 first readpos value after reading
386 in new chunk in read_more()
387
388 When returning from m_getfld()/m_unknown():
389 1) Save the internal file position in last_internal_pos. That's the
390 m_getfld() position reference in the input file.
391 2) Set file stream position so that callers can use ftell().
392
393 When entering m_getfld()/m_unknown():
394 Check to see if the call had changed the file position. If so,
395 adjust the internal position reference accordingly. If not, restore
396 the internal file position from last_internal_pos.
397 */
398
399
400 static void
401 enter_getfld (m_getfld_state_t *gstate, FILE *iob) {
402 m_getfld_state_t s;
403 off_t pos;
404 off_t pos_movement;
405
406 if (! *gstate) {
407 *gstate = m_getfld_state_init(iob);
408 }
409 s = *gstate;
410 s->bytes_read = 0;
411
412 /* This is ugly and no longer necessary, but is retained just in
413 case it's needed again. The parser used to open the input file
414 multiple times, so we had to always use the FILE * that's
415 passed to m_getfld(). Now the parser inits a new
416 m_getfld_state for each file. See comment below about the
417 readpos shift code being currently unused. */
418 s->iob = iob;
419
420 if (!s->track_filepos)
421 return;
422
423 if ((pos = ftello(iob)) == -1)
424 adios("getfld's iob", "failed to get offset on entry");
425 if (pos == 0 && s->last_internal_pos == 0)
426 return;
427
428 if (s->last_internal_pos == 0) {
429 s->total_bytes_read = pos;
430 return;
431 }
432
433 pos_movement = pos - s->last_caller_pos; /* Can be < 0. */
434 if (pos_movement == 0) {
435 pos = s->last_internal_pos;
436 } else {
437 /* The current file stream position differs from the
438 last one, so caller must have called ftell/o().
439 Or, this is the first call and the file position
440 was not at 0. */
441
442 if (s->readpos + pos_movement >= s->msg_buf &&
443 s->readpos + pos_movement < s->end) {
444 /* This is currently unused. It could be used by
445 parse_mime() if it was changed to use a global
446 m_getfld_state. */
447 /* We can shift readpos and remain within the
448 bounds of msg_buf. */
449 s->readpos += pos_movement;
450 s->total_bytes_read += pos_movement;
451 pos = s->last_internal_pos;
452 } else {
453 off_t off;
454 size_t num_read;
455
456 /* This seek skips past an integral number of
457 chunks of size MSG_INPUT_SIZE. */
458 off = pos / MSG_INPUT_SIZE * MSG_INPUT_SIZE;
459 if (fseeko(iob, off, SEEK_SET) == -1)
460 adios("getfld's iob", "failed to set offset to skip: "
461 "%" PRIdMAX, (intmax_t)off);
462 num_read = fread (s->msg_buf, 1, MSG_INPUT_SIZE, iob);
463 s->readpos = s->msg_buf + pos % MSG_INPUT_SIZE;
464 s->end = s->msg_buf + num_read;
465 s->total_bytes_read = pos;
466 }
467 }
468
469 if (fseeko(iob, pos, SEEK_SET) == -1)
470 adios("getfld's iob", "failed to set offset on entry: %" PRIdMAX,
471 (intmax_t)pos);
472 }
473
474 static void
475 leave_getfld (m_getfld_state_t s) {
476 s->total_bytes_read += s->bytes_read;
477
478 if (s->track_filepos) {
479 /* Save the internal file position that we use for the input buffer. */
480 if ((s->last_internal_pos = ftello(s->iob)) == -1)
481 adios("getfld's iob", "failed to get offset before seek");
482
483 /* Set file stream position so that callers can use ftell(). */
484 if (fseeko(s->iob, s->total_bytes_read, SEEK_SET) == -1)
485 adios("getfld's iob", "failed to set offset: %" PRIdMAX,
486 (intmax_t)s->total_bytes_read);
487
488 s->last_caller_pos = s->total_bytes_read;
489 }
490 }
491
492 static size_t
493 read_more (m_getfld_state_t s) {
494 /* Retain at least edelimlen characters that have already been read,
495 if at least edelimlen have been read, so that we can back up to them
496 in m_Eom(). */
497 ssize_t retain = s->end - s->msg_buf < s->edelimlen ? 0 : s->edelimlen;
498 size_t num_read;
499
500 if (retain > 0) {
501 if (retain < s->end - s->readpos)
502 retain = s->end - s->readpos;
503 assert (retain <= s->readpos - s->msg_buf);
504
505 /* Move what we want to retain at end of the buffer to the beginning. */
506 memmove (s->msg_buf, s->readpos - retain, retain);
507 }
508
509 s->readpos = s->msg_buf + retain;
510 num_read = fread (s->readpos, 1, MSG_INPUT_SIZE, s->iob);
511 s->end = s->readpos + num_read;
512
513 return num_read;
514 }
515
516 /* Return the next character consumed from the input, fetching more of
517 * the input for the buffer if required, or EOF on end of file. */
518 static int
519 Getc (m_getfld_state_t s) {
520 if ((s->end - s->readpos < 1 && read_more (s) == 0) ||
521 s->readpos >= s->end)
522 return EOF;
523
524 s->bytes_read++;
525 return (unsigned char)*s->readpos++;
526 }
527
528 /* Return the next character that Getc() would return, which may be EOF. */
529 static int
530 Peek (m_getfld_state_t s)
531 {
532 int c;
533
534 c = Getc(s);
535 if (c != EOF)
536 Ungetc(s);
537
538 return c;
539 }
540
541 /* If there's room, undo the consumption of one character from msg_buf,
542 * rewinding so it's read next, else die. */
543 static void
544 Ungetc(m_getfld_state_t s)
545 {
546 if (s->readpos == s->msg_buf)
547 adios(NULL, "Ungetc() at start of message buffer.");
548
549 s->readpos--;
550 s->bytes_read--;
551 }
552
553
554 int
555 m_getfld (m_getfld_state_t *gstate, char name[NAMESZ], char *buf, int *bufsz,
556 FILE *iob)
557 {
558 m_getfld_state_t s;
559 char *cp;
560 int max, n, c;
561
562 enter_getfld (gstate, iob);
563 s = *gstate;
564
565 if ((c = Getc(s)) == EOF) {
566 *bufsz = *buf = 0;
567 leave_getfld (s);
568 return s->state = FILEEOF;
569 }
570 if (eom (c, s)) {
571 /* flush null messages */
572 while ((c = Getc(s)) != EOF && eom (c, s))
573 ;
574
575 if (c != EOF)
576 Ungetc(s);
577 *bufsz = *buf = 0;
578 leave_getfld (s);
579 return s->state = FILEEOF;
580 }
581
582 switch (s->state) {
583 case FLD:
584 if (c == '\n' || c == '-') {
585 /* we hit the header/body separator */
586 while (c != '\n' && (c = Getc(s)) != EOF)
587 ;
588
589 if (c == EOF || (c = Getc(s)) == EOF || eom (c, s)) {
590 /* flush null messages */
591 while ((c = Getc(s)) != EOF && eom (c, s))
592 ;
593 if (c != EOF)
594 Ungetc(s);
595 *bufsz = *buf = 0;
596 leave_getfld (s);
597 return s->state = FILEEOF;
598 }
599 s->state = BODY;
600 goto body;
601 }
602 /*
603 * get the name of this component. take characters up
604 * to a ':', a newline or NAMESZ-1 characters, whichever
605 * comes first.
606 */
607 cp = name;
608 max = NAMESZ - 1;
609 /* Get the field name. The first time through the loop,
610 this copies out the first character, which was loaded
611 into c prior to loop entry. Initialize n to 1 to
612 account for that. */
613 for (n = 1;
614 c != ':' && c != '\n' && c != EOF && n < max;
615 ++n, c = Getc (s)) {
616 *cp++ = c;
617 }
618
619 /* Check for next character, which is either the space after
620 the ':' or the first folded whitespace. */
621 {
622 int next_char;
623 if (c == EOF || (next_char = Peek (s)) == EOF) {
624 *bufsz = *cp = *buf = 0;
625 inform("eof encountered in field \"%s\"", name);
626 leave_getfld (s);
627 return s->state = FMTERR;
628 }
629 }
630
631 /* If c isn't ':' here, something went wrong. Possibilities are:
632 * . hit a newline (error)
633 * . got more than namesz chars. (error)
634 */
635 if (c == ':') {
636 /* Finished header name, fall through to FLDPLUS below. */
637 } else if (c == '\n') {
638 /* We hit the end of the line without seeing ':' to
639 * terminate the field name. This is usually (always?)
640 * spam. But, blowing up is lame, especially when
641 * scan(1)ing a folder with such messages. Pretend such
642 * lines are the first of the body (at least mutt also
643 * handles it this way). */
644
645 /* See if buf can hold this line, since we were assuming
646 * we had a buffer of NAMESZ, not bufsz. */
647 /* + 1 for the newline */
648 if (*bufsz < n + 1) {
649 /* No, it can't. Oh well, guess we'll blow up. */
650 *bufsz = *cp = *buf = 0;
651 inform("eol encountered in field \"%s\"", name);
652 s->state = FMTERR;
653 break;
654 }
655 memcpy (buf, name, n - 1);
656 buf[n - 1] = '\n';
657 buf[n] = '\0';
658 /* Indicate this wasn't a header field using a character
659 that can't appear in a header field. */
660 name[0] = ':';
661 /* The last character read was '\n'. s->bytes_read
662 (and n) include that, but it was not put into the
663 name array in the for loop above. So subtract 1. */
664 *bufsz = --s->bytes_read; /* == n - 1 */
665 leave_getfld (s);
666 return s->state = BODY;
667 }
668 if (max <= n) {
669 /* By design, the loop above discards the last character
670 it had read. It's in c, use it. */
671 *cp++ = c;
672 *bufsz = *cp = *buf = 0;
673 inform("field name \"%s\" exceeds %d bytes", name,
674 NAMESZ - 2);
675 s->state = LENERR;
676 break;
677 }
678
679 /* Trim any trailing spaces from the end of name. */
680 while (isspace ((unsigned char) *--cp) && cp >= name) continue;
681 *++cp = 0;
682 /* readpos points to the first character of the field body. */
683 /* FALLTHRU */
684
685 case FLDPLUS: {
686 /*
687 * get (more of) the text of a field. Take
688 * characters up to the end of this field (newline
689 * followed by non-blank) or bufsz-1 characters.
690 */
691 int finished;
692
693 cp = buf;
694 max = *bufsz-1;
695 n = 0;
696 for (finished = 0; ! finished; ) {
697 while (c != '\n' && c != EOF && n++ < max) {
698 if ((c = Getc (s)) != EOF)
699 *cp++ = c;
700 }
701
702 if (c != EOF)
703 c = Peek (s);
704 if (max < n) {
705 /* The dest buffer is full. Need to back the read
706 pointer up by one because when m_getfld() is
707 reentered, it will read a character. Then
708 we'll jump right to the FLDPLUS handling code,
709 which will not store that character, but
710 instead move on to the next one. */
711 if (s->readpos > s->msg_buf) {
712 --s->readpos;
713 --s->bytes_read;
714 }
715 s->state = FLDPLUS;
716 finished = 1;
717 } else if (c != ' ' && c != '\t') {
718 /* The next character is not folded whitespace, so
719 prepare to move on to the next field. It's OK
720 if c is EOF, it will be handled on the next
721 call to m_getfld (). */
722 s->state = FLD;
723 finished = 1;
724 } else {
725 /* Folded header field, continues on the next line. */
726 }
727 }
728 *bufsz = s->bytes_read;
729 break;
730 }
731
732 body:
733 case BODY: {
734 /*
735 * get the message body up to bufsz characters or the
736 * end of the message.
737 */
738 char *bp;
739
740 name[0] = '\0';
741 max = *bufsz-1;
742 /* Back up and store the current position. */
743 bp = --s->readpos;
744 c = min(s->end - s->readpos, max);
745 if (s->msg_style != MS_DEFAULT && c > 1) {
746 /*
747 * packed maildrop - only take up to the (possible)
748 * start of the next message. This "matchc" should
749 * probably be a Boyer-Moore matcher for non-vaxen,
750 * particularly since we have the alignment table
751 * all built for the end-of-buffer test (next).
752 * But our vax timings indicate that the "matchc"
753 * instruction is 50% faster than a carefully coded
754 * B.M. matcher for most strings. (So much for elegant
755 * algorithms vs. brute force.) Since I (currently)
756 * run MH on a vax, we use the matchc instruction. --vj
757 */
758 char *ep;
759
760 if ((ep = memmem(bp, c, s->fdelim, s->fdelimlen)))
761 /* Plus one to nab the '\n' that starts fdelim as
762 * that ends the previous line; it isn't part of
763 * msg_delim. */
764 c = ep - bp + 1;
765 else {
766 /*
767 * There's no delim in the buffer but there may be
768 * a partial one at the end. If so, we want to leave
769 * it so the "eom" check on the next call picks it up.
770 * Use a modified Boyer-Moore matcher to make this
771 * check relatively cheap. The first "if" figures
772 * out what position in the pattern matches the last
773 * character in the buffer. The inner "while" matches
774 * the pattern against the buffer, backwards starting
775 * at that position. Note that unless the buffer
776 * ends with one of the characters in the pattern
777 * (excluding the first and last), we do only one test.
778 */
779 char *sp;
780
781 ep = bp + c - 1; /* The last byte. */
782 if ((sp = s->pat_map[(unsigned char) *ep])) {
783 do {
784 /* This if() is true unless (a) the buffer is too
785 * small to contain this delimiter prefix, or
786 * (b) it contains exactly enough chars for the
787 * delimiter prefix.
788 * For case (a) obviously we aren't going to match.
789 * For case (b), if the buffer really contained exactly
790 * a delim prefix, then the m_eom call at entry
791 * should have found it. Thus it's not a delim
792 * and we know we won't get a match.
793 */
794 if (((sp - s->fdelim) + 2) <= c) {
795 cp = sp;
796 /* Unfortunately although fdelim has a preceding NUL
797 * we can't use this as a sentinel in case the buffer
798 * contains a NUL in exactly the wrong place (this
799 * would cause us to run off the front of fdelim).
800 */
801 while (*--ep == *--cp)
802 if (cp < s->fdelim)
803 break;
804 if (cp < s->fdelim) {
805 /* we matched the entire delim prefix,
806 * so only take the buffer up to there.
807 * we know ep >= bp -- check above prevents underrun
808 */
809 c = (ep - bp) + 2;
810 break;
811 }
812 }
813 /* try matching one less char of delim string */
814 ep = bp + c - 1;
815 } while (--sp > s->fdelim);
816 }
817 }
818 }
819 memcpy( buf, bp, c );
820 /* Advance the current position to reflect the copy out.
821 c is less than or equal to the number of bytes remaining
822 in the read buffer, so will not overrun it. */
823 s->readpos += c;
824 cp = buf + c;
825 /* Subtract 1 from c because the first character was read by
826 Getc(), and therefore already accounted for in s->bytes_read. */
827 s->bytes_read += c - 1;
828 *bufsz = s->bytes_read;
829 break;
830 }
831
832 default:
833 adios (NULL, "m_getfld() called with bogus state of %d", s->state);
834 }
835
836 *cp = 0;
837 leave_getfld (s);
838
839 return s->state;
840 }
841
842
843 /* m_getfld() with the existing iob. */
844 int m_getfld2(m_getfld_state_t *gstate, char name[NAMESZ], char *buf, int *bufsz)
845 {
846 if (!*gstate)
847 adios(NULL, "m_getfld2 without gstate");
848
849 return m_getfld(gstate, name, buf, bufsz, (*gstate)->iob);
850 }
851
852
853 void
854 m_unknown(m_getfld_state_t *gstate, FILE *iob)
855 {
856 m_getfld_state_t s;
857 int c;
858 char text[MAX_DELIMITER_SIZE];
859 char from[] = "From ";
860 char *cp;
861 char *delimstr;
862 unsigned int i;
863
864 enter_getfld (gstate, iob);
865 s = *gstate;
866
867 /*
868 * Figure out what the message delimiter string is for this
869 * maildrop. (This used to be part of m_Eom but I didn't like
870 * the idea of an "if" statement that could only succeed on the
871 * first call to m_Eom getting executed on each call, i.e., at
872 * every newline in the message).
873 *
874 * If the first line of the maildrop is a Unix "From " line, we
875 * say the style is MBOX and eat the rest of the line. Otherwise
876 * we say the style is MMDF and look for the delimiter string
877 * specified when nmh was built (or from the mts.conf file).
878 */
879
880 s->msg_style = MS_UNKNOWN;
881
882 for (i = 0, cp = text; i < sizeof text; ++i, ++cp) {
883 if ((c = Getc (s)) == EOF) {
884 *cp = '\0';
885 break;
886 }
887 *cp = c;
888 }
889
890 if (i == sizeof from-1 && strncmp (text, "From ", sizeof from-1) == 0) {
891 s->msg_style = MS_MBOX;
892 delimstr = "\nFrom ";
893 while ((c = Getc(s)) != EOF && c != '\n')
894 ;
895 } else {
896 /* not a Unix style maildrop */
897 s->readpos -= s->bytes_read;
898 s->bytes_read = 0;
899 delimstr = MMDF_DELIM;
900 s->msg_style = MS_MMDF;
901 }
902
903 /* "\nFrom \0" 7 "\001\001\001\001\n\0" 6
904 * | |
905 * delimstr c=6 delimstr c=5
906 */
907 c = strlen (delimstr);
908 s->fdelim = mh_xmalloc (c + 3); /* \0, \n, delimstr, \0 */
909 *s->fdelim++ = '\0';
910 *s->fdelim = '\n';
911 s->fdelimlen = c + 1;
912 s->msg_delim = s->fdelim+1;
913 strcpy (s->msg_delim, delimstr);
914 s->edelim = s->msg_delim+1;
915 s->edelimlen = c - 1;
916 s->delimend = s->msg_delim + s->edelimlen;
917 if (s->edelimlen <= 1)
918 adios (NULL, "maildrop delimiter must be at least 2 bytes");
919
920 /*
921 * build a Boyer-Moore end-position map for the matcher in m_getfld.
922 * N.B. - we don't match just the first char (since it's the newline
923 * separator) or the last char (since the matchc would have found it
924 * if it was a real delim).
925 */
926 s->pat_map = (char **) mh_xcalloc (256, sizeof(char *));
927
928 for (cp = s->fdelim + 1; cp < s->delimend; cp++ )
929 s->pat_map[(unsigned char)*cp] = cp;
930
931 if (s->msg_style == MS_MMDF) {
932 /* flush extra msg hdrs */
933 while ((c = Getc(s)) != EOF && eom (c, s))
934 ;
935 if (c != EOF)
936 Ungetc(s);
937 }
938
939 leave_getfld (s);
940 }
941
942
943 /* m_unknown() with the existing iob. */
944 void m_unknown2(m_getfld_state_t *gstate)
945 {
946 if (!*gstate)
947 adios(NULL, "m_unknown2 without gstate");
948
949 m_unknown(gstate, (*gstate)->iob);
950 }
951
952
953 /*
954 * test for msg delimiter string
955 */
956
957 static int
958 m_Eom (m_getfld_state_t s)
959 {
960 int i;
961 char text[MAX_DELIMITER_SIZE];
962 char *cp;
963 int adjust = 1;
964
965 for (i = 0, cp = text; i < s->edelimlen; ++i, ++cp) {
966 int c2;
967
968 if ((c2 = Getc (s)) == EOF) {
969 *cp = '\0';
970 break;
971 }
972 *cp = c2;
973 }
974
975 if (i != s->edelimlen ||
976 strncmp (text, (char *)s->edelim, s->edelimlen)) {
977 if (i == 0 && s->msg_style == MS_MBOX) {
978 /* the final newline in the (brain damaged) unix-format
979 * maildrop is part of the delimiter - delete it.
980 */
981 return 1;
982 }
983
984 if (i <= 2 && s->msg_style == MS_MBOX &&
985 i != s->edelimlen && ! strncmp(text, s->fdelim, i)) {
986 /* If all or part of fdelim appeared at the end of the file,
987 back up even more so that the bytes are included in the
988 message. */
989 adjust = 2;
990 }
991
992 /* Did not find delimiter, so restore the read position.
993 Note that on input, a character had already been read
994 with Getc(). It will be unget by m_getfld () on return. */
995 s->readpos -= s->bytes_read - adjust;
996 s->bytes_read = adjust;
997 return 0;
998 }
999
1000 if (s->msg_style == MS_MBOX) {
1001 int c;
1002 while ((c = Getc(s)) != EOF && c != '\n')
1003 ;
1004 }
1005
1006 return 1;
1007 }