server.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2011 Andy Balholm. 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. // Network connections and request dispatch for the ICAP server.
  5. package icap
  6. import (
  7. "bufio"
  8. "bytes"
  9. "crypto/tls"
  10. "fmt"
  11. "log"
  12. "net"
  13. "net/http"
  14. "net/textproto"
  15. "net/url"
  16. "runtime/debug"
  17. "time"
  18. )
  19. // Handler Objects implementing the Handler interface can be registered
  20. // to serve ICAP requests.
  21. //
  22. // ServeICAP should write reply headers and data to the ResponseWriter
  23. // and then return.
  24. type Handler interface {
  25. ServeICAP(ResponseWriter, *Request)
  26. }
  27. // The HandlerFunc type is an adapter to allow the use of
  28. // ordinary functions as ICAP handlers. If f is a function
  29. // with the appropriate signature, HandlerFunc(f) is a
  30. // Handler object that calls f.
  31. type HandlerFunc func(ResponseWriter, *Request)
  32. // ServeICAP calls f(w, r).
  33. func (f HandlerFunc) ServeICAP(w ResponseWriter, r *Request) {
  34. f(w, r)
  35. }
  36. // A conn represents the server side of an ICAP connection.
  37. type conn struct {
  38. remoteAddr string // network address of remote side
  39. handler Handler // request handler
  40. rwc net.Conn // i/o connection
  41. buf *bufio.ReadWriter // buffered rwc
  42. }
  43. // Create new connection from rwc.
  44. func newConn(rwc net.Conn, handler Handler) (c *conn, err error) {
  45. c = new(conn)
  46. c.remoteAddr = rwc.RemoteAddr().String()
  47. c.handler = handler
  48. c.rwc = rwc
  49. br := bufio.NewReader(rwc)
  50. bw := bufio.NewWriter(rwc)
  51. c.buf = bufio.NewReadWriter(br, bw)
  52. return c, nil
  53. }
  54. // Read next request from connection.
  55. func (c *conn) readRequest() (w *respWriter, err error) {
  56. var req *Request
  57. if req, err = ReadRequest(c.buf); err != nil {
  58. //return req, err
  59. }
  60. if req == nil {
  61. req = new(Request)
  62. } else {
  63. req.RemoteAddr = c.remoteAddr
  64. }
  65. w = new(respWriter)
  66. w.conn = c
  67. w.req = req
  68. w.header = make(http.Header)
  69. return w, err
  70. }
  71. // Close the connection.
  72. func (c *conn) close() {
  73. if c.buf != nil {
  74. c.buf.Flush()
  75. c.buf = nil
  76. }
  77. if c.rwc != nil {
  78. c.rwc.Close()
  79. c.rwc = nil
  80. }
  81. }
  82. // Serve a new connection.
  83. func (c *conn) serve(debugLevel int) {
  84. defer func() {
  85. err := recover()
  86. if err == nil {
  87. return
  88. }
  89. c.rwc.Close()
  90. var buf bytes.Buffer
  91. fmt.Fprintf(&buf, "icap: panic serving %v: %v\n", c.remoteAddr, err)
  92. buf.Write(debug.Stack())
  93. log.Print(buf.String())
  94. }()
  95. var w *respWriter
  96. w, err := c.readRequest()
  97. // In a case of parsing error there should be an option to handle a dummy request to not fail the whole service.
  98. if err != nil {
  99. if debugLevel > 0 {
  100. log.Println("error while reading request:", err)
  101. log.Println("error while reading request:", w)
  102. log.Println("error while reading request:", w.conn)
  103. log.Println("error while reading request:", w.req)
  104. log.Println("error while reading request:", w.header)
  105. }
  106. // c.rwc.Close()
  107. // return
  108. if w == nil {
  109. w = new(respWriter)
  110. }
  111. w.conn = c
  112. w.req = new(Request)
  113. w.req.Method = "ERRDUMMY"
  114. w.req.RawURL = "/"
  115. w.req.Proto = "ICAP/1.0"
  116. w.req.URL, _ = url.ParseRequestURI("icap://localhost/")
  117. w.req.Header = textproto.MIMEHeader{
  118. "Connection": {"close"},
  119. // "Error:": {err.Error()},
  120. }
  121. }
  122. c.handler.ServeICAP(w, w.req)
  123. w.finishRequest()
  124. c.close()
  125. }
  126. // A Server defines parameters for running an ICAP server.
  127. type Server struct {
  128. Addr string // TCP address to listen on, ":1344" if empty
  129. Handler Handler // handler to invoke
  130. ReadTimeout time.Duration
  131. WriteTimeout time.Duration
  132. DebugLevel int
  133. }
  134. // ListenAndServe listens on the TCP network address srv.Addr and then
  135. // calls Serve to handle requests on incoming connections. If
  136. // srv.Addr is blank, ":1344" is used.
  137. func (srv *Server) ListenAndServe() error {
  138. addr := srv.Addr
  139. if addr == "" {
  140. addr = ":1344"
  141. }
  142. l, err := net.Listen("tcp", addr)
  143. if err != nil {
  144. return err
  145. }
  146. return srv.Serve(l)
  147. }
  148. // ListenAndServeTLS ---
  149. func (srv *Server) ListenAndServeTLS(cert, key string) error {
  150. cer, err := tls.LoadX509KeyPair(cert, key)
  151. if err != nil {
  152. return err
  153. }
  154. addr := srv.Addr
  155. if addr == "" {
  156. addr = ":1344"
  157. }
  158. config := &tls.Config{Certificates: []tls.Certificate{cer}}
  159. l, err := tls.Listen("tcp", addr, config)
  160. if err != nil {
  161. return err
  162. }
  163. return srv.Serve(l)
  164. }
  165. // Serve accepts incoming connections on the Listener l, creating a
  166. // new service thread for each. The service threads read requests and
  167. // then call srv.Handler to reply to them.
  168. func (srv *Server) Serve(l net.Listener) error {
  169. defer l.Close()
  170. handler := srv.Handler
  171. if handler == nil {
  172. handler = DefaultServeMux
  173. }
  174. for {
  175. rw, err := l.Accept()
  176. if err != nil {
  177. if ne, ok := err.(net.Error); ok && ne.Temporary() {
  178. log.Printf("icap: Accept error: %v", err)
  179. continue
  180. }
  181. return err
  182. }
  183. if srv.ReadTimeout != 0 {
  184. rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
  185. }
  186. if srv.WriteTimeout != 0 {
  187. rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
  188. }
  189. c, err := newConn(rw, handler)
  190. if err != nil {
  191. continue
  192. }
  193. go c.serve(srv.DebugLevel)
  194. }
  195. // The next line is only there to see one specific edge case whichc should never happen.
  196. panic("Shuold never be reached")
  197. }
  198. // Serve accepts incoming ICAP connections on the listener l,
  199. // creating a new service thread for each. The service threads
  200. // read requests and then call handler to reply to them.
  201. func Serve(l net.Listener, handler Handler) error {
  202. srv := &Server{Handler: handler}
  203. return srv.Serve(l)
  204. }
  205. // ListenAndServe listens on the TCP network address addr
  206. // and then calls Serve with handler to handle requests
  207. // on incoming connections.
  208. func ListenAndServe(addr string, handler Handler) error {
  209. server := &Server{Addr: addr, Handler: handler}
  210. return server.ListenAndServe()
  211. }
  212. // ListenAndServeTLS --
  213. func ListenAndServeTLS(addr, cert, key string, handler Handler) error {
  214. server := &Server{Addr: addr, Handler: handler}
  215. return server.ListenAndServeTLS(cert, key)
  216. }