RegionState.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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.Collections.Generic;
  29. using System.Reflection;
  30. using System.Text.RegularExpressions;
  31. using log4net;
  32. using Nini.Config;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.Framework.Scenes;
  36. namespace OpenSim.Region.OptionalModules.Avatar.Chat
  37. {
  38. // An instance of this class exists for every active region
  39. internal class RegionState
  40. {
  41. private static readonly ILog m_log =
  42. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. // This computation is not the real region center if the region is larger than 256.
  44. // This computation isn't fixed because there is not a handle back to the region.
  45. private static readonly OpenMetaverse.Vector3 CenterOfRegion = new OpenMetaverse.Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20);
  46. private const int DEBUG_CHANNEL = 2147483647;
  47. private static int _idk_ = 0;
  48. // Runtime variables; these values are assigned when the
  49. // IrcState is created and remain constant thereafter.
  50. internal string Region = String.Empty;
  51. internal string Host = String.Empty;
  52. internal string LocX = String.Empty;
  53. internal string LocY = String.Empty;
  54. internal string IDK = String.Empty;
  55. // System values - used only be the IRC classes themselves
  56. internal ChannelState cs = null; // associated IRC configuration
  57. internal Scene scene = null; // associated scene
  58. internal IConfig config = null; // configuration file reference
  59. internal bool enabled = true;
  60. //AgentAlert
  61. internal bool showAlert = false;
  62. internal string alertMessage = String.Empty;
  63. internal IDialogModule dialogModule = null;
  64. // This list is used to keep track of who is here, and by
  65. // implication, who is not.
  66. internal List<IClientAPI> clients = new List<IClientAPI>();
  67. // Setup runtime variable values
  68. public RegionState(Scene p_scene, IConfig p_config)
  69. {
  70. scene = p_scene;
  71. config = p_config;
  72. Region = scene.RegionInfo.RegionName;
  73. Host = scene.RegionInfo.ExternalHostName;
  74. LocX = Convert.ToString(scene.RegionInfo.RegionLocX);
  75. LocY = Convert.ToString(scene.RegionInfo.RegionLocY);
  76. IDK = Convert.ToString(_idk_++);
  77. showAlert = config.GetBoolean("alert_show", false);
  78. string alertServerInfo = String.Empty;
  79. if (showAlert)
  80. {
  81. bool showAlertServerInfo = config.GetBoolean("alert_show_serverinfo", true);
  82. if (showAlertServerInfo)
  83. alertServerInfo = String.Format("\nServer: {0}\nPort: {1}\nChannel: {2}\n\n",
  84. config.GetString("server", ""), config.GetString("port", ""), config.GetString("channel", ""));
  85. string alertPreMessage = config.GetString("alert_msg_pre", "This region is linked to Irc.");
  86. string alertPostMessage = config.GetString("alert_msg_post", "Everything you say in public chat can be listened.");
  87. alertMessage = String.Format("{0}\n{1}{2}", alertPreMessage, alertServerInfo, alertPostMessage);
  88. dialogModule = scene.RequestModuleInterface<IDialogModule>();
  89. }
  90. // OpenChannel conditionally establishes a connection to the
  91. // IRC server. The request will either succeed, or it will
  92. // throw an exception.
  93. ChannelState.OpenChannel(this, config);
  94. // Connect channel to world events
  95. scene.EventManager.OnChatFromWorld += OnSimChat;
  96. scene.EventManager.OnChatFromClient += OnSimChat;
  97. scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
  98. scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
  99. m_log.InfoFormat("[IRC-Region {0}] Initialization complete", Region);
  100. }
  101. // Auto cleanup when abandoned
  102. ~RegionState()
  103. {
  104. if (cs != null)
  105. cs.RemoveRegion(this);
  106. }
  107. // Called by PostInitialize after all regions have been created
  108. public void Open()
  109. {
  110. cs.Open(this);
  111. enabled = true;
  112. }
  113. // Called by IRCBridgeModule.Close immediately prior to unload
  114. // of the module for this region. This happens when the region
  115. // is being removed or the server is terminating. The IRC
  116. // BridgeModule will remove the region from the region list
  117. // when control returns.
  118. public void Close()
  119. {
  120. enabled = false;
  121. cs.Close(this);
  122. }
  123. // The agent has disconnected, cleanup associated resources
  124. private void OnClientLoggedOut(IClientAPI client)
  125. {
  126. try
  127. {
  128. if (clients.Contains(client))
  129. {
  130. if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting))
  131. {
  132. m_log.InfoFormat("[IRC-Region {0}]: {1} has left", Region, client.Name);
  133. //Check if this person is excluded from IRC
  134. if (!cs.ExcludeList.Contains(client.Name.ToLower()))
  135. {
  136. cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", client.Name));
  137. }
  138. }
  139. client.OnLogout -= OnClientLoggedOut;
  140. client.OnConnectionClosed -= OnClientLoggedOut;
  141. clients.Remove(client);
  142. }
  143. }
  144. catch (Exception ex)
  145. {
  146. m_log.ErrorFormat("[IRC-Region {0}]: ClientLoggedOut exception: {1}", Region, ex.Message);
  147. m_log.Debug(ex);
  148. }
  149. }
  150. // This event indicates that the agent has left the building. We should treat that the same
  151. // as if the agent has logged out (we don't want cross-region noise - or do we?)
  152. private void OnMakeChildAgent(ScenePresence presence)
  153. {
  154. IClientAPI client = presence.ControllingClient;
  155. try
  156. {
  157. if (clients.Contains(client))
  158. {
  159. if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting))
  160. {
  161. string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname);
  162. m_log.DebugFormat("[IRC-Region {0}] {1} has left", Region, clientName);
  163. cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", clientName));
  164. }
  165. client.OnLogout -= OnClientLoggedOut;
  166. client.OnConnectionClosed -= OnClientLoggedOut;
  167. clients.Remove(client);
  168. }
  169. }
  170. catch (Exception ex)
  171. {
  172. m_log.ErrorFormat("[IRC-Region {0}]: MakeChildAgent exception: {1}", Region, ex.Message);
  173. m_log.Debug(ex);
  174. }
  175. }
  176. // An agent has entered the region (from another region). Add the client to the locally
  177. // known clients list
  178. private void OnMakeRootAgent(ScenePresence presence)
  179. {
  180. IClientAPI client = presence.ControllingClient;
  181. try
  182. {
  183. if (!clients.Contains(client))
  184. {
  185. client.OnLogout += OnClientLoggedOut;
  186. client.OnConnectionClosed += OnClientLoggedOut;
  187. clients.Add(client);
  188. if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting))
  189. {
  190. string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname);
  191. m_log.DebugFormat("[IRC-Region {0}] {1} has arrived", Region, clientName);
  192. //Check if this person is excluded from IRC
  193. if (!cs.ExcludeList.Contains(clientName.ToLower()))
  194. {
  195. cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has arrived", clientName));
  196. }
  197. }
  198. }
  199. if (dialogModule != null && showAlert)
  200. dialogModule.SendAlertToUser(client, alertMessage, true);
  201. }
  202. catch (Exception ex)
  203. {
  204. m_log.ErrorFormat("[IRC-Region {0}]: MakeRootAgent exception: {1}", Region, ex.Message);
  205. m_log.Debug(ex);
  206. }
  207. }
  208. // This handler detects chat events int he virtual world.
  209. public void OnSimChat(Object sender, OSChatMessage msg)
  210. {
  211. // early return if this comes from the IRC forwarder
  212. if (cs.irc.Equals(sender)) return;
  213. // early return if nothing to forward
  214. if (msg.Message.Length == 0) return;
  215. // check for commands coming from avatars or in-world
  216. // object (if commands are enabled)
  217. if (cs.CommandsEnabled && msg.Channel == cs.CommandChannel)
  218. {
  219. m_log.DebugFormat("[IRC-Region {0}] command on channel {1}: {2}", Region, msg.Channel, msg.Message);
  220. string[] messages = msg.Message.Split(' ');
  221. string command = messages[0].ToLower();
  222. try
  223. {
  224. switch (command)
  225. {
  226. // These commands potentially require a change in the
  227. // underlying ChannelState.
  228. case "server":
  229. cs.Close(this);
  230. cs = cs.UpdateServer(this, messages[1]);
  231. cs.Open(this);
  232. break;
  233. case "port":
  234. cs.Close(this);
  235. cs = cs.UpdatePort(this, messages[1]);
  236. cs.Open(this);
  237. break;
  238. case "channel":
  239. cs.Close(this);
  240. cs = cs.UpdateChannel(this, messages[1]);
  241. cs.Open(this);
  242. break;
  243. case "nick":
  244. cs.Close(this);
  245. cs = cs.UpdateNickname(this, messages[1]);
  246. cs.Open(this);
  247. break;
  248. // These may also (but are less likely) to require a
  249. // change in ChannelState.
  250. case "client-reporting":
  251. cs = cs.UpdateClientReporting(this, messages[1]);
  252. break;
  253. case "in-channel":
  254. cs = cs.UpdateRelayIn(this, messages[1]);
  255. break;
  256. case "out-channel":
  257. cs = cs.UpdateRelayOut(this, messages[1]);
  258. break;
  259. // These are all taken to be temporary changes in state
  260. // so the underlying connector remains intact. But note
  261. // that with regions sharing a connector, there could
  262. // be interference.
  263. case "close":
  264. enabled = false;
  265. cs.Close(this);
  266. break;
  267. case "connect":
  268. enabled = true;
  269. cs.Open(this);
  270. break;
  271. case "reconnect":
  272. enabled = true;
  273. cs.Close(this);
  274. cs.Open(this);
  275. break;
  276. // This one is harmless as far as we can judge from here.
  277. // If it is not, then the complaints will eventually make
  278. // that evident.
  279. default:
  280. m_log.DebugFormat("[IRC-Region {0}] Forwarding unrecognized command to IRC : {1}",
  281. Region, msg.Message);
  282. cs.irc.Send(msg.Message);
  283. break;
  284. }
  285. }
  286. catch (Exception ex)
  287. {
  288. m_log.WarnFormat("[IRC-Region {0}] error processing in-world command channel input: {1}",
  289. Region, ex.Message);
  290. m_log.Debug(ex);
  291. }
  292. return;
  293. }
  294. // The command channel remains enabled, even if we have otherwise disabled the IRC
  295. // interface.
  296. if (!enabled)
  297. return;
  298. // drop messages unless they are on a valid in-world
  299. // channel as configured in the ChannelState
  300. if (!cs.ValidInWorldChannels.Contains(msg.Channel))
  301. {
  302. m_log.DebugFormat("[IRC-Region {0}] dropping message {1} on channel {2}", Region, msg, msg.Channel);
  303. return;
  304. }
  305. ScenePresence avatar = null;
  306. string fromName = msg.From;
  307. if (msg.Sender != null)
  308. {
  309. avatar = scene.GetScenePresence(msg.Sender.AgentId);
  310. if (avatar != null) fromName = avatar.Name;
  311. }
  312. if (!cs.irc.Connected)
  313. {
  314. m_log.WarnFormat("[IRC-Region {0}] IRCConnector not connected: dropping message from {1}", Region, fromName);
  315. return;
  316. }
  317. m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message);
  318. if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL))
  319. {
  320. string txt = msg.Message;
  321. if (txt.StartsWith("/me "))
  322. txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4));
  323. cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt);
  324. return;
  325. }
  326. if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword &&
  327. msg.Channel == cs.RelayChannelOut)
  328. {
  329. Match m = cs.AccessPasswordRegex.Match(msg.Message);
  330. if (null != m)
  331. {
  332. m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(),
  333. m.Groups["message"].ToString());
  334. cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(),
  335. scene.RegionInfo.RegionName, m.Groups["message"].ToString());
  336. }
  337. }
  338. }
  339. // This method gives the region an opportunity to interfere with
  340. // message delivery. For now we just enforce the enable/disable
  341. // flag.
  342. internal void OSChat(Object irc, OSChatMessage msg)
  343. {
  344. if (enabled)
  345. {
  346. // m_log.DebugFormat("[IRC-OSCHAT] Region {0} being sent message", region.Region);
  347. msg.Scene = scene;
  348. scene.EventManager.TriggerOnChatBroadcast(irc, msg);
  349. }
  350. }
  351. // This supports any local message traffic that might be needed in
  352. // support of command processing. At present there is none.
  353. internal void LocalChat(string msg)
  354. {
  355. if (enabled)
  356. {
  357. OSChatMessage osm = new OSChatMessage();
  358. osm.From = "IRC Agent";
  359. osm.Message = msg;
  360. osm.Type = ChatTypeEnum.Region;
  361. osm.Position = CenterOfRegion;
  362. osm.Sender = null;
  363. osm.SenderUUID = OpenMetaverse.UUID.Zero; // Hmph! Still?
  364. osm.Channel = 0;
  365. OSChat(this, osm);
  366. }
  367. }
  368. }
  369. }