]> code.delx.au - gnu-emacs-elpa/blob - packages/web-server/web-server.el
2e8f9e704565bec9529249f0e99439d987689003
[gnu-emacs-elpa] / packages / web-server / web-server.el
1 ;;; web-server.el --- Emacs Web Server
2
3 ;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
4
5 ;; Author: Eric Schulte <schulte.eric@gmail.com>
6 ;; Maintainer: Eric Schulte <schulte.eric@gmail.com>
7 ;; Version: 0.1.1
8 ;; Package-Requires: ((emacs "24.3"))
9 ;; Keywords: http, server, network
10 ;; URL: https://github.com/eschulte/emacs-web-server
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
27 ;; A web server in Emacs running handlers written in Emacs Lisp.
28 ;;
29 ;; Full support for GET and POST requests including URL-encoded
30 ;; parameters and multipart/form data. Supports web sockets.
31 ;;
32 ;; See the examples/ directory for examples demonstrating the usage of
33 ;; the Emacs Web Server. The following launches a simple "hello
34 ;; world" server.
35 ;;
36 ;; (ws-start
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")))))
42 ;; 9000)
43
44 ;;; Code:
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
49 (require 'eieio)
50 (eval-when-compile (require 'cl))
51 (require 'cl-lib)
52
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)))
58
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))))
67
68 (defvar ws-servers nil
69 "List holding all web servers.")
70
71 (defvar ws-log-time-format "%Y.%m.%d.%H.%M.%S.%N"
72 "Logging time format passed to `format-time-string'.")
73
74 (defvar ws-guid "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
75 "This GUID is defined in RFC6455.")
76
77 ;;;###autoload
78 (defun ws-start (handlers port &optional log-buffer &rest network-args)
79 "Start a server using HANDLERS and return the server object.
80
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.
86
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
90 specified by KEYWORD.
91
92 Any supplied NETWORK-ARGS are assumed to be keyword arguments for
93 `make-network-process' to which they are passed directly.
94
95 For example, the following starts a simple hello-world server on
96 port 8080.
97
98 (ws-start
99 (lambda (request)
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\")))
103 8080)
104
105 Equivalently, the following starts an identical server using a
106 function MATCH and the `ws-response-header' convenience
107 function.
108
109 (ws-start
110 '(((lambda (_) t) .
111 (lambda (proc request)
112 (ws-response-header proc 200 '(\"Content-type\" . \"text/plain\"))
113 (process-send-string proc \"hello world\")
114 t)))
115 8080)
116
117 "
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)
121 (apply
122 #'make-network-process
123 :name "ws-server"
124 :service (port server)
125 :filter 'ws-filter
126 :server t
127 :nowait t
128 :family 'ipv4
129 :coding 'no-conversion
130 :plist (append (list :server server)
131 (when log (list :log-buffer log)))
132 :log (when 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))))))
141 network-args))
142 (push server ws-servers)
143 server))
144
145 (defun ws-stop (server)
146 "Stop SERVER."
147 (setq ws-servers (remove server ws-servers))
148 (mapc #'delete-process (append (mapcar #'process (requests server))
149 (list (process server)))))
150
151 (defun ws-stop-all ()
152 "Stop all servers in `ws-servers'."
153 (interactive)
154 (mapc #'ws-stop ws-servers))
155
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.")
158
159 (defvar ws-http-method-rx
160 (format "^\\(%s\\) \\([^[:space:]]+\\) \\([^[:space:]]+\\)$"
161 (mapconcat #'symbol-name ws-http-common-methods "\\|")))
162
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)))
167
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)))))
171 (cond
172 ;; Method
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)))))
181 ;; Authorization
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
186 (cons protocol
187 (case protocol
188 (:BASIC
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"
195 protocol))))))))
196 ;; All other headers
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))))
201
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))))))
208 string)
209
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))
216 index)
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)))
225 dp)))))
226
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)
238 :keep-alive))
239 :keep-alive))
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))))))
245
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.
254 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
259 (case context
260 ;; Parse URL data.
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
266 "\\+" " "
267 (ws-trim (substring pending index)))))
268 (throw 'finished-parsing-headers t))
269 ;; Set custom delimiter for multipart form data.
270 (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)
275 (progn
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
285 index next-index))))
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
290 ;; dispatch above.
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)))))
298 (setq index tmp)))))
299 (setf (active request) nil)
300 nil))
301
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)))))))
321 handlers)
322 (ws-error (process request) "no handler matched request: %S"
323 (headers request))))
324
325 (defun ws-error (proc msg &rest args)
326 (let ((buf (plist-get (process-plist proc) :log-buffer))
327 (c (process-contact proc)))
328 (when buf
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)
333 (first c) (second c)
334 (apply #'format msg args)))))
335 (apply #'ws-send-500 proc msg args)))
336
337 \f
338 ;;; Web Socket
339 ;; Implement to conform to http://tools.ietf.org/html/rfc6455.
340
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 "")))
361
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.
369
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)
384 (set-process-plist
385 process (list :message (make-instance 'ws-message
386 :handler handler :process process)))
387 (set-process-filter process 'ws-web-socket-filter)
388 process)))
389
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)))
398
399 (defun ws-web-socket-mask (masking-key data)
400 (let ((masking-data (apply #'concat (make-list (+ 1 (/ (length data) 4))
401 masking-key))))
402 (apply #'string (cl-mapcar #'logxor masking-data data))))
403
404 ;; Binary framing protocol
405 ;; from http://tools.ietf.org/html/rfc6455#section-5.2
406 ;;
407 ;; 0 1 2 3
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) |
413 ;; | |1|2|3| |K| | |
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 ;; +---------------------------------------------------------------+
425 ;;
426 (defun ws-web-socket-parse-messages (message)
427 "Web socket filter to pass whole frames to the client.
428 See RFC6455."
429 (with-slots (process active pending data handler new) message
430 (let ((index 0))
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)))
435 (when (>= int val)
436 (setq int (- int val))
437 (aset result place t))))
438 (reverse (number-sequence 0 (- size 1))))
439 (reverse (append result nil))))
440 (bits-to-int (bits)
441 (let ((place 0))
442 (apply #'+
443 (mapcar (lambda (bit)
444 (prog1 (if bit (expt 2 place) 0) (incf place)))
445 (reverse bits)))))
446 (bits (length)
447 (apply #'append
448 (mapcar (lambda (int) (int-to-bits int 8))
449 (cl-subseq
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)))
454 (setq fin (car byte)
455 rsvs (cl-subseq byte 1 4)
456 opcode
457 (let ((it (bits-to-int (cl-subseq byte 4))))
458 (case it
459 (0 :CONTINUATION)
460 (1 :TEXT)
461 (2 :BINARY)
462 ((3 4 5 6 7) :NON-CONTROL)
463 (8 :CLOSE)
464 (9 :PING)
465 (10 :PONG)
466 ((11 12 13 14 15) :CONTROL)
467 ;; If an unknown opcode is received, the receiving
468 ;; endpoint MUST _Fail the WebSocket Connection_.
469 (t (ws-error process
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))))
479 (unless (eq mask t)
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"))
482 (cond
483 ((= pl 126) (setq pl (bits-to-int (bits 2))))
484 ((= pl 127) (setq pl (bits-to-int (bits 8)))))
485 ;; unmask data
486 (when mask (setq mask-key (cl-subseq pending index (incf index 4))))
487 (setq data (concat data
488 (ws-web-socket-mask
489 mask-key (cl-subseq pending index (+ index pl)))))
490 (if fin
491 ;; wipe the message state and call the handler
492 (let ((it data))
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)))))
504
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
511 (concat
512 (cond
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)
517 (logand len 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)
527 (logand len 255))))
528 string)))
529
530 \f
531 ;;; Content and Transfer encoding support
532 (defvar ws-compress-cmd "compress"
533 "Command used for the \"compress\" Content or Transfer coding.")
534
535 (defvar ws-deflate-cmd "zlib-flate -compress"
536 "Command used for the \"deflate\" Content or Transfer coding.")
537
538 (defvar ws-gzip-cmd "gzip"
539 "Command used for the \"gzip\" Content or Transfer coding.")
540
541 (defmacro ws-encoding-cmd-to-fn (cmd)
542 "Return a function which applies CMD to strings."
543 `(lambda (s)
544 (with-temp-buffer
545 (insert s)
546 (shell-command-on-region (point-min) (point-max) ,cmd nil 'replace)
547 (buffer-string))))
548
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))
552
553 \f
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
558 list of known codes.
559
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.
564
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))))
571 (when content
572 (set-process-plist proc
573 (append
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)
580 ((exi pack200-zip)
581 (ws-error proc "`%s' Content-encoding not supported."
582 content))))
583 (process-plist proc))))
584 (when transfer
585 (set-process-plist proc
586 (append
587 (when (string= transfer "chunked") (list :ender "0\r\n\r\n"))
588 (list :transfer-encoding
589 (ecase (intern transfer)
590 (chunked #'ws-chunk)
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)))))
595 (let ((headers
596 (cons
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"))))
601
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."
606 (let
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)))))
610
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))
619
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)
626 "404 Not Found"))
627 (throw 'close-connection nil))
628
629 (defun ws-send-file (proc path &optional mime-type)
630 "Send PATH to PROC.
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
637 (with-temp-buffer
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))))
642 (buffer-string)))))
643
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
650 (concat "<ul>"
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)
657 "\n")
658 "</ul>")))
659
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))
666 parent
667 (let ((expanded (expand-file-name path parent)))
668 (and (>= (length expanded) (length parent))
669 (string= parent (substring expanded 0 (length parent)))
670 expanded))))
671
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
677 . PASSWORD).
678
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
683 respectively."
684 (lexical-let ((handler handler)
685 (credentials credentials)
686 (realm realm)
687 (unauth unauth)
688 (invalid invalid))
689 (lambda (request)
690 (with-slots (process headers) request
691 (let ((auth (cddr (assoc :AUTHORIZATION headers))))
692 (cond
693 ;; no authentication information provided
694 ((not auth)
695 (if unauth
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
706 (t
707 (if invalid
708 (funcall invalid request)
709 (ws-response-header process 403 '("Content-type" . "text/plain"))
710 (process-send-string process "invalid credentials")))))))))
711
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)))
715
716 (provide 'web-server)
717 ;;; web-server.el ends here