SshData.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 Encoding _ascii = new ASCIIEncoding();
  14. #if SILVERLIGHT
  15. private static Encoding _utf8 = Encoding.UTF8;
  16. #else
  17. private static 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></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 (uint)(data[0] << 56 | data[1] << 48 | data[2] << 40 | data[3] << 32 | data[4] << 24 | data[5] << 16 | 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. var length = this.ReadUInt32();
  210. if (length > (uint)int.MaxValue)
  211. {
  212. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  213. }
  214. return _utf8.GetString(this.ReadBytes((int)length), 0, (int)length);
  215. }
  216. /// <summary>
  217. /// Reads next string data type from internal buffer.
  218. /// </summary>
  219. /// <returns>string read</returns>
  220. protected byte[] ReadBinaryString()
  221. {
  222. var length = this.ReadUInt32();
  223. if (length > (uint)int.MaxValue)
  224. {
  225. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  226. }
  227. return this.ReadBytes((int)length);
  228. }
  229. /// <summary>
  230. /// Reads next mpint data type from internal buffer.
  231. /// </summary>
  232. /// <returns>mpint read.</returns>
  233. protected BigInteger ReadBigInt()
  234. {
  235. var length = this.ReadUInt32();
  236. var data = this.ReadBytes((int)length);
  237. return new BigInteger(data.Reverse().ToArray());
  238. }
  239. /// <summary>
  240. /// Reads next name-list data type from internal buffer.
  241. /// </summary>
  242. /// <returns></returns>
  243. protected string[] ReadNamesList()
  244. {
  245. var namesList = this.ReadString();
  246. return namesList.Split(',');
  247. }
  248. /// <summary>
  249. /// Reads next extension-pair data type from internal buffer.
  250. /// </summary>
  251. /// <returns></returns>
  252. protected IDictionary<string, string> ReadExtensionPair()
  253. {
  254. Dictionary<string, string> result = new Dictionary<string, string>();
  255. while (this._readerIndex < this._data.Count)
  256. {
  257. var extensionName = this.ReadString();
  258. var extensionData = this.ReadString();
  259. result.Add(extensionName, extensionData);
  260. }
  261. return result;
  262. }
  263. /// <summary>
  264. /// Writes bytes array data into internal buffer.
  265. /// </summary>
  266. /// <param name="data">Byte array data to write.</param>
  267. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  268. protected void Write(IEnumerable<byte> data)
  269. {
  270. this._data.AddRange(data);
  271. }
  272. /// <summary>
  273. /// Writes byte data into internal buffer.
  274. /// </summary>
  275. /// <param name="data">Byte data to write.</param>
  276. protected void Write(byte data)
  277. {
  278. this._data.Add(data);
  279. }
  280. /// <summary>
  281. /// Writes boolean data into internal buffer.
  282. /// </summary>
  283. /// <param name="data">Boolean data to write.</param>
  284. protected void Write(bool data)
  285. {
  286. if (data)
  287. {
  288. this.Write(1);
  289. }
  290. else
  291. {
  292. this.Write(0);
  293. }
  294. }
  295. /// <summary>
  296. /// Writes uint16 data into internal buffer.
  297. /// </summary>
  298. /// <param name="data">uint16 data to write.</param>
  299. protected void Write(UInt16 data)
  300. {
  301. this.Write(data.GetBytes());
  302. }
  303. /// <summary>
  304. /// Writes uint32 data into internal buffer.
  305. /// </summary>
  306. /// <param name="data">uint32 data to write.</param>
  307. protected void Write(UInt32 data)
  308. {
  309. this.Write(data.GetBytes());
  310. }
  311. /// <summary>
  312. /// Writes uint64 data into internal buffer.
  313. /// </summary>
  314. /// <param name="data">uint64 data to write.</param>
  315. protected void Write(UInt64 data)
  316. {
  317. this.Write(data.GetBytes());
  318. }
  319. /// <summary>
  320. /// Writes int64 data into internal buffer.
  321. /// </summary>
  322. /// <param name="data">int64 data to write.</param>
  323. protected void Write(Int64 data)
  324. {
  325. this.Write(data.GetBytes());
  326. }
  327. /// <summary>
  328. /// Writes string data into internal buffer using default encoding.
  329. /// </summary>
  330. /// <param name="data">string data to write.</param>
  331. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  332. protected void Write(string data)
  333. {
  334. if (data == null)
  335. throw new ArgumentNullException("data");
  336. var bytes = _utf8.GetBytes(data);
  337. this.Write((uint)bytes.Length);
  338. this.Write(bytes);
  339. }
  340. /// <summary>
  341. /// Writes string data into internal buffer as ASCII.
  342. /// </summary>
  343. /// <param name="data">string data to write.</param>
  344. protected void WriteAscii(string data)
  345. {
  346. if (data == null)
  347. throw new ArgumentNullException("data");
  348. var bytes = _ascii.GetBytes(data);
  349. this.Write((uint)bytes.Length);
  350. this.Write(bytes);
  351. }
  352. /// <summary>
  353. /// Writes string data into internal buffer.
  354. /// </summary>
  355. /// <param name="data">string data to write.</param>
  356. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  357. protected void WriteBinaryString(byte[] data)
  358. {
  359. if (data == null)
  360. throw new ArgumentNullException("data");
  361. this.Write((uint)data.Length);
  362. this._data.AddRange(data);
  363. }
  364. /// <summary>
  365. /// Writes mpint data into internal buffer.
  366. /// </summary>
  367. /// <param name="data">mpint data to write.</param>
  368. protected void Write(BigInteger data)
  369. {
  370. var bytes = data.ToByteArray().Reverse().ToList();
  371. this.Write((uint)bytes.Count);
  372. this.Write(bytes);
  373. }
  374. /// <summary>
  375. /// Writes name-list data into internal buffer.
  376. /// </summary>
  377. /// <param name="data">name-list data to write.</param>
  378. protected void Write(string[] data)
  379. {
  380. this.WriteAscii(string.Join(",", data));
  381. }
  382. /// <summary>
  383. /// Writes extension-pair data into internal buffer.
  384. /// </summary>
  385. /// <param name="data">extension-pair data to write.</param>
  386. protected void Write(IDictionary<string, string> data)
  387. {
  388. foreach (var item in data)
  389. {
  390. this.WriteAscii(item.Key);
  391. this.WriteAscii(item.Value);
  392. }
  393. }
  394. }
  395. }