OSDN Git Service

libgo: Update to weekly 2011-11-09.
[pf3gnuchains/gcc-fork.git] / libgo / go / net / http / server.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // HTTP server.  See RFC 2616.
6
7 // TODO(rsc):
8 //      logging
9
10 package http
11
12 import (
13         "bufio"
14         "bytes"
15         "crypto/rand"
16         "crypto/tls"
17         "errors"
18         "fmt"
19         "io"
20         "io/ioutil"
21         "log"
22         "net"
23         "net/url"
24         "path"
25         "runtime/debug"
26         "strconv"
27         "strings"
28         "sync"
29         "time"
30 )
31
32 // Errors introduced by the HTTP server.
33 var (
34         ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
35         ErrBodyNotAllowed  = errors.New("http: response status code does not allow body")
36         ErrHijacked        = errors.New("Conn has been hijacked")
37         ErrContentLength   = errors.New("Conn.Write wrote more than the declared Content-Length")
38 )
39
40 // Objects implementing the Handler interface can be
41 // registered to serve a particular path or subtree
42 // in the HTTP server.
43 //
44 // ServeHTTP should write reply headers and data to the ResponseWriter
45 // and then return.  Returning signals that the request is finished
46 // and that the HTTP server can move on to the next request on
47 // the connection.
48 type Handler interface {
49         ServeHTTP(ResponseWriter, *Request)
50 }
51
52 // A ResponseWriter interface is used by an HTTP handler to
53 // construct an HTTP response.
54 type ResponseWriter interface {
55         // Header returns the header map that will be sent by WriteHeader.
56         // Changing the header after a call to WriteHeader (or Write) has
57         // no effect.
58         Header() Header
59
60         // Write writes the data to the connection as part of an HTTP reply.
61         // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
62         // before writing the data.
63         Write([]byte) (int, error)
64
65         // WriteHeader sends an HTTP response header with status code.
66         // If WriteHeader is not called explicitly, the first call to Write
67         // will trigger an implicit WriteHeader(http.StatusOK).
68         // Thus explicit calls to WriteHeader are mainly used to
69         // send error codes.
70         WriteHeader(int)
71 }
72
73 // The Flusher interface is implemented by ResponseWriters that allow
74 // an HTTP handler to flush buffered data to the client.
75 //
76 // Note that even for ResponseWriters that support Flush,
77 // if the client is connected through an HTTP proxy,
78 // the buffered data may not reach the client until the response
79 // completes.
80 type Flusher interface {
81         // Flush sends any buffered data to the client.
82         Flush()
83 }
84
85 // The Hijacker interface is implemented by ResponseWriters that allow
86 // an HTTP handler to take over the connection.
87 type Hijacker interface {
88         // Hijack lets the caller take over the connection.
89         // After a call to Hijack(), the HTTP server library
90         // will not do anything else with the connection.
91         // It becomes the caller's responsibility to manage
92         // and close the connection.
93         Hijack() (net.Conn, *bufio.ReadWriter, error)
94 }
95
96 // A conn represents the server side of an HTTP connection.
97 type conn struct {
98         remoteAddr string               // network address of remote side
99         server     *Server              // the Server on which the connection arrived
100         rwc        net.Conn             // i/o connection
101         lr         *io.LimitedReader    // io.LimitReader(rwc)
102         buf        *bufio.ReadWriter    // buffered(lr,rwc), reading from bufio->limitReader->rwc
103         hijacked   bool                 // connection has been hijacked by handler
104         tlsState   *tls.ConnectionState // or nil when not using TLS
105         body       []byte
106 }
107
108 // A response represents the server side of an HTTP response.
109 type response struct {
110         conn          *conn
111         req           *Request // request for this response
112         chunking      bool     // using chunked transfer encoding for reply body
113         wroteHeader   bool     // reply header has been written
114         wroteContinue bool     // 100 Continue response was written
115         header        Header   // reply header parameters
116         written       int64    // number of bytes written in body
117         contentLength int64    // explicitly-declared Content-Length; or -1
118         status        int      // status code passed to WriteHeader
119         needSniff     bool     // need to sniff to find Content-Type
120
121         // close connection after this reply.  set on request and
122         // updated after response from handler if there's a
123         // "Connection: keep-alive" response header and a
124         // Content-Length.
125         closeAfterReply bool
126
127         // requestBodyLimitHit is set by requestTooLarge when
128         // maxBytesReader hits its max size. It is checked in
129         // WriteHeader, to make sure we don't consume the the
130         // remaining request body to try to advance to the next HTTP
131         // request. Instead, when this is set, we stop doing
132         // subsequent requests on this connection and stop reading
133         // input from it.
134         requestBodyLimitHit bool
135 }
136
137 // requestTooLarge is called by maxBytesReader when too much input has
138 // been read from the client.
139 func (w *response) requestTooLarge() {
140         w.closeAfterReply = true
141         w.requestBodyLimitHit = true
142         if !w.wroteHeader {
143                 w.Header().Set("Connection", "close")
144         }
145 }
146
147 type writerOnly struct {
148         io.Writer
149 }
150
151 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
152         // Flush before checking w.chunking, as Flush will call
153         // WriteHeader if it hasn't been called yet, and WriteHeader
154         // is what sets w.chunking.
155         w.Flush()
156         if !w.chunking && w.bodyAllowed() && !w.needSniff {
157                 if rf, ok := w.conn.rwc.(io.ReaderFrom); ok {
158                         n, err = rf.ReadFrom(src)
159                         w.written += n
160                         return
161                 }
162         }
163         // Fall back to default io.Copy implementation.
164         // Use wrapper to hide w.ReadFrom from io.Copy.
165         return io.Copy(writerOnly{w}, src)
166 }
167
168 // noLimit is an effective infinite upper bound for io.LimitedReader
169 const noLimit int64 = (1 << 63) - 1
170
171 // Create new connection from rwc.
172 func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
173         c = new(conn)
174         c.remoteAddr = rwc.RemoteAddr().String()
175         c.server = srv
176         c.rwc = rwc
177         c.body = make([]byte, sniffLen)
178         c.lr = io.LimitReader(rwc, noLimit).(*io.LimitedReader)
179         br := bufio.NewReader(c.lr)
180         bw := bufio.NewWriter(rwc)
181         c.buf = bufio.NewReadWriter(br, bw)
182         return c, nil
183 }
184
185 // DefaultMaxHeaderBytes is the maximum permitted size of the headers
186 // in an HTTP request.
187 // This can be overridden by setting Server.MaxHeaderBytes.
188 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
189
190 func (srv *Server) maxHeaderBytes() int {
191         if srv.MaxHeaderBytes > 0 {
192                 return srv.MaxHeaderBytes
193         }
194         return DefaultMaxHeaderBytes
195 }
196
197 // wrapper around io.ReaderCloser which on first read, sends an
198 // HTTP/1.1 100 Continue header
199 type expectContinueReader struct {
200         resp       *response
201         readCloser io.ReadCloser
202         closed     bool
203 }
204
205 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
206         if ecr.closed {
207                 return 0, errors.New("http: Read after Close on request Body")
208         }
209         if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked {
210                 ecr.resp.wroteContinue = true
211                 io.WriteString(ecr.resp.conn.buf, "HTTP/1.1 100 Continue\r\n\r\n")
212                 ecr.resp.conn.buf.Flush()
213         }
214         return ecr.readCloser.Read(p)
215 }
216
217 func (ecr *expectContinueReader) Close() error {
218         ecr.closed = true
219         return ecr.readCloser.Close()
220 }
221
222 // TimeFormat is the time format to use with
223 // time.Parse and time.Time.Format when parsing
224 // or generating times in HTTP headers.
225 // It is like time.RFC1123 but hard codes GMT as the time zone.
226 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
227
228 var errTooLarge = errors.New("http: request too large")
229
230 // Read next request from connection.
231 func (c *conn) readRequest() (w *response, err error) {
232         if c.hijacked {
233                 return nil, ErrHijacked
234         }
235         c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
236         var req *Request
237         if req, err = ReadRequest(c.buf.Reader); err != nil {
238                 if c.lr.N == 0 {
239                         return nil, errTooLarge
240                 }
241                 return nil, err
242         }
243         c.lr.N = noLimit
244
245         req.RemoteAddr = c.remoteAddr
246         req.TLS = c.tlsState
247
248         w = new(response)
249         w.conn = c
250         w.req = req
251         w.header = make(Header)
252         w.contentLength = -1
253         c.body = c.body[:0]
254         return w, nil
255 }
256
257 func (w *response) Header() Header {
258         return w.header
259 }
260
261 // maxPostHandlerReadBytes is the max number of Request.Body bytes not
262 // consumed by a handler that the server will read from the a client
263 // in order to keep a connection alive.  If there are more bytes than
264 // this then the server to be paranoid instead sends a "Connection:
265 // close" response.
266 //
267 // This number is approximately what a typical machine's TCP buffer
268 // size is anyway.  (if we have the bytes on the machine, we might as
269 // well read them)
270 const maxPostHandlerReadBytes = 256 << 10
271
272 func (w *response) WriteHeader(code int) {
273         if w.conn.hijacked {
274                 log.Print("http: response.WriteHeader on hijacked connection")
275                 return
276         }
277         if w.wroteHeader {
278                 log.Print("http: multiple response.WriteHeader calls")
279                 return
280         }
281         w.wroteHeader = true
282         w.status = code
283
284         // Check for a explicit (and valid) Content-Length header.
285         var hasCL bool
286         var contentLength int64
287         if clenStr := w.header.Get("Content-Length"); clenStr != "" {
288                 var err error
289                 contentLength, err = strconv.Atoi64(clenStr)
290                 if err == nil {
291                         hasCL = true
292                 } else {
293                         log.Printf("http: invalid Content-Length of %q sent", clenStr)
294                         w.header.Del("Content-Length")
295                 }
296         }
297
298         if w.req.wantsHttp10KeepAlive() && (w.req.Method == "HEAD" || hasCL) {
299                 _, connectionHeaderSet := w.header["Connection"]
300                 if !connectionHeaderSet {
301                         w.header.Set("Connection", "keep-alive")
302                 }
303         } else if !w.req.ProtoAtLeast(1, 1) {
304                 // Client did not ask to keep connection alive.
305                 w.closeAfterReply = true
306         }
307
308         if w.header.Get("Connection") == "close" {
309                 w.closeAfterReply = true
310         }
311
312         // Per RFC 2616, we should consume the request body before
313         // replying, if the handler hasn't already done so.  But we
314         // don't want to do an unbounded amount of reading here for
315         // DoS reasons, so we only try up to a threshold.
316         if w.req.ContentLength != 0 && !w.closeAfterReply {
317                 ecr, isExpecter := w.req.Body.(*expectContinueReader)
318                 if !isExpecter || ecr.resp.wroteContinue {
319                         n, _ := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1)
320                         if n >= maxPostHandlerReadBytes {
321                                 w.requestTooLarge()
322                                 w.header.Set("Connection", "close")
323                         } else {
324                                 w.req.Body.Close()
325                         }
326                 }
327         }
328
329         if code == StatusNotModified {
330                 // Must not have body.
331                 for _, header := range []string{"Content-Type", "Content-Length", "Transfer-Encoding"} {
332                         if w.header.Get(header) != "" {
333                                 // TODO: return an error if WriteHeader gets a return parameter
334                                 // or set a flag on w to make future Writes() write an error page?
335                                 // for now just log and drop the header.
336                                 log.Printf("http: StatusNotModified response with header %q defined", header)
337                                 w.header.Del(header)
338                         }
339                 }
340         } else {
341                 // If no content type, apply sniffing algorithm to body.
342                 if w.header.Get("Content-Type") == "" {
343                         w.needSniff = true
344                 }
345         }
346
347         if _, ok := w.header["Date"]; !ok {
348                 w.Header().Set("Date", time.UTC().Format(TimeFormat))
349         }
350
351         te := w.header.Get("Transfer-Encoding")
352         hasTE := te != ""
353         if hasCL && hasTE && te != "identity" {
354                 // TODO: return an error if WriteHeader gets a return parameter
355                 // For now just ignore the Content-Length.
356                 log.Printf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
357                         te, contentLength)
358                 w.header.Del("Content-Length")
359                 hasCL = false
360         }
361
362         if w.req.Method == "HEAD" || code == StatusNotModified {
363                 // do nothing
364         } else if hasCL {
365                 w.contentLength = contentLength
366                 w.header.Del("Transfer-Encoding")
367         } else if w.req.ProtoAtLeast(1, 1) {
368                 // HTTP/1.1 or greater: use chunked transfer encoding
369                 // to avoid closing the connection at EOF.
370                 // TODO: this blows away any custom or stacked Transfer-Encoding they
371                 // might have set.  Deal with that as need arises once we have a valid
372                 // use case.
373                 w.chunking = true
374                 w.header.Set("Transfer-Encoding", "chunked")
375         } else {
376                 // HTTP version < 1.1: cannot do chunked transfer
377                 // encoding and we don't know the Content-Length so
378                 // signal EOF by closing connection.
379                 w.closeAfterReply = true
380                 w.header.Del("Transfer-Encoding") // in case already set
381         }
382
383         // Cannot use Content-Length with non-identity Transfer-Encoding.
384         if w.chunking {
385                 w.header.Del("Content-Length")
386         }
387         if !w.req.ProtoAtLeast(1, 0) {
388                 return
389         }
390         proto := "HTTP/1.0"
391         if w.req.ProtoAtLeast(1, 1) {
392                 proto = "HTTP/1.1"
393         }
394         codestring := strconv.Itoa(code)
395         text, ok := statusText[code]
396         if !ok {
397                 text = "status code " + codestring
398         }
399         io.WriteString(w.conn.buf, proto+" "+codestring+" "+text+"\r\n")
400         w.header.Write(w.conn.buf)
401
402         // If we need to sniff the body, leave the header open.
403         // Otherwise, end it here.
404         if !w.needSniff {
405                 io.WriteString(w.conn.buf, "\r\n")
406         }
407 }
408
409 // sniff uses the first block of written data,
410 // stored in w.conn.body, to decide the Content-Type
411 // for the HTTP body.
412 func (w *response) sniff() {
413         if !w.needSniff {
414                 return
415         }
416         w.needSniff = false
417
418         data := w.conn.body
419         fmt.Fprintf(w.conn.buf, "Content-Type: %s\r\n\r\n", DetectContentType(data))
420
421         if len(data) == 0 {
422                 return
423         }
424         if w.chunking {
425                 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data))
426         }
427         _, err := w.conn.buf.Write(data)
428         if w.chunking && err == nil {
429                 io.WriteString(w.conn.buf, "\r\n")
430         }
431 }
432
433 // bodyAllowed returns true if a Write is allowed for this response type.
434 // It's illegal to call this before the header has been flushed.
435 func (w *response) bodyAllowed() bool {
436         if !w.wroteHeader {
437                 panic("")
438         }
439         return w.status != StatusNotModified && w.req.Method != "HEAD"
440 }
441
442 func (w *response) Write(data []byte) (n int, err error) {
443         if w.conn.hijacked {
444                 log.Print("http: response.Write on hijacked connection")
445                 return 0, ErrHijacked
446         }
447         if !w.wroteHeader {
448                 w.WriteHeader(StatusOK)
449         }
450         if len(data) == 0 {
451                 return 0, nil
452         }
453         if !w.bodyAllowed() {
454                 return 0, ErrBodyNotAllowed
455         }
456
457         w.written += int64(len(data)) // ignoring errors, for errorKludge
458         if w.contentLength != -1 && w.written > w.contentLength {
459                 return 0, ErrContentLength
460         }
461
462         var m int
463         if w.needSniff {
464                 // We need to sniff the beginning of the output to
465                 // determine the content type.  Accumulate the
466                 // initial writes in w.conn.body.
467                 // Cap m so that append won't allocate.
468                 m := cap(w.conn.body) - len(w.conn.body)
469                 if m > len(data) {
470                         m = len(data)
471                 }
472                 w.conn.body = append(w.conn.body, data[:m]...)
473                 data = data[m:]
474                 if len(data) == 0 {
475                         // Copied everything into the buffer.
476                         // Wait for next write.
477                         return m, nil
478                 }
479
480                 // Filled the buffer; more data remains.
481                 // Sniff the content (flushes the buffer)
482                 // and then proceed with the remainder
483                 // of the data as a normal Write.
484                 // Calling sniff clears needSniff.
485                 w.sniff()
486         }
487
488         // TODO(rsc): if chunking happened after the buffering,
489         // then there would be fewer chunk headers.
490         // On the other hand, it would make hijacking more difficult.
491         if w.chunking {
492                 fmt.Fprintf(w.conn.buf, "%x\r\n", len(data)) // TODO(rsc): use strconv not fmt
493         }
494         n, err = w.conn.buf.Write(data)
495         if err == nil && w.chunking {
496                 if n != len(data) {
497                         err = io.ErrShortWrite
498                 }
499                 if err == nil {
500                         io.WriteString(w.conn.buf, "\r\n")
501                 }
502         }
503
504         return m + n, err
505 }
506
507 func (w *response) finishRequest() {
508         // If this was an HTTP/1.0 request with keep-alive and we sent a Content-Length
509         // back, we can make this a keep-alive response ...
510         if w.req.wantsHttp10KeepAlive() {
511                 sentLength := w.header.Get("Content-Length") != ""
512                 if sentLength && w.header.Get("Connection") == "keep-alive" {
513                         w.closeAfterReply = false
514                 }
515         }
516         if !w.wroteHeader {
517                 w.WriteHeader(StatusOK)
518         }
519         if w.needSniff {
520                 w.sniff()
521         }
522         if w.chunking {
523                 io.WriteString(w.conn.buf, "0\r\n")
524                 // trailer key/value pairs, followed by blank line
525                 io.WriteString(w.conn.buf, "\r\n")
526         }
527         w.conn.buf.Flush()
528         // Close the body, unless we're about to close the whole TCP connection
529         // anyway.
530         if !w.closeAfterReply {
531                 w.req.Body.Close()
532         }
533         if w.req.MultipartForm != nil {
534                 w.req.MultipartForm.RemoveAll()
535         }
536
537         if w.contentLength != -1 && w.contentLength != w.written {
538                 // Did not write enough. Avoid getting out of sync.
539                 w.closeAfterReply = true
540         }
541 }
542
543 func (w *response) Flush() {
544         if !w.wroteHeader {
545                 w.WriteHeader(StatusOK)
546         }
547         w.sniff()
548         w.conn.buf.Flush()
549 }
550
551 // Close the connection.
552 func (c *conn) close() {
553         if c.buf != nil {
554                 c.buf.Flush()
555                 c.buf = nil
556         }
557         if c.rwc != nil {
558                 c.rwc.Close()
559                 c.rwc = nil
560         }
561 }
562
563 // Serve a new connection.
564 func (c *conn) serve() {
565         defer func() {
566                 err := recover()
567                 if err == nil {
568                         return
569                 }
570                 if c.rwc != nil { // may be nil if connection hijacked
571                         c.rwc.Close()
572                 }
573
574                 var buf bytes.Buffer
575                 fmt.Fprintf(&buf, "http: panic serving %v: %v\n", c.remoteAddr, err)
576                 buf.Write(debug.Stack())
577                 log.Print(buf.String())
578         }()
579
580         if tlsConn, ok := c.rwc.(*tls.Conn); ok {
581                 if err := tlsConn.Handshake(); err != nil {
582                         c.close()
583                         return
584                 }
585                 c.tlsState = new(tls.ConnectionState)
586                 *c.tlsState = tlsConn.ConnectionState()
587         }
588
589         for {
590                 w, err := c.readRequest()
591                 if err != nil {
592                         msg := "400 Bad Request"
593                         if err == errTooLarge {
594                                 // Their HTTP client may or may not be
595                                 // able to read this if we're
596                                 // responding to them and hanging up
597                                 // while they're still writing their
598                                 // request.  Undefined behavior.
599                                 msg = "413 Request Entity Too Large"
600                         } else if err == io.ErrUnexpectedEOF {
601                                 break // Don't reply
602                         } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
603                                 break // Don't reply
604                         }
605                         fmt.Fprintf(c.rwc, "HTTP/1.1 %s\r\n\r\n", msg)
606                         break
607                 }
608
609                 // Expect 100 Continue support
610                 req := w.req
611                 if req.expectsContinue() {
612                         if req.ProtoAtLeast(1, 1) {
613                                 // Wrap the Body reader with one that replies on the connection
614                                 req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
615                         }
616                         if req.ContentLength == 0 {
617                                 w.Header().Set("Connection", "close")
618                                 w.WriteHeader(StatusBadRequest)
619                                 w.finishRequest()
620                                 break
621                         }
622                         req.Header.Del("Expect")
623                 } else if req.Header.Get("Expect") != "" {
624                         // TODO(bradfitz): let ServeHTTP handlers handle
625                         // requests with non-standard expectation[s]? Seems
626                         // theoretical at best, and doesn't fit into the
627                         // current ServeHTTP model anyway.  We'd need to
628                         // make the ResponseWriter an optional
629                         // "ExpectReplier" interface or something.
630                         //
631                         // For now we'll just obey RFC 2616 14.20 which says
632                         // "If a server receives a request containing an
633                         // Expect field that includes an expectation-
634                         // extension that it does not support, it MUST
635                         // respond with a 417 (Expectation Failed) status."
636                         w.Header().Set("Connection", "close")
637                         w.WriteHeader(StatusExpectationFailed)
638                         w.finishRequest()
639                         break
640                 }
641
642                 handler := c.server.Handler
643                 if handler == nil {
644                         handler = DefaultServeMux
645                 }
646
647                 // HTTP cannot have multiple simultaneous active requests.[*]
648                 // Until the server replies to this request, it can't read another,
649                 // so we might as well run the handler in this goroutine.
650                 // [*] Not strictly true: HTTP pipelining.  We could let them all process
651                 // in parallel even if their responses need to be serialized.
652                 handler.ServeHTTP(w, w.req)
653                 if c.hijacked {
654                         return
655                 }
656                 w.finishRequest()
657                 if w.closeAfterReply {
658                         break
659                 }
660         }
661         c.close()
662 }
663
664 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
665 // and a Hijacker.
666 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
667         if w.conn.hijacked {
668                 return nil, nil, ErrHijacked
669         }
670         w.conn.hijacked = true
671         rwc = w.conn.rwc
672         buf = w.conn.buf
673         w.conn.rwc = nil
674         w.conn.buf = nil
675         return
676 }
677
678 // The HandlerFunc type is an adapter to allow the use of
679 // ordinary functions as HTTP handlers.  If f is a function
680 // with the appropriate signature, HandlerFunc(f) is a
681 // Handler object that calls f.
682 type HandlerFunc func(ResponseWriter, *Request)
683
684 // ServeHTTP calls f(w, r).
685 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
686         f(w, r)
687 }
688
689 // Helper handlers
690
691 // Error replies to the request with the specified error message and HTTP code.
692 func Error(w ResponseWriter, error string, code int) {
693         w.Header().Set("Content-Type", "text/plain; charset=utf-8")
694         w.WriteHeader(code)
695         fmt.Fprintln(w, error)
696 }
697
698 // NotFound replies to the request with an HTTP 404 not found error.
699 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
700
701 // NotFoundHandler returns a simple request handler
702 // that replies to each request with a ``404 page not found'' reply.
703 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
704
705 // StripPrefix returns a handler that serves HTTP requests
706 // by removing the given prefix from the request URL's Path
707 // and invoking the handler h. StripPrefix handles a
708 // request for a path that doesn't begin with prefix by
709 // replying with an HTTP 404 not found error.
710 func StripPrefix(prefix string, h Handler) Handler {
711         return HandlerFunc(func(w ResponseWriter, r *Request) {
712                 if !strings.HasPrefix(r.URL.Path, prefix) {
713                         NotFound(w, r)
714                         return
715                 }
716                 r.URL.Path = r.URL.Path[len(prefix):]
717                 h.ServeHTTP(w, r)
718         })
719 }
720
721 // Redirect replies to the request with a redirect to url,
722 // which may be a path relative to the request path.
723 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
724         if u, err := url.Parse(urlStr); err == nil {
725                 // If url was relative, make absolute by
726                 // combining with request path.
727                 // The browser would probably do this for us,
728                 // but doing it ourselves is more reliable.
729
730                 // NOTE(rsc): RFC 2616 says that the Location
731                 // line must be an absolute URI, like
732                 // "http://www.google.com/redirect/",
733                 // not a path like "/redirect/".
734                 // Unfortunately, we don't know what to
735                 // put in the host name section to get the
736                 // client to connect to us again, so we can't
737                 // know the right absolute URI to send back.
738                 // Because of this problem, no one pays attention
739                 // to the RFC; they all send back just a new path.
740                 // So do we.
741                 oldpath := r.URL.Path
742                 if oldpath == "" { // should not happen, but avoid a crash if it does
743                         oldpath = "/"
744                 }
745                 if u.Scheme == "" {
746                         // no leading http://server
747                         if urlStr == "" || urlStr[0] != '/' {
748                                 // make relative path absolute
749                                 olddir, _ := path.Split(oldpath)
750                                 urlStr = olddir + urlStr
751                         }
752
753                         var query string
754                         if i := strings.Index(urlStr, "?"); i != -1 {
755                                 urlStr, query = urlStr[:i], urlStr[i:]
756                         }
757
758                         // clean up but preserve trailing slash
759                         trailing := urlStr[len(urlStr)-1] == '/'
760                         urlStr = path.Clean(urlStr)
761                         if trailing && urlStr[len(urlStr)-1] != '/' {
762                                 urlStr += "/"
763                         }
764                         urlStr += query
765                 }
766         }
767
768         w.Header().Set("Location", urlStr)
769         w.WriteHeader(code)
770
771         // RFC2616 recommends that a short note "SHOULD" be included in the
772         // response because older user agents may not understand 301/307.
773         // Shouldn't send the response for POST or HEAD; that leaves GET.
774         if r.Method == "GET" {
775                 note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
776                 fmt.Fprintln(w, note)
777         }
778 }
779
780 var htmlReplacer = strings.NewReplacer(
781         "&", "&amp;",
782         "<", "&lt;",
783         ">", "&gt;",
784         `"`, "&quot;",
785         "'", "&apos;",
786 )
787
788 func htmlEscape(s string) string {
789         return htmlReplacer.Replace(s)
790 }
791
792 // Redirect to a fixed URL
793 type redirectHandler struct {
794         url  string
795         code int
796 }
797
798 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
799         Redirect(w, r, rh.url, rh.code)
800 }
801
802 // RedirectHandler returns a request handler that redirects
803 // each request it receives to the given url using the given
804 // status code.
805 func RedirectHandler(url string, code int) Handler {
806         return &redirectHandler{url, code}
807 }
808
809 // ServeMux is an HTTP request multiplexer.
810 // It matches the URL of each incoming request against a list of registered
811 // patterns and calls the handler for the pattern that
812 // most closely matches the URL.
813 //
814 // Patterns named fixed, rooted paths, like "/favicon.ico",
815 // or rooted subtrees, like "/images/" (note the trailing slash).
816 // Longer patterns take precedence over shorter ones, so that
817 // if there are handlers registered for both "/images/"
818 // and "/images/thumbnails/", the latter handler will be
819 // called for paths beginning "/images/thumbnails/" and the
820 // former will receiver requests for any other paths in the
821 // "/images/" subtree.
822 //
823 // Patterns may optionally begin with a host name, restricting matches to
824 // URLs on that host only.  Host-specific patterns take precedence over
825 // general patterns, so that a handler might register for the two patterns
826 // "/codesearch" and "codesearch.google.com/" without also taking over
827 // requests for "http://www.google.com/".
828 //
829 // ServeMux also takes care of sanitizing the URL request path,
830 // redirecting any request containing . or .. elements to an
831 // equivalent .- and ..-free URL.
832 type ServeMux struct {
833         m map[string]Handler
834 }
835
836 // NewServeMux allocates and returns a new ServeMux.
837 func NewServeMux() *ServeMux { return &ServeMux{make(map[string]Handler)} }
838
839 // DefaultServeMux is the default ServeMux used by Serve.
840 var DefaultServeMux = NewServeMux()
841
842 // Does path match pattern?
843 func pathMatch(pattern, path string) bool {
844         if len(pattern) == 0 {
845                 // should not happen
846                 return false
847         }
848         n := len(pattern)
849         if pattern[n-1] != '/' {
850                 return pattern == path
851         }
852         return len(path) >= n && path[0:n] == pattern
853 }
854
855 // Return the canonical path for p, eliminating . and .. elements.
856 func cleanPath(p string) string {
857         if p == "" {
858                 return "/"
859         }
860         if p[0] != '/' {
861                 p = "/" + p
862         }
863         np := path.Clean(p)
864         // path.Clean removes trailing slash except for root;
865         // put the trailing slash back if necessary.
866         if p[len(p)-1] == '/' && np != "/" {
867                 np += "/"
868         }
869         return np
870 }
871
872 // Find a handler on a handler map given a path string
873 // Most-specific (longest) pattern wins
874 func (mux *ServeMux) match(path string) Handler {
875         var h Handler
876         var n = 0
877         for k, v := range mux.m {
878                 if !pathMatch(k, path) {
879                         continue
880                 }
881                 if h == nil || len(k) > n {
882                         n = len(k)
883                         h = v
884                 }
885         }
886         return h
887 }
888
889 // ServeHTTP dispatches the request to the handler whose
890 // pattern most closely matches the request URL.
891 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
892         // Clean path to canonical form and redirect.
893         if p := cleanPath(r.URL.Path); p != r.URL.Path {
894                 w.Header().Set("Location", p)
895                 w.WriteHeader(StatusMovedPermanently)
896                 return
897         }
898         // Host-specific pattern takes precedence over generic ones
899         h := mux.match(r.Host + r.URL.Path)
900         if h == nil {
901                 h = mux.match(r.URL.Path)
902         }
903         if h == nil {
904                 h = NotFoundHandler()
905         }
906         h.ServeHTTP(w, r)
907 }
908
909 // Handle registers the handler for the given pattern.
910 func (mux *ServeMux) Handle(pattern string, handler Handler) {
911         if pattern == "" {
912                 panic("http: invalid pattern " + pattern)
913         }
914
915         mux.m[pattern] = handler
916
917         // Helpful behavior:
918         // If pattern is /tree/, insert permanent redirect for /tree.
919         n := len(pattern)
920         if n > 0 && pattern[n-1] == '/' {
921                 mux.m[pattern[0:n-1]] = RedirectHandler(pattern, StatusMovedPermanently)
922         }
923 }
924
925 // HandleFunc registers the handler function for the given pattern.
926 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
927         mux.Handle(pattern, HandlerFunc(handler))
928 }
929
930 // Handle registers the handler for the given pattern
931 // in the DefaultServeMux.
932 // The documentation for ServeMux explains how patterns are matched.
933 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
934
935 // HandleFunc registers the handler function for the given pattern
936 // in the DefaultServeMux.
937 // The documentation for ServeMux explains how patterns are matched.
938 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
939         DefaultServeMux.HandleFunc(pattern, handler)
940 }
941
942 // Serve accepts incoming HTTP connections on the listener l,
943 // creating a new service thread for each.  The service threads
944 // read requests and then call handler to reply to them.
945 // Handler is typically nil, in which case the DefaultServeMux is used.
946 func Serve(l net.Listener, handler Handler) error {
947         srv := &Server{Handler: handler}
948         return srv.Serve(l)
949 }
950
951 // A Server defines parameters for running an HTTP server.
952 type Server struct {
953         Addr           string  // TCP address to listen on, ":http" if empty
954         Handler        Handler // handler to invoke, http.DefaultServeMux if nil
955         ReadTimeout    int64   // the net.Conn.SetReadTimeout value for new connections
956         WriteTimeout   int64   // the net.Conn.SetWriteTimeout value for new connections
957         MaxHeaderBytes int     // maximum size of request headers, DefaultMaxHeaderBytes if 0
958 }
959
960 // ListenAndServe listens on the TCP network address srv.Addr and then
961 // calls Serve to handle requests on incoming connections.  If
962 // srv.Addr is blank, ":http" is used.
963 func (srv *Server) ListenAndServe() error {
964         addr := srv.Addr
965         if addr == "" {
966                 addr = ":http"
967         }
968         l, e := net.Listen("tcp", addr)
969         if e != nil {
970                 return e
971         }
972         return srv.Serve(l)
973 }
974
975 // Serve accepts incoming connections on the Listener l, creating a
976 // new service thread for each.  The service threads read requests and
977 // then call srv.Handler to reply to them.
978 func (srv *Server) Serve(l net.Listener) error {
979         defer l.Close()
980         for {
981                 rw, e := l.Accept()
982                 if e != nil {
983                         if ne, ok := e.(net.Error); ok && ne.Temporary() {
984                                 log.Printf("http: Accept error: %v", e)
985                                 continue
986                         }
987                         return e
988                 }
989                 if srv.ReadTimeout != 0 {
990                         rw.SetReadTimeout(srv.ReadTimeout)
991                 }
992                 if srv.WriteTimeout != 0 {
993                         rw.SetWriteTimeout(srv.WriteTimeout)
994                 }
995                 c, err := srv.newConn(rw)
996                 if err != nil {
997                         continue
998                 }
999                 go c.serve()
1000         }
1001         panic("not reached")
1002 }
1003
1004 // ListenAndServe listens on the TCP network address addr
1005 // and then calls Serve with handler to handle requests
1006 // on incoming connections.  Handler is typically nil,
1007 // in which case the DefaultServeMux is used.
1008 //
1009 // A trivial example server is:
1010 //
1011 //      package main
1012 //
1013 //      import (
1014 //              "http"
1015 //              "io"
1016 //              "log"
1017 //      )
1018 //
1019 //      // hello world, the web server
1020 //      func HelloServer(w http.ResponseWriter, req *http.Request) {
1021 //              io.WriteString(w, "hello, world!\n")
1022 //      }
1023 //
1024 //      func main() {
1025 //              http.HandleFunc("/hello", HelloServer)
1026 //              err := http.ListenAndServe(":12345", nil)
1027 //              if err != nil {
1028 //                      log.Fatal("ListenAndServe: ", err.String())
1029 //              }
1030 //      }
1031 func ListenAndServe(addr string, handler Handler) error {
1032         server := &Server{Addr: addr, Handler: handler}
1033         return server.ListenAndServe()
1034 }
1035
1036 // ListenAndServeTLS acts identically to ListenAndServe, except that it
1037 // expects HTTPS connections. Additionally, files containing a certificate and
1038 // matching private key for the server must be provided. If the certificate
1039 // is signed by a certificate authority, the certFile should be the concatenation
1040 // of the server's certificate followed by the CA's certificate.
1041 //
1042 // A trivial example server is:
1043 //
1044 //      import (
1045 //              "http"
1046 //              "log"
1047 //      )
1048 //
1049 //      func handler(w http.ResponseWriter, req *http.Request) {
1050 //              w.Header().Set("Content-Type", "text/plain")
1051 //              w.Write([]byte("This is an example server.\n"))
1052 //      }
1053 //
1054 //      func main() {
1055 //              http.HandleFunc("/", handler)
1056 //              log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
1057 //              err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
1058 //              if err != nil {
1059 //                      log.Fatal(err)
1060 //              }
1061 //      }
1062 //
1063 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
1064 func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
1065         server := &Server{Addr: addr, Handler: handler}
1066         return server.ListenAndServeTLS(certFile, keyFile)
1067 }
1068
1069 // ListenAndServeTLS listens on the TCP network address srv.Addr and
1070 // then calls Serve to handle requests on incoming TLS connections.
1071 //
1072 // Filenames containing a certificate and matching private key for
1073 // the server must be provided. If the certificate is signed by a
1074 // certificate authority, the certFile should be the concatenation
1075 // of the server's certificate followed by the CA's certificate.
1076 //
1077 // If srv.Addr is blank, ":https" is used.
1078 func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
1079         addr := s.Addr
1080         if addr == "" {
1081                 addr = ":https"
1082         }
1083         config := &tls.Config{
1084                 Rand:       rand.Reader,
1085                 Time:       time.Seconds,
1086                 NextProtos: []string{"http/1.1"},
1087         }
1088
1089         var err error
1090         config.Certificates = make([]tls.Certificate, 1)
1091         config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
1092         if err != nil {
1093                 return err
1094         }
1095
1096         conn, err := net.Listen("tcp", addr)
1097         if err != nil {
1098                 return err
1099         }
1100
1101         tlsListener := tls.NewListener(conn, config)
1102         return s.Serve(tlsListener)
1103 }
1104
1105 // TimeoutHandler returns a Handler that runs h with the given time limit.
1106 //
1107 // The new Handler calls h.ServeHTTP to handle each request, but if a
1108 // call runs for more than ns nanoseconds, the handler responds with
1109 // a 503 Service Unavailable error and the given message in its body.
1110 // (If msg is empty, a suitable default message will be sent.)
1111 // After such a timeout, writes by h to its ResponseWriter will return
1112 // ErrHandlerTimeout.
1113 func TimeoutHandler(h Handler, ns int64, msg string) Handler {
1114         f := func() <-chan int64 {
1115                 return time.After(ns)
1116         }
1117         return &timeoutHandler{h, f, msg}
1118 }
1119
1120 // ErrHandlerTimeout is returned on ResponseWriter Write calls
1121 // in handlers which have timed out.
1122 var ErrHandlerTimeout = errors.New("http: Handler timeout")
1123
1124 type timeoutHandler struct {
1125         handler Handler
1126         timeout func() <-chan int64 // returns channel producing a timeout
1127         body    string
1128 }
1129
1130 func (h *timeoutHandler) errorBody() string {
1131         if h.body != "" {
1132                 return h.body
1133         }
1134         return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
1135 }
1136
1137 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
1138         done := make(chan bool)
1139         tw := &timeoutWriter{w: w}
1140         go func() {
1141                 h.handler.ServeHTTP(tw, r)
1142                 done <- true
1143         }()
1144         select {
1145         case <-done:
1146                 return
1147         case <-h.timeout():
1148                 tw.mu.Lock()
1149                 defer tw.mu.Unlock()
1150                 if !tw.wroteHeader {
1151                         tw.w.WriteHeader(StatusServiceUnavailable)
1152                         tw.w.Write([]byte(h.errorBody()))
1153                 }
1154                 tw.timedOut = true
1155         }
1156 }
1157
1158 type timeoutWriter struct {
1159         w ResponseWriter
1160
1161         mu          sync.Mutex
1162         timedOut    bool
1163         wroteHeader bool
1164 }
1165
1166 func (tw *timeoutWriter) Header() Header {
1167         return tw.w.Header()
1168 }
1169
1170 func (tw *timeoutWriter) Write(p []byte) (int, error) {
1171         tw.mu.Lock()
1172         timedOut := tw.timedOut
1173         tw.mu.Unlock()
1174         if timedOut {
1175                 return 0, ErrHandlerTimeout
1176         }
1177         return tw.w.Write(p)
1178 }
1179
1180 func (tw *timeoutWriter) WriteHeader(code int) {
1181         tw.mu.Lock()
1182         if tw.timedOut || tw.wroteHeader {
1183                 tw.mu.Unlock()
1184                 return
1185         }
1186         tw.wroteHeader = true
1187         tw.mu.Unlock()
1188         tw.w.WriteHeader(code)
1189 }