]> Pileus Git - ~andy/fetchmail/blob - rfc822.c
Fix lots of warnings, most around string literals...
[~andy/fetchmail] / rfc822.c
1 /*****************************************************************************
2
3 NAME:
4    rfc822.c -- code for slicing and dicing RFC822 mail headers
5
6 ENTRY POINTS:
7    nextaddr() -- parse the next address out of an RFC822 header
8    reply_hack() -- append hostname to local header addresses 
9
10 THEORY:
11    How to parse RFC822 headers in C. This is not a fully conformant
12 implementation of RFC822 or RFC2822, but it has been in production use
13 in a widely-deployed MTA (fetcmail) since 1996 without complaints.
14 Really perverse combinations of quoting and commenting could break it.
15
16 AUTHOR:
17    Eric S. Raymond <esr@thyrsus.com>, 1997.  This source code example
18 is part of fetchmail and the Unix Cookbook, and are released under the
19 MIT license.  Compile with -DMAIN to build the demonstrator.
20
21 ******************************************************************************/
22 #include  <stdio.h>
23 #include  <ctype.h>
24 #include  <string.h>
25 #include  <stdlib.h>
26
27 #include "fetchmail.h"
28
29 #ifndef MAIN
30 #include "i18n.h"
31 #else
32 #include  <unistd.h>
33 static int verbose;
34 const char *program_name = "rfc822";
35 #endif /* MAIN */
36
37 #ifndef TRUE
38 #define TRUE 1
39 #define FALSE 0
40 #endif
41
42 #define HEADER_END(p)   ((p)[0] == '\n' && ((p)[1] != ' ' && (p)[1] != '\t'))
43
44 char *reply_hack(
45         char *buf               /* header to be hacked */,
46         const char *host        /* server hostname */,
47         size_t *length)
48 /* hack message headers so replies will work properly */
49 {
50     char *from, *cp, last_nws = '\0', *parens_from = NULL;
51     int parendepth, state, has_bare_name_part, has_host_part;
52 #ifndef MAIN
53     int addresscount = 1;
54 #endif /* MAIN */
55
56     if (strncasecmp("From:", buf, 5)
57         && strncasecmp("To:", buf, 3)
58         && strncasecmp("Reply-To:", buf, 9)
59         && strncasecmp("Return-Path:", buf, 12)
60         && strncasecmp("Cc:", buf, 3)
61         && strncasecmp("Bcc:", buf, 4)
62         && strncasecmp("Resent-From:", buf, 12)
63         && strncasecmp("Resent-To:", buf, 10)
64         && strncasecmp("Resent-Cc:", buf, 10)
65         && strncasecmp("Resent-Bcc:", buf, 11)
66         && strncasecmp("Apparently-From:", buf, 16)
67         && strncasecmp("Apparently-To:", buf, 14)
68         && strncasecmp("Sender:", buf, 7)
69         && strncasecmp("Resent-Sender:", buf, 14)
70        ) {
71         return(buf);
72     }
73
74 #ifndef MAIN
75     if (outlevel >= O_DEBUG)
76         report_build(stdout, GT_("About to rewrite %s"), buf);
77
78     /* make room to hack the address; buf must be malloced */
79     for (cp = buf; *cp; cp++)
80         if (*cp == ',' || isspace((unsigned char)*cp))
81             addresscount++;
82     buf = (char *)xrealloc(buf, strlen(buf) + addresscount * (strlen(host) + 1) + 1);
83 #endif /* MAIN */
84
85     /*
86      * This is going to foo up on some ill-formed addresses.
87      * Note that we don't rewrite the fake address <> in order to
88      * avoid screwing up bounce suppression with a null Return-Path.
89      */
90
91     parendepth = state = 0;
92     has_host_part = has_bare_name_part = FALSE;
93     for (from = buf; *from; from++)
94     {
95 #ifdef MAIN
96         if (verbose)
97         {
98             printf("state %d: %s", state, buf);
99             printf("%*s^\n", (int)(from - buf + 10), " ");
100         }
101 #endif /* MAIN */
102         if (state != 2)
103         {
104             if (*from == '(')
105                 ++parendepth;
106             else if (*from == ')')
107                 --parendepth;
108         }
109
110         if (!parendepth && !has_host_part)
111             switch (state)
112             {
113             case 0:     /* before header colon */
114                 if (*from == ':')
115                     state = 1;
116                 break;
117
118             case 1:     /* we've seen the colon, we're looking for addresses */
119                 if (!isspace((unsigned char)*from))
120                     last_nws = *from;
121                 if (*from == '<')
122                     state = 3;
123                 else if (*from == '@' || *from == '!')
124                     has_host_part = TRUE;
125                 else if (*from == '"')
126                     state = 2;
127                 /*
128                  * Not expanding on last non-WS == ';' deals with groupnames,
129                  * an obscure misfeature described in sections
130                  * 6.1, 6.2.6, and A.1.5 of the RFC822 standard.
131                  */
132                 else if ((*from == ',' || HEADER_END(from))
133                          && has_bare_name_part
134                          && !has_host_part
135                          && last_nws != ';')
136                 {
137                     int hostlen;
138                     char *p;
139
140                     p = from;
141                     if (parens_from)
142                         from = parens_from;
143                     while (isspace((unsigned char)*from) || (*from == ','))
144                         --from;
145                     from++;
146                     hostlen = strlen(host);
147                     for (cp = from + strlen(from); cp >= from; --cp)
148                         cp[hostlen+1] = *cp;
149                     *from++ = '@';
150                     memcpy(from, host, hostlen);
151                     from = p + hostlen + 1;
152                     has_host_part = TRUE;
153                 } 
154                 else if (from[1] == '('
155                          && has_bare_name_part
156                          && !has_host_part
157                          && last_nws != ';' && last_nws != ')')
158                 {
159                     parens_from = from;
160                 } 
161                 else if (!isspace((unsigned char)*from))
162                     has_bare_name_part = TRUE;
163                 break;
164
165             case 2:     /* we're in a string */
166                 if (*from == '"')
167                 {
168                     char        *bp;
169                     int         bscount;
170
171                     bscount = 0;
172                     for (bp = from - 1; *bp == '\\'; bp--)
173                         bscount++;
174                     if (!(bscount % 2))
175                         state = 1;
176                 }
177                 break;
178
179             case 3:     /* we're in a <>-enclosed address */
180                 if (*from == '@' || *from == '!')
181                     has_host_part = TRUE;
182                 else if (*from == '>' && (from > buf && from[-1] != '<'))
183                 {
184                     state = 1;
185                     if (!has_host_part)
186                     {
187                         int hostlen;
188
189                         hostlen = strlen(host);
190                         for (cp = from + strlen(from); cp >= from; --cp)
191                             cp[hostlen+1] = *cp;
192                         *from++ = '@';
193                         memcpy(from, host, hostlen);
194                         from += hostlen;
195                         has_host_part = TRUE;
196                     }
197                 }
198                 break;
199             }
200
201         /*
202          * If we passed a comma, reset everything.
203          */
204         if ((from > buf && from[-1] == ',') && !parendepth) {
205           has_host_part = has_bare_name_part = FALSE;
206           parens_from = NULL;
207         }
208     }
209
210 #ifndef MAIN
211     if (outlevel >= O_DEBUG)
212         report_complete(stdout, GT_("Rewritten version is %s\n"), buf);
213 #endif /* MAIN */
214     *length = strlen(buf);
215     return(buf);
216 }
217
218 char *nxtaddr(const char *hdr /* header to be parsed, NUL to continue previous hdr */)
219 /* parse addresses in succession out of a specified RFC822 header */
220 {
221     static char address[BUFSIZ];
222     static size_t tp;
223     static const char *hp;
224     static int  state, oldstate;
225 #ifdef MAIN
226     static const char *orighdr;
227 #endif /* MAIN */
228     int parendepth = 0;
229
230 #define START_HDR       0       /* before header colon */
231 #define SKIP_JUNK       1       /* skip whitespace, \n, and junk */
232 #define BARE_ADDRESS    2       /* collecting address without delimiters */
233 #define INSIDE_DQUOTE   3       /* inside double quotes */
234 #define INSIDE_PARENS   4       /* inside parentheses */
235 #define INSIDE_BRACKETS 5       /* inside bracketed address */
236 #define ENDIT_ALL       6       /* after last address */
237
238 #define NEXTTP()        ((tp < sizeof(address)-1) ? tp++ : tp)
239
240     if (hdr)
241     {
242         hp = hdr;
243         state = START_HDR;
244 #ifdef MAIN
245         orighdr = hdr;
246 #endif /* MAIN */
247         tp = 0;
248     }
249
250     if (!hp) return NULL;
251
252     for (; *hp; hp++)
253     {
254 #ifdef MAIN
255         if (verbose)
256         {
257             printf("state %d: %s", state, orighdr);
258             printf("%*s^\n", (int)(hp - orighdr + 10), " ");
259         }
260 #endif /* MAIN */
261
262         if (state == ENDIT_ALL)         /* after last address */
263             return(NULL);
264         else if (HEADER_END(hp))
265         {
266             state = ENDIT_ALL;
267             if (tp)
268             {
269                 while (tp > 0 && isspace((unsigned char)address[tp - 1]))
270                     tp--;
271                 address[tp] = '\0';
272                 tp = 0;
273                 return (address);
274             }
275             return(NULL);
276         }
277         else if (*hp == '\\')           /* handle RFC822 escaping */
278         {
279             if (state != INSIDE_PARENS)
280             {
281                 address[NEXTTP()] = *hp++;      /* take the escape */
282                 address[NEXTTP()] = *hp;        /* take following unsigned char */
283             }
284         }
285         else switch (state)
286         {
287         case START_HDR:   /* before header colon */
288             if (*hp == ':')
289                 state = SKIP_JUNK;
290             break;
291
292         case SKIP_JUNK:         /* looking for address start */
293             if (*hp == '"')     /* quoted string */
294             {
295                 oldstate = SKIP_JUNK;
296                 state = INSIDE_DQUOTE;
297                 address[NEXTTP()] = *hp;
298             }
299             else if (*hp == '(')        /* address comment -- ignore */
300             {
301                 parendepth = 1;
302                 oldstate = SKIP_JUNK;
303                 state = INSIDE_PARENS;    
304             }
305             else if (*hp == '<')        /* begin <address> */
306             {
307                 state = INSIDE_BRACKETS;
308                 tp = 0;
309             }
310             else if (*hp != ',' && !isspace((unsigned char)*hp))
311             {
312                 --hp;
313                 state = BARE_ADDRESS;
314             }
315             break;
316
317         case BARE_ADDRESS:      /* collecting address without delimiters */
318             if (*hp == ',')     /* end of address */
319             {
320                 if (tp)
321                 {
322                     address[NEXTTP()] = '\0';
323                     state = SKIP_JUNK;
324                     tp = 0;
325                     return(address);
326                 }
327             }
328             else if (*hp == '(')        /* beginning of comment */
329             {
330                 parendepth = 1;
331                 oldstate = BARE_ADDRESS;
332                 state = INSIDE_PARENS;    
333             }
334             else if (*hp == '<')        /* beginning of real address */
335             {
336                 state = INSIDE_BRACKETS;
337                 tp = 0;
338             }
339             else if (*hp == '"')        /* quoted word, copy verbatim */
340             {
341                 oldstate = state;
342                 state = INSIDE_DQUOTE;
343                 address[NEXTTP()] = *hp;
344             }
345             else if (!isspace((unsigned char)*hp))      /* just take it, ignoring whitespace */
346                 address[NEXTTP()] = *hp;
347             break;
348
349         case INSIDE_DQUOTE:     /* we're in a quoted string, copy verbatim */
350             address[NEXTTP()] = *hp;
351             if (*hp == '"')
352                 state = oldstate;
353             break;
354
355         case INSIDE_PARENS:     /* we're in a parenthesized comment, ignore */
356             if (*hp == '(')
357                 ++parendepth;
358             else if (*hp == ')')
359                 --parendepth;
360             if (parendepth == 0)
361                 state = oldstate;
362             break;
363
364         case INSIDE_BRACKETS:   /* possible <>-enclosed address */
365             if (*hp == '>')     /* end of address */
366             {
367                 address[NEXTTP()] = '\0';
368                 state = SKIP_JUNK;
369                 ++hp;
370                 tp = 0;
371                 return(address);
372             }
373             else if (*hp == '<')        /* nested <> */
374                 tp = 0;
375             else if (*hp == '"')        /* quoted address */
376             {
377                 address[NEXTTP()] = *hp;
378                 oldstate = INSIDE_BRACKETS;
379                 state = INSIDE_DQUOTE;
380             }
381             else                        /* just copy address */
382                 address[NEXTTP()] = *hp;
383             break;
384         }
385     }
386
387     return(NULL);
388 }
389
390 #ifdef MAIN
391 static void parsebuf(char *longbuf, int reply)
392 {
393     char        *cp;
394     size_t      dummy;
395
396     if (reply)
397     {
398         reply_hack(longbuf, "HOSTNAME.NET", &dummy);
399         printf("Rewritten buffer: %s", (char *)longbuf);
400     }
401     else
402         if ((cp = nxtaddr(longbuf)) != (char *)NULL)
403             do {
404                 printf("\t-> \"%s\"\n", (char *)cp);
405             } while
406                 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
407 }
408
409
410
411 int main(int argc, char *argv[])
412 {
413     char        buf[BUFSIZ], longbuf[BUFSIZ];
414     int         ch, reply;
415     
416     verbose = reply = FALSE;
417     while ((ch = getopt(argc, argv, "rv")) != EOF)
418         switch(ch)
419         {
420         case 'r':
421             reply = TRUE;
422             break;
423
424         case 'v':
425             verbose = TRUE;
426             break;
427         }
428
429     while (fgets(buf, sizeof(buf)-1, stdin))
430     {
431         if (buf[0] == ' ' || buf[0] == '\t')
432             strlcat(longbuf, buf, sizeof(longbuf));
433         else if (!strncasecmp("From: ", buf, 6)
434                     || !strncasecmp("To: ", buf, 4)
435                     || !strncasecmp("Reply-", buf, 6)
436                     || !strncasecmp("Cc: ", buf, 4)
437                     || !strncasecmp("Bcc: ", buf, 5))
438             strlcpy(longbuf, buf, sizeof(longbuf));
439         else if (longbuf[0])
440         {
441             if (verbose)
442                 fputs(longbuf, stdout);
443             parsebuf(longbuf, reply);
444             longbuf[0] = '\0';
445         }
446     }
447     if (longbuf[0])
448     {
449         if (verbose)
450             fputs(longbuf, stdout);
451         parsebuf(longbuf, reply);
452     }
453     exit(0);
454 }
455 #endif /* MAIN */
456
457 /* rfc822.c end */