Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
236 changes: 72 additions & 164 deletions src/Main/Main.java
Original file line number Diff line number Diff line change
@@ -1,186 +1,94 @@
package Main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Scanner;

import discovery.CentralRegistry;
import discovery.FileData;
import discovery.Handshake;
import discovery.Node;
import discovery.messages.CentralRegistryRequest;
import discovery.messages.CentralRegistryResponse;
import discovery.messages.FileRequest;
import discovery.messages.FileResponse;
import discovery.messages.TransferRequest;
import discovery.messages.TransferResponse;
import p2p.BroadCastTransfer;
import p2p.ConnectionHandlerSequential;
import discovery.CentralRegistry;
import p2p.FileReciever;
import p2p.ObjectTransfer;
import testing.FileTesting;
import utils.Config;

public class Main {
public static void main(String[] args) throws IOException {
// Initialize nodes

// args are as follows
// args[0] = central / peer -> decides the role
// args[1] = IP of self ( for listening for connections)
// args[2] = port of self
// args[3] = only if it is peer // (central IP)
// args[4] = only if it is a peer (central port)



if(args[0].equals("testing")) {
String filePath = new File(Config.getTestDir(), args[1]).getPath();
int maxLines = 1000; // Assume a maximum number of lines in the file
String[] paths = new String[maxLines]; // Create an array with the assumed size
int index = 0;

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // Trim the line to remove any leading/trailing whitespace
if (!line.isEmpty()) { // Ignore empty lines
if (index >= maxLines) {
throw new RuntimeException("Exceeded maximum number of lines: " + maxLines);
}
paths[index++] = line; // Add the path to the array
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to read the file: " + filePath, e);
}

// Resize the array to the actual number of paths read
String[] result = new String[index];
System.arraycopy(paths, 0, result, 0, index);
FileTesting.test(result);
}


if(args[0].equals("central")) {
Node central = new Node();
central.setPeerIP(args[1]);
central.setPeerPort(Integer.parseInt(args[2]));
CentralRegistry.start(central);
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Usage: java Main <peer|central> [args...]");
return;
}


if(args[0].equals("peer")) {
// one does this
Node client = new Node();
client.setPeerIP(args[1]);
client.setPeerPort(Integer.parseInt(args[2]));





Node central = new Node();
central.setPeerIP(args[3]);
central.setPeerPort(Integer.parseInt(args[4]));






try {



Handshake.setClient(client);
Handshake.setCentralRegistry(central);




Thread t = new Thread(() -> Handshake.start(client.getPeerPort() , client));
t.start(); //this thread line will be started for each of the peer


Scanner scanner = new Scanner(System.in);
System.out.print("Enter command (upload <FilePath> or download <FileHash>): ");

while (true) {

String userInput = scanner.nextLine().trim();

// Exit condition
if (userInput.equalsIgnoreCase("exit")) {
System.out.println("Exiting program...");
break;
}

// Split the input into command and argument
String[] parts = userInput.split(" ");
if (parts.length < 2) {
System.out.println("Invalid command. Usage: upload <FilePath> or download <FileHash>");
continue;
}
if (args[0].equals("central")) {
Node central = new Node();
central.setPeerIP(args[1]);
central.setPeerPort(Integer.parseInt(args[2]));
System.out.println("Central Registry started...");
CentralRegistry.start(central); // blocks and handles requests
}

else if (args[0].equals("peer")) {
Node client = new Node();
client.setPeerIP(args[1]);
client.setPeerPort(Integer.parseInt(args[2]));

Node central = new Node();
central.setPeerIP(args[3]);
central.setPeerPort(Integer.parseInt(args[4]));

Handshake.setClient(client);
Handshake.setCentralRegistry(central);

Thread handshakeThread = new Thread(() -> {
Handshake.start(client.getPeerPort(), client);
});
handshakeThread.start();

String command = parts[0];
String argument = parts[1];

// Process the command
switch (command.toLowerCase()) {
case "upload":
// Start a new thread for upload
FileData fileupload = new FileData(argument);
System.out.println("The Hash of the File is " + fileupload.getFileHash());
Handshake.registerFile(fileupload , argument);
break;
case "download":
// Start a new thread for download
FileReciever.downloadFile(argument, central);

break;
case "broadcastfile":
FileData f = new FileData(argument);

System.out.println("The File Hash of the File to be broadcasted is " + f.getFileHash());
System.out.println("Type broadcast to enter broadcasting period");

userInput = scanner.nextLine().trim();
BroadCastTransfer.BroadcastFile(f , Handshake.getClient() , argument);
break;

case "broadcastrecieve":
BroadCastTransfer.RecieveFile(argument);
break;

default:
System.out.println("Invalid command. Usage: upload <FilePath> or download <FileHash>");
break;
System.out.println("Peer started. Commands: upload <FilePath(s)>, download <FileHash>, exit");

Scanner sc = new Scanner(System.in);

while (true) {
System.out.print("> ");
String command = sc.nextLine();

if (command.startsWith("upload ")) {
String pathsStr = command.substring(7).trim();
String[] files = pathsStr.split(";");
System.out.print("Enter passkey for these file(s): ");
String passkey = sc.nextLine();

for (String filePath : files) {
File fCheck = new File(filePath.trim());
if (!fCheck.exists()) {
System.out.println("File not found: " + filePath);
continue;
}
try {
FileData f = new FileData(filePath.trim());
Handshake.registerFile(f, filePath.trim(), passkey);
System.out.println("File registered: " + filePath);
System.out.println("File hash: " + f.getFileHash()); // <-- HASH PRINTED HERE
} catch (IOException e) {
System.out.println("Error reading file: " + filePath);
}
}
}

scanner.close();

else if (command.startsWith("download ")) {
String fileHash = command.substring(9).trim();
System.out.print("Enter passkey to download the file: ");
String passkey = sc.nextLine();
FileReciever.downloadFile(fileHash, central, passkey);
}


} catch (IOException e) {
e.printStackTrace();
else if (command.equals("exit")) {
System.out.println("Exiting...");
break;
}

else {
System.out.println("Invalid command.");
}
}
}


// System.out.println("GO CHECK README FOR TUTORIAL");



}
}
}
55 changes: 23 additions & 32 deletions src/discovery/FileData.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileData implements Serializable{
public class FileData implements Serializable {

// Fields representing file metadata
private String fileName;
private long fileSize; // Size in bytes
private String fileType; // MIME type or file extension
private String fileHash; // Checksum or hash for integrity verification

// New fields for passkey-protected encryption
private String encFileKeyBase64; // Encrypted AES file key, Base64 encoded
private String saltBase64; // Salt for PBKDF2 key derivation, Base64 encoded

// Constructors
public FileData() {
// Default constructor
Expand Down Expand Up @@ -44,45 +48,30 @@ public FileData(String filePath) throws IOException {
this.fileHash = calculateFileHash(file);
}

// Getters and Setters
public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public long getFileSize() {
return fileSize;
}
// Getters and Setters for existing fields
public String getFileName() { return fileName; }
public void setFileName(String fileName) { this.fileName = fileName; }

public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public long getFileSize() { return fileSize; }
public void setFileSize(long fileSize) { this.fileSize = fileSize; }

public String getFileType() {
return fileType;
}
public String getFileType() { return fileType; }
public void setFileType(String fileType) { this.fileType = fileType; }

public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileHash() { return fileHash; }
public void setFileHash(String fileHash) { this.fileHash = fileHash; }

public String getFileHash() {
return fileHash;
}
// Getters and Setters for new fields
public String getEncFileKeyBase64() { return encFileKeyBase64; }
public void setEncFileKeyBase64(String encFileKeyBase64) { this.encFileKeyBase64 = encFileKeyBase64; }

public void setFileHash(String fileHash) {
this.fileHash = fileHash;
}
public String getSaltBase64() { return saltBase64; }
public void setSaltBase64(String saltBase64) { this.saltBase64 = saltBase64; }

// Helper method to extract the file extension
private String getFileExtension(String fileName) {
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex == -1) {
return ""; // No extension
}
if (lastDotIndex == -1) return ""; // No extension
return fileName.substring(lastDotIndex + 1);
}

Expand Down Expand Up @@ -116,6 +105,8 @@ public String toString() {
", fileSize=" + fileSize +
", fileType='" + fileType + '\'' +
", fileHash='" + fileHash + '\'' +
", encFileKeyBase64='" + encFileKeyBase64 + '\'' +
", saltBase64='" + saltBase64 + '\'' +
'}';
}
}
}
Loading