Debian Codegraph @

appservice/appservice.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package appservice
8
9 import (
10 "errors"
11 "fmt"
12 "html/template"
13 "io/ioutil"
14 "net/http"
15 "net/http/cookiejar"
16 "os"
17 "path/filepath"
18 "strings"
19 "sync"
20 "syscall"
21 "time"
22
23 "github.com/gorilla/mux"
24 "github.com/gorilla/websocket"
25 "golang.org/x/net/publicsuffix"
26 "gopkg.in/yaml.v2"
27
28 "maunium.net/go/maulogger/v2"
29
30 "maunium.net/go/mautrix"
31 "maunium.net/go/mautrix/event"
32 "maunium.net/go/mautrix/id"
33 )
34
35 // EventChannelSize is the size for the Events channel in Appservice instances.
36 var EventChannelSize = 64
37 var OTKChannelSize = 4
38
39 // Create a blank appservice instance.
40 func Create() *AppService {
41 jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
42 return &AppService{
43 LogConfig: CreateLogConfig(),
44 clients: make(map[id.UserID]*mautrix.Client),
45 intents: make(map[id.UserID]*IntentAPI),
46 HTTPClient: &http.Client{Timeout: 180 * time.Second, Jar: jar},
47 StateStore: NewBasicStateStore(),
48 Router: mux.NewRouter(),
49 UserAgent: mautrix.DefaultUserAgent,
50 txnIDC: NewTransactionIDCache(128),
51 Live: true,
52 Ready: false,
53 }
54 }
55
56 // Load an appservice config from a file.
57 func Load(path string) (*AppService, error) {
58 data, readErr := ioutil.ReadFile(path)
59 if readErr != nil {
60 return nil, readErr
61 }
62
63 config := Create()
64 return config, yaml.Unmarshal(data, config)
65 }
66
67 // QueryHandler handles room alias and user ID queries from the homeserver.
68 type QueryHandler interface {
69 QueryAlias(alias string) bool
70 QueryUser(userID id.UserID) bool
71 }
72
73 type QueryHandlerStub struct{}
74
75 func (qh *QueryHandlerStub) QueryAlias(alias string) bool {
76 return false
77 }
78
79 func (qh *QueryHandlerStub) QueryUser(userID id.UserID) bool {
80 return false
81 }
82
83 type WebsocketHandler func(WebsocketCommand) (ok bool, data interface{})
84
85 // AppService is the main config for all appservices.
86 // It also serves as the appservice instance struct.
87 type AppService struct {
88 HomeserverDomain string `yaml:"homeserver_domain"`
89 HomeserverURL string `yaml:"homeserver_url"`
90 RegistrationPath string `yaml:"registration"`
91 Host HostConfig `yaml:"host"`
92 LogConfig LogConfig `yaml:"logging"`
93
94 Registration *Registration `yaml:"-"`
95 Log maulogger.Logger `yaml:"-"`
96
97 txnIDC *TransactionIDCache
98
99 Events chan *event.Event `yaml:"-"`
100 DeviceLists chan *mautrix.DeviceLists `yaml:"-"`
101 OTKCounts chan *mautrix.OTKCount `yaml:"-"`
102 QueryHandler QueryHandler `yaml:"-"`
103 StateStore StateStore `yaml:"-"`
104
105 Router *mux.Router `yaml:"-"`
106 UserAgent string `yaml:"-"`
107 server *http.Server
108 HTTPClient *http.Client
109 botClient *mautrix.Client
110 botIntent *IntentAPI
111
112 MessageSendCheckpointEndpoint string
113
114 DefaultHTTPRetries int
115
116 Live bool
117 Ready bool
118
119 clients map[id.UserID]*mautrix.Client
120 clientsLock sync.RWMutex
121 intents map[id.UserID]*IntentAPI
122 intentsLock sync.RWMutex
123
124 ws *websocket.Conn
125 wsWriteLock sync.Mutex
126 StopWebsocket func(error)
127 websocketHandlers map[string]WebsocketHandler
128 websocketHandlersLock sync.RWMutex
129 websocketRequests map[int]chan<- *WebsocketCommand
130 websocketRequestsLock sync.RWMutex
131 websocketRequestID int32
132 // ProcessID is an identifier sent to the websocket proxy for debugging connections
133 ProcessID string
134 }
135
136 func getDefaultProcessID() string {
137 pid := syscall.Getpid()
138 uid := syscall.Getuid()
139 hostname, _ := os.Hostname()
140 return fmt.Sprintf("%s-%d-%d", hostname, uid, pid)
141 }
142
143 func (as *AppService) PrepareWebsocket() {
144 if as.websocketHandlers == nil {
145 as.websocketHandlers = make(map[string]WebsocketHandler, 32)
146 as.websocketRequests = make(map[int]chan<- *WebsocketCommand)
147 }
148 }
149
150 // HostConfig contains info about how to host the appservice.
151 type HostConfig struct {
152 Hostname string `yaml:"hostname"`
153 Port uint16 `yaml:"port"`
154 TLSKey string `yaml:"tls_key,omitempty"`
155 TLSCert string `yaml:"tls_cert,omitempty"`
156 }
157
158 // Address gets the whole address of the Appservice.
159 func (hc *HostConfig) Address() string {
160 return fmt.Sprintf("%s:%d", hc.Hostname, hc.Port)
161 }
162
163 // Save saves this config into a file at the given path.
164 func (as *AppService) Save(path string) error {
165 data, err := yaml.Marshal(as)
166 if err != nil {
167 return err
168 }
169 return ioutil.WriteFile(path, data, 0644)
170 }
171
172 // YAML returns the config in YAML format.
173 func (as *AppService) YAML() (string, error) {
174 data, err := yaml.Marshal(as)
175 if err != nil {
176 return "", err
177 }
178 return string(data), nil
179 }
180
181 func (as *AppService) BotMXID() id.UserID {
182 return id.NewUserID(as.Registration.SenderLocalpart, as.HomeserverDomain)
183 }
184
185 func (as *AppService) makeIntent(userID id.UserID) *IntentAPI {
186 as.intentsLock.Lock()
187 defer as.intentsLock.Unlock()
188
189 intent, ok := as.intents[userID]
190 if ok {
191 return intent
192 }
193
194 localpart, homeserver, err := userID.Parse()
195 if err != nil || len(localpart) == 0 || homeserver != as.HomeserverDomain {
196 if err != nil {
197 as.Log.Fatalfln("Failed to parse user ID %s: %v", userID, err)
198 } else if len(localpart) == 0 {
199 as.Log.Fatalfln("Failed to make intent for %s: localpart is empty", userID)
200 } else if homeserver != as.HomeserverDomain {
201 as.Log.Fatalfln("Failed to make intent for %s: homeserver isn't %s", userID, as.HomeserverDomain)
202 }
203 return nil
204 }
205 intent = as.NewIntentAPI(localpart)
206 as.intents[userID] = intent
207 return intent
208 }
209
210 func (as *AppService) Intent(userID id.UserID) *IntentAPI {
211 as.intentsLock.RLock()
212 intent, ok := as.intents[userID]
213 as.intentsLock.RUnlock()
214 if !ok {
215 return as.makeIntent(userID)
216 }
217 return intent
218 }
219
220 func (as *AppService) BotIntent() *IntentAPI {
221 if as.botIntent == nil {
222 as.botIntent = as.makeIntent(as.BotMXID())
223 }
224 return as.botIntent
225 }
226
227 func (as *AppService) makeClient(userID id.UserID) *mautrix.Client {
228 as.clientsLock.Lock()
229 defer as.clientsLock.Unlock()
230
231 client, ok := as.clients[userID]
232 if ok {
233 return client
234 }
235
236 client, err := mautrix.NewClient(as.HomeserverURL, userID, as.Registration.AppToken)
237 if err != nil {
238 as.Log.Fatalln("Failed to create mautrix client instance:", err)
239 return nil
240 }
241 client.UserAgent = as.UserAgent
242 client.Syncer = nil
243 client.Store = nil
244 client.AppServiceUserID = userID
245 client.Logger = as.Log.Sub(string(userID))
246 client.Client = as.HTTPClient
247 client.DefaultHTTPRetries = as.DefaultHTTPRetries
248 as.clients[userID] = client
249 return client
250 }
251
252 func (as *AppService) Client(userID id.UserID) *mautrix.Client {
253 as.clientsLock.RLock()
254 client, ok := as.clients[userID]
255 as.clientsLock.RUnlock()
256 if !ok {
257 return as.makeClient(userID)
258 }
259 return client
260 }
261
262 func (as *AppService) BotClient() *mautrix.Client {
263 if as.botClient == nil {
264 as.botClient = as.makeClient(as.BotMXID())
265 as.botClient.Logger = as.Log.Sub("Bot")
266 }
267 return as.botClient
268 }
269
270 // Init initializes the logger and loads the registration of this appservice.
271 func (as *AppService) Init() (bool, error) {
272 as.Events = make(chan *event.Event, EventChannelSize)
273 as.OTKCounts = make(chan *mautrix.OTKCount, OTKChannelSize)
274 as.DeviceLists = make(chan *mautrix.DeviceLists, EventChannelSize)
275 as.QueryHandler = &QueryHandlerStub{}
276
277 if len(as.UserAgent) == 0 {
278 as.UserAgent = mautrix.DefaultUserAgent
279 }
280 if len(as.ProcessID) == 0 {
281 as.ProcessID = getDefaultProcessID()
282 }
283
284 as.Log = maulogger.Create()
285 as.LogConfig.Configure(as.Log)
286 as.Log.Debugln("Logger initialized successfully.")
287
288 if len(as.RegistrationPath) > 0 {
289 var err error
290 as.Registration, err = LoadRegistration(as.RegistrationPath)
291 if err != nil {
292 return false, err
293 }
294 }
295
296 as.Log.Debugln("Appservice initialized successfully.")
297 return true, nil
298 }
299
300 // LogConfig contains configs for the logger.
301 type LogConfig struct {
302 Directory string `yaml:"directory"`
303 FileNameFormat string `yaml:"file_name_format"`
304 FileDateFormat string `yaml:"file_date_format"`
305 FileMode uint32 `yaml:"file_mode"`
306 TimestampFormat string `yaml:"timestamp_format"`
307 RawPrintLevel string `yaml:"print_level"`
308 JSONStdout bool `yaml:"print_json"`
309 JSONFile bool `yaml:"file_json"`
310 PrintLevel int `yaml:"-"`
311 }
312
313 type umLogConfig LogConfig
314
315 func (lc *LogConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
316 err := unmarshal((*umLogConfig)(lc))
317 if err != nil {
318 return err
319 }
320
321 switch strings.ToUpper(lc.RawPrintLevel) {
322 case "TRACE":
323 lc.PrintLevel = -10
324 case "DEBUG":
325 lc.PrintLevel = maulogger.LevelDebug.Severity
326 case "INFO":
327 lc.PrintLevel = maulogger.LevelInfo.Severity
328 case "WARN", "WARNING":
329 lc.PrintLevel = maulogger.LevelWarn.Severity
330 case "ERR", "ERROR":
331 lc.PrintLevel = maulogger.LevelError.Severity
332 case "FATAL":
333 lc.PrintLevel = maulogger.LevelFatal.Severity
334 default:
335 return errors.New("invalid print level " + lc.RawPrintLevel)
336 }
337 return err
338 }
339
340 func (lc *LogConfig) MarshalYAML() (interface{}, error) {
341 switch {
342 case lc.PrintLevel >= maulogger.LevelFatal.Severity:
343 lc.RawPrintLevel = maulogger.LevelFatal.Name
344 case lc.PrintLevel >= maulogger.LevelError.Severity:
345 lc.RawPrintLevel = maulogger.LevelError.Name
346 case lc.PrintLevel >= maulogger.LevelWarn.Severity:
347 lc.RawPrintLevel = maulogger.LevelWarn.Name
348 case lc.PrintLevel >= maulogger.LevelInfo.Severity:
349 lc.RawPrintLevel = maulogger.LevelInfo.Name
350 default:
351 lc.RawPrintLevel = maulogger.LevelDebug.Name
352 }
353 return lc, nil
354 }
355
356 // CreateLogConfig creates a basic LogConfig.
357 func CreateLogConfig() LogConfig {
358 return LogConfig{
359 Directory: "./logs",
360 FileNameFormat: "%[1]s-%02[2]d.log",
361 TimestampFormat: "Jan _2, 2006 15:04:05",
362 FileMode: 0600,
363 FileDateFormat: "2006-01-02",
364 PrintLevel: 10,
365 }
366 }
367
368 type FileFormatData struct {
369 Date string
370 Index int
371 }
372
373 // GetFileFormat returns a mauLogger-compatible logger file format based on the data in the struct.
374 func (lc LogConfig) GetFileFormat() maulogger.LoggerFileFormat {
375 if len(lc.Directory) > 0 {
376 _ = os.MkdirAll(lc.Directory, 0700)
377 }
378 path := filepath.Join(lc.Directory, lc.FileNameFormat)
379 tpl, _ := template.New("fileformat").Parse(path)
380
381 return func(now string, i int) string {
382 var buf strings.Builder
383 _ = tpl.Execute(&buf, FileFormatData{
384 Date: now,
385 Index: i,
386 })
387 return buf.String()
388 }
389 }
390
391 // Configure configures a mauLogger instance with the data in this struct.
392 func (lc LogConfig) Configure(log maulogger.Logger) {
393 basicLogger := log.(*maulogger.BasicLogger)
394 basicLogger.FileFormat = lc.GetFileFormat()
395 basicLogger.FileMode = os.FileMode(lc.FileMode)
396 basicLogger.FileTimeFormat = lc.FileDateFormat
397 basicLogger.TimeFormat = lc.TimestampFormat
398 basicLogger.PrintLevel = lc.PrintLevel
399 basicLogger.JSONFile = lc.JSONFile
400 if lc.JSONStdout {
401 basicLogger.EnableJSONStdout()
402 }
403 }