From da18a6e261ac7602e824ced203d0555935e2c5a0 Mon Sep 17 00:00:00 2001 From: initframs Date: Thu, 18 Jun 2026 18:11:14 -0700 Subject: restruct: seperate libvsic and vsicd --- README.md | 94 ++-------- cmd/vsicd/main.go | 491 ----------------------------------------------------- go.mod | 4 +- go.sum | 22 --- libvsic/libvsic.go | 131 -------------- vsic.go | 131 ++++++++++++++ 6 files changed, 142 insertions(+), 731 deletions(-) delete mode 100644 cmd/vsicd/main.go delete mode 100644 go.sum delete mode 100644 libvsic/libvsic.go create mode 100644 vsic.go 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/libvsic/libvsic.go deleted file mode 100644 index f38a7cf..0000000 --- a/libvsic/libvsic.go +++ /dev/null @@ -1,131 +0,0 @@ -package vsic - -import ( - "bufio" - "crypto/rand" - "encoding/binary" - "errors" - "net" - "strings" - "time" -) - -const Version = "0.1.0" - -type Config struct { - MaxMsgSize int - TimeoutSec int -} - -type Conn struct { - NetConn net.Conn - R *bufio.Reader - W *bufio.Writer - Nick string - cfg Config -} - -func Wrap(c net.Conn, cfg Config) *Conn { - if cfg.MaxMsgSize <= 0 { - cfg.MaxMsgSize = 4096 - } - if cfg.TimeoutSec <= 0 { - cfg.TimeoutSec = 120 - } - - return &Conn{ - NetConn: c, - R: bufio.NewReaderSize(c, cfg.MaxMsgSize), - W: bufio.NewWriter(c), - cfg: cfg, - } -} - -func (c *Conn) Close() error { - return c.NetConn.Close() -} - -func (c *Conn) ReadLine() (string, error) { - _ = c.NetConn.SetReadDeadline(time.Now().Add(time.Duration(c.cfg.TimeoutSec) * time.Second)) - - line, err := c.R.ReadString('\n') - if err != nil { - return "", err - } - - if len(line) > c.cfg.MaxMsgSize { - return "", errors.New("message too big") - } - - line = strings.TrimRight(line, "\r\n") - - if strings.Contains(line, "\n") || strings.Contains(line, "\r") { - return "", errors.New("invalid control chars") - } - - return line, nil -} - -func (c *Conn) WriteLine(s string) error { - _ = c.NetConn.SetWriteDeadline(time.Now().Add(10 * time.Second)) - - if len(s) > c.cfg.MaxMsgSize { - return errors.New("message too big") - } - - if strings.ContainsAny(s, "\n\r") { - return errors.New("invalid control chars") - } - - if _, err := c.W.WriteString(s + "\n"); err != nil { - return err - } - - return c.W.Flush() -} - -func ParseCommand(line string) (cmd string, arg string) { - if i := strings.IndexByte(line, ' '); i != -1 { - return line[:i], strings.TrimSpace(line[i+1:]) - } - return line, "" -} - -func ValidNick(n string) bool { - if len(n) < 3 || len(n) > 20 { - return false - } - for _, r := range n { - if !(r >= 'a' && r <= 'z' || - r >= 'A' && r <= 'Z' || - r >= '0' && r <= '9' || - r == '_') { - return false - } - } - return true -} - -func RandomSuffix() string { - var b [2]byte - _, _ = rand.Read(b[:]) - n := binary.BigEndian.Uint16(b[:]) % 10000 - return "_" + pad4(int(n)) -} - -func pad4(n int) string { - if n < 10 { - return "000" + itoa(n) - } - if n < 100 { - return "00" + itoa(n) - } - if n < 1000 { - return "0" + itoa(n) - } - return itoa(n) -} - -func itoa(n int) string { - return strings.TrimPrefix(strings.TrimPrefix(time.Unix(int64(n), 0).UTC().Format("0000"), "1970"), "") -} diff --git a/vsic.go b/vsic.go new file mode 100644 index 0000000..f38a7cf --- /dev/null +++ b/vsic.go @@ -0,0 +1,131 @@ +package vsic + +import ( + "bufio" + "crypto/rand" + "encoding/binary" + "errors" + "net" + "strings" + "time" +) + +const Version = "0.1.0" + +type Config struct { + MaxMsgSize int + TimeoutSec int +} + +type Conn struct { + NetConn net.Conn + R *bufio.Reader + W *bufio.Writer + Nick string + cfg Config +} + +func Wrap(c net.Conn, cfg Config) *Conn { + if cfg.MaxMsgSize <= 0 { + cfg.MaxMsgSize = 4096 + } + if cfg.TimeoutSec <= 0 { + cfg.TimeoutSec = 120 + } + + return &Conn{ + NetConn: c, + R: bufio.NewReaderSize(c, cfg.MaxMsgSize), + W: bufio.NewWriter(c), + cfg: cfg, + } +} + +func (c *Conn) Close() error { + return c.NetConn.Close() +} + +func (c *Conn) ReadLine() (string, error) { + _ = c.NetConn.SetReadDeadline(time.Now().Add(time.Duration(c.cfg.TimeoutSec) * time.Second)) + + line, err := c.R.ReadString('\n') + if err != nil { + return "", err + } + + if len(line) > c.cfg.MaxMsgSize { + return "", errors.New("message too big") + } + + line = strings.TrimRight(line, "\r\n") + + if strings.Contains(line, "\n") || strings.Contains(line, "\r") { + return "", errors.New("invalid control chars") + } + + return line, nil +} + +func (c *Conn) WriteLine(s string) error { + _ = c.NetConn.SetWriteDeadline(time.Now().Add(10 * time.Second)) + + if len(s) > c.cfg.MaxMsgSize { + return errors.New("message too big") + } + + if strings.ContainsAny(s, "\n\r") { + return errors.New("invalid control chars") + } + + if _, err := c.W.WriteString(s + "\n"); err != nil { + return err + } + + return c.W.Flush() +} + +func ParseCommand(line string) (cmd string, arg string) { + if i := strings.IndexByte(line, ' '); i != -1 { + return line[:i], strings.TrimSpace(line[i+1:]) + } + return line, "" +} + +func ValidNick(n string) bool { + if len(n) < 3 || len(n) > 20 { + return false + } + for _, r := range n { + if !(r >= 'a' && r <= 'z' || + r >= 'A' && r <= 'Z' || + r >= '0' && r <= '9' || + r == '_') { + return false + } + } + return true +} + +func RandomSuffix() string { + var b [2]byte + _, _ = rand.Read(b[:]) + n := binary.BigEndian.Uint16(b[:]) % 10000 + return "_" + pad4(int(n)) +} + +func pad4(n int) string { + if n < 10 { + return "000" + itoa(n) + } + if n < 100 { + return "00" + itoa(n) + } + if n < 1000 { + return "0" + itoa(n) + } + return itoa(n) +} + +func itoa(n int) string { + return strings.TrimPrefix(strings.TrimPrefix(time.Unix(int64(n), 0).UTC().Format("0000"), "1970"), "") +} -- cgit v1.2.3