Reformat code

This commit is contained in:
Ilya 2020-11-20 19:01:11 +03:00
parent 630e76198e
commit bdffb7a457
8 changed files with 458 additions and 429 deletions

View File

@ -5,31 +5,33 @@ import java.security.MessageDigest;
public class CheckSum { public class CheckSum {
static String getChecksum(String fileName) { static String getChecksum(String fileName) {
StringBuffer sb = new StringBuffer(""); StringBuffer sb = new StringBuffer("");
try { try {
String datafile = fileName; String datafile = fileName;
//use SHA1 to calculate checksum //use SHA1 to calculate checksum
MessageDigest md = MessageDigest.getInstance("SHA1"); MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(datafile); FileInputStream fis = new FileInputStream(datafile);
byte[] dataBytes = new byte[1024]; byte[] dataBytes = new byte[1024];
int nread = 0; int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) { while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread); md.update(dataBytes, 0, nread);
} }
fis.close(); fis.close();
byte[] mdbytes = md.digest(); byte[] mdbytes = md.digest();
// convert the byte to hex format // convert the byte to hex format
for (int i = 0; i < mdbytes.length; i++) { for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
} }
} catch (Exception e){System.out.println("Generate Checksum Failed: "+e.getMessage());} } catch (Exception e) {
System.out.println("Generate Checksum Failed: " + e.getMessage());
}
return sb.toString(); return sb.toString();
} }
} }

View File

@ -2,8 +2,12 @@ package ru.redguy.tftpserver;
public interface ErrorEvent { public interface ErrorEvent {
public void onPacketReceiveException(Exception exception); public void onPacketReceiveException(Exception exception);
public void onPacketReadException(Exception exception); public void onPacketReadException(Exception exception);
public void onPacketWriteException(Exception exception); public void onPacketWriteException(Exception exception);
public void onClientReadException(Exception exception, TFTPread tftPread); public void onClientReadException(Exception exception, TFTPread tftPread);
public void onClientWriteException(Exception exception, TFTPwrite tftPwrite); public void onClientWriteException(Exception exception, TFTPwrite tftPwrite);
} }

View File

@ -1,87 +1,88 @@
package ru.redguy.tftpserver; package ru.redguy.tftpserver;
import java.net.*; import java.io.IOException;
import java.io.*; import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class TFTPServer { public class TFTPServer {
private DatagramSocket socket; private DatagramSocket socket;
private Runner runner; private Runner runner;
private Thread thread; private Thread thread;
private ErrorEvent errorEvent; private ErrorEvent errorEvent;
public void start() throws SocketException { public void start() throws SocketException {
start(69); start(69);
} }
public void start(int port) throws SocketException { public void start(int port) throws SocketException {
socket = new DatagramSocket(port); socket = new DatagramSocket(port);
runner = new Runner(socket,this); runner = new Runner(socket, this);
thread = new Thread(runner); thread = new Thread(runner);
thread.setDaemon(true); thread.setDaemon(true);
thread.start(); thread.start();
} }
public void start(String host, int port) throws UnknownHostException, SocketException { public void start(String host, int port) throws UnknownHostException, SocketException {
socket = new DatagramSocket(port,InetAddress.getByName(host)); socket = new DatagramSocket(port, InetAddress.getByName(host));
runner = new Runner(socket,this); runner = new Runner(socket, this);
thread.setDaemon(true); thread.setDaemon(true);
thread.start(); thread.start();
} }
public int getPort() { public int getPort() {
return socket.getLocalPort(); return socket.getLocalPort();
} }
public void stop() { public void stop() {
thread.interrupt(); thread.interrupt();
} }
public void onError(ErrorEvent event) { public void onError(ErrorEvent event) {
this.errorEvent = event; this.errorEvent = event;
} }
static class Runner implements Runnable { static class Runner implements Runnable {
DatagramSocket datagramSocket; DatagramSocket datagramSocket;
TFTPServer server; TFTPServer server;
boolean run = true; boolean run = true;
public Runner(DatagramSocket socket,TFTPServer server) { public Runner(DatagramSocket socket, TFTPServer server) {
this.datagramSocket = socket; this.datagramSocket = socket;
this.server = server; this.server = server;
} }
public void stop() { public void stop() {
run = false; run = false;
} }
@Override @Override
public void run() { public void run() {
while (run) { while (run) {
TFTPpacket in = null; TFTPpacket in = null;
try { try {
in = TFTPpacket.receive(datagramSocket); in = TFTPpacket.receive(datagramSocket);
} catch (IOException e) { } catch (IOException e) {
server.errorEvent.onPacketReceiveException(e); server.errorEvent.onPacketReceiveException(e);
} }
if (in instanceof TFTPread) { if (in instanceof TFTPread) {
try { try {
TFTPserverRRQ r = new TFTPserverRRQ((TFTPread) in, server.errorEvent); TFTPserverRRQ r = new TFTPserverRRQ((TFTPread) in, server.errorEvent);
} catch (TftpException e) { } catch (TftpException e) {
server.errorEvent.onPacketReadException(e); server.errorEvent.onPacketReadException(e);
} }
} } else if (in instanceof TFTPwrite) {
try {
else if (in instanceof TFTPwrite) { TFTPserverWRQ w = new TFTPserverWRQ((TFTPwrite) in, server.errorEvent);
try { } catch (TftpException e) {
TFTPserverWRQ w = new TFTPserverWRQ((TFTPwrite) in, server.errorEvent); server.errorEvent.onPacketWriteException(e);
} catch (TftpException e) { }
server.errorEvent.onPacketWriteException(e); }
} }
} }
} }
}
}
} }

View File

@ -1,132 +1,138 @@
package ru.redguy.tftpserver; package ru.redguy.tftpserver;
import java.net.*; import java.io.FileInputStream;
import java.io.*; import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class TftpException extends Exception { class TftpException extends Exception {
public TftpException() { public TftpException() {
super(); super();
} }
public TftpException(String s) {
super(s); public TftpException(String s) {
} super(s);
}
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
//GENERAL packet: define the packet structure, necessary members and methods// //GENERAL packet: define the packet structure, necessary members and methods//
//of TFTP packet. To be extended by other specific packet(read, write, etc) // //of TFTP packet. To be extended by other specific packet(read, write, etc) //
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
public class TFTPpacket { public class TFTPpacket {
// TFTP constants // TFTP constants
public static int tftpPort = 69; public static int tftpPort = 69;
public static int maxTftpPakLen=516; public static int maxTftpPakLen = 516;
public static int maxTftpData=512; public static int maxTftpData = 512;
// Tftp opcodes // Tftp opcodes
protected static final short tftpRRQ=1; protected static final short tftpRRQ = 1;
protected static final short tftpWRQ=2; protected static final short tftpWRQ = 2;
protected static final short tftpDATA=3; protected static final short tftpDATA = 3;
protected static final short tftpACK=4; protected static final short tftpACK = 4;
protected static final short tftpERROR=5; protected static final short tftpERROR = 5;
// Packet Offsets // Packet Offsets
protected static final int opOffset=0; protected static final int opOffset = 0;
protected static final int fileOffset=2; protected static final int fileOffset = 2;
protected static final int blkOffset=2; protected static final int blkOffset = 2;
protected static final int dataOffset=4; protected static final int dataOffset = 4;
protected static final int numOffset=2; protected static final int numOffset = 2;
protected static final int msgOffset=4; protected static final int msgOffset = 4;
// The actual packet for UDP transfer // The actual packet for UDP transfer
protected byte [] message; protected byte[] message;
protected int length; protected int length;
// Address info (required for replies) // Address info (required for replies)
protected InetAddress host; protected InetAddress host;
protected int port; protected int port;
// Constructor // Constructor
public TFTPpacket() { public TFTPpacket() {
message=new byte[maxTftpPakLen]; message = new byte[maxTftpPakLen];
length=maxTftpPakLen; length = maxTftpPakLen;
}
// Methods to receive packet and convert it to yhe right type(data/ack/read/...)
public static TFTPpacket receive(DatagramSocket sock) throws IOException {
TFTPpacket in=new TFTPpacket(), retPak=new TFTPpacket();
//receive data and put them into in.message
DatagramPacket inPak = new DatagramPacket(in.message,in.length);
sock.receive(inPak);
//Check the opcode in message, then cast the message into the corresponding type
switch (in.get(0)) {
case tftpRRQ:
retPak=new TFTPread();
break;
case tftpWRQ:
retPak=new TFTPwrite();
break;
case tftpDATA:
retPak=new TFTPdata();
break;
case tftpACK:
retPak=new TFTPack();
break;
case tftpERROR:
retPak=new TFTPerror();
break;
} }
retPak.message=in.message;
retPak.length=inPak.getLength();
retPak.host=inPak.getAddress();
retPak.port=inPak.getPort();
return retPak; // Methods to receive packet and convert it to yhe right type(data/ack/read/...)
} public static TFTPpacket receive(DatagramSocket sock) throws IOException {
TFTPpacket in = new TFTPpacket(), retPak = new TFTPpacket();
//receive data and put them into in.message
DatagramPacket inPak = new DatagramPacket(in.message, in.length);
sock.receive(inPak);
//Method to send packet //Check the opcode in message, then cast the message into the corresponding type
public void send(InetAddress ip, int port, DatagramSocket s) throws IOException { switch (in.get(0)) {
s.send(new DatagramPacket(message,length,ip,port)); case tftpRRQ:
} retPak = new TFTPread();
break;
case tftpWRQ:
retPak = new TFTPwrite();
break;
case tftpDATA:
retPak = new TFTPdata();
break;
case tftpACK:
retPak = new TFTPack();
break;
case tftpERROR:
retPak = new TFTPerror();
break;
}
retPak.message = in.message;
retPak.length = inPak.getLength();
retPak.host = inPak.getAddress();
retPak.port = inPak.getPort();
// DatagramPacket like methods return retPak;
public InetAddress getAddress() { }
return host;
}
public int getPort() { //Method to send packet
return port; public void send(InetAddress ip, int port, DatagramSocket s) throws IOException {
} s.send(new DatagramPacket(message, length, ip, port));
}
public int getLength() { // DatagramPacket like methods
return length; public InetAddress getAddress() {
} return host;
}
// Methods to put opcode, blkNum, error code into the byte array 'message'. public int getPort() {
protected void put(int at, short value) { return port;
message[at++] = (byte)(value >>> 8); // first byte }
message[at] = (byte)(value % 256); // last byte
}
@SuppressWarnings("deprecation") public int getLength() {
//Put the filename and mode into the 'message' at 'at' follow by byte "del" return length;
protected void put(int at, String value, byte del) { }
value.getBytes(0, value.length(), message, at);
message[at + value.length()] = del;
}
protected int get(int at) { // Methods to put opcode, blkNum, error code into the byte array 'message'.
return (message[at] & 0xff) << 8 | message[at+1] & 0xff; protected void put(int at, short value) {
} message[at++] = (byte) (value >>> 8); // first byte
message[at] = (byte) (value % 256); // last byte
}
protected String get (int at, byte del) { @SuppressWarnings("deprecation")
StringBuffer result = new StringBuffer(); //Put the filename and mode into the 'message' at 'at' follow by byte "del"
while (message[at] != del) result.append((char)message[at++]); protected void put(int at, String value, byte del) {
return result.toString(); value.getBytes(0, value.length(), message, at);
} message[at + value.length()] = del;
}
protected int get(int at) {
return (message[at] & 0xff) << 8 | message[at + 1] & 0xff;
}
protected String get(int at, byte del) {
StringBuffer result = new StringBuffer();
while (message[at] != del) result.append((char) message[at++]);
return result.toString();
}
} }
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////
@ -135,35 +141,37 @@ public class TFTPpacket {
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////
final class TFTPdata extends TFTPpacket { final class TFTPdata extends TFTPpacket {
// Constructors // Constructors
protected TFTPdata() {} protected TFTPdata() {
public TFTPdata(int blockNumber, FileInputStream in) throws IOException { }
this.message = new byte[maxTftpPakLen];
// manipulate message
this.put(opOffset, tftpDATA);
this.put(blkOffset, (short) blockNumber);
// read the file into packet and calculate the entire length
length = in.read(message, dataOffset, maxTftpData) + 4;
}
// Accessors public TFTPdata(int blockNumber, FileInputStream in) throws IOException {
this.message = new byte[maxTftpPakLen];
// manipulate message
this.put(opOffset, tftpDATA);
this.put(blkOffset, (short) blockNumber);
// read the file into packet and calculate the entire length
length = in.read(message, dataOffset, maxTftpData) + 4;
}
public int blockNumber() { // Accessors
return this.get(blkOffset);
}
/* public int blockNumber() {
* public void data(byte[] buffer) { buffer = new byte[length-4]; return this.get(blkOffset);
* }
* for (int i=0; i<length-4; i++) buffer[i]=message[i+dataOffset]; }
*/
// File output /*
public int write(FileOutputStream out) throws IOException { * public void data(byte[] buffer) { buffer = new byte[length-4];
out.write(message, dataOffset, length - 4); *
* for (int i=0; i<length-4; i++) buffer[i]=message[i+dataOffset]; }
*/
return (length - 4); // File output
} public int write(FileOutputStream out) throws IOException {
out.write(message, dataOffset, length - 4);
return (length - 4);
}
} }
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
@ -172,25 +180,27 @@ final class TFTPdata extends TFTPpacket {
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
class TFTPerror extends TFTPpacket { class TFTPerror extends TFTPpacket {
// Constructors // Constructors
protected TFTPerror() { protected TFTPerror() {
} }
//Generate error packet
public TFTPerror(int number, String message) {
length = 4 + message.length() + 1;
this.message = new byte[length];
put(opOffset, tftpERROR);
put(numOffset, (short) number);
put(msgOffset, message, (byte) 0);
}
// Accessors //Generate error packet
public int number() { public TFTPerror(int number, String message) {
return this.get(numOffset); length = 4 + message.length() + 1;
} this.message = new byte[length];
public String message() { put(opOffset, tftpERROR);
return this.get(msgOffset, (byte) 0); put(numOffset, (short) number);
} put(msgOffset, message, (byte) 0);
}
// Accessors
public int number() {
return this.get(numOffset);
}
public String message() {
return this.get(msgOffset, (byte) 0);
}
} }
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
@ -199,21 +209,22 @@ class TFTPerror extends TFTPpacket {
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
final class TFTPack extends TFTPpacket { final class TFTPack extends TFTPpacket {
// Constructors // Constructors
protected TFTPack() { protected TFTPack() {
} }
//Generate ack packet
public TFTPack(int blockNumber) {
length = 4;
this.message = new byte[length];
put(opOffset, tftpACK);
put(blkOffset, (short) blockNumber);
}
// Accessors //Generate ack packet
public int blockNumber() { public TFTPack(int blockNumber) {
return this.get(blkOffset); length = 4;
} this.message = new byte[length];
put(opOffset, tftpACK);
put(blkOffset, (short) blockNumber);
}
// Accessors
public int blockNumber() {
return this.get(blkOffset);
}
} }

View File

@ -1,97 +1,105 @@
package ru.redguy.tftpserver; package ru.redguy.tftpserver;
import java.net.*; import java.io.File;
import java.io.*; import java.io.FileInputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
class TFTPserverRRQ extends Thread { class TFTPserverRRQ extends Thread {
protected DatagramSocket sock; protected DatagramSocket sock;
protected InetAddress host; protected InetAddress host;
protected int port; protected int port;
protected FileInputStream source; protected FileInputStream source;
protected TFTPpacket req; protected TFTPpacket req;
protected int timeoutLimit=5; protected int timeoutLimit = 5;
protected String fileName; protected String fileName;
// initialize read request // initialize read request
public TFTPserverRRQ(TFTPread request, ErrorEvent event) throws TftpException { public TFTPserverRRQ(TFTPread request, ErrorEvent event) throws TftpException {
try { try {
req = request; req = request;
//open new socket with random port num for tranfer //open new socket with random port num for tranfer
sock = new DatagramSocket(); sock = new DatagramSocket();
sock.setSoTimeout(1000); sock.setSoTimeout(1000);
fileName = request.fileName(); fileName = request.fileName();
host = request.getAddress(); host = request.getAddress();
port = request.getPort(); port = request.getPort();
//create file object in parent folder //create file object in parent folder
File srcFile = new File(fileName); File srcFile = new File(fileName);
/*System.out.println("procce checking");*/ /*System.out.println("procce checking");*/
//check file //check file
if (srcFile.exists() && srcFile.isFile() && srcFile.canRead()) { if (srcFile.exists() && srcFile.isFile() && srcFile.canRead()) {
source = new FileInputStream(srcFile); source = new FileInputStream(srcFile);
this.start(); //open new thread for transfer this.start(); //open new thread for transfer
} else } else
throw new TftpException("access violation"); throw new TftpException("access violation");
} catch (Exception e) { } catch (Exception e) {
TFTPerror ePak = new TFTPerror(1, e.getMessage()); // error code 1 TFTPerror ePak = new TFTPerror(1, e.getMessage()); // error code 1
try { try {
ePak.send(host, port, sock); ePak.send(host, port, sock);
} catch (Exception f) { } catch (Exception f) {
} }
event.onClientReadException(e,request); event.onClientReadException(e, request);
} }
} }
//everything is fine, open new thread to transfer file
public void run() {
int bytesRead = TFTPpacket.maxTftpPakLen;
// handle read request
if (req instanceof TFTPread) {
try {
for (int blkNum = 1; bytesRead == TFTPpacket.maxTftpPakLen; blkNum++) {
TFTPdata outPak = new TFTPdata(blkNum, source);
/*System.out.println("send block no. " + outPak.blockNumber()); */
bytesRead = outPak.getLength();
/*System.out.println("bytes sent: " + bytesRead);*/
outPak.send(host, port, sock);
/*System.out.println("current op code " + outPak.get(0)); */
//wait for the correct ack. if incorrect, retry up to 5 times //everything is fine, open new thread to transfer file
while (timeoutLimit!=0) { public void run() {
try { int bytesRead = TFTPpacket.maxTftpPakLen;
TFTPpacket ack = TFTPpacket.receive(sock); // handle read request
if (!(ack instanceof TFTPack)){throw new Exception("Client failed");} if (req instanceof TFTPread) {
TFTPack a = (TFTPack) ack; try {
for (int blkNum = 1; bytesRead == TFTPpacket.maxTftpPakLen; blkNum++) {
TFTPdata outPak = new TFTPdata(blkNum, source);
/*System.out.println("send block no. " + outPak.blockNumber()); */
bytesRead = outPak.getLength();
/*System.out.println("bytes sent: " + bytesRead);*/
outPak.send(host, port, sock);
/*System.out.println("current op code " + outPak.get(0)); */
if(a.blockNumber()!=blkNum){ //check ack //wait for the correct ack. if incorrect, retry up to 5 times
throw new SocketTimeoutException("last packet lost, resend packet");} while (timeoutLimit != 0) {
/*System.out.println("confirm blk num " + a.blockNumber()+" from "+a.getPort());*/ try {
break; TFTPpacket ack = TFTPpacket.receive(sock);
} if (!(ack instanceof TFTPack)) {
catch (SocketTimeoutException t) {//resend last packet throw new Exception("Client failed");
System.out.println("Resent blk " + blkNum); }
timeoutLimit--; TFTPack a = (TFTPack) ack;
outPak.send(host, port, sock);
}
} // end of while
if(timeoutLimit==0){throw new Exception("connection failed");}
}
System.out.println("Transfer completed.(Client " +host +")" );
System.out.println("Filename: "+fileName + "\nSHA1 checksum: "+CheckSum.getChecksum(fileName)+"\n");
} catch (Exception e) {
TFTPerror ePak = new TFTPerror(1, e.getMessage());
try { if (a.blockNumber() != blkNum) { //check ack
ePak.send(host, port, sock); throw new SocketTimeoutException("last packet lost, resend packet");
} catch (Exception f) { }
} /*System.out.println("confirm blk num " + a.blockNumber()+" from "+a.getPort());*/
break;
} catch (SocketTimeoutException t) {//resend last packet
System.out.println("Resent blk " + blkNum);
timeoutLimit--;
outPak.send(host, port, sock);
}
} // end of while
if (timeoutLimit == 0) {
throw new Exception("connection failed");
}
}
System.out.println("Transfer completed.(Client " + host + ")");
System.out.println("Filename: " + fileName + "\nSHA1 checksum: " + CheckSum.getChecksum(fileName) + "\n");
} catch (Exception e) {
TFTPerror ePak = new TFTPerror(1, e.getMessage());
System.out.println("Client failed: " + e.getMessage()); try {
} ePak.send(host, port, sock);
} } catch (Exception f) {
} }
System.out.println("Client failed: " + e.getMessage());
}
}
}
} }

View File

@ -1,106 +1,111 @@
package ru.redguy.tftpserver; package ru.redguy.tftpserver;
import java.net.*; import java.io.File;
import java.io.*; import java.io.FileOutputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
class TFTPserverWRQ extends Thread { class TFTPserverWRQ extends Thread {
protected DatagramSocket sock; protected DatagramSocket sock;
protected InetAddress host; protected InetAddress host;
protected int port; protected int port;
protected FileOutputStream outFile; protected FileOutputStream outFile;
protected TFTPpacket req; protected TFTPpacket req;
protected int timeoutLimit = 5; protected int timeoutLimit = 5;
//protected int testloss=0; //protected int testloss=0;
protected File saveFile; protected File saveFile;
protected String fileName; protected String fileName;
// Initialize read request // Initialize read request
public TFTPserverWRQ(TFTPwrite request, ErrorEvent event) throws TftpException { public TFTPserverWRQ(TFTPwrite request, ErrorEvent event) throws TftpException {
try { try {
req = request; req = request;
sock = new DatagramSocket(); // new port for transfer sock = new DatagramSocket(); // new port for transfer
sock.setSoTimeout(1000); sock.setSoTimeout(1000);
host = request.getAddress(); host = request.getAddress();
port = request.getPort(); port = request.getPort();
fileName = request.fileName(); fileName = request.fileName();
//create file object in parent folder //create file object in parent folder
saveFile = new File(fileName); saveFile = new File(fileName);
if (!saveFile.exists()) { if (!saveFile.exists()) {
outFile = new FileOutputStream(saveFile); outFile = new FileOutputStream(saveFile);
TFTPack a = new TFTPack(0); TFTPack a = new TFTPack(0);
a.send(host, port, sock); // send ack 0 at first, ready to a.send(host, port, sock); // send ack 0 at first, ready to
// receive // receive
this.start(); this.start();
} else } else
throw new TftpException("access violation, file exists"); throw new TftpException("access violation, file exists");
} catch (Exception e) { } catch (Exception e) {
TFTPerror ePak = new TFTPerror(1, e.getMessage()); // error code 1 TFTPerror ePak = new TFTPerror(1, e.getMessage()); // error code 1
try { try {
ePak.send(host, port, sock); ePak.send(host, port, sock);
} catch (Exception f) { } catch (Exception f) {
} }
event.onClientWriteException(e,request); event.onClientWriteException(e, request);
} }
} }
public void run() { public void run() {
/*int bytesRead = TFTPpacket.maxTftpPakLen;*/ /*int bytesRead = TFTPpacket.maxTftpPakLen;*/
// handle write request // handle write request
if (req instanceof TFTPwrite) { if (req instanceof TFTPwrite) {
try { try {
for (int blkNum = 1, bytesOut = 512; bytesOut == 512; blkNum++) { for (int blkNum = 1, bytesOut = 512; bytesOut == 512; blkNum++) {
while (timeoutLimit != 0) { while (timeoutLimit != 0) {
try { try {
TFTPpacket inPak = TFTPpacket.receive(sock); TFTPpacket inPak = TFTPpacket.receive(sock);
//check packet type //check packet type
if (inPak instanceof TFTPerror) { if (inPak instanceof TFTPerror) {
TFTPerror p = (TFTPerror) inPak; TFTPerror p = (TFTPerror) inPak;
throw new TftpException(p.message()); throw new TftpException(p.message());
} else if (inPak instanceof TFTPdata) { } else if (inPak instanceof TFTPdata) {
TFTPdata p = (TFTPdata) inPak; TFTPdata p = (TFTPdata) inPak;
/*System.out.println("incoming data " + p.blockNumber());*/ /*System.out.println("incoming data " + p.blockNumber());*/
// check blk num // check blk num
if (/*testloss==20||*/p.blockNumber() != blkNum) { //expect to be the same if (/*testloss==20||*/p.blockNumber() != blkNum) { //expect to be the same
//System.out.println("loss. testloss="+testloss+"timeoutLimit="+timeoutLimit); //System.out.println("loss. testloss="+testloss+"timeoutLimit="+timeoutLimit);
//testloss++; //testloss++;
throw new SocketTimeoutException(); throw new SocketTimeoutException();
} }
//write to the file and send ack //write to the file and send ack
bytesOut = p.write(outFile); bytesOut = p.write(outFile);
TFTPack a = new TFTPack(blkNum); TFTPack a = new TFTPack(blkNum);
a.send(host, port, sock); a.send(host, port, sock);
//testloss++; //testloss++;
break; break;
} }
} catch (SocketTimeoutException t2) { } catch (SocketTimeoutException t2) {
System.out.println("Time out, resend ack"); System.out.println("Time out, resend ack");
TFTPack a = new TFTPack(blkNum - 1); TFTPack a = new TFTPack(blkNum - 1);
a.send(host, port, sock); a.send(host, port, sock);
timeoutLimit--; timeoutLimit--;
} }
} }
if(timeoutLimit==0){throw new Exception("Connection failed");} if (timeoutLimit == 0) {
} throw new Exception("Connection failed");
outFile.close(); }
System.out.println("Transfer completed.(Client " +host +")" ); }
System.out.println("Filename: "+fileName + "\nSHA1 checksum: "+CheckSum.getChecksum(fileName)+"\n"); outFile.close();
System.out.println("Transfer completed.(Client " + host + ")");
System.out.println("Filename: " + fileName + "\nSHA1 checksum: " + CheckSum.getChecksum(fileName) + "\n");
} catch (Exception e) { } catch (Exception e) {
TFTPerror ePak = new TFTPerror(1, e.getMessage()); TFTPerror ePak = new TFTPerror(1, e.getMessage());
try { try {
ePak.send(host, port, sock); ePak.send(host, port, sock);
} catch (Exception f) { } catch (Exception f) {
} }
System.out.println("Client failed: " + e.getMessage()); System.out.println("Client failed: " + e.getMessage());
saveFile.delete(); saveFile.delete();
} }
} }
} }
} }

View File

@ -1,7 +1,5 @@
package ru.redguy.tftpserver.datasource; package ru.redguy.tftpserver.datasource;
import ru.redguy.tftpserver.IDataSource;
import java.io.File; import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;

View File

@ -1,4 +1,4 @@
package ru.redguy.tftpserver; package ru.redguy.tftpserver.datasource;
public interface IDataSource { public interface IDataSource {
public boolean isFileExists(String localPath); public boolean isFileExists(String localPath);