/
response.go
587 lines (470 loc) · 13.5 KB
/
response.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
package response
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/lxd/ucred"
"github.com/canonical/lxd/lxd/util"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/tcp"
)
var debug bool
// Init sets the debug variable to the provided value.
func Init(d bool) {
debug = d
}
// Response represents an API response.
type Response interface {
Render(w http.ResponseWriter) error
String() string
}
// Devlxd response.
type devLxdResponse struct {
content any
code int
contentType string
}
func (r *devLxdResponse) Render(w http.ResponseWriter) error {
var err error
if r.code != http.StatusOK {
http.Error(w, fmt.Sprintf("%s", r.content), r.code)
} else if r.contentType == "json" {
w.Header().Set("Content-Type", "application/json")
var debugLogger logger.Logger
if debug {
debugLogger = logger.Logger(logger.Log)
}
err = util.WriteJSON(w, r.content, debugLogger)
} else if r.contentType != "websocket" {
w.Header().Set("Content-Type", "application/octet-stream")
_, err = fmt.Fprint(w, r.content.(string))
}
if err != nil {
return err
}
return nil
}
func (r *devLxdResponse) String() string {
if r.code == http.StatusOK {
return "success"
}
return "failure"
}
// DevLxdErrorResponse returns an error response. If rawResponse is true, a api.ResponseRaw will be sent instead of a minimal devLxdResponse.
func DevLxdErrorResponse(err error, rawResponse bool) Response {
if rawResponse {
return SmartError(err)
}
code, ok := api.StatusErrorMatch(err)
if ok {
return &devLxdResponse{content: err.Error(), code: code, contentType: "raw"}
}
return &devLxdResponse{content: err.Error(), code: http.StatusInternalServerError, contentType: "raw"}
}
// DevLxdResponse represents a devLxdResponse. If rawResponse is true, a api.ResponseRaw will be sent instead of a minimal devLxdResponse.
func DevLxdResponse(code int, content any, contentType string, rawResponse bool) Response {
if rawResponse {
return SyncResponse(true, content)
}
return &devLxdResponse{content: content, code: code, contentType: contentType}
}
// Sync response.
type syncResponse struct {
success bool
etag any
metadata any
location string
code int
headers map[string]string
plaintext bool
compress bool
}
// EmptySyncResponse represents an empty syncResponse.
var EmptySyncResponse = &syncResponse{success: true, metadata: make(map[string]any)}
// SyncResponse returns a new syncResponse with the success and metadata fields
// set to the provided values.
func SyncResponse(success bool, metadata any) Response {
return &syncResponse{success: success, metadata: metadata}
}
// SyncResponseETag returns a new syncResponse with an etag.
func SyncResponseETag(success bool, metadata any, etag any) Response {
return &syncResponse{success: success, metadata: metadata, etag: etag}
}
// SyncResponseLocation returns a new syncResponse with a location.
func SyncResponseLocation(success bool, metadata any, location string) Response {
return &syncResponse{success: success, metadata: metadata, location: location}
}
// SyncResponseRedirect returns a new syncResponse with a location, indicating
// a permanent redirect.
func SyncResponseRedirect(address string) Response {
return &syncResponse{success: true, location: address, code: http.StatusPermanentRedirect}
}
// SyncResponseHeaders returns a new syncResponse with headers.
func SyncResponseHeaders(success bool, metadata any, headers map[string]string) Response {
return &syncResponse{success: success, metadata: metadata, headers: headers}
}
// SyncResponsePlain return a new syncResponse with plaintext.
func SyncResponsePlain(success bool, compress bool, metadata string) Response {
return &syncResponse{success: success, metadata: metadata, plaintext: true, compress: compress}
}
func (r *syncResponse) Render(w http.ResponseWriter) error {
// Set an appropriate ETag header
if r.etag != nil {
etag, err := util.EtagHash(r.etag)
if err == nil {
w.Header().Set("ETag", fmt.Sprintf("\"%s\"", etag))
}
}
if r.headers != nil {
for h, v := range r.headers {
w.Header().Set(h, v)
}
}
code := r.code
if r.location != "" {
w.Header().Set("Location", r.location)
if code == 0 {
code = 201
}
}
// Handle plain text headers.
if r.plaintext {
w.Header().Set("Content-Type", "text/plain")
}
// Handle compression.
if r.compress {
w.Header().Set("Content-Encoding", "gzip")
}
// Write header and status code.
if code == 0 {
code = http.StatusOK
}
if w.Header().Get("Connection") != "keep-alive" {
w.WriteHeader(code)
}
// Prepare the JSON response
status := api.Success
if !r.success {
status = api.Failure
// If the metadata is an error, consider the response a SmartError
// to propagate the data and preserve the status code.
err, ok := r.metadata.(error)
if ok {
return SmartError(err).Render(w)
}
}
// Handle plain text responses.
if r.plaintext {
if r.metadata != nil {
if r.compress {
comp := gzip.NewWriter(w)
defer comp.Close()
_, err := comp.Write([]byte(r.metadata.(string)))
if err != nil {
return err
}
} else {
_, err := w.Write([]byte(r.metadata.(string)))
if err != nil {
return err
}
}
}
return nil
}
// Handle JSON responses.
resp := api.ResponseRaw{
Type: api.SyncResponse,
Status: status.String(),
StatusCode: int(status),
Metadata: r.metadata,
}
var debugLogger logger.Logger
if debug {
debugLogger = logger.AddContext(logger.Ctx{"http_code": code})
}
return util.WriteJSON(w, resp, debugLogger)
}
func (r *syncResponse) String() string {
if r.success {
return "success"
}
return "failure"
}
// Error response.
type errorResponse struct {
code int // Code to return in both the HTTP header and Code field of the response body.
msg string // Message to return in the Error field of the response body.
}
// ErrorResponse returns an error response with the given code and msg.
func ErrorResponse(code int, msg string) Response {
return &errorResponse{code, msg}
}
// BadRequest returns a bad request response (400) with the given error.
func BadRequest(err error) Response {
return &errorResponse{http.StatusBadRequest, err.Error()}
}
// Conflict returns a conflict response (409) with the given error.
func Conflict(err error) Response {
message := "already exists"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusConflict, message}
}
// Forbidden returns a forbidden response (403) with the given error.
func Forbidden(err error) Response {
message := "not authorized"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusForbidden, message}
}
// InternalError returns an internal error response (500) with the given error.
func InternalError(err error) Response {
return &errorResponse{http.StatusInternalServerError, err.Error()}
}
// NotFound returns a not found response (404) with the given error.
func NotFound(err error) Response {
message := "not found"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusNotFound, message}
}
// NotImplemented returns a not implemented response (501) with the given error.
func NotImplemented(err error) Response {
message := "not implemented"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusNotImplemented, message}
}
// PreconditionFailed returns a precondition failed response (412) with the
// given error.
func PreconditionFailed(err error) Response {
return &errorResponse{http.StatusPreconditionFailed, err.Error()}
}
// Unavailable return an unavailable response (503) with the given error.
func Unavailable(err error) Response {
message := "unavailable"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusServiceUnavailable, message}
}
func (r *errorResponse) String() string {
return r.msg
}
func (r *errorResponse) Render(w http.ResponseWriter) error {
var output io.Writer
buf := &bytes.Buffer{}
output = buf
var captured *bytes.Buffer
if debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(buf, captured)
}
resp := api.ResponseRaw{
Type: api.ErrorResponse,
Error: r.msg,
Code: r.code, // Set the error code in the Code field of the response body.
}
err := json.NewEncoder(output).Encode(resp)
if err != nil {
return err
}
if debug {
debugLogger := logger.AddContext(logger.Ctx{"http_code": r.code})
util.DebugJSON("Error Response", captured, debugLogger)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
if w.Header().Get("Connection") != "keep-alive" {
w.WriteHeader(r.code) // Set the error code in the HTTP header response.
}
_, err = fmt.Fprintln(w, buf.String())
return err
}
// FileResponseEntry represents a file response entry.
type FileResponseEntry struct {
// Required.
Identifier string
Filename string
// Read from a filesystem path.
Path string
// Read from a file.
File io.ReadSeeker
FileSize int64
FileModified time.Time
// Optional.
Cleanup func()
}
type fileResponse struct {
req *http.Request
files []FileResponseEntry
headers map[string]string
}
// FileResponse returns a new file response.
func FileResponse(r *http.Request, files []FileResponseEntry, headers map[string]string) Response {
return &fileResponse{r, files, headers}
}
func (r *fileResponse) Render(w http.ResponseWriter) error {
if r.headers != nil {
for k, v := range r.headers {
w.Header().Set(k, v)
}
}
// No file, well, it's easy then
if len(r.files) == 0 {
return nil
}
// For a single file, return it inline
if len(r.files) == 1 {
remoteConn := ucred.GetConnFromContext(r.req.Context())
remoteTCP, _ := tcp.ExtractConn(remoteConn)
if remoteTCP != nil {
// Apply TCP timeouts if remote connection is TCP (rather than Unix).
err := tcp.SetTimeouts(remoteTCP, 10*time.Second)
if err != nil {
return api.StatusErrorf(http.StatusInternalServerError, "Failed setting TCP timeouts on remote connection: %w", err)
}
}
var rs io.ReadSeeker
var mt time.Time
var sz int64
if r.files[0].Cleanup != nil {
defer r.files[0].Cleanup()
}
if r.files[0].File != nil {
rs = r.files[0].File
mt = r.files[0].FileModified
sz = r.files[0].FileSize
} else {
f, err := os.Open(r.files[0].Path)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
fi, err := f.Stat()
if err != nil {
return err
}
mt = fi.ModTime()
sz = fi.Size()
rs = f
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", fmt.Sprintf("%d", sz))
w.Header().Set("Content-Disposition", fmt.Sprintf("inline;filename=%s", r.files[0].Filename))
http.ServeContent(w, r.req, r.files[0].Filename, mt, rs)
return nil
}
// Now the complex multipart answer.
mw := multipart.NewWriter(w)
defer func() { _ = mw.Close() }()
w.Header().Set("Content-Type", mw.FormDataContentType())
w.Header().Set("Transfer-Encoding", "chunked")
for _, entry := range r.files {
var rd io.Reader
if entry.File != nil {
rd = entry.File
} else {
fd, err := os.Open(entry.Path)
if err != nil {
return err
}
defer func() { _ = fd.Close() }()
rd = fd
}
fw, err := mw.CreateFormFile(entry.Identifier, entry.Filename)
if err != nil {
return err
}
_, err = io.Copy(fw, rd)
if err != nil {
return err
}
if entry.Cleanup != nil {
entry.Cleanup()
}
}
return mw.Close()
}
func (r *fileResponse) String() string {
return fmt.Sprintf("%d files", len(r.files))
}
type forwardedResponse struct {
client lxd.InstanceServer
request *http.Request
}
// ForwardedResponse takes a request directed to a node and forwards it to
// another node, writing back the response it gegs.
func ForwardedResponse(client lxd.InstanceServer, request *http.Request) Response {
return &forwardedResponse{
client: client,
request: request,
}
}
func (r *forwardedResponse) Render(w http.ResponseWriter) error {
info, err := r.client.GetConnectionInfo()
if err != nil {
return err
}
url := fmt.Sprintf("%s%s", info.Addresses[0], r.request.URL.RequestURI())
forwarded, err := http.NewRequest(r.request.Method, url, r.request.Body)
if err != nil {
return err
}
for key := range r.request.Header {
forwarded.Header.Set(key, r.request.Header.Get(key))
}
httpClient, err := r.client.GetHTTPClient()
if err != nil {
return err
}
response, err := httpClient.Do(forwarded)
if err != nil {
return err
}
for key := range response.Header {
w.Header().Set(key, response.Header.Get(key))
}
if w.Header().Get("Connection") != "keep-alive" {
w.WriteHeader(response.StatusCode)
}
_, err = io.Copy(w, response.Body)
return err
}
func (r *forwardedResponse) String() string {
return fmt.Sprintf("request to %s", r.request.URL)
}
type manualResponse struct {
hook func(w http.ResponseWriter) error
}
// ManualResponse creates a new manual response responder.
func ManualResponse(hook func(w http.ResponseWriter) error) Response {
return &manualResponse{hook: hook}
}
func (r *manualResponse) Render(w http.ResponseWriter) error {
return r.hook(w)
}
func (r *manualResponse) String() string {
return "unknown"
}
// Unauthorized return an unauthorized response (401) with the given error.
func Unauthorized(err error) Response {
message := "unauthorized"
if err != nil {
message = err.Error()
}
return &errorResponse{http.StatusUnauthorized, message}
}