-
Notifications
You must be signed in to change notification settings - Fork 23
/
parse.go
347 lines (309 loc) · 9.46 KB
/
parse.go
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
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nginxconf
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
which "github.com/hairyhenderson/go-which"
)
// Reference: https://wiki.debian.org/Nginx/DirectoryStructure
var nginxConfPrefix string
func init() {
switch runtime.GOOS {
case "freebsd", "darwin":
// https://www.cyberciti.biz/faq/freebsd-install-nginx-webserver/
nginxConfPrefix = "/usr/local/etc/nginx"
case "netbsd":
// https://www.netbsd.mx/nginx-php.html
nginxConfPrefix = "/usr/pkg/etc/nginx"
case "solaris", "illumos":
// https://www.nginx.com/resources/wiki/start/topics/tutorials/solaris_11/
nginxConfPrefix = "/opt/local/nginx"
for k, v := range nginxConfDirs {
if v == "conf.d/" {
nginxConfDirs[k] = "conf/"
}
}
case "windows":
// "nginx/Windows uses the directory where it has been run as the prefix for relative paths in the configuration."
// Source: https://nginx.org/en/docs/windows.html
// However, the "conf/" directory, where some of the standard snippets live, is neighboring the nginx.exe. Therefore,
// it's more likely to hit a match in this root than elsewhere.
nginxPath := which.Which("nginx.exe")
nginxConfPrefix = filepath.Dir(nginxPath)
for k, v := range nginxConfDirs {
if v == "conf.d/" {
nginxConfDirs[k] = "conf/"
}
}
default:
nginxConfPrefix = "/etc/nginx"
}
}
func parse(tokens []token) ([]Directive, error) {
parser := nginxParser{tokens: tokens}
return parser.nextBlock()
}
type nginxParser struct {
tokens []token
cursor int // incrementing this is analogous to consuming the token
}
func (p *nginxParser) currentToken() token {
return p.tokens[p.cursor]
}
// nextBlock returns the next block of directives.
func (p *nginxParser) nextBlock() ([]Directive, error) {
var dirs []Directive
for {
// if we've reached end of input (main context)
// or the end of current block, we're done
if p.cursor >= len(p.tokens) {
break
}
if p.tokens[p.cursor].text == "}" {
p.cursor++
break
}
dir, err := p.next()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
dirs = append(dirs, dir)
}
return dirs, nil
}
// next returns the next directive.
func (p *nginxParser) next() (Directive, error) {
if p.cursor == len(p.tokens) {
return Directive{}, io.EOF
}
dir := Directive{
File: p.tokens[p.cursor].file,
Line: p.tokens[p.cursor].line,
}
for ; p.cursor < len(p.tokens); p.cursor++ {
tkn := p.tokens[p.cursor]
if tkn.text == ";" {
p.cursor++
break
}
if tkn.text == "{" {
p.cursor++
dirs, err := p.nextBlock()
if err != nil {
return Directive{}, err
}
dir.Block = dirs
break
}
if tkn.text == "include" {
p.cursor++
err := p.doInclude()
if err != nil {
return Directive{}, err
}
tkn = p.tokens[p.cursor]
dir.File = tkn.file
dir.Line = tkn.line
}
dir.Params = append(dir.Params, tkn.text)
}
return dir, nil
}
var nginxConfDirs = []string{
"conf.d/",
"modules-available/",
"modules-enabled/",
"sites-available/",
"sites-enabled/",
"snippets/",
}
var nginxStdConfs = []string{
"fastcgi.conf",
"fastcgi_params",
"koi-utf",
"koi-win",
"mime.types",
"nginx.conf",
"proxy_params",
"scgi_params",
"uwsgi_params",
"win-utf",
}
// TODO: support relative path includes
func (p *nginxParser) doInclude() error {
includeToken := p.currentToken()
includeArg := filepath.Clean(includeToken.text)
if strings.Count(includeArg, "*") > 1 || strings.Count(includeArg, "?") > 1 ||
(strings.Contains(includeArg, "[") && strings.Contains(includeArg, "]")) {
// See issue #2096 - a pattern with many glob expansions can hang for too long
return fmt.Errorf("Glob pattern may only contain one wildcard (*), but has others: %s", includeArg)
}
// first assume the included file is relative
var importedFiles []string
globArg := includeArg
if !filepath.IsAbs(includeArg) {
currentConfDir := filepath.Dir(p.currentToken().file)
globArg = filepath.Join(currentConfDir, includeArg)
}
matches, err := filepath.Glob(globArg)
if err != nil {
return err
}
for _, v := range matches {
if _, err := os.Stat(v); !os.IsNotExist(err) {
importedFiles = append(importedFiles, v)
}
}
// if not absolute, we'll only support including files within standard config location.
if len(importedFiles) == 0 {
// is it one of the standard files?
for _, v := range nginxStdConfs {
if v == includeArg {
importedFiles = append(importedFiles, filepath.Join(nginxConfPrefix, v))
break
}
}
}
if len(importedFiles) == 0 {
// by here it is not one of the direct descendant files of /etc/nginx/.
// Is it in one of the subdirectories?
//
// The `filepath.HasPrefix` is bad before it just does `strings.HasPrefix` and
// doesn't respoect directories boundaries.
for _, v := range nginxConfDirs {
testablePath := filepath.Join(nginxConfPrefix, v, includeArg)
// The argument could have a glob (e.g. custom-*.conf), so expand the glob.
matches, err := filepath.Glob(filepath.Clean(testablePath))
if err != nil {
return err // this is bad glob pattern, so nothing can be done except return
}
importedFiles = append(importedFiles, matches...)
}
}
if len(importedFiles) == 0 {
return fmt.Errorf("included file is not found: %s:%d %s", includeToken.file, includeToken.line, includeArg)
}
var importedTokens []token
for _, importFile := range importedFiles {
newTokens, err := p.doSingleInclude(importFile)
if err != nil {
return err
}
importedTokens = append(importedTokens, newTokens...)
}
// splice out the import directive and its argument (2 tokens total)
tokensBefore := p.tokens[:p.cursor-1]
tokensAfter := p.tokens[p.cursor+2:]
// splice the imported tokens in the place of the import statement
// and rewind cursor so Next() will land on first imported token
p.tokens = append(tokensBefore, append(importedTokens, tokensAfter...)...)
p.cursor--
return nil
}
// doSingleImport lexes the individual file at importFile and returns
// its tokens or an error, if any.
func (p *nginxParser) doSingleInclude(importFile string) ([]token, error) {
file, err := os.Open(importFile)
if err != nil {
return nil, fmt.Errorf("Could not import %s: %v", importFile, err)
}
defer file.Close()
if info, err := file.Stat(); err != nil {
return nil, fmt.Errorf("Could not import %s: %v", importFile, err)
} else if info.IsDir() {
return nil, fmt.Errorf("Could not import %s: is a directory", importFile)
}
input, err := ioutil.ReadAll(file)
if err != nil {
return nil, fmt.Errorf("Could not read imported file %s: %v", importFile, err)
}
importedTokens := allTokens(importFile, input)
return importedTokens, nil
}
// allTokens lexes the entire input, but does not parse it.
// It returns all the tokens from the input, unstructured
// and in order.
func allTokens(filename string, input []byte) []token {
tokens := tokenize(input, filename)
for i := range tokens {
tokens[i].file = filename
}
return tokens
}
// Directive represents an nginx configuration directive.
type Directive struct {
// Params contains the name and parameters on
// the line. The first element is the name.
Params []string
// Block contains the block contents, if present.
Block []Directive
File string
Line int
}
// Name returns the value of the first parameter.
func (d Directive) Name() string {
return d.Param(0)
}
// Param returns the parameter at position idx.
func (d Directive) Param(idx int) string {
if idx < len(d.Params) {
return d.Params[idx]
}
return ""
}
func getDirective(dirs []Directive, name string) (Directive, bool) {
for _, dir := range dirs {
if dir.Name() == name {
return dir, true
}
}
return Directive{}, false
}
func getAllDirectives(dirs []Directive, name string) []Directive {
var matched []Directive
for _, dir := range dirs {
if dir.Name() == name {
matched = append(matched, dir)
}
}
return matched
}
/*
From: http://nginx.org/en/docs/beginners_guide.html
nginx consists of modules which are controlled by directives specified in the configuration file.
Directives are divided into simple directives and block directives. A simple directive consists of
the name and parameters separated by spaces and ends with a semicolon (;). A block directive has
the same structure as a simple directive, but instead of the semicolon it ends with a set of
additional instructions surrounded by braces ({ and }). If a block directive can have other
directives inside braces, it is called a context (examples: events, http, server, and location).
Directives placed in the configuration file outside of any contexts are considered to be in the main
context. The events and http directives reside in the main context, server in http, and location in
server.
The rest of a line after the # sign is considered a comment.
*/
/*
other references:
https://github.com/recoye/config
https://github.com/yangchenxing/go-nginx-conf-parser
https://www.nginx.com/resources/wiki/start/topics/examples/full/
*/