forked from myles-keough/gowinlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winlogwatcher.go
286 lines (246 loc) · 8.78 KB
/
winlogwatcher.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
//go:build windows
// +build windows
// Winlog hooks into the Windows Event Log and streams events through channels
package winlog
import (
"fmt"
"time"
)
/* WinLogWatcher encompasses the overall functionality, eventlog subscriptions etc. */
// Event Channel for receiving events
func (wlw *WinLogWatcher) Event() <-chan *WinLogEvent {
return wlw.eventChan
}
// Channel for receiving errors (not "error" events)
func (wlw *WinLogWatcher) Error() <-chan error {
return wlw.errChan
}
// NewWinLogWatcher creates a new watcher
func NewWinLogWatcher() (*WinLogWatcher, error) {
cHandle, err := GetSystemRenderContext()
if err != nil {
return nil, err
}
return &WinLogWatcher{
shutdown: make(chan interface{}),
errChan: make(chan error),
eventChan: make(chan *WinLogEvent),
renderContext: cHandle,
watches: make(map[string]*channelWatcher),
}, nil
}
// Subscribe to a Windows Event Log channel, starting with the first event
// in the log. `query` is an XPath expression for filtering events: to recieve
// all events on the channel, use "*" as the query.
func (self *WinLogWatcher) SubscribeFromBeginning(channel, query string) error {
return self.subscribeWithoutBookmark(channel, query, EvtSubscribeStartAtOldestRecord)
}
// Subscribe to a Windows Event Log channel, starting with the next event
// that arrives. `query` is an XPath expression for filtering events: to recieve
// all events on the channel, use "*" as the query.
func (self *WinLogWatcher) SubscribeFromNow(channel, query string) error {
return self.subscribeWithoutBookmark(channel, query, EvtSubscribeToFutureEvents)
}
func (self *WinLogWatcher) subscribeWithoutBookmark(channel, query string, flags EVT_SUBSCRIBE_FLAGS) error {
self.watchMutex.Lock()
defer self.watchMutex.Unlock()
if _, ok := self.watches[channel]; ok {
return fmt.Errorf("A watcher for channel %q already exists", channel)
}
newBookmark, err := CreateBookmark()
if err != nil {
return fmt.Errorf("Failed to create new bookmark handle: %v", err)
}
callback := &LogEventCallbackWrapper{callback: self, subscribedChannel: channel}
subscription, err := CreateListener(channel, query, flags, callback)
if err != nil {
CloseEventHandle(uint64(newBookmark))
return err
}
self.watches[channel] = &channelWatcher{
bookmark: newBookmark,
subscription: subscription,
callback: callback,
}
return nil
}
// Subscribe to a Windows Event Log channel, starting with the first event in the log
// after the bookmarked event. There may be a gap if events have been purged. `query`
// is an XPath expression for filtering events: to recieve all events on the channel,
// use "*" as the query
func (self *WinLogWatcher) SubscribeFromBookmark(channel, query string, xmlString string) error {
self.watchMutex.Lock()
defer self.watchMutex.Unlock()
if _, ok := self.watches[channel]; ok {
return fmt.Errorf("A watcher for channel %q already exists", channel)
}
callback := &LogEventCallbackWrapper{callback: self, subscribedChannel: channel}
bookmark, err := CreateBookmarkFromXml(xmlString)
if err != nil {
return fmt.Errorf("Failed to create new bookmark handle: %v", err)
}
subscription, err := CreateListenerFromBookmark(channel, query, callback, bookmark)
if err != nil {
CloseEventHandle(uint64(bookmark))
return fmt.Errorf("Failed to add listener: %v", err)
}
self.watches[channel] = &channelWatcher{
bookmark: bookmark,
subscription: subscription,
callback: callback,
}
return nil
}
/* Remove subscription from channel */
func (self *WinLogWatcher) RemoveSubscription(channel string) error {
self.watchMutex.Lock()
defer self.watchMutex.Unlock()
var cancelErr, closeErr error
if watch, ok := self.watches[channel]; ok {
cancelErr = CancelEventHandle(uint64(watch.subscription))
closeErr = CloseEventHandle(uint64(watch.subscription))
CloseEventHandle(uint64(watch.bookmark))
}
delete(self.watches, channel)
if cancelErr != nil {
return cancelErr
}
return closeErr
}
// Remove all subscriptions from this watcher and shut down.
func (self *WinLogWatcher) Shutdown() {
close(self.shutdown)
for channel := range self.watches {
self.RemoveSubscription(channel)
}
CloseEventHandle(uint64(self.renderContext))
close(self.errChan)
close(self.eventChan)
}
/* Publish the received error to the errChan, but discard if shutdown is in progress */
func (self *WinLogWatcher) PublishError(err error) {
select {
case self.errChan <- err:
case <-self.shutdown:
}
}
func (self *WinLogWatcher) convertEvent(handle EventHandle, subscribedChannel string) (*WinLogEvent, error) {
// Rendered values
var computerName, providerName, channel string
var level, task, opcode, recordId, qualifiers, eventId, processId, threadId, version uint64
var created time.Time
// Localized fields
var keywordsText, msgText, lvlText, taskText, providerText, opcodeText, channelText, idText string
// Publisher fields
var publisherHandle PublisherHandle
var publisherHandleErr error
// Render the values
renderedFields, renderedFieldsErr := RenderEventValues(self.renderContext, handle)
xml, xmlErr := RenderEventXML(handle)
if renderedFieldsErr == nil {
// If fields don't exist we include the nil value
computerName, _ = renderedFields.String(EvtSystemComputer)
providerName, _ = renderedFields.String(EvtSystemProviderName)
channel, _ = renderedFields.String(EvtSystemChannel)
level, _ = renderedFields.Uint(EvtSystemLevel)
task, _ = renderedFields.Uint(EvtSystemTask)
opcode, _ = renderedFields.Uint(EvtSystemOpcode)
recordId, _ = renderedFields.Uint(EvtSystemEventRecordId)
qualifiers, _ = renderedFields.Uint(EvtSystemQualifiers)
eventId, _ = renderedFields.Uint(EvtSystemEventID)
processId, _ = renderedFields.Uint(EvtSystemProcessID)
threadId, _ = renderedFields.Uint(EvtSystemThreadID)
version, _ = renderedFields.Uint(EvtSystemVersion)
created, _ = renderedFields.FileTime(EvtSystemTimeCreated)
// Render localized fields
publisherHandle, publisherHandleErr = GetEventPublisherHandle(renderedFields)
if publisherHandleErr == nil {
if self.RenderKeywords {
keywordsText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageKeyword)
}
if self.RenderMessage {
msgText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageEvent)
}
if self.RenderLevel {
lvlText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageLevel)
}
if self.RenderTask {
taskText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageTask)
}
if self.RenderProvider {
providerText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageProvider)
}
if self.RenderOpcode {
opcodeText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageOpcode)
}
if self.RenderChannel {
channelText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageChannel)
}
if self.RenderId {
idText, _ = FormatMessage(publisherHandle, handle, EvtFormatMessageId)
}
CloseEventHandle(uint64(publisherHandle))
}
}
event := WinLogEvent{
Xml: xml,
XmlErr: xmlErr,
ProviderName: providerName,
EventId: eventId,
Qualifiers: qualifiers,
Level: level,
Task: task,
Opcode: opcode,
Created: created,
RecordId: recordId,
ProcessId: processId,
ThreadId: threadId,
Channel: channel,
ComputerName: computerName,
Version: version,
RenderedFieldsErr: renderedFieldsErr,
Keywords: keywordsText,
Msg: msgText,
LevelText: lvlText,
TaskText: taskText,
OpcodeText: opcodeText,
ChannelText: channelText,
ProviderText: providerText,
IdText: idText,
PublisherHandleErr: publisherHandleErr,
SubscribedChannel: subscribedChannel,
}
return &event, nil
}
/* Publish a new event */
func (self *WinLogWatcher) PublishEvent(handle EventHandle, subscribedChannel string) {
// Convert the event from the event log schema
event, err := self.convertEvent(handle, subscribedChannel)
if err != nil {
self.PublishError(err)
return
}
// Get the bookmark for the channel
self.watchMutex.Lock()
watch, ok := self.watches[subscribedChannel]
self.watchMutex.Unlock()
if !ok {
self.errChan <- fmt.Errorf("No handle for channel bookmark %q", subscribedChannel)
return
}
// Update the bookmark with the current event
UpdateBookmark(watch.bookmark, handle)
// Serialize the boomark as XML and include it in the event
bookmarkXml, err := RenderBookmark(watch.bookmark)
if err != nil {
self.PublishError(fmt.Errorf("Error rendering bookmark for event - %v", err))
return
}
event.Bookmark = bookmarkXml
// Don't block when shutting down if the consumer has gone away
select {
case self.eventChan <- event:
case <-self.shutdown:
return
}
}