/
Session.cs
2807 lines (2470 loc) · 116 KB
/
Session.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.IO;
using System.Reflection;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml;
#if !NETSTANDARD
using Microsoft.Win32;
#endif
using System.Diagnostics;
#if !NETSTANDARD
using System.Security;
#endif
using System.Text.RegularExpressions;
using System.Linq;
namespace WinSCP
{
[Guid("38649D44-B839-4F2C-A9DC-5D45EEA4B5E9")]
[ComVisible(true)]
public enum SynchronizationMode
{
Local = 0,
Remote = 1,
Both = 2,
}
[Guid("3F770EC1-35F5-4A7B-A000-46A2F7A213D8")]
[ComVisible(true)]
[Flags]
public enum SynchronizationCriteria
{
None = 0x00,
Time = 0x01,
Size = 0x02,
Either = Time | Size,
}
[Guid("6C441F60-26AA-44FC-9B93-08884768507B")]
[ComVisible(true)]
[Flags]
public enum EnumerationOptions
{
None = 0x00,
AllDirectories = 0x01,
MatchDirectories = 0x02,
EnumerateDirectories = 0x04,
}
[Guid("16B6D8F6-C0B4-487D-9546-A25BBF582ED6")]
[ComVisible(true)]
public enum ProgressSide
{
Local = 0,
Remote = 1,
}
public delegate void OutputDataReceivedEventHandler(object sender, OutputDataReceivedEventArgs e);
public delegate void FileTransferredEventHandler(object sender, TransferEventArgs e);
public delegate void FileTransferProgressEventHandler(object sender, FileTransferProgressEventArgs e);
public delegate void FailedEventHandler(object sender, FailedEventArgs e);
public delegate void QueryReceivedEventHandler(object sender, QueryReceivedEventArgs e);
[Guid("56FFC5CE-3867-4EF0-A3B5-CFFBEB99EA35")]
[ClassInterface(Constants.ClassInterface)]
[ComVisible(true)]
[ComSourceInterfaces(typeof(ISessionEvents))]
public sealed class Session : IDisposable, IReflect
{
public string ExecutablePath { get { return _executablePath; } set { CheckNotOpened(); _executablePath = value; } }
#if !NETSTANDARD
public string ExecutableProcessUserName { get { return _executableProcessUserName; } set { CheckNotOpened(); _executableProcessUserName = value; } }
public SecureString ExecutableProcessPassword { get { return _executableProcessPassword; } set { CheckNotOpened(); _executableProcessPassword = value; } }
#endif
public string AdditionalExecutableArguments { get { return _additionalExecutableArguments; } set { CheckNotOpened(); _additionalExecutableArguments = value; } }
[Obsolete("Use AddRawConfiguration")]
public bool DefaultConfiguration { get { return _defaultConfiguration; } set { CheckNotOpened(); _defaultConfiguration = value; } }
public bool DisableVersionCheck { get { return _disableVersionCheck; } set { CheckNotOpened(); _disableVersionCheck = value; } }
[Obsolete("Use AddRawConfiguration")]
public string IniFilePath { get { return _iniFilePath; } set { CheckNotOpened(); _iniFilePath = value; } }
public TimeSpan ReconnectTime { get { return _reconnectTime; } set { CheckNotOpened(); _reconnectTime = value; } }
public int ReconnectTimeInMilliseconds { get { return Tools.TimeSpanToMilliseconds(ReconnectTime); } set { ReconnectTime = Tools.MillisecondsToTimeSpan(value); } }
public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
public int DebugLogLevel { get { CheckNotDisposed(); return Logger.LogLevel; } set { CheckNotDisposed(); Logger.LogLevel = value; } }
public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
public bool XmlLogPreserve { get; set; }
#if DEBUG
public bool GuardProcessWithJob { get { return GuardProcessWithJobInternal; } set { GuardProcessWithJobInternal = value; } }
public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
#endif
public string HomePath { get { CheckOpened(); return _homePath; } }
public TimeSpan Timeout { get; set; }
public StringCollection Output { get; private set; }
public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
public event FileTransferredEventHandler FileTransferred;
public event FailedEventHandler Failed;
public event OutputDataReceivedEventHandler OutputDataReceived;
public event FileTransferProgressEventHandler FileTransferProgress
{
add
{
using (Logger.CreateCallstackAndLock())
{
CheckNotOpened();
_fileTransferProgress += value;
}
}
remove
{
using (Logger.CreateCallstackAndLock())
{
CheckNotOpened();
_fileTransferProgress -= value;
}
}
}
public event QueryReceivedEventHandler QueryReceived { add { AddQueryReceived(value); } remove { RemoveQueryReceived(value); } }
private void AddQueryReceived(QueryReceivedEventHandler value)
{
using (Logger.CreateCallstackAndLock())
{
bool send = (_queryReceived == null);
_queryReceived += value;
if (Opened && send)
{
SendOptionBatchCommand();
WaitForGroup();
}
}
}
private void RemoveQueryReceived(QueryReceivedEventHandler value)
{
using (Logger.CreateCallstackAndLock())
{
if (_queryReceived != null)
{
_queryReceived -= value;
if (Opened && (_queryReceived == null))
{
SendOptionBatchCommand();
WaitForGroup();
}
}
}
}
public Session()
{
Logger = new Logger();
using (Logger.CreateCallstackAndLock())
{
Timeout = new TimeSpan(0, 1, 0);
_reconnectTime = new TimeSpan(0, 2, 0); // keep in sync with TScript::OptionImpl
ResetOutput();
_operationResults = new List<OperationResultBase>();
_events = new List<Action>();
_eventsEvent = new AutoResetEvent(false);
_choiceEvent = new ManualResetEvent(false);
_disposed = false;
_defaultConfiguration = true;
_logUnique = 0;
_guardProcessWithJob = true;
RawConfiguration = new Dictionary<string, string>();
}
}
private void ResetOutput()
{
Output = new StringCollection();
_error = new StringCollection();
}
public void Dispose()
{
using (Logger.CreateCallstackAndLock())
{
_disposed = true;
Cleanup();
Logger.Dispose();
if (_eventsEvent != null)
{
_eventsEvent.Close();
_eventsEvent = null;
}
if (_choiceEvent != null)
{
_choiceEvent.Close();
_choiceEvent = null;
}
GC.SuppressFinalize(this);
}
}
public void Abort()
{
using (Logger.CreateCallstack())
{
CheckOpened();
_aborted = true;
// double-check
if (_process != null)
{
_process.Abort();
}
}
}
public void Open(SessionOptions sessionOptions)
{
using (Logger.CreateCallstackAndLock())
{
CheckNotDisposed();
if (Opened)
{
throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
}
if (sessionOptions == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(sessionOptions)));
}
try
{
SetupTempPath();
ResetOutput();
_process = ExeSessionProcess.CreateForSession(this);
_process.OutputDataReceived += ProcessOutputDataReceived;
_process.Start();
GotOutput();
// setup batch mode
SendOptionBatchCommand();
WriteCommand("option confirm off");
object reconnectTimeValue;
if (ReconnectTime != TimeSpan.MaxValue)
{
reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
}
else
{
reconnectTimeValue = "off";
}
string reconnectTimeCommand =
string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
WriteCommand(reconnectTimeCommand);
SessionOptionsToUrlAndSwitches(sessionOptions, false, out string command, out string log);
const string openCommand = "open ";
command = openCommand + command;
log = openCommand + log;
WriteCommand(command, log);
Logger.WriteLine("Waiting for XML log file");
// Wait until the log file gets created or WinSCP terminates (in case of fatal error)
do
{
string logExplanation;
lock (Output)
{
if (_error.Count > 0)
{
logExplanation = GetErrorOutputMessage();
}
else if (Output.Count > 0)
{
logExplanation =
string.Format(
CultureInfo.CurrentCulture, "Output was \"{0}\". ", ListToString(Output));
}
else
{
logExplanation = "There was no output. ";
}
}
logExplanation +=
string.Format(CultureInfo.CurrentCulture,
"Response log file {0} was not created. This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
XmlLogPath);
if (_process.HasExited && !File.Exists(XmlLogPath))
{
#if !NETSTANDARD
Logger.WriteCounters();
#endif
Logger.WriteProcesses();
_process.WriteStatus();
string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
if (_process.ExitCode < 0)
{
exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
}
throw Logger.WriteException(
new SessionLocalException(this,
string.Format(CultureInfo.CurrentCulture, "WinSCP process terminated with exit code {0}. ", exitCode) +
logExplanation));
}
Thread.Sleep(50);
CheckForTimeout(
"WinSCP has not responded in time. " +
logExplanation);
} while (!File.Exists(XmlLogPath));
Logger.WriteLine("XML log file created");
_logReader = new SessionLogReader(this);
_logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);
// special variant of ElementLogReader that throws when closing element (</session>) is encountered
_reader = new SessionElementLogReader(_logReader);
// Skip "open" command <group>
WaitForGroup();
WriteCommand("pwd");
using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
{
while (cwdReader.Read(0))
{
if (cwdReader.GetEmptyElementValue("cwd", out string value))
{
_homePath = value;
}
}
groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
}
_sessionTimeout = sessionOptions.Timeout;
}
catch (Exception e)
{
Logger.WriteLine("Exception: {0}", e);
Cleanup();
throw;
}
}
}
private void SendOptionBatchCommand()
{
string command = string.Format(CultureInfo.InvariantCulture, "option batch {0}", (_queryReceived != null ? "off" : "on"));
WriteCommand(command);
}
private void WaitForGroup()
{
using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
{
ReadElement(groupReader, LogReadFlags.ThrowFailures);
}
}
internal string GetErrorOutputMessage()
{
string result = null;
if (_error.Count > 0)
{
result = string.Format(CultureInfo.CurrentCulture, "Error output was \"{0}\". ", ListToString(_error));
}
return result;
}
private static string ListToString(StringCollection list)
{
string[] stringArray = new string[list.Count];
list.CopyTo(stringArray, 0);
string s = string.Join(Environment.NewLine, stringArray);
return s;
}
public string ScanFingerprint(SessionOptions sessionOptions, string algorithm)
{
using (Logger.CreateCallstackAndLock())
{
string normalizeAlgorithm = NormalizeIdent(algorithm);
if (string.IsNullOrEmpty(normalizeAlgorithm))
{
throw Logger.WriteException(new ArgumentException("Algorithm cannot be empty", nameof(algorithm)));
}
string result;
CheckNotDisposed();
if (Opened)
{
throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
}
try
{
ResetOutput();
SessionOptionsToUrlAndSwitches(sessionOptions, true, out string command, out string log);
string additionalArguments = "/fingerprintscan " + command;
_process = ExeSessionProcess.CreateForConsole(this, additionalArguments);
_process.OutputDataReceived += ProcessOutputDataReceived;
_process.Start();
GotOutput();
while (!_process.HasExited)
{
Thread.Sleep(50);
CheckForTimeout();
}
if (_process.ExitCode == 0)
{
result = null;
foreach (string s in Output)
{
int p = s.IndexOf(":", StringComparison.Ordinal);
if (p < 0)
{
throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Unexpected fingerprint scan result line '{0}'", s)));
}
string a = NormalizeIdent(s.Substring(0, p).Trim());
if (normalizeAlgorithm.Equals(a, StringComparison.OrdinalIgnoreCase))
{
result = s.Substring(p + 1).Trim();
break;
}
}
if (result == null)
{
throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Fingerprint for algorithm {0} not supported", algorithm)));
}
}
else
{
throw Logger.WriteException(new SessionRemoteException(this, ListToString(Output)));
}
}
catch (Exception e)
{
Logger.WriteLine("Exception: {0}", e);
throw;
}
finally
{
Cleanup();
}
return result;
}
}
private static string NormalizeIdent(string algorithm)
{
return algorithm.Replace("-", string.Empty);
}
public void Close()
{
using (Logger.CreateCallstackAndLock())
{
CheckOpened();
Cleanup();
}
}
public RemoteDirectoryInfo ListDirectory(string path)
{
using (Logger.CreateCallstackAndLock())
{
CheckOpened();
WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", Tools.ArgumentEscape(IncludeTrailingSlash(path))));
RemoteDirectoryInfo result = new RemoteDirectoryInfo();
using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
{
string destination = null;
if (lsReader.TryWaitForEmptyElement("destination", 0))
{
lsReader.GetEmptyElementValue("destination", out destination);
}
if ((destination != null) && lsReader.TryWaitForNonEmptyElement("files", 0))
{
destination = IncludeTrailingSlash(destination);
using (ElementLogReader filesReader = lsReader.CreateLogReader())
{
while (filesReader.TryWaitForNonEmptyElement("file", 0))
{
RemoteFileInfo fileInfo = new RemoteFileInfo();
using (ElementLogReader fileReader = filesReader.CreateLogReader())
{
while (fileReader.Read(0))
{
if (fileReader.GetEmptyElementValue("filename", out string value))
{
fileInfo.Name = value;
fileInfo.FullName = destination + value;
}
else
{
ReadFile(fileInfo, fileReader);
}
}
result.AddFile(fileInfo);
}
}
}
lsReader.ReadToEnd(LogReadFlags.ThrowFailures);
groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
}
else
{
// "files" not found, keep reading, we expect "failure"
// This happens only in case of fatal errors,
// in case of normal error (non existing folder),
// the "failure" is caught in "group" already, before the "ls".
groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
// only if not "failure", throw "files" not found
throw Logger.WriteException(SessionLocalException.CreateElementNotFound(this, "files"));
}
}
return result;
}
}
private IEnumerable<RemoteFileInfo> DoEnumerateRemoteFiles(string path, Regex regex, EnumerationOptions options, bool throwReadErrors)
{
Logger.WriteLine("Starting enumeration of {0} ...", path);
bool allDirectories = ((options & EnumerationOptions.AllDirectories) == EnumerationOptions.AllDirectories);
bool matchDirectories = ((options & EnumerationOptions.MatchDirectories) == EnumerationOptions.MatchDirectories);
bool enumerateDirectories = ((options & EnumerationOptions.EnumerateDirectories) == EnumerationOptions.EnumerateDirectories);
if (enumerateDirectories && !allDirectories)
{
throw Logger.WriteException(new ArgumentException("Cannot use enumeration option EnumerateDirectories without AllDirectories"));
}
if (enumerateDirectories && matchDirectories)
{
throw Logger.WriteException(new ArgumentException("Cannot combine enumeration option EnumerateDirectories with MatchDirectories"));
}
RemoteDirectoryInfo directoryInfo;
try
{
// Need to use guarded method for the listing, see a comment in EnumerateRemoteFiles
directoryInfo = ListDirectory(path);
}
catch (SessionRemoteException)
{
if (throwReadErrors)
{
throw;
}
else
{
directoryInfo = null;
}
}
if (directoryInfo != null)
{
foreach (RemoteFileInfo fileInfo in directoryInfo.Files)
{
if (!fileInfo.IsThisDirectory && !fileInfo.IsParentDirectory)
{
bool matches = regex.IsMatch(fileInfo.Name);
bool enumerate;
if (!fileInfo.IsDirectory)
{
enumerate = matches;
}
else
{
if (enumerateDirectories)
{
enumerate = true;
}
else if (matchDirectories)
{
enumerate = matches;
}
else
{
enumerate = false;
}
}
if (enumerate)
{
Logger.WriteLine("Enumerating {0}", fileInfo.FullName);
yield return fileInfo;
}
if (fileInfo.IsDirectory && allDirectories)
{
foreach (RemoteFileInfo fileInfo2 in DoEnumerateRemoteFiles(RemotePath.Combine(path, fileInfo.Name), regex, options, false))
{
yield return fileInfo2;
}
}
}
}
}
Logger.WriteLine("Ended enumeration of {0}", path);
}
public IEnumerable<RemoteFileInfo> EnumerateRemoteFiles(string path, string mask, EnumerationOptions options)
{
// Note that this method exits as soon as DoEnumerateRemoteFiles is entered,
// so the Session object is not guarded during the whole enumeration.
// Though it should not matter as it uses only guarded methods (ListDirectory)
// for the actual work on the session
using (Logger.CreateCallstackAndLock())
{
CheckOpened();
Regex regex = MaskToRegex(mask);
return DoEnumerateRemoteFiles(path, regex, options, true);
}
}
internal static Regex MaskToRegex(string mask)
{
if (string.IsNullOrEmpty(mask) ||
// *.* has to match even filename without dot
(mask == "*.*"))
{
mask = "*";
}
return
new Regex(
'^' +
mask
.Replace(".", "[.]")
.Replace("*", ".*")
.Replace("?", ".") +
'$',
RegexOptions.IgnoreCase);
}
public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
{
using (Logger.CreateCallstackAndLock())
{
return DoPutFiles(localPath, remotePath, remove, options);
}
}
public TransferOperationResult DoPutFiles(string localPath, string remotePath, bool remove, TransferOptions options)
{
using (Logger.CreateCallstack())
{
if (options == null)
{
options = new TransferOptions();
}
CheckOpened();
WriteCommand(
string.Format(CultureInfo.InvariantCulture,
"put {0} {1} -- \"{2}\" \"{3}\"",
BooleanSwitch(remove, "delete"), options.ToSwitches(),
Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
TransferOperationResult result = new TransferOperationResult();
using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
using (RegisterOperationResult(result))
using (CreateProgressHandler())
{
TransferEventArgs args = null;
bool mkdir = false;
while (groupReader.Read(0))
{
if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
{
AddTransfer(result, args);
args = TransferEventArgs.Read(ProgressSide.Local, groupReader);
mkdir = false;
}
else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
{
AddTransfer(result, args);
args = null;
mkdir = true;
// For now, silently ignoring results (even errors)
// of mkdir operation, including future chmod/touch
}
else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
{
if (!mkdir)
{
if (args == null)
{
throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag upload"));
}
args.Chmod = ChmodEventArgs.Read(groupReader);
}
}
else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
{
if (!mkdir)
{
if (args == null)
{
throw Logger.WriteException(new InvalidOperationException("Tag touch before tag upload"));
}
args.Touch = TouchEventArgs.Read(groupReader);
}
}
}
AddTransfer(result, args);
}
return result;
}
}
public TransferOperationResult PutFilesToDirectory(
string localDirectory, string remoteDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
{
// Not locking, locked in PutFiles
using (Logger.CreateCallstack())
{
if (localDirectory == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
}
if (remoteDirectory == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
}
if (string.IsNullOrEmpty(filemask))
{
filemask = "*";
}
string localPath = Path.Combine(localDirectory, filemask);
const string remoteSeparator = "/";
string remotePath =
remoteDirectory +
(remoteDirectory.EndsWith(remoteSeparator, StringComparison.Ordinal) ? string.Empty : remoteSeparator);
return PutFiles(localPath, remotePath, remove, options);
}
}
public TransferEventArgs PutFileToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
{
// Not locking, locked in PutFiles (within PutFilesToDirectory)
using (Logger.CreateCallstack())
{
if (!File.Exists(localFilePath))
{
throw Logger.WriteException(new FileNotFoundException($"File {localFilePath} does not exist", localFilePath));
}
TransferOperationResult operationResult = PutEntryToDirectory(localFilePath, remoteDirectory, remove, options);
return GetOnlyFileOperation(operationResult.Transfers);
}
}
public void PutFile(Stream stream, string remoteFilePath, TransferOptions options = null)
{
using (Logger.CreateCallstackAndLock())
{
if (remoteFilePath == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(remoteFilePath)));
}
if (_process.StdIn != null)
{
throw Logger.WriteException(new InvalidOperationException("Already uploading from a stream"));
}
_process.StdIn = stream ?? throw Logger.WriteException(new ArgumentNullException(nameof(stream)));
try
{
remoteFilePath = RemotePath.EscapeOperationMask(remoteFilePath);
TransferOperationResult operationResult = DoPutFiles("-", remoteFilePath, false, options);
operationResult.Check();
// Assert that any transfer took place at all
GetOnlyFileOperation(operationResult.Transfers);
}
finally
{
_process.StdIn = null;
}
}
}
internal TransferOperationResult PutEntryToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
{
using (Logger.CreateCallstack())
{
if (string.IsNullOrEmpty(localFilePath))
{
throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(localFilePath)));
}
string localDirectory = Path.GetDirectoryName(localFilePath);
string filemask = Path.GetFileName(localFilePath);
TransferOperationResult operationResult = PutFilesToDirectory(localDirectory, remoteDirectory, filemask, remove, options);
operationResult.Check();
return operationResult;
}
}
private void AddTransfer(TransferOperationResult result, TransferEventArgs args)
{
if (args != null)
{
result.AddTransfer(args);
RaiseFileTransferredEvent(args);
}
}
public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
{
using (Logger.CreateCallstackAndLock())
{
return DoGetFiles(remotePath, localPath, remove, options, string.Empty);
}
}
private TransferOperationResult DoGetFiles(
string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
{
using (Logger.CreateCallstack())
{
StartGetCommand(remotePath, localPath, remove, options, additionalParams);
TransferOperationResult result = new TransferOperationResult();
using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
using (RegisterOperationResult(result))
using (CreateProgressHandler())
{
TransferEventArgs args = null;
while (groupReader.Read(0))
{
if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
{
AddTransfer(result, args);
args = TransferEventArgs.Read(ProgressSide.Remote, groupReader);
}
else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
{
// When "downloading and deleting" a folder,
// we get "rm" tag without preceeding "download" tag.
// So we use only the first "rm" tag after preceeding "download" tag,
// silently ignoring the others
if ((args != null) && (args.Removal == null))
{
args.Removal = RemovalEventArgs.Read(groupReader);
}
}
}
AddTransfer(result, args);
}
return result;
}
}
private void StartGetCommand(string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
{
if (options == null)
{
options = new TransferOptions();
}
CheckOpened();
WriteCommand(
string.Format(CultureInfo.InvariantCulture, "get {0} {1} {2} -- \"{3}\" \"{4}\"",
BooleanSwitch(remove, "delete"), options.ToSwitches(), additionalParams,
Tools.ArgumentEscape(remotePath), Tools.ArgumentEscape(localPath)));
}
public TransferOperationResult GetFilesToDirectory(
string remoteDirectory, string localDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
{
using (Logger.CreateCallstackAndLock())
{
return DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, null);
}
}
private TransferOperationResult DoGetFilesToDirectory(
string remoteDirectory, string localDirectory, string filemask, bool remove, TransferOptions options, string additionalParams)
{
using (Logger.CreateCallstack())
{
if (remoteDirectory == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
}
if (localDirectory == null)
{
throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
}
if (string.IsNullOrEmpty(filemask))
{
filemask = "*";
}
string remotePath = RemotePath.Combine(remoteDirectory, filemask);
if (!Directory.Exists(localDirectory))
{
throw Logger.WriteException(new DirectoryNotFoundException(localDirectory));
}
string localSeparator = Path.DirectorySeparatorChar.ToString();
string localPath =
localDirectory +
(localDirectory.EndsWith(localSeparator, StringComparison.Ordinal) ? string.Empty : localSeparator);
return DoGetFiles(remotePath, localPath, remove, options, additionalParams);
}
}
public TransferEventArgs GetFileToDirectory(string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null)
{
using (Logger.CreateCallstackAndLock())
{
const string additionalParams = "-onlyfile";
TransferOperationResult operationResult = GetEntryToDirectory(remoteFilePath, localDirectory, remove, options, additionalParams);
return GetOnlyFileOperation(operationResult.Transfers);
}
}
internal TransferOperationResult GetEntryToDirectory(
string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null, string additionalParams = null)
{
using (Logger.CreateCallstack())
{
ParseRemotePath(remoteFilePath, out string remoteDirectory, out string filemask);
TransferOperationResult operationResult =
DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, additionalParams ?? string.Empty);
operationResult.Check();
return operationResult;
}
}
private void ParseRemotePath(string remoteFilePath, out string remoteDirectory, out string filemask)
{
if (string.IsNullOrEmpty(remoteFilePath))