-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGnutella.java
364 lines (305 loc) · 12.4 KB
/
Gnutella.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
public class Gnutella {
public final static short DEFAULT_PORT = 6345;
public final static int MAX_CONNECTIONS = 40;
public final static int SLEEP_TIME_SECONDS = 60;
public static String DEFAULT_DIR = System.getenv("HOME") + "/.gnutella-dir/";
public static void main(String[] args) throws Exception {
Gnutella g = new Gnutella();
for (int i = 0; i < args.length; ++i) {
try {
switch (args[i++]) {
case "--port":
g.setPort(Integer.parseInt(args[i]));
break;
case "--connect":
g.connect(args[i]);
break;
case "--query":
g.addQuery(args[i], Long.parseLong(args[++i]));
break;
case "--dir":
g.setDir(args[i]);
break;
default:
System.err.println("Invalid argument: " + args[i - 1]);
return;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Invalid arguments");
}
}
g.start();
}
ArrayList<Peer> peers = new ArrayList<>();
ArrayList<Integer> servicedQueries = new ArrayList<>();
ArrayList<File> files = new ArrayList<>();
ArrayList<Query> queries = new ArrayList<>();
String dir = DEFAULT_DIR;
Ping myPing;
Gnutella() {
this.myPing = new Ping(DEFAULT_PORT, getLocalIP(), 0, 0);
}
public void setPort(int port) {
myPing.port = (short) port;
}
public void connect(String addr) {
String[] split = addr.split(":", 2);
String ip = split[0];
if (ip.equalsIgnoreCase("localhost") || ip.equalsIgnoreCase("127.0.0.1"))
{
ip = getLocalIP();
}
short connectPort = DEFAULT_PORT;
if (split.length > 1)
connectPort = Short.parseShort(split[1]);
peers.add(new Peer(new Ping(connectPort, ip, 0, 0), System.currentTimeMillis()));
}
public void addQuery(String search, long timeToLive) {
queries.add(new Query(myPing.IP, (short) (myPing.port + queries.size() + 1), search, timeToLive));
}
public void setDir(String dir) {
if (!dir.endsWith("/"))
dir += "/";
this.dir = dir;
}
public void start() {
PingListener pingListener = new PingListener();
PingSender pingSender = new PingSender();
FileSystem fileSystem = new FileSystem(this.dir);
ArrayList<QuerySender> querySenders = new ArrayList<>();
for (Query query : queries) {
querySenders.add(new QuerySender(query));
}
fileSystem.start();
pingListener.start();
pingSender.start();
for (QuerySender querySender : querySenders) {
querySender.start();
}
}
private class PingSender extends Thread {
public PingSender() {
}
public void run() {
while (true) {
try (DatagramSocket clientSocket = new DatagramSocket()) {
ArrayList<Peer> toRemovePeers = new ArrayList<>();
for (Peer peer : peers) {
if (System.currentTimeMillis() - peer.lastMessage > SLEEP_TIME_SECONDS * 1000 * 5)
toRemovePeers.add(peer);
else {
byte[] sendData = myPing.toBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(peer.ping.IP), peer.ping.port);
clientSocket.send(sendPacket);
}
}
if (toRemovePeers.size() > 0)
peers.removeAll(toRemovePeers);
TimeUnit.SECONDS.sleep(SLEEP_TIME_SECONDS);
} catch (Exception e) {
System.err.println("PingSender Error: " + e.getMessage());
e.printStackTrace();
}
}
}
}
private class PingListener extends Thread {
public PingListener() {
}
public void run() {
try (DatagramSocket serverSocket = new DatagramSocket(myPing.port)) {
while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
byte[] data = receivePacket.getData();
if (receivePacket.getLength() == Ping.BASE_PACKET_LENGTH) {
Ping recievedPing = new Ping(data);
ProccessPing pp = new ProccessPing(recievedPing);
pp.start();
} else { // Is a query
Query recievedQuery = new Query(data);
ProccessQuery pq = new ProccessQuery(recievedQuery);
pq.start();
}
}
} catch (Exception e) {
System.err.println("PingListener Error: " + e.getMessage());
e.printStackTrace();
}
}
}
private class ProccessPing extends Thread {
Ping ping;
public ProccessPing(Ping ping) {
this.ping = ping;
}
public void run() {
if (ping.equals(myPing))
return;
boolean found = false;
for (Peer peer : peers) {
if (peer.ping.equals(ping)) {
peer.lastMessage = System.currentTimeMillis();
peer.ping = ping;
found = true;
}
}
if (!found && peers.size() <= MAX_CONNECTIONS)
peers.add(new Peer(ping, System.currentTimeMillis()));
try (DatagramSocket clientSocket = new DatagramSocket()) {
byte[] sendData = myPing.toBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(ping.IP), ping.port);
clientSocket.send(sendPacket);
sendData = ping.toBytes();
for (Peer peer : peers) {
if (peer.ping.equals(ping))
continue;
sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(peer.ping.IP),
peer.ping.port);
clientSocket.send(sendPacket);
}
} catch (Exception e) {
System.err.println("ProccessPing Error: " + e.getMessage());
e.printStackTrace();
}
}
}
private class QuerySender extends Thread {
Query query;
public QuerySender(Query query) {
this.query = query;
servicedQueries.add(query.id);
}
public void run() {
try (DatagramSocket clientSocket = new DatagramSocket()) {
for (Peer peer : peers) {
byte[] sendData = this.query.toBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(peer.ping.IP), peer.ping.port);
clientSocket.send(sendPacket);
}
} catch (Exception e) {
System.err.println("QuerySender Error: " + e.getMessage());
e.printStackTrace();
}
try (ServerSocket serverSocket = new ServerSocket(query.requestPort)) {
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
int dataLength = in.readInt();
byte[] data = new byte[dataLength];
in.read(data);
FileOutputStream fos = new FileOutputStream(dir + query.searchString);
fos.write(data);
fos.close();
in.close();
System.out.println("Query " + query.id + " served, " + data.length + " bytes wrote");
} catch (Exception e) {
System.err.println("QuerySender Socket Error: " + e.getMessage());
e.printStackTrace();
}
}
}
private class ProccessQuery extends Thread {
Query query;
public ProccessQuery(Query query) {
this.query = query;
}
public void run() {
if (System.currentTimeMillis() - query.timestamp >= query.timeToLive)
return;
if (servicedQueries.contains(query.id))
return;
servicedQueries.add(query.id);
for (File file : files) {
if (query.searchString.equals(file.getName())) {
try (Socket socket = new Socket(query.requestIP, query.requestPort)) {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
byte[] fileContent = Files.readAllBytes(file.toPath());
out.writeInt(fileContent.length);
out.write(fileContent);
out.close();
socket.close();
System.out
.println("Serviced query id: " + query.id + ", " + fileContent.length + " bytes sent");
} catch (Exception e) {
System.err.println("ProccessQuery Socket Error: " + e.getMessage());
e.printStackTrace();
}
return;
}
}
// File not found
try (DatagramSocket clientSocket = new DatagramSocket()) {
byte[] sendData = query.toBytes();
for (Peer peer : peers) {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(peer.ping.IP), peer.ping.port);
clientSocket.send(sendPacket);
}
} catch (Exception e) {
System.err.println("ProccessQuery Error: " + e.getMessage());
e.printStackTrace();
}
}
}
private class FileSystem extends Thread {
private String folderLocation;
public FileSystem(String folderLocation) {
this.folderLocation = folderLocation;
}
public void run() {
File f = new File(folderLocation);
f.mkdirs();
while (true) {
updatePing();
try {
TimeUnit.SECONDS.sleep(SLEEP_TIME_SECONDS);
} catch (Exception e) {
System.err.println("FileSystem Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public void updatePing(){
findFiles(folderLocation, files);
int totalSize = 0;
for (File file : files) {
totalSize += file.length();
}
myPing.sizeOfFiles = totalSize;
myPing.numFiles = files.size();
}
private void findFiles(String directoryName, List<File> f) {
File directory = new File(directoryName);
File[] fList = directory.listFiles();
if (fList != null) {
for (File file : fList) {
if (file.isFile() && !files.contains(file)) {
f.add(file);
} else if (file.isDirectory()) {
findFiles(file.getAbsolutePath(), f);
}
}
}
}
}
public static String getLocalIP() {
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 8080);
return socket.getLocalAddress().getHostAddress();
} catch (Exception e) {
System.err.println("Error getting local IP: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}