forked from andybalholm/redwood
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
209 lines (178 loc) · 4.68 KB
/
log.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
package main
import (
"bytes"
"crypto/md5"
"encoding/csv"
"fmt"
"log"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/baruwa-enterprise/clamd"
)
// recording pages filtered to access log
var (
accessLog CSVLog
tlsLog CSVLog
contentLog CSVLog
starlarkLog CSVLog
)
type CSVLog struct {
lock sync.Mutex
file *os.File
csv *csv.Writer
}
func (l *CSVLog) Open(filename string) {
l.lock.Lock()
defer l.lock.Unlock()
if l.file != nil && l.file != os.Stdout {
l.file.Close()
l.file = nil
}
if filename != "" {
logfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
log.Printf("Could not open log file (%s): %s\n Sending log messages to standard output instead.", filename, err)
} else {
l.file = logfile
}
}
if l.file == nil {
l.file = os.Stdout
}
l.csv = csv.NewWriter(l.file)
}
func (l *CSVLog) Log(data []string) {
l.lock.Lock()
defer l.lock.Unlock()
l.csv.Write(data)
l.csv.Flush()
}
func logAccess(req *http.Request, resp *http.Response, contentLength int64, pruned bool, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule, title string, ignored []string, clamdResponse []*clamd.Response) []string {
conf := getConfig()
modified := ""
if pruned {
modified = "pruned"
}
status := 0
if resp != nil {
status = resp.StatusCode
}
if rule.Action == "" {
rule.Action = "allow"
}
var contentType string
if resp != nil {
contentType = resp.Header.Get("Content-Type")
}
if ct2, _, err := mime.ParseMediaType(contentType); err == nil {
contentType = ct2
}
var userAgent string
if conf.LogUserAgent {
userAgent = req.Header.Get("User-Agent")
}
var clamdStatus string
if len(clamdResponse) > 0 {
r := clamdResponse[0]
if r.Signature != "" {
clamdStatus = r.Status + " " + r.Signature
} else {
clamdStatus = r.Status
}
}
if len(title) > 500 {
title = title[:500]
}
logLine := toStrings(time.Now().Format("2006-01-02 15:04:05.000000"), user, rule.Action, req.URL, req.Method, status, contentType, contentLength, modified, listTally(stringTally(tally)), listTally(scores), rule.Conditions(), title, strings.Join(ignored, ","), userAgent, req.Proto, req.Referer(), platform(req.Header.Get("User-Agent")), downloadedFilename(resp), clamdStatus, rule.Description)
accessLog.Log(logLine)
return logLine
}
func downloadedFilename(resp *http.Response) string {
if resp == nil {
return ""
}
disposition := resp.Header.Get("Content-Disposition")
if disposition == "" {
return ""
}
_, params, err := mime.ParseMediaType(disposition)
if err != nil {
return ""
}
return params["filename"]
}
func logTLS(user, serverAddr, serverName string, err error, cachedCert bool, tlsFingerprint string) {
errStr := ""
if err != nil {
errStr = err.Error()
}
cached := ""
if cachedCert {
cached = "cached certificate"
}
tlsLog.Log(toStrings(time.Now().Format("2006-01-02 15:04:05.000000"), user, serverName, serverAddr, errStr, cached, tlsFingerprint))
}
func logContent(u *url.URL, content []byte, scores map[string]int) {
conf := getConfig()
if conf.ContentLogDir == "" {
return
}
filename := fmt.Sprintf("%x", md5.Sum(content))
path := filepath.Join(conf.ContentLogDir, filename)
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Error creating content log file (%s): %v", path, err)
return
}
defer f.Close()
topCategory, topScore := "", 0
for c, s := range scores {
if s > topScore && conf.Categories[c] != nil && conf.Categories[c].action != ACL {
topCategory = c
topScore = s
}
}
f.Write(content)
contentLog.Log([]string{u.String(), filename, topCategory, strconv.Itoa(topScore)})
}
// toStrings converts its arguments into a slice of strings.
func toStrings(a ...interface{}) []string {
result := make([]string, len(a))
for i, x := range a {
result[i] = fmt.Sprint(x)
}
return result
}
// stringTally returns a copy of tally with strings instead of rules as keys.
func stringTally(tally map[rule]int) map[string]int {
st := make(map[string]int)
for r, n := range tally {
st[r.String()] = n
}
return st
}
// listTally sorts the tally and formats it as a comma-separated string.
func listTally(tally map[string]int) string {
b := new(bytes.Buffer)
for i, rule := range sortedKeys(tally) {
if i > 0 {
b.WriteString(", ")
}
fmt.Fprint(b, rule, " ", tally[rule])
}
return b.String()
}
// logVerbose logs a message with log.Printf, but only if the --verbose flag
// is turned on for the category.
func logVerbose(messageCategory string, format string, v ...interface{}) {
if getConfig().Verbose[messageCategory] {
log.Printf(format, v...)
}
}