soju/server.go

117 lines
2.1 KiB
Go
Raw Normal View History

2020-03-13 17:13:03 +00:00
package soju
2020-02-04 09:46:22 +00:00
import (
"fmt"
2020-02-07 10:36:42 +00:00
"log"
2020-02-04 09:46:22 +00:00
"net"
"sync"
"time"
2020-02-04 09:46:22 +00:00
"gopkg.in/irc.v3"
)
// TODO: make configurable
var keepAlivePeriod = time.Minute
var retryConnectMinDelay = time.Minute
var connectTimeout = 15 * time.Second
var writeTimeout = 10 * time.Second
2020-02-06 14:50:46 +00:00
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
}
2020-02-06 19:25:37 +00:00
type prefixLogger struct {
logger Logger
prefix string
}
var _ Logger = (*prefixLogger)(nil)
func (l *prefixLogger) Print(v ...interface{}) {
v = append([]interface{}{l.prefix}, v...)
l.logger.Print(v...)
}
func (l *prefixLogger) Printf(format string, v ...interface{}) {
v = append([]interface{}{l.prefix}, v...)
l.logger.Printf("%v"+format, v...)
}
2020-02-06 15:03:07 +00:00
type Server struct {
2020-03-04 18:23:24 +00:00
Hostname string
Logger Logger
RingCap int
LogPath string
2020-03-04 18:23:24 +00:00
Debug bool
db *DB
lock sync.Mutex
users map[string]*user
2020-02-07 10:36:42 +00:00
}
func NewServer(db *DB) *Server {
2020-02-07 10:36:42 +00:00
return &Server{
Logger: log.New(log.Writer(), "", log.LstdFlags),
RingCap: 4096,
users: make(map[string]*user),
db: db,
2020-02-07 10:36:42 +00:00
}
2020-02-04 17:56:07 +00:00
}
2020-02-04 09:46:22 +00:00
2020-02-04 17:56:07 +00:00
func (s *Server) prefix() *irc.Prefix {
return &irc.Prefix{Name: s.Hostname}
}
2020-02-04 10:25:53 +00:00
func (s *Server) Run() error {
users, err := s.db.ListUsers()
if err != nil {
return err
}
2020-02-07 10:36:42 +00:00
s.lock.Lock()
for _, record := range users {
s.Logger.Printf("starting bouncer for user %q", record.Username)
u := newUser(s, &record)
s.users[u.Username] = u
2020-02-07 10:36:42 +00:00
go u.run()
2020-02-06 15:03:07 +00:00
}
s.lock.Unlock()
select {}
2020-02-06 15:03:07 +00:00
}
2020-02-07 10:39:56 +00:00
func (s *Server) getUser(name string) *user {
s.lock.Lock()
u := s.users[name]
s.lock.Unlock()
return u
}
2020-02-04 10:25:53 +00:00
func (s *Server) Serve(ln net.Listener) error {
var nextDownstreamID uint64 = 1
2020-02-04 09:46:22 +00:00
for {
netConn, err := ln.Accept()
2020-02-04 09:46:22 +00:00
if err != nil {
return fmt.Errorf("failed to accept connection: %v", err)
}
dc := newDownstreamConn(s, netConn, nextDownstreamID)
nextDownstreamID++
2020-02-04 09:46:22 +00:00
go func() {
if err := dc.runUntilRegistered(); err != nil {
dc.logger.Print(err)
} else {
dc.user.events <- eventDownstreamConnected{dc}
if err := dc.readMessages(dc.user.events); err != nil {
dc.logger.Print(err)
}
dc.user.events <- eventDownstreamDisconnected{dc}
2020-02-04 09:46:22 +00:00
}
2020-02-18 15:54:06 +00:00
dc.Close()
2020-02-04 09:46:22 +00:00
}()
}
}