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