release 1.2.25
[hunchentoot.git] / acceptor.lisp
blobe621179badf3f8439b75c2ebb1b3b3541e785126
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 (defgeneric start (acceptor)
208 (:documentation "Starts the ACCEPTOR so that it begins accepting
209 connections. Returns the acceptor."))
211 (defgeneric stop (acceptor &key soft)
212 (:documentation "Stops the ACCEPTOR so that it no longer accepts
213 requests. If SOFT is true, and there are any requests in progress,
214 wait until all requests are fully processed, but meanwhile do not
215 accept new requests. Note that SOFT must not be set when calling
216 STOP from within a request handler, as that will deadlock."))
218 (defgeneric start-listening (acceptor)
219 (:documentation "Sets up a listen socket for the given ACCEPTOR and
220 enables it to listen to incoming connections. This function is called
221 from the thread that starts the acceptor initially and may return
222 errors resulting from the listening operation \(like 'address in use'
223 or similar)."))
225 (defgeneric accept-connections (acceptor)
226 (:documentation "In a loop, accepts a connection and hands it over
227 to the acceptor's taskmaster for processing using
228 HANDLE-INCOMING-CONNECTION. On LispWorks, this function returns
229 immediately, on other Lisps it retusn only once the acceptor has been
230 stopped."))
232 (defgeneric initialize-connection-stream (acceptor stream)
233 (:documentation "Can be used to modify the stream which is used to
234 communicate between client and server before the request is read. The
235 default method of ACCEPTOR does nothing, but see for example the
236 method defined for SSL-ACCEPTOR. All methods of this generic function
237 must return the stream to use."))
239 (defgeneric reset-connection-stream (acceptor stream)
240 (:documentation "Resets the stream which is used to communicate
241 between client and server after one request has been served so that it
242 can be used to process the next request. This generic function is
243 called after a request has been processed and must return the
244 stream."))
246 (defgeneric process-connection (acceptor socket)
247 (:documentation "This function is called by the taskmaster when a
248 new client connection has been established. Its arguments are the
249 ACCEPTOR object and a LispWorks socket handle or a usocket socket
250 stream object in SOCKET. It reads the request headers, sets up the
251 request and reply objects, and hands over to PROCESS-REQUEST. This is
252 done in a loop until the stream has to be closed or until a connection
253 timeout occurs.
255 It is probably not a good idea to re-implement this method until you
256 really, really know what you're doing."))
258 (defgeneric handle-request (acceptor request)
259 (:documentation "This function is called once the request has been
260 read and a REQUEST object has been created. Its job is to set up
261 standard error handling and request logging.
263 Might be a good place for around methods specialized for your subclass
264 of ACCEPTOR which bind or rebind special variables which can then be
265 accessed by your handlers."))
267 (defgeneric acceptor-dispatch-request (acceptor request)
268 (:documentation "This function is called to actually dispatch the
269 request once the standard logging and error handling has been set up.
270 ACCEPTOR subclasses implement methods for this function in order to
271 perform their own request routing. If a method does not want to
272 handle the request, it is supposed to invoke CALL-NEXT-METHOD so that
273 the next ACCEPTOR in the inheritance chain gets a chance to handle the
274 request."))
276 (defgeneric acceptor-ssl-p (acceptor)
277 (:documentation "Returns a true value if ACCEPTOR uses SSL
278 connections. The default is to unconditionally return NIL and
279 subclasses of ACCEPTOR must specialize this method to signal that
280 they're using secure connections - see the SSL-ACCEPTOR class."))
282 ;; general implementation
284 (defmethod start ((acceptor acceptor))
285 (setf (acceptor-shutdown-p acceptor) nil)
286 (start-listening acceptor)
287 (let ((taskmaster (acceptor-taskmaster acceptor)))
288 (setf (taskmaster-acceptor taskmaster) acceptor)
289 (execute-acceptor taskmaster))
290 acceptor)
292 (defmethod stop ((acceptor acceptor) &key soft)
293 (setf (acceptor-shutdown-p acceptor) t)
294 (when soft
295 (with-lock-held ((acceptor-shutdown-lock acceptor))
296 (when (plusp (accessor-requests-in-progress acceptor))
297 (condition-variable-wait (acceptor-shutdown-queue acceptor)
298 (acceptor-shutdown-lock acceptor)))))
299 (shutdown (acceptor-taskmaster acceptor))
300 #-lispworks
301 (usocket:socket-close (acceptor-listen-socket acceptor))
302 #-lispworks
303 (setf (acceptor-listen-socket acceptor) nil)
304 #+lispworks
305 (mp:process-kill (acceptor-process acceptor))
306 acceptor)
308 (defmethod initialize-connection-stream ((acceptor acceptor) stream)
309 ;; default method does nothing
310 stream)
312 (defmethod reset-connection-stream ((acceptor acceptor) stream)
313 ;; turn chunking off at this point
314 (cond ((typep stream 'chunked-stream)
315 ;; flush the stream first and check if there's unread input
316 ;; which would be an error
317 (setf (chunked-stream-output-chunking-p stream) nil
318 (chunked-stream-input-chunking-p stream) nil)
319 ;; switch back to bare socket stream
320 (chunked-stream-stream stream))
321 (t stream)))
323 (defmethod process-connection :around ((*acceptor* acceptor) (socket t))
324 ;; this around method is used for error handling
325 ;; note that this method also binds *ACCEPTOR*
326 (with-conditions-caught-and-logged ()
327 (with-mapped-conditions ()
328 (call-next-method))))
330 (defun do-with-acceptor-request-count-incremented (*acceptor* function)
331 (with-lock-held ((acceptor-shutdown-lock *acceptor*))
332 (incf (accessor-requests-in-progress *acceptor*)))
333 (unwind-protect
334 (funcall function)
335 (with-lock-held ((acceptor-shutdown-lock *acceptor*))
336 (decf (accessor-requests-in-progress *acceptor*))
337 (when (acceptor-shutdown-p *acceptor*)
338 (condition-variable-signal (acceptor-shutdown-queue *acceptor*))))))
340 (defmacro with-acceptor-request-count-incremented ((acceptor) &body body)
341 "Execute BODY with ACCEPTOR-REQUESTS-IN-PROGRESS of ACCEPTOR
342 incremented by one. If the ACCEPTOR-SHUTDOWN-P returns true after
343 the BODY has been executed, the ACCEPTOR-SHUTDOWN-QUEUE condition
344 variable of the ACCEPTOR is signalled in order to finish shutdown
345 processing."
346 `(do-with-acceptor-request-count-incremented ,acceptor (lambda () ,@body)))
348 (defun acceptor-make-request (acceptor socket
349 &key
350 headers-in
351 content-stream
352 method
354 server-protocol)
355 "Make a REQUEST instance for the ACCEPTOR, setting up those slots
356 that are determined from the SOCKET by calling the appropriate
357 socket query functions."
358 (multiple-value-bind (remote-addr remote-port)
359 (get-peer-address-and-port socket)
360 (multiple-value-bind (local-addr local-port)
361 (get-local-address-and-port socket)
362 (make-instance (acceptor-request-class acceptor)
363 :acceptor acceptor
364 :local-addr local-addr
365 :local-port local-port
366 :remote-addr remote-addr
367 :remote-port remote-port
368 :headers-in headers-in
369 :content-stream content-stream
370 :method method
371 :uri uri
372 :server-protocol server-protocol))))
374 (defmethod process-connection ((*acceptor* acceptor) (socket t))
375 (let ((*hunchentoot-stream* (make-socket-stream socket *acceptor*)))
376 (unwind-protect
377 ;; process requests until either the acceptor is shut down,
378 ;; *CLOSE-HUNCHENTOOT-STREAM* has been set to T by the
379 ;; handler, or the peer fails to send a request
380 (let ((*hunchentoot-stream* (initialize-connection-stream *acceptor* *hunchentoot-stream*)))
381 (loop
382 (let ((*close-hunchentoot-stream* t))
383 (when (acceptor-shutdown-p *acceptor*)
384 (return))
385 (multiple-value-bind (headers-in method url-string protocol)
386 (get-request-data *hunchentoot-stream*)
387 ;; check if there was a request at all
388 (unless method
389 (return))
390 ;; bind per-request special variables, then process the
391 ;; request - note that *ACCEPTOR* was bound above already
392 (let ((*reply* (make-instance (acceptor-reply-class *acceptor*)))
393 (*session* nil)
394 (transfer-encodings (cdr (assoc* :transfer-encoding headers-in))))
395 (when transfer-encodings
396 (setq transfer-encodings
397 (split "\\s*,\\s*" transfer-encodings))
398 (when (member "chunked" transfer-encodings :test #'equalp)
399 (cond ((acceptor-input-chunking-p *acceptor*)
400 ;; turn chunking on before we read the request body
401 (setf *hunchentoot-stream* (make-chunked-stream *hunchentoot-stream*)
402 (chunked-stream-input-chunking-p *hunchentoot-stream*) t))
403 (t (hunchentoot-error "Client tried to use ~
404 chunked encoding, but acceptor is configured to not use it.")))))
405 (with-acceptor-request-count-incremented (*acceptor*)
406 (process-request (acceptor-make-request *acceptor* socket
407 :headers-in headers-in
408 :content-stream *hunchentoot-stream*
409 :method method
410 :uri url-string
411 :server-protocol protocol))))
412 (finish-output *hunchentoot-stream*)
413 (setq *hunchentoot-stream* (reset-connection-stream *acceptor* *hunchentoot-stream*))
414 (when *close-hunchentoot-stream*
415 (return))))))
416 (when *hunchentoot-stream*
417 ;; as we are at the end of the request here, we ignore all
418 ;; errors that may occur while flushing and/or closing the
419 ;; stream.
420 (ignore-errors*
421 (finish-output *hunchentoot-stream*))
422 (ignore-errors*
423 (close *hunchentoot-stream* :abort t))))))
425 (defmethod acceptor-ssl-p ((acceptor t))
426 ;; the default is to always answer "no"
427 nil)
429 (defgeneric acceptor-log-access (acceptor &key return-code)
430 (:documentation
431 "Function to call to log access to the acceptor. The RETURN-CODE,
432 CONTENT and CONTENT-LENGTH keyword arguments contain additional
433 information about the request to log. In addition, it can use the
434 standard request accessor functions that are available to handler
435 functions to find out more information about the request."))
437 (defmethod acceptor-log-access ((acceptor acceptor) &key return-code)
438 "Default method for access logging. It logs the information to the
439 destination determined by (ACCEPTOR-ACCESS-LOG-DESTINATION ACCEPTOR)
440 \(unless that value is NIL) in a format that can be parsed by most
441 Apache log analysis tools.)"
443 (with-log-stream (stream (acceptor-access-log-destination acceptor) *access-log-lock*)
444 (format stream "~:[-~@[ (~A)~]~;~:*~A~@[ (~A)~]~] ~:[-~;~:*~A~] [~A] \"~A ~A~@[?~A~] ~
445 ~A\" ~D ~:[-~;~:*~D~] \"~:[-~;~:*~A~]\" \"~:[-~;~:*~A~]\"~%"
446 (remote-addr*)
447 (header-in* :x-forwarded-for)
448 (authorization)
449 (iso-time)
450 (request-method*)
451 (script-name*)
452 (query-string*)
453 (server-protocol*)
454 return-code
455 (content-length*)
456 (referer)
457 (user-agent))))
459 (defgeneric acceptor-log-message (acceptor log-level format-string &rest format-arguments)
460 (:documentation
461 "Function to call to log messages by the ACCEPTOR. It must accept
462 a severity level for the message, which will be one of :ERROR, :INFO,
463 or :WARNING, a format string and an arbitary number of formatting
464 arguments."))
466 (defmethod acceptor-log-message ((acceptor acceptor) log-level format-string &rest format-arguments)
467 "Default function to log server messages. Sends a formatted message
468 to the destination denoted by (ACCEPTOR-MESSAGE-LOG-DESTINATION
469 ACCEPTOR). FORMAT and ARGS are as in FORMAT. LOG-LEVEL is a
470 keyword denoting the log level or NIL in which case it is ignored."
471 (with-log-stream (stream (acceptor-message-log-destination acceptor) *message-log-lock*)
472 (handler-case
473 (format stream "[~A~@[ [~A]~]] ~?~%"
474 (iso-time) log-level
475 format-string format-arguments)
476 (error (e)
477 (ignore-errors
478 (format *trace-output* "error ~A while writing to error log, error not logged~%" e))))))
480 (defun log-message* (log-level format-string &rest format-arguments)
481 "Convenience function which calls the message logger of the current
482 acceptor \(if there is one) with the same arguments it accepts.
484 This is the function which Hunchentoot itself uses to log errors it
485 catches during request processing."
486 (apply 'acceptor-log-message *acceptor* log-level format-string format-arguments))
488 ;; usocket implementation
490 #-:lispworks
491 (defmethod start-listening ((acceptor acceptor))
492 (when (acceptor-listen-socket acceptor)
493 (hunchentoot-error "acceptor ~A is already listening" acceptor))
494 (setf (acceptor-listen-socket acceptor)
495 (usocket:socket-listen (or (acceptor-address acceptor)
496 usocket:*wildcard-host*)
497 (acceptor-port acceptor)
498 :reuseaddress t
499 :backlog (acceptor-listen-backlog acceptor)
500 :element-type '(unsigned-byte 8)))
501 (values))
503 #-:lispworks
504 (defmethod accept-connections ((acceptor acceptor))
505 (usocket:with-server-socket (listener (acceptor-listen-socket acceptor))
506 (loop
507 (when (acceptor-shutdown-p acceptor)
508 (return))
509 (when (usocket:wait-for-input listener :ready-only t :timeout +new-connection-wait-time+)
510 (when-let (client-connection
511 (handler-case (usocket:socket-accept listener)
512 ;; ignore condition
513 (usocket:connection-aborted-error ())))
514 (set-timeouts client-connection
515 (acceptor-read-timeout acceptor)
516 (acceptor-write-timeout acceptor))
517 (handle-incoming-connection (acceptor-taskmaster acceptor)
518 client-connection))))))
520 ;; LispWorks implementation
522 #+:lispworks
523 (defmethod start-listening ((acceptor acceptor))
524 (multiple-value-bind (listener-process startup-condition)
525 (comm:start-up-server :service (acceptor-port acceptor)
526 :address (acceptor-address acceptor)
527 :process-name (format nil "Hunchentoot listener \(~A:~A)"
528 (or (acceptor-address acceptor) "*")
529 (acceptor-port acceptor))
530 ;; this function is called once on startup - we
531 ;; use it to check for errors
532 :announce (lambda (socket &optional condition)
533 (declare (ignore socket))
534 (when condition
535 (error condition)))
536 ;; this function is called whenever a connection
537 ;; is made
538 :function (lambda (handle)
539 (unless (acceptor-shutdown-p acceptor)
540 (handle-incoming-connection
541 (acceptor-taskmaster acceptor) handle)))
542 ;; wait until the acceptor was successfully started
543 ;; or an error condition is returned
544 :wait t)
545 (when startup-condition
546 (error startup-condition))
547 (mp:process-stop listener-process)
548 (setf (acceptor-process acceptor) listener-process)
549 (values)))
551 #+:lispworks
552 (defmethod accept-connections ((acceptor acceptor))
553 (mp:process-unstop (acceptor-process acceptor))
554 nil)
556 (defmethod acceptor-dispatch-request ((acceptor acceptor) request)
557 "Detault implementation of the request dispatch method, generates an
558 +http-not-found+ error."
559 (let ((path (and (acceptor-document-root acceptor)
560 (request-pathname request))))
561 (cond
562 (path
563 (handle-static-file
564 (merge-pathnames (if (equal "/" (script-name request)) #p"index.html" path)
565 (acceptor-document-root acceptor))))
567 (setf (return-code *reply*) +http-not-found+)
568 (abort-request-handler)))))
570 (defmethod handle-request ((*acceptor* acceptor) (*request* request))
571 "Standard method for request handling. Calls the request dispatcher
572 of *ACCEPTOR* to determine how the request should be handled. Also
573 sets up standard error handling which catches any errors within the
574 handler."
575 (handler-bind ((error
576 (lambda (cond)
577 ;; if the headers were already sent, the error
578 ;; happened within the body and we have to close
579 ;; the stream
580 (when *headers-sent*
581 (setq *close-hunchentoot-stream* t))
582 (throw 'handler-done
583 (values nil cond (get-backtrace)))))
584 (warning
585 (lambda (cond)
586 (when *log-lisp-warnings-p*
587 (log-message* *lisp-warnings-log-level* "~A" cond)))))
588 (with-debugger
589 (acceptor-dispatch-request *acceptor* *request*))))
591 (defgeneric acceptor-status-message (acceptor http-status-code &key &allow-other-keys)
592 (:documentation
593 "This function is called after the request's handler has been
594 invoked to convert the HTTP-STATUS-CODE to a HTML message to be
595 displayed to the user. If this function returns a string, that
596 string is sent to the client instead of the content produced by the
597 handler, if any.
599 If an ERROR-TEMPLATE-DIRECTORY is set in the current acceptor and
600 the directory contains a file corresponding to HTTP-STATUS-CODE
601 named <code>.html, that file is sent to the client after variable
602 substitution. Variables are referenced by ${<variable-name>}.
604 Additional keyword arguments may be provided which are made
605 available to the templating logic as substitution variables. These
606 variables can be interpolated into error message templates in,
607 which contains the current URL relative to the server and without
608 GET parameters.
610 In addition to the variables corresponding to keyword arguments,
611 the script-name, lisp-implementation-type,
612 lisp-implementation-version and hunchentoot-version variables are
613 available."))
615 (defun make-cooked-message (http-status-code &key error backtrace)
616 (labels ((cooked-message (format &rest arguments)
617 (setf (content-type*) "text/html; charset=iso-8859-1")
618 (format nil "<html><head><title>~D ~A</title></head><body><h1>~:*~A</h1>~?<p><hr>~A</p></body></html>"
619 http-status-code (reason-phrase http-status-code)
620 format (mapcar (lambda (arg)
621 (if (stringp arg)
622 (escape-for-html arg)
623 arg))
624 arguments)
625 (address-string))))
626 (case http-status-code
627 ((#.+http-moved-temporarily+
628 #.+http-moved-permanently+)
629 (cooked-message "The document has moved <a href='~A'>here</a>" (header-out :location)))
630 ((#.+http-authorization-required+)
631 (cooked-message "The server could not verify that you are authorized to access the document requested. ~
632 Either you supplied the wrong credentials \(e.g., bad password), or your browser doesn't ~
633 understand how to supply the credentials required."))
634 ((#.+http-forbidden+)
635 (cooked-message "You don't have permission to access ~A on this server."
636 (script-name *request*)))
637 ((#.+http-not-found+)
638 (cooked-message "The requested URL ~A was not found on this server."
639 (script-name *request*)))
640 ((#.+http-bad-request+)
641 (cooked-message "Your browser sent a request that this server could not understand."))
642 ((#.+http-internal-server-error+)
643 (if *show-lisp-errors-p*
644 (cooked-message "<pre>~A~@[~%~%Backtrace:~%~%~A~]</pre>"
645 (escape-for-html (princ-to-string error))
646 (when *show-lisp-backtraces-p*
647 (escape-for-html (princ-to-string backtrace))))
648 (cooked-message "An error has occurred")))
650 (when (<= 400 http-status-code)
651 (cooked-message "An error has occurred"))))))
653 (defmethod acceptor-status-message ((acceptor t) http-status-code &rest args &key &allow-other-keys)
654 (apply 'make-cooked-message http-status-code args))
656 (defmethod acceptor-status-message :around ((acceptor acceptor) http-status-code &rest args &key &allow-other-keys)
657 (handler-case
658 (call-next-method)
659 (error (e)
660 (log-message* :error "error ~A during error processing, sending cooked message to client" e)
661 (apply 'make-cooked-message http-status-code args))))
663 (defun string-as-keyword (string)
664 "Intern STRING as keyword using the reader so that case conversion is done with the reader defaults."
665 (let ((*package* (find-package :keyword)))
666 (read-from-string string)))
668 (defmethod acceptor-status-message ((acceptor acceptor) http-status-code &rest properties &key &allow-other-keys)
669 "Default function to generate error message sent to the client."
670 (labels
671 ((substitute-request-context-variables (string)
672 (let ((properties (append `(:script-name ,(script-name*)
673 :lisp-implementation-type ,(lisp-implementation-type)
674 :lisp-implementation-version ,(lisp-implementation-version)
675 :hunchentoot-version ,*hunchentoot-version*)
676 properties)))
677 (unless *show-lisp-backtraces-p*
678 (setf (getf properties :backtrace) nil))
679 (cl-ppcre:regex-replace-all "(?i)\\$\\{([a-z0-9-_]+)\\}"
680 string
681 (lambda (target-string start end match-start match-end reg-starts reg-ends)
682 (declare (ignore start end match-start match-end))
683 (let ((variable-name (string-as-keyword (subseq target-string
684 (aref reg-starts 0)
685 (aref reg-ends 0)))))
686 (escape-for-html (princ-to-string (getf properties variable-name variable-name))))))))
687 (file-contents (file)
688 (let ((buf (make-string (file-length file))))
689 (read-sequence buf file)
690 buf))
691 (error-contents-from-template ()
692 (let ((error-file-template-pathname (and (acceptor-error-template-directory acceptor)
693 (probe-file (make-pathname :name (princ-to-string http-status-code)
694 :type "html"
695 :defaults (acceptor-error-template-directory acceptor))))))
696 (when error-file-template-pathname
697 (with-open-file (file error-file-template-pathname :if-does-not-exist nil :element-type 'character)
698 (when file
699 (setf (content-type*) "text/html")
700 (substitute-request-context-variables (file-contents file))))))))
701 (or (unless (< 300 http-status-code)
702 (call-next-method)) ; don't ever try template for positive return codes
703 (when *show-lisp-errors-p*
704 (error-contents-from-template)) ; try template
705 (call-next-method)))) ; fall back to cooked message
707 (defgeneric acceptor-remove-session (acceptor session)
708 (:documentation
709 "This function is called whenever a session in ACCEPTOR is being
710 destroyed because of a session timout or an explicit REMOVE-SESSION
711 call."))
713 (defmethod acceptor-remove-session ((acceptor acceptor) (session t))
714 "Default implementation for the session removal hook function. This
715 function is called whenever a session is destroyed."
716 nil)
718 (defgeneric acceptor-server-name (acceptor)
719 (:documentation "Returns a string which can be used for 'Server' headers.")
720 (:method ((acceptor acceptor))
721 (format nil "Hunchentoot ~A" *hunchentoot-version*)))