-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
289 lines (248 loc) · 9.1 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
package main
import (
"log"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"unsafe"
"github.com/lxn/win"
"golang.org/x/sys/windows"
)
// credits: https://github.com/GregoryDosh/automidically/blob/57c52df4621946c2665271361bf3248df7b9e1e2/internal/activewindow/activewindow.go
var (
// listenerLock = &sync.Mutex{}
listener *Listener
lastForegroundApp string
)
type process struct {
pid uint32
exe string
}
type Listener struct {
AllProcesses map[win.HWND]process
AllPIDs map[uint32]struct{}
EVENT_OBJECT_CREATE win.HWINEVENTHOOK
EVENT_SYSTEM_FOREGROUND win.HWINEVENTHOOK
EVENT_OBJECT_DESTROY win.HWINEVENTHOOK
mutex sync.Mutex
}
var STATUSCODES = map[uint32]string{
win.EVENT_OBJECT_CREATE: "EVENT_OBJECT_CREATE",
win.EVENT_SYSTEM_FOREGROUND: "EVENT_SYSTEM_FOREGROUND",
win.EVENT_OBJECT_DESTROY: "EVENT_OBJECT_DESTROY",
}
const (
OBJID_WINDOW = 0
CHILDID_SELF = 0
WM_APPEXIT = 0x0400 + 1
)
// newActiveWindowCallback is passed to Windows to be called whenever the active window changes.
// When it is called it will attempt to find the process of an associated handle, then get the executable associated with that.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-wineventproc
func (l *Listener) newActiveWindowCallback(
hWinEventHook win.HWINEVENTHOOK, // Handle to an event hook function. This value is returned by SetWinEventHook when the hook function is installed and is specific to each instance of the hook function.
event uint32, // Specifies the event that occurred. This value is one of the event constants.
hwnd win.HWND, // Handle to the window that generates the event, or NULL if no window is associated with the event. For example, the mouse pointer is not associated with a window.
idObject int32, // Identifies the object associated with the event. This is one of the object identifiers or a custom object ID.
idChild int32, // Identifies whether the event was triggered by an object or a child element of the object. If this value is CHILDID_SELF, the event was triggered by the object; otherwise, this value is the child ID of the element that triggered the event.
idEventThread uint32,
dwmsEventTime uint32, // Specifies the time, in milliseconds, that the event was generated.
) (ret uintptr) {
l.mutex.Lock()
defer l.mutex.Unlock()
if idObject != OBJID_WINDOW || idChild != CHILDID_SELF {
return
}
val, ok := l.AllProcesses[hwnd]
if ok {
if event == win.EVENT_OBJECT_DESTROY {
_, oldPid := l.AllPIDs[val.pid]
delete(l.AllPIDs, val.pid)
if oldPid { // diese PID wird zum ersten mal destroyed
OnProcessFinish(val.pid, val.exe)
}
delete(l.AllProcesses, hwnd)
} else if event == win.EVENT_SYSTEM_FOREGROUND {
if lastForegroundApp != val.exe {
OnForeground(val.exe, val.pid)
lastForegroundApp = val.exe
}
}
return
}
if hwnd == 0 {
return
}
if event == win.EVENT_OBJECT_DESTROY {
// hwnd war noch nicht in der DB und muss da auch nicht mehr rein
return
}
var pid uint32 = 0
if v, ok := l.AllProcesses[hwnd]; ok {
if v.pid != 0 {
pid = v.pid
}
} else {
win.GetWindowThreadProcessId(hwnd, &pid)
if pid == 0 {
return
}
}
_, foundPid := l.AllPIDs[pid]
if foundPid && event == win.EVENT_OBJECT_CREATE {
return
}
pHndl, err := windows.OpenProcess(ProcessQueryInformation, false, pid)
defer windows.CloseHandle(pHndl)
if pHndl == 0 || err != nil {
return
}
buf := make([]uint16, syscall.MAX_PATH)
err = windows.GetModuleFileNameEx(pHndl, 0, &buf[0], uint32(len(buf)))
if err != nil {
return
}
processFilename := filepath.Base(strings.ToLower(syscall.UTF16ToString(buf)))
if processFilename == "rundll32.exe" {
return
}
l.AllPIDs[pid] = struct{}{}
l.AllProcesses[hwnd] = process{
pid: pid,
exe: processFilename,
}
if event == win.EVENT_SYSTEM_FOREGROUND {
if lastForegroundApp != processFilename {
OnForeground(processFilename, pid)
lastForegroundApp = processFilename
}
} else {
OnProcessStart(pid, processFilename)
}
return 0
}
func startListenerMessageLoop() {
var err error
EVENT_OBJECT_CREATE, err := setActiveWindowWinEventHook(listener.newActiveWindowCallback, win.EVENT_OBJECT_CREATE)
if err != nil {
_ = err
panic(err)
}
defer win.UnhookWinEvent(EVENT_OBJECT_CREATE)
EVENT_SYSTEM_FOREGROUND, err := setActiveWindowWinEventHook(listener.newActiveWindowCallback, win.EVENT_SYSTEM_FOREGROUND)
if err != nil {
panic(err)
}
defer win.UnhookWinEvent(EVENT_SYSTEM_FOREGROUND)
EVENT_OBJECT_DESTROY, err := setActiveWindowWinEventHook(listener.newActiveWindowCallback, win.EVENT_OBJECT_DESTROY)
if err != nil {
_ = err
panic(err)
}
defer win.UnhookWinEvent(EVENT_OBJECT_DESTROY)
var msg win.MSG
for win.GetMessage(&msg, 0, 0, 0) != 0 {
if msg.Message == WM_APPEXIT {
break
}
win.TranslateMessage(&msg)
win.DispatchMessage(&msg)
}
}
// setActiveWindowWinEventHook is for informing windows which function should be called whenever a
// foreground window has changed. https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook
func setActiveWindowWinEventHook(callbackFunction win.WINEVENTPROC, event uint32) (win.HWINEVENTHOOK, error) {
ret, err := win.SetWinEventHook(
event, // Specifies the event constant for the lowest event value in the range of events that are handled by the hook function. This parameter can be set to EVENT_MIN to indicate the lowest possible event value.
event, // Specifies the event constant for the highest event value in the range of events that are handled by the hook function. This parameter can be set to EVENT_MAX to indicate the highest possible event value.
0, // Handle to the DLL that contains the hook function at lpfnWinEventProc, if the WINEVENT_INCONTEXT flag is specified in the dwFlags parameter. If the hook function is not located in a DLL, or if the WINEVENT_OUTOFCONTEXT flag is specified, this parameter is NULL.
callbackFunction, // Pointer to the event hook function. For more information about this function, see WinEventProc.
0, // Specifies the ID of the process from which the hook function receives events. Specify zero (0) to receive events from all processes on the current desktop.
0, // Specifies the ID of the thread from which the hook function receives events. If this parameter is zero, the hook function is associated with all existing threads on the current desktop.
win.WINEVENT_OUTOFCONTEXT|win.WINEVENT_SKIPOWNPROCESS, // Flag values that specify the location of the hook function and of the events to be skipped. The following flags are valid:
)
if ret == 0 {
return 0, err
}
return ret, nil
}
func main() {
listener = &Listener{}
listener.AllProcesses = make(map[win.HWND]process)
listener.AllPIDs = make(map[uint32]struct{})
go startListenerMessageLoop()
select {}
}
func UTF16toString(p *uint16) string {
return syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(p))[:])
// ptr := unsafe.Pointer(p) // necessary to arbitrarily cast to *[4096]uint16 (?)
// uint16ptrarr := (*[4096]uint16)(ptr)[:] // 4096 is arbitrary? could be smaller
// return syscall.UTF16ToString(uint16ptrarr) // now uint16ptrarr is in a format to pass to the builtin converter
}
var lastForeground []Scripts
// EVENT_SYSTEM_FOREGROUND
func OnForeground(exe string, pid uint32) {
log.Println(Green, "EVENT_SYSTEM_FOREGROUND", Reset, exe)
if len(lastForeground) != 0 {
for _, script := range lastForeground {
runScript(pid, script)
}
lastForeground = []Scripts{}
}
if len(gamesList[exe].OnProcessStart) != 0 {
for _, script := range gamesList[exe].OnProcessStart {
if script.OnForeground {
runScript(pid, script)
}
}
}
lastForeground = []Scripts{}
if len(gamesList[exe].OnProcessFinish) != 0 {
for _, script := range gamesList[exe].OnProcessFinish {
if script.OnBackground {
lastForeground = append(lastForeground, script)
}
}
}
}
// EVENT_OBJECT_DESTROY
func OnProcessFinish(pid uint32, exe string) {
log.Println(Red, "EVENT_OBJECT_DESTROY", Reset, exe)
if len(gamesList[exe].OnProcessFinish) != 0 {
for _, script := range gamesList[exe].OnProcessFinish {
runScript(pid, script)
}
}
}
// EVENT_OBJECT_CREATE
func OnProcessStart(pid uint32, exe string) {
log.Println(Cyan, "EVENT_OBJECT_CREATE", Reset, exe)
if len(gamesList[exe].OnProcessStart) != 0 {
for _, script := range gamesList[exe].OnProcessStart {
runScript(pid, script)
}
}
}
func runScript(pid uint32, script Scripts) {
var cmd_instance *exec.Cmd
if script.Args == "" {
log.Printf("exec.Command(%s)\n", script.Name)
cmd_instance = exec.Command(script.Name)
} else {
tempArgs := strings.ReplaceAll(script.Args, "%pid%", strconv.Itoa(int(pid)))
log.Printf("exec.Command(%s, %s)\n", script.Name, tempArgs)
cmd_instance = exec.Command(script.Name, strings.Split(tempArgs, " ")...)
}
if script.HideWindow {
cmd_instance.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
cmd_instance.Start()
// output, err := cmd_instance.CombinedOutput()
// if err != nil {
// log.Println(err)
// }
// println("output", string(output))
}