RegionState.cs 16 KB

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