RegionState.cs 17 KB

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