Repository navigation
Expand file tree
/
Copy pathhttp.go
More file actions
219 lines (188 loc) · 5.46 KB
/
Copy pathhttp.go
File metadata and controls
219 lines (188 loc) · 5.46 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
func webserver(netbootDir string, b *Broker, m *Machines) (*http.ServeMux, error) {
server := http.NewServeMux()
if netbootDir == "" {
log.Printf("netboot directory was not specified, will not serve it: %s", netbootDir)
} else if _, err := os.Stat(netbootDir); os.IsNotExist(err) {
log.Printf("netboot directory does not exist, will not serve it: %s", netbootDir)
} else {
server.HandleFunc("/mac/{mac_addr}/boot.efi", func(w http.ResponseWriter, r *http.Request) {
// Extract MAC address from path
macStr := r.PathValue("mac_addr")
mac, err := net.ParseMAC(macStr)
if err != nil {
log.Printf("Got request with something that didn't look like a MAC address. Returning 404.")
http.NotFound(w, r)
return
}
name := path.Clean(path.Join(netbootDir, mac.String(), "boot.efi"))
if !strings.HasPrefix(name, netbootDir+"/") {
log.Println("Path did not clean to subordinate of", netbootDir)
http.Error(w, "fishy path", 400)
return
}
f, err := os.Open(name)
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
if stat.IsDir() {
http.Error(w, "boot.efi was a directory", 500)
return
}
w.Header().Set("Content-Length", strconv.FormatInt(stat.Size(), 10))
w.Header().Set("Content-Type", "application/octet-stream")
machine := m.GetOrInitMachine(mac)
event := TransferEvent{
Filename: name,
State: "init",
TotalBytes: stat.Size(),
}
if r.TLS == nil {
event.Protocol = "http"
} else {
event.Protocol = "https"
}
// Trigger state transition to http_fetch_uki
if err := machine.Event(r.Context(), "http_fetch_uki", event); err != nil {
log.Printf("Failed to transition to http_fetch_uki for %s: %v", macStr, err)
}
event.State = "sending"
reader := newProgressReader(f, func(bytes int64) error {
event.SentBytes = bytes
machine.Event(context.Background(), "http_fetch_uki", event)
return nil
})
_, err = io.Copy(w, reader)
if err != nil {
event.State = "error"
event.Error = err.Error()
machine.Event(context.Background(), "http_fetch_uki", event)
log.Printf("Serving failure: %v", err)
} else {
event.State = "complete"
machine.Event(context.Background(), "http_fetch_uki", event)
}
})
}
// SSE endpoint
server.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
macStr := params.Get("mac")
mac, err := net.ParseMAC(macStr)
if macStr != "" && err != nil {
http.Error(w, fmt.Sprintf("MAC error: %v", err), http.StatusBadRequest)
return
}
// Mandatory SSE headers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
// Tell client to retry in 3s if disconnected
if _, err = fmt.Fprint(w, "retry: 3000\n\n"); err != nil {
return
}
if macStr == "" {
data, err := json.Marshal(m)
if err != nil {
log.Println("JSON marshalling error: ", err)
} else {
if _, err = fmt.Fprintf(w, "data: %s\n\n", string(data)); err != nil {
return
}
}
} else {
data, err := json.Marshal(machines.GetMachine(mac))
if err != nil {
log.Println("JSON marshalling error: ", err)
} else {
if _, err := fmt.Fprintf(w, "data: %s\n\n", string(data)); err != nil {
return
}
}
}
flusher.Flush()
// Subscribe this client
ch, unsubscribe := b.Subscribe()
defer unsubscribe()
// Heartbeats to keep connections alive through proxies
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
case <-heartbeat.C:
// comment lines are ignored by EventSource but keep the pipe warm
if _, err = fmt.Fprint(w, ": heartbeat\n\n"); err != nil {
return
}
flusher.Flush()
case msg, ok := <-ch:
if !ok {
return
}
if macStr == "" || msg.Mac.String() == "" || msg.Mac.String() == mac.String() {
data, err := json.Marshal(msg)
if err != nil {
log.Println("JSON marshalling error: ", err)
} else {
if _, err = fmt.Fprintf(w, "data: %s\n\n", string(data)); err != nil {
return
}
flusher.Flush()
}
}
}
}
})
return server, nil
}
// Following was lifted from net/http:
//
// toHTTPError returns a non-specific HTTP error message and status code
// for a given non-nil error value. It's important that toHTTPError does not
// actually return err.Error(), since msg and httpStatus are returned to users,
// and historically Go's ServeContent always returned just "404 Not Found" for
// all errors. We don't want to start leaking information in error messages.
func toHTTPError(err error) (msg string, httpStatus int) {
if errors.Is(err, fs.ErrNotExist) {
return "404 page not found", http.StatusNotFound
}
if errors.Is(err, fs.ErrPermission) {
return "403 Forbidden", http.StatusForbidden
}
// Default:
return "500 Internal Server Error", http.StatusInternalServerError
}