Session.cs 119 KB

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