SshData.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Globalization;
  6. namespace Renci.SshNet.Common
  7. {
  8. /// <summary>
  9. /// Base ssh data serialization type
  10. /// </summary>
  11. public abstract class SshData
  12. {
  13. private static readonly Encoding _ascii = new ASCIIEncoding();
  14. #if SILVERLIGHT
  15. private static readonly Encoding _utf8 = Encoding.UTF8;
  16. #else
  17. private static readonly Encoding _utf8 = Encoding.Default;
  18. #endif
  19. /// <summary>
  20. /// Data byte array that hold message unencrypted data
  21. /// </summary>
  22. private List<byte> _data;
  23. private int _readerIndex;
  24. /// <summary>
  25. /// Gets a value indicating whether all data from the buffer has been read.
  26. /// </summary>
  27. /// <value>
  28. /// <c>true</c> if this instance is end of data; otherwise, <c>false</c>.
  29. /// </value>
  30. public bool IsEndOfData
  31. {
  32. get
  33. {
  34. return this._readerIndex >= this._data.Count();
  35. }
  36. }
  37. private byte[] _loadedData;
  38. /// <summary>
  39. /// Gets the index that represents zero in current data type.
  40. /// </summary>
  41. /// <value>
  42. /// The index of the zero reader.
  43. /// </value>
  44. protected virtual int ZeroReaderIndex
  45. {
  46. get
  47. {
  48. return 0;
  49. }
  50. }
  51. /// <summary>
  52. /// Gets data bytes array
  53. /// </summary>
  54. /// <returns>Byte array representation of data structure.</returns>
  55. public virtual byte[] GetBytes()
  56. {
  57. this._data = new List<byte>();
  58. this.SaveData();
  59. return this._data.ToArray();
  60. }
  61. internal T OfType<T>() where T : SshData, new()
  62. {
  63. var result = new T();
  64. result.LoadBytes(this._loadedData);
  65. result.LoadData();
  66. return result;
  67. }
  68. /// <summary>
  69. /// Loads data from specified bytes.
  70. /// </summary>
  71. /// <param name="value">Bytes array.</param>
  72. /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
  73. public void Load(byte[] value)
  74. {
  75. if (value == null)
  76. throw new ArgumentNullException("value");
  77. this.LoadBytes(value);
  78. this.LoadData();
  79. }
  80. /// <summary>
  81. /// Called when type specific data need to be loaded.
  82. /// </summary>
  83. protected abstract void LoadData();
  84. /// <summary>
  85. /// Called when type specific data need to be saved.
  86. /// </summary>
  87. protected abstract void SaveData();
  88. /// <summary>
  89. /// Loads data bytes into internal buffer.
  90. /// </summary>
  91. /// <param name="bytes">The bytes.</param>
  92. /// <exception cref="ArgumentNullException"><paramref name="bytes"/> is null.</exception>
  93. protected void LoadBytes(byte[] bytes)
  94. {
  95. // Note about why I check for null here, and in Load(byte[]) in this class.
  96. // This method is called by several other classes, such as SshNet.Messages.Message, SshNet.Sftp.SftpMessage.
  97. if (bytes == null)
  98. throw new ArgumentNullException("bytes");
  99. this.ResetReader();
  100. this._loadedData = bytes;
  101. this._data = new List<byte>(bytes);
  102. }
  103. /// <summary>
  104. /// Resets internal data reader index.
  105. /// </summary>
  106. protected void ResetReader()
  107. {
  108. this._readerIndex = this.ZeroReaderIndex; // Set to 1 to skip first byte which specifies message type
  109. }
  110. /// <summary>
  111. /// Reads all data left in internal buffer at current position.
  112. /// </summary>
  113. /// <returns>An array of bytes containing the remaining data in the internal buffer.</returns>
  114. protected byte[] ReadBytes()
  115. {
  116. var data = new byte[this._data.Count - this._readerIndex];
  117. this._data.CopyTo(this._readerIndex, data, 0, data.Length);
  118. return data;
  119. }
  120. /// <summary>
  121. /// Reads next specified number of bytes data type from internal buffer.
  122. /// </summary>
  123. /// <param name="length">Number of bytes to read.</param>
  124. /// <returns>An array of bytes that was read from the internal buffer.</returns>
  125. /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is greater than the internal buffer size.</exception>
  126. protected byte[] ReadBytes(int length)
  127. {
  128. // Note that this also prevents allocating non-relevant lengths, such as if length is greater than _data.Count but less than int.MaxValue.
  129. // For the nerds, the condition translates to: if (length > data.Count && length < int.MaxValue)
  130. // Which probably would cause all sorts of exception, most notably OutOfMemoryException.
  131. if (length > this._data.Count)
  132. throw new ArgumentOutOfRangeException("length");
  133. var result = new byte[length];
  134. this._data.CopyTo(this._readerIndex, result, 0, length);
  135. this._readerIndex += length;
  136. return result;
  137. }
  138. /// <summary>
  139. /// Reads next byte data type from internal buffer.
  140. /// </summary>
  141. /// <returns>Byte read.</returns>
  142. protected byte ReadByte()
  143. {
  144. return this.ReadBytes(1).FirstOrDefault();
  145. }
  146. /// <summary>
  147. /// Reads next boolean data type from internal buffer.
  148. /// </summary>
  149. /// <returns>Boolean read.</returns>
  150. protected bool ReadBoolean()
  151. {
  152. return this.ReadByte() == 0 ? false : true;
  153. }
  154. /// <summary>
  155. /// Reads next uint16 data type from internal buffer.
  156. /// </summary>
  157. /// <returns>uint16 read</returns>
  158. protected UInt16 ReadUInt16()
  159. {
  160. var data = this.ReadBytes(2);
  161. return (ushort)(data[0] << 8 | data[1]);
  162. }
  163. /// <summary>
  164. /// Reads next uint32 data type from internal buffer.
  165. /// </summary>
  166. /// <returns>uint32 read</returns>
  167. protected UInt32 ReadUInt32()
  168. {
  169. var data = this.ReadBytes(4);
  170. return (uint)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]);
  171. }
  172. /// <summary>
  173. /// Reads next uint64 data type from internal buffer.
  174. /// </summary>
  175. /// <returns>uint64 read</returns>
  176. protected UInt64 ReadUInt64()
  177. {
  178. var data = this.ReadBytes(8);
  179. return ((ulong)data[0] << 56 | (ulong)data[1] << 48 | (ulong)data[2] << 40 | (ulong)data[3] << 32 | (ulong)data[4] << 24 | (ulong)data[5] << 16 | (ulong)data[6] << 8 | data[7]);
  180. }
  181. /// <summary>
  182. /// Reads next int64 data type from internal buffer.
  183. /// </summary>
  184. /// <returns>int64 read</returns>
  185. protected Int64 ReadInt64()
  186. {
  187. var data = this.ReadBytes(8);
  188. return (int)(data[0] << 56 | data[1] << 48 | data[2] << 40 | data[3] << 32 | data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  189. }
  190. /// <summary>
  191. /// Reads next string data type from internal buffer.
  192. /// </summary>
  193. /// <returns>string read</returns>
  194. protected string ReadAsciiString()
  195. {
  196. var length = this.ReadUInt32();
  197. if (length > (uint)int.MaxValue)
  198. {
  199. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  200. }
  201. return _ascii.GetString(this.ReadBytes((int)length), 0, (int)length);
  202. }
  203. /// <summary>
  204. /// Reads next string data type from internal buffer.
  205. /// </summary>
  206. /// <returns>string read</returns>
  207. protected string ReadString()
  208. {
  209. return this.ReadString(SshData._utf8);
  210. }
  211. /// <summary>
  212. /// Reads next string data type from internal buffer.
  213. /// </summary>
  214. /// <returns>string read</returns>
  215. protected string ReadString(Encoding encoding)
  216. {
  217. var length = this.ReadUInt32();
  218. if (length > (uint)int.MaxValue)
  219. {
  220. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  221. }
  222. return encoding.GetString(this.ReadBytes((int)length), 0, (int)length);
  223. }
  224. /// <summary>
  225. /// Reads next string data type from internal buffer.
  226. /// </summary>
  227. /// <returns>string read</returns>
  228. protected byte[] ReadBinaryString()
  229. {
  230. var length = this.ReadUInt32();
  231. if (length > (uint)int.MaxValue)
  232. {
  233. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  234. }
  235. return this.ReadBytes((int)length);
  236. }
  237. /// <summary>
  238. /// Reads next mpint data type from internal buffer.
  239. /// </summary>
  240. /// <returns>mpint read.</returns>
  241. protected BigInteger ReadBigInt()
  242. {
  243. var length = this.ReadUInt32();
  244. var data = this.ReadBytes((int)length);
  245. return new BigInteger(data.Reverse().ToArray());
  246. }
  247. /// <summary>
  248. /// Reads next name-list data type from internal buffer.
  249. /// </summary>
  250. /// <returns>String array or read data..</returns>
  251. protected string[] ReadNamesList()
  252. {
  253. var namesList = this.ReadString();
  254. return namesList.Split(',');
  255. }
  256. /// <summary>
  257. /// Reads next extension-pair data type from internal buffer.
  258. /// </summary>
  259. /// <returns>Extensions pair dictionary.</returns>
  260. protected IDictionary<string, string> ReadExtensionPair()
  261. {
  262. Dictionary<string, string> result = new Dictionary<string, string>();
  263. while (this._readerIndex < this._data.Count)
  264. {
  265. var extensionName = this.ReadString();
  266. var extensionData = this.ReadString();
  267. result.Add(extensionName, extensionData);
  268. }
  269. return result;
  270. }
  271. /// <summary>
  272. /// Writes bytes array data into internal buffer.
  273. /// </summary>
  274. /// <param name="data">Byte array data to write.</param>
  275. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  276. protected void Write(IEnumerable<byte> data)
  277. {
  278. this._data.AddRange(data);
  279. }
  280. /// <summary>
  281. /// Writes byte data into internal buffer.
  282. /// </summary>
  283. /// <param name="data">Byte data to write.</param>
  284. protected void Write(byte data)
  285. {
  286. this._data.Add(data);
  287. }
  288. /// <summary>
  289. /// Writes boolean data into internal buffer.
  290. /// </summary>
  291. /// <param name="data">Boolean data to write.</param>
  292. protected void Write(bool data)
  293. {
  294. if (data)
  295. {
  296. this.Write(1);
  297. }
  298. else
  299. {
  300. this.Write(0);
  301. }
  302. }
  303. /// <summary>
  304. /// Writes uint16 data into internal buffer.
  305. /// </summary>
  306. /// <param name="data">uint16 data to write.</param>
  307. protected void Write(UInt16 data)
  308. {
  309. this.Write(data.GetBytes());
  310. }
  311. /// <summary>
  312. /// Writes uint32 data into internal buffer.
  313. /// </summary>
  314. /// <param name="data">uint32 data to write.</param>
  315. protected void Write(UInt32 data)
  316. {
  317. this.Write(data.GetBytes());
  318. }
  319. /// <summary>
  320. /// Writes uint64 data into internal buffer.
  321. /// </summary>
  322. /// <param name="data">uint64 data to write.</param>
  323. protected void Write(UInt64 data)
  324. {
  325. this.Write(data.GetBytes());
  326. }
  327. /// <summary>
  328. /// Writes int64 data into internal buffer.
  329. /// </summary>
  330. /// <param name="data">int64 data to write.</param>
  331. protected void Write(Int64 data)
  332. {
  333. this.Write(data.GetBytes());
  334. }
  335. /// <summary>
  336. /// Writes string data into internal buffer as ASCII.
  337. /// </summary>
  338. /// <param name="data">string data to write.</param>
  339. protected void WriteAscii(string data)
  340. {
  341. this.Write(data, SshData._ascii);
  342. }
  343. /// <summary>
  344. /// Writes string data into internal buffer using default encoding.
  345. /// </summary>
  346. /// <param name="data">string data to write.</param>
  347. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  348. protected void Write(string data)
  349. {
  350. this.Write(data, SshData._utf8);
  351. }
  352. /// <summary>
  353. /// Writes string data into internal buffer using the specified encoding.
  354. /// </summary>
  355. /// <param name="data">string data to write.</param>
  356. /// <param name="encoding">The character encoding to use.</param>
  357. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  358. /// <exception cref="ArgumentNullException"><paramref name="encoding"/> is null.</exception>
  359. protected void Write(string data, Encoding encoding)
  360. {
  361. if (data == null)
  362. throw new ArgumentNullException("data");
  363. if (encoding == null)
  364. throw new ArgumentNullException("encoding");
  365. var bytes = encoding.GetBytes(data);
  366. this.Write((uint)bytes.Length);
  367. this.Write(bytes);
  368. }
  369. /// <summary>
  370. /// Writes string data into internal buffer.
  371. /// </summary>
  372. /// <param name="data">string data to write.</param>
  373. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  374. protected void WriteBinaryString(byte[] data)
  375. {
  376. if (data == null)
  377. throw new ArgumentNullException("data");
  378. this.Write((uint)data.Length);
  379. this._data.AddRange(data);
  380. }
  381. /// <summary>
  382. /// Writes mpint data into internal buffer.
  383. /// </summary>
  384. /// <param name="data">mpint data to write.</param>
  385. protected void Write(BigInteger data)
  386. {
  387. var bytes = data.ToByteArray().Reverse().ToList();
  388. this.Write((uint)bytes.Count);
  389. this.Write(bytes);
  390. }
  391. /// <summary>
  392. /// Writes name-list data into internal buffer.
  393. /// </summary>
  394. /// <param name="data">name-list data to write.</param>
  395. protected void Write(string[] data)
  396. {
  397. this.WriteAscii(string.Join(",", data));
  398. }
  399. /// <summary>
  400. /// Writes extension-pair data into internal buffer.
  401. /// </summary>
  402. /// <param name="data">extension-pair data to write.</param>
  403. protected void Write(IDictionary<string, string> data)
  404. {
  405. foreach (var item in data)
  406. {
  407. this.WriteAscii(item.Key);
  408. this.WriteAscii(item.Value);
  409. }
  410. }
  411. }
  412. }