Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.IO;
- using LibUsbDotNet;
- using LibUsbDotNet.Info;
- using LibUsbDotNet.Main;
- using System.Collections.ObjectModel;
- /*
- * sda-flashtool alpha r06
- * developed by slashdevandroid '15
- *
- * Released under the following terms: for personal, non-commercial, and/or educational use only. As-is.
- * UNCONDITIONALLY: you accept all terms, conditions, and all associated risks and liabilities. Portions may have
- * additional rights and/or restrictions by other parties.
- *
- * *** FAIR USE NOTICE ***
- * Portions may have additional rights and/or restrictions by other parties.
- */
- namespace sda_flashtool
- {
- public static class SharedGlobally
- {
- public static int ProgramVersion = 6;
- public static string ProgramInfo = String.Format("sda-flashtool [ALPHA] r{0:00}\nDeveloped by: slashdevandroid '15\n", ProgramVersion);
- public static string ReleaseAndUseConditions = "Released under the following terms: for personal, non-commercial, and/or educational use only. As-is. UNCONDITIONALLY: you accept all terms, conditions, and all associated risks and liabilities. Portions may have additional rights and/or restrictions by other parties.";
- public static bool waitingResponse = false;
- public static byte[] responseBuffer = new byte[4132];
- public static int defaultTimeoutInMS = 90 * 1000;
- public static int transferredOut;
- public static int transferredIn;
- public static UsbTransfer usbWriteTransfer;
- public static UsbTransfer usbReadTransfer;
- public static ErrorCode ecWrite = ErrorCode.None;
- public static ErrorCode ecRead = ErrorCode.None;
- public static bool PhoneInFailState = false;
- }
- class MainClass
- {
- public static UsbDevice MyUsbDevice;
- public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x1ebf, 0x7001);
- public static UsbEndpointWriter usbWriter;
- public static UsbEndpointReader usbReader;
- // methods for changing hex to strings and so forth
- public static byte[] StringToByteArrayFastest(string hex)
- {
- if (hex.Length % 2 == 1)
- return new byte[] { 0x00 };
- byte[] arr = new byte[hex.Length >> 1];
- for (int i = 0; i < hex.Length >> 1; ++i)
- {
- arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
- }
- return arr;
- }
- public static int GetHexVal(char hex)
- {
- int val = (int)hex;
- return val - (val < 58 ? 48 : 55);
- }
- public static string HexToStr(string HexString)
- {
- HexString = HexString.Replace("-", "");
- HexString = HexString.Replace(":", "");
- byte[] raw = new byte[HexString.Length / 2];
- for (int i = 0; i < raw.Length; i++)
- {
- raw[i] = Convert.ToByte(HexString.Substring(i * 2, 2), 16);
- }
- return (string)Encoding.ASCII.GetString(raw);
- }
- public static string StrToHex(string toHex)
- {
- char[] values = toHex.ToCharArray();
- string hexOut = string.Empty;
- foreach (char letter in values)
- {
- int value = Convert.ToInt32(letter);
- hexOut += String.Format("{0:X}", value);
- }
- return hexOut;
- }
- public static string byteArrayToHexString(byte[] raw, int len = -1)
- {
- string returnVal;
- if (len == -1)
- returnVal = BitConverter.ToString(raw);
- else
- returnVal = BitConverter.ToString(raw, 0, len);
- return (string)returnVal;
- }
- // begin usb interface stuff
- public static void SendData(byte[] byteArray, int timeOut = 30000)
- {
- int bytesWritten;
- if (MainClass.usbReader == null || MainClass.usbWriter == null)
- return;
- System.Threading.Thread.Sleep(10);
- try
- {
- SharedGlobally.ecWrite = MainClass.usbWriter.Transfer(byteArray, 0, byteArray.Length, timeOut, out bytesWritten);
- if (SharedGlobally.ecWrite != ErrorCode.None)
- {
- Console.WriteLine(SharedGlobally.ecWrite.ToString() + UsbDevice.LastErrorString.ToString());
- }
- }
- catch
- {
- Console.WriteLine(SharedGlobally.ecWrite.ToString() + UsbDevice.LastErrorString.ToString());
- }
- }
- public static void SendRawCommand(byte[] byteCmd, string descrp = "", bool waitResponse = true)
- {
- Console.ForegroundColor = ConsoleColor.Green;
- if (descrp == "")
- Console.WriteLine("SEND: {0}", byteArrayToHexString(byteCmd, 4));
- else
- Console.WriteLine("SEND: {0}", descrp);
- Console.ResetColor();
- SharedGlobally.waitingResponse = waitResponse;
- SendData(byteCmd);
- }
- public static void SendCommand(string d, bool waitResponse = true)
- {
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine("SEND: COMMAND:" + d.ToString());
- byte[] byteCmd = new byte[d.Length];
- byteCmd = Encoding.ASCII.GetBytes(d);
- Console.ResetColor();
- SharedGlobally.waitingResponse = waitResponse;
- SendData(byteCmd);
- }
- public static void SendByPKTTransferMethod(string @fileName, string flashTarget)
- {
- long fileByteSize = (new System.IO.FileInfo(fileName).Length);
- int length = (int)fileByteSize;
- byte[] initialHeaderArray = new byte[12];
- byte[] finalHeaderArray = new byte[12];
- int maxPKTLength = 209715200;
- int numOfEvenSystemPackets = 1;
- if (length > maxPKTLength)
- numOfEvenSystemPackets = (int)length / (int)maxPKTLength;
- string hexLength = maxPKTLength.ToString("x").PadLeft(8, '0');
- Buffer.BlockCopy(Encoding.ASCII.GetBytes(hexLength), 0, initialHeaderArray, 0, 8);
- // FAIR USE
- Buffer.BlockCopy(FairUseOnly.lengthConstant, 0, initialHeaderArray, 9, FairUseOnly.lengthConstant.Length);
- initialHeaderArray = FairUseOnly.headerLengthSimpleSubstitution(initialHeaderArray);
- string encodedInitialAndMiddle = BitConverter.ToString(initialHeaderArray).Replace("-", ":");
- string encodedFinalHeader = BitConverter.ToString(finalHeaderArray).Replace("-", ":");
- Console.ForegroundColor = ConsoleColor.White;
- Console.WriteLine("\nFlashing...");
- Console.WriteLine("File: '{0}'\nSize: '{1}' (bytes)", fileName, length, hexLength);
- Console.WriteLine("ATTEMPTING FLASH: {0} -> {1}", fileName, flashTarget);
- Console.ResetColor();
- string downloadPKTstr;
- int currentPKTNumber = 1;
- // begin transfering
- byte[] fileChunk = new byte[4096];
- using (FileStream fs = File.OpenRead(fileName))
- {
- using (BinaryReader br = new BinaryReader(fs))
- {
- byte[] header;
- for (currentPKTNumber = 1; currentPKTNumber < (numOfEvenSystemPackets + 1); currentPKTNumber++)
- {
- Console.ForegroundColor = ConsoleColor.White;
- Console.WriteLine("\nATTEMPTING Transfer of PKT{0}\n", currentPKTNumber);
- Console.ResetColor();
- downloadPKTstr = "download-pkt:" + hexLength + string.Format(",{0:00}", currentPKTNumber);
- SendCommand(downloadPKTstr);
- awaitResponse();
- Array.Copy(initialHeaderArray, fileChunk, initialHeaderArray.Length);
- header = new byte[4096 - initialHeaderArray.Length];
- header = br.ReadBytes(4096 - initialHeaderArray.Length);
- Array.Copy(header, 0, fileChunk, initialHeaderArray.Length, header.Length);
- if (SharedGlobally.PhoneInFailState == false)
- {
- SendData(fileChunk, 100);
- }
- // 1 (header) + 51199 = 51200 * 4096 = 0xC800000 = max PKT size before flash.
- for (int startPacket = 1; startPacket < 51200; startPacket++)
- {
- Console.Title = string.Format("Transfering: PKT{0}/4 Transmitted:{1}/{2}", currentPKTNumber, fs.Position, fs.Length);
- Array.Clear(fileChunk, 0, fileChunk.Length);
- fileChunk = br.ReadBytes(4096);
- if (SharedGlobally.PhoneInFailState == false)
- {
- SendData(fileChunk, 100);
- }
- }
- System.Threading.Thread.Sleep(3000);
- // AWAIT OKAY
- awaitResponse();
- // FLASH IT.
- SendCommand("flash-pkt:" + flashTarget + string.Format(" {0:00}", currentPKTNumber));
- awaitResponse();
- }
- // LAST PKT
- currentPKTNumber = (numOfEvenSystemPackets + 1);
- int lastPacketSize = 12 + (int)fs.Length - (int)fs.Position;
- string finalHexLength = lastPacketSize.ToString("x").PadLeft(8, '0');
- Buffer.BlockCopy(Encoding.ASCII.GetBytes(finalHexLength), 0, finalHeaderArray, 0, 8);
- downloadPKTstr = "download-pkt:" + finalHexLength + string.Format(",{0:00}", currentPKTNumber);
- finalHeaderArray = FairUseOnly.headerLengthSimpleSubstitution(finalHeaderArray);
- encodedFinalHeader = BitConverter.ToString(finalHeaderArray).Replace("-", ":");
- Console.ForegroundColor = ConsoleColor.White;
- Console.WriteLine("\nTransfer of Final PKT{0}\n", currentPKTNumber);
- Console.ResetColor();
- SendCommand(downloadPKTstr);
- awaitResponse();
- fileChunk = new byte[4096];
- Array.Copy(finalHeaderArray, fileChunk, finalHeaderArray.Length);
- header = new byte[4096 - finalHeaderArray.Length];
- header = br.ReadBytes(4096 - finalHeaderArray.Length);
- Array.Copy(header, 0, fileChunk, finalHeaderArray.Length, header.Length);
- if (SharedGlobally.PhoneInFailState == false)
- {
- SendData(fileChunk, 100);
- }
- int packetsLeft = ((int)length - (int)fs.Position) / 4096;
- for (int packetNo = 0; packetNo < packetsLeft; packetNo++)
- {
- Console.Title = string.Format("Transfering: PKT{0}/4 Transmitted:{1}/{2}", currentPKTNumber, fs.Position, fs.Length);
- Array.Clear(fileChunk, 0, fileChunk.Length);
- fileChunk = br.ReadBytes(4096);
- if (SharedGlobally.PhoneInFailState == false)
- {
- SendData(fileChunk, 100);
- }
- }
- fileChunk = new byte[fs.Length - fs.Position];
- fileChunk = br.ReadBytes(fileChunk.Length);
- SendData(fileChunk);
- if (fs.Position == fs.Length)
- Console.ForegroundColor = ConsoleColor.Cyan;
- else
- Console.ForegroundColor = ConsoleColor.Red;
- System.Threading.Thread.Sleep(4000);
- awaitResponse();
- SendCommand("flash-pkt:" + flashTarget + string.Format(" {0:00}", currentPKTNumber));
- awaitResponse();
- }
- }
- }
- private static void RECVFromUSB(object sender, EndpointDataEventArgs e)
- {
- Console.ResetColor();
- string check = System.Text.Encoding.UTF8.GetString(e.Buffer, 0, 10);
- Console.ForegroundColor = ConsoleColor.Blue;
- if (check.Contains("OKAY") && !check.Contains("OKAYV1"))
- {
- Console.WriteLine("RECV: OKAY", check);
- }
- if (check.Contains("FAIL"))
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("RECV: DEVICE OPERATION FAILURE - FAIL{0}", System.Text.Encoding.UTF8.GetString(e.Buffer, 5, 14));
- SharedGlobally.PhoneInFailState = true;
- }
- if (check.Contains("DATA"))
- {
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("RECV: DEVICE AWAITING DATA TRANSFER: {0}", System.Text.Encoding.UTF8.GetString(e.Buffer, 4, 14));
- }
- if (check.Contains("OKAYV1"))
- {
- Console.WriteLine("RECV: DEVICE ACKs CMD");
- }
- Console.ResetColor();
- lock (SharedGlobally.responseBuffer)
- {
- Array.Copy(e.Buffer, SharedGlobally.responseBuffer, e.Buffer.Length);
- }
- SharedGlobally.waitingResponse = false;
- }
- private static void awaitResponse(int waitTime = -1, string expectedResponse = "")
- {
- if (waitTime == -1)
- waitTime = SharedGlobally.defaultTimeoutInMS;
- int _currentIdle = 0;
- while (SharedGlobally.waitingResponse == true)
- {
- if (_currentIdle < waitTime)
- {
- Console.Title = String.Format("Timeout in: {0}/{1}", _currentIdle, waitTime);
- System.Threading.Thread.Sleep(20);
- _currentIdle += 20;
- }
- else
- {
- throw new Exception("error awaiting response");
- }
- }
- System.Threading.Thread.Sleep(19);
- SharedGlobally.waitingResponse = false;
- }
- // FAIR USE -- REQUIRED TO FLASH/TRANSFER TO DEVICE
- public static void DoUnlockSequence()
- {
- SendRawCommand(FairUseOnly.StartDownloadOne, "StartDownload One/Two");
- awaitResponse();
- SendRawCommand(FairUseOnly.StartDownloadTwo, "StartDownload Two/Two");
- awaitResponse();
- SendCommand("unlock-boot");
- awaitResponse();
- SendRawCommand(FairUseOnly.enableUpgradeMode, "Enabling Upgrade Mode");
- awaitResponse();
- }
- // FAIR USE -- REQUIRED TO FLASH/TRANSFER TO DEVICE
- public static void DoLockSequence()
- {
- System.Threading.Thread.Sleep(2000);
- SendCommand("lock-boot");
- awaitResponse();
- Console.WriteLine("FAIR USE - cleartext: write-par:V1?2");
- SendRawCommand(FairUseOnly.disableUpgradeMode, "Disabling Upgrade mode - FAIR USE");
- awaitResponse();
- SendCommand("StopDownload");
- Console.WriteLine("REBOOTING DEVICE IN in 10s");
- System.Threading.Thread.Sleep(10000);
- SendCommand("reboot-bootloader");
- awaitResponse();
- System.Threading.Thread.Sleep(3000);
- }
- public static void ShowAuthorNoticesAndDisclaimer()
- {
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine(SharedGlobally.ProgramInfo);
- Console.WriteLine("If you agree: type 'I agree' and press enter.\n");
- Console.ResetColor();
- string writeYes = Console.ReadLine();
- if (writeYes != "I agree")
- {
- Console.WriteLine("You didn't agree to the terms. Terminating.");
- Environment.Exit(0);
- }
- }
- public static void Main(string[] args)
- {
- ShowAuthorNoticesAndDisclaimer();
- try
- {
- MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
- if (MyUsbDevice == null)
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("ERROR: USB Device: 0x1ebf:0x7001 not connected");
- throw new Exception("ERROR: USB Device was not found");
- }
- MainClass.usbReader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
- MainClass.usbWriter = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
- usbReader.DataReceived += (RECVFromUSB);
- usbReader.DataReceivedEnabled = true;
- DoUnlockSequence();
- SendByPKTTransferMethod(@"new_system.img", "system");
- DoLockSequence();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- finally
- {
- if (usbReader != null)
- {
- usbReader.DataReceivedEnabled = false;
- usbReader.DataReceived -= (RECVFromUSB);
- }
- if (MyUsbDevice != null)
- {
- if (MyUsbDevice.IsOpen)
- {
- MyUsbDevice.Close();
- }
- MyUsbDevice = null;
- UsbDevice.Exit();
- }
- }
- Console.ResetColor();
- Console.WriteLine("All Done! Enjoy.");
- Environment.Exit(0);
- }
- }
- }
Add Comment
Please, Sign In to add comment