1 ;;; Mudsync --- Live hackable MUD
2 ;;; Copyright © 2016-2017 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;; This file is part of Mudsync.
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.
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.
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/>.
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)
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)
38 #:export (;; Should we be exporting these?
48 (define %default-server #f)
49 (define %default-port 8889)
50 (define %default-web-server-port 8888)
52 (define-actor <network-manager> (<actor>)
54 (lambda* (actor message
55 #:key (server %default-server)
57 (web-server-port %default-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))
67 (web-server #:accessor .web-server)
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))
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)
81 ;; ;; close all clients
85 ;; (if remove-from-agenda
86 ;; (8sync-port-remove client)))
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))))
95 ;; Maximum number of backlogged connections when we listen
96 (define %maximum-backlog-conns 128) ; same as SOMAXCONN on Linux 2.X,
99 (define (nm-install-socket nm server port)
100 "Install socket on SERVER with PORT"
102 (socket PF_INET ; ipv4
103 SOCK_STREAM ; two-way connection-based byte stream
107 (inet-pton AF_INET server)
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)
122 ;; Make port non-blocking
123 (fcntl s F_SETFL (logior O_NONBLOCK (fcntl s F_GETFL)))
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?
131 (slot-set! nm 'server-socket s)
133 (format #t "Listening for clients in pid: ~s\n" (getpid))
135 ;; TODO: set up periodic close of idle connections?
137 ;; (yield) ;; @@: Do we need this?
138 (define client-connection (accept s))
139 (<- (actor-id nm) 'new-socket-client
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"
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))
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))
166 (define (nm-client-receive-loop nm client-socket client-id)
167 "Make a method to receive client data"
169 (define line (read-line client-socket))
170 (if (eof-object? line)
171 (<- (actor-id nm) 'client-disconnected client-id)
173 (nm-handle-line nm client-id
174 (string-trim-right line #\return))
175 (when (actor-alive? nm)
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))
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
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))
195 (#f (throw 'no-such-client
196 "Asked to send data to client but that client doesn't exist"
199 (('socket . client-socket)
200 (display data client-socket))
201 (('websocket . ws-client-id)
202 (<- (.web-server nm) 'ws-send ws-client-id data))))
204 (define (nm-incoming-line-action nm message client-id line)
205 "Handle LINE coming in, probably from an external message handler,
207 (nm-handle-line nm client-id line))
211 ;;; Web server interface
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))
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))))
234 (define (view:main-display request body)
236 '(div (@ (class "stream-entry"))
237 (p (b "<foo>") " Wow, it's so shiny!")))
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!"))
246 (div (@ (id "input-metabox"))
247 (input (@ (id "main-input"))))))
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"))))
258 (define (write-template-to-string)
259 (with-fluids ((%default-port-encoding "UTF-8"))
260 (call-with-output-string
262 (sxml->xml (main-tmpl) p)))))
263 (values (build-response #:code 200
264 #:headers '((content-type . (application/xhtml+xml))))
265 (write-template-to-string)))
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)))
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."))
277 (define (route request)
278 (match (split-and-decode-uri-path (uri-path (request-uri request)))
279 (() (values view:main-display '()))
281 (("static" static-path ...)
282 ;; TODO: make this toggle'able
283 (values view:render-static
284 (list (string-append "/" (string-join
288 (_ (values view:standard-four-oh-four '()))))
290 (define (http-handler request body)
293 (apply view request body args)))
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)
300 (<- (.network-manager websocket-server) 'incoming-line
301 (hash-ref (.nm-client-ids websocket-server)
304 ;; binary data is ignored
307 (define (websocket-client-connect websocket-server 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)))
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))