Repository navigation
Expand file tree
/
Copy pathWeb.cs
More file actions
319 lines (307 loc) · 13.1 KB
/
Copy pathWeb.cs
File metadata and controls
319 lines (307 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace SamFirm
{
internal class Web
{
public static string JSessionID = string.Empty;
public static CookieContainer CookieContainer = new CookieContainer();
public static string EncryptedNonce = string.Empty;
public static byte[] DecryptedNonce = null;
public static string Nonce => DecryptedNonce == null ? string.Empty : Encoding.ASCII.GetString(DecryptedNonce);
public static string Auth = string.Empty;
public static string AuthHeaderWithNonce => $"FUS nonce=\"{EncryptedNonce}\", signature=\"{Auth}\", nc=\"\", type=\"\", realm=\"\", newauth=\"1\"";
public static string AuthHeaderNoNonce => $"FUS nonce=\"{EncryptedNonce}\", signature=\"{Auth}\", nc=\"\", type=\"\", realm=\"\", newauth=\"1\"";
public static Form1 form;
public static int GenerateNonce()
{
HttpWebRequest wr = KiesRequest.Create("https://neofussvr.sslcs.cdngc.net/NF_SmartDownloadGenerateNonce.do");
wr.Method = "POST";
string authv = $"FUS nonce=\"\", signature=\"\", nc=\"\", type=\"\", realm=\"\", newauth=\"1\"";
wr.Headers["Authorization"] = authv;
wr.ContentLength = 0L;
using (HttpWebResponse responseFus = (HttpWebResponse)wr.GetResponseFUS())
{
if (responseFus == null)
return 901;
int statusCode = (int)responseFus.StatusCode;
return statusCode;
}
}
public static int DownloadBinaryInform(string xml, out string xmlresponse)
{
return Web.XMLFUSRequest("https://neofussvr.sslcs.cdngc.net/NF_SmartDownloadBinaryInform.do", xml, out xmlresponse);
}
public static int DownloadBinaryInit(string xml, out string xmlresponse)
{
return Web.XMLFUSRequest("https://neofussvr.sslcs.cdngc.net/NF_SmartDownloadBinaryInitForMass.do", xml, out xmlresponse);
}
private static int XMLFUSRequest(string URL, string xml, out string xmlresponse)
{
xmlresponse = (string)null;
HttpWebRequest wr = KiesRequest.Create(URL);
wr.Method = "POST";
wr.Headers["Authorization"] = AuthHeaderNoNonce;
byte[] bytes = Encoding.ASCII.GetBytes(Regex.Replace(xml, "\\r\\n?|\\n|\\t", string.Empty));
wr.ContentLength = (long)bytes.Length;
using (Stream requestStream = wr.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse responseFus = (HttpWebResponse)wr.GetResponseFUS())
{
if (responseFus == null)
return 901;
if (responseFus.StatusCode == HttpStatusCode.OK)
{
try
{
xmlresponse = new StreamReader(responseFus.GetResponseStream()).ReadToEnd();
}
catch (Exception ex)
{
return 900;
}
}
return (int)responseFus.StatusCode;
}
}
public static void SetReconnect()
{
if (!Utility.run_by_cmd)
{
if (!Web.form.PauseDownload)
Utility.ReconnectDownload = true;
Web.form.PauseDownload = true;
}
else
Utility.ReconnectDownload = true;
}
public static int DownloadBinary(
string path,
string file,
string saveTo,
string size,
bool GUI = true,
bool decryptInline = false)
{
long bytesTransferred = 0;
HttpWebRequest wr = KiesRequest.Create("http://cloud-neofussvr.samsungmobile.com/NF_SmartDownloadBinaryForMass.do?file=" + path + file);
wr.Method = "GET";
wr.Headers["Authorization"] = AuthHeaderWithNonce;
wr.Timeout = 25000;
wr.ReadWriteTimeout = 25000;
string inlineResumeMarker = saveTo + ".resume";
if (decryptInline)
{
bool canResume = System.IO.File.Exists(saveTo) && System.IO.File.Exists(inlineResumeMarker);
if (canResume)
{
long decryptedLength = new FileInfo(saveTo).Length;
if (decryptedLength % 16 != 0)
{
Logger.WriteLog("Inline download state is incomplete. Restarting download...", false);
System.IO.File.Delete(saveTo);
System.IO.File.Delete(inlineResumeMarker);
}
else
{
Logger.WriteLog("Resuming inline download...", false);
wr.AddRange(decryptedLength);
bytesTransferred = decryptedLength;
}
}
else
{
if (System.IO.File.Exists(saveTo))
System.IO.File.Delete(saveTo);
if (System.IO.File.Exists(inlineResumeMarker))
System.IO.File.Delete(inlineResumeMarker);
}
}
if (!decryptInline && System.IO.File.Exists(saveTo))
{
long length = new FileInfo(saveTo).Length;
if (long.Parse(size) == length)
{
Logger.WriteLog("File already downloaded.", false);
return 200;
}
Logger.WriteLog("File exists. Resuming download...", false);
//wr.AddRange((int) length); // This creates an error, if download continues when file size has exceeded 2 GByte, since AddRange then adds a negative range!
wr.AddRange(length); // Fixed using an extension, handling range typed as long
bytesTransferred = length;
}
using (HttpWebResponse responseFus = (HttpWebResponse)wr.GetResponseFUS())
{
if (responseFus == null)
{
Logger.WriteLog("Error downloading: response is null", false);
return 901;
}
if (responseFus.StatusCode != HttpStatusCode.OK && responseFus.StatusCode != HttpStatusCode.PartialContent)
{
Logger.WriteLog("Error downloading: " + (object)(int)responseFus.StatusCode, false);
}
else
{
// A few CDNs ignore Range. Do not append a full response to a partial package.
if (decryptInline && bytesTransferred > 0 && responseFus.StatusCode == HttpStatusCode.OK)
{
Logger.WriteLog("Server ignored resume request. Restarting inline download...", false);
bytesTransferred = 0;
System.IO.File.Delete(saveTo);
System.IO.File.Delete(inlineResumeMarker);
}
long total = long.Parse(responseFus.GetResponseHeader("content-length")) + bytesTransferred;
if (!System.IO.File.Exists(saveTo) || new FileInfo(saveTo).Length != total)
{
byte[] buffer = new byte[256 * 1024];
Stopwatch sw = new Stopwatch();
Utility.ResetSpeed(bytesTransferred);
try
{
Utility.PreventDeepSleep(Utility.PDSMode.Start);
if (decryptInline)
System.IO.File.WriteAllText(inlineResumeMarker, "inline");
using (FileStream output = new FileStream(saveTo, FileMode.Append, FileAccess.Write, FileShare.Read))
using (ICryptoTransform decryptor = decryptInline ? Crypto.CreateDecryptor() : null)
{
if (decryptInline && decryptor == null)
return 3;
byte[] pendingCipher = new byte[16];
int pendingCount = 0;
byte[] lastPlain = new byte[16];
bool hasLastPlain = false;
bool completed = true;
int count;
do
{
Utility.PreventDeepSleep(Utility.PDSMode.Continue);
if (GUI)
{
if (Web.form.PauseDownload)
{
completed = false;
break;
}
}
bytesTransferred += (long)(count = responseFus.GetResponseStream().Read(buffer, 0, buffer.Length));
if (count > 0)
{
if (!decryptInline)
output.Write(buffer, 0, count);
else
{
int offset = 0;
while (offset < count)
{
int copy = Math.Min(16 - pendingCount, count - offset);
Buffer.BlockCopy(buffer, offset, pendingCipher, pendingCount, copy);
pendingCount += copy;
offset += copy;
if (pendingCount == 16)
{
byte[] plain = new byte[16];
decryptor.TransformBlock(pendingCipher, 0, 16, plain, 0);
if (hasLastPlain)
output.Write(lastPlain, 0, lastPlain.Length);
Buffer.BlockCopy(plain, 0, lastPlain, 0, lastPlain.Length);
hasLastPlain = true;
pendingCount = 0;
}
}
}
if (GUI)
{
int dlspeed = Utility.DownloadSpeed(bytesTransferred, sw);
if (dlspeed != -1)
Web.form.lbl_speed.Invoke((Delegate)((Action)(() => Web.form.lbl_speed.Text = dlspeed.ToString() + " KB/s")));
}
}
if (GUI)
Web.form.SetProgressBar(Utility.GetProgress(bytesTransferred, total), bytesTransferred);
else
CmdLine.SetProgress(Utility.GetProgress(bytesTransferred, total));
}
while (count > 0);
if (decryptInline && completed)
{
if (pendingCount != 0 || !hasLastPlain)
throw new IOException("Encrypted firmware stream ended on a partial AES block");
int padding = lastPlain[15];
if (padding < 1 || padding > 16)
throw new IOException("Encrypted firmware has invalid padding");
for (int i = 1; i <= padding; ++i)
{
if (lastPlain[16 - i] != padding)
throw new IOException("Encrypted firmware has invalid padding");
}
output.Write(lastPlain, 0, 16 - padding);
output.Flush();
System.IO.File.Delete(inlineResumeMarker);
}
}
}
catch (IOException ex)
{
if (ex.InnerException is SocketException ||
ex.Message.IndexOf("transport connection", StringComparison.OrdinalIgnoreCase) >= 0)
{
Logger.WriteLog("Error: Connection interrupted. Resuming download...", false);
Web.SetReconnect();
return -1;
}
Logger.WriteLog("Error: Can't access output file " + saveTo, false);
if (GUI)
Web.form.PauseDownload = true;
Logger.WriteLog(ex.ToString(), false);
return -1;
}
catch (WebException ex)
{
Logger.WriteLog("Error: Connection interrupted", false);
Web.SetReconnect();
}
finally
{
Utility.PreventDeepSleep(Utility.PDSMode.Stop);
if (GUI)
Web.form.lbl_speed.Invoke((Delegate)((Action)(() => Web.form.lbl_speed.Text = "0 KB/s")));
}
}
}
return (int)responseFus.StatusCode;
}
}
}
public static class Extensions
{
static MethodInfo httpWebRequestAddRangeHelper = typeof(WebHeaderCollection).GetMethod
("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
/// <summary>
/// Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
/// <param name="request">The <see cref="System.Web.HttpWebRequest"/> to add the range specifier to.</param>
/// <param name="start">The starting or ending point of the range.</param>
public static void AddRange(this HttpWebRequest request, long start) { request.AddRange(start, -1L); }
/// <summary>Adds a byte range header to the request for a specified range.</summary>
/// <param name="request">The <see cref="System.Web.HttpWebRequest"/> to add the range specifier to.</param>
/// <param name="start">The position at which to start sending data.</param>
/// <param name="end">The position at which to stop sending data.</param>
public static void AddRange(this HttpWebRequest request, long start, long end)
{
if (request == null) throw new ArgumentNullException("request");
if (start < 0) throw new ArgumentOutOfRangeException("start", "Starting byte cannot be less than 0.");
if (end < start) end = -1;
string key = "Range";
string val = string.Format("bytes={0}-{1}", start, end == -1 ? "" : end.ToString());
httpWebRequestAddRangeHelper.Invoke(request.Headers, new object[] { key, val });
}
}
}