-
Notifications
You must be signed in to change notification settings - Fork 1
/
output.go
258 lines (218 loc) · 6.81 KB
/
output.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
// Package output is responsible for writing logs and received response data.
package output
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/ameshkov/gocurl/internal/config"
)
// Output is responsible for all the output, be it logging or writing received
// data.
type Output struct {
receivedDataFile *os.File
logFile *os.File
verbose bool
}
// NewOutput creates a new instance of Output. path is an optional path to the
// file where the tool will write the received data. If not specified, this
// information will be written to stdout. verbose defines whether we need to
// write extended information.
func NewOutput(path string, verbose bool) (o *Output, err error) {
o = &Output{
verbose: verbose,
logFile: os.Stderr,
receivedDataFile: os.Stdout,
}
if path != "" {
o.receivedDataFile, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644)
}
return o, err
}
// Write writes received data to the output path (or stdout if not specified).
func (o *Output) Write(resp *http.Response, cfg *config.Config) {
var err error
if cfg.OutputJSON {
var b []byte
b, err = responseToJSON(resp)
if err != nil {
panic(err)
}
_, err = o.receivedDataFile.Write(b)
} else if cfg.Head {
_, err = o.receivedDataFile.WriteString(responseToString(resp))
} else {
_, err = io.Copy(o.receivedDataFile, resp.Body)
}
if err != nil {
panic(err)
}
}
// Info writes INFO-level log to stderr.
func (o *Output) Info(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
_, err := os.Stderr.WriteString(msg + "\n")
if err != nil {
panic(err)
}
}
// Debug writes DEBUG-level log to stderr (controlled by the verbose flag).
func (o *Output) Debug(format string, args ...any) {
if !o.verbose {
return
}
_, err := os.Stderr.WriteString(fmt.Sprintf(format, args...) + "\n")
if err != nil {
panic(err)
}
}
// DebugRequest writes information about the HTTP request to the output.
//
// TODO(ameshkov): instead of this, log the actual data sent to tls.Conn.
func (o *Output) DebugRequest(req *http.Request) {
o.Debug("Request:\n%s", requestToString(req))
}
// DebugResponse writes information about the HTTP response to the output.
//
// TODO(ameshkov): instead of this, log the actual data received from tls.Conn.
func (o *Output) DebugResponse(resp *http.Response) {
if resp.TLS != nil {
s := stateToTLSState(resp.TLS)
o.Debug("\n----\nTLS:")
o.Debug("Server name: %s", s.ServerName)
o.Debug("Version: %s", s.Version)
o.Debug("Cipher: %s", s.CipherSuite)
if s.NegotiatedProtocol != "" {
o.Debug("Negotiated protocol: %s", s.NegotiatedProtocol)
}
o.Debug("\n----\nCertificates:")
for i, certInfo := range s.Certificates {
o.Debug("Certificate №%d:\n", i+1)
o.Debug("Subject: %s", certInfo.Subject)
o.Debug("Issuer: %s", certInfo.Issuer)
o.Debug("Not before: %s", certInfo.NotBefore)
o.Debug("Not after: %s", certInfo.NotAfter)
if len(certInfo.DNSNames) > 0 {
o.Debug("DNS names:\n%s", strings.Join(certInfo.DNSNames, "\n"))
}
if len(certInfo.IPAddresses) > 0 {
o.Debug("IP addresses:\n%s", strings.Join(certInfo.IPAddresses, "\n"))
}
o.Debug("Raw certificate:")
o.Debug(certInfo.Raw)
}
}
o.Debug("Response:\n----\n%s", responseToString(resp))
}
// requestToString converts HTTP request to a string.
func requestToString(req *http.Request) (str string) {
cloneReq := req.Clone(context.Background())
b := &bytes.Buffer{}
_ = cloneReq.Write(b)
return b.String()
}
// responseToString converts HTTP response to a string.
func responseToString(resp *http.Response) (str string) {
return fmt.Sprintf(
"%s %s\r\n%s",
resp.Proto,
resp.Status,
headersToString(resp.Header),
)
}
// headersToString converts HTTP headers to a string.
func headersToString(headers http.Header) (str string) {
for key, values := range headers {
for _, value := range values {
str = str + fmt.Sprintf("%s: %s\r\n", key, value)
}
}
return str
}
// TLSCertificate is a helper object for serializing information about x509
// certificates.
type TLSCertificate struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
DNSNames []string `json:"dns_names"`
IPAddresses []string `json:"ip_addresses"`
Raw string `json:"raw"`
}
// TLSState is a helper object for serializing response data to JSON.
type TLSState struct {
ServerName string `json:"server_name"`
Version string `json:"version"`
CipherSuite string `json:"cipher_suite"`
NegotiatedProtocol string `json:"negotiated_protocol"`
Certificates []TLSCertificate `json:"certificates"`
}
// ResponseData is a helper object for serializing response data to JSON.
type ResponseData struct {
StatusCode int `json:"status_code"`
Status string `json:"status"`
Proto string `json:"proto"`
TLS *TLSState `json:"tls"`
Headers map[string][]string `json:"headers"`
BodyBase64 string `json:"body_base64"`
}
// stateToTLSState converts tls.ConnectionState to TLSState.
func stateToTLSState(state *tls.ConnectionState) (s *TLSState) {
s = &TLSState{
ServerName: state.ServerName,
Version: tls.VersionName(state.Version),
CipherSuite: tls.CipherSuiteName(state.CipherSuite),
NegotiatedProtocol: state.NegotiatedProtocol,
}
for _, cert := range state.PeerCertificates {
var certInfo TLSCertificate
certInfo.Subject = cert.Subject.String()
certInfo.Issuer = cert.Issuer.String()
certInfo.NotBefore = cert.NotBefore
certInfo.NotAfter = cert.NotAfter
certInfo.DNSNames = cert.DNSNames
for _, ip := range cert.IPAddresses {
certInfo.IPAddresses = append(certInfo.IPAddresses, ip.String())
}
certInfo.Raw = certToPEM(cert.Raw)
s.Certificates = append(s.Certificates, certInfo)
}
return s
}
// responseToJSON transforms response data to JSON format.
func responseToJSON(resp *http.Response) (b []byte, err error) {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
data := ResponseData{
StatusCode: resp.StatusCode,
Status: resp.Status,
Proto: resp.Proto,
Headers: resp.Header,
BodyBase64: base64.StdEncoding.EncodeToString(body),
}
if resp.TLS != nil {
data.TLS = stateToTLSState(resp.TLS)
}
b, err = json.MarshalIndent(data, "", " ")
return b, err
}
// certToPEM serializes certificate bytes to PEM format.
func certToPEM(certBytes []byte) (str string) {
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
}
pemBytes := pem.EncodeToMemory(block)
return string(pemBytes)
}