-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClientHandler.java
303 lines (258 loc) · 7.8 KB
/
ClientHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.regex.Pattern;
/**
* @author martin (cernama9@fit.cvut.cz)
* @since 6.3.15.
*/
final class ClientHandler implements Runnable
{
private Socket clientSocket;
private InputStream input;
private PrintWriter output;
private ClientStates clientState;
private String clientRobotName;
private OutputCommand oc;
private InputCommand ic;
private Boolean lineMode;
/**
* Constructs the ClientHandler
*
* @param clientSocket Client's socket
*/
public ClientHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
this.clientRobotName = null;
this.input = null;
this.output = null;
this.clientState = ClientStates.USERNAME;
this.oc = null;
this.lineMode = true;
}
/**
* Closes the connection. Flushes output and waits a for a short time before closing it
*/
private void closeConnection()
{
try
{
output.flush();
Thread.sleep(100);
input.close();
output.close();
if (!clientSocket.isClosed()) clientSocket.close();
}
catch (Exception e)
{
System.err.println("Unable to gracefully close connection.");
}
}
/**
* In case the connection hans for too long, this method can be called to gracefully timeout
*/
public void kill()
{
System.err.println("[DEBUG][!][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] We took " +
"too long, ClientHandler killer called. Sending TIMEOUT now");
oc.sendMessage(OutputCommand.MessageTypes.TIMEOUT);
closeConnection();
}
/**
* Main method, sets up streams and handles all communication logic
*/
@Override
public void run()
{
try
{
output = new PrintWriter(clientSocket.getOutputStream(), true);
input = clientSocket.getInputStream();
oc = new OutputCommand(output, clientSocket);
ic = new InputCommand(input, clientSocket);
}
catch (IOException e)
{
System.err.println("Unable to open streams");
return;
}
/**
* Send a LOGIN message to client
*/
oc.sendMessage(OutputCommand.MessageTypes.LOGIN);
String inputLine = "";
/**
* Main loop
*/
while (!clientSocket.isClosed())
{
/**
* We like to read till \r\n whenever we can
*/
if (lineMode)
{
inputLine = ic.readLine();
if (inputLine == null)
{
closeConnection();
return;
}
}
/**
* Mail communication logic switch
*/
switch (clientState)
{
case USERNAME:
clientRobotName = inputLine;
oc.sendMessage(OutputCommand.MessageTypes.PASSWORD);
clientState = ClientStates.PASSWORD;
break;
case PASSWORD:
UsernameLexicalAnalyzer usernameAnalyzer = new UsernameLexicalAnalyzer();
PasswordLexicalAnalyzer passwordAnalyzer = new PasswordLexicalAnalyzer();
try
{
usernameAnalyzer.parseTokens(clientRobotName);
passwordAnalyzer.parseTokens(inputLine);
if (!Authenticator.areCredentialsValid(clientRobotName, inputLine))
throw new Exception("Credentials invalid");
}
catch (Exception e)
{
oc.sendMessage(OutputCommand.MessageTypes.LOGIN_FAILED);
closeConnection();
return;
}
oc.sendMessage(OutputCommand.MessageTypes.OK);
clientState = ClientStates.AUTHENTICATED;
lineMode = false;
break;
case AUTHENTICATED:
PayloadTypeLexicalInstancedAnalyzer payloadTypeAnalyzer = new PayloadTypeLexicalInstancedAnalyzer();
StringBuilder sb = new StringBuilder();
try
{
for (int i = 0; i < 5; i++)
{
char c = ic.readChar();
sb.append(c);
payloadTypeAnalyzer.parseCharacter(c);
}
PayloadTypeLexicalInstancedAnalyzer.PayloadModes payloadMode = payloadTypeAnalyzer.getPayloadType();
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Recognized message type - " + payloadMode);
switch (payloadMode)
{
case INFO:
lineMode = true;
clientState = ClientStates.INFO_MESSAGE;
break;
case FOTO:
lineMode = false;
clientState = ClientStates.FOTO_MESSAGE;
}
}
catch (SyntaxIncorrect syntaxIncorrect)
{
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Bad message format. Received: \"" + sb.toString() + "\"");
oc.sendMessage(OutputCommand.MessageTypes.SYNTAX_ERROR);
closeConnection();
return;
}
catch (Exception e)
{
closeConnection();
return;
}
break;
case INFO_MESSAGE:
InfoMessageLexicalAnalyzer infoMessageAnalyzer = new InfoMessageLexicalAnalyzer();
infoMessageAnalyzer.parseTokens(inputLine);
oc.sendMessage(OutputCommand.MessageTypes.OK);
clientState = ClientStates.AUTHENTICATED;
lineMode = false;
break;
case FOTO_MESSAGE:
FotoMessageLengthLexicalInstancedAnalyzer fotoMessageLengthAnalyzer = new FotoMessageLengthLexicalInstancedAnalyzer();
StringBuilder messageLengthBuilder = new StringBuilder();
while (!fotoMessageLengthAnalyzer.isStateFinal())
{
try
{
char c = ic.readChar();
fotoMessageLengthAnalyzer.parseCharacter(c);
if (fotoMessageLengthAnalyzer.isStateFinal()) break;
messageLengthBuilder.append(c);
}
catch (SyntaxIncorrect syntaxIncorrect)
{
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Bad FOTO message length format. Received: \"" +
messageLengthBuilder.toString() + "\"");
oc.sendMessage(OutputCommand.MessageTypes.SYNTAX_ERROR);
closeConnection();
return;
}
catch (Exception e)
{
closeConnection();
return;
}
}
String dataLengthString = messageLengthBuilder.toString();
int dataLength;
if (!Pattern.matches("^\\d+$", dataLengthString))
{
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Bad image length format. Received: \"" + dataLengthString + "\"");
oc.sendMessage(OutputCommand.MessageTypes.SYNTAX_ERROR);
closeConnection();
return;
}
dataLength = Integer.parseInt(dataLengthString);
byte imageData[] = ic.readBytes(dataLength);
if (imageData == null)
{
closeConnection();
return;
}
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() +
"] Received " + dataLengthString + " bytes of image data");
byte correctChecksumBytes[] = ic.readBytes(4);
if (correctChecksumBytes == null)
{
closeConnection();
return;
}
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() +
"] Received 4 bytes of image checksum");
ByteBuffer bb = ByteBuffer.wrap(correctChecksumBytes);
bb.order(ByteOrder.BIG_ENDIAN);
int correctChecksum = bb.getInt();
final int calculatedChecksum = ImageDataValidator.calculateChecksum(imageData);
if (calculatedChecksum != correctChecksum)
{
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Checksum mismatch. Received: " + correctChecksum + ", " +
"calculated: " + calculatedChecksum);
oc.sendMessage(OutputCommand.MessageTypes.BAD_CHECKSUM);
clientState = ClientStates.AUTHENTICATED;
break;
}
//TODO: save image to disk
oc.sendMessage(OutputCommand.MessageTypes.OK);
clientState = ClientStates.AUTHENTICATED;
break;
}
}
closeConnection();
}
/**
* Client state during the communication
*/
private enum ClientStates
{
USERNAME, PASSWORD, AUTHENTICATED, INFO_MESSAGE, FOTO_MESSAGE
}
}