1 ;;; guile-websocket --- WebSocket client/server
2 ;;; Copyright © 2016 David Thompson <davet@gnu.org>
3 ;;; Copyright © 2017 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;; Copyright © 2019, 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
6 ;;; This file is part of guile-websocket.
8 ;;; Guile-websocket is free software; you can redistribute it and/or modify
9 ;;; it under the terms of the GNU Lesser General Public License as
10 ;;; published by the Free Software Foundation; either version 3 of the
11 ;;; License, or (at your option) any later version.
13 ;;; Guile-websocket is distributed in the hope that it will be useful,
14 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ;;; Lesser General Public License for more details.
18 ;;; You should have received a copy of the GNU Lesser General Public
19 ;;; License along with guile-websocket. If not, see
20 ;;; <http://www.gnu.org/licenses/>.
28 (define-module (8sync systems websocket client)
29 #:use-module (ice-9 match)
30 #:use-module (srfi srfi-26)
31 #:use-module (rnrs bytevectors)
32 #:use-module (rnrs io ports)
33 #:use-module (web request)
34 #:use-module (web response)
35 #:use-module (web uri)
36 #:use-module (oop goops)
38 #:use-module (8sync ports)
39 #:use-module (8sync contrib base64)
40 #:use-module (8sync systems websocket frame)
41 #:use-module (8sync systems websocket utils)
61 (define no-op (const #f))
63 (define-actor <websocket> (<actor>)
64 ((*init* websocket-init)
65 (close websocket-close)
67 (send websocket-send))
69 (state #:accessor .state #:init-value 'closed #:init-keyword #:state)
70 (socket #:accessor .socket #:init-value #f #:init-keyword #:socket)
71 (url #:getter .url #:init-value #f #:init-keyword #:url)
72 (uri #:accessor .uri #:init-value #f #:init-keyword #:uri)
73 (entropy-port #:accessor .entropy-port #:init-form (open-entropy-port))
75 (on-close #:init-keyword #:on-close
78 (on-error #:init-keyword #:on-error
81 (on-message #:init-keyword #:on-message
82 #:accessor .on-message)
83 (on-open #:init-keyword #:on-open
87 (define-method (websocket-close (websocket <websocket>) message)
88 (when (websocket-open? websocket)
89 (false-if-exception (close-port (.socket websocket)))
90 (set! (.state websocket) 'closed)
91 (false-if-exception ((.on-close websocket) websocket))
92 (set! (.socket websocket) #f)))
94 (define-method (websocket-open (websocket <websocket>) message uri-or-string)
95 (if (websocket-closed? websocket)
96 (let ((uri (match uri-or-string
98 ((? string? str) (string->uri str)))))
99 (if (websocket-uri? uri)
102 (set! (.uri websocket) uri)
103 (let ((sock (make-client-socket uri)))
104 (set! (.socket websocket) sock)
105 (handshake websocket)
106 (websocket-loop websocket message)))
108 ((.on-error websocket) websocket (format #f "open failed: ~s: ~s" uri-or-string args))))
109 ((.on-error websocket) websocket (format #f "not a websocket uri: ~s" uri-or-string))))
110 ((.on-error websocket) websocket (format #f "cannot open websocket in state: ~s" (.state websocket)))))
112 (define (subbytevector bv start end)
113 (if (= (bytevector-length bv) end) bv
114 (let* ((length (- end start))
115 (sub (make-bytevector length)))
116 (bytevector-copy! bv start sub 0 length)
119 (define* (make-fragmented-frames data #:key (fragment-size (expt 2 15)))
120 (let ((length (if (string? data) (string-length data)
121 (bytevector-length data))))
122 (let loop ((offset 0))
123 (let* ((size (min fragment-size (- length offset)))
124 (end (+ offset size))
125 (final? (= end length))
126 (continuation? (not (zero? offset)))
127 (frame (if (string? data) (make-text-frame (substring data offset end) #:final? final? #:continuation? continuation?)
128 (make-binary-frame (subbytevector data offset end) #:final? final? #:continuation? continuation?))))
129 (if final? (list frame)
130 (cons frame (loop end)))))))
132 (define-method (websocket-send (websocket <websocket>) message data)
133 (catch #t ; expect: wrong-type-arg (open port), system-error
135 (let* ((frames (make-fragmented-frames data)))
136 (let loop ((frames frames) (written '(nothing)))
138 (write-frame (car frames) (.socket websocket))
139 (loop (cdr frames) (cons (car frames) written))))))
141 (let ((message (format #f "~a: ~s" key args)))
142 ((.on-error websocket) websocket (format #f "send failed: ~s ~a\n" websocket message))
143 (websocket-close websocket message)))))
145 (define-method (websocket-init (websocket <websocket>) message)
146 (and=> (.url websocket) (cut websocket-open websocket message <>)))
148 (define-method (websocket-loop (websocket <websocket>) message)
150 (define (handle-data-frame type data)
151 ((.on-message websocket)
154 ('text (utf8->string data))
157 (define (read-frame-maybe)
158 (and (not (eof-object? (lookahead-u8 (.socket websocket))))
159 (read-frame (.socket websocket))))
162 (websocket-close websocket message))
164 ((.on-open websocket) websocket)
166 (let loop ((fragments '())
168 (let* ((socket (.socket websocket))
169 (frame (and (websocket-open? websocket)
170 (read-frame-maybe))))
172 ;; EOF - port is closed.
173 ;; @@: Sometimes the eof object appears here as opposed to
174 ;; at lookahead, but I'm not sure why
175 ((or (not frame) (eof-object? frame))
177 ;; Per section 5.4, control frames may appear interspersed
178 ;; along with a fragmented message.
179 ((close-frame? frame)
180 ;; Per section 5.5.1, echo the close frame back to the
181 ;; socket before closing the socket. The socket may no
182 ;; longer be listening.
184 (write-frame (make-close-frame (frame-data frame)) socket))
187 ;; Per section 5.5.3, a pong frame must include the exact
188 ;; same data as the ping frame.
189 (write-frame (make-pong-frame (frame-data frame)) socket)
190 (loop fragments type))
191 ((pong-frame? frame) ; silently ignore pongs
192 (loop fragments type))
193 ((first-fragment-frame? frame) ; begin accumulating fragments
194 (loop (list frame) (frame-type frame)))
195 ((final-fragment-frame? frame) ; concatenate all fragments
196 (handle-data-frame type (frame-concatenate
197 (reverse (cons frame fragments))))
199 ((fragment-frame? frame) ; add a fragment
200 (loop (cons frame fragments) type))
201 ((data-frame? frame) ; unfragmented data frame
202 (handle-data-frame (frame-type frame) (frame-data frame))
205 ;; See Section 3 - WebSocket URIs
206 (define (encrypted-websocket-scheme? uri)
207 "Return #t if the scheme for URI is 'wss', the secure WebSocket
209 (eq? (uri-scheme uri) 'wss))
211 (define (unencrypted-websocket-scheme? uri)
212 "Return #t if the scheme for URI is 'ws', the insecure WebSocket
214 (eq? (uri-scheme uri) 'ws))
216 (define (websocket-uri? uri)
217 "Return #t if URI is a valid WebSocket URI."
218 (and (or (encrypted-websocket-scheme? uri)
219 (unencrypted-websocket-scheme? uri))
220 (not (uri-fragment uri))))
222 (define (set-nonblocking! port)
223 (fcntl port F_SETFL (logior O_NONBLOCK (fcntl port F_GETFL)))
224 (setvbuf port 'block 1024))
226 (define (make-client-socket uri)
227 "Connect a socket to the remote resource described by URI."
228 (let* ((port (uri-port uri))
229 (info (car (getaddrinfo (uri-host uri)
231 (number->string port)
232 (symbol->string (uri-scheme uri)))
236 (sock (with-fluids ((%default-port-encoding #f))
237 (socket (addrinfo:fam info) SOCK_STREAM IPPROTO_IP))))
239 (set-nonblocking! sock)
240 ;; Disable buffering for websockets
243 ;; TODO: Configure I/O buffering?
244 (connect sock (addrinfo:addr info))
247 (define-method (write (o <websocket>) port)
248 (format port "#<websocket ~a ~a>"
252 (define-method (websocket-connecting? (websocket <websocket>))
253 "Return #t if WEBSOCKET is in the connecting state."
254 (eq? (.state websocket) 'connecting))
256 (define-method (websocket-open? (websocket <websocket>))
257 "Return #t if WEBSOCKET is in the open state."
258 (eq? (.state websocket) 'open))
260 (define-method (websocket-closing? (websocket <websocket>))
261 "Return #t if WEBSOCKET is in the closing state."
262 (eq? (.state websocket) 'closing))
264 (define-method (websocket-closed? (websocket <websocket>))
265 "Return #t if WEBSOCKET is in the closed state."
266 (eq? (.state websocket) 'closed))
268 (define-method (generate-client-key (websocket <websocket>))
269 "Return a random, base64 encoded nonce using the entropy source of
272 (get-bytevector-n (.entropy-port websocket) 16)))
274 ;; See Section 4.1 - Client Requirements
275 (define (make-handshake-request uri key)
276 "Create an HTTP request for initiating a WebSocket connection with
277 the remote resource described by URI, using a randomly generated nonce
279 (let ((headers `((host . (,(uri-host uri) . #f))
280 (upgrade . ("WebSocket"))
281 (connection . (upgrade))
282 (sec-websocket-key . ,key)
283 (sec-websocket-version . "13"))))
284 (build-request uri #:method 'GET #:headers headers)))
286 (define-method (handshake (websocket <websocket>))
287 "Perform the WebSocket handshake for the client WEBSOCKET."
288 (let ((key (generate-client-key websocket)))
289 (write-request (make-handshake-request (.uri websocket) key)
291 (let* ((response (read-response (.socket websocket)))
292 (headers (response-headers response))
293 (upgrade (assoc-ref headers 'upgrade))
294 (connection (assoc-ref headers 'connection))
295 (accept (assoc-ref headers 'sec-websocket-accept)))
296 ;; Validate the handshake.
297 (if (and (= (response-code response) 101)
298 (string-ci=? (car upgrade) "websocket")
299 (equal? connection '(upgrade))
300 (string=? (string-trim-both accept) (make-accept-key key)))
301 (set! (.state websocket) 'open)
303 (websocket-close websocket)
304 ((.on-error websocket) websocket
305 (format #f "websocket handshake failed: ~s"
306 (uri->string (.uri websocket)))))))))
308 (define (open-entropy-port)
309 "Return an open input port to a reliable source of entropy for the
311 ;; XXX: This works on GNU/Linux and OS X systems, but this isn't
313 (open-input-file "/dev/urandom"))
315 (define-method (websocket-close (websocket <websocket>))
316 "Close the WebSocket connection for the client WEBSOCKET."
317 (let ((socket (.socket websocket)))
318 (set! (.state websocket) 'closing)
319 (write-frame (make-close-frame (make-bytevector 0)) socket)
320 ;; Per section 5.5.1 , wait for the server to close the connection
321 ;; for a reasonable amount of time.
323 (match (select #() (vector socket) #() 1) ; 1 second timeout
324 ((#() #(socket) #()) ; there is output to read
325 (unless (port-eof? socket)
326 (read-frame socket) ; throw it away
329 (close-port (.entropy-port websocket))
330 (set! (.state websocket) 'closed)))