eliminate duplicate logging of warnings (reported by loke)
[hunchentoot.git] / acceptor.lisp
blob61ef3ecdd252a6e2e5f5e0bcaab4070bff15ea14
1 ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
3 ;;; Copyright (c) 2004-2010, Dr. Edmund Weitz. All rights reserved.
5 ;;; Redistribution and use in source and binary forms, with or without
6 ;;; modification, are permitted provided that the following conditions
7 ;;; are met:
9 ;;; * Redistributions of source code must retain the above copyright
10 ;;; notice, this list of conditions and the following disclaimer.
12 ;;; * Redistributions in binary form must reproduce the above
13 ;;; copyright notice, this list of conditions and the following
14 ;;; disclaimer in the documentation and/or other materials
15 ;;; provided with the distribution.
17 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
18 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
21 ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23 ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 (in-package :hunchentoot)
31 (eval-when (:load-toplevel :compile-toplevel :execute)
32 (defun default-document-directory (&optional sub-directory)
33 (let ((source-directory #.(or *compile-file-truename* *load-truename*)))
34 (merge-pathnames (make-pathname :directory (append (pathname-directory source-directory)
35 (list "www")
36 (when sub-directory
37 (list sub-directory)))
38 :name nil
39 :type nil
40 :defaults source-directory)))))
42 (defclass acceptor ()
43 ((port :initarg :port
44 :reader acceptor-port
45 :documentation "The port the acceptor is listening on. The
46 default is 80. Note that depending on your operating system you might
47 need special privileges to listen on port 80.")
48 (address :initarg :address
49 :reader acceptor-address
50 :documentation "The address the acceptor is listening on.
51 If address is a string denoting an IP address, then the server only
52 receives connections for that address. This must be one of the
53 addresses associated with the machine and allowed values are host
54 names such as \"www.zappa.com\" and address strings such as
55 \"72.3.247.29\". If address is NIL, then the server will receive
56 connections to all IP addresses on the machine. This is the default.")
57 (name :initarg :name
58 :accessor acceptor-name
59 :documentation "The optional name of the acceptor, a symbol.
60 This name can be utilized when defining \"easy handlers\" - see
61 DEFINE-EASY-HANDLER. The default name is an uninterned symbol as
62 returned by GENSYM.")
63 (request-class :initarg :request-class
64 :accessor acceptor-request-class
65 :documentation "Determines which class of request
66 objects is created when a request comes in and should be \(a symbol
67 naming) a class which inherits from REQUEST. The default is the
68 symbol REQUEST.")
69 (reply-class :initarg :reply-class
70 :accessor acceptor-reply-class
71 :documentation "Determines which class of reply
72 objects is created when a request is served in and should be \(a
73 symbol naming) a class which inherits from REPLY. The default is the
74 symbol REPLY.")
75 (taskmaster :initarg :taskmaster
76 :reader acceptor-taskmaster
77 :documentation "The taskmaster \(i.e. an instance of a
78 subclass of TASKMASTER) that is responsible for scheduling the work
79 for this acceptor. The default depends on the MP capabilities of the
80 underlying Lisp.")
81 (output-chunking-p :initarg :output-chunking-p
82 :accessor acceptor-output-chunking-p
83 :documentation "A generalized boolean denoting
84 whether the acceptor may use chunked encoding for output, i.e. when
85 sending data to the client. The default is T and there's usually no
86 reason to change this to NIL.")
87 (input-chunking-p :initarg :input-chunking-p
88 :accessor acceptor-input-chunking-p
89 :documentation "A generalized boolean denoting
90 whether the acceptor may use chunked encoding for input, i.e. when
91 accepting request bodies from the client. The default is T and
92 there's usually no reason to change this to NIL.")
93 (persistent-connections-p :initarg :persistent-connections-p
94 :accessor acceptor-persistent-connections-p
95 :documentation "A generalized boolean
96 denoting whether the acceptor supports persistent connections, which
97 is the default for threaded acceptors. If this property is NIL,
98 Hunchentoot closes each incoming connection after having processed one
99 request. This is the default for non-threaded acceptors.")
100 (read-timeout :initarg :read-timeout
101 :reader acceptor-read-timeout
102 :documentation "The read timeout of the acceptor,
103 specified in \(fractional) seconds. The precise semantics of this
104 parameter is determined by the underlying Lisp's implementation of
105 socket timeouts. NIL means no timeout.")
106 (write-timeout :initarg :write-timeout
107 :reader acceptor-write-timeout
108 :documentation "The write timeout of the acceptor,
109 specified in \(fractional) seconds. The precise semantics of this
110 parameter is determined by the underlying Lisp's implementation of
111 socket timeouts. NIL means no timeout.")
112 #+:lispworks
113 (process :accessor acceptor-process
114 :documentation "The Lisp process which accepts incoming
115 requests. This is the process started by COMM:START-UP-SERVER and no
116 matter what kind of taskmaster you are using this will always be a new
117 process different from the one where START was called.")
118 #-:lispworks
119 (listen-socket :initform nil
120 :accessor acceptor-listen-socket
121 :documentation "The socket listening for incoming
122 connections.")
123 #-:lispworks
124 (listen-backlog :initarg :listen-backlog
125 :reader acceptor-listen-backlog
126 :documentation "Number of pending connections
127 allowed in the listen socket before the kernel rejects
128 further incoming connections.")
129 (acceptor-shutdown-p :initform t
130 :accessor acceptor-shutdown-p
131 :documentation "A flag that makes the acceptor
132 shutdown itself when set to something other than NIL.")
133 (requests-in-progress :initform 0
134 :accessor accessor-requests-in-progress
135 :documentation "The number of
136 requests currently in progress.")
137 (shutdown-queue :initform (make-condition-variable)
138 :accessor acceptor-shutdown-queue
139 :documentation "A condition variable
140 used with soft shutdown, signaled when all requests
141 have been processed.")
142 (shutdown-lock :initform (make-lock "hunchentoot-acceptor-shutdown")
143 :accessor acceptor-shutdown-lock
144 :documentation "The lock protecting the shutdown-queue
145 condition variable and the requests-in-progress counter.")
146 (access-log-destination :initarg :access-log-destination
147 :accessor acceptor-access-log-destination
148 :documentation "Destination of the access log
149 which contains one log entry per request handled in a format similar
150 to Apache's access.log. Can be set to a pathname or string
151 designating the log file, to a open output stream or to NIL to
152 suppress logging.")
153 (message-log-destination :initarg :message-log-destination
154 :accessor acceptor-message-log-destination
155 :documentation "Destination of the server
156 error log which is used to log informational, warning and error
157 messages in a free-text format intended for human inspection. Can be
158 set to a pathname or string designating the log file, to a open output
159 stream or to NIL to suppress logging.")
160 (error-template-directory :initarg :error-template-directory
161 :accessor acceptor-error-template-directory
162 :documentation "Directory pathname that
163 contains error message template files for server-generated error
164 messages. Files must be named <return-code>.html with <return-code>
165 representing the HTTP return code that the file applies to,
166 i.e. 404.html would be used as the content for a HTTP 404 Not found
167 response.")
168 (document-root :initarg :document-root
169 :accessor acceptor-document-root
170 :documentation "Directory pathname that points to
171 files that are served by the acceptor if no more specific
172 acceptor-dispatch-request method handles the request."))
173 (:default-initargs
174 :address nil
175 :port 80
176 :name (gensym)
177 :request-class 'request
178 :reply-class 'reply
179 #-lispworks :listen-backlog #-lispworks 50
180 :taskmaster (make-instance (cond (*supports-threads-p* 'one-thread-per-connection-taskmaster)
181 (t 'single-threaded-taskmaster)))
182 :output-chunking-p t
183 :input-chunking-p t
184 :persistent-connections-p t
185 :read-timeout *default-connection-timeout*
186 :write-timeout *default-connection-timeout*
187 :access-log-destination *error-output*
188 :message-log-destination *error-output*
189 :document-root (load-time-value (default-document-directory))
190 :error-template-directory (load-time-value (default-document-directory "errors")))
191 (:documentation "To create a Hunchentoot webserver, you make an
192 instance of this class and use the generic function START to start it
193 \(and STOP to stop it). Use the :PORT initarg if you don't want to
194 listen on the default http port 80. There are other initargs most of
195 which you probably won't need very often. They are explained in
196 detail in the docstrings of the slot definitions for this class.
198 Unless you are in a Lisp without MP capabilities, you can have several
199 active instances of ACCEPTOR \(listening on different ports) at the
200 same time."))
202 (defmethod print-object ((acceptor acceptor) stream)
203 (print-unreadable-object (acceptor stream :type t)
204 (format stream "\(host ~A, port ~A)"
205 (or (acceptor-address acceptor) "*") (acceptor-port acceptor))))
207 (defmethod initialize-instance :after ((acceptor acceptor) &key)
208 (with-accessors ((document-root acceptor-document-root)
209 (error-template-directory acceptor-error-template-directory)) acceptor
210 (when document-root
211 (setf document-root (translate-logical-pathname document-root)))
212 (when error-template-directory
213 (setf error-template-directory (translate-logical-pathname error-template-directory)))))
215 (defgeneric start (acceptor)
216 (:documentation "Starts the ACCEPTOR so that it begins accepting
217 connections. Returns the acceptor."))
219 (defgeneric stop (acceptor &key soft)
220 (:documentation "Stops the ACCEPTOR so that it no longer accepts
221 requests. If SOFT is true, and there are any requests in progress,
222 wait until all requests are fully processed, but meanwhile do not
223 accept new requests. Note that SOFT must not be set when calling
224 STOP from within a request handler, as that will deadlock."))
226 (defgeneric start-listening (acceptor)
227 (:documentation "Sets up a listen socket for the given ACCEPTOR and
228 enables it to listen to incoming connections. This function is called
229 from the thread that starts the acceptor initially and may return
230 errors resulting from the listening operation \(like 'address in use'
231 or similar)."))
233 (defgeneric accept-connections (acceptor)
234 (:documentation "In a loop, accepts a connection and hands it over
235 to the acceptor's taskmaster for processing using
236 HANDLE-INCOMING-CONNECTION. On LispWorks, this function returns
237 immediately, on other Lisps it retusn only once the acceptor has been
238 stopped."))
240 (defgeneric initialize-connection-stream (acceptor stream)
241 (:documentation "Can be used to modify the stream which is used to
242 communicate between client and server before the request is read. The
243 default method of ACCEPTOR does nothing, but see for example the
244 method defined for SSL-ACCEPTOR. All methods of this generic function
245 must return the stream to use."))
247 (defgeneric reset-connection-stream (acceptor stream)
248 (:documentation "Resets the stream which is used to communicate
249 between client and server after one request has been served so that it
250 can be used to process the next request. This generic function is
251 called after a request has been processed and must return the
252 stream."))
254 (defgeneric process-connection (acceptor socket)
255 (:documentation "This function is called by the taskmaster when a
256 new client connection has been established. Its arguments are the
257 ACCEPTOR object and a LispWorks socket handle or a usocket socket
258 stream object in SOCKET. It reads the request headers, sets up the
259 request and reply objects, and hands over to PROCESS-REQUEST. This is
260 done in a loop until the stream has to be closed or until a connection
261 timeout occurs.
263 It is probably not a good idea to re-implement this method until you
264 really, really know what you're doing."))
266 (defgeneric handle-request (acceptor request)
267 (:documentation "This function is called once the request has been
268 read and a REQUEST object has been created. Its job is to set up
269 standard error handling and request logging.
271 Might be a good place for around methods specialized for your subclass
272 of ACCEPTOR which bind or rebind special variables which can then be
273 accessed by your handlers."))
275 (defgeneric acceptor-dispatch-request (acceptor request)
276 (:documentation "This function is called to actually dispatch the
277 request once the standard logging and error handling has been set up.
278 ACCEPTOR subclasses implement methods for this function in order to
279 perform their own request routing. If a method does not want to
280 handle the request, it is supposed to invoke CALL-NEXT-METHOD so that
281 the next ACCEPTOR in the inheritance chain gets a chance to handle the
282 request."))
284 (defgeneric acceptor-ssl-p (acceptor)
285 (:documentation "Returns a true value if ACCEPTOR uses SSL
286 connections. The default is to unconditionally return NIL and
287 subclasses of ACCEPTOR must specialize this method to signal that
288 they're using secure connections - see the SSL-ACCEPTOR class."))
290 ;; general implementation
292 (defmethod start ((acceptor acceptor))
293 (setf (acceptor-shutdown-p acceptor) nil)
294 (start-listening acceptor)
295 (let ((taskmaster (acceptor-taskmaster acceptor)))
296 (setf (taskmaster-acceptor taskmaster) acceptor)
297 (execute-acceptor taskmaster))
298 acceptor)
300 (defmethod stop ((acceptor acceptor) &key soft)
301 (setf (acceptor-shutdown-p acceptor) t)
302 (when soft
303 (with-lock-held ((acceptor-shutdown-lock acceptor))
304 (when (plusp (accessor-requests-in-progress acceptor))
305 (condition-variable-wait (acceptor-shutdown-queue acceptor)
306 (acceptor-shutdown-lock acceptor)))))
307 (shutdown (acceptor-taskmaster acceptor))
308 #-lispworks
309 (usocket:socket-close (acceptor-listen-socket acceptor))
310 #-lispworks
311 (setf (acceptor-listen-socket acceptor) nil)
312 #+lispworks
313 (mp:process-kill (acceptor-process acceptor))
314 acceptor)
316 (defmethod initialize-connection-stream ((acceptor acceptor) stream)
317 ;; default method does nothing
318 stream)
320 (defmethod reset-connection-stream ((acceptor acceptor) stream)
321 ;; turn chunking off at this point
322 (cond ((typep stream 'chunked-stream)
323 ;; flush the stream first and check if there's unread input
324 ;; which would be an error
325 (setf (chunked-stream-output-chunking-p stream) nil
326 (chunked-stream-input-chunking-p stream) nil)
327 ;; switch back to bare socket stream
328 (chunked-stream-stream stream))
329 (t stream)))
331 (defmethod process-connection :around ((*acceptor* acceptor) (socket t))
332 ;; this around method is used for error handling
333 ;; note that this method also binds *ACCEPTOR*
334 (with-conditions-caught-and-logged ()
335 (with-mapped-conditions ()
336 (call-next-method))))
338 (defun do-with-acceptor-request-count-incremented (*acceptor* function)
339 (with-lock-held ((acceptor-shutdown-lock *acceptor*))
340 (incf (accessor-requests-in-progress *acceptor*)))
341 (unwind-protect
342 (funcall function)
343 (with-lock-held ((acceptor-shutdown-lock *acceptor*))
344 (decf (accessor-requests-in-progress *acceptor*))
345 (when (acceptor-shutdown-p *acceptor*)
346 (condition-variable-signal (acceptor-shutdown-queue *acceptor*))))))
348 (defmacro with-acceptor-request-count-incremented ((acceptor) &body body)
349 "Execute BODY with ACCEPTOR-REQUESTS-IN-PROGRESS of ACCEPTOR
350 incremented by one. If the ACCEPTOR-SHUTDOWN-P returns true after
351 the BODY has been executed, the ACCEPTOR-SHUTDOWN-QUEUE condition
352 variable of the ACCEPTOR is signalled in order to finish shutdown
353 processing."
354 `(do-with-acceptor-request-count-incremented ,acceptor (lambda () ,@body)))
356 (defun acceptor-make-request (acceptor socket
357 &key
358 headers-in
359 content-stream
360 method
362 server-protocol)
363 "Make a REQUEST instance for the ACCEPTOR, setting up those slots
364 that are determined from the SOCKET by calling the appropriate
365 socket query functions."
366 (multiple-value-bind (remote-addr remote-port)
367 (get-peer-address-and-port socket)
368 (multiple-value-bind (local-addr local-port)
369 (get-local-address-and-port socket)
370 (make-instance (acceptor-request-class acceptor)
371 :acceptor acceptor
372 :local-addr local-addr
373 :local-port local-port
374 :remote-addr remote-addr
375 :remote-port remote-port
376 :headers-in headers-in
377 :content-stream content-stream
378 :method method
379 :uri uri
380 :server-protocol server-protocol))))
382 (defmethod process-connection ((*acceptor* acceptor) (socket t))
383 (let* ((socket-stream (make-socket-stream socket *acceptor*))
384 (*hunchentoot-stream* (initialize-connection-stream *acceptor* socket-stream)))
385 (unwind-protect
386 ;; process requests until either the acceptor is shut down,
387 ;; *CLOSE-HUNCHENTOOT-STREAM* has been set to T by the
388 ;; handler, or the peer fails to send a request
389 (loop
390 (let ((*close-hunchentoot-stream* t))
391 (when (acceptor-shutdown-p *acceptor*)
392 (return))
393 (multiple-value-bind (headers-in method url-string protocol)
394 (get-request-data *hunchentoot-stream*)
395 ;; check if there was a request at all
396 (unless method
397 (return))
398 ;; bind per-request special variables, then process the
399 ;; request - note that *ACCEPTOR* was bound above already
400 (let ((*reply* (make-instance (acceptor-reply-class *acceptor*)))
401 (*session* nil)
402 (transfer-encodings (cdr (assoc* :transfer-encoding headers-in))))
403 (when transfer-encodings
404 (setq transfer-encodings
405 (split "\\s*,\\s*" transfer-encodings))
406 (when (member "chunked" transfer-encodings :test #'equalp)
407 (cond ((acceptor-input-chunking-p *acceptor*)
408 ;; turn chunking on before we read the request body
409 (setf *hunchentoot-stream* (make-chunked-stream *hunchentoot-stream*)
410 (chunked-stream-input-chunking-p *hunchentoot-stream*) t))
411 (t (hunchentoot-error "Client tried to use ~
412 chunked encoding, but acceptor is configured to not use it.")))))
413 (with-acceptor-request-count-incremented (*acceptor*)
414 (process-request (acceptor-make-request *acceptor* socket
415 :headers-in headers-in
416 :content-stream *hunchentoot-stream*
417 :method method
418 :uri url-string
419 :server-protocol protocol))))
420 (finish-output *hunchentoot-stream*)
421 (setq *hunchentoot-stream* (reset-connection-stream *acceptor* *hunchentoot-stream*))
422 (when *close-hunchentoot-stream*
423 (return)))))
424 (unless (eql socket-stream *hunchentoot-stream*)
425 ;; as we are at the end of the request here, we ignore all
426 ;; errors that may occur while flushing and/or closing the
427 ;; stream.
428 (ignore-errors*
429 (finish-output *hunchentoot-stream*))
430 (ignore-errors*
431 (close *hunchentoot-stream* :abort t)))
432 (when socket-stream
433 ;; as we are at the end of the request here, we ignore all
434 ;; errors that may occur while flushing and/or closing the
435 ;; stream.
436 (ignore-errors*
437 (finish-output socket-stream))
438 (ignore-errors*
439 (close socket-stream :abort t))))))
441 (defmethod acceptor-ssl-p ((acceptor t))
442 ;; the default is to always answer "no"
443 nil)
445 (defgeneric acceptor-log-access (acceptor &key return-code)
446 (:documentation
447 "Function to call to log access to the acceptor. The RETURN-CODE,
448 CONTENT and CONTENT-LENGTH keyword arguments contain additional
449 information about the request to log. In addition, it can use the
450 standard request accessor functions that are available to handler
451 functions to find out more information about the request."))
453 (defmethod acceptor-log-access ((acceptor acceptor) &key return-code)
454 "Default method for access logging. It logs the information to the
455 destination determined by (ACCEPTOR-ACCESS-LOG-DESTINATION ACCEPTOR)
456 \(unless that value is NIL) in a format that can be parsed by most
457 Apache log analysis tools.)"
459 (with-log-stream (stream (acceptor-access-log-destination acceptor) *access-log-lock*)
460 (format stream "~:[-~@[ (~A)~]~;~:*~A~@[ (~A)~]~] ~:[-~;~:*~A~] [~A] \"~A ~A~@[?~A~] ~
461 ~A\" ~D ~:[-~;~:*~D~] \"~:[-~;~:*~A~]\" \"~:[-~;~:*~A~]\"~%"
462 (remote-addr*)
463 (header-in* :x-forwarded-for)
464 (authorization)
465 (iso-time)
466 (request-method*)
467 (script-name*)
468 (query-string*)
469 (server-protocol*)
470 return-code
471 (content-length*)
472 (referer)
473 (user-agent))))
475 (defgeneric acceptor-log-message (acceptor log-level format-string &rest format-arguments)
476 (:documentation
477 "Function to call to log messages by the ACCEPTOR. It must accept
478 a severity level for the message, which will be one of :ERROR, :INFO,
479 or :WARNING, a format string and an arbitary number of formatting
480 arguments."))
482 (defmethod acceptor-log-message ((acceptor acceptor) log-level format-string &rest format-arguments)
483 "Default function to log server messages. Sends a formatted message
484 to the destination denoted by (ACCEPTOR-MESSAGE-LOG-DESTINATION
485 ACCEPTOR). FORMAT and ARGS are as in FORMAT. LOG-LEVEL is a
486 keyword denoting the log level or NIL in which case it is ignored."
487 (with-log-stream (stream (acceptor-message-log-destination acceptor) *message-log-lock*)
488 (handler-case
489 (format stream "[~A~@[ [~A]~]] ~?~%"
490 (iso-time) log-level
491 format-string format-arguments)
492 (error (e)
493 (ignore-errors
494 (format *trace-output* "error ~A while writing to error log, error not logged~%" e))))))
496 (defun log-message* (log-level format-string &rest format-arguments)
497 "Convenience function which calls the message logger of the current
498 acceptor \(if there is one) with the same arguments it accepts.
500 This is the function which Hunchentoot itself uses to log errors it
501 catches during request processing."
502 (apply 'acceptor-log-message *acceptor* log-level format-string format-arguments))
504 ;; usocket implementation
506 #-:lispworks
507 (defmethod start-listening ((acceptor acceptor))
508 (when (acceptor-listen-socket acceptor)
509 (hunchentoot-error "acceptor ~A is already listening" acceptor))
510 (setf (acceptor-listen-socket acceptor)
511 (usocket:socket-listen (or (acceptor-address acceptor)
512 usocket:*wildcard-host*)
513 (acceptor-port acceptor)
514 :reuseaddress t
515 :backlog (acceptor-listen-backlog acceptor)
516 :element-type '(unsigned-byte 8)))
517 (values))
519 #-:lispworks
520 (defmethod accept-connections ((acceptor acceptor))
521 (usocket:with-server-socket (listener (acceptor-listen-socket acceptor))
522 (loop
523 (when (acceptor-shutdown-p acceptor)
524 (return))
525 (when (usocket:wait-for-input listener :ready-only t :timeout +new-connection-wait-time+)
526 (when-let (client-connection
527 (handler-case (usocket:socket-accept listener)
528 ;; ignore condition
529 (usocket:connection-aborted-error ())))
530 (set-timeouts client-connection
531 (acceptor-read-timeout acceptor)
532 (acceptor-write-timeout acceptor))
533 (handle-incoming-connection (acceptor-taskmaster acceptor)
534 client-connection))))))
536 ;; LispWorks implementation
538 #+:lispworks
539 (defmethod start-listening ((acceptor acceptor))
540 (multiple-value-bind (listener-process startup-condition)
541 (comm:start-up-server :service (acceptor-port acceptor)
542 :address (acceptor-address acceptor)
543 :process-name (format nil "Hunchentoot listener \(~A:~A)"
544 (or (acceptor-address acceptor) "*")
545 (acceptor-port acceptor))
546 ;; this function is called once on startup - we
547 ;; use it to check for errors
548 :announce (lambda (socket &optional condition)
549 (declare (ignore socket))
550 (when condition
551 (error condition)))
552 ;; this function is called whenever a connection
553 ;; is made
554 :function (lambda (handle)
555 (unless (acceptor-shutdown-p acceptor)
556 (handle-incoming-connection
557 (acceptor-taskmaster acceptor) handle)))
558 ;; wait until the acceptor was successfully started
559 ;; or an error condition is returned
560 :wait t)
561 (when startup-condition
562 (error startup-condition))
563 (mp:process-stop listener-process)
564 (setf (acceptor-process acceptor) listener-process)
565 (values)))
567 #+:lispworks
568 (defmethod accept-connections ((acceptor acceptor))
569 (mp:process-unstop (acceptor-process acceptor))
570 nil)
572 (defmethod acceptor-dispatch-request ((acceptor acceptor) request)
573 "Detault implementation of the request dispatch method, generates an
574 +http-not-found+ error."
575 (let ((path (and (acceptor-document-root acceptor)
576 (request-pathname request))))
577 (cond
578 (path
579 (handle-static-file
580 (merge-pathnames (if (equal "/" (script-name request)) #p"index.html" path)
581 (acceptor-document-root acceptor))))
583 (setf (return-code *reply*) +http-not-found+)
584 (abort-request-handler)))))
586 (defmethod handle-request ((*acceptor* acceptor) (*request* request))
587 "Standard method for request handling. Calls the request dispatcher
588 of *ACCEPTOR* to determine how the request should be handled. Also
589 sets up standard error handling which catches any errors within the
590 handler."
591 (handler-bind ((error
592 (lambda (cond)
593 ;; if the headers were already sent, the error
594 ;; happened within the body and we have to close
595 ;; the stream
596 (when *headers-sent*
597 (setq *close-hunchentoot-stream* t))
598 (throw 'handler-done
599 (values nil cond (get-backtrace))))))
600 (with-debugger
601 (acceptor-dispatch-request *acceptor* *request*))))
603 (defgeneric acceptor-status-message (acceptor http-status-code &key &allow-other-keys)
604 (:documentation
605 "This function is called after the request's handler has been
606 invoked to convert the HTTP-STATUS-CODE to a HTML message to be
607 displayed to the user. If this function returns a string, that
608 string is sent to the client instead of the content produced by the
609 handler, if any.
611 If an ERROR-TEMPLATE-DIRECTORY is set in the current acceptor and
612 the directory contains a file corresponding to HTTP-STATUS-CODE
613 named <code>.html, that file is sent to the client after variable
614 substitution. Variables are referenced by ${<variable-name>}.
616 Additional keyword arguments may be provided which are made
617 available to the templating logic as substitution variables. These
618 variables can be interpolated into error message templates in,
619 which contains the current URL relative to the server and without
620 GET parameters.
622 In addition to the variables corresponding to keyword arguments,
623 the script-name, lisp-implementation-type,
624 lisp-implementation-version and hunchentoot-version variables are
625 available."))
627 (defun make-cooked-message (http-status-code &key error backtrace)
628 (labels ((cooked-message (format &rest arguments)
629 (setf (content-type*) "text/html; charset=iso-8859-1")
630 (format nil "<html><head><title>~D ~A</title></head><body><h1>~:*~A</h1>~?<p><hr>~A</p></body></html>"
631 http-status-code (reason-phrase http-status-code)
632 format (mapcar (lambda (arg)
633 (if (stringp arg)
634 (escape-for-html arg)
635 arg))
636 arguments)
637 (address-string))))
638 (case http-status-code
639 ((#.+http-moved-temporarily+
640 #.+http-moved-permanently+)
641 (cooked-message "The document has moved <a href='~A'>here</a>" (header-out :location)))
642 ((#.+http-authorization-required+)
643 (cooked-message "The server could not verify that you are authorized to access the document requested. ~
644 Either you supplied the wrong credentials \(e.g., bad password), or your browser doesn't ~
645 understand how to supply the credentials required."))
646 ((#.+http-forbidden+)
647 (cooked-message "You don't have permission to access ~A on this server."
648 (script-name *request*)))
649 ((#.+http-not-found+)
650 (cooked-message "The requested URL ~A was not found on this server."
651 (script-name *request*)))
652 ((#.+http-bad-request+)
653 (cooked-message "Your browser sent a request that this server could not understand."))
654 ((#.+http-internal-server-error+)
655 (if *show-lisp-errors-p*
656 (cooked-message "<pre>~A~@[~%~%Backtrace:~%~%~A~]</pre>"
657 (escape-for-html (princ-to-string error))
658 (when *show-lisp-backtraces-p*
659 (escape-for-html (princ-to-string backtrace))))
660 (cooked-message "An error has occurred")))
662 (when (<= 400 http-status-code)
663 (cooked-message "An error has occurred"))))))
665 (defmethod acceptor-status-message ((acceptor t) http-status-code &rest args &key &allow-other-keys)
666 (apply 'make-cooked-message http-status-code args))
668 (defmethod acceptor-status-message :around ((acceptor acceptor) http-status-code &rest args &key &allow-other-keys)
669 (handler-case
670 (call-next-method)
671 (error (e)
672 (log-message* :error "error ~A during error processing, sending cooked message to client" e)
673 (apply 'make-cooked-message http-status-code args))))
675 (defun string-as-keyword (string)
676 "Intern STRING as keyword using the reader so that case conversion is done with the reader defaults."
677 (let ((*package* (find-package :keyword)))
678 (read-from-string string)))
680 (defmethod acceptor-status-message ((acceptor acceptor) http-status-code &rest properties &key &allow-other-keys)
681 "Default function to generate error message sent to the client."
682 (labels
683 ((substitute-request-context-variables (string)
684 (let ((properties (append `(:script-name ,(script-name*)
685 :lisp-implementation-type ,(lisp-implementation-type)
686 :lisp-implementation-version ,(lisp-implementation-version)
687 :hunchentoot-version ,*hunchentoot-version*)
688 properties)))
689 (unless *show-lisp-backtraces-p*
690 (setf (getf properties :backtrace) nil))
691 (cl-ppcre:regex-replace-all "(?i)\\$\\{([a-z0-9-_]+)\\}"
692 string
693 (lambda (target-string start end match-start match-end reg-starts reg-ends)
694 (declare (ignore start end match-start match-end))
695 (let ((variable-name (string-as-keyword (subseq target-string
696 (aref reg-starts 0)
697 (aref reg-ends 0)))))
698 (escape-for-html (princ-to-string (getf properties variable-name variable-name))))))))
699 (file-contents (file)
700 (let ((buf (make-string (file-length file))))
701 (read-sequence buf file)
702 buf))
703 (error-contents-from-template ()
704 (let ((error-file-template-pathname (and (acceptor-error-template-directory acceptor)
705 (probe-file (make-pathname :name (princ-to-string http-status-code)
706 :type "html"
707 :defaults (acceptor-error-template-directory acceptor))))))
708 (when error-file-template-pathname
709 (with-open-file (file error-file-template-pathname :if-does-not-exist nil :element-type 'character)
710 (when file
711 (setf (content-type*) "text/html")
712 (substitute-request-context-variables (file-contents file))))))))
713 (or (unless (< 300 http-status-code)
714 (call-next-method)) ; don't ever try template for positive return codes
715 (when *show-lisp-errors-p*
716 (error-contents-from-template)) ; try template
717 (call-next-method)))) ; fall back to cooked message
719 (defgeneric acceptor-remove-session (acceptor session)
720 (:documentation
721 "This function is called whenever a session in ACCEPTOR is being
722 destroyed because of a session timout or an explicit REMOVE-SESSION
723 call."))
725 (defmethod acceptor-remove-session ((acceptor acceptor) (session t))
726 "Default implementation for the session removal hook function. This
727 function is called whenever a session is destroyed."
728 nil)
730 (defgeneric acceptor-server-name (acceptor)
731 (:documentation "Returns a string which can be used for 'Server' headers.")
732 (:method ((acceptor acceptor))
733 (format nil "Hunchentoot ~A" *hunchentoot-version*)))