]> code.delx.au - gnu-emacs-elpa/blob - packages/websocket/websocket.el
Merge commit '4c9fdc8a28ee4cfd795c94bc4b872138f363ae0f'
[gnu-emacs-elpa] / packages / websocket / websocket.el
1 ;;; websocket.el --- Emacs WebSocket client and server
2
3 ;; Copyright (c) 2013 Free Software Foundation, Inc.
4
5 ;; Author: Andrew Hyatt <ahyatt at gmail dot com>
6 ;; Maintainer: Andrew Hyatt <ahyatt at gmail dot com>
7 ;; Keywords: Communication, Websocket, Server
8 ;; Version: 1.3
9 ;;
10 ;; This program is free software; you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation; either version 3 of the
13 ;; License, or (at your option) any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 ;; General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24 ;; This implements RFC 6455, which can be found at
25 ;; http://tools.ietf.org/html/rfc6455.
26 ;;
27 ;; This library contains code to connect Emacs as a client to a
28 ;; websocket server, and for Emacs to act as a server for websocket
29 ;; connections.
30 ;;
31 ;; Websockets clients are created by calling `websocket-open', which
32 ;; returns a `websocket' struct. Users of this library use the
33 ;; websocket struct, and can call methods `websocket-send-text', which
34 ;; sends text over the websocket, or `websocket-send', which sends a
35 ;; `websocket-frame' struct, enabling finer control of what is sent.
36 ;; A callback is passed to `websocket-open' that will retrieve
37 ;; websocket frames called from the websocket. Websockets are
38 ;; eventually closed with `websocket-close'.
39 ;;
40 ;; Server functionality is similar. A server is started with
41 ;; `websocket-server' called with a port and the callbacks to use,
42 ;; which returns a process. The process can later be closed with
43 ;; `websocket-server-close'. A `websocket' struct is also created
44 ;; for every connection, and is exposed through the callbacks.
45
46 (require 'bindat)
47 (require 'url-parse)
48 (eval-when-compile (require 'cl))
49
50 ;;; Code:
51
52 (defstruct (websocket
53 (:constructor nil)
54 (:constructor websocket-inner-create))
55 "A websocket structure.
56 This follows the W3C Websocket API, except translated to elisp
57 idioms. The API is implemented in both the websocket struct and
58 additional methods. Due to how defstruct slots are accessed, all
59 API methods are prefixed with \"websocket-\" and take a websocket
60 as an argument, so the distrinction between the struct API and
61 the additional helper APIs are not visible to the caller.
62
63 A websocket struct is created with `websocket-open'.
64
65 `ready-state' contains one of 'connecting, 'open, or
66 'closed, depending on the state of the websocket.
67
68 The W3C API \"bufferedAmount\" call is not currently implemented,
69 since there is no elisp API to get the buffered amount from the
70 subprocess. There may, in fact, be output data buffered,
71 however, when the `on-message' or `on-close' callbacks are
72 called.
73
74 `on-open', `on-message', `on-close', and `on-error' are described
75 in `websocket-open'.
76
77 The `negotiated-extensions' slot lists the extensions accepted by
78 both the client and server, and `negotiated-protocols' does the
79 same for the protocols.
80 "
81 ;; API
82 (ready-state 'connecting)
83 client-data
84 on-open
85 on-message
86 on-close
87 on-error
88 negotiated-protocols
89 negotiated-extensions
90 (server-p nil :read-only t)
91
92 ;; Other data - clients should not have to access this.
93 (url (assert nil) :read-only t)
94 (protocols nil :read-only t)
95 (extensions nil :read-only t)
96 (conn (assert nil) :read-only t)
97 ;; Only populated for servers, this is the server connection.
98 server-conn
99 accept-string
100 (inflight-input nil))
101
102 (defvar websocket-version "1.3"
103 "Version numbers of this version of websocket.el.")
104
105 (defvar websocket-debug nil
106 "Set to true to output debugging info to a per-websocket buffer.
107 The buffer is ` *websocket URL debug*' where URL is the
108 URL of the connection.")
109
110 (defconst websocket-guid "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
111 "The websocket GUID as defined in RFC 6455.
112 Do not change unless the RFC changes.")
113
114 (defvar websocket-callback-debug-on-error nil
115 "If true, when an error happens in a client callback, invoke the debugger.
116 Having this on can cause issues with missing frames if the debugger is
117 exited by quitting instead of continuing, so it's best to have this set
118 to nil unless it is especially needed.")
119
120 (defmacro websocket-document-function (function docstring)
121 "Document FUNCTION with DOCSTRING. Use this for defstruct accessor etc."
122 (declare (indent defun)
123 (doc-string 2))
124 `(put ',function 'function-documentation ,docstring))
125
126 (websocket-document-function websocket-on-open
127 "Accessor for websocket on-open callback.
128 See `websocket-open' for details.
129
130 \(fn WEBSOCKET)")
131
132 (websocket-document-function websocket-on-message
133 "Accessor for websocket on-message callback.
134 See `websocket-open' for details.
135
136 \(fn WEBSOCKET)")
137
138 (websocket-document-function websocket-on-close
139 "Accessor for websocket on-close callback.
140 See `websocket-open' for details.
141
142 \(fn WEBSOCKET)")
143
144 (websocket-document-function websocket-on-error
145 "Accessor for websocket on-error callback.
146 See `websocket-open' for details.
147
148 \(fn WEBSOCKET)")
149
150 (defun websocket-genbytes (nbytes)
151 "Generate NBYTES random bytes."
152 (let ((s (make-string nbytes ?\s)))
153 (dotimes (i nbytes)
154 (aset s i (random 256)))
155 s))
156
157 (defun websocket-try-callback (websocket-callback callback-type websocket
158 &rest rest)
159 "Invoke function WEBSOCKET-CALLBACK with WEBSOCKET and REST args.
160 If an error happens, it is handled according to
161 `websocket-callback-debug-on-error'."
162 ;; This looks like it should be able to done more efficiently, but
163 ;; I'm not sure that's the case. We can't do it as a macro, since
164 ;; we want it to change whenever websocket-callback-debug-on-error
165 ;; changes.
166 (let ((args rest)
167 (debug-on-error websocket-callback-debug-on-error))
168 (push websocket args)
169 (if websocket-callback-debug-on-error
170 (condition-case err
171 (apply (funcall websocket-callback websocket) args)
172 ((debug error) (funcall (websocket-on-error websocket)
173 websocket callback-type err)))
174 (condition-case err
175 (apply (funcall websocket-callback websocket) args)
176 (error (funcall (websocket-on-error websocket) websocket
177 callback-type err))))))
178
179 (defun websocket-genkey ()
180 "Generate a key suitable for the websocket handshake."
181 (base64-encode-string (websocket-genbytes 16)))
182
183 (defun websocket-calculate-accept (key)
184 "Calculate the expect value of the accept header.
185 This is based on the KEY from the Sec-WebSocket-Key header."
186 (base64-encode-string
187 (sha1 (concat key websocket-guid) nil nil t)))
188
189 (defun websocket-get-bytes (s n)
190 "From string S, retrieve the value of N bytes.
191 Return the value as an unsigned integer. The value N must be a
192 power of 2, up to 8.
193
194 We support getting frames up to 536870911 bytes (2^29 - 1),
195 approximately 537M long."
196 (if (= n 8)
197 (let* ((32-bit-parts
198 (bindat-get-field (bindat-unpack '((:val vec 2 u32)) s) :val))
199 (cval
200 (logior (lsh (aref 32-bit-parts 0) 32) (aref 32-bit-parts 1))))
201 (if (and (= (aref 32-bit-parts 0) 0)
202 (= (lsh (aref 32-bit-parts 1) -29) 0))
203 cval
204 (signal 'websocket-unparseable-frame
205 "Frame value found too large to parse!")))
206 ;; n is not 8
207 (bindat-get-field
208 (condition-case _
209 (bindat-unpack
210 `((:val
211 ,(cond ((= n 1) 'u8)
212 ((= n 2) 'u16)
213 ((= n 4) 'u32)
214 ;; This is an error with the library,
215 ;; not a user-facing, meaningful error.
216 (t (error
217 "websocket-get-bytes: Unknown N: %s" n)))))
218 s)
219 (args-out-of-range (signal 'websocket-unparseable-frame
220 (format "Frame unexpectedly shortly: %s" s))))
221 :val)))
222
223 (defun websocket-to-bytes (val nbytes)
224 "Encode the integer VAL in NBYTES of data.
225 NBYTES much be a power of 2, up to 8.
226
227 This supports encoding values up to 536870911 bytes (2^29 - 1),
228 approximately 537M long."
229 (when (and (< nbytes 8)
230 (> val (expt 2 (* 8 nbytes))))
231 ;; not a user-facing error, this must be caused from an error in
232 ;; this library
233 (error "websocket-to-bytes: Value %d could not be expressed in %d bytes"
234 val nbytes))
235 (if (= nbytes 8)
236 (progn
237 (let ((hi-32bits (lsh val -32))
238 (low-32bits (logand #xffffffff val)))
239 (when (or (> hi-32bits 0) (> (lsh low-32bits -29) 0))
240 (signal 'websocket-frame-too-large val))
241 (bindat-pack `((:val vec 2 u32))
242 `((:val . [,hi-32bits ,low-32bits])))))
243 (bindat-pack
244 `((:val ,(cond ((= nbytes 1) 'u8)
245 ((= nbytes 2) 'u16)
246 ((= nbytes 4) 'u32)
247 ;; Library error, not system error
248 (t (error "websocket-to-bytes: Unknown NBYTES: %s" nbytes)))))
249 `((:val . ,val)))))
250
251 (defun websocket-get-opcode (s)
252 "Retrieve the opcode from first byte of string S."
253 (websocket-ensure-length s 1)
254 (let ((opcode (logand #xf (websocket-get-bytes s 1))))
255 (cond ((= opcode 0) 'continuation)
256 ((= opcode 1) 'text)
257 ((= opcode 2) 'binary)
258 ((= opcode 8) 'close)
259 ((= opcode 9) 'ping)
260 ((= opcode 10) 'pong))))
261
262 (defun websocket-get-payload-len (s)
263 "Parse out the payload length from the string S.
264 We start at position 0, and return a cons of the payload length and how
265 many bytes were consumed from the string."
266 (websocket-ensure-length s 1)
267 (let* ((initial-val (logand 127 (websocket-get-bytes s 1))))
268 (cond ((= initial-val 127)
269 (websocket-ensure-length s 9)
270 (cons (websocket-get-bytes (substring s 1) 8) 9))
271 ((= initial-val 126)
272 (websocket-ensure-length s 3)
273 (cons (websocket-get-bytes (substring s 1) 2) 3))
274 (t (cons initial-val 1)))))
275
276 (defstruct websocket-frame opcode payload length completep)
277
278 (defun websocket-mask (key data)
279 "Using string KEY, mask string DATA according to the RFC.
280 This is used to both mask and unmask data."
281 (apply
282 'string
283 (loop for b across data
284 for i from 0 to (length data)
285 collect (logxor (websocket-get-bytes (substring key (mod i 4)) 1) b))))
286
287 (defun websocket-ensure-length (s n)
288 "Ensure the string S has at most N bytes.
289 Otherwise we throw the error `websocket-incomplete-frame'."
290 (when (< (length s) n)
291 (throw 'websocket-incomplete-frame nil)))
292
293 (defun websocket-encode-frame (frame should-mask)
294 "Encode the FRAME struct to the binary representation.
295 We mask the frame or not, depending on SHOULD-MASK."
296 (let* ((opcode (websocket-frame-opcode frame))
297 (payload (websocket-frame-payload frame))
298 (fin (websocket-frame-completep frame))
299 (payloadp (memq opcode '(continuation text binary)))
300 (mask-key (when should-mask (websocket-genbytes 4))))
301 (apply 'unibyte-string
302 (append (list
303 (logior (cond ((eq opcode 'continuation) 0)
304 ((eq opcode 'text) 1)
305 ((eq opcode 'binary) 2)
306 ((eq opcode 'close) 8)
307 ((eq opcode 'ping) 9)
308 ((eq opcode 'pong) 10))
309 (if fin 128 0)))
310 (when payloadp
311 (list
312 (logior
313 (if should-mask 128 0)
314 (cond ((< (length payload) 126) (length payload))
315 ((< (length payload) 65536) 126)
316 (t 127)))))
317 (when (and payloadp (>= (length payload) 126))
318 (append (websocket-to-bytes (length payload)
319 (cond ((< (length payload) 126) 1)
320 ((< (length payload) 65536) 2)
321 (t 8))) nil))
322 (when (and payloadp should-mask)
323 (append mask-key nil))
324 (when payloadp
325 (append (if should-mask (websocket-mask mask-key payload)
326 payload)
327 nil))))))
328
329 (defun websocket-read-frame (s)
330 "Read from string S a `websocket-frame' struct with the contents.
331 This only gets complete frames. Partial frames need to wait until
332 the frame finishes. If the frame is not completed, return NIL."
333 (catch 'websocket-incomplete-frame
334 (websocket-ensure-length s 1)
335 (let* ((opcode (websocket-get-opcode s))
336 (fin (logand 128 (websocket-get-bytes s 1)))
337 (payloadp (memq opcode '(continuation text binary)))
338 (payload-len (when payloadp
339 (websocket-get-payload-len (substring s 1))))
340 (maskp (and
341 payloadp
342 (= 128 (logand 128 (websocket-get-bytes (substring s 1) 1)))))
343 (payload-start (when payloadp (+ (if maskp 5 1) (cdr payload-len))))
344 (payload-end (when payloadp (+ payload-start (car payload-len))))
345 (unmasked-payload (when payloadp
346 (websocket-ensure-length s payload-end)
347 (substring s payload-start payload-end))))
348 (make-websocket-frame
349 :opcode opcode
350 :payload
351 (if maskp
352 (let ((masking-key (substring s (+ 1 (cdr payload-len))
353 (+ 5 (cdr payload-len)))))
354 (websocket-mask masking-key unmasked-payload))
355 unmasked-payload)
356 :length (if payloadp payload-end 1)
357 :completep (> fin 0)))))
358
359 (defun websocket-format-error (err)
360 "Format an error message like command level does.
361 ERR should be a cons of error symbol and error data."
362
363 ;; Formatting code adapted from `edebug-report-error'
364 (concat (or (get (car err) 'error-message)
365 (format "peculiar error (%s)" (car err)))
366 (when (cdr err)
367 (format ": %s"
368 (mapconcat #'prin1-to-string
369 (cdr err) ", ")))))
370
371 (defun websocket-default-error-handler (_websocket type err)
372 "The default error handler used to handle errors in callbacks."
373 (display-warning 'websocket
374 (format "in callback `%S': %s"
375 type
376 (websocket-format-error err))
377 :error))
378
379 ;; Error symbols in use by the library
380 (put 'websocket-unsupported-protocol 'error-conditions
381 '(error websocket-error websocket-unsupported-protocol))
382 (put 'websocket-unsupported-protocol 'error-message "Unsupported websocket protocol")
383 (put 'websocket-wss-needs-emacs-24 'error-conditions
384 '(error websocket-error websocket-unsupported-protocol
385 websocket-wss-needs-emacs-24))
386 (put 'websocket-wss-needs-emacs-24 'error-message
387 "wss protocol is not supported for Emacs before version 24.")
388 (put 'websocket-received-error-http-response 'error-conditions
389 '(error websocket-error websocket-received-error-http-response))
390 (put 'websocket-received-error-http-response 'error-message
391 "Error response received from websocket server")
392 (put 'websocket-invalid-header 'error-conditions
393 '(error websocket-error websocket-invalid-header))
394 (put 'websocket-invalid-header 'error-message
395 "Invalid HTTP header sent")
396 (put 'websocket-illegal-frame 'error-conditions
397 '(error websocket-error websocket-illegal-frame))
398 (put 'websocket-illegal-frame 'error-message
399 "Cannot send illegal frame to websocket")
400 (put 'websocket-closed 'error-conditions
401 '(error websocket-error websocket-closed))
402 (put 'websocket-closed 'error-message
403 "Cannot send message to a closed websocket")
404 (put 'websocket-unparseable-frame 'error-conditions
405 '(error websocket-error websocket-unparseable-frame))
406 (put 'websocket-unparseable-frame 'error-message
407 "Received an unparseable frame")
408 (put 'websocket-frame-too-large 'error-conditions
409 '(error websocket-error websocket-frame-too-large))
410 (put 'websocket-frame-too-large 'error-message
411 "The frame being sent is too large for this emacs to handle")
412
413 (defun websocket-intersect (a b)
414 "Simple list intersection, should function like Common Lisp's `intersection'."
415 (let ((result))
416 (dolist (elem a (nreverse result))
417 (when (member elem b)
418 (push elem result)))))
419
420 (defun websocket-get-debug-buffer-create (websocket)
421 "Get or create the buffer corresponding to WEBSOCKET."
422 (let ((buf (get-buffer-create (format "*websocket %s debug*"
423 (websocket-url websocket)))))
424 (when (= 0 (buffer-size buf))
425 (buffer-disable-undo buf))
426 buf))
427
428 (defun websocket-debug (websocket msg &rest args)
429 "In the WEBSOCKET's debug buffer, send MSG, with format ARGS."
430 (when websocket-debug
431 (let ((buf (websocket-get-debug-buffer-create websocket)))
432 (save-excursion
433 (with-current-buffer buf
434 (goto-char (point-max))
435 (insert "[WS] ")
436 (insert (apply 'format (append (list msg) args)))
437 (insert "\n"))))))
438
439 (defun websocket-verify-response-code (output)
440 "Verify that OUTPUT contains a valid HTTP response code.
441 The only acceptable one to websocket is responce code 101.
442 A t value will be returned on success, and an error thrown
443 if not."
444 (string-match "HTTP/1.1 \\([[:digit:]]+\\)" output)
445 (unless (equal "101" (match-string 1 output))
446 (signal 'websocket-received-error-http-response
447 (string-to-number (match-string 1 output))))
448 t)
449
450 (defun websocket-parse-repeated-field (output field)
451 "From header-containing OUTPUT, parse out the list from a
452 possibly repeated field."
453 (let ((pos 0)
454 (extensions))
455 (while (and pos
456 (string-match (format "\r\n%s: \\(.*\\)\r\n" field)
457 output pos))
458 (when (setq pos (match-end 1))
459 (setq extensions (append extensions (split-string
460 (match-string 1 output) ", ?")))))
461 extensions))
462
463 (defun websocket-process-frame (websocket frame)
464 "Using the WEBSOCKET's filter and connection, process the FRAME.
465 This returns a lambda that should be executed when all frames have
466 been processed. If the frame has a payload, the lambda has the frame
467 passed to the filter slot of WEBSOCKET. If the frame is a ping,
468 the lambda has a reply with a pong. If the frame is a close, the lambda
469 has connection termination."
470 (let ((opcode (websocket-frame-opcode frame)))
471 (lexical-let ((lex-ws websocket)
472 (lex-frame frame))
473 (cond ((memq opcode '(continuation text binary))
474 (lambda () (websocket-try-callback 'websocket-on-message 'on-message
475 lex-ws lex-frame)))
476 ((eq opcode 'ping)
477 (lambda () (websocket-send lex-ws
478 (make-websocket-frame :opcode 'pong :completep t))))
479 ((eq opcode 'close)
480 (lambda () (delete-process (websocket-conn lex-ws))))
481 (t (lambda ()))))))
482
483 (defun websocket-process-input-on-open-ws (websocket text)
484 "This handles input processing for both the client and server filters."
485 (let ((current-frame)
486 (processing-queue)
487 (start-point 0))
488 (while (setq current-frame (websocket-read-frame
489 (substring text start-point)))
490 (push (websocket-process-frame websocket current-frame) processing-queue)
491 (incf start-point (websocket-frame-length current-frame)))
492 (when (> (length text) start-point)
493 (setf (websocket-inflight-input websocket)
494 (substring text start-point)))
495 (dolist (to-process (nreverse processing-queue))
496 (funcall to-process))))
497
498 (defun websocket-send-text (websocket text)
499 "To the WEBSOCKET, send TEXT as a complete frame."
500 (websocket-send
501 websocket
502 (make-websocket-frame :opcode 'text
503 :payload (encode-coding-string
504 text 'raw-text)
505 :completep t)))
506
507 (defun websocket-check (frame)
508 "Check FRAME for correctness, returning true if correct."
509 (and (equal (not (memq (websocket-frame-opcode frame)
510 '(continuation text binary)))
511 (and (not (websocket-frame-payload frame))
512 (websocket-frame-completep frame)))))
513
514 (defun websocket-send (websocket frame)
515 "To the WEBSOCKET server, send the FRAME.
516 This will raise an error if the frame is illegal.
517
518 The error signaled may be of type `websocket-illegal-frame' if
519 the frame is malformed in some way, also having the condition
520 type of `websocket-error'. The data associated with the signal
521 is the frame being sent.
522
523 If the websocket is closed a signal `websocket-closed' is sent,
524 also with `websocket-error' condition. The data in the signal is
525 also the frame.
526
527 The frame may be too large for this buid of Emacs, in which case
528 `websocket-frame-too-large' is returned, with the data of the
529 size of the frame which was too large to process. This also has
530 the `websocket-error' condition."
531 (unless (websocket-check frame)
532 (signal 'websocket-illegal-frame frame))
533 (websocket-debug websocket "Sending frame, opcode: %s payload: %s"
534 (websocket-frame-opcode frame)
535 (websocket-frame-payload frame))
536 (websocket-ensure-connected websocket)
537 (unless (websocket-openp websocket)
538 (signal 'websocket-closed frame))
539 (process-send-string (websocket-conn websocket)
540 ;; We mask only when we're a client, following the spec.
541 (websocket-encode-frame frame (not (websocket-server-p websocket)))))
542
543 (defun websocket-openp (websocket)
544 "Check WEBSOCKET and return non-nil if it is open, and either
545 connecting or open."
546 (and websocket
547 (not (eq 'close (websocket-ready-state websocket)))
548 (member (process-status (websocket-conn websocket)) '(open run))))
549
550 (defun websocket-close (websocket)
551 "Close WEBSOCKET and erase all the old websocket data."
552 (websocket-debug websocket "Closing websocket")
553 (websocket-try-callback 'websocket-on-close 'on-close websocket)
554 (when (websocket-openp websocket)
555 (websocket-send websocket
556 (make-websocket-frame :opcode 'close
557 :completep t))
558 (setf (websocket-ready-state websocket) 'closed))
559 (delete-process (websocket-conn websocket)))
560
561 (defun websocket-ensure-connected (websocket)
562 "If the WEBSOCKET connection is closed, open it."
563 (unless (and (websocket-conn websocket)
564 (ecase (process-status (websocket-conn websocket))
565 ((run open listen) t)
566 ((stop exit signal closed connect failed nil) nil)))
567 (websocket-close websocket)
568 (websocket-open (websocket-url websocket)
569 :protocols (websocket-protocols websocket)
570 :extensions (websocket-extensions websocket)
571 :on-open (websocket-on-open websocket)
572 :on-message (websocket-on-message websocket)
573 :on-close (websocket-on-close websocket)
574 :on-error (websocket-on-error websocket))))
575
576 ;;;;;;;;;;;;;;;;;;;;;;
577 ;; Websocket client ;;
578 ;;;;;;;;;;;;;;;;;;;;;;
579
580 (defun* websocket-open (url &key protocols extensions (on-open 'identity)
581 (on-message (lambda (_w _f))) (on-close 'identity)
582 (on-error 'websocket-default-error-handler))
583 "Open a websocket connection to URL, returning the `websocket' struct.
584 The PROTOCOL argument is optional, and setting it will declare to
585 the server that this client supports the protocols in the list
586 given. We will require that the server also has to support that
587 protocols.
588
589 Similar logic applies to EXTENSIONS, which is a list of conses,
590 the car of which is a string naming the extension, and the cdr of
591 which is the list of parameter strings to use for that extension.
592 The parameter strings are of the form \"key=value\" or \"value\".
593 EXTENSIONS can be NIL if none are in use. An example value would
594 be '(\"deflate-stream\" . (\"mux\" \"max-channels=4\")).
595
596 Optionally you can specify
597 ON-OPEN, ON-MESSAGE and ON-CLOSE callbacks as well.
598
599 The ON-OPEN callback is called after the connection is
600 established with the websocket as the only argument. The return
601 value is unused.
602
603 The ON-MESSAGE callback is called after receiving a frame, and is
604 called with the websocket as the first argument and
605 `websocket-frame' struct as the second. The return value is
606 unused.
607
608 The ON-CLOSE callback is called after the connection is closed, or
609 failed to open. It is called with the websocket as the only
610 argument, and the return value is unused.
611
612 The ON-ERROR callback is called when any of the other callbacks
613 have an error. It takes the websocket as the first argument, and
614 a symbol as the second argument either `on-open', `on-message',
615 or `on-close', and the error as the third argument. Do NOT
616 rethrow the error, or else you may miss some websocket messages.
617 You similarly must not generate any other errors in this method.
618 If you want to debug errors, set
619 `websocket-callback-debug-on-error' to `t', but this also can be
620 dangerous is the debugger is quit out of. If not specified,
621 `websocket-default-error-handler' is used.
622
623 For each of these event handlers, the client code can store
624 arbitrary data in the `client-data' slot in the returned
625 websocket.
626
627 The following errors might be thrown in this method or in
628 websocket processing, all of them having the error-condition
629 `websocket-error' in addition to their own symbol:
630
631 `websocket-unsupported-protocol': Data in the error signal is the
632 protocol that is unsupported. For example, giving a URL starting
633 with http by mistake raises this error.
634
635 `websocket-wss-needs-emacs-24': Trying to connect wss protocol
636 using Emacs < 24 raises this error. You can catch this error
637 also by `websocket-unsupported-protocol'.
638
639 `websocket-received-error-http-response': Data in the error
640 signal is the integer error number.
641
642 `websocket-invalid-header': Data in the error is a string
643 describing the invalid header received from the server.
644
645 `websocket-unparseable-frame': Data in the error is a string
646 describing the problem with the frame.
647 "
648 (let* ((name (format "websocket to %s" url))
649 (url-struct (url-generic-parse-url url))
650 (key (websocket-genkey))
651 (coding-system-for-read 'binary)
652 (coding-system-for-write 'binary)
653 (conn (if (member (url-type url-struct) '("ws" "wss"))
654 (let* ((type (if (equal (url-type url-struct) "ws")
655 'plain 'tls))
656 (port (if (= 0 (url-port url-struct))
657 (if (eq type 'tls) 443 80)
658 (url-port url-struct)))
659 (host (url-host url-struct)))
660 (if (eq type 'plain)
661 (make-network-process :name name :buffer nil :host host
662 :service port :nowait nil)
663 (condition-case-unless-debug nil
664 (open-network-stream name nil host port :type type :nowait nil)
665 (wrong-number-of-arguments
666 (signal 'websocket-wss-needs-emacs-24 "wss")))))
667 (signal 'websocket-unsupported-protocol (url-type url-struct))))
668 (websocket (websocket-inner-create
669 :conn conn
670 :url url
671 :on-open on-open
672 :on-message on-message
673 :on-close on-close
674 :on-error on-error
675 :protocols protocols
676 :extensions (mapcar 'car extensions)
677 :accept-string
678 (websocket-calculate-accept key))))
679 (unless conn (error "Could not establish the websocket connection to %s" url))
680 (process-put conn :websocket websocket)
681 (set-process-filter conn
682 (lambda (process output)
683 (let ((websocket (process-get process :websocket)))
684 (websocket-outer-filter websocket output))))
685 (set-process-sentinel
686 conn
687 (lambda (process change)
688 (let ((websocket (process-get process :websocket)))
689 (websocket-debug websocket "State change to %s" change)
690 (when (and
691 (member (process-status process) '(closed failed exit signal))
692 (not (eq 'closed (websocket-ready-state websocket))))
693 (websocket-try-callback 'websocket-on-close 'on-close websocket)))))
694 (set-process-query-on-exit-flag conn nil)
695 (process-send-string conn
696 (format "GET %s HTTP/1.1\r\n"
697 (let ((path (url-filename url-struct)))
698 (if (> (length path) 0) path "/"))))
699 (websocket-debug websocket "Sending handshake, key: %s, acceptance: %s"
700 key (websocket-accept-string websocket))
701 (process-send-string conn
702 (websocket-create-headers url key protocols extensions))
703 (websocket-debug websocket "Websocket opened")
704 websocket))
705
706 (defun websocket-outer-filter (websocket output)
707 "Filter the WEBSOCKET server's OUTPUT.
708 This will parse headers and process frames repeatedly until there
709 is no more output or the connection closes. If the websocket
710 connection is invalid, the connection will be closed."
711 (websocket-debug websocket "Received: %s" output)
712 (let ((start-point)
713 (text (concat (websocket-inflight-input websocket) output))
714 (header-end-pos))
715 (setf (websocket-inflight-input websocket) nil)
716 ;; If we've received the complete header, check to see if we've
717 ;; received the desired handshake.
718 (when (and (eq 'connecting (websocket-ready-state websocket))
719 (setq header-end-pos (string-match "\r\n\r\n" text))
720 (setq start-point (+ 4 header-end-pos)))
721 (condition-case err
722 (progn
723 (websocket-verify-response-code text)
724 (websocket-verify-headers websocket text))
725 (error
726 (websocket-close websocket)
727 (signal (car err) (cdr err))))
728 (setf (websocket-ready-state websocket) 'open)
729 (websocket-try-callback 'websocket-on-open 'on-open websocket))
730 (when (eq 'open (websocket-ready-state websocket))
731 (websocket-process-input-on-open-ws
732 websocket (substring text (or start-point 0))))))
733
734 (defun websocket-verify-headers (websocket output)
735 "Based on WEBSOCKET's data, ensure the headers in OUTPUT are valid.
736 The output is assumed to have complete headers. This function
737 will either return t or call `error'. This has the side-effect
738 of populating the list of server extensions to WEBSOCKET."
739 (let ((accept-string
740 (concat "Sec-WebSocket-Accept: " (websocket-accept-string websocket))))
741 (websocket-debug websocket "Checking for accept header: %s" accept-string)
742 (unless (string-match (regexp-quote accept-string) output)
743 (signal 'websocket-invalid-header
744 "Incorrect handshake from websocket: is this really a websocket connection?")))
745 (let ((case-fold-search t))
746 (websocket-debug websocket "Checking for upgrade header")
747 (unless (string-match "\r\nUpgrade: websocket\r\n" output)
748 (signal 'websocket-invalid-header
749 "No 'Upgrade: websocket' header found"))
750 (websocket-debug websocket "Checking for connection header")
751 (unless (string-match "\r\nConnection: upgrade\r\n" output)
752 (signal 'websocket-invalid-header
753 "No 'Connection: upgrade' header found"))
754 (when (websocket-protocols websocket)
755 (dolist (protocol (websocket-protocols websocket))
756 (websocket-debug websocket "Checking for protocol match: %s"
757 protocol)
758 (let ((protocols
759 (if (string-match (format "\r\nSec-Websocket-Protocol: %s\r\n"
760 protocol)
761 output)
762 (list protocol)
763 (signal 'websocket-invalid-header
764 "Incorrect or missing protocol returned by the server."))))
765 (setf (websocket-negotiated-protocols websocket) protocols))))
766 (let* ((extensions (websocket-parse-repeated-field
767 output
768 "Sec-WebSocket-Extensions"))
769 (extra-extensions))
770 (dolist (ext extensions)
771 (let ((x (first (split-string ext "; ?"))))
772 (unless (or (member x (websocket-extensions websocket))
773 (member x extra-extensions))
774 (push x extra-extensions))))
775 (when extra-extensions
776 (signal 'websocket-invalid-header
777 (format "Non-requested extensions returned by server: %S"
778 extra-extensions)))
779 (setf (websocket-negotiated-extensions websocket) extensions)))
780 t)
781
782 ;;;;;;;;;;;;;;;;;;;;;;
783 ;; Websocket server ;;
784 ;;;;;;;;;;;;;;;;;;;;;;
785
786 (defvar websocket-server-websockets nil
787 "A list of current websockets live on any server.")
788
789 (defun* websocket-server (port &rest plist)
790 "Open a websocket server on PORT.
791 This also takes a plist of callbacks: `:on-open', `:on-message',
792 `:on-close' and `:on-error', which operate exactly as documented
793 in the websocket client function `websocket-open'. Returns the
794 connection, which should be kept in order to pass to
795 `websocket-server-close'."
796 (let* ((conn (make-network-process
797 :name (format "websocket server on port %s" port)
798 :server t
799 :family 'ipv4
800 :filter 'websocket-server-filter
801 :log 'websocket-server-accept
802 :filter-multibyte nil
803 :plist plist
804 :service port)))
805 conn))
806
807 (defun websocket-server-close (conn)
808 "Closes the websocket, as well as all open websockets for this server."
809 (let ((to-delete))
810 (dolist (ws websocket-server-websockets)
811 (when (eq (websocket-server-conn ws) conn)
812 (if (eq (websocket-ready-state ws) 'closed)
813 (unless (member ws to-delete)
814 (push ws to-delete))
815 (websocket-close ws))))
816 (dolist (ws to-delete)
817 (setq websocket-server-websockets (remove ws websocket-server-websockets))))
818 (delete-process conn))
819
820 (defun websocket-server-accept (server client message)
821 "Accept a new websocket connection from a client."
822 (let ((ws (websocket-inner-create
823 :server-conn server
824 :conn client
825 :url client
826 :server-p t
827 :on-open (or (process-get server :on-open) 'identity)
828 :on-message (or (process-get server :on-message) (lambda (_ws _frame)))
829 :on-close (lexical-let ((user-method
830 (or (process-get server :on-close) 'identity)))
831 (lambda (ws)
832 (setq websocket-server-websockets
833 (remove ws websocket-server-websockets))
834 (funcall user-method ws)))
835 :on-error (or (process-get server :on-error)
836 'websocket-default-error-handler)
837 :protocols (process-get server :protocol)
838 :extensions (mapcar 'car (process-get server :extensions)))))
839 (unless (member ws websocket-server-websockets)
840 (push ws websocket-server-websockets))
841 (process-put client :websocket ws)
842 (set-process-coding-system client 'binary 'binary)
843 (set-process-sentinel client
844 (lambda (process change)
845 (let ((websocket (process-get process :websocket)))
846 (websocket-debug websocket "State change to %s" change)
847 (when (and
848 (member (process-status process) '(closed failed exit signal))
849 (not (eq 'closed (websocket-ready-state websocket))))
850 (websocket-try-callback 'websocket-on-close 'on-close websocket)))))))
851
852 (defun websocket-create-headers (url key protocol extensions)
853 "Create connections headers for the given URL, KEY, PROTOCOL and EXTENSIONS.
854 These are defined as in `websocket-open'."
855 (format (concat "Host: %s\r\n"
856 "Upgrade: websocket\r\n"
857 "Connection: Upgrade\r\n"
858 "Sec-WebSocket-Key: %s\r\n"
859 "Sec-WebSocket-Version: 13\r\n"
860 (when protocol
861 (concat
862 (mapconcat (lambda (protocol)
863 (format "Sec-WebSocket-Protocol: %s" protocol))
864 protocol "\r\n")
865 "\r\n"))
866 (when extensions
867 (format "Sec-WebSocket-Extensions: %s\r\n"
868 (mapconcat
869 (lambda (ext)
870 (concat (car ext)
871 (when (cdr ext) "; ")
872 (when (cdr ext)
873 (mapconcat 'identity (cdr ext) "; "))))
874 extensions ", ")))
875 "\r\n")
876 (url-host (url-generic-parse-url url))
877 key
878 protocol))
879
880 (defun websocket-get-server-response (websocket client-protocols client-extensions)
881 "Get the websocket response from client WEBSOCKET."
882 (let ((separator "\r\n"))
883 (concat "HTTP/1.1 101 Switching Protocols" separator
884 "Upgrade: websocket" separator
885 "Connection: Upgrade" separator
886 "Sec-WebSocket-Accept: "
887 (websocket-accept-string websocket) separator
888 (let ((protocols
889 (websocket-intersect client-protocols
890 (websocket-protocols websocket))))
891 (when protocols
892 (concat
893 (mapconcat
894 (lambda (protocol) (format "Sec-WebSocket-Protocol: %s"
895 protocol)) protocols separator)
896 separator)))
897 (let ((extensions (websocket-intersect
898 client-extensions
899 (websocket-extensions websocket))))
900 (when extensions
901 (concat
902 (mapconcat
903 (lambda (extension) (format "Sec-Websocket-Extensions: %s"
904 extension)) extensions separator)
905 separator)))
906 separator)))
907
908 (defun websocket-server-filter (process output)
909 "This acts on all OUTPUT from websocket clients PROCESS."
910 (let* ((ws (process-get process :websocket))
911 (text (concat (websocket-inflight-input ws) output)))
912 (setf (websocket-inflight-input ws) nil)
913 (cond ((eq (websocket-ready-state ws) 'connecting)
914 ;; check for connection string
915 (let ((end-of-header-pos
916 (let ((pos (string-match "\r\n\r\n" text)))
917 (when pos (+ 4 pos)))))
918 (if end-of-header-pos
919 (progn
920 (let ((header-info (websocket-verify-client-headers text)))
921 (if header-info
922 (progn (setf (websocket-accept-string ws)
923 (websocket-calculate-accept
924 (plist-get header-info :key)))
925 (process-send-string
926 process
927 (websocket-get-server-response
928 ws (plist-get header-info :protocols)
929 (plist-get header-info :extensions)))
930 (setf (websocket-ready-state ws) 'open)
931 (websocket-try-callback 'websocket-on-open
932 'on-open ws))
933 (message "Invalid client headers found in: %s" output)
934 (process-send-string process "HTTP/1.1 400 Bad Request\r\n\r\n")
935 (websocket-close ws)))
936 (when (> (length text) (+ 1 end-of-header-pos))
937 (websocket-server-filter process (substring
938 text
939 end-of-header-pos))))
940 (setf (websocket-inflight-input ws) text))))
941 ((eq (websocket-ready-state ws) 'open)
942 (websocket-process-input-on-open-ws ws text))
943 ((eq (websocket-ready-state ws) 'closed)
944 (message "WARNING: Should not have received further input on closed websocket")))))
945
946 (defun websocket-verify-client-headers (output)
947 "Verify the headers from the WEBSOCKET client connection in OUTPUT.
948 Unlike `websocket-verify-headers', this is a quieter routine. We
949 don't want to error due to a bad client, so we just print out
950 messages and a plist containing `:key', the websocket key,
951 `:protocols' and `:extensions'."
952 (block nil
953 (let ((case-fold-search t)
954 (plist))
955 (unless (string-match "HTTP/1.1" output)
956 (message "Websocket client connection: HTTP/1.1 not found")
957 (return nil))
958 (unless (string-match "^Host: " output)
959 (message "Websocket client connection: Host header not found")
960 (return nil))
961 (unless (string-match "^Upgrade: websocket\r\n" output)
962 (message "Websocket client connection: Upgrade: websocket not found")
963 (return nil))
964 (if (string-match "^Sec-WebSocket-Key: \\([[:graph:]]+\\)\r\n" output)
965 (setq plist (plist-put plist :key (match-string 1 output)))
966 (message "Websocket client connect: No key sent")
967 (return nil))
968 (unless (string-match "^Sec-WebSocket-Version: 13" output)
969 (message "Websocket client connect: Websocket version 13 not found")
970 (return nil))
971 (when (string-match "^Sec-WebSocket-Protocol:" output)
972 (setq plist (plist-put plist :protocols (websocket-parse-repeated-field
973 output
974 "Sec-Websocket-Protocol"))))
975 (when (string-match "^Sec-WebSocket-Extensions:" output)
976 (setq plist (plist-put plist :extensions (websocket-parse-repeated-field
977 output
978 "Sec-Websocket-Extensions"))))
979 plist)))
980
981 (provide 'websocket)
982
983 ;;; websocket.el ends here