Session.cs 117 KB

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