-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.go
More file actions
318 lines (276 loc) · 8.14 KB
/
app.go
File metadata and controls
318 lines (276 loc) · 8.14 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package fedbox
import (
"context"
"net/http"
"os"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"git.sr.ht/~mariusor/lw"
m "git.sr.ht/~mariusor/servermux"
"git.sr.ht/~mariusor/storage-all"
w "git.sr.ht/~mariusor/wrapper"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/auth"
"github.com/go-ap/cache"
"github.com/go-ap/client"
"github.com/go-ap/errors"
ap "github.com/go-ap/fedbox/activitypub"
"github.com/go-ap/fedbox/internal/config"
"github.com/go-ap/processing"
"github.com/go-chi/chi/v5"
)
func init() {
// set local path typer to validate collections
processing.Typer = pathTyper{}
}
type LogFn func(string, ...any)
type canStore = cache.CanStore
type FedBOX struct {
*Base
server m.Server
R chi.Router
caches canStore
maintenanceMode atomic.Bool
shuttingDown atomic.Bool
keyGenerator func(act *vocab.Actor) error
}
func initHttpServer(app *FedBOX) (m.Server, error) {
setters := []m.SetFn{m.Handler(app.R)}
lwCtx := lw.Ctx{}
if app.Conf.Secure {
if len(app.Conf.CertPath)+len(app.Conf.KeyPath) > 0 {
setters = append(setters, m.WithTLSCert(app.Conf.CertPath, app.Conf.KeyPath))
lwCtx["TLS"] = true
} else {
app.Conf.Secure = false
}
}
// NOTE(marius): we now set-up a default socket listener
if !app.Conf.Env.IsTest() {
_ = os.RemoveAll(app.Conf.InternalSocketPath())
setters = append(setters, m.OnSocket(app.Conf.InternalSocketPath()))
}
listenHTTP := app.Conf.HTTPListen()
if len(listenHTTP) == 0 {
return nil, errors.Newf("No valid HTTP listen configurations")
}
for _, pathOrHost := range listenHTTP {
if pathOrHost == "systemd" {
lwCtx["systemd"] = true
setters = append(setters, m.OnSystemd())
} else if filepath.IsAbs(pathOrHost) {
dir := filepath.Dir(pathOrHost)
lwCtx["socket"] = pathOrHost
if _, err := os.Stat(dir); err == nil {
setters = append(setters, m.OnSocket(pathOrHost))
}
} else {
lwCtx["host"] = app.Conf.ListenHost
lwCtx["port"] = app.Conf.HTTPPort
setters = append(setters, m.OnTCP(pathOrHost))
}
}
httpSrv, err := m.HttpServer(setters...)
if err != nil {
return nil, err
}
app.Logger.WithContext(lwCtx).Debugf("Accepting HTTP requests")
return httpSrv, nil
}
// New instantiates a new FedBOX instance
func New(ctl *Base) (*FedBOX, error) {
if ctl == nil {
return nil, errors.Newf("invalid initializer")
}
db := ctl.Storage
if db == nil {
return nil, errors.Newf("invalid storage")
}
conf := ctl.Conf
if err := db.Open(); err != nil {
return nil, errors.Annotatef(err, "unable to open storage: %s", conf.StoragePath)
}
if ctl.in == nil {
ctl.in = os.Stdin
}
if ctl.out == nil {
ctl.out = os.Stdout
}
if ctl.err == nil {
ctl.err = os.Stderr
}
app := FedBOX{
Base: ctl,
R: chi.NewRouter(),
caches: cache.New(conf.RequestCache),
}
if metaSaver, ok := db.(storage.MetadataStorage); ok {
keysType := ap.KeyTypeED25519
if conf.MastodonCompatible {
keysType = ap.KeyTypeRSA
}
ctl.Logger.Debugf("Setting actor key generator %T[%s]", metaSaver, keysType)
app.keyGenerator = ap.KeyGenerator(metaSaver, keysType)
}
if err := ctl.LoadServiceActor(); err != nil {
app.Logger.WithContext(lw.Ctx{"err": err, "iri": ctl.Conf.BaseURL}).Warnf("no root service exists")
}
app.debugMode.Store(conf.Env.IsDev())
app.R.Group(app.Routes())
muxSetters := make([]m.MuxFn, 0, 1)
if !(app.Conf.Env.IsTest() || app.Conf.Env.IsDev()) {
muxSetters = append(muxSetters, m.GracefulWait(app.Conf.TimeOut))
}
// NOTE(marius): we initialize the HTTP Server
httpSrv, err := initHttpServer(&app)
if err != nil {
return nil, err
}
muxSetters = append(muxSetters, m.WithServer(httpSrv))
sshServ, err := initSSHServer(&app)
if err != nil {
app.Logger.WithContext(lw.Ctx{"err": err}).Errorf("unable to open SSH connection")
}
if sshServ != nil {
// NOTE(marius): if the SSH Server could be initialized
muxSetters = append(muxSetters, m.WithServer(sshServ))
}
app.server, err = m.Mux(muxSetters...)
if err != nil {
return nil, err
}
return &app, nil
}
func (f *FedBOX) Pause() error {
if f.maintenanceMode.Load() {
// restart everything
f.Storage.Close()
} else {
return f.Storage.Open()
}
return nil
}
// Stop
func (f *FedBOX) Stop(ctx context.Context) error {
f.Storage.Close()
f.shuttingDown.Store(true)
defer func() {
_ = os.RemoveAll(f.Conf.PidPath())
_ = os.RemoveAll(f.Conf.InternalSocketPath())
if filepath.IsAbs(f.Conf.SocketPath) {
if _, err := os.Stat(f.Conf.SocketPath); err == nil {
_ = os.RemoveAll(f.Conf.SocketPath)
}
}
}()
return f.server.Stop(ctx)
}
func (f *FedBOX) reload() (err error) {
f.Conf, err = config.Load(".", f.Conf.Env)
f.caches.Delete()
return err
}
func IsProxyURL(i vocab.IRI) bool {
return strings.ToLower(filepath.Base(i.String())) == strings.ToLower("proxyUrl")
}
func (f *FedBOX) actorFromRequestWithClient(r *http.Request, cl *client.C, receivedIn vocab.IRI) vocab.Actor {
// NOTE(marius): if the Storage is nil, we can still use the remote client in the load function
isLocalFn := func(iri vocab.IRI) bool {
return iri.Contains(vocab.IRI(f.Conf.BaseURL), true)
}
var logFn auth.LoggerFn = func(ctx lw.Ctx, msg string, p ...any) {
f.Logger.WithContext(ctx).Debugf(msg, p...)
}
initFns := []auth.SolverInitFn{
auth.SolverWithLogger(logFn),
auth.SolverWithStorage(f.Storage),
auth.SolverWithLocalIRIFn(isLocalFn),
}
var ar auth.ActorVerifier
switch {
case processing.IsInbox(receivedIn):
ar = auth.HTTPSignatureResolver(cl, initFns...)
case processing.IsOutbox(receivedIn) || IsProxyURL(receivedIn):
ar = auth.OAuth2Resolver(cl, initFns...)
default:
ar = auth.Resolver(cl, initFns...)
}
actor, err := ar.Verify(r)
if err != nil {
f.Logger.WithContext(lw.Ctx{"err": err.Error()}).Errorf("unable to load an authorized Actor from request")
}
return actor
}
// Run is the wrapper for starting the web-server and handling signals
func (f *FedBOX) Run(ctx context.Context) error {
logCtx := lw.Ctx{}
if f.Conf.BaseURL != "" {
logCtx["URL"] = f.Conf.BaseURL
}
if f.Conf.Version != "" {
logCtx["version"] = f.Conf.Version
}
var cancelFn func()
ctx, cancelFn = context.WithCancel(ctx)
defer cancelFn()
logger := f.Logger.WithContext(logCtx)
logger.Infof("Started")
if err := f.Conf.WritePid(); err != nil {
logger.Warnf("Unable to write pid file: %s", err)
logger.Warnf("Some CLI commands relying on it will not work")
}
exitWithErrOrInterrupt := func(err error, exit chan<- error) {
if err == nil {
err = w.Interrupt
}
exit <- err
}
err := w.RegisterSignalHandlers(w.SignalHandlers{
syscall.SIGHUP: func(_ chan<- error) {
logger.Debugf("SIGHUP received, reloading configuration")
if err := f.reload(); err != nil {
logger.Errorf("Failed: %+s", err.Error())
}
},
syscall.SIGUSR2: func(_ chan<- error) {
isDebug := f.debugMode.Load()
f.debugMode.Store(!isDebug)
logger.WithContext(lw.Ctx{"debug": !isDebug}).Debugf("SIGUSR2 received, toggle debug mode")
},
syscall.SIGUSR1: func(_ chan<- error) {
isMaintenance := f.maintenanceMode.Load()
f.maintenanceMode.Store(!isMaintenance)
logFn := logger.WithContext(lw.Ctx{"maintenance": !isMaintenance}).Debugf
if err := f.Pause(); err != nil {
logFn = logger.WithContext(lw.Ctx{"err": err.Error()}).Warnf
}
logFn("SIGUSR1 received, toggle maintenance mode")
},
syscall.SIGINT: func(exit chan<- error) {
if !(f.Conf.Env.IsTest() || f.Conf.Env.IsDev()) {
logger = logger.WithContext(lw.Ctx{"wait": f.Conf.TimeOut})
}
logger.Debugf("SIGINT received, interrupted")
exitWithErrOrInterrupt(f.Stop(ctx), exit)
},
syscall.SIGTERM: func(exit chan<- error) {
if !(f.Conf.Env.IsTest() || f.Conf.Env.IsDev()) {
logger = logger.WithContext(lw.Ctx{"wait": f.Conf.TimeOut})
}
logger.Debugf("SIGTERM received, stopping with cleanup")
exitWithErrOrInterrupt(f.Stop(ctx), exit)
},
syscall.SIGQUIT: func(exit chan<- error) {
logger.Debugf("SIGQUIT received, ungraceful force stopping")
// NOTE(marius): to skip any graceful wait on the listening server, cancel the context first
cancelFn()
exitWithErrOrInterrupt(f.Stop(ctx), exit)
},
}).Exec(ctx, f.server.Start)
if err == nil {
logger.Infof("Stopped")
}
return err
}