Session.cs 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840
  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 TryGetFileInfo(string path, out RemoteFileInfo fileInfo)
  1360. {
  1361. using (CreateCallstackAndLock())
  1362. {
  1363. CheckOpened();
  1364. try
  1365. {
  1366. _ignoreFailed = true;
  1367. try
  1368. {
  1369. fileInfo = DoGetFileInfo(path);
  1370. }
  1371. finally
  1372. {
  1373. _ignoreFailed = false;
  1374. }
  1375. return true;
  1376. }
  1377. catch (SessionRemoteException)
  1378. {
  1379. fileInfo = null;
  1380. return false;
  1381. }
  1382. }
  1383. }
  1384. public bool FileExists(string path)
  1385. {
  1386. return TryGetFileInfo(path, out _);
  1387. }
  1388. public byte[] CalculateFileChecksum(string algorithm, string path)
  1389. {
  1390. using (CreateCallstackAndLock())
  1391. {
  1392. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  1393. string hex = null;
  1394. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1395. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  1396. {
  1397. while (checksumReader.Read(0))
  1398. {
  1399. if (checksumReader.GetEmptyElementValue("checksum", out string value))
  1400. {
  1401. hex = value;
  1402. }
  1403. }
  1404. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1405. }
  1406. int len = hex.Length;
  1407. if ((len % 2) != 0)
  1408. {
  1409. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  1410. throw Logger.WriteException(new SessionLocalException(this, error));
  1411. }
  1412. int count = len / 2;
  1413. byte[] bytes = new byte[count];
  1414. for (int i = 0; i < count; i++)
  1415. {
  1416. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  1417. }
  1418. return bytes;
  1419. }
  1420. }
  1421. public void CreateDirectory(string path)
  1422. {
  1423. using (CreateCallstackAndLock())
  1424. {
  1425. CheckOpened();
  1426. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  1427. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1428. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  1429. {
  1430. ReadElement(mkdirReader, 0);
  1431. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1432. }
  1433. }
  1434. }
  1435. public void MoveFile(string sourcePath, string targetPath)
  1436. {
  1437. using (CreateCallstackAndLock())
  1438. {
  1439. CheckOpened();
  1440. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  1441. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1442. {
  1443. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  1444. {
  1445. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1446. }
  1447. else
  1448. {
  1449. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  1450. {
  1451. ReadElement(mvReader, 0);
  1452. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1453. }
  1454. }
  1455. }
  1456. }
  1457. }
  1458. public void DuplicateFile(string sourcePath, string targetPath)
  1459. {
  1460. using (CreateCallstackAndLock())
  1461. {
  1462. CheckOpened();
  1463. string sourceArgument = Tools.ArgumentEscape(RemotePath.EscapeFileMask(sourcePath));
  1464. string targetArgument = Tools.ArgumentEscape(targetPath);
  1465. string command = string.Format(CultureInfo.InvariantCulture, "cp \"{0}\" \"{1}\"", sourceArgument, targetArgument);
  1466. WriteCommand(command);
  1467. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1468. {
  1469. if (!groupReader.TryWaitForNonEmptyElement("cp", LogReadFlags.ThrowFailures))
  1470. {
  1471. throw Logger.WriteException(new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath)));
  1472. }
  1473. else
  1474. {
  1475. using (ElementLogReader cpReader = groupReader.CreateLogReader())
  1476. {
  1477. ReadElement(cpReader, 0);
  1478. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1479. }
  1480. }
  1481. }
  1482. }
  1483. }
  1484. [Obsolete("Use RemotePath.EscapeFileMask")]
  1485. public string EscapeFileMask(string fileMask)
  1486. {
  1487. return RemotePath.EscapeFileMask(fileMask);
  1488. }
  1489. [Obsolete("Use RemotePath.TranslateRemotePathToLocal")]
  1490. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  1491. {
  1492. return RemotePath.TranslateRemotePathToLocal(remotePath, remoteRoot, localRoot);
  1493. }
  1494. [Obsolete("Use RemotePath.TranslateLocalPathToRemote")]
  1495. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  1496. {
  1497. return RemotePath.TranslateLocalPathToRemote(localPath, localRoot, remoteRoot);
  1498. }
  1499. [Obsolete("Use RemotePath.CombinePaths")]
  1500. public string CombinePaths(string path1, string path2)
  1501. {
  1502. return RemotePath.Combine(path1, path2);
  1503. }
  1504. public void AddRawConfiguration(string setting, string value)
  1505. {
  1506. CheckNotOpened();
  1507. RawConfiguration.Add(setting, value);
  1508. }
  1509. #if !NETSTANDARD
  1510. [ComRegisterFunction]
  1511. private static void ComRegister(Type t)
  1512. {
  1513. string subKey = GetTypeLibKey(t);
  1514. Assembly assembly = Assembly.GetAssembly(t);
  1515. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  1516. if (attributes.Length == 0)
  1517. {
  1518. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  1519. }
  1520. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  1521. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  1522. }
  1523. [ComUnregisterFunction]
  1524. private static void ComUnregister(Type t)
  1525. {
  1526. string subKey = GetTypeLibKey(t);
  1527. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  1528. }
  1529. #endif
  1530. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  1531. {
  1532. using (Logger.CreateCallstack())
  1533. {
  1534. if (fileReader.GetEmptyElementValue("type", out string value))
  1535. {
  1536. fileInfo.FileType = value[0];
  1537. }
  1538. else if (fileReader.GetEmptyElementValue("size", out value))
  1539. {
  1540. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  1541. }
  1542. else if (fileReader.GetEmptyElementValue("modification", out value))
  1543. {
  1544. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  1545. }
  1546. else if (fileReader.GetEmptyElementValue("permissions", out value))
  1547. {
  1548. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  1549. }
  1550. else if (fileReader.GetEmptyElementValue("owner", out value))
  1551. {
  1552. fileInfo.Owner = value;
  1553. }
  1554. else if (fileReader.GetEmptyElementValue("group", out value))
  1555. {
  1556. fileInfo.Group = value;
  1557. }
  1558. }
  1559. }
  1560. internal static string BooleanSwitch(bool flag, string name)
  1561. {
  1562. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1563. }
  1564. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1565. {
  1566. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1567. }
  1568. private void AddSynchronizationTransfer(SynchronizationResult result, TransferEventArgs transfer)
  1569. {
  1570. if (transfer != null)
  1571. {
  1572. if (transfer.Side == ProgressSide.Local)
  1573. {
  1574. result.AddUpload(transfer);
  1575. }
  1576. else
  1577. {
  1578. result.AddDownload(transfer);
  1579. }
  1580. RaiseFileTransferredEvent(transfer);
  1581. }
  1582. }
  1583. private static string IncludeTrailingSlash(string path)
  1584. {
  1585. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1586. {
  1587. path += '/';
  1588. }
  1589. return path;
  1590. }
  1591. private void Cleanup()
  1592. {
  1593. using (Logger.CreateCallstack())
  1594. {
  1595. if (_process != null)
  1596. {
  1597. Logger.WriteLine("Terminating process");
  1598. try
  1599. {
  1600. try
  1601. {
  1602. WriteCommand("exit");
  1603. _process.Close();
  1604. }
  1605. finally
  1606. {
  1607. _process.Dispose();
  1608. _process = null;
  1609. }
  1610. }
  1611. catch (Exception e)
  1612. {
  1613. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1614. }
  1615. }
  1616. Logger.WriteLine("Disposing log readers");
  1617. if (_reader != null)
  1618. {
  1619. _reader.Dispose();
  1620. _reader = null;
  1621. }
  1622. if (_logReader != null)
  1623. {
  1624. _logReader.Dispose();
  1625. _logReader = null;
  1626. }
  1627. // Cleanup log file
  1628. if ((XmlLogPath != null) && File.Exists(XmlLogPath) && !XmlLogPreserve)
  1629. {
  1630. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1631. try
  1632. {
  1633. File.Delete(XmlLogPath);
  1634. }
  1635. catch (DirectoryNotFoundException e)
  1636. {
  1637. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1638. }
  1639. catch (IOException e)
  1640. {
  1641. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1642. }
  1643. catch (UnauthorizedAccessException e)
  1644. {
  1645. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1646. }
  1647. _xmlLogPath = null;
  1648. }
  1649. }
  1650. }
  1651. private void WriteCommand(string command)
  1652. {
  1653. WriteCommand(command, command);
  1654. }
  1655. private void WriteCommand(string command, string log)
  1656. {
  1657. Logger.WriteLine("Command: [{0}]", log);
  1658. _process.ExecuteCommand(command, log);
  1659. GotOutput();
  1660. }
  1661. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1662. {
  1663. while (reader.Read(flags))
  1664. {
  1665. }
  1666. }
  1667. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1668. {
  1669. using (Logger.CreateCallstack())
  1670. {
  1671. if (sessionOptions.WebdavSecure)
  1672. {
  1673. if (sessionOptions.Protocol != Protocol.Webdav)
  1674. {
  1675. throw Logger.WriteException(new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav."));
  1676. }
  1677. }
  1678. string head;
  1679. switch (sessionOptions.Protocol)
  1680. {
  1681. case Protocol.Sftp:
  1682. head = "sftp://";
  1683. break;
  1684. case Protocol.Scp:
  1685. head = "scp://";
  1686. break;
  1687. case Protocol.Ftp:
  1688. head = "ftp://";
  1689. break;
  1690. case Protocol.Webdav:
  1691. if (!sessionOptions.WebdavSecure)
  1692. {
  1693. head = "dav://";
  1694. }
  1695. else
  1696. {
  1697. head = "davs://";
  1698. }
  1699. break;
  1700. case Protocol.S3:
  1701. head = "s3://";
  1702. break;
  1703. default:
  1704. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol)));
  1705. }
  1706. bool hasUsername;
  1707. if (!scanFingerprint)
  1708. {
  1709. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1710. if (hasUsername)
  1711. {
  1712. head += UriEscape(sessionOptions.UserName);
  1713. }
  1714. }
  1715. else
  1716. {
  1717. hasUsername = false;
  1718. }
  1719. string url = head;
  1720. string logUrl = head;
  1721. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1722. {
  1723. if (!hasUsername)
  1724. {
  1725. throw Logger.WriteException(new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not."));
  1726. }
  1727. url += ":" + UriEscape(sessionOptions.Password);
  1728. logUrl += ":***";
  1729. }
  1730. string tail = string.Empty;
  1731. if (hasUsername)
  1732. {
  1733. tail += "@";
  1734. }
  1735. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1736. {
  1737. throw Logger.WriteException(new ArgumentException("SessionOptions.HostName is not set."));
  1738. }
  1739. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1740. // but it works anyway...
  1741. tail += UriEscape(sessionOptions.HostName);
  1742. if (sessionOptions.PortNumber != 0)
  1743. {
  1744. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1745. }
  1746. if (!string.IsNullOrEmpty(sessionOptions.RootPath) && !scanFingerprint)
  1747. {
  1748. if ((sessionOptions.Protocol != Protocol.Webdav) && (sessionOptions.Protocol != Protocol.S3))
  1749. {
  1750. throw Logger.WriteException(new ArgumentException("SessionOptions.RootPath is set, but SessionOptions.Protocol is not Protocol.Webdav nor Protocol.S3."));
  1751. }
  1752. tail += sessionOptions.RootPath;
  1753. }
  1754. url += tail;
  1755. logUrl += tail;
  1756. SessionOptionsToSwitches(sessionOptions, scanFingerprint, out string arguments, out string logArguments);
  1757. const string switchName = "-rawsettings";
  1758. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, switchName, false);
  1759. Tools.AddRawParameters(ref logArguments, sessionOptions.RawSettings, switchName, false);
  1760. if (!string.IsNullOrEmpty(arguments))
  1761. {
  1762. arguments = " " + arguments;
  1763. logArguments = " " + logArguments;
  1764. }
  1765. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1766. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1767. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + logArguments;
  1768. }
  1769. }
  1770. private void SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string arguments, out string logArguments)
  1771. {
  1772. using (Logger.CreateCallstack())
  1773. {
  1774. List<string> switches = new List<string>();
  1775. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1776. ((sessionOptions.SshHostKeyPolicy != SshHostKeyPolicy.Check) && !scanFingerprint))
  1777. {
  1778. if (!sessionOptions.IsSsh)
  1779. {
  1780. 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."));
  1781. }
  1782. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1783. switch (sessionOptions.SshHostKeyPolicy)
  1784. {
  1785. case SshHostKeyPolicy.Check:
  1786. // noop
  1787. break;
  1788. case SshHostKeyPolicy.GiveUpSecurityAndAcceptAny:
  1789. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1790. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1791. break;
  1792. case SshHostKeyPolicy.AcceptNew:
  1793. if (!string.IsNullOrEmpty(sshHostKeyFingerprint))
  1794. {
  1795. throw Logger.WriteException(new ArgumentException("SessionOptions.SshHostKeyFingerprint is set and SshHostKeyPolicy is not Check"));
  1796. }
  1797. sshHostKeyFingerprint = "acceptnew";
  1798. break;
  1799. }
  1800. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1801. }
  1802. else
  1803. {
  1804. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1805. {
  1806. throw Logger.WriteException(new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set."));
  1807. }
  1808. }
  1809. bool hasSshPrivateKeyPath = !string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath);
  1810. bool hasSshPrivateKey = !string.IsNullOrEmpty(sessionOptions.SshPrivateKey);
  1811. if ((hasSshPrivateKeyPath || hasSshPrivateKey) && !scanFingerprint)
  1812. {
  1813. if (!sessionOptions.IsSsh)
  1814. {
  1815. throw Logger.WriteException(new ArgumentException("SessionOptions.SshPrivateKeyPath or SessionOptions.SshPrivateKey is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp."));
  1816. }
  1817. if (hasSshPrivateKeyPath && hasSshPrivateKey)
  1818. {
  1819. throw Logger.WriteException(new ArgumentException("Set only one of SessionOptions.SshPrivateKeyPath or SessionOptions.SshPrivateKey."));
  1820. }
  1821. string privateKey;
  1822. if (hasSshPrivateKeyPath)
  1823. {
  1824. privateKey = sessionOptions.SshPrivateKeyPath;
  1825. }
  1826. else
  1827. {
  1828. privateKey = "@" + GenerateInMemoryPrivateKey(sessionOptions);
  1829. }
  1830. switches.Add(FormatSwitch("privatekey", privateKey));
  1831. }
  1832. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1833. {
  1834. if (!sessionOptions.IsTls)
  1835. {
  1836. throw Logger.WriteException(new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled nor is the protocol S3."));
  1837. }
  1838. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1839. }
  1840. if (sessionOptions.FtpSecure != FtpSecure.None)
  1841. {
  1842. if (sessionOptions.Protocol != Protocol.Ftp)
  1843. {
  1844. throw Logger.WriteException(new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp."));
  1845. }
  1846. switch (sessionOptions.FtpSecure)
  1847. {
  1848. case FtpSecure.Implicit:
  1849. switches.Add(FormatSwitch("implicit"));
  1850. break;
  1851. case FtpSecure.Explicit:
  1852. switches.Add(FormatSwitch("explicit"));
  1853. break;
  1854. default:
  1855. throw Logger.WriteException(new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure)));
  1856. }
  1857. }
  1858. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1859. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1860. !scanFingerprint)
  1861. {
  1862. if (!sessionOptions.IsTls)
  1863. {
  1864. 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."));
  1865. }
  1866. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1867. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1868. {
  1869. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1870. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1871. }
  1872. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1873. }
  1874. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1875. {
  1876. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1877. }
  1878. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1879. List<string> logSwitches = new List<string>(switches);
  1880. if ((sessionOptions.SecurePrivateKeyPassphrase != null) && !scanFingerprint)
  1881. {
  1882. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) &&
  1883. string.IsNullOrEmpty(sessionOptions.SshPrivateKey) &&
  1884. string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1885. {
  1886. throw Logger.WriteException(new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath, SessionOptions.SshPrivateKey nor SessionOptions.TlsClientCertificatePath is set."));
  1887. }
  1888. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1889. logSwitches.Add(FormatSwitch("passphrase", "***"));
  1890. }
  1891. if ((sessionOptions.SecureNewPassword != null) && !scanFingerprint)
  1892. {
  1893. if (sessionOptions.SecurePassword == null)
  1894. {
  1895. throw Logger.WriteException(new ArgumentException("SessionOptions.SecureNewPassword is set, but SessionOptions.SecurePassword is not."));
  1896. }
  1897. switches.Add(FormatSwitch("newpassword", sessionOptions.NewPassword));
  1898. logSwitches.Add(FormatSwitch("newpassword", "***"));
  1899. }
  1900. arguments = string.Join(" ", switches.ToArray());
  1901. logArguments = string.Join(" ", logSwitches.ToArray());
  1902. }
  1903. }
  1904. internal static string GenerateInMemoryPrivateKey(SessionOptions sessionOptions)
  1905. {
  1906. byte[] bytes = Encoding.Default.GetBytes(sessionOptions.SshPrivateKey);
  1907. return BitConverter.ToString(bytes).Replace("-", "");
  1908. }
  1909. private static string AddStarToList(string list)
  1910. {
  1911. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1912. }
  1913. private RemoteFileInfo DoGetFileInfo(string path)
  1914. {
  1915. using (Logger.CreateCallstack())
  1916. {
  1917. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1918. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1919. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1920. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1921. {
  1922. while (statReader.Read(0))
  1923. {
  1924. if (statReader.GetEmptyElementValue("filename", out string value))
  1925. {
  1926. string name = value;
  1927. int p = name.LastIndexOf('/');
  1928. if (p >= 0)
  1929. {
  1930. name = name.Substring(p + 1);
  1931. }
  1932. fileInfo.Name = name;
  1933. fileInfo.FullName = value;
  1934. }
  1935. else if (statReader.IsNonEmptyElement("file"))
  1936. {
  1937. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1938. {
  1939. while (fileReader.Read(0))
  1940. {
  1941. ReadFile(fileInfo, fileReader);
  1942. }
  1943. }
  1944. }
  1945. }
  1946. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1947. }
  1948. return fileInfo;
  1949. }
  1950. }
  1951. internal static string FormatSwitch(string key)
  1952. {
  1953. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1954. }
  1955. internal static string FormatSwitch(string key, string value)
  1956. {
  1957. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1958. }
  1959. internal static string FormatSwitch(string key, int value)
  1960. {
  1961. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1962. }
  1963. internal static string FormatSwitch(string key, bool value)
  1964. {
  1965. return FormatSwitch(key, (value ? 1 : 0));
  1966. }
  1967. private static string UriEscape(string s)
  1968. {
  1969. return Uri.EscapeDataString(s);
  1970. }
  1971. internal void GotOutput()
  1972. {
  1973. _lastOutput = DateTime.Now;
  1974. }
  1975. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1976. {
  1977. if (e == null)
  1978. {
  1979. Logger.WriteLine("Got incomplete progress output");
  1980. }
  1981. else
  1982. {
  1983. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1984. string s = e.Data.TrimEnd(new[] { '\r' });
  1985. lock (Output)
  1986. {
  1987. Output.InternalAdd(s);
  1988. if (Output.Count > 1000)
  1989. {
  1990. Output.InternalRemoveFirst();
  1991. }
  1992. if (e.Error)
  1993. {
  1994. _error.InternalAdd(s);
  1995. if (_error.Count > 1000)
  1996. {
  1997. _error.InternalRemoveFirst();
  1998. }
  1999. }
  2000. }
  2001. ScheduleEvent(() => RaiseOutputDataReceived(e.Data, e.Error));
  2002. }
  2003. GotOutput();
  2004. }
  2005. private void ScheduleEvent(Action action)
  2006. {
  2007. lock (_events)
  2008. {
  2009. _events.Add(action);
  2010. _eventsEvent.Set();
  2011. }
  2012. }
  2013. internal void CheckForTimeout(string additional = null)
  2014. {
  2015. TimeSpan timeout = Timeout;
  2016. if (timeout < _sessionTimeout)
  2017. {
  2018. timeout = _sessionTimeout + TimeSpan.FromSeconds(1);
  2019. }
  2020. if (DateTime.Now - _lastOutput > timeout)
  2021. {
  2022. Logger.WriteLine("Timeout waiting for WinSCP to respond - asking for callstack");
  2023. _process.RequestCallstack();
  2024. string message = "Timeout waiting for WinSCP to respond";
  2025. if (additional != null)
  2026. {
  2027. message += " - " + additional;
  2028. }
  2029. if (_logReader != null)
  2030. {
  2031. _logReader.SetTimeouted();
  2032. }
  2033. Cleanup();
  2034. throw Logger.WriteException(new TimeoutException(message));
  2035. }
  2036. if (_aborted)
  2037. {
  2038. throw Logger.WriteException(new SessionLocalException(this, "Aborted."));
  2039. }
  2040. if (_throwStdOut && (_process.StdOut != null) && _process.StdOut.ReadAvailable(1))
  2041. {
  2042. // This is here to return from GetFile asap (?)
  2043. // Not logging the exception, as it's not really an exception.
  2044. Logger.WriteLine("Got data");
  2045. throw new StdOutException();
  2046. }
  2047. }
  2048. private void RaiseFileTransferredEvent(TransferEventArgs args)
  2049. {
  2050. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  2051. FileTransferred?.Invoke(this, args);
  2052. }
  2053. internal void RaiseFailed(SessionRemoteException e)
  2054. {
  2055. Logger.WriteLine("Failed: [{0}]", e);
  2056. if ((Failed != null) && !_ignoreFailed)
  2057. {
  2058. Failed(this, new FailedEventArgs { Error = e });
  2059. }
  2060. foreach (OperationResultBase operationResult in _operationResults)
  2061. {
  2062. operationResult.AddFailure(e);
  2063. }
  2064. }
  2065. private void CheckNotDisposed()
  2066. {
  2067. if (_disposed)
  2068. {
  2069. throw Logger.WriteException(new InvalidOperationException("Object is disposed"));
  2070. }
  2071. if (_aborted)
  2072. {
  2073. throw Logger.WriteException(new InvalidOperationException("Session was aborted"));
  2074. }
  2075. }
  2076. private void CheckOpened()
  2077. {
  2078. if (!Opened)
  2079. {
  2080. throw Logger.WriteException(new InvalidOperationException("Session is not opened"));
  2081. }
  2082. }
  2083. private void CheckNotOpened()
  2084. {
  2085. if (Opened)
  2086. {
  2087. throw Logger.WriteException(new InvalidOperationException("Session is already opened"));
  2088. }
  2089. }
  2090. private void RaiseOutputDataReceived(string data, bool error)
  2091. {
  2092. Logger.WriteLine("Output: [{0}]", data);
  2093. OutputDataReceived?.Invoke(this, new OutputDataReceivedEventArgs(data, error));
  2094. }
  2095. internal void DispatchEvents(int interval)
  2096. {
  2097. DateTime start = DateTime.Now;
  2098. while (_eventsEvent.WaitOne(interval, false))
  2099. {
  2100. lock (_events)
  2101. {
  2102. foreach (Action action in _events)
  2103. {
  2104. action();
  2105. }
  2106. _events.Clear();
  2107. }
  2108. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  2109. if (interval < 0)
  2110. {
  2111. break;
  2112. }
  2113. start = DateTime.Now;
  2114. }
  2115. }
  2116. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  2117. {
  2118. _operationResults.Add(operationResult);
  2119. return new OperationResultGuard(this, operationResult);
  2120. }
  2121. internal void UnregisterOperationResult(OperationResultBase operationResult)
  2122. {
  2123. // GetFile relies on this not to throw
  2124. _operationResults.Remove(operationResult);
  2125. }
  2126. internal bool WantsProgress
  2127. {
  2128. get
  2129. {
  2130. return (_fileTransferProgress != null);
  2131. }
  2132. }
  2133. private IDisposable CreateProgressHandler()
  2134. {
  2135. using (Logger.CreateCallstack())
  2136. {
  2137. _progressHandling++;
  2138. return new ProgressHandler(this);
  2139. }
  2140. }
  2141. internal void DisableProgressHandling()
  2142. {
  2143. using (Logger.CreateCallstack())
  2144. {
  2145. if (_progressHandling <= 0)
  2146. {
  2147. throw Logger.WriteException(new InvalidOperationException("Progress handling not enabled"));
  2148. }
  2149. // make sure we process all pending progress events
  2150. DispatchEvents(0);
  2151. _progressHandling--;
  2152. }
  2153. }
  2154. internal void ProcessChoice(QueryReceivedEventArgs args)
  2155. {
  2156. if (_queryReceived != null) // optimization
  2157. {
  2158. _choiceEvent.Reset();
  2159. ScheduleEvent(() => Choice(args));
  2160. _choiceEvent.WaitOne();
  2161. }
  2162. }
  2163. private void Choice(QueryReceivedEventArgs args)
  2164. {
  2165. _queryReceived?.Invoke(this, args);
  2166. _choiceEvent.Set();
  2167. }
  2168. internal void ProcessProgress(FileTransferProgressEventArgs args)
  2169. {
  2170. ScheduleEvent(() => Progress(args));
  2171. }
  2172. private void Progress(FileTransferProgressEventArgs args)
  2173. {
  2174. if ((_progressHandling >= 0) && WantsProgress)
  2175. {
  2176. _fileTransferProgress(this, args);
  2177. if (args.Cancel)
  2178. {
  2179. _process.Cancel();
  2180. }
  2181. }
  2182. }
  2183. private void SetupTempPath()
  2184. {
  2185. using (Logger.CreateCallstack())
  2186. {
  2187. if (!string.IsNullOrEmpty(_xmlLogPath))
  2188. {
  2189. bool exists = File.Exists(_xmlLogPath);
  2190. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  2191. if (exists)
  2192. {
  2193. throw Logger.WriteException(new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath)));
  2194. }
  2195. }
  2196. else
  2197. {
  2198. string path = Path.GetTempPath();
  2199. Logger.WriteLine("Temporary folder: {0}", path);
  2200. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  2201. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  2202. string filename;
  2203. bool exists;
  2204. do
  2205. {
  2206. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  2207. ++_logUnique;
  2208. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  2209. exists = File.Exists(filename);
  2210. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  2211. }
  2212. while (exists);
  2213. _xmlLogPath = filename;
  2214. }
  2215. }
  2216. }
  2217. #if !NETSTANDARD
  2218. private static string GetTypeLibKey(Type t)
  2219. {
  2220. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  2221. }
  2222. #endif
  2223. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  2224. {
  2225. using (Logger.CreateCallstack())
  2226. {
  2227. Logger.WriteLine("Name [{0}]", name);
  2228. FieldInfo result = GetType().GetField(name, bindingAttr);
  2229. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2230. return result;
  2231. }
  2232. }
  2233. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  2234. {
  2235. using (Logger.CreateCallstack())
  2236. {
  2237. FieldInfo[] result = GetType().GetFields(bindingAttr);
  2238. Logger.WriteLine("Fields [{0}]", result.Length);
  2239. return result;
  2240. }
  2241. }
  2242. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  2243. {
  2244. using (Logger.CreateCallstack())
  2245. {
  2246. Logger.WriteLine("Name [{0}]", name);
  2247. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  2248. Logger.WriteLine("Result [{0}]", result.Length);
  2249. return result;
  2250. }
  2251. }
  2252. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  2253. {
  2254. using (Logger.CreateCallstack())
  2255. {
  2256. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  2257. Logger.WriteLine("Result [{0}]", result.Length);
  2258. return result;
  2259. }
  2260. }
  2261. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  2262. {
  2263. using (Logger.CreateCallstack())
  2264. {
  2265. Logger.WriteLine("Name [{0}]", name);
  2266. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  2267. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2268. return result;
  2269. }
  2270. }
  2271. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  2272. {
  2273. using (Logger.CreateCallstack())
  2274. {
  2275. Logger.WriteLine("Name [{0}]", name);
  2276. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  2277. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2278. return result;
  2279. }
  2280. }
  2281. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  2282. {
  2283. using (Logger.CreateCallstack())
  2284. {
  2285. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  2286. Logger.WriteLine("Result [{0}]", result.Length);
  2287. return result;
  2288. }
  2289. }
  2290. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  2291. {
  2292. using (Logger.CreateCallstack())
  2293. {
  2294. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  2295. Logger.WriteLine("Result [{0}]", result.Length);
  2296. return result;
  2297. }
  2298. }
  2299. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  2300. {
  2301. using (Logger.CreateCallstack())
  2302. {
  2303. Logger.WriteLine("Name [{0}]", name);
  2304. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  2305. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2306. return result;
  2307. }
  2308. }
  2309. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  2310. {
  2311. using (Logger.CreateCallstack())
  2312. {
  2313. Logger.WriteLine("Name [{0}]", name);
  2314. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  2315. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  2316. return result;
  2317. }
  2318. }
  2319. private void LogInvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2320. {
  2321. Logger.WriteLine("Name [{0}]", name);
  2322. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  2323. Logger.WriteLine("Binder [{0}]", binder);
  2324. Logger.WriteLine("Target [{0}]", target);
  2325. if (args != null)
  2326. {
  2327. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  2328. for (int i = 0; i < args.Length; ++i)
  2329. {
  2330. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  2331. }
  2332. }
  2333. Logger.WriteLine("Culture [{0}]", culture);
  2334. if (namedParameters != null)
  2335. {
  2336. foreach (string namedParameter in namedParameters)
  2337. {
  2338. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  2339. }
  2340. }
  2341. }
  2342. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  2343. {
  2344. using (Logger.CreateCallstack())
  2345. {
  2346. object result;
  2347. try
  2348. {
  2349. bool wasLogging = Logger.Logging;
  2350. if (wasLogging)
  2351. {
  2352. // factored out to reduce this method complexity
  2353. LogInvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2354. }
  2355. if (target == null)
  2356. {
  2357. throw Logger.WriteException(new ArgumentNullException(nameof(target)));
  2358. }
  2359. Type type = target.GetType();
  2360. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  2361. // that fails to match method, if integer value is provided to enum argument
  2362. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  2363. // This does not happen if we do not implement IReflect, though no idea why.
  2364. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  2365. // and call the only instance directly.
  2366. // Calling MethodInfo.Invoke with int values for enum arguments works.
  2367. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  2368. // the method with given name does not exist at all)
  2369. MethodInfo method = null;
  2370. PropertyInfo property = null;
  2371. // would be way too difficult to implement the below involving named arguments
  2372. if (namedParameters == null)
  2373. {
  2374. try
  2375. {
  2376. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  2377. method = type.GetMethod(name, bindingFlags);
  2378. if (args == null)
  2379. {
  2380. throw Logger.WriteException(new ArgumentNullException(nameof(args)));
  2381. }
  2382. if (method != null)
  2383. {
  2384. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  2385. ParameterInfo[] parameters = method.GetParameters();
  2386. if (args.Length < parameters.Length)
  2387. {
  2388. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  2389. object[] args2 = new object[parameters.Length];
  2390. for (int i = 0; i < parameters.Length; i++)
  2391. {
  2392. if (i < args.Length)
  2393. {
  2394. args2[i] = args[i];
  2395. }
  2396. else
  2397. {
  2398. if (!parameters[i].IsOptional)
  2399. {
  2400. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  2401. args2 = null;
  2402. break;
  2403. }
  2404. else
  2405. {
  2406. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  2407. args2[i] = parameters[i].DefaultValue;
  2408. }
  2409. }
  2410. }
  2411. if (args2 != null)
  2412. {
  2413. args = args2;
  2414. }
  2415. }
  2416. }
  2417. else if (args.Length == 1) // sanity check
  2418. {
  2419. property = type.GetProperty(name, bindingFlags);
  2420. }
  2421. }
  2422. catch (AmbiguousMatchException e)
  2423. {
  2424. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  2425. }
  2426. }
  2427. if (method != null)
  2428. {
  2429. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  2430. result = method.Invoke(target, invokeAttr, binder, args, culture);
  2431. }
  2432. else if (property != null)
  2433. {
  2434. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  2435. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  2436. result = null;
  2437. }
  2438. else
  2439. {
  2440. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  2441. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  2442. }
  2443. if (!wasLogging && Logger.Logging)
  2444. {
  2445. Logger.WriteLine("Invoking member {0} enabled debug logging", name);
  2446. // Might call LogInvokeMember here, but it's not really useful.
  2447. }
  2448. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  2449. }
  2450. catch (Exception e)
  2451. {
  2452. Logger.WriteLine("Error [{0}]", e);
  2453. throw;
  2454. }
  2455. return result;
  2456. }
  2457. }
  2458. Type IReflect.UnderlyingSystemType
  2459. {
  2460. get { return GetType(); }
  2461. }
  2462. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  2463. internal Logger Logger { get; private set; }
  2464. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  2465. internal bool TestHandlesClosedInternal { get; set; }
  2466. internal Dictionary<string, string> RawConfiguration { get; private set; }
  2467. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  2468. internal string IniFilePathInternal { get { return _iniFilePath; } }
  2469. private ExeSessionProcess _process;
  2470. private DateTime _lastOutput;
  2471. private ElementLogReader _reader;
  2472. private SessionLogReader _logReader;
  2473. private readonly IList<OperationResultBase> _operationResults;
  2474. private readonly IList<Action> _events;
  2475. private AutoResetEvent _eventsEvent;
  2476. private ManualResetEvent _choiceEvent;
  2477. private bool _disposed;
  2478. private string _executablePath;
  2479. private string _additionalExecutableArguments;
  2480. private bool _defaultConfiguration;
  2481. private bool _disableVersionCheck;
  2482. private string _iniFilePath;
  2483. private TimeSpan _reconnectTime;
  2484. private string _sessionLogPath;
  2485. private bool _aborted;
  2486. private int _logUnique;
  2487. private string _xmlLogPath;
  2488. private FileTransferProgressEventHandler _fileTransferProgress;
  2489. private int _progressHandling;
  2490. private bool _guardProcessWithJob;
  2491. private string _homePath;
  2492. #if !NETSTANDARD
  2493. private string _executableProcessUserName;
  2494. private SecureString _executableProcessPassword;
  2495. #endif
  2496. private StringCollection _error;
  2497. private bool _ignoreFailed;
  2498. private TimeSpan _sessionTimeout;
  2499. private QueryReceivedEventHandler _queryReceived;
  2500. private bool _throwStdOut;
  2501. }
  2502. }