a6f3fcc3a3dcf4fa78f1866534f704663342843b
[WeStealzYourDataz.git] / src / uk / ac / ntu / n0521366 / wsyd / libs / net / NetworkServerUDP.java
1 /*
2  * The MIT License
3  *
4  * Copyright 2015 TJ <hacker@iam.tj>.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
25
26 import java.text.MessageFormat;
27 import java.io.IOException;
28 import java.io.ObjectStreamException;
29 import java.net.InetSocketAddress;
30 import java.net.DatagramSocket;
31 import java.net.DatagramPacket;
32 import java.net.SocketException;
33 import java.net.SocketTimeoutException;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36 import java.util.logging.LogRecord;
37 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageLogRecord;
38 import uk.ac.ntu.n0521366.wsyd.libs.net.ServiceAddressMap;
39
40
41
42 /**
43  * Dual-use multithreading network UDP server that can be used stand-alone
44  * or in a Swing GUI application as a background worker thread.
45  *
46  * @see NetworkServerAbstract
47  * @author TJ <hacker@iam.tj>
48  */
49 public class NetworkServerUDP extends NetworkServerAbstract {
50     /**
51      * Server socket.
52      */
53     private DatagramSocket _datagramSocket = null;
54     
55     /**
56      * Maximum size of UDP packet payload
57      */
58     public static final int UDP_PAYLOAD_SIZE_MAX =  65507;
59     
60     /**
61      * Construct the server with a Logger.
62      * 
63      * No socket is opened.
64      * 
65      * @param socketAddress The socket to listen on
66      * @param title source identifier for use in log messages and sent NetworkMessage objects
67      * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
68      * @param logger An instance of Logger to be used by all objects of this class
69      */
70     public NetworkServerUDP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap, Logger logger) {
71         super(socketAddress, title, serviceToHostMap, logger);
72     }
73
74     /**
75      * Construct the server without a Logger.
76      * 
77      * No socket is opened.
78      * 
79      * @param socketAddress The socket to listen on
80      * @param title source identifier for use in log messages and sent NetworkMessage objects
81      * @param serviceToHostMap the map object used for host <> InetSocketAddress lookups
82      */
83     public NetworkServerUDP(WSYD_SocketAddress socketAddress, String title, ServiceAddressMap serviceToHostMap) {
84         super(socketAddress, title, serviceToHostMap);
85     }
86
87     /**
88      * Get the DatagramSocket for this service.
89      * 
90      * @return the socket
91      */
92     public DatagramSocket getSocket() {
93         return this._datagramSocket;
94     }
95
96     /**
97      * Open the socket ready for accepting packets.
98      * 
99      * It should also set a reasonable socket timeout with a call to setSoTimeout()
100      * to prevent unnecessary blocking.
101      * 
102      * @throws SocketException 
103      */
104     @Override
105     public  void serverOpen() throws SocketException {
106         _datagramSocket = new DatagramSocket(_socketAddress.getPort(), _socketAddress.getAddress());
107         _datagramSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive()
108
109         if (_socketAddress.getPort() == Network.PORTS_EPHEMERAL) {
110             // reflect the actual port in use if an ephermal port was requested
111             InetSocketAddress actualSA = (InetSocketAddress)_datagramSocket.getLocalSocketAddress();
112             _socketAddress.setAddress(actualSA.getAddress());
113             _socketAddress.setPort(actualSA.getPort());
114         }
115     }
116     
117     /**
118      * Close the socket.
119      * 
120      * @throws SocketException
121      */
122     @Override
123     public void serverClose() throws SocketException {
124         // use 'this' to ensure sub-classes refer to their own '_datagramSocket' when inheriting this method
125         if (this._datagramSocket != null)
126             this._datagramSocket.close();
127     }
128
129     /**
130      * Accept packet from remote hosts.
131      * 
132      * 
133      * 
134      * @return true if the server should continue listening
135      */
136     @Override
137     public boolean serverListen() {
138         boolean result = false;
139         byte[] dataReceive = new byte[UDP_PAYLOAD_SIZE_MAX];
140         DatagramPacket packetReceive = new DatagramPacket(dataReceive, dataReceive.length);
141         NetworkMessage messageReceived;
142         try {
143             /* blocks waiting for packet until socket timeout expires, when SocketTimeOut
144              * exception is thrown.
145             */
146             if (this.getSocket() != null)
147                 this.getSocket().receive(packetReceive);
148             else
149                 throw new SocketTimeoutException("No socket available!");
150             
151             // packet was received
152             messageReceived = NetworkMessage.deserialize(packetReceive.getData());
153             
154             // prevent loopbacks
155             if (!messageReceived.getSender().equals(_title)) {
156             
157                 // add or update the last-seen time of the Sender host in the known services map
158                 ServiceAddressMap.LastSeenHost host = new ServiceAddressMap.LastSeenHost((InetSocketAddress)packetReceive.getSocketAddress());
159                 this._serviceToHostMap.put(messageReceived.getSender(), host);
160                 log(Level.FINEST, _title, MessageFormat.format("Added \"{0}\" to service map", messageReceived.getSender()));
161
162                 // pass the message to the process() method in the Owner Thread
163                 publish(messageReceived);
164
165                 result = true; // successful
166             }
167
168         } catch (SocketTimeoutException e) {
169             result = false; // no packet received
170             if (this._simulate) {
171                 LogRecord record = new LogRecord(Level.FINEST, "Simulated received message");
172                 record.setSourceClassName("Simulator");
173                 record.setMillis(System.currentTimeMillis());
174                 MessageLogRecord m = new MessageLogRecord(record);
175                 publish(new NetworkMessage("Log","Simulator",m));
176                 result = true;
177             }
178             
179         } catch (ObjectStreamException e) {
180             /* order of these Exception catches is important
181              * Deeper sub-classes must be listed before their super classes
182              */
183             // TODO: serverListen() add ObjectStreamException handler
184             System.err.println("ObjectStreamException");
185
186         } catch (IOException e) {
187             // TODO: serverListen() add IOException handler
188             System.err.println("IOException");
189
190         } catch (ClassNotFoundException e) {
191             // TODO: serverListen() add ClassNotFoundException handler
192             System.err.println("ClassNotFoundException");
193         }
194
195         return result;
196     }
197
198     /**
199      * Send an unsolicited message to a remote service.
200      * 
201      * This method is called by the main worker loop if there is a message to
202      * be sent.
203      * 
204      * @param message must have its _serviceTarget parameter set
205      * @return true if the message was sent
206      */
207     @Override
208     protected boolean serverSend(NetworkMessage message) {
209         boolean result = false;
210
211         if (message != null) {
212             ServiceAddressMap.LastSeenHost host = _serviceToHostMap.get(message.getTarget());
213             if (host != null) {
214                 InetSocketAddress address = host.address;
215                 if (address != null) {
216                     message.setSender(_title);
217                     try {
218                         byte[] dataSend = NetworkMessage.serialize(message);
219                         DatagramPacket packetSend = new DatagramPacket(dataSend, dataSend.length);
220                         // set target's remote host address and port
221                         packetSend.setAddress(address.getAddress());
222                         packetSend.setPort(address.getPort());
223
224                         // acknowledge receipt
225                         this.getSocket().send(packetSend);
226                         log(Level.FINEST, _title,
227                             MessageFormat.format("Sending packet for {0} to {1} ({3}:{4}) from {2}",
228                                 message.getIntent(),
229                                 message.getTarget(),
230                                 message.getSender(),
231                                 packetSend.getAddress().getHostAddress(),
232                                 packetSend.getPort()
233                             )
234                         );
235
236                         result = true; // successful
237                     } catch (IOException e) {
238                         // TODO: serverSend() add IOException handler
239                         e.printStackTrace();
240                     }
241                 }
242             } else {
243                 log(Level.WARNING, _title, MessageFormat.format("Unable to send message for \"{0}\" to unknown target \"{1}\"", message.getIntent(), message.getTarget()));
244             }
245         }
246         return result;
247     }
248
249     /* XXX: Methods below here all execute on the GUI Event Dispatch Thread */
250     
251     /**
252      * Clean up after doInBackground() has returned.
253      * 
254      * This method will run on the Owner Thread so must complete quickly.
255      */
256     @Override
257     protected  void done() {
258         // TODO: done() implement any clean-up after doInBackground() has returned
259     }
260 }