-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRobustDownload.cs
1456 lines (1315 loc) · 57.5 KB
/
RobustDownload.cs
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO; // For File, Path, FileInfo classes
using System.Text; // For StringBuilder class
using System.Threading; // For AutoResetEvent, Thread classes
using System.Net; // For network-related classes
using System.Diagnostics; // For Process, ProcessStartInfo classes
using System.Collections.Generic; // For Dictionary and List classes
/// <summary>
/// A robust class for downloading content from URLs using various methods including curl, wget, and PowerShell.
/// DEPENDENCIES: Requires curl.exe and/or wget.exe to be available in the system's PATH for the respective
/// download methods to function. PowerShell.exe is required for the PowerShell method.
/// </summary>
public class RobustDownload
{
/// <summary>
/// Defines the available download methods.
/// </summary>
public enum DownloadMethod
{
Auto = 0, // Automatically choose the best method
Curl = 1, // Use curl as primary method
Wget = 2, // Use wget as primary method
PowerShell = 3 // Use PowerShell WebClient as primary method
}
/// <summary>
/// Class to hold the result of a download operation.
/// </summary>
public class DownloadResult
{
private bool _success = false;
private string _content = "";
private byte[] _data = null;
private string _filePath = "";
private string _errorMessage = "";
private DownloadMethod _usedMethod = DownloadMethod.Auto;
private int _statusCode = 0;
private long _durationMs = 0;
private Dictionary<DownloadMethod, string> _allErrors = new Dictionary<DownloadMethod, string>();
/// <summary>
/// Whether the download was successful.
/// </summary>
public bool Success
{
get { return _success; }
set { _success = value; }
}
/// <summary>
/// The downloaded content as a string (if text content was downloaded).
/// NOTE: When content is captured directly from command-line tools (not from file),
/// the encoding depends on the console output encoding of the external tool.
/// Use DownloadStringWithEncoding for explicit encoding control.
/// </summary>
public string Content
{
get { return _content; }
set { _content = value; }
}
/// <summary>
/// The downloaded content as a byte array (if binary content was downloaded).
/// </summary>
public byte[] Data
{
get { return _data; }
set { _data = value; }
}
/// <summary>
/// Path to the saved file (if content was saved to a file).
/// </summary>
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
/// <summary>
/// Error message if the download failed.
/// </summary>
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
/// <summary>
/// The download method that was successfully used.
/// </summary>
public DownloadMethod UsedMethod
{
get { return _usedMethod; }
set { _usedMethod = value; }
}
/// <summary>
/// HTTP status code if available. Note: This might be approximate as not all tools
/// provide direct access to the status code. Default is 200 for success, 0 for failure.
/// </summary>
public int StatusCode
{
get { return _statusCode; }
set { _statusCode = value; }
}
/// <summary>
/// Duration of the download operation in milliseconds.
/// </summary>
public long DurationMs
{
get { return _durationMs; }
set { _durationMs = value; }
}
/// <summary>
/// Collection of errors from all attempted methods if multiple methods were tried.
/// </summary>
public Dictionary<DownloadMethod, string> AllErrors
{
get { return _allErrors; }
set { _allErrors = value; }
}
/// <summary>
/// Creates a new success result.
/// </summary>
public static DownloadResult CreateSuccess(DownloadMethod method, string content = "",
byte[] data = null, string filePath = "",
int statusCode = 200,
long durationMs = 0)
{
DownloadResult result = new DownloadResult();
result.Success = true;
result.Content = content;
result.Data = data;
result.FilePath = filePath;
result.UsedMethod = method;
result.StatusCode = statusCode;
result.DurationMs = durationMs;
return result;
}
/// <summary>
/// Creates a new failure result.
/// </summary>
public static DownloadResult CreateFailure(string errorMessage, DownloadMethod method,
int statusCode = 0,
long durationMs = 0)
{
DownloadResult result = new DownloadResult();
result.Success = false;
result.ErrorMessage = errorMessage;
result.UsedMethod = method;
result.StatusCode = statusCode;
result.DurationMs = durationMs;
return result;
}
}
/// <summary>
/// Downloads content from a URL using the specified method with fallback options.
/// Returns a DownloadResult object containing the result status and content.
/// </summary>
/// <param name="url">The URL to download content from.</param>
/// <param name="method">The primary download method to use.</param>
/// <param name="enableFallback">Whether to try alternative methods if the primary method fails.</param>
/// <param name="useragent">The User-Agent header value.</param>
/// <param name="username">Optional username for authentication.</param>
/// <param name="password">Optional password for authentication.</param>
/// <param name="headers">Optional additional HTTP headers.</param>
/// <param name="timeoutSeconds">Timeout in seconds.</param>
/// <param name="proxyUrl">Optional proxy URL.</param>
/// <param name="outputFile">Optional path to save the downloaded content.</param>
/// <param name="allowInsecureSSL">Whether to allow insecure SSL connections (not recommended for security reasons).</param>
/// <returns>A DownloadResult object containing the result of the operation.</returns>
public static DownloadResult Download(
string url,
DownloadMethod method = DownloadMethod.Auto,
bool enableFallback = true,
string useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
string username = "",
string password = "",
Dictionary<string, string> headers = null,
int timeoutSeconds = 60,
string proxyUrl = "",
string outputFile = "",
bool allowInsecureSSL = false)
{
// Track operation time
long startTime = DateTime.Now.Ticks;
// Flag to determine if we're saving to a file
bool isSavingToFile = !string.IsNullOrEmpty(outputFile);
// Create a temporary output file if needed
string tempOutputFile = "";
if (isSavingToFile)
{
tempOutputFile = outputFile;
}
// Determine methods to try based on primary method and fallback setting
List<DownloadMethod> methodsToTry = new List<DownloadMethod>();
if (method == DownloadMethod.Auto)
{
// Try curl first, then wget, then PowerShell
methodsToTry.Add(DownloadMethod.Curl);
methodsToTry.Add(DownloadMethod.Wget);
methodsToTry.Add(DownloadMethod.PowerShell);
}
else
{
// Start with the specified method
methodsToTry.Add(method);
// Add fallbacks if enabled
if (enableFallback)
{
if (method != DownloadMethod.Curl) methodsToTry.Add(DownloadMethod.Curl);
if (method != DownloadMethod.Wget) methodsToTry.Add(DownloadMethod.Wget);
if (method != DownloadMethod.PowerShell) methodsToTry.Add(DownloadMethod.PowerShell);
}
}
// Create a result to collect errors if we need to try multiple methods
DownloadResult finalResult = new DownloadResult();
// Try each method in order until one succeeds
foreach (DownloadMethod downloadMethod in methodsToTry)
{
DownloadResult result = null;
switch (downloadMethod)
{
case DownloadMethod.Curl:
if (IsCurlAvailable())
{
result = DownloadWithCurl(url, tempOutputFile, useragent, username, password, headers, timeoutSeconds, proxyUrl, allowInsecureSSL);
if (result.Success)
{
// Calculate duration
result.DurationMs = (DateTime.Now.Ticks - startTime) / 10000;
return result;
}
else
{
// Store the error for later reporting
finalResult.AllErrors[DownloadMethod.Curl] = result.ErrorMessage;
}
}
break;
case DownloadMethod.Wget:
if (IsWgetAvailable())
{
result = DownloadWithWget(url, tempOutputFile, useragent, username, password, headers, timeoutSeconds, proxyUrl, allowInsecureSSL);
if (result.Success)
{
// Calculate duration
result.DurationMs = (DateTime.Now.Ticks - startTime) / 10000;
return result;
}
else
{
// Store the error for later reporting
finalResult.AllErrors[DownloadMethod.Wget] = result.ErrorMessage;
}
}
break;
case DownloadMethod.PowerShell:
result = DownloadWithPowerShell(url, tempOutputFile, useragent, username, password, headers, timeoutSeconds, proxyUrl, allowInsecureSSL);
if (result.Success)
{
// Calculate duration
result.DurationMs = (DateTime.Now.Ticks - startTime) / 10000;
return result;
}
else
{
// Store the error for later reporting
finalResult.AllErrors[DownloadMethod.PowerShell] = result.ErrorMessage;
}
break;
}
}
// If we get here, all methods failed
StringBuilder errorMsg = new StringBuilder("All download methods failed for URL: " + url);
// Add detailed errors from each method that was tried
if (finalResult.AllErrors.Count > 0)
{
errorMsg.AppendLine();
errorMsg.AppendLine("Detailed errors by method:");
foreach (KeyValuePair<DownloadMethod, string> err in finalResult.AllErrors)
{
errorMsg.AppendLine("- " + err.Key.ToString() + ": " + err.Value);
}
}
return DownloadResult.CreateFailure(errorMsg.ToString(), method, 0, (DateTime.Now.Ticks - startTime) / 10000);
}
/// <summary>
/// Downloads a string from a URL using the best available method.
/// This is a simplified version of Download that returns just the string content.
/// NOTE: When capturing content directly from command-line tools, the text encoding
/// depends on the console output encoding. Use DownloadStringWithEncoding for
/// explicit encoding control.
/// </summary>
/// <param name="url">The URL to download from.</param>
/// <param name="method">The primary download method to use.</param>
/// <param name="defaultValue">Default value to return if download fails.</param>
/// <param name="useragent">The User-Agent header value.</param>
/// <returns>The downloaded string or defaultValue if download failed.</returns>
public static string DownloadString(
string url,
DownloadMethod method = DownloadMethod.Auto,
string defaultValue = "",
string useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0")
{
DownloadResult result = Download(url, method, true, useragent);
if (result.Success)
{
return result.Content;
}
else
{
Debug.Print("DownloadString failed: " + result.ErrorMessage);
return defaultValue;
}
}
/// <summary>
/// Downloads content from a URL using curl.
/// </summary>
/// <returns>A DownloadResult object containing the result of the operation.</returns>
private static DownloadResult DownloadWithCurl(
string url,
string outputFile,
string useragent,
string username,
string password,
Dictionary<string, string> headers,
int timeoutSeconds,
string proxyUrl,
bool allowInsecureSSL)
{
StringBuilder stdOutput = new StringBuilder();
StringBuilder stdError = new StringBuilder();
int statusCode = 0;
bool isSavingToFile = !string.IsNullOrEmpty(outputFile);
try
{
// Create process start info
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "curl.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
// Build arguments
StringBuilder args = new StringBuilder();
// Basic curl options
args.Append("-s -L "); // -s: silent, -L: follow redirects
// Add write-out option to get status code
args.Append("-w \"%{http_code}\" ");
// Add insecure SSL flag only if explicitly allowed
if (allowInsecureSSL)
{
args.Append("-k "); // -k: insecure, allows connections to SSL sites without certificates
Debug.Print("WARNING: Using insecure SSL connections with curl");
}
// User agent
args.Append("-A \"").Append(useragent).Append("\" ");
// Authentication
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
args.Append("--user ").Append(username).Append(":").Append(password).Append(" ");
}
// Proxy
if (!string.IsNullOrEmpty(proxyUrl))
{
args.Append("--proxy ").Append(proxyUrl).Append(" ");
}
// Headers
if (headers != null && headers.Count > 0)
{
foreach (KeyValuePair<string, string> header in headers)
{
args.Append("-H \"").Append(header.Key).Append(": ").Append(header.Value).Append("\" ");
}
}
// Timeout - add both connect timeout and maximum operation time
args.Append("--connect-timeout ").Append(timeoutSeconds).Append(" ");
args.Append("--max-time ").Append(timeoutSeconds).Append(" ");
// URL
args.Append("\"").Append(url).Append("\" ");
// Output file if specified
if (isSavingToFile)
{
args.Append("-o \"").Append(outputFile).Append("\" ");
}
startInfo.Arguments = args.ToString();
// Execute curl with proper stream handling
using (Process process = new Process())
{
process.StartInfo = startInfo;
// Set up output and error handling
AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
AutoResetEvent errorWaitHandle = new AutoResetEvent(false);
process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
// The last line should be the status code when using -w "%{http_code}"
int parsedStatusCode;
if (int.TryParse(e.Data.Trim(), out parsedStatusCode))
{
// This is the status code, don't add to content
statusCode = parsedStatusCode;
}
else
{
stdOutput.AppendLine(e.Data);
}
}
else
{
outputWaitHandle.Set();
}
};
process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
stdError.AppendLine(e.Data);
}
else
{
errorWaitHandle.Set();
}
};
// Start the process
process.Start();
// Begin reading stdout and stderr asynchronously
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// Wait for the process to exit
if (process.WaitForExit(timeoutSeconds * 1000))
{
// Wait for async reads to complete
outputWaitHandle.WaitOne(1000);
errorWaitHandle.WaitOne(1000);
// Check result
int exitCode = process.ExitCode;
string errorText = stdError.ToString().Trim();
if (exitCode == 0)
{
// Set default status code if we couldn't parse it
if (statusCode == 0) statusCode = 200;
// Check if HTTP status indicates success (2xx)
if (statusCode >= 200 && statusCode < 300)
{
// Success
if (isSavingToFile)
{
// Check if file exists and has content
if (File.Exists(outputFile) && new FileInfo(outputFile).Length > 0)
{
return DownloadResult.CreateSuccess(DownloadMethod.Curl, "", null, outputFile, statusCode);
}
else
{
return DownloadResult.CreateFailure("Curl reported success but output file is empty or missing", DownloadMethod.Curl, statusCode);
}
}
else
{
// Return the content from stdout
string content = stdOutput.ToString();
if (!string.IsNullOrEmpty(content))
{
return DownloadResult.CreateSuccess(DownloadMethod.Curl, content, null, "", statusCode);
}
else
{
return DownloadResult.CreateFailure("Curl reported success but no content was returned", DownloadMethod.Curl, statusCode);
}
}
}
else
{
// HTTP error
return DownloadResult.CreateFailure("HTTP error: " + statusCode, DownloadMethod.Curl, statusCode);
}
}
else
{
// Process error
string msg = "Curl process exited with code: " + exitCode;
if (!string.IsNullOrEmpty(errorText))
{
msg += Environment.NewLine + "Curl error: " + errorText;
}
return DownloadResult.CreateFailure(msg, DownloadMethod.Curl, statusCode);
}
}
else
{
// Process timed out
try
{
if (!process.HasExited)
{
process.Kill();
}
}
catch (Exception)
{
// Ignore errors killing the process
}
return DownloadResult.CreateFailure("Curl process timed out after " + timeoutSeconds + " seconds", DownloadMethod.Curl);
}
}
}
catch (Exception ex)
{
return DownloadResult.CreateFailure("Curl execution error: " + ex.Message, DownloadMethod.Curl);
}
}
/// <summary>
/// Downloads content from a URL using wget.
/// </summary>
/// <returns>A DownloadResult object containing the result of the operation.</returns>
private static DownloadResult DownloadWithWget(
string url,
string outputFile,
string useragent,
string username,
string password,
Dictionary<string, string> headers,
int timeoutSeconds,
string proxyUrl,
bool allowInsecureSSL)
{
StringBuilder stdOutput = new StringBuilder();
StringBuilder stdError = new StringBuilder();
bool isSavingToFile = !string.IsNullOrEmpty(outputFile);
string tempOutputFile = isSavingToFile ? outputFile : Path.GetTempFileName();
int statusCode = 0;
try
{
// Create process start info
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "wget.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
// Set proxy environment variables if specified
if (!string.IsNullOrEmpty(proxyUrl))
{
startInfo.EnvironmentVariables["http_proxy"] = proxyUrl;
startInfo.EnvironmentVariables["https_proxy"] = proxyUrl;
}
// Build arguments
StringBuilder args = new StringBuilder();
// Basic wget options - quiet mode but show server response
args.Append("-q -S "); // -q: quiet, -S: show server response in stderr
// Add insecure SSL flag only if explicitly allowed
if (allowInsecureSSL)
{
args.Append("--no-check-certificate ");
Debug.Print("WARNING: Using insecure SSL connections with wget");
}
// User agent
args.Append("--user-agent=\"").Append(useragent).Append("\" ");
// Authentication
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
args.Append("--http-user=").Append(username).Append(" ");
args.Append("--http-password=").Append(password).Append(" ");
}
// Headers
if (headers != null && headers.Count > 0)
{
foreach (KeyValuePair<string, string> header in headers)
{
args.Append("--header=\"").Append(header.Key).Append(": ").Append(header.Value).Append("\" ");
}
}
// Timeout
args.Append("-T ").Append(timeoutSeconds).Append(" ");
// Output to stdout if not saving to file
if (!isSavingToFile)
{
args.Append("-O - "); // Output to stdout
}
else
{
args.Append("-O \"").Append(tempOutputFile).Append("\" ");
}
// URL
args.Append("\"").Append(url).Append("\"");
startInfo.Arguments = args.ToString();
// Execute wget with proper stream handling
using (Process process = new Process())
{
process.StartInfo = startInfo;
// Set up output and error handling
AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
AutoResetEvent errorWaitHandle = new AutoResetEvent(false);
process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
stdOutput.AppendLine(e.Data);
}
else
{
outputWaitHandle.Set();
}
};
process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
// Try to extract the status code from server response
// Wget shows HTTP responses in stderr with -S flag
if (e.Data.Contains("HTTP/") && e.Data.Contains(" "))
{
try
{
string[] parts = e.Data.Trim().Split(' ');
if (parts.Length >= 2)
{
int.TryParse(parts[1], out statusCode);
}
}
catch
{
// Ignore parsing errors
}
}
stdError.AppendLine(e.Data);
}
else
{
errorWaitHandle.Set();
}
};
// Start the process
process.Start();
// Begin reading stdout and stderr asynchronously
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// Wait for the process to exit
if (process.WaitForExit(timeoutSeconds * 1000))
{
// Wait for async reads to complete
outputWaitHandle.WaitOne(1000);
errorWaitHandle.WaitOne(1000);
// Check result
int exitCode = process.ExitCode;
string errorText = stdError.ToString().Trim();
// Set default status code if we couldn't extract it
if (statusCode == 0 && exitCode == 0)
{
statusCode = 200; // Assume 200 OK if process succeeded
}
if (exitCode == 0)
{
// Success
if (isSavingToFile)
{
// Check if file exists and has content
if (File.Exists(tempOutputFile) && new FileInfo(tempOutputFile).Length > 0)
{
return DownloadResult.CreateSuccess(DownloadMethod.Wget, "", null, tempOutputFile, statusCode);
}
else
{
return DownloadResult.CreateFailure("Wget reported success but output file is empty or missing", DownloadMethod.Wget, statusCode);
}
}
else
{
// Return the content from stdout
string content = stdOutput.ToString();
// Clean up temporary file
try
{
if (File.Exists(tempOutputFile))
{
File.Delete(tempOutputFile);
}
}
catch (Exception)
{
// Ignore temp file cleanup errors
}
if (!string.IsNullOrEmpty(content))
{
return DownloadResult.CreateSuccess(DownloadMethod.Wget, content, null, "", statusCode);
}
else
{
return DownloadResult.CreateFailure("Wget reported success but no content was returned", DownloadMethod.Wget, statusCode);
}
}
}
else
{
// Failure
// Clean up temporary file if we created one
if (!isSavingToFile)
{
try
{
if (File.Exists(tempOutputFile))
{
File.Delete(tempOutputFile);
}
}
catch (Exception)
{
// Ignore temp file cleanup errors
}
}
string msg = "Wget process exited with code: " + exitCode;
if (!string.IsNullOrEmpty(errorText))
{
msg += Environment.NewLine + "Wget error: " + errorText;
}
return DownloadResult.CreateFailure(msg, DownloadMethod.Wget, statusCode);
}
}
else
{
// Process timed out
try
{
if (!process.HasExited)
{
process.Kill();
}
}
catch (Exception)
{
// Ignore errors killing the process
}
// Clean up temporary file if we created one
if (!isSavingToFile)
{
try
{
if (File.Exists(tempOutputFile))
{
File.Delete(tempOutputFile);
}
}
catch (Exception)
{
// Ignore temp file cleanup errors
}
}
return DownloadResult.CreateFailure("Wget process timed out after " + timeoutSeconds + " seconds", DownloadMethod.Wget);
}
}
}
catch (Exception ex)
{
// Clean up temporary file if we created one
if (!isSavingToFile)
{
try
{
if (File.Exists(tempOutputFile))
{
File.Delete(tempOutputFile);
}
}
catch
{
// Ignore temp file cleanup errors
}
}
return DownloadResult.CreateFailure("Wget execution error: " + ex.Message, DownloadMethod.Wget);
}
}
/// <summary>
/// Downloads content from a URL using PowerShell.
/// </summary>
/// <returns>A DownloadResult object containing the result of the operation.</returns>
private static DownloadResult DownloadWithPowerShell(
string url,
string outputFile,
string useragent,
string username,
string password,
Dictionary<string, string> headers,
int timeoutSeconds,
string proxyUrl,
bool allowInsecureSSL)
{
bool isSavingToFile = !string.IsNullOrEmpty(outputFile);
string tempOutputFile = isSavingToFile ? outputFile : Path.GetTempFileName();
string scriptFile = Path.GetTempFileName() + ".ps1";
try
{
// Build PowerShell script content
StringBuilder script = new StringBuilder();
// Set security protocol to support multiple TLS versions
script.AppendLine("[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls");
// Skip certificate validation if requested (INSECURE)
if (allowInsecureSSL)
{
script.AppendLine("Add-Type @'");
script.AppendLine("using System.Net;");
script.AppendLine("using System.Security.Cryptography.X509Certificates;");
script.AppendLine("public class TrustAllCertsPolicy : ICertificatePolicy {");
script.AppendLine(" public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) {");
script.AppendLine(" return true;");
script.AppendLine(" }");
script.AppendLine("}");
script.AppendLine("'@");
script.AppendLine("[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy");
Debug.Print("WARNING: Using insecure SSL connections with PowerShell");
}
// Use Invoke-WebRequest for better status code reporting
script.AppendLine("try {");
script.AppendLine(" $params = @{");
script.AppendLine(" Uri = '" + url.Replace("'", "''") + "'");
script.AppendLine(" UseBasicParsing = $true");
script.AppendLine(" TimeoutSec = " + timeoutSeconds);
script.AppendLine(" UserAgent = '" + useragent.Replace("'", "''") + "'");
// Add headers
if (headers != null && headers.Count > 0)
{
script.AppendLine(" Headers = @{");
bool isFirst = true;
foreach (KeyValuePair<string, string> header in headers)
{
if (!isFirst) script.AppendLine(";");
script.Append(" '" + header.Key.Replace("'", "''") + "' = '" + header.Value.Replace("'", "''") + "'");
isFirst = false;
}
script.AppendLine("");
script.AppendLine(" }");
}
// Add credentials
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
script.AppendLine(" Credential = (New-Object System.Management.Automation.PSCredential('" + username.Replace("'", "''") + "', (ConvertTo-SecureString -String '" + password.Replace("'", "''") + "' -AsPlainText -Force)))");
}
// Add proxy
if (!string.IsNullOrEmpty(proxyUrl))
{
script.AppendLine(" Proxy = '" + proxyUrl.Replace("'", "''") + "'");
}
script.AppendLine(" }");
script.AppendLine(" $response = Invoke-WebRequest @params");
// Output status code on first line, content follows
script.AppendLine(" Write-Output ('STATUS_CODE:' + $response.StatusCode)");
// Save content
if (isSavingToFile)
{
script.AppendLine(" $response.Content | Set-Content -Path '" + tempOutputFile.Replace("'", "''") + "' -Encoding Byte");
script.AppendLine(" if (Test-Path '" + tempOutputFile.Replace("'", "''") + "') { Write-Output 'Download completed successfully' }");
script.AppendLine(" else { throw 'File was not created' }");
}
else
{
script.AppendLine(" $response.Content"); // Output content to stdout
}
script.AppendLine("} catch {");
script.AppendLine(" if ($_.Exception.Response -ne $null) {");
script.AppendLine(" Write-Output ('STATUS_CODE:' + [int]$_.Exception.Response.StatusCode)");
script.AppendLine(" }");
script.AppendLine(" Write-Error $_.Exception.Message");
script.AppendLine(" exit 1");
script.AppendLine("}");
// Write script to file
File.WriteAllText(scriptFile, script.ToString());
// Create process start info for PowerShell
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "powershell.exe";
startInfo.Arguments = "-ExecutionPolicy Bypass -File \"" + scriptFile + "\"";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
// Execute PowerShell script
StringBuilder stdOutput = new StringBuilder();
StringBuilder stdError = new StringBuilder();
int statusCode = 0;
using (Process process = new Process())
{
process.StartInfo = startInfo;
// Set up output and error handling
AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
AutoResetEvent errorWaitHandle = new AutoResetEvent(false);
process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
// Check for status code output
if (e.Data.StartsWith("STATUS_CODE:"))
{
try
{
statusCode = int.Parse(e.Data.Substring("STATUS_CODE:".Length));
}
catch
{
// Ignore parsing errors
}
}
else
{
stdOutput.AppendLine(e.Data);
}