-
Notifications
You must be signed in to change notification settings - Fork 8
/
Program.cs
1453 lines (1163 loc) · 53.6 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
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;
using Security.WinTrust;
using Squared.Task;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web.Script.Serialization;
using System.Data.SQLite;
using Squared.Task.Data;
using Squared.Util.Event;
using System.Security.Principal;
using System.Threading;
namespace ShootBlues {
public class PythonException : Exception {
public ProcessInfo Process;
public PythonException (ProcessInfo process, string traceback)
: base(traceback) {
Process = process;
}
}
public class ScriptName {
public readonly string Name;
public readonly string DefaultSearchPath;
private readonly string Invariant;
public ScriptName (string name) {
Name = name;
DefaultSearchPath = null;
Invariant = name.ToLowerInvariant();
}
public ScriptName (string name, string defaultSearchPath) {
Name = name;
DefaultSearchPath = defaultSearchPath;
Invariant = name.ToLowerInvariant();
}
public static implicit operator string (ScriptName name) {
if (name != null)
return name.Name;
else
return null;
}
public string NameWithoutExtension {
get {
return Path.GetFileNameWithoutExtension(Name);
}
}
public string Extension {
get {
return Path.GetExtension(Name).ToLower();
}
}
public override int GetHashCode () {
return Invariant.GetHashCode();
}
public override string ToString () {
return Name;
}
public override bool Equals (object obj) {
var sn = obj as ScriptName;
if (sn != null)
return Invariant.Equals(sn.Invariant);
else {
var fn = obj as Filename;
if (fn != null)
return Invariant.Equals(fn.Name.Invariant);
else {
var str = obj as String;
if (str != null)
return Invariant.Equals(str.ToLowerInvariant());
else
return base.Equals(obj);
}
}
}
}
public class Filename {
public readonly string FullPath;
private readonly string Invariant;
private Filename (string filename, bool resolved) {
if (!resolved) {
try {
FullPath = Path.GetFullPath(filename);
} catch {
FullPath = filename;
}
} else
FullPath = filename;
Invariant = FullPath.ToLowerInvariant();
}
public Filename (string filename)
: this(filename, false) {
}
public string Extension {
get {
return Path.GetExtension(FullPath).ToLower();
}
}
public string NameWithoutExtension {
get {
return Path.GetFileNameWithoutExtension(FullPath);
}
}
public ScriptName Name {
get {
return new ScriptName(
Path.GetFileName(FullPath),
Path.GetDirectoryName(FullPath)
);
}
}
public string Directory {
get {
return Path.GetDirectoryName(FullPath);
}
}
public static implicit operator Filename (string filename) {
return new Filename(filename, false);
}
public static implicit operator string (Filename filename) {
if (filename != null)
return filename.FullPath;
else
return null;
}
public override int GetHashCode () {
return Invariant.GetHashCode();
}
public override string ToString () {
return FullPath;
}
public override bool Equals (object obj) {
var fn = obj as Filename;
if (fn != null)
return Invariant.Equals(fn.Invariant);
else {
var str = obj as String;
if (str != null)
return Invariant.Equals(str.ToLowerInvariant());
else
return base.Equals(obj);
}
}
}
public struct PendingFunctionCall {
public readonly string ModuleName, FunctionName;
public readonly object[] Parameters;
public readonly IFuture ResultFuture;
}
public class ProcessInfo : IDisposable {
public Process Process = null;
public RPCChannel Channel = null;
public string Status = "Unknown";
public bool Ready = false;
internal HashSet<ScriptName> LoadedScripts = new HashSet<ScriptName>();
internal HashSet<string> LoadedPythonModules = new HashSet<string>();
internal List<Func<IFuture>> PendingFunctionCalls = new List<Func<IFuture>>();
public readonly OwnedFutureSet OwnedFutures = new OwnedFutureSet();
private Dictionary<string, RPCResponseChannel> NamedChannels = new Dictionary<string, RPCResponseChannel>();
public ProcessInfo (Process process) {
Process = process;
Channel = new RPCChannel(process);
}
public RPCResponseChannel GetNamedChannel (string name) {
RPCResponseChannel result;
if (!NamedChannels.TryGetValue(name, out result))
NamedChannels[name] = result = new RPCResponseChannel(Process);
return result;
}
public IFuture Start (ISchedulable schedulable) {
var f = Program.Scheduler.Start(
schedulable, TaskExecutionPolicy.RunAsBackgroundTask
);
OwnedFutures.Add(f);
return f;
}
public IFuture Start (IEnumerator<object> task) {
var f = Program.Scheduler.Start(
task, TaskExecutionPolicy.RunAsBackgroundTask
);
OwnedFutures.Add(f);
return f;
}
public void Dispose () {
OwnedFutures.Dispose();
foreach (var nc in NamedChannels.Values)
nc.Dispose();
NamedChannels.Clear();
Channel.Dispose();
Process.Dispose();
}
public override int GetHashCode () {
return Process.Id.GetHashCode();
}
public override string ToString () {
return String.Format("{0} - {1}", Process.Id, Status);
}
public bool IsAlive {
get {
try {
return !(Process.HasExited);
} catch {
return false;
}
}
}
public override bool Equals (object obj) {
var rhs = obj as ProcessInfo;
if (rhs != null) {
return Process.Id == rhs.Process.Id;
} else {
return base.Equals(obj);
}
}
}
public static class Program {
private static StatusWindow StatusWindowInstance = null;
private static ErrorDialog ErrorDialogInstance = null;
private static ContextMenuStrip TrayMenu = null;
private static Dictionary<ScriptName, SignalFuture> LoadingScripts = new Dictionary<ScriptName, SignalFuture>();
private static HashSet<string> AttachedDatabases = new HashSet<string>();
private static int ExitCode = 0;
internal static Dictionary<ScriptName, IManagedScript> LoadedScripts = new Dictionary<ScriptName, IManagedScript>();
public static readonly Dictionary<string, ScriptName> PythonModuleToScript = new Dictionary<string, ScriptName>();
public static readonly HashSet<ProcessInfo> RunningProcesses = new HashSet<ProcessInfo>();
public static readonly HashSet<Filename> Scripts = new HashSet<Filename>();
public static readonly HashSet<ScriptName> FailedScripts = new HashSet<ScriptName>();
public static readonly EventBus EventBus = new EventBus();
public static NotifyIcon TrayIcon;
public static IProfile Profile;
public static string ProfilePath;
public static TaskScheduler Scheduler;
public static ConnectionWrapper Database;
[STAThread]
private static void Main () {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool isFirstInstance = false;
var mutex = new Mutex(true, "Local\\ShootBlues", out isFirstInstance);
if (!isFirstInstance) {
mutex.Close();
MessageBox.Show("Shoot Blues is already running.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Environment.Exit(1);
}
using (mutex)
using (Scheduler = new TaskScheduler(JobQueue.WindowsMessageBased))
using (Database = new ConnectionWrapper(Scheduler, OpenDatabase(), true)) {
Scheduler.ErrorHandler = OnTaskError;
using (var fMainTask = Scheduler.Start(MainTask(), TaskExecutionPolicy.RunAsBackgroundTask)) {
fMainTask.RegisterOnComplete((_) => {
if (_.Failed) {
ExitCode = 1;
MessageBox.Show(_.Error.ToString(), "Shoot Blues Fatal Error");
Application.Exit();
}
});
Application.Run();
fMainTask.Dispose();
}
using (var fTeardownTask = Scheduler.Start(Teardown(), TaskExecutionPolicy.RunAsBackgroundTask))
Application.Run();
}
Environment.Exit(ExitCode);
}
public static string GetDataFolder () {
var dataFolder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"ShootBlues"
);
if (!Directory.Exists(dataFolder))
Directory.CreateDirectory(dataFolder);
return dataFolder;
}
private static SQLiteConnection OpenDatabase () {
var dataFolder = GetDataFolder();
var dbPath = Path.Combine(
dataFolder, "prefs.db"
);
var conn = new SQLiteConnection(String.Format("Data Source={0}", dbPath));
conn.Open();
return conn;
}
private static bool OnTaskError (Exception error) {
var pye = error as PythonException;
if (pye != null)
ShowErrorMessage(pye.Message, pye.Process);
else
ShowErrorMessage(error.ToString());
return true;
}
public static IEnumerable<ProcessInfo> GetProcessesRunningScript (IManagedScript script) {
foreach (var process in RunningProcesses) {
if (!process.Ready)
continue;
if (!process.LoadedScripts.Contains(script.Name))
continue;
foreach (var dep in script.Dependencies)
if (!process.LoadedScripts.Contains(dep))
continue;
yield return process;
}
}
public static void ShowErrorMessage (string text) {
ShowErrorMessage(text, (Process)null);
}
public static void ShowErrorMessage (string text, ProcessInfo process) {
ShowErrorMessage(text, process.Process);
}
public static void ShowErrorMessage (string text, Process process) {
string title = "Error in background task";
if (process != null)
title = String.Format("Error in process {0}", process.Id);
if (ErrorDialogInstance == null) {
ErrorDialogInstance = new ErrorDialog(Scheduler);
Scheduler.Start(ErrorDialogTask(), TaskExecutionPolicy.RunAsBackgroundTask);
}
ErrorDialogInstance.AddError(text, title);
}
private static IEnumerator<object> ErrorDialogTask () {
using (ErrorDialogInstance)
yield return ErrorDialogInstance.Show();
ErrorDialogInstance = null;
}
public static string GetStatusText () {
bool isAdmin = false;
try {
isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) ? true : false;
} catch {
}
string result;
if (Profile != null)
result = String.Format("Shoot Blues v{0} - {1}", Application.ProductVersion, Profile.ProfileName);
else
result = String.Format("Shoot Blues v{0}", Application.ProductVersion);
result += isAdmin ? " (Administrator)" : " (Limited User)";
return result;
}
private static IEnumerator<object> MainTask () {
// We need to enable the debug privilege for our process before doing anything
// because the System.Diagnostics.Process class attempts to open process handles
// even though it may not have rights to do so. The debug privilege ensures that
// opening handles will succeed.
Win32.AdjustProcessPrivilege(Process.GetCurrentProcess().Id, "SeDebugPrivilege", true);
TrayMenu = new ContextMenuStrip();
TrayMenu.AddItem("&Status", (s, e) => Scheduler.Start(ShowStatusWindow(), TaskExecutionPolicy.RunAsBackgroundTask));
TrayMenu.Items.Add("-");
TrayMenu.AddItem("E&xit", (s, e) => Application.Exit());
using (TrayMenu)
using (var loadingWindow = new LoadingWindow())
using (TrayIcon = new NotifyIcon {
Text = GetStatusText(),
Icon = Properties.Resources.icon,
ContextMenuStrip = TrayMenu
}) {
TrayIcon.Visible = true;
loadingWindow.SetStatus("Loading profile", null);
loadingWindow.Show();
yield return Database.ExecuteSQL("PRAGMA journal_mode = MEMORY");
yield return Database.ExecuteSQL("PRAGMA temp_store = MEMORY");
yield return Database.ExecuteSQL("PRAGMA synchronous = 0");
RunToCompletion<IProfile> loadProfile = new RunToCompletion<IProfile>(
LoadProfile(loadingWindow), TaskExecutionPolicy.RunAsBackgroundTask
);
yield return loadProfile;
using (Profile = loadProfile.Result)
try {
yield return CreateDBTable(
"scripts",
"( profileName TEXT NOT NULL, filename TEXT NOT NULL, PRIMARY KEY (profileName, filename) )"
);
yield return CreateDBTable(
"whitelistedScripts",
"( scriptHash TEXT NOT NULL PRIMARY KEY )"
);
string[] filenames = null;
yield return Database.ExecutePrimitiveArray<string>(
"SELECT filename FROM scripts WHERE profileName = ?",
Profile.ProfileName
).Bind(() => filenames);
foreach (var filename in filenames)
Scripts.Add(filename);
loadingWindow.Close();
EventBus.Subscribe(Profile, "OnScriptsAdded", Scheduler, OnScriptsChanging);
EventBus.Subscribe(Profile, "OnScriptRemoved", Scheduler, OnScriptsChanging);
TrayIcon.DoubleClick += (s, e) => Scheduler.Start(ShowStatusWindow(), TaskExecutionPolicy.RunAsBackgroundTask);
TrayIcon.Text = GetStatusText();
yield return OnScriptsChanging(null);
yield return Profile.Run();
} finally {
TrayIcon.Visible = false;
}
}
}
public static IEnumerator<object> Teardown () {
try {
Console.WriteLine("Shutting down...");
foreach (var process in RunningProcesses) {
Console.WriteLine("Unloading scripts from process {0}...", process.Process.Id);
foreach (var scriptName in process.LoadedScripts)
yield return LoadedScripts[scriptName].UnloadFrom(process);
yield return process.Channel.Send(new RPCMessage {
Type = RPCMessageType.ReloadModules
}, true);
process.LoadedScripts.Clear();
process.Dispose();
}
RunningProcesses.Clear();
Console.WriteLine("Destroying scripts...");
foreach (var script in LoadedScripts.Values)
script.Dispose();
LoadedScripts.Clear();
Console.WriteLine("Done shutting down.");
} finally {
Application.Exit();
}
}
public static IEnumerator<object> AttachDB (string dbName) {
var dbPath = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(Application.ExecutablePath),
dbName + ".db"
));
yield return AttachDB(dbPath, dbName);
}
public static IEnumerator<object> AttachDB (string dbPath, string dbName) {
if (AttachedDatabases.Contains(dbName))
yield break;
AttachedDatabases.Add(dbName);
yield return Database.ExecuteSQL(String.Format(
"ATTACH DATABASE '{0}' AS {1}", dbPath.Replace("'", "''"), dbName
));
}
public static IEnumerator<object> DefaultTableConverter (string oldTableName, string newTableName, string oldTableSql, string newTableSql) {
string sql;
string[] oldColumnNames = null, newColumnNames = null;
using (var q = Database.BuildQuery(String.Format("SELECT * FROM {0} LIMIT 0", oldTableName)))
yield return q.GetColumnNames().Bind(() => oldColumnNames);
using (var q = Database.BuildQuery(String.Format("SELECT * FROM {0} LIMIT 0", newTableName)))
yield return q.GetColumnNames().Bind(() => newColumnNames);
var sharedColumns = new HashSet<string>(oldColumnNames);
sharedColumns.IntersectWith(newColumnNames);
using (var q = Database.BuildQuery(String.Format("SELECT {1} FROM {0}", oldTableName, string.Join(", ", sharedColumns.ToArray())))) {
var fReader = q.ExecuteReader();
yield return fReader;
using (fReader.Result) {
var reader = fReader.Result.Reader;
int numColumns = reader.FieldCount;
var columnNames = new string[numColumns];
for (int i = 0; i < numColumns; i++)
columnNames[i] = reader.GetName(i);
sql = String.Format(
"INSERT INTO {0} ({2}) SELECT {2} FROM {1}", newTableName, oldTableName, String.Join(", ", sharedColumns.ToArray())
);
}
}
yield return Database.ExecuteSQL(sql);
}
public static IEnumerator<object> CreateDBTable (string tableName, string tableDef) {
return CreateDBTable(tableName, tableDef, DefaultTableConverter);
}
public static IEnumerator<object> CreateDBTable (string tableName, string tableDef, TableConverterTask tableConverter) {
string dbName = "";
if (tableName.Contains(".")) {
var parts = tableName.Split('.');
dbName = parts[0] + ".";
tableName = parts[1];
}
tableDef = tableDef.Trim();
string sql = null;
string newSql = String.Format("CREATE TABLE {0} {1}", tableName, tableDef);
string oldName = String.Format("{0}_old", tableName);
using (var xact = Database.CreateTransaction(true)) {
yield return xact;
using (var q = Database.BuildQuery(String.Format(
@"SELECT sql FROM {0}sqlite_master WHERE tbl_name = ? AND type = 'table'",
dbName
)))
yield return q.ExecuteScalar<string>(tableName).Bind(() => sql);
if (String.Compare(sql, newSql, true) == 0)
yield break;
if (sql != null)
yield return Database.ExecuteSQL(String.Format("ALTER TABLE {2}{0} RENAME TO {1}", tableName, oldName, dbName));
newSql = String.Format("CREATE TABLE {2}{0} {1}", tableName, tableDef, dbName);
yield return Database.ExecuteSQL(newSql);
if (sql != null) {
yield return tableConverter(dbName + oldName, dbName + tableName, sql, newSql);
yield return Database.ExecuteSQL(String.Format("DROP TABLE {1}{0}", oldName, dbName));
}
yield return xact.Commit();
}
}
private static IEnumerator<object> LoadProfile (LoadingWindow loadingWindow) {
IProfile instance = null;
{
var args = Environment.GetCommandLineArgs();
if (args.Length > 1)
ProfilePath = args[1];
}
bool validProfile = false;
try {
validProfile = (ProfilePath != null) && File.Exists(ProfilePath);
} catch {
}
while (instance == null) {
if (!validProfile)
using (var dialog = new OpenFileDialog()) {
dialog.Title = "Select Profile";
dialog.Filter = "Shoot Blues Profiles|*.profile.dll";
dialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath);
if (dialog.ShowDialog(loadingWindow) != DialogResult.OK) {
Application.Exit();
yield break;
}
ProfilePath = dialog.FileName;
}
var fAssembly = Future.RunInThread(() =>
Assembly.LoadFile(ProfilePath)
);
yield return fAssembly;
var fTypes = Future.RunInThread(() => fAssembly.Result.GetTypes());
yield return fTypes;
var profileInterface = typeof(IProfile);
foreach (var type in fTypes.Result) {
if (!profileInterface.IsAssignableFrom(type))
continue;
var constructor = type.GetConstructor(new Type[0]);
instance = constructor.Invoke(null) as IProfile;
break;
}
if (instance == null) {
validProfile = false;
Program.ShowErrorMessage(
String.Format("The file '{0}' is not a valid profile.", ProfilePath)
);
}
}
yield return new Result(instance);
}
public static void AddCustomMenu (ToolStripMenuItem menu) {
if (TrayMenu.Items.Count == 3)
TrayMenu.Items.Insert(1, new ToolStripSeparator());
TrayMenu.Items.Insert(TrayMenu.Items.Count - 2, menu);
}
public static void RemoveCustomMenu (ToolStripMenuItem menu) {
TrayMenu.Items.Remove(menu);
if (TrayMenu.Items.Count == 4)
TrayMenu.Items.RemoveAt(1);
}
public static IEnumerator<object> ShowStatusWindow () {
return ShowStatusWindow(null);
}
public static IEnumerator<object> ShowStatusWindow (string initialPage) {
if (StatusWindowInstance != null) {
StatusWindowInstance.Activate();
StatusWindowInstance.Focus();
if (initialPage != null)
StatusWindowInstance.SelectTab(initialPage);
yield break;
}
using (StatusWindowInstance = new StatusWindow(Scheduler)) {
var names = (from sn in LoadedScripts.Keys orderby sn.Name select sn).ToArray();
foreach (var sn in names) {
var instance = LoadedScripts[sn];
var f = Scheduler.Start(
instance.OnStatusWindowShown(StatusWindowInstance), TaskExecutionPolicy.RunAsBackgroundTask
);
yield return f;
var temp = f.Failed;
}
if (initialPage != null)
StatusWindowInstance.SelectTab(initialPage);
yield return StatusWindowInstance.Show();
}
StatusWindowInstance = null;
}
public static IEnumerator<object> BuildOrderedScriptList (LoadingWindow loadingWindow) {
IManagedScript instance = null;
var visited = new HashSet<ScriptName>();
var result = new List<ScriptName>();
var allScripts = new HashSet<ScriptName>(from fn in Scripts select fn.Name);
foreach (var name in Profile.Dependencies)
allScripts.Add(name);
var toVisit = new LinkedList<ScriptName>();
foreach (var name in Profile.Dependencies)
toVisit.AddLast(name);
foreach (var name in allScripts)
toVisit.AddLast(name);
var majorScripts = new HashSet<ScriptName>(allScripts);
int initialCount = majorScripts.Count;
while (toVisit.Count > 0) {
if (loadingWindow != null)
loadingWindow.SetProgress(
1.0f - (majorScripts.Count / (float)initialCount)
);
var current = toVisit.PopFirst();
if (result.Contains(current))
continue;
visited.Add(current);
majorScripts.Remove(current);
yield return new RunAsBackground(LoadScript(current, loadingWindow));
if (!LoadedScripts.TryGetValue(current, out instance)) {
if (!FailedScripts.Contains(current))
FailedScripts.Add(current);
continue;
} else {
if (!allScripts.Contains(current))
allScripts.Add(current);
}
var head = toVisit.First;
bool resolved = true;
foreach (var dep in instance.Dependencies) {
if (visited.Contains(dep))
continue;
if (head != null)
toVisit.AddBefore(head, dep);
else
toVisit.AddLast(dep);
resolved = false;
}
foreach (var dep in instance.OptionalDependencies) {
if (visited.Contains(dep))
continue;
if (!allScripts.Contains(dep))
continue;
if (head != null)
toVisit.AddBefore(head, dep);
else
toVisit.AddLast(dep);
resolved = false;
}
if (resolved) {
result.Add(current);
} else {
if (head != null)
toVisit.AddBefore(head, current);
else
toVisit.AddLast(current);
}
}
Console.WriteLine(String.Join(", ", (from sn in result select sn.Name).ToArray()));
yield return new Result(result.ToArray());
}
private static IEnumerator<object> SaveScriptsToDatabase () {
using (var xact = Database.CreateTransaction(true)) {
yield return xact;
yield return Database.ExecuteSQL("DELETE FROM scripts WHERE profileName = ?", Profile.ProfileName);
using (var q = Database.BuildQuery("INSERT INTO scripts (profileName, filename) VALUES (?, ?)"))
foreach (var filename in Scripts)
yield return q.ExecuteNonQuery(Profile.ProfileName, filename.FullPath);
yield return xact.Commit();
}
}
private static IEnumerator<object> OnScriptsChanging (Squared.Util.Event.EventInfo evt) {
yield return new RunAsBackground(SaveScriptsToDatabase());
using (var loadingWindow = new LoadingWindow()) {
loadingWindow.SetStatus("Loading scripts", null);
loadingWindow.Show();
var buildScriptList = new RunToCompletion<ScriptName[]>(
BuildOrderedScriptList(loadingWindow), TaskExecutionPolicy.RunWhileFutureLives
);
yield return buildScriptList;
var scriptList = buildScriptList.Result;
foreach (var process in RunningProcesses)
process.Ready = false;
var loadedScriptNames = LoadedScripts.Keys.ToArray();
foreach (var scriptName in loadedScriptNames)
if (!scriptList.Contains(scriptName))
yield return UnloadScript(scriptName);
foreach (var scriptName in scriptList)
if (!LoadedScripts.ContainsKey(scriptName))
yield return new RunAsBackground(LoadScript(scriptName, loadingWindow));
yield return new RunAsBackground(ReloadAllScripts(scriptList));
EventBus.Broadcast(Profile, "ScriptsChanged", scriptList);
}
}
public static IEnumerator<object> NotifyNewProcess (Process process) {
if (process.HasExited)
yield break;
var payload = Future.RunInThread(() => {
using (var payloadStream = Assembly.GetExecutingAssembly().
GetManifestResourceStream("ShootBlues.payload.dll")) {
return new PortableExecutable(payloadStream);
}
});
yield return payload;
if (process.HasExited)
yield break;
var processExit = new SignalFuture();
process.Exited += (s, e) => {
processExit.Complete();
process.EnableRaisingEvents = false;
};
process.EnableRaisingEvents = true;
using (var pi = new ProcessInfo(process)) {
var payloadResult = new Future<Int32>();
var threadId = new Future<UInt32>();
// mov eax, 1; ret 4; nop
var returnOne = new byte[] {
0xb8, 0x01, 0x00, 0x00, 0x00, 0xc2, 0x04, 0x00, 0x90
};
// Suspend the target process before we inject
var ps = KernelFunctionDisabler.SuspendProcess(process);
// Temporarily disable DLL_THREAD_ATTACH before we start our thread, if we can.
var kfd = new KernelFunctionDisabler(process);
try {
kfd.ReplaceFunction(
"ntdll.dll", "RtlIsCurrentThreadAttachExempt", returnOne
);
} catch (FunctionNotExportedException) {
// If the current version of windows doesn't export it, no big deal
}
var fCodeRegion = Future.RunInThread(() =>
ProcessInjector.Inject(process, payload.Result, pi.Channel.Handle, payloadResult, threadId)
);
yield return Future.WaitForFirst(
fCodeRegion, processExit
);
pi.Channel.RemoteThreadId = threadId.Result;
using (fCodeRegion.Result) {
RunningProcesses.Add(pi);
pi.Status = "Waiting for startup";
var nextMsg = pi.Channel.Receive();
using (nextMsg)
yield return Future.WaitForFirst(
nextMsg, processExit
);
pi.Ready = true;
// Now that we know our payload thread is running (because it sent
// us a message), we can re-enable DLL_THREAD_ATTACH and resume the process's other threads
kfd.Dispose();
ps.Dispose();
// At this point the process is alive again so our payload will have a chance to begin
// initializing its python data structures, and it should accept RPCs relatively soon
var fRpcTask = Scheduler.Start(RPCTask(pi), TaskExecutionPolicy.RunWhileFutureLives);
yield return Profile.WaitUntilProcessReady(pi);
string oldStatus = pi.Status = "Loading scripts into process";
EventBus.Broadcast(Profile, "RunningProcessAdded", pi);
var buildScriptList = new RunToCompletion<ScriptName[]>(
BuildOrderedScriptList(null), TaskExecutionPolicy.RunWhileFutureLives
);
yield return buildScriptList;
if (pi.IsAlive)
yield return Future.WaitForFirst(
Scheduler.Start(
LoadScriptsInto(pi, buildScriptList.Result),
TaskExecutionPolicy.RunAsBackgroundTask
), processExit
);
if (pi.IsAlive) {
if (pi.Status == oldStatus)
pi.Status = "Scripts loaded";
EventBus.Broadcast(Profile, "RunningProcessChanged", pi);
using (fRpcTask)
yield return Future.WaitForFirst(
payloadResult, processExit
);
if (payloadResult.Completed) {
pi.Status = String.Format("Payload terminated with exit code {0}.", payloadResult.Result);
EventBus.Broadcast(Profile, "RunningProcessChanged", pi);
}
} else {
fRpcTask.Dispose();
}
}
yield return processExit;
RunningProcesses.Remove(pi);
EventBus.Broadcast(Profile, "RunningProcessRemoved", pi);
}
}
public static Filename FindScript (ScriptName script) {
foreach (var filename in Scripts)
if (script.Equals(filename))
return filename;
if (script.DefaultSearchPath != null) {
var candidatePath = Path.Combine(
script.DefaultSearchPath, script.Name
);
if (File.Exists(candidatePath))
return new Filename(candidatePath);
}
return null;
}
public static IEnumerator<object> FindScriptInteractive (ScriptName script, LoadingWindow loadingWindow) {
var filename = FindScript(script);
if (filename != null)
yield return new Result(filename);