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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use combine::{eof, many, many1, ParseResult, parser, Parser};
use combine::{choice, position};
use combine::error::StreamError;
use combine::easy::Error;
use ast::{self, Main, Directive, Item};
use error::ParseError;
use helpers::{semi, ident, text, string};
use position::Pos;
use tokenizer::{TokenStream, Token};
use value::Value;
use core;
use gzip;
use headers;
use proxy;
use rewrite;
pub enum Code {
Redirect(u32),
Normal(u32),
}
pub fn bool<'a>(input: &mut TokenStream<'a>)
-> ParseResult<bool, TokenStream<'a>>
{
choice((
ident("on").map(|_| true),
ident("off").map(|_| false),
))
.parse_stream(input)
}
pub fn value<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Value, TokenStream<'a>>
{
(position(), string())
.and_then(|(p, v)| Value::parse(p, v))
.parse_stream(input)
}
pub fn worker_processes<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use ast::WorkerProcesses;
ident("worker_processes")
.with(choice((
ident("auto").map(|_| WorkerProcesses::Auto),
string().and_then(|s| s.value.parse().map(WorkerProcesses::Exact)),
)))
.skip(semi())
.map(Item::WorkerProcesses)
.parse_stream(input)
}
pub fn server_name<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use ast::ServerName::*;
ident("server_name")
.with(many1(
string().map(|t| {
if t.value.starts_with("~") {
Regex(t.value[1..].to_string())
} else if t.value.starts_with("*.") {
StarSuffix(t.value[2..].to_string())
} else if t.value.ends_with(".*") {
StarPrefix(t.value[..t.value.len()-2].to_string())
} else if t.value.starts_with(".") {
Suffix(t.value[1..].to_string())
} else {
Exact(t.value.to_string())
}
})
))
.skip(semi())
.map(Item::ServerName)
.parse_stream(input)
}
pub fn map<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use tokenizer::Kind::{BlockStart, BlockEnd};
use helpers::kind;
enum Tok {
Hostnames,
Volatile,
Pattern(String, Value),
Default(Value),
Include(String),
}
ident("map")
.with(parser(value))
.and(string().and_then(|t| {
let ch1 = t.value.chars().nth(0).unwrap_or(' ');
let ch2 = t.value.chars().nth(1).unwrap_or(' ');
if ch1 == '$' && matches!(ch2, 'a'...'z' | 'A'...'Z' | '_') &&
t.value[2..].chars()
.all(|x| matches!(x, 'a'...'z' | 'A'...'Z' | '0'...'9' | '_'))
{
Ok(t.value[1..].to_string())
} else {
Err(Error::unexpected_message("invalid variable"))
}
}))
.skip(kind(BlockStart))
.and(many(choice((
ident("hostnames").map(|_| Tok::Hostnames),
ident("volatile").map(|_| Tok::Volatile),
ident("default").with(parser(value)).map(|v| Tok::Default(v)),
ident("include").with(parser(raw)).map(|v| Tok::Include(v)),
parser(raw).and(parser(value)).map(|(s, v)| Tok::Pattern(s, v)),
)).skip(semi())))
.skip(kind(BlockEnd))
.map(|((expression, variable), vec): ((_, _), Vec<Tok>)| {
let mut res = ::ast::Map {
variable, expression,
default: None,
hostnames: false,
volatile: false,
includes: Vec::new(),
patterns: Vec::new(),
};
for val in vec {
match val {
Tok::Hostnames => res.hostnames = true,
Tok::Volatile => res.volatile = true,
Tok::Default(v) => res.default = Some(v),
Tok::Include(path) => res.includes.push(path),
Tok::Pattern(x, targ) => {
use ast::MapPattern::*;
let mut s = &x[..];
if s.starts_with('~') {
res.patterns.push((Regex(s[1..].to_string()), targ));
continue;
} else if s.starts_with('\\') {
s = &s[1..];
}
let pat = if res.hostnames {
if s.starts_with("*.") {
StarSuffix(s[2..].to_string())
} else if s.ends_with(".*") {
StarPrefix(s[..s.len()-2].to_string())
} else if s.starts_with(".") {
Suffix(s[1..].to_string())
} else {
Exact(s.to_string())
}
} else {
Exact(s.to_string())
};
res.patterns.push((pat, targ));
}
}
}
Item::Map(res)
})
.parse_stream(input)
}
pub fn block<'a>(input: &mut TokenStream<'a>)
-> ParseResult<((Pos, Pos), Vec<Directive>), TokenStream<'a>>
{
use tokenizer::Kind::{BlockStart, BlockEnd};
use helpers::kind;
(
position(),
kind(BlockStart)
.with(many(parser(directive)))
.skip(kind(BlockEnd)),
position(),
)
.map(|(s, dirs, e)| ((s, e), dirs))
.parse_stream(input)
}
pub fn raw<'a>(input: &mut TokenStream<'a>)
-> ParseResult<String, TokenStream<'a>>
{
string().and_then(|t| Ok::<_, Error<_, _>>(t.value.to_string()))
.parse_stream(input)
}
pub fn location<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use ast::LocationPattern::*;
ident("location").with(choice((
text("=").with(parser(raw).map(Exact)),
text("^~").with(parser(raw).map(FinalPrefix)),
text("~").with(parser(raw).map(Regex)),
text("~*").with(parser(raw).map(RegexInsensitive)),
parser(raw)
.map(|v| if v.starts_with('*') {
Named(v)
} else {
Prefix(v)
}),
))).and(parser(block))
.map(|(pattern, (position, directives))| {
Item::Location(ast::Location { pattern, position, directives })
})
.parse_stream(input)
}
impl Code {
pub fn parse<'x, 'y>(code_str: &'x str)
-> Result<Code, Error<Token<'y>, Token<'y>>>
{
let code = code_str.parse::<u32>()?;
match code {
301 | 302 | 303 | 307 | 308 => Ok(Code::Redirect(code)),
200...599 => Ok(Code::Normal(code)),
_ => return Err(Error::unexpected_message(
format!("invalid response code {}", code))),
}
}
pub fn as_code(&self) -> u32 {
match *self {
Code::Redirect(code) => code,
Code::Normal(code) => code,
}
}
}
pub fn try_files<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use ast::TryFilesLastOption::*;
use ast::Item::TryFiles;
use value::Item::*;
ident("try_files")
.with(many1(parser(value)))
.skip(semi())
.and_then(|mut v: Vec<_>| -> Result<_, Error<_, _>> {
let last = v.pop().unwrap();
let last = match &last.data[..] {
[Literal(x)] if x.starts_with("=") => {
Code(self::Code::parse(&x[1..])?.as_code())
}
[Literal(x)] if x.starts_with("@") => {
NamedLocation(x[1..].to_string())
}
_ => Uri(last.clone()),
};
Ok(TryFiles(::ast::TryFiles {
options: v,
last_option: last,
}))
})
.parse_stream(input)
}
pub fn openresty<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Item, TokenStream<'a>>
{
use ast::Item::*;
choice((
ident("rewrite_by_lua_file").with(parser(value)).skip(semi())
.map(Item::RewriteByLuaFile),
ident("balancer_by_lua_file").with(parser(value)).skip(semi())
.map(BalancerByLuaFile),
ident("access_by_lua_file").with(parser(value)).skip(semi())
.map(AccessByLuaFile),
ident("header_filter_by_lua_file").with(parser(value)).skip(semi())
.map(HeaderFilterByLuaFile),
ident("content_by_lua_file").with(parser(value)).skip(semi())
.map(ContentByLuaFile),
ident("body_filter_by_lua_file").with(parser(value)).skip(semi())
.map(BodyFilterByLuaFile),
ident("log_by_lua_file").with(parser(value)).skip(semi())
.map(LogByLuaFile),
ident("lua_need_request_body").with(parser(value)).skip(semi())
.map(LuaNeedRequestBody),
ident("ssl_certificate_by_lua_file").with(parser(value)).skip(semi())
.map(SslCertificateByLuaFile),
ident("ssl_session_fetch_by_lua_file").with(parser(value)).skip(semi())
.map(SslSessionFetchByLuaFile),
ident("ssl_session_store_by_lua_file").with(parser(value)).skip(semi())
.map(SslSessionStoreByLuaFile),
))
.parse_stream(input)
}
pub fn directive<'a>(input: &mut TokenStream<'a>)
-> ParseResult<Directive, TokenStream<'a>>
{
position()
.and(choice((
ident("daemon").with(parser(bool)).skip(semi())
.map(Item::Daemon),
ident("master_process").with(parser(bool)).skip(semi())
.map(Item::MasterProcess),
parser(worker_processes),
ident("http").with(parser(block))
.map(|(position, directives)| ast::Http { position, directives })
.map(Item::Http),
ident("server").with(parser(block))
.map(|(position, directives)| ast::Server { position, directives })
.map(Item::Server),
rewrite::directives(),
parser(try_files),
ident("include").with(parser(value)).skip(semi()).map(Item::Include),
ident("ssl_certificate").with(parser(value)).skip(semi())
.map(Item::SslCertificate),
ident("ssl_certificate_key").with(parser(value)).skip(semi())
.map(Item::SslCertificateKey),
parser(location),
headers::directives(),
parser(server_name),
parser(map),
ident("client_max_body_size").with(parser(value)).skip(semi())
.map(Item::ClientMaxBodySize),
parser(proxy::directives),
parser(gzip::directives),
core::directives(),
parser(openresty),
ident("empty_gif").skip(semi()).map(|_| Item::EmptyGif),
)))
.map(|(pos, dir)| Directive {
position: pos,
item: dir,
})
.parse_stream(input)
}
pub fn parse_main(s: &str) -> Result<Main, ParseError> {
parse_directives(s).map(|directives| Main { directives })
}
pub fn parse_directives(s: &str) -> Result<Vec<Directive>, ParseError> {
let mut tokens = TokenStream::new(s);
let (doc, _) = many1(parser(directive))
.skip(eof())
.parse_stream(&mut tokens)
.map_err(|e| e.into_inner().error)?;
Ok(doc)
}