forked from ortuman/jackal
/
c2s.go
87 lines (76 loc) · 1.89 KB
/
c2s.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* Copyright (c) 2018 Miguel Ángel Ortuño.
* See the LICENSE file for more information.
*/
package c2s
import (
"sync"
"github.com/ortuman/jackal/log"
"github.com/pkg/errors"
)
const (
streamMailboxSize = 64
iqResultMailboxSize = 32
)
const (
streamNamespace = "http://etherx.jabber.org/streams"
tlsNamespace = "urn:ietf:params:xml:ns:xmpp-tls"
compressProtocolNamespace = "http://jabber.org/protocol/compress"
bindNamespace = "urn:ietf:params:xml:ns:xmpp-bind"
sessionNamespace = "urn:ietf:params:xml:ns:xmpp-session"
saslNamespace = "urn:ietf:params:xml:ns:xmpp-sasl"
blockedErrorNamespace = "urn:xmpp:blocking:errors"
)
var (
mu sync.RWMutex
servers = make(map[string]*server)
shutdownCh = make(chan chan struct{})
initialized bool
)
// Initialize initializes c2s sub system spawning a connection listener
// for every server configuration.
func Initialize(srvConfigurations []Config) {
mu.Lock()
if initialized {
mu.Unlock()
return
}
if len(srvConfigurations) == 0 {
log.Error(errors.New("at least one c2s configuration is required"))
return
}
// initialize all servers
for i := 0; i < len(srvConfigurations); i++ {
if _, err := initializeServer(&srvConfigurations[i]); err != nil {
log.Fatalf("%v", err)
}
}
initialized = true
mu.Unlock()
// wait until shutdown...
doneCh := <-shutdownCh
mu.Lock()
// close all servers
for k, srv := range servers {
if err := srv.shutdown(); err != nil {
log.Error(err)
}
delete(servers, k)
}
close(doneCh)
initialized = false
mu.Unlock()
}
// Shutdown closes every server listener.
// This method should be used only for testing purposes.
func Shutdown() {
ch := make(chan struct{})
shutdownCh <- ch
<-ch
}
func initializeServer(cfg *Config) (*server, error) {
srv := &server{cfg: cfg}
servers[cfg.ID] = srv
go srv.start()
return srv, nil
}