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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
|
#include "common.h"
enum {
Buffersize = 64*1024,
};
typedef struct Inbuf Inbuf;
struct Inbuf
{
char buf[Buffersize];
char *wp;
char *rp;
int eof;
int in;
int out;
int last;
ulong bytes;
};
static Inbuf*
allocinbuf(int in, int out)
{
Inbuf *b;
b = mallocz(sizeof(Inbuf), 1);
if(b == nil)
sysfatal("reading mailbox: %r");
b->rp = b->wp = b->buf;
b->in = in;
b->out = out;
return b;
}
/* should only be called at start of file or when b->rp[-1] == '\n' */
static int
fill(Inbuf *b, int addspace)
{
int i, n;
if(b->eof && b->wp - b->rp == 0)
return 0;
n = b->rp - b->buf;
if(n > 0){
i = write(b->out, b->buf, n);
if(i != n)
return -1;
b->last = b->buf[n-1];
b->bytes += n;
}
if(addspace){
if(write(b->out, " ", 1) != 1)
return -1;
b->last = ' ';
b->bytes++;
}
n = b->wp - b->rp;
memmove(b->buf, b->rp, n);
b->rp = b->buf;
b->wp = b->rp + n;
i = read(b->in, b->buf+n, sizeof(b->buf)-n);
if(i < 0)
return -1;
b->wp += i;
return b->wp - b->rp;
}
enum { Fromlen = sizeof "From " - 1, };
/* code to escape ' '*From' ' at the beginning of a line */
int
appendfiletombox(int in, int out)
{
int addspace, n, sol;
char *p;
Inbuf *b;
seek(out, 0, 2);
b = allocinbuf(in, out);
addspace = 0;
sol = 1;
for(;;){
if(b->wp - b->rp < Fromlen){
/*
* not enough unread bytes in buffer to match "From ",
* so get some more. We must only inject a space at
* the start of a line (one that begins with "From ").
*/
if (b->rp == b->buf || b->rp[-1] == '\n') {
n = fill(b, addspace);
addspace = 0;
} else
n = fill(b, 0);
if(n < 0)
goto error;
if(n == 0)
break;
if(n < Fromlen){ /* still can't match? */
b->rp = b->wp;
continue;
}
}
/* state machine looking for ' '*From' ' */
if(!sol){
p = memchr(b->rp, '\n', b->wp - b->rp);
if(p == nil)
b->rp = b->wp;
else{
b->rp = p+1;
sol = 1;
}
continue;
} else {
if(*b->rp == ' ' || strncmp(b->rp, "From ", Fromlen) != 0){
b->rp++;
continue;
}
addspace = 1;
sol = 0;
}
}
/* mailbox entries always terminate with two newlines */
n = b->last == '\n' ? 1 : 2;
if(write(out, "\n\n", n) != n)
goto error;
n += b->bytes;
free(b);
return n;
error:
free(b);
return -1;
}
int
appendfiletofile(int in, int out)
{
int n;
Inbuf *b;
seek(out, 0, 2);
b = allocinbuf(in, out);
for(;;){
n = fill(b, 0);
if(n < 0)
goto error;
if(n == 0)
break;
b->rp = b->wp;
}
n = b->bytes;
free(b);
return n;
error:
free(b);
return -1;
}
|