r5549: *** empty log message ***
[wol.git] / project.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: wol -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          project.lisp
6 ;;;; Purpose:       Project handler for wol library
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  July 2003
9 ;;;;
10 ;;;; $Id: project.lisp,v 1.13 2003/08/10 17:56:44 kevin Exp $
11 ;;;;
12 ;;;; This file and Wol are Copyright (c) 2001-2003 by Kevin M. Rosenberg
13 ;;;; *************************************************************************
14
15 (in-package #:wol)
16
17 (defun wol-project (name &key (project-prefix "/") map index
18                               (sessions t) (session-lifetime 18000)
19                               (reap-interval 300) server
20                               (connector :modlisp)
21                               timeout)
22   (unless server
23     (setq server 
24           (ecase connector
25             (:modlisp ml:*ml-server*)
26             (:aserve net.aserve:*wserver*))))
27   
28   (unless server
29     (warn "Can't start project without server")
30     (return-from wol-project nil))
31   
32   (multiple-value-bind (project found) (gethash name *active-projects*)
33     (unless found
34       (setq project (make-instance 'wol-project))
35       (setf (gethash name *active-projects*) project))
36     
37     (setf (project-name project) name)
38     (setf (project-prefix project) project-prefix)
39     (setf (project-map project) map)
40     (setf (project-index project) index) 
41     (setf (project-server project) server)
42     (setf (project-connector project) connector)
43     (setf (lifetime (session-master project)) session-lifetime)
44     (setf (cookie-name (session-master project)) name)
45
46     (let ((hash (make-hash-table :size (length map) :test 'equal)))
47       (dolist (map-item map)
48         (setf (gethash (first map-item) hash) (second map-item)))
49       (setf (project-hash-map project) hash))
50
51     (ecase connector
52       (:modlisp
53        (setf (ml::processor server) 'wol-ml-processor))
54       (:aserve
55        (net.aserve:publish-prefix :prefix project-prefix
56                                   :server server
57                                   :function 'wol-aserve-processor
58                                   :timeout timeout)))
59   
60   (if sessions
61         (when (null (sessions (session-master project)))
62           (setf (sessions (session-master project))
63             (make-hash-table :test 'eq)))
64       (when (sessions (session-master project))
65         (setf (sessions (session-master project)) nil)))
66
67     (setq *reap-interval* reap-interval)
68     (when (and sessions (null *reaper-process*))
69       (setq *reaper-process* (start-reaper)))))
70
71 (defun wol-ml-processor (command)
72   "Processes an incoming modlisp command"
73   (let* ((req (command->request command
74                                 :ml-server *ml-server*))
75          (ent (make-entity-for-request req)))
76     (if ent
77         (dispatch-request req ent)
78         (no-url-handler req ent))))
79
80
81 (defun wol-aserve-processor (as-req as-ent)
82   "Processes an incoming modlisp command"
83   (multiple-value-bind (req ent) (make-request/ent-from-aserve as-req as-ent)
84     (if (entity-project ent)
85         (dispatch-request req ent)
86       (no-url-handler req ent))))
87
88     
89 (defun make-request/ent-from-aserve (as-req as-ent)
90   (let* ((req (make-instance
91                'http-request
92                :method (net.aserve:request-method as-req)
93                ;;:host (net.aserve:request-host as-req)
94                :raw-request (net.aserve::request-raw-request as-req)
95                :raw-uri (puri:intern-uri
96                          (net.uri:render-uri
97                          (net.aserve:request-raw-uri as-req) nil))
98                :decoded-uri-path
99                (net.aserve::request-decoded-uri-path as-req)
100                :uri (puri:intern-uri
101                      (net.uri:render-uri
102                      (net.aserve:request-uri as-req) nil))
103                :protocol (net.aserve:request-protocol as-req)
104                :protocol-string
105                (net.aserve:request-protocol-string as-req)
106                :posted-content (net.aserve::request-request-body as-req)
107                :socket (net.aserve:request-socket as-req)
108                :headers (net.aserve::request-headers as-req)
109                :aserve-server net.aserve:*wserver*
110                :aserve-request as-req))
111          (project (find-project-for-request req))
112          (ent (make-instance 'entity :project project
113                              :aserve-entity as-ent)))
114     (values req ent)))
115
116
117 (defun command->request (command &key ml-server)
118   "Convert a cl-modlisp command into a wol request"
119   (let ((req
120          (make-instance 'http-request
121            :host (header-value command :host)
122            :raw-request (header-value command :url) 
123            :raw-uri  (puri:intern-uri (header-value command :url))
124            :uri (puri:intern-uri (command->uri command))
125            :protocol (ensure-keyword
126                       (header-value command :server-protocol))
127            :protocol-string (header-value command :server-protocol)
128            :method (ensure-keyword (header-value command :method))
129            :posted-content (header-value command :posted-content)
130            :headers command
131            :socket *modlisp-socket*
132            :ml-server ml-server)))
133     (awhen (request-raw-uri req)
134            (setf (request-decoded-uri-path req) (puri:uri-path it)))
135     req))
136
137 (defun header-slot-value (req slot)
138   (header-value (request-headers req) slot))
139
140 (defun command->uri (command)
141   (format nil "http://~A:~D~A"
142           (header-value command :host)
143           (header-value command :server-ip-port)
144           (header-value command :url)))
145
146 (defun is-index-request (req ent)
147   (string= (request-decoded-uri-path req)
148            (project-prefix (entity-project ent))))
149
150 (defun set-cookie (req ent)
151   (let ((session (websession-from-req req)))
152     (when (and session (websession-key session)
153                (not (eq :url (websession-method session))))
154       (let ((proj (entity-project ent)))
155         (ecase (project-connector proj)
156           (:aserve
157            (net.aserve:set-cookie-header (aserve-request req)
158                                          :name (project-name
159                                                 (entity-project ent))
160                                          :expires :never
161                                          :secure nil
162                                          :domain ".b9.com"
163                                          :value (websession-key
164                                                  (websession-from-req req))
165                                          :path "/"))
166           (:modlisp
167            ;; fixme
168            ))))))
169
170
171 (defun redirect-entity (page req ent &optional plist)
172   (let ((proj (entity-project ent))
173         (url (render-uri
174               (copy-uri (request-uri req)
175                         :path (make-wol-url page req ent plist))
176               nil)))
177     (ecase (project-connector proj)
178       (:aserve
179        (net.aserve:with-http-response 
180            ((aserve-request req) 
181             (entity-aserve-entity ent)
182             :response net.aserve:*response-temporary-redirect*)
183          (set-cookie req ent)
184          (net.aserve:with-http-body 
185              ((aserve-request req) 
186               (entity-aserve-entity ent)
187               :headers `((:location . ,url))))))
188       (:modlisp
189        (redirect-to-location url)))))
190
191 (defun dispatch-request (req ent)
192   (setq *req* req)
193   (setq *ent* ent)
194   (let ((proj (entity-project ent)))
195     (if (is-index-request req ent)
196         (redirect-entity (project-index proj) req ent)
197         (progn
198           (compute-uris req ent)
199           (dispatch-to-handler req ent)))))
200
201 (defun make-entity (&key project)
202   (make-instance 'entity :project project))
203
204 (defun make-entity-for-request (req)
205   (awhen (find-project-for-request req)
206          (make-entity :project it)))
207
208 (defun find-project-for-request (req)
209   (maphash (lambda (name project)
210              (declare (ignore name))
211              (when (and (eq (project-server project)
212                             (or (request-aserve-server req)
213                                 (request-ml-server req)))
214                         (request-matches-prefix
215                          req (project-prefix project)))
216                (return-from find-project-for-request project)))
217            *active-projects*))
218
219 (defun request-matches-prefix (req prefix)
220   "Returns project if request matches project"
221   (string-starts-with prefix (request-decoded-uri-path req)))
222
223
224 (defun dispatch-to-handler (req ent)
225   (let ((handler (request-find-handler req ent))
226         (*wol-stream* (request-socket req)))
227     (if handler
228         (handle-request handler req ent)
229       (no-url-handler req ent))))
230
231 (defun request-find-handler (req ent)
232   (nth-value 0 (gethash (request-page req) 
233                         (project-hash-map (entity-project ent)))))
234
235 (defun handle-request (handler req ent)
236   (typecase handler
237     (null
238      nil)
239     ((or symbol function)
240      (when (and (symbolp handler)
241                 (not (fboundp handler)))
242        (cmsg "handler given a symbol without a function ~S" handler)
243        (return-from handle-request nil))
244      (let ((next-page (funcall handler req ent)))
245        (typecase next-page
246          (string
247           (redirect-entity next-page req ent))
248          (cons
249           (redirect-entity (car next-page) req ent (cadr next-page)))
250          (null
251           t)
252          (t
253           (cmsg "handler should return nil or a string, not ~S" next-page))))
254      t)
255     (string
256      (cmsg "string handler not supported: ~A" handler)
257      nil)
258     (t
259      (cmsg "unknown handler type: ~S" handler)
260      nil)))
261
262
263
264 (defun wol-version-string ()
265   (format nil "~{~D~^.~}" *wol-version*))
266
267 (defun alist-key->keyword (alist)
268   (loop for a in alist
269       collect (cons (kmrcl:ensure-keyword (car a)) (cdr a))))
270
271 (defun request-query (req &key (uri t) (post t))
272   (aif (aserve-request req)
273        (alist-key->keyword
274         (net.aserve:request-query it :uri uri :post post))
275     (let ((desired (cons uri post)))
276       (if (equal desired (request-desired-query req))
277           ;; Same desired as cached 
278           (request-query-alist req)
279         (progn
280           (setf (request-desired-query req) desired)
281           (setf (request-query-alist req)
282             (append
283              (when (and uri (request-uri-query req))
284                (query-to-alist (request-uri-query req)))
285              (when (and post (request-posted-content req))
286                (query-to-alist (request-posted-content req))))))))))
287
288 (defun request-query-value (key req &key (uri t) (post t))
289   (aif (aserve-request req)
290        (net.aserve:request-query-value (string key) it :uri uri :post post)
291        (cdr (assoc key (request-query req :uri uri :post post)
292                    :test 'equal))))
293     
294 (defun websession-variable (ws name)
295   (when ws
296     (gethash name (websession-variables ws))))
297
298 (defun (setf websession-variable) (value ws name)
299   (when ws
300     (setf (gethash name (websession-variables ws)) value)))
301
302
303 (defmacro with-wol-page ((req ent
304                           &key (format :html) (precompute t) headers
305                                (response-code 200)
306                                timeout)
307                          &body body)
308   `(if (request-aserve-server ,req)
309       (net.aserve:with-http-response 
310           ((aserve-request ,req) 
311            (entity-aserve-entity ,ent)
312            :content-type (ml::format-string ,format)
313            :timeout ,timeout
314            :response
315            (case ,response-code
316              (302 net.aserve::*response-moved-permanently*)
317              (307 net.aserve::*response-temporary-redirect*)
318              (404 net.aserve::*response-not-found*)
319              (otherwise net.aserve::*response-ok*)))
320         (set-cookie ,req ,ent)
321           (net.aserve:with-http-body 
322               ((aserve-request ,req) 
323                (entity-aserve-entity ,ent)
324                :headers ,headers)
325             (let ((*html-stream* net.html.generator:*html-stream*))
326               ,@body)))
327      (%with-wol-page (,req ,ent :format ,format :precompute ,precompute
328                            :headers ,headers 
329                            :response-string 
330                            (case ,response-code
331                              (302 "302 Moved Permanently")
332                              (307 "307 Temporary Redirect")
333                              (404 "404 Not Found")
334                               (otherwise "200 OK")))
335                      ,@body)))
336   
337
338 (defmacro %with-wol-page ((req ent
339                            &key (format :html) (precompute t) headers
340                                 (response-string "200 OK"))
341                          &body body)
342   (declare (ignore req ent))
343   (let ((fmt (gensym "FMT-"))
344         (precomp (gensym "PRE-"))
345         (result (gensym "RES-"))
346         (outstr (gensym "STR-"))
347         (stream (gensym "STRM-"))
348         (hdr (gensym "HDR-")))
349     `(let ((,fmt ,format)
350            (,precomp ,precompute)
351            ,result ,outstr ,stream)
352        (declare (ignorable ,stream))
353        (write-header-line "Status" ,response-string)
354        (write-header-line "Content-Type" (ml::format-string ,fmt))
355        (dolist (,hdr ,headers)
356          (write-header-line (car ,hdr) (cdr ,hdr)))
357        (unless ,precomp
358          (write-string "end" *wol-stream*)
359          (write-char #\NewLine *wol-stream*))
360        (setq ,outstr
361          (with-output-to-string (,stream)
362            (let ((*html-stream* (if ,precomp
363                                    ,stream
364                                    *wol-stream*))
365                  (*wol-stream* (if ,precomp
366                                    ,stream
367                                    *wol-stream*)))
368              (setq ,result (progn ,@body)))))
369        (cond
370         (,precomp
371          (write-header-line "Content-Length" 
372                             (write-to-string (length ,outstr)))
373          (write-header-line "Keep-Socket" "1")
374          (write-header-line "Connection" "Keep-Alive")
375          (write-string "end" *wol-stream*)
376          (write-char #\NewLine *wol-stream*)
377          (write-string ,outstr *wol-stream*)
378          (finish-output *wol-stream*)
379          (setq *close-modlisp-socket* nil))
380         (t
381          (finish-output *wol-stream*)
382          (setq *close-modlisp-socket* t)))
383        ,result)))
384
385
386 (defun no-url-handler (req ent)
387   (with-wol-page (req ent :response-code 404)
388     (html
389      (:html
390       (:head
391        (:title "404 - NotFound"))
392       (:body
393        (:h1 "Not Found")
394        (:p "The request for "
395            (:b (:write-string (render-uri (request-uri req) nil)))
396            " was not found on this server.")
397        (:hr)
398        (:div (:i "WOL "
399                  (:write-string (wol-version-string)))))))))