websocket + http actor starting to work
[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-class <websocket-server> (<web-server>)
61   (upgrade-paths #:init-value `(("websocket" .
62                                  ,(wrap-apply websocket-client-loop)))
63                  #:allocation #:each-subclass
64                  #:accessor .upgrade-paths)
65   (websocket-handler #:init-keyword #:websocket-handler
66                      #:getter .websocket-handler))
67
68 (define (websocket-client-loop websocket-server client request body)
69   "Serve client connected via CLIENT by performing the HTTP
70 handshake and listening for control and data frames.  HANDLER is
71 called for each complete message that is received."
72   (define (handle-data-frame type data)
73     (let* ((result   ((.websocket-handler websocket-server)
74                       (match type
75                         ('text   (utf8->string data))
76                         ('binary data))))
77            (response (cond
78                       ((string? result)
79                        (make-text-frame result))
80                       ((bytevector? result)
81                        (make-binary-frame result))
82                       ((not result)
83                        #f))))
84       (when response
85         (write-frame response client))))
86
87   (define (read-frame-maybe)
88     (and (not (eof-object? (lookahead-u8 client)))
89          (read-frame client)))
90
91   ;; Disable buffering for websockets
92   (setvbuf client 'none)
93
94   ;; Perform the HTTP handshake and upgrade to WebSocket protocol.
95   (let* ((client-key (assoc-ref (request-headers request) 'sec-websocket-key))
96          (response (make-handshake-response client-key)))
97     (write-response response client)
98     (let loop ((fragments '())
99                (type #f))
100       (let ((frame (read-frame-maybe)))
101         (cond
102          ;; EOF - port is closed.
103          ((not frame)
104           (close-port client))
105          ;; Per section 5.4, control frames may appear interspersed
106          ;; along with a fragmented message.
107          ((close-frame? frame)
108           ;; Per section 5.5.1, echo the close frame back to the
109           ;; client before closing the socket.  The client may no
110           ;; longer be listening.
111           (false-if-exception
112            (write-frame (make-close-frame (frame-data frame)) client))
113           (close-port client))
114          ((ping-frame? frame)
115           ;; Per section 5.5.3, a pong frame must include the exact
116           ;; same data as the ping frame.
117           (write-frame (make-pong-frame (frame-data frame)) client)
118           (loop fragments type))
119          ((pong-frame? frame) ; silently ignore pongs
120           (loop fragments type))
121          ((first-fragment-frame? frame) ; begin accumulating fragments
122           (loop (list frame) (frame-type frame)))
123          ((final-fragment-frame? frame) ; concatenate all fragments
124           (handle-data-frame type (frame-concatenate (reverse fragments)))
125           (loop '() #f))
126          ((fragment-frame? frame) ; add a fragment
127           (loop (cons frame fragments) type))
128          ((data-frame? frame) ; unfragmented data frame
129           (handle-data-frame (frame-type frame) (frame-data frame))
130           (loop '() #f)))))))