summaryrefslogtreecommitdiff
path: root/internal/api/handlers.go
blob: 8749646a84dc253b92ca8cfe59273ccd24ce4ac1 (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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package api

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"vpnem/internal/models"
	"vpnem/internal/rules"
)

type Handler struct {
	store *rules.Store
}

func NewHandler(store *rules.Store) *Handler {
	return &Handler{store: store}
}

func (h *Handler) Servers(w http.ResponseWriter, r *http.Request) {
	servers, err := h.store.LoadServers()
	if err != nil {
		log.Printf("error loading servers: %v", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, servers)
}

func (h *Handler) RuleSetManifest(w http.ResponseWriter, r *http.Request) {
	manifest, err := h.store.LoadRuleSets()
	if err != nil {
		log.Printf("error loading rulesets: %v", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, manifest)
}

func (h *Handler) Version(w http.ResponseWriter, r *http.Request) {
	ver, err := h.store.LoadVersion()
	if err != nil {
		log.Printf("error loading version: %v", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, ver)
}

func (h *Handler) CatalogV2(w http.ResponseWriter, r *http.Request) {
	catalog, err := h.store.LoadCatalogV2OrLegacy()
	if err != nil {
		if os.IsNotExist(err) {
			http.Error(w, "catalog-v2 not found", http.StatusNotFound)
			return
		}
		log.Printf("error loading catalog-v2: %v", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, catalog)
}

func (h *Handler) RoutingPolicy(w http.ResponseWriter, r *http.Request) {
	policy, err := h.store.LoadRoutingPolicy()
	if err != nil {
		log.Printf("error loading routing policy: %v", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, policy)
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(v); err != nil {
		log.Printf("error encoding json: %v", err)
	}
}

// ClientLog receives error logs from vpnem clients.
// POST /logs2026vpnem/errors with JSON body: {"version":"2.0.11","os":"windows","lines":["..."]}
func (h *Handler) ClientLog(w http.ResponseWriter, r *http.Request) {
	if r.ContentLength > 64*1024 {
		http.Error(w, "too large", http.StatusRequestEntityTooLarge)
		return
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 64*1024))
	r.Body.Close()
	if err != nil {
		http.Error(w, "read error", http.StatusBadRequest)
		return
	}

	logDir := filepath.Join(h.store.DataDir(), "client-logs")
	if err := os.MkdirAll(logDir, 0755); err != nil {
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	stamp := time.Now().UTC().Format("2006-01-02T15-04-05")
	src := r.RemoteAddr
	if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
		src = fwd
	}
	filename := fmt.Sprintf("%s_%s.log", stamp, src)
	if err := os.WriteFile(filepath.Join(logDir, filename), body, 0644); err != nil {
		http.Error(w, "write error", http.StatusInternalServerError)
		return
	}
	log.Printf("client log saved: %s (%d bytes)", filename, len(body))
	w.WriteHeader(http.StatusAccepted)
}

// ClientLogsViewer shows a simple HTML page listing all client error logs.
func (h *Handler) ClientLogsViewer(w http.ResponseWriter, r *http.Request) {
	logDir := filepath.Join(h.store.DataDir(), "client-logs")

	// Check for file view request
	viewFile := r.URL.Query().Get("file")
	if viewFile != "" {
		safeName := filepath.Base(viewFile)
		data, err := os.ReadFile(filepath.Join(logDir, safeName))
		if err != nil {
			http.Error(w, "file not found", http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write(data)
		return
	}

	// List all log files
	entries, err := os.ReadDir(logDir)
	if err != nil {
		entries = nil
	}

	var rows string
	for i := len(entries) - 1; i >= 0; i-- {
		e := entries[i]
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".log") {
			continue
		}
		info, _ := e.Info()
		size := info.Size()
		rows += fmt.Sprintf(`<tr><td><a href="/client-logs?file=%s">%s</a></td><td>%s</td><td>%d B</td></tr>`,
			e.Name(), e.Name(), info.ModTime().Format("2006-01-02 15:04"), size)
	}

	html := fmt.Sprintf(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Client Error Logs</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 900px; margin: 2rem auto; padding: 0 1rem; background: #f9fafb; }
h1 { font-size: 1.4rem; }
table { width: 100%%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
th { background: #111827; color: #fff; text-align: left; padding: 0.6rem 1rem; }
td { padding: 0.5rem 1rem; border-top: 1px solid #e5e7eb; }
tr:hover td { background: #f3f4f6; }
a { color: #2563eb; text-decoration: none; }
a:hover { text-decoration: underline; }
.empty { padding: 2rem; text-align: center; color: #6b7280; }
</style></head><body>
<h1>📋 Client Error Logs</h1>
<p>Files from vpnem clients that reported errors.</p>
%s
</body></html>`, func() string {
		if rows == "" {
			return `<div class="empty">No client error logs yet.</div>`
		}
		return `<table><tr><th>File</th><th>Modified</th><th>Size</th></tr>` + rows + `</table>`
	}())

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Write([]byte(html))
}

// ClientConnect records a client connection. Server auto-detects real IP via RealIP middleware.
// POST /api/v1/connect with JSON body: {"server_ip":"5.180.97.198","node_id":"nl-198","os":"windows","version":"2.0.11"}
func (h *Handler) ClientConnect(w http.ResponseWriter, r *http.Request) {
	clientIP := GetRealIP(r)
	if clientIP == "" {
		log.Printf("connect: could not determine client IP, remote=%s", r.RemoteAddr)
		http.Error(w, "could not determine client IP", http.StatusBadRequest)
		return
	}

	var req models.ConnectRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		log.Printf("connect: invalid request body from %s: %v", clientIP, err)
		http.Error(w, "invalid request body", http.StatusBadRequest)
		return
	}

	if req.ServerIP == "" {
		log.Printf("connect: missing server_ip from %s", clientIP)
		http.Error(w, "server_ip is required", http.StatusBadRequest)
		return
	}

	h.store.Connections().Connect(clientIP, req.ServerIP, req.NodeID, req.OS, req.Version)
	log.Printf("connect: %s  %s (%s)", clientIP, req.ServerIP, req.NodeID)

	// Return updated recommendation for NEXT client
	availableIPs := h.getAvailableServerIPs()
	healthyIPs := h.getHealthyServerIPs()
	recommendation := h.store.Connections().GetRecommendation(clientIP, availableIPs, healthyIPs)
	log.Printf("connect: recommendation for %s  %s (%s)", clientIP, recommendation.RecommendedServerIP, recommendation.Reason)

	writeJSON(w, recommendation)
}

// ClientDisconnect records a client disconnection.
// POST /api/v1/disconnect with JSON body: {"server_ip":"5.180.97.198","node_id":"nl-198"}
func (h *Handler) ClientDisconnect(w http.ResponseWriter, r *http.Request) {
	clientIP := GetRealIP(r)
	if clientIP == "" {
		log.Printf("disconnect: could not determine client IP, remote=%s", r.RemoteAddr)
		http.Error(w, "could not determine client IP", http.StatusBadRequest)
		return
	}

	var req models.DisconnectRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		// Allow empty body — just use client IP
		h.store.Connections().Disconnect(clientIP)
		log.Printf("disconnect: %s (empty body)", clientIP)
		writeJSON(w, map[string]string{"status": "disconnected"})
		return
	}

	h.store.Connections().Disconnect(clientIP)
	log.Printf("disconnect: %s from %s (%s)", clientIP, req.ServerIP, req.NodeID)
	writeJSON(w, map[string]string{"status": "disconnected"})
}

// Recommend returns the recommended server for a client based on their real IP.
// GET /api/v1/recommend — server auto-detects client IP from X-Forwarded-For.
func (h *Handler) Recommend(w http.ResponseWriter, r *http.Request) {
	clientIP := GetRealIP(r)
	if clientIP == "" {
		log.Printf("recommend: could not determine client IP, remote=%s", r.RemoteAddr)
		http.Error(w, "could not determine client IP", http.StatusBadRequest)
		return
	}

	availableIPs := h.getAvailableServerIPs()
	healthyIPs := h.getHealthyServerIPs()
	recommendation := h.store.Connections().GetRecommendation(clientIP, availableIPs, healthyIPs)
	log.Printf("recommend: %s  %s (%s)", clientIP, recommendation.RecommendedServerIP, recommendation.Reason)

	writeJSON(w, recommendation)
}

// getHealthyServerIPs returns a set of server IPs that are considered healthy.
// For now, all available IPs are considered healthy.
// This can be extended to check node health states from the control plane.
func (h *Handler) getHealthyServerIPs() map[string]bool {
	ips := h.getAvailableServerIPs()
	healthy := make(map[string]bool)
	for _, ip := range ips {
		healthy[ip] = true
	}
	return healthy
}

// getAvailableServerIPs extracts unique server IPs from nodes that have MULTI protocols.
// Only MULTI-capable nodes (vless-reality + hysteria2) are included in the recommendation pool.
// SOCKS5-only nodes are excluded — they exist as fallback but are never recommended.
func (h *Handler) getAvailableServerIPs() []string {
	catalog, err := h.store.LoadCatalogV2OrLegacy()
	if err != nil {
		return nil
	}

	seen := make(map[string]bool)
	var ips []string

	for _, node := range catalog.Nodes {
		// Skip nodes that don't have MULTI protocols
		if !hasMultiProtocol(node) {
			continue
		}

		host := node.PublicHost
		if host == "" {
			if node.Domain != "" {
				host = node.Domain
			} else {
				host = node.Host
			}
		}
		// Only include IP addresses, skip hostnames
		if host != "" && isIPAddress(host) && !seen[host] {
			seen[host] = true
			ips = append(ips, host)
		}
	}

	sort.Strings(ips)
	return ips
}

// hasMultiProtocol checks if a node has MULTI protocols (vless-reality + hysteria2).
func hasMultiProtocol(node models.CatalogNode) bool {
	hasReality := false
	hasHy2 := false
	for _, p := range node.Protocols {
		if !p.Enabled {
			continue
		}
		if p.Type == "vless-reality" {
			hasReality = true
		}
		if p.Type == "hysteria2" {
			hasHy2 = true
		}
	}
	return hasReality && hasHy2
}

func isIPAddress(s string) bool {
	// Simple IPv4 check: X.X.X.X where X is 1-3 digits
	parts := strings.Split(s, ".")
	if len(parts) != 4 {
		return false
	}
	for _, part := range parts {
		if len(part) == 0 || len(part) > 3 {
			return false
		}
		for _, c := range part {
			if c < '0' || c > '9' {
				return false
			}
		}
	}
	return true
}