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