Merge branch 'dev' into jeremi

# Conflicts:
#	app/src/main/java/lightcontainer/protocol/rules/reader/RetrieveOkRule.java
#	app/src/main/java/lightcontainer/protocol/rules/reader/SendOkRule.java
#	app/src/main/java/lightcontainer/protocol/rules/writer/GetFileErrorRule.java
#	app/src/main/java/lightcontainer/protocol/rules/writer/GetFileOkRule.java
#	app/src/main/java/lightcontainer/protocol/rules/writer/SaveFileErrorRule.java
#	app/src/main/java/lightcontainer/protocol/rules/writer/SaveFileOkRule.java
This commit is contained in:
Jérémi N ‘EndMove’ 2022-03-19 17:41:30 +01:00
commit 45f1bf20f7
Signed by: EndMove
GPG Key ID: 65C4A02E1F5371A4
56 changed files with 633 additions and 338 deletions

View File

@ -3,6 +3,7 @@
*/ */
package lightcontainer; package lightcontainer;
import lightcontainer.domains.FFETimer;
import lightcontainer.domains.server.MulticastServerListener; import lightcontainer.domains.server.MulticastServerListener;
import lightcontainer.domains.server.UnicastServerListener; import lightcontainer.domains.server.UnicastServerListener;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
@ -17,13 +18,14 @@ import lightcontainer.storage.JsonAdapter;
import lightcontainer.storage.Repository; import lightcontainer.storage.Repository;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Timer;
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
setupVM(); setupVM();
Repository repositoryStorage = prepareStorage(); Repository repositoryStorage = prepareStorage();
// Create all repository // Create all repository
ClientHandlerRepository clientRep = new ClientHandlerRepository(); ClientHandlerRepository clientRep = new ClientHandlerRepository();
StoreProcessorRepository storeRep = new StoreProcessorRepository(); StoreProcessorRepository storeRep = new StoreProcessorRepository();
@ -36,6 +38,11 @@ public class App {
FileFrontEnd ffe = new FileFrontEnd(clientRep, storeRep, protocolRep); FileFrontEnd ffe = new FileFrontEnd(clientRep, storeRep, protocolRep);
new UnicastServerListener(ffe, clientRep, protocolRep, repositoryStorage, repositoryStorage.getUnicastPort()); new UnicastServerListener(ffe, clientRep, protocolRep, repositoryStorage, repositoryStorage.getUnicastPort());
new MulticastServerListener(ffe, storeRep, protocolRep, repositoryStorage.getMulticastIp(), repositoryStorage.getMulticastPort(), repositoryStorage.getNetworkInterface()); new MulticastServerListener(ffe, storeRep, protocolRep, repositoryStorage.getMulticastIp(), repositoryStorage.getMulticastPort(), repositoryStorage.getNetworkInterface());
// S'occupe de distribué les timeout pour les SBE plus connecté et donc de Timeout les clients
Timer ffeTimer = new Timer();
ffeTimer.schedule(new FFETimer(storeRep), 50000, 50000);
} }
private static void initProtocols(Repository repositoryStorage, ProtocolRepository protocolRep) { private static void initProtocols(Repository repositoryStorage, ProtocolRepository protocolRep) {
@ -87,9 +94,9 @@ public class App {
} }
private static void setupVM() { private static void setupVM() {
System.setProperty("javax.net.ssl.keyStore","../ffe.labo.swilabus.com.p12"); System.setProperty("javax.net.ssl.keyStore", "../ffe.labo.swilabus.com.p12");
System.setProperty("javax.net.ssl.keyStorePassword","labo2022"); System.setProperty("javax.net.ssl.keyStorePassword", "labo2022");
System.setProperty("https.protocols","TLSv1.3"); System.setProperty("https.protocols", "TLSv1.3");
} }
} }

View File

@ -0,0 +1,34 @@
package lightcontainer.domains;
import lightcontainer.interfaces.MulticastSPR;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.TimerTask;
/**
* Class s'occupant de gérer les timeout des différents SBE
*/
public class FFETimer extends TimerTask {
private final MulticastSPR processorRepository;
public FFETimer(MulticastSPR processorRepository) {
this.processorRepository = processorRepository;
}
@Override
public void run() {
System.out.println("Timer 1");
for (String domain : processorRepository.getDomains()) {
LocalDateTime lastAnnounce = processorRepository.getLastAnnounce(domain);
long secondBetween = Math.abs(ChronoUnit.SECONDS.between(lastAnnounce, LocalDateTime.now()));
System.out.println("Timer 2 : " + secondBetween);
if (secondBetween > 50) {
System.out.println("Timer 3");
processorRepository.closeStore(domain);
}
}
}
}

View File

@ -10,13 +10,13 @@ import lightcontainer.protocol.ProtocolWriter;
public class Task { public class Task {
// Variables // Variables
private TaskStatus status; private TaskStatus status;
private ProtocolWriter.ProtocolResult command; private final ProtocolWriter.ProtocolResult command;
/** /**
* Défini le context courrant dans laquelle la tâche opère * Défini le context courant dans laquelle la tâche opère
*/ */
private Context context; private final Context context;
public Task(Context context, TaskStatus status, ProtocolWriter.ProtocolResult command) { public Task(Context context, TaskStatus status, ProtocolWriter.ProtocolResult command) {
this.context = context; this.context = context;
@ -26,26 +26,29 @@ public class Task {
/** /**
* Permet de créer une instance de la class {@link Task} * Permet de créer une instance de la class {@link Task}
*
* @param context Context à utiliser pour cette tâche * @param context Context à utiliser pour cette tâche
* @param command Commande à exécuter * @param command Commande à exécuter
* @return L'instance de la tâche créée * @return L'instance de la tâche créée
*/ */
public static Task newInstance(Context context, ProtocolWriter.ProtocolResult command) { public static Task newInstance(Context context, ProtocolWriter.ProtocolResult command) {
Task task = new Task(context, TaskStatus.PENDING, command); return new Task(context, TaskStatus.PENDING, command);
return task;
} }
/** /**
* Permet de savoir si la réponse est destinée au client * Permet de savoir si la réponse est destinée au client
*
* @param storeDomain Nom du store back end fournissant la réponse. * @param storeDomain Nom du store back end fournissant la réponse.
* @return TRUE si le client doit recevoir cette réponse. * @return TRUE si le client doit recevoir cette réponse.
*/ */
public boolean isResponseOfClient(String storeDomain) { public boolean isResponseOfClient(String storeDomain) {
System.out.println(status + " - " + context.getDomain() + " | " + storeDomain);
return (status == TaskStatus.PROCESSING && context.getDomain().equals(storeDomain)); return (status == TaskStatus.PROCESSING && context.getDomain().equals(storeDomain));
} }
/** /**
* Permet de récupérer le login du client associé à la tâche * Permet de récupérer le login du client associé à la tâche
*
* @return Login du client * @return Login du client
*/ */
public String getClient() { public String getClient() {
@ -54,6 +57,7 @@ public class Task {
/** /**
* Permet de récupérer la commande à executer * Permet de récupérer la commande à executer
*
* @return Commande à exécuter * @return Commande à exécuter
*/ */
public ProtocolWriter.ProtocolResult getCommand() { public ProtocolWriter.ProtocolResult getCommand() {
@ -62,6 +66,7 @@ public class Task {
/** /**
* Permet de définir le StorBackEnd à utiliser pour cette tâche * Permet de définir le StorBackEnd à utiliser pour cette tâche
*
* @param storeDomain Le StorBackEnd à utiliser * @param storeDomain Le StorBackEnd à utiliser
*/ */
public void setDomain(String storeDomain) { public void setDomain(String storeDomain) {

View File

@ -1,6 +1,5 @@
package lightcontainer.domains.client; package lightcontainer.domains.client;
import lightcontainer.domains.server.UnicastServerListener;
import lightcontainer.interfaces.ClientHandlerFFE; import lightcontainer.interfaces.ClientHandlerFFE;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.interfaces.UnicastCHR; import lightcontainer.interfaces.UnicastCHR;
@ -10,36 +9,32 @@ import lightcontainer.protocol.rules.reader.SigninRule;
import lightcontainer.protocol.rules.reader.SignoutRule; import lightcontainer.protocol.rules.reader.SignoutRule;
import lightcontainer.protocol.rules.reader.SignupRule; import lightcontainer.protocol.rules.reader.SignupRule;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule;
import javax.crypto.BadPaddingException;
import javax.net.ssl.SSLHandshakeException;
import java.io.*; import java.io.*;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
/** /**
* ClientHandler * ClientHandler
* * <p>
* <!> UNICAST CLIENT <!> * <!> UNICAST CLIENT <!>
* Class communicating with the client, and * Class communicating with the client, and
* intercepting and sending files to the client. * intercepting and sending files to the client.
* *
* @version 1.1 * @author Jérémi NIHART <j.nihart@student.helmo.be>
* @since 1.0 * @version 1.1
* * @see Runnable
* @see Runnable * @see AutoCloseable
* @see AutoCloseable * @since 1.0
* @author Jérémi NIHART <j.nihart@student.helmo.be>
*/ */
public class ClientHandler implements Runnable, AutoCloseable { public class ClientHandler implements Runnable, AutoCloseable {
// Variables // Variables
private ClientHandlerFFE fileFrontEnd; private final ClientHandlerFFE fileFrontEnd;
private final Socket client; private final Socket client;
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
private Context context; private final Context context;
private boolean client_run; private boolean client_run;
private UnicastCHR repository; private final UnicastCHR repository;
private BufferedReader reader; private BufferedReader reader;
@ -60,21 +55,20 @@ public class ClientHandler implements Runnable, AutoCloseable {
/** /**
* Initialise the Client's Reader and Writer. * Initialise the Client's Reader and Writer.
* *
* @since 1.0 * @see BufferedReader
* * @see PrintWriter
* @see BufferedReader * @since 1.0
* @see PrintWriter
*/ */
private void initClient() { private void initClient() {
// Start the thread // Start the thread
try { try {
this.reader = new BufferedReader(new InputStreamReader( this.reader = new BufferedReader(new InputStreamReader(
this.client.getInputStream(), this.client.getInputStream(),
StandardCharsets.UTF_8 StandardCharsets.UTF_8
)); ));
this.writer = new PrintWriter(new OutputStreamWriter( this.writer = new PrintWriter(new OutputStreamWriter(
this.client.getOutputStream(), this.client.getOutputStream(),
StandardCharsets.UTF_8 StandardCharsets.UTF_8
), true); ), true);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -85,7 +79,7 @@ public class ClientHandler implements Runnable, AutoCloseable {
* Thread Function * Thread Function
* Start the dialogue with the client. * Start the dialogue with the client.
* *
* @since 1.0 * @since 1.0
*/ */
@Override @Override
public void run() { public void run() {
@ -116,30 +110,33 @@ public class ClientHandler implements Runnable, AutoCloseable {
ProtocolWriter.ProtocolResult writerCommand = ruleResult.getResultCommand(); ProtocolWriter.ProtocolResult writerCommand = ruleResult.getResultCommand();
// TODO : Vérifier que le StorBackEnd demandé (Pas toujours demandé) est disponible // TODO : Vérifier que le StorBackEnd demandé (Pas toujours demandé) est disponible
if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND && !fileFrontEnd.canExecuteCommand(ruleResult.getRequestDomain())) { if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND && !fileFrontEnd.canExecuteCommand(ruleResult.getRequestDomain())) {
System.out.println("[1] 1");
writer.print(ruleResult.onNotExecutable(context)); // Renvoie au client writer.print(ruleResult.onNotExecutable(context)); // Renvoie au client
writer.flush(); writer.flush();
} else if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) { } else if (ruleResult.getReceiver() == ProtocolReader.ResultCmdReceiver.STOREBACKEND) {
System.out.println("[1] 2");
fileFrontEnd.newCommand(context, writerCommand); // Envoie dans la file de tâche FileFrontEnd en attente d'un traitement d'un StorBackEnd fileFrontEnd.newCommand(context, writerCommand); // Envoie dans la file de tâche FileFrontEnd en attente d'un traitement d'un StorBackEnd
// Attend la fin de la réalisation de la tâche // Attend la fin de la réalisation de la tâche
waitTaskResponse(); waitTaskResponse();
System.out.println("[1] 4");
if (response != null) { if (response != null) {
System.out.println("[1] 5");
writer.write(response.getCommand()); // Renvoie au client writer.write(response.getCommand()); // Renvoie au client
writer.flush(); writer.flush();
response.write(this.client.getOutputStream()); // Ecrit au client si nécessaire response.write(this.client.getOutputStream()); // Ecrit au client si nécessaire
} else { } else {
System.out.println("[1] 6");
writer.print(ruleResult.onNotExecutable(context)); // Renvoie au client writer.print(ruleResult.onNotExecutable(context)); // Renvoie au client
writer.flush(); writer.flush();
} }
} else { } else {
System.out.println("[1] 3");
writer.print(writerCommand.getCommand()); // Renvoie au client writer.print(writerCommand.getCommand()); // Renvoie au client
writer.flush(); writer.flush();
} }
} else { } else {
System.out.println(4);
accessDenied(); accessDenied();
} }
} catch (IOException e) { } catch (IOException e) {
@ -153,11 +150,13 @@ public class ClientHandler implements Runnable, AutoCloseable {
this.writer.close(); this.writer.close();
this.client.close(); this.client.close();
System.out.printf("[CLIENT] %s s'est déconnecté\n", context.getLogin()); System.out.printf("[CLIENT] %s s'est déconnecté\n", context.getLogin());
} catch (IOException ignored) { } } catch (IOException ignored) {
}
} }
/** /**
* Permet de vérifier si le client possède l'accès demandé * Permet de vérifier si le client possède l'accès demandé
*
* @param ruleResult La règle * @param ruleResult La règle
* @return TRUE si le client possède l'accès demandé * @return TRUE si le client possède l'accès demandé
*/ */
@ -175,7 +174,8 @@ public class ClientHandler implements Runnable, AutoCloseable {
try { try {
ruleResult.getClass().asSubclass(SigninRule.Result.class); ruleResult.getClass().asSubclass(SigninRule.Result.class);
return true; return true;
} catch (ClassCastException e2) { } } catch (ClassCastException e2) {
}
} }
return false; return false;
@ -193,23 +193,25 @@ public class ClientHandler implements Runnable, AutoCloseable {
/** /**
* Vérifie s'il s'âgit d'une demande de déconnexion * Vérifie s'il s'âgit d'une demande de déconnexion
*
* @param ruleResult * @param ruleResult
*/ */
private void checkSignout(ProtocolReader.ProtocolResult ruleResult) { private void checkSignout(ProtocolReader.ProtocolResult ruleResult) {
try { try {
ruleResult.getClass().asSubclass(SignoutRule.Result.class); ruleResult.getClass().asSubclass(SignoutRule.Result.class);
repository.disconnect(this); repository.disconnect(this);
} catch (ClassCastException e2) { } } catch (ClassCastException e2) {
}
} }
/** /**
* Vérifie s'il s'âgit d'une demande de déconnexion * Vérifie s'il s'âgit d'une demande de déconnexion
* @param ruleResult * @param ruleResult
private void checkSignError(ProtocolWriter.ProtocolResult ruleResult) { private void checkSignError(ProtocolWriter.ProtocolResult ruleResult) {
if (ruleResult.getCommand().startsWith(SignErrorRule.NAME)) { if (ruleResult.getCommand().startsWith(SignErrorRule.NAME)) {
System.out.println("Pas pu connecter"); System.out.println("Pas pu connecter");
repository.disconnect(this); repository.disconnect(this);
} }
} }
*/ */
@ -220,12 +222,15 @@ public class ClientHandler implements Runnable, AutoCloseable {
synchronized (this) { synchronized (this) {
try { try {
this.wait(); this.wait();
} catch (InterruptedException e) { e.printStackTrace(); } } catch (InterruptedException e) {
e.printStackTrace();
}
} }
} }
/** /**
* Permet d'envoyer la réponse au client. * Permet d'envoyer la réponse au client.
*
* @param response La réponse * @param response La réponse
*/ */
public void respond(ProtocolWriter.ProtocolResult response) { public void respond(ProtocolWriter.ProtocolResult response) {
@ -239,7 +244,7 @@ public class ClientHandler implements Runnable, AutoCloseable {
* AutoClosable Function * AutoClosable Function
* Close the Client thread and resources. * Close the Client thread and resources.
* *
* @since 1.0 * @since 1.0
*/ */
@Override @Override
public void close() { public void close() {

View File

@ -107,7 +107,7 @@ public class Context {
} }
/** /**
* Permet d'ajouter des données pour la requête courrante * Permet d'ajouter des données pour la requête courante
* *
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé * @param value La valeur associée à la clé
@ -117,7 +117,7 @@ public class Context {
} }
/** /**
* Permet d'ajouter des données pour la requête courrante * Permet d'ajouter des données pour la requête courante
* *
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé * @param value La valeur associée à la clé
@ -127,7 +127,15 @@ public class Context {
} }
/** /**
* Permet de récupérer des données pour la requête courrante * @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé
*/
public void putDataLong(String key, long value) {
requestBundle.putLong(key, value);
}
/**
* Permet de récupérer des données pour la requête courante
* *
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé ou null * @return La valeur associée à la clé ou null
@ -137,7 +145,7 @@ public class Context {
} }
/** /**
* Permet de récupérer des données pour la requête courrante * Permet de récupérer des données pour la requête courante
* *
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé * @return La valeur associée à la clé
@ -146,6 +154,14 @@ public class Context {
return requestBundle.getInt(key); return requestBundle.getInt(key);
} }
/**
* @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé
*/
public long getDataLong(String key) {
return requestBundle.getLong(key);
}
/** /**
* Permet d'ajouter un fichier à l'utilisateur * Permet d'ajouter un fichier à l'utilisateur
* *
@ -156,7 +172,7 @@ public class Context {
* @param domain Domain dans lequel est stocké le fichier * @param domain Domain dans lequel est stocké le fichier
* @return TRUE si le fichier a pu être enregistré. * @return TRUE si le fichier a pu être enregistré.
*/ */
public boolean addFile(String fileName, String fileNameSalt, int size, String iv, String domain) { public boolean addFile(String fileName, String fileNameSalt, long size, String iv, String domain) {
return this.repository.addFileFor(new File(fileName, fileNameSalt, size, iv, Set.of(domain)), getLogin()); return this.repository.addFileFor(new File(fileName, fileNameSalt, size, iv, Set.of(domain)), getLogin());
} }

View File

@ -5,13 +5,16 @@ import java.util.Map;
public class RequestBundle { public class RequestBundle {
private Map<String, String> stringData = new HashMap<>(); private final Map<String, String> stringData = new HashMap<>();
private Map<String, Integer> intData = new HashMap<>(); private final Map<String, Integer> intData = new HashMap<>();
private final Map<String, Long> longData = new HashMap<>();
/** /**
* Permet d'ajouter des String * Permet d'ajouter des String
* @param key La clé permettant de retrouver la valeur *
* @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé * @param value La valeur associée à la clé
*/ */
public void putString(String key, String value) { public void putString(String key, String value) {
@ -20,7 +23,8 @@ public class RequestBundle {
/** /**
* Permet d'ajouter des int * Permet d'ajouter des int
* @param key La clé permettant de retrouver la valeur *
* @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé * @param value La valeur associée à la clé
*/ */
public void putInt(String key, int value) { public void putInt(String key, int value) {
@ -29,6 +33,7 @@ public class RequestBundle {
/** /**
* Permet de récupérer des données string * Permet de récupérer des données string
*
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé ou null * @return La valeur associée à la clé ou null
*/ */
@ -38,10 +43,28 @@ public class RequestBundle {
/** /**
* Permet de récupérer des données int * Permet de récupérer des données int
*
* @param key La clé permettant de retrouver la valeur * @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé * @return La valeur associée à la clé
*/ */
public int getInt(String key) { public int getInt(String key) {
return intData.get(key); return intData.get(key);
} }
/**
* @param key La clé permettant de retrouver la valeur
* @param value La valeur associée à la clé
*/
public void putLong(String key, long value) {
longData.put(key, value);
}
/**
*
* @param key La clé permettant de retrouver la valeur
* @return La valeur associée à la clé ou null
*/
public long getLong(String key) {
return longData.get(key);
}
} }

View File

@ -10,21 +10,21 @@ import java.io.*;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException; import java.net.SocketException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Objects; import java.util.Objects;
/** /**
* StoreProcessor * StoreProcessor
* * <p>
* <!> MULTICAST CLIENT <!> * <!> MULTICAST CLIENT <!>
* Class communicating with the storebackend and * Class communicating with the storebackend and
* processing the tasks in the FileFrontEnd * processing the tasks in the FileFrontEnd
* *
* @version 1.1 * @author Jérémi NIHART <j.nihart@student.helmo.be>
* @since 1.0 * @version 1.1
* * @see Runnable
* @see Runnable * @see AutoCloseable
* @see AutoCloseable * @since 1.0
* @author Jérémi NIHART <j.nihart@student.helmo.be>
*/ */
public class StoreProcessor extends Thread implements AutoCloseable { public class StoreProcessor extends Thread implements AutoCloseable {
// Variables // Variables
@ -32,12 +32,14 @@ public class StoreProcessor extends Thread implements AutoCloseable {
private final Socket store; private final Socket store;
private final String domain; private final String domain;
private boolean client_run; private boolean client_run;
private LocalDateTime lastAnnounce;
private BufferedReader reader; private BufferedReader reader;
private Context context; private Context context;
private PrintWriter writer; private PrintWriter writer;
private ProtocolWriter.ProtocolResult protocolResult; private ProtocolWriter.ProtocolResult protocolResult;
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
// Constructor // Constructor
public StoreProcessor(Socket socket, String domain, StoreProcessorFFE ffe, ProtocolRepository protocolRep) { public StoreProcessor(Socket socket, String domain, StoreProcessorFFE ffe, ProtocolRepository protocolRep) {
@ -81,9 +83,12 @@ public class StoreProcessor extends Thread implements AutoCloseable {
@Override @Override
public void run() { public void run() {
this.client_run = true; this.client_run = true;
while (this.client_run) { while (this.client_run) {
try { try {
waitAction(); if (protocolResult == null) { // Si on n'a pas encore la commande à envoyer
waitAction();
}
System.out.println("[SBE] Envoie commande : " + protocolResult.getCommand()); System.out.println("[SBE] Envoie commande : " + protocolResult.getCommand());
// Request // Request
@ -93,9 +98,8 @@ public class StoreProcessor extends Thread implements AutoCloseable {
try { try {
protocolResult.write(this.store.getOutputStream()); protocolResult.write(this.store.getOutputStream());
} catch (IOException writeException) { // Si SBE fermé } catch (IOException writeException) { // Si SBE fermé
System.out.println("STOPPER");
// Envoie au client que la requête n'a pu être traitée // Envoie au client que la requête n'a pu être traitée
alertAvalaible(null); alertAvailable(null);
break; break;
} }
@ -105,19 +109,19 @@ public class StoreProcessor extends Thread implements AutoCloseable {
responseCommand += "\r\n"; responseCommand += "\r\n";
ProtocolReader.ProtocolResult responseResult = protocolRep.executeReader(context, responseCommand); ProtocolReader.ProtocolResult responseResult = protocolRep.executeReader(context, responseCommand);
if (responseResult != null) { if (responseResult != null) {
System.out.println("StoreBackEnd response to client: " + responseResult.getResultCommand()); System.out.println("StoreBackEnd (" + domain + ") response to client: " + responseResult.getResultCommand());
responseResult.read( responseResult.read(
this.store.getInputStream() this.store.getInputStream()
); );
alertAvalaible(responseResult.getResultCommand()); alertAvailable(responseResult.getResultCommand());
} else { } else {
System.out.println("StoreBackEnd result: Commande null"); System.out.println("StoreBackEnd result: Commande null");
alertAvalaible(null); alertAvailable(null);
} }
} else { } else {
System.out.println("StoreBackEnd: Commande null"); System.out.println("StoreBackEnd: Commande null");
alertAvalaible(null); alertAvailable(null);
} }
} catch (IOException exception) { } catch (IOException exception) {
@ -139,6 +143,7 @@ public class StoreProcessor extends Thread implements AutoCloseable {
/** /**
* Permet de demander au StoreBackEnd d'effectuer une commande * Permet de demander au StoreBackEnd d'effectuer une commande
*
* @param protocolResult La commande à effectuer * @param protocolResult La commande à effectuer
*/ */
public void executeCommand(Context context, ProtocolWriter.ProtocolResult protocolResult) { public void executeCommand(Context context, ProtocolWriter.ProtocolResult protocolResult) {
@ -152,7 +157,7 @@ public class StoreProcessor extends Thread implements AutoCloseable {
/** /**
* Permet de déclarer le StoreBackEnd disponible * Permet de déclarer le StoreBackEnd disponible
*/ */
private void alertAvalaible(ProtocolWriter.ProtocolResult responseCommand) { private void alertAvailable(ProtocolWriter.ProtocolResult responseCommand) {
synchronized (this) { synchronized (this) {
this.protocolResult = null; this.protocolResult = null;
if (responseCommand == null) { if (responseCommand == null) {
@ -169,7 +174,9 @@ public class StoreProcessor extends Thread implements AutoCloseable {
synchronized (this) { synchronized (this) {
try { try {
this.wait(); this.wait();
} catch (InterruptedException e) { e.printStackTrace(); } } catch (InterruptedException e) {
e.printStackTrace();
}
} }
} }
@ -183,6 +190,7 @@ public class StoreProcessor extends Thread implements AutoCloseable {
public void close() { public void close() {
if (this.client_run) { if (this.client_run) {
this.client_run = false; this.client_run = false;
System.out.println("[FERMETURE SBE] " + domain);
// TODO : Gérer déconnection (enlever du repo et prévenir client et FileFrontEnd) // TODO : Gérer déconnection (enlever du repo et prévenir client et FileFrontEnd)
} }
} }
@ -206,11 +214,26 @@ public class StoreProcessor extends Thread implements AutoCloseable {
return Objects.hash(domain); return Objects.hash(domain);
} }
public boolean canProcessTask(Task task) { public boolean canProcessTask() {
return this.protocolResult == null; // Vérifier si tâche veut ce SBE return this.protocolResult == null; // Vérifier si tâche veut ce SBE
} }
public String getDomain() { public String getDomain() {
return this.domain; return this.domain;
} }
/**
* Permet de mettre à jours la dernière annonce de ce SBE au FFE
*/
public void setLastAnnounce(LocalDateTime lastAnnounce) {
this.lastAnnounce = lastAnnounce;
}
/**
* Permet de mettre à jours la dernière annonce de ce SBE au FFE
*/
public LocalDateTime getLastAnnounce() {
return lastAnnounce;
}
} }

View File

@ -94,6 +94,8 @@ public class MulticastServerListener implements Runnable {
// Add the store processor to its repository // Add the store processor to its repository
this.repository.addStore(storeProcessor); this.repository.addStore(storeProcessor);
} }
// Contient déjà le SBE donc maj de la dernière activité
this.repository.updateLastAnnounce(readerResult.getDomain());
} catch (IOException | ClassCastException exception) { } catch (IOException | ClassCastException exception) {
System.out.println("[ERREUR] Une SBE essaye de se connecter avec une mauvaise configuration : " + exception.getMessage()); System.out.println("[ERREUR] Une SBE essaye de se connecter avec une mauvaise configuration : " + exception.getMessage());
} }

View File

@ -3,7 +3,7 @@ package lightcontainer.enumerations;
import lightcontainer.domains.Task; import lightcontainer.domains.Task;
/** /**
* enumeration to define the type of a {@link Task}. * enumeration to define the type of {@link Task}.
*/ */
public enum TaskType { public enum TaskType {
SEND, SEND,

View File

@ -13,6 +13,7 @@ public interface ClientHandlerFFE {
/** /**
* Demande le traitement d'une commande * Demande le traitement d'une commande
*
* @param context Context de la requête * @param context Context de la requête
* @param command Commande à traiter * @param command Commande à traiter
*/ */

View File

@ -5,23 +5,28 @@ import lightcontainer.domains.client.StoreProcessor;
import lightcontainer.domains.server.MulticastServerListener; import lightcontainer.domains.server.MulticastServerListener;
import lightcontainer.repository.StoreProcessorRepository; import lightcontainer.repository.StoreProcessorRepository;
import java.time.LocalDateTime;
import java.util.Collection;
/** /**
* A communication interface between a {@link StoreProcessor} and the {@link StoreProcessorRepository}. * A communication interface between a {@link StoreProcessor} and the {@link StoreProcessorRepository}.
*/ */
public interface MulticastSPR { public interface MulticastSPR {
/** /**
* Setter, allow to define the ServerListener of a repository. * Setter, allow to define the ServerListener of a repository.
*
* @param server ServerListener to set as default. * @param server ServerListener to set as default.
*/ */
void setServerListener(MulticastServerListener server); void setServerListener(MulticastServerListener server);
/** /**
* Add a StorePorcessor. * Add a StorePorcessor.
*
* @param store Store processor to add. * @param store Store processor to add.
*/ */
boolean addStore(StoreProcessor store); boolean addStore(StoreProcessor store);
String findDomain(Task task); String findDomain();
void assignTask(String stor, Task task); void assignTask(String stor, Task task);
@ -36,7 +41,27 @@ public interface MulticastSPR {
/** /**
* Permet de déconnecter un SBE * Permet de déconnecter un SBE
*
* @param domain Le domaine du SBE à déconnecter * @param domain Le domaine du SBE à déconnecter
*/ */
void closeStore(String domain); void closeStore(String domain);
/**
* Permet de mettre à jours la dernière annonce de ce SBE au FFE
* @param domain Le domain s'annoncant
*/
void updateLastAnnounce(String domain);
/**
* Permet de récupérer les noms des domaines connectés au FFE
* @return Les noms des domaines connectés au FFE
*/
Collection<String> getDomains();
/**
* Permet de récupérer la dernière annonce d'un SBE
* @return La dernière annonce d'un SBE
*/
LocalDateTime getLastAnnounce(String domain);
} }

View File

@ -8,7 +8,7 @@ public interface ProtocolRepository {
<T extends ProtocolReader.ProtocolResult> T executeReader(Context context, String data); <T extends ProtocolReader.ProtocolResult> T executeReader(Context context, String data);
<T extends ProtocolWriter.ProtocolResult> T executeWriter(Context context, String cmdName, String... data); <T extends ProtocolWriter.ProtocolResult> T executeWriter(Context context, String cmdName, String... data);
void addReader(ProtocolReader reader); void addReader(ProtocolReader reader);

View File

@ -10,13 +10,15 @@ import lightcontainer.repository.FileFrontEnd;
public interface StoreProcessorFFE { public interface StoreProcessorFFE {
/** /**
* Allows a {@link StoreProcessor} to notify the FFE that it's available. * Allows a {@link StoreProcessor} to notify the FFE that it's available.
* @param store The store processor that is now available. *
* @param responseCommand * @param store The store processor that is now available.
* @param response
*/ */
void onStoreAvailable(StoreProcessor store, ProtocolWriter.ProtocolResult response); void onStoreAvailable(StoreProcessor store, ProtocolWriter.ProtocolResult response);
/** /**
* Permet de déconnecter un SBE * Permet de déconnecter un SBE
*
* @param domain Le domaine du SBE à déconnecter * @param domain Le domaine du SBE à déconnecter
*/ */
void onStoreDisconnect(String domain); void onStoreDisconnect(String domain);

View File

@ -12,18 +12,21 @@ import lightcontainer.repository.ClientHandlerRepository;
public interface UnicastCHR { public interface UnicastCHR {
/** /**
* Setter, allow to define the ServerListener of a repository. * Setter, allow to define the ServerListener of a repository.
*
* @param server ServerListener to set as default. * @param server ServerListener to set as default.
*/ */
void setServerListener(UnicastServerListener server); void setServerListener(UnicastServerListener server);
/** /**
* Add a ClientHandler. * Add a ClientHandler.
*
* @param client Client Handler to add. * @param client Client Handler to add.
*/ */
void addClient(ClientHandler client); void addClient(ClientHandler client);
/** /**
* Permet de demander la déconnection d'un client * Permet de demander la déconnection d'un client
*
* @param client Le client à déconnecter * @param client Le client à déconnecter
*/ */
void disconnect(ClientHandler client); void disconnect(ClientHandler client);

View File

@ -95,7 +95,8 @@ public abstract class ProtocolReader {
* *
* @param reader Buffer rempli du fichier * @param reader Buffer rempli du fichier
*/ */
public void read(InputStream reader) { } public void read(InputStream reader) {
}
/** /**
* Permet de récupérer le context courant * Permet de récupérer le context courant

View File

@ -23,6 +23,7 @@ public abstract class ProtocolWriter {
/** /**
* Permet de récupérer le nom de la commande. * Permet de récupérer le nom de la commande.
*
* @return Nom de la commande. * @return Nom de la commande.
*/ */
public final String getCmdName() { public final String getCmdName() {
@ -50,12 +51,15 @@ public abstract class ProtocolWriter {
/** /**
* Permet d'écrire un fichier sur le réseau. Cad envoyer le contenu d'un fichier sur le réseau. * Permet d'écrire un fichier sur le réseau. Cad envoyer le contenu d'un fichier sur le réseau.
* Redéfinissez cette méthode pour l'utiliser. * Redéfinissez cette méthode pour l'utiliser.
*
* @param writer Buffer à remplir qui sera envoyer via le réseau * @param writer Buffer à remplir qui sera envoyer via le réseau
*/ */
public void write(OutputStream writer) throws IOException {} public void write(OutputStream writer) throws IOException {
}
/** /**
* Accesseur au contexte courant sur lequel opère la commande * Accesseur au contexte courant sur lequel opère la commande
*
* @return Context * @return Context
*/ */
public Context getContext() { public Context getContext() {
@ -66,6 +70,7 @@ public abstract class ProtocolWriter {
/** /**
* Permet de contruire une commande selon une règle établie. * Permet de contruire une commande selon une règle établie.
*
* @param data Les données à ajouter dans la commande; L'ordre défini leur position dans la commande * @param data Les données à ajouter dans la commande; L'ordre défini leur position dans la commande
* @return La commande construites * @return La commande construites
*/ */
@ -74,7 +79,7 @@ public abstract class ProtocolWriter {
StringBuilder builder = new StringBuilder(this.cmdName); StringBuilder builder = new StringBuilder(this.cmdName);
for (String param : data) for (String param : data)
builder.append(" " + param); builder.append(" ").append(param);
String command = builder + "\r\n"; String command = builder + "\r\n";
Matcher ruleMatcher = this.rulePattern.matcher(command); // Vérifie que tout match (cf. Matcher). Si match alors on retourne la commande build, sinon on retourne NULL Matcher ruleMatcher = this.rulePattern.matcher(command); // Vérifie que tout match (cf. Matcher). Si match alors on retourne la commande build, sinon on retourne NULL

View File

@ -5,10 +5,10 @@ public class StandardizedDefinitions {
//Parties de regex non-utilisées en dehors de cette classe. //Parties de regex non-utilisées en dehors de cette classe.
private final static String DIGIT = "[\\x30-\\x39]"; private final static String DIGIT = "[\\x30-\\x39]";
private final static String VISIBLECHAR = "[\\x20-\\xFF]"; private final static String VISIBLECHAR = "[\\x20-\\xFF]";
private final static String PASSCHAR = "[\\x20-\\xFF]"; private final static String PASSCHAR = "[\\x22-\\xFF]";
private final static String BINARY = "[\\x00-\\xFF]"; private final static String BINARY = "[\\x00-\\xFF]";
private final static String LETTER = "[\\x41-\\x5A\\x61-\\x7A]"; private final static String LETTER = "[\\x41-\\x5A\\x61-\\x7A]";
private final static String DIGIT_LETTER = DIGIT + "|" + LETTER; private final static String DIGIT_LETTER = "[\\x30-\\x39\\x41-\\x5A\\x61-\\x7A]";
private final static String PORT = "(6553[\\x30-\\x35])|(655[\\x30-\\x32][\\x30-\\x39])|(65[\\x30-\\x34][\\x30-\\x32]{2})|(6[\\x30-\\x34][\\x30-\\x39]{3})|([\\x31-\\x35][\\x30-\\x39]{4})|([\\x30-\\x35]{0,5})|([\\x30-\\x39]{1,4})"; private final static String PORT = "(6553[\\x30-\\x35])|(655[\\x30-\\x32][\\x30-\\x39])|(65[\\x30-\\x34][\\x30-\\x32]{2})|(6[\\x30-\\x34][\\x30-\\x39]{3})|([\\x31-\\x35][\\x30-\\x39]{4})|([\\x30-\\x35]{0,5})|([\\x30-\\x39]{1,4})";
private final static String SIZE = DIGIT + "{1,10}"; private final static String SIZE = DIGIT + "{1,10}";
private final static String LINE = "\\x0D\\x0A"; private final static String LINE = "\\x0D\\x0A";
@ -18,7 +18,7 @@ public class StandardizedDefinitions {
private final static String DOMAIN = "[a-z-A-Z0-9\\.]{5,20}"; private final static String DOMAIN = "[a-z-A-Z0-9\\.]{5,20}";
private final static String HASH_FILENAME = DIGIT_LETTER + "{50,200}"; private final static String HASH_FILENAME = DIGIT_LETTER + "{50,200}";
private final static String HASH_FILECONTENT = DIGIT_LETTER + "{50,200}"; private final static String HASH_FILECONTENT = DIGIT_LETTER + "{50,200}";
private final static String FILE_INFO = HASH_FILENAME + BL + SIZE + BL + HASH_FILECONTENT; private final static String FILE_INFO = "(" + HASH_FILENAME + ")" + BL + "(" + SIZE + ")" + BL + "(" + HASH_FILECONTENT + ")";
private final static String LOGIN = DIGIT_LETTER + "{5,20}"; private final static String LOGIN = DIGIT_LETTER + "{5,20}";
//Regex à utiliser dans les différents protocoles. //Regex à utiliser dans les différents protocoles.
@ -29,11 +29,11 @@ public class StandardizedDefinitions {
public final static String FFE_SENDFILE = "^SENDFILE" + BL + FILE_INFO + LINE + "$"; public final static String FFE_SENDFILE = "^SENDFILE" + BL + FILE_INFO + LINE + "$";
public final static String SBE_SEND_RESULT_OK = "^SEND_OK" + LINE + "$"; public final static String SBE_SEND_RESULT_OK = "^SEND_OK" + LINE + "$";
public final static String SBE_SEND_RESULT_ERROR = "^SEND_ERROR" + LINE + "$"; public final static String SBE_SEND_RESULT_ERROR = "^SEND_ERROR" + LINE + "$";
public final static String FFE_ERASE_FILE = "^ERASEFILE" + BL + HASH_FILENAME + LINE + "$"; public final static String FFE_ERASE_FILE = "^ERASEFILE" + BL + "(" + HASH_FILENAME + ")" + LINE + "$";
public final static String SBE_ERASE_RESULT_OK = "^ERASE_OK" + LINE + "$"; public final static String SBE_ERASE_RESULT_OK = "^ERASE_OK" + LINE + "$";
public final static String SBE_ERASE_RESULT_ERROR = "^ERASE_ERROR" + LINE + "$"; public final static String SBE_ERASE_RESULT_ERROR = "^ERASE_ERROR" + LINE + "$";
public final static String FFE_RETRIEVE_FILE = "^RETRIEVEFILE" + BL + HASH_FILENAME + LINE + "$"; public final static String FFE_RETRIEVE_FILE = "^RETRIEVEFILE" + BL + "(" + HASH_FILENAME + ")" + LINE + "$";
public final static String SBE_RETRIEVE_RESULT_OK = "^RETRIEVE_OK" + BL + "(" + FILE_INFO + ")" + LINE + "$"; public final static String SBE_RETRIEVE_RESULT_OK = "^RETRIEVE_OK" + BL + FILE_INFO + LINE + "$";
public final static String SBE_RETRIEVE_RESULT_ERROR = "^RETRIEVE_ERROR" + LINE + "$"; public final static String SBE_RETRIEVE_RESULT_ERROR = "^RETRIEVE_ERROR" + LINE + "$";
//Client demande à FFE une tâche. FFE répond à client. //Client demande à FFE une tâche. FFE répond à client.
@ -42,7 +42,7 @@ public class StandardizedDefinitions {
public final static String FFE_SIGN_OK = "^SIGN_OK" + LINE + "$"; public final static String FFE_SIGN_OK = "^SIGN_OK" + LINE + "$";
public final static String FFE_SIGN_ERROR = "^SIGN_ERROR" + LINE + "$"; public final static String FFE_SIGN_ERROR = "^SIGN_ERROR" + LINE + "$";
public final static String CLIENT_FILE_LIST = "^FILELIST" + LINE + "$"; public final static String CLIENT_FILE_LIST = "^FILELIST" + LINE + "$";
public final static String FFE_FILE_LIST_RESULT = "^FILES" + "((" + PASSCHAR + "{1,20})!(" + DIGIT + "{1,10})){0,50}" + LINE + "$"; public final static String FFE_FILE_LIST_RESULT = "^FILES" + "( (" + PASSCHAR + "{1,20})!(" + DIGIT + "{1,10})){0,50}" + LINE + "$";
public final static String CLIENT_SAVE_FILE = "^SAVEFILE" + BL + "(" + FILENAME + ")" + BL + "(" + SIZE + ")" + LINE + "$"; public final static String CLIENT_SAVE_FILE = "^SAVEFILE" + BL + "(" + FILENAME + ")" + BL + "(" + SIZE + ")" + LINE + "$";
public final static String FFE_SAVE_FILE_OK = "^SAVEFILE_OK" + LINE + "$"; public final static String FFE_SAVE_FILE_OK = "^SAVEFILE_OK" + LINE + "$";
public final static String FFE_SAVE_FILE_ERROR = "^SAVEFILE_ERROR" + LINE + "$"; public final static String FFE_SAVE_FILE_ERROR = "^SAVEFILE_ERROR" + LINE + "$";

View File

@ -5,9 +5,11 @@ import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.RemoveFileErrorRule; import lightcontainer.protocol.rules.writer.RemoveFileErrorRule;
public class EraseErrorRule extends ProtocolReader { import static lightcontainer.protocol.StandardizedDefinitions.SBE_ERASE_RESULT_ERROR;
private static final String PATTERN = "^ERASE_ERROR\r\n$"; public class EraseErrorRule extends ProtocolReader {
//"^ERASE_ERROR\r\n$"
private static final String PATTERN = SBE_ERASE_RESULT_ERROR;
private static final String NAME = "ERASE_ERROR"; private static final String NAME = "ERASE_ERROR";

View File

@ -5,9 +5,11 @@ import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.RemoveFileOkRule; import lightcontainer.protocol.rules.writer.RemoveFileOkRule;
import static lightcontainer.protocol.StandardizedDefinitions.SBE_ERASE_RESULT_OK;
public class EraseOkRule extends ProtocolReader { public class EraseOkRule extends ProtocolReader {
private static final String PATTERN = "^ERASE_OK\r\n$"; private static final String PATTERN = SBE_ERASE_RESULT_OK;
private static final String NAME = "ERASE_OK"; private static final String NAME = "ERASE_OK";

View File

@ -7,16 +7,18 @@ import lightcontainer.protocol.rules.writer.FilesRule;
import java.util.List; import java.util.List;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_FILE_LIST;
/** /**
* Règle permettant de récupérer la liste des fichiers d'un utilisateur * Règle permettant de récupérer la liste des fichiers d'un utilisateur
*/ */
public class FilelistRule extends ProtocolReader { public class FilelistRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^FILELIST\r\n$"; private static final String PATTERN = CLIENT_FILE_LIST;
private static final String NAME = "FILELIST"; private static final String NAME = "FILELIST";
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
// Constructor // Constructor
public FilelistRule(ProtocolRepository protocolRep) { public FilelistRule(ProtocolRepository protocolRep) {

View File

@ -4,15 +4,17 @@ import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.GetFileErrorRule; import lightcontainer.protocol.rules.writer.GetFileErrorRule;
import lightcontainer.protocol.rules.writer.RemoveFileErrorRule;
import lightcontainer.protocol.rules.writer.RetrieveFileRule; import lightcontainer.protocol.rules.writer.RetrieveFileRule;
import lightcontainer.storage.ReadOnlyFile; import lightcontainer.storage.ReadOnlyFile;
import java.util.Iterator; import java.util.Iterator;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_GET_FILE;
public class GetFileRule extends ProtocolReader { public class GetFileRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^GETFILE ([^ !]{1,20})\r\n$"; //"^GETFILE ([^ !]{1,20})\r\n$"
private static final String PATTERN = CLIENT_GET_FILE;
private static final String NAME = "GETFILE"; private static final String NAME = "GETFILE";
// -- arguments // -- arguments
private static final int FILE_NAME = 0; // Index file name. private static final int FILE_NAME = 0; // Index file name.
@ -59,7 +61,7 @@ public class GetFileRule extends ProtocolReader {
// Save into bundle // Save into bundle
context.putDataString("fileName", file.getName()); context.putDataString("fileName", file.getName());
context.putDataInt("fileSize", file.getSize()); context.putDataLong("fileSize", file.getSize());
context.putDataString("fileIV", file.getIv()); context.putDataString("fileIV", file.getIv());
// Create cmd for storebacked // Create cmd for storebacked
@ -80,9 +82,11 @@ public class GetFileRule extends ProtocolReader {
return result; return result;
} }
/** TMP /**
* TMP
* TODO : But futur est de pouvoir en avoir plusieurs (sbe) * TODO : But futur est de pouvoir en avoir plusieurs (sbe)
* Cette méthode permet de choisir le domaine voulu. * Cette méthode permet de choisir le domaine voulu.
*
* @param storageIterator Les domaines * @param storageIterator Les domaines
* @return Le domain choisi * @return Le domain choisi
*/ */

View File

@ -3,14 +3,16 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import static lightcontainer.protocol.StandardizedDefinitions.SBE_HELLO;
/** /**
* Règle permettant d'être alerter de l'annoncement d'un SBE * Règle permettant d'être alerter de l'annoncement d'un SBE
*/ */
public class HelloRule extends ProtocolReader { public class HelloRule extends ProtocolReader {
//"^HELLO ([A-Za-z0-9.]{5,20}) ([\\d]{0,5})\r\n$"
private static final String PATTERN = SBE_HELLO;
private static final String PATTERN = "^HELLO ([A-Za-z0-9]{5,20}) ([0-9]{1,5})\r\n$"; private static final String NAME = "HELLO";
private static final String NAME = "HELLO";
// Index du domain dans le tableau de donnée // Index du domain dans le tableau de donnée
private static final int DOMAIN = 0; private static final int DOMAIN = 0;

View File

@ -3,15 +3,18 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.protocol.rules.writer.EraseFileRule; import lightcontainer.protocol.rules.writer.EraseFileRule;
import lightcontainer.protocol.rules.writer.RemoveFileErrorRule; import lightcontainer.protocol.rules.writer.RemoveFileErrorRule;
import lightcontainer.storage.ReadOnlyFile; import lightcontainer.storage.ReadOnlyFile;
import java.util.Iterator; import java.util.Iterator;
public class RemoveFileRule extends ProtocolReader { import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_REMOVE_FILE;
private static final String PATTERN = "^REMOVEFILE ([^ !]{1,20})\r\n$"; public class RemoveFileRule extends ProtocolReader {
//"^REMOVEFILE ([^ !]{1,20})\r\n$"
private static final String PATTERN = CLIENT_REMOVE_FILE;
private static final String NAME = "REMOVEFILE"; private static final String NAME = "REMOVEFILE";
@ -68,6 +71,7 @@ public class RemoveFileRule extends ProtocolReader {
/** /**
* TODO : But futur est de pouvoir en avoir plusieurs * TODO : But futur est de pouvoir en avoir plusieurs
* Cette méthode permet de choisir le domaine voulu. * Cette méthode permet de choisir le domaine voulu.
*
* @param storageIterator Les domaines * @param storageIterator Les domaines
* @return Le domain choisi * @return Le domain choisi
*/ */

View File

@ -3,11 +3,15 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.protocol.rules.writer.GetFileErrorRule; import lightcontainer.protocol.rules.writer.GetFileErrorRule;
import static lightcontainer.protocol.StandardizedDefinitions.SBE_RETRIEVE_RESULT_ERROR;
public class RetrieveErrorRule extends ProtocolReader { public class RetrieveErrorRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^RETRIEVE_ERROR\r\n$"; //"^RETRIEVE_ERROR\r\n$"
private static final String PATTERN = SBE_RETRIEVE_RESULT_ERROR;
private static final String NAME = "RETRIEVE_ERROR"; private static final String NAME = "RETRIEVE_ERROR";
// Variables // Variables

View File

@ -10,9 +10,12 @@ import lightcontainer.utils.SHA;
import java.io.InputStream; import java.io.InputStream;
import static lightcontainer.protocol.StandardizedDefinitions.SBE_RETRIEVE_RESULT_OK;
public class RetrieveOkRule extends ProtocolReader { public class RetrieveOkRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^RETRIEVE_OK ([A-Za-z0-9.]{50,200}) ([0-9]{1,10}) ([A-Za-z0-9.]{50,200})\r\n$"; //"^RETRIEVE_OK ([A-Za-z0-9.]{50,200}) ([0-9]{1,10}) ([A-Za-z0-9.]{50,200})\r\n$"
private static final String PATTERN = SBE_RETRIEVE_RESULT_OK;
private static final String NAME = "RETRIEVE_OK"; private static final String NAME = "RETRIEVE_OK";
// -- arguments // -- arguments
private static final int HASHED_FILE_NAME = 0; // Index hashed filename private static final int HASHED_FILE_NAME = 0; // Index hashed filename
@ -20,8 +23,8 @@ public class RetrieveOkRule extends ProtocolReader {
private static final int HASHED_FILE_CONTENT = 2; // Index hashed file content private static final int HASHED_FILE_CONTENT = 2; // Index hashed file content
// Variables // Variables
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
private String storagePath; private final String storagePath;
// Variables // Variables
public RetrieveOkRule(ProtocolRepository protocolRep, String storagePath) { public RetrieveOkRule(ProtocolRepository protocolRep, String storagePath) {
@ -32,11 +35,11 @@ public class RetrieveOkRule extends ProtocolReader {
public class Result extends ProtocolResult { public class Result extends ProtocolResult {
// Variables // Variables
private String filename; private final String filename;
private int filesize; private final long filesize;
private String hashedFileContent; private String hashedFileContent;
public Result(Context context, String filename, int filesize, String hashedFileContent) { public Result(Context context, String filename, long filesize, String hashedFileContent) {
super(context); super(context);
this.filename = filename; this.filename = filename;
this.filesize = filesize; this.filesize = filesize;
@ -47,12 +50,11 @@ public class RetrieveOkRule extends ProtocolReader {
return filename; return filename;
} }
public int getFilesize() { public long getFilesize() {
return filesize; return filesize;
} }
/** /**
* Bitch has bettern than my money
* @param reader Buffer rempli du fichier * @param reader Buffer rempli du fichier
*/ */
@Override @Override
@ -84,11 +86,11 @@ public class RetrieveOkRule extends ProtocolReader {
RetrieveOkRule.Result result = new RetrieveOkRule.Result(context, data[HASHED_FILE_NAME], Integer.parseInt(data[FILE_SIZE]), data[HASHED_FILE_CONTENT]); RetrieveOkRule.Result result = new RetrieveOkRule.Result(context, data[HASHED_FILE_NAME], Integer.parseInt(data[FILE_SIZE]), data[HASHED_FILE_CONTENT]);
// save encrypted file size into bundle // save encrypted file size into bundle
context.putDataInt("encryptedFileSize", result.getFilesize()); // TODO to long ?! context.putDataLong("encryptedFileSize", result.getFilesize()); // TODO to long ?!
context.putDataString("hashedFileName", result.getFilename()); context.putDataString("hashedFileName", result.getFilename());
// Set result command // Set result command
result.setResultCommand(protocolRep.executeWriter(context, GetFileOkRule.NAME, context.getDataString("fileName"), String.valueOf(context.getDataInt("fileSize"))), ResultCmdReceiver.CLIENT); result.setResultCommand(protocolRep.executeWriter(context, GetFileOkRule.NAME, context.getDataString("fileName"), String.valueOf(context.getDataLong("fileSize"))), ResultCmdReceiver.CLIENT);
return result; return result;
} }

View File

@ -3,15 +3,15 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.protocol.rules.writer.SaveFileErrorRule; import lightcontainer.protocol.rules.writer.SaveFileErrorRule;
import lightcontainer.protocol.rules.writer.SaveFileOkRule;
import lightcontainer.protocol.rules.writer.SendfileRule; import lightcontainer.protocol.rules.writer.SendfileRule;
import lightcontainer.utils.*; import lightcontainer.utils.*;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_SAVE_FILE;
/** /**
* Règle permettant de sauvegarder un fichier sur le SBE. * Règle permettant de sauvegarder un fichier sur le SBE.
@ -19,15 +19,16 @@ import java.security.NoSuchAlgorithmException;
*/ */
public class SavefileRule extends ProtocolReader { public class SavefileRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^SAVEFILE ([^ !]{1,20}) ([0-9]{1,10})\r\n$"; //"^SAVEFILE ([^ !]{1,20}) ([0-9]{1,10})\r\n$"
private static final String PATTERN = CLIENT_SAVE_FILE;
private static final String NAME = "SAVEFILE"; private static final String NAME = "SAVEFILE";
private static final int FILE_NAME = 0; // Index file name. private static final int FILE_NAME = 0; // Index file name.
private static final int FILE_SIZE = 1; // Index file size. private static final int FILE_SIZE = 1; // Index file size.
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
private String storagePath; private final String storagePath;
// Constructor // Constructor
public SavefileRule(ProtocolRepository protocolRep, String storagePath) { public SavefileRule(ProtocolRepository protocolRep, String storagePath) {
@ -39,13 +40,14 @@ public class SavefileRule extends ProtocolReader {
public class Result extends ProtocolResult { public class Result extends ProtocolResult {
// Variables // Variables
private String filename; private String filename;
private int size; private final long size;
// Construct // Construct
public Result(Context context, String filename, int size) { public Result(Context context, String filename, long size) {
super(context); super(context);
this.filename = filename; this.filename = filename;
this.size = size; this.size = size;
System.out.println(size);
} }
@Override @Override
@ -70,13 +72,15 @@ public class SavefileRule extends ProtocolReader {
String iv = AES_GCM.generateIV(); String iv = AES_GCM.generateIV();
// retrieve file and new size // retrieve file and new size
int encryptedFileSize = fileReceiver.receiveFile(reader, this.filename, this.size, key, iv); long encryptedFileSize = fileReceiver.receiveFile(reader, this.filename, this.size, key, iv);
if (encryptedFileSize < 0) throw new IOException(); if (encryptedFileSize < 0) throw new IOException();
System.out.println(encryptedFileSize);
String fileHash = SHA.hashFile(storagePath, this.filename); String fileHash = SHA.hashFile(storagePath, this.filename);
// On met les données de la requête actuelle // On met les données de la requête actuelle
getContext().putDataInt("size", size); getContext().putDataLong("size", size);
getContext().putDataString("iv", iv); getContext().putDataString("iv", iv);
getContext().putDataString("fileNameSalt", fileNameSalt); getContext().putDataString("fileNameSalt", fileNameSalt);

View File

@ -3,23 +3,22 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.protocol.rules.writer.SaveFileErrorRule; import lightcontainer.protocol.rules.writer.SaveFileErrorRule;
import lightcontainer.utils.ShaHasher;
import java.io.IOException; import static lightcontainer.protocol.StandardizedDefinitions.SBE_SEND_RESULT_ERROR;
import java.nio.file.Files;
import java.nio.file.Path;
/** /**
* Règle permettant de de confirmer la sauvegrade d'un fichier. * Règle permettant de de confirmer la sauvegrade d'un fichier.
*/ */
public class SendErrorRule extends ProtocolReader { public class SendErrorRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^SEND_ERROR\r\n$"; //"^SEND_ERROR\r\n$"
private static final String PATTERN = SBE_SEND_RESULT_ERROR;
private static final String NAME = "SEND_ERROR"; private static final String NAME = "SENDERROR";
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
// Constructor // Constructor
public SendErrorRule(ProtocolRepository protocolRep) { public SendErrorRule(ProtocolRepository protocolRep) {

View File

@ -5,13 +5,16 @@ import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.SaveFileOkRule; import lightcontainer.protocol.rules.writer.SaveFileOkRule;
import static lightcontainer.protocol.StandardizedDefinitions.SBE_SEND_RESULT_OK;
/** /**
* Règle permettant de de confirmer la sauvegrade d'un fichier. * Règle permettant de de confirmer la sauvegrade d'un fichier.
*/ */
public class SendOkRule extends ProtocolReader { public class SendOkRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^SEND_OK\r\n$"; //"^SEND_OK\r\n$"
private static final String PATTERN = SBE_SEND_RESULT_OK;
private static final String NAME = "SEND_OK"; private static final String NAME = "SEND_OK";

View File

@ -3,22 +3,26 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.interfaces.ProtocolRepository; import lightcontainer.interfaces.ProtocolRepository;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule; import lightcontainer.protocol.rules.writer.SignOkRule;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_SIGN_IN;
/** /**
* Règle permettant de gérer la connection d'un utilisateur * Règle permettant de gérer la connection d'un utilisateur
*/ */
public class SigninRule extends ProtocolReader { public class SigninRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^SIGNIN ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"; //"^SIGNIN ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"
private static final String PATTERN = CLIENT_SIGN_IN;
private static final String NAME = "SIGNIN"; private static final String NAME = "SIGNIN";
private static final int LOGIN = 0; // Index du domain dans le tableau de données private static final int LOGIN = 0; // Index du domain dans le tableau de données
private static final int PASSWORD = 1; // Index du port dans le tableau de données private static final int PASSWORD = 1; // Index du port dans le tableau de données
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
// Constructor // Constructor
public SigninRule(ProtocolRepository protocolRep) { public SigninRule(ProtocolRepository protocolRep) {

View File

@ -2,13 +2,16 @@ package lightcontainer.protocol.rules.reader;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolReader; import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.StandardizedDefinitions;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_SIGN_OUT;
/** /**
* Règle demandant la déconnexion du client * Règle demandant la déconnexion du client
*/ */
public class SignoutRule extends ProtocolReader { public class SignoutRule extends ProtocolReader {
//"^SIGNOUT\r\n$"
private static final String PATTERN = "^SIGNOUT\r\n$"; private static final String PATTERN = CLIENT_SIGN_OUT;
public static final String NAME = "SIGNOUT"; public static final String NAME = "SIGNOUT";

View File

@ -6,17 +6,20 @@ import lightcontainer.protocol.ProtocolReader;
import lightcontainer.protocol.rules.writer.SignErrorRule; import lightcontainer.protocol.rules.writer.SignErrorRule;
import lightcontainer.protocol.rules.writer.SignOkRule; import lightcontainer.protocol.rules.writer.SignOkRule;
import static lightcontainer.protocol.StandardizedDefinitions.CLIENT_SIGN_UP;
/** /**
* Règle permettant de gérer la création d'un utilisateur * Règle permettant de gérer la création d'un utilisateur
*/ */
public class SignupRule extends ProtocolReader { public class SignupRule extends ProtocolReader {
// Constants // Constants
private static final String PATTERN = "^SIGNUP ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"; //"^SIGNUP ([A-Za-z0-9]{5,20}) ([^ !]{5,50})\r\n$"
private static final String PATTERN = CLIENT_SIGN_UP;
private static final String NAME = "SIGNUP"; private static final String NAME = "SIGNUP";
private static final int LOGIN = 0; private static final int LOGIN = 0;
private static final int PASSWORD = 1; private static final int PASSWORD = 1;
private ProtocolRepository protocolRep; private final ProtocolRepository protocolRep;
public SignupRule(ProtocolRepository protocolRep) { public SignupRule(ProtocolRepository protocolRep) {
super(NAME, PATTERN); super(NAME, PATTERN);

View File

@ -1,15 +1,20 @@
package lightcontainer.protocol.rules.writer; package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.StandardizedDefinitions;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_ERASE_FILE;
public class EraseFileRule extends ProtocolWriter { public class EraseFileRule extends ProtocolWriter {
private static final String PATTERN = "^ERASEFILE ([A-Za-z0-9.]{50,200})\r\n$"; //"^ERASEFILE ([A-Za-z0-9.]{50,200})\r\n$"
private static final String PATTERN = FFE_ERASE_FILE;
public static String NAME = "ERASEFILE"; public static String NAME = "ERASEFILE";
public EraseFileRule() { public EraseFileRule() {
super(NAME, PATTERN); super(NAME, PATTERN);
System.out.println(PATTERN);
} }
} }

View File

@ -1,13 +1,16 @@
package lightcontainer.protocol.rules.writer; package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.StandardizedDefinitions;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_FILE_LIST_RESULT;
/** /**
* Règle permettant de construire une commande contenant la liste des fichiers d'un utilisateur * Règle permettant de construire une commande contenant la liste des fichiers d'un utilisateur
*/ */
public class FilesRule extends ProtocolWriter { public class FilesRule extends ProtocolWriter {
//"^FILES( ([^ !]{1,20})!([0-9]{1,10})){0,50}\r\n$"
private static final String PATTERN = "^FILES( ([^ !]{1,20})!([0-9]{1,10})){0,50}\r\n$"; private static final String PATTERN = FFE_FILE_LIST_RESULT;
public static final String NAME = "FILES"; public static final String NAME = "FILES";

View File

@ -10,7 +10,8 @@ import lightcontainer.utils.DeepFileEraser;
*/ */
public class GetFileErrorRule extends ProtocolWriter { public class GetFileErrorRule extends ProtocolWriter {
// Constants // Constants
private static final String PATTERN = "^GETFILE_ERROR\r\n$"; //"^GETFILE_ERROR\r\n$"
private static final String PATTERN = FFE_GET_FILE_RESULT_ERROR;
public static final String NAME = "GETFILE_ERROR"; public static final String NAME = "GETFILE_ERROR";
// Variables // Variables

View File

@ -8,16 +8,19 @@ import lightcontainer.utils.FileSender;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_GET_FILE_RESULT_OK;
public class GetFileOkRule extends ProtocolWriter { public class GetFileOkRule extends ProtocolWriter {
// Constants // Constants
private static final String PATTERN = "^GETFILE_OK ([^ !]{1,20}) ([0-9]{1,10})\r\n$"; //"^GETFILE_OK ([^ !]{1,20}) ([0-9]{1,10})\r\n$"
private static final String PATTERN = FFE_GET_FILE_RESULT_OK;
public static final String NAME = "GETFILE_OK"; public static final String NAME = "GETFILE_OK";
// -- params // -- params
private static final int FILE_NAME = 0; // Index file name hashed private static final int FILE_NAME = 0; // Index file name hashed
private static final int FILE_SIZE = 1; // Index file size private static final int FILE_SIZE = 1; // Index file size
// Variables // Variables
private String storagePath; private final String storagePath;
// Constructors // Constructors
public GetFileOkRule(String storagePath) { public GetFileOkRule(String storagePath) {
@ -27,11 +30,11 @@ public class GetFileOkRule extends ProtocolWriter {
public class Result extends ProtocolWriter.ProtocolResult { public class Result extends ProtocolWriter.ProtocolResult {
// Variables // Variables
private String filename; private final String filename;
private int filesize; private final long filesize;
// Constructors // Constructors
public Result(Context context, String filename, int filesize) { public Result(Context context, String filename, long filesize) {
super(context); super(context);
this.filename = filename; this.filename = filename;
this.filesize = filesize; this.filesize = filesize;
@ -39,17 +42,19 @@ public class GetFileOkRule extends ProtocolWriter {
/** /**
* Oh yeahh baby by tonton EndMove ;-) * Oh yeahh baby by tonton EndMove ;-)
*
* @param writer Buffer à remplir qui sera envoyer via le réseau * @param writer Buffer à remplir qui sera envoyer via le réseau
*/ */
@Override @Override
public void write(OutputStream writer) throws IOException { public void write(OutputStream writer) throws IOException {
System.out.printf("Sauvegarde du fichier : %s %d\n", this.filename, this.filesize); System.out.printf("Sauvegarde du fichier : %s %d\n", this.filename, this.filesize);
System.out.println("Encrypted size for parsing: " + getContext().getDataLong("encryptedFileSize") + " normal: " + getContext().getDataLong("fileSize"));
FileSender fileSender = new FileSender(storagePath); FileSender fileSender = new FileSender(storagePath);
fileSender.sendFile( fileSender.sendFile(
getContext().getDataString("hashedFileName"), getContext().getDataString("hashedFileName"),
writer, writer,
getContext().getDataInt("encryptedFileSize"), // Encrypted file size (because data is parsing into AES system) getContext().getDataLong("encryptedFileSize"), // Encrypted file size (because data is parsing into AES system)
getContext().getAesKey(), getContext().getAesKey(),
getContext().getDataString("fileIV") getContext().getDataString("fileIV")
); );

View File

@ -2,9 +2,12 @@ package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_REMOVE_ERROR;
public class RemoveFileErrorRule extends ProtocolWriter { public class RemoveFileErrorRule extends ProtocolWriter {
private static final String PATTERN = "^REMOVEFILE_ERROR\r\n$"; //"^REMOVEFILE_ERROR\r\n$"
private static final String PATTERN = FFE_REMOVE_ERROR;
public static String NAME = "REMOVEFILE_ERROR"; public static String NAME = "REMOVEFILE_ERROR";

View File

@ -2,9 +2,11 @@ package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
public class RemoveFileOkRule extends ProtocolWriter { import static lightcontainer.protocol.StandardizedDefinitions.FFE_REMOVE_OK;
private static final String PATTERN = "^REMOVEFILE_OK\r\n$"; public class RemoveFileOkRule extends ProtocolWriter {
//"^REMOVEFILE_OK\r\n$"
private static final String PATTERN = FFE_REMOVE_OK;
public static String NAME = "REMOVEFILE_OK"; public static String NAME = "REMOVEFILE_OK";
public RemoveFileOkRule() { public RemoveFileOkRule() {

View File

@ -2,9 +2,12 @@ package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_RETRIEVE_FILE;
public class RetrieveFileRule extends ProtocolWriter { public class RetrieveFileRule extends ProtocolWriter {
// Constants // Constants
private static final String PATTERN = "^RETRIEVEFILE ([A-Za-z0-9.]{50,200})\r\n$"; //"^RETRIEVEFILE ([A-Za-z0-9]{50,200})\r\n$"
private static final String PATTERN = FFE_RETRIEVE_FILE;
public static final String NAME = "RETRIEVEFILE"; public static final String NAME = "RETRIEVEFILE";
// Constructor // Constructor

View File

@ -5,12 +5,14 @@ import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.utils.DeepFileEraser; import lightcontainer.utils.DeepFileEraser;
import lightcontainer.utils.ShaHasher; import lightcontainer.utils.ShaHasher;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_SAVE_FILE_ERROR;
/** /**
* Règle signifiant que la sauvegarde d'un fichier a échoué * Règle signifiant que la sauvegarde d'un fichier a échoué
*/ */
public class SaveFileErrorRule extends ProtocolWriter { public class SaveFileErrorRule extends ProtocolWriter {
//"^SAVEFILE_ERROR\r\n$"
private static final String PATTERN = "^SAVEFILE_ERROR\r\n$"; private static final String PATTERN = FFE_SAVE_FILE_ERROR;
public static final String NAME = "SAVEFILE_ERROR"; public static final String NAME = "SAVEFILE_ERROR";
@ -25,13 +27,18 @@ public class SaveFileErrorRule extends ProtocolWriter {
@Override @Override
protected ProtocolResult onExecuted(Context context, String... data) { protected ProtocolResult onExecuted(Context context, String... data) {
ProtocolResult result = new ProtocolResult(context); ProtocolResult result = new ProtocolResult(context);
String fileName = context.getDataString("fileName");
String fileNameSalt = context.getDataString("fileNameSalt");
// Suppression du fichier temporaire dans le stockage du FFE if (fileName != null && fileNameSalt != null) {
ShaHasher hasher = new ShaHasher(context.getLogin() + "_" + context.getDataString("fileName")); // Suppression du fichier temporaire dans le stockage du FFE
try { ShaHasher hasher = new ShaHasher(context.getLogin() + "_" + context.getDataString("fileName"));
DeepFileEraser.eraseFile(String.format("%s/%s", this.storagePath, try {
hasher.fromSalt(hasher.saltToByte(context.getDataString("fileNameSalt"))))); DeepFileEraser.eraseFile(String.format("%s/%s", this.storagePath,
} catch (DeepFileEraser.DeepFileEraserException ignore) { } hasher.fromSalt(hasher.saltToByte(context.getDataString("fileNameSalt")))));
} catch (DeepFileEraser.DeepFileEraserException ignore) {
}
}
return result; return result;
} }
} }

View File

@ -4,12 +4,14 @@ import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.utils.DeepFileEraser; import lightcontainer.utils.DeepFileEraser;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_SAVE_FILE_OK;
/** /**
* Règle signifiant que la sauvegarde d'un fichier fût un succès * Règle signifiant que la sauvegarde d'un fichier fût un succès
*/ */
public class SaveFileOkRule extends ProtocolWriter { public class SaveFileOkRule extends ProtocolWriter {
//"^SAVEFILE_OK\r\n$"
private static final String PATTERN = "^SAVEFILE_OK\r\n$"; private static final String PATTERN = FFE_SAVE_FILE_OK;
public static final String NAME = "SAVEFILE_OK"; public static final String NAME = "SAVEFILE_OK";
@ -24,8 +26,9 @@ public class SaveFileOkRule extends ProtocolWriter {
protected ProtocolWriter.ProtocolResult onExecuted(Context context, String... data) { protected ProtocolWriter.ProtocolResult onExecuted(Context context, String... data) {
ProtocolWriter.ProtocolResult result = new ProtocolWriter.ProtocolResult(context); ProtocolWriter.ProtocolResult result = new ProtocolWriter.ProtocolResult(context);
System.out.println("===> Save en json " + context.getDomain() + " - " + context.getLogin());
// Sauvegarder dans JSON // Sauvegarder dans JSON
context.addFile(context.getDataString("fileName"), context.getDataString("fileNameSalt"), context.getDataInt("size"), context.getDataString("iv"), context.getDomain()); context.addFile(context.getDataString("fileName"), context.getDataString("fileNameSalt"), context.getDataLong("size"), context.getDataString("iv"), context.getDomain());
// Suppression du fichier temporaire dans le stockage du FFE // Suppression du fichier temporaire dans le stockage du FFE
String hashedFileName = context.getHashedFileName(context.getDataString("fileName")); String hashedFileName = context.getHashedFileName(context.getDataString("fileName"));

View File

@ -2,25 +2,28 @@ package lightcontainer.protocol.rules.writer;
import lightcontainer.domains.client.Context; import lightcontainer.domains.client.Context;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.StandardizedDefinitions;
import lightcontainer.utils.FileSender; import lightcontainer.utils.FileSender;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_SENDFILE;
/** /**
* Règle envoyée au SBE, demandant la sauvegarde d'un fichier. * Règle envoyée au SBE, demandant la sauvegarde d'un fichier.
*/ */
public class SendfileRule extends ProtocolWriter { public class SendfileRule extends ProtocolWriter {
//"^SENDFILE [A-Za-z0-9]{50,200} [0-9]{1,10} [A-Za-z0-9]{50,200}\r\n$"
private static final String PATTERN = "^SENDFILE [A-Za-z0-9.]{50,200} [0-9]{1,10} [A-Za-z0-9.]{50,200}\r\n$"; private static final String PATTERN = FFE_SENDFILE;
public static final String NAME = "SENDFILE"; public static final String NAME = "SENDFILE";
private static final int HASHED_FILE_NAME = 0; // Index file name hashed. private static final int HASHED_FILE_NAME = 0; // Index file name hashed.
private static final int FILE_SIZE = 1; // Index file size. private static final int FILE_SIZE = 1; // Index file size.
private static final int HASHED_FILE_CONTENT = 2; // Index file content hashed. private static final int HASHED_FILE_CONTENT = 2; // Index file content hashed.
private String storagePath; private final String storagePath;
public SendfileRule(String storagePath) { public SendfileRule(String storagePath) {
super(NAME, PATTERN); super(NAME, PATTERN);
@ -30,10 +33,10 @@ public class SendfileRule extends ProtocolWriter {
public class Result extends ProtocolWriter.ProtocolResult { public class Result extends ProtocolWriter.ProtocolResult {
private final String hashedFileName; private final String hashedFileName;
private final int fileSize; private final long fileSize;
private final String hashedFileContent; private final String hashedFileContent;
public Result(Context context, String hashedFileName, int fileSize, String hashedFileContent) { public Result(Context context, String hashedFileName, long fileSize, String hashedFileContent) {
super(context); super(context);
this.hashedFileName = hashedFileName; this.hashedFileName = hashedFileName;
this.fileSize = fileSize; this.fileSize = fileSize;

View File

@ -1,13 +1,16 @@
package lightcontainer.protocol.rules.writer; package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.StandardizedDefinitions;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_SIGN_ERROR;
/** /**
* Règle renvoyée au client lorsque l'authentification a échoué. * Règle renvoyée au client lorsque l'authentification a échoué.
*/ */
public class SignErrorRule extends ProtocolWriter { public class SignErrorRule extends ProtocolWriter {
//"^SIGN_ERROR\r\n$"
private static final String PATTERN = "^SIGN_ERROR\r\n$"; private static final String PATTERN = FFE_SIGN_ERROR;
public static final String NAME = "SIGN_ERROR"; public static final String NAME = "SIGN_ERROR";

View File

@ -1,13 +1,16 @@
package lightcontainer.protocol.rules.writer; package lightcontainer.protocol.rules.writer;
import lightcontainer.protocol.ProtocolWriter; import lightcontainer.protocol.ProtocolWriter;
import lightcontainer.protocol.StandardizedDefinitions;
import static lightcontainer.protocol.StandardizedDefinitions.FFE_SIGN_OK;
/** /**
* Règle renvoyée au client lorsque l'authentification a réusie. * Règle renvoyée au client lorsque l'authentification a réusie.
*/ */
public class SignOkRule extends ProtocolWriter { public class SignOkRule extends ProtocolWriter {
//"^SIGN_OK\r\n$"
private static final String PATTERN = "^SIGN_OK\r\n$"; private static final String PATTERN = FFE_SIGN_OK;
public static final String NAME = "SIGN_OK"; public static final String NAME = "SIGN_OK";

View File

@ -8,18 +8,18 @@ import lightcontainer.protocol.ProtocolWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
// TODO : C'est genre un ClientHandlerManager quoi hein, normal qu'il fasse blinder de chose ;) // TODO : C'est genre un ClientHandlerManager quoi hein, normal qu'il fasse blinder de chose ;)
/** /**
* ClientHandlerRepository * ClientHandlerRepository
* * <p>
* Repository storing ClientHandler class. * Repository storing ClientHandler class.
* Contains some utility functions. * Contains some utility functions.
* *
* @version 1.0 * @author Jérémi NIHART <j.nihart@student.helmo.be>
* @since 1.0 * @version 1.0
* * @see ClientHandler
* @see ClientHandler * @see AutoCloseable
* @see AutoCloseable * @since 1.0
* @author Jérémi NIHART <j.nihart@student.helmo.be>
*/ */
public class ClientHandlerRepository implements AutoCloseable, UnicastCHR { public class ClientHandlerRepository implements AutoCloseable, UnicastCHR {
// Variable // Variable
@ -34,9 +34,9 @@ public class ClientHandlerRepository implements AutoCloseable, UnicastCHR {
/** /**
* Setter, allow to define the ServerListener of a repository. * Setter, allow to define the ServerListener of a repository.
* & Start the server. * & Start the server.
* @param server ServerListener to set as default.
* *
* @since 1.0 * @param server ServerListener to set as default.
* @since 1.0
*/ */
@Override @Override
public void setServerListener(UnicastServerListener server) { public void setServerListener(UnicastServerListener server) {
@ -46,9 +46,9 @@ public class ClientHandlerRepository implements AutoCloseable, UnicastCHR {
/** /**
* Add a ClientHandler. * Add a ClientHandler.
* @param client Client Handler to add.
* *
* @since 1.0 * @param client Client Handler to add.
* @since 1.0
*/ */
@Override @Override
public void addClient(ClientHandler client) { public void addClient(ClientHandler client) {
@ -75,7 +75,7 @@ public class ClientHandlerRepository implements AutoCloseable, UnicastCHR {
* AutoClosable Function * AutoClosable Function
* Closes all ClientHandlers stored in this repository and deallocates all resources. * Closes all ClientHandlers stored in this repository and deallocates all resources.
* *
* @since 1.0 * @since 1.0
*/ */
@Override @Override
public void close() { public void close() {

View File

@ -16,8 +16,8 @@ import java.util.concurrent.ConcurrentLinkedDeque;
public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE { public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE {
// Variables // Variables
private Deque<Task> tasks = new ConcurrentLinkedDeque<>(); private Deque<Task> tasks = new ConcurrentLinkedDeque<>();
private ClientHandlerRepository clientRepository; // TODO -> pourquoi pas une interface ? end private final ClientHandlerRepository clientRepository; // TODO -> pourquoi pas une interface ? end
private StoreProcessorRepository storeRepository; // TODO -> pourquoi pas une interface ? end private final StoreProcessorRepository storeRepository; // TODO -> pourquoi pas une interface ? end
private ProtocolRepository protocolRepository; private ProtocolRepository protocolRepository;
// Constructor // Constructor
@ -32,7 +32,7 @@ public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE {
*/ */
public void alertStoreProcessors(Task task) { public void alertStoreProcessors(Task task) {
// On avertit les stor processors d'une nouvelle tâche // On avertit les stor processors d'une nouvelle tâche
String stor = storeRepository.findDomain(task); String stor = storeRepository.findDomain();
if (stor != null) { if (stor != null) {
storeRepository.assignTask(stor, task); storeRepository.assignTask(stor, task);
task.setDomain(stor); task.setDomain(stor);
@ -47,13 +47,10 @@ public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE {
*/ */
@Override @Override
public void onStoreAvailable(StoreProcessor store, ProtocolWriter.ProtocolResult response) { public void onStoreAvailable(StoreProcessor store, ProtocolWriter.ProtocolResult response) {
// TODO : Chercher une tâche appropriée
Iterator<Task> it = tasks.iterator(); Iterator<Task> it = tasks.iterator();
while (it.hasNext()) { while (it.hasNext()) {
Task task = it.next(); Task task = it.next();
System.out.println("Cherche");
if (task.isResponseOfClient(store.getDomain())) { if (task.isResponseOfClient(store.getDomain())) {
System.out.println("Task trouvée");
clientRepository.respondToClient(task.getClient(), response); clientRepository.respondToClient(task.getClient(), response);
it.remove(); // Suppression de la tâche it.remove(); // Suppression de la tâche
break; break;
@ -70,12 +67,11 @@ public class FileFrontEnd implements ClientHandlerFFE, StoreProcessorFFE {
private void assignOtherTask(StoreProcessor store) { private void assignOtherTask(StoreProcessor store) {
Iterator<Task> it = tasks.iterator(); Iterator<Task> it = tasks.iterator();
while (it.hasNext()) { while (it.hasNext()) {
Task task = it.next(); Task task = it.next();
if (store.canProcessTask(task)) { if (task.getDomain() == null && store.canProcessTask()) {
storeRepository.assignTask(store.getDomain(), task);
task.setDomain(store.getDomain()); task.setDomain(store.getDomain());
store.executeCommand(task.getContext(), task.getCommand());
return; return;
} }
} }

View File

@ -31,7 +31,6 @@ public class ProtocolRepositoryImpl implements ProtocolRepository {
return command; return command;
} }
} }
System.out.println("COMMANDE NULL");
return null; return null;
} }

View File

@ -5,21 +5,23 @@ import lightcontainer.domains.client.StoreProcessor;
import lightcontainer.domains.server.MulticastServerListener; import lightcontainer.domains.server.MulticastServerListener;
import lightcontainer.interfaces.MulticastSPR; import lightcontainer.interfaces.MulticastSPR;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
// TODO : C'est genre un ClientHandlerManager quoi hein, normal qu'il fasse blinder de chose ;) // TODO : C'est genre un ClientHandlerManager quoi hein, normal qu'il fasse blinder de chose ;)
/** /**
* StoreProcessorRepository * StoreProcessorRepository
* * <p>
* Repository storing StorePorcessor class. * Repository storing StorePorcessor class.
* Contains some utility functions. * Contains some utility functions.
* *
* @version 1.0 * @author Jérémi NIHART <j.nihart@student.helmo.be>
* @since 1.0 * @version 1.0
* * @see StoreProcessor
* @see StoreProcessor * @since 1.0
* @author Jérémi NIHART <j.nihart@student.helmo.be>
*/ */
public class StoreProcessorRepository implements AutoCloseable, MulticastSPR { public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
// Variables // Variables
@ -34,9 +36,9 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
/** /**
* Setter, allow to define the ServerListener of a repository. * Setter, allow to define the ServerListener of a repository.
* & start the server. * & start the server.
* @param server ServerListener to set as default.
* *
* @since 1.0 * @param server ServerListener to set as default.
* @since 1.0
*/ */
@Override @Override
public void setServerListener(MulticastServerListener server) { public void setServerListener(MulticastServerListener server) {
@ -46,9 +48,9 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
/** /**
* Add a StorePorcessor. * Add a StorePorcessor.
* @param store Store processor to add.
* *
* @since 1.0 * @param store Store processor to add.
* @since 1.0
*/ */
@Override @Override
public boolean addStore(StoreProcessor store) { public boolean addStore(StoreProcessor store) {
@ -60,14 +62,24 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
} }
@Override @Override
public String findDomain(Task task) { public String findDomain() {
StoreProcessor handler = findSBE(task); StoreProcessor handler = findSBE();
return handler == null ? null : handler.getDomain(); return handler == null ? null : handler.getDomain();
} }
private StoreProcessor findSBE(Task task) { private StoreProcessor findSBE() {
for (StoreProcessor handler : handlers) { for (StoreProcessor handler : handlers) {
if (handler.canProcessTask(task)) { if (handler.canProcessTask()) {
return handler;
}
}
return null;
}
private StoreProcessor getSBE(String stor) {
for (StoreProcessor handler : handlers) {
if (handler.getDomain().equals(stor)) {
return handler; return handler;
} }
} }
@ -77,9 +89,10 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
@Override @Override
public void assignTask(String stor, Task task) { public void assignTask(String stor, Task task) {
StoreProcessor handler = findSBE(task); StoreProcessor handler = getSBE(stor);
System.out.println("Find stor : " + handler); if (handler != null) {
handler.executeCommand(task.getContext(), task.getCommand()); handler.executeCommand(task.getContext(), task.getCommand());
}
} }
@Override @Override
@ -112,24 +125,59 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
*/ */
@Override @Override
public void closeStore(String domain) { public void closeStore(String domain) {
Iterator<StoreProcessor> it = this.handlers.iterator(); StoreProcessor storeProcessor = getSBE(domain);
if (storeProcessor != null) {
System.out.println("1 Nombre de SBE : " + handlers.size()); storeProcessor.close();
while (it.hasNext()) { handlers.remove(storeProcessor);
StoreProcessor storeProcessor = it.next();
if (storeProcessor.getDomain().equals(domain)) {
storeProcessor.close();
it.remove();
return;
}
} }
} }
/**
* Permet de mettre à jours la dernière annonce de ce SBE au FFE
*
* @param domain Le domain s'annoncant
*/
@Override
public void updateLastAnnounce(String domain) {
StoreProcessor storeProcessor = getSBE(domain);
if (storeProcessor != null) {
storeProcessor.setLastAnnounce(LocalDateTime.now());
}
}
/**
* Permet de récupérer les noms des domaines connectés au FFE
*
* @return Les noms des domaines connectés au FFE
*/
@Override
public Collection<String> getDomains() {
Set<String> domains = new HashSet<>();
for (StoreProcessor domain : handlers) {
domains.add(domain.getDomain());
}
return domains;
}
/**
* Permet de récupérer la dernière annonce d'un SBE
*
* @param domain
* @return La dernière annonce d'un SBE
*/
@Override
public LocalDateTime getLastAnnounce(String domain) {
StoreProcessor storeProcessor = getSBE(domain);
return storeProcessor == null ? null : storeProcessor.getLastAnnounce();
}
/** /**
* AutoClosable Function * AutoClosable Function
* Closes all StoreProcessor stored in this repository and deallocates all resources. * Closes all StoreProcessor stored in this repository and deallocates all resources.
* *
* @since 1.0 * @since 1.0
*/ */
@Override @Override
public void close() { public void close() {
@ -138,4 +186,7 @@ public class StoreProcessorRepository implements AutoCloseable, MulticastSPR {
// Close each client. // Close each client.
this.handlers.forEach(StoreProcessor::close); this.handlers.forEach(StoreProcessor::close);
} }
} }

View File

@ -90,6 +90,7 @@ public class AppConfig {
/** /**
* Méthode permettant de récupérer le chemin de sauvegarde des fichiers * Méthode permettant de récupérer le chemin de sauvegarde des fichiers
*
* @return Chemin de sauvegarde * @return Chemin de sauvegarde
*/ */
public String getStoragePath() { public String getStoragePath() {

View File

@ -10,12 +10,12 @@ public class File implements ReadOnlyFile {
// Variables // Variables
private final String name; private final String name;
private final String fileNameSalt; private final String fileNameSalt;
private final int size; private final long size;
private final String iv; private final String iv;
private final Set<String> storage; private final Set<String> storage;
// Constructor // Constructor
public File(String name, String fileNameSalt, int size, String iv, Set<String> storage) { public File(String name, String fileNameSalt, long size, String iv, Set<String> storage) {
this.name = name; this.name = name;
this.fileNameSalt = fileNameSalt; this.fileNameSalt = fileNameSalt;
this.size = size; this.size = size;
@ -34,7 +34,7 @@ public class File implements ReadOnlyFile {
} }
@Override @Override
public int getSize() { public long getSize() {
return size; return size;
} }

View File

@ -8,7 +8,7 @@ public interface ReadOnlyFile {
String getFileNameSalt(); String getFileNameSalt();
int getSize(); long getSize();
String getIv(); String getIv();

View File

@ -11,10 +11,9 @@ import java.util.Base64;
/** /**
* AES GCM 256 Encryption Class [DO NOT EDIT] * AES GCM 256 Encryption Class [DO NOT EDIT]
* *
* @since 1.0
* @version 1.0
*
* @author Jérémi Nihart <contact@endmove.eu> * @author Jérémi Nihart <contact@endmove.eu>
* @version 1.0
* @since 1.0
*/ */
public class AES_GCM { public class AES_GCM {
// Constants // Constants
@ -23,8 +22,7 @@ public class AES_GCM {
public static final int GCM_TAG_LENGTH = 16; public static final int GCM_TAG_LENGTH = 16;
// Main method for testing // Main method for testing
public static void main(String[] args) throws Exception public static void main(String[] args) throws Exception {
{
/* /*
* FILE ENCRYPTION DEMO * FILE ENCRYPTION DEMO
*/ */
@ -38,20 +36,20 @@ public class AES_GCM {
String IVFile = generateIV(); String IVFile = generateIV();
String keyFile = generateSecretKey(); String keyFile = generateSecretKey();
// Show options // Show options
System.out.println("IV : "+IVFile); System.out.println("IV : " + IVFile);
System.out.println("Key : "+keyFile); System.out.println("Key : " + keyFile);
// Encrypt // Encrypt
encryptStream( encryptStream(
new FileInputStream(inFile), new FileInputStream(inFile),
new FileOutputStream(outFile), new FileOutputStream(outFile),
inFile.length(), inFile.length(),
IVFile, IVFile,
keyFile keyFile
); );
// Decrypt // Decrypt
decryptStream( decryptStream(
new FileInputStream(outFile), new FileInputStream(outFile),
new FileOutputStream(clearFile), new FileOutputStream(clearFile),
outFile.length(), outFile.length(),
IVFile, IVFile,
keyFile keyFile
@ -65,8 +63,8 @@ public class AES_GCM {
String IV = generateIV(); String IV = generateIV();
String key = generateSecretKey(); String key = generateSecretKey();
// Show options // Show options
System.out.println("IV : "+IV); System.out.println("IV : " + IV);
System.out.println("Key : "+key); System.out.println("Key : " + key);
System.out.println("Original text : " + plainText); System.out.println("Original text : " + plainText);
// Crypt // Crypt
String cryptText = encrypt(plainText, key, IV); String cryptText = encrypt(plainText, key, IV);
@ -79,8 +77,8 @@ public class AES_GCM {
/** /**
* Decoder to decode base64 vector to byte vector. * Decoder to decode base64 vector to byte vector.
* *
* @param base64Vector A base64 encoded vector. * @param base64Vector A base64 encoded vector.
* @return Byte vector. * @return Byte vector.
*/ */
private static byte[] decodeBase64Vector(String base64Vector) { private static byte[] decodeBase64Vector(String base64Vector) {
Base64.Decoder b64Decoder = Base64.getDecoder(); Base64.Decoder b64Decoder = Base64.getDecoder();
@ -90,10 +88,9 @@ public class AES_GCM {
/** /**
* Decoder to decode base64 string to plain string. * Decoder to decode base64 string to plain string.
* *
* @param base64String A base64 encoded string. * @param base64String A base64 encoded string.
* @return Plain string. * @return Plain string.
* * @see AES_GCM#decodeBase64Vector(String)
* @see AES_GCM#decodeBase64Vector(String)
*/ */
private static String decodeBase64String(String base64String) { private static String decodeBase64String(String base64String) {
return new String(decodeBase64Vector(base64String)); return new String(decodeBase64Vector(base64String));
@ -101,8 +98,9 @@ public class AES_GCM {
/** /**
* Encoder to encode vector to base64 string. * Encoder to encode vector to base64 string.
* @param rawVector A raw vector. *
* @return A base64 encoded vector. * @param rawVector A raw vector.
* @return A base64 encoded vector.
*/ */
private static String encodeBase64(byte[] rawVector) { private static String encodeBase64(byte[] rawVector) {
Base64.Encoder b64Encoder = Base64.getEncoder(); Base64.Encoder b64Encoder = Base64.getEncoder();
@ -111,10 +109,10 @@ public class AES_GCM {
/** /**
* Encoder to encode string to base64 string. * Encoder to encode string to base64 string.
* @param rawString A raw string.
* @return A base64 encoded string.
* *
* @see AES_GCM#encodeBase64(byte[])) * @param rawString A raw string.
* @return A base64 encoded string.
* @see AES_GCM#encodeBase64(byte[]))
*/ */
private static String encodeBase64(String rawString) { private static String encodeBase64(String rawString) {
return encodeBase64(rawString.getBytes(StandardCharsets.UTF_8)); return encodeBase64(rawString.getBytes(StandardCharsets.UTF_8));
@ -123,14 +121,12 @@ public class AES_GCM {
/** /**
* FACTORY, to setting up a Java cryptographic cypher. * FACTORY, to setting up a Java cryptographic cypher.
* *
* @param op_mode the operation mode of this cipher (this is one of the * @param op_mode the operation mode of this cipher (this is one of the
* following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE) * following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE)
* @param key Base64 encoded secret key. * @param key Base64 encoded secret key.
* @param IV Base64 encoded vector. * @param IV Base64 encoded vector.
* * @return A Cryptography cypher.
* @return A Cryptography cypher. * @throws AesGcmException Throw an exception in case of an error occur while setting up the the cypher.
*
* @throws AesGcmException Throw an exception in case of an error occur while setting up the the cypher.
*/ */
private static Cipher createCipher(int op_mode, String key, String IV) throws AesGcmException { private static Cipher createCipher(int op_mode, String key, String IV) throws AesGcmException {
try { try {
@ -151,9 +147,8 @@ public class AES_GCM {
/** /**
* Generate a secret key base64 encoded. * Generate a secret key base64 encoded.
* *
* @return New Secret key b64 encoded. * @return New Secret key b64 encoded.
* * @throws AesGcmException Exception if an error occur.
* @throws AesGcmException Exception if an error occur.
*/ */
public static String generateSecretKey() throws AesGcmException { public static String generateSecretKey() throws AesGcmException {
try { try {
@ -169,7 +164,7 @@ public class AES_GCM {
/** /**
* Generate an IV (initialisation vector) base64 encoded. * Generate an IV (initialisation vector) base64 encoded.
* *
* @return New generated IV b64 encoded. * @return New generated IV b64 encoded.
*/ */
public static String generateIV() { public static String generateIV() {
byte[] IV = new byte[GCM_IV_LENGTH]; byte[] IV = new byte[GCM_IV_LENGTH];
@ -181,13 +176,11 @@ public class AES_GCM {
/** /**
* Encrypt text, with AES GCM. * Encrypt text, with AES GCM.
* *
* @param plainText Plain text to encrypt. * @param plainText Plain text to encrypt.
* @param key Base64 encoded secret key. * @param key Base64 encoded secret key.
* @param IV Base64 encoded vector. * @param IV Base64 encoded vector.
* * @return The encrypted plain text Base64 encoded.
* @return The encrypted plain text Base64 encoded. * @throws AesGcmException Exception if an error occur.
*
* @throws AesGcmException Exception if an error occur.
*/ */
public static String encrypt(String plainText, String key, String IV) throws AesGcmException { public static String encrypt(String plainText, String key, String IV) throws AesGcmException {
try { try {
@ -204,13 +197,12 @@ public class AES_GCM {
* Encrypt stream, with AES GCM. * Encrypt stream, with AES GCM.
* The output stream is automatically closed after processing. * The output stream is automatically closed after processing.
* *
* @param in InputStream to the input, flux to encrypt. * @param in InputStream to the input, flux to encrypt.
* @param out OutputStream to the output, encrypted flux. * @param out OutputStream to the output, encrypted flux.
* @param fileSize Stream/file size (! unencrypted size !). * @param fileSize Stream/file size (! unencrypted size !).
* @param key Base64 encoded secret key. * @param key Base64 encoded secret key.
* @param IV Base64 encoded vector. * @param IV Base64 encoded vector.
* * @throws AesGcmException Exception if an error occur.
* @throws AesGcmException Exception if an error occur.
*/ */
public static void encryptStream(InputStream in, OutputStream out, long fileSize, String key, String IV) throws AesGcmException { public static void encryptStream(InputStream in, OutputStream out, long fileSize, String key, String IV) throws AesGcmException {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -222,7 +214,7 @@ public class AES_GCM {
// Initialize a CipherOutputStream // Initialize a CipherOutputStream
CipherOutputStream cipherOut = new CipherOutputStream(out, cipher); CipherOutputStream cipherOut = new CipherOutputStream(out, cipher);
// Encryption Process // Encryption Process
while((currentSize < fileSize) && (bytes = in.read(buffer)) > 0) { while ((currentSize < fileSize) && (bytes = in.read(buffer)) > 0) {
cipherOut.write(buffer, 0, bytes); cipherOut.write(buffer, 0, bytes);
cipherOut.flush(); cipherOut.flush();
currentSize += bytes; currentSize += bytes;
@ -237,13 +229,11 @@ public class AES_GCM {
/** /**
* Decrypt, with AES GCM. * Decrypt, with AES GCM.
* *
* @param cryptText The encrypted text. * @param cryptText The encrypted text.
* @param key Base64 encoded secret key. * @param key Base64 encoded secret key.
* @param IV Base64 encoded vector. * @param IV Base64 encoded vector.
* * @return The decrypted plain text.
* @return The decrypted plain text. * @throws AesGcmException Exception if an error occur.
*
* @throws AesGcmException Exception if an error occur.
*/ */
public static String decrypt(String cryptText, String key, String IV) throws AesGcmException { public static String decrypt(String cryptText, String key, String IV) throws AesGcmException {
try { try {
@ -260,13 +250,12 @@ public class AES_GCM {
* Decrypt stream, with AES GCM. * Decrypt stream, with AES GCM.
* The input stream is automatically closed after processing. * The input stream is automatically closed after processing.
* *
* @param in InputStream to the input, flux to decrypt. * @param in InputStream to the input, flux to decrypt.
* @param out OutputStream to the output, decrypted flux. * @param out OutputStream to the output, decrypted flux.
* @param fileSize Stream/file size (! encrypted size !). * @param fileSize Stream/file size (! encrypted size !).
* @param key Base64 encoded secret key. * @param key Base64 encoded secret key.
* @param IV Base64 encoded vector. * @param IV Base64 encoded vector.
* * @throws AesGcmException Exception if an error occur.
* @throws AesGcmException Exception if an error occur.
*/ */
public static void decryptStream(InputStream in, OutputStream out, long fileSize, String key, String IV) throws AesGcmException { public static void decryptStream(InputStream in, OutputStream out, long fileSize, String key, String IV) throws AesGcmException {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -278,7 +267,7 @@ public class AES_GCM {
// Initialize a CipherOutputStream // Initialize a CipherOutputStream
CipherInputStream cipherIn = new CipherInputStream(in, cipher); CipherInputStream cipherIn = new CipherInputStream(in, cipher);
// Encryption Process // Encryption Process
while((currentSize < fileSize) && (bytes = cipherIn.read(buffer)) > 0) { while ((currentSize < fileSize) && (bytes = cipherIn.read(buffer)) > 0) {
out.write(buffer, 0, bytes); out.write(buffer, 0, bytes);
out.flush(); out.flush();
currentSize += bytes; currentSize += bytes;
@ -301,7 +290,7 @@ public class AES_GCM {
* Constructor of AesGcmException, * Constructor of AesGcmException,
* which define it's own detail message. * which define it's own detail message.
* *
* @param msg The detail message. * @param msg The detail message.
*/ */
public AesGcmException(String msg) { public AesGcmException(String msg) {
super(msg); super(msg);
@ -312,7 +301,7 @@ public class AES_GCM {
* which propagates the error triggering * which propagates the error triggering
* a crash of the encryption system. * a crash of the encryption system.
* *
* @param e Previous exception throwable. * @param e Previous exception throwable.
*/ */
public AesGcmException(Throwable e) { public AesGcmException(Throwable e) {
super(e); super(e);
@ -324,8 +313,8 @@ public class AES_GCM {
* a crash of the encryption system with * a crash of the encryption system with
* a chosen detail message. * a chosen detail message.
* *
* @param e Previous exception throwable. * @param e Previous exception throwable.
* @param msg The detail message. * @param msg The detail message.
*/ */
public AesGcmException(GeneralSecurityException e, String msg) { public AesGcmException(GeneralSecurityException e, String msg) {
super(msg, e); super(msg, e);

View File

@ -3,11 +3,13 @@ package lightcontainer.utils;
import java.io.*; import java.io.*;
public class FileReceiver { public class FileReceiver {
private String path; private final String path;
public FileReceiver(String path) { this.path = path; } public FileReceiver(String path) {
this.path = path;
}
public int receiveFile(InputStream input, String fileName, int fileSize, String key, String iv) { public int receiveFile(InputStream input, String fileName, long fileSize, String key, String iv) {
try { try {
File file = new File(String.format("%s/%s", path, fileName)); File file = new File(String.format("%s/%s", path, fileName));
if (file.createNewFile()) { if (file.createNewFile()) {
@ -16,8 +18,8 @@ public class FileReceiver {
AES_GCM.encryptStream(input, bufferedStream, fileSize, key, iv); AES_GCM.encryptStream(input, bufferedStream, fileSize, key, iv);
} }
} }
return (int)file.length(); // TODO change the size to LONG return (int) file.length(); // TODO change the size to LONG
} catch(IOException | AES_GCM.AesGcmException ex) { } catch (IOException | AES_GCM.AesGcmException ex) {
ex.printStackTrace(); ex.printStackTrace();
return -1; return -1;
} }
@ -32,7 +34,7 @@ public class FileReceiver {
bosFile = new BufferedOutputStream(new FileOutputStream(String.format("%s/%s", path, fileName))); bosFile = new BufferedOutputStream(new FileOutputStream(String.format("%s/%s", path, fileName)));
long currentOffset = 0; long currentOffset = 0;
while((currentOffset < fileSize) && ((bytesReceived = input.read(buffer)) > 0)) { while ((currentOffset < fileSize) && ((bytesReceived = input.read(buffer)) > 0)) {
bosFile.write(buffer, 0, bytesReceived); bosFile.write(buffer, 0, bytesReceived);
currentOffset += bytesReceived; currentOffset += bytesReceived;
} }
@ -40,9 +42,14 @@ public class FileReceiver {
bosFile.close(); bosFile.close();
return true; return true;
} catch(Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
if(bosFile != null) { try { bosFile.close(); } catch(Exception e) {} } if (bosFile != null) {
try {
bosFile.close();
} catch (Exception e) {
}
}
return false; return false;
} }
} }

View File

@ -3,46 +3,49 @@ package lightcontainer.utils;
import java.io.*; import java.io.*;
public class FileSender { public class FileSender {
private static final int DEFAULT_BUFFER=8000; private static final int DEFAULT_BUFFER = 8000;
private final String path; private final String path;
public FileSender(String path) { this.path = path; } public FileSender(String path) {
this.path = path;
}
public boolean sendFile(String filename, OutputStream out, int fileSize, String aesKey, String iv) throws IOException { public boolean sendFile(String filename, OutputStream out, long fileSize, String aesKey, String iv) throws IOException {
BufferedInputStream bisFile; BufferedInputStream bisFile;
System.out.printf("Envoie fichier : %s - %s - %s \n", filename, aesKey, iv); System.out.printf("Envoie fichier : %s - %s - %s \n", filename, aesKey, iv);
try { try {
File f = new File(String.format("%s/%s", path, filename)); File f = new File(String.format("%s/%s", path, filename));
if(f.exists()) { if (f.exists()) {
bisFile = new BufferedInputStream(new FileInputStream(f)); bisFile = new BufferedInputStream(new FileInputStream(f));
AES_GCM.decryptStream(bisFile, out, fileSize, aesKey, iv); AES_GCM.decryptStream(bisFile, out, fileSize, aesKey, iv);
return true; return true;
} else } else
return false; return false;
} catch(IOException | AES_GCM.AesGcmException ex) { } catch (IOException | AES_GCM.AesGcmException ex) {
throw new IOException(); throw new IOException();
} }
} }
public boolean sendFile(String filename, OutputStream out) throws IOException { public boolean sendFile(String filename, OutputStream out) throws IOException {
BufferedInputStream bisFile; BufferedInputStream bisFile;
int bytesReaded = 0; int bytesRead = 0;
try { try {
File file = new File(String.format("%s/%s", path, filename)); File file = new File(String.format("%s/%s", path, filename));
long fileSize = file.length(); long fileSize = file.length();
if(file.exists()) { if (file.exists()) {
byte[] buffer = new byte[DEFAULT_BUFFER]; byte[] buffer = new byte[DEFAULT_BUFFER];
bisFile = new BufferedInputStream(new FileInputStream(file)); bisFile = new BufferedInputStream(new FileInputStream(file));
long currentOffset = 0; long currentOffset = 0;
while((currentOffset < fileSize) && (bytesReaded = bisFile.read(buffer)) > 0) { while ((currentOffset < fileSize) && (bytesRead = bisFile.read(buffer)) > 0) {
out.write(buffer, 0, bytesReaded); out.flush(); out.write(buffer, 0, bytesRead);
currentOffset+= bytesReaded; out.flush();
currentOffset += bytesRead;
} }
bisFile.close(); bisFile.close();
return true; return true;
} else } else
return false; return false;
} catch(IOException ex) {// todo change } catch (IOException ex) {// todo change
throw ex; throw ex;
} }
} }

View File

@ -18,7 +18,7 @@ public class NetChooser {
public NetworkInterface requestInterface() { public NetworkInterface requestInterface() {
Scanner console = new Scanner(System.in); Scanner console = new Scanner(System.in);
String[] allInterfaceNames = getInterfaces(); String[] allInterfaceNames = getInterfaces();
for(int index=0; index < allInterfaceNames.length; ++index) { for (int index = 0; index < allInterfaceNames.length; ++index) {
System.out.printf("%d. %s\n", index, allInterfaceNames[index]); System.out.printf("%d. %s\n", index, allInterfaceNames[index]);
} }
System.out.printf("Select your interface :"); System.out.printf("Select your interface :");
@ -35,28 +35,28 @@ public class NetChooser {
NetworkInterface currentInterface = discoveredInterfaces.nextElement(); NetworkInterface currentInterface = discoveredInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = currentInterface.getInetAddresses(); Enumeration<InetAddress> inetAddresses = currentInterface.getInetAddresses();
int ipCount = 0; int ipCount = 0;
while(inetAddresses.hasMoreElements()) { while (inetAddresses.hasMoreElements()) {
InetAddress currentAddress = inetAddresses.nextElement(); InetAddress currentAddress = inetAddresses.nextElement();
ipCount++; ipCount++;
} }
if(ipCount > 0) if (ipCount > 0)
interfaces.add(currentInterface); interfaces.add(currentInterface);
} }
} catch(SocketException ex) { } catch (SocketException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public NetworkInterface getInterfacesByIndex(int i) { public NetworkInterface getInterfacesByIndex(int i) {
if(i >= 0) if (i >= 0)
return interfaces.get(i); return interfaces.get(i);
else else
return null; return null;
} }
public String[] getInterfaces() { public String[] getInterfaces() {
if(interfaces.size() > 0) { if (interfaces.size() > 0) {
String[] result = new String[interfaces.size()]; String[] result = new String[interfaces.size()];
for (int i = 0; i < interfaces.size(); ++i) { for (int i = 0; i < interfaces.size(); ++i) {
result[i] = interfaces.get(i).getDisplayName() + " --> " + interfaces.get(i).getName(); result[i] = interfaces.get(i).getDisplayName() + " --> " + interfaces.get(i).getName();

View File

@ -13,10 +13,9 @@ import java.util.Base64;
/** /**
* SHA 256 Hashing and borrowing Class [DO NOT EDIT] * SHA 256 Hashing and borrowing Class [DO NOT EDIT]
* *
* @since 1.0
* @version 1.0
*
* @author Jérémi Nihart <contact@endmove.eu> * @author Jérémi Nihart <contact@endmove.eu>
* @version 1.0
* @since 1.0
*/ */
public class SHA { public class SHA {
// Constants // Constants
@ -42,12 +41,10 @@ public class SHA {
/** /**
* Make a borrowing of the stream. * Make a borrowing of the stream.
* *
* @param in InputStream to the input, flux to hash. * @param in InputStream to the input, flux to hash.
* @param fileSize Stream/file size. * @param fileSize Stream/file size.
* * @return Borrowing of the full current flux.
* @return Borrowing of the full current flux. * @throws ShaException if an error occur.
*
* @throws ShaException if an error occur.
*/ */
public static String hashStream(InputStream in, long fileSize) throws ShaException { public static String hashStream(InputStream in, long fileSize) throws ShaException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -58,7 +55,7 @@ public class SHA {
// Init Digest algo // Init Digest algo
MessageDigest digest = MessageDigest.getInstance(SHA_VERSION); MessageDigest digest = MessageDigest.getInstance(SHA_VERSION);
// Process flux // Process flux
while ((currentSize < fileSize) && (bytes=in.read(buffer)) > 0) { while ((currentSize < fileSize) && (bytes = in.read(buffer)) > 0) {
digest.update(buffer, 0, bytes); digest.update(buffer, 0, bytes);
currentSize += bytes; currentSize += bytes;
} }
@ -77,12 +74,10 @@ public class SHA {
/** /**
* Make a borrowing of the file. * Make a borrowing of the file.
* *
* @param rootPath Root path of the file. * @param rootPath Root path of the file.
* @param fileName File Name. * @param fileName File Name.
* * @return Borrowing of the file.
* @return Borrowing of the file. * @throws ShaException if an error occur.
*
* @throws ShaException if an error occur.
*/ */
public static String hashFile(String rootPath, String fileName) throws ShaException { public static String hashFile(String rootPath, String fileName) throws ShaException {
try { try {
@ -109,7 +104,7 @@ public class SHA {
* which propagates the error triggering * which propagates the error triggering
* a crash of the hash system. * a crash of the hash system.
* *
* @param e Previous exception throwable. * @param e Previous exception throwable.
*/ */
public ShaException(Throwable e) { public ShaException(Throwable e) {
super(e); super(e);

View File

@ -1 +1,24 @@
{"unicast_port":8000,"multicast_ip":"224.66.66.1","multicast_port":15502,"network_interface":"lo","tls":true,"storagePath":"D:\\ffe","users":[{"name":"aaaaa","password":"$2a$10$HAupXer5aVEDgIAtFQchyOSB.SyCq7irV7EZNcMTE3R9k.1UJGOLu","aes_key":"FvsflaQGR+OoV11chJTCxd24owRPvyz1T42JXIU9fwE=","files":[{"name":"map_91.dat","fileNameSalt":"vtUOlQQ6Vt4bbpNexyBvog==","size":693,"iv":"ylk0R79Fq2/eDccVi8GTfA==","storage":["orglightcont01"]},{"name":"OutPutStream.mp3","fileNameSalt":"3qw+LauZUc13xh6fwnMHnQ==","size":53037,"iv":"40sIX0VtASM9man5XkM64Q==","storage":["orglightcont01"]},{"name":"wait.mp4","fileNameSalt":"1wnuehjUPI895TgCy2e/EQ==","size":1210962,"iv":"fCM6WG1PxOu9ieEjPuQiFg==","storage":["orglightcont01"]},{"name":"loader.gif","fileNameSalt":"05nNafgD/SNPg+y/MzI2DA==","size":89594,"iv":"GLoY4/PybIz72Sbz9jFgRQ==","storage":["orglightcont01"]},{"name":"extensions.mp4","fileNameSalt":"BYam5baM4WUPdaQZDu2eyw==","size":1501471,"iv":"ugCXHr7yVsY8rnB1znEfew==","storage":["orglightcont01"]},{"name":"007.mp4","fileNameSalt":"12jEfd3/dT9akqzdWn1vsg==","size":1742707,"iv":"CyKf2OHPABn//ez5L2o3Jg==","storage":["orglightcont01"]}]}]} {
"unicast_port": 8000,
"multicast_ip": "224.66.66.1",
"multicast_port": 15502,
"network_interface": "wlp1s0",
"tls": true,
"storagePath": "/home/benjamin/ffe",
"users": [
{
"name": "benjamin",
"password": "$2a$10$I4vHt83CTYuQCP7xvZ04Ne7Vb0cswBiVZhV0n23k9FCxoH0ny9fZG",
"aes_key": "mAP6izUBUhBxIkakH2yB/TplhRz1OQV5Fp6HQmhywns=",
"files": [
]
},
{
"name": "aaaaa",
"password": "$2a$10$nDCEDVwbNO/YDQ4qdRcxfuES4.aboluLzWouXXsk6vDoaWocv516W",
"aes_key": "kYtwHy9qJBg30WS6axWTFGVE0Ge5kpYiJJlC+COIEI4=",
"files": [
]
}
]
}