package main import errors fmt github com slasyz panda handle bufio io

  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
package main
import (
"errors"
"fmt"
//"github.com/slasyz/panda/handle"
"bufio"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
//"strings"
)
// HandleFunc is handler function for HTTP request type
type HandleFunc func(request http.Request) (response http.Response)
type SizeParameter int
// GlobalParameters is variable containing all panda parameters
var GlobalParameters struct {
Listen []int
User string
AccessLogger *log.Logger
ErrorLogger *log.Logger
PathToTPL string
Servers []*Server
}
var OpenedFiles map[string]*log.Logger
// Server is type containing each server parameters
type Server struct {
IP string
Port int
Hostname string
Type string
Handler HandleFunc
}
// configError is type containing config error (Captain Obvious at your
// service)
type configError struct {
fileName string
lineNumber int
message string
}
func (err *configError) Error() string {
return fmt.Sprintf("%s:%d: %s", err.fileName, err.lineNumber, err.message)
}
var lineContentRegexp *regexp.Regexp
var virtualHostRegexp *regexp.Regexp
var fieldRegexp *regexp.Regexp
var commandRegexp *regexp.Regexp
var integerRegexp *regexp.Regexp
var sizeRegexp *regexp.Regexp
func getRegexpSubmatches(reg *regexp.Regexp, names []string, s string) (submatches []string) {
index := reg.FindStringSubmatchIndex(s)
submatches = make([]string, len(names), len(names))
for i, name := range names {
submatches[i] = string(reg.ExpandString([]byte{}, "$"+name, s, index))
}
return
}
func openLogFile(fileName string) (logger *log.Logger, err error) {
logger, ok := OpenedFiles[fileName]
if ok {
return
} else {
file, err := os.Open(fileName)
if err != nil {
err = errors.New("cannot open file " + fileName)
}
logger = log.New(file, "", log.LstdFlags)
}
return
}
func getTypeName(typ string) string {
switch typ {
case "**log.Logger":
return "a string"
case "*string":
return "a string"
case "*int":
return "an integer"
case "*bool":
return "true or false"
case "*SizeParameter":
return "data size, e.g. 1000B, 100KB, 10MB, 1GB"
default:
return typ
}
}
func setConfigValue(name string, sign string, value string, configVariable interface{}, currentFile string) (err error) {
var neededType string
var resultValue interface{}
if integerRegexp.MatchString(value) {
switch t := configVariable.(type) {
case *int, *[]int:
resultValue, _ = strconv.Atoi(value)
default:
neededType = fmt.Sprintf("%T", t)
}
} else if sizeRegexp.MatchString(value) {
submatches := getRegexpSubmatches(sizeRegexp, []string{"value", "unit"}, value)
resultValue, _ := strconv.Atoi(submatches[0])
unit := submatches[1]
factor := 1
switch unit {
case "GB":
factor *= 1024
fallthrough
case "MB":
factor *= 1024
fallthrough
case "KB":
factor *= 1024
}
switch t := configVariable.(type) {
case *int, *[]int, *SizeParameter:
resultValue *= factor
default:
neededType = fmt.Sprintf("%T", t)
}
} else if value[0] == '"' && value[len(value)-1] == '"' {
stringValue := value[1 : len(value)-1] // remove the quotes
switch t := configVariable.(type) {
case *string, *[]string:
resultValue = stringValue
case **log.Logger:
abspath, _ := filepath.Abs(filepath.Join(filepath.Dir(currentFile), stringValue))
resultValue, err = openLogFile(abspath)
if err != nil {
return
}
default:
neededType = fmt.Sprintf("%T", t)
}
} else if value == "true" {
switch t := configVariable.(type) {
case bool:
resultValue = true
default:
neededType = fmt.Sprintf("%T", t)
}
} else if value == "false" {
switch t := configVariable.(type) {
case bool:
resultValue = false
default:
neededType = fmt.Sprintf("%T", t)
}
}
if sign == "=" {
switch configVariable.(type) {
case *int, *string, *bool, **log.Logger:
configVariable = resultValue
default:
err = errors.New("you can only append to this type (must be \"+=\" instead of \"=\"")
return
}
} else if sign == "+=" {
switch configVariable.(type) {
case *[]int:
configVariable = append(*configVariable.(*[]int), resultValue.(int))
case *[]string:
configVariable = append(*configVariable.(*[]string), resultValue.(string))
default:
err = errors.New("you can only assign to this type (must be \"=\" instead of \"+=\"")
return
}
}
if neededType != "" {
err = errors.New("wrong type of " + name + " field: it must be " + neededType)
}
return
}
func parseGlobalParameter(name, sign, value, currentFile string) (err error) {
switch name {
case "User":
err = setConfigValue(name, sign, value, &GlobalParameters.User, currentFile)
case "Listen":
err = setConfigValue(name, sign, value, &GlobalParameters.Listen, currentFile)
case "AccessLog":
err = setConfigValue(name, sign, value, &GlobalParameters.AccessLogger, currentFile)
}
return
}
func parseServerParameter(name, sign, value string, serverNumber int, currentFileName string) (err error) {
return
}
func parseConfig(file io.Reader, currentFileName string, currentServer *int) (errs []configError) {
scanner := bufio.NewScanner(file)
currentLineNumber := 0
for scanner.Scan() {
currentLineNumber++
currentLine := scanner.Text()
if !lineContentRegexp.MatchString(currentLine) {
errs = append(errs, configError{currentFileName, currentLineNumber, "syntax error (unpaired quotation mark?)"})
}
currentLine = getRegexpSubmatches(lineContentRegexp, []string{"content"}, currentLine)[0]
switch {
case currentLine == "":
continue
case virtualHostRegexp.MatchString(currentLine):
submatches := getRegexpSubmatches(virtualHostRegexp, []string{"ip", "port"}, currentLine)
ip := submatches[0]
port := submatches[1]
// TODO
Debug("%s:%d: found new virtualhost with IP %s and port %s", currentFileName, currentLineNumber, ip, port)
case fieldRegexp.MatchString(currentLine):
submatches := getRegexpSubmatches(fieldRegexp, []string{"name", "sign", "value"}, currentLine)
name := submatches[0]
sign := submatches[1]
value := submatches[2]
Debug("%s:%d: found field %s with value %s", currentFileName, currentLineNumber, name, value)
var err error
if *currentServer == -1 {
err = parseGlobalParameter(name, sign, value, currentFileName)
} else {
err = parseServerParameter(name, sign, value, *currentServer, currentFileName)
}
if err != nil {
errs = append(errs, configError{currentFileName, currentLineNumber, err.Error()})
}
case commandRegexp.MatchString(currentLine):
submatches := getRegexpSubmatches(commandRegexp, []string{"command", "argument"}, currentLine)
command := submatches[0]
argument := submatches[1]
if command == "include" {
includedFileName := filepath.Join(filepath.Dir(currentFileName), argument)
includedFile, err := os.Open(includedFileName)
if err != nil {
errs = append(errs, configError{currentFileName, currentLineNumber, "file " + includedFileName + " can not be open"})
}
Debug("%s:%d: enter the file %s", currentFileName, currentLineNumber, includedFileName)
errs = append(errs, parseConfig(includedFile, includedFileName, currentServer)...)
} else if command == "include_dir" {
// TODO
}
default:
errs = append(errs, configError{currentFileName, currentLineNumber, "wrong line format"})
}
}
return
}
func ParseConfigStart(fileName string) (errs []error) {
file, err := os.Open(fileName)
if err != nil {
return []error{errors.New(fmt.Sprintf("Cannot read config file %s (%s)", fileName, err))}
}
defer file.Close()
// Compile the regexps once
lineContentRegexp = regexp.MustCompile(`^\s*` +
`(?P<content>(("[^"]*")|([^"]))*?)` +
`\s*(\/\/.*)?\s*$`)
virtualHostRegexp = regexp.MustCompile(`^` +
`\[VirtualHost\s*\"` +
`(?P<ip>[^"]+)` +
`:` +
`(?P<port>[^":]+)` +
`\"\]` +
`$`)
fieldRegexp = regexp.MustCompile(`^` +
`(?P<name>[a-zA-Z0-9_]+)` +
`\s*` +
`(?P<sign>\+?=)` +
`\s*` +
`(?P<value>\"[^"]*\"|\d+(B|KB|MB|GB)?|true|false)` + // string, integer or bool fields
`$`)
commandRegexp = regexp.MustCompile(`^` +
`(?P<command>\w+)` +
`\(` +
`(?P<argument>[^)]*)` +
`\)$`)
integerRegexp = regexp.MustCompile(`^\d+$`)
sizeRegexp = regexp.MustCompile(`^(?P<value>\d+)(?P<unit>B|KB|MB|GB)`)
currentServer := -1
configErrors := parseConfig(file, fileName, &currentServer)
if len(configErrors) != 0 {
errs = make([]error, len(configErrors), len(configErrors))
for i, err := range configErrors {
errs[i] = errors.New(err.Error())
}
}
return
// and join several errors into one
}