summaryrefslogtreecommitdiff
path: root/cmd/installer/main.go
blob: 07f7fe8dce010fa0a53122a0865696397175707c (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
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
// vpnem-installer: Windows offline installer (GUI, no console window).
// Bundles all binaries — no network download needed.
// Installs to Program Files, creates Task Scheduler task for UAC-free launch.
// Requires admin (one-time). Supports silent mode: vpnem-installer.exe /S
// Cross-compiles from Linux with -ldflags "-H windowsgui"
package main

import (
	"embed"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

//go:embed files/*
var bundledFiles embed.FS

const (
	installDir = `C:\Program Files\vpnem`
	dataDir    = `C:\ProgramData\vpnem`
	taskName   = "vpnem"

	baseURL    = "https://vpn.em-sysadmin.xyz/releases"
	vpnemURL   = baseURL + "/vpnem-windows-amd64.exe"
)

var (
	silent     bool
	noShortcut bool
	launch     bool
	logFile    *os.File
)

func main() {
	// Parse flags
	for _, arg := range os.Args[1:] {
		a := strings.ToLower(strings.TrimLeft(arg, "/-"))
		switch a {
		case "s", "silent":
			silent = true
		case "noshortcut":
			noShortcut = true
		case "launch":
			launch = true
		}
	}

	if !isElevated() {
		if err := relaunchElevated(); err != nil {
			fatal("request administrator privileges: %v", err)
		}
		return
	}

	// 1. Kill ALL running instances immediately
	step("stopping running instances")
	exec.Command("taskkill", "/F", "/IM", "vpnem.exe").Run()
	exec.Command("taskkill", "/F", "/IM", "sing-box.exe").Run()
	time.Sleep(2 * time.Second)

	// 2. Remove OLD installation directories completely (clean slate)
	step("removing old installation")
	if err := os.RemoveAll(installDir); err != nil {
		log.Printf("warning: could not remove old install dir: %v", err)
	}
	if err := os.RemoveAll(dataDir); err != nil {
		log.Printf("warning: could not remove old data dir: %v", err)
	}
	// Also remove old ProxySwitcher if exists
	os.RemoveAll(`C:\ProxySwitcher`)

	// 3. Create fresh directories
	if err := os.MkdirAll(installDir, 0o755); err != nil {
		fatal("create install dir: %v", err)
	}
	if err := os.MkdirAll(dataDir, 0o755); err != nil {
		fatal("create data dir: %v", err)
	}

	// Write bundled files instead of downloading
	step("extracting bundled vpnem.exe")
	if err := writeEmbedded("files/vpnem.exe", filepath.Join(installDir, "vpnem.exe")); err != nil {
		fatal("extract vpnem.exe: %v", err)
	}
	step("extracting bundled sing-box.exe")
	if err := writeEmbedded("files/sing-box.exe", filepath.Join(installDir, "sing-box.exe")); err != nil {
		fatal("extract sing-box.exe: %v", err)
	}
	step("extracting bundled wintun.dll")
	if err := writeEmbedded("files/wintun.dll", filepath.Join(installDir, "wintun.dll")); err != nil {
		fatal("extract wintun.dll: %v", err)
	}

	// Create Task Scheduler task — runs vpnem as admin WITHOUT UAC prompt.
	// This is the key: task created by admin runs with highest privileges silently.
	step("creating scheduled task (UAC-free launch)")
	createTask()

	// Desktop shortcut — launches via schtasks (no UAC popup)
	if !noShortcut {
		step("creating desktop shortcut")
		createShortcut()
	}

	step("installation complete")

	if launch {
		step("launching vpnem")
		exec.Command("schtasks", "/Run", "/TN", taskName).Run()
	}

	if !silent {
		showDoneMessage()
	}
}

// createTask sets up a scheduled task that:
// 1. Runs vpnem.exe with highest privileges (no UAC)
// 2. Starts at logon with 15s delay (autostart)
// The same task is used for both manual launch and autostart.
func createTask() {
	exec.Command("schtasks", "/Delete", "/TN", taskName, "/F").Run()

	// Create XML task definition for full control
	exePath := filepath.Join(installDir, "vpnem.exe")
	xml := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>vpnem VPN client</Description>
  </RegistrationInfo>
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
      <Delay>PT15S</Delay>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <AllowHardTerminate>true</AllowHardTerminate>
  </Settings>
  <Actions>
    <Exec>
      <Command>%s</Command>
      <Arguments>--data "%s"</Arguments>
      <WorkingDirectory>%s</WorkingDirectory>
    </Exec>
  </Actions>
</Task>`, exePath, dataDir, installDir)

	xmlPath := filepath.Join(dataDir, "task.xml")
	os.WriteFile(xmlPath, []byte(xml), 0o644)

	cmd := exec.Command("schtasks", "/Create", "/TN", taskName, "/XML", xmlPath, "/F")
	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Printf("task create failed: %v\n%s", err, string(out))
	} else {
		log.Println("task created ok")
	}
	os.Remove(xmlPath)
}

// createShortcut makes a desktop shortcut that runs the scheduled task (no UAC)
// IconLocation points to vpnem.exe so the shortcut has the app icon
func createShortcut() {
	exePath := filepath.Join(installDir, "vpnem.exe")
	ps := `
$ws = New-Object -ComObject WScript.Shell
$s = $ws.CreateShortcut("$env:USERPROFILE\Desktop\vpnem.lnk")
$s.TargetPath = "schtasks.exe"
$s.Arguments = "/Run /TN vpnem"
$s.WorkingDirectory = "` + installDir + `"
$s.IconLocation = "` + exePath + `,0"
$s.Description = "vpnem VPN client"
$s.Save()
`
	cmd := exec.Command("powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command", ps)
	if err := cmd.Run(); err != nil {
		log.Printf("shortcut failed: %v (non-critical)", err)
	}
}

func step(msg string) {
	log.Println(msg)
}

func writeEmbedded(name, dest string) error {
	data, err := bundledFiles.ReadFile(name)
	if err != nil {
		return fmt.Errorf("read embedded file %s: %w", name, err)
	}
	tmp := dest + ".tmp"
	if err := os.WriteFile(tmp, data, 0o755); err != nil {
		return fmt.Errorf("write %s: %w", dest, err)
	}
	info, _ := os.Stat(tmp)
	log.Printf("  %s (%.1f MB)", filepath.Base(dest), float64(info.Size())/1024/1024)
	return os.Rename(tmp, dest)
}

func fatal(format string, args ...any) {
	msg := fmt.Sprintf(format, args...)
	log.Printf("FATAL: %s", msg)
	if silent {
		os.Exit(1)
	}
	showError(msg)
	os.Exit(1)
}

func showDoneMessage() {
	msg := fmt.Sprintf("vpnem installed to %s\\n\\nDesktop shortcut created.\\nAutostart at logon enabled.\\n\\nNo admin prompts needed to launch.", installDir)
	exec.Command("powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command",
		fmt.Sprintf(`Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show("%s", "vpnem installer", "OK", "Information")`, msg),
	).Run()
}

func showError(msg string) {
	exec.Command("powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command",
		fmt.Sprintf(`Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show("Installation failed:\n%s", "vpnem installer", "OK", "Error")`, msg),
	).Run()
}