NetConfSession.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. using System;
  2. using System.Globalization;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Common;
  6. using System.Xml;
  7. using System.Text.RegularExpressions;
  8. namespace Renci.SshNet.NetConf
  9. {
  10. internal class NetConfSession : SubsystemSession
  11. {
  12. private const string Prompt = "]]>]]>";
  13. private readonly StringBuilder _data = new StringBuilder();
  14. private bool _usingFramingProtocol;
  15. private EventWaitHandle _serverCapabilitiesConfirmed = new AutoResetEvent(false);
  16. private EventWaitHandle _rpcReplyReceived = new AutoResetEvent(false);
  17. private StringBuilder _rpcReply = new StringBuilder();
  18. private int _messageId;
  19. /// <summary>
  20. /// Gets NetConf server capabilities.
  21. /// </summary>
  22. public XmlDocument ServerCapabilities { get; private set; }
  23. /// <summary>
  24. /// Gets NetConf client capabilities.
  25. /// </summary>
  26. public XmlDocument ClientCapabilities { get; private set; }
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="NetConfSession"/> class.
  29. /// </summary>
  30. /// <param name="session">The session.</param>
  31. /// <param name="operationTimeout">The operation timeout.</param>
  32. public NetConfSession(ISession session, TimeSpan operationTimeout)
  33. : base(session, "netconf", operationTimeout, Encoding.UTF8)
  34. {
  35. ClientCapabilities = new XmlDocument();
  36. ClientCapabilities.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
  37. "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
  38. "<capabilities>" +
  39. "<capability>" +
  40. "urn:ietf:params:netconf:base:1.0" +
  41. "</capability>" +
  42. "</capabilities>" +
  43. "</hello>");
  44. }
  45. public XmlDocument SendReceiveRpc(XmlDocument rpc, bool automaticMessageIdHandling)
  46. {
  47. _data.Clear();
  48. XmlNamespaceManager nsMgr = null;
  49. if (automaticMessageIdHandling)
  50. {
  51. _messageId++;
  52. nsMgr = new XmlNamespaceManager(rpc.NameTable);
  53. nsMgr.AddNamespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0");
  54. rpc.SelectSingleNode("/nc:rpc/@message-id", nsMgr).Value = _messageId.ToString(CultureInfo.InvariantCulture);
  55. }
  56. _rpcReply = new StringBuilder();
  57. _rpcReplyReceived.Reset();
  58. var reply = new XmlDocument();
  59. if (_usingFramingProtocol)
  60. {
  61. var command = new StringBuilder(rpc.InnerXml.Length + 10);
  62. command.AppendFormat("\n#{0}\n", rpc.InnerXml.Length);
  63. command.Append(rpc.InnerXml);
  64. command.Append("\n##\n");
  65. SendData(Encoding.UTF8.GetBytes(command.ToString()));
  66. WaitOnHandle(_rpcReplyReceived, OperationTimeout);
  67. reply.LoadXml(_rpcReply.ToString());
  68. }
  69. else
  70. {
  71. SendData(Encoding.UTF8.GetBytes(rpc.InnerXml + Prompt));
  72. WaitOnHandle(_rpcReplyReceived, OperationTimeout);
  73. reply.LoadXml(_rpcReply.ToString());
  74. }
  75. if (automaticMessageIdHandling)
  76. {
  77. var replyId = rpc.SelectSingleNode("/nc:rpc/@message-id", nsMgr).Value;
  78. if (replyId != _messageId.ToString(CultureInfo.InvariantCulture))
  79. {
  80. throw new NetConfServerException("The rpc message id does not match the rpc-reply message id.");
  81. }
  82. }
  83. return reply;
  84. }
  85. protected override void OnChannelOpen()
  86. {
  87. _data.Clear();
  88. var message = string.Format("{0}{1}", ClientCapabilities.InnerXml, Prompt);
  89. SendData(Encoding.UTF8.GetBytes(message));
  90. WaitOnHandle(_serverCapabilitiesConfirmed, OperationTimeout);
  91. }
  92. protected override void OnDataReceived(uint dataTypeCode, byte[] data)
  93. {
  94. var chunk = Encoding.UTF8.GetString(data);
  95. if (ServerCapabilities == null) // This must be server capabilities, old protocol
  96. {
  97. _data.Append(chunk);
  98. if (!chunk.Contains(Prompt))
  99. {
  100. return;
  101. }
  102. try
  103. {
  104. chunk = _data.ToString();
  105. _data.Clear();
  106. ServerCapabilities = new XmlDocument();
  107. ServerCapabilities.LoadXml(chunk.Replace(Prompt, ""));
  108. }
  109. catch (XmlException e)
  110. {
  111. throw new NetConfServerException("Server capabilities received are not well formed XML", e);
  112. }
  113. var nsMgr = new XmlNamespaceManager(ServerCapabilities.NameTable);
  114. nsMgr.AddNamespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0");
  115. _usingFramingProtocol = (ServerCapabilities.SelectSingleNode("/nc:hello/nc:capabilities/nc:capability[text()='urn:ietf:params:netconf:base:1.1']", nsMgr) != null);
  116. _serverCapabilitiesConfirmed.Set();
  117. }
  118. else if (_usingFramingProtocol)
  119. {
  120. int position = 0;
  121. for (; ; )
  122. {
  123. var match = Regex.Match(chunk.Substring(position), @"\n#(?<length>\d+)\n");
  124. if (!match.Success)
  125. {
  126. break;
  127. }
  128. var fractionLength = Convert.ToInt32(match.Groups["length"].Value);
  129. _rpcReply.Append(chunk, position + match.Index + match.Length, fractionLength);
  130. position += match.Index + match.Length + fractionLength;
  131. }
  132. if (Regex.IsMatch(chunk.Substring(position), @"\n##\n"))
  133. {
  134. _rpcReplyReceived.Set();
  135. }
  136. }
  137. else // Old protocol
  138. {
  139. _data.Append(chunk);
  140. if (!chunk.Contains(Prompt))
  141. {
  142. return;
  143. //throw new NetConfServerException("Server XML message does not end with the prompt " + _prompt);
  144. }
  145. chunk = _data.ToString();
  146. _data.Clear();
  147. _rpcReply.Append(chunk.Replace(Prompt, ""));
  148. _rpcReplyReceived.Set();
  149. }
  150. }
  151. protected override void Dispose(bool disposing)
  152. {
  153. base.Dispose(disposing);
  154. if (disposing)
  155. {
  156. if (_serverCapabilitiesConfirmed != null)
  157. {
  158. _serverCapabilitiesConfirmed.Dispose();
  159. _serverCapabilitiesConfirmed = null;
  160. }
  161. if (_rpcReplyReceived != null)
  162. {
  163. _rpcReplyReceived.Dispose();
  164. _rpcReplyReceived = null;
  165. }
  166. }
  167. }
  168. }
  169. }