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