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