pg: forwarding messages
[neatmail.git] / msg.c
blobb433704f8d3e0af002f9fb70c8d85a5338d13883
1 #include <ctype.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "mail.h"
6 static char *hdrnext(char *s, char *e)
8 char *r;
9 while (s + 1 < e && s[0] != '\n' && (s[0] != '\r' || s[1] != '\n')) {
10 if (!(r = memchr(s, '\n', e - s - 1)))
11 return NULL;
12 if (isalpha((unsigned char) r[1]))
13 return r + 1;
14 s = r + 1;
16 return NULL;
19 /* return 1 if r starts with s */
20 int startswith(char *r, char *s)
22 while (*s)
23 if (tolower((unsigned char) *s++) != tolower((unsigned char) *r++))
24 return 0;
25 return 1;
28 char *msg_get(char *msg, long msz, char *hdr)
30 char *s = msg;
31 char *e = msg + msz;
32 while (s && s < e) {
33 if (startswith(s, hdr))
34 return s;
35 s = hdrnext(s, e);
37 return NULL;
40 int msg_set(char *msg, long msz, char **mod, long *modlen, char *hdr, char *val)
42 char *h = msg_get(msg, msz, hdr);
43 int off;
44 int hlen = h ? hdrlen(h, msg + msz - h) : 0;
45 int vlen = strlen(val);
46 if (!h) {
47 h = msg;
48 while (hdrnext(h, msg + msz))
49 h = hdrnext(h, msg + msz);
50 h = h + hdrlen(h, msg + msz - h);
52 off = h - msg;
53 *modlen = msz - hlen + vlen;
54 *mod = malloc(*modlen + 1);
55 if (!*mod)
56 return 1;
57 memcpy(*mod, msg, off);
58 memcpy(*mod + off, val, vlen);
59 memcpy(*mod + off + vlen, msg + off + hlen, msz - off - hlen + 1);
60 (*mod)[*modlen] = '\0';
61 return 0;
64 int hdrlen(char *hdr, long len)
66 char *r, *s = hdr;
67 do {
68 if (!(r = strchr(s, '\n')))
69 return strchr(s, '\0') - hdr;
70 s = r + 1;
71 } while (s[0] && (s[0] == ' ' || s[0] == '\t'));
72 return s - hdr;