forked from 0xrawsec/whids
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logfile.go
248 lines (202 loc) · 5.51 KB
/
logfile.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
package logger
import (
"bufio"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/0xrawsec/golang-utils/fsutil"
"github.com/0xrawsec/whids/utils"
)
// RenameIndexedLogfile renames both an IndexLogfile and its associated IndexFile
func RenameIndexedLogfile(old, new string) (lastErr error) {
if err := os.Rename(old, new); err != nil {
lastErr = err
}
if err := os.Rename(IndexFileFromPath(old), IndexFileFromPath(new)); err != nil {
lastErr = err
}
return
}
// RemoveIndexedLogfile removes both an IndexLogfile and its associated IndexFile
func RemoveIndexedLogfile(path string) (lastErr error) {
if err := os.Remove(path); err != nil {
lastErr = err
}
if err := os.Remove(path); err != nil {
lastErr = err
}
return
}
// ArchiveFilename returns a standardized name to archive and IndexedLogfile
func ArchiveFilename(path string) string {
now := time.Now()
ext := filepath.Ext(path)
rest := strings.TrimRight(path, ext)
return fmt.Sprintf("%s-%d%s", rest, now.UTC().UnixNano(), ext)
}
// IndexedLogfile structure
type IndexedLogfile struct {
sync.Mutex
path string
fd *os.File
writer *gzip.Writer
indexEntry IndexEntry
}
// OpenIndexedLogfile opens an IndexedLogfile
func OpenIndexedLogfile(path string) (l *IndexedLogfile, err error) {
l = &IndexedLogfile{path: path}
if l.fd, err = os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE, DefaultLogPerm); err != nil {
return
}
if err == nil {
l.writer = gzip.NewWriter(l.fd)
}
err = l.resetIndexEntry()
return
}
// IndexFileFromPath returns a standardized IndexFile name from a path
func IndexFileFromPath(path string) string {
return fmt.Sprintf("%s%s", path, IndexExt)
}
func (f *IndexedLogfile) resetIndexEntry() (err error) {
f.indexEntry = IndexEntry{}
if f.indexEntry.Offset, err = f.size(); err != nil {
return fmt.Errorf("failed to reset index entry: %w", err)
}
return
}
// IndexFile returns the path of the IndexFile associated to the IndexedLogfile
func (f *IndexedLogfile) IndexFile() string {
return fmt.Sprintf("%s%s", f.path, IndexExt)
}
func (f *IndexedLogfile) size() (size int64, err error) {
var saved int64
// we save current offset
if saved, err = f.fd.Seek(0, io.SeekCurrent); err != nil {
return
}
// we get the file size
if size, err = f.fd.Seek(0, io.SeekEnd); err != nil {
return
}
// we restore the offset
if _, err = f.fd.Seek(saved, io.SeekStart); err != nil {
return
}
return
}
// Size returns the size of the IndexedLogfile
func (f *IndexedLogfile) Size() (size int64, err error) {
f.Lock()
defer f.Unlock()
return f.size()
}
// ReadRawEvents reads n RawEvents located at offset in IndexedLogfile
func (f *IndexedLogfile) ReadRawEvents(offset int64, n int64) (events []*RawEvent, err error) {
f.Lock()
defer f.Unlock()
var r *gzip.Reader
var saved int64
var s *bufio.Scanner
events = make([]*RawEvent, 0, n)
// we save current offset
if saved, err = f.fd.Seek(0, io.SeekCurrent); err != nil {
return
}
// we go at wanted offset
if _, err = f.fd.Seek(offset, io.SeekStart); err != nil {
return
}
if r, err = gzip.NewReader(f.fd); err != nil {
goto Cleanup
}
defer r.Close()
s = bufio.NewScanner(r)
for s.Scan() && int64(len(events)) < n {
var raw *RawEvent
if raw, err = DecodeRawEvent(s.Bytes()); err != nil {
return
}
events = append(events, raw)
}
Cleanup:
// we restore the offset
if _, e := f.fd.Seek(saved, io.SeekStart); e != nil {
err = e
return
}
return
}
// WriteRawEventWithTimestamp writes a RawEvent with an associated event timestamp in the IndexLogfile
func (f *IndexedLogfile) WriteRawEventWithTimestamp(e *RawEvent, timestamp time.Time) (n int, err error) {
f.Lock()
defer f.Unlock()
var b []byte
timestamp = stdTime(timestamp)
// we go at the end of file
if _, err = f.fd.Seek(0, io.SeekEnd); err != nil {
return
}
// we update timestamps only if write succeded
b = append(e.Encode(), '\n')
if n, err = f.writer.Write(b); err == nil {
f.indexEntry.UpdateTime(timestamp)
// we increment the event counter
f.indexEntry.EventCount += 1
}
return
}
// WriteRawEvent writes a RawEvent in IndexLogfile taking the event timestamp as reference time
func (f *IndexedLogfile) WriteRawEvent(e *RawEvent) (n int, err error) {
return f.WriteRawEventWithTimestamp(e, e.Timestamp)
}
func (f *IndexedLogfile) flush() (err error) {
var indexFd *os.File
// we commit to index file only if we wrote at least one event
if f.indexEntry.EventCount > 0 {
header := !fsutil.Exists(f.IndexFile())
if indexFd, err = os.OpenFile(f.IndexFile(), os.O_APPEND|os.O_RDWR|os.O_CREATE, utils.DefaultFilePerm); err != nil {
return
}
defer indexFd.Close()
if header {
if _, err = indexFd.WriteString(IndexHeader + "\n"); err != nil {
return fmt.Errorf("failed to write index file: %w", err)
}
}
if _, err = indexFd.WriteString(f.indexEntry.ToCSV() + "\n"); err != nil {
return fmt.Errorf("failed to write index file: %w", err)
}
if err = f.writer.Flush(); err != nil {
return fmt.Errorf("failed at flushing gzip writer: %w", err)
}
return f.resetIndexEntry()
}
return
}
// Flush flushes the IndexedLogfile to disk
func (f *IndexedLogfile) Flush() (err error) {
f.Lock()
defer f.Unlock()
return f.flush()
}
// Close flushes and closes an IndexedLogfile
func (f *IndexedLogfile) Close() (err error) {
f.Lock()
defer f.Unlock()
if err = f.flush(); err != nil {
return
}
// we close gzip writer
f.writer.Close()
// close the log file
if e := f.fd.Close(); e != nil {
err = e
}
return
}