RemoteConsole.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. FireOnOutput(text.Trim());
  93. System.Console.WriteLine(text.Trim());
  94. }
  95. public override void Output(string text)
  96. {
  97. Output(text, "normal");
  98. }
  99. public override string ReadLine(string p, bool isCommand, bool e)
  100. {
  101. if (isCommand)
  102. Output("+++"+p);
  103. else
  104. Output("-++"+p);
  105. m_DataEvent.WaitOne();
  106. string cmdinput;
  107. lock (m_InputData)
  108. {
  109. if (m_InputData.Count == 0)
  110. {
  111. m_DataEvent.Reset();
  112. return "";
  113. }
  114. cmdinput = m_InputData[0];
  115. m_InputData.RemoveAt(0);
  116. if (m_InputData.Count == 0)
  117. m_DataEvent.Reset();
  118. }
  119. if (isCommand)
  120. {
  121. string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
  122. if (cmd.Length != 0)
  123. {
  124. int i;
  125. for (i=0 ; i < cmd.Length ; i++)
  126. {
  127. if (cmd[i].Contains(" "))
  128. cmd[i] = "\"" + cmd[i] + "\"";
  129. }
  130. return String.Empty;
  131. }
  132. }
  133. return cmdinput;
  134. }
  135. private Hashtable CheckOrigin(Hashtable result)
  136. {
  137. if (!string.IsNullOrEmpty(m_AllowedOrigin))
  138. result["access_control_allow_origin"] = m_AllowedOrigin;
  139. return result;
  140. }
  141. /* TODO: Figure out how PollServiceHTTPHandler can access the request headers
  142. * in order to use m_AllowedOrigin as a regular expression
  143. private Hashtable CheckOrigin(Hashtable headers, Hashtable result)
  144. {
  145. if (!string.IsNullOrEmpty(m_AllowedOrigin))
  146. {
  147. if (headers.ContainsKey("origin"))
  148. {
  149. string origin = headers["origin"].ToString();
  150. if (Regex.IsMatch(origin, m_AllowedOrigin))
  151. result["access_control_allow_origin"] = origin;
  152. }
  153. }
  154. return result;
  155. }
  156. */
  157. private void DoExpire()
  158. {
  159. List<UUID> expired = new List<UUID>();
  160. lock (m_Connections)
  161. {
  162. foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
  163. {
  164. if (System.Environment.TickCount - kvp.Value.last > 500000)
  165. expired.Add(kvp.Key);
  166. }
  167. foreach (UUID id in expired)
  168. {
  169. m_Connections.Remove(id);
  170. CloseConnection(id);
  171. }
  172. }
  173. }
  174. private Hashtable HandleHttpStartSession(Hashtable request)
  175. {
  176. DoExpire();
  177. Hashtable post = DecodePostString(request["body"].ToString());
  178. Hashtable reply = new Hashtable();
  179. reply["str_response_string"] = "";
  180. reply["int_response_code"] = 401;
  181. reply["content_type"] = "text/plain";
  182. if (m_UserName == String.Empty)
  183. return reply;
  184. if (post["USER"] == null || post["PASS"] == null)
  185. return reply;
  186. if (m_UserName != post["USER"].ToString() ||
  187. m_Password != post["PASS"].ToString())
  188. {
  189. return reply;
  190. }
  191. ConsoleConnection c = new ConsoleConnection();
  192. c.last = System.Environment.TickCount;
  193. c.lastLineSeen = 0;
  194. UUID sessionID = UUID.Random();
  195. lock (m_Connections)
  196. {
  197. m_Connections[sessionID] = c;
  198. }
  199. string uri = "/ReadResponses/" + sessionID.ToString() + "/";
  200. m_Server.AddPollServiceHTTPHandler(
  201. uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, sessionID,25000)); // 25 secs timeout
  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 HandleHttpCloseSession(Hashtable request)
  223. {
  224. DoExpire();
  225. Hashtable post = DecodePostString(request["body"].ToString());
  226. Hashtable reply = new Hashtable();
  227. reply["str_response_string"] = "";
  228. reply["int_response_code"] = 404;
  229. reply["content_type"] = "text/plain";
  230. if (post["ID"] == null)
  231. return reply;
  232. UUID id;
  233. if (!UUID.TryParse(post["ID"].ToString(), out id))
  234. return reply;
  235. lock (m_Connections)
  236. {
  237. if (m_Connections.ContainsKey(id))
  238. {
  239. m_Connections.Remove(id);
  240. CloseConnection(id);
  241. }
  242. }
  243. XmlDocument xmldoc = new XmlDocument();
  244. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  245. "", "");
  246. xmldoc.AppendChild(xmlnode);
  247. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  248. "");
  249. xmldoc.AppendChild(rootElement);
  250. XmlElement res = xmldoc.CreateElement("", "Result", "");
  251. res.AppendChild(xmldoc.CreateTextNode("OK"));
  252. rootElement.AppendChild(res);
  253. reply["str_response_string"] = xmldoc.InnerXml;
  254. reply["int_response_code"] = 200;
  255. reply["content_type"] = "text/xml";
  256. reply = CheckOrigin(reply);
  257. return reply;
  258. }
  259. private Hashtable HandleHttpSessionCommand(Hashtable request)
  260. {
  261. DoExpire();
  262. Hashtable post = DecodePostString(request["body"].ToString());
  263. Hashtable reply = new Hashtable();
  264. reply["str_response_string"] = "";
  265. reply["int_response_code"] = 404;
  266. reply["content_type"] = "text/plain";
  267. if (post["ID"] == null)
  268. return reply;
  269. UUID id;
  270. if (!UUID.TryParse(post["ID"].ToString(), out id))
  271. return reply;
  272. lock (m_Connections)
  273. {
  274. if (!m_Connections.ContainsKey(id))
  275. return reply;
  276. }
  277. if (post["COMMAND"] == null)
  278. return reply;
  279. lock (m_InputData)
  280. {
  281. m_DataEvent.Set();
  282. m_InputData.Add(post["COMMAND"].ToString());
  283. }
  284. XmlDocument xmldoc = new XmlDocument();
  285. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  286. "", "");
  287. xmldoc.AppendChild(xmlnode);
  288. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  289. "");
  290. xmldoc.AppendChild(rootElement);
  291. XmlElement res = xmldoc.CreateElement("", "Result", "");
  292. res.AppendChild(xmldoc.CreateTextNode("OK"));
  293. rootElement.AppendChild(res);
  294. reply["str_response_string"] = xmldoc.InnerXml;
  295. reply["int_response_code"] = 200;
  296. reply["content_type"] = "text/xml";
  297. reply = CheckOrigin(reply);
  298. return reply;
  299. }
  300. private Hashtable DecodePostString(string data)
  301. {
  302. Hashtable result = new Hashtable();
  303. string[] terms = data.Split(new char[] {'&'});
  304. foreach (string term in terms)
  305. {
  306. string[] elems = term.Split(new char[] {'='});
  307. if (elems.Length == 0)
  308. continue;
  309. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  310. string value = String.Empty;
  311. if (elems.Length > 1)
  312. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  313. result[name] = value;
  314. }
  315. return result;
  316. }
  317. public void CloseConnection(UUID id)
  318. {
  319. try
  320. {
  321. string uri = "/ReadResponses/" + id.ToString() + "/";
  322. m_Server.RemovePollServiceHTTPHandler("", uri);
  323. }
  324. catch (Exception)
  325. {
  326. }
  327. }
  328. private bool HasEvents(UUID RequestID, UUID sessionID)
  329. {
  330. ConsoleConnection c = null;
  331. lock (m_Connections)
  332. {
  333. if (!m_Connections.ContainsKey(sessionID))
  334. return false;
  335. c = m_Connections[sessionID];
  336. }
  337. c.last = System.Environment.TickCount;
  338. if (c.lastLineSeen < m_LineNumber)
  339. return true;
  340. return false;
  341. }
  342. private Hashtable GetEvents(UUID RequestID, UUID sessionID)
  343. {
  344. ConsoleConnection c = null;
  345. lock (m_Connections)
  346. {
  347. if (!m_Connections.ContainsKey(sessionID))
  348. return NoEvents(RequestID, UUID.Zero);
  349. c = m_Connections[sessionID];
  350. }
  351. c.last = System.Environment.TickCount;
  352. if (c.lastLineSeen >= m_LineNumber)
  353. return NoEvents(RequestID, UUID.Zero);
  354. Hashtable result = new Hashtable();
  355. XmlDocument xmldoc = new XmlDocument();
  356. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  357. "", "");
  358. xmldoc.AppendChild(xmlnode);
  359. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  360. "");
  361. if (c.newConnection)
  362. {
  363. c.newConnection = false;
  364. Output("+++" + DefaultPrompt);
  365. }
  366. lock (m_Scrollback)
  367. {
  368. long startLine = m_LineNumber - m_Scrollback.Count;
  369. long sendStart = startLine;
  370. if (sendStart < c.lastLineSeen)
  371. sendStart = c.lastLineSeen;
  372. for (long i = sendStart ; i < m_LineNumber ; i++)
  373. {
  374. XmlElement res = xmldoc.CreateElement("", "Line", "");
  375. long line = i + 1;
  376. res.SetAttribute("Number", line.ToString());
  377. res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
  378. rootElement.AppendChild(res);
  379. }
  380. }
  381. c.lastLineSeen = m_LineNumber;
  382. xmldoc.AppendChild(rootElement);
  383. result["str_response_string"] = xmldoc.InnerXml;
  384. result["int_response_code"] = 200;
  385. result["content_type"] = "application/xml";
  386. result["keepalive"] = false;
  387. result["reusecontext"] = false;
  388. result = CheckOrigin(result);
  389. return result;
  390. }
  391. private Hashtable NoEvents(UUID RequestID, UUID id)
  392. {
  393. Hashtable result = new Hashtable();
  394. XmlDocument xmldoc = new XmlDocument();
  395. XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
  396. "", "");
  397. xmldoc.AppendChild(xmlnode);
  398. XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
  399. "");
  400. xmldoc.AppendChild(rootElement);
  401. result["str_response_string"] = xmldoc.InnerXml;
  402. result["int_response_code"] = 200;
  403. result["content_type"] = "text/xml";
  404. result["keepalive"] = false;
  405. result["reusecontext"] = false;
  406. result = CheckOrigin(result);
  407. return result;
  408. }
  409. }
  410. }