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