Session.cs 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  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. using Microsoft.Win32;
  10. using System.Diagnostics;
  11. using System.Security;
  12. using System.Text.RegularExpressions;
  13. namespace WinSCP
  14. {
  15. [Guid("38649D44-B839-4F2C-A9DC-5D45EEA4B5E9")]
  16. [ComVisible(true)]
  17. public enum SynchronizationMode
  18. {
  19. Local = 0,
  20. Remote = 1,
  21. Both = 2,
  22. }
  23. [Guid("3F770EC1-35F5-4A7B-A000-46A2F7A213D8")]
  24. [ComVisible(true)]
  25. [Flags]
  26. public enum SynchronizationCriteria
  27. {
  28. None = 0x00,
  29. Time = 0x01,
  30. Size = 0x02,
  31. Either = Time | Size,
  32. }
  33. [Guid("6C441F60-26AA-44FC-9B93-08884768507B")]
  34. [ComVisible(true)]
  35. [Flags]
  36. public enum EnumerationOptions
  37. {
  38. None = 0x00,
  39. AllDirectories = 0x01,
  40. MatchDirectories = 0x02,
  41. EnumerateDirectories = 0x04,
  42. }
  43. public delegate void OutputDataReceivedEventHandler(object sender, OutputDataReceivedEventArgs e);
  44. public delegate void FileTransferredEventHandler(object sender, TransferEventArgs e);
  45. public delegate void FileTransferProgressEventHandler(object sender, FileTransferProgressEventArgs e);
  46. public delegate void FailedEventHandler(object sender, FailedEventArgs e);
  47. [Guid("56FFC5CE-3867-4EF0-A3B5-CFFBEB99EA35")]
  48. [ClassInterface(Constants.ClassInterface)]
  49. [ComVisible(true)]
  50. [ComSourceInterfaces(typeof(ISessionEvents))]
  51. public sealed class Session : IDisposable, IReflect
  52. {
  53. public string ExecutablePath { get { return _executablePath; } set { CheckNotOpened(); _executablePath = value; } }
  54. public string ExecutableProcessUserName { get { return _executableProcessUserName; } set { CheckNotOpened(); _executableProcessUserName = value; } }
  55. public SecureString ExecutableProcessPassword { get { return _executableProcessPassword; } set { CheckNotOpened(); _executableProcessPassword = value; } }
  56. public string AdditionalExecutableArguments { get { return _additionalExecutableArguments; } set { CheckNotOpened(); _additionalExecutableArguments = value; } }
  57. [Obsolete("Use AddRawConfiguration")]
  58. public bool DefaultConfiguration { get { return _defaultConfiguration; } set { CheckNotOpened(); _defaultConfiguration = value; } }
  59. public bool DisableVersionCheck { get { return GetDisableVersionCheck(); } set { CheckNotOpened(); _disableVersionCheck = value; } }
  60. [Obsolete("Use AddRawConfiguration")]
  61. public string IniFilePath { get { return _iniFilePath; } set { CheckNotOpened(); _iniFilePath = value; } }
  62. public TimeSpan ReconnectTime { get { return _reconnectTime; } set { CheckNotOpened(); _reconnectTime = value; } }
  63. public int ReconnectTimeInMilliseconds { get { return Tools.TimeSpanToMilliseconds(ReconnectTime); } set { ReconnectTime = Tools.MillisecondsToTimeSpan(value); } }
  64. public string DebugLogPath { get { CheckNotDisposed(); return Logger.LogPath; } set { CheckNotDisposed(); Logger.LogPath = value; } }
  65. public int DebugLogLevel { get { CheckNotDisposed(); return Logger.LogLevel; } set { CheckNotDisposed(); Logger.LogLevel = value; } }
  66. public string SessionLogPath { get { return _sessionLogPath; } set { CheckNotOpened(); _sessionLogPath = value; } }
  67. public string XmlLogPath { get { return _xmlLogPath; } set { CheckNotOpened(); _xmlLogPath = value; } }
  68. #if DEBUG
  69. public bool GuardProcessWithJob { get { return GuardProcessWithJobInternal; } set { GuardProcessWithJobInternal = value; } }
  70. public bool TestHandlesClosed { get { return TestHandlesClosedInternal; } set { TestHandlesClosedInternal = value; } }
  71. #endif
  72. public string HomePath { get { CheckOpened(); return _homePath; } }
  73. public TimeSpan Timeout { get; set; }
  74. public StringCollection Output { get; private set; }
  75. public bool Opened { get { CheckNotDisposed(); return (_process != null); } }
  76. public event FileTransferredEventHandler FileTransferred;
  77. public event FailedEventHandler Failed;
  78. public event OutputDataReceivedEventHandler OutputDataReceived;
  79. public event FileTransferProgressEventHandler FileTransferProgress
  80. {
  81. add
  82. {
  83. using (Logger.CreateCallstackAndLock())
  84. {
  85. CheckNotOpened();
  86. _fileTransferProgress += value;
  87. }
  88. }
  89. remove
  90. {
  91. using (Logger.CreateCallstackAndLock())
  92. {
  93. CheckNotOpened();
  94. _fileTransferProgress -= value;
  95. }
  96. }
  97. }
  98. public Session()
  99. {
  100. Logger = new Logger();
  101. using (Logger.CreateCallstackAndLock())
  102. {
  103. Timeout = new TimeSpan(0, 1, 0);
  104. _reconnectTime = new TimeSpan(0, 2, 0); // keep in sync with TScript::OptionImpl
  105. Output = new StringCollection();
  106. _operationResults = new List<OperationResultBase>();
  107. _events = new List<Action>();
  108. _eventsEvent = new AutoResetEvent(false);
  109. _disposed = false;
  110. _defaultConfiguration = true;
  111. _logUnique = 0;
  112. _guardProcessWithJob = true;
  113. RawConfiguration = new Dictionary<string, string>();
  114. }
  115. }
  116. public void Dispose()
  117. {
  118. using (Logger.CreateCallstackAndLock())
  119. {
  120. _disposed = true;
  121. Cleanup();
  122. Logger.Dispose();
  123. if (_eventsEvent != null)
  124. {
  125. _eventsEvent.Close();
  126. _eventsEvent = null;
  127. }
  128. GC.SuppressFinalize(this);
  129. }
  130. }
  131. public void Abort()
  132. {
  133. using (Logger.CreateCallstack())
  134. {
  135. CheckOpened();
  136. _aborted = true;
  137. // double-check
  138. if (_process != null)
  139. {
  140. _process.Abort();
  141. }
  142. }
  143. }
  144. public void Open(SessionOptions sessionOptions)
  145. {
  146. using (Logger.CreateCallstackAndLock())
  147. {
  148. CheckNotDisposed();
  149. if (Opened)
  150. {
  151. throw new InvalidOperationException("Session is already opened");
  152. }
  153. try
  154. {
  155. SetupTempPath();
  156. _process = ExeSessionProcess.CreateForSession(this);
  157. _process.OutputDataReceived += ProcessOutputDataReceived;
  158. _process.Start();
  159. GotOutput();
  160. // setup batch mode
  161. WriteCommand("option batch on");
  162. WriteCommand("option confirm off");
  163. object reconnectTimeValue;
  164. if (ReconnectTime != TimeSpan.MaxValue)
  165. {
  166. reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
  167. }
  168. else
  169. {
  170. reconnectTimeValue = "off";
  171. }
  172. string reconnectTimeCommand =
  173. string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
  174. WriteCommand(reconnectTimeCommand);
  175. string command;
  176. string log;
  177. SessionOptionsToUrlAndSwitches(sessionOptions, false, out command, out log);
  178. const string openCommand = "open ";
  179. command = openCommand + command;
  180. log = openCommand + log;
  181. WriteCommand(command, log);
  182. string logExplanation =
  183. string.Format(CultureInfo.CurrentCulture,
  184. "(response log file {0} was not created). This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
  185. XmlLogPath);
  186. // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
  187. do
  188. {
  189. if (_process.HasExited && !File.Exists(XmlLogPath))
  190. {
  191. string[] output = new string[Output.Count];
  192. Output.CopyTo(output, 0);
  193. Logger.WriteCounters();
  194. Logger.WriteProcesses();
  195. _process.WriteStatus();
  196. string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
  197. if (_process.ExitCode < 0)
  198. {
  199. exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
  200. }
  201. throw new SessionLocalException(this,
  202. string.Format(CultureInfo.CurrentCulture,
  203. "WinSCP process terminated with exit code {0} and output \"{1}\", without responding {2}",
  204. exitCode, string.Join(Environment.NewLine, output), logExplanation));
  205. }
  206. Thread.Sleep(50);
  207. CheckForTimeout(
  208. string.Format(CultureInfo.CurrentCulture,
  209. "WinSCP has not responded in time {0}",
  210. logExplanation));
  211. } while (!File.Exists(XmlLogPath));
  212. _logReader = new SessionLogReader(this);
  213. _logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);
  214. // special variant of ElementLogReader that throws when closing element (</session>) is encountered
  215. _reader = new SessionElementLogReader(_logReader);
  216. // Skip "open" command <group>
  217. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  218. {
  219. ReadElement(groupReader, LogReadFlags.ThrowFailures);
  220. }
  221. WriteCommand("pwd");
  222. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  223. using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
  224. {
  225. while (cwdReader.Read(0))
  226. {
  227. string value;
  228. if (cwdReader.GetEmptyElementValue("cwd", out value))
  229. {
  230. _homePath = value;
  231. }
  232. }
  233. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  234. }
  235. }
  236. catch(Exception e)
  237. {
  238. Logger.WriteLine("Exception: {0}", e);
  239. Cleanup();
  240. throw;
  241. }
  242. }
  243. }
  244. public string ScanFingerprint(SessionOptions sessionOptions)
  245. {
  246. using (Logger.CreateCallstackAndLock())
  247. {
  248. string result;
  249. CheckNotDisposed();
  250. if (Opened)
  251. {
  252. throw new InvalidOperationException("Session is already opened");
  253. }
  254. try
  255. {
  256. string command;
  257. string log; // unused
  258. SessionOptionsToUrlAndSwitches(sessionOptions, true, out command, out log);
  259. string additionalArguments = "/fingerprintscan " + command;
  260. _process = ExeSessionProcess.CreateForConsole(this, additionalArguments);
  261. _process.OutputDataReceived += ProcessOutputDataReceived;
  262. _process.Start();
  263. GotOutput();
  264. while (!_process.HasExited)
  265. {
  266. Thread.Sleep(50);
  267. CheckForTimeout();
  268. }
  269. string output = string.Join(Environment.NewLine, new List<string>(Output).ToArray());
  270. if (_process.ExitCode == 0)
  271. {
  272. result = output;
  273. }
  274. else
  275. {
  276. throw new SessionRemoteException(this, output);
  277. }
  278. }
  279. catch (Exception e)
  280. {
  281. Logger.WriteLine("Exception: {0}", e);
  282. throw;
  283. }
  284. finally
  285. {
  286. Cleanup();
  287. }
  288. return result;
  289. }
  290. }
  291. public void Close()
  292. {
  293. using (Logger.CreateCallstackAndLock())
  294. {
  295. CheckOpened();
  296. Cleanup();
  297. }
  298. }
  299. public RemoteDirectoryInfo ListDirectory(string path)
  300. {
  301. using (Logger.CreateCallstackAndLock())
  302. {
  303. CheckOpened();
  304. WriteCommand(string.Format(CultureInfo.InvariantCulture, "ls -- \"{0}\"", Tools.ArgumentEscape(IncludeTrailingSlash(path))));
  305. RemoteDirectoryInfo result = new RemoteDirectoryInfo();
  306. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  307. using (ElementLogReader lsReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("ls", LogReadFlags.ThrowFailures))
  308. {
  309. string destination = null;
  310. if (lsReader.TryWaitForEmptyElement("destination", 0))
  311. {
  312. lsReader.GetEmptyElementValue("destination", out destination);
  313. }
  314. if ((destination != null) && lsReader.TryWaitForNonEmptyElement("files", 0))
  315. {
  316. destination = IncludeTrailingSlash(destination);
  317. using (ElementLogReader filesReader = lsReader.CreateLogReader())
  318. {
  319. while (filesReader.TryWaitForNonEmptyElement("file", 0))
  320. {
  321. RemoteFileInfo fileInfo = new RemoteFileInfo();
  322. using (ElementLogReader fileReader = filesReader.CreateLogReader())
  323. {
  324. while (fileReader.Read(0))
  325. {
  326. string value;
  327. if (fileReader.GetEmptyElementValue("filename", out value))
  328. {
  329. fileInfo.Name = value;
  330. fileInfo.FullName = destination + value;
  331. }
  332. else
  333. {
  334. ReadFile(fileInfo, fileReader);
  335. }
  336. }
  337. result.AddFile(fileInfo);
  338. }
  339. }
  340. }
  341. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  342. }
  343. else
  344. {
  345. // "files" not found, keep reading, we expect "failure"
  346. // This happens only in case of fatal errors,
  347. // in case of normal error (non existing folder),
  348. // the "failure" is caught in "group" already, before the "ls".
  349. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  350. // only if not "failure", throw "files" not found
  351. throw SessionLocalException.CreateElementNotFound(this, "files");
  352. }
  353. }
  354. return result;
  355. }
  356. }
  357. private IEnumerable<RemoteFileInfo> DoEnumerateRemoteFiles(string path, Regex regex, EnumerationOptions options)
  358. {
  359. bool allDirectories = ((options & EnumerationOptions.AllDirectories) == EnumerationOptions.AllDirectories);
  360. bool matchDirectories = ((options & EnumerationOptions.MatchDirectories) == EnumerationOptions.MatchDirectories);
  361. bool enumerateDirectories = ((options & EnumerationOptions.EnumerateDirectories) == EnumerationOptions.EnumerateDirectories);
  362. if (enumerateDirectories && !allDirectories)
  363. {
  364. throw new ArgumentException("Cannot use enumeration option EnumerateDirectories without AllDirectories");
  365. }
  366. if (enumerateDirectories && matchDirectories)
  367. {
  368. throw new ArgumentException("Cannot combine enumeration option EnumerateDirectories with MatchDirectories");
  369. }
  370. // Need to use guarded method for the listing, see a comment in EnumerateRemoteFiles
  371. RemoteDirectoryInfo directoryInfo = ListDirectory(path);
  372. foreach (RemoteFileInfo fileInfo in directoryInfo.Files)
  373. {
  374. if (!fileInfo.IsThisDirectory && !fileInfo.IsParentDirectory)
  375. {
  376. bool matches = regex.IsMatch(fileInfo.Name);
  377. bool enumerate;
  378. if (!fileInfo.IsDirectory)
  379. {
  380. enumerate = matches;
  381. }
  382. else
  383. {
  384. if (enumerateDirectories)
  385. {
  386. enumerate = true;
  387. }
  388. else if (matchDirectories)
  389. {
  390. enumerate = matches;
  391. }
  392. else
  393. {
  394. enumerate = false;
  395. }
  396. }
  397. if (enumerate)
  398. {
  399. yield return fileInfo;
  400. }
  401. if (fileInfo.IsDirectory && allDirectories)
  402. {
  403. foreach (RemoteFileInfo fileInfo2 in DoEnumerateRemoteFiles(CombinePaths(path, fileInfo.Name), regex, options))
  404. {
  405. yield return fileInfo2;
  406. }
  407. }
  408. }
  409. }
  410. }
  411. public IEnumerable<RemoteFileInfo> EnumerateRemoteFiles(string path, string mask, EnumerationOptions options)
  412. {
  413. // Note that this method exits as soon as DoEnumerateRemoteFiles is entered,
  414. // so the Session object is not guarded during the whole enumeration.
  415. // Though it should not matter as it uses only guarded methods (ListDirectory)
  416. // for the actual work on the session
  417. using (Logger.CreateCallstackAndLock())
  418. {
  419. CheckOpened();
  420. Regex regex = MaskToRegex(mask);
  421. return DoEnumerateRemoteFiles(path, regex, options);
  422. }
  423. }
  424. private static Regex MaskToRegex(string mask)
  425. {
  426. if (string.IsNullOrEmpty(mask) ||
  427. // *.* has to match even filename without dot
  428. (mask == "*.*"))
  429. {
  430. mask = "*";
  431. }
  432. return
  433. new Regex(
  434. '^' +
  435. mask
  436. .Replace(".", "[.]")
  437. .Replace("*", ".*")
  438. .Replace("?", ".") +
  439. '$',
  440. RegexOptions.IgnoreCase);
  441. }
  442. public TransferOperationResult PutFiles(string localPath, string remotePath, bool remove = false, TransferOptions options = null)
  443. {
  444. using (Logger.CreateCallstackAndLock())
  445. {
  446. if (options == null)
  447. {
  448. options = new TransferOptions();
  449. }
  450. CheckOpened();
  451. WriteCommand(
  452. string.Format(CultureInfo.InvariantCulture,
  453. "put {0} {1} -- \"{2}\" \"{3}\"",
  454. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  455. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  456. TransferOperationResult result = new TransferOperationResult();
  457. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  458. using (RegisterOperationResult(result))
  459. using (CreateProgressHandler())
  460. {
  461. TransferEventArgs args = null;
  462. bool mkdir = false;
  463. while (groupReader.Read(0))
  464. {
  465. if (groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag))
  466. {
  467. AddTransfer(result, args);
  468. args = TransferEventArgs.Read(groupReader);
  469. mkdir = false;
  470. }
  471. else if (groupReader.IsNonEmptyElement(TransferEventArgs.MkDirTag))
  472. {
  473. AddTransfer(result, args);
  474. args = null;
  475. mkdir = true;
  476. // For now, silently ignoring results (even errors)
  477. // of mkdir operation, including future chmod/touch
  478. }
  479. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  480. {
  481. if (!mkdir)
  482. {
  483. if (args == null)
  484. {
  485. throw new InvalidOperationException("Tag chmod before tag upload");
  486. }
  487. args.Chmod = ChmodEventArgs.Read(groupReader);
  488. }
  489. }
  490. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  491. {
  492. if (!mkdir)
  493. {
  494. if (args == null)
  495. {
  496. throw new InvalidOperationException("Tag touch before tag upload");
  497. }
  498. args.Touch = TouchEventArgs.Read(groupReader);
  499. }
  500. }
  501. }
  502. AddTransfer(result, args);
  503. }
  504. return result;
  505. }
  506. }
  507. private void AddTransfer(TransferOperationResult result, TransferEventArgs args)
  508. {
  509. if (args != null)
  510. {
  511. result.AddTransfer(args);
  512. RaiseFileTransferredEvent(args);
  513. }
  514. }
  515. public TransferOperationResult GetFiles(string remotePath, string localPath, bool remove = false, TransferOptions options = null)
  516. {
  517. using (Logger.CreateCallstackAndLock())
  518. {
  519. if (options == null)
  520. {
  521. options = new TransferOptions();
  522. }
  523. CheckOpened();
  524. WriteCommand(
  525. string.Format(CultureInfo.InvariantCulture, "get {0} {1} -- \"{2}\" \"{3}\"",
  526. BooleanSwitch(remove, "delete"), options.ToSwitches(),
  527. Tools.ArgumentEscape(remotePath), Tools.ArgumentEscape(localPath)));
  528. TransferOperationResult result = new TransferOperationResult();
  529. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  530. using (RegisterOperationResult(result))
  531. using (CreateProgressHandler())
  532. {
  533. TransferEventArgs args = null;
  534. while (groupReader.Read(0))
  535. {
  536. if (groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  537. {
  538. AddTransfer(result, args);
  539. args = TransferEventArgs.Read(groupReader);
  540. }
  541. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  542. {
  543. // When "downloading and deleting" a folder,
  544. // we get "rm" tag without preceeding "download" tag.
  545. // So we use only the first "rm" tag after preceeding "download" tag,
  546. // silently ignoring the others
  547. if ((args != null) && (args.Removal == null))
  548. {
  549. args.Removal = RemovalEventArgs.Read(groupReader);
  550. }
  551. }
  552. }
  553. AddTransfer(result, args);
  554. }
  555. return result;
  556. }
  557. }
  558. public RemovalOperationResult RemoveFiles(string path)
  559. {
  560. using (Logger.CreateCallstackAndLock())
  561. {
  562. CheckOpened();
  563. WriteCommand(string.Format(CultureInfo.InvariantCulture, "rm -- \"{0}\"", Tools.ArgumentEscape(path)));
  564. RemovalOperationResult result = new RemovalOperationResult();
  565. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  566. using (RegisterOperationResult(result))
  567. {
  568. while (groupReader.Read(0))
  569. {
  570. if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  571. {
  572. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  573. }
  574. }
  575. }
  576. return result;
  577. }
  578. }
  579. public SynchronizationResult SynchronizeDirectories(
  580. SynchronizationMode mode, string localPath, string remotePath,
  581. bool removeFiles, bool mirror = false, SynchronizationCriteria criteria = SynchronizationCriteria.Time,
  582. TransferOptions options = null)
  583. {
  584. using (Logger.CreateCallstackAndLock())
  585. {
  586. if (options == null)
  587. {
  588. options = new TransferOptions();
  589. }
  590. CheckOpened();
  591. if (removeFiles && (mode == SynchronizationMode.Both))
  592. {
  593. throw new ArgumentException("Cannot delete files in synchronization mode Both");
  594. }
  595. if (mirror && (mode == SynchronizationMode.Both))
  596. {
  597. throw new ArgumentException("Cannot mirror files in synchronization mode Both");
  598. }
  599. if ((criteria != SynchronizationCriteria.Time) && (mode == SynchronizationMode.Both))
  600. {
  601. throw new ArgumentException("Only Time criteria is allowed in synchronization mode Both");
  602. }
  603. string modeName;
  604. switch (mode)
  605. {
  606. case SynchronizationMode.Local:
  607. modeName = "local";
  608. break;
  609. case SynchronizationMode.Remote:
  610. modeName = "remote";
  611. break;
  612. case SynchronizationMode.Both:
  613. modeName = "both";
  614. break;
  615. default:
  616. throw new ArgumentOutOfRangeException("mode");
  617. }
  618. string criteriaName;
  619. switch (criteria)
  620. {
  621. case SynchronizationCriteria.None:
  622. criteriaName = "none";
  623. break;
  624. case SynchronizationCriteria.Time:
  625. criteriaName = "time";
  626. break;
  627. case SynchronizationCriteria.Size:
  628. criteriaName = "size";
  629. break;
  630. case SynchronizationCriteria.Either:
  631. criteriaName = "either";
  632. break;
  633. default:
  634. throw new ArgumentOutOfRangeException("criteria");
  635. }
  636. WriteCommand(
  637. string.Format(CultureInfo.InvariantCulture,
  638. "synchronize {0} {1} {2} {3} -criteria=\"{4}\" -- \"{5}\" \"{6}\"",
  639. modeName,
  640. BooleanSwitch(removeFiles, "delete"),
  641. BooleanSwitch(mirror, "mirror"),
  642. options.ToSwitches(),
  643. criteriaName,
  644. Tools.ArgumentEscape(localPath), Tools.ArgumentEscape(remotePath)));
  645. return ReadSynchronizeDirectories();
  646. }
  647. }
  648. private SynchronizationResult ReadSynchronizeDirectories()
  649. {
  650. using (Logger.CreateCallstack())
  651. {
  652. SynchronizationResult result = new SynchronizationResult();
  653. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  654. using (RegisterOperationResult(result))
  655. using (CreateProgressHandler())
  656. {
  657. bool transferIsUpload = false;
  658. TransferEventArgs transfer = null;
  659. while (groupReader.Read(0))
  660. {
  661. bool transferWillBeUpload;
  662. if ((transferWillBeUpload = groupReader.IsNonEmptyElement(TransferEventArgs.UploadTag)) ||
  663. groupReader.IsNonEmptyElement(TransferEventArgs.DownloadTag))
  664. {
  665. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  666. transfer = TransferEventArgs.Read(groupReader);
  667. transferIsUpload = transferWillBeUpload;
  668. }
  669. else if (groupReader.IsNonEmptyElement(RemovalEventArgs.Tag))
  670. {
  671. result.AddRemoval(RemovalEventArgs.Read(groupReader));
  672. }
  673. else if (groupReader.IsNonEmptyElement(ChmodEventArgs.Tag))
  674. {
  675. if (transfer == null)
  676. {
  677. throw new InvalidOperationException("Tag chmod before tag download");
  678. }
  679. transfer.Chmod = ChmodEventArgs.Read(groupReader);
  680. }
  681. else if (groupReader.IsNonEmptyElement(TouchEventArgs.Tag))
  682. {
  683. if (transfer == null)
  684. {
  685. throw new InvalidOperationException("Tag touch before tag download");
  686. }
  687. transfer.Touch = TouchEventArgs.Read(groupReader);
  688. }
  689. }
  690. AddSynchronizationTransfer(result, transferIsUpload, transfer);
  691. }
  692. return result;
  693. }
  694. }
  695. public CommandExecutionResult ExecuteCommand(string command)
  696. {
  697. using (Logger.CreateCallstackAndLock())
  698. {
  699. CheckOpened();
  700. WriteCommand(string.Format(CultureInfo.InvariantCulture, "call {0}", command));
  701. CommandExecutionResult result = new CommandExecutionResult();
  702. // registering before creating group reader, so that
  703. // it is still registered, when group reader is read to the end in its .Dispose();
  704. using (RegisterOperationResult(result))
  705. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  706. using (ElementLogReader callReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("call", LogReadFlags.ThrowFailures))
  707. {
  708. while (callReader.Read(0))
  709. {
  710. string value;
  711. if (callReader.GetEmptyElementValue("output", out value))
  712. {
  713. result.Output = value;
  714. }
  715. if (callReader.GetEmptyElementValue("erroroutput", out value))
  716. {
  717. result.ErrorOutput = value;
  718. }
  719. if (callReader.GetEmptyElementValue("exitcode", out value))
  720. {
  721. result.ExitCode = int.Parse(value, CultureInfo.InvariantCulture);
  722. }
  723. }
  724. }
  725. return result;
  726. }
  727. }
  728. public RemoteFileInfo GetFileInfo(string path)
  729. {
  730. using (Logger.CreateCallstackAndLock())
  731. {
  732. CheckOpened();
  733. return DoGetFileInfo(path);
  734. }
  735. }
  736. public bool FileExists(string path)
  737. {
  738. using (Logger.CreateCallstackAndLock())
  739. {
  740. CheckOpened();
  741. try
  742. {
  743. DoGetFileInfo(path);
  744. return true;
  745. }
  746. catch (SessionRemoteException)
  747. {
  748. return false;
  749. }
  750. }
  751. }
  752. public byte[] CalculateFileChecksum(string algorithm, string path)
  753. {
  754. using (Logger.CreateCallstackAndLock())
  755. {
  756. WriteCommand(string.Format(CultureInfo.InvariantCulture, "checksum -- \"{0}\" \"{1}\"", Tools.ArgumentEscape(algorithm), Tools.ArgumentEscape(path)));
  757. string hex = null;
  758. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  759. using (ElementLogReader checksumReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("checksum", LogReadFlags.ThrowFailures))
  760. {
  761. while (checksumReader.Read(0))
  762. {
  763. string value;
  764. if (checksumReader.GetEmptyElementValue("checksum", out value))
  765. {
  766. hex = value;
  767. }
  768. }
  769. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  770. }
  771. int len = hex.Length;
  772. if ((len % 2) != 0)
  773. {
  774. string error = string.Format(CultureInfo.CurrentCulture, "Invalid string representation of checksum - {0}", hex);
  775. throw new SessionLocalException(this, error);
  776. }
  777. int count = len / 2;
  778. byte[] bytes = new byte[count];
  779. for (int i = 0; i < count; i++)
  780. {
  781. bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  782. }
  783. return bytes;
  784. }
  785. }
  786. public void CreateDirectory(string path)
  787. {
  788. using (Logger.CreateCallstackAndLock())
  789. {
  790. CheckOpened();
  791. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mkdir \"{0}\"", Tools.ArgumentEscape(path)));
  792. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  793. using (ElementLogReader mkdirReader = groupReader.WaitForNonEmptyElementAndCreateLogReader(TransferEventArgs.MkDirTag, LogReadFlags.ThrowFailures))
  794. {
  795. ReadElement(mkdirReader, 0);
  796. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  797. }
  798. }
  799. }
  800. public void MoveFile(string sourcePath, string targetPath)
  801. {
  802. using (Logger.CreateCallstackAndLock())
  803. {
  804. CheckOpened();
  805. WriteCommand(string.Format(CultureInfo.InvariantCulture, "mv \"{0}\" \"{1}\"", Tools.ArgumentEscape(sourcePath), Tools.ArgumentEscape(targetPath)));
  806. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  807. {
  808. if (!groupReader.TryWaitForNonEmptyElement("mv", LogReadFlags.ThrowFailures))
  809. {
  810. throw new SessionRemoteException(this, string.Format(CultureInfo.CurrentCulture, "{0} not found.", sourcePath));
  811. }
  812. else
  813. {
  814. using (ElementLogReader mvReader = groupReader.CreateLogReader())
  815. {
  816. ReadElement(mvReader, 0);
  817. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  818. }
  819. }
  820. }
  821. }
  822. }
  823. // This is not static method only to make it visible to COM
  824. public string EscapeFileMask(string fileMask)
  825. {
  826. if (fileMask == null)
  827. {
  828. throw new ArgumentNullException("fileMask");
  829. }
  830. int lastSlash = fileMask.LastIndexOf('/');
  831. string path = lastSlash > 0 ? fileMask.Substring(0, lastSlash + 1) : string.Empty;
  832. string mask = lastSlash > 0 ? fileMask.Substring(lastSlash + 1) : fileMask;
  833. // Keep in sync with EscapeFileMask in GenerateUrl.cpp
  834. mask = mask.Replace("[", "[[]").Replace("*", "[*]").Replace("?", "[?]");
  835. return path + mask;
  836. }
  837. public string TranslateRemotePathToLocal(string remotePath, string remoteRoot, string localRoot)
  838. {
  839. if (remotePath == null)
  840. {
  841. throw new ArgumentNullException("remotePath");
  842. }
  843. if (remoteRoot == null)
  844. {
  845. throw new ArgumentNullException("remoteRoot");
  846. }
  847. if (localRoot == null)
  848. {
  849. throw new ArgumentNullException("localRoot");
  850. }
  851. if ((localRoot.Length > 0) && !localRoot.EndsWith("\\", StringComparison.Ordinal))
  852. {
  853. localRoot += "\\";
  854. }
  855. // not adding to empty root paths, because the path may not even start with slash
  856. if ((remoteRoot.Length > 0) && !remoteRoot.EndsWith("/", StringComparison.Ordinal))
  857. {
  858. remoteRoot += "/";
  859. }
  860. string localPath;
  861. // special case
  862. if (remotePath == remoteRoot)
  863. {
  864. localPath = localRoot;
  865. }
  866. else
  867. {
  868. if (!remotePath.StartsWith(remoteRoot, StringComparison.Ordinal))
  869. {
  870. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "{0} does not start with {1}", remotePath, remoteRoot));
  871. }
  872. string subPath = remotePath.Substring(remoteRoot.Length);
  873. // can happen only when remoteRoot is empty
  874. if (subPath.StartsWith("/", StringComparison.Ordinal))
  875. {
  876. subPath = subPath.Substring(1);
  877. }
  878. subPath = subPath.Replace('/', '\\');
  879. localPath = localRoot + subPath;
  880. }
  881. return localPath;
  882. }
  883. public string TranslateLocalPathToRemote(string localPath, string localRoot, string remoteRoot)
  884. {
  885. if (localPath == null)
  886. {
  887. throw new ArgumentNullException("localPath");
  888. }
  889. if (localRoot == null)
  890. {
  891. throw new ArgumentNullException("localRoot");
  892. }
  893. if (remoteRoot == null)
  894. {
  895. throw new ArgumentNullException("remoteRoot");
  896. }
  897. if ((localRoot.Length > 0) && !localRoot.EndsWith("\\", StringComparison.Ordinal))
  898. {
  899. localRoot += "\\";
  900. }
  901. // not adding to empty root paths, because the path may not even start with slash
  902. if ((remoteRoot.Length > 0) && !remoteRoot.EndsWith("/", StringComparison.Ordinal))
  903. {
  904. remoteRoot += "/";
  905. }
  906. string remotePath;
  907. // special case
  908. if (localPath == localRoot)
  909. {
  910. remotePath = remoteRoot;
  911. }
  912. else
  913. {
  914. if (!localPath.StartsWith(localRoot, StringComparison.Ordinal))
  915. {
  916. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "{0} does not start with {1}", localPath, localRoot));
  917. }
  918. string subPath = localPath.Substring(localRoot.Length);
  919. // can happen only when localRoot is empty
  920. if (subPath.StartsWith("\\", StringComparison.Ordinal))
  921. {
  922. subPath = subPath.Substring(1);
  923. }
  924. subPath = subPath.Replace('\\', '/');
  925. remotePath = remoteRoot + subPath;
  926. }
  927. return remotePath;
  928. }
  929. public string CombinePaths(string path1, string path2)
  930. {
  931. if (path1 == null)
  932. {
  933. throw new ArgumentNullException("path1");
  934. }
  935. if (path2 == null)
  936. {
  937. throw new ArgumentNullException("path2");
  938. }
  939. string result;
  940. if (path2.StartsWith("/", StringComparison.Ordinal))
  941. {
  942. result = path2;
  943. }
  944. else
  945. {
  946. result =
  947. path1 +
  948. ((path1.Length == 0) || (path2.Length == 0) || path1.EndsWith("/", StringComparison.Ordinal) ? string.Empty : "/") +
  949. path2;
  950. }
  951. return result;
  952. }
  953. public void AddRawConfiguration(string setting, string value)
  954. {
  955. CheckNotOpened();
  956. RawConfiguration.Add(setting, value);
  957. }
  958. [ComRegisterFunction]
  959. private static void ComRegister(Type t)
  960. {
  961. string subKey = GetTypeLibKey(t);
  962. Assembly assembly = Assembly.GetAssembly(t);
  963. object[] attributes = assembly.GetCustomAttributes(typeof(GuidAttribute), false);
  964. if (attributes.Length == 0)
  965. {
  966. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot find {0} attribute for assembly {1}", typeof(GuidAttribute), assembly));
  967. }
  968. GuidAttribute guidAttribute = (GuidAttribute)attributes[0];
  969. Registry.ClassesRoot.CreateSubKey(subKey).SetValue(null, guidAttribute.Value);
  970. }
  971. [ComUnregisterFunction]
  972. private static void ComUnregister(Type t)
  973. {
  974. string subKey = GetTypeLibKey(t);
  975. Registry.ClassesRoot.DeleteSubKey(subKey, false);
  976. }
  977. private void ReadFile(RemoteFileInfo fileInfo, CustomLogReader fileReader)
  978. {
  979. using (Logger.CreateCallstack())
  980. {
  981. string value;
  982. if (fileReader.GetEmptyElementValue("type", out value))
  983. {
  984. fileInfo.FileType = value[0];
  985. }
  986. else if (fileReader.GetEmptyElementValue("size", out value))
  987. {
  988. fileInfo.Length = long.Parse(value, CultureInfo.InvariantCulture);
  989. }
  990. else if (fileReader.GetEmptyElementValue("modification", out value))
  991. {
  992. fileInfo.LastWriteTime = XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Local);
  993. }
  994. else if (fileReader.GetEmptyElementValue("permissions", out value))
  995. {
  996. fileInfo.FilePermissions = FilePermissions.CreateReadOnlyFromText(value);
  997. }
  998. else if (fileReader.GetEmptyElementValue("owner", out value))
  999. {
  1000. fileInfo.Owner = value;
  1001. }
  1002. else if (fileReader.GetEmptyElementValue("group", out value))
  1003. {
  1004. fileInfo.Group = value;
  1005. }
  1006. }
  1007. }
  1008. internal static string BooleanSwitch(bool flag, string name)
  1009. {
  1010. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", name) : null;
  1011. }
  1012. internal static string BooleanSwitch(bool flag, string onName, string offName)
  1013. {
  1014. return flag ? string.Format(CultureInfo.InvariantCulture, "-{0}", onName) : string.Format(CultureInfo.InvariantCulture, "-{0}", offName);
  1015. }
  1016. private void AddSynchronizationTransfer(SynchronizationResult result, bool transferIsUpload, TransferEventArgs transfer)
  1017. {
  1018. if (transfer != null)
  1019. {
  1020. if (transferIsUpload)
  1021. {
  1022. result.AddUpload(transfer);
  1023. }
  1024. else
  1025. {
  1026. result.AddDownload(transfer);
  1027. }
  1028. RaiseFileTransferredEvent(transfer);
  1029. }
  1030. }
  1031. private static string IncludeTrailingSlash(string path)
  1032. {
  1033. if (!string.IsNullOrEmpty(path) && !path.EndsWith("/", StringComparison.Ordinal))
  1034. {
  1035. path += '/';
  1036. }
  1037. return path;
  1038. }
  1039. private void Cleanup()
  1040. {
  1041. using (Logger.CreateCallstack())
  1042. {
  1043. if (_process != null)
  1044. {
  1045. Logger.WriteLine("Terminating process");
  1046. try
  1047. {
  1048. try
  1049. {
  1050. WriteCommand("exit");
  1051. _process.Close();
  1052. }
  1053. finally
  1054. {
  1055. _process.Dispose();
  1056. _process = null;
  1057. }
  1058. }
  1059. catch (Exception e)
  1060. {
  1061. Logger.WriteLine("Process cleanup Exception: {0}", e);
  1062. }
  1063. }
  1064. Logger.WriteLine("Disposing log readers");
  1065. if (_reader != null)
  1066. {
  1067. _reader.Dispose();
  1068. _reader = null;
  1069. }
  1070. if (_logReader != null)
  1071. {
  1072. _logReader.Dispose();
  1073. _logReader = null;
  1074. }
  1075. // Cleanup log file
  1076. if ((XmlLogPath != null) && File.Exists(XmlLogPath))
  1077. {
  1078. Logger.WriteLine("Deleting XML log file [{0}]", XmlLogPath);
  1079. try
  1080. {
  1081. File.Delete(XmlLogPath);
  1082. }
  1083. catch (DirectoryNotFoundException e)
  1084. {
  1085. Logger.WriteLine("XML log cleanup DirectoryNotFoundException: {0}", e);
  1086. }
  1087. catch (IOException e)
  1088. {
  1089. Logger.WriteLine("XML log cleanup IOException: {0}", e);
  1090. }
  1091. catch (UnauthorizedAccessException e)
  1092. {
  1093. Logger.WriteLine("XML log cleanup UnauthorizedAccessException: {0}", e);
  1094. }
  1095. _xmlLogPath = null;
  1096. }
  1097. }
  1098. }
  1099. private void WriteCommand(string command)
  1100. {
  1101. WriteCommand(command, command);
  1102. }
  1103. private void WriteCommand(string command, string log)
  1104. {
  1105. Logger.WriteLine("Command: [{0}]", log);
  1106. _process.ExecuteCommand(command);
  1107. GotOutput();
  1108. }
  1109. private static void ReadElement(CustomLogReader reader, LogReadFlags flags)
  1110. {
  1111. while (reader.Read(flags))
  1112. {
  1113. }
  1114. }
  1115. private void SessionOptionsToUrlAndSwitches(SessionOptions sessionOptions, bool scanFingerprint, out string command, out string log)
  1116. {
  1117. using (Logger.CreateCallstack())
  1118. {
  1119. if (sessionOptions.WebdavSecure)
  1120. {
  1121. if (sessionOptions.Protocol != Protocol.Webdav)
  1122. {
  1123. throw new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav.");
  1124. }
  1125. }
  1126. string head;
  1127. switch (sessionOptions.Protocol)
  1128. {
  1129. case Protocol.Sftp:
  1130. head = "sftp://";
  1131. break;
  1132. case Protocol.Scp:
  1133. head = "scp://";
  1134. break;
  1135. case Protocol.Ftp:
  1136. head = "ftp://";
  1137. break;
  1138. case Protocol.Webdav:
  1139. if (!sessionOptions.WebdavSecure)
  1140. {
  1141. head = "http://";
  1142. }
  1143. else
  1144. {
  1145. head = "https://";
  1146. }
  1147. break;
  1148. default:
  1149. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol));
  1150. }
  1151. bool hasUsername;
  1152. if (!scanFingerprint)
  1153. {
  1154. hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
  1155. if (hasUsername)
  1156. {
  1157. head += UriEscape(sessionOptions.UserName);
  1158. }
  1159. }
  1160. else
  1161. {
  1162. hasUsername = false;
  1163. }
  1164. string url = head;
  1165. string logUrl = head;
  1166. if ((sessionOptions.SecurePassword != null) && !scanFingerprint)
  1167. {
  1168. if (!hasUsername)
  1169. {
  1170. throw new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not.");
  1171. }
  1172. url += ":" + UriEscape(sessionOptions.Password);
  1173. logUrl += ":***";
  1174. }
  1175. string tail = string.Empty;
  1176. if (hasUsername)
  1177. {
  1178. tail += "@";
  1179. }
  1180. if (string.IsNullOrEmpty(sessionOptions.HostName))
  1181. {
  1182. throw new ArgumentException("SessionOptions.HostName is not set.");
  1183. }
  1184. // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
  1185. // but it works anyway...
  1186. tail += UriEscape(sessionOptions.HostName);
  1187. if (sessionOptions.PortNumber != 0)
  1188. {
  1189. tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
  1190. }
  1191. if (!string.IsNullOrEmpty(sessionOptions.WebdavRoot) && !scanFingerprint)
  1192. {
  1193. if (sessionOptions.Protocol != Protocol.Webdav)
  1194. {
  1195. throw new ArgumentException("SessionOptions.WebdavRoot is set, but SessionOptions.Protocol is not Protocol.Webdav.");
  1196. }
  1197. tail += sessionOptions.WebdavRoot;
  1198. }
  1199. url += tail;
  1200. logUrl += tail;
  1201. string arguments = SessionOptionsToSwitches(sessionOptions, scanFingerprint);
  1202. Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, "-rawsettings");
  1203. if (!string.IsNullOrEmpty(arguments))
  1204. {
  1205. arguments = " " + arguments;
  1206. }
  1207. // Switches should (and particularly the -rawsettings MUST) come after the URL
  1208. command = "\"" + Tools.ArgumentEscape(url) + "\"" + arguments;
  1209. log = "\"" + Tools.ArgumentEscape(logUrl) + "\"" + arguments;
  1210. }
  1211. }
  1212. private string SessionOptionsToSwitches(SessionOptions sessionOptions, bool scanFingerprint)
  1213. {
  1214. using (Logger.CreateCallstack())
  1215. {
  1216. List<string> switches = new List<string>();
  1217. if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
  1218. (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey && !scanFingerprint))
  1219. {
  1220. if (!sessionOptions.IsSsh)
  1221. {
  1222. throw new ArgumentException("SessionOptions.SshHostKeyFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp.");
  1223. }
  1224. string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
  1225. if (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
  1226. {
  1227. Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
  1228. sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
  1229. }
  1230. switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
  1231. }
  1232. else
  1233. {
  1234. if (sessionOptions.IsSsh && DefaultConfigurationInternal && !scanFingerprint)
  1235. {
  1236. throw new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.SshHostKeyFingerprint is not set.");
  1237. }
  1238. }
  1239. if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && !scanFingerprint)
  1240. {
  1241. if (!sessionOptions.IsSsh)
  1242. {
  1243. throw new ArgumentException("SessionOptions.SshPrivateKeyPath is set, but SessionOptions.Protocol is neither Protocol.Sftp nor Protocol.Scp.");
  1244. }
  1245. switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
  1246. }
  1247. if (!string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath) && !scanFingerprint)
  1248. {
  1249. if (!sessionOptions.IsTls)
  1250. {
  1251. throw new ArgumentException("SessionOptions.TlsClientCertificatePath is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled.");
  1252. }
  1253. switches.Add(FormatSwitch("clientcert", sessionOptions.TlsClientCertificatePath));
  1254. }
  1255. if (!string.IsNullOrEmpty(sessionOptions.PrivateKeyPassphrase) && !scanFingerprint)
  1256. {
  1257. if (string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath) && string.IsNullOrEmpty(sessionOptions.TlsClientCertificatePath))
  1258. {
  1259. throw new ArgumentException("SessionOptions.PrivateKeyPassphrase is set, but neither SessionOptions.SshPrivateKeyPath nor SessionOptions.TlsClientCertificatePath is set.");
  1260. }
  1261. switches.Add(FormatSwitch("passphrase", sessionOptions.PrivateKeyPassphrase));
  1262. }
  1263. if (sessionOptions.FtpSecure != FtpSecure.None)
  1264. {
  1265. if (sessionOptions.Protocol != Protocol.Ftp)
  1266. {
  1267. throw new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp.");
  1268. }
  1269. switch (sessionOptions.FtpSecure)
  1270. {
  1271. case FtpSecure.Implicit:
  1272. switches.Add(FormatSwitch("implicit"));
  1273. break;
  1274. case FtpSecure.Explicit:
  1275. switches.Add(FormatSwitch("explicit"));
  1276. break;
  1277. default:
  1278. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure));
  1279. }
  1280. }
  1281. if ((!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
  1282. sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate) &&
  1283. !scanFingerprint)
  1284. {
  1285. if (!sessionOptions.IsTls)
  1286. {
  1287. throw new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, but neither SessionOptions.FtpSecure nor SessionOptions.WebdavSecure is enabled.");
  1288. }
  1289. string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
  1290. if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
  1291. {
  1292. Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
  1293. tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
  1294. }
  1295. switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
  1296. }
  1297. if ((sessionOptions.Protocol == Protocol.Ftp) && !scanFingerprint)
  1298. {
  1299. switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
  1300. }
  1301. switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));
  1302. return string.Join(" ", switches.ToArray());
  1303. }
  1304. }
  1305. private static string AddStarToList(string list)
  1306. {
  1307. return (string.IsNullOrEmpty(list) ? string.Empty : list + ";") + "*";
  1308. }
  1309. private RemoteFileInfo DoGetFileInfo(string path)
  1310. {
  1311. using (Logger.CreateCallstack())
  1312. {
  1313. WriteCommand(string.Format(CultureInfo.InvariantCulture, "stat -- \"{0}\"", Tools.ArgumentEscape(path)));
  1314. RemoteFileInfo fileInfo = new RemoteFileInfo();
  1315. using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
  1316. using (ElementLogReader statReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("stat", LogReadFlags.ThrowFailures))
  1317. {
  1318. while (statReader.Read(0))
  1319. {
  1320. string value;
  1321. if (statReader.GetEmptyElementValue("filename", out value))
  1322. {
  1323. string name = value;
  1324. int p = name.LastIndexOf('/');
  1325. if (p >= 0)
  1326. {
  1327. name = name.Substring(p + 1);
  1328. }
  1329. fileInfo.Name = name;
  1330. fileInfo.FullName = value;
  1331. }
  1332. else if (statReader.IsNonEmptyElement("file"))
  1333. {
  1334. using (ElementLogReader fileReader = statReader.CreateLogReader())
  1335. {
  1336. while (fileReader.Read(0))
  1337. {
  1338. ReadFile(fileInfo, fileReader);
  1339. }
  1340. }
  1341. }
  1342. }
  1343. groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
  1344. }
  1345. return fileInfo;
  1346. }
  1347. }
  1348. internal static string FormatSwitch(string key)
  1349. {
  1350. return string.Format(CultureInfo.InvariantCulture, "-{0}", key);
  1351. }
  1352. internal static string FormatSwitch(string key, string value)
  1353. {
  1354. return string.Format(CultureInfo.InvariantCulture, "-{0}=\"{1}\"", key, Tools.ArgumentEscape(value));
  1355. }
  1356. internal static string FormatSwitch(string key, int value)
  1357. {
  1358. return string.Format(CultureInfo.InvariantCulture, "-{0}={1}", key, value.ToString(CultureInfo.InvariantCulture));
  1359. }
  1360. internal static string FormatSwitch(string key, bool value)
  1361. {
  1362. return FormatSwitch(key, (value ? 1 : 0));
  1363. }
  1364. private static string UriEscape(string s)
  1365. {
  1366. return Uri.EscapeDataString(s);
  1367. }
  1368. internal void GotOutput()
  1369. {
  1370. _lastOutput = DateTime.Now;
  1371. }
  1372. private void ProcessOutputDataReceived(object sender, OutputDataReceivedEventArgs e)
  1373. {
  1374. Logger.WriteLine("Scheduling output: [{0}]", e.Data);
  1375. Output.InternalAdd(e.Data);
  1376. if (Output.Count > 1000)
  1377. {
  1378. Output.InternalRemoveFirst();
  1379. }
  1380. GotOutput();
  1381. ScheduleEvent(() => RaiseOutputDataReceived(e.Data));
  1382. }
  1383. private void ScheduleEvent(Action action)
  1384. {
  1385. lock (_events)
  1386. {
  1387. _events.Add(action);
  1388. _eventsEvent.Set();
  1389. }
  1390. }
  1391. internal void CheckForTimeout(string additional = null)
  1392. {
  1393. if (DateTime.Now - _lastOutput > Timeout)
  1394. {
  1395. string message = "Timeout waiting for WinSCP to respond";
  1396. if (additional != null)
  1397. {
  1398. message += " - " + additional;
  1399. }
  1400. throw new TimeoutException(message);
  1401. }
  1402. if (_aborted)
  1403. {
  1404. throw new SessionLocalException(this, "Aborted.");
  1405. }
  1406. }
  1407. private void RaiseFileTransferredEvent(TransferEventArgs args)
  1408. {
  1409. Logger.WriteLine("FileTransferredEvent: [{0}]", args.FileName);
  1410. if (FileTransferred != null)
  1411. {
  1412. FileTransferred(this, args);
  1413. }
  1414. }
  1415. internal void RaiseFailed(SessionRemoteException e)
  1416. {
  1417. Logger.WriteLine("Failed: [{0}]", e);
  1418. if (Failed != null)
  1419. {
  1420. Failed(this, new FailedEventArgs { Error = e });
  1421. }
  1422. foreach (OperationResultBase operationResult in _operationResults)
  1423. {
  1424. operationResult.AddFailure(e);
  1425. }
  1426. }
  1427. private void CheckNotDisposed()
  1428. {
  1429. if (_disposed)
  1430. {
  1431. throw new InvalidOperationException("Object is disposed");
  1432. }
  1433. if (_aborted)
  1434. {
  1435. throw new InvalidOperationException("Session was aborted");
  1436. }
  1437. }
  1438. private void CheckOpened()
  1439. {
  1440. if (!Opened)
  1441. {
  1442. throw new InvalidOperationException("Session is not opened");
  1443. }
  1444. }
  1445. private void CheckNotOpened()
  1446. {
  1447. if (Opened)
  1448. {
  1449. throw new InvalidOperationException("Session is already opened");
  1450. }
  1451. }
  1452. private void RaiseOutputDataReceived(string data)
  1453. {
  1454. Logger.WriteLine("Output: [{0}]", data);
  1455. if (OutputDataReceived != null)
  1456. {
  1457. OutputDataReceived(this, new OutputDataReceivedEventArgs(data));
  1458. }
  1459. }
  1460. internal void DispatchEvents(int interval)
  1461. {
  1462. DateTime start = DateTime.Now;
  1463. while (_eventsEvent.WaitOne(interval, false))
  1464. {
  1465. lock (_events)
  1466. {
  1467. foreach (Action action in _events)
  1468. {
  1469. action();
  1470. }
  1471. _events.Clear();
  1472. }
  1473. interval -= (int) (DateTime.Now - start).TotalMilliseconds;
  1474. if (interval < 0)
  1475. {
  1476. break;
  1477. }
  1478. start = DateTime.Now;
  1479. }
  1480. }
  1481. private IDisposable RegisterOperationResult(OperationResultBase operationResult)
  1482. {
  1483. _operationResults.Add(operationResult);
  1484. return new OperationResultGuard(this, operationResult);
  1485. }
  1486. internal void UnregisterOperationResult(OperationResultBase operationResult)
  1487. {
  1488. _operationResults.Remove(operationResult);
  1489. }
  1490. internal bool WantsProgress
  1491. {
  1492. get
  1493. {
  1494. return (_fileTransferProgress != null);
  1495. }
  1496. }
  1497. private IDisposable CreateProgressHandler()
  1498. {
  1499. using (Logger.CreateCallstack())
  1500. {
  1501. _progressHandling++;
  1502. return new ProgressHandler(this);
  1503. }
  1504. }
  1505. internal void DisableProgressHandling()
  1506. {
  1507. using (Logger.CreateCallstack())
  1508. {
  1509. if (_progressHandling <= 0)
  1510. {
  1511. throw new InvalidOperationException("Progress handling not enabled");
  1512. }
  1513. // make sure we process all pending progress events
  1514. DispatchEvents(0);
  1515. _progressHandling--;
  1516. }
  1517. }
  1518. internal void ProcessProgress(FileTransferProgressEventArgs args)
  1519. {
  1520. ScheduleEvent(() => Progress(args));
  1521. }
  1522. private void Progress(FileTransferProgressEventArgs args)
  1523. {
  1524. if ((_progressHandling >= 0) && WantsProgress)
  1525. {
  1526. _fileTransferProgress(this, args);
  1527. }
  1528. }
  1529. private void SetupTempPath()
  1530. {
  1531. using (Logger.CreateCallstack())
  1532. {
  1533. if (!string.IsNullOrEmpty(_xmlLogPath))
  1534. {
  1535. bool exists = File.Exists(_xmlLogPath);
  1536. Logger.WriteLine("Configured temporary file: {0} - Exists [{1}]", _xmlLogPath, exists);
  1537. if (exists)
  1538. {
  1539. throw new SessionLocalException(this, string.Format(CultureInfo.CurrentCulture, "Configured temporary file {0} already exists", _xmlLogPath));
  1540. }
  1541. }
  1542. else
  1543. {
  1544. string path = Path.GetTempPath();
  1545. Logger.WriteLine("Temporary folder: {0}", path);
  1546. string process = Process.GetCurrentProcess().Id.ToString("X4", CultureInfo.InvariantCulture);
  1547. string instance = GetHashCode().ToString("X8", CultureInfo.InvariantCulture);
  1548. string filename;
  1549. bool exists;
  1550. do
  1551. {
  1552. string uniqueStr = (_logUnique > 0 ? "." + _logUnique.ToString(CultureInfo.InvariantCulture) : string.Empty);
  1553. ++_logUnique;
  1554. filename = Path.Combine(path, "wscp" + process + "." + instance + uniqueStr + ".tmp");
  1555. exists = File.Exists(filename);
  1556. Logger.WriteLine("Temporary file [{0}] - Exists [{1}]", filename, exists);
  1557. }
  1558. while (exists);
  1559. _xmlLogPath = filename;
  1560. }
  1561. }
  1562. }
  1563. private bool GetDisableVersionCheck()
  1564. {
  1565. bool result = _disableVersionCheck;
  1566. #if DEBUG
  1567. string env = Environment.GetEnvironmentVariable("WINSCPNET_DISABLE_VERSION_CHECK");
  1568. int envFlag;
  1569. if (!string.IsNullOrEmpty(env) && int.TryParse(env, out envFlag))
  1570. {
  1571. result = (envFlag != 0);
  1572. }
  1573. #endif
  1574. return result;
  1575. }
  1576. private static string GetTypeLibKey(Type t)
  1577. {
  1578. return "CLSID\\{" + t.GUID.ToString().ToUpperInvariant() + "}\\TypeLib";
  1579. }
  1580. FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
  1581. {
  1582. using (Logger.CreateCallstack())
  1583. {
  1584. Logger.WriteLine("Name [{0}]", name);
  1585. FieldInfo result = GetType().GetField(name, bindingAttr);
  1586. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1587. return result;
  1588. }
  1589. }
  1590. FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
  1591. {
  1592. using (Logger.CreateCallstack())
  1593. {
  1594. FieldInfo[] result = GetType().GetFields(bindingAttr);
  1595. Logger.WriteLine("Fields [{0}]", result.Length);
  1596. return result;
  1597. }
  1598. }
  1599. MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
  1600. {
  1601. using (Logger.CreateCallstack())
  1602. {
  1603. Logger.WriteLine("Name [{0}]", name);
  1604. MemberInfo[] result = GetType().GetMember(name, bindingAttr);
  1605. Logger.WriteLine("Result [{0}]", result.Length);
  1606. return result;
  1607. }
  1608. }
  1609. MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
  1610. {
  1611. using (Logger.CreateCallstack())
  1612. {
  1613. MemberInfo[] result = GetType().GetMembers(bindingAttr);
  1614. Logger.WriteLine("Result [{0}]", result.Length);
  1615. return result;
  1616. }
  1617. }
  1618. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
  1619. {
  1620. using (Logger.CreateCallstack())
  1621. {
  1622. Logger.WriteLine("Name [{0}]", name);
  1623. MethodInfo result = GetType().GetMethod(name, bindingAttr);
  1624. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1625. return result;
  1626. }
  1627. }
  1628. MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
  1629. {
  1630. using (Logger.CreateCallstack())
  1631. {
  1632. Logger.WriteLine("Name [{0}]", name);
  1633. MethodInfo result = GetType().GetMethod(name, bindingAttr, binder, types, modifiers);
  1634. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1635. return result;
  1636. }
  1637. }
  1638. MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
  1639. {
  1640. using (Logger.CreateCallstack())
  1641. {
  1642. MethodInfo[] result = GetType().GetMethods(bindingAttr);
  1643. Logger.WriteLine("Result [{0}]", result.Length);
  1644. return result;
  1645. }
  1646. }
  1647. PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
  1648. {
  1649. using (Logger.CreateCallstack())
  1650. {
  1651. PropertyInfo[] result = GetType().GetProperties(bindingAttr);
  1652. Logger.WriteLine("Result [{0}]", result.Length);
  1653. return result;
  1654. }
  1655. }
  1656. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
  1657. {
  1658. using (Logger.CreateCallstack())
  1659. {
  1660. Logger.WriteLine("Name [{0}]", name);
  1661. PropertyInfo result = GetType().GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
  1662. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1663. return result;
  1664. }
  1665. }
  1666. PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
  1667. {
  1668. using (Logger.CreateCallstack())
  1669. {
  1670. Logger.WriteLine("Name [{0}]", name);
  1671. PropertyInfo result = GetType().GetProperty(name, bindingAttr);
  1672. Logger.WriteLine("Result [{0}]", result != null ? result.Name : "null");
  1673. return result;
  1674. }
  1675. }
  1676. object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
  1677. {
  1678. using (Logger.CreateCallstack())
  1679. {
  1680. object result;
  1681. try
  1682. {
  1683. if (Logger.Logging)
  1684. {
  1685. Logger.WriteLine("Name [{0}]", name);
  1686. Logger.WriteLine("BindingFlags [{0}]", invokeAttr);
  1687. Logger.WriteLine("Binder [{0}]", binder);
  1688. Logger.WriteLine("Target [{0}]", target);
  1689. if (args != null)
  1690. {
  1691. Logger.WriteLine("Args [{0}] [{1}]", args.Length, modifiers != null ? modifiers.Length.ToString(CultureInfo.InvariantCulture) : "null");
  1692. for (int i = 0; i < args.Length; ++i)
  1693. {
  1694. Logger.WriteLine("Arg [{0}] [{1}] [{1}] [{2}]", i, args[i], (args[i] != null ? args[i].GetType().ToString() : "null"), (modifiers != null ? modifiers[i].ToString() : "null"));
  1695. }
  1696. }
  1697. Logger.WriteLine("Culture [{0}]", culture);
  1698. if (namedParameters != null)
  1699. {
  1700. foreach (string namedParameter in namedParameters)
  1701. {
  1702. Logger.WriteLine("NamedParameter [{0}]", namedParameter);
  1703. }
  1704. }
  1705. }
  1706. if (target == null)
  1707. {
  1708. throw new ArgumentNullException("target");
  1709. }
  1710. Type type = target.GetType();
  1711. // RuntimeType.InvokeMember below calls into Binder.BindToMethod (Binder is OleAutBinder)
  1712. // that fails to match method, if integer value is provided to enum argument
  1713. // (SynchronizeDirectories with its SynchronizationMode and SynchronizationCriteria).
  1714. // This does not happen if we do not implement IReflect, though no idea why.
  1715. // So as a workaround we check, if the method has no overloads (what is always true for Session),
  1716. // and call the only instance directly.
  1717. // Calling MethodInfo.Invoke with int values for enum arguments works.
  1718. // Only as a fallback, we call InvokeMember (what is currently actually used only when
  1719. // the method with given name does not exist at all)
  1720. MethodInfo method = null;
  1721. PropertyInfo property = null;
  1722. // would be way too difficult to implement the below involving named arguments
  1723. if (namedParameters == null)
  1724. {
  1725. try
  1726. {
  1727. BindingFlags bindingFlags = invokeAttr | BindingFlags.Instance | BindingFlags.Public;
  1728. method = type.GetMethod(name, bindingFlags);
  1729. if (args == null)
  1730. {
  1731. throw new ArgumentNullException("args");
  1732. }
  1733. if (method != null)
  1734. {
  1735. // MethodInfo.Invoke does not fill-in optional arguments (contrary to RuntimeType.InvokeMember)
  1736. ParameterInfo[] parameters = method.GetParameters();
  1737. if (args.Length < parameters.Length)
  1738. {
  1739. Logger.WriteLine("Provided less parameters [{0}] than defined [{1}]", args.Length, parameters.Length);
  1740. object[] args2 = new object[parameters.Length];
  1741. for (int i = 0; i < parameters.Length; i++)
  1742. {
  1743. if (i < args.Length)
  1744. {
  1745. args2[i] = args[i];
  1746. }
  1747. else
  1748. {
  1749. if (!parameters[i].IsOptional)
  1750. {
  1751. Logger.WriteLine("Parameter [{0}] of [{1}] is not optional", i, method);
  1752. args2 = null;
  1753. break;
  1754. }
  1755. else
  1756. {
  1757. Logger.WriteLine("Adding default value [{0}] for optional parameter [{1}]", parameters[i].DefaultValue, i);
  1758. args2[i] = parameters[i].DefaultValue;
  1759. }
  1760. }
  1761. }
  1762. if (args2 != null)
  1763. {
  1764. args = args2;
  1765. }
  1766. }
  1767. }
  1768. else if (args.Length == 1) // sanity check
  1769. {
  1770. property = type.GetProperty(name, bindingFlags);
  1771. }
  1772. }
  1773. catch (AmbiguousMatchException e)
  1774. {
  1775. Logger.WriteLine("Unexpected ambiguous match [{0}]", e.Message);
  1776. }
  1777. }
  1778. if (method != null)
  1779. {
  1780. Logger.WriteLine("Invoking unambiguous method [{0}]", method);
  1781. result = method.Invoke(target, invokeAttr, binder, args, culture);
  1782. }
  1783. else if (property != null)
  1784. {
  1785. Logger.WriteLine("Setting unambiguous property [{0}]", property);
  1786. property.SetValue(target, args[0], invokeAttr, binder, null, culture);
  1787. result = null;
  1788. }
  1789. else
  1790. {
  1791. Logger.WriteLine("Invoking ambiguous/non-existing method 2 [{0}]", name);
  1792. result = type.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
  1793. }
  1794. Logger.WriteLine("Result [{0}] [{1}]", result, (result != null ? result.GetType().ToString() : "null"));
  1795. }
  1796. catch (Exception e)
  1797. {
  1798. Logger.WriteLine("Error [{0}]", e);
  1799. throw;
  1800. }
  1801. return result;
  1802. }
  1803. }
  1804. Type IReflect.UnderlyingSystemType
  1805. {
  1806. get { return GetType(); }
  1807. }
  1808. internal const string Namespace = "http://winscp.net/schema/session/1.0";
  1809. internal Logger Logger { get; private set; }
  1810. internal bool GuardProcessWithJobInternal { get { return _guardProcessWithJob; } set { CheckNotOpened(); _guardProcessWithJob = value; } }
  1811. internal bool TestHandlesClosedInternal { get; set; }
  1812. internal Dictionary<string, string> RawConfiguration { get; private set; }
  1813. internal bool DefaultConfigurationInternal { get { return _defaultConfiguration; } }
  1814. internal string IniFilePathInternal { get { return _iniFilePath; } }
  1815. private ExeSessionProcess _process;
  1816. private DateTime _lastOutput;
  1817. private ElementLogReader _reader;
  1818. private SessionLogReader _logReader;
  1819. private readonly IList<OperationResultBase> _operationResults;
  1820. private delegate void Action();
  1821. private readonly IList<Action> _events;
  1822. private AutoResetEvent _eventsEvent;
  1823. private bool _disposed;
  1824. private string _executablePath;
  1825. private string _additionalExecutableArguments;
  1826. private bool _defaultConfiguration;
  1827. private bool _disableVersionCheck;
  1828. private string _iniFilePath;
  1829. private TimeSpan _reconnectTime;
  1830. private string _sessionLogPath;
  1831. private bool _aborted;
  1832. private int _logUnique;
  1833. private string _xmlLogPath;
  1834. private FileTransferProgressEventHandler _fileTransferProgress;
  1835. private int _progressHandling;
  1836. private bool _guardProcessWithJob;
  1837. private string _homePath;
  1838. private string _executableProcessUserName;
  1839. private SecureString _executableProcessPassword;
  1840. }
  1841. }