Repository navigation
Expand file tree
/
Copy pathSessionSupport.cs
More file actions
1408 lines (1248 loc) · 50.9 KB
/
Copy pathSessionSupport.cs
File metadata and controls
1408 lines (1248 loc) · 50.9 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
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.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
namespace TermWrap
{
internal enum ConnectionProtocol
{
Ssh,
Telnet
}
internal sealed class StartOptions
{
public string SessionName;
public ConnectionProtocol Protocol = ConnectionProtocol.Ssh;
public string UserName;
public string Password;
public string Host;
public int Port;
public string[] ExtraArgs = new string[0];
public string LoginPrompt = "login:";
public string PasswordPrompt = "password:";
public bool EnableLegacySsh;
public bool WaitReady;
public bool AskPassword;
public bool PasswordStdin;
public string GetPromptConfig()
{
return (LoginPrompt ?? string.Empty) + "\n" + (PasswordPrompt ?? string.Empty);
}
}
internal sealed class StopOptions
{
public string SessionName;
public bool ClearStale;
public bool Prune;
public bool All;
}
internal sealed class SessionCommandOptions
{
public string SessionName;
public bool Clear;
public bool Wait;
public string TextValue;
public string LineValue;
public string HexValue;
public string ControlValue;
}
internal sealed class TailSnapshot
{
public long StartOffset;
public long EndOffset;
public byte[] Data = new byte[0];
}
internal sealed class TailBuffer
{
private readonly int _capacity;
private readonly object _sync = new object();
private long _startOffset;
private byte[] _data = new byte[0];
public TailBuffer(int capacity)
{
_capacity = capacity;
}
public void Append(byte[] source, int count)
{
lock (_sync)
{
int copyCount = Math.Min(count, _capacity);
byte[] next = new byte[Math.Min(_data.Length + copyCount, _capacity)];
int preserved = Math.Min(_data.Length, _capacity - copyCount);
if (preserved > 0)
{
Buffer.BlockCopy(_data, _data.Length - preserved, next, 0, preserved);
}
Buffer.BlockCopy(source, count - copyCount, next, preserved, copyCount);
_startOffset += _data.Length - preserved;
_data = next;
}
}
public TailSnapshot Read(long requestedOffset)
{
lock (_sync)
{
long endOffset = _startOffset + _data.Length;
long effectiveOffset = requestedOffset < 0 ? _startOffset : Math.Max(requestedOffset, _startOffset);
int byteCount = (int)(endOffset - effectiveOffset);
TailSnapshot snapshot = new TailSnapshot();
snapshot.StartOffset = effectiveOffset;
snapshot.EndOffset = endOffset;
if (byteCount <= 0)
{
return snapshot;
}
byte[] data = new byte[byteCount];
int startIndex = (int)(effectiveOffset - _startOffset);
Buffer.BlockCopy(_data, startIndex, data, 0, byteCount);
snapshot.Data = data;
return snapshot;
}
}
public TailSnapshot ReadAll()
{
return Read(-1);
}
public TailSnapshot ReadAllAndClear()
{
lock (_sync)
{
TailSnapshot snapshot = new TailSnapshot();
snapshot.StartOffset = _startOffset;
snapshot.EndOffset = _startOffset + _data.Length;
snapshot.Data = new byte[_data.Length];
if (_data.Length > 0)
{
Buffer.BlockCopy(_data, 0, snapshot.Data, 0, _data.Length);
}
_startOffset = snapshot.EndOffset;
_data = new byte[0];
return snapshot;
}
}
}
internal static class SessionPaths
{
private static readonly string Sessions = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".termwrap-sessions");
public static string SessionsRoot { get { return Sessions; } }
public static string DefaultKnownHostsFile { get { return GetWindowsSharedKnownHostsFile(); } }
public static string GetWindowsSharedKnownHostsFile()
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ssh", "ssh_known_hosts");
}
public static string GetSessionKnownHostsFile(string sessionName)
{
return Path.Combine(GetSessionDir(sessionName), "known_hosts");
}
public static string[] GetKnownSessions(bool includeStopped)
{
Directory.CreateDirectory(SessionsRoot);
string[] dirs = Directory.GetDirectories(SessionsRoot);
List<string> names = new List<string>();
for (int i = 0; i < dirs.Length; i++)
{
string sessionName = Path.GetFileName(dirs[i]);
if (!includeStopped)
{
SessionInfo info = SessionInfo.Load(sessionName);
if (!info.IsAlive())
{
continue;
}
}
names.Add(sessionName);
}
return names.ToArray();
}
public static string GetSessionDir(string sessionName)
{
string sanitized = Sanitize(sessionName);
if (sanitized == "." || sanitized == "..")
{
throw new InvalidOperationException("session name cannot be '.' or '..'");
}
string root = Path.GetFullPath(SessionsRoot);
string candidate = Path.GetFullPath(Path.Combine(root, sanitized));
string rootPrefix = root.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!candidate.StartsWith(rootPrefix, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("session path escapes the sessions directory");
}
return candidate;
}
public static bool SessionDirectoryExists(string sessionName)
{
return Directory.Exists(GetSessionDir(sessionName));
}
public static void DeleteSessionDirectory(string sessionName)
{
string dir = GetSessionDir(sessionName);
if (Directory.Exists(dir))
{
RejectReparsePoint(dir);
Directory.Delete(dir, true);
}
}
public static string GetCommandPipeName(string sessionName)
{
return "termwrap.cmd." + Sanitize(sessionName);
}
public static string GetMutexName(string sessionName)
{
return "Local\\termwrap.mutex." + Sanitize(sessionName);
}
public static string Sanitize(string value)
{
if (string.IsNullOrEmpty(value))
{
throw new InvalidOperationException("session name cannot be empty");
}
StringBuilder builder = new StringBuilder(value.Length);
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
if (!char.IsLetterOrDigit(c) && c != '-' && c != '_' && c != '.')
{
throw new InvalidOperationException("session name contains an unsupported character: " + c);
}
builder.Append(c);
}
return builder.ToString();
}
public static void EnsureSecureSessionDirectory(string sessionName)
{
EnsureSecureDirectory(SessionsRoot);
EnsureSecureDirectory(GetSessionDir(sessionName));
}
private static void EnsureSecureDirectory(string path)
{
Directory.CreateDirectory(path);
RejectReparsePoint(path);
DirectorySecurity security = new DirectorySecurity();
security.SetAccessRuleProtection(true, false);
AddFullControlRules(security, true);
Directory.SetAccessControl(path, security);
}
private static void RejectReparsePoint(string path)
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReparsePoint) != 0)
{
throw new InvalidOperationException("session paths cannot be reparse points: " + path);
}
}
internal static void AddFullControlRules(FileSystemSecurity security, bool inheritToChildren)
{
InheritanceFlags inheritance = inheritToChildren
? InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
: InheritanceFlags.None;
SecurityIdentifier currentUser = WindowsIdentity.GetCurrent().User;
if (currentUser != null)
{
security.AddAccessRule(new FileSystemAccessRule(currentUser, FileSystemRights.FullControl, inheritance, PropagationFlags.None, AccessControlType.Allow));
}
security.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
FileSystemRights.FullControl,
inheritance,
PropagationFlags.None,
AccessControlType.Allow));
security.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
FileSystemRights.FullControl,
inheritance,
PropagationFlags.None,
AccessControlType.Allow));
}
}
internal static class CredentialStore
{
public static string Create(string sessionName, string password)
{
if (password == null)
{
return string.Empty;
}
SessionPaths.EnsureSecureSessionDirectory(sessionName);
string path = Path.Combine(SessionPaths.GetSessionDir(sessionName), "credential.secret");
WriteProtected(path, password, new UTF8Encoding(false));
return path;
}
public static void WriteProtected(string path, string content, Encoding encoding)
{
File.WriteAllText(path, content, encoding);
FileSecurity security = new FileSecurity();
security.SetAccessRuleProtection(true, false);
SessionPaths.AddFullControlRules(security, false);
File.SetAccessControl(path, security);
}
public static string Consume(string sessionName, string path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
string expectedPath = Path.GetFullPath(Path.Combine(SessionPaths.GetSessionDir(sessionName), "credential.secret"));
string fullPath = Path.GetFullPath(path);
if (!string.Equals(fullPath, expectedPath, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("invalid credential file path");
}
try
{
return File.ReadAllText(fullPath, Encoding.UTF8);
}
finally
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
}
}
public static void Delete(string path)
{
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
File.Delete(path);
}
}
public static string Read(string path)
{
return File.ReadAllText(path, Encoding.UTF8);
}
}
internal static class Logger
{
private static readonly object Sync = new object();
private static string _version;
private static string _appLogFile;
public static void Initialize(string version, string logFolder)
{
_version = version;
if (!string.IsNullOrEmpty(logFolder))
{
Directory.CreateDirectory(logFolder);
_appLogFile = Path.Combine(logFolder, "termwrap.log");
}
Info("logger initialized version={0}", version);
}
public static void Info(string format, params object[] args)
{
Write("INFO", string.Format(CultureInfo.InvariantCulture, format, args));
}
public static void Error(string message)
{
Write("ERROR", message);
}
private static void Write(string level, string message)
{
if (string.IsNullOrEmpty(_appLogFile))
{
return;
}
lock (Sync)
{
string line = string.Format(
CultureInfo.InvariantCulture,
"{0} [{1}] v{2} pid={3} {4}{5}",
DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
level,
_version ?? "unknown",
Process.GetCurrentProcess().Id,
message,
Environment.NewLine);
byte[] data = Encoding.UTF8.GetBytes(line);
using (FileStream stream = new FileStream(_appLogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
}
}
internal sealed class SessionInfo
{
public string SessionName;
public int DaemonPid;
public int RemotePid;
public string RemoteStartedAtUtc;
public string Protocol;
public string Host;
public int Port;
public string StartedAtUtc;
public string Target;
public string AuthMode;
public string Status;
public string LastError;
public string ExitReason;
public string StderrTail;
public bool IsAlive()
{
if (DaemonPid <= 0)
{
return false;
}
try
{
Process process = Process.GetProcessById(DaemonPid);
string expectedName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
if (process.HasExited || !string.Equals(process.ProcessName, expectedName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
DateTime recordedStart;
if (!DateTime.TryParse(
StartedAtUtc,
CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind,
out recordedStart))
{
return false;
}
// A PID can be reused long after a session daemon exits. The
// metadata timestamp is captured in the daemon constructor,
// so allow a small startup margin but reject another process.
TimeSpan difference = process.StartTime.ToUniversalTime() - recordedStart.ToUniversalTime();
if (Math.Abs(difference.TotalSeconds) > 30)
{
return false;
}
return true;
}
catch
{
return false;
}
}
public static SessionInfo Load(string sessionName)
{
SessionInfo info = new SessionInfo();
info.SessionName = sessionName;
string file = Path.Combine(SessionPaths.GetSessionDir(sessionName), "session.info");
if (!File.Exists(file))
{
return info;
}
foreach (string line in ReadAllLinesShared(file))
{
int index = line.IndexOf('=');
if (index <= 0)
{
continue;
}
string key = line.Substring(0, index);
string value = line.Substring(index + 1);
if (key == "daemonPid") { int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out info.DaemonPid); }
else if (key == "remotePid") { int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out info.RemotePid); }
else if (key == "remoteStartedAtUtc") { info.RemoteStartedAtUtc = value; }
else if (key == "protocol") { info.Protocol = value; }
else if (key == "host") { info.Host = value; }
else if (key == "port") { int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out info.Port); }
else if (key == "startedAtUtc") { info.StartedAtUtc = value; }
else if (key == "target") { info.Target = value; }
else if (key == "authMode") { info.AuthMode = value; }
else if (key == "status") { info.Status = value; }
else if (key == "lastError") { info.LastError = value; }
else if (key == "exitReason") { info.ExitReason = value; }
else if (key == "stderrTail") { info.StderrTail = value; }
}
return info;
}
private static string[] ReadAllLinesShared(string file)
{
for (int attempt = 0; attempt < 5; attempt++)
{
try
{
List<string> lines = new List<string>();
using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
while (!reader.EndOfStream)
{
lines.Add(reader.ReadLine());
}
}
return lines.ToArray();
}
catch (IOException)
{
if (attempt == 4)
{
throw;
}
Thread.Sleep(100);
}
}
return new string[0];
}
}
internal interface ISessionTransport : IDisposable
{
string ProtocolName { get; }
string TargetDescription { get; }
int RemotePid { get; }
string RemoteStartedAtUtc { get; }
bool HasExited { get; }
string DescribeState();
Stream InputStream { get; }
Stream OutputStream { get; }
Stream ErrorStream { get; }
void Start();
void Stop();
bool WaitForExit(int milliseconds);
}
internal sealed class SshSessionTransport : ISessionTransport
{
private readonly string _sshPath;
private readonly string _sshArguments;
private readonly string _password;
private readonly string _sessionDir;
private Process _process;
private string _askPassScriptPath;
private string _askPassSecretPath;
public SshSessionTransport(string sshPath, string sshArguments, string password, string sessionDir)
{
_sshPath = sshPath;
_sshArguments = sshArguments;
_password = password;
_sessionDir = sessionDir;
}
public string ProtocolName { get { return "ssh"; } }
public string TargetDescription { get { return _sshArguments; } }
public int RemotePid { get { return _process == null ? 0 : _process.Id; } }
public string RemoteStartedAtUtc
{
get
{
return _process == null
? string.Empty
: _process.StartTime.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture);
}
}
public bool HasExited { get { return _process == null || _process.HasExited; } }
public string DescribeState()
{
if (_process == null)
{
return "process=null";
}
if (!_process.HasExited)
{
return "process=running";
}
return "process=exited exitCode=" + _process.ExitCode.ToString(CultureInfo.InvariantCulture);
}
public Stream InputStream { get { return _process.StandardInput.BaseStream; } }
public Stream OutputStream { get { return _process.StandardOutput.BaseStream; } }
public Stream ErrorStream { get { return _process.StandardError.BaseStream; } }
public void Start()
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = _sshPath,
Arguments = _sshArguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
if (_password != null)
{
_askPassScriptPath = CreateAskPassScript();
startInfo.EnvironmentVariables["SSH_ASKPASS"] = _askPassScriptPath;
startInfo.EnvironmentVariables["SSH_ASKPASS_REQUIRE"] = "force";
startInfo.EnvironmentVariables["DISPLAY"] = "termwrap";
}
_process = Process.Start(startInfo);
if (_process == null)
{
throw new InvalidOperationException("failed to start ssh transport");
}
}
public void Stop()
{
try
{
if (_process != null && !_process.HasExited)
{
_process.StandardInput.Close();
if (!_process.WaitForExit(2000))
{
_process.Kill();
}
}
}
finally
{
DeleteAskPassScript();
}
}
public bool WaitForExit(int milliseconds)
{
return _process == null || _process.WaitForExit(milliseconds);
}
public void Dispose()
{
Stop();
if (_process != null)
{
_process.Dispose();
_process = null;
}
}
private string CreateAskPassScript()
{
string path = Path.Combine(_sessionDir, "askpass.cmd");
_askPassSecretPath = Path.Combine(_sessionDir, "askpass.secret");
CredentialStore.WriteProtected(_askPassSecretPath, _password, new UTF8Encoding(false));
string executablePath = Process.GetCurrentProcess().MainModule.FileName;
CredentialStore.WriteProtected(
path,
"@echo off" + Environment.NewLine +
QuoteForBatch(executablePath) + " --askpass-secret " + QuoteForBatch(_askPassSecretPath) + Environment.NewLine,
Encoding.ASCII);
return path;
}
private void DeleteAskPassScript()
{
try
{
if (!string.IsNullOrEmpty(_askPassScriptPath) && File.Exists(_askPassScriptPath))
{
File.Delete(_askPassScriptPath);
}
CredentialStore.Delete(_askPassSecretPath);
}
catch (Exception ex)
{
Logger.Error("askpass cleanup " + ex);
}
}
private static string QuoteForBatch(string value)
{
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
}
internal sealed class SessionDaemon
{
private readonly string _sessionName;
private readonly string _protocol;
private readonly string _host;
private readonly string _transportPath;
private readonly string _transportArguments;
private readonly string _userName;
private readonly string _password;
private readonly string _sessionDir;
private readonly string _metaFile;
private readonly string _outputLog;
private readonly string _sessionKnownHostsFile;
private readonly TailBuffer _tailBuffer;
private readonly TailBuffer _readBuffer;
private readonly object _sync = new object();
private readonly object _metadataSync = new object();
private readonly DateTime _startedAtUtc;
private Mutex _mutex;
private volatile bool _stopping;
private FileStream _outputFile;
private ISessionTransport _transport;
private int _promptStage;
private string _loginPrompt;
private string _passwordPrompt;
private string _recentText = string.Empty;
private string _lastError = string.Empty;
private string _exitReason = string.Empty;
private string _stderrTail = string.Empty;
public SessionDaemon(string sessionName, string protocol, string host, string transportPath, string transportArguments, string userName, string password, string promptConfig)
{
_sessionName = SessionPaths.Sanitize(sessionName);
_protocol = protocol;
_host = host;
_transportPath = transportPath;
_transportArguments = transportArguments;
_userName = userName;
_password = password;
_sessionDir = SessionPaths.GetSessionDir(_sessionName);
_metaFile = Path.Combine(_sessionDir, "session.info");
_outputLog = Path.Combine(_sessionDir, "output.log");
_sessionKnownHostsFile = SessionPaths.GetSessionKnownHostsFile(_sessionName);
_tailBuffer = new TailBuffer(1024 * 1024);
_readBuffer = new TailBuffer(1024 * 1024);
_startedAtUtc = DateTime.UtcNow;
ParsePromptConfig(promptConfig);
}
public int Run()
{
SessionPaths.EnsureSecureSessionDirectory(_sessionName);
bool createdNew;
_mutex = new Mutex(false, SessionPaths.GetMutexName(_sessionName), out createdNew);
if (!_mutex.WaitOne(0))
{
throw new InvalidOperationException("session already active: " + _sessionName);
}
try
{
EnsureSessionKnownHostsFile();
_outputFile = new FileStream(_outputLog, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
_transport = CreateTransport();
_transport.Start();
WriteMetadata();
Thread stdoutThread = StartPumpThread(_transport.OutputStream, "stdout");
Thread stderrThread = _transport.ErrorStream == null ? null : StartPumpThread(_transport.ErrorStream, "stderr");
Thread commandThread = StartCommandServerThread();
Thread transportMonitorThread = StartTransportMonitorThread();
Logger.Info("daemon loop start session={0} transport={1} state={2}", _sessionName, _transport.ProtocolName, _transport.DescribeState());
while (!_stopping && !_transport.HasExited)
{
Thread.Sleep(250);
}
Logger.Info(
"daemon loop exit session={0} stopping={1} transportExited={2} state={3}",
_sessionName,
_stopping,
_transport.HasExited,
_transport.DescribeState());
_exitReason = _stopping ? "stop requested" : "transport exited";
_stopping = true;
_transport.Stop();
if (stdoutThread != null) { stdoutThread.Join(1000); }
if (stderrThread != null) { stderrThread.Join(1000); }
if (commandThread != null) { commandThread.Join(1000); }
if (transportMonitorThread != null) { transportMonitorThread.Join(1000); }
WriteMetadata();
Logger.Info("daemon shutdown complete session={0}", _sessionName);
return 0;
}
catch (Exception ex)
{
_lastError = ex.Message;
_exitReason = "exception";
WriteMetadata();
Logger.Error("daemon startup/run failed session=" + _sessionName + " " + ex);
throw;
}
finally
{
Logger.Info("daemon finally session={0}", _sessionName);
if (_transport != null) { _transport.Dispose(); }
if (_outputFile != null) { _outputFile.Dispose(); }
ReleaseMutex();
}
}
private void ParsePromptConfig(string promptConfig)
{
string[] parts = (promptConfig ?? string.Empty).Split(new[] { '\n' }, 2);
_loginPrompt = parts.Length > 0 && !string.IsNullOrEmpty(parts[0]) ? parts[0] : "login:";
_passwordPrompt = parts.Length > 1 && !string.IsNullOrEmpty(parts[1]) ? parts[1] : "password:";
}
private ISessionTransport CreateTransport()
{
if (string.Equals(_protocol, "ssh", StringComparison.OrdinalIgnoreCase))
{
return new SshSessionTransport(_transportPath, _transportArguments, _password, _sessionDir);
}
if (string.Equals(_protocol, "telnet", StringComparison.OrdinalIgnoreCase))
{
int port = int.Parse(_transportArguments, CultureInfo.InvariantCulture);
return new TelnetSessionTransport(_host, port);
}
throw new InvalidOperationException("unsupported protocol: " + _protocol);
}
private Thread StartPumpThread(Stream source, string sourceName)
{
Thread thread = new Thread(new ThreadStart(delegate { PumpStream(source, sourceName); }));
thread.IsBackground = true;
thread.Start();
return thread;
}
private Thread StartCommandServerThread()
{
Thread thread = new Thread(new ThreadStart(RunCommandServer));
thread.IsBackground = true;
thread.Start();
return thread;
}
private Thread StartTransportMonitorThread()
{
Thread thread = new Thread(new ThreadStart(MonitorTransportExit));
thread.IsBackground = true;
thread.Start();
return thread;
}
private void MonitorTransportExit()
{
while (!_stopping && _transport != null && !_transport.HasExited)
{
Thread.Sleep(100);
}
if (_transport == null || _stopping)
{
return;
}
_exitReason = "transport exited: " + _transport.DescribeState();
WriteMetadata();
Logger.Info("transport exit monitor session={0} state={1}", _sessionName, _transport.DescribeState());
}
private void RunCommandServer()
{
while (!_stopping)
{
NamedPipeServerStream pipe = null;
try
{
string pipeName = SessionPaths.GetCommandPipeName(_sessionName);
pipe = new NamedPipeServerStream(
pipeName,
PipeDirection.InOut,
1,
PipeTransmissionMode.Byte,
PipeOptions.None,
4096,
4096,
PipeSecurityFactory.Create());
Logger.Info("command server listening session={0} pipe={1} identity={2}", _sessionName, pipeName, GetProcessIdentityForLog());
pipe.WaitForConnection();
Logger.Info("command server connected session={0} pipe={1} identity={2}", _sessionName, pipeName, GetProcessIdentityForLog());
using (pipe)
using (StreamReader reader = new StreamReader(pipe, Encoding.UTF8, false, 1024, true))
using (StreamWriter writer = new StreamWriter(pipe, Encoding.UTF8, 1024, true))
{
writer.NewLine = "\n";
string command = reader.ReadLine() ?? string.Empty;
Logger.Info("command server request session={0} pipe={1} command={2}", _sessionName, pipeName, SummarizePipeMessage(command));
string response = HandleCommand(command);
writer.WriteLine(response);
writer.Flush();
Logger.Info("command server response session={0} pipe={1} response={2}", _sessionName, pipeName, SummarizePipeMessage(response));
}
}
catch (Exception ex)
{
if (!_stopping)
{
Logger.Error("command server " + ex.Message);
}
if (pipe != null)
{
pipe.Dispose();
}
}
}
}
private string HandleCommand(string command)
{
try
{
if (string.Equals(command, "STOP", StringComparison.Ordinal))
{
_stopping = true;
return "OK stopped";
}
if (string.Equals(command, "PING", StringComparison.Ordinal))
{
return "OK pong";
}
if (string.Equals(command, "READ", StringComparison.Ordinal)) { return EncodeSnapshot("READ", _readBuffer.ReadAll()); }
if (string.Equals(command, "READ_CLEAR", StringComparison.Ordinal)) { return EncodeSnapshot("READ_CLEAR", _readBuffer.ReadAllAndClear()); }
if (command.StartsWith("TAIL ", StringComparison.Ordinal))
{
long offset = long.Parse(command.Substring(5), CultureInfo.InvariantCulture);
return EncodeSnapshot("TAIL", _tailBuffer.Read(offset));
}
if (command.StartsWith("SEND_TEXT ", StringComparison.Ordinal))
{
byte[] data = Convert.FromBase64String(command.Substring(10));
WriteToTransport(data);
return "OK sent text";
}
if (command.StartsWith("SEND_HEX ", StringComparison.Ordinal))
{
byte[] data = HexToBytes(command.Substring(9));
WriteToTransport(data);
return "OK sent hex";
}
if (command.StartsWith("SEND_CONTROL ", StringComparison.Ordinal))
{
byte[] data = ControlNameToBytes(command.Substring(13));
WriteToTransport(data);
return "OK sent control";
}
return "ERR unknown command";
}
catch (Exception ex)
{
Logger.Error("command failed session=" + _sessionName + " command=" + SummarizePipeMessage(command) + " " + ex.Message);
return "ERR " + ex.Message.Replace('\r', ' ').Replace('\n', ' ');
}
}
private static string SummarizePipeMessage(string message)
{
if (string.IsNullOrEmpty(message))
{
return string.Empty;
}