4ae342d9c919f776b8ff3498ffff23999e79458b
[8sync.git] / 8sync / systems / websocket / client.scm
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>
5 ;;;
6 ;;; This file is part of guile-websocket.
7 ;;;
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.
12 ;;;
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.
17 ;;;
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/>.
21
22 ;;; Commentary:
23 ;;
24 ;; WebSocket client.
25 ;;
26 ;;; Code:
27
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)
37   #:use-module (8sync)
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)
42   #:export (<websocket>
43             .on-close
44             .on-error
45             .on-message
46             .on-open
47             .socket
48             .state
49             .url
50
51             websocket-closed?
52             websocket-closing?
53             websocket-connect
54             websocket-connecting?
55             websocket-open?
56
57             websocket-close
58             websocket-loop
59             websocket-send))
60
61 (define no-op (const #f))
62
63 (define-actor <websocket> (<actor>)
64   ((*init* websocket-init)
65    (close websocket-close)
66    (open websocket-open)
67    (send websocket-send))
68
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))
74
75   (on-close #:init-keyword #:on-close
76                  #:init-value no-op
77                  #:accessor .on-close)
78   (on-error #:init-keyword #:on-error
79             #:init-value no-op
80             #:accessor .on-error)
81   (on-message #:init-keyword #:on-message
82               #:accessor .on-message)
83   (on-open #:init-keyword #:on-open
84                 #:init-value no-op
85                 #:accessor .on-open))
86
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)))
93
94 (define-method (websocket-open (websocket <websocket>) message uri-or-string)
95   (if (websocket-closed? websocket)
96       (let ((uri (match uri-or-string
97                    ((? uri? uri) uri)
98                    ((? string? str) (string->uri str)))))
99         (if (websocket-uri? uri)
100             (catch 'system-error
101               (lambda _
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)))
107               (lambda (key . args)
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)))))
111
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)
117         sub)))
118
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)))))))
131
132 (define-method (websocket-send (websocket <websocket>) message data)
133   (catch #t           ; expect: wrong-type-arg (open port), system-error
134     (lambda _
135       (let* ((frames (make-fragmented-frames data)))
136         (let loop ((frames frames) (written '(nothing)))
137           (when (pair? frames)
138             (write-frame (car frames) (.socket websocket))
139             (loop (cdr frames) (cons (car frames) written))))))
140     (lambda (key . args)
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)))))
144
145 (define-method (websocket-init (websocket <websocket>) message)
146   (and=> (.url websocket) (cut websocket-open websocket message <>)))
147
148 (define-method (websocket-loop (websocket <websocket>) message)
149
150   (define (handle-data-frame type data)
151     ((.on-message websocket)
152      websocket
153      (match type
154        ('text   (utf8->string data))
155        ('binary data))))
156
157   (define (read-frame-maybe)
158     (and (not (eof-object? (lookahead-u8 (.socket websocket))))
159          (read-frame (.socket websocket))))
160
161   (define (close-down)
162     (websocket-close websocket message))
163
164   ((.on-open websocket) websocket)
165
166   (let loop ((fragments '())
167              (type #f))
168     (let* ((socket (.socket websocket))
169            (frame (and (websocket-open? websocket)
170                        (read-frame-maybe))))
171       (cond
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))
176         (close-down))
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.
183         (false-if-exception
184          (write-frame (make-close-frame (frame-data frame)) socket))
185         (close-down))
186        ((ping-frame? frame)
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))))
198         (loop '() #f))
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))
203         (loop '() #f))))))
204
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
208 scheme."
209   (eq? (uri-scheme uri) 'wss))
210
211 (define (unencrypted-websocket-scheme? uri)
212   "Return #t if the scheme for URI is 'ws', the insecure WebSocket
213 scheme."
214   (eq? (uri-scheme uri) 'ws))
215
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))))
221
222 (define (set-nonblocking! port)
223   (fcntl port F_SETFL (logior O_NONBLOCK (fcntl port F_GETFL)))
224   (setvbuf port 'block 1024))
225
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)
230                                  (if port
231                                      (number->string port)
232                                      (symbol->string (uri-scheme uri)))
233                                  (if port
234                                      AI_NUMERICSERV
235                                      0))))
236          (sock (with-fluids ((%default-port-encoding #f))
237                  (socket (addrinfo:fam info) SOCK_STREAM IPPROTO_IP))))
238
239     (set-nonblocking! sock)
240     ;; Disable buffering for websockets
241     (setvbuf sock 'none)
242
243     ;; TODO: Configure I/O buffering?
244     (connect sock (addrinfo:addr info))
245     sock))
246
247 (define-method (write (o <websocket>) port)
248    (format port "#<websocket ~a ~a>"
249            (.url o)
250            (.state o)))
251
252 (define-method (websocket-connecting? (websocket <websocket>))
253   "Return #t if WEBSOCKET is in the connecting state."
254   (eq? (.state websocket) 'connecting))
255
256 (define-method (websocket-open? (websocket <websocket>))
257   "Return #t if WEBSOCKET is in the open state."
258   (eq? (.state websocket) 'open))
259
260 (define-method (websocket-closing? (websocket <websocket>))
261   "Return #t if WEBSOCKET is in the closing state."
262   (eq? (.state websocket) 'closing))
263
264 (define-method (websocket-closed? (websocket <websocket>))
265   "Return #t if WEBSOCKET is in the closed state."
266   (eq? (.state websocket) 'closed))
267
268 (define-method (generate-client-key (websocket <websocket>))
269   "Return a random, base64 encoded nonce using the entropy source of
270 WEBSOCKET."
271   (base64-encode
272    (get-bytevector-n (.entropy-port websocket) 16)))
273
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
278 KEY."
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)))
285
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)
290                    (.socket websocket))
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)
302           (begin
303             (websocket-close websocket)
304             ((.on-error websocket) websocket
305              (format #f "websocket handshake failed: ~s"
306                      (uri->string (.uri websocket)))))))))
307
308 (define (open-entropy-port)
309   "Return an open input port to a reliable source of entropy for the
310 current system."
311   (if (file-exists? "/dev/urandom")
312       (open-input-file "/dev/urandom")
313       ;; XXX: This works as a fall back but this isn't exactly a
314       ;; reliable source of entropy.
315       (make-soft-port (vector (const #f) (const #f) (const #f)
316                               (lambda _ (let ((r (random 256))) (integer->char r)))
317                               (const #f)
318                               (const #t)) "r")))
319
320 (define-method (websocket-close (websocket <websocket>))
321   "Close the WebSocket connection for the client WEBSOCKET."
322   (let ((socket (.socket websocket)))
323     (set! (.state websocket) 'closing)
324     (write-frame (make-close-frame (make-bytevector 0)) socket)
325     ;; Per section 5.5.1 , wait for the server to close the connection
326     ;; for a reasonable amount of time.
327     (let loop ()
328       (match (select #() (vector socket) #() 1) ; 1 second timeout
329         ((#() #(socket) #()) ; there is output to read
330          (unless (port-eof? socket)
331            (read-frame socket) ; throw it away
332            (loop)))))
333     (close-port socket)
334     (close-port (.entropy-port websocket))
335     (set! (.state websocket) 'closed)))