summaryrefslogtreecommitdiff
path: root/src/headerbody.c
blob: 460b1a0972a76337aabc9c66731eda56d1a2cb4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "headerbody.h"

#include "getln.h"

#include "hfield.h"

static int getsa(buffer *b, stralloc *sa, int *match)
{
  if (!*match) return 0;
  if (getln(b, sa, match, '\n') == -1) return -1;
  if (*match) return 1;
  if (!sa->len) return 0;
  if (!stralloc_append(sa, "\n")) return -1;

  return 1;
}

static stralloc line = {0};
static stralloc nextline = {0};

int headerbody(buffer *b, void (*dohf)(stralloc *), void (*hdone)(void), void (*dobl)(stralloc *))
{
  int match;
  int flaglineok;
  match = 1;
  flaglineok = 0;

  for (;;) {
    switch (getsa(b, &nextline, &match)) {
      case -1: return -1;
      case 0:
        if (flaglineok) dohf(&line);
        hdone();
        /* no message body; could insert blank line here */
        return 0;
    }

    if (flaglineok) {
      if ((nextline.s[0] == ' ') || (nextline.s[0] == '\t')) {
        if (!stralloc_cat(&line, &nextline)) return -1;
        continue;
      }
      dohf(&line);
    }

    if (nextline.len == 1) {
      hdone();
      dobl(&nextline);
      break;
    }

    if (stralloc_starts(&nextline, "From ")) {
      if (!stralloc_copys(&line, "MBOX-Line: ")) return -1;
      if (!stralloc_cat(&line, &nextline)) return -1;
    } else if (hfield_valid(nextline.s, nextline.len)) {
      if (!stralloc_copy(&line, &nextline)) return -1;
    } else {
      hdone();
      if (!stralloc_copys(&line, "\n")) return -1;
      dobl(&line);
      dobl(&nextline);
      break;
    }
    flaglineok = 1;
  }

  for (;;) {
    switch (getsa(b, &nextline, &match)) {
      case -1: return -1;
      case 0:  return 0;
      case 1:  dobl(&nextline);
    }
  }
}