1
0

RemoteConsole.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. public bool newConnection = true;
  46. }
  47. // A console that uses REST interfaces
  48. //
  49. public class RemoteConsole : CommandConsole
  50. {
  51. private IHttpServer m_Server = null;
  52. private IConfigSource m_Config = null;
  53. private List<string> m_Scrollback = new List<string>();
  54. private ManualResetEvent m_DataEvent = new ManualResetEvent(false);
  55. private List<string> m_InputData = new List<string>();
  56. private long m_LineNumber = 0;
  57. private Dictionary<UUID, ConsoleConnection> m_Connections =
  58. new Dictionary<UUID, ConsoleConnection>();
  59. private string m_UserName = String.Empty;
  60. private string m_Password = String.Empty;
  61. public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
  62. {
  63. }
  64. public void ReadConfig(IConfigSource config)
  65. {
  66. m_Config = config;
  67. IConfig netConfig = m_Config.Configs["Network"];
  68. if (netConfig == null)
  69. return;
  70. m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
  71. m_Password = netConfig.GetString("ConsolePass", String.Empty);
  72. }
  73. public void SetServer(IHttpServer server)
  74. {
  75. m_Server = server;
  76. m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
  77. m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
  78. m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
  79. }
  80. public override void Output(string text, string level)
  81. {
  82. lock (m_Scrollback)
  83. {
  84. while (m_Scrollback.Count >= 1000)
  85. m_Scrollback.RemoveAt(0);
  86. m_LineNumber++;
  87. m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
  88. }
  89. System.Console.WriteLine(text.Trim());
  90. }
  91. public override void Output(string text)
  92. {
  93. Output(text, "normal");
  94. }
  95. public override string ReadLine(string p, bool isCommand, bool e)
  96. {
  97. if (isCommand)
  98. Output("+++"+p);
  99. else
  100. Output("-++"+p);
  101. m_DataEvent.WaitOne();
  102. string cmdinput;
  103. lock (m_InputData)
  104. {
  105. if (m_InputData.Count == 0)
  106. {
  107. m_DataEvent.Reset();
  108. return "";
  109. }
  110. cmdinput = m_InputData[0];
  111. m_InputData.RemoveAt(0);
  112. if (m_InputData.Count == 0)
  113. m_DataEvent.Reset();
  114. }
  115. if (isCommand)
  116. {
  117. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  118. if (cmd.Length != 0)
  119. {
  120. int i;
  121. for (i=0 ; i < cmd.Length ; i++)
  122. {
  123. if (cmd[i].Contains(" "))
  124. cmd[i] = "\"" + cmd[i] + "\"";
  125. }
  126. return String.Empty;
  127. }
  128. }
  129. return cmdinput;
  130. }
  131. private void DoExpire()
  132. {
  133. List<UUID> expired = new List<UUID>();
  134. lock (m_Connections)
  135. {
  136. foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
  137. {
  138. if (System.Environment.TickCount - kvp.Value.last > 500000)
  139. expired.Add(kvp.Key);
  140. }
  141. foreach (UUID id in expired)
  142. {
  143. m_Connections.Remove(id);
  144. CloseConnection(id);
  145. }
  146. }
  147. }
  148. private Hashtable HandleHttpStartSession(Hashtable request)
  149. {
  150. DoExpire();
  151. Hashtable post = DecodePostString(request["body"].ToString());
  152. Hashtable reply = new Hashtable();
  153. reply["str_response_string"] = "";
  154. reply["int_response_code"] = 401;
  155. reply["content_type"] = "text/plain";
  156. if (m_UserName == String.Empty)
  157. return reply;
  158. if (post["USER"] == null || post["PASS"] == null)
  159. return reply;
  160. if (m_UserName != post["USER"].ToString() ||
  161. m_Password != post["PASS"].ToString())
  162. {
  163. return reply;
  164. }
  165. ConsoleConnection c = new ConsoleConnection();
  166. c.last = System.Environment.TickCount;
  167. c.lastLineSeen = 0;
  168. UUID sessionID = UUID.Random();
  169. lock (m_Connections)
  170. {
  171. m_Connections[sessionID] = c;
  172. }
  173. string uri = "/ReadResponses/" + sessionID.ToString() + "/";
  174. m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
  175. new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
  176. sessionID));
  177. XmlDocument xmldoc = new XmlDocument();
  178. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  179. "", "");
  180. xmldoc.AppendChild(xmlnode);
  181. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  182. "");
  183. xmldoc.AppendChild(rootElement);
  184. XmlElement id = xmldoc.CreateElement("", "SessionID", "");
  185. id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
  186. rootElement.AppendChild(id);
  187. XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
  188. prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
  189. rootElement.AppendChild(prompt);
  190. rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
  191. reply["str_response_string"] = xmldoc.InnerXml;
  192. reply["int_response_code"] = 200;
  193. reply["content_type"] = "text/xml";
  194. return reply;
  195. }
  196. private Hashtable HandleHttpPoll(Hashtable request)
  197. {
  198. return new Hashtable();
  199. }
  200. private Hashtable HandleHttpCloseSession(Hashtable request)
  201. {
  202. DoExpire();
  203. Hashtable post = DecodePostString(request["body"].ToString());
  204. Hashtable reply = new Hashtable();
  205. reply["str_response_string"] = "";
  206. reply["int_response_code"] = 404;
  207. reply["content_type"] = "text/plain";
  208. if (post["ID"] == null)
  209. return reply;
  210. UUID id;
  211. if (!UUID.TryParse(post["ID"].ToString(), out id))
  212. return reply;
  213. lock (m_Connections)
  214. {
  215. if (m_Connections.ContainsKey(id))
  216. {
  217. m_Connections.Remove(id);
  218. CloseConnection(id);
  219. }
  220. }
  221. XmlDocument xmldoc = new XmlDocument();
  222. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  223. "", "");
  224. xmldoc.AppendChild(xmlnode);
  225. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  226. "");
  227. xmldoc.AppendChild(rootElement);
  228. XmlElement res = xmldoc.CreateElement("", "Result", "");
  229. res.AppendChild(xmldoc.CreateTextNode("OK"));
  230. rootElement.AppendChild(res);
  231. reply["str_response_string"] = xmldoc.InnerXml;
  232. reply["int_response_code"] = 200;
  233. reply["content_type"] = "text/plain";
  234. return reply;
  235. }
  236. private Hashtable HandleHttpSessionCommand(Hashtable request)
  237. {
  238. DoExpire();
  239. Hashtable post = DecodePostString(request["body"].ToString());
  240. Hashtable reply = new Hashtable();
  241. reply["str_response_string"] = "";
  242. reply["int_response_code"] = 404;
  243. reply["content_type"] = "text/plain";
  244. if (post["ID"] == null)
  245. return reply;
  246. UUID id;
  247. if (!UUID.TryParse(post["ID"].ToString(), out id))
  248. return reply;
  249. lock (m_Connections)
  250. {
  251. if (!m_Connections.ContainsKey(id))
  252. return reply;
  253. }
  254. if (post["COMMAND"] == null)
  255. return reply;
  256. lock (m_InputData)
  257. {
  258. m_DataEvent.Set();
  259. m_InputData.Add(post["COMMAND"].ToString());
  260. }
  261. XmlDocument xmldoc = new XmlDocument();
  262. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  263. "", "");
  264. xmldoc.AppendChild(xmlnode);
  265. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  266. "");
  267. xmldoc.AppendChild(rootElement);
  268. XmlElement res = xmldoc.CreateElement("", "Result", "");
  269. res.AppendChild(xmldoc.CreateTextNode("OK"));
  270. rootElement.AppendChild(res);
  271. reply["str_response_string"] = xmldoc.InnerXml;
  272. reply["int_response_code"] = 200;
  273. reply["content_type"] = "text/plain";
  274. return reply;
  275. }
  276. private Hashtable DecodePostString(string data)
  277. {
  278. Hashtable result = new Hashtable();
  279. string[] terms = data.Split(new char[] {'&'});
  280. foreach (string term in terms)
  281. {
  282. string[] elems = term.Split(new char[] {'='});
  283. if (elems.Length == 0)
  284. continue;
  285. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  286. string value = String.Empty;
  287. if (elems.Length > 1)
  288. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  289. result[name] = value;
  290. }
  291. return result;
  292. }
  293. public void CloseConnection(UUID id)
  294. {
  295. try
  296. {
  297. string uri = "/ReadResponses/" + id.ToString() + "/";
  298. m_Server.RemovePollServiceHTTPHandler("", uri);
  299. }
  300. catch (Exception)
  301. {
  302. }
  303. }
  304. private bool HasEvents(UUID RequestID, UUID sessionID)
  305. {
  306. ConsoleConnection c = null;
  307. lock (m_Connections)
  308. {
  309. if (!m_Connections.ContainsKey(sessionID))
  310. return false;
  311. c = m_Connections[sessionID];
  312. }
  313. c.last = System.Environment.TickCount;
  314. if (c.lastLineSeen < m_LineNumber)
  315. return true;
  316. return false;
  317. }
  318. private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
  319. {
  320. ConsoleConnection c = null;
  321. lock (m_Connections)
  322. {
  323. if (!m_Connections.ContainsKey(sessionID))
  324. return NoEvents(RequestID, UUID.Zero);
  325. c = m_Connections[sessionID];
  326. }
  327. c.last = System.Environment.TickCount;
  328. if (c.lastLineSeen >= m_LineNumber)
  329. return NoEvents(RequestID, UUID.Zero);
  330. Hashtable result = new Hashtable();
  331. XmlDocument xmldoc = new XmlDocument();
  332. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  333. "", "");
  334. xmldoc.AppendChild(xmlnode);
  335. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  336. "");
  337. if (c.newConnection)
  338. {
  339. c.newConnection = false;
  340. Output("+++" + DefaultPrompt);
  341. }
  342. lock (m_Scrollback)
  343. {
  344. long startLine = m_LineNumber - m_Scrollback.Count;
  345. long sendStart = startLine;
  346. if (sendStart < c.lastLineSeen)
  347. sendStart = c.lastLineSeen;
  348. for (long i = sendStart ; i < m_LineNumber ; i++)
  349. {
  350. XmlElement res = xmldoc.CreateElement("", "Line", "");
  351. long line = i + 1;
  352. res.SetAttribute("Number", line.ToString());
  353. res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
  354. rootElement.AppendChild(res);
  355. }
  356. }
  357. c.lastLineSeen = m_LineNumber;
  358. xmldoc.AppendChild(rootElement);
  359. result["str_response_string"] = xmldoc.InnerXml;
  360. result["int_response_code"] = 200;
  361. result["content_type"] = "application/xml";
  362. result["keepalive"] = false;
  363. result["reusecontext"] = false;
  364. return result;
  365. }
  366. private Hashtable NoEvents(UUID RequestID, UUID id)
  367. {
  368. Hashtable result = new Hashtable();
  369. XmlDocument xmldoc = new XmlDocument();
  370. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  371. "", "");
  372. xmldoc.AppendChild(xmlnode);
  373. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  374. "");
  375. xmldoc.AppendChild(rootElement);
  376. result["str_response_string"] = xmldoc.InnerXml;
  377. result["int_response_code"] = 200;
  378. result["content_type"] = "text/xml";
  379. result["keepalive"] = false;
  380. result["reusecontext"] = false;
  381. return result;
  382. }
  383. }
  384. }