Session.cs 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Globalization;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. using System.Xml;
  9. #if !NETSTANDARD
  10. using Microsoft.Win32;
  11. #endif
  12. using System.Diagnostics;
  13. #if !NETSTANDARD
  14. using System.Security;
  15. #endif
  16. using System.Text.RegularExpressions;
  17. using System.Linq;
  18. namespace WinSCP
  19. {
  20. [Guid("38649D44-B839-4F2C-A9DC-5D45EEA4B5E9")]
  21. [ComVisible(true)]
  22. public enum SynchronizationMode
  23. {
  24. Local = 0,
  25. Remote = 1,
  26. Both = 2,
  27. }
  28. [Guid("3F770EC1-35F5-4A7B-A000-46A2F7A213D8")]
  29. [ComVisible(true)]
  30. [Flags]
  31. public enum SynchronizationCriteria
  32. {
  33. None = 0x00,
  34. Time = 0x01,
  35. Size = 0x02,
  36. Either = Time | Size,
  37. }
  38. [Guid("6C441F60-26AA-44FC-9B93-08884768507B")]
  39. [ComVisible(true)]
  40. [Flags]
  41. public enum EnumerationOptions
  42. {
  43. None = 0x00,
  44. AllDirectories = 0x01,
  45. MatchDirectories = 0x02,
  46. EnumerateDirectories = 0x04,
  47. }
  48. [Guid("16B6D8F6-C0B4-487D-9546-A25BBF582ED6")]
  49. [ComVisible(true)]
  50. public enum ProgressSide
  51. {
  52. Local = 0,
  53. Remote = 1,
  54. }
  55. public delegate void OutputDataReceivedEventHandler(object sender, OutputDataReceivedEventArgs e);
  56. public delegate void FileTransferredEventHandler(object sender, TransferEventArgs e);
  57. public delegate void FileTransferProgressEventHandler(object sender, FileTransferProgressEventArgs e);
  58. public delegate void FailedEventHandler(object sender, FailedEventArgs e);
  59. public delegate void QueryReceivedEventHandler(object sender, QueryReceivedEventArgs e);
  60. [Guid("56FFC5CE-3867-4EF0-A3B5-CFFBEB99EA35")]
  61. [ClassInterface(Constants.ClassInterface)]
  62. [ComVisible(true)]
  63. [ComSourceInterfaces(typeof(ISessionEvents))]
  64. public sealed class Session : IDisposable, IReflect
  65. {
  66. public string ExecutablePath { get { return _executablePath; } set { CheckNotOpened(); _executablePath = value; } }
  67. #if !NETSTANDARD
  68. public string ExecutableProcessUserName { get { return _executableProcessUserName; } set { CheckNotOpened(); _executableProcessUserName = value; } }
  69. public SecureString ExecutableProcessPassword { get { return _executableProcessPassword; } set { CheckNotOpened(); _executableProcessPassword = value; } }
  70. #endif
  71. public string AdditionalExecutableArguments { get { return _additionalExecutableArguments; } set { CheckNotOpened(); _additionalExecutableArguments = value; } }
  72. [Obsolete("Use AddRawConfiguration")]
  73. public bool DefaultConfiguration { get { return _defaultConfiguration; } set { CheckNotOpened(); _defaultConfiguration = value; } }
  74. public bool DisableVersionCheck { get { return _disableVersionCheck; } set { CheckNotOpened(); _disableVersionCheck = value; } }
  75. [Obsolete("Use AddRawConfiguration")]
  76. public string IniFilePath { get { return _iniFilePath; } set { CheckNotOpened(); _iniFilePath = value; } }
  77. public TimeSpan ReconnectTime { get { return _reconnectTime; } set { CheckNotOpened(); _reconnectTime = value; } }
  78. public int ReconnectTimeInMilliseconds { get { return Tools.TimeSpanToMilliseconds(ReconnectTime); } set { ReconnectTime = Tools.MillisecondsToTimeSpan(value); } }
  79. public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
  80. public int DebugLogLevel { get { CheckNotDisposed(); return Logger.LogLevel; } set { CheckNotDisposed(); Logger.LogLevel = value; } }
  81. public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
  82. public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
  83. public bool XmlLogPreserve { get; set; }
  84. #if DEBUG
  85. public bool GuardProcessWithJob { get { return GuardProcessWithJobInternal; } set { GuardProcessWithJobInternal = value; } }
  86. public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
  87. #endif
  88. public string HomePath { get { CheckOpened(); return _homePath; } }
  89. public TimeSpan Timeout { get; set; }
  90. public StringCollection Output { get; private set; }
  91. public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
  92. public event FileTransferredEventHandler FileTransferred;
  93. public event FailedEventHandler Failed;
  94. public event OutputDataReceivedEventHandler OutputDataReceived;
  95. public event FileTransferProgressEventHandler FileTransferProgress
  96. {
  97. add
  98. {
  99. using (CreateCallstackAndLock())
  100. {
  101. CheckNotOpened();
  102. _fileTransferProgress += value;
  103. }
  104. }
  105. remove
  106. {
  107. using (CreateCallstackAndLock())
  108. {
  109. CheckNotOpened();
  110. _fileTransferProgress -= value;
  111. }
  112. }
  113. }
  114. private IDisposable CreateCallstackAndLock()
  115. {
  116. var result = Logger.CreateCallstackAndLock();
  117. if ((_process != null) && (_process.StdOut != null))
  118. {
  119. result.Dispose();
  120. throw Logger.WriteException(new InvalidOperationException("Finish reading the stream from Session.GetFile first."));
  121. }
  122. return result;
  123. }
  124. public event QueryReceivedEventHandler QueryReceived { add { AddQueryReceived(value); } remove { RemoveQueryReceived(value); } }
  125. private void AddQueryReceived(QueryReceivedEventHandler value)
  126. {
  127. using (CreateCallstackAndLock())
  128. {
  129. bool send = (_queryReceived == null);
  130. _queryReceived += value;
  131. if (Opened && send)
  132. {
  133. SendOptionBatchCommand();
  134. WaitForGroup();
  135. }
  136. }
  137. }
  138. private void RemoveQueryReceived(QueryReceivedEventHandler value)
  139. {
  140. using (CreateCallstackAndLock())
  141. {
  142. if (_queryReceived != null)
  143. {
  144. _queryReceived -= value;
  145. if (Opened && (_queryReceived == null))
  146. {
  147. SendOptionBatchCommand();
  148. WaitForGroup();
  149. }
  150. }
  151. }
  152. }
  153. public Session()
  154. {
  155. Logger = new Logger();
  156. using (CreateCallstackAndLock())
  157. {
  158. Timeout = new TimeSpan(0, 1, 0);
  159. _reconnectTime = new TimeSpan(0, 2, 0); // keep in sync with TScript::OptionImpl
  160. ResetOutput();
  161. _operationResults = new List<OperationResultBase>();
  162. _events = new List<Action>();
  163. _eventsEvent = new AutoResetEvent(false);
  164. _choiceEvent = new ManualResetEvent(false);
  165. _disposed = false;
  166. _defaultConfiguration = true;
  167. _logUnique = 0;
  168. _guardProcessWithJob = true;
  169. RawConfiguration = new Dictionary<string, string>();
  170. }
  171. }
  172. private void ResetOutput()
  173. {
  174. Output = new StringCollection();
  175. _error = new StringCollection();
  176. }
  177. public void Dispose()
  178. {
  179. using (CreateCallstackAndLock())
  180. {
  181. _disposed = true;
  182. Cleanup();
  183. Logger.Dispose();
  184. if (_eventsEvent != null)
  185. {
  186. _eventsEvent.Close();
  187. _eventsEvent = null;
  188. }
  189. if (_choiceEvent != null)
  190. {
  191. _choiceEvent.Close();
  192. _choiceEvent = null;
  193. }
  194. GC.SuppressFinalize(this);
  195. }
  196. }
  197. public void Abort()
  198. {
  199. using (Logger.CreateCallstack())
  200. {
  201. CheckOpened();
  202. _aborted = true;
  203. // double-check
  204. if (_process != null)
  205. {
  206. _process.Abort();
  207. }
  208. }
  209. }
  210. public void Open(SessionOptions sessionOptions)
  211. {
  212. using (CreateCallstackAndLock())
  213. {
  214. CheckNotOpened();
  215. if (sessionOptions == null)
  216. {
  217. throw Logger.WriteException(new ArgumentNullException(nameof(sessionOptions)));
  218. }
  219. try
  220. {
  221. SetupTempPath();
  222. ResetOutput();
  223. _process = ExeSessionProcess.CreateForSession(this);
  224. _process.OutputDataReceived += ProcessOutputDataReceived;
  225. _process.Start();
  226. GotOutput();
  227. // setup batch mode
  228. SendOptionBatchCommand();
  229. WriteCommand("option confirm off");
  230. object reconnectTimeValue;
  231. if (ReconnectTime != TimeSpan.MaxValue)
  232. {
  233. reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
  234. }
  235. else
  236. {
  237. reconnectTimeValue = "off";
  238. }
  239. string reconnectTimeCommand =
  240. string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
  241. WriteCommand(reconnectTimeCommand);
  242. SessionOptionsToUrlAndSwitches(sessionOptions, false, out string command, out string log);
  243. const string openCommand = "open ";
  244. command = openCommand + command;
  245. log = openCommand + log;
  246. WriteCommand(command, log);
  247. Logger.WriteLine("Waiting for XML log file");
  248. // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
  249. do
  250. {
  251. string logExplanation;
  252. lock (Output)
  253. {
  254. if (_error.Count > 0)
  255. {
  256. logExplanation = GetErrorOutputMessage();
  257. }
  258. else if (Output.Count > 0)
  259. {
  260. logExplanation =
  261. string.Format(
  262. CultureInfo.CurrentCulture, "Output was \"{0}\". ", ListToString(Output));
  263. }
  264. else
  265. {
  266. logExplanation = "There was no output. ";
  267. }
  268. }
  269. logExplanation +=
  270. string.Format(CultureInfo.CurrentCulture,
  271. "Response log file {0} was not created. This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
  272. XmlLogPath);
  273. if (_process.HasExited && !File.Exists(XmlLogPath))
  274. {
  275. #if !NETSTANDARD
  276. Logger.WriteCounters();
  277. #endif
  278. Logger.WriteProcesses();
  279. _process.WriteStatus();
  280. string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
  281. if (_process.ExitCode < 0)
  282. {
  283. exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
  284. }
  285. throw Logger.WriteException(
  286. new SessionLocalException(this,
  287. string.Format(CultureInfo.CurrentCulture, "WinSCP process terminated with exit code {0}. ", exitCode) +
  288. logExplanation));
  289. }
  290. Thread.Sleep(50);
  291. CheckForTimeout(
  292. "WinSCP has not responded in time. " +
  293. logExplanation);
  294. } while (!File.Exists(XmlLogPath));
  295. Logger.WriteLine("XML log file created");
  296. _logReader = new SessionLogReader(this);
  297. _logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);
  298. // special variant of ElementLogReader that throws when closing element (</session>) is encountered
  299. _reader = new SessionElementLogReader(_logReader);
  300. // Skip "open" command <group>
  301. WaitForGroup();
  302. WriteCommand("pwd");
  303. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  304. using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
  305. {
  306. while (cwdReader.Read(0))
  307. {
  308. if (cwdReader.GetEmptyElementValue("cwd", out string value))
  309. {
  310. _homePath = value;
  311. }
  312. }
  313. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  314. }
  315. _sessionTimeout = sessionOptions.Timeout;
  316. }
  317. catch (Exception e)
  318. {
  319. Logger.WriteLine("Exception: {0}", e);
  320. Cleanup();
  321. throw;
  322. }
  323. }
  324. }
  325. private void SendOptionBatchCommand()
  326. {
  327. string command = string.Format(CultureInfo.InvariantCulture, "option batch {0}", (_queryReceived != null ? "off" : "on"));
  328. WriteCommand(command);
  329. }
  330. private void WaitForGroup()
  331. {
  332. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  333. {
  334. ReadElement(groupReader, LogReadFlags.ThrowFailures);
  335. }
  336. }
  337. internal string GetErrorOutputMessage()
  338. {
  339. string result = null;
  340. if (_error.Count > 0)
  341. {
  342. result = string.Format(CultureInfo.CurrentCulture, "Error output was \"{0}\". ", ListToString(_error));
  343. }
  344. return result;
  345. }
  346. private static string ListToString(StringCollection list)
  347. {
  348. string[] stringArray = new string[list.Count];
  349. list.CopyTo(stringArray, 0);
  350. string s = string.Join(Environment.NewLine, stringArray);
  351. return s;
  352. }
  353. public string ScanFingerprint(SessionOptions sessionOptions, string algorithm)
  354. {
  355. using (CreateCallstackAndLock())
  356. {
  357. string normalizeAlgorithm = NormalizeIdent(algorithm);
  358. if (string.IsNullOrEmpty(normalizeAlgorithm))
  359. {
  360. throw Logger.WriteException(new ArgumentException("Algorithm cannot be empty", nameof(algorithm)));
  361. }
  362. string result;
  363. CheckNotOpened();
  364. try
  365. {
  366. ResetOutput();
  367. SessionOptionsToUrlAndSwitches(sessionOptions, true, out string command, out string log);
  368. string additionalArguments = "/fingerprintscan " + command;
  369. _process = ExeSessionProcess.CreateForConsole(this, additionalArguments);
  370. _process.OutputDataReceived += ProcessOutputDataReceived;
  371. _process.Start();
  372. GotOutput();
  373. while (!_process.HasExited)
  374. {
  375. Thread.Sleep(50);
  376. CheckForTimeout();
  377. }
  378. if (_process.ExitCode == 0)
  379. {
  380. result = null;
  381. foreach (string s in Output)
  382. {
  383. int p = s.IndexOf(":", StringComparison.Ordinal);
  384. if (p < 0)
  385. {
  386. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Unexpected fingerprint scan result line '{0}'", s)));
  387. }
  388. string a = NormalizeIdent(s.Substring(0, p).Trim());
  389. if (normalizeAlgorithm.Equals(a, StringComparison.OrdinalIgnoreCase))
  390. {
  391. result = s.Substring(p + 1).Trim();
  392. break;
  393. }
  394. }
  395. if (result == null)
  396. {
  397. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Fingerprint for algorithm {0} not supported", algorithm)));
  398. }
  399. }
  400. else
  401. {
  402. throw Logger.WriteException(new SessionRemoteException(this, ListToString(Output)));
  403. }
  404. }
  405. catch (Exception e)
  406. {
  407. Logger.WriteLine("Exception: {0}", e);
  408. throw;
  409. }
  410. finally
  411. {
  412. Cleanup();
  413. }
  414. return result;
  415. }
  416. }
  417. private static string NormalizeIdent(string algorithm)
  418. {
  419. return algorithm.Replace("-", string.Empty);
  420. }
  421. public void Close()
  422. {
  423. using (CreateCallstackAndLock())
  424. {
  425. CheckOpened();
  426. Cleanup();
  427. }
  428. }
  429. public RemoteDirectoryInfo ListDirectory(string path)
  430. {
  431. using (CreateCallstackAndLock())
  432. {
  433. CheckOpened();
  434. WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", Tools.ArgumentEscape(IncludeTrailingSlash(path))));
  435. RemoteDirectoryInfo result = new RemoteDirectoryInfo();
  436. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  437. using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
  438. {
  439. string destination = null;
  440. if (lsReader.TryWaitForEmptyElement("destination", 0))
  441. {
  442. lsReader.GetEmptyElementValue("destination", out destination);
  443. }
  444. if ((destination != null) && lsReader.TryWaitForNonEmptyElement("files", 0))
  445. {
  446. destination = IncludeTrailingSlash(destination);
  447. using (ElementLogReader filesReader = lsReader.CreateLogReader())
  448. {
  449. while (filesReader.TryWaitForNonEmptyElement("file", 0))
  450. {
  451. RemoteFileInfo fileInfo = new RemoteFileInfo();
  452. using (ElementLogReader fileReader = filesReader.CreateLogReader())
  453. {
  454. while (fileReader.Read(0))
  455. {
  456. if (fileReader.GetEmptyElementValue("filename", out string value))
  457. {
  458. fileInfo.Name = value;
  459. fileInfo.FullName = destination + value;
  460. }
  461. else
  462. {
  463. ReadFile(fileInfo, fileReader);
  464. }
  465. }
  466. result.AddFile(fileInfo);
  467. }
  468. }
  469. }
  470. lsReader.ReadToEnd(LogReadFlags.ThrowFailures);
  471. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  472. }
  473. else
  474. {
  475. // "files" not found, keep reading, we expect "failure"
  476. // This happens only in case of fatal errors,
  477. // in case of normal error (non existing folder),
  478. // the "failure" is caught in "group" already, before the "ls".
  479. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  480. // only if not "failure", throw "files" not found
  481. throw Logger.WriteException(SessionLocalException.CreateElementNotFound(this, "files"));
  482. }
  483. }
  484. return result;
  485. }
  486. }
  487. private IEnumerable<RemoteFileInfo> DoEnumerateRemoteFiles(string path, Regex regex, EnumerationOptions options, bool throwReadErrors)
  488. {
  489. Logger.WriteLine("Starting enumeration of {0} ...", path);
  490. bool allDirectories = ((options & EnumerationOptions.AllDirectories) == EnumerationOptions.AllDirectories);
  491. bool matchDirectories = ((options & EnumerationOptions.MatchDirectories) == EnumerationOptions.MatchDirectories);
  492. bool enumerateDirectories = ((options & EnumerationOptions.EnumerateDirectories) == EnumerationOptions.EnumerateDirectories);
  493. if (enumerateDirectories && !allDirectories)
  494. {
  495. throw Logger.WriteException(new ArgumentException("Cannot use enumeration option EnumerateDirectories without AllDirectories"));
  496. }
  497. if (enumerateDirectories && matchDirectories)
  498. {
  499. throw Logger.WriteException(new ArgumentException("Cannot combine enumeration option EnumerateDirectories with MatchDirectories"));
  500. }
  501. RemoteDirectoryInfo directoryInfo;
  502. try
  503. {
  504. // Need to use guarded method for the listing, see a comment in EnumerateRemoteFiles
  505. directoryInfo = ListDirectory(path);
  506. }
  507. catch (SessionRemoteException)
  508. {
  509. if (throwReadErrors)
  510. {
  511. throw;
  512. }
  513. else
  514. {
  515. directoryInfo = null;
  516. }
  517. }
  518. if (directoryInfo != null)
  519. {
  520. foreach (RemoteFileInfo fileInfo in directoryInfo.Files)
  521. {
  522. if (!fileInfo.IsThisDirectory && !fileInfo.IsParentDirectory)
  523. {
  524. bool matches = regex.IsMatch(fileInfo.Name);
  525. bool enumerate;
  526. if (!fileInfo.IsDirectory)
  527. {
  528. enumerate = matches;
  529. }
  530. else
  531. {
  532. if (enumerateDirectories)
  533. {
  534. enumerate = true;
  535. }
  536. else if (matchDirectories)
  537. {
  538. enumerate = matches;
  539. }
  540. else
  541. {
  542. enumerate = false;
  543. }
  544. }
  545. if (enumerate)
  546. {
  547. Logger.WriteLine("Enumerating {0}", fileInfo.FullName);
  548. yield return fileInfo;
  549. }
  550. if (fileInfo.IsDirectory && allDirectories)
  551. {
  552. foreach (RemoteFileInfo fileInfo2 in DoEnumerateRemoteFiles(RemotePath.Combine(path, fileInfo.Name), regex, options, false))
  553. {
  554. yield return fileInfo2;
  555. }
  556. }
  557. }
  558. }
  559. }
  560. Logger.WriteLine("Ended enumeration of {0}", path);
  561. }
  562. public IEnumerable<RemoteFileInfo> EnumerateRemoteFiles(string path, string mask, EnumerationOptions options)
  563. {
  564. // Note that this method exits as soon as DoEnumerateRemoteFiles is entered,
  565. // so the Session object is not guarded during the whole enumeration.
  566. // Though it should not matter as it uses only guarded methods (ListDirectory)
  567. // for the actual work on the session
  568. using (CreateCallstackAndLock())
  569. {
  570. CheckOpened();
  571. Regex regex = MaskToRegex(mask);
  572. return new ImplicitEnumerable<RemoteFileInfo>(DoEnumerateRemoteFiles(path, regex, options, true));
  573. }
  574. }
  575. internal static Regex MaskToRegex(string mask)
  576. {
  577. if (string.IsNullOrEmpty(mask) ||
  578. // *.* has to match even filename without dot
  579. (mask == "*.*"))
  580. {
  581. mask = "*";
  582. }
  583. return
  584. new Regex(
  585. '^' +
  586. mask
  587. .Replace(".", "[.]")
  588. .Replace("*", ".*")
  589. .Replace("?", ".") +
  590. '$',
  591. RegexOptions.IgnoreCase);
  592. }
  593. public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
  594. {
  595. using (CreateCallstackAndLock())
  596. {
  597. return DoPutFiles(localPath, remotePath, remove, options);
  598. }
  599. }
  600. public TransferOperationResult DoPutFiles(string localPath, string remotePath, bool remove, TransferOptions options)
  601. {
  602. using (Logger.CreateCallstack())
  603. {
  604. if (options == null)
  605. {
  606. options = new TransferOptions();
  607. }
  608. CheckOpened();
  609. WriteCommand(
  610. string.Format(CultureInfo.InvariantCulture,
  611. "put {0} {1} -- \"{2}\" \"{3}\"",
  612. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  613. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  614. TransferOperationResult result = new TransferOperationResult();
  615. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  616. using (RegisterOperationResult(result))
  617. using (CreateProgressHandler())
  618. {
  619. TransferEventArgs args = null;
  620. bool mkdir = false;
  621. while (groupReader.Read(0))
  622. {
  623. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  624. {
  625. AddTransfer(result, args);
  626. args = TransferEventArgs.Read(ProgressSide.Local, groupReader);
  627. mkdir = false;
  628. }
  629. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  630. {
  631. AddTransfer(result, args);
  632. args = null;
  633. mkdir = true;
  634. // For now, silently ignoring results (even errors)
  635. // of mkdir operation, including future chmod/touch
  636. }
  637. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  638. {
  639. if (!mkdir)
  640. {
  641. if (args == null)
  642. {
  643. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag upload"));
  644. }
  645. args.Chmod = ChmodEventArgs.Read(groupReader);
  646. }
  647. }
  648. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  649. {
  650. if (!mkdir)
  651. {
  652. if (args == null)
  653. {
  654. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag upload"));
  655. }
  656. args.Touch = TouchEventArgs.Read(groupReader);
  657. }
  658. }
  659. }
  660. AddTransfer(result, args);
  661. }
  662. return result;
  663. }
  664. }
  665. public TransferOperationResult PutFilesToDirectory(
  666. string localDirectory, string remoteDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
  667. {
  668. // Not locking, locked in PutFiles
  669. using (Logger.CreateCallstack())
  670. {
  671. if (localDirectory == null)
  672. {
  673. throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
  674. }
  675. if (remoteDirectory == null)
  676. {
  677. throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
  678. }
  679. if (string.IsNullOrEmpty(filemask))
  680. {
  681. filemask = "*";
  682. }
  683. string localPath = Path.Combine(localDirectory, filemask);
  684. string remotePath = RemotePath.AddDirectorySeparator(remoteDirectory);
  685. return PutFiles(localPath, remotePath, remove, options);
  686. }
  687. }
  688. public TransferEventArgs PutFileToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
  689. {
  690. // Not locking, locked in PutFiles (within PutFilesToDirectory)
  691. using (Logger.CreateCallstack())
  692. {
  693. if (!File.Exists(localFilePath))
  694. {
  695. throw Logger.WriteException(new FileNotFoundException($"File {localFilePath} does not exist", localFilePath));
  696. }
  697. TransferOperationResult operationResult = PutEntryToDirectory(localFilePath, remoteDirectory, remove, options);
  698. return GetOnlyFileOperation(operationResult.Transfers);
  699. }
  700. }
  701. public void PutFile(Stream stream, string remoteFilePath, TransferOptions options = null)
  702. {
  703. using (CreateCallstackAndLock())
  704. {
  705. if (remoteFilePath == null)
  706. {
  707. throw Logger.WriteException(new ArgumentNullException(nameof(remoteFilePath)));
  708. }
  709. if (_process.StdIn != null)
  710. {
  711. throw Logger.WriteException(new InvalidOperationException("Already uploading from a stream"));
  712. }
  713. _process.StdIn = stream ?? throw Logger.WriteException(new ArgumentNullException(nameof(stream)));
  714. try
  715. {
  716. remoteFilePath = RemotePath.EscapeOperationMask(remoteFilePath);
  717. TransferOperationResult operationResult = DoPutFiles("-", remoteFilePath, false, options);
  718. operationResult.Check();
  719. // Assert that any transfer took place at all
  720. GetOnlyFileOperation(operationResult.Transfers);
  721. }
  722. finally
  723. {
  724. _process.StdIn = null;
  725. }
  726. }
  727. }
  728. internal TransferOperationResult PutEntryToDirectory(string localFilePath, string remoteDirectory, bool remove = false, TransferOptions options = null)
  729. {
  730. using (Logger.CreateCallstack())
  731. {
  732. if (string.IsNullOrEmpty(localFilePath))
  733. {
  734. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(localFilePath)));
  735. }
  736. string localDirectory = Path.GetDirectoryName(localFilePath);
  737. string filemask = Path.GetFileName(localFilePath);
  738. TransferOperationResult operationResult = PutFilesToDirectory(localDirectory, remoteDirectory, filemask, remove, options);
  739. operationResult.Check();
  740. return operationResult;
  741. }
  742. }
  743. private void AddTransfer(TransferOperationResult result, TransferEventArgs args)
  744. {
  745. if (args != null)
  746. {
  747. result.AddTransfer(args);
  748. RaiseFileTransferredEvent(args);
  749. }
  750. }
  751. public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
  752. {
  753. using (CreateCallstackAndLock())
  754. {
  755. return DoGetFiles(remotePath, localPath, remove, options, string.Empty);
  756. }
  757. }
  758. private TransferOperationResult DoGetFiles(
  759. string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
  760. {
  761. using (Logger.CreateCallstack())
  762. {
  763. StartGetCommand(remotePath, localPath, remove, options, additionalParams);
  764. TransferOperationResult result = new TransferOperationResult();
  765. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  766. using (RegisterOperationResult(result))
  767. using (CreateProgressHandler())
  768. {
  769. TransferEventArgs args = null;
  770. while (groupReader.Read(0))
  771. {
  772. if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  773. {
  774. AddTransfer(result, args);
  775. args = TransferEventArgs.Read(ProgressSide.Remote, groupReader);
  776. }
  777. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  778. {
  779. // When "downloading and deleting" a folder,
  780. // we get "rm" tag without preceeding "download" tag.
  781. // So we use only the first "rm" tag after preceeding "download" tag,
  782. // silently ignoring the others
  783. if ((args != null) && (args.Removal == null))
  784. {
  785. args.Removal = RemovalEventArgs.Read(groupReader);
  786. }
  787. }
  788. }
  789. AddTransfer(result, args);
  790. }
  791. return result;
  792. }
  793. }
  794. private void StartGetCommand(string remotePath, string localPath, bool remove, TransferOptions options, string additionalParams)
  795. {
  796. if (options == null)
  797. {
  798. options = new TransferOptions();
  799. }
  800. CheckOpened();
  801. WriteCommand(
  802. string.Format(CultureInfo.InvariantCulture, "get {0} {1} {2} -- \"{3}\" \"{4}\"",
  803. BooleanSwitch(remove, "delete"), options.ToSwitches(), additionalParams,
  804. Tools.ArgumentEscape(remotePath), Tools.ArgumentEscape(localPath)));
  805. }
  806. public TransferOperationResult GetFilesToDirectory(
  807. string remoteDirectory, string localDirectory, string filemask = null, bool remove = false, TransferOptions options = null)
  808. {
  809. using (CreateCallstackAndLock())
  810. {
  811. return DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, null);
  812. }
  813. }
  814. private TransferOperationResult DoGetFilesToDirectory(
  815. string remoteDirectory, string localDirectory, string filemask, bool remove, TransferOptions options, string additionalParams)
  816. {
  817. using (Logger.CreateCallstack())
  818. {
  819. if (remoteDirectory == null)
  820. {
  821. throw Logger.WriteException(new ArgumentNullException(nameof(remoteDirectory)));
  822. }
  823. if (localDirectory == null)
  824. {
  825. throw Logger.WriteException(new ArgumentNullException(nameof(localDirectory)));
  826. }
  827. if (string.IsNullOrEmpty(filemask))
  828. {
  829. filemask = "*";
  830. }
  831. string remotePath = RemotePath.Combine(remoteDirectory, filemask);
  832. if (!Directory.Exists(localDirectory))
  833. {
  834. throw Logger.WriteException(new DirectoryNotFoundException(localDirectory));
  835. }
  836. string localSeparator = Path.DirectorySeparatorChar.ToString();
  837. string localPath =
  838. localDirectory +
  839. (localDirectory.EndsWith(localSeparator, StringComparison.Ordinal) ? string.Empty : localSeparator);
  840. return DoGetFiles(remotePath, localPath, remove, options, additionalParams);
  841. }
  842. }
  843. public TransferEventArgs GetFileToDirectory(string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null)
  844. {
  845. using (CreateCallstackAndLock())
  846. {
  847. const string additionalParams = "-onlyfile";
  848. TransferOperationResult operationResult = GetEntryToDirectory(remoteFilePath, localDirectory, remove, options, additionalParams);
  849. return GetOnlyFileOperation(operationResult.Transfers);
  850. }
  851. }
  852. internal TransferOperationResult GetEntryToDirectory(
  853. string remoteFilePath, string localDirectory, bool remove = false, TransferOptions options = null, string additionalParams = null)
  854. {
  855. using (Logger.CreateCallstack())
  856. {
  857. ParseRemotePath(remoteFilePath, out string remoteDirectory, out string filemask);
  858. TransferOperationResult operationResult =
  859. DoGetFilesToDirectory(remoteDirectory, localDirectory, filemask, remove, options, additionalParams ?? string.Empty);
  860. operationResult.Check();
  861. return operationResult;
  862. }
  863. }
  864. private void ParseRemotePath(string remoteFilePath, out string remoteDirectory, out string filemask)
  865. {
  866. if (string.IsNullOrEmpty(remoteFilePath))
  867. {
  868. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(remoteFilePath)));
  869. }
  870. remoteDirectory = RemotePath.GetDirectoryName(remoteFilePath);
  871. filemask = RemotePath.EscapeFileMask(RemotePath.GetFileName(remoteFilePath));
  872. }
  873. private T GetOnlyFileOperation<T>(ICollection<T> operations)
  874. {
  875. // For "get", this should happen only when the filename is mask-like, otherwise "get" throws straight away.
  876. // For "put", this should not happen.
  877. if (operations.Count == 0)
  878. {
  879. throw Logger.WriteException(new FileNotFoundException("File not found"));
  880. }
  881. if (operations.Count > 1)
  882. {
  883. throw Logger.WriteException(new InvalidOperationException("More then one file has been unexpectedly found"));
  884. }
  885. return operations.First();
  886. }
  887. public Stream GetFile(string remoteFilePath, TransferOptions options = null)
  888. {
  889. using (CreateCallstackAndLock())
  890. {
  891. const string additionalParams = "-onlyfile";
  892. ParseRemotePath(remoteFilePath, out string remoteDirectory, out string filemask);
  893. string remotePath = RemotePath.Combine(remoteDirectory, filemask);
  894. // only to collect failures
  895. TransferOperationResult result = new TransferOperationResult();
  896. ElementLogReader groupReader = null;
  897. IDisposable operationResultGuard = null;
  898. IDisposable progressHandler = null;
  899. // should never happen
  900. if (_process.StdOut != null)
  901. {
  902. throw Logger.WriteException(new InvalidOperationException("Data stream already exist"));
  903. }
  904. PipeStream stream = new PipeStream();
  905. _process.StdOut = stream;
  906. void onGetEnd()
  907. {
  908. using (Logger.CreateCallstack())
  909. {
  910. try
  911. {
  912. // This can throw
  913. progressHandler?.Dispose();
  914. }
  915. finally
  916. {
  917. try
  918. {
  919. groupReader?.Dispose();
  920. }
  921. finally
  922. {
  923. _process.StdOut = null;
  924. // Only after disposing the group reader, so when called from onGetEndWithExit, the Check() has all failures.
  925. operationResultGuard?.Dispose();
  926. }
  927. }
  928. }
  929. }
  930. void onGetEndWithExit()
  931. {
  932. // Explicitly not Session.CreateCallstackAndLock
  933. using (Logger.CreateCallstackAndLock())
  934. {
  935. Logger.WriteLine("Closing download stream");
  936. try
  937. {
  938. onGetEnd();
  939. }
  940. finally
  941. {
  942. Logger.WriteLine("Closed download stream");
  943. result.Check();
  944. }
  945. }
  946. }
  947. try
  948. {
  949. StartGetCommand(remotePath, "-", false, options, additionalParams);
  950. groupReader = _reader.WaitForGroupAndCreateLogReader();
  951. operationResultGuard = RegisterOperationResult(result);
  952. progressHandler = CreateProgressHandler();
  953. if (_throwStdOut)
  954. {
  955. throw Logger.WriteException(new InvalidOperationException());
  956. }
  957. _throwStdOut = true;
  958. bool downloadFound;
  959. try
  960. {
  961. // Not using WaitForNonEmptyElement only to allow throwing better exception message below.
  962. // Not using ThrowFailures as we need to return the stream, if there's <download>,
  963. // even if there's a <failure> as well.
  964. downloadFound = groupReader.TryWaitForNonEmptyElement(TransferEventArgs.DownloadTag, 0);
  965. }
  966. catch (StdOutException)
  967. {
  968. downloadFound = true;
  969. }
  970. finally
  971. {
  972. _throwStdOut = false;
  973. }
  974. if (downloadFound)
  975. {
  976. Logger.WriteLine("Download stream started");
  977. stream.OnDispose = onGetEndWithExit;
  978. return stream;
  979. }
  980. else
  981. {
  982. // First throw any specific error from <failure>
  983. result.Check();
  984. // And only then fallback to the generic one.
  985. // See also the comment in GetOnlyFileOperation.
  986. throw Logger.WriteException(new FileNotFoundException("File not found"));
  987. }
  988. }
  989. catch
  990. {
  991. onGetEnd();
  992. throw;
  993. }
  994. }
  995. }
  996. public RemovalOperationResult RemoveFiles(string path)
  997. {
  998. using (CreateCallstackAndLock())
  999. {
  1000. return DoRemoveFiles(path, string.Empty);
  1001. }
  1002. }
  1003. private RemovalOperationResult DoRemoveFiles(string path, string additionalParams)
  1004. {
  1005. using (Logger.CreateCallstack())
  1006. {
  1007. CheckOpened();
  1008. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm {0} -- \"{1}\"", additionalParams, Tools.ArgumentEscape(path)));
  1009. RemovalOperationResult result = new RemovalOperationResult();
  1010. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1011. using (RegisterOperationResult(result))
  1012. {
  1013. while (groupReader.Read(0))
  1014. {
  1015. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  1016. {
  1017. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  1018. }
  1019. }
  1020. }
  1021. return result;
  1022. }
  1023. }
  1024. public RemovalEventArgs RemoveFile(string path)
  1025. {
  1026. using (CreateCallstackAndLock())
  1027. {
  1028. RemovalOperationResult operationResult = RemoveEntry(path, "-onlyfile");
  1029. return GetOnlyFileOperation(operationResult.Removals);
  1030. }
  1031. }
  1032. internal RemovalOperationResult RemoveEntry(string path, string additionalParams = null)
  1033. {
  1034. using (Logger.CreateCallstack())
  1035. {
  1036. if (string.IsNullOrEmpty(path))
  1037. {
  1038. throw Logger.WriteException(new ArgumentException("File to path cannot be empty", nameof(path)));
  1039. }
  1040. string remoteDirectory = RemotePath.GetDirectoryName(path);
  1041. string filemask = RemotePath.EscapeFileMask(RemotePath.GetFileName(path));
  1042. if (string.IsNullOrEmpty(filemask))
  1043. {
  1044. throw Logger.WriteException(new ArgumentException("File name cannot be empty", nameof(path)));
  1045. }
  1046. path = RemotePath.Combine(remoteDirectory, filemask);
  1047. RemovalOperationResult operationResult = DoRemoveFiles(path, additionalParams ?? string.Empty);
  1048. operationResult.Check();
  1049. return operationResult;
  1050. }
  1051. }
  1052. public SynchronizationResult SynchronizeDirectories(
  1053. SynchronizationMode mode, string localPath, string remotePath,
  1054. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1055. TransferOptions options = null)
  1056. {
  1057. using (CreateCallstackAndLock())
  1058. {
  1059. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, string.Empty);
  1060. return ReadSynchronizeDirectories();
  1061. }
  1062. }
  1063. private void DoSynchronizeDirectories(
  1064. SynchronizationMode mode, string localPath, string remotePath, bool removeFiles, bool mirror,
  1065. SynchronizationCriteria criteria, TransferOptions options, string additionalParameters)
  1066. {
  1067. if (options == null)
  1068. {
  1069. options = new TransferOptions();
  1070. }
  1071. CheckOpened();
  1072. if (removeFiles && (mode == SynchronizationMode.Both))
  1073. {
  1074. throw Logger.WriteException(new ArgumentException("Cannot delete files in synchronization mode Both"));
  1075. }
  1076. if (mirror && (mode == SynchronizationMode.Both))
  1077. {
  1078. throw Logger.WriteException(new ArgumentException("Cannot mirror files in synchronization mode Both"));
  1079. }
  1080. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  1081. {
  1082. throw Logger.WriteException(new ArgumentException("Only Time criteria is allowed in synchronization mode Both"));
  1083. }
  1084. string modeName;
  1085. switch (mode)
  1086. {
  1087. case SynchronizationMode.Local:
  1088. modeName = "local";
  1089. break;
  1090. case SynchronizationMode.Remote:
  1091. modeName = "remote";
  1092. break;
  1093. case SynchronizationMode.Both:
  1094. modeName = "both";
  1095. break;
  1096. default:
  1097. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(mode)));
  1098. }
  1099. string criteriaName;
  1100. switch (criteria)
  1101. {
  1102. case SynchronizationCriteria.None:
  1103. criteriaName = "none";
  1104. break;
  1105. case SynchronizationCriteria.Time:
  1106. criteriaName = "time";
  1107. break;
  1108. case SynchronizationCriteria.Size:
  1109. criteriaName = "size";
  1110. break;
  1111. case SynchronizationCriteria.Either:
  1112. criteriaName = "either";
  1113. break;
  1114. default:
  1115. throw Logger.WriteException(new ArgumentOutOfRangeException(nameof(criteria)));
  1116. }
  1117. WriteCommand(
  1118. string.Format(CultureInfo.InvariantCulture,
  1119. "synchronize {0} {1} {2} {3} -criteria=\"{4}\" {5} -- \"{6}\" \"{7}\"",
  1120. modeName,
  1121. BooleanSwitch(removeFiles, "delete"),
  1122. BooleanSwitch(mirror, "mirror"),
  1123. options.ToSwitches(),
  1124. criteriaName,
  1125. additionalParameters,
  1126. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  1127. }
  1128. private SynchronizationResult ReadSynchronizeDirectories()
  1129. {
  1130. using (Logger.CreateCallstack())
  1131. {
  1132. SynchronizationResult result = new SynchronizationResult();
  1133. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1134. using (RegisterOperationResult(result))
  1135. using (CreateProgressHandler())
  1136. {
  1137. TransferEventArgs transfer = null;
  1138. bool mkdir = false;
  1139. while (groupReader.Read(0))
  1140. {
  1141. ProgressSide? newSide = null;
  1142. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  1143. {
  1144. newSide = ProgressSide.Local;
  1145. }
  1146. else if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  1147. {
  1148. newSide = ProgressSide.Remote;
  1149. }
  1150. if (newSide.HasValue)
  1151. {
  1152. AddSynchronizationTransfer(result, transfer);
  1153. transfer = TransferEventArgs.Read(newSide.Value, groupReader);
  1154. mkdir = false;
  1155. }
  1156. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  1157. {
  1158. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  1159. }
  1160. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  1161. {
  1162. AddSynchronizationTransfer(result, transfer);
  1163. transfer = null;
  1164. mkdir = true;
  1165. // For now, silently ignoring results (even errors)
  1166. // of mkdir operation, including future chmod/touch
  1167. }
  1168. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  1169. {
  1170. if (!mkdir)
  1171. {
  1172. if (transfer == null)
  1173. {
  1174. throw Logger.WriteException(new InvalidOperationException("Tag chmod before tag download"));
  1175. }
  1176. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  1177. }
  1178. }
  1179. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  1180. {
  1181. if (!mkdir)
  1182. {
  1183. if (transfer == null)
  1184. {
  1185. throw Logger.WriteException(new InvalidOperationException("Tag touch before tag download"));
  1186. }
  1187. transfer.Touch = TouchEventArgs.Read(groupReader);
  1188. }
  1189. }
  1190. }
  1191. AddSynchronizationTransfer(result, transfer);
  1192. }
  1193. return result;
  1194. }
  1195. }
  1196. public ComparisonDifferenceCollection CompareDirectories(
  1197. SynchronizationMode mode, string localPath, string remotePath,
  1198. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  1199. TransferOptions options = null)
  1200. {
  1201. using (CreateCallstackAndLock())
  1202. {
  1203. DoSynchronizeDirectories(mode, localPath, remotePath, removeFiles, mirror, criteria, options, "-preview");
  1204. return ReadCompareDirectories(localPath, remotePath);
  1205. }
  1206. }
  1207. private ComparisonDifferenceCollection ReadCompareDirectories(string localPath, string remotePath)
  1208. {
  1209. using (Logger.CreateCallstack())
  1210. {
  1211. ComparisonDifferenceCollection result = new ComparisonDifferenceCollection();
  1212. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1213. {
  1214. while (groupReader.TryWaitForNonEmptyElement("difference", LogReadFlags.ThrowFailures))
  1215. {
  1216. using (ElementLogReader differenceReader = groupReader.CreateLogReader())
  1217. {
  1218. ComparisonDifference difference = new ComparisonDifference(localPath, remotePath);
  1219. ComparisonFileInfo current = null;
  1220. while (differenceReader.Read(0))
  1221. {
  1222. if (differenceReader.GetEmptyElementValue("action", out string actionName))
  1223. {
  1224. if ((difference.Local != null) || (difference.Remote != null))
  1225. {
  1226. throw Logger.WriteException(new InvalidOperationException("Tag action after filename"));
  1227. }
  1228. if (actionName.Equals("uploadnew", StringComparison.OrdinalIgnoreCase))
  1229. {
  1230. difference.Action = SynchronizationAction.UploadNew;
  1231. difference.Local = new ComparisonFileInfo();
  1232. }
  1233. else if (actionName.Equals("downloadnew", StringComparison.OrdinalIgnoreCase))
  1234. {
  1235. difference.Action = SynchronizationAction.DownloadNew;
  1236. difference.Remote = new ComparisonFileInfo();
  1237. }
  1238. else if (actionName.Equals("uploadupdate", StringComparison.OrdinalIgnoreCase))
  1239. {
  1240. difference.Action = SynchronizationAction.UploadUpdate;
  1241. difference.Local = new ComparisonFileInfo();
  1242. difference.Remote = new ComparisonFileInfo();
  1243. }
  1244. else if (actionName.Equals("downloadupdate", StringComparison.OrdinalIgnoreCase))
  1245. {
  1246. difference.Action = SynchronizationAction.DownloadUpdate;
  1247. difference.Remote = new ComparisonFileInfo();
  1248. difference.Local = new ComparisonFileInfo();
  1249. }
  1250. else if (actionName.Equals("deleteremote", StringComparison.OrdinalIgnoreCase))
  1251. {
  1252. difference.Action = SynchronizationAction.DeleteRemote;
  1253. difference.Remote = new ComparisonFileInfo();
  1254. }
  1255. else if (actionName.Equals("deletelocal", StringComparison.OrdinalIgnoreCase))
  1256. {
  1257. difference.Action = SynchronizationAction.DeleteLocal;
  1258. difference.Local = new ComparisonFileInfo();
  1259. }
  1260. else
  1261. {
  1262. throw Logger.WriteException(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Unknown synchronization action \"{0}\"", actionName)));
  1263. }
  1264. }
  1265. else if (differenceReader.GetEmptyElementValue("type", out string fileType))
  1266. {
  1267. difference.IsDirectory = (fileType.Length == 1) && RemoteFileInfo.IsDirectoryFileType(fileType[0]);
  1268. }
  1269. else if (differenceReader.GetEmptyElementValue("filename", out string value))
  1270. {
  1271. if (current == null)
  1272. {
  1273. current = difference.Local ?? difference.Remote;
  1274. }
  1275. else if (current == difference.Local)
  1276. {
  1277. current = difference.Remote;
  1278. }
  1279. if (current == null)
  1280. {
  1281. throw Logger.WriteException(new InvalidOperationException("Unexpected filename tag"));
  1282. }
  1283. current.FileName = value;
  1284. }
  1285. else if (differenceReader.GetEmptyElementValue("modification", out value))
  1286. {
  1287. if (current == null)
  1288. {
  1289. throw Logger.WriteException(new InvalidOperationException("Unexpected modification tag"));
  1290. }
  1291. current.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1292. }
  1293. else if (differenceReader.GetEmptyElementValue("size", out value))
  1294. {
  1295. if (current == null)
  1296. {
  1297. throw Logger.WriteException(new InvalidOperationException("Unexpected size tag"));
  1298. }
  1299. current.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1300. }
  1301. }
  1302. if (difference.Action == default)
  1303. {
  1304. throw Logger.WriteException(new InvalidOperationException("No action tag found"));
  1305. }
  1306. if (((difference.Local != null) && string.IsNullOrEmpty(difference.Local.FileName)) ||
  1307. ((difference.Remote != null) && string.IsNullOrEmpty(difference.Remote.FileName)))
  1308. {
  1309. throw Logger.WriteException(new InvalidOperationException("Missing file information"));
  1310. }
  1311. result.InternalAdd(difference);
  1312. }
  1313. }
  1314. }
  1315. return result;
  1316. }
  1317. }
  1318. public CommandExecutionResult ExecuteCommand(string command)
  1319. {
  1320. using (CreateCallstackAndLock())
  1321. {
  1322. CheckOpened();
  1323. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  1324. CommandExecutionResult result = new CommandExecutionResult();
  1325. // registering before creating group reader, so that
  1326. // it is still registered, when group reader is read to the end in its .Dispose();
  1327. using (RegisterOperationResult(result))
  1328. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1329. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  1330. {
  1331. while (callReader.Read(0))
  1332. {
  1333. if (callReader.GetEmptyElementValue("output", out string value))
  1334. {
  1335. result.Output = value;
  1336. }
  1337. if (callReader.GetEmptyElementValue("erroroutput", out value))
  1338. {
  1339. result.ErrorOutput = value;
  1340. }
  1341. if (callReader.GetEmptyElementValue("exitcode", out value))
  1342. {
  1343. result.ExitCode = int.Parse(value, CultureInfo.InvariantCulture);
  1344. }
  1345. }
  1346. }
  1347. return result;
  1348. }
  1349. }
  1350. public RemoteFileInfo GetFileInfo(string path)
  1351. {
  1352. using (CreateCallstackAndLock())
  1353. {
  1354. CheckOpened();
  1355. return DoGetFileInfo(path);
  1356. }
  1357. }
  1358. public bool FileExists(string path)
  1359. {
  1360. using (CreateCallstackAndLock())
  1361. {
  1362. CheckOpened();
  1363. try
  1364. {
  1365. _ignoreFailed = true;
  1366. try
  1367. {
  1368. DoGetFileInfo(path);
  1369. }
  1370. finally
  1371. {
  1372. _ignoreFailed = false;
  1373. }
  1374. return true;
  1375. }
  1376. catch (SessionRemoteException)
  1377. {
  1378. return false;
  1379. }
  1380. }
  1381. }
  1382. public byte[] CalculateFileChecksum(string algorithm, string path)
  1383. {
  1384. using (CreateCallstackAndLock())
  1385. {
  1386. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  1387. string hex = null;
  1388. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1389. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  1390. {
  1391. while (checksumReader.Read(0))
  1392. {
  1393. if (checksumReader.GetEmptyElementValue("checksum", out string value))
  1394. {
  1395. hex = value;
  1396. }
  1397. }
  1398. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1399. }
  1400. int len = hex.Length;
  1401. if ((len % 2) != 0)
  1402. {
  1403. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  1404. throw Logger.WriteException(new SessionLocalException(this, error));
  1405. }
  1406. int count = len / 2;
  1407. byte[] bytes = new byte[count];
  1408. for (int i = 0; i < count; i++)
  1409. {
  1410. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  1411. }
  1412. return bytes;
  1413. }
  1414. }
  1415. public void CreateDirectory(string path)
  1416. {
  1417. using (CreateCallstackAndLock())
  1418. {
  1419. CheckOpened();
  1420. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  1421. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1422. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  1423. {
  1424. ReadElement(mkdirReader, 0);
  1425. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1426. }
  1427. }
  1428. }
  1429. public void MoveFile(string sourcePath, string targetPath)
  1430. {
  1431. using (CreateCallstackAndLock())
  1432. {
  1433. CheckOpened();
  1434. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  1435. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1436. {
  1437. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  1438. {
  1439. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1440. }
  1441. else
  1442. {
  1443. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  1444. {
  1445. ReadElement(mvReader, 0);
  1446. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. }
  1452. public void DuplicateFile(string sourcePath, string targetPath)
  1453. {
  1454. using (CreateCallstackAndLock())
  1455. {
  1456. CheckOpened();
  1457. string sourceArgument = Tools.ArgumentEscape(RemotePath.EscapeFileMask(sourcePath));
  1458. string targetArgument = Tools.ArgumentEscape(targetPath);
  1459. string command = string.Format(CultureInfo.InvariantCulture, "cp \"{0}\" \"{1}\"", sourceArgument, targetArgument);
  1460. WriteCommand(command);
  1461. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1462. {
  1463. if (!groupReader.TryWaitForNonEmptyElement("cp", LogReadFlags.ThrowFailures))
  1464. {
  1465. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1466. }
  1467. else
  1468. {
  1469. using (ElementLogReader cpReader = groupReader.CreateLogReader())
  1470. {
  1471. ReadElement(cpReader, 0);
  1472. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1473. }
  1474. }
  1475. }
  1476. }
  1477. }
  1478. [Obsolete("Use RemotePath.EscapeFileMask")]
  1479. public string EscapeFileMask(string fileMask)
  1480. {
  1481. return RemotePath.EscapeFileMask(fileMask);
  1482. }
  1483. [Obsolete("Use RemotePath.TranslateRemotePathToLocal")]
  1484. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  1485. {
  1486. return RemotePath.TranslateRemotePathToLocal(remotePath, remoteRoot, localRoot);
  1487. }
  1488. [Obsolete("Use RemotePath.TranslateLocalPathToRemote")]
  1489. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  1490. {
  1491. return RemotePath.TranslateLocalPathToRemote(localPath, localRoot, remoteRoot);
  1492. }
  1493. [Obsolete("Use RemotePath.CombinePaths")]
  1494. public string CombinePaths(string path1, string path2)
  1495. {
  1496. return RemotePath.Combine(path1, path2);
  1497. }
  1498. public void AddRawConfiguration(string setting, string value)
  1499. {
  1500. CheckNotOpened();
  1501. RawConfiguration.Add(setting, value);
  1502. }
  1503. #if !NETSTANDARD
  1504. [ComRegisterFunction]
  1505. private static void ComRegister(Type t)
  1506. {
  1507. string subKey = GetTypeLibKey(t);
  1508. Assembly assembly = Assembly.GetAssembly(t);
  1509. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  1510. if (attributes.Length == 0)
  1511. {
  1512. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  1513. }
  1514. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  1515. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  1516. }
  1517. [ComUnregisterFunction]
  1518. private static void ComUnregister(Type t)
  1519. {
  1520. string subKey = GetTypeLibKey(t);
  1521. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  1522. }
  1523. #endif
  1524. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  1525. {
  1526. using (Logger.CreateCallstack())
  1527. {
  1528. if (fileReader.GetEmptyElementValue("type", out string value))
  1529. {
  1530. fileInfo.FileType = value[0];
  1531. }
  1532. else if (fileReader.GetEmptyElementValue("size", out value))
  1533. {
  1534. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1535. }
  1536. else if (fileReader.GetEmptyElementValue("modification", out value))
  1537. {
  1538. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1539. }
  1540. else if (fileReader.GetEmptyElementValue("permissions", out value))
  1541. {
  1542. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  1543. }
  1544. else if (fileReader.GetEmptyElementValue("owner", out value))
  1545. {
  1546. fileInfo.Owner = value;
  1547. }
  1548. else if (fileReader.GetEmptyElementValue("group", out value))
  1549. {
  1550. fileInfo.Group = value;
  1551. }
  1552. }
  1553. }
  1554. internal static string BooleanSwitch(bool flag, string name)
  1555. {
  1556. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1557. }
  1558. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1559. {
  1560. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1561. }
  1562. private void AddSynchronizationTransfer(SynchronizationResult result, TransferEventArgs transfer)
  1563. {
  1564. if (transfer != null)
  1565. {
  1566. if (transfer.Side == ProgressSide.Local)
  1567. {
  1568. result.AddUpload(transfer);
  1569. }
  1570. else
  1571. {
  1572. result.AddDownload(transfer);
  1573. }
  1574. RaiseFileTransferredEvent(transfer);
  1575. }
  1576. }
  1577. private static string IncludeTrailingSlash(string path)
  1578. {
  1579. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1580. {
  1581. path += '/';
  1582. }
  1583. return path;
  1584. }
  1585. private void Cleanup()
  1586. {
  1587. using (Logger.CreateCallstack())
  1588. {
  1589. if (_process != null)
  1590. {
  1591. Logger.WriteLine("Terminating process");
  1592. try
  1593. {
  1594. try
  1595. {
  1596. WriteCommand("exit");
  1597. _process.Close();
  1598. }
  1599. finally
  1600. {
  1601. _process.Dispose();
  1602. _process = null;
  1603. }
  1604. }
  1605. catch (Exception e)
  1606. {
  1607. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1608. }
  1609. }
  1610. Logger.WriteLine("Disposing log readers");
  1611. if (_reader != null)
  1612. {
  1613. _reader.Dispose();
  1614. _reader = null;
  1615. }
  1616. if (_logReader != null)
  1617. {
  1618. _logReader.Dispose();
  1619. _logReader = null;
  1620. }
  1621. // Cleanup log file
  1622. if ((XmlLogPath != null) && File.Exists(XmlLogPath) && !XmlLogPreserve)
  1623. {
  1624. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1625. try
  1626. {
  1627. File.Delete(XmlLogPath);
  1628. }
  1629. catch (DirectoryNotFoundException e)
  1630. {
  1631. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1632. }
  1633. catch (IOException e)
  1634. {
  1635. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1636. }
  1637. catch (UnauthorizedAccessException e)
  1638. {
  1639. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1640. }
  1641. _xmlLogPath = null;
  1642. }
  1643. }
  1644. }
  1645. private void WriteCommand(string command)
  1646. {
  1647. WriteCommand(command, command);
  1648. }
  1649. private void WriteCommand(string command, string log)
  1650. {
  1651. Logger.WriteLine("Command: [{0}]", log);
  1652. _process.ExecuteCommand(command, log);
  1653. GotOutput();
  1654. }
  1655. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1656. {
  1657. while (reader.Read(flags))
  1658. {
  1659. }
  1660. }
  1661. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1662. {
  1663. using (Logger.CreateCallstack())
  1664. {
  1665. if (sessionOptions.WebdavSecure)
  1666. {
  1667. if (sessionOptions.Protocol != Protocol.Webdav)
  1668. {
  1669. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1670. }
  1671. }
  1672. string head;
  1673. switch (sessionOptions.Protocol)
  1674. {
  1675. case Protocol.Sftp:
  1676. head = "sftp://";
  1677. break;
  1678. case Protocol.Scp:
  1679. head = "scp://";
  1680. break;
  1681. case Protocol.Ftp:
  1682. head = "ftp://";
  1683. break;
  1684. case Protocol.Webdav:
  1685. if (!sessionOptions.WebdavSecure)
  1686. {
  1687. head = "dav://";
  1688. }
  1689. else
  1690. {
  1691. head = "davs://";
  1692. }
  1693. break;
  1694. case Protocol.S3:
  1695. head = "s3://";
  1696. break;
  1697. default:
  1698. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol)));
  1699. }
  1700. bool hasUsername;
  1701. if (!scanFingerprint)
  1702. {
  1703. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1704. if (hasUsername)
  1705. {
  1706. head += UriEscape(sessionOptions.UserName);
  1707. }
  1708. }
  1709. else
  1710. {
  1711. hasUsername = false;
  1712. }
  1713. string url = head;
  1714. string logUrl = head;
  1715. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1716. {
  1717. if (!hasUsername)
  1718. {
  1719. throw Logger.WriteException(new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not."));
  1720. }
  1721. url += ":" + UriEscape(sessionOptions.Password);
  1722. logUrl += ":***";
  1723. }
  1724. string tail = string.Empty;
  1725. if (hasUsername)
  1726. {
  1727. tail += "@";
  1728. }
  1729. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1730. {
  1731. throw Logger.WriteException(new ArgumentException("SessionOptions.HostName is not set."));
  1732. }
  1733. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1734. // but it works anyway...
  1735. tail += UriEscape(sessionOptions.HostName);
  1736. if (sessionOptions.PortNumber != 0)
  1737. {
  1738. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1739. }
  1740. if (!string.IsNullOrEmpty(sessionOptions.RootPath) && !scanFingerprint)
  1741. {
  1742. if ((sessionOptions.Protocol != Protocol.Webdav) && (sessionOptions.Protocol != Protocol.S3))
  1743. {
  1744. throw Logger.WriteException(new ArgumentException("SessionOptions.RootPath is set, but SessionOptions.Protocol is not Protocol.Webdav nor Protocol.S3."));
  1745. }
  1746. tail += sessionOptions.RootPath;
  1747. }
  1748. url += tail;
  1749. logUrl += tail;
  1750. SessionOptionsToSwitches(sessionOptions, scanFingerprint, out string arguments, out string logArguments);
  1751. const string switchName = "-rawsettings";
  1752. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, switchName, false);
  1753. Tools.AddRawParameters(ref logArguments, sessionOptions.RawSettings, switchName, false);
  1754. if (!string.IsNullOrEmpty(arguments))
  1755. {
  1756. arguments = " " + arguments;
  1757. logArguments = " " + logArguments;
  1758. }
  1759. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1760. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1761. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + logArguments;
  1762. }
  1763. }
  1764. private void SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string arguments, out string logArguments)
  1765. {
  1766. using (Logger.CreateCallstack())
  1767. {
  1768. List<string> switches = new List<string>();
  1769. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1770. ((sessionOptions.SshHostKeyPolicy != SshHostKeyPolicy.Check) && !scanFingerprint))
  1771. {
  1772. if (!sessionOptions.IsSsh)
  1773. {
  1774. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint is set or sessionOptions.SshHostKeyPolicy has not the default value Check, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1775. }
  1776. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1777. switch (sessionOptions.SshHostKeyPolicy)
  1778. {
  1779. case SshHostKeyPolicy.Check:
  1780. // noop
  1781. break;
  1782. case SshHostKeyPolicy.GiveUpSecurityAndAcceptAny:
  1783. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1784. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1785. break;
  1786. case SshHostKeyPolicy.AcceptNew:
  1787. if (!string.IsNullOrEmpty(sshHostKeyFingerprint))
  1788. {
  1789. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint is set and SshHostKeyPolicy is not Check"));
  1790. }
  1791. sshHostKeyFingerprint = "acceptnew";
  1792. break;
  1793. }
  1794. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1795. }
  1796. else
  1797. {
  1798. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1799. {
  1800. throw Logger.WriteException(new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set."));
  1801. }
  1802. }
  1803. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && !scanFingerprint)
  1804. {
  1805. if (!sessionOptions.IsSsh)
  1806. {
  1807. throw Logger.WriteException(new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1808. }
  1809. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  1810. }
  1811. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1812. {
  1813. if (!sessionOptions.IsTls)
  1814. {
  1815. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled nor is the protocol S3."));
  1816. }
  1817. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1818. }
  1819. if (sessionOptions.FtpSecure != FtpSecure.None)
  1820. {
  1821. if (sessionOptions.Protocol != Protocol.Ftp)
  1822. {
  1823. throw Logger.WriteException(new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp."));
  1824. }
  1825. switch (sessionOptions.FtpSecure)
  1826. {
  1827. case FtpSecure.Implicit:
  1828. switches.Add(FormatSwitch("implicit"));
  1829. break;
  1830. case FtpSecure.Explicit:
  1831. switches.Add(FormatSwitch("explicit"));
  1832. break;
  1833. default:
  1834. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure)));
  1835. }
  1836. }
  1837. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1838. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1839. !scanFingerprint)
  1840. {
  1841. if (!sessionOptions.IsTls)
  1842. {
  1843. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled nor is the protocol S3."));
  1844. }
  1845. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1846. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1847. {
  1848. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1849. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1850. }
  1851. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1852. }
  1853. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1854. {
  1855. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1856. }
  1857. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1858. List<string> logSwitches = new List<string>(switches);
  1859. if ((sessionOptions.SecurePrivateKeyPassphrase != null) && !scanFingerprint)
  1860. {
  1861. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1862. {
  1863. throw Logger.WriteException(new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath nor SessionOptions.TlsClientCertificatePath is set."));
  1864. }
  1865. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1866. logSwitches.Add(FormatSwitch("passphrase", "***"));
  1867. }
  1868. if ((sessionOptions.SecureNewPassword != null) && !scanFingerprint)
  1869. {
  1870. if (sessionOptions.SecurePassword == null)
  1871. {
  1872. throw Logger.WriteException(new ArgumentException("SessionOptions.SecureNewPassword is set, but SessionOptions.SecurePassword is not."));
  1873. }
  1874. switches.Add(FormatSwitch("newpassword", sessionOptions.NewPassword));
  1875. logSwitches.Add(FormatSwitch("newpassword", "***"));
  1876. }
  1877. arguments = string.Join(" ", switches.ToArray());
  1878. logArguments = string.Join(" ", logSwitches.ToArray());
  1879. }
  1880. }
  1881. private static string AddStarToList(string list)
  1882. {
  1883. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1884. }
  1885. private RemoteFileInfo DoGetFileInfo(string path)
  1886. {
  1887. using (Logger.CreateCallstack())
  1888. {
  1889. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1890. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1891. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1892. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1893. {
  1894. while (statReader.Read(0))
  1895. {
  1896. if (statReader.GetEmptyElementValue("filename", out string value))
  1897. {
  1898. string name = value;
  1899. int p = name.LastIndexOf('/');
  1900. if (p >= 0)
  1901. {
  1902. name = name.Substring(p + 1);
  1903. }
  1904. fileInfo.Name = name;
  1905. fileInfo.FullName = value;
  1906. }
  1907. else if (statReader.IsNonEmptyElement("file"))
  1908. {
  1909. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1910. {
  1911. while (fileReader.Read(0))
  1912. {
  1913. ReadFile(fileInfo, fileReader);
  1914. }
  1915. }
  1916. }
  1917. }
  1918. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1919. }
  1920. return fileInfo;
  1921. }
  1922. }
  1923. internal static string FormatSwitch(string key)
  1924. {
  1925. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1926. }
  1927. internal static string FormatSwitch(string key, string value)
  1928. {
  1929. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1930. }
  1931. internal static string FormatSwitch(string key, int value)
  1932. {
  1933. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1934. }
  1935. internal static string FormatSwitch(string key, bool value)
  1936. {
  1937. return FormatSwitch(key, (value ? 1 : 0));
  1938. }
  1939. private static string UriEscape(string s)
  1940. {
  1941. return Uri.EscapeDataString(s);
  1942. }
  1943. internal void GotOutput()
  1944. {
  1945. _lastOutput = DateTime.Now;
  1946. }
  1947. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1948. {
  1949. if (e == null)
  1950. {
  1951. Logger.WriteLine("Got incomplete progress output");
  1952. }
  1953. else
  1954. {
  1955. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1956. string s = e.Data.TrimEnd(new[] { '\r' });
  1957. lock (Output)
  1958. {
  1959. Output.InternalAdd(s);
  1960. if (Output.Count > 1000)
  1961. {
  1962. Output.InternalRemoveFirst();
  1963. }
  1964. if (e.Error)
  1965. {
  1966. _error.InternalAdd(s);
  1967. if (_error.Count > 1000)
  1968. {
  1969. _error.InternalRemoveFirst();
  1970. }
  1971. }
  1972. }
  1973. ScheduleEvent(() => RaiseOutputDataReceived(e.Data, e.Error));
  1974. }
  1975. GotOutput();
  1976. }
  1977. private void ScheduleEvent(Action action)
  1978. {
  1979. lock (_events)
  1980. {
  1981. _events.Add(action);
  1982. _eventsEvent.Set();
  1983. }
  1984. }
  1985. internal void CheckForTimeout(string additional = null)
  1986. {
  1987. TimeSpan timeout = Timeout;
  1988. if (timeout < _sessionTimeout)
  1989. {
  1990. timeout = _sessionTimeout + TimeSpan.FromSeconds(1);
  1991. }
  1992. if (DateTime.Now - _lastOutput > timeout)
  1993. {
  1994. Logger.WriteLine("Timeout waiting for WinSCP to respond - asking for callstack");
  1995. _process.RequestCallstack();
  1996. string message = "Timeout waiting for WinSCP to respond";
  1997. if (additional != null)
  1998. {
  1999. message += " - " + additional;
  2000. }
  2001. if (_logReader != null)
  2002. {
  2003. _logReader.SetTimeouted();
  2004. }
  2005. Cleanup();
  2006. throw Logger.WriteException(new TimeoutException(message));
  2007. }
  2008. if (_aborted)
  2009. {
  2010. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  2011. }
  2012. if (_throwStdOut && (_process.StdOut != null) && _process.StdOut.ReadAvailable(1))
  2013. {
  2014. // This is here to return from GetFile asap (?)
  2015. // Not logging the exception, as it's not really an exception.
  2016. Logger.WriteLine("Got data");
  2017. throw new StdOutException();
  2018. }
  2019. }
  2020. private void RaiseFileTransferredEvent(TransferEventArgs args)
  2021. {
  2022. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  2023. FileTransferred?.Invoke(this, args);
  2024. }
  2025. internal void RaiseFailed(SessionRemoteException e)
  2026. {
  2027. Logger.WriteLine("Failed: [{0}]", e);
  2028. if ((Failed != null) && !_ignoreFailed)
  2029. {
  2030. Failed(this, new FailedEventArgs { Error = e });
  2031. }
  2032. foreach (OperationResultBase operationResult in _operationResults)
  2033. {
  2034. operationResult.AddFailure(e);
  2035. }
  2036. }
  2037. private void CheckNotDisposed()
  2038. {
  2039. if (_disposed)
  2040. {
  2041. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  2042. }
  2043. if (_aborted)
  2044. {
  2045. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  2046. }
  2047. }
  2048. private void CheckOpened()
  2049. {
  2050. if (!Opened)
  2051. {
  2052. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  2053. }
  2054. }
  2055. private void CheckNotOpened()
  2056. {
  2057. if (Opened)
  2058. {
  2059. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  2060. }
  2061. }
  2062. private void RaiseOutputDataReceived(string data, bool error)
  2063. {
  2064. Logger.WriteLine("Output: [{0}]", data);
  2065. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(data, error));
  2066. }
  2067. internal void DispatchEvents(int interval)
  2068. {
  2069. DateTime start = DateTime.Now;
  2070. while (_eventsEvent.WaitOne(interval, false))
  2071. {
  2072. lock (_events)
  2073. {
  2074. foreach (Action action in _events)
  2075. {
  2076. action();
  2077. }
  2078. _events.Clear();
  2079. }
  2080. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  2081. if (interval < 0)
  2082. {
  2083. break;
  2084. }
  2085. start = DateTime.Now;
  2086. }
  2087. }
  2088. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  2089. {
  2090. _operationResults.Add(operationResult);
  2091. return new OperationResultGuard(this, operationResult);
  2092. }
  2093. internal void UnregisterOperationResult(OperationResultBase operationResult)
  2094. {
  2095. // GetFile relies on this not to throw
  2096. _operationResults.Remove(operationResult);
  2097. }
  2098. internal bool WantsProgress
  2099. {
  2100. get
  2101. {
  2102. return (_fileTransferProgress != null);
  2103. }
  2104. }
  2105. private IDisposable CreateProgressHandler()
  2106. {
  2107. using (Logger.CreateCallstack())
  2108. {
  2109. _progressHandling++;
  2110. return new ProgressHandler(this);
  2111. }
  2112. }
  2113. internal void DisableProgressHandling()
  2114. {
  2115. using (Logger.CreateCallstack())
  2116. {
  2117. if (_progressHandling <= 0)
  2118. {
  2119. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  2120. }
  2121. // make sure we process all pending progress events
  2122. DispatchEvents(0);
  2123. _progressHandling--;
  2124. }
  2125. }
  2126. internal void ProcessChoice(QueryReceivedEventArgs args)
  2127. {
  2128. if (_queryReceived != null) // optimization
  2129. {
  2130. _choiceEvent.Reset();
  2131. ScheduleEvent(() => Choice(args));
  2132. _choiceEvent.WaitOne();
  2133. }
  2134. }
  2135. private void Choice(QueryReceivedEventArgs args)
  2136. {
  2137. _queryReceived?.Invoke(this, args);
  2138. _choiceEvent.Set();
  2139. }
  2140. internal void ProcessProgress(FileTransferProgressEventArgs args)
  2141. {
  2142. ScheduleEvent(() => Progress(args));
  2143. }
  2144. private void Progress(FileTransferProgressEventArgs args)
  2145. {
  2146. if ((_progressHandling >= 0) && WantsProgress)
  2147. {
  2148. _fileTransferProgress(this, args);
  2149. if (args.Cancel)
  2150. {
  2151. _process.Cancel();
  2152. }
  2153. }
  2154. }
  2155. private void SetupTempPath()
  2156. {
  2157. using (Logger.CreateCallstack())
  2158. {
  2159. if (!string.IsNullOrEmpty(_xmlLogPath))
  2160. {
  2161. bool exists = File.Exists(_xmlLogPath);
  2162. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  2163. if (exists)
  2164. {
  2165. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  2166. }
  2167. }
  2168. else
  2169. {
  2170. string path = Path.GetTempPath();
  2171. Logger.WriteLine("Temporary folder: {0}", path);
  2172. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  2173. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  2174. string filename;
  2175. bool exists;
  2176. do
  2177. {
  2178. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  2179. ++_logUnique;
  2180. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  2181. exists = File.Exists(filename);
  2182. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  2183. }
  2184. while (exists);
  2185. _xmlLogPath = filename;
  2186. }
  2187. }
  2188. }
  2189. #if !NETSTANDARD
  2190. private static string GetTypeLibKey(Type t)
  2191. {
  2192. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  2193. }
  2194. #endif
  2195. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  2196. {
  2197. using (Logger.CreateCallstack())
  2198. {
  2199. Logger.WriteLine("Name [{0}]", name);
  2200. FieldInfo result = GetType().GetField(name, bindingAttr);
  2201. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2202. return result;
  2203. }
  2204. }
  2205. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  2206. {
  2207. using (Logger.CreateCallstack())
  2208. {
  2209. FieldInfo[] result = GetType().GetFields(bindingAttr);
  2210. Logger.WriteLine("Fields [{0}]", result.Length);
  2211. return result;
  2212. }
  2213. }
  2214. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  2215. {
  2216. using (Logger.CreateCallstack())
  2217. {
  2218. Logger.WriteLine("Name [{0}]", name);
  2219. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  2220. Logger.WriteLine("Result [{0}]", result.Length);
  2221. return result;
  2222. }
  2223. }
  2224. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  2225. {
  2226. using (Logger.CreateCallstack())
  2227. {
  2228. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  2229. Logger.WriteLine("Result [{0}]", result.Length);
  2230. return result;
  2231. }
  2232. }
  2233. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  2234. {
  2235. using (Logger.CreateCallstack())
  2236. {
  2237. Logger.WriteLine("Name [{0}]", name);
  2238. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  2239. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2240. return result;
  2241. }
  2242. }
  2243. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  2244. {
  2245. using (Logger.CreateCallstack())
  2246. {
  2247. Logger.WriteLine("Name [{0}]", name);
  2248. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  2249. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2250. return result;
  2251. }
  2252. }
  2253. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  2254. {
  2255. using (Logger.CreateCallstack())
  2256. {
  2257. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  2258. Logger.WriteLine("Result [{0}]", result.Length);
  2259. return result;
  2260. }
  2261. }
  2262. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  2263. {
  2264. using (Logger.CreateCallstack())
  2265. {
  2266. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  2267. Logger.WriteLine("Result [{0}]", result.Length);
  2268. return result;
  2269. }
  2270. }
  2271. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  2272. {
  2273. using (Logger.CreateCallstack())
  2274. {
  2275. Logger.WriteLine("Name [{0}]", name);
  2276. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  2277. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2278. return result;
  2279. }
  2280. }
  2281. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  2282. {
  2283. using (Logger.CreateCallstack())
  2284. {
  2285. Logger.WriteLine("Name [{0}]", name);
  2286. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  2287. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2288. return result;
  2289. }
  2290. }
  2291. private void LogInvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2292. {
  2293. Logger.WriteLine("Name [{0}]", name);
  2294. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  2295. Logger.WriteLine("Binder [{0}]", binder);
  2296. Logger.WriteLine("Target [{0}]", target);
  2297. if (args != null)
  2298. {
  2299. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  2300. for (int i = 0; i < args.Length; ++i)
  2301. {
  2302. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  2303. }
  2304. }
  2305. Logger.WriteLine("Culture [{0}]", culture);
  2306. if (namedParameters != null)
  2307. {
  2308. foreach (string namedParameter in namedParameters)
  2309. {
  2310. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  2311. }
  2312. }
  2313. }
  2314. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2315. {
  2316. using (Logger.CreateCallstack())
  2317. {
  2318. object result;
  2319. try
  2320. {
  2321. bool wasLogging = Logger.Logging;
  2322. if (wasLogging)
  2323. {
  2324. // factored out to reduce this method complexity
  2325. LogInvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2326. }
  2327. if (target == null)
  2328. {
  2329. throw Logger.WriteException(new ArgumentNullException(nameof(target)));
  2330. }
  2331. Type type = target.GetType();
  2332. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  2333. // that fails to match method, if integer value is provided to enum argument
  2334. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  2335. // This does not happen if we do not implement IReflect, though no idea why.
  2336. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  2337. // and call the only instance directly.
  2338. // Calling MethodInfo.Invoke with int values for enum arguments works.
  2339. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  2340. // the method with given name does not exist at all)
  2341. MethodInfo method = null;
  2342. PropertyInfo property = null;
  2343. // would be way too difficult to implement the below involving named arguments
  2344. if (namedParameters == null)
  2345. {
  2346. try
  2347. {
  2348. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  2349. method = type.GetMethod(name, bindingFlags);
  2350. if (args == null)
  2351. {
  2352. throw Logger.WriteException(new ArgumentNullException(nameof(args)));
  2353. }
  2354. if (method != null)
  2355. {
  2356. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  2357. ParameterInfo[] parameters = method.GetParameters();
  2358. if (args.Length < parameters.Length)
  2359. {
  2360. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  2361. object[] args2 = new object[parameters.Length];
  2362. for (int i = 0; i < parameters.Length; i++)
  2363. {
  2364. if (i < args.Length)
  2365. {
  2366. args2[i] = args[i];
  2367. }
  2368. else
  2369. {
  2370. if (!parameters[i].IsOptional)
  2371. {
  2372. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  2373. args2 = null;
  2374. break;
  2375. }
  2376. else
  2377. {
  2378. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  2379. args2[i] = parameters[i].DefaultValue;
  2380. }
  2381. }
  2382. }
  2383. if (args2 != null)
  2384. {
  2385. args = args2;
  2386. }
  2387. }
  2388. }
  2389. else if (args.Length == 1) // sanity check
  2390. {
  2391. property = type.GetProperty(name, bindingFlags);
  2392. }
  2393. }
  2394. catch (AmbiguousMatchException e)
  2395. {
  2396. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  2397. }
  2398. }
  2399. if (method != null)
  2400. {
  2401. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  2402. result = method.Invoke(target, invokeAttr, binder, args, culture);
  2403. }
  2404. else if (property != null)
  2405. {
  2406. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  2407. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  2408. result = null;
  2409. }
  2410. else
  2411. {
  2412. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  2413. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2414. }
  2415. if (!wasLogging && Logger.Logging)
  2416. {
  2417. Logger.WriteLine("Invoking member {0} enabled debug logging", name);
  2418. // Might call LogInvokeMember here, but it's not really useful.
  2419. }
  2420. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  2421. }
  2422. catch (Exception e)
  2423. {
  2424. Logger.WriteLine("Error [{0}]", e);
  2425. throw;
  2426. }
  2427. return result;
  2428. }
  2429. }
  2430. Type IReflect.UnderlyingSystemType
  2431. {
  2432. get { return GetType(); }
  2433. }
  2434. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  2435. internal Logger Logger { get; private set; }
  2436. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  2437. internal bool TestHandlesClosedInternal { get; set; }
  2438. internal Dictionary<string, string> RawConfiguration { get; private set; }
  2439. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  2440. internal string IniFilePathInternal { get { return _iniFilePath; } }
  2441. private ExeSessionProcess _process;
  2442. private DateTime _lastOutput;
  2443. private ElementLogReader _reader;
  2444. private SessionLogReader _logReader;
  2445. private readonly IList<OperationResultBase> _operationResults;
  2446. private readonly IList<Action> _events;
  2447. private AutoResetEvent _eventsEvent;
  2448. private ManualResetEvent _choiceEvent;
  2449. private bool _disposed;
  2450. private string _executablePath;
  2451. private string _additionalExecutableArguments;
  2452. private bool _defaultConfiguration;
  2453. private bool _disableVersionCheck;
  2454. private string _iniFilePath;
  2455. private TimeSpan _reconnectTime;
  2456. private string _sessionLogPath;
  2457. private bool _aborted;
  2458. private int _logUnique;
  2459. private string _xmlLogPath;
  2460. private FileTransferProgressEventHandler _fileTransferProgress;
  2461. private int _progressHandling;
  2462. private bool _guardProcessWithJob;
  2463. private string _homePath;
  2464. #if !NETSTANDARD
  2465. private string _executableProcessUserName;
  2466. private SecureString _executableProcessPassword;
  2467. #endif
  2468. private StringCollection _error;
  2469. private bool _ignoreFailed;
  2470. private TimeSpan _sessionTimeout;
  2471. private QueryReceivedEventHandler _queryReceived;
  2472. private bool _throwStdOut;
  2473. }
  2474. }