logfilesrefsstats
diff options
context:
space:
mode:
-rw-r--r--README.md94
-rw-r--r--cmd/vsicd/main.go491
-rw-r--r--go.mod4
-rw-r--r--go.sum22
-rw-r--r--vsic.go (renamed from libvsic/libvsic.go)0
5 files changed, 11 insertions, 600 deletions
diff --git a/README.md b/README.md
index 5580945..e260ae2 100644
--- a/README.md
+++ b/README.md
@@ -1,98 +1,24 @@
# vsic
-![GitHub last commit](https://img.shields.io/github/last-commit/initframs/vsic) ![GitHub License](https://img.shields.io/github/license/initframs/vsic) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/initframs/vsic) ![Static Badge](https://img.shields.io/badge/binary%20size-5.47MB-blue)
+![GitHub last commit](https://img.shields.io/github/last-commit/initframs/vsic) ![GitHub License](https://img.shields.io/github/license/initframs/vsic) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/initframs/vsic) ![Static Badge](https://img.shields.io/badge/binary%20size-5.47MB-blue)
*very* simple internet chat
+this part of the project, `libvsic`, handles framing, parsing, and other useful vsic protocol stuff. if you're looking to run a vsic server, check out [vsicd](https://github.com/initframs/vsicd).
+
## features
- minimal text-based protocol- no client needed, it's simple enough to be used over just plain `nc`
- tiny (5.47M) and fast (starts in 0.004s, stops in 0.005s*)
- easily customizable (toml config!)
- > *note: start time measured as average over 128 starts/stops. excluding fixed sleep times in code
-
-## vsicd
-
-a vsic server written in go, designed to be completely async and have an ultra small footprint. only 1 config file and 3 commands.
-
-```bash
-vsicd start # start the vsic daemon
-vsicd stop # stop the vsic daemon
-vsicd info # see stats like ram/cpu usage, connected clients, and more
-```
-
-```toml
-# ~/.config/vsicd/config.toml
-name = "my cool server"
-motd = """
-i love vsicd
-irc still good though
-""" # vsicd automatically trims blank lines so your config can look better :D
-
-[moderation]
-# banlist = "~/.config/vsicd/bans.txt" (todo)
-# modcmd = "python3 ~/.config/vsicd/moderation.py" (todo)
-
-max_conns_per_ip = 4
-max_msgs_per_sec = 1
-max_msg_size = 4096
-max_keepalive_timeout = 120
-
-[server.tcp]
-enabled = false # exactly one of server.tcp/server.tls must be enabled
-
-[server.tls]
-enabled = true
-port = 4570
-ssl_cert = "/etc/certs/example.com.crt"
-ssl_key = "/etc/certs/example.com.key"
-```
-
-### building vsicd
-
-vsicd is pure go, so there's no need for C interop support :)
-
-`-ldflags="-s -w"` removes the DWARF debugging info and the symbol table. this isn't recommended for development, but it reduces binary size. when reporting errors/bugs, don't use these options.
-
-```bash
-CGO_ENABLED=0 go build -ldflags="-s -w" -o vsicd
-```
+ > *note: start time measured as average over 128 starts/stops. excluding fixed sleep times in code*
## libvsic
libvsic is a collection of utils to help keep protocol behavior repeatable and to allow the protocol to be reused in other client/server implementations.
-## protocol reference
-
-the actual vsic TCP protocol. Commands are sent in the format `COMMAND [param]`.
-
-### commands (client)
-
-the responses in the table are assuming normal behavior, they don't include cases like hitting rate limits or sending invalid parameters.
-
-
-| Command | Sent | Purpose | Responses |
-| ------------------ | --------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
-| `n/a` | when connecting to a server | inform the client they've connected | `CONNECTED` |
-| `HELLO [username]` | when connecting to a server | initiate connection and register a username | `HELLO [username]` (note that if the name is already taken, a random numerical suffix is added), followed by an `MOTD` message |
-| `MSG [msg]` | when sending a message | send a message for the server to broadcast | `MSG [username]: [msg]` is sent to all clients, including the original sender |
-| `PING` | at specific timed intervals | tcp keepalive | `PONG` |
-| `BYE` | when disconnecting | end connection | `CYA`, then server ends connection. |
-
-
-### errors
-
-#### `ERROR 100`
-
-Sent after a malformed command or invalid parameter is received during the handshake. Terminates the connection.
-
-#### `ERROR 101`
-
-Sent after an invalid parameter is received (for example, empty `MSG`), but does not terminate the connection. Indicates the command was ignored by the server.
-
-#### `ERROR 102`
-
-Sent after an invalid command is received, but does not terminate the connection. Indicates the command was ignored by the server.
-
-#### `ERROR 200`
-
-Sent after the client attempts to send a message, but is being rate limited.
+the vsic protocol is designed to be human readable, even over the raw tcp connection. to achieve this, the general command structure is very simple:
+```
+COMMAND param1 param2 [etc etc] \n
+```
+this structure is used both by the client and the server.
+> *note: while the actual vsic protocol works this way, web clients like [lwvc](https://github.com/initframs/lwvc) most likely use a different, json-framed protocol due to the need to communicate with a ws-tcp or wss-tls compatibility layer (example: [wssc](https://github.com/initframs/wssc)) \ No newline at end of file
diff --git a/cmd/vsicd/main.go b/cmd/vsicd/main.go
deleted file mode 100644
index 2661c17..0000000
--- a/cmd/vsicd/main.go
+++ /dev/null
@@ -1,491 +0,0 @@
-package main
-
-import (
- "crypto/tls"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "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"`
- AllowPrivilegedPort bool `toml:"allow_privileged_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 ispidrunning(pid int) bool {
- if pid <= 0 {
- return false
- }
-
- path := "/proc/" + strconv.Itoa(pid)
- info, err := os.Stat(path)
- if err != nil {
- return false
- }
-
- return info.IsDir()
-}
-
-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")
-
- logDir := filepath.Join(baseDir, "logs")
- os.MkdirAll(logDir, 0755)
- logFile, err := os.OpenFile(filepath.Join(logDir, "vsicd.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
- if err != nil {
- fmt.Println("failed to open log file:", err)
- return
- }
-
- cmd.Stdout = logFile
- cmd.Stderr = logFile
-
- if err := cmd.Start(); err != nil {
- fmt.Println("failed to start daemon:", err)
- return
- }
-
- fmt.Println("vsicd started in background, pid:", cmd.Process.Pid)
- time.Sleep(time.Second)
- if !ispidrunning(cmd.Process.Pid) {
- fmt.Println("vsicd crashed at start, the logs below may help:")
- logFile.Seek(0, io.SeekStart)
- io.Copy(os.Stdout, logFile)
- fmt.Println()
- return
- }
- 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, errCert := tls.LoadX509KeyPair(expand(cfg.Server.TLS.Cert), expand(cfg.Server.TLS.Key))
- if errCert != nil {
- panic(errCert)
- }
- 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()
-
- 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)
-
- vconn.WriteLine("CONNECTED")
-
- 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)
-
- if s.cfg.Motd != "" {
- for _, line := range strings.Split(s.cfg.Motd, "\n") {
- if line != "" {
- client.Conn.WriteLine("MOTD " + line)
- }
- }
- }
-
- 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 arg == "" {
- client.Conn.WriteLine("ERROR 101")
- continue
- }
- if time.Since(client.LastMsg) < time.Second/time.Duration(max(1, s.cfg.MaxMsgsPerSec)) {
- client.Conn.WriteLine("ERROR 200")
- 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
-
- default:
- client.Conn.WriteLine("ERROR 102")
- continue
- }
- }
-
- 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
- }
-
- if cfg.MaxConnsPerIP <= 0 {
- cfg.MaxConnsPerIP = 4
- }
-
- if cfg.MaxMsgsPerSec <= 0 {
- cfg.MaxMsgsPerSec = 1
- }
-
- if !cfg.AllowPrivilegedPort {
- cfg.AllowPrivilegedPort = false
- }
-
- tcpOn := cfg.Server.TCP.Enabled
- tlsOn := cfg.Server.TLS.Enabled
- if tcpOn == tlsOn {
- if !tcpOn {
- nicepanic("neither server.tcp nor server.tls is enabled; enable one")
- }
- nicepanic("server.tcp and server.tls cannot both be enabled; enable just one")
- }
-
- if tlsOn {
- if cfg.Server.TLS.Port <= 0 {
- nicepanic("tls enabled but server.tls.port is missing or invalid")
- }
- if cfg.Server.TLS.Cert == "" || cfg.Server.TLS.Key == "" {
- nicepanic("tls enabled but cert or key not defined")
- }
- } else {
- if cfg.Server.TCP.Port <= 0 {
- nicepanic("tcp enabled but server.tcp.port is missing or invalid")
- }
- }
-
- if ((cfg.Server.TLS.Port <= 1000 && cfg.Server.TLS.Enabled) || (cfg.Server.TCP.Port <= 1000 && cfg.Server.TCP.Enabled)) && (cfg.AllowPrivilegedPort == false) {
- nicepanic("it looks like you're trying to run vsicd on a privileged port (<1000). this is disabled by default, but you can enable it by setting `allow_privileged_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, if it should be, check the logs at ~/.config/vsicd/logs/vsicd.log")
- 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
-}
diff --git a/go.mod b/go.mod
index 803a472..69fa8cf 100644
--- a/go.mod
+++ b/go.mod
@@ -1,5 +1,3 @@
module vsic
-go 1.26
-
-require github.com/pelletier/go-toml/v2 v2.3.0 \ No newline at end of file
+go 1.26 \ No newline at end of file
diff --git a/go.sum b/go.sum
deleted file mode 100644
index 1a7fb03..0000000
--- a/go.sum
+++ /dev/null
@@ -1,22 +0,0 @@
-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
-github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
-github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM=
-github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
-github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
-github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
-github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/libvsic/libvsic.go b/vsic.go
index f38a7cf..f38a7cf 100644
--- a/libvsic/libvsic.go
+++ b/vsic.go