Removed defines for obsolete BSD bcopy functions; Use getc() directly.
[mmh] / sbr / m_getfld.c
1 /*
2 ** m_getfld.c -- read/parse a message
3 **
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.
7 */
8
9 #include <h/mh.h>
10 #include <h/mts.h>
11 #include <h/utils.h>
12
13 /*
14 ** This module has a long and checkered history.  First, it didn't burst
15 ** maildrops correctly because it considered two CTRL-A:s in a row to be
16 ** an inter-message delimiter.  It really is four CTRL-A:s followed by a
17 ** newline.  Unfortunately, MMDF will convert this delimiter *inside* a
18 ** message to a CTRL-B followed by three CTRL-A:s and a newline.  This
19 ** caused the old version of m_getfld() to declare eom prematurely.  The
20 ** fix was a lot slower than
21 **
22 **              c == '\001' && peekc (iob) == '\001'
23 **
24 ** but it worked, and to increase generality, MBOX style maildrops could
25 ** be parsed as well.  Unfortunately the speed issue finally caught up with
26 ** us since this routine is at the very heart of MH.
27 **
28 ** To speed things up considerably, the routine Eom() was made an auxilary
29 ** function called by the macro eom().  Unless we are bursting a maildrop,
30 ** the eom() macro returns FALSE saying we aren't at the end of the
31 ** message.
32 **
33 ** The next thing to do is to read the mts.conf file and initialize
34 ** delimiter[] and delimlen accordingly...
35 **
36 ** After mhl was made a built-in in msh, m_getfld() worked just fine
37 ** (using m_unknown() at startup).  Until one day: a message which was
38 ** the result of a bursting was shown. Then, since the burst boundaries
39 ** aren't CTRL-A:s, m_getfld() would blinding plunge on past the boundary.
40 ** Very sad.  The solution: introduce m_eomsbr().  This hook gets called
41 ** after the end of each line (since testing for eom involves an fseek()).
42 ** This worked fine, until one day: a message with no body portion arrived.
43 ** Then the
44 **
45 **                 while (eom(c = getc(iob), iob))
46 **                      continue;
47 **
48 ** loop caused m_getfld() to return FMTERR.  So, that logic was changed to
49 ** check for (*eom_action) and act accordingly.
50 **
51 ** [ Note by meillo 2011-10:
52 **   as msh was removed from mmh, m_eomsbr() became irrelevant. ]
53 **
54 ** This worked fine, until one day: someone didn't use four CTRL:A's as
55 ** their delimiters.  So, the bullet got bit and we read mts.h and
56 ** continue to struggle on.  It's not that bad though, since the only time
57 ** the code gets executed is when inc (or msh) calls it, and both of these
58 ** have already called mts_init().
59 **
60 ** ------------------------
61 ** (Written by Van Jacobson for the mh6 m_getfld, January, 1986):
62 **
63 ** This routine was accounting for 60% of the cpu time used by most mh
64 ** programs.  I spent a bit of time tuning and it now accounts for <10%
65 ** of the time used.  Like any heavily tuned routine, it's a bit
66 ** complex and you want to be sure you understand everything that it's
67 ** doing before you start hacking on it.  Let me try to emphasize
68 ** that:  every line in this atrocity depends on every other line,
69 ** sometimes in subtle ways.  You should understand it all, in detail,
70 ** before trying to change any part.  If you do change it, test the
71 ** result thoroughly (I use a hand-constructed test file that exercises
72 ** all the ways a header name, header body, header continuation,
73 ** header-body separator, body line and body eom can align themselves
74 ** with respect to a buffer boundary).  "Minor" bugs in this routine
75 ** result in garbaged or lost mail.
76 **
77 ** If you hack on this and slow it down, I, my children and my
78 ** children's children will curse you.
79 **
80 ** This routine gets used on three different types of files: normal,
81 ** single msg files, "packed" unix or mmdf mailboxs (when used by inc)
82 ** and packed, directoried bulletin board files (when used by msh).
83 ** The biggest impact of different file types is in "eom" testing.  The
84 ** code has been carefully organized to test for eom at appropriate
85 ** times and at no other times (since the check is quite expensive).
86 ** I have tried to arrange things so that the eom check need only be
87 ** done on entry to this routine.  Since an eom can only occur after a
88 ** newline, this is easy to manage for header fields.  For the msg
89 ** body, we try to efficiently search the input buffer to see if
90 ** contains the eom delimiter.  If it does, we take up to the
91 ** delimiter, otherwise we take everything in the buffer.  (The change
92 ** to the body eom/copy processing produced the most noticeable
93 ** performance difference, particularly for "inc" and "show".)
94 **
95 ** There are three qualitatively different things this routine busts
96 ** out of a message: field names, field text and msg bodies.  Field
97 ** names are typically short (~8 char) and the loop that extracts them
98 ** might terminate on a colon, newline or max width.  I considered
99 ** using a Vax "scanc" to locate the end of the field followed by a
100 ** "bcopy" but the routine call overhead on a Vax is too large for this
101 ** to work on short names.  If Berkeley ever makes "inline" part of the
102 ** C optimiser (so things like "scanc" turn into inline instructions) a
103 ** change here would be worthwhile.
104 **
105 ** Field text is typically 60 - 100 characters so there's (barely)
106 ** a win in doing a routine call to something that does a "locc"
107 ** followed by a "bmove".  About 30% of the fields have continuations
108 ** (usually the 822 "received:" lines) and each continuation generates
109 ** another routine call.  "Inline" would be a big win here, as well.
110 **
111 ** Messages, as of this writing, seem to come in two flavors: small
112 ** (~1K) and long (>2K).  Most messages have 400 - 600 bytes of headers
113 ** so message bodies average at least a few hundred characters.
114 ** Assuming your system uses reasonably sized stdio buffers (1K or
115 ** more), this routine should be able to remove the body in large
116 ** (>500 byte) chunks.  The makes the cost of a call to "bcopy"
117 ** small but there is a premium on checking for the eom in packed
118 ** maildrops.  The eom pattern is always a simple string so we can
119 ** construct an efficient pattern matcher for it (e.g., a Vax "matchc"
120 ** instruction).  Some thought went into recognizing the start of
121 ** an eom that has been split across two buffers.
122 **
123 ** This routine wants to deal with large chunks of data so, rather
124 ** than "getc" into a local buffer, it uses stdio's buffer.  If
125 ** you try to use it on a non-buffered file, you'll get what you
126 ** deserve.  This routine "knows" that struct FILEs have a _ptr
127 ** and a _cnt to describe the current state of the buffer and
128 ** it knows that _filbuf ignores the _ptr & _cnt and simply fills
129 ** the buffer.  If stdio on your system doesn't work this way, you
130 ** may have to make small changes in this routine.
131 **
132 ** This routine also "knows" that an EOF indication on a stream is
133 ** "sticky" (i.e., you will keep getting EOF until you reposition the
134 ** stream).  If your system doesn't work this way it is broken and you
135 ** should complain to the vendor.  As a consequence of the sticky
136 ** EOF, this routine will never return any kind of EOF status when
137 ** there is data in "name" or "buf").
138 */
139
140
141 /*
142 ** static prototypes
143 */
144 static int m_Eom(int, FILE *);
145 static unsigned char *matchc(int, char *, int, char *);
146 static unsigned char *locc(int, unsigned char *, unsigned char);
147
148 #define eom(c,iob)  (msg_style != MS_DEFAULT && \
149         (((c) == *msg_delim && m_Eom(c,iob)) ||\
150         (eom_action && (*eom_action)(c))))
151
152 static unsigned char **pat_map;
153
154 /*
155 ** defined in sbr/m_msgdef.c = 0
156 ** This is a disgusting hack for "inc" so it can know how many
157 ** characters were stuffed in the buffer on the last call
158 ** (see comments in uip/scansbr.c).
159 */
160 extern int msg_count;
161
162 /*
163 ** defined in sbr/m_msgdef.c = MS_DEFAULT
164 */
165 extern int msg_style;
166
167 /*
168 ** The "full" delimiter string for a packed maildrop consists
169 ** of a newline followed by the actual delimiter.  E.g., the
170 ** full string for a Unix maildrop would be: "\n\nFrom ".
171 ** "Fdelim" points to the start of the full string and is used
172 ** in the BODY case of the main routine to search the buffer for
173 ** a possible eom.  Msg_delim points to the first character of
174 ** the actual delim. string (i.e., fdelim+1).  Edelim
175 ** points to the 2nd character of actual delimiter string.  It
176 ** is used in m_Eom because the first character of the string
177 ** has been read and matched before m_Eom is called.
178 */
179 extern char *msg_delim;  /* defined in sbr/m_msgdef.c = "" */
180 static unsigned char *fdelim;
181 static unsigned char *delimend;
182 static int fdelimlen;
183 static unsigned char *edelim;
184 static int edelimlen;
185
186 static int (*eom_action)(int) = NULL;
187
188 #ifdef _FSTDIO
189 # define _ptr _p  /* Gag   */
190 # define _cnt _r  /* Retch */
191 # define _filbuf __srget  /* Puke  */
192 # define DEFINED__FILBUF_TO_SOMETHING_SPECIFIC
193 #endif
194
195 #ifdef SCO_5_STDIO
196 # define _ptr  __ptr
197 # define _cnt  __cnt
198 # define _base __base
199 # define _filbuf(fp)  ((fp)->__cnt = 0, __filbuf(fp))
200 # define DEFINED__FILBUF_TO_SOMETHING_SPECIFIC
201 #endif
202
203 #ifndef DEFINED__FILBUF_TO_SOMETHING_SPECIFIC
204 extern int  _filbuf(FILE*);
205 #endif
206
207
208 int
209 m_getfld(int state, unsigned char *name, unsigned char *buf,
210         int bufsz, FILE *iob)
211 {
212         register unsigned char  *bp, *cp, *ep, *sp;
213         register int cnt, c, i, j;
214
215         if ((c = getc(iob)) < 0) {
216                 msg_count = 0;
217                 *buf = 0;
218                 return FILEEOF;
219         }
220         if (eom(c, iob)) {
221                 if (! eom_action) {
222                         /* flush null messages */
223                         while ((c = getc(iob)) >= 0 && eom(c, iob))
224                                 ;
225                         if (c >= 0)
226                                 ungetc(c, iob);
227                 }
228                 msg_count = 0;
229                 *buf = 0;
230                 return FILEEOF;
231         }
232
233         switch (state) {
234                 case FLDEOF:
235                 case BODYEOF:
236                 case FLD:
237                         if (c == '\n' || c == '-') {
238                                 /* we hit the header/body separator */
239                                 while (c != '\n' && (c = getc(iob)) >= 0)
240                                         ;
241
242                                 if (c < 0 || (c = getc(iob)) < 0 || eom(c, iob)) {
243                                         if (! eom_action) {
244                                                 /* flush null messages */
245                                                 while ((c = getc(iob)) >= 0 && eom(c, iob))
246                                                         ;
247                                                 if (c >= 0)
248                                                         ungetc(c, iob);
249                                         }
250                                         msg_count = 0;
251                                         *buf = 0;
252                                         return FILEEOF;
253                                 }
254                                 state = BODY;
255                                 goto body;
256                         }
257                         /*
258                         ** get the name of this component.  take characters up
259                         ** to a ':', a newline or NAMESZ-1 characters,
260                         ** whichever comes first.
261                         */
262                         cp = name;
263                         i = NAMESZ - 1;
264                         for (;;) {
265 #ifdef LINUX_STDIO
266                                 bp = sp = (unsigned char *) iob->_IO_read_ptr - 1;
267                                 j = (cnt = ((long) iob->_IO_read_end -
268                                         (long) iob->_IO_read_ptr)  + 1) < i ? cnt : i;
269 #elif defined(__DragonFly__)
270                                 bp = sp = (unsigned char *) ((struct __FILE_public *)iob)->_p - 1;
271                                 j = (cnt = ((struct __FILE_public *)iob)->_r+1) < i ? cnt : i;
272 #else
273                                 bp = sp = (unsigned char *) iob->_ptr - 1;
274                                 j = (cnt = iob->_cnt+1) < i ? cnt : i;
275 #endif
276                                 while (--j >= 0 && (c = *bp++) != ':' && c != '\n')
277                                         *cp++ = c;
278
279                                 j = bp - sp;
280                                 if ((cnt -= j) <= 0) {
281 #ifdef LINUX_STDIO
282                                         iob->_IO_read_ptr = iob->_IO_read_end;
283                                         if (__underflow(iob) == EOF) {
284 #elif defined(__DragonFly__)
285                                         if (__srget(iob) == EOF) {
286 #else
287                                         if (_filbuf(iob) == EOF) {
288 #endif
289                                                 *cp = *buf = 0;
290                                                 advise(NULL, "eof encountered in field \"%s\"", name);
291                                                 return FMTERR;
292                                         }
293 #ifdef LINUX_STDIO
294                                         iob->_IO_read_ptr++; /* NOT automatic in __underflow()! */
295 #endif
296                                 } else {
297 #ifdef LINUX_STDIO
298                                         iob->_IO_read_ptr = bp + 1;
299 #elif defined(__DragonFly__)
300                                         ((struct __FILE_public *)iob)->_p = bp + 1;
301                                         ((struct __FILE_public *)iob)->_r = cnt - 1;
302 #else
303                                         iob->_ptr = bp + 1;
304                                         iob->_cnt = cnt - 1;
305 #endif
306                                 }
307                                 if (c == ':')
308                                         break;
309
310                                 /*
311                                 ** something went wrong.  possibilities are:
312                                 **  . hit a newline (error)
313                                 **  . got more than namesz chars. (error)
314                                 **  . hit the end of the buffer. (loop)
315                                 */
316                                 if (c == '\n') {
317                                         /*
318                                         ** We hit the end of the line
319                                         ** without seeing ':' to terminate
320                                         ** the field name.  This is usually
321                                         ** (always?)  spam.  But, blowing
322                                         ** up is lame, especially when
323                                         ** scan(1)ing a folder with such
324                                         ** messages.  Pretend such lines are
325                                         ** the first of the body (at least
326                                         ** mutt also handles it this way).
327                                         */
328
329                                         /*
330                                         ** See if buf can hold this line,
331                                         ** since we were assuming we had
332                                         ** a buffer of NAMESZ, not bufsz.
333                                         */
334                                         /* + 1 for the newline */
335                                         if (bufsz < j + 1) {
336                                                 /*
337                                                 ** No, it can't.  Oh well,
338                                                 ** guess we'll blow up.
339                                                 */
340                                                 *cp = *buf = 0;
341                                                 advise(NULL, "eol encountered in field \"%s\"", name);
342                                                 state = FMTERR;
343                                                 goto finish;
344                                         }
345                                         memcpy(buf, name, j - 1);
346                                         buf[j - 1] = '\n';
347                                         buf[j] = '\0';
348                                         /*
349                                         ** mhparse.c:get_content wants to
350                                         ** find the position of the body
351                                         ** start, but it thinks there's a
352                                         ** blank line between the header
353                                         ** and the body (naturally!), so
354                                         ** seek back so that things line
355                                         ** up even though we don't have
356                                         ** that blank line in this case.
357                                         ** Simpler parsers (e.g. mhl)
358                                         ** get extra newlines, but that
359                                         ** should be harmless enough, right?
360                                         ** This is a corrupt message anyway.
361                                         */
362                                         fseek(iob, ftell(iob) - 2, SEEK_SET);
363                                         return BODY;
364                                 }
365                                 if ((i -= j) <= 0) {
366                                         *cp = *buf = 0;
367                                         advise(NULL, "field name \"%s\" exceeds %d bytes", name, NAMESZ - 2);
368                                         state = LENERR;
369                                         goto finish;
370                                 }
371                         }
372
373                         while (isspace(*--cp) && cp >= name)
374                                 ;
375                         *++cp = 0;
376                         /* fall through */
377
378                 case FLDPLUS:
379                         /*
380                         ** get (more of) the text of a field.  take
381                         ** characters up to the end of this field (newline
382                         ** followed by non-blank) or bufsz-1 characters.
383                         */
384                         cp = buf; i = bufsz-1;
385                         for (;;) {
386 #ifdef LINUX_STDIO
387                                 cnt = (long) iob->_IO_read_end - (long) iob->_IO_read_ptr;
388                                 bp = (unsigned char *) --iob->_IO_read_ptr;
389 #elif defined(__DragonFly__)
390                                 cnt = ((struct __FILE_public *)iob)->_r++;
391                                 bp = (unsigned char *) --((struct __FILE_public *)iob)->_p;
392 #else
393                                 cnt = iob->_cnt++;
394                                 bp = (unsigned char *) --iob->_ptr;
395 #endif
396                                 c = cnt < i ? cnt : i;
397                                 while ((ep = locc( c, bp, '\n' ))) {
398                                         /*
399                                         ** if we hit the end of this field,
400                                         ** return.
401                                         */
402                                         if ((j = *++ep) != ' ' && j != '\t') {
403 #ifdef LINUX_STDIO
404                                                 j = ep - (unsigned char *) iob->_IO_read_ptr;
405                                                 memcpy(cp, iob->_IO_read_ptr, j);
406                                                 iob->_IO_read_ptr = ep;
407 #elif defined(__DragonFly__)
408                                                 j = ep - (unsigned char *) ((struct __FILE_public *)iob)->_p;
409                                                 memcpy(cp, ((struct __FILE_public *)iob)->_p, j);
410                                                 ((struct __FILE_public *)iob)->_p = ep;
411                                                 ((struct __FILE_public *)iob)->_r -= j;
412 #else
413                                                 j = ep - (unsigned char *) iob->_ptr;
414                                                 memcpy(cp, iob->_ptr, j);
415                                                 iob->_ptr = ep;
416                                                 iob->_cnt -= j;
417 #endif
418                                                 cp += j;
419                                                 state = FLD;
420                                                 goto finish;
421                                         }
422                                         c -= ep - bp;
423                                         bp = ep;
424                                 }
425                                 /*
426                                 ** end of input or dest buffer - copy what
427                                 ** we've found.
428                                 */
429 #ifdef LINUX_STDIO
430                                 c += bp - (unsigned char *) iob->_IO_read_ptr;
431                                 memcpy(cp, iob->_IO_read_ptr, c);
432 #elif defined(__DragonFly__)
433                                 c += bp - (unsigned char *) ((struct __FILE_public *)iob)->_p;
434                                 memcpy(cp, ((struct __FILE_public *)iob)->_p, c);
435 #else
436                                 c += bp - (unsigned char *) iob->_ptr;
437                                 memcpy(cp, iob->_ptr, c);
438 #endif
439                                 i -= c;
440                                 cp += c;
441                                 if (i <= 0) {
442                                         /* the dest buffer is full */
443 #ifdef LINUX_STDIO
444                                         iob->_IO_read_ptr += c;
445 #elif defined(__DragonFly__)
446                                         ((struct __FILE_public *)iob)->_r -= c;
447                                         ((struct __FILE_public *)iob)->_p += c;
448 #else
449                                         iob->_cnt -= c;
450                                         iob->_ptr += c;
451 #endif
452                                         state = FLDPLUS;
453                                         break;
454                                 }
455                                 /*
456                                 ** There's one character left in the input
457                                 ** buffer.  Copy it & fill the buffer.
458                                 ** If the last char was a newline and the
459                                 ** next char is not whitespace, this is
460                                 ** the end of the field.  Otherwise loop.
461                                 */
462                                 --i;
463 #ifdef LINUX_STDIO
464                                 *cp++ = j = *(iob->_IO_read_ptr + c);
465                                 iob->_IO_read_ptr = iob->_IO_read_end;
466                                 c = __underflow(iob);
467                                 iob->_IO_read_ptr++;  /* NOT automatic! */
468 #elif defined(__DragonFly__)
469                                 *cp++ =j = *(((struct __FILE_public *)iob)->_p + c);
470                                 c = __srget(iob);
471 #else
472                                 *cp++ = j = *(iob->_ptr + c);
473                                 c = _filbuf(iob);
474 #endif
475                                 if (c == EOF ||
476                                   ((j == '\0' || j == '\n') && c != ' ' && c != '\t')) {
477                                         if (c != EOF) {
478 #ifdef LINUX_STDIO
479                                                 --iob->_IO_read_ptr;
480 #elif defined(__DragonFly__)
481                                                 --((struct __FILE_public *)iob)->_p;
482                                                 ++((struct __FILE_public *)iob)->_r;
483 #else
484                                                 --iob->_ptr;
485                                                 ++iob->_cnt;
486 #endif
487                                         }
488                                         state = FLD;
489                                         break;
490                                 }
491                         }
492                         break;
493
494                 case BODY:
495                 body:
496                         /*
497                         ** get the message body up to bufsz characters or
498                         ** the end of the message.  Sleazy hack: if bufsz
499                         ** is negative we assume that we were called to
500                         ** copy directly into the output buffer and we
501                         ** don't add an eos.
502                         */
503                         i = (bufsz < 0) ? -bufsz : bufsz-1;
504 #ifdef LINUX_STDIO
505                         bp = (unsigned char *) --iob->_IO_read_ptr;
506                         cnt = (long) iob->_IO_read_end - (long) iob->_IO_read_ptr;
507 #elif defined(__DragonFly__)
508                         bp = (unsigned char *) --((struct __FILE_public *)iob)->_p;
509                         cnt = ++((struct __FILE_public *)iob)->_r;
510 #else
511                         bp = (unsigned char *) --iob->_ptr;
512                         cnt = ++iob->_cnt;
513 #endif
514                         c = (cnt < i ? cnt : i);
515                         if (msg_style != MS_DEFAULT && c > 1) {
516                                 /*
517                                 ** packed maildrop - only take up to the
518                                 ** (possible) start of the next message.
519                                 ** This "matchc" should probably be a
520                                 ** Boyer-Moore matcher for non-vaxen,
521                                 ** particularly since we have the alignment
522                                 ** table all built for the end-of-buffer
523                                 ** test (next).  But our vax timings
524                                 ** indicate that the "matchc" instruction
525                                 ** is 50% faster than a carefully coded
526                                 ** B.M. matcher for most strings.  (So much
527                                 ** for elegant algorithms vs. brute force.)
528                                 ** Since I (currently) run MH on a vax,
529                                 ** we use the matchc instruction. --vj
530                                 */
531                                 if ((ep = matchc( fdelimlen, fdelim, c, bp )))
532                                         c = ep - bp + 1;
533                                 else {
534                                         /*
535                                         ** There's no delim in the buffer
536                                         ** but there may be a partial one
537                                         ** at the end.  If so, we want
538                                         ** to leave it so the "eom" check
539                                         ** on the next call picks it up.
540                                         ** Use a modified Boyer-Moore
541                                         ** matcher to make this check
542                                         ** relatively cheap.  The first
543                                         ** "if" figures out what position
544                                         ** in the pattern matches the
545                                         ** last character in the buffer.
546                                         ** The inner "while" matches the
547                                         ** pattern against the buffer,
548                                         ** backwards starting at that
549                                         ** position.  Note that unless
550                                         ** the buffer ends with one of
551                                         ** the characters in the pattern
552                                         ** (excluding the first and last),
553                                         ** we do only one test.
554                                         */
555                                         ep = bp + c - 1;
556                                         if ((sp = pat_map[*ep])) {
557                                                 do {
558                                                         /*
559                                                         ** This if() is
560                                                         ** true unless (a)
561                                                         ** the buffer is too
562                                                         ** small to contain
563                                                         ** this delimiter
564                                                         ** prefix, or (b)
565                                                         ** it contains
566                                                         ** exactly enough
567                                                         ** chars for the
568                                                         ** delimiter prefix.
569                                                         ** For case (a)
570                                                         ** obviously we
571                                                         ** aren't going
572                                                         ** to match.
573                                                         ** For case (b),
574                                                         ** if the buffer
575                                                         ** really contained
576                                                         ** exactly a delim
577                                                         ** prefix, then
578                                                         ** the m_eom call
579                                                         ** at entry should
580                                                         ** have found it.
581                                                         ** Thus it's not
582                                                         ** a delim and we
583                                                         ** know we won't
584                                                         ** get a match.
585                                                         */
586                                                         if (((sp - fdelim) + 2) <= c) {
587                                                                 cp = sp;
588                                                                 /*
589                                                                 ** Unfortunately although fdelim has a preceding NUL
590                                                                 ** we can't use this as a sentinel in case the buffer
591                                                                 ** contains a NUL in exactly the wrong place (this
592                                                                 ** would cause us to run off the front of fdelim).
593                                                                 */
594                                                                 while (*--ep == *--cp)
595                                                                         if (cp < fdelim)
596                                                                                 break;
597                                                                 if (cp < fdelim) {
598                                                                         /* we matched the entire delim prefix,
599                                                                         ** so only take the buffer up to there.
600                                                                         ** we know ep >= bp -- check above prevents underrun
601                                                                         */
602                                                                         c = (ep - bp) + 2;
603                                                                         break;
604                                                                 }
605                                                         }
606                                                         /* try matching one less char of delim string */
607                                                         ep = bp + c - 1;
608                                                 } while (--sp > fdelim);
609                                         }
610                                 }
611                         }
612                         memcpy( buf, bp, c );
613 #ifdef LINUX_STDIO
614                         iob->_IO_read_ptr += c;
615 #elif defined(__DragonFly__)
616                         ((struct __FILE_public *)iob)->_r -= c;
617                         ((struct __FILE_public *)iob)->_p += c;
618 #else
619                         iob->_cnt -= c;
620                         iob->_ptr += c;
621 #endif
622                         if (bufsz < 0) {
623                                 msg_count = c;
624                                 return (state);
625                         }
626                         cp = buf + c;
627                         break;
628
629                 default:
630                         adios(NULL, "m_getfld() called with bogus state of %d", state);
631         }
632 finish:
633         *cp = 0;
634         msg_count = cp - buf;
635         return (state);
636 }
637
638
639 #ifdef RPATHS
640 static char unixbuf[BUFSIZ] = "";
641 #endif /* RPATHS */
642
643 void
644 m_unknown(FILE *iob)
645 {
646         register int c;
647         register long pos;
648         char text[10];
649         register char *cp;
650         register char *delimstr;
651
652 /*
653 ** Figure out what the message delimitter string is for this
654 ** maildrop.  (This used to be part of m_Eom but I didn't like
655 ** the idea of an "if" statement that could only succeed on the
656 ** first call to m_Eom getting executed on each call, i.e., at
657 ** every newline in the message).
658 **
659 ** If the first line of the maildrop is a Unix "From " line, we
660 ** say the style is MBOX and eat the rest of the line.  Otherwise
661 ** we say the style is MMDF and look for the delimiter string
662 ** specified when nmh was built (or from the mts.conf file).
663 */
664
665         msg_style = MS_UNKNOWN;
666
667         pos = ftell(iob);
668         if (fread(text, sizeof(*text), 5, iob) == 5
669                 && strncmp(text, "From ", 5) == 0) {
670                 msg_style = MS_MBOX;
671                 delimstr = "\nFrom ";
672 #ifndef RPATHS
673                 while ((c = getc(iob)) != '\n' && c >= 0)
674                         ;
675 #else /* RPATHS */
676                 cp = unixbuf;
677                 while ((c = getc(iob)) != '\n' && cp - unixbuf < BUFSIZ - 1)
678                         *cp++ = c;
679                 *cp = 0;
680 #endif /* RPATHS */
681         } else {
682                 /* not a Unix style maildrop */
683                 fseek(iob, pos, SEEK_SET);
684                 if (mmdlm2 == NULL || *mmdlm2 == 0)
685                         mmdlm2 = "\001\001\001\001\n";
686                 delimstr = mmdlm2;
687                 msg_style = MS_MMDF;
688         }
689         c = strlen(delimstr);
690         fdelim = (unsigned char *) mh_xmalloc((size_t) (c + 3));
691         *fdelim++ = '\0';
692         *fdelim = '\n';
693         msg_delim = (char *)fdelim+1;
694         edelim = (unsigned char *)msg_delim+1;
695         fdelimlen = c + 1;
696         edelimlen = c - 1;
697         strcpy(msg_delim, delimstr);
698         delimend = (unsigned char *)msg_delim + edelimlen;
699         if (edelimlen <= 1)
700                 adios(NULL, "maildrop delimiter must be at least 2 bytes");
701         /*
702         ** build a Boyer-Moore end-position map for the matcher in m_getfld.
703         ** N.B. - we don't match just the first char (since it's the newline
704         ** separator) or the last char (since the matchc would have found it
705         ** if it was a real delim).
706         */
707         pat_map = (unsigned char **) calloc(256, sizeof(unsigned char *));
708
709         for (cp = (char *) fdelim + 1; cp < (char *) delimend; cp++ )
710                 pat_map[(unsigned char)*cp] = (unsigned char *) cp;
711
712         if (msg_style == MS_MMDF) {
713                 /* flush extra msg hdrs */
714                 while ((c = getc(iob)) >= 0 && eom(c, iob))
715                         ;
716                 if (c >= 0)
717                         ungetc(c, iob);
718         }
719 }
720
721
722 /*
723 ** test for msg delimiter string
724 */
725
726 static int
727 m_Eom(int c, FILE *iob)
728 {
729         register long pos = 0L;
730         register int i;
731         char text[10];
732 #ifdef RPATHS
733         register char *cp;
734 #endif /* RPATHS */
735
736         pos = ftell(iob);
737         if ((i = fread(text, sizeof *text, edelimlen, iob)) != edelimlen
738                 || strncmp(text, (char *)edelim, edelimlen)) {
739                 if (i == 0 && msg_style == MS_MBOX)
740                         /*
741                         ** the final newline in the (brain damaged) unix-format
742                         ** maildrop is part of the delimitter - delete it.
743                         */
744                         return 1;
745
746 #if 0
747                 fseek(iob, pos, SEEK_SET);
748 #endif
749
750                 fseek(iob, (long)(pos-1), SEEK_SET);
751                 getc(iob);  /* should be OK */
752                 return 0;
753         }
754
755         if (msg_style == MS_MBOX) {
756 #ifndef RPATHS
757                 while ((c = getc(iob)) != '\n')
758                         if (c < 0)
759                                 break;
760 #else /* RPATHS */
761                 cp = unixbuf;
762                 while ((c = getc(iob)) != '\n' && c >= 0 && cp - unixbuf < BUFSIZ - 1)
763                         *cp++ = c;
764                 *cp = 0;
765 #endif /* RPATHS */
766         }
767
768         return 1;
769 }
770
771
772 #ifdef RPATHS
773 /*
774 ** Return the Return-Path and Delivery-Date
775 ** header information.
776 **
777 ** Currently, I'm assuming that the "From " line
778 ** takes one of the following forms.
779 **
780 ** From sender date remote from host   (for UUCP delivery)
781 ** From sender@host  date              (for sendmail delivery)
782 */
783
784 int
785 get_returnpath(char *rp, int rplen, char *dd, int ddlen)
786 {
787         char *ap, *bp, *cp, *dp;
788
789         ap = unixbuf;
790         if (!(bp = cp = strchr(ap, ' ')))
791                 return 0;
792
793         /*
794         ** Check for "remote from" in envelope to see
795         ** if this message uses UUCP style addressing
796         */
797         while ((cp = strchr(++cp, 'r'))) {
798                 if (strncmp(cp, "remote from", 11) == 0) {
799                         cp = strrchr(cp, ' ');
800                         break;
801                 }
802         }
803
804         /*
805         ** Get the Return-Path information from
806         ** the "From " envelope.
807         */
808         if (cp) {
809                 /* return path for UUCP style addressing */
810                 dp = strchr(++cp, '\n');
811                 snprintf(rp, rplen, "%.*s!%.*s\n", (int)(dp - cp), cp, (int)(bp - ap), ap);
812         } else {
813                 /* return path for standard domain addressing */
814                 snprintf(rp, rplen, "%.*s\n", (int)(bp - ap), ap);
815         }
816
817         /*
818         ** advance over the spaces to get to
819         ** delivery date on envelope
820         */
821         while (*bp == ' ')
822                 bp++;
823
824         /* Now get delivery date from envelope */
825         snprintf(dd, ddlen, "%.*s\n", 24, bp);
826
827         unixbuf[0] = 0;
828         return 1;
829 }
830 #endif /* RPATHS */
831
832
833 static unsigned char *
834 matchc(int patln, char *pat, int strln, char *str)
835 {
836         register char *es = str + strln - patln;
837         register char *sp;
838         register char *pp;
839         register char *ep = pat + patln;
840         register char pc = *pat++;
841
842         for(;;) {
843                 while (pc != *str++)
844                         if (str > es)
845                                 return 0;
846                 if (str > es+1)
847                         return 0;
848                 sp = str; pp = pat;
849                 while (pp < ep && *sp++ == *pp)
850                         pp++;
851                 if (pp >= ep)
852                         return ((unsigned char *)--str);
853         }
854 }
855
856
857 /*
858 ** Locate character "term" in the next "cnt" characters of "src".
859 ** If found, return its address, otherwise return 0.
860 */
861
862 static unsigned char *
863 locc(int cnt, unsigned char *src, unsigned char term)
864 {
865         while (*src++ != term && --cnt > 0)
866                 ;
867
868         return (cnt > 0 ? --src : (unsigned char *)0);
869 }