Files

1275 lines
26 KiB
Go

package hall
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"maps"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/pion/ice/v4"
"github.com/pion/interceptor"
"github.com/pion/webrtc/v4"
"git.stormux.org/storm/skald/token"
)
var Directory, DataDirectory string
var UseMDNS bool
var UDPMin, UDPMax uint16
var udpMux ice.UDPMux
type NotAuthorisedError struct {
err error
}
func (err *NotAuthorisedError) Error() string {
if err.err != nil {
return "not authorised: " + err.err.Error()
}
return "not authorised"
}
func (err *NotAuthorisedError) Unwrap() error {
return err.err
}
var ErrBadPassword = &NotAuthorisedError{
err: errors.New("bad password"),
}
var ErrNoSuchUsername = &NotAuthorisedError{
err: errors.New("user not found"),
}
var ErrDuplicateUsername = &NotAuthorisedError{
err: errors.New("this username is taken"),
}
type UserError string
func (err UserError) Error() string {
return string(err)
}
type KickError struct {
Id string
Username *string
Message string
}
func (err KickError) Error() string {
m := "kicked out"
if err.Message != "" {
m += " (" + err.Message + ")"
}
if err.Username != nil && *err.Username != "" {
m += " by " + *err.Username
}
return m
}
type ProtocolError string
func (err ProtocolError) Error() string {
return string(err)
}
type ChatHistoryEntry struct {
Id string
Source string
User *string
Time time.Time
Kind string
Value interface{}
}
const (
LowBitrate = 100 * 1024
MinBitrate = LowBitrate * 2
MaxBitrate = 1024 * 1024 * 1024
)
type Hall struct {
name string
mu sync.Mutex
description *Description
locked *string
clients map[string]Client
history []ChatHistoryEntry
timestamp time.Time
data map[string]interface{}
chalkboard ChalkboardState
}
type ChalkboardState struct {
Text string `json:"text"`
Revision uint64 `json:"revision"`
}
func (g *Hall) Name() string {
return g.name
}
func (g *Hall) Locked() (bool, string) {
g.mu.Lock()
defer g.mu.Unlock()
if g.locked != nil {
return true, *g.locked
} else {
return false, ""
}
}
func (g *Hall) SetLocked(locked bool, message string) {
g.mu.Lock()
if locked {
g.locked = &message
} else {
g.locked = nil
}
clients := g.getClientsUnlocked(nil)
g.mu.Unlock()
for _, c := range clients {
c.Joined(g.Name(), "change")
}
}
func (g *Hall) Data() map[string]interface{} {
g.mu.Lock()
defer g.mu.Unlock()
return maps.Clone(g.data)
}
func (g *Hall) UpdateData(d map[string]interface{}) {
g.mu.Lock()
if g.data == nil {
g.data = make(map[string]interface{})
}
for k, v := range d {
if v == nil {
delete(g.data, k)
} else {
g.data[k] = v
}
}
clients := g.getClientsUnlocked(nil)
g.mu.Unlock()
for _, c := range clients {
c.Joined(g.Name(), "change")
}
}
func (g *Hall) Chalkboard() ChalkboardState {
g.mu.Lock()
defer g.mu.Unlock()
return g.chalkboard
}
func (g *Hall) UpdateChalkboard(text string) ChalkboardState {
g.mu.Lock()
defer g.mu.Unlock()
g.chalkboard.Text = text
g.chalkboard.Revision++
return g.chalkboard
}
func (g *Hall) Description() *Description {
g.mu.Lock()
defer g.mu.Unlock()
return g.description
}
func (g *Hall) ClientCount() int {
g.mu.Lock()
defer g.mu.Unlock()
return g.clientCountUnlocked()
}
func (g *Hall) clientCountUnlocked() int {
count := 0
for _, c := range g.clients {
if !isSystemClient(c) {
count++
}
}
return count
}
func (g *Hall) mayExpire() bool {
g.mu.Lock()
defer g.mu.Unlock()
if g.description.Public {
return false
}
if len(g.clients) > 0 {
return false
}
return time.Since(g.timestamp) > maxHistoryAge(g.description)
}
var halls struct {
mu sync.Mutex
halls map[string]*Hall
}
func (g *Hall) API() (*webrtc.API, error) {
g.mu.Lock()
codecs := g.description.Codecs
g.mu.Unlock()
return APIFromNames(codecs)
}
func fmtpValue(fmtp, key string) string {
fields := strings.Split(fmtp, ";")
for _, f := range fields {
k, v, found := strings.Cut(f, "=")
if found && k == key {
return v
}
}
return ""
}
func CodecPayloadType(codec webrtc.RTPCodecCapability) (webrtc.PayloadType, error) {
switch strings.ToLower(codec.MimeType) {
case "audio/opus":
return 111, nil
case "audio/g722":
return 9, nil
case "audio/pcmu":
return 0, nil
case "audio/pcma":
return 8, nil
default:
return 0, fmt.Errorf("unknown codec %v", codec.MimeType)
}
}
// AudioRTCPFeedback is the RTCP feedback for audio tracks.
var AudioRTCPFeedback = []webrtc.RTCPFeedback(nil)
func codecsFromName(name string) ([]webrtc.RTPCodecParameters, error) {
var codecs []webrtc.RTPCodecCapability
switch name {
case "opus":
codecs = []webrtc.RTPCodecCapability{
{
MimeType: "audio/opus",
ClockRate: 48000,
Channels: 2,
SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1",
RTCPFeedback: AudioRTCPFeedback,
},
}
case "g722":
codecs = []webrtc.RTPCodecCapability{
{
MimeType: "audio/G722",
ClockRate: 8000,
Channels: 1,
RTCPFeedback: AudioRTCPFeedback,
},
}
case "pcmu":
codecs = []webrtc.RTPCodecCapability{
{
MimeType: "audio/PCMU",
ClockRate: 8000,
Channels: 1,
RTCPFeedback: AudioRTCPFeedback,
},
}
case "pcma":
codecs = []webrtc.RTPCodecCapability{
{
MimeType: "audio/PCMA",
ClockRate: 8000,
Channels: 1,
RTCPFeedback: AudioRTCPFeedback,
},
}
default:
return nil, errors.New("unknown codec")
}
parms := make([]webrtc.RTPCodecParameters, 0, len(codecs))
for _, c := range codecs {
ptype, err := CodecPayloadType(c)
if err != nil {
log.Printf("Couldn't determine ptype for codec %v: %v",
c.MimeType, err)
continue
}
parms = append(parms, webrtc.RTPCodecParameters{
RTPCodecCapability: c,
PayloadType: ptype,
})
}
return parms, nil
}
func SetUDPMux(port int) error {
var err error
udpMux, err = ice.NewMultiUDPMuxFromPort(port)
return err
}
func APIFromCodecs(codecs []webrtc.RTPCodecParameters) (*webrtc.API, error) {
s := webrtc.SettingEngine{}
s.SetSRTPReplayProtectionWindow(512)
s.DisableActiveTCP(true)
if !UseMDNS {
s.SetICEMulticastDNSMode(ice.MulticastDNSModeDisabled)
}
m := webrtc.MediaEngine{}
for _, codec := range codecs {
err := m.RegisterCodec(codec, webrtc.RTPCodecTypeAudio)
if err != nil {
log.Printf("%v", err)
continue
}
}
if udpMux != nil {
s.SetICEUDPMux(udpMux)
} else if UDPMin > 0 && UDPMax > 0 {
s.SetEphemeralUDPPortRange(UDPMin, UDPMax)
}
ir := interceptor.Registry{}
return webrtc.NewAPI(
webrtc.WithSettingEngine(s),
webrtc.WithMediaEngine(&m),
webrtc.WithInterceptorRegistry(&ir),
), nil
}
func APIFromNames(names []string) (*webrtc.API, error) {
if len(names) == 0 {
names = []string{"opus"}
}
var codecs []webrtc.RTPCodecParameters
for _, n := range names {
cs, err := codecsFromName(n)
if err != nil {
log.Printf("Codec %v: %v", n, err)
continue
}
codecs = append(codecs, cs...)
}
return APIFromCodecs(codecs)
}
func Add(name string, desc *Description) (*Hall, error) {
g, notify, err := add(name, desc)
for _, c := range notify {
c.Joined(g.Name(), "change")
}
return g, err
}
func validHallName(name string) bool {
if strings.ContainsRune(name, '\\') {
return false
}
if s := filepath.Separator; s != '/' && s != '\\' {
if strings.ContainsRune(name, s) {
return false
}
}
s := path.Clean("/" + name)
if s == "/" {
return false
}
return s == "/"+name
}
// ValidHallName reports whether name is safe to use as a hall name.
func ValidHallName(name string) bool {
return validHallName(name)
}
func add(name string, desc *Description) (*Hall, []Client, error) {
if !validHallName(name) {
return nil, nil, UserError("illegal hall name")
}
halls.mu.Lock()
defer halls.mu.Unlock()
if halls.halls == nil {
halls.halls = make(map[string]*Hall)
}
var err error
g := halls.halls[name]
if g == nil {
if desc == nil {
desc, err = readDescription(name, true)
if err != nil {
return nil, nil, err
}
}
g = &Hall{
name: name,
description: desc,
clients: make(map[string]Client),
timestamp: time.Now(),
}
halls.halls[name] = g
}
g.mu.Lock()
defer g.mu.Unlock()
notify := false
if desc != nil {
if !descriptionMatch(g.description, desc) {
g.description = desc
notify = true
}
} else if !descriptionUnchanged(name, g.description) {
desc, err = readDescription(name, true)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Printf("Reading hall %v: %v", name, err)
}
deleteUnlocked(g)
return nil, nil, err
}
g.description = desc
notify = true
}
autoLockKick(g)
var clients []Client
if notify {
clients = g.getClientsUnlocked(nil)
}
return g, clients, nil
}
func Range(f func(g *Hall) bool) {
halls.mu.Lock()
defer halls.mu.Unlock()
for _, g := range halls.halls {
ok := f(g)
if !ok {
break
}
}
}
func GetNames() []string {
names := make([]string, 0)
Range(func(g *Hall) bool {
names = append(names, g.name)
return true
})
return names
}
type SubHall struct {
Name string
Clients int
}
func GetSubHalls(parent string) []SubHall {
prefix := parent + "/"
subhalls := make([]SubHall, 0)
Range(func(g *Hall) bool {
if strings.HasPrefix(g.name, prefix) {
g.mu.Lock()
count := len(g.clients)
g.mu.Unlock()
if count > 0 {
subhalls = append(subhalls,
SubHall{g.name, count})
}
}
return true
})
return subhalls
}
func Get(name string) *Hall {
halls.mu.Lock()
defer halls.mu.Unlock()
if halls.halls == nil {
return nil
}
return halls.halls[name]
}
func Delete(name string) bool {
halls.mu.Lock()
defer halls.mu.Unlock()
g := halls.halls[name]
if g == nil {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
return deleteUnlocked(g)
}
// Called with both halls.mu and g.mu taken.
func deleteUnlocked(g *Hall) bool {
if len(g.clients) != 0 {
return false
}
delete(halls.halls, g.name)
return true
}
func member(v string, l []string) bool {
for _, w := range l {
if v == w {
return true
}
}
return false
}
func isSystemClient(c Client) bool {
return member("system", c.Permissions())
}
func AddClient(hall string, c Client, creds ClientCredentials) (*Hall, error) {
g, err := Add(hall, nil)
if err != nil {
return nil, err
}
g.mu.Lock()
defer g.mu.Unlock()
clients := g.getClientsUnlocked(nil)
systemClient := isSystemClient(c)
if !systemClient {
username, perms, err := g.getPermission(creds)
if err != nil {
return nil, err
}
c.SetUsername(username)
c.SetPermissions(perms)
for _, cc := range clients {
if !isSystemClient(cc) && cc.Username() == username {
return nil, UserError("username already in use")
}
}
if !member("op", perms) {
if g.locked != nil {
m := *g.locked
if m == "" {
m = "Hall is locked."
}
return nil, UserError(m)
}
if g.description.NotBefore != nil ||
g.description.Expires != nil {
now := time.Now()
if g.description.NotBefore != nil &&
g.description.NotBefore.After(now) {
return nil, UserError(
"this hall is not open yet",
)
}
if g.description.Expires != nil &&
g.description.Expires.Before(now) {
return nil, UserError(
"this hall is closed",
)
}
}
if g.description.Autokick {
ops := false
for _, c := range clients {
if member("op", c.Permissions()) {
ops = true
break
}
}
if !ops {
return nil, UserError(
"there are no operators " +
"in this hall",
)
}
}
}
if !member("op", perms) && g.description.MaxClients > 0 {
if g.clientCountUnlocked() >= g.description.MaxClients {
return nil, UserError("too many users")
}
}
}
id := c.Id()
if id == "" {
return nil, errors.New("client has empty id")
}
if g.clients[id] != nil {
return nil, ProtocolError("duplicate client id")
}
g.clients[id] = c
g.timestamp = time.Now()
c.Joined(g.Name(), "join")
u := c.Username()
p := c.Permissions()
s := c.Data()
if !systemClient {
c.PushClient(g.Name(), "add", c.Id(), u, p, s)
}
for _, cc := range clients {
pp := cc.Permissions()
uu := cc.Username()
if !isSystemClient(cc) {
c.PushClient(
g.Name(), "add", cc.Id(), uu, pp, cc.Data(),
)
}
if !systemClient {
cc.PushClient(g.Name(), "add", id, u, p, s)
}
}
return g, nil
}
// called locked
func autoLockKick(g *Hall) {
if !(g.description.Autolock && g.locked == nil) &&
!g.description.Autokick {
return
}
clients := g.getClientsUnlocked(nil)
for _, c := range clients {
if member("op", c.Permissions()) {
return
}
}
if g.description.Autolock && g.locked == nil {
m := "Hall is locked."
g.locked = &m
for _, c := range clients {
c.Joined(g.Name(), "change")
}
}
if g.description.Autokick {
// we cannot call kickall, since it requires the hall to
// be unlocked. And calling it asynchronously might
// spuriously kick out an operator.
go func(clients []Client) {
for _, c := range clients {
c.Kick(
"", nil,
"there are no operators in this hall",
)
}
}(g.getClientsUnlocked(nil))
}
}
func DelClient(c Client) {
g := c.Hall()
if g == nil {
return
}
systemClient := isSystemClient(c)
g.mu.Lock()
if g.clients[c.Id()] != c {
log.Printf("Deleting unknown client")
g.mu.Unlock()
return
}
delete(g.clients, c.Id())
g.timestamp = time.Now()
clients := g.getClientsUnlocked(nil)
g.mu.Unlock()
c.Joined(g.Name(), "leave")
if !systemClient {
for _, cc := range clients {
cc.PushClient(
g.Name(), "delete", c.Id(), c.Username(), nil, nil,
)
}
}
closeSystemClientsIfNoUsers(g, clients)
autoLockKick(g)
}
func closeSystemClientsIfNoUsers(g *Hall, clients []Client) {
var system []Client
for _, c := range clients {
if member("system", c.Permissions()) {
system = append(system, c)
} else {
return
}
}
for _, c := range system {
c.Kick("", nil, "hall is empty")
}
}
func (g *Hall) GetClients(except Client) []Client {
g.mu.Lock()
defer g.mu.Unlock()
return g.getClientsUnlocked(except)
}
func (g *Hall) getClientsUnlocked(except Client) []Client {
clients := make([]Client, 0, len(g.clients))
for _, c := range g.clients {
if c != except {
clients = append(clients, c)
}
}
return clients
}
func (g *Hall) GetClient(id string) Client {
g.mu.Lock()
defer g.mu.Unlock()
return g.getClientUnlocked(id)
}
func (g *Hall) getClientUnlocked(id string) Client {
for idd, c := range g.clients {
if idd == id {
return c
}
}
return nil
}
func (g *Hall) Range(f func(c Client) bool) {
g.mu.Lock()
defer g.mu.Unlock()
for _, c := range g.clients {
ok := f(c)
if !ok {
break
}
}
}
func kickall(g *Hall, message string) {
g.Range(func(c Client) bool {
c.Kick("", nil, message)
return true
})
}
func Shutdown(message string) {
Range(func(g *Hall) bool {
g.SetLocked(true, message)
kickall(g, message)
return true
})
}
type warner interface {
Warn(oponly bool, message string) error
}
func (g *Hall) WallOps(message string) {
clients := g.GetClients(nil)
for _, c := range clients {
w, ok := c.(warner)
if !ok {
continue
}
err := w.Warn(true, message)
if err != nil {
log.Printf("WallOps: %v", err)
}
}
}
const maxChatHistory = 50
// deleteFunc is just like slices.DeleteFunc.
// Remove this once we require Go 1.21.
func deleteFunc[S ~[]E, E any](s S, f func(E) bool) S {
i := 0
for i = range s {
if f(s[i]) {
break
}
}
if i >= len(s) {
return s
}
for j := i + 1; j < len(s); j++ {
if v := s[j]; !f(v) {
s[i] = v
i++
}
}
var zero E
for j := i; j < len(s); j++ {
s[j] = zero
}
return s[:i]
}
func (g *Hall) ClearChatHistory(id string, userId string) {
g.mu.Lock()
defer g.mu.Unlock()
if id == "" && userId == "" {
g.history = nil
return
}
g.history = deleteFunc(g.history, func(e ChatHistoryEntry) bool {
return e.Source == userId && (id == "" || e.Id == id)
})
}
func (g *Hall) AddToChatHistory(id, source string, user *string, time time.Time, kind string, value interface{}) {
g.mu.Lock()
defer g.mu.Unlock()
if len(g.history) >= maxChatHistory {
copy(g.history, g.history[1:])
g.history = g.history[:len(g.history)-1]
}
g.history = append(g.history,
ChatHistoryEntry{Id: id, Source: source, User: user, Time: time, Kind: kind, Value: value},
)
}
func discardObsoleteHistory(h []ChatHistoryEntry, duration time.Duration) []ChatHistoryEntry {
i := 0
for i < len(h) {
if time.Since(h[i].Time) <= duration {
break
}
i++
}
if i > 0 {
copy(h, h[i:])
h = h[:len(h)-i]
}
return h
}
func (g *Hall) GetChatHistory() []ChatHistoryEntry {
g.mu.Lock()
defer g.mu.Unlock()
g.history = discardObsoleteHistory(
g.history, maxHistoryAge(g.description),
)
h := make([]ChatHistoryEntry, len(g.history))
copy(h, g.history)
return h
}
// Configuration represents the contents of the data/config.json file.
type Configuration struct {
// The modtime and size of the file. These are used to detect
// when a file has changed on disk.
modTime time.Time `json:"-"`
fileSize int64 `json:"-"`
CanonicalHost string `json:"canonicalHost,omitempty"`
AllowOrigin []string `json:"allowOrigin,omitempty"`
AllowAdminOrigin []string `json:"allowAdminOrigin,omitempty"`
ProxyURL string `json:"proxyURL,omitempty"`
WritableHalls bool `json:"writableHalls,omitempty"`
RecordingRetention string `json:"recordingRetention,omitempty"`
Users map[string]UserDescription `json:"users,omitempty"`
// obsolete fields
Admin []ClientPattern `json:"admin,omitempty"`
}
func (conf Configuration) Zero() bool {
return conf.modTime.Equal(time.Time{}) &&
conf.fileSize == 0
}
var configuration struct {
mu sync.Mutex
configuration *Configuration
}
func GetConfiguration() (*Configuration, error) {
configuration.mu.Lock()
defer configuration.mu.Unlock()
if configuration.configuration == nil {
configuration.configuration = &Configuration{}
}
filename := filepath.Join(DataDirectory, "config.json")
fi, err := os.Stat(filename)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
if !configuration.configuration.Zero() {
configuration.configuration = &Configuration{}
}
return configuration.configuration, nil
}
return nil, err
}
if configuration.configuration.modTime.Equal(fi.ModTime()) &&
configuration.configuration.fileSize == fi.Size() {
return configuration.configuration, nil
}
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
d := json.NewDecoder(f)
d.DisallowUnknownFields()
var conf Configuration
err = d.Decode(&conf)
if err != nil {
return nil, err
}
if conf.Admin != nil {
log.Printf("%v: field \"admin\" is obsolete, ignored", filename)
conf.Admin = nil
}
configuration.configuration = &conf
return configuration.configuration, nil
}
// called locked
func (g *Hall) getPasswordPermission(creds ClientCredentials) (Permissions, error) {
desc := g.description
if creds.Username == nil {
return Permissions{}, errors.New("username not provided")
}
if desc.Users != nil {
if c, found := desc.Users[*creds.Username]; found {
ok, err := c.Password.Match(creds.Password)
if err != nil {
return Permissions{}, err
}
if ok {
return c.Permissions, nil
} else {
return Permissions{}, ErrBadPassword
}
}
}
if desc.WildcardUser != nil {
ok, _ := desc.WildcardUser.Password.Match(creds.Password)
if ok {
return desc.WildcardUser.Permissions, nil
}
}
return Permissions{}, ErrNoSuchUsername
}
// Return true if there is a user entry with the given username.
// Always return false for an empty username.
func (g *Hall) UserExists(username string) bool {
g.mu.Lock()
defer g.mu.Unlock()
return g.userExists(username)
}
// called locked
func (g *Hall) userExists(username string) bool {
desc := g.description
if desc.Users == nil {
return false
}
_, found := desc.Users[username]
return found
}
// validUsername returns true if a string is a valid username.
// On the one hand, we want to allow usernames such as "jch@work"
// or "Alice c/o Bob". On the other hand, not restricting
// usernames might lead to security vulnaribilities.
// For now, we just do the minimal validation that avoids path traversal.
func validUsername(username string) bool {
return username != "" && validHallName(username)
}
// ValidUsername reports whether username is safe to use as a login name.
func ValidUsername(username string) bool {
return validUsername(username)
}
// called locked
func (g *Hall) getPermission(creds ClientCredentials) (string, []string, error) {
desc := g.description
var username string
var perms []string
if creds.Token != "" {
tok, err := token.Parse(creds.Token, desc.AuthKeys)
if err != nil {
return "", nil, &NotAuthorisedError{err: err}
}
conf, err := GetConfiguration()
if err != nil {
return "", nil, err
}
username, perms, err =
tok.Check(conf.CanonicalHost, g.name, creds.Username)
if err != nil {
return "", nil, &NotAuthorisedError{err: err}
}
if username == "" && creds.Username != nil {
if g.userExists(*creds.Username) {
return "", nil, ErrDuplicateUsername
}
username = *creds.Username
}
} else if creds.Username != nil {
username = *creds.Username
ps, err := g.getPasswordPermission(creds)
if err != nil {
return "", nil, err
}
perms = ps.Permissions(desc)
} else {
return "", nil, errors.New("neither username nor token provided")
}
if !validUsername(username) {
return "", nil, &NotAuthorisedError{
errors.New("invalid username"),
}
}
return username, perms, nil
}
func (g *Hall) GetPermission(creds ClientCredentials) (string, []string, error) {
g.mu.Lock()
defer g.mu.Unlock()
return g.getPermission(creds)
}
type Status struct {
Name string `json:"name"`
Redirect string `json:"redirect,omitempty"`
Location string `json:"location,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Description string `json:"description,omitempty"`
AuthServer string `json:"authServer,omitempty"`
AuthPortal string `json:"authPortal,omitempty"`
Locked bool `json:"locked,omitempty"`
Recording bool `json:"recording,omitempty"`
ClientCount *int `json:"clientCount,omitempty"`
CanChangePassword bool `json:"canChangePassword,omitempty"`
}
// Status returns a hall's status.
// Base is the base URL for halls; if omitted, then both the Location and
// Endpoint members are omitted from the result.
func (g *Hall) Status(authentified bool, base *url.URL) Status {
desc := g.Description()
if desc.Redirect != "" {
return Status{
Name: g.name,
Redirect: desc.Redirect,
DisplayName: desc.DisplayName,
Description: desc.Description,
}
}
var location, endpoint string
if base != nil {
wss := "wss"
if base.Scheme == "http" {
wss = "ws"
}
l := url.URL{
Scheme: base.Scheme,
Host: base.Host,
Path: path.Join(
path.Join(base.Path, "/hall/"),
g.Name()) + "/",
}
location = l.String()
e := url.URL{
Scheme: wss,
Host: base.Host,
Path: path.Join(base.Path, "/ws"),
}
endpoint = e.String()
}
d := Status{
Name: g.name,
Location: location,
Endpoint: endpoint,
DisplayName: desc.DisplayName,
AuthServer: desc.AuthServer,
AuthPortal: desc.AuthPortal,
Description: desc.Description,
}
if authentified || desc.Public {
// these are considered private information
locked, _ := g.Locked()
count := g.ClientCount()
d.Locked = locked
d.ClientCount = &count
}
if authentified {
conf, err := GetConfiguration()
if err == nil {
d.CanChangePassword = conf.WritableHalls
}
}
return d
}
func GetPublic(base *url.URL) []Status {
gs := make([]Status, 0)
Range(func(g *Hall) bool {
if g.Description().Public {
gs = append(gs, g.Status(false, base))
}
return true
})
sort.Slice(gs, func(i, j int) bool {
return gs[i].Name < gs[j].Name
})
return gs
}
// Update checks that all in-memory halls are up-to-date and updates the
// list of public halls. It also removes from memory any non-public
// halls that haven't been accessed in maxHistoryAge.
func Update() {
_, err := GetConfiguration()
if err != nil {
log.Printf("%v: %v",
filepath.Join(DataDirectory, "config.json"),
err,
)
}
names := GetNames()
for _, name := range names {
g := Get(name)
if g == nil {
continue
}
deleted := false
if g.mayExpire() {
// Delete checks if the hall is still empty
deleted = Delete(name)
}
// update hall description
if !deleted {
Add(name, nil)
}
}
err = filepath.WalkDir(
Directory,
func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Printf("Hall file %v: %v", path, err)
return nil
}
if d.IsDir() {
base := filepath.Base(path)
if base[0] == '.' {
log.Printf(
"Ignoring hall directory %v",
path,
)
return fs.SkipDir
}
return nil
}
filename, err := filepath.Rel(Directory, path)
if err != nil {
log.Printf("Hall file %v: %v", path, err)
return nil
}
if !strings.HasSuffix(filename, ".json") {
log.Printf(
"Unexpected extension for hall file %v",
path,
)
return nil
}
base := filepath.Base(filename)
if base[0] == '.' {
log.Printf("Ignoring hall file %v", filename)
return nil
}
name := strings.TrimSuffix(filename, ".json")
desc, err := GetDescription(name)
if err != nil {
log.Printf("Hall file %v: %v", path, err)
return nil
}
if desc.Public {
Add(name, desc)
}
return nil
},
)
if err != nil {
log.Printf("Couldn't read halls: %v", err)
}
}