1
Fork 0
mirror of https://github.com/jech/galene.git synced 2024-11-23 00:55:58 +01:00
galene/group/group.go

1355 lines
27 KiB
Go
Raw Normal View History

package group
2020-04-24 19:38:21 +02:00
import (
2020-04-25 02:25:51 +02:00
"encoding/json"
2020-12-02 00:07:31 +01:00
"errors"
"io/fs"
2020-04-24 19:38:21 +02:00
"log"
2021-10-29 23:37:05 +02:00
"net/url"
2020-04-25 02:25:51 +02:00
"os"
2020-11-22 19:54:54 +01:00
"path"
2020-04-25 02:25:51 +02:00
"path/filepath"
2020-04-29 16:08:07 +02:00
"sort"
2020-04-25 04:08:43 +02:00
"strings"
2020-04-25 17:36:35 +02:00
"sync"
"time"
2020-04-24 19:38:21 +02:00
2020-10-06 06:08:29 +02:00
"github.com/pion/ice/v2"
2021-04-29 17:03:25 +02:00
"github.com/pion/sdp/v3"
2020-07-16 20:17:32 +02:00
"github.com/pion/webrtc/v3"
2021-10-29 23:37:05 +02:00
"github.com/jech/galene/token"
2020-04-24 19:38:21 +02:00
)
var Directory, DataDirectory string
2020-10-06 06:08:29 +02:00
var UseMDNS bool
2021-04-29 22:02:36 +02:00
var UDPMin, UDPMax uint16
2020-12-02 00:07:31 +01:00
var ErrNotAuthorised = errors.New("not authorised")
var ErrAnonymousNotAuthorised = errors.New("anonymous users not authorised in this group")
2020-12-02 00:07:31 +01:00
type UserError string
func (err UserError) Error() string {
return string(err)
}
2020-11-30 16:26:11 +01:00
type KickError struct {
Id string
Username string
Message string
}
func (err KickError) Error() string {
m := "kicked out"
if err.Message != "" {
2021-08-24 00:04:30 +02:00
m += " (" + err.Message + ")"
2020-11-30 16:26:11 +01:00
}
if err.Username != "" {
m += " by " + err.Username
}
return m
}
type ProtocolError string
func (err ProtocolError) Error() string {
return string(err)
}
type ChatHistoryEntry struct {
Id string
User string
2020-10-08 14:38:33 +02:00
Time int64
Kind string
Value interface{}
2020-04-25 21:16:49 +02:00
}
const (
2021-05-11 15:28:30 +02:00
LowBitrate = 100 * 1024
MinBitrate = LowBitrate * 2
2022-01-25 19:45:49 +01:00
MaxBitrate = 1024 * 1024 * 1024
)
type Group struct {
name string
2020-04-24 19:38:21 +02:00
mu sync.Mutex
description *Description
locked *string
clients map[string]Client
history []ChatHistoryEntry
timestamp time.Time
data map[string]interface{}
2020-04-24 19:38:21 +02:00
}
func (g *Group) Name() string {
return g.name
}
2020-09-18 11:40:00 +02:00
func (g *Group) Locked() (bool, string) {
g.mu.Lock()
defer g.mu.Unlock()
2020-09-24 22:03:41 +02:00
if g.locked != nil {
2020-09-18 11:40:00 +02:00
return true, *g.locked
} else {
return false, ""
}
}
2020-09-18 11:40:00 +02:00
func (g *Group) SetLocked(locked bool, message string) {
g.mu.Lock()
2020-09-18 11:40:00 +02:00
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 *Group) Data() map[string]interface{} {
g.mu.Lock()
defer g.mu.Unlock()
return g.data
}
func (g *Group) 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 *Group) Description() *Description {
g.mu.Lock()
defer g.mu.Unlock()
return g.description
}
2021-10-26 22:22:48 +02:00
func (g *Group) ClientCount() int {
g.mu.Lock()
defer g.mu.Unlock()
return len(g.clients)
}
2022-10-08 22:46:28 +02:00
func (g *Group) mayExpire() bool {
g.mu.Lock()
defer g.mu.Unlock()
2022-10-08 22:46:28 +02:00
if g.description.Public {
return false
}
if len(g.clients) > 0 {
2022-10-08 22:46:28 +02:00
return false
}
2022-10-08 22:46:28 +02:00
return time.Since(g.timestamp) > maxHistoryAge(g.description)
}
2020-04-24 19:38:21 +02:00
var groups struct {
mu sync.Mutex
groups map[string]*Group
2020-04-24 19:38:21 +02:00
}
2021-04-29 20:38:06 +02:00
func (g *Group) 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 {
kv := strings.SplitN(f, "=", 2)
if len(kv) != 2 {
continue
}
if kv[0] == key {
return kv[1]
}
}
return ""
2020-09-13 13:01:06 +02:00
}
func CodecPayloadType(codec webrtc.RTPCodecCapability) (webrtc.PayloadType, error) {
switch strings.ToLower(codec.MimeType) {
case "video/vp8":
return 96, nil
case "video/vp9":
profile := fmtpValue(codec.SDPFmtpLine, "profile-id")
switch profile {
case "0":
return 98, nil
case "2":
return 100, nil
default:
return 0, errors.New("unknown VP9 profile")
}
case "video/av1":
return 35, nil
case "video/h264":
profile := fmtpValue(codec.SDPFmtpLine, "profile-level-id")
if len(profile) < 4 {
return 0, errors.New("malforned H.264 profile")
}
switch strings.ToLower(profile[:4]) {
case "4200":
return 102, nil
case "42e0":
return 108, nil
default:
return 0, errors.New("unknown H.264 profile")
}
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, errors.New("unknown codec")
}
}
func codecsFromName(name string) ([]webrtc.RTPCodecParameters, error) {
fb := []webrtc.RTCPFeedback{
{"goog-remb", ""},
{"nack", ""},
{"nack", "pli"},
{"ccm", "fir"},
}
var codecs []webrtc.RTPCodecCapability
switch name {
case "vp8":
codecs = []webrtc.RTPCodecCapability{
{
"video/VP8", 90000, 0,
"",
fb,
},
}
case "vp9":
codecs = []webrtc.RTPCodecCapability{
{
"video/VP9", 90000, 0,
"profile-id=0",
fb,
},
{
"video/VP9", 90000, 0,
"profile-id=2",
fb,
},
}
case "av1":
codecs = []webrtc.RTPCodecCapability{
{
"video/AV1", 90000, 0,
"",
fb,
},
}
case "h264":
codecs = []webrtc.RTPCodecCapability{
{
"video/H264", 90000, 0,
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
fb,
},
}
case "opus":
codecs = []webrtc.RTPCodecCapability{
{
"audio/opus", 48000, 2,
"minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1",
nil,
},
}
case "g722":
codecs = []webrtc.RTPCodecCapability{
{
"audio/G722", 8000, 1,
"",
nil,
},
}
case "pcmu":
codecs = []webrtc.RTPCodecCapability{
{
"audio/PCMU", 8000, 1,
"",
nil,
},
}
case "pcma":
codecs = []webrtc.RTPCodecCapability{
{
"audio/PCMU", 8000, 1,
"",
nil,
},
}
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 APIFromCodecs(codecs []webrtc.RTPCodecParameters) (*webrtc.API, error) {
s := webrtc.SettingEngine{}
s.SetSRTPReplayProtectionWindow(512)
if !UseMDNS {
s.SetICEMulticastDNSMode(ice.MulticastDNSModeDisabled)
}
m := webrtc.MediaEngine{}
for _, codec := range codecs {
tpe := webrtc.RTPCodecTypeVideo
if strings.HasPrefix(strings.ToLower(codec.MimeType), "audio/") {
tpe = webrtc.RTPCodecTypeAudio
}
err := m.RegisterCodec(codec, tpe)
2021-04-29 20:38:06 +02:00
if err != nil {
log.Printf("%v", err)
continue
}
2020-04-24 19:38:21 +02:00
}
2021-04-29 22:02:36 +02:00
if UDPMin > 0 && UDPMax > 0 {
s.SetEphemeralUDPPortRange(UDPMin, UDPMax)
}
2021-04-29 17:03:25 +02:00
m.RegisterHeaderExtension(
webrtc.RTPHeaderExtensionCapability{sdp.SDESMidURI},
webrtc.RTPCodecTypeVideo)
m.RegisterHeaderExtension(
webrtc.RTPHeaderExtensionCapability{sdp.SDESRTPStreamIDURI},
webrtc.RTPCodecTypeVideo)
2021-04-29 22:02:36 +02:00
return webrtc.NewAPI(
webrtc.WithSettingEngine(s),
webrtc.WithMediaEngine(&m),
2021-04-29 20:38:06 +02:00
), nil
}
2021-04-29 20:38:06 +02:00
func APIFromNames(names []string) (*webrtc.API, error) {
if len(names) == 0 {
names = []string{"vp8", "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) (*Group, error) {
g, notify, err := add(name, desc)
for _, c := range notify {
c.Joined(g.Name(), "change")
}
return g, err
}
func validGroupName(name string) bool {
if filepath.Separator != '/' &&
strings.ContainsRune(name, filepath.Separator) {
return false
}
s := path.Clean("/" + name)
if s == "/" {
return false
}
return s == "/"+name
}
func add(name string, desc *Description) (*Group, []Client, error) {
if !validGroupName(name) {
return nil, nil, UserError("illegal group name")
}
groups.mu.Lock()
defer groups.mu.Unlock()
if groups.groups == nil {
groups.groups = make(map[string]*Group)
}
2020-04-24 19:38:21 +02:00
2020-04-25 04:08:43 +02:00
var err error
2020-04-24 19:38:21 +02:00
g := groups.groups[name]
if g == nil {
2020-04-25 17:36:35 +02:00
if desc == nil {
desc, err = readDescription(name)
2020-04-25 04:08:43 +02:00
if err != nil {
return nil, nil, err
2020-04-25 04:08:43 +02:00
}
2020-04-25 02:25:51 +02:00
}
g = &Group{
2020-04-25 02:25:51 +02:00
name: name,
description: desc,
clients: make(map[string]Client),
timestamp: time.Now(),
2020-04-24 19:38:21 +02:00
}
groups.groups[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)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("Reading group %v: %v", name, err)
}
deleteUnlocked(g)
return nil, nil, err
}
g.description = desc
notify = true
2020-04-24 19:38:21 +02:00
}
autoLockKick(g)
2020-04-24 19:38:21 +02:00
var clients []Client
if notify {
clients = g.getClientsUnlocked(nil)
}
return g, clients, nil
2020-04-24 19:38:21 +02:00
}
func Range(f func(g *Group) bool) {
2020-04-29 16:08:07 +02:00
groups.mu.Lock()
defer groups.mu.Unlock()
2020-09-13 12:24:06 +02:00
for _, g := range groups.groups {
ok := f(g)
if !ok {
break
}
2020-04-29 16:08:07 +02:00
}
2020-09-13 12:24:06 +02:00
}
func GetNames() []string {
2020-09-13 12:24:06 +02:00
names := make([]string, 0)
Range(func(g *Group) bool {
2020-09-13 12:24:06 +02:00
names = append(names, g.name)
return true
})
2020-04-29 16:08:07 +02:00
return names
}
2020-12-02 19:47:32 +01:00
type SubGroup struct {
Name string
Clients int
}
func GetSubGroups(parent string) []SubGroup {
prefix := parent + "/"
subgroups := make([]SubGroup, 0)
Range(func(g *Group) bool {
if strings.HasPrefix(g.name, prefix) {
g.mu.Lock()
count := len(g.clients)
g.mu.Unlock()
if count > 0 {
subgroups = append(subgroups,
SubGroup{g.name, count})
}
}
return true
})
return subgroups
}
func Get(name string) *Group {
2020-04-29 16:08:07 +02:00
groups.mu.Lock()
defer groups.mu.Unlock()
if groups.groups == nil {
return nil
}
2020-04-29 16:08:07 +02:00
return groups.groups[name]
}
func Delete(name string) bool {
groups.mu.Lock()
defer groups.mu.Unlock()
2020-04-24 19:38:21 +02:00
g := groups.groups[name]
if g == nil {
2020-12-02 00:07:31 +01:00
return false
2020-04-24 19:38:21 +02:00
}
g.mu.Lock()
defer g.mu.Unlock()
return deleteUnlocked(g)
}
// Called with both groups.mu and g.mu taken.
func deleteUnlocked(g *Group) bool {
2020-04-24 19:38:21 +02:00
if len(g.clients) != 0 {
return false
}
delete(groups.groups, g.name)
2020-04-24 19:38:21 +02:00
return true
}
func member(v string, l []string) bool {
for _, w := range l {
if v == w {
return true
}
}
return false
}
func AddClient(group string, c Client, creds ClientCredentials) (*Group, error) {
2020-11-29 14:26:42 +01:00
g, err := Add(group, nil)
2020-04-24 19:38:21 +02:00
if err != nil {
return nil, err
2020-04-24 19:38:21 +02:00
}
g.mu.Lock()
defer g.mu.Unlock()
2021-01-17 21:52:26 +01:00
clients := g.getClientsUnlocked(nil)
if !member("system", c.Permissions()) {
2022-09-08 20:55:05 +02:00
username, perms, err := g.getPermission(creds)
if err != nil {
return nil, err
}
c.SetUsername(username)
c.SetPermissions(perms)
2020-04-25 02:25:51 +02:00
if !member("op", perms) {
2021-01-17 21:52:26 +01:00
if g.locked != nil {
m := *g.locked
if m == "" {
m = "this group is locked"
}
return nil, UserError(m)
}
if g.description.Autokick {
ops := false
for _, c := range clients {
if member("op", c.Permissions()) {
2021-01-17 21:52:26 +01:00
ops = true
break
}
}
if !ops {
return nil, UserError(
"there are no operators " +
"in this group",
)
}
}
2020-09-18 11:40:00 +02:00
}
2020-05-18 15:24:04 +02:00
if !member("op", perms) && g.description.MaxClients > 0 {
if len(g.clients) >= g.description.MaxClients {
return nil, UserError("too many users")
}
2020-04-25 02:37:41 +02:00
}
}
2020-06-08 22:14:28 +02:00
if g.clients[c.Id()] != nil {
return nil, ProtocolError("duplicate client id")
2020-04-25 21:29:21 +02:00
}
2020-06-08 22:14:28 +02:00
g.clients[c.Id()] = c
g.timestamp = time.Now()
c.Joined(g.Name(), "join")
id := c.Id()
u := c.Username()
p := c.Permissions()
s := c.Data()
c.PushClient(g.Name(), "add", c.Id(), u, p, s)
2021-02-15 13:43:10 +01:00
for _, cc := range clients {
pp := cc.Permissions()
c.PushClient(
g.Name(), "add", cc.Id(), cc.Username(), pp, cc.Data(),
)
cc.PushClient(g.Name(), "add", id, u, p, s)
}
return g, nil
2020-04-24 19:38:21 +02:00
}
2021-01-14 03:56:37 +01:00
// called locked
func autoLockKick(g *Group) {
2021-01-17 21:29:07 +01:00
if !(g.description.Autolock && g.locked == nil) &&
!g.description.Autokick {
return
}
clients := g.getClientsUnlocked(nil)
2021-01-17 21:29:07 +01:00
for _, c := range clients {
if member("op", c.Permissions()) {
2021-01-17 21:29:07 +01:00
return
2021-01-14 03:56:37 +01:00
}
}
2021-01-17 21:29:07 +01:00
if g.description.Autolock && g.locked == nil {
m := "this group is locked"
g.locked = &m
for _, c := range clients {
c.Joined(g.Name(), "change")
}
2021-01-17 21:29:07 +01:00
}
if g.description.Autokick {
go kickall(g, "there are no operators in this group")
}
2021-01-14 03:56:37 +01:00
}
func DelClient(c Client) {
2020-06-08 22:14:28 +02:00
g := c.Group()
if g == nil {
return
}
2020-05-28 02:35:09 +02:00
g.mu.Lock()
2020-06-08 22:14:28 +02:00
if g.clients[c.Id()] != c {
2020-04-25 21:29:21 +02:00
log.Printf("Deleting unknown client")
g.mu.Unlock()
2020-04-25 21:29:21 +02:00
return
}
2020-06-08 22:14:28 +02:00
delete(g.clients, c.Id())
g.timestamp = time.Now()
2021-01-14 03:56:37 +01:00
clients := g.getClientsUnlocked(nil)
g.mu.Unlock()
2021-01-14 03:56:37 +01:00
c.Joined(g.Name(), "leave")
for _, cc := range clients {
cc.PushClient(
g.Name(), "delete", c.Id(), "", nil, nil,
)
}
autoLockKick(g)
2020-04-24 19:38:21 +02:00
}
func (g *Group) GetClients(except Client) []Client {
2020-04-24 19:38:21 +02:00
g.mu.Lock()
defer g.mu.Unlock()
return g.getClientsUnlocked(except)
}
func (g *Group) getClientsUnlocked(except Client) []Client {
clients := make([]Client, 0, len(g.clients))
2020-04-24 19:38:21 +02:00
for _, c := range g.clients {
if c != except {
clients = append(clients, c)
}
}
return clients
}
func (g *Group) GetClient(id string) Client {
g.mu.Lock()
defer g.mu.Unlock()
return g.getClientUnlocked(id)
}
func (g *Group) getClientUnlocked(id string) Client {
2020-05-28 02:35:09 +02:00
for idd, c := range g.clients {
if idd == id {
2020-04-25 17:36:35 +02:00
return c
}
}
return nil
}
func (g *Group) Range(f func(c Client) bool) {
2020-04-24 19:38:21 +02:00
g.mu.Lock()
defer g.mu.Unlock()
for _, c := range g.clients {
ok := f(c)
2020-04-25 02:25:51 +02:00
if !ok {
break
2020-04-24 19:38:21 +02:00
}
}
}
2021-01-17 21:29:07 +01:00
func kickall(g *Group, message string) {
g.Range(func(c Client) bool {
c.Kick("", "", message)
return true
})
}
2021-09-11 15:42:14 +02:00
func Shutdown(message string) {
Range(func(g *Group) bool {
g.SetLocked(true, message)
kickall(g, message)
return true
})
2021-01-17 21:29:07 +01:00
}
type warner interface {
Warn(oponly bool, message string) error
}
func (g *Group) 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)
}
}
}
2020-10-08 14:38:33 +02:00
func FromJSTime(tm int64) time.Time {
if tm == 0 {
return time.Time{}
}
return time.Unix(int64(tm)/1000, (int64(tm)%1000)*1000000)
}
func ToJSTime(tm time.Time) int64 {
return int64((tm.Sub(time.Unix(0, 0)) + time.Millisecond/2) /
time.Millisecond)
}
2020-09-18 11:48:21 +02:00
const maxChatHistory = 50
2020-04-25 21:16:49 +02:00
func (g *Group) ClearChatHistory() {
2020-04-30 19:13:10 +02:00
g.mu.Lock()
defer g.mu.Unlock()
g.history = nil
}
func (g *Group) AddToChatHistory(id, user string, time int64, kind string, value interface{}) {
2020-04-25 21:16:49 +02:00
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,
2020-09-30 00:33:23 +02:00
ChatHistoryEntry{Id: id, User: user, Time: time, Kind: kind, Value: value},
2020-04-25 21:16:49 +02:00
)
}
func discardObsoleteHistory(h []ChatHistoryEntry, duration time.Duration) []ChatHistoryEntry {
2020-10-08 14:38:33 +02:00
i := 0
for i < len(h) {
if time.Since(FromJSTime(h[i].Time)) <= duration {
2020-10-08 14:38:33 +02:00
break
}
i++
}
if i > 0 {
copy(h, h[i:])
h = h[:len(h)-i]
}
return h
}
func (g *Group) GetChatHistory() []ChatHistoryEntry {
2020-04-25 21:16:49 +02:00
g.mu.Lock()
2020-05-12 12:48:56 +02:00
defer g.mu.Unlock()
2020-04-25 21:16:49 +02:00
g.history = discardObsoleteHistory(
g.history, maxHistoryAge(g.description),
)
2020-10-08 14:38:33 +02:00
h := make([]ChatHistoryEntry, len(g.history))
2020-04-25 21:16:49 +02:00
copy(h, g.history)
return h
}
2022-09-08 20:55:05 +02:00
func matchClient(creds ClientCredentials, users []ClientPattern) (bool, bool) {
matched := false
2020-04-25 02:25:51 +02:00
for _, u := range users {
if u.Username == creds.Username {
matched = true
if u.Password == nil {
return true, true
}
m, _ := u.Password.Match(creds.Password)
if m {
return true, true
}
}
}
if matched {
return true, false
}
for _, u := range users {
if u.Username == "" {
if u.Password == nil {
return true, true
}
m, _ := u.Password.Match(creds.Password)
if m {
2020-11-29 14:26:42 +01:00
return true, true
}
2020-04-25 02:25:51 +02:00
}
}
return false, false
}
// 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"`
ProxyURL string `json:"proxyURL"`
Admin []ClientPattern `json:"admin"`
}
2021-10-31 22:39:35 +01:00
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 os.IsNotExist(err) {
2021-10-31 22:39:35 +01:00
if !configuration.configuration.Zero() {
configuration.configuration = &Configuration{}
}
2021-10-31 22:39:35 +01:00
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
}
configuration.configuration = &conf
return configuration.configuration, nil
}
// Description represents a group description together with some metadata
// about the JSON file it was deserialised from.
type Description struct {
// The file this was deserialised from. This is not necessarily
// the name of the group, for example in case of a subgroup.
FileName string `json:"-"`
// The modtime and size of the file. These are used to detect
// when a file has changed on disk.
2021-04-29 20:38:06 +02:00
modTime time.Time `json:"-"`
fileSize int64 `json:"-"`
// The user-friendly group name
DisplayName string `json:"displayName,omitempty"`
// A user-readable description of the group.
Description string `json:"description,omitempty"`
// A user-readable contact, typically an e-mail address.
Contact string `json:"contact,omitempty"`
// A user-readable comment. Ignored by the server.
Comment string `json:"comment,omitempty"`
// Whether to display the group on the landing page.
Public bool `json:"public,omitempty"`
// A URL to redirect the group to. If this is not empty, most
// other fields are ignored.
Redirect string `json:"redirect,omitempty"`
// The maximum number of simultaneous clients. Unlimited if 0.
MaxClients int `json:"max-clients,omitempty"`
// The time for which history entries are kept.
MaxHistoryAge int `json:"max-history-age,omitempty"`
// Whether users are allowed to log in with an empty username.
AllowAnonymous bool `json:"allow-anonymous,omitempty"`
// Whether recording is allowed.
AllowRecording bool `json:"allow-recording,omitempty"`
// Whether subgroups are created on the fly.
AllowSubgroups bool `json:"allow-subgroups,omitempty"`
// Whether to lock the group when the last op logs out.
Autolock bool `json:"autolock,omitempty"`
// Whether to kick all users when the last op logs out.
Autokick bool `json:"autokick,omitempty"`
// A list of logins for ops.
Op []ClientPattern `json:"op,omitempty"`
// A list of logins for presenters.
Presenter []ClientPattern `json:"presenter,omitempty"`
// A list of logins for non-presenting users.
Other []ClientPattern `json:"other,omitempty"`
2022-02-19 23:58:31 +01:00
// The (public) keys used for token authentication.
AuthKeys []map[string]interface{} `json:"authKeys"`
// The URL of the authentication server, if any.
2021-10-29 23:37:05 +02:00
AuthServer string `json:"authServer"`
2022-02-19 23:58:31 +01:00
// The URL of the authentication portal, if any.
AuthPortal string `json:"authPortal"`
2021-10-29 23:37:05 +02:00
// Codec preferences. If empty, a suitable default is chosen in
// the APIFromNames function.
Codecs []string `json:"codecs,omitempty"`
2020-04-25 02:25:51 +02:00
}
const DefaultMaxHistoryAge = 4 * time.Hour
func maxHistoryAge(desc *Description) time.Duration {
if desc.MaxHistoryAge != 0 {
return time.Duration(desc.MaxHistoryAge) * time.Second
}
return DefaultMaxHistoryAge
}
2020-11-22 19:54:54 +01:00
func openDescriptionFile(name string) (*os.File, string, bool, error) {
isParent := false
for name != "" {
fileName := filepath.Join(
Directory, path.Clean("/"+name)+".json",
)
r, err := os.Open(fileName)
if !os.IsNotExist(err) {
return r, fileName, isParent, err
}
isParent = true
name, _ = path.Split(name)
name = strings.TrimRight(name, "/")
}
2020-11-22 19:54:54 +01:00
return nil, "", false, os.ErrNotExist
}
func statDescriptionFile(name string) (os.FileInfo, string, bool, error) {
isParent := false
for name != "" {
fileName := filepath.Join(
Directory, path.Clean("/"+name)+".json",
)
fi, err := os.Stat(fileName)
if !os.IsNotExist(err) {
return fi, fileName, isParent, err
}
isParent = true
name, _ = path.Split(name)
name = strings.TrimRight(name, "/")
}
2020-11-22 19:54:54 +01:00
return nil, "", false, os.ErrNotExist
}
// descriptionMatch returns true if the description hasn't changed between
// d1 and d2
func descriptionMatch(d1, d2 *Description) bool {
if d1.FileName != d2.FileName {
return false
}
if d1.fileSize != d2.fileSize || !d1.modTime.Equal(d2.modTime) {
return false
}
return true
}
// descriptionUnchanged returns true if a group's description hasn't
2020-11-22 19:54:54 +01:00
// changed since it was last read.
func descriptionUnchanged(name string, desc *Description) bool {
2020-11-22 19:54:54 +01:00
fi, fileName, _, err := statDescriptionFile(name)
if err != nil || fileName != desc.FileName {
return false
2020-11-22 19:54:54 +01:00
}
if fi.Size() != desc.fileSize || !fi.ModTime().Equal(desc.modTime) {
return false
2020-11-22 19:54:54 +01:00
}
return true
}
// GetDescription gets a group description, either from cache or from disk
func GetDescription(name string) (*Description, error) {
g := Get(name)
if g != nil {
if descriptionUnchanged(name, g.description) {
return g.description, nil
}
}
return readDescription(name)
}
// readDescription reads a group's description from disk
func readDescription(name string) (*Description, error) {
2020-11-22 19:54:54 +01:00
r, fileName, isParent, err := openDescriptionFile(name)
2020-04-25 02:25:51 +02:00
if err != nil {
return nil, err
}
defer r.Close()
var desc Description
fi, err := r.Stat()
if err != nil {
return nil, err
}
2020-04-25 02:25:51 +02:00
d := json.NewDecoder(r)
d.DisallowUnknownFields()
2020-04-25 02:25:51 +02:00
err = d.Decode(&desc)
if err != nil {
return nil, err
}
2020-11-22 19:54:54 +01:00
if isParent {
if !desc.AllowSubgroups {
return nil, os.ErrNotExist
}
desc.Public = false
desc.Description = ""
}
desc.FileName = fileName
2020-11-22 19:54:54 +01:00
desc.fileSize = fi.Size()
desc.modTime = fi.ModTime()
2020-04-25 02:25:51 +02:00
return &desc, nil
}
2022-09-08 20:55:05 +02:00
// called locked
func (g *Group) getPermission(creds ClientCredentials) (string, []string, error) {
desc := g.description
if creds.Token == "" {
if !desc.AllowAnonymous && creds.Username == "" {
return "", nil, ErrAnonymousNotAuthorised
}
2022-09-08 20:55:05 +02:00
if found, good := matchClient(creds, desc.Op); found {
if good {
var p []string
p = []string{"op", "present"}
if desc.AllowRecording {
p = append(p, "record")
}
return creds.Username, p, nil
2020-05-30 00:23:54 +02:00
}
return "", nil, ErrNotAuthorised
2020-04-25 02:25:51 +02:00
}
2022-09-08 20:55:05 +02:00
if found, good := matchClient(creds, desc.Presenter); found {
if good {
return creds.Username, []string{"present"}, nil
}
return "", nil, ErrNotAuthorised
2020-04-25 02:25:51 +02:00
}
2022-09-08 20:55:05 +02:00
if found, good := matchClient(creds, desc.Other); found {
if good {
return creds.Username, nil, nil
}
return "", nil, ErrNotAuthorised
2020-04-25 02:25:51 +02:00
}
return "", nil, ErrNotAuthorised
2020-04-25 02:25:51 +02:00
}
2021-10-29 23:37:05 +02:00
sub, aud, perms, err := token.Valid(creds.Token, desc.AuthKeys)
if err != nil {
log.Printf("Token authentication: %v", err)
return "", nil, ErrNotAuthorised
}
if !desc.AllowAnonymous && sub == "" {
return "", nil, ErrAnonymousNotAuthorised
}
conf, err := GetConfiguration()
if err != nil {
log.Printf("Read config.json: %v", err)
return "", nil, err
}
ok := false
for _, u := range aud {
url, err := url.Parse(u)
2021-10-29 23:37:05 +02:00
if err != nil {
log.Printf("Token URL: %v", err)
continue
2021-10-29 23:37:05 +02:00
}
// if canonicalHost is not set, we allow tokens
// for any domain name. Hopefully different
// servers use distinct keys.
if conf.CanonicalHost != "" {
if !strings.EqualFold(
url.Host, conf.CanonicalHost,
) {
2021-10-29 23:37:05 +02:00
continue
}
}
2022-09-08 20:55:05 +02:00
if url.Path == path.Join("/group", g.name)+"/" {
ok = true
break
2021-10-29 23:37:05 +02:00
}
}
if !ok {
return "", nil, ErrNotAuthorised
}
return sub, perms, nil
2020-04-25 17:36:35 +02:00
}
2022-09-08 20:55:05 +02:00
func (g *Group) GetPermission(creds ClientCredentials) (string, []string, error) {
g.mu.Lock()
defer g.mu.Unlock()
return g.getPermission(creds)
}
2021-10-26 22:22:48 +02:00
type Status struct {
2020-04-24 19:38:21 +02:00
Name string `json:"name"`
Redirect string `json:"redirect,omitempty"`
Location string `json:"location,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
DisplayName string `json:"displayName,omitempty"`
2020-09-24 22:03:41 +02:00
Description string `json:"description,omitempty"`
2021-10-29 23:37:05 +02:00
AuthServer string `json:"authServer,omitempty"`
2022-02-19 23:58:31 +01:00
AuthPortal string `json:"authPortal,omitempty"`
Locked bool `json:"locked,omitempty"`
2021-10-26 22:22:48 +02:00
ClientCount *int `json:"clientCount,omitempty"`
}
// Status returns a group's status.
// Base is the base URL for groups; if omitted, then both the Location and
// Endpoint members are omitted from the result.
func (g *Group) Status(authentified bool, base string) Status {
2021-10-26 22:22:48 +02:00
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 != "" {
burl, err := url.Parse(base)
if err == nil {
wss := "wss"
if burl.Scheme == "http" {
wss = "ws"
}
l := url.URL{
Scheme: burl.Scheme,
Host: burl.Host,
Path: path.Join(burl.Path, g.name) + "/",
}
location = l.String()
e := url.URL{
Scheme: wss,
Host: burl.Host,
Path: "/ws",
}
endpoint = e.String()
} else {
log.Printf("Couldn't parse base URL %v", base)
}
}
2021-10-26 22:22:48 +02:00
d := Status{
Name: g.name,
Location: location,
Endpoint: endpoint,
2021-10-26 22:22:48 +02:00
DisplayName: desc.DisplayName,
2021-10-29 23:37:05 +02:00
AuthServer: desc.AuthServer,
2022-02-19 23:58:31 +01:00
AuthPortal: desc.AuthPortal,
2021-10-26 22:22:48 +02:00
Description: desc.Description,
}
if authentified || desc.Public {
// these are considered private information
locked, _ := g.Locked()
count := g.ClientCount()
d.Locked = locked
d.ClientCount = &count
}
return d
2020-04-24 19:38:21 +02:00
}
func GetPublic(base string) []Status {
2021-10-26 22:22:48 +02:00
gs := make([]Status, 0)
Range(func(g *Group) bool {
2021-10-26 22:22:48 +02:00
if g.Description().Public {
gs = append(gs, g.Status(false, base))
2020-04-24 19:38:21 +02:00
}
2020-09-13 12:24:06 +02:00
return true
})
2020-04-30 22:32:44 +02:00
sort.Slice(gs, func(i, j int) bool {
return gs[i].Name < gs[j].Name
})
2020-04-24 19:38:21 +02:00
return gs
}
2020-04-25 04:08:43 +02:00
// Update checks that all in-memory groups are up-to-date and updates the
// list of public groups. It also removes from memory any non-public
// groups 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
2022-10-08 22:46:28 +02:00
if g.mayExpire() {
// Delete checks if the group is still empty
deleted = Delete(name)
}
2022-10-08 22:46:28 +02:00
// update group description
if !deleted {
Add(name, nil)
}
}
err = filepath.WalkDir(
Directory,
func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Printf("Group file %v: %v", path, err)
2021-01-14 01:45:50 +01:00
return nil
}
if d.IsDir() {
return nil
}
filename, err := filepath.Rel(Directory, path)
if err != nil {
log.Printf("Group file %v: %v", path, err)
return nil
}
if !strings.HasSuffix(filename, ".json") {
log.Printf(
"Unexpected extension for group file %v",
path,
)
return nil
}
base := filepath.Base(filename)
if base[0] == '.' {
log.Printf("Group file %v ignored", filename)
return nil
}
name := strings.TrimSuffix(filename, ".json")
desc, err := GetDescription(name)
if err != nil {
log.Printf("Group file %v: %v", path, err)
return nil
}
if desc.Public {
Add(name, desc)
}
return nil
},
)
2020-04-25 04:08:43 +02:00
if err != nil {
2021-01-14 01:45:50 +01:00
log.Printf("Couldn't read groups: %v", err)
2020-04-25 04:08:43 +02:00
}
}