-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpserver.go
411 lines (358 loc) · 9.59 KB
/
httpserver.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package httpserver
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
// Packages
"github.com/mutablelogic/go-server"
fcgi "github.com/mutablelogic/go-server/pkg/httpserver/fcgi"
"github.com/mutablelogic/go-server/pkg/provider"
// Namespace imports
. "github.com/djthorpe/go-errors"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
// Server configuration
type Config struct {
Listen string `hcl:"listen" description:"Network address and port to listen on, or path to file socket"`
TLS struct {
Key string `hcl:"key" description:"Path to private key (if provided, tls.cert is also required)"`
Cert string `hcl:"cert" description:"Path to certificate (if provided, tls.key is also required)"`
} `hcl:"tls"`
Timeout time.Duration `hcl:"timeout" description:"Read request timeout"`
Owner string `hcl:"owner" description:"User ID of the file socket (if listen is a file socket)"`
Group string `hcl:"group" description:"Group ID of the file socket (if listen is a file socket)"`
Router http.Handler `hcl:"router" description:"HTTP router for requests"`
}
// Server interface
type Server interface {
server.Task
// Return the type of server (http, https or fcgi)
Type() string
// Return the listening address or path
Addr() string
// Return the router associated with the server
Router() http.Handler
}
// http server instance
type httpserver struct {
fcgi *fcgi.Server
http *http.Server
}
// Check interfaces are satisfied
var _ server.Plugin = Config{}
var _ server.Task = (*httpserver)(nil)
///////////////////////////////////////////////////////////////////////////////
// GLOBALS
const (
defaultName = "httpserver"
defaultTimeout = 10 * time.Second
defaultListen = ":http"
defaultListenTLS = ":https"
defaultMode = os.FileMode(0600)
defaultDirMode = os.FileMode(0700)
groupMode = os.FileMode(0060)
groupDirMode = os.FileMode(0070)
allMode = os.FileMode(0777)
)
///////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
// Name returns the name of the service
func (Config) Name() string {
return defaultName
}
// Description returns the description of the service
func (Config) Description() string {
return "serves requests and provides responses over HTTP, HTTPS and FCGI"
}
// Create a new http server from the configuration
func (c Config) New() (server.Task, error) {
self := new(httpserver)
// Create a default router if not provided
if c.Router == nil {
c.Router = http.DefaultServeMux
}
// Set defaults
if c.Listen == "" {
if c.TLS.Cert != "" || c.TLS.Key != "" {
c.Listen = defaultListenTLS
} else {
c.Listen = defaultListen
}
}
// Choose HTTP or FCGI server
if strings.ContainsRune(c.Listen, ':') {
host, port, err := c.isHostPort()
if err != nil {
return nil, err
}
// Read the TLS configuration
tls, err := c.tls()
if err != nil {
return nil, err
}
// Create net server
addr := fmt.Sprintf("%s:%d", host, port)
if http, err := netserver(addr, tls, c.timeout(), c.Router); err != nil {
return nil, err
} else {
self.http = http
}
} else if abs, err := filepath.Abs(c.Listen); err != nil {
return nil, err
} else {
// file socket parameters
if owner, err := c.owner(); err != nil {
return nil, err
} else if group, err := c.group(); err != nil {
return nil, err
} else if fcgi, err := fcgiserver(abs, owner, group, c.fileMode(), c.dirMode(), c.Router); err != nil {
return nil, err
} else {
self.fcgi = fcgi
}
}
// Return success
return self, nil
}
///////////////////////////////////////////////////////////////////////////////
// STRINGIFY
// Return the configuration as a string
func (c Config) String() string {
data, _ := json.MarshalIndent(c, "", " ")
return string(data)
}
func (h httpserver) String() string {
var server struct {
Type string `json:"type"`
Addr string `json:"addr"`
}
if h.fcgi != nil {
server.Type = "fcgi"
server.Addr = h.fcgi.Addr
}
if h.http != nil {
server.Type = "http"
server.Addr = h.http.Addr
}
data, _ := json.MarshalIndent(server, "", " ")
return string(data)
}
/////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
// Run the http server until the context is cancelled
func (self *httpserver) Run(ctx context.Context) error {
var result error
var wg sync.WaitGroup
// Create cancelable context
child, cancel := context.WithCancel(ctx)
defer cancel()
// Stop server on context cancel
wg.Add(1)
go func() {
defer wg.Done()
<-child.Done()
if err := self.stop(); err != nil {
result = errors.Join(result, err)
}
}()
// Log the server is running
if log := provider.Logger(ctx); log != nil {
log.Printf(ctx, "Starting %v server on %q", self.Type(), self.Addr())
}
// Run server in foreground, cancel when done
if err := self.runInForeground(); err != nil && !errors.Is(err, http.ErrServerClosed) {
result = errors.Join(result, err)
cancel()
}
// Wait for gorutines to finish
wg.Wait()
// Return any errors
return result
}
// Return the label for the task
func (self *httpserver) Label() string {
// TODO
return defaultName
}
// Return the router for the server
func (self *httpserver) Router() http.Handler {
if self.fcgi != nil {
return self.fcgi.Handler
} else {
return self.http.Handler
}
}
// Return the type of server
func (self *httpserver) Type() string {
if self.fcgi != nil {
return "fcgi"
}
return "http"
}
// Return the listening address or path
func (self *httpserver) Addr() string {
if self.fcgi != nil {
return self.fcgi.Addr
}
return self.http.Addr
}
/////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
// Return the timeout value from the configuration
func (c Config) timeout() time.Duration {
if c.Timeout != 0 {
return c.Timeout
} else {
return defaultTimeout
}
}
// Return the TLS configuration
func (c Config) tls() (*tls.Config, error) {
if c.TLS.Cert == "" || c.TLS.Key == "" {
return nil, nil
}
if cert, err := tls.LoadX509KeyPair(c.TLS.Cert, c.TLS.Cert); err != nil {
return nil, fmt.Errorf("LoadX509KeyPair: %w", err)
} else {
return &tls.Config{
Certificates: []tls.Certificate{cert},
}, nil
}
}
// Return the uid of the socket owner
func (c Config) owner() (int, error) {
if c.Owner == "" {
return -1, nil
}
if user, err := user.Lookup(c.Owner); err != nil {
return -1, err
} else if uid, err := strconv.ParseUint(user.Uid, 0, 32); err != nil {
return -1, err
} else {
return int(uid), nil
}
}
// Return the gid of the socket group
func (c Config) group() (int, error) {
if c.Group == "" {
return -1, nil
}
if group, err := user.LookupGroup(c.Group); err != nil {
return -1, err
} else if gid, err := strconv.ParseUint(group.Gid, 0, 32); err != nil {
return -1, err
} else {
return int(gid), nil
}
}
// Return the socket filemode
func (c Config) fileMode() os.FileMode {
fileMode := defaultMode
if gid, err := c.group(); gid != -1 && err == nil {
fileMode |= groupMode
}
return (fileMode & allMode)
}
// Return the socket dir mode
func (c Config) dirMode() os.FileMode {
dirMode := defaultDirMode
if gid, err := c.group(); gid != -1 && err == nil {
dirMode |= groupDirMode
}
return (dirMode & allMode)
}
// Returns the host and port number from the configuration
// Random port number is chosen if port is not provided or is zero
func (c Config) isHostPort() (string, int, error) {
// Empty string not acceptable
if c.Listen == "" {
return "", 0, ErrBadParameter.With("empty listen address")
}
// Check for host:port and if no error, return true
if host, port, err := net.SplitHostPort(c.Listen); err != nil {
return "", 0, err
} else if port == "" || port == "0" {
if port, err := getFreePort(); err != nil {
return "", 0, err
} else {
return host, port, nil
}
} else if port_, err := strconv.ParseUint(port, 10, 16); err != nil {
if port_, err := net.LookupPort("tcp", port); err != nil {
return "", 0, err
} else {
return host, port_, nil
}
} else {
return host, int(port_), nil
}
}
// getFreePort returns a random free port
func getFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
// Run the server and block until stopped
func (self *httpserver) runInForeground() error {
if self.fcgi != nil {
return self.fcgi.ListenAndServe()
} else if self.http.TLSConfig != nil {
return self.http.ListenAndServeTLS("", "")
} else {
return self.http.ListenAndServe()
}
}
// Stop the server
func (self *httpserver) stop() error {
if self.fcgi != nil {
return self.fcgi.Close()
} else {
return self.http.Close()
}
}
// Create a fastcgi file socket server
func fcgiserver(path string, uid, gid int, fileMode os.FileMode, dirMode os.FileMode, handler http.Handler) (*fcgi.Server, error) {
fcgi := new(fcgi.Server)
fcgi.Network = "unix"
fcgi.Addr = path
fcgi.Handler = handler
fcgi.Owner = uid
fcgi.Group = gid
fcgi.Mode = fileMode
fcgi.DirMode = dirMode
// Return success
return fcgi, nil
}
// Create a network socket server
func netserver(addr string, config *tls.Config, timeout time.Duration, handler http.Handler) (*http.Server, error) {
srv := new(http.Server)
srv.Addr = addr
srv.Handler = handler
srv.ReadHeaderTimeout = timeout
srv.IdleTimeout = timeout
if config != nil {
srv.TLSConfig = config
}
// Return success
return srv, nil
}