RemoteConsole.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Xml;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Threading;
  35. using OpenMetaverse;
  36. using Nini.Config;
  37. using OpenSim.Framework.Servers.HttpServer;
  38. using log4net;
  39. namespace OpenSim.Framework.Console
  40. {
  41. public class ConsoleConnection
  42. {
  43. public int last;
  44. public long lastLineSeen;
  45. }
  46. // A console that uses REST interfaces
  47. //
  48. public class RemoteConsole : CommandConsole
  49. {
  50. private IHttpServer m_Server = null;
  51. private IConfigSource m_Config = null;
  52. private List<string> m_Scrollback = new List<string>();
  53. private ManualResetEvent m_DataEvent = new ManualResetEvent(false);
  54. private List<string> m_InputData = new List<string>();
  55. private long m_LineNumber = 0;
  56. private Dictionary<UUID, ConsoleConnection> m_Connections =
  57. new Dictionary<UUID, ConsoleConnection>();
  58. private string m_UserName = String.Empty;
  59. private string m_Password = String.Empty;
  60. public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
  61. {
  62. }
  63. public void ReadConfig(IConfigSource config)
  64. {
  65. m_Config = config;
  66. IConfig netConfig = m_Config.Configs["Network"];
  67. if (netConfig == null)
  68. return;
  69. m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
  70. m_Password = netConfig.GetString("ConsolePass", String.Empty);
  71. }
  72. public void SetServer(IHttpServer server)
  73. {
  74. m_Server = server;
  75. m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
  76. m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
  77. m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
  78. }
  79. public override void Output(string text, string level)
  80. {
  81. lock (m_Scrollback)
  82. {
  83. while (m_Scrollback.Count >= 1000)
  84. m_Scrollback.RemoveAt(0);
  85. m_LineNumber++;
  86. m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
  87. }
  88. System.Console.WriteLine(text.Trim());
  89. }
  90. public override void Output(string text)
  91. {
  92. Output(text, "normal");
  93. }
  94. public override string ReadLine(string p, bool isCommand, bool e)
  95. {
  96. m_DataEvent.WaitOne();
  97. lock (m_InputData)
  98. {
  99. if (m_InputData.Count == 0)
  100. {
  101. m_DataEvent.Reset();
  102. return "";
  103. }
  104. string cmdinput = m_InputData[0];
  105. m_InputData.RemoveAt(0);
  106. if (m_InputData.Count == 0)
  107. m_DataEvent.Reset();
  108. if (isCommand)
  109. {
  110. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  111. if (cmd.Length != 0)
  112. {
  113. int i;
  114. for (i=0 ; i < cmd.Length ; i++)
  115. {
  116. if (cmd[i].Contains(" "))
  117. cmd[i] = "\"" + cmd[i] + "\"";
  118. }
  119. return String.Empty;
  120. }
  121. }
  122. return cmdinput;
  123. }
  124. }
  125. private void DoExpire()
  126. {
  127. List<UUID> expired = new List<UUID>();
  128. lock (m_Connections)
  129. {
  130. foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
  131. {
  132. if (System.Environment.TickCount - kvp.Value.last > 500000)
  133. expired.Add(kvp.Key);
  134. }
  135. foreach (UUID id in expired)
  136. {
  137. m_Connections.Remove(id);
  138. CloseConnection(id);
  139. }
  140. }
  141. }
  142. private Hashtable HandleHttpStartSession(Hashtable request)
  143. {
  144. DoExpire();
  145. Hashtable post = DecodePostString(request["body"].ToString());
  146. Hashtable reply = new Hashtable();
  147. reply["str_response_string"] = "";
  148. reply["int_response_code"] = 401;
  149. reply["content_type"] = "text/plain";
  150. if (m_UserName == String.Empty)
  151. return reply;
  152. if (post["USER"] == null || post["PASS"] == null)
  153. return reply;
  154. if (m_UserName != post["USER"].ToString() ||
  155. m_Password != post["PASS"].ToString())
  156. {
  157. return reply;
  158. }
  159. ConsoleConnection c = new ConsoleConnection();
  160. c.last = System.Environment.TickCount;
  161. c.lastLineSeen = 0;
  162. UUID sessionID = UUID.Random();
  163. lock (m_Connections)
  164. {
  165. m_Connections[sessionID] = c;
  166. }
  167. string uri = "/ReadResponses/" + sessionID.ToString() + "/";
  168. m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
  169. new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
  170. sessionID));
  171. XmlDocument xmldoc = new XmlDocument();
  172. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  173. "", "");
  174. xmldoc.AppendChild(xmlnode);
  175. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  176. "");
  177. xmldoc.AppendChild(rootElement);
  178. XmlElement id = xmldoc.CreateElement("", "SessionID", "");
  179. id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
  180. rootElement.AppendChild(id);
  181. XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
  182. prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
  183. rootElement.AppendChild(prompt);
  184. rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
  185. reply["str_response_string"] = xmldoc.InnerXml;
  186. reply["int_response_code"] = 200;
  187. reply["content_type"] = "text/xml";
  188. return reply;
  189. }
  190. private Hashtable HandleHttpPoll(Hashtable request)
  191. {
  192. return new Hashtable();
  193. }
  194. private Hashtable HandleHttpCloseSession(Hashtable request)
  195. {
  196. DoExpire();
  197. Hashtable post = DecodePostString(request["body"].ToString());
  198. Hashtable reply = new Hashtable();
  199. reply["str_response_string"] = "";
  200. reply["int_response_code"] = 404;
  201. reply["content_type"] = "text/plain";
  202. if (post["ID"] == null)
  203. return reply;
  204. UUID id;
  205. if (!UUID.TryParse(post["ID"].ToString(), out id))
  206. return reply;
  207. lock (m_Connections)
  208. {
  209. if (m_Connections.ContainsKey(id))
  210. {
  211. m_Connections.Remove(id);
  212. CloseConnection(id);
  213. }
  214. }
  215. XmlDocument xmldoc = new XmlDocument();
  216. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  217. "", "");
  218. xmldoc.AppendChild(xmlnode);
  219. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  220. "");
  221. xmldoc.AppendChild(rootElement);
  222. XmlElement res = xmldoc.CreateElement("", "Result", "");
  223. res.AppendChild(xmldoc.CreateTextNode("OK"));
  224. rootElement.AppendChild(res);
  225. reply["str_response_string"] = xmldoc.InnerXml;
  226. reply["int_response_code"] = 200;
  227. reply["content_type"] = "text/plain";
  228. return reply;
  229. }
  230. private Hashtable HandleHttpSessionCommand(Hashtable request)
  231. {
  232. DoExpire();
  233. Hashtable post = DecodePostString(request["body"].ToString());
  234. Hashtable reply = new Hashtable();
  235. reply["str_response_string"] = "";
  236. reply["int_response_code"] = 404;
  237. reply["content_type"] = "text/plain";
  238. if (post["ID"] == null)
  239. return reply;
  240. UUID id;
  241. if (!UUID.TryParse(post["ID"].ToString(), out id))
  242. return reply;
  243. if (post["COMMAND"] == null || post["COMMAND"].ToString() == String.Empty)
  244. return reply;
  245. lock (m_InputData)
  246. {
  247. m_DataEvent.Set();
  248. m_InputData.Add(post["COMMAND"].ToString());
  249. }
  250. XmlDocument xmldoc = new XmlDocument();
  251. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  252. "", "");
  253. xmldoc.AppendChild(xmlnode);
  254. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  255. "");
  256. xmldoc.AppendChild(rootElement);
  257. XmlElement res = xmldoc.CreateElement("", "Result", "");
  258. res.AppendChild(xmldoc.CreateTextNode("OK"));
  259. rootElement.AppendChild(res);
  260. reply["str_response_string"] = xmldoc.InnerXml;
  261. reply["int_response_code"] = 200;
  262. reply["content_type"] = "text/plain";
  263. return reply;
  264. }
  265. private Hashtable DecodePostString(string data)
  266. {
  267. Hashtable result = new Hashtable();
  268. string[] terms = data.Split(new char[] {'&'});
  269. foreach (string term in terms)
  270. {
  271. string[] elems = term.Split(new char[] {'='});
  272. if (elems.Length == 0)
  273. continue;
  274. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  275. string value = String.Empty;
  276. if (elems.Length > 1)
  277. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  278. result[name] = value;
  279. }
  280. return result;
  281. }
  282. public void CloseConnection(UUID id)
  283. {
  284. try
  285. {
  286. string uri = "/ReadResponses/" + id.ToString() + "/";
  287. m_Server.RemovePollServiceHTTPHandler("", uri);
  288. }
  289. catch (Exception)
  290. {
  291. }
  292. }
  293. private bool HasEvents(UUID RequestID, UUID sessionID)
  294. {
  295. ConsoleConnection c = null;
  296. lock (m_Connections)
  297. {
  298. if (!m_Connections.ContainsKey(sessionID))
  299. return false;
  300. c = m_Connections[sessionID];
  301. }
  302. c.last = System.Environment.TickCount;
  303. if (c.lastLineSeen < m_LineNumber)
  304. return true;
  305. return false;
  306. }
  307. private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
  308. {
  309. ConsoleConnection c = null;
  310. lock (m_Connections)
  311. {
  312. if (!m_Connections.ContainsKey(sessionID))
  313. return NoEvents(RequestID, UUID.Zero);
  314. c = m_Connections[sessionID];
  315. }
  316. c.last = System.Environment.TickCount;
  317. if (c.lastLineSeen >= m_LineNumber)
  318. return NoEvents(RequestID, UUID.Zero);
  319. Hashtable result = new Hashtable();
  320. XmlDocument xmldoc = new XmlDocument();
  321. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  322. "", "");
  323. xmldoc.AppendChild(xmlnode);
  324. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  325. "");
  326. lock (m_Scrollback)
  327. {
  328. long startLine = m_LineNumber - m_Scrollback.Count;
  329. long sendStart = startLine;
  330. if (sendStart < c.lastLineSeen)
  331. sendStart = c.lastLineSeen;
  332. for (long i = sendStart ; i < m_LineNumber ; i++)
  333. {
  334. XmlElement res = xmldoc.CreateElement("", "Line", "");
  335. long line = i + 1;
  336. res.SetAttribute("Number", line.ToString());
  337. res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
  338. rootElement.AppendChild(res);
  339. }
  340. }
  341. c.lastLineSeen = m_LineNumber;
  342. xmldoc.AppendChild(rootElement);
  343. result["str_response_string"] = xmldoc.InnerXml;
  344. result["int_response_code"] = 200;
  345. result["content_type"] = "application/xml";
  346. result["keepalive"] = false;
  347. result["reusecontext"] = false;
  348. return result;
  349. }
  350. private Hashtable NoEvents(UUID RequestID, UUID id)
  351. {
  352. Hashtable result = new Hashtable();
  353. XmlDocument xmldoc = new XmlDocument();
  354. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  355. "", "");
  356. xmldoc.AppendChild(xmlnode);
  357. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  358. "");
  359. xmldoc.AppendChild(rootElement);
  360. result["str_response_string"] = xmldoc.InnerXml;
  361. result["int_response_code"] = 200;
  362. result["content_type"] = "text/xml";
  363. result["keepalive"] = false;
  364. result["reusecontext"] = false;
  365. return result;
  366. }
  367. }
  368. }