]> code.delx.au - gnu-emacs-elpa/blob - emacs-web-server.el
MAYBE incremental handler calls
[gnu-emacs-elpa] / emacs-web-server.el
1 ;;; emacs-web-server.el --- Emacs Web Server
2
3 ;; Copyright (C) 2013 Eric Schulte <schulte.eric@gmail.com>
4
5 ;; Author: Eric Schulte <schulte.eric@gmail.com>
6 ;; Keywords: http
7 ;; License: GPLV3 (see the COPYING file in this directory)
8
9 ;;; Code:
10 (require 'emacs-web-server-status-codes)
11 (require 'mail-parse) ; to parse multipart data in headers
12 (require 'mm-encode) ; to look-up mime types for files
13 (require 'url-util) ; to decode url-encoded params
14 (require 'eieio)
15 (eval-when-compile (require 'cl))
16 (require 'cl-lib)
17
18 (defclass ews-server ()
19 ((handlers :initarg :handlers :accessor handlers :initform nil)
20 (process :initarg :process :accessor process :initform nil)
21 (port :initarg :port :accessor port :initform nil)
22 (requests :initarg :requests :accessor requests :initform nil)))
23
24 (defclass ews-request ()
25 ((process :initarg :process :accessor process :initform nil)
26 (pending :initarg :pending :accessor pending :initform "")
27 (context :initarg :context :accessor context :initform nil)
28 (boundary :initarg :boundary :accessor boundary :initform nil)
29 (headers :initarg :headers :accessor headers :initform (list nil))))
30
31 (defvar ews-servers nil
32 "List holding all ews servers.")
33
34 (defvar ews-log-time-format "%Y.%m.%d.%H.%M.%S.%N"
35 "Logging time format passed to `format-time-string'.")
36
37 (defun ews-start (handlers port &optional log-buffer &rest network-args)
38 "Start a server using HANDLERS and return the server object.
39
40 HANDLERS should be a list of cons of the form (MATCH . ACTION),
41 where MATCH is either a function (in which case it is called on
42 the request object) or a cons cell of the form (KEYWORD . STRING)
43 in which case STRING is matched against the value of the header
44 specified by KEYWORD. In either case when MATCH returns non-nil,
45 then the function ACTION is called with two arguments, the
46 process and the request object.
47
48 Any supplied NETWORK-ARGS are assumed to be keyword arguments for
49 `make-network-process' to which they are passed directly.
50
51 For example, the following starts a simple hello-world server on
52 port 8080.
53
54 (ews-start
55 '(((:GET . \".*\") .
56 (lambda (proc request)
57 (process-send-string proc
58 \"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello world\r\n\")
59 t)))
60 8080)
61
62 Equivalently, the following starts an identical server using a
63 function MATCH and the `ews-response-header' convenience
64 function.
65
66 (ews-start
67 '(((lambda (_) t) .
68 (lambda (proc request)
69 (ews-response-header proc 200 '(\"Content-type\" . \"text/plain\"))
70 (process-send-string proc \"hello world\")
71 t)))
72 8080)
73
74 "
75 (let ((server (make-instance 'ews-server :handlers handlers :port port))
76 (log (when log-buffer (get-buffer-create log-buffer))))
77 (setf (process server)
78 (apply
79 #'make-network-process
80 :name "ews-server"
81 :service (port server)
82 :filter 'ews-filter
83 :server t
84 :nowait t
85 :family 'ipv4
86 :plist (append (list :server server)
87 (when log (list :log-buffer log)))
88 :log (when log
89 (lambda (proc request message)
90 (let ((c (process-contact request))
91 (buf (plist-get (process-plist proc) :log-buffer)))
92 (with-current-buffer buf
93 (goto-char (point-max))
94 (insert (format "%s\t%s\t%s\t%s"
95 (format-time-string ews-log-time-format)
96 (first c) (second c) message))))))
97 network-args))
98 (push server ews-servers)
99 server))
100
101 (defun ews-stop (server)
102 "Stop SERVER."
103 (setq ews-servers (remove server ews-servers))
104 (mapc #'delete-process (append (mapcar #'car (requests server))
105 (list (process server)))))
106
107 (defvar ews-http-common-methods '(GET HEAD POST PUT DELETE TRACE)
108 "HTTP methods from http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.")
109
110 (defvar ews-http-method-rx
111 (format "^\\(%s\\) \\([^[:space:]]+\\) \\([^[:space:]]+\\)$"
112 (mapconcat #'symbol-name ews-http-common-methods "\\|")))
113
114 (defun ews-parse-query-string (string)
115 "Thin wrapper around `url-parse-query-string'."
116 (mapcar (lambda (pair) (cons (first pair) (second pair)))
117 (url-parse-query-string string nil 'allow-newlines)))
118
119 (defun ews-parse (proc string)
120 (cl-flet ((to-keyword (s) (intern (concat ":" (upcase (match-string 1 s))))))
121 (cond
122 ((string-match ews-http-method-rx string)
123 (let ((method (to-keyword (match-string 1 string)))
124 (url (match-string 2 string)))
125 (if (string-match "?" url)
126 (cons (cons method (substring url 0 (match-beginning 0)))
127 (ews-parse-query-string
128 (url-unhex-string (substring url (match-end 0)))))
129 (list (cons method url)))))
130 ((string-match "^\\([^[:space:]]+\\): \\(.*\\)$" string)
131 (list (cons (to-keyword string) (match-string 2 string))))
132 (:otherwise (ews-error proc "bad header: %S" string) nil))))
133
134 (defun ews-trim (string)
135 (while (and (> (length string) 0)
136 (or (and (string-match "[\r\n]" (substring string -1))
137 (setq string (substring string 0 -1)))
138 (and (string-match "[\r\n]" (substring string 0 1))
139 (setq string (substring string 1))))))
140 string)
141
142 (defun ews-parse-multipart/form (string)
143 ;; ignore empty and non-content blocks
144 (when (string-match "Content-Disposition:[[:space:]]*\\(.*\\)\r\n" string)
145 (let ((dp (mail-header-parse-content-disposition (match-string 1 string))))
146 (cons (cdr (assoc 'name (cdr dp)))
147 (ews-trim (substring string (match-end 0)))))))
148
149 (defun ews-filter (proc string)
150 (with-slots (handlers requests) (plist-get (process-plist proc) :server)
151 (unless (cl-find-if (lambda (c) (equal proc (process c))) requests)
152 (push (make-instance 'ews-request :process proc) requests))
153 (let ((request (cl-find-if (lambda (c) (equal proc (process c))) requests)))
154 (with-slots (pending) request (setq pending (concat pending string)))
155 (when (not (eq (catch 'close-connection
156 (if (ews-parse-request request string)
157 (ews-call-handler request handlers)
158 :keep-open))
159 :keep-open))
160 (setq requests (cl-remove-if (lambda (r) (eql proc (process r))) requests))
161 (delete-process proc)))))
162
163 (defun ews-parse-request (request string)
164 "Parse request STRING from REQUEST with process PROC.
165 Return non-nil only when parsing is complete."
166 (with-slots (process pending context boundary headers) request
167 (setq pending (concat pending string))
168 (let ((delimiter (concat "\r\n" (if boundary (concat "--" boundary) "")))
169 ;; Track progress through string, always work with the
170 ;; section of string between LAST-INDEX and INDEX.
171 (last-index 0) index)
172 (catch 'finished-parsing-headers
173 ;; parse headers and append to request
174 (while (setq index (string-match delimiter pending last-index))
175 (let ((tmp (+ index (length delimiter))))
176 (if (= last-index index) ; double \r\n ends current run of headers
177 (case context
178 ;; Parse URL data.
179 ;; http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
180 (application/x-www-form-urlencoded
181 (mapc (lambda (pair) (setcdr (last headers) (list pair)))
182 (ews-parse-query-string
183 (replace-regexp-in-string
184 "\\+" " "
185 (ews-trim (substring pending last-index)))))
186 (throw 'finished-parsing-headers t))
187 ;; Set custom delimiter for multipart form data.
188 (multipart/form-data
189 (setq delimiter (concat "\r\n--" boundary)))
190 ;; No special context so we're done.
191 (t (throw 'finished-parsing-headers t)))
192 (if (eql context 'multipart/form-data)
193 (progn
194 (setcdr (last headers)
195 (list (ews-parse-multipart/form
196 (ews-trim
197 (substring pending last-index index)))))
198 ;; Boundary suffixed by "--" indicates end of the headers.
199 (when (and (> (length pending) (+ tmp 2))
200 (string= (substring pending tmp (+ tmp 2)) "--"))
201 (throw 'finished-parsing-headers t)))
202 ;; Standard header parsing.
203 (let ((header (ews-parse process (substring pending
204 last-index index))))
205 ;; Content-Type indicates that the next double \r\n
206 ;; will be followed by a special type of content which
207 ;; will require special parsing. Thus we will note
208 ;; the type in the CONTEXT variable for parsing
209 ;; dispatch above.
210 (if (and (caar header) (eql (caar header) :CONTENT-TYPE))
211 (cl-destructuring-bind (type &rest data)
212 (mail-header-parse-content-type (cdar header))
213 (setq boundary (cdr (assoc 'boundary data)))
214 (setq context (intern (downcase type))))
215 ;; All other headers are collected directly.
216 (setcdr (last headers) header)))))
217 (setq last-index tmp)))
218 (setq pending (ews-trim (substring pending last-index)))
219 nil))))
220
221 (defun ews-call-handler (request handlers)
222 (catch 'matched-handler
223 (mapc (lambda (handler)
224 (let ((match (car handler))
225 (function (cdr handler)))
226 (when (or (and (consp match)
227 (assoc (car match) (headers request))
228 (string-match (cdr match)
229 (cdr (assoc (car match)
230 (headers request)))))
231 (and (functionp match) (funcall match request)))
232 (throw 'matched-handler
233 (condition-case e (funcall function request)
234 (error (ews-error (process request)
235 "Caught Error: %S" e)))))))
236 handlers)
237 (ews-error (process request) "no handler matched request: %S"
238 (headers request))))
239
240 (defun ews-error (proc msg &rest args)
241 (let ((buf (plist-get (process-plist proc) :log-buffer))
242 (c (process-contact proc)))
243 (when buf
244 (with-current-buffer buf
245 (goto-char (point-max))
246 (insert (format "%s\t%s\t%s\tEWS-ERROR: %s"
247 (format-time-string ews-log-time-format)
248 (first c) (second c)
249 (apply #'format msg args)))))
250 (apply #'ews-send-500 proc msg args)))
251
252 \f
253 ;;; Convenience functions to write responses
254 (defun ews-response-header (proc code &rest header)
255 "Send the headers for an HTTP response to PROC.
256 Currently CODE should be an HTTP status code, see
257 `ews-status-codes' for a list of known codes."
258 (let ((headers
259 (cons
260 (format "HTTP/1.1 %d %s" code (cdr (assoc code ews-status-codes)))
261 (mapcar (lambda (h) (format "%s: %s" (car h) (cdr h))) header))))
262 (setcdr (last headers) (list "" ""))
263 (process-send-string proc (mapconcat #'identity headers "\r\n"))))
264
265 (defun ews-send-500 (proc &rest msg-and-args)
266 "Send 500 \"Internal Server Error\" to PROC with an optional message."
267 (ews-response-header proc 500
268 '("Content-type" . "text/plain"))
269 (process-send-string proc (if msg-and-args
270 (apply #'format msg-and-args)
271 "500 Internal Server Error"))
272 (throw 'close-connection nil))
273
274 (defun ews-send-404 (proc &rest msg-and-args)
275 "Send 404 \"Not Found\" to PROC with an optional message."
276 (ews-response-header proc 404
277 '("Content-type" . "text/plain"))
278 (process-send-string proc (if msg-and-args
279 (apply #'format msg-and-args)
280 "404 Not Found"))
281 (throw 'close-connection nil))
282
283 (defun ews-send-file (proc path &optional mime-type)
284 "Send PATH to PROC.
285 Optionally explicitly set MIME-TYPE, otherwise it is guessed by
286 `mm-default-file-encoding'."
287 (let ((mime (or mime-type
288 (mm-default-file-encoding path)
289 "application/octet-stream")))
290 (ews-response-header proc 200 (cons "Content-type" mime))
291 (process-send-string proc
292 (with-temp-buffer
293 (insert-file-contents-literally path)
294 (buffer-string)))))
295
296 (defun ews-in-directory-p (parent path)
297 "Check if PATH is under the PARENT directory.
298 If so return PATH, if not return nil."
299 (let ((expanded (expand-file-name path parent)))
300 (and (>= (length expanded) (length parent))
301 (string= parent (substring expanded 0 (length parent)))
302 expanded)))
303
304 (provide 'emacs-web-server)
305 ;;; emacs-web-server.el ends here