RemoteConsole.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. lock (m_Connections)
  244. {
  245. if (!m_Connections.ContainsKey(id))
  246. return reply;
  247. }
  248. if (post["COMMAND"] == null || post["COMMAND"].ToString() == String.Empty)
  249. return reply;
  250. lock (m_InputData)
  251. {
  252. m_DataEvent.Set();
  253. m_InputData.Add(post["COMMAND"].ToString());
  254. }
  255. XmlDocument xmldoc = new XmlDocument();
  256. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  257. "", "");
  258. xmldoc.AppendChild(xmlnode);
  259. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  260. "");
  261. xmldoc.AppendChild(rootElement);
  262. XmlElement res = xmldoc.CreateElement("", "Result", "");
  263. res.AppendChild(xmldoc.CreateTextNode("OK"));
  264. rootElement.AppendChild(res);
  265. reply["str_response_string"] = xmldoc.InnerXml;
  266. reply["int_response_code"] = 200;
  267. reply["content_type"] = "text/plain";
  268. return reply;
  269. }
  270. private Hashtable DecodePostString(string data)
  271. {
  272. Hashtable result = new Hashtable();
  273. string[] terms = data.Split(new char[] {'&'});
  274. foreach (string term in terms)
  275. {
  276. string[] elems = term.Split(new char[] {'='});
  277. if (elems.Length == 0)
  278. continue;
  279. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  280. string value = String.Empty;
  281. if (elems.Length > 1)
  282. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  283. result[name] = value;
  284. }
  285. return result;
  286. }
  287. public void CloseConnection(UUID id)
  288. {
  289. try
  290. {
  291. string uri = "/ReadResponses/" + id.ToString() + "/";
  292. m_Server.RemovePollServiceHTTPHandler("", uri);
  293. }
  294. catch (Exception)
  295. {
  296. }
  297. }
  298. private bool HasEvents(UUID RequestID, UUID sessionID)
  299. {
  300. ConsoleConnection c = null;
  301. lock (m_Connections)
  302. {
  303. if (!m_Connections.ContainsKey(sessionID))
  304. return false;
  305. c = m_Connections[sessionID];
  306. }
  307. c.last = System.Environment.TickCount;
  308. if (c.lastLineSeen < m_LineNumber)
  309. return true;
  310. return false;
  311. }
  312. private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
  313. {
  314. ConsoleConnection c = null;
  315. lock (m_Connections)
  316. {
  317. if (!m_Connections.ContainsKey(sessionID))
  318. return NoEvents(RequestID, UUID.Zero);
  319. c = m_Connections[sessionID];
  320. }
  321. c.last = System.Environment.TickCount;
  322. if (c.lastLineSeen >= m_LineNumber)
  323. return NoEvents(RequestID, UUID.Zero);
  324. Hashtable result = new Hashtable();
  325. XmlDocument xmldoc = new XmlDocument();
  326. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  327. "", "");
  328. xmldoc.AppendChild(xmlnode);
  329. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  330. "");
  331. lock (m_Scrollback)
  332. {
  333. long startLine = m_LineNumber - m_Scrollback.Count;
  334. long sendStart = startLine;
  335. if (sendStart < c.lastLineSeen)
  336. sendStart = c.lastLineSeen;
  337. for (long i = sendStart ; i < m_LineNumber ; i++)
  338. {
  339. XmlElement res = xmldoc.CreateElement("", "Line", "");
  340. long line = i + 1;
  341. res.SetAttribute("Number", line.ToString());
  342. res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
  343. rootElement.AppendChild(res);
  344. }
  345. }
  346. c.lastLineSeen = m_LineNumber;
  347. xmldoc.AppendChild(rootElement);
  348. result["str_response_string"] = xmldoc.InnerXml;
  349. result["int_response_code"] = 200;
  350. result["content_type"] = "application/xml";
  351. result["keepalive"] = false;
  352. result["reusecontext"] = false;
  353. return result;
  354. }
  355. private Hashtable NoEvents(UUID RequestID, UUID id)
  356. {
  357. Hashtable result = new Hashtable();
  358. XmlDocument xmldoc = new XmlDocument();
  359. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  360. "", "");
  361. xmldoc.AppendChild(xmlnode);
  362. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  363. "");
  364. xmldoc.AppendChild(rootElement);
  365. result["str_response_string"] = xmldoc.InnerXml;
  366. result["int_response_code"] = 200;
  367. result["content_type"] = "text/xml";
  368. result["keepalive"] = false;
  369. result["reusecontext"] = false;
  370. return result;
  371. }
  372. }
  373. }