338 lines
14 KiB
Java
338 lines
14 KiB
Java
/*
|
|
Copyright 2019-2020 Dmitry Isaenko, DarkMatterCore
|
|
|
|
This file is part of NS-USBloader.
|
|
|
|
NS-USBloader is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU General Public License as published by
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
(at your option) any later version.
|
|
|
|
NS-USBloader is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU General Public License for more details.
|
|
|
|
You should have received a copy of the GNU General Public License
|
|
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
package nsusbloader.Utilities;
|
|
|
|
import javafx.concurrent.Task;
|
|
import nsusbloader.COM.USB.UsbErrorCodes;
|
|
import nsusbloader.ModelControllers.LogPrinter;
|
|
import nsusbloader.NSLDataTypes.EMsgType;
|
|
import org.usb4java.DeviceHandle;
|
|
import org.usb4java.LibUsb;
|
|
|
|
import java.io.*;
|
|
import java.nio.ByteBuffer;
|
|
import java.nio.ByteOrder;
|
|
import java.nio.IntBuffer;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.util.Arrays;
|
|
|
|
class NxdtUsbAbi1 {
|
|
private LogPrinter logPrinter;
|
|
private DeviceHandle handlerNS;
|
|
private Task<Boolean> task;
|
|
private String saveToPath;
|
|
|
|
private boolean isWindows;
|
|
|
|
private static final int NXDT_COMMAND_SIZE = 0x1000;
|
|
private static final int NXDT_FILE_CHUNK_SIZE = 0x800000;
|
|
|
|
private static final byte ABI_VERSION = 1;
|
|
private static final byte[] MAGIC_NXDT = { 0x4e, 0x58, 0x44, 0x54 };
|
|
|
|
private static final int CMD_HANDSHAKE = 0;
|
|
private static final int CMD_SEND_FILE_PROPERTIES = 1;
|
|
private static final int CMD_ENDSESSION = 3;
|
|
|
|
// Standard set of possible replies
|
|
private static final byte[] USBSTATUS_SUCCESS = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
private static final byte[] USBSTATUS_INVALID_MAGIC = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x04, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
private static final byte[] USBSTATUS_UNSUPPORTED_CMD = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x05, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
private static final byte[] USBSTATUS_UNSUPPORTED_ABI = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x06, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
private static final byte[] USBSTATUS_MALFORMED_CMD = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x07, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
private static final byte[] USBSTATUS_HOSTIOERROR = { 0x4e, 0x58, 0x44, 0x54,
|
|
0x08, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00,
|
|
0x00, 0x00, 0x00, 0x00 };
|
|
|
|
public NxdtUsbAbi1(DeviceHandle handler,
|
|
Task<Boolean> task,
|
|
LogPrinter logPrinter,
|
|
String saveToPath
|
|
){
|
|
this.handlerNS = handler;
|
|
this.task = task;
|
|
this.logPrinter = logPrinter;
|
|
this.isWindows = System.getProperty("os.name").toLowerCase().contains("windows");
|
|
|
|
if (! saveToPath.endsWith(File.separator))
|
|
this.saveToPath = saveToPath + File.separator;
|
|
else
|
|
this.saveToPath = saveToPath;
|
|
|
|
readLoop();
|
|
}
|
|
|
|
private void readLoop(){
|
|
logPrinter.print("Awaiting for handshake", EMsgType.INFO);
|
|
try {
|
|
byte[] directive;
|
|
int command;
|
|
while (true){
|
|
directive = readUsbCmd();
|
|
|
|
if (isInvalidCommand(directive))
|
|
continue;
|
|
|
|
command = getLEint(directive, 4);
|
|
|
|
switch (command){
|
|
case CMD_HANDSHAKE:
|
|
performHandshake(directive);
|
|
break;
|
|
case CMD_SEND_FILE_PROPERTIES:
|
|
handleSendFileProperties(directive);
|
|
break;
|
|
case CMD_ENDSESSION:
|
|
logPrinter.print("Session successfully ended", EMsgType.PASS);
|
|
return;
|
|
default:
|
|
writeUsb(USBSTATUS_UNSUPPORTED_CMD);
|
|
}
|
|
}
|
|
}
|
|
catch (InterruptedException ioe){
|
|
logPrinter.print("Execution interrupted", EMsgType.INFO);
|
|
}
|
|
catch (Exception e){
|
|
e.printStackTrace();
|
|
logPrinter.print(e.getCause()+" "+e.getMessage(), EMsgType.INFO);
|
|
logPrinter.print("Terminating now", EMsgType.FAIL);
|
|
}
|
|
};
|
|
|
|
private boolean isInvalidCommand(byte[] message) throws Exception{
|
|
if (! Arrays.equals(Arrays.copyOfRange(message, 0,4), MAGIC_NXDT)){
|
|
writeUsb(USBSTATUS_INVALID_MAGIC);
|
|
logPrinter.print("Invalid magic command", EMsgType.INFO);
|
|
return true;
|
|
}
|
|
if (message.length != NXDT_COMMAND_SIZE){
|
|
writeUsb(USBSTATUS_MALFORMED_CMD);
|
|
logPrinter.print("Invalid command size. Expected size is 4096 while received is "+message.length, EMsgType.INFO);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void performHandshake(byte[] message) throws Exception{
|
|
final byte versionMajor = message[10];
|
|
final byte versionMinor = message[11];
|
|
final byte versionMicro = message[12];
|
|
final byte versionABI = message[13];
|
|
|
|
logPrinter.print("nxdumptool v"+versionMajor+"."+versionMinor+"."+versionMicro+" ABI v"+versionABI, EMsgType.INFO);
|
|
|
|
if (ABI_VERSION != versionABI){
|
|
writeUsb(USBSTATUS_UNSUPPORTED_ABI);
|
|
throw new Exception("ABI v"+message[11]+" is not supported in current version.");
|
|
}
|
|
writeUsb(USBSTATUS_SUCCESS);
|
|
// consider refactoring: create sub-classes for various ABI versions and check if it's supported or not
|
|
}
|
|
|
|
private void handleSendFileProperties(byte[] message) throws Exception{
|
|
final long fileSize = getLElong(message, 0x10);
|
|
final int fileNameLen = getLEint(message, 0x18);
|
|
String filename = new String(message, 0x20, fileNameLen, StandardCharsets.UTF_8);
|
|
|
|
// TODO: In here should be also a field with NSP Header size that would be transmitted after the end of main data transfer; NOTE: Handle with RandomAccessFile.
|
|
|
|
logPrinter.print("Write request for: '"+filename+"' ("+fileSize+" bytes)", EMsgType.INFO);
|
|
// If RomFs related
|
|
if (filename.startsWith("/")) {
|
|
if (isWindows)
|
|
filename = saveToPath + filename.replaceAll("/", "\\\\");
|
|
else
|
|
filename = saveToPath + filename;
|
|
|
|
try {
|
|
createPath(filename);
|
|
}
|
|
catch (Exception e){
|
|
writeUsb(USBSTATUS_HOSTIOERROR);
|
|
logPrinter.print("Unable to create dir(s) for file in "+filename+
|
|
"\n Returned: "+e.getMessage(), EMsgType.FAIL);
|
|
return;
|
|
}
|
|
}
|
|
else
|
|
filename = saveToPath + filename;
|
|
|
|
File fileToDump = new File(filename);
|
|
|
|
// Check if enough space
|
|
if (fileToDump.getFreeSpace() <= fileSize){
|
|
writeUsb(USBSTATUS_HOSTIOERROR);
|
|
logPrinter.print("Not enough space on selected volume. Need: "+fileSize+" while available: "+fileToDump.getFreeSpace(), EMsgType.FAIL);
|
|
return;
|
|
}
|
|
// Check if FS is NOT read-only
|
|
if (! fileToDump.canWrite()){
|
|
writeUsb(USBSTATUS_HOSTIOERROR);
|
|
logPrinter.print("Unable to write into selected volume: "+fileToDump.getAbsolutePath(), EMsgType.FAIL);
|
|
return;
|
|
}
|
|
|
|
dumpFile(fileToDump, fileSize);
|
|
|
|
writeUsb(USBSTATUS_SUCCESS);
|
|
|
|
// TODO: check if NSP_SIZE != 0 then go dump header
|
|
}
|
|
|
|
private void createPath(String path) throws Exception{
|
|
File resultingFile = new File(path);
|
|
File folderForTheFile = resultingFile.getParentFile();
|
|
folderForTheFile.mkdirs();
|
|
}
|
|
|
|
private void dumpFile(File file, long size) throws Exception{
|
|
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, false));
|
|
|
|
byte[] readBuffer;
|
|
long received = 0;
|
|
int bufferSize;
|
|
|
|
while (received < size){
|
|
readBuffer = readUsbFile();
|
|
bos.write(readBuffer);
|
|
bufferSize = readBuffer.length;
|
|
received += bufferSize;
|
|
|
|
logPrinter.updateProgress((received + bufferSize) / (size / 100.0) / 100.0);
|
|
}
|
|
|
|
logPrinter.updateProgress(1.0);
|
|
bos.close();
|
|
}
|
|
|
|
|
|
private int getLEint(byte[] bytes, int fromOffset){
|
|
return ByteBuffer.wrap(bytes, fromOffset, 0x4).order(ByteOrder.LITTLE_ENDIAN).getInt();
|
|
}
|
|
|
|
private long getLElong(byte[] bytes, int fromOffset){
|
|
return ByteBuffer.wrap(bytes, fromOffset, 0x8).order(ByteOrder.LITTLE_ENDIAN).getLong();
|
|
}
|
|
|
|
/**
|
|
* Sending any byte array to USB device
|
|
* @return 'false' if no issues
|
|
* 'true' if errors happened
|
|
* */
|
|
private void writeUsb(byte[] message) throws Exception{
|
|
ByteBuffer writeBuffer = ByteBuffer.allocateDirect(message.length);
|
|
writeBuffer.put(message);
|
|
IntBuffer writeBufTransferred = IntBuffer.allocate(1);
|
|
int result;
|
|
|
|
while (! task.isCancelled()) {
|
|
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x01, writeBuffer, writeBufTransferred, 5050);
|
|
|
|
switch (result){
|
|
case LibUsb.SUCCESS:
|
|
if (writeBufTransferred.get() == message.length)
|
|
return;
|
|
throw new Exception("Data transfer issue [write]" +
|
|
"\n Requested: "+message.length+
|
|
"\n Transferred: "+writeBufTransferred.get());
|
|
case LibUsb.ERROR_TIMEOUT:
|
|
continue;
|
|
default:
|
|
throw new Exception("Data transfer issue [write]" +
|
|
"\n Returned: "+ UsbErrorCodes.getErrCode(result) +
|
|
"\n (execution stopped)");
|
|
}
|
|
}
|
|
throw new InterruptedException("Execution interrupted");
|
|
}
|
|
/**
|
|
* Reading what USB device responded (command).
|
|
* @return byte array if data read successful
|
|
* 'null' if read failed
|
|
* */
|
|
private byte[] readUsbCmd() throws Exception{
|
|
ByteBuffer readBuffer = ByteBuffer.allocateDirect(NXDT_COMMAND_SIZE);
|
|
// We can limit it to 32 bytes, but there is a non-zero chance to got OVERFLOW from libusb.
|
|
IntBuffer readBufTransferred = IntBuffer.allocate(1);
|
|
int result;
|
|
while (! task.isCancelled()) {
|
|
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000); // last one is TIMEOUT. 0 stands for unlimited. Endpoint IN = 0x81
|
|
|
|
switch (result) {
|
|
case LibUsb.SUCCESS:
|
|
int trans = readBufTransferred.get();
|
|
byte[] receivedBytes = new byte[trans];
|
|
readBuffer.get(receivedBytes);
|
|
return receivedBytes;
|
|
case LibUsb.ERROR_TIMEOUT:
|
|
continue;
|
|
default:
|
|
throw new Exception("Data transfer issue [read command]" +
|
|
"\n Returned: " + UsbErrorCodes.getErrCode(result)+
|
|
"\n (execution stopped)");
|
|
}
|
|
}
|
|
throw new InterruptedException();
|
|
}
|
|
/**
|
|
* Reading what USB device responded (file).
|
|
* @return byte array if data read successful
|
|
* 'null' if read failed
|
|
* */
|
|
private byte[] readUsbFile() throws Exception{
|
|
ByteBuffer readBuffer = ByteBuffer.allocateDirect(NXDT_FILE_CHUNK_SIZE);
|
|
IntBuffer readBufTransferred = IntBuffer.allocate(1);
|
|
int result;
|
|
while (! task.isCancelled()) {
|
|
result = LibUsb.bulkTransfer(handlerNS, (byte) 0x81, readBuffer, readBufTransferred, 1000);
|
|
|
|
switch (result) {
|
|
case LibUsb.SUCCESS:
|
|
int trans = readBufTransferred.get();
|
|
byte[] receivedBytes = new byte[trans];
|
|
readBuffer.get(receivedBytes);
|
|
return receivedBytes;
|
|
case LibUsb.ERROR_TIMEOUT:
|
|
continue;
|
|
default:
|
|
throw new Exception("Data transfer issue [read file]" +
|
|
"\n Returned: " + UsbErrorCodes.getErrCode(result)+
|
|
"\n (execution stopped)");
|
|
}
|
|
}
|
|
throw new InterruptedException();
|
|
}
|
|
}
|