]> code.delx.au - gnu-emacs-elpa/blob - emacs-web-server.el
helper to send a file with mime type
[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 'eieio)
14 (eval-when-compile (require 'cl))
15 (require 'cl-lib)
16
17 (defclass ews-server ()
18 ((handler :initarg :handler :accessor handler :initform nil)
19 (process :initarg :process :accessor process :initform nil)
20 (port :initarg :port :accessor port :initform nil)
21 (clients :initarg :clients :accessor clients :initform nil)))
22
23 (defclass ews-client ()
24 ((leftover :initarg :leftover :accessor leftover :initform "")
25 (boundary :initarg :boundary :accessor boundary :initform nil)
26 (headers :initarg :headers :accessor headers :initform (list nil))))
27
28 (defvar ews-servers nil
29 "List holding all ews servers.")
30
31 (defvar ews-time-format "%Y.%m.%d.%H.%M.%S.%N"
32 "Logging time format passed to `format-time-string'.")
33
34 (defun ews-start (handler port &optional log-buffer &rest network-args)
35 "Start a server using HANDLER and return the server object.
36
37 HANDLER should be a list of cons of the form (MATCH . ACTION),
38 where MATCH is either a function (in which case it is called on
39 the request object) or a cons cell of the form (KEYWORD . STRING)
40 in which case STRING is matched against the value of the header
41 specified by KEYWORD. In either case when MATCH returns non-nil,
42 then the function ACTION is called with two arguments, the
43 process and the request object.
44
45 Any supplied NETWORK-ARGS are assumed to be keyword arguments for
46 `make-network-process' to which they are passed directly.
47
48 For example, the following starts a simple hello-world server on
49 port 8080.
50
51 (ews-start
52 '(((:GET . \".*\") .
53 (lambda (proc request)
54 (process-send-string proc
55 \"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello world\r\n\")
56 t)))
57 8080)
58
59 Equivalently, the following starts an identical server using a
60 function MATCH and the `ews-response-header' convenience
61 function.
62
63 (ews-start
64 '(((lambda (_) t) .
65 (lambda (proc request)
66 (ews-response-header proc 200 '(\"Content-type\" . \"text/plain\"))
67 (process-send-string proc \"hello world\")
68 t)))
69 8080)
70
71 "
72 (let ((server (make-instance 'ews-server :handler handler :port port))
73 (log (when log-buffer (get-buffer-create log-buffer))))
74 (setf (process server)
75 (apply
76 #'make-network-process
77 :name "ews-server"
78 :service (port server)
79 :filter 'ews-filter
80 :server t
81 :nowait t
82 :family 'ipv4
83 :plist (append (list :server server)
84 (when log (list :log-buffer log)))
85 :log (when log
86 (lambda (proc client message)
87 (let ((c (process-contact client))
88 (buf (plist-get (process-plist proc) :log-buffer)))
89 (with-current-buffer buf
90 (goto-char (point-max))
91 (insert (format "%s\t%s\t%s\t%s"
92 (format-time-string ews-time-format)
93 (first c) (second c) message))))))
94 network-args))
95 (push server ews-servers)
96 server))
97
98 (defun ews-stop (server)
99 "Stop SERVER."
100 (setq ews-servers (remove server ews-servers))
101 (mapc #'delete-process (append (mapcar #'car (clients server))
102 (list (process server)))))
103
104 (defun ews-parse (string)
105 (cl-flet ((to-keyword (s) (intern (concat ":" (upcase (match-string 1 s))))))
106 (cond
107 ((string-match
108 "^\\(GET\\|POST\\) \\([^[:space:]]+\\) \\([^[:space:]]+\\)$" string)
109 (list (cons (to-keyword (match-string 1 string)) (match-string 2 string))
110 (cons :TYPE (match-string 3 string))))
111 ((string-match "^\\([^[:space:]]+\\): \\(.*\\)$" string)
112 (list (cons (to-keyword string) (match-string 2 string))))
113 (:otherwise (ews-error proc "bad header: %S" string) nil))))
114
115 (defun ews-trim (string)
116 (while (and (> (length string) 0)
117 (or (and (string-match "[\r\n]" (substring string -1))
118 (setq string (substring string 0 -1)))
119 (and (string-match "[\r\n]" (substring string 0 1))
120 (setq string (substring string 1))))))
121 string)
122
123 (defun ews-parse-multipart/form (string)
124 ;; ignore empty and non-content blocks
125 (when (string-match "Content-Disposition:[[:space:]]*\\(.*\\)\r\n" string)
126 (let ((dp (mail-header-parse-content-disposition (match-string 1 string))))
127 (cons (cdr (assoc 'name (cdr dp)))
128 (ews-trim (substring string (match-end 0)))))))
129
130 (defun ews-filter (proc string)
131 (with-slots (handler clients) (plist-get (process-plist proc) :server)
132 (unless (assoc proc clients)
133 (push (cons proc (make-instance 'ews-client)) clients))
134 (let ((client (cdr (assoc proc clients))))
135 (when (ews-do-filter client string)
136 (when (not (eq (catch 'close-connection
137 (ews-call-handler proc (cdr (headers client)) handler))
138 :keep-open))
139 (setq clients (assq-delete-all proc clients))
140 (delete-process proc))))))
141
142 (defun ews-do-filter (client string)
143 "Return non-nil when finished and the client may be deleted."
144 (with-slots (leftover boundary headers) client
145 (let ((pending (concat leftover string))
146 (delimiter (if boundary
147 (regexp-quote (concat "\r\n--" boundary))
148 "\r\n"))
149 (last-index 0) index tmp-index)
150 (catch 'finished-parsing-headers
151 ;; parse headers and append to client
152 (while (setq index (string-match delimiter pending last-index))
153 (let ((tmp (+ index (length delimiter))))
154 (cond
155 ;; Double \r\n outside of post data means we are done
156 ;; w/headers and should call the handler.
157 ((= last-index index)
158 (throw 'finished-parsing-headers t))
159 ;; Build up multipart data.
160 (boundary
161 (setcdr (last headers)
162 (list (ews-parse-multipart/form
163 (ews-trim
164 (substring pending last-index index)))))
165 ;; a boundary suffixed by "--" indicates the end of the headers
166 (when (and (> (length pending) (+ tmp 2))
167 (string= (substring pending tmp (+ tmp 2)) "--"))
168 (throw 'finished-parsing-headers t)))
169 ;; Standard header parsing.
170 (:otherwise
171 (let ((this (ews-parse (substring pending last-index index))))
172 (if (and (caar this) (eql (caar this) :CONTENT-TYPE))
173 (cl-destructuring-bind (type &rest data)
174 (mail-header-parse-content-type (cdar this))
175 (unless (string= type "multipart/form-data")
176 (ews-error proc "TODO: handle content type: %S" type))
177 (when (assoc 'boundary data)
178 (setq boundary (cdr (assoc 'boundary data)))
179 (setq delimiter (concat "\r\n--" boundary))))
180 (setcdr (last headers) this)))))
181 (setq last-index tmp)))
182 (setq leftover (ews-trim (substring pending last-index)))
183 nil))))
184
185 (defun ews-call-handler (proc request handler)
186 (catch 'matched-handler
187 (mapc (lambda (handler)
188 (let ((match (car handler))
189 (function (cdr handler)))
190 (when (or (and (consp match)
191 (assoc (car match) request)
192 (string-match (cdr match)
193 (cdr (assoc (car match) request))))
194 (and (functionp match) (funcall match request)))
195 (throw 'matched-handler
196 (condition-case e
197 (funcall function proc request)
198 (error (ews-error proc "Caught Error: %S" e)))))))
199 handler)
200 (ews-error proc "no handler matched request: %S" request)))
201
202 (defun ews-error (proc msg &rest args)
203 (let ((buf (plist-get (process-plist proc) :log-buffer))
204 (c (process-contact proc)))
205 (when buf
206 (with-current-buffer buf
207 (goto-char (point-max))
208 (insert (format "%s\t%s\t%s\tEWS-ERROR: %s"
209 (format-time-string ews-time-format)
210 (first c) (second c)
211 (apply #'format msg args)))))
212 (apply #'ews-send-500 proc msg args)))
213
214 \f
215 ;;; Convenience functions to write responses
216 (defun ews-response-header (proc code &rest header)
217 "Send the headers for an HTTP response to PROC.
218 Currently CODE should be an HTTP status code, see
219 `ews-status-codes' for a list of known codes."
220 (let ((headers
221 (cons
222 (format "HTTP/1.1 %d %s" code (cdr (assoc code ews-status-codes)))
223 (mapcar (lambda (h) (format "%s: %s" (car h) (cdr h))) header))))
224 (setcdr (last headers) (list "" ""))
225 (process-send-string proc (mapconcat #'identity headers "\r\n"))))
226
227 (defun ews-send-500 (proc &rest msg-and-args)
228 "Send 500 \"Internal Server Error\" to PROC with an optional message."
229 (ews-response-header proc 500
230 '("Content-type" . "text/plain"))
231 (process-send-string proc (if msg-and-args
232 (apply #'format msg-and-args)
233 "500 Internal Server Error"))
234 (throw 'close-connection nil))
235
236 (defun ews-send-404 (proc &rest msg-and-args)
237 "Send 404 \"Not Found\" to PROC with an optional message."
238 (ews-response-header proc 404
239 '("Content-type" . "text/plain"))
240 (process-send-string proc (if msg-and-args
241 (apply #'format msg-and-args)
242 "404 Not Found"))
243 (throw 'close-connection nil))
244
245 (defun ews-send-file (proc path &optional mime-type)
246 "Send PATH to PROC.
247 Optionally explicitly set MIME-TYPE, otherwise it is guessed by
248 `mm-default-file-encoding'."
249 (let ((mime (or mime-type
250 (mm-default-file-encoding path)
251 "application/octet-stream")))
252 (ews-response-header proc 200 (cons "Content-type" mime))
253 (process-send-string proc
254 (with-temp-buffer
255 (insert-file-contents-literally path)
256 (buffer-string)))))
257
258 (provide 'emacs-web-server)
259 ;;; emacs-web-server.el ends here