RemoteConsole.cs 17 KB

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