2
0

SshData.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 _readerIndex >= _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. _data = new List<byte>();
  58. SaveData();
  59. return _data.ToArray();
  60. }
  61. internal T OfType<T>() where T : SshData, new()
  62. {
  63. var result = new T();
  64. result.LoadBytes(_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. LoadBytes(value);
  78. 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. ResetReader();
  100. _loadedData = bytes;
  101. _data = new List<byte>(bytes);
  102. }
  103. /// <summary>
  104. /// Resets internal data reader index.
  105. /// </summary>
  106. protected void ResetReader()
  107. {
  108. _readerIndex = 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[_data.Count - _readerIndex];
  117. _data.CopyTo(_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 > _data.Count)
  132. throw new ArgumentOutOfRangeException("length");
  133. var result = new byte[length];
  134. _data.CopyTo(_readerIndex, result, 0, length);
  135. _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 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 ReadByte() != 0;
  153. }
  154. /// <summary>
  155. /// Reads next uint16 data type from internal buffer.
  156. /// </summary>
  157. /// <returns>uint16 read</returns>
  158. protected ushort ReadUInt16()
  159. {
  160. var data = 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 uint ReadUInt32()
  168. {
  169. var data = 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 ulong ReadUInt64()
  177. {
  178. var data = ReadBytes(8);
  179. return ((ulong) data[0] << 56 | (ulong) data[1] << 48 | (ulong) data[2] << 40 | (ulong) data[3] << 32 |
  180. (ulong) data[4] << 24 | (ulong) data[5] << 16 | (ulong) data[6] << 8 | data[7]);
  181. }
  182. /// <summary>
  183. /// Reads next int64 data type from internal buffer.
  184. /// </summary>
  185. /// <returns>int64 read</returns>
  186. protected long ReadInt64()
  187. {
  188. var data = ReadBytes(8);
  189. return data[0] << 56 | data[1] << 48 | data[2] << 40 | data[3] << 32 | data[4] << 24 | data[5] << 16 |
  190. data[6] << 8 | data[7];
  191. }
  192. /// <summary>
  193. /// Reads next string data type from internal buffer.
  194. /// </summary>
  195. /// <returns>string read</returns>
  196. protected string ReadAsciiString()
  197. {
  198. var length = ReadUInt32();
  199. if (length > int.MaxValue)
  200. {
  201. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  202. }
  203. return Ascii.GetString(ReadBytes((int)length), 0, (int)length);
  204. }
  205. /// <summary>
  206. /// Reads next string data type from internal buffer.
  207. /// </summary>
  208. /// <returns>string read</returns>
  209. protected string ReadString()
  210. {
  211. return ReadString(Utf8);
  212. }
  213. /// <summary>
  214. /// Reads next string data type from internal buffer.
  215. /// </summary>
  216. /// <returns>string read</returns>
  217. protected string ReadString(Encoding encoding)
  218. {
  219. var length = ReadUInt32();
  220. if (length > int.MaxValue)
  221. {
  222. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  223. }
  224. return encoding.GetString(ReadBytes((int)length), 0, (int)length);
  225. }
  226. /// <summary>
  227. /// Reads next string data type from internal buffer.
  228. /// </summary>
  229. /// <returns>string read</returns>
  230. protected byte[] ReadBinaryString()
  231. {
  232. var length = ReadUInt32();
  233. if (length > int.MaxValue)
  234. {
  235. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Strings longer than {0} is not supported.", int.MaxValue));
  236. }
  237. return ReadBytes((int)length);
  238. }
  239. /// <summary>
  240. /// Reads next mpint data type from internal buffer.
  241. /// </summary>
  242. /// <returns>mpint read.</returns>
  243. protected BigInteger ReadBigInt()
  244. {
  245. var length = ReadUInt32();
  246. var data = ReadBytes((int)length);
  247. return new BigInteger(data.Reverse().ToArray());
  248. }
  249. /// <summary>
  250. /// Reads next name-list data type from internal buffer.
  251. /// </summary>
  252. /// <returns>String array or read data..</returns>
  253. protected string[] ReadNamesList()
  254. {
  255. var namesList = ReadString();
  256. return namesList.Split(',');
  257. }
  258. /// <summary>
  259. /// Reads next extension-pair data type from internal buffer.
  260. /// </summary>
  261. /// <returns>Extensions pair dictionary.</returns>
  262. protected IDictionary<string, string> ReadExtensionPair()
  263. {
  264. var result = new Dictionary<string, string>();
  265. while (_readerIndex < _data.Count)
  266. {
  267. var extensionName = ReadString();
  268. var extensionData = ReadString();
  269. result.Add(extensionName, extensionData);
  270. }
  271. return result;
  272. }
  273. /// <summary>
  274. /// Writes bytes array data into internal buffer.
  275. /// </summary>
  276. /// <param name="data">Byte array data to write.</param>
  277. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  278. protected void Write(IEnumerable<byte> data)
  279. {
  280. _data.AddRange(data);
  281. }
  282. /// <summary>
  283. /// Writes byte data into internal buffer.
  284. /// </summary>
  285. /// <param name="data">Byte data to write.</param>
  286. protected void Write(byte data)
  287. {
  288. _data.Add(data);
  289. }
  290. /// <summary>
  291. /// Writes boolean data into internal buffer.
  292. /// </summary>
  293. /// <param name="data">Boolean data to write.</param>
  294. protected void Write(bool data)
  295. {
  296. Write(data ? 1 : 0);
  297. }
  298. /// <summary>
  299. /// Writes uint16 data into internal buffer.
  300. /// </summary>
  301. /// <param name="data">uint16 data to write.</param>
  302. protected void Write(UInt16 data)
  303. {
  304. Write(data.GetBytes());
  305. }
  306. /// <summary>
  307. /// Writes uint32 data into internal buffer.
  308. /// </summary>
  309. /// <param name="data">uint32 data to write.</param>
  310. protected void Write(UInt32 data)
  311. {
  312. Write(data.GetBytes());
  313. }
  314. /// <summary>
  315. /// Writes uint64 data into internal buffer.
  316. /// </summary>
  317. /// <param name="data">uint64 data to write.</param>
  318. protected void Write(UInt64 data)
  319. {
  320. Write(data.GetBytes());
  321. }
  322. /// <summary>
  323. /// Writes int64 data into internal buffer.
  324. /// </summary>
  325. /// <param name="data">int64 data to write.</param>
  326. protected void Write(Int64 data)
  327. {
  328. Write(data.GetBytes());
  329. }
  330. /// <summary>
  331. /// Writes string data into internal buffer as ASCII.
  332. /// </summary>
  333. /// <param name="data">string data to write.</param>
  334. protected void WriteAscii(string data)
  335. {
  336. Write(data, Ascii);
  337. }
  338. /// <summary>
  339. /// Writes string data into internal buffer using default encoding.
  340. /// </summary>
  341. /// <param name="data">string data to write.</param>
  342. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  343. protected void Write(string data)
  344. {
  345. Write(data, Utf8);
  346. }
  347. /// <summary>
  348. /// Writes string data into internal buffer using the specified encoding.
  349. /// </summary>
  350. /// <param name="data">string data to write.</param>
  351. /// <param name="encoding">The character encoding to use.</param>
  352. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  353. /// <exception cref="ArgumentNullException"><paramref name="encoding"/> is null.</exception>
  354. protected void Write(string data, Encoding encoding)
  355. {
  356. if (data == null)
  357. throw new ArgumentNullException("data");
  358. if (encoding == null)
  359. throw new ArgumentNullException("encoding");
  360. var bytes = encoding.GetBytes(data);
  361. Write((uint)bytes.Length);
  362. Write(bytes);
  363. }
  364. /// <summary>
  365. /// Writes string data into internal buffer.
  366. /// </summary>
  367. /// <param name="data">string data to write.</param>
  368. /// <exception cref="ArgumentNullException"><paramref name="data"/> is null.</exception>
  369. protected void WriteBinaryString(byte[] data)
  370. {
  371. if (data == null)
  372. throw new ArgumentNullException("data");
  373. Write((uint)data.Length);
  374. _data.AddRange(data);
  375. }
  376. /// <summary>
  377. /// Writes mpint data into internal buffer.
  378. /// </summary>
  379. /// <param name="data">mpint data to write.</param>
  380. protected void Write(BigInteger data)
  381. {
  382. var bytes = data.ToByteArray().Reverse().ToList();
  383. Write((uint)bytes.Count);
  384. Write(bytes);
  385. }
  386. /// <summary>
  387. /// Writes name-list data into internal buffer.
  388. /// </summary>
  389. /// <param name="data">name-list data to write.</param>
  390. protected void Write(string[] data)
  391. {
  392. WriteAscii(string.Join(",", data));
  393. }
  394. /// <summary>
  395. /// Writes extension-pair data into internal buffer.
  396. /// </summary>
  397. /// <param name="data">extension-pair data to write.</param>
  398. protected void Write(IDictionary<string, string> data)
  399. {
  400. foreach (var item in data)
  401. {
  402. WriteAscii(item.Key);
  403. WriteAscii(item.Value);
  404. }
  405. }
  406. }
  407. }