-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
3967 lines (3289 loc) · 133 KB
/
Program.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
//#define kill_msi_after_exec
//#define TOPMOST
using CommandLine;
using IWshRuntimeLibrary;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace PoolWatcher
{
public static class Extensions
{
public static string Filter(this string str, List<char> charsToRemove)
{
foreach (char c in charsToRemove)
{
str = str.Replace(c.ToString(), String.Empty);
}
return str;
}
public static string Filter(this string str, List<string> stringsToRemove)
{
foreach (string s in stringsToRemove)
{
str = str.Replace(s, String.Empty);
}
return str;
}
}
public static class ConsoleWindow
{
public static class NativeFunctions
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int uFlags);
public enum StdHandle : int
{
STD_INPUT_HANDLE = -10,
STD_OUTPUT_HANDLE = -11,
STD_ERROR_HANDLE = -12,
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle); //returns Handle
public enum ConsoleMode : uint
{
ENABLE_ECHO_INPUT = 0x0004,
ENABLE_EXTENDED_FLAGS = 0x0080,
ENABLE_INSERT_MODE = 0x0020,
ENABLE_LINE_INPUT = 0x0002,
ENABLE_MOUSE_INPUT = 0x0010,
ENABLE_PROCESSED_INPUT = 0x0001,
ENABLE_QUICK_EDIT_MODE = 0x0040,
ENABLE_WINDOW_INPUT = 0x0008,
ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200,
//screen buffer handle
ENABLE_PROCESSED_OUTPUT = 0x0001,
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002,
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004,
DISABLE_NEWLINE_AUTO_RETURN = 0x0008,
ENABLE_LVB_GRID_WORLDWIDE = 0x0010
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
}
public static void QuickEditMode(bool Enable)
{
//QuickEdit lets the user select text in the console window with the mouse, to copy to the windows clipboard.
//But selecting text stops the console process (e.g. unzipping). This may not be always wanted.
IntPtr consoleHandle = NativeFunctions.GetStdHandle((int)NativeFunctions.StdHandle.STD_INPUT_HANDLE);
UInt32 consoleMode;
NativeFunctions.GetConsoleMode(consoleHandle, out consoleMode);
if (Enable)
consoleMode |= ((uint)NativeFunctions.ConsoleMode.ENABLE_QUICK_EDIT_MODE);
else
consoleMode &= ~((uint)NativeFunctions.ConsoleMode.ENABLE_QUICK_EDIT_MODE);
consoleMode |= ((uint)NativeFunctions.ConsoleMode.ENABLE_EXTENDED_FLAGS);
NativeFunctions.SetConsoleMode(consoleHandle, consoleMode);
}
}
class Options
{
public const int default_wait_timeout_value = 360;
public const int default_share_wait_timeout_value = 1200;
public const int default_sleep_timeout = 90000;
[Option('k', "kill_pill", Default = 0, Required = false)]
public int kill_pill { get; set; }
[Option('w', "without_external_windows", Default = 1, Required = false)]
public int without_external_windows { get; set; }
[Option('s', "with_antiwatchdog", Default = 1, Required = false)]
public int with_antiwatchdog { get; set; }
[Option('o', "direct_order", Default = 1, Required = false)]
public int direct_order { get; set; }
[Option('e', "exit_after_miner_fail", Default = 1, Required = false)]
public int exit_after_miner_fail { get; set; }
[Option('d', "use_dummy_miner", Default = 0, Required = false)]
public int use_dummy_miner { get; set; }
[Option('p', "wait_timeout", Default = default_wait_timeout_value, Required = false)]
public int wait_timeout { get; set; }
[Option('q', "share_wait_timeout", Default = default_share_wait_timeout_value, Required = false)]
public int share_wait_timeout { get; set; }
[Option('i', "ignore_no_active_pools_message", Default = 1, Required = false)]
public int ignore_no_active_pools_message { get; set; }
[Option('v', "ban_timeout", Default = 30, Required = false)]
public int ban_timeout { get; set; }
[Option('h', "hide_miner_messages", Default = 0, Required = false)]
public int hide_miner_messages { get; set; }
[Option('m', "ban_or_restart_no_shares_event", Default = 1, Required = false)]
public int ban_or_restart_no_shares_event { get; set; }
}
[SecurityCritical]
public static class ProcessHelpers
{
public static bool IsRunning(string name) => Process.GetProcessesByName(name).Length > 0;
}
[SecurityCritical]
public static class ArrayExtensions
{
public static int IndexOf<T>(this T[] array, T value)
{
return Array.IndexOf(array, value);
}
}
[SecurityCritical]
public static class Program
{
static readonly int sleep_default_timeout = 500; // базовая единица ожидания
static volatile Object _lockObj = new Object();
// Основная монета
static readonly string defaultPool = "vds.666pool.cn";
static readonly int defaultPort = 9338;
static readonly string default_dummy_params = "--algo vds --server " + defaultPool + " --port " + defaultPort + " --user [email protected] --pass x --pec 0 --watchdog 0";
/// <summary>
/// Converts a wmi date into a proper date
/// </summary>
/// <param jobName="wmiDate">Wmi formatted date</param>
/// <returns>Date time object</returns>
private static bool ConvertFromWmiDate(string wmiDate, out DateTime properDate)
{
properDate = DateTime.MinValue;
string properDateString;
if (String.IsNullOrEmpty(wmiDate)) return false;
wmiDate = wmiDate.Trim().ToLower(CultureInfo.CurrentCulture).Replace("*", "0");
string[] months = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
try
{
properDateString = String.Format(null, "{0}-{1}-{2} {3}:{4}:{5}.{6}",
wmiDate.Substring(6, 2),
months[int.Parse(wmiDate.Substring(4, 2), null) - 1],
wmiDate.Substring(0, 4),
wmiDate.Substring(8, 2),
wmiDate.Substring(10, 2),
wmiDate.Substring(12, 2),
wmiDate.Substring(15, 6));
}
catch (InvalidCastException) { return false; }
catch (ArgumentOutOfRangeException) { return false; }
if (!DateTime.TryParse(properDateString, out properDate)) return false;
return true;
}
static UInt64 masterMinerProcessCounter, slave0MinerProcessCounter, slave1MinerProcessCounter;
[DllImport("kernel32.dll")]
static extern ErrorModes SetErrorMode(ErrorModes uMode);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetThreadErrorMode(ErrorModes dwNewMode, out ErrorModes lpOldMode);
[DllImport("wer.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int WerAddExcludedApplication(String pwzExeName, bool bAllUsers);
[Flags]
enum ErrorModes : uint
{
SYSTEM_DEFAULT = 0x0,
SEM_FAILCRITICALERRORS = 0x0001,
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
SEM_NOGPFAULTERRORBOX = 0x0002,
SEM_NOOPENFILEERRORBOX = 0x8000,
SEM_NONE = SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[Flags]
enum CreateProcessFlags : uint
{
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
NORMAL_PRIORITY_CLASS = 0x00000020,
IDLE_PRIORITY_CLASS = 0x00000040,
HIGH_PRIORITY_CLASS = 0x00000080,
REALTIME_PRIORITY_CLASS = 0x00000100,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_FORCEDOS = 0x00002000,
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,
INHERIT_PARENT_AFFINITY = 0x00010000,
INHERIT_CALLER_PRIORITY = 0x00020000,
CREATE_PROTECTED_PROCESS = 0x00040000,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000,
PROCESS_MODE_BACKGROUND_END = 0x00200000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
PROFILE_USER = 0x10000000,
PROFILE_KERNEL = 0x20000000,
PROFILE_SERVER = 0x40000000,
CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000,
}
[DllImport("kernel32.dll")]
static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetHandleInformation(IntPtr hObject, HANDLE_FLAGS dwMask, HANDLE_FLAGS dwFlags);
[Flags]
enum HANDLE_FLAGS : uint
{
None = 0,
INHERIT = 1,
PROTECT_FROM_CLOSE = 2
}
/// <summary>
/// Determines whether certain StartUpInfo members are used when the process creates a window.
/// </summary>
[FlagsAttribute]
enum StartUpInfoFlags : uint
{
/// <summary>
/// If this value is not specified, the wShowWindow member is ignored.
/// </summary>
UseShowWindow = 0x0000001,
/// <summary>
/// If this value is not specified, the dwXSize and dwYSize members are ignored.
/// </summary>
UseSize = 0x00000002,
/// <summary>
/// If this value is not specified, the dwX and dwY members are ignored.
/// </summary>
UsePosition = 0x00000004,
/// <summary>
/// If this value is not specified, the dwXCountChars and dwYCountChars members are ignored.
/// </summary>
UseCountChars = 0x00000008,
/// <summary>
/// If this value is not specified, the dwFillAttribute member is ignored.
/// </summary>
UseFillAttribute = 0x00000010,
/// <summary>
/// Indicates that the process should be run in full-screen mode, rather than in windowed mode.
/// </summary>
RunFullScreen = 0x00000020,
/// <summary>
/// Indicates that the cursor is in feedback mode after CreateProcess is called. The system turns the feedback cursor off after the first call to GetMessage.
/// </summary>
ForceOnFeedback = 0x00000040,
/// <summary>
/// Indicates that the feedback cursor is forced off while the process is starting. The Normal Select cursor is displayed.
/// </summary>
ForceOffFeedback = 0x00000080,
/// <summary>
/// Sets the standard input, standard output, and standard error handles for the process to the handles specified in the hStdInput, hStdOutput, and hStdError members of the StartUpInfo structure. If this value is not specified, the hStdInput, hStdOutput, and hStdError members of the STARTUPINFO structure are ignored.
/// </summary>
UseStandardHandles = 0x00000100,
/// <summary>
/// When this flag is specified, the hStdInput member is to be used as the hotkey value instead of the standard-input pipe.
/// </summary>
UseHotKey = 0x00000200,
/// <summary>
/// When this flag is specified, the StartUpInfo's hStdOutput member is used to specify a handle to a monitor, on which to start the new process. This monitor handle can be obtained by any of the multiple-monitor display functions (i.e. EnumDisplayMonitors, MonitorFromPoint, MonitorFromWindow, etc...).
/// </summary>
UseMonitor = 0x00000400,
/// <summary>
/// Use the HICON specified in the hStdOutput member (incompatible with UseMonitor).
/// </summary>
UseIcon = 0x00000400,
/// <summary>
/// Program was started through a shortcut. The lpTitle contains the shortcut path.
/// </summary>
TitleShortcut = 0x00000800,
/// <summary>
/// The process starts with normal priority. After the first call to GetMessage, the priority is lowered to idle.
/// </summary>
Screensaver = 0x08000000
}
[StructLayout(LayoutKind.Sequential)]
struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
[Flags]
enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
[DllImport("user32.dll")]
static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);
const int MF_BYPOSITION = 0x400;
[DllImport("User32")]
private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("User32")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("User32")]
private static extern int GetMenuItemCount(IntPtr hWnd);
[DllImport("kernel32.dll", ExactSpelling = true)]
static extern IntPtr GetConsoleWindow();
enum ProcessVariant
{
Master,
Slave0,
Slave1
}
[HandleProcessCorruptedStateExceptions, SecurityCritical]
static void CallProcess(bool isBatFile, string commandLine, string workingDirectory, CreateProcessFlags creationFlags, ProcessVariant pvar, bool redirect_input)
{
try
{
SafeFileHandle shStdOutRead = null, shStdErrRead = null;
SafeFileHandle shStdInWrite = null;
StreamReader readerStdOut = null, readerStdErr = null;
StreamWriter writerStdIn = null;
var hToken = WindowsIdentity.GetCurrent().Token;
if (hToken == IntPtr.Zero)
{
if (Program.ru_lang)
throw new InvalidOperationException("Токен аутентификации не был установлен с LogonUser");
else
throw new InvalidOperationException("Authentication Token has not been set with LogonUser");
}
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = IntPtr.Zero;
sa.bInheritHandle = 1;
STARTUPINFO startupInfo = new STARTUPINFO();
{
startupInfo.cb = Marshal.SizeOf(startupInfo);
if (options.without_external_windows == 1)
{
bool success;
// OUT
success = CreatePipe(out IntPtr hHandle, out IntPtr hChildHandle, ref sa, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
startupInfo.hStdOutput = hChildHandle;
success = SetHandleInformation(hHandle, HANDLE_FLAGS.INHERIT, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
shStdOutRead = new SafeFileHandle(hHandle, true);
FileStream fs = new FileStream(shStdOutRead, FileAccess.Read);
readerStdOut = new StreamReader(fs);
// ERR
success = CreatePipe(out hHandle, out hChildHandle, ref sa, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
startupInfo.hStdError = hChildHandle;
success = SetHandleInformation(hHandle, HANDLE_FLAGS.INHERIT, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
shStdErrRead = new SafeFileHandle(hHandle, true);
fs = new FileStream(shStdErrRead, FileAccess.Read);
readerStdErr = new StreamReader(fs);
if (redirect_input)
{
// IN
success = CreatePipe(out hChildHandle, out hHandle, ref sa, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
startupInfo.hStdInput = hChildHandle;
success = SetHandleInformation(hHandle, HANDLE_FLAGS.INHERIT, 0);
if (!success) throw new System.ComponentModel.Win32Exception();
shStdInWrite = new SafeFileHandle(hHandle, true);
fs = new FileStream(shStdInWrite, FileAccess.Write);
writerStdIn = new StreamWriter(fs);
}
}
startupInfo.dwFlags = (int)StartUpInfoFlags.UseStandardHandles;
}
if (isBatFile)
{
if (Program.ru_lang)
Console.WriteLine("Запуск майнера должен быть выполнен не позднее чем через " + options.wait_timeout + ".000 секунд; если Ваш батник не сразу запускает процесс добычи, а Вы остановите батник тем или иным способом, то процесс прервется после соответствующего таймаута, не нервничайте, будьте счастливы");
else
Console.WriteLine("Miner launch must be completed no later than in " + options.wait_timeout + ".000 seconds; if Your bat-file does not immediately start the mining process, and You stop bat-file in one way or another, the process will be interrupted after a corresponding timeout, don't worry be happy");
}
DateTime dummyDate = DateTime.Now;
bool result = CreateProcessAsUser(hToken, null, commandLine, ref sa, ref sa, true, (uint)creationFlags, IntPtr.Zero, workingDirectory, ref startupInfo, out PROCESS_INFORMATION processInfo);
if (result == false) throw new System.ComponentModel.Win32Exception();
DateTime timeOfStart;
Process curr_process = null;
try
{
curr_process = Process.GetProcessById(processInfo.dwProcessId);
timeOfStart = curr_process.StartTime;
}
catch
{
timeOfStart = dummyDate;
}
switch (pvar)
{
case ProcessVariant.Master:
{
masterMinerProcessStartTime = timeOfStart;
break;
}
case ProcessVariant.Slave0:
{
slaveMinerProcess0StartTime = timeOfStart;
break;
}
case ProcessVariant.Slave1:
{
slaveMinerProcess1StartTime = timeOfStart;
break;
}
}
switch (pvar)
{
case ProcessVariant.Master:
{
masterMinerProcess = curr_process;
masterMinerProcessId = processInfo.dwProcessId;
break;
}
case ProcessVariant.Slave0:
{
slaveMinerProcess0 = curr_process;
slaveMinerProcess0Id = processInfo.dwProcessId;
break;
}
case ProcessVariant.Slave1:
{
slaveMinerProcess1 = curr_process;
slaveMinerProcess1Id = processInfo.dwProcessId;
break;
}
}
// thread monitoring
{
if (options.without_external_windows == 1)
{
if (redirect_input) CloseHandle(startupInfo.hStdInput);
CloseHandle(startupInfo.hStdError);
CloseHandle(startupInfo.hStdOutput);
if (redirect_input)
{
//writerStdIn.WriteLine("dir");
writerStdIn.Close();
if (shStdInWrite.IsClosed == false)
shStdInWrite.Close();
}
}
Thread outThread = null;
Thread errThread = null;
if (options.without_external_windows == 1)
{
outThread = new Thread(() =>
{
DateTime thead_dt = DateTime.Now;
try
{
while (readerStdOut.BaseStream.CanRead)
{
string output = String.Empty;
Task<string> t = readerStdOut.ReadLineAsync();
bool global_break = false;
while (true)
{
DateTime dt = DateTime.Now;
switch (pvar)
{
case ProcessVariant.Master:
{
dt = masterMinerProcessStartTime;
break;
}
case ProcessVariant.Slave0:
{
dt = slaveMinerProcess0StartTime;
break;
}
case ProcessVariant.Slave1:
{
dt = slaveMinerProcess1StartTime;
break;
}
}
bool t_wait_result = false;
for (int i = 0; i < 100; i++)
{
t_wait_result = t.Wait(3000);
if ((dt - thead_dt).TotalMilliseconds > 2500)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("OUT Exit 0");
break;
}
else if (curr_process == null)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("OUT Exit 1");
break;
}
else
{
try
{
if (curr_process.HasExited)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("OUT Exit 2");
break;
}
}
catch
{
t_wait_result = false;
global_break = true;
Console.WriteLine("OUT Exit 3");
break;
}
}
if (t_wait_result == true) break;
}
if (global_break) break;
if (t_wait_result)
{
output = t.Result;
if (!String.IsNullOrEmpty(output))
{
lock (lobj)
{
ParseMessage(curr_process, output);
break;
}
}
else
{
Thread.Sleep(1000);
}
}
else
{
lock (lobj)
{
if (Program.ru_lang)
Console.WriteLine("Контроль OUT-потока майнера продолжается");
else
Console.WriteLine("OUT-thread control online");
}
}
}
if (global_break)
{
lock (lobj)
{
if (Program.ru_lang)
Console.WriteLine("Контроль OUT-потока майнера завершен");
else
Console.WriteLine("OUT-thread control finished");
}
break;
}
}
readerStdOut.Close();
if (shStdOutRead.IsClosed == false)
{
shStdOutRead.Close();
}
}
catch (Exception ex)
{
lock (lobj)
{
Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
if (Program.ru_lang)
Console.WriteLine("Убиваем зависший процесс");
else
Console.WriteLine("Kill hung process");
}
criticalEvent(curr_process);
}
});
errThread = new Thread(() =>
{
DateTime thead_dt = DateTime.Now;
try
{
while (readerStdErr.BaseStream.CanRead)
{
string output = String.Empty;
Task<string> t = readerStdErr.ReadLineAsync();
bool global_break = false;
while (true)
{
DateTime dt = DateTime.Now;
switch (pvar)
{
case ProcessVariant.Master:
{
dt = masterMinerProcessStartTime;
break;
}
case ProcessVariant.Slave0:
{
dt = slaveMinerProcess0StartTime;
break;
}
case ProcessVariant.Slave1:
{
dt = slaveMinerProcess1StartTime;
break;
}
}
bool t_wait_result = false;
for (int i = 0; i < 100; i++)
{
t_wait_result = t.Wait(3000);
if ((dt - thead_dt).TotalMilliseconds > 2500)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("ERR Exit 0");
break;
}
else if (curr_process == null)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("ERR Exit 1");
break;
}
else
{
try
{
if (curr_process.HasExited)
{
t_wait_result = false;
global_break = true;
Console.WriteLine("ERR Exit 2");
break;
}
}
catch
{
t_wait_result = false;
global_break = true;
Console.WriteLine("ERR Exit 3");
break;
}
}
if (t_wait_result == true) break;
}
if (global_break) break;
if (t_wait_result)
{
output = t.Result;
if (!String.IsNullOrEmpty(output))
{
lock (lobj)
{
ParseMessage(curr_process, output);
break;
}
}
else
{
Thread.Sleep(1000);
}
}
else
{
lock (lobj)
{
if (Program.ru_lang)
Console.WriteLine("Контроль CERR-потока майнера продолжается");
else
Console.WriteLine("CERR-thread control online");
}
}
}
if (global_break)
{
lock (lobj)
{
if (Program.ru_lang)
Console.WriteLine("Контроль CERR-потока майнера завершен");
else
Console.WriteLine("CERR-thread control finished");
}
break;
}
}
readerStdErr.Close();
if (shStdErrRead.IsClosed == false)
shStdErrRead.Close();
}
catch (Exception ex)
{
lock (lobj)
{
Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
if (Program.ru_lang)
Console.WriteLine("Убиваем зависший процесс");
else
Console.WriteLine("Kill hung process");
}
criticalEvent(curr_process);
}
});
}
Thread asyncThread = null;
if (isBatFile)
{
asyncThread = new Thread(() =>
{
List<DateTime> catched_childrens_of_miners_first_seen = new List<DateTime>();
List<DateTime> catched_childrens_of_miners_last_update = new List<DateTime>();
List<int> catched_miners = new List<int>();
List<DateTime> catched_miners_start_datetime = new List<DateTime>();
List<List<int>> childrens_of_catched_miners = new List<List<int>>();
bool fastThreadExit = false;
DateTime dt_now = DateTime.Now;
while (true)
{
if (options.without_external_windows == 1 && outThread.IsAlive == false && errThread.IsAlive == false)
{
fastThreadExit = true;
break;
}
else
{
UInt32 minersProcessesCounter = 0;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"SELECT * " +
"FROM Win32_Process " +
"WHERE ParentProcessId=" + processInfo.dwProcessId);
ManagementObjectCollection collection = searcher.Get();
if (collection.Count > 0)
{
foreach (var item in collection)
{
if (ConvertFromWmiDate((string)item["CreationDate"], out DateTime createDate))
{
if (DateTime.Compare(timeOfStart, createDate) <= 0)
{
try
{
string ProcessName = Path.GetFileNameWithoutExtension((string)item["Name"]);
if (ProcessName != "OhGodAnETHlargementPill-r2" && ProcessName != "sleep" && ProcessName != "timeout" && ProcessName != "conhost" && ProcessName != "MSIAfterburner" && ProcessName != "curl" && ProcessName != "tasklist" && ProcessName != "find" && ProcessName != "powershell" && ProcessName != "start" && ProcessName != "cd" && ProcessName != "taskkill")
{
if (minersProcessesCounter == 0)
{
if (Program.ru_lang)
Console.WriteLine(Environment.NewLine + "Выявлено начало добычи" + Environment.NewLine);
else
Console.WriteLine(Environment.NewLine + "Catched mining start" + Environment.NewLine);
if (mainThread_enabled)
{
lock (timeOfLatestAccepted_SyncObject)
{
timeOfLatestAccepted = (object)DateTime.Now;
acceptedTimeOut = (object)(options.share_wait_timeout + 360);
Console.WriteLine("Инициализировали слежение за шарами, первую шару ждем {0}.000 секунд; следующие шары на 360 секунд меньше", ((int)acceptedTimeOut).ToString());
}
}
}
UInt32 childProcessId = (UInt32)item["ProcessId"];
List<int> childrens = new List<int>();
ManagementObjectSearcher mos = new ManagementObjectSearcher(String.Format(null, "Select * From Win32_Process Where ParentProcessID={0}", childProcessId));
var mos_get = mos.Get();
DateTime first_seen = DateTime.Now;