websockets support works! :D
[mudsync.git] / mudsync / networking.scm
1 ;;; Mudsync --- Live hackable MUD
2 ;;; Copyright © 2016-2017 Christopher Allan Webber <cwebber@dustycloud.org>
3 ;;;
4 ;;; This file is part of Mudsync.
5 ;;;
6 ;;; Mudsync is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or
9 ;;; (at your option) any later version.
10 ;;;
11 ;;; Mudsync is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;;; General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with Mudsync.  If not, see <http://www.gnu.org/licenses/>.
18
19 (define-module (mudsync networking)
20   #:use-module (8sync actors)
21   #:use-module (8sync agenda)
22   #:use-module (8sync systems websocket server)
23   #:use-module (ice-9 format)
24   #:use-module (ice-9 match)
25   #:use-module (ice-9 rdelim)
26   #:use-module (ice-9 receive)
27   #:use-module (oop goops)
28
29   ;; used by web server only
30   #:use-module (sxml simple)
31   #:use-module (web request)
32   #:use-module (web response)
33   #:use-module (web uri)
34   #:use-module (mudsync package-config)
35   #:use-module (mudsync contrib mime-types)
36   #:use-module (rnrs io ports)
37
38   #:export (;; Should we be exporting these?
39             %default-server
40             %default-port
41
42             <network-manager>
43             nm-close-everything))
44
45 ;;; Networking
46 ;;; ==========
47
48 (define %default-server #f)
49 (define %default-port 8889)
50 (define %default-web-server-port 8888)
51
52 (define-actor <network-manager> (<actor>)
53   ((start-listening
54     (lambda* (actor message
55                     #:key (server %default-server)
56                     (port %default-port)
57                     (web-server-port %default-web-server-port))
58       (if web-server-port
59           (nm-install-web-server actor server web-server-port))
60       (nm-install-socket actor server port)))
61    (send-to-client nm-send-to-client-id)
62    (new-socket-client nm-new-socket-client)
63    (new-web-client nm-new-web-client)
64    (client-disconnected nm-client-disconnected)
65    (incoming-line nm-incoming-line-action))
66
67   (web-server #:accessor .web-server)
68
69   (server-socket #:getter nm-server-socket)
70   ;; mapping of client -> client-id
71   (clients #:getter nm-clients
72            #:init-thunk make-hash-table)
73   ;; send input to this actor
74   (send-input-to #:getter nm-send-input-to
75                  #:init-keyword #:send-input-to))
76
77 ;;; TODO: We should provide something like this, but this isn't used currently,
78 ;;;    and uses old deprecated code (the 8sync-port-remove stuff).
79 ;; (define-method (nm-close-everything (nm <network-manager>) remove-from-agenda)
80 ;;   "Shut it down!"
81 ;;   ;; close all clients
82 ;;   (hash-for-each
83 ;;    (lambda (_ client)
84 ;;      (close client)
85 ;;      (if remove-from-agenda
86 ;;          (8sync-port-remove client)))
87 ;;    (nm-clients nm))
88 ;;   ;; reset the clients list
89 ;;   (set! (nm-clients) (make-hash-table))
90 ;;   ;; close the server
91 ;;   (close (nm-server-socket nm))
92 ;;   (if remove-from-agenda
93 ;;       (8sync-port-remove (nm-server-socket nm))))
94
95 ;; Maximum number of backlogged connections when we listen
96 (define %maximum-backlog-conns 128)     ; same as SOMAXCONN on Linux 2.X,
97                                         ; says the intarwebs
98
99 (define (nm-install-socket nm server port)
100   "Install socket on SERVER with PORT"
101   (define s
102     (socket PF_INET  ; ipv4
103             SOCK_STREAM  ; two-way connection-based byte stream
104             0))
105   (define addr
106     (if server
107         (inet-pton AF_INET server)
108         INADDR_LOOPBACK))
109
110   ;; Totally mimed from the Guile manual.  Not sure if we need this, but:
111   ;; http://www.unixguide.net/network/socketfaq/4.5.shtml
112   (setsockopt s SOL_SOCKET SO_REUSEADDR 1) ; reuse port even if port is busy
113   ;; Connecting to a non-specific address:
114   ;;   (bind s AF_INET INADDR_ANY port)
115   ;; Should this be an option?  Guess I don't know why we'd need it
116   ;; @@: If we wanted to support listening on a particular hostname,
117   ;;   could see 8sync's irc.scm...
118   (bind s AF_INET addr port)
119   ;; Listen to connections
120   (listen s %maximum-backlog-conns)
121
122   ;; Make port non-blocking
123   (fcntl s F_SETFL (logior O_NONBLOCK (fcntl s F_GETFL)))
124
125   ;; @@: This is used in Guile's http server under the commit:
126   ;;       * module/web/server/http.scm (http-open): Ignore SIGPIPE. Keeps the
127   ;;         server from dying in some circumstances.
128   ;;   (sigaction SIGPIPE SIG_IGN)
129   ;; Will this break other things that use pipes for us though?
130
131   (slot-set! nm 'server-socket s)
132
133   (format #t "Listening for clients in pid: ~s\n" (getpid))
134
135   ;; TODO: set up periodic close of idle connections?
136   (let loop ()
137     ;; (yield)  ;; @@: Do we need this?
138     (define client-connection (accept s))
139     (<- (actor-id nm) 'new-socket-client
140         s client-connection)
141     (loop)))
142
143 (define (nm-new-socket-client nm message s client-connection)
144   "Handle new client coming in to socket S"
145   (define client-details (cdr client-connection))
146   (define client-socket (car client-connection))
147   (define client-id (big-random-number))
148   (format #t "New client: ~s\n" client-details)
149   (format #t "Client address: ~s\n"
150           (gethostbyaddr
151            (sockaddr:addr client-details)))
152   (fcntl client-socket F_SETFL (logior O_NONBLOCK (fcntl client-socket F_GETFL)))
153   (hash-set! (nm-clients nm) client-id
154              (cons 'socket client-socket))
155   (<- (nm-send-input-to nm) 'new-client #:client client-id)
156   (nm-client-receive-loop nm client-socket client-id))
157
158 (define (nm-new-web-client nm message ws-client-id)
159   ;; nm client id, as opposed to the websocket one
160   (define client-id (big-random-number))
161   (hash-set! (nm-clients nm) client-id
162              (cons 'websocket ws-client-id))
163   (<- (nm-send-input-to nm) 'new-client #:client client-id)
164   (<-reply message client-id))
165
166 (define (nm-client-receive-loop nm client-socket client-id)
167   "Make a method to receive client data"
168   (define (loop)
169     (define line (read-line client-socket))
170     (if (eof-object? line)
171         (<- (actor-id nm) 'client-disconnected client-id)
172         (begin
173           (nm-handle-line nm client-id
174                           (string-trim-right line #\return))
175           (when (actor-alive? nm)
176             (loop)))))
177   (loop))
178
179 (define (nm-client-disconnected nm message client-id)
180   "Handle a closed port"
181   (format #t "DEBUG: handled closed port ~a\n" client-id)
182   (hash-remove! (nm-clients nm) client-id)
183   (<-* `(#:actor ,nm) (nm-send-input-to nm) 'client-closed #:client client-id))
184
185 (define (nm-handle-line nm client-id line)
186   "Handle an incoming line of input from a client"
187   (<-* `(#:actor ,nm) (nm-send-input-to nm) 'client-input
188       #:data line
189       #:client client-id))
190
191 (define* (nm-send-to-client-id nm message #:key client data)
192   "Send DATA to TO-CLIENT id"
193   (define client-obj (hash-ref (nm-clients nm) client))
194   (match client-obj
195     (#f (throw 'no-such-client
196                "Asked to send data to client but that client doesn't exist"
197                #:client-id client
198                #:data data))
199     (('socket . client-socket)
200      (display data client-socket))
201     (('websocket . ws-client-id)
202      (<- (.web-server nm) 'ws-send ws-client-id data))))
203
204 (define (nm-incoming-line-action nm message client-id line)
205   "Handle LINE coming in, probably from an external message handler,
206 like the web one"
207   (nm-handle-line nm client-id line))
208
209
210 \f
211 ;;; Web server interface
212
213 (define-class <mudsync-ws-server> (<websocket-server>)
214   (network-manager #:init-keyword #:network-manager
215                    #:accessor .network-manager)
216   ;; This is a kludge... we really shouldn't have to double
217   ;; record these, should we?
218   (nm-client-ids #:init-thunk make-hash-table
219                  #:accessor .nm-client-ids))
220
221 (define (nm-install-web-server nm server web-server-port)
222   "This installs the web server, which we see in use below...."
223   (set! (.web-server nm)
224         (create-actor nm <mudsync-ws-server>
225                       #:network-manager (actor-id nm)
226                       #:port web-server-port
227                       #:http-handler (wrap-apply http-handler)
228                       #:on-ws-message (wrap-apply websocket-new-message)
229                       #:on-ws-client-connect
230                       (wrap-apply websocket-client-connect)
231                       #:on-ws-client-disconnect
232                       (wrap-apply websocket-client-disconnect))))
233
234 (define (view:main-display request body)
235   (define one-entry
236      '(div (@ (class "stream-entry"))
237           (p (b "<foo>") " Wow, it's so shiny!")))
238
239   (define body-tmpl
240     `((div (@ (id "stream-metabox"))
241            (div (@ (id "stream"))
242                 ;; ,@(map (const one-entry) (iota 25))
243                 ;; (div (@ (class "stream-entry"))
244                 ;;      (p (b "<bar>") " Last one!"))
245                 ))
246       (div (@ (id "input-metabox"))
247            (input (@ (id "main-input"))))))
248
249   (define (main-tmpl)
250     `(html (@ (xmlns "http://www.w3.org/1999/xhtml"))
251            (head (title "Mudsync!")
252                  (meta (@ (charset "UTF-8")))
253                  (link (@ (rel "stylesheet")
254                           (href "/static/css/main.css")))
255                  (script (@ (type "text/javascript")
256                             (src "/static/js/mudsync.js"))))
257            (body ,@body-tmpl)))
258   (define (write-template-to-string)
259     (with-fluids ((%default-port-encoding "UTF-8"))
260       (call-with-output-string
261         (lambda (p)
262           (sxml->xml (main-tmpl) p)))))
263   (values (build-response #:code 200
264                           #:headers '((content-type . (application/xhtml+xml))))
265           (write-template-to-string)))
266
267 (define (view:render-static request body static-path)
268   (values (build-response #:code 200
269                           #:headers `((content-type . (,(mime-type static-path)))))
270           (call-with-input-file (web-static-filepath static-path) get-bytevector-all)))
271
272 (define (view:standard-four-oh-four . args)
273   (values (build-response #:code 404
274                           #:headers '((content-type . (text/plain))))
275           "Four-oh-four!  Not found."))
276
277 (define (route request)
278   (match (split-and-decode-uri-path (uri-path (request-uri request)))
279     (() (values view:main-display '()))
280
281     (("static" static-path ...)
282      ;; TODO: make this toggle'able
283      (values view:render-static
284              (list (string-append "/" (string-join
285                                        static-path "/")))))
286
287     ;; Not found!
288     (_ (values view:standard-four-oh-four '()))))
289
290 (define (http-handler request body)
291   (receive (view args)
292       (route request)
293     (apply view request body args)))
294
295 ;; Respond to text messages by reversing the message.  Respond to
296 ;; binary messages with "hello".
297 (define (websocket-new-message websocket-server client-id data)
298   (cond
299    ((string? data)
300     (<- (.network-manager websocket-server) 'incoming-line
301         (hash-ref (.nm-client-ids websocket-server)
302                   client-id)
303         data))
304    ;; binary data is ignored
305    (else #f)))
306
307 (define (websocket-client-connect websocket-server client-id)
308   (let ((nm-client-id
309          (mbody-val (<-wait (.network-manager websocket-server)
310                             'new-web-client client-id))))
311     (hash-set! (.nm-client-ids websocket-server)
312                client-id nm-client-id)))
313
314 (define (websocket-client-disconnect websocket-server client-id)
315   (<- (.network-manager websocket-server) 'client-disconnected
316       (hash-ref (.nm-client-ids websocket-server) client-id))
317   (hash-remove! (.nm-client-ids websocket-server) client-id))