forked from scalingdata/gowinlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwinlog.go
322 lines (278 loc) · 9.93 KB
/
winlog.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
// +build windows
package winlog
import (
"fmt"
"time"
"unsafe"
)
func (self *WinLogWatcher) Event() <-chan *WinLogEvent {
return self.eventChan
}
func (self *WinLogWatcher) Error() <-chan error {
return self.errChan
}
// Create 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),
renderMessage: true,
renderLevel: true,
renderTask: true,
renderProvider: true,
renderOpcode: true,
renderChannel: true,
renderId: true,
}, nil
}
// Whether to use EvtFormatMessage to render the event message
func (self *WinLogWatcher) SetRenderMessage(render bool) {
self.renderMessage = render
}
// Whether to use EvtFormatMessage to render the event level
func (self *WinLogWatcher) SetRenderLevel(render bool) {
self.renderLevel = render
}
// Whether to use EvtFormatMessage to render the event task
func (self *WinLogWatcher) SetRenderTask(render bool) {
self.renderTask = render
}
// Whether to use EvtFormatMessage to render the event provider
func (self *WinLogWatcher) SetRenderProvider(render bool) {
self.renderProvider = render
}
// Whether to use EvtFormatMessage to render the event opcode
func (self *WinLogWatcher) SetRenderOpcode(render bool) {
self.renderOpcode = render
}
// Whether to use EvtFormatMessage to render the event channel
func (self *WinLogWatcher) SetRenderChannel(render bool) {
self.renderChannel = render
}
// Whether to use EvtFormatMessage to render the event ID
func (self *WinLogWatcher) SetRenderId(render bool) {
self.renderId = render
}
// 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
}
func (self *WinLogWatcher) removeSubscription(channel string, watch *channelWatcher) error {
cancelErr := CancelEventHandle(uint64(watch.subscription))
closeErr := CloseEventHandle(uint64(watch.subscription))
CloseEventHandle(uint64(watch.bookmark))
self.watchMutex.Lock()
delete(self.watches, channel)
self.watchMutex.Unlock()
if cancelErr != nil {
return cancelErr
}
return closeErr
}
// Remove all subscriptions from this watcher and shut down.
func (self *WinLogWatcher) Shutdown() {
self.watchMutex.Lock()
watches := self.watches
self.watchMutex.Unlock()
close(self.shutdown)
for channel, watch := range watches {
self.removeSubscription(channel, watch)
}
CloseEventHandle(uint64(self.renderContext))
close(self.errChan)
close(self.eventChan)
}
func (self *WinLogWatcher) PublishError(err error) {
// Publish the received error to the errChan, but
// discard if shutdown is in progress
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 msgText, lvlText, taskText, providerText, opcodeText, channelText, idText string
// Publisher fields
var publisherHandle PublisherHandle
var publisherHandleErr error
// Render XML, any error is stored in the returned WinLogEvent
xml, xmlErr := RenderEventXML(handle)
// Render the values
renderedFields, renderedFieldsErr := RenderEventValues(self.renderContext, handle)
if renderedFieldsErr == nil {
// If fields don't exist we include the nil value
computerName, _ = RenderStringField(renderedFields, EvtSystemComputer)
providerName, _ = RenderStringField(renderedFields, EvtSystemProviderName)
channel, _ = RenderStringField(renderedFields, EvtSystemChannel)
level, _ = RenderUIntField(renderedFields, EvtSystemLevel)
task, _ = RenderUIntField(renderedFields, EvtSystemTask)
opcode, _ = RenderUIntField(renderedFields, EvtSystemOpcode)
recordId, _ = RenderUIntField(renderedFields, EvtSystemEventRecordId)
qualifiers, _ = RenderUIntField(renderedFields, EvtSystemQualifiers)
eventId, _ = RenderUIntField(renderedFields, EvtSystemEventID)
processId, _ = RenderUIntField(renderedFields, EvtSystemProcessID)
threadId, _ = RenderUIntField(renderedFields, EvtSystemThreadID)
version, _ = RenderUIntField(renderedFields, EvtSystemVersion)
created, _ = RenderFileTimeField(renderedFields, EvtSystemTimeCreated)
// Render localized fields
publisherHandle, publisherHandleErr = GetEventPublisherHandle(renderedFields)
if publisherHandleErr == nil {
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))
Free(unsafe.Pointer(renderedFields))
}
// Return an error if we couldn't render anything useful
if xmlErr != nil && renderedFieldsErr != nil {
return nil, fmt.Errorf("Failed to render event values and XML: %v", []error{renderedFieldsErr, xmlErr})
}
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,
Msg: msgText,
LevelText: lvlText,
TaskText: taskText,
OpcodeText: opcodeText,
ChannelText: channelText,
ProviderText: providerText,
IdText: idText,
PublisherHandleErr: publisherHandleErr,
SubscribedChannel: subscribedChannel,
}
return &event, nil
}
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
}
}