Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1052 lines
46 KiB

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