47510672b4ebcc7ef84266000ff49e25a1bb10f4
[8sync.git] / 8sync / systems / websocket / server.scm
1 ;;; guile-websocket --- WebSocket client/server
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
3 ;;; Copyright © 2017 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;;
5 ;;; This file is part of guile-websocket.
6 ;;;
7 ;;; Guile-websocket is free software; you can redistribute it and/or modify
8 ;;; it under the terms of the GNU Lesser General Public License as
9 ;;; published by the Free Software Foundation; either version 3 of the
10 ;;; License, or (at your option) any later version.
11 ;;;
12 ;;; Guile-websocket is distributed in the hope that it will be useful,
13 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;;; Lesser General Public License for more details.
16 ;;;
17 ;;; You should have received a copy of the GNU Lesser General Public
18 ;;; License along with guile-websocket.  If not, see
19 ;;; <http://www.gnu.org/licenses/>.
20
21 ;;; Commentary:
22 ;;
23 ;; WebSocket server.
24 ;;
25 ;;; Code:
26
27 (define-module (8sync systems websocket server)
28   #:use-module (ice-9 match)
29   #:use-module (rnrs bytevectors)
30   #:use-module (rnrs io ports)
31   #:use-module (web request)
32   #:use-module (web response)
33   #:use-module (web uri)
34   #:use-module (oop goops)
35   #:use-module (8sync)
36   #:use-module (8sync ports)
37   #:use-module (8sync systems web)
38   #:use-module (8sync systems websocket frame)
39   #:use-module (8sync systems websocket utils)
40   #:export (<websocket-server>
41             .websocket-handler))
42
43 ;; See section 4.2 for explanation of the handshake.
44 (define (read-handshake-request client-socket)
45   "Read HTTP request from CLIENT-SOCKET that should contain the
46 headers required for a WebSocket handshake."
47   ;; See section 4.2.1.
48   (read-request client-socket))
49
50 (define (make-handshake-response client-key)
51   "Return an HTTP response object for upgrading to a WebSocket
52 connection for the client whose key is CLIENT-KEY, a base64 encoded
53 string."
54   ;; See section 4.2.2.
55   (let ((accept-key (make-accept-key (string-trim-both client-key))))
56     (build-response #:code 101
57                     #:headers `((upgrade . ("websocket"))
58                                 (connection . (upgrade))
59                                 (sec-websocket-accept . ,accept-key)))))
60
61 (define no-op (const #f))
62
63 (define (make-simple-counter)
64   (let ((count 0))
65     (lambda ()
66       (set! count (1+ count))
67       count)))
68
69 (define-actor <websocket-server> (<web-server>)
70   ((ws-send websocket-server-send))
71   (upgrade-paths #:init-value `(("websocket" . ,websocket-client-loop))
72                  #:allocation #:each-subclass
73                  #:accessor .upgrade-paths)
74
75   (gen-client-id #:init-thunk make-simple-counter)
76
77   ;; active websocket connections
78   (ws-clients #:init-thunk make-hash-table
79               #:accessor .ws-clients)
80
81   (on-ws-message #:init-keyword #:on-ws-message 
82                  #:getter .on-ws-message)
83   (on-ws-client-connect #:init-keyword #:on-ws-client-connect
84                         #:init-value no-op
85                         #:getter .on-ws-client-connect)
86   (on-ws-client-disconnect #:init-keyword #:on-ws-client-disconnect
87                            #:init-value no-op
88                            #:getter .on-ws-client-disconnect))
89
90 (define (web-server-gen-client-id websocket-server)
91   ((slot-ref websocket-server 'gen-client-id)))
92
93 (define (websocket-client-loop websocket-server client request body)
94   "Serve client connected via CLIENT by performing the HTTP
95 handshake and listening for control and data frames.  HANDLER is
96 called for each complete message that is received."
97   ;; TODO: We'll also want to handle stuff like the sub-protocol.
98   (define (handle-data-frame type data)
99     ((.on-ws-message websocket-server)
100      websocket-server client-id
101      (match type
102        ('text   (utf8->string data))
103        ('binary data))))
104
105   (define (read-frame-maybe)
106     (and (not (eof-object? (lookahead-u8 client)))
107          (read-frame client)))
108
109   ;; Allows other actors to send things to this specific client
110   ;; @@: We probably could just increment a counter...
111   (define client-id (web-server-gen-client-id websocket-server))
112
113   (define (close-down)
114     (close-port client)
115     (hash-remove! (.ws-clients websocket-server) client-id)
116     ((.on-ws-client-disconnect websocket-server)
117      websocket-server client-id))
118
119   (hash-set! (.ws-clients websocket-server) client-id client)
120
121   ;; Disable buffering for websockets
122   (setvbuf client 'none)
123
124   ((.on-ws-client-connect websocket-server)
125    websocket-server client-id)
126
127   (with-actor-nonblocking-ports
128    (lambda ()
129      ;; Perform the HTTP handshake and upgrade to WebSocket protocol.
130      (let* ((client-key (assoc-ref (request-headers request) 'sec-websocket-key))
131             (response (make-handshake-response client-key)))
132        (write-response response client)
133        (let loop ((fragments '())
134                   (type #f))
135          (let ((frame (read-frame-maybe)))
136            (cond
137             ;; EOF - port is closed.
138             ;; @@: Sometimes the eof object appears here as opposed to
139             ;;   at lookahead, but I'm not sure why
140             ((or (not frame) (eof-object? frame))
141              (close-down))
142             ;; Per section 5.4, control frames may appear interspersed
143             ;; along with a fragmented message.
144             ((close-frame? frame)
145              ;; Per section 5.5.1, echo the close frame back to the
146              ;; client before closing the socket.  The client may no
147              ;; longer be listening.
148              (false-if-exception
149               (write-frame (make-close-frame (frame-data frame)) client))
150              (close-down))
151             ((ping-frame? frame)
152              ;; Per section 5.5.3, a pong frame must include the exact
153              ;; same data as the ping frame.
154              (write-frame (make-pong-frame (frame-data frame)) client)
155              (loop fragments type))
156             ((pong-frame? frame) ; silently ignore pongs
157              (loop fragments type))
158             ((first-fragment-frame? frame) ; begin accumulating fragments
159              (loop (list frame) (frame-type frame)))
160             ((final-fragment-frame? frame) ; concatenate all fragments
161              (handle-data-frame type (frame-concatenate (reverse fragments)))
162              (loop '() #f))
163             ((fragment-frame? frame) ; add a fragment
164              (loop (cons frame fragments) type))
165             ((data-frame? frame) ; unfragmented data frame
166              (handle-data-frame (frame-type frame) (frame-data frame))
167              (loop '() #f)))))))))
168
169 (define (websocket-server-send websocket-server message client-id data)
170   (with-actor-nonblocking-ports
171    (lambda ()
172      (cond ((hash-ref (.ws-clients websocket-server) client-id) =>
173             (lambda (client)
174               (write-frame
175                (cond ((string? data)
176                       (make-text-frame data))
177                      ((bytevector? data)
178                       (make-binary-frame data)))
179                client)
180               ;; ok is like success, amirite
181               'ok))
182            ;; No such client with that id.
183            ;; Either it closed, or it was never there.
184            (else 'client-gone)))))