RegionState.cs 18 KB

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