1 ;;; web-server.el --- Emacs Web Server
3 ;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte <schulte.eric@gmail.com>
6 ;; Maintainer: Eric Schulte <schulte.eric@gmail.com>
8 ;; Package-Requires: ((emacs "24.3"))
9 ;; Keywords: http, server, network
10 ;; URL: https://github.com/eschulte/emacs-web-server
12 ;; This software is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This software is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; A web server in Emacs running handlers written in Emacs Lisp.
29 ;; Full support for GET and POST requests including URL-encoded
30 ;; parameters and multipart/form data. Supports web sockets.
32 ;; See the examples/ directory for examples demonstrating the usage of
33 ;; the Emacs Web Server. The following launches a simple "hello
37 ;; '(((lambda (_) t) . ; match every request
38 ;; (lambda (request) ; reply with "hello world"
39 ;; (with-slots (process) request
40 ;; (ws-response-header process 200 '("Content-type" . "text/plain"))
41 ;; (process-send-string process "hello world")))))
45 (require 'web-server-status-codes)
46 (require 'mail-parse) ; to parse multipart data in headers
47 (require 'mm-encode) ; to look-up mime types for files
48 (require 'url-util) ; to decode url-encoded params
50 (eval-when-compile (require 'cl))
53 (defclass ws-server ()
54 ((handlers :initarg :handlers :accessor handlers :initform nil)
55 (process :initarg :process :accessor process :initform nil)
56 (port :initarg :port :accessor port :initform nil)
57 (requests :initarg :requests :accessor requests :initform nil)))
59 (defclass ws-request ()
60 ((process :initarg :process :accessor process :initform nil)
61 (pending :initarg :pending :accessor pending :initform "")
62 (context :initarg :context :accessor context :initform nil)
63 (boundary :initarg :boundary :accessor boundary :initform nil)
64 (index :initarg :index :accessor index :initform 0)
65 (active :initarg :active :accessor active :initform nil)
66 (headers :initarg :headers :accessor headers :initform (list nil))))
68 (defvar ws-servers nil
69 "List holding all web servers.")
71 (defvar ws-log-time-format "%Y.%m.%d.%H.%M.%S.%N"
72 "Logging time format passed to `format-time-string'.")
74 (defvar ws-guid "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
75 "This GUID is defined in RFC6455.")
78 (defun ws-start (handlers port &optional log-buffer &rest network-args)
79 "Start a server using HANDLERS and return the server object.
81 HANDLERS may be a single function (which is then called on every
82 request) or a list of conses of the form (MATCHER . FUNCTION),
83 where the FUNCTION associated with the first successful MATCHER
84 is called. Handler functions are called with two arguments, the
85 process and the request object.
87 A MATCHER may be either a function (in which case it is called on
88 the request object) or a cons cell of the form (KEYWORD . STRING)
89 in which case STRING is matched against the value of the header
92 Any supplied NETWORK-ARGS are assumed to be keyword arguments for
93 `make-network-process' to which they are passed directly.
95 For example, the following starts a simple hello-world server on
100 (with-slots (process headers) request
101 (process-send-string process
102 \"HTTP/1.1 200 OK\\r\\nContent-Type: text/plain\\r\\n\\r\\nhello world\")))
105 Equivalently, the following starts an identical server using a
106 function MATCH and the `ws-response-header' convenience
111 (lambda (proc request)
112 (ws-response-header proc 200 '(\"Content-type\" . \"text/plain\"))
113 (process-send-string proc \"hello world\")
118 (let ((server (make-instance 'ws-server :handlers handlers :port port))
119 (log (when log-buffer (get-buffer-create log-buffer))))
120 (setf (process server)
122 #'make-network-process
124 :service (port server)
129 :coding 'no-conversion
130 :plist (append (list :server server)
131 (when log (list :log-buffer log)))
133 (lambda (proc request message)
134 (let ((c (process-contact request))
135 (buf (plist-get (process-plist proc) :log-buffer)))
136 (with-current-buffer buf
137 (goto-char (point-max))
138 (insert (format "%s\t%s\t%s\t%s"
139 (format-time-string ws-log-time-format)
140 (first c) (second c) message))))))
142 (push server ws-servers)
145 (defun ws-stop (server)
147 (setq ws-servers (remove server ws-servers))
148 (mapc #'delete-process (append (mapcar #'process (requests server))
149 (list (process server)))))
151 (defun ws-stop-all ()
152 "Stop all servers in `ws-servers'."
154 (mapc #'ws-stop ws-servers))
156 (defvar ws-http-common-methods '(GET HEAD POST PUT DELETE TRACE)
157 "HTTP methods from http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.")
159 (defvar ws-http-method-rx
160 (format "^\\(%s\\) \\([^[:space:]]+\\) \\([^[:space:]]+\\)$"
161 (mapconcat #'symbol-name ws-http-common-methods "\\|")))
163 (defun ws-parse-query-string (string)
164 "Thin wrapper around `url-parse-query-string'."
165 (mapcar (lambda (pair) (cons (first pair) (second pair)))
166 (url-parse-query-string string nil 'allow-newlines)))
168 (defun ws-parse (proc string)
169 "Parse HTTP headers in STRING reporting errors to PROC."
170 (cl-flet ((to-keyword (s) (intern (concat ":" (upcase s)))))
173 ((string-match ws-http-method-rx string)
174 (let ((method (to-keyword (match-string 1 string)))
175 (url (match-string 2 string)))
176 (if (string-match "?" url)
177 (cons (cons method (substring url 0 (match-beginning 0)))
178 (ws-parse-query-string
179 (url-unhex-string (substring url (match-end 0)))))
180 (list (cons method url)))))
182 ((string-match "^AUTHORIZATION: \\([^[:space:]]+\\) \\(.*\\)$" string)
183 (let ((protocol (to-keyword (match-string 1 string)))
184 (credentials (match-string 2 string)))
185 (list (cons :AUTHORIZATION
189 (let ((cred (base64-decode-string credentials)))
190 (if (string-match ":" cred)
191 (cons (substring cred 0 (match-beginning 0))
192 (substring cred (match-end 0)))
193 (ws-error proc "bad credentials: %S" cred))))
194 (t (ws-error proc "un-support protocol: %s"
197 ((string-match "^\\([^[:space:]]+\\): \\(.*\\)$" string)
198 (list (cons (to-keyword (match-string 1 string))
199 (match-string 2 string))))
200 (:otherwise (ws-error proc "bad header: %S" string) nil))))
202 (defun ws-trim (string)
203 (while (and (> (length string) 0)
204 (or (and (string-match "[\r\n]" (substring string -1))
205 (setq string (substring string 0 -1)))
206 (and (string-match "[\r\n]" (substring string 0 1))
207 (setq string (substring string 1))))))
210 (defun ws-parse-multipart/form (proc string)
211 ;; ignore empty and non-content blocks
212 (when (string-match "Content-Disposition:[[:space:]]*\\(.*\\)\r\n" string)
213 (let ((dp (cdr (mail-header-parse-content-disposition
214 (match-string 1 string))))
215 (last-index (match-end 0))
217 ;; every line up until the double \r\n is a header
218 (while (and (setq index (string-match "\r\n" string last-index))
219 (not (= index last-index)))
220 (setcdr (last dp) (ws-parse proc (substring string last-index index)))
221 (setq last-index (+ 2 index)))
222 ;; after double \r\n is all content
223 (cons (cdr (assoc 'name dp))
224 (cons (cons 'content (substring string (+ 2 last-index)))
227 (defun ws-filter (proc string)
228 (with-slots (handlers requests) (plist-get (process-plist proc) :server)
229 (unless (cl-find-if (lambda (c) (equal proc (process c))) requests)
230 (push (make-instance 'ws-request :process proc) requests))
231 (let ((request (cl-find-if (lambda (c) (equal proc (process c))) requests)))
232 (with-slots (pending) request (setq pending (concat pending string)))
233 (unless (active request) ; don't re-start if request is being parsed
234 (setf (active request) t)
235 (when (not (eq (catch 'close-connection
236 (if (ws-parse-request request)
237 (ws-call-handler request handlers)
240 ;; Properly shut down processes requiring an ending (e.g., chunked)
241 (let ((ender (plist-get (process-plist proc) :ender)))
242 (when ender (process-send-string proc ender)))
243 (setq requests (cl-remove-if (lambda (r) (eql proc (process r))) requests))
244 (delete-process proc))))))
246 (defun ws-parse-request (request)
247 "Parse request STRING from REQUEST with process PROC.
248 Return non-nil only when parsing is complete."
249 (catch 'finished-parsing-headers
250 (with-slots (process pending context boundary headers index) request
251 (let ((delimiter (concat "\r\n" (if boundary (concat "--" boundary) "")))
252 ;; Track progress through string, always work with the
253 ;; section of string between INDEX and NEXT-INDEX.
255 ;; parse headers and append to request
256 (while (setq next-index (string-match delimiter pending index))
257 (let ((tmp (+ next-index (length delimiter))))
258 (if (= index next-index) ; double \r\n ends current run of headers
261 ;; http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
262 (application/x-www-form-urlencoded
263 (mapc (lambda (pair) (setcdr (last headers) (list pair)))
264 (ws-parse-query-string
265 (replace-regexp-in-string
267 (ws-trim (substring pending index)))))
268 (throw 'finished-parsing-headers t))
269 ;; Set custom delimiter for multipart form data.
271 (setq delimiter (concat "\r\n--" boundary)))
272 ;; No special context so we're done.
273 (t (throw 'finished-parsing-headers t)))
274 (if (eql context 'multipart/form-data)
276 (setcdr (last headers)
277 (list (ws-parse-multipart/form process
278 (substring pending index next-index))))
279 ;; Boundary suffixed by "--" indicates end of the headers.
280 (when (and (> (length pending) (+ tmp 2))
281 (string= (substring pending tmp (+ tmp 2)) "--"))
282 (throw 'finished-parsing-headers t)))
283 ;; Standard header parsing.
284 (let ((header (ws-parse process (substring pending
286 ;; Content-Type indicates that the next double \r\n
287 ;; will be followed by a special type of content which
288 ;; will require special parsing. Thus we will note
289 ;; the type in the CONTEXT variable for parsing
291 (if (and (caar header) (eql (caar header) :CONTENT-TYPE))
292 (cl-destructuring-bind (type &rest data)
293 (mail-header-parse-content-type (cdar header))
294 (setq boundary (cdr (assoc 'boundary data)))
295 (setq context (intern (downcase type))))
296 ;; All other headers are collected directly.
297 (setcdr (last headers) header)))))
299 (setf (active request) nil)
302 (defun ws-call-handler (request handlers)
303 (catch 'matched-handler
304 (when (functionp handlers)
305 (throw 'matched-handler
306 (condition-case e (funcall handlers request)
307 (error (ws-error (process request) "Caught Error: %S" e)))))
308 (mapc (lambda (handler)
309 (let ((match (car handler))
310 (function (cdr handler)))
311 (when (or (and (consp match)
312 (assoc (car match) (headers request))
313 (string-match (cdr match)
314 (cdr (assoc (car match)
315 (headers request)))))
316 (and (functionp match) (funcall match request)))
317 (throw 'matched-handler
318 (condition-case e (funcall function request)
319 (error (ws-error (process request)
320 "Caught Error: %S" e)))))))
322 (ws-error (process request) "no handler matched request: %S"
325 (defun ws-error (proc msg &rest args)
326 (let ((buf (plist-get (process-plist proc) :log-buffer))
327 (c (process-contact proc)))
329 (with-current-buffer buf
330 (goto-char (point-max))
331 (insert (format "%s\t%s\t%s\tWS-ERROR: %s"
332 (format-time-string ws-log-time-format)
334 (apply #'format msg args)))))
335 (apply #'ws-send-500 proc msg args)))
339 ;; Implement to conform to http://tools.ietf.org/html/rfc6455.
341 ;; The `ws-message' object is used to hold state across multiple calls
342 ;; of the process filter on the websocket network process. The fields
343 ;; play the following roles.
344 ;; process ------ holds the process itself, used for communication
345 ;; pending ------ holds text received from the client but not yet parsed
346 ;; active ------- indicates that parsing is active to avoid re-entry
347 ;; of the `ws-web-socket-parse-messages' function
348 ;; new ---------- indicates that new text was received during parsing
349 ;; and causes `ws-web-socket-parse-messages' to be
350 ;; called again after it terminates
351 ;; data --------- holds the data of parsed messages
352 ;; handler ------ holds the user-supplied function used called on the
353 ;; data of parsed messages
354 (defclass ws-message () ; web socket message object
355 ((process :initarg :process :accessor process :initform "")
356 (pending :initarg :pending :accessor pending :initform "")
357 (active :initarg :active :accessor active :initform nil)
358 (new :initarg :new :accessor new :initform nil)
359 (data :initarg :data :accessor data :initform "")
360 (handler :initarg :handler :accessor handler :initform "")))
362 (defun ws-web-socket-connect (request handler)
363 "Establish a web socket connection with request.
364 If the connection is successful this function will throw
365 `:keep-alive' to `close-connection' skipping any remaining code
366 in the request handler. If no web-socket connection is
367 established (e.g., because REQUEST is not attempting to establish
368 a connection) then no actions are taken and nil is returned.
370 Second argument HANDLER should be a function of one argument
371 which will be called on all complete messages as they are
372 received and parsed from the network."
373 (with-slots (process headers) request
374 (when (assoc :SEC-WEBSOCKET-KEY headers)
375 ;; Accept the connection
376 (ws-response-header process 101
377 (cons "Upgrade" "websocket")
378 (cons "Connection" "upgrade")
379 (cons "Sec-WebSocket-Accept"
380 (ws-web-socket-handshake
381 (cdr (assoc :SEC-WEBSOCKET-KEY headers)))))
382 ;; Setup the process filter
383 (set-process-coding-system process 'binary)
385 process (list :message (make-instance 'ws-message
386 :handler handler :process process)))
387 (set-process-filter process 'ws-web-socket-filter)
390 (defun ws-web-socket-filter (process string)
391 (let ((message (plist-get (process-plist process) :message)))
392 (if (active message) ; don't re-start if message is being parsed
393 (setf (new message) string)
394 (setf (pending message) (concat (pending message) string))
395 (setf (active message) t)
396 (ws-web-socket-parse-messages message))
397 (setf (active message) nil)))
399 (defun ws-web-socket-mask (masking-key data)
400 (let ((masking-data (apply #'concat (make-list (+ 1 (/ (length data) 4))
402 (apply #'string (cl-mapcar #'logxor masking-data data))))
404 ;; Binary framing protocol
405 ;; from http://tools.ietf.org/html/rfc6455#section-5.2
408 ;; 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
409 ;; +-+-+-+-+-------+-+-------------+-------------------------------+
410 ;; |F|R|R|R| opcode|M| Payload len | Extended payload length |
411 ;; |I|S|S|S| (4) |A| (7) | (16/64) |
412 ;; |N|V|V|V| |S| | (if payload len==126/127) |
414 ;; +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
415 ;; | Extended payload length continued, if payload len == 127 |
416 ;; + - - - - - - - - - - - - - - - +-------------------------------+
417 ;; | |Masking-key, if MASK set to 1 |
418 ;; +-------------------------------+-------------------------------+
419 ;; | Masking-key (continued) | Payload Data |
420 ;; +-------------------------------- - - - - - - - - - - - - - - - +
421 ;; : Payload Data continued ... :
422 ;; + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
423 ;; | Payload Data continued ... |
424 ;; +---------------------------------------------------------------+
426 (defun ws-web-socket-parse-messages (message)
427 "Web socket filter to pass whole frames to the client.
429 (with-slots (process active pending data handler new) message
431 (cl-labels ((int-to-bits (int size)
432 (let ((result (make-bool-vector size nil)))
433 (mapc (lambda (place)
434 (let ((val (expt 2 place)))
436 (setq int (- int val))
437 (aset result place t))))
438 (reverse (number-sequence 0 (- size 1))))
439 (reverse (append result nil))))
443 (mapcar (lambda (bit)
444 (prog1 (if bit (expt 2 place) 0) (incf place)))
448 (mapcar (lambda (int) (int-to-bits int 8))
450 pending index (incf index length))))))
451 (let (fin rsvs opcode mask pl mask-key)
452 ;; Parse fin bit, rsvs bits and opcode
453 (let ((byte (bits 1)))
455 rsvs (cl-subseq byte 1 4)
457 (let ((it (bits-to-int (cl-subseq byte 4))))
462 ((3 4 5 6 7) :NON-CONTROL)
466 ((11 12 13 14 15) :CONTROL)
467 ;; If an unknown opcode is received, the receiving
468 ;; endpoint MUST _Fail the WebSocket Connection_.
470 "Web Socket Fail: bad opcode %d" it))))))
471 (unless (cl-every #'null rsvs)
472 ;; MUST be 0 unless an extension is negotiated that defines
473 ;; meanings for non-zero values.
474 (ws-error process "Web Socket Fail: non-zero RSV 1 2 or 3"))
475 ;; Parse mask and payload length
476 (let ((byte (bits 1)))
477 (setq mask (car byte)
478 pl (bits-to-int (cl-subseq byte 1))))
480 ;; All frames sent from client to server have this bit set to 1.
481 (ws-error process "Web Socket Fail: client must mask data"))
483 ((= pl 126) (setq pl (bits-to-int (bits 2))))
484 ((= pl 127) (setq pl (bits-to-int (bits 8)))))
486 (when mask (setq mask-key (cl-subseq pending index (incf index 4))))
487 (setq data (concat data
489 mask-key (cl-subseq pending index (+ index pl)))))
491 ;; wipe the message state and call the handler
493 (setq data "" active nil pending "" new nil)
494 ;; close on a close frame, otherwise call the handler
495 (if (not (eql opcode :CLOSE))
496 (funcall handler process it)
497 (process-send-string process
498 (unibyte-string (logior (lsh 1 7) 8) 0))))
499 ;; add any remaining un-parsed network data to pending
500 (when (< (+ index pl) (length pending))
501 (setq pending (substring pending (+ index pl)))))))
502 ;; possibly re-parse any pending input
503 (when (new message) (ws-web-socket-parse-messages message)))))
505 (defun ws-web-socket-frame (string &optional opcode)
506 "Frame STRING for web socket communication."
507 (let* ((fin 1) ;; set to 0 if not final frame
508 (len (length string))
509 (opcode (ecase (or opcode :TEXT) (:TEXT 1) (:BINARY 2))))
510 ;; Does not do any masking which is only required of client communication
513 ((< len 126) (unibyte-string (logior (lsh fin 7) opcode) len))
514 ((< len 65536) (unibyte-string (logior (lsh fin 7) opcode) 126
515 ;; extended 16-bit length
516 (logand (lsh len -8) 255)
518 (t (unibyte-string (logior (lsh fin 7) opcode) 127
519 ;; more extended 64-bit length
520 (logand (lsh len -56) 255)
521 (logand (lsh len -48) 255)
522 (logand (lsh len -40) 255)
523 (logand (lsh len -32) 255)
524 (logand (lsh len -24) 255)
525 (logand (lsh len -16) 255)
526 (logand (lsh len -8) 255)
531 ;;; Content and Transfer encoding support
532 (defvar ws-compress-cmd "compress"
533 "Command used for the \"compress\" Content or Transfer coding.")
535 (defvar ws-deflate-cmd "zlib-flate -compress"
536 "Command used for the \"deflate\" Content or Transfer coding.")
538 (defvar ws-gzip-cmd "gzip"
539 "Command used for the \"gzip\" Content or Transfer coding.")
541 (defmacro ws-encoding-cmd-to-fn (cmd)
542 "Return a function which applies CMD to strings."
546 (shell-command-on-region (point-min) (point-max) ,cmd nil 'replace)
549 (defun ws-chunk (string)
550 "Convert STRING to a valid chunk for HTTP chunked Transfer-encoding."
551 (format "%x\r\n%s\r\n" (string-bytes string) string))
554 ;;; Convenience functions to write responses
555 (defun ws-response-header (proc code &rest headers)
556 "Send the headers for an HTTP response to PROC.
557 CODE should be an HTTP status code, see `ws-status-codes' for a
560 When \"Content-Encoding\" or \"Transfer-Encoding\" headers are
561 supplied any subsequent data written to PROC using `ws-send' will
562 be encoded appropriately including sending the appropriate data
563 upon the end of transmission for chunked transfer encoding.
565 For example with the header `(\"Content-Encoding\" . \"gzip\")',
566 any data subsequently written to PROC using `ws-send' will be
567 compressed using the command specified in `ws-gzip-cmd'."
568 ;; update process to reflect any Content or Transfer encodings
569 (let ((content (cdr (assoc "Content-Encoding" headers)))
570 (transfer (cdr (assoc "Transfer-Encoding" headers))))
572 (set-process-plist proc
574 (list :content-encoding
575 (ecase (intern content)
576 ((compress x-compress) (ws-encoding-cmd-to-fn ws-compress-cmd))
577 ((deflate x-deflate) (ws-encoding-cmd-to-fn ws-deflate-cmd))
578 ((gzip x-gzip) (ws-encoding-cmd-to-fn ws-gzip-cmd))
579 (identity #'identity)
581 (ws-error proc "`%s' Content-encoding not supported."
583 (process-plist proc))))
585 (set-process-plist proc
587 (when (string= transfer "chunked") (list :ender "0\r\n\r\n"))
588 (list :transfer-encoding
589 (ecase (intern transfer)
591 ((compress x-compress) (ws-encoding-cmd-to-fn ws-compress-cmd))
592 ((deflate x-deflate) (ws-encoding-cmd-to-fn ws-deflate-cmd))
593 ((gzip x-gzip) (ws-encoding-cmd-to-fn ws-gzip-cmd))))
594 (process-plist proc)))))
597 (format "HTTP/1.1 %d %s" code (cdr (assoc code ws-status-codes)))
598 (mapcar (lambda (h) (format "%s: %s" (car h) (cdr h))) headers))))
599 (setcdr (last headers) (list "" ""))
600 (process-send-string proc (mapconcat #'identity headers "\r\n"))))
602 (defun ws-send (proc string)
603 "Send STRING to process PROC.
604 If any Content or Transfer encodings are in use, apply them to
605 STRING before sending."
607 ((cc (or (plist-get (process-plist proc) :content-encoding) #'identity))
608 (tc (or (plist-get (process-plist proc) :transfer-encoding) #'identity)))
609 (process-send-string proc (funcall tc (funcall cc string)))))
611 (defun ws-send-500 (proc &rest msg-and-args)
612 "Send 500 \"Internal Server Error\" to PROC with an optional message."
613 (ws-response-header proc 500
614 '("Content-type" . "text/plain"))
615 (process-send-string proc (if msg-and-args
616 (apply #'format msg-and-args)
617 "500 Internal Server Error"))
618 (throw 'close-connection nil))
620 (defun ws-send-404 (proc &rest msg-and-args)
621 "Send 404 \"Not Found\" to PROC with an optional message."
622 (ws-response-header proc 404
623 '("Content-type" . "text/plain"))
624 (process-send-string proc (if msg-and-args
625 (apply #'format msg-and-args)
627 (throw 'close-connection nil))
629 (defun ws-send-file (proc path &optional mime-type)
631 Optionally explicitly set MIME-TYPE, otherwise it is guessed by
632 `mm-default-file-encoding'."
633 (let ((mime (or mime-type
634 (mm-default-file-encoding path)
635 "application/octet-stream")))
636 (process-send-string proc
638 (insert-file-contents-literally path)
639 (ws-response-header proc 200
640 (cons "Content-type" mime)
641 (cons "Content-length" (- (point-max) (point-min))))
644 (defun ws-send-directory-list (proc directory &optional match)
645 "Send a listing of files in DIRECTORY to PROC.
646 Optional argument MATCH is passed to `directory-files' and may be
647 used to limit the files sent."
648 (ws-response-header proc 200 (cons "Content-type" "text/html"))
649 (process-send-string proc
651 (mapconcat (lambda (f)
652 (let* ((full (expand-file-name f directory))
653 (end (if (file-directory-p full) "/" ""))
654 (url (url-encode-url (concat f end))))
655 (format "<li><a href=%s>%s</li>" url f)))
656 (directory-files directory nil match)
660 (defun ws-in-directory-p (parent path)
661 "Check if PATH is under the PARENT directory.
662 If so return PATH, if not return nil. Note: the PARENT directory
663 must be full expanded as with `expand-file-name' and should not
664 contain e.g., \"~\" for a user home directory."
665 (if (zerop (length path))
667 (let ((expanded (expand-file-name path parent)))
668 (and (>= (length expanded) (length parent))
669 (string= parent (substring expanded 0 (length parent)))
672 (defun ws-with-authentication (handler credentials
673 &optional realm unauth invalid)
674 "Return a version of HANDLER protected by CREDENTIALS.
675 HANDLER should be a function as passed to `ws-start', and
676 CREDENTIALS should be an alist of elements of the form (USERNAME
679 Optional argument REALM sets the realm in the authentication
680 challenge. Optional arguments UNAUTH and INVALID should be
681 functions which are called on the request when no authentication
682 information, or invalid authentication information are provided
684 (lexical-let ((handler handler)
685 (credentials credentials)
690 (with-slots (process headers) request
691 (let ((auth (cddr (assoc :AUTHORIZATION headers))))
693 ;; no authentication information provided
696 (funcall unauth request)
697 (ws-response-header process 401
698 (cons "WWW-Authenticate"
699 (format "Basic realm=%S" (or realm "restricted")))
700 '("Content-type" . "text/plain"))
701 (process-send-string process "authentication required")))
702 ;; valid authentication information
703 ((string= (cdr auth) (cdr (assoc (car auth) credentials)))
704 (funcall handler request))
705 ;; invalid authentication information
708 (funcall invalid request)
709 (ws-response-header process 403 '("Content-type" . "text/plain"))
710 (process-send-string process "invalid credentials")))))))))
712 (defun ws-web-socket-handshake (key)
713 "Perform the handshake defined in RFC6455."
714 (base64-encode-string (sha1 (concat (ws-trim key) ws-guid) nil nil 'binary)))
716 (provide 'web-server)
717 ;;; web-server.el ends here