/
api_logging.go
250 lines (216 loc) · 6.42 KB
/
api_logging.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
/*
Copyright © 2020 Dell Inc. or its subsidiaries. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
log "github.com/sirupsen/logrus"
)
func isBinOctetBody(h http.Header) bool {
return h.Get(HeaderKeyContentType) == headerValContentTypeBinaryOctetStream
}
func logRequest(
ctx context.Context,
req *http.Request,
lf func(func(args ...interface{}), string)) {
w := &bytes.Buffer{}
fmt.Fprintln(w)
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "POWERMAX HTTP REQUEST")
fmt.Fprintln(w, " -------------------------")
buf, err := dumpRequest(req, !isBinOctetBody(req.Header))
if err != nil {
return
}
WriteIndented(w, buf) // #nosec G20
fmt.Fprintln(w)
lf(log.Debug, w.String())
}
func logResponse(
ctx context.Context,
res *http.Response,
lf func(func(args ...interface{}), string)) {
w := &bytes.Buffer{}
fmt.Fprintln(w)
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "POWERMAX HTTP RESPONSE")
fmt.Fprintln(w, " -------------------------")
buf, err := httputil.DumpResponse(res, !isBinOctetBody(res.Header))
if err != nil {
return
}
bw := &bytes.Buffer{}
WriteIndented(bw, buf) // #nosec G20
scanner := bufio.NewScanner(bw)
for {
if !scanner.Scan() {
break
}
fmt.Fprintln(w, scanner.Text())
}
log.Debug(w.String())
}
// WriteIndentedN indents all lines n spaces.
func WriteIndentedN(w io.Writer, b []byte, n int) error {
s := bufio.NewScanner(bytes.NewReader(b))
if !s.Scan() {
return nil
}
l := s.Text()
for {
for x := 0; x < n; x++ {
if _, err := fmt.Fprint(w, " "); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, l); err != nil {
return err
}
if !s.Scan() {
break
}
l = s.Text()
if _, err := fmt.Fprint(w, "\n"); err != nil {
return err
}
}
return nil
}
// WriteIndented indents all lines four spaces.
func WriteIndented(w io.Writer, b []byte) error {
return WriteIndentedN(w, b, 4)
}
var reqWriteExcludeHeaderDump = map[string]bool{
"Host": true, // not in Header map anyway
"Transfer-Encoding": true,
"Trailer": true,
"Authorization": true,
}
// drainBody reads all of b to memory and then returns two equivalent
// ReadClosers yielding the same bytes.
//
// It returns an error if the initial slurp of all bytes fails. It does not attempt
// to make the returned ReadClosers have identical error-matching behavior.
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if b == http.NoBody {
// No copying needed. Preserve the magic sentinel meaning of NoBody.
return http.NoBody, http.NoBody, nil
}
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
// dumpRequest returns the given request in its HTTP/1.x wire
// representation. It should only be used by servers to debug client
// requests. The returned representation is an approximation only;
// some details of the initial request are lost while parsing it into
// an http.Request. In particular, the order and case of header field
// names are lost. The order of values in multi-valued headers is kept
// intact. HTTP/2 requests are dumped in HTTP/1.x form, not in their
// original binary representations.
//
// If body is true, DumpRequest also returns the body. To do so, it
// consumes req.Body and then replaces it with a new io.ReadCloser
// that yields the same bytes. If DumpRequest returns an error,
// the state of req is undefined.
//
// The documentation for http.Request.Write details which fields
// of req are included in the dump.
func dumpRequest(req *http.Request, body bool) ([]byte, error) {
var err error
save := req.Body
if !body || req.Body == nil {
req.Body = nil
} else {
save, req.Body, err = drainBody(req.Body)
if err != nil {
return nil, err
}
}
var b bytes.Buffer
// By default, print out the unmodified req.RequestURI, which
// is always set for incoming server requests. But because we
// previously used req.URL.RequestURI and the docs weren't
// always so clear about when to use DumpRequest vs
// DumpRequestOut, fall back to the old way if the caller
// provides a non-server Request.
reqURI := req.RequestURI
if reqURI == "" {
reqURI = req.URL.RequestURI()
}
method := "GET"
if req.Method != "" {
method = req.Method
}
fmt.Fprintf(&b, "%s %s HTTP/%d.%d\r\n", method, reqURI, req.ProtoMajor, req.ProtoMinor)
absRequestURI := strings.HasPrefix(req.RequestURI, "http://") || strings.HasPrefix(req.RequestURI, "https://")
if !absRequestURI {
host := req.Host
if host == "" && req.URL != nil {
host = req.URL.Host
}
if host != "" {
fmt.Fprintf(&b, "Host: %s\r\n", host)
}
}
chunked := len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked"
if len(req.TransferEncoding) > 0 {
fmt.Fprintf(&b, "Transfer-Encoding: %s\r\n", strings.Join(req.TransferEncoding, ","))
}
if req.Close {
fmt.Fprintf(&b, "Connection: close\r\n")
}
if encodedCred, isAuth := req.Header["Authorization"]; isAuth {
decodedCred, err := base64.StdEncoding.DecodeString(strings.Split(encodedCred[0], " ")[1])
if err != nil {
fmt.Println("decode error:", err.Error())
return b.Bytes(), err
}
cred := strings.Split(string(decodedCred), ":")
log.Debugf("username: %s , password: %s", cred[0], "*****")
}
err = req.Header.WriteSubset(&b, reqWriteExcludeHeaderDump)
if err != nil {
return nil, err
}
io.WriteString(&b, "\r\n") // #nosec G20
if req.Body != nil {
var dest io.Writer = &b
if chunked {
dest = httputil.NewChunkedWriter(dest)
}
_, err = io.Copy(dest, req.Body)
if chunked {
dest.(io.Closer).Close() // #nosec G20
io.WriteString(&b, "\r\n") // #nosec G20
}
}
req.Body = save
if err != nil {
return nil, err
}
return b.Bytes(), nil
}