-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
484 lines (419 loc) · 10.8 KB
/
main.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"text/template"
"github.com/fsnotify/fsnotify"
toml "github.com/pelletier/go-toml/v2"
)
type SiteLink struct {
Title string
Url string
}
type config struct {
SiteTitle string
HomePageLink string
HomePageTitle string
FootPrint string
BlogDir string
Ip string
Port int
OpenDirMonitor bool
SiteLinks []SiteLink
CacheTime int
LogFile string
DevMode string
}
type Article struct {
SiteTitle string
HomePageLink string
HomePageTitle string
FootPrint string
Content string
}
type Index struct {
SiteTitle string
FootPrint string
Content string
SiteLinks []SiteLink
}
var (
conf config
is_head = true
confPath = "./config.toml"
indexTemplatePath = "./tmpl/index.tmpl"
articleTemplatePath = "./tmpl/article.tmpl"
queryTemplatePath = "./tmpl/query.tmpl"
styleTemplatePath = "./tmpl/style.tmpl"
query_file = "query.data"
forbidden_files = make(map[string]bool)
root_dir, _ = filepath.Abs("./")
)
func base_log(msg string) {
if conf.DevMode == "debug" {
fmt.Println(msg)
}
log.Println(msg)
}
func info_log(format string, v ... any) {
msg := "[INFO] " + fmt.Sprintf(format, v...)
base_log(msg)
}
func warn_log(format string, v ...any) {
msg := "[WARN] " + fmt.Sprintf(format, v...)
base_log(msg)
}
func err_log(format string, v ...any) {
msg := "[ERROR] " + fmt.Sprintf(format, v...)
base_log(msg)
}
// 加载 toml 配置
func loadConfig() bool {
data, err := os.ReadFile(confPath)
if err != nil {
err_log("read config file failed. file path is %s", confPath)
return false
}
err = toml.Unmarshal(data, &conf)
if err != nil {
err_log("config.toml's content is error, %s", err)
return false
}
// forbidden visit files
forbidden_files["./directory_monitor.sh"] = true
forbidden_files["./genindex.py"] = true
forbidden_files["./main.go"] = true
forbidden_files["./config.toml"] = true
forbidden_files["./genindex.sh"] = true
forbidden_files["./run.sh"] = true
forbidden_files["./mssws_prog"] = true
forbidden_files[conf.LogFile] = true
return true
}
// 将目录及其子目录加入 fsnotify Watch
// fsnotify 默认不会监测子目录
func watchSubDir(watcher *fsnotify.Watcher, dir string) {
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
path, err := filepath.Abs(path)
if err != nil {
err_log("get abs path failed, err:%v", err)
return err
}
if err := watcher.Add(path); err != nil {
err_log("watch path failed, path:%s, err:%v", path, err)
return err
}
}
return nil
})
}
// 文件监控
func dirMonitor() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
err_log("NewWatcher failed, err:%v", err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
defer close(done)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
info_log("run bash genindex.sh, event name:%s event op:%s", event.Name, event.Op)
cmd := exec.Command("bash", "./genindex.sh")
if err := cmd.Run(); err != nil {
err_log("run genindex.sh failed, err:%v", err)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
err_log("watcher err:%v", err)
}
}
}()
watchSubDir(watcher, conf.BlogDir)
<-done
}
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
func IsFile(path string) bool {
return !IsDir(path)
}
// strings.Split 函数切割数组后可能会出现空字符串,违反直觉,这个函数用来去掉空字符串
func Split(s string, sep string) []string {
tmp := strings.Split(s, sep)
res := make([]string, 0)
for _, k := range tmp {
if k != "" {
res = append(res, k)
}
}
return res
}
func GetContentType(suffix string) string {
switch suffix {
case "html":
return "text/html;charset=utf-8"
case "xml":
return "application/rss+xml;charset=utf-8"
case "ico":
return "image/x-icon"
case "js":
return "application/x-javascript"
case "css":
return "text/css"
case "pdf":
return "application/pdf"
case "png":
return "application/x-png"
case "svg":
return "image/svg+xml"
case "ttf":
return "application/x-font-truetype"
case "woff", "woff2":
return "application/x-font-woff"
default:
return "text/html;charset=utf-8"
}
}
func query_single_file(filepath string, query_str string) bool {
if filepath == "" {
err_log("query filepath is empty, filepath:%s, quert_str:%s", filepath, query_str)
return false
}
if ok := IsFile(filepath); !ok {
err_log("query path is not file, filepath:%s, query_str:%s", filepath, query_str)
return false
}
os_cmd := exec.Command("grep", query_str, filepath)
// create command stdout pipe
stdout, err := os_cmd.StdoutPipe()
if err != nil {
err_log("create pipe failed, filepath:%s, query_str:%s, err:%v", filepath, query_str, err)
return false
}
// run command
if err := os_cmd.Start(); err != nil {
err_log("execute cmd failed, filepath:%s, query_str:%s, err:%v", filepath, query_str, err)
return false
}
// read command output
bytes, err := io.ReadAll(stdout)
if err != nil {
return false
}
out_str := strings.TrimSpace(string(bytes))
if out_str == "" {
return false
} else {
return true
}
}
func query(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
info_log("query string is:%s", r.Form["search"])
if len(r.Form["search"]) == 0 {
w.Write([]byte("query string is empty."))
return
}
query_str := r.Form["search"][0]
if query_str == "" {
err_log("query string is empty")
w.Write([]byte("query string is empty."))
return
}
f_query, err := os.Open(query_file)
if err != nil {
err_log("query open file failed, query_str:%s, query_file:%s", query_str, query_file)
w.Write([]byte("open query file error."))
return
}
defer f_query.Close()
var return_lines []string
br := bufio.NewReader(f_query)
for {
line, _, c := br.ReadLine()
if c == io.EOF {
break
}
if ok := query_single_file(string(line), query_str); ok {
str := fmt.Sprintf("<a href=\"%s\">%s</a></br>", line, line)
return_lines = append(return_lines, str)
}
}
var buffer bytes.Buffer
for _, s := range return_lines {
buffer.WriteString(s)
}
temp, err := template.ParseFiles(queryTemplatePath, styleTemplatePath)
if err != nil {
err_log("load query template failed, quertTemplatePath:%s, stypeTemplatePath:%s",
queryTemplatePath, styleTemplatePath)
w.Write([]byte("load query template file failed."))
return
}
article := Article{
SiteTitle: "",
HomePageLink: conf.HomePageLink,
HomePageTitle: conf.HomePageTitle,
FootPrint: "",
Content: buffer.String(),
}
temp.Execute(w, article)
}
func indexPage(w http.ResponseWriter, _ *http.Request) {
content, err := os.ReadFile("index.data")
if err != nil {
err_log("open index.data failed")
w.Write([]byte("Sorry, Index Page Not Exist."))
return
}
content_type := GetContentType("html")
w.Header().Set("Content-Type", content_type)
temp, err := template.ParseFiles(indexTemplatePath, styleTemplatePath)
if err != nil {
err_log("load index template failed, quertTemplatePath:%s, stypeTemplatePath:%s",
queryTemplatePath, styleTemplatePath)
w.Write([]byte("load index template file failed."))
return
}
index := Index{
SiteTitle: conf.SiteTitle,
FootPrint: conf.FootPrint,
Content: string(content),
SiteLinks: conf.SiteLinks,
}
temp.Execute(w, index)
}
func index(w http.ResponseWriter, r *http.Request) {
url, err := url.PathUnescape(r.URL.Path)
if err != nil {
err_log("url decode failed, path:%s, err:%v", r.URL.Path, err)
w.Write([]byte("url decode error."))
return
}
if url == "/" || url == "" || strings.ToLower(url) == "/index.html" {
indexPage(w, r)
return
}
url = strings.TrimSpace(url)
filePath := fmt.Sprintf(".%s", url)
info_log("visit file:%s", filePath)
if _, ok := forbidden_files[filePath]; ok {
w.Write([]byte("try to visit forbieedn file."))
return
}
real_path, err := filepath.Abs(filePath)
if err != nil {
w.Write([]byte("invalid link."))
return
}
if !strings.HasPrefix(real_path, root_dir) {
w.Write([]byte("try visit invalid directory."))
return
}
if strings.HasPrefix(real_path, root_dir+"/.git") {
w.Write([]byte("try to visit forbidden directories."))
return
}
if ok := IsFile(filePath); !ok {
w.Write([]byte("[404] file not exist."))
return
}
suffix := ""
if split_list := Split(filePath, "."); len(split_list) > 1 {
suffix = split_list[len(split_list)-1]
}
content_type := GetContentType(suffix)
w.Header().Set("Content-Type", content_type)
if conf.CacheTime > 0 {
if suffix == "js" || suffix == "css" || suffix == "ico" {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.CacheTime))
}
}
// markdown file
if suffix == "md" {
temp, err := template.ParseFiles(articleTemplatePath, styleTemplatePath)
if err != nil {
err_log("load article template failed, quertTemplatePath:%s, stypeTemplatePath:%s",
queryTemplatePath, styleTemplatePath)
w.Write([]byte("load article template file failed."))
return
}
content, err := os.ReadFile(filePath)
articleName := path.Base(filePath)
article := Article{
SiteTitle: articleName,
HomePageLink: conf.HomePageLink,
HomePageTitle: conf.HomePageTitle,
FootPrint: conf.FootPrint,
Content: string(content),
}
temp.Execute(w, article)
} else {
content, err := os.ReadFile(filePath)
if err != nil {
warn_log("try to visit unexist file:%s", filePath)
w.Write([]byte("404 file not exist."))
return
}
w.Write(content)
}
}
func main() {
loadConfig()
info_log("mssws starting...")
// init log
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log_file, err := os.OpenFile(conf.LogFile, os.O_WRONLY | os.O_APPEND | os.O_CREATE, 0644)
if err != nil {
err_log("open log file failed, file=%s, err=%v", conf.LogFile, err)
os.Exit(1)
}
log.SetOutput(log_file)
info_log("create logger success")
if conf.OpenDirMonitor == true {
go dirMonitor()
}
http.HandleFunc("/", index)
http.HandleFunc("/query", query)
ip_port := conf.Ip + ":" + strconv.Itoa(conf.Port)
info_log(fmt.Sprintf("mssws start listen and serve in %s...", ip_port))
err = http.ListenAndServe(ip_port, nil)
if err != nil {
err_log("listen and serve failed, err=%v", err)
os.Exit(1)
}
}