RegionState.cs 16 KB

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