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