-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
362 lines (319 loc) · 9.04 KB
/
main.go
File metadata and controls
362 lines (319 loc) · 9.04 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
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
package main
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"github.com/spf13/pflag"
)
var (
version = "*unset*"
versionFlag bool
dumpRequestFlag bool
dumpBodyFlag bool
statusCodeFlag uint
responseHeadersFlag []string
responseBodyFlag string
exitAfterFlag uint
certFileFlag string
keyFileFlag string
userFlag string
responseCount uint = 0
absBaseDir string
)
func main() {
pflag.BoolVar(&versionFlag, "version", false, "show version")
pflag.BoolVar(&dumpRequestFlag, "dump", false, "dump client request")
pflag.BoolVar(&dumpBodyFlag, "dump-body", false, "dump client request body")
pflag.UintVarP(&statusCodeFlag, "status", "s", 200, "return status code")
pflag.StringArrayVarP(&responseHeadersFlag, "header", "H", []string{}, "HTTP response header")
pflag.StringVarP(&responseBodyFlag, "data", "d", "", "add HTTP response body")
pflag.UintVarP(&exitAfterFlag, "count", "c", 0, "exit after number of requests (0 keep running)")
pflag.StringVar(&certFileFlag, "cert", "", "TLS certificate file")
pflag.StringVarP(&userFlag, "user", "u", "", "user credentials '<user:password>' for Basic Auth")
pflag.Usage = func() {
_, _ = fmt.Fprintf(os.Stderr, "Usage: %s [options...] <addr>\n%s", filepath.Base(os.Args[0]),
pflag.CommandLine.FlagUsages(),
)
}
pflag.Parse()
if versionFlag {
fmt.Printf("surl %s\n", version)
os.Exit(0)
}
addr, err := parseAddr()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%s\n", err)
pflag.Usage()
os.Exit(1)
}
if responseBodyFlag != "" && strings.HasPrefix(responseBodyFlag, "@") {
fn := trimFirst(responseBodyFlag)
s, err := os.Stat(fn)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%s\n", err)
pflag.Usage()
os.Exit(1)
}
if s.IsDir() {
absBaseDir, err = filepath.Abs(fn)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%s\n", err)
pflag.Usage()
os.Exit(1)
}
}
}
srv := http.Server{Addr: addr}
description := fmt.Sprintf("surl/%s", version)
sigChan := make(chan os.Signal, 1)
http.Handle("/", requestLogger(globalHandler(description, sigChan)))
go func() {
log.Printf("starting %s on %s %s", description, addr, desc(exitAfterFlag))
if absBaseDir != "" {
log.Printf("serving files from: %s", absBaseDir)
}
if certFileFlag != "" && keyFileFlag != "" {
if err := srv.ListenAndServeTLS(certFileFlag, keyFileFlag); !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("startup error: %v", err)
}
return
}
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("startup error: %v", err)
}
}()
// wait for request count
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()
if exitAfterFlag != responseCount {
log.Printf("shutting down after %d responses", responseCount)
}
err = srv.Shutdown(shutdownCtx)
if err != nil {
log.Fatalf("shutdown error: %v", err)
}
}
type ctxLogDataKey struct{}
type collectingResponseWriter struct {
http.ResponseWriter
statusCode int
size int
}
func (crw *collectingResponseWriter) WriteHeader(code int) {
crw.statusCode = code
crw.ResponseWriter.WriteHeader(code)
}
func (crw *collectingResponseWriter) Write(b []byte) (int, error) {
n, err := crw.ResponseWriter.Write(b)
crw.size += n
return n, err
}
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
logData := make(map[string]any)
ctx := context.WithValue(r.Context(), ctxLogDataKey{}, logData)
r = r.WithContext(ctx)
cw := &collectingResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(cw, r)
log.Printf("%s - %s \"%s %s %s\" %d %d %s %s [%s]%s",
logUser(r),
r.RemoteAddr,
r.Method,
logPath(r, logData),
r.Proto,
cw.statusCode,
cw.size,
r.Referer(),
r.UserAgent(),
time.Since(started),
logDump(logData),
)
})
}
func logDump(logData map[string]any) string {
if d, ok := logData["dump"].([]byte); ok {
return fmt.Sprintf("\n%s", indent(hex.Dump(d), 20))
}
return ""
}
func indent(s string, spaces int) string {
indent := strings.Repeat(" ", spaces)
return fmt.Sprintln(indent + strings.ReplaceAll(s, "\n", "\n"+indent))
}
func logUser(r *http.Request) string {
if user, _, ok := r.BasicAuth(); ok {
return user
}
return "???"
}
func logPath(r *http.Request, logdata map[string]any) string {
p := r.URL.Path
if logdata != nil {
if s, ok := logdata["served-file"]; ok && s != "" {
p += fmt.Sprintf(" (%s)", s)
}
}
return p
}
func addLogData(r *http.Request, key string, value any) {
if logData, ok := r.Context().Value(ctxLogDataKey{}).(map[string]any); ok {
logData[key] = value
}
}
func globalHandler(description string, sigChan chan os.Signal) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if userFlag != "" {
if !validateBasicAuth(r, userFlag) {
w.Header().Add("WWW-Authenticate", "Basic realm=\"Auth Required\"")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
responseCount += 1
if dumpRequestFlag || dumpBodyFlag {
dump, err := httputil.DumpRequest(r, dumpBodyFlag)
if err != nil {
log.Printf("error: unable to dump client request: %s", err)
return
}
addLogData(r, "dump", dump)
// log.Printf("\n--\n%q\n--\n", dump)
}
if len(responseHeadersFlag) != 0 {
for _, hdr := range responseHeadersFlag {
if err := addRawHeader(w.Header(), hdr); err != nil {
log.Printf("error: unable to add response header: %s", err)
}
}
}
if w.Header().Get("Server") == "" {
w.Header().Add("Server", description)
}
if responseBodyFlag != "" {
if strings.HasPrefix(responseBodyFlag, "@") {
// response is filename
filename := trimFirst(responseBodyFlag)
s, err := os.Stat(filename)
if err != nil {
log.Printf("error: unable to stat file: '%s'", filename)
return
}
if s.IsDir() {
requestPath := filepath.Join(filename, filepath.Clean("/"+r.URL.Path))
absRequestPath, err := filepath.Abs(requestPath)
if err != nil {
log.Printf("error: unable to establish absolute path from '%s': %s", requestPath, err)
return
}
if !strings.HasPrefix(absRequestPath, absBaseDir) {
log.Printf("error: path '%s' outside of base '%s'", requestPath, filename)
return
}
filename = absRequestPath
s, err = os.Stat(filename)
if err != nil {
log.Printf("error: unable to stat file: '%s'", filename)
return
}
}
addLogData(r, "served-file", filename)
file, err := os.Open(filename)
if err != nil {
log.Printf("error: unable to open file: '%s'", filename)
return
}
defer quietClose(file)
if w.Header().Get("Content-Length") == "" {
w.Header().Add("Content-Length", strconv.Itoa(int(s.Size())))
}
w.WriteHeader(int(statusCodeFlag)) // start sending body
if _, err = io.Copy(w, file); err != nil {
log.Printf("error: unable to write response body: %s", err)
}
} else {
w.WriteHeader(int(statusCodeFlag)) // start sending body
if _, err := w.Write([]byte(responseBodyFlag)); err != nil {
log.Printf("error: unable to write response body: %s", err)
}
}
} else {
w.WriteHeader(int(statusCodeFlag))
}
if exitAfterFlag != 0 && exitAfterFlag == responseCount {
log.Printf("response count of %d reached, shutting down", responseCount)
sigChan <- os.Interrupt
}
})
}
func validAddr(s string) error {
p := strings.SplitN(s, ":", 2)
if p == nil || len(p) != 2 {
return fmt.Errorf("invalid format ([host]:<port>)")
}
if _, err := strconv.Atoi(p[1]); err != nil {
return err
}
return nil
}
func validateBasicAuth(r *http.Request, up string) bool {
if user, pass, ok := r.BasicAuth(); ok {
return up == user+":"+pass
}
return false
}
func parseAddr() (string, error) {
if pflag.NArg() != 1 {
return "", fmt.Errorf("requred: 'addr'")
}
addr := pflag.Arg(0)
if err := validAddr(addr); err != nil {
return "", fmt.Errorf("invalid addr: %s (%s)\n", addr, err)
}
return addr, nil
}
func desc(c uint) string {
if c == 0 {
return "(run for ever)"
}
return fmt.Sprintf("(run for %d requests)", c)
}
func trimFirst(s string) string {
_, i := utf8.DecodeRuneInString(s)
return s[i:]
}
func splitToKeyValue(s string, sep string) (string, string, error) {
kv := strings.SplitN(s, sep, 2)
if len(kv) != 2 {
return "", "", fmt.Errorf("invalid key%svalue format: '%s'", sep, s)
}
return kv[0], kv[1], nil
}
func addRawHeader(headers http.Header, rawHeader string) error {
name, value, err := splitToKeyValue(rawHeader, ":")
if err != nil {
return fmt.Errorf("invalid http header: '%w'", err)
}
headers.Add(name, value)
return nil
}
func quietClose(c io.Closer) {
if err := c.Close(); err != nil {
log.Printf("error: unable to close: %s", err)
}
}