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