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