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