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
use combine::{eof, many, many1, Parser};
use combine::{choice, position};
use combine::combinator::{opaque, no_partial, FnOpaque};
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 access;
use core;
use gzip;
use headers;
use proxy;
use rewrite;
use log;
use real_ip;


pub enum Code {
    Redirect(u32),
    Normal(u32),
}

pub fn bool<'a>() -> impl Parser<Output=bool, Input=TokenStream<'a>> {
    choice((
        ident("on").map(|_| true),
        ident("off").map(|_| false),
    ))
}

pub fn value<'a>() -> impl Parser<Output=Value, Input=TokenStream<'a>> {
    (position(), string())
    .and_then(|(p, v)| Value::parse(p, v))
}

pub fn worker_processes<'a>()
    -> impl Parser<Output=Item, Input=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)
}

pub fn server_name<'a>() -> impl Parser<Output=Item, Input=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)
}


pub fn map<'a>() -> impl Parser<Output=Item, Input=TokenStream<'a>> {
    use tokenizer::Kind::{BlockStart, BlockEnd};
    use helpers::kind;
    enum Tok {
        Hostnames,
        Volatile,
        Pattern(String, Value),
        Default(Value),
        Include(String),
    }
    ident("map")
    .with(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(value()).map(|v| Tok::Default(v)),
        ident("include").with(raw()).map(|v| Tok::Include(v)),
        raw().and(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)
    })
}

pub fn block<'a>()
    -> FnOpaque<TokenStream<'a>, ((Pos, Pos), Vec<Directive>)>
{
    use tokenizer::Kind::{BlockStart, BlockEnd};
    use helpers::kind;
    opaque(|f| {
        f(&mut no_partial((
                position(),
                kind(BlockStart)
                    .with(many(directive()))
                    .skip(kind(BlockEnd)),
                position(),
        ))
        .map(|(s, dirs, e)| ((s, e), dirs)))
    })
}

// A string that forbids variables
pub fn raw<'a>() -> impl Parser<Output=String, Input=TokenStream<'a>> {
    // TODO(tailhook) unquote single and double quotes
    // error on variables?
    string().and_then(|t| Ok::<_, Error<_, _>>(t.value.to_string()))
}

pub fn location<'a>() -> impl Parser<Output=Item, Input=TokenStream<'a>> {
    use ast::LocationPattern::*;
    ident("location").with(choice((
        text("=").with(raw().map(Exact)),
        text("^~").with(raw().map(FinalPrefix)),
        text("~").with(raw().map(Regex)),
        text("~*").with(raw().map(RegexInsensitive)),
        raw()
            .map(|v| if v.starts_with('*') {
                Named(v)
            } else {
                Prefix(v)
            }),
    ))).and(block())
    .map(|(pattern, (position, directives))| {
        Item::Location(ast::Location { pattern, position, directives })
    })
}

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>() -> impl Parser<Output=Item, Input=TokenStream<'a>> {
    use ast::TryFilesLastOption::*;
    use ast::Item::TryFiles;
    use value::Item::*;

    ident("try_files")
    .with(many1(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,
        }))
    })
}


pub fn openresty<'a>() -> impl Parser<Output=Item, Input=TokenStream<'a>> {
    use ast::Item::*;
    choice((
        ident("rewrite_by_lua_file").with(value()).skip(semi())
            .map(Item::RewriteByLuaFile),
        ident("balancer_by_lua_file").with(value()).skip(semi())
            .map(BalancerByLuaFile),
        ident("access_by_lua_file").with(value()).skip(semi())
            .map(AccessByLuaFile),
        ident("header_filter_by_lua_file").with(value()).skip(semi())
            .map(HeaderFilterByLuaFile),
        ident("content_by_lua_file").with(value()).skip(semi())
            .map(ContentByLuaFile),
        ident("body_filter_by_lua_file").with(value()).skip(semi())
            .map(BodyFilterByLuaFile),
        ident("log_by_lua_file").with(value()).skip(semi())
            .map(LogByLuaFile),
        ident("lua_need_request_body").with(value()).skip(semi())
            .map(LuaNeedRequestBody),
        ident("ssl_certificate_by_lua_file").with(value()).skip(semi())
            .map(SslCertificateByLuaFile),
        ident("ssl_session_fetch_by_lua_file").with(value()).skip(semi())
            .map(SslSessionFetchByLuaFile),
        ident("ssl_session_store_by_lua_file").with(value()).skip(semi())
            .map(SslSessionStoreByLuaFile),
    ))
}

pub fn directive<'a>() -> impl Parser<Output=Directive, Input=TokenStream<'a>>
{
    position()
    .and(choice((
        ident("daemon").with(bool()).skip(semi())
            .map(Item::Daemon),
        ident("master_process").with(bool()).skip(semi())
            .map(Item::MasterProcess),
        worker_processes(),
        ident("http").with(block())
            .map(|(position, directives)| ast::Http { position, directives })
            .map(Item::Http),
        ident("server").with(block())
            .map(|(position, directives)| ast::Server { position, directives })
            .map(Item::Server),
        rewrite::directives(),
        try_files(),
        ident("include").with(value()).skip(semi()).map(Item::Include),
        ident("ssl_certificate").with(value()).skip(semi())
            .map(Item::SslCertificate),
        ident("ssl_certificate_key").with(value()).skip(semi())
            .map(Item::SslCertificateKey),
        location(),
        headers::directives(),
        server_name(),
        map(),
        ident("client_max_body_size").with(value()).skip(semi())
            .map(Item::ClientMaxBodySize),
        proxy::directives(),
        gzip::directives(),
        core::directives(),
        access::directives(),
        log::directives(),
        real_ip::directives(),
        openresty(),
        // it's own module
        ident("empty_gif").skip(semi()).map(|_| Item::EmptyGif),
        ident("index").with(many(value())).skip(semi())
            .map(Item::Index),
    )))
    .map(|(pos, dir)| Directive {
        position: pos,
        item: dir,
    })
}


/// Parses a piece of config in "main" context (i.e. top-level)
///
/// Currently, this is the same as parse_directives (except wraps everyting
/// to a `Main` struct), but we expect to
/// add validation/context checks in this function.
pub fn parse_main(s: &str) -> Result<Main, ParseError> {
    parse_directives(s).map(|directives| Main { directives })
}

/// Parses a piece of config from arbitrary context
///
/// This implies no validation of what context directives belong to.
pub fn parse_directives(s: &str) -> Result<Vec<Directive>, ParseError> {
    let mut tokens = TokenStream::new(s);
    let (doc, _) = many1(directive())
        .skip(eof())
        .parse_stream(&mut tokens)
        .map_err(|e| e.into_inner().error)?;
    Ok(doc)
}