logfilesrefsstats
path: root/cmd/vsicd/main.go
blob: 2ebe50ea57770ab1121688f1287b6ea373fbe076 (plain) (blame)
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
	vsic "vsic/libvsic"

	"github.com/pelletier/go-toml/v2"
)

type Config struct {
	Name                 string `toml:"name"`
	Motd                 string `toml:"motd"`
	AllowPriviledgedPort bool   `toml:"allow_priviledged_port"`

	Moderation struct {
		Banlist string `toml:"banlist"`
		Modcmd  string `toml:"modcmd"`
	} `toml:"moderation"`

	MaxConnsPerIP int `toml:"max_conns_per_ip"`
	MaxMsgsPerSec int `toml:"max_msgs_per_sec"`
	MaxMsgSize    int `toml:"max_msg_size"`
	MaxKeepalive  int `toml:"max_keepalive_timeout"`

	Server struct {
		TCP struct {
			Enabled bool `toml:"enabled"`
			Port    int  `toml:"port"`
		} `toml:"tcp"`
		TLS struct {
			Enabled bool   `toml:"enabled"`
			Port    int    `toml:"port"`
			Cert    string `toml:"ssl_cert"`
			Key     string `toml:"ssl_key"`
		} `toml:"tls"`
	} `toml:"server"`
}

type Client struct {
	Conn     *vsic.Conn
	Send     chan string
	IP       string
	LastMsg  time.Time
	MsgCount int
}

type Server struct {
	cfg       Config
	clients   map[string]*Client
	ipCounts  map[string]int
	mu        sync.RWMutex
	startTime time.Time
	totalMsg  int64
}

var (
	baseDir  = filepath.Join(os.Getenv("HOME"), ".config/vsicd")
	pidFile  = filepath.Join(baseDir, "vsicd.pid")
	statFile = filepath.Join(baseDir, "vsicd.stats")
)

func nicepanic(s string) {
	fmt.Println(s)
	os.Exit(1)
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("usage: vsicd [start|stop|info]")
		return
	}

	switch os.Args[1] {
	case "start":
		start()
	case "stop":
		stop()
	case "info":
		info()
	}
}

func start() {
	if data, err := os.ReadFile(pidFile); err == nil {
		pidStr := strings.TrimSpace(string(data))
		pid, _ := strconv.Atoi(pidStr)
		if err := syscall.Kill(pid, 0); err == nil {
			fmt.Println("vsicd is already running, PID:", pid)
			return
		}
		os.Remove(pidFile)
	}

	if os.Getenv("_VSICD_DAEMON") != "1" {
		cmd := exec.Command(os.Args[0], "start")
		cmd.Env = append(os.Environ(), "_VSICD_DAEMON=1")
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		if err := cmd.Start(); err != nil {
			fmt.Println("failed to start daemon:", err)
			return
		}
		fmt.Println("vsicd started in background, pid:", cmd.Process.Pid)
		return
	}

	cfg := loadConfig()
	writePID()

	s := &Server{
		cfg:       cfg,
		clients:   make(map[string]*Client),
		ipCounts:  make(map[string]int),
		startTime: time.Now(),
	}

	go s.writeStats()

	var ln net.Listener
	var err error

	if cfg.Server.TLS.Enabled {
		cert, err := tls.LoadX509KeyPair(expand(cfg.Server.TLS.Cert), expand(cfg.Server.TLS.Key))
		if err != nil {
			panic(err)
		}
		ln, err = tls.Listen("tcp", fmt.Sprintf(":%d", cfg.Server.TLS.Port),
			&tls.Config{Certificates: []tls.Certificate{cert}})
	} else {
		ln, err = net.Listen("tcp", fmt.Sprintf(":%d", cfg.Server.TCP.Port))
	}
	if err != nil {
		panic(err)
	}

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sig
		fmt.Println("shutting down...")
		ln.Close() // stop accepting new conns

		s.mu.Lock()
		for _, c := range s.clients {
			c.Conn.Close()
		}
		s.mu.Unlock()

		os.Remove(pidFile)
		fmt.Println("vsicd stopped")
		os.Exit(0)
	}()

	for {
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		go s.handle(conn)
	}
}

func (s *Server) handle(nc net.Conn) {
	ip := strings.Split(nc.RemoteAddr().String(), ":")[0]

	s.mu.Lock()
	if s.ipCounts[ip] >= s.cfg.MaxConnsPerIP {
		s.mu.Unlock()
		nc.Close()
		return
	}
	s.ipCounts[ip]++
	s.mu.Unlock()

	vconn := vsic.Wrap(nc, vsic.Config{
		MaxMsgSize: s.cfg.MaxMsgSize,
		TimeoutSec: s.cfg.MaxKeepalive,
	})

	client := &Client{
		Conn: vconn,
		Send: make(chan string, 16),
		IP:   ip,
	}

	go s.writeLoop(client)

	line, err := vconn.ReadLine()
	if err != nil {
		s.disconnect(client)
		return
	}

	cmd, arg := vsic.ParseCommand(line)
	if cmd != "HELLO" || !vsic.ValidNick(arg) {
		vconn.WriteLine("ERROR 100")
		s.disconnect(client)
		return
	}

	nick := s.uniqueNick(arg)
	vconn.Nick = nick
	client.Conn.WriteLine("HELLO " + nick)

	s.mu.Lock()
	s.clients[nick] = client
	s.mu.Unlock()

	for {
		line, err := vconn.ReadLine()
		if err != nil {
			break
		}

		cmd, arg := vsic.ParseCommand(line)

		switch cmd {

		case "MSG":
			if time.Since(client.LastMsg) < time.Second/time.Duration(max(1, s.cfg.MaxMsgsPerSec)) {
				continue
			}
			client.LastMsg = time.Now()
			s.broadcast("MSG " + nick + ": " + arg)

		case "PING":
			client.Conn.WriteLine("PONG")

		case "BYE":
			client.Conn.WriteLine("CYA")
			s.disconnect(client)
			return
		}
	}

	s.disconnect(client)
}

func (s *Server) writeLoop(c *Client) {
	for msg := range c.Send {
		c.Conn.WriteLine(msg)
	}
}

func (s *Server) broadcast(msg string) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	for _, c := range s.clients {
		select {
		case c.Send <- msg:
		default:
		}
	}
	s.totalMsg++
}

func (s *Server) disconnect(c *Client) {
	c.Conn.Close()
	close(c.Send)

	s.mu.Lock()
	delete(s.clients, c.Conn.Nick)
	s.ipCounts[c.IP]--
	s.mu.Unlock()
}

func (s *Server) uniqueNick(n string) string {
	s.mu.RLock()
	_, exists := s.clients[n]
	s.mu.RUnlock()

	if !exists {
		return n
	}
	return n + vsic.RandomSuffix()
}

func (s *Server) writeStats() {
	for {
		time.Sleep(5 * time.Second)
		m := runtime.MemStats{}
		runtime.ReadMemStats(&m)

		stats := map[string]interface{}{
			"clients":    len(s.clients),
			"goroutines": runtime.NumGoroutine(),
			"mem_mb":     m.Alloc / 1024 / 1024,
			"uptime_sec": int(time.Since(s.startTime).Seconds()),
			"messages":   s.totalMsg,
		}

		data, _ := json.MarshalIndent(stats, "", "  ")
		os.WriteFile(statFile, data, 0644)
	}
}

func loadConfig() Config {
	cfgPath := expand(filepath.Join(baseDir, "config.toml"))
	if _, err := os.Stat(cfgPath); errors.Is(err, os.ErrNotExist) {
		nicepanic("config not found, try creating it at ~/.config/vsicd/config.toml")
	}
	data, err := os.ReadFile(cfgPath)
	if err != nil {
		panic(err)
	}
	var cfg Config
	if err := toml.Unmarshal(data, &cfg); err != nil {
		nicepanic("invalid toml config")
	}

	// todo: more config validation

	if cfg.MaxMsgSize <= 0 {
		cfg.MaxMsgSize = 4096 // so that someone cant just nuke the entire server if MaxMsgSize isnt specified
	}

	if cfg.MaxConnsPerIP <= 0 {
		cfg.MaxConnsPerIP = 4
	}

	if cfg.MaxMsgsPerSec <= 0 {
		cfg.MaxMsgsPerSec = 1
	}

	if !cfg.AllowPriviledgedPort {
		cfg.AllowPriviledgedPort = false
	}

	if cfg.Server.TLS.Port == 0 && cfg.Server.TCP.Port == 0 {
		nicepanic("no tcp or tls port defined, nothing to do")
	}

	if cfg.Server.TLS.Enabled && (cfg.Server.TLS.Cert == "" || cfg.Server.TLS.Key == "") {
		nicepanic("tls enabled but cert or key not defined")
	}

	if ((cfg.Server.TLS.Port <= 1000 && cfg.Server.TLS.Enabled) || (cfg.Server.TCP.Port <= 1000 && cfg.Server.TCP.Enabled)) && (cfg.AllowPriviledgedPort == false) {
		fmt.Println(cfg.Server.TLS.Port)
		fmt.Println(cfg.Server.TCP.Port)
		nicepanic("it looks like you're trying to run vsicd on a priviledged port (<1000). this is disabled by default, but you can enable it by setting `allow_priviledged_port` at the root of your config")
	}

	return cfg
}

func writePID() {
	os.MkdirAll(baseDir, 0755)
	os.WriteFile(pidFile, []byte(fmt.Sprint(os.Getpid())), 0644)
}

func stop() {
	data, err := os.ReadFile(pidFile)
	if err != nil {
		fmt.Println("vsicd not running")
		return
	}

	pidStr := strings.TrimSpace(string(data))
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		fmt.Println("invalid PID file, removing")
		os.Remove(pidFile)
		return
	}

	if err := syscall.Kill(pid, 0); err != nil {
		fmt.Println("process not running, removing stale PID file")
		os.Remove(pidFile)
		return
	}

	proc, _ := os.FindProcess(pid)
	fmt.Println("sending SIGTERM to process", pid)
	proc.Signal(syscall.SIGTERM)

	for i := 0; i < 10; i++ {
		time.Sleep(time.Second)
		if err := syscall.Kill(pid, 0); err != nil {
			os.Remove(pidFile)
			fmt.Println("vsicd stopped successfully")
			return
		}
	}

	fmt.Println("warning: vsicd may not have stopped!")
}

func info() {
	data, err := os.ReadFile(statFile)
	if err != nil {
		fmt.Println("no stats")
		return
	}
	os.Stdout.Write(data)
	fmt.Println()
}

func expand(p string) string {
	if strings.HasPrefix(p, "~/") {
		return filepath.Join(os.Getenv("HOME"), p[2:])
	}
	return p
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}