Debian Codegraph @

api/v0/messenger/decoder.go

raw symbols SCIP
1 package messenger
2
3 import (
4 "bufio"
5 "bytes"
6 "errors"
7 "io"
8 "net"
9 "net/http"
10 "net/textproto"
11 "net/url"
12 "strconv"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "syscall"
17 "time"
18
19 log "github.com/golang/glog"
20 )
21
22 const (
23 // writeFlushPeriod is the amount of time we're willing to wait for a single
24 // response buffer to be fully written to the underlying TCP connection; after
25 // this amount of time the remaining bytes of the response are discarded. see
26 // responseWriter().
27 writeFlushPeriod = 30 * time.Second
28 )
29
30 type decoderID int32
31
32 func (did decoderID) String() string {
33 return "[" + strconv.Itoa(int(did)) + "]"
34 }
35
36 func (did *decoderID) next() decoderID {
37 return decoderID(atomic.AddInt32((*int32)(did), 1))
38 }
39
40 var (
41 errHijackFailed = errors.New("failed to hijack http connection")
42 did decoderID // decoder ID counter
43 )
44
45 type Decoder interface {
46 Requests() <-chan *Request
47 Err() <-chan error
48 Cancel(bool)
49 }
50
51 type Request struct {
52 *http.Request
53 response chan<- Response // callers that are finished with a Request should ensure that response is *always* closed, regardless of whether a Response has been written.
54 }
55
56 type Response struct {
57 code int
58 reason string
59 }
60
61 type httpDecoder struct {
62 req *http.Request // original request
63 kalive bool // keepalive
64 chunked bool // chunked
65 msg chan *Request
66 con net.Conn
67 rw *bufio.ReadWriter
68 errCh chan error
69 buf *bytes.Buffer
70 lrc *io.LimitedReader
71 shouldQuit chan struct{} // signal chan, closes upon calls to Cancel(...)
72 forceQuit chan struct{} // signal chan, indicates that quit is NOT graceful; closes upon Cancel(false)
73 cancelGuard sync.Mutex
74 readTimeout time.Duration
75 writeTimeout time.Duration
76 idtag string // useful for debugging
77 sendError func(err error) // abstraction for error handling
78 outCh chan *bytes.Buffer // chan of responses to be written to the connection
79 }
80
81 // DecodeHTTP hijacks an HTTP server connection and generates mesos libprocess HTTP
82 // requests via the returned chan. Upon generation of an error in the error chan the
83 // decoder's internal goroutine will terminate. This func returns immediately.
84 // The caller should immediately *stop* using the ResponseWriter and Request that were
85 // passed as parameters; the decoder assumes full control of the HTTP transport.
86 func DecodeHTTP(w http.ResponseWriter, r *http.Request) Decoder {
87 id := did.next()
88 d := &httpDecoder{
89 msg: make(chan *Request),
90 errCh: make(chan error, 1),
91 req: r,
92 shouldQuit: make(chan struct{}),
93 forceQuit: make(chan struct{}),
94 readTimeout: ReadTimeout,
95 writeTimeout: WriteTimeout,
96 idtag: id.String(),
97 outCh: make(chan *bytes.Buffer),
98 }
99 d.sendError = d.defaultSendError
100 go d.run(w)
101 return d
102 }
103
104 func (d *httpDecoder) Requests() <-chan *Request {
105 return d.msg
106 }
107
108 func (d *httpDecoder) Err() <-chan error {
109 return d.errCh
110 }
111
112 // Cancel the decoding process; if graceful then process pending responses before terminating
113 func (d *httpDecoder) Cancel(graceful bool) {
114 log.V(2).Infof("%scancel:%t", d.idtag, graceful)
115 d.cancelGuard.Lock()
116 defer d.cancelGuard.Unlock()
117 select {
118 case <-d.shouldQuit:
119 // already quitting, but perhaps gracefully?
120 default:
121 close(d.shouldQuit)
122 }
123 // allow caller to "upgrade" from a graceful cancel to a forced one
124 if !graceful {
125 select {
126 case <-d.forceQuit:
127 // already forcefully quitting
128 default:
129 close(d.forceQuit) // push it!
130 }
131 }
132 }
133
134 func (d *httpDecoder) run(res http.ResponseWriter) {
135 defer func() {
136 close(d.outCh) // we're finished generating response objects
137 log.V(2).Infoln(d.idtag + "run: terminating")
138 }()
139
140 for state := d.bootstrapState(res); state != nil; {
141 next := state(d)
142 state = next
143 }
144 }
145
146 // tryFlushResponse flushes the response buffer (if not empty); returns true if flush succeeded
147 func (d *httpDecoder) tryFlushResponse(out *bytes.Buffer) {
148 log.V(2).Infof(d.idtag+"try-flush-responses: %d bytes to flush", out.Len())
149 // set a write deadline here so that we don't block for very long.
150 err := d.setWriteTimeout()
151 if err != nil {
152 // this is a problem because if we can't set the timeout then we can't guarantee
153 // how long a write op might block for. Log the error and skip this response.
154 log.Errorln("failed to set write deadline, aborting response:", err.Error())
155 } else {
156 _, err = out.WriteTo(d.rw.Writer)
157 if err != nil {
158 if neterr, ok := err.(net.Error); ok && neterr.Timeout() && out.Len() > 0 {
159 // we couldn't fully write before timing out, return rch and hope that
160 // we have better luck next time.
161 return
162 }
163 // we don't really know how to deal with other kinds of errors, so
164 // log it and skip the rest of the response.
165 log.Errorln("failed to write response buffer:", err.Error())
166 }
167 err = d.rw.Flush()
168 if err != nil {
169 if neterr, ok := err.(net.Error); ok && neterr.Timeout() && out.Len() > 0 {
170 return
171 }
172 log.Errorln("failed to flush response buffer:", err.Error())
173 }
174 }
175 }
176
177 // TODO(jdef) make this a func on Response, to write its contents to a *bytes.Buffer
178 func (d *httpDecoder) buildResponseEntity(resp *Response) *bytes.Buffer {
179 log.V(2).Infoln(d.idtag + "build-response-entity")
180
181 out := &bytes.Buffer{}
182
183 // generate new response buffer content and continue; buffer should have
184 // at least a response status-line w/ Content-Length: 0
185 out.WriteString("HTTP/1.1 ")
186 out.WriteString(strconv.Itoa(resp.code))
187 out.WriteString(" ")
188 out.WriteString(resp.reason)
189 out.WriteString(crlf + "Content-Length: 0" + crlf)
190
191 select {
192 case <-d.shouldQuit:
193 // this is the last request in the pipeline and we've been told to quit, so
194 // indicate that the server will close the connection.
195 out.WriteString("Connection: Close" + crlf)
196 default:
197 }
198 out.WriteString(crlf) // this ends the HTTP response entity
199 return out
200 }
201
202 // updateForRequest updates the chunked and kalive fields of the decoder to align
203 // with the header values of the request
204 func (d *httpDecoder) updateForRequest(bootstrapping bool) {
205 // check "Transfer-Encoding" for "chunked"
206 d.chunked = false
207 for _, v := range d.req.Header["Transfer-Encoding"] {
208 if v == "chunked" {
209 d.chunked = true
210 break
211 }
212 }
213 if !d.chunked && d.req.ContentLength < 0 {
214 if bootstrapping {
215 // strongly suspect that Go's internal net/http lib is stripping
216 // the Transfer-Encoding header from the initial request, so this
217 // workaround makes a very mesos-specific assumption: an unknown
218 // Content-Length indicates a chunked stream.
219 d.chunked = true
220 } else {
221 // via https://tools.ietf.org/html/rfc7230#section-3.3.2
222 d.req.ContentLength = 0
223 }
224 }
225
226 // check "Connection" for "Keep-Alive"
227 d.kalive = d.req.Header.Get("Connection") == "Keep-Alive"
228
229 log.V(2).Infof(d.idtag+"update-for-request: chunked %v keep-alive %v", d.chunked, d.kalive)
230 }
231
232 func (d *httpDecoder) readBodyContent() httpState {
233 log.V(2).Info(d.idtag + "read-body-content")
234 if d.chunked {
235 d.buf = &bytes.Buffer{}
236 return readChunkHeaderState
237 } else {
238 d.lrc = limit(d.rw.Reader, d.req.ContentLength)
239 d.buf = &bytes.Buffer{}
240 return readBodyState
241 }
242 }
243
244 const http202response = "HTTP/1.1 202 OK\r\nContent-Length: 0\r\n\r\n"
245
246 func (d *httpDecoder) generateRequest() httpState {
247 log.V(2).Infof(d.idtag + "generate-request")
248 // send a Request to msg
249 b := d.buf.Bytes()
250 rch := make(chan Response, 1)
251 r := &Request{
252 Request: &http.Request{
253 Method: d.req.Method,
254 URL: d.req.URL,
255 Proto: d.req.Proto,
256 ProtoMajor: d.req.ProtoMajor,
257 ProtoMinor: d.req.ProtoMinor,
258 Header: d.req.Header,
259 Close: !d.kalive,
260 Host: d.req.Host,
261 RequestURI: d.req.RequestURI,
262 Body: &body{bytes.NewBuffer(b)},
263 ContentLength: int64(len(b)),
264 },
265 response: rch,
266 }
267
268 select {
269 case d.msg <- r:
270 case <-d.forceQuit:
271 return terminateState
272 }
273
274 select {
275 case <-d.forceQuit:
276 return terminateState
277 case resp, ok := <-rch:
278 if ok {
279 // response required, so build it and ship it
280 out := d.buildResponseEntity(&resp)
281 select {
282 case <-d.forceQuit:
283 return terminateState
284 case d.outCh <- out:
285 }
286 }
287 }
288
289 if d.kalive {
290 d.req = &http.Request{
291 ContentLength: -1,
292 Header: make(http.Header),
293 }
294 return awaitRequestState
295 } else {
296 return gracefulTerminateState
297 }
298 }
299
300 func (d *httpDecoder) defaultSendError(err error) {
301 d.errCh <- err
302 }
303
304 type httpState func(d *httpDecoder) httpState
305
306 // terminateState forcefully shuts down the state machine
307 func terminateState(d *httpDecoder) httpState {
308 log.V(2).Infoln(d.idtag + "terminate-state")
309 // closing these chans tells Decoder users that it's wrapping up
310 close(d.msg)
311 close(d.errCh)
312
313 // attempt to forcefully close the connection and signal response handlers that
314 // no further responses should be written
315 d.Cancel(false)
316
317 if d.con != nil {
318 d.con.Close()
319 }
320
321 // there is no spoon
322 return nil
323 }
324
325 func gracefulTerminateState(d *httpDecoder) httpState {
326 log.V(2).Infoln(d.idtag + "gracefully-terminate-state")
327 // closing these chans tells Decoder users that it's wrapping up
328 close(d.msg)
329 close(d.errCh)
330
331 // gracefully terminate the connection; signal that we should flush pending
332 // responses before closing the connection.
333 d.Cancel(true)
334
335 return nil
336 }
337
338 func limit(r *bufio.Reader, limit int64) *io.LimitedReader {
339 return &io.LimitedReader{
340 R: r,
341 N: limit,
342 }
343 }
344
345 // bootstrapState expects to be called when the standard net/http lib has already
346 // read the initial request query line + headers from a connection. the request
347 // is ready to be hijacked at this point.
348 func (d *httpDecoder) bootstrapState(res http.ResponseWriter) httpState {
349 log.V(2).Infoln(d.idtag + "bootstrap-state")
350
351 d.updateForRequest(true)
352
353 // hijack
354 hj, ok := res.(http.Hijacker)
355 if !ok {
356 http.Error(res, "server does not support hijack", http.StatusInternalServerError)
357 d.sendError(errHijackFailed)
358 return terminateState
359 }
360 c, rw, err := hj.Hijack()
361 if err != nil {
362 http.Error(res, "failed to hijack the connection", http.StatusInternalServerError)
363 d.sendError(errHijackFailed)
364 return terminateState
365 }
366
367 d.rw = rw
368 d.con = c
369
370 go d.responseWriter()
371 return d.readBodyContent()
372 }
373
374 func (d *httpDecoder) responseWriter() {
375 defer func() {
376 log.V(3).Infoln(d.idtag + "response-writer: closing connection")
377 d.con.Close()
378 }()
379 for buf := range d.outCh {
380 //TODO(jdef) I worry about this busy-looping
381
382 // write & flush the buffer until there's nothing left in it, or else
383 // we exceed the write/flush period.
384 now := time.Now()
385 for buf.Len() > 0 && time.Since(now) < writeFlushPeriod {
386 select {
387 case <-d.forceQuit:
388 return
389 default:
390 }
391 d.tryFlushResponse(buf)
392 }
393 if buf.Len() > 0 {
394 //TODO(jdef) should we abort the entire connection instead? a partially written
395 // response doesn't do anyone any good. That said, real libprocess agents don't
396 // really care about the response channel anyway - the entire system is fire and
397 // forget. So I've decided to err on the side that we might lose response bytes
398 // in favor of completely reading the connection request stream before we terminate.
399 log.Errorln(d.idtag + "failed to fully flush output buffer within write-flush period")
400 }
401 }
402 }
403
404 type body struct {
405 *bytes.Buffer
406 }
407
408 func (b *body) Close() error { return nil }
409
410 // checkTimeoutOrFail tests whether the given error is related to a timeout condition.
411 // returns true if the caller should advance to the returned state.
412 func (d *httpDecoder) checkTimeoutOrFail(err error, stateContinue httpState) (httpState, bool) {
413 if err != nil {
414 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
415 select {
416 case <-d.forceQuit:
417 return terminateState, true
418 case <-d.shouldQuit:
419 return gracefulTerminateState, true
420 default:
421 return stateContinue, true
422 }
423 }
424 d.sendError(err)
425 return terminateState, true
426 }
427 return nil, false
428 }
429
430 func (d *httpDecoder) setReadTimeoutOrFail() bool {
431 if d.readTimeout > 0 {
432 err := d.con.SetReadDeadline(time.Now().Add(d.readTimeout))
433 if err != nil {
434 d.sendError(err)
435 return false
436 }
437 }
438 return true
439 }
440
441 func (d *httpDecoder) setWriteTimeout() error {
442 if d.writeTimeout > 0 {
443 return d.con.SetWriteDeadline(time.Now().Add(d.writeTimeout))
444 }
445 return nil
446 }
447
448 func readChunkHeaderState(d *httpDecoder) httpState {
449 log.V(2).Infoln(d.idtag + "read-chunk-header-state")
450 tr := textproto.NewReader(d.rw.Reader)
451 if !d.setReadTimeoutOrFail() {
452 return terminateState
453 }
454 hexlen, err := tr.ReadLine()
455 if next, ok := d.checkTimeoutOrFail(err, readChunkHeaderState); ok {
456 return next
457 }
458
459 clen, err := strconv.ParseInt(hexlen, 16, 64)
460 if err != nil {
461 d.sendError(err)
462 return terminateState
463 }
464
465 if clen == 0 {
466 return readEndOfChunkStreamState
467 }
468
469 d.lrc = limit(d.rw.Reader, clen)
470 return readChunkState
471 }
472
473 func readChunkState(d *httpDecoder) httpState {
474 log.V(2).Infoln(d.idtag+"read-chunk-state, bytes remaining:", d.lrc.N)
475 if !d.setReadTimeoutOrFail() {
476 return terminateState
477 }
478 _, err := d.buf.ReadFrom(d.lrc)
479 if next, ok := d.checkTimeoutOrFail(err, readChunkState); ok {
480 return next
481 }
482 return readEndOfChunkState
483 }
484
485 const crlf = "\r\n"
486
487 func readEndOfChunkState(d *httpDecoder) httpState {
488 log.V(2).Infoln(d.idtag + "read-end-of-chunk-state")
489 if !d.setReadTimeoutOrFail() {
490 return terminateState
491 }
492 b, err := d.rw.Reader.Peek(2)
493 if len(b) == 2 {
494 if string(b) == crlf {
495 d.rw.ReadByte()
496 d.rw.ReadByte()
497 return readChunkHeaderState
498 }
499 d.sendError(errors.New(d.idtag + "unexpected data at end-of-chunk marker"))
500 return terminateState
501 }
502 // less than two bytes avail
503 if next, ok := d.checkTimeoutOrFail(err, readEndOfChunkState); ok {
504 return next
505 }
506 panic("couldn't peek 2 bytes, but didn't get an error?!")
507 }
508
509 func readEndOfChunkStreamState(d *httpDecoder) httpState {
510 log.V(2).Infoln(d.idtag + "read-end-of-chunk-stream-state")
511 if !d.setReadTimeoutOrFail() {
512 return terminateState
513 }
514 b, err := d.rw.Reader.Peek(2)
515 if len(b) == 2 {
516 if string(b) == crlf {
517 d.rw.ReadByte()
518 d.rw.ReadByte()
519 return d.generateRequest()
520 }
521 d.sendError(errors.New(d.idtag + "unexpected data at end-of-chunk marker"))
522 return terminateState
523 }
524 // less than 2 bytes avail
525 if next, ok := d.checkTimeoutOrFail(err, readEndOfChunkStreamState); ok {
526 return next
527 }
528 panic("couldn't peek 2 bytes, but didn't get an error?!")
529 }
530
531 func readBodyState(d *httpDecoder) httpState {
532 log.V(2).Infof(d.idtag+"read-body-state: %d bytes remaining", d.lrc.N)
533 // read remaining bytes into the buffer
534 var err error
535 if d.lrc.N > 0 {
536 if !d.setReadTimeoutOrFail() {
537 return terminateState
538 }
539 _, err = d.buf.ReadFrom(d.lrc)
540 }
541 if d.lrc.N <= 0 {
542 return d.generateRequest()
543 }
544 if next, ok := d.checkTimeoutOrFail(err, readBodyState); ok {
545 return next
546 }
547 return readBodyState
548 }
549
550 func isGracefulTermSignal(err error) bool {
551 if err == io.EOF {
552 return true
553 }
554 if operr, ok := err.(*net.OpError); ok {
555 return operr.Op == "read" && err == syscall.ECONNRESET
556 }
557 return false
558 }
559
560 func awaitRequestState(d *httpDecoder) httpState {
561 log.V(2).Infoln(d.idtag + "await-request-state")
562 tr := textproto.NewReader(d.rw.Reader)
563 if !d.setReadTimeoutOrFail() {
564 return terminateState
565 }
566 requestLine, err := tr.ReadLine()
567 if requestLine == "" && isGracefulTermSignal(err) {
568 // we're actually expecting this at some point, so don't react poorly
569 return gracefulTerminateState
570 }
571 if next, ok := d.checkTimeoutOrFail(err, awaitRequestState); ok {
572 return next
573 }
574 ss := strings.SplitN(requestLine, " ", 3)
575 if len(ss) < 3 {
576 if err == io.EOF {
577 return gracefulTerminateState
578 }
579 d.sendError(errors.New(d.idtag + "illegal request line"))
580 return terminateState
581 }
582 r := d.req
583 r.Method = ss[0]
584 r.RequestURI = ss[1]
585 r.URL, err = url.ParseRequestURI(ss[1])
586 if err != nil {
587 d.sendError(err)
588 return terminateState
589 }
590 major, minor, ok := http.ParseHTTPVersion(ss[2])
591 if !ok {
592 d.sendError(errors.New(d.idtag + "malformed HTTP version"))
593 return terminateState
594 }
595 r.ProtoMajor = major
596 r.ProtoMinor = minor
597 r.Proto = ss[2]
598 return readHeaderState
599 }
600
601 func readHeaderState(d *httpDecoder) httpState {
602 log.V(2).Infoln(d.idtag + "read-header-state")
603 if !d.setReadTimeoutOrFail() {
604 return terminateState
605 }
606 r := d.req
607 tr := textproto.NewReader(d.rw.Reader)
608 h, err := tr.ReadMIMEHeader()
609 // merge any headers that were read successfully (before a possible error)
610 for k, v := range h {
611 if rh, exists := r.Header[k]; exists {
612 r.Header[k] = append(rh, v...)
613 } else {
614 r.Header[k] = v
615 }
616 log.V(2).Infoln(d.idtag+"request header", k, v)
617 }
618 if next, ok := d.checkTimeoutOrFail(err, readHeaderState); ok {
619 return next
620 }
621
622 // special headers: Host, Content-Length, Transfer-Encoding
623 r.Host = r.Header.Get("Host")
624 r.TransferEncoding = r.Header["Transfer-Encoding"]
625 if cl := r.Header.Get("Content-Length"); cl != "" {
626 l, err := strconv.ParseInt(cl, 10, 64)
627 if err != nil {
628 d.sendError(err)
629 return terminateState
630 }
631 if l > -1 {
632 r.ContentLength = l
633 log.V(2).Infoln(d.idtag+"set content length", r.ContentLength)
634 }
635 }
636 d.updateForRequest(false)
637 return d.readBodyContent()
638 }