summaryrefslogtreecommitdiff
path: root/cmd/client/kill_windows.go
blob: ba8c75a1e481fb800322a9a61e2a6b90eb637a2e (plain)
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
//go:build windows

package main

import (
	"log"
	"os"
	"os/exec"
	"strconv"
	"time"
)

func killPrevious() {
	myPID := os.Getpid()
	log.Printf("killing previous instances (my PID: %d)", myPID)

	// Kill other vpnem.exe processes (not ourselves)
	// Use WMIC to find PIDs, then taskkill each except ours
	out, _ := exec.Command("wmic", "process", "where",
		"name='vpnem.exe'", "get", "processid", "/format:list").Output()
	for _, line := range splitLines(string(out)) {
		if len(line) > 10 && line[:10] == "ProcessId=" {
			pidStr := line[10:]
			pid, err := strconv.Atoi(pidStr)
			if err == nil && pid != myPID {
				log.Printf("killing old vpnem.exe PID %d", pid)
				exec.Command("taskkill", "/F", "/PID", strconv.Itoa(pid)).Run()
			}
		}
	}

	// Kill any orphaned sing-box.exe
	exec.Command("taskkill", "/F", "/IM", "sing-box.exe").Run()
	time.Sleep(500 * time.Millisecond)
}

func splitLines(s string) []string {
	var lines []string
	start := 0
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			line := s[start:i]
			if len(line) > 0 && line[len(line)-1] == '\r' {
				line = line[:len(line)-1]
			}
			if line != "" {
				lines = append(lines, line)
			}
			start = i + 1
		}
	}
	if start < len(s) {
		lines = append(lines, s[start:])
	}
	return lines
}