Adding missing (c) notices (thx jxself)
[mudsync.git] / mudsync / networking.scm
1 ;;; Mudsync --- Live hackable MUD
2 ;;; Copyright © 2016 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 systems actors)
21   #:use-module (8sync agenda)
22   #:use-module (ice-9 format)
23   #:use-module (ice-9 match)
24   #:use-module (oop goops)
25
26   #:export (;; Should we be exporting these?
27             %default-server
28             %default-port
29
30             <network-manager>
31             nm-close-everything))
32
33 ;;; Networking
34 ;;; ==========
35
36 (define %default-server #f)
37 (define %default-port 8889)
38
39 (define-class <network-manager> (<actor>)
40   (server-socket #:getter nm-server-socket)
41   ;; mapping of client -> client-id
42   (clients #:getter nm-clients
43            #:init-thunk make-hash-table)
44   ;; send input to this actor
45   (send-input-to #:getter nm-send-input-to
46                  #:init-keyword #:send-input-to)
47   (message-handler
48    #:init-value
49    (make-action-dispatch
50     ((start-listening actor message)
51      (nm-install-socket actor (message-ref message 'server %default-server)
52                         (message-ref message 'port %default-port)))
53     ((send-to-client actor message client data)
54      (nm-send-to-client-id actor client data)))))
55
56 (define-method (nm-close-everything (nm <network-manager>) remove-from-agenda)
57   "Shut it down!"
58   ;; close all clients
59   (hash-for-each
60    (lambda (_ client)
61      (close client)
62      (if remove-from-agenda
63          (8sync-port-remove client)))
64    (nm-clients nm))
65   ;; reset the clients list
66   (set! (nm-clients) (make-hash-table))
67   ;; close the server
68   (close (nm-server-socket nm))
69   (if remove-from-agenda
70       (8sync-port-remove (nm-server-socket nm))))
71
72 ;; Maximum number of backlogged connections when we listen
73 (define %maximum-backlog-conns 128)     ; same as SOMAXCONN on Linux 2.X,
74                                         ; says the intarwebs
75
76 (define (nm-install-socket nm server port)
77   "Install socket on SERVER with PORT"
78   (let ((s (socket PF_INET  ; ipv4
79                    SOCK_STREAM  ; two-way connection-based byte stream
80                    0))
81         (addr (if server
82                   (inet-pton AF_INET server)
83                   INADDR_LOOPBACK)))
84     ;; Totally mimed from the Guile manual.  Not sure if we need this, but:
85     ;; http://www.unixguide.net/network/socketfaq/4.5.shtml
86     (setsockopt s SOL_SOCKET SO_REUSEADDR 1) ; reuse port even if port is busy
87     ;; Connecting to a non-specific address:
88     ;;   (bind s AF_INET INADDR_ANY port)
89     ;; Should this be an option?  Guess I don't know why we'd need it
90     ;; @@: If we wanted to support listening on a particular hostname,
91     ;;   could see 8sync's irc.scm...
92     (bind s AF_INET addr port)
93     ;; Listen to connections
94     (listen s %maximum-backlog-conns)
95
96     ;; Throw a system-error rather than block on an (accept)
97     ;; that has nothing to do
98     (fcntl s F_SETFL
99            (logior O_NONBLOCK
100                    (fcntl s F_GETFL)))
101
102     ;; @@: This is used in Guile's http server under the commit:
103     ;;       * module/web/server/http.scm (http-open): Ignore SIGPIPE. Keeps the
104     ;;         server from dying in some circumstances.
105     ;;   (sigaction SIGPIPE SIG_IGN)
106     ;; Will this break other things that use pipes for us though?
107
108     (slot-set! nm 'server-socket s)
109
110     (format #t "Listening for clients in pid: ~s\n" (getpid))
111     (8sync-port s #:read (lambda (s) (nm-new-client nm s)))
112     ;; TODO: set up periodic close of idle connections?
113     ))
114
115 (define (nm-new-client nm s)
116   "Handle new client coming in to socket S"
117   (let* ((client-connection (accept s))
118          (client-details (cdr client-connection))
119          (client (car client-connection)))
120     (format #t "New client: ~s\n" client-details)
121     (format #t "Client address: ~s\n"
122             (gethostbyaddr
123              (sockaddr:addr client-details)))
124
125     (let ((client-id (big-random-number)))
126       (hash-set! (nm-clients nm) client-id client)
127       ;; @@: Do we need an 8sync-port-wait here?
128       ;;   Is such a thing even possible? :\
129       (8sync-port client #:read (nm-make-client-receive nm client-id))
130       (<- nm (nm-send-input-to nm) 'new-client #:client client-id))))
131
132 (define (nm-make-client-receive nm client-id)
133   "Make a method to receive client data"
134   (let ((buffer '()))
135     (define (reset-buffer)
136       (set! buffer '()))
137     (define (should-read-char client)
138       (and (not (port-closed? client))
139            (char-ready? client)
140            (not (eof-object? (peek-char client)))))
141     (define (receive-handler client)
142       (while (should-read-char client)
143         (set! buffer (cons (read-char client) buffer))
144         (match buffer
145           (;; @@: Do we need the "char?"
146            (#\newline #\return (? char? line-chars) ...)
147            (let ((ready-line (list->string (reverse line-chars))))
148              ;; reset buffer
149              (set! buffer '())
150              ;; run it
151              (nm-handle-line nm client client-id ready-line)))
152           (_ #f)))
153       ;; Shut things down on closed port or EOF object
154       (cond
155        ((port-closed? client)
156         (nm-handle-port-closed nm client client-id))
157        ((and (char-ready? client)
158              (eof-object? (peek-char client)))
159         (nm-handle-port-eof nm client client-id))))
160     receive-handler))
161
162 (define (nm-handle-port-closed nm client client-id)
163   "Handle a closed port"
164   (format #t "DEBUG: handled closed port ~x\n" client-id)
165   (8sync-port-remove client)
166   (hash-remove! (nm-clients nm) client-id)
167   (<- nm (nm-send-input-to nm) 'client-closed #:client client-id))
168
169 (define-method (nm-handle-port-eof nm client client-id)
170   "Handle seeing an EOF on port"
171   (format #t "DEBUG: handled eof-object on port ~x\n" client-id)
172   (close client)
173   (8sync-port-remove client)
174   (hash-remove! (nm-clients nm) client-id)
175   (<- nm (nm-send-input-to nm) 'client-closed #:client client-id))
176
177 (define-method (nm-handle-line nm client client-id line)
178   "Handle an incoming line of input from a client"
179   (<- nm (nm-send-input-to nm) 'client-input
180       #:data line
181       #:client client-id))
182
183 (define-method (nm-send-to-client-id nm client-id data)
184   "Send DATA to TO-CLIENT id"
185   (define client-obj (hash-ref (nm-clients nm) client-id))
186   (if (not client-obj)
187       (throw 'no-such-client
188              "Asked to send data to client but that client doesn't exist"
189              #:client-id client-id
190              #:data data))
191   (display data client-obj))