1 ;;; emacs-web-server.el --- Emacs Web Server
3 ;; Copyright (C) 2013 Eric Schulte <schulte.eric@gmail.com>
5 ;; Author: Eric Schulte <schulte.eric@gmail.com>
7 ;; License: GPLV3 (see the COPYING file in this directory)
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
14 (eval-when-compile (require 'cl))
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)))
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))))
28 (defvar ews-servers nil
29 "List holding all ews servers.")
31 (defvar ews-time-format "%Y.%m.%d.%H.%M.%S.%N"
32 "Logging time format passed to `format-time-string'.")
34 (defun ews-start (handler port &optional log-buffer &rest network-args)
35 "Start a server using HANDLER and return the server object.
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.
45 Any supplied NETWORK-ARGS are assumed to be keyword arguments for
46 `make-network-process' to which they are passed directly.
48 For example, the following starts a simple hello-world server on
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\")
59 Equivalently, the following starts an identical server using a
60 function MATCH and the `ews-response-header' convenience
65 (lambda (proc request)
66 (ews-response-header proc 200 '(\"Content-type\" . \"text/plain\"))
67 (process-send-string proc \"hello world\")
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)
76 #'make-network-process
78 :service (port server)
83 :plist (append (list :server server)
84 (when log (list :log-buffer 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))))))
95 (push server ews-servers)
98 (defun ews-stop (server)
100 (setq ews-servers (remove server ews-servers))
101 (mapc #'delete-process (append (mapcar #'car (clients server))
102 (list (process server)))))
104 (defun ews-parse (string)
105 (cl-flet ((to-keyword (s) (intern (concat ":" (upcase (match-string 1 s))))))
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))))
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))))))
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)))))))
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))
139 (setq clients (assq-delete-all proc clients))
140 (delete-process proc))))))
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))
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))))
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.
161 (setcdr (last headers)
162 (list (ews-parse-multipart/form
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.
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)))
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
197 (funcall function proc request)
198 (error (ews-error proc "Caught Error: %S" e)))))))
200 (ews-error proc "no handler matched request: %S" request)))
202 (defun ews-error (proc msg &rest args)
203 (let ((buf (plist-get (process-plist proc) :log-buffer))
204 (c (process-contact proc)))
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)
211 (apply #'format msg args)))))
212 (apply #'ews-send-500 proc msg args)))
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."
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"))))
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))
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)
243 (throw 'close-connection nil))
245 (defun ews-send-file (proc path &optional mime-type)
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
255 (insert-file-contents-literally path)
258 (provide 'emacs-web-server)
259 ;;; emacs-web-server.el ends here