websockets: Initial websocket support.
[8sync.git] / 8sync / systems / websocket / server.scm
1 ;;; guile-websocket --- WebSocket client/server
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
3 ;;;
4 ;;; This file is part of guile-websocket.
5 ;;;
6 ;;; Guile-websocket is free software; you can redistribute it and/or modify
7 ;;; it under the terms of the GNU Lesser General Public License as
8 ;;; published by the Free Software Foundation; either version 3 of the
9 ;;; License, or (at your option) any later version.
10 ;;;
11 ;;; Guile-websocket is distributed in the hope that it will be useful,
12 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;;; Lesser General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU Lesser General Public
17 ;;; License along with guile-websocket.  If not, see
18 ;;; <http://www.gnu.org/licenses/>.
19
20 ;;; Commentary:
21 ;;
22 ;; WebSocket server.
23 ;;
24 ;;; Code:
25
26 (define-module (8sync systems websocket server)
27   #:use-module (ice-9 match)
28   #:use-module (rnrs bytevectors)
29   #:use-module (rnrs io ports)
30   #:use-module (web request)
31   #:use-module (web response)
32   #:use-module (web uri)
33   #:use-module (oop goops)
34   #:use-module (8sync)
35   #:use-module (8sync ports)
36   #:use-module (8sync systems web)
37   #:use-module (8sync systems websocket frame)
38   #:use-module (8sync systems websocket utils)
39   #:export (<websocket-server>
40             .websocket-handler))
41
42 ;; See section 4.2 for explanation of the handshake.
43 (define (read-handshake-request client-socket)
44   "Read HTTP request from CLIENT-SOCKET that should contain the
45 headers required for a WebSocket handshake."
46   ;; See section 4.2.1.
47   (read-request client-socket))
48
49 (define (make-handshake-response client-key)
50   "Return an HTTP response object for upgrading to a WebSocket
51 connection for the client whose key is CLIENT-KEY, a base64 encoded
52 string."
53   ;; See section 4.2.2.
54   (let ((accept-key (make-accept-key (string-trim-both client-key))))
55     (build-response #:code 101
56                     #:headers `((upgrade . ("websocket"))
57                                 (connection . (upgrade))
58                                 (sec-websocket-accept . ,accept-key)))))
59
60 (define no-op (const #f))
61
62 (define (make-simple-counter)
63   (let ((count 0))
64     (lambda ()
65       (set! count (1+ count))
66       count)))
67
68 (define-actor <websocket-server> (<web-server>)
69   ((ws-send websocket-server-send))
70   (upgrade-paths #:init-value `(("websocket" .
71                                  ,(wrap-apply 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   ;; Perform the HTTP handshake and upgrade to WebSocket protocol.
128   (let* ((client-key (assoc-ref (request-headers request) 'sec-websocket-key))
129          (response (make-handshake-response client-key)))
130     (write-response response client)
131     (let loop ((fragments '())
132                (type #f))
133       (let ((frame (read-frame-maybe)))
134         (cond
135          ;; EOF - port is closed.
136          ((not frame)
137           (close-down))
138          ;; Per section 5.4, control frames may appear interspersed
139          ;; along with a fragmented message.
140          ((close-frame? frame)
141           ;; Per section 5.5.1, echo the close frame back to the
142           ;; client before closing the socket.  The client may no
143           ;; longer be listening.
144           (false-if-exception
145            (write-frame (make-close-frame (frame-data frame)) client))
146           (close-down))
147          ((ping-frame? frame)
148           ;; Per section 5.5.3, a pong frame must include the exact
149           ;; same data as the ping frame.
150           (write-frame (make-pong-frame (frame-data frame)) client)
151           (loop fragments type))
152          ((pong-frame? frame) ; silently ignore pongs
153           (loop fragments type))
154          ((first-fragment-frame? frame) ; begin accumulating fragments
155           (loop (list frame) (frame-type frame)))
156          ((final-fragment-frame? frame) ; concatenate all fragments
157           (handle-data-frame type (frame-concatenate (reverse fragments)))
158           (loop '() #f))
159          ((fragment-frame? frame) ; add a fragment
160           (loop (cons frame fragments) type))
161          ((data-frame? frame) ; unfragmented data frame
162           (handle-data-frame (frame-type frame) (frame-data frame))
163           (loop '() #f)))))))
164
165 (define (websocket-server-send websocket-server message client-id data)
166   (cond ((hash-ref (.ws-clients websocket-server) client-id) =>
167          (lambda (client)
168            (write-frame
169             (cond ((string? data)
170                    (make-text-frame data))
171                   ((bytevector? data)
172                    (make-binary-frame data)))
173             client)
174            ;; ok is like success, amirite
175            (<-reply message 'ok)))
176         (else
177          ;; No such client with that id.
178          ;; Either it closed, or it was never there.
179          (<-reply message 'client-gone))))